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): viewer auto-switch, all-board search, wildcard bulk delete and shell fixes (#9959)
Josh Corbett901f244a3676
diff --git a/docs/src/content/docs/Users Guide/01.Workbench/01.introduction.mdx b/docs/src/content/docs/Users Guide/01.Workbench/01.introduction.mdxindex e23db246c9..50fa924fc9 100644--- a/docs/src/content/docs/Users Guide/01.Workbench/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/01.Workbench/01.introduction.mdx@@ -55,6 +55,16 @@ The center panel shows one **view** at a time. The button in its top-left cornerPress <kbd>Z</kbd> to swap the Preview into the center and back to the view you had before. It is a quick way to check a result while you work on the canvas or a workflow.+The Preview's **Auto-switch** menu, in its header, chooses what it shows while work runs:++- **In progress**: each image as it is being generated, then the finished result. New projects start here.+- **Newest**: each finished result, without the in-progress frames.+- **Off**: the Preview stays on what you chose; new results appear in the Gallery only.++Choosing an item yourself, in the Gallery or with the Preview's arrows, turns Auto-switch **Off** so your choice stays on screen; clicking a generating tile in the Gallery turns it back to **In progress**. The setting is saved with the project. Projects created before this setting existed open with it **Off**.++To step through the Gallery's items in the Preview, press the arrow keys, or hover over the image and click the arrows at its left and right edges.+### The status bar and bottom panelThe status bar along the bottom holds small chips. Hover over **Server Status**, the queue chip or **Autosave** for details; click **Notifications** to see recent messages. Some chips, such as **Gallery**, open a **bottom panel** above the status bar. Drag the top edge of the bottom panel to resize it.@@ -122,7 +132,7 @@ On a touchscreen, press and hold an icon briefly before dragging.| <kbd>F</kbd> | Collapse or expand all side and bottom panels at once, for a clear view of the center || <kbd>Z</kbd> | Swap the Preview into or out of the center || <kbd>Shift</kbd>+<kbd>R</kbd> | Revert to the active preset's saved layout |-| <kbd>Alt</kbd>+<kbd>1</kbd> to <kbd>Alt</kbd>+<kbd>4</kbd> | Switch to the Compose, Edit, Video or Automate preset |+| <kbd>Alt</kbd>+<kbd>1</kbd> to <kbd>Alt</kbd>+<kbd>4</kbd> | Switch to the Compose, Edit, Video or Workflow preset |These shortcuts don't fire while you are typing in a text field. You can change any of them; see [Hotkeys](/users-guide/workbench/hotkeys/).@@ -139,7 +149,7 @@ Invoke comes with four presets:| **Compose**: generate images from text | Preview (Gallery also available) | Generate, Upscale | Gallery, Image Map, Queue || **Edit**: paint and composite on the canvas | Canvas (Preview also available) | Generate, Upscale | Layers, Preview || **Video**: generate video | Preview | Video, Upscale | Gallery, Queue |-| **Automate**: build and run workflows | Workflow editor (Preview also available) | Workflow | Queue, Preview, Gallery, Image Map |+| **Workflow**: build and run workflows | Workflow editor (Preview also available) | Workflow | Queue, Preview, Gallery, Image Map |Each preset also sets where **Invoke** takes its settings from and where results go. For example, Compose generates from the Generate panel into the Gallery, while Edit works from and into the Canvas. A source or destination you have locked from the routing control next to **Invoke** is left alone.diff --git a/docs/src/content/docs/Users Guide/01.Workbench/assets/workbench-layout.svg b/docs/src/content/docs/Users Guide/01.Workbench/assets/workbench-layout.svgindex 0278c50111..90fd324984 100644--- a/docs/src/content/docs/Users Guide/01.Workbench/assets/workbench-layout.svg+++ b/docs/src/content/docs/Users Guide/01.Workbench/assets/workbench-layout.svg@@ -52,7 +52,7 @@<path d="M530 45l4 4 4-4" fill="none" stroke="#9aa1ab" stroke-width="1.8" stroke-linecap="round"/><text x="564" y="52" fill="#b5bbc4" font-size="14">Edit</text><text x="614" y="52" fill="#b5bbc4" font-size="14">Video</text>- <text x="672" y="52" fill="#b5bbc4" font-size="14">Automate</text>+ <text x="672" y="52" fill="#b5bbc4" font-size="14">Workflow</text><path d="M758 47h14M765 40v14" stroke="#e8eaed" stroke-width="2.2" stroke-linecap="round"/><!-- Invoke cluster --><rect x="908" y="31" width="40" height="32" rx="6" fill="#1c1f23" stroke="#454b55"/>diff --git a/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx b/docs/src/content/docs/Users Guide/02.Projects/introduction.mdxindex 75ecd3e973..1c4eda91cb 100644--- a/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx+++ b/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx@@ -29,7 +29,7 @@ Invoke saves projects automatically on the server, so there is no Save button to| 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 in the Library |-| Project settings: **Use CPU noise**, the **NSFW checker** and **Invisible watermark** output filters, **Antialias progress images** and the Preview's progress image toggle | Generate recipes |+| Project settings: **Use CPU noise**, the **NSFW checker** and **Invisible watermark** output filters, **Antialias progress images** and the Preview's **Auto-switch** mode | Generate recipes || 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.@@ -48,7 +48,7 @@ To create a project, click **New project**. The arrow beside it (**Choose how to| **Edit on canvas** | The Edit layout, with the canvas in front || **Upscale an image** | The Compose layout, set up for upscaling || **Generate a video** | The Video layout |-| **Build a workflow** | The Automate layout, for the workflow editor |+| **Build a workflow** | The Workflow layout, for the workflow editor |The starting point only chooses the initial layout. Every tool remains available, and you can [rearrange the workspace](/users-guide/workbench/introduction/) at any time.diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/01.introduction.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/01.introduction.mdxindex 7cd6c0fd3e..c9ec47b894 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/01.introduction.mdx@@ -49,7 +49,7 @@ If a required component is missing, **Invoke** is disabled and its tooltip names</Steps>-Hover over **Invoke** to see what will be queued, for example *1 prompt × 4 iterations → 4 generations*. When Invoke is disabled, the same tooltip lists what is stopping it. To run a batch ahead of the work you already have queued, press **Ctrl+Shift+Enter** (**Cmd+Shift+Enter** on macOS) or choose **Invoke (Front of Queue)** from the command palette. When several people share a server, the default round-robin queue still alternates between users, so the batch only moves ahead of your own jobs; a server set to first-in, first-out (`session_queue_mode: FIFO`) runs it ahead of everyone's pending jobs.+Hover over **Invoke** to see what will be queued, for example *1 prompt × 4 iterations → 4 generations*. When Invoke is disabled, the same tooltip lists what is stopping it. To run a batch ahead of the work you already have queued, **Shift+click** Invoke, press **Ctrl+Shift+Enter** (**Cmd+Shift+Enter** on macOS), or choose **Invoke (front of queue)** from the command palette. The Invoke tooltip names both. When several people share a server, the default round-robin queue still alternates between users, so the batch only moves ahead of your own jobs; a server set to first-in, first-out (`session_queue_mode: FIFO`) runs it ahead of everyone's pending jobs.The **Queue** panel lists recent jobs. Cancel a pending, waiting or running job from its row, and retry a failed or canceled job from the session the server saved for it, independently of your current settings. A retried job's results go where the original was headed while the tab that sent it is still open: back to its place in the Canvas staging area, or to the Gallery board it was sent to. This also holds when you retry several failed items of one batch one after another. A retried Canvas job is staged in a tab where its project is open; if that project is open nowhere, its result does not appear. Once that tab is gone, for example after a reload, or once its Canvas was replaced with a new document, Canvas results are staged once, at the current bounding box, by a tab with the project open, and Gallery results appear in the Gallery, on **Uncategorized** unless the job itself saved them to a board. Expand a row to cancel its whole batch while other batches keep running, or to open **View JSON**, which shows the graph the server actually ran, its results and the embedded workflow. The panel menu clears failed items, clears every finished item while keeping queued and running work, or clears the whole queue. Administrators also see the **Invocation Cache** beneath the queue, next to the model cache, where cached node outputs can be cleared, disabled or re-enabled.diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdxindex 1aaa8a63fb..9916dfcbaa 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/prompting-guide.mdx@@ -304,6 +304,7 @@ Wildcards are managed on the **Wildcards** tab of the **Dynamic** popover.* Click a wildcard to insert it at the cursor (**Insert into the prompt**). You can also type `__` in the prompt, or use the **+** [prompt trigger](/users-guide/image-generation/prompt-tools/#prompt-triggers) menu.* Use the pencil and trash buttons on a wildcard to edit or delete it.* **Search wildcards** finds wildcards by name or value.+* To delete several wildcards at once, tick the checkbox beside each one, or use **Select all** above the list to select every wildcard the search shows (selections from earlier searches are kept). Then choose **Delete** and confirm once. The **×** button clears the selection.Wildcards belong to your account. On a multi-user installation, each user has their own set.diff --git a/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx b/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdxindex 5b870c8039..5745991a29 100644--- a/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx+++ b/docs/src/content/docs/Users Guide/05.Video Generation/introduction.mdx@@ -273,7 +273,7 @@ If decode fails with `size mismatch for ... AutoencoderKLWan`, the **wrong VAE**### Preview images don't appear1. **A video is already loaded in the viewer** — the progress preview overlays it. If missing entirely, hard-refresh the browser (`Ctrl+Shift+R` / `Cmd+Shift+R`).-2. **`Show progress in viewer` is disabled** — check the gallery settings (gear icon).+2. **The Preview's Auto-switch is not set to In progress** — choose **In progress** from the **Auto-switch** menu in the Preview's header. **Newest** shows only finished results, and **Off** leaves the Preview on the item you chose.### Pipeline runs but the final MP4 is glitchydiff --git a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdxindex 1175902355..d83663f091 100644--- a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx+++ b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx@@ -1,7 +1,7 @@---title: Organizing your mediadescription: Use the Gallery to organize images and videos into boards, choose where new results go, search by metadata or by content, upload media, and move, star, download or delete it.-lastUpdated: 2026-10-10+lastUpdated: 2026-10-19sidebar:order: 1---@@ -67,10 +67,10 @@ 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** — 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.+ * **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. Click a project's name, or focus it and press **Enter** or **Space**, to collapse or expand that project's boards on their own. While you search the boards, every project with a matching board is shown expanded, and collapsed projects stay collapsed afterwards. You can still drag a board onto a collapsed project's name to move it there.* **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.+These choices, and which projects under **Other projects** are collapsed, are saved with the project, so each project can list boards differently.### Renaming, archiving, downloading and deleting boards@@ -78,7 +78,7 @@ Right-click a board, or hover over it and click its **⋯** button, to rename, m## Finding media in a board-Search, the starred filter and the sort order apply to the selected board and the current tab (Media or Uploads).+Search, the starred filter and the sort order apply to the selected board and the current tab (Media or Uploads). A search can also look in every board; see [Searching all boards](#searching-all-boards).### Searching by metadata@@ -103,10 +103,16 @@ When image indexing is turned on, the Gallery can also search by what media *sho* **Search by text.** Click the sparkle button at the right end of the search field (**Search semantically**). The field changes to **Describe what to find…**; describe what you are looking for. Any text already in the field is used straight away.* **Search by image.** Drag an image onto the search field: a thumbnail from the Gallery, an image from the Preview, an image file from your computer, or an image from another browser tab. The Gallery then shows the media most similar to it, labelled **Similar to …**.-Results are ranked by similarity, most similar first, up to 500 items from the selected board. Videos are included unless the media type filter hides them. The Media and Uploads tabs, the sort order, the starred filter and date tokens do not apply to ranked results.+Results are ranked by similarity, most similar first, up to 500 items from the selected board, or from every board with [All boards](#searching-all-boards). Videos are included unless the media type filter hides them. The Media and Uploads tabs, the sort order, the starred filter and date tokens do not apply to ranked results.To leave semantic search, click the **✕** in the search field, click the sparkle button again (**Exit semantic search**), or switch tabs. If the index model is not installed, the Gallery says so when you try to search. Archived boards are not indexed.+### Searching all boards++While a search is active, by metadata or by content, an **All boards** toggle appears inside the search field, beside the field's other buttons; its tooltip says where the search looks (**Search in: This board** or **Search in: All boards**). Turn it on to search everywhere you can see: your **Uncategorized** media and every board you can open that is not archived, including boards in other projects and boards others share with you. Everything else works as it does on one board: the tabs, the starred and media type filters, the sort order and date tokens apply to a metadata search as before. Selecting a result keeps you in the search: the arrow keys and the Preview step through its results.++Searching all boards changes neither the selected board nor where new results go. You cannot upload while it is on, since the search has no board of its own. Clearing the search, or anything else that clears it, such as **Find in Gallery**, returns it to **This board**.+### Sorting and filteringThe sort menu orders media by creation time, **Newest** first (the default) or **Oldest** first. The star button (**Starred only**) shows only starred items.diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdxindex 141c171988..6f2ffb7258 100644--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx@@ -14,7 +14,7 @@ This page describes the Canvas itself: its tools, controls and menus. For an intEach project has one canvas. It opens in the center of the **Edit** layout (**Alt+2**), or press **2** to bring it to the front.-<Image src={toolbar} alt="The Canvas with its tool strip on the left and the header buttons along the top: zoom, fit buttons, undo and redo, save, new canvas, settings and more." width={560} />+<Image src={toolbar} alt="The Canvas with its tool strip on the left and the header buttons along the top: zoom, fit buttons, undo and redo, save, clear canvas, settings and more." width={560} />## Tools@@ -72,8 +72,8 @@ The buttons along the top of the canvas, from left to right:* **Fit frame to layers** (**Shift+N**) — resizes the generation frame to enclose all layers.* **Fit frame to masks** (**Shift+B**) — resizes the generation frame to enclose the inpaint masks.* **Undo canvas edit** (**Ctrl+Z**) and **Redo canvas edit** (**Ctrl+Shift+Z** or **Ctrl+Y**).-* **Save Canvas to Gallery** — saves the visible canvas as an image on the Gallery's selected board. Its arrow offers **Save BBox to Gallery**, which saves only what is inside the generation frame.-* **New session → New canvas** — clears all layers and starts a fresh canvas with an empty inpaint mask. This cannot be undone.+* **Save Canvas to Gallery** — saves the visible canvas as an image on the board new results go to: the auto-add board, or the selected board when none is set (see [Choosing where new media goes](/users-guide/gallery/introduction/#choosing-where-new-media-goes)). Its arrow offers **Save BBox to Gallery**, which saves only what is inside the generation frame. A message names the board the image went to; its **Show in Gallery** button selects the image in the Gallery and keeps the Canvas in the center.+* **Clear canvas** (**Ctrl+Alt+N**, **Cmd+Option+N** on macOS) — after you confirm, clears all layers and starts a fresh canvas with an empty inpaint mask. This cannot be undone.* **Canvas settings** — see [below](#canvas-settings).## The generation framediff --git a/docs/src/content/docs/Users Guide/08.Workflows/01.introduction.mdx b/docs/src/content/docs/Users Guide/08.Workflows/01.introduction.mdxindex ae326de90a..55f5b18e1b 100644--- a/docs/src/content/docs/Users Guide/08.Workflows/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/08.Workflows/01.introduction.mdx@@ -40,11 +40,11 @@ Workflows expose the individual steps of image generation. The [Diffusion overvi## A tour of the workflow editor-Workflows are built and run in the **Automate** layout (**Alt+4**). The editor fills the center, the workflow's form is on the left, and the Gallery and Queue are on the right.+Workflows are built and run in the **Workflow** layout (**Alt+4**). The editor fills the center, the workflow's form is on the left, and the Gallery and Queue are on the right.<EditorTourrole="group"- aria-label="The Automate layout: the Workflow form panel on the left, the workflow editor with a graph of nodes in the center, and the Gallery on the right. Numbered callouts mark the parts described below."+ aria-label="The Workflow layout: the Workflow form panel on the left, the workflow editor with a graph of nodes in the center, and the Gallery on the right. Numbered callouts mark the parts described below."style="width: 100%; height: auto;"/>@@ -60,7 +60,7 @@ Hover over a numbered circle, or tap it on a touchscreen, for a short descriptio| 6 | **The graph** | The workflow's nodes and connections. Drag nodes by their title bar; scroll to zoom; drag empty space to pan. || 7 | **Minimap** | An overview of the whole graph for finding your way around large workflows. || 8 | **Gallery and Queue** | Where results appear, with the Queue, Preview and Image Map on the right-hand rail. |-| 9 | **Automate** | The layout preset for workflows. |+| 9 | **Workflow** | The layout preset for workflows. || 10 | **Invoke** | Runs the active workflow. The routing control beside it shows the source (**Workflow**) and the destination (**Gallery**). |### The essentials@@ -82,7 +82,7 @@ You need an SDXL model and an SDXL VAE, such as the *sdxl-vae-fp16-fix* starter<Steps>-1. Press **Alt+4** for the Automate layout.+1. Press **Alt+4** for the Workflow layout.2. Click the workflow's name at the top of the editor to open the **Workflows** library, go to **Browse**, and open **Text to Image - SDXL**. A copy is added to your project and becomes the active workflow.diff --git a/docs/src/content/docs/Users Guide/08.Workflows/assets/workflow-editor-tour.svg b/docs/src/content/docs/Users Guide/08.Workflows/assets/workflow-editor-tour.svgindex 5c3b250cc6..d9897b1d3a 100644--- a/docs/src/content/docs/Users Guide/08.Workflows/assets/workflow-editor-tour.svg+++ b/docs/src/content/docs/Users Guide/08.Workflows/assets/workflow-editor-tour.svg@@ -28,7 +28,7 @@<g id="wfe-c6" class="wfe-callout" tabindex="0" role="button" aria-label="6: The graph"><circle cx="744" cy="264" r="16"/><text x="744" y="270">6</text></g><g id="wfe-c7" class="wfe-callout" tabindex="0" role="button" aria-label="7: Minimap"><circle cx="1112" cy="788" r="16"/><text x="1112" y="794">7</text></g><g id="wfe-c8" class="wfe-callout" tabindex="0" role="button" aria-label="8: Gallery, Queue and more"><circle cx="1408" cy="50" r="16"/><text x="1408" y="56">8</text></g>- <g id="wfe-c9" class="wfe-callout" tabindex="0" role="button" aria-label="9: Automate layout"><circle cx="938" cy="18" r="16"/><text x="938" y="24">9</text></g>+ <g id="wfe-c9" class="wfe-callout" tabindex="0" role="button" aria-label="9: Workflow layout"><circle cx="938" cy="18" r="16"/><text x="938" y="24">9</text></g><g id="wfe-c10" class="wfe-callout" tabindex="0" role="button" aria-label="10: Invoke"><circle cx="1370" cy="37" r="16"/><text x="1370" y="43">10</text></g><g id="wfe-t1" class="wfe-tip" aria-hidden="true"><rect x="54" y="76" width="420" height="122" rx="10"/><text class="wfe-tip-title" x="70" y="106">Workflow panel</text><text x="70" y="134">The linear form: the workflow's key</text><text x="70" y="160">settings as simple controls. View uses</text><text x="70" y="186">the form; Edit builds it.</text></g><g id="wfe-t2" class="wfe-tip" aria-hidden="true"><rect x="10" y="108" width="420" height="148" rx="10"/><text class="wfe-tip-title" x="26" y="138">View and Edit</text><text x="26" y="166">Switch between using the form (View)</text><text x="26" y="192">and designing it (Edit), with the</text><text x="26" y="218">workflow's details and a Node</text><text x="26" y="244">Inspector.</text></g>@@ -38,6 +38,6 @@<g id="wfe-t6" class="wfe-tip" aria-hidden="true"><rect x="534" y="290" width="420" height="148" rx="10"/><text class="wfe-tip-title" x="550" y="320">The graph</text><text x="550" y="348">Nodes and the connections between</text><text x="550" y="374">them. Drag from an output on the right</text><text x="550" y="400">of a node to an input on the left of</text><text x="550" y="426">another.</text></g><g id="wfe-t7" class="wfe-tip" aria-hidden="true"><rect x="902" y="666" width="420" height="96" rx="10"/><text class="wfe-tip-title" x="918" y="696">Minimap</text><text x="918" y="724">An overview of the whole graph. Drag</text><text x="918" y="750">in it to move around large workflows.</text></g><g id="wfe-t8" class="wfe-tip" aria-hidden="true"><rect x="1170" y="76" width="420" height="122" rx="10"/><text class="wfe-tip-title" x="1170" y="106">Gallery, Queue and more</text><text x="1170" y="134">The right panel shows the Gallery,</text><text x="1170" y="160">where results appear, with the Queue,</text><text x="1170" y="186">Preview and Image Map on its rail.</text></g>- <g id="wfe-t9" class="wfe-tip" aria-hidden="true"><rect x="728" y="44" width="420" height="122" rx="10"/><text class="wfe-tip-title" x="744" y="74">Automate layout</text><text x="744" y="102">The layout preset for workflows</text><text x="744" y="128">(Alt+4): form on the left, editor in</text><text x="744" y="154">the center, results on the right.</text></g>+ <g id="wfe-t9" class="wfe-tip" aria-hidden="true"><rect x="728" y="44" width="420" height="122" rx="10"/><text class="wfe-tip-title" x="744" y="74">Workflow layout</text><text x="744" y="102">The layout preset for workflows</text><text x="744" y="128">(Alt+4): form on the left, editor in</text><text x="744" y="154">the center, results on the right.</text></g><g id="wfe-t10" class="wfe-tip" aria-hidden="true"><rect x="1108" y="63" width="420" height="148" rx="10"/><text class="wfe-tip-title" x="1124" y="93">Invoke</text><text x="1124" y="121">Runs the active workflow. The routing</text><text x="1124" y="147">control beside it shows Workflow as</text><text x="1124" y="173">the source and Gallery as the</text><text x="1124" y="199">destination.</text></g></svg>\ No newline at end of filediff --git a/invokeai/app/api/routers/gallery.py b/invokeai/app/api/routers/gallery.pyindex e1b655a7c3..a7361b1139 100644--- a/invokeai/app/api/routers/gallery.py+++ b/invokeai/app/api/routers/gallery.py@@ -20,6 +20,15 @@ from invokeai.app.services.shared.pagination import MAX_PAGE_SIZE, OffsetPaginatgallery_router = APIRouter(prefix="/v1/gallery", tags=["gallery"])+# Scopes rather than boards: the listing itself limits them to what the caller may read, so no board is checked.+_BOARD_SENTINELS = ("none", "all")++BoardIdQuery = Query(+ default=None,+ description="The board id to filter by. Use 'none' for items on no board (the current user's, unless an "+ "administrator), or 'all' for those items plus the items on every non-archived board the current user may read.",+)+MediaKindQuery = Query(default=None,description="List only images ('image') or only videos ('video'). Omit to include both. Totals, positions and "@@ -40,10 +49,7 @@ def list_gallery_items(description="The categories to include. Shared between images and videos.",),is_intermediate: Optional[bool] = Query(default=None, description="Whether to list intermediate items."),- board_id: Optional[str] = Query(- default=None,- description="The board id to filter by. Use 'none' to find items without a board.",- ),+ board_id: Optional[str] = BoardIdQuery,# Bounds matter: these flow verbatim into SQL, and a negative LIMIT means# *unlimited* in SQLite — one request would materialize the entire gallery.offset: int = Query(default=0, ge=0, description="The page offset"),@@ -64,7 +70,7 @@ def list_gallery_items(),) -> OffsetPaginatedResults[GalleryItem]:"""Returns a paginated, time-sorted stream of polymorphic gallery items (images + videos)."""- if board_id is not None and board_id != "none":+ if board_id is not None and board_id not in _BOARD_SENTINELS:_assert_board_read_access(board_id, current_user)return ApiDependencies.invoker.services.gallery.list_items(@@ -101,10 +107,7 @@ def get_gallery_item_location(description="The categories to include. Shared between images and videos.",),is_intermediate: Optional[bool] = Query(default=None, description="Whether to list intermediate items."),- board_id: Optional[str] = Query(- default=None,- description="The board id to filter by. Use 'none' to find items without a board.",- ),+ board_id: Optional[str] = BoardIdQuery,order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),starred: Optional[bool] = Query(default=None,@@ -120,7 +123,7 @@ def get_gallery_item_location(),) -> GalleryItemLocation:"""Returns exact item's position in an ordinary filtered gallery listing."""- if board_id is not None and board_id != "none":+ if board_id is not None and board_id not in _BOARD_SENTINELS:_assert_board_read_access(board_id, current_user)location = ApiDependencies.invoker.services.gallery.get_item_location(@@ -157,10 +160,7 @@ def list_gallery_item_names(description="The categories to include. Shared between images and videos.",),is_intermediate: Optional[bool] = Query(default=None, description="Whether to list intermediate items."),- board_id: Optional[str] = Query(- default=None,- description="The board id to filter by. Use 'none' to find items without a board.",- ),+ board_id: Optional[str] = BoardIdQuery,created_date: Optional[str] = Query(default=None,description="Restrict to items created on this ISO date, e.g. '2026-03-18'. Used by date-based virtual boards.",@@ -185,7 +185,7 @@ def list_gallery_item_names(Names are polymorphic: image and video names are interleaved by `created_at`. A name endingin `.mp4` is a video."""- if board_id is not None and board_id != "none":+ if board_id is not None and board_id not in _BOARD_SENTINELS:_assert_board_read_access(board_id, current_user)try:@@ -223,10 +223,7 @@ def get_gallery_item_names(description="The categories to include. Shared between images and videos.",),is_intermediate: Optional[bool] = Query(default=None, description="Whether to list intermediate items."),- board_id: Optional[str] = Query(- default=None,- description="The board id to filter by. Use 'none' to find items without a board.",- ),+ board_id: Optional[str] = BoardIdQuery,order_dir: SQLiteDirection = Query(default=SQLiteDirection.Descending, description="The order of sort"),starred_first: bool = Query(default=True, description="Whether to sort by starred items first"),starred: Optional[bool] = Query(@@ -248,7 +245,7 @@ def get_gallery_item_names(list. The `kind` discriminator here costs a model per row — ~800ms on a 200k-item library —for a value callers already derive from the file extension."""- if board_id is not None and board_id != "none":+ if board_id is not None and board_id not in _BOARD_SENTINELS:_assert_board_read_access(board_id, current_user)try:diff --git a/invokeai/app/api/routers/wildcards.py b/invokeai/app/api/routers/wildcards.pyindex 66b88aa712..1546673d03 100644--- a/invokeai/app/api/routers/wildcards.py+++ b/invokeai/app/api/routers/wildcards.py@@ -1,9 +1,13 @@+from typing import Annotated+from fastapi import Body, HTTPException, Pathfrom fastapi.routing import APIRouter+from pydantic import StringConstraintsfrom invokeai.app.api.auth_dependencies import CurrentUserOrDefaultfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.services.wildcard_records.wildcard_records_common import (+ DeleteWildcardsResult,WildcardChanges,WildcardNameConflictError,WildcardNotFoundError,@@ -13,6 +17,10 @@ from invokeai.app.services.wildcard_records.wildcard_records_common import (wildcards_router = APIRouter(prefix="/v1/wildcards", tags=["wildcards"])+# The most ids one batch delete takes; clients send larger selections in batches of this size.+MAX_WILDCARD_BATCH_SIZE = 1000+WildcardId = Annotated[str, StringConstraints(max_length=255)]+def _get_owned_wildcard(wildcard_id: str, user_id: str) -> WildcardRecordDTO:"""Loads a wildcard, treating someone else's as absent rather than forbidden.@@ -88,3 +96,28 @@ def delete_wildcard("""Deletes a wildcard owned by the current user."""_get_owned_wildcard(wildcard_id, current_user.user_id)ApiDependencies.invoker.services.wildcard_records.delete(wildcard_id)+++@wildcards_router.post(+ "/delete",+ operation_id="delete_wildcards",+ response_model=DeleteWildcardsResult,+)+def delete_wildcards(+ current_user: CurrentUserOrDefault,+ wildcard_ids: list[WildcardId] = Body(+ description="The ids of the wildcards to delete",+ embed=True,+ min_length=1,+ max_length=MAX_WILDCARD_BATCH_SIZE,+ ),+) -> DeleteWildcardsResult:+ """Deletes those of the wildcards that the current user owns.++ Unknown ids and other users' ids are skipped and left out of the result, as the single delete answers 404+ for both, so the result never confirms that someone else's id exists.+ """+ deleted_ids = ApiDependencies.invoker.services.wildcard_records.delete_many(+ user_id=current_user.user_id, wildcard_ids=wildcard_ids+ )+ return DeleteWildcardsResult(deleted_ids=deleted_ids)diff --git a/invokeai/app/services/boards/boards_common.py b/invokeai/app/services/boards/boards_common.pyindex 1bbbdad553..f669d7d426 100644--- a/invokeai/app/services/boards/boards_common.py+++ b/invokeai/app/services/boards/boards_common.py@@ -21,16 +21,18 @@ class BoardDTO(BoardRecord):"""The name of the cover video, set when the most-recent item on the board is a video rather than an image."""image_count: int = Field(description="The number of images in the board.")"""The number of images in the board."""- video_count: int = Field(default=0, description="The number of videos in the board.")- """The number of videos in the board."""+ video_count: int = Field(+ default=0, description="The number of videos in the board that the gallery's Media or Uploads view lists."+ )+ """Generated ('general') and asset videos together. Like images, a video of a category neither view lists is+ not counted."""asset_count: int = Field(description="The number of assets in the board.")"""The number of assets in the board."""asset_video_count: int = Field(- default=0, description="The number of asset-category (non-'general') videos in the board."+ default=0, description="The number of asset-category videos in the board, which the Uploads view lists.")- """Uploaded videos are assets ('user' category) while generated videos are 'general', mirroring- images. `video_count` stays the total so "delete board with N videos" copy remains honest; this- field lets clients split the total across the Media/Assets views."""+ """Uploaded videos are assets ('user' category) while generated videos are 'general', mirroring images. Part of+ `video_count`; it lets clients split that count across the Media and Uploads views."""owner_username: Optional[str] = Field(default=None,description=(diff --git a/invokeai/app/services/shared/database/queries/board_access.py b/invokeai/app/services/shared/database/queries/board_access.pyindex 5e2e15b978..00e54a054a 100644--- a/invokeai/app/services/shared/database/queries/board_access.py+++ b/invokeai/app/services/shared/database/queries/board_access.py@@ -1,6 +1,6 @@"""Which boards an account may read: one rule for every query that lists boards or media through them."""-from sqlalchemy import ColumnElement, exists, or_+from sqlalchemy import ColumnElement, bindparam, exists, false, or_from invokeai.app.services.shared.database.schema.boards import board_members, boards@@ -10,3 +10,11 @@ def readable_board(user_id: ColumnElement[str]) -> ColumnElement[bool]:those it is a member of. Archived boards are not excluded here: listings decide that themselves."""member = exists().where(board_members.c.board_id == boards.c.board_id, board_members.c.user_id == user_id)return or_(boards.c.user_id == user_id, boards.c.general_access != "restricted", member)+++def listed_board(scoped: bool) -> list[ColumnElement[bool]]:+ """The conditions on a board whose items a listing of every readable board shows: active, and with `scoped` one+ the account bound as `user_id` may read."""+ if not scoped:+ return [boards.c.archived == false()]+ return [boards.c.archived == false(), readable_board(bindparam("user_id"))]diff --git a/invokeai/app/services/shared/database/queries/board_videos.py b/invokeai/app/services/shared/database/queries/board_videos.pyindex 06516d32cc..0e73ac54f2 100644--- a/invokeai/app/services/shared/database/queries/board_videos.py+++ b/invokeai/app/services/shared/database/queries/board_videos.py@@ -5,7 +5,11 @@ from typing import Any, Optionalfrom sqlalchemy import Connection, Insert, Select, bindparam, case, delete, false, func, literal, select-from invokeai.app.services.image_records.image_records_common import ImageCategory+from invokeai.app.services.image_records.image_records_common import (+ ASSETS_CATEGORIES,+ IMAGE_CATEGORIES,+ ImageCategory,+)from invokeai.app.services.shared.database.dialect import upsertfrom invokeai.app.services.shared.database.queries.base import QueryModule, read, writefrom invokeai.app.services.shared.database.schema.boards import board_videos@@ -14,11 +18,19 @@ from invokeai.app.services.shared.database.types import now_text_BOARD_OF = select(board_videos.c.board_id).where(board_videos.c.video_name == bindparam("video_name"))_REMOVE = delete(board_videos).where(board_videos.c.video_name == bindparam("video_name"))-# Both counts in one pass: every video, and those of a category other than general (assets).+# Both counts in one pass, as the gallery's views list videos: those either view lists, and those Uploads lists+# (assets). An OTHER video, which neither view shows, is in neither count._COUNTS = (- select(func.count(), func.count(case((videos.c.video_category != literal(ImageCategory.GENERAL.value), 1))))+ select(+ func.count(),+ func.count(case((videos.c.video_category.in_([literal(c.value) for c in ASSETS_CATEGORIES]), 1))),+ ).select_from(board_videos.join(videos, board_videos.c.video_name == videos.c.video_name))- .where(videos.c.is_intermediate == false(), board_videos.c.board_id == bindparam("board_id"))+ .where(+ videos.c.is_intermediate == false(),+ board_videos.c.board_id == bindparam("board_id"),+ videos.c.video_category.in_([literal(c.value) for c in [*IMAGE_CATEGORIES, *ASSETS_CATEGORIES]]),+ ))@@ -85,6 +97,6 @@ class BoardVideoQueries(QueryModule):@readdef counts(self, conn: Connection, board_id: str) -> tuple[int, int]:- """The board's videos that are not intermediates: all of them, and those of a category other than general."""+ """The board's videos that are not intermediates and that a gallery view lists: all of those, and the assets."""counts = conn.execute(_COUNTS, {"board_id": board_id}).one()return counts[0], counts[1]diff --git a/invokeai/app/services/shared/database/queries/gallery.py b/invokeai/app/services/shared/database/queries/gallery.pyindex dec8eabe06..70a6341bd0 100644--- a/invokeai/app/services/shared/database/queries/gallery.py+++ b/invokeai/app/services/shared/database/queries/gallery.py@@ -47,7 +47,8 @@ from invokeai.app.services.shared.database.dialect import (like_contains,)from invokeai.app.services.shared.database.queries.base import IN_CHUNK, QueryModule, day_after, read-from invokeai.app.services.shared.database.schema.boards import board_images, board_videos+from invokeai.app.services.shared.database.queries.board_access import listed_board+from invokeai.app.services.shared.database.schema.boards import board_images, board_videos, boardsfrom invokeai.app.services.shared.database.schema.images import imagesfrom invokeai.app.services.shared.database.schema.videos import videos@@ -76,7 +77,7 @@ class _Shape(NamedTuple):categories: Optional[tuple[str, ...]]intermediate: boolstarred: bool- # "any" (no board filter), "none" (on no board) or "one".+ # "any" (no board filter), "none" (on no board), "all" (on no board or a readable, active one) or "one".board: str# Whether the listing is limited to one account's items; else everything, as for an administrator.scoped: bool@@ -112,7 +113,7 @@ class Filters(NamedTuple):else tuple(sorted({ImageCategory(c).value for c in self.categories})),intermediate=self.is_intermediate is not None,starred=self.starred is not None,- board="any" if self.board_id is None else "none" if self.board_id == "none" else "one",+ board="any" if self.board_id is None else self.board_id if self.board_id in ("none", "all") else "one",scoped=self.user_id is not None and not self.is_admin,search=bool(self.search_term),created_date=self.created_date is not None,@@ -144,12 +145,14 @@ def _from(kind: str, shape: _Shape, with_board: bool) -> tuple[FromClause, Columon = membership.c[half.name] == media.c[half.name]if shape.board == "one":return OrderedJoin(membership, media, on), membership.c.board_id- if shape.board == "any" and with_board:+ if shape.board in ("any", "all") and with_board:return media.outerjoin(membership, on), membership.c.board_idreturn media, null()-def _conditions(kind: str, shape: _Shape) -> list[ColumnElement[bool]]:+def _conditions(kind: str, shape: _Shape, joined: bool) -> list[ColumnElement[bool]]:+ """The listing's conditions. `joined`: the half lists through a LEFT JOIN of its memberships (`_from` with the+ board id), so a membership is read from the join rather than checked per item."""half = _HALVES[kind]media, membership = half.media, half.membershipconditions: list[ColumnElement[bool]] = []@@ -173,6 +176,22 @@ def _conditions(kind: str, shape: _Shape) -> list[ColumnElement[bool]]:conditions.append(~exists(select(literal(1)).where(membership.c[half.name] == media.c[half.name])))if shape.scoped:conditions.append(own)+ elif shape.board == "all":+ # As the images listing's "all": the account's own items on no board (every one when not scoped), and the+ # items on any active board it may read.+ if joined:+ on_no_board = membership.c.board_id.is_(None)+ on_listed_board = exists(+ select(literal(1)).where(boards.c.board_id == membership.c.board_id, *listed_board(shape.scoped))+ )+ else:+ on_no_board = ~exists(select(literal(1)).where(membership.c[half.name] == media.c[half.name]))+ on_listed_board = exists(+ select(literal(1))+ .select_from(membership.join(boards, boards.c.board_id == membership.c.board_id))+ .where(membership.c[half.name] == media.c[half.name], *listed_board(shape.scoped))+ )+ conditions.append(or_(and_(on_no_board, own) if shape.scoped else on_no_board, on_listed_board))elif shape.board == "one":conditions.append(membership.c.board_id == bindparam("board_id"))elif shape.scoped:@@ -190,6 +209,7 @@ def _half(kind: str, shape: _Shape, names_only: bool) -> Select[Any]:half = _HALVES[kind]media = half.mediasource, board_id = _from(kind, shape, with_board=not names_only)+ joined = shape.board == "all" and not names_onlyif names_only:columns: list[ColumnElement[Any]] = [literal(kind).label("kind"),@@ -211,7 +231,7 @@ def _half(kind: str, shape: _Shape, names_only: bool) -> Select[Any]:(media.c.duration if kind == "video" else null()).label("duration"),(media.c.fps if kind == "video" else null()).label("fps"),]- return select(*columns).select_from(source).where(*_conditions(kind, shape))+ return select(*columns).select_from(source).where(*_conditions(kind, shape, joined))def _items(shape: _Shape, names_only: bool) -> Subquery:@@ -253,7 +273,9 @@ def _count(shape: _Shape) -> Select[Any]:# Without the board id a listing shows: a membership join cannot change the count, and MySQL does not# eliminate it.source, _ = _from(kind, shape, with_board=False)- counts.append(select(func.count()).select_from(source).where(*_conditions(kind, shape)).scalar_subquery())+ counts.append(+ select(func.count()).select_from(source).where(*_conditions(kind, shape, False)).scalar_subquery()+ )return select(functools.reduce(operator.add, counts))@@ -267,26 +289,28 @@ def _in(column: ColumnElement[Any], categories: Sequence[ImageCategory]) -> Colureturn column.in_([literal(category.value) for category in categories])+# What the gallery's two views list: Media (`IMAGE_CATEGORIES`) and Uploads (`ASSETS_CATEGORIES`).+_LISTED_CATEGORIES = [*IMAGE_CATEGORIES, *ASSETS_CATEGORIES]++def _counted(items: Subquery) -> list[ColumnElement[int]]:- """Image and asset counts as the gallery's views list them (`IMAGE_CATEGORIES`, `ASSETS_CATEGORIES`), so that a- count never includes canvas-owned images (OTHER), which neither view shows; and every video, and those of a- category other than general, as a board counts its videos."""+ """Counts as the gallery's views list items, so that a count never includes what neither view shows (OTHER, such as+ canvas-owned images): images in Media, images in Uploads, videos in either view, and videos in Uploads."""is_image, is_video = items.c.kind == literal("image"), items.c.kind == literal("video")return [func.sum(case((and_(is_image, _in(items.c.category, IMAGE_CATEGORIES)), 1), else_=0)),func.sum(case((and_(is_image, _in(items.c.category, ASSETS_CATEGORIES)), 1), else_=0)),- func.sum(case((is_video, 1), else_=0)),- func.sum(case((and_(is_video, items.c.category != literal(ImageCategory.GENERAL.value)), 1), else_=0)),+ func.sum(case((and_(is_video, _in(items.c.category, _LISTED_CATEGORIES)), 1), else_=0)),+ func.sum(case((and_(is_video, _in(items.c.category, ASSETS_CATEGORIES)), 1), else_=0)),]def _dated(kind: str, scoped: bool) -> Select[Any]:half = _HALVES[kind]media = half.media- conditions = [media.c.is_intermediate == false()]- if kind == "image":- # Only what the gallery's views show: canvas-owned images (OTHER) neither make a day nor cover one.- conditions.append(_in(media.c[half.category], [*IMAGE_CATEGORIES, *ASSETS_CATEGORIES]))+ # Only what the gallery's views show: an OTHER item (such as a canvas-owned image) neither makes a day nor covers+ # one.+ conditions = [media.c.is_intermediate == false(), _in(media.c[half.category], _LISTED_CATEGORIES)]if scoped:conditions.append(media.c.user_id == bindparam("user_id"))return select(diff --git a/invokeai/app/services/shared/database/queries/images.py b/invokeai/app/services/shared/database/queries/images.pyindex 4ac4580dec..9218216b58 100644--- a/invokeai/app/services/shared/database/queries/images.py+++ b/invokeai/app/services/shared/database/queries/images.py@@ -38,7 +38,7 @@ from invokeai.app.services.shared.database.dialect import (like_contains,)from invokeai.app.services.shared.database.queries.base import IN_CHUNK, QueryModule, day_after, mapped, read, write-from invokeai.app.services.shared.database.queries.board_access import readable_board+from invokeai.app.services.shared.database.queries.board_access import listed_boardfrom invokeai.app.services.shared.database.schema.boards import board_images, boardsfrom invokeai.app.services.shared.database.schema.images import images@@ -193,14 +193,6 @@ def _parameters(}-def _listed_board(scoped: bool) -> list[ColumnElement[bool]]:- """The conditions on a board whose images the scope lists: active, and with `scoped` one the account may read- (its own, shared with everyone, or shared with the account)."""- if not scoped:- return [_B.archived == false()]- return [_B.archived == false(), readable_board(bindparam("user_id"))]--def _conditions(shape: _Shape, joined: bool) -> list[ColumnElement[bool]]:"""The listing's conditions. `joined` lists through a LEFT JOIN of the board memberships, for the board data apage of records returns; else the memberships are checked per image, so that SQLite scans the images alone."""@@ -221,13 +213,13 @@ def _conditions(shape: _Shape, joined: bool) -> list[ColumnElement[bool]]:conditions.append(own)elif shape.board == "all":if joined:- board = exists(select(literal(1)).where(_B.board_id == _BI.board_id, *_listed_board(shape.scoped)))+ board = exists(select(literal(1)).where(_B.board_id == _BI.board_id, *listed_board(shape.scoped)))else:memberships = board_images.join(boards, _B.board_id == _BI.board_id)board = exists(select(literal(1)).select_from(memberships)- .where(_BI.image_name == _I.image_name, *_listed_board(shape.scoped))+ .where(_BI.image_name == _I.image_name, *listed_board(shape.scoped)))conditions.append(or_(and_(on_no_board, own) if shape.scoped else on_no_board, board))elif shape.board == "one":diff --git a/invokeai/app/services/shared/database/queries/wildcards.py b/invokeai/app/services/shared/database/queries/wildcards.pyindex e411734e74..5635de9059 100644--- a/invokeai/app/services/shared/database/queries/wildcards.py+++ b/invokeai/app/services/shared/database/queries/wildcards.py@@ -1,13 +1,14 @@"""Wildcards: an account's named lists of values that a prompt can draw from."""import functools+import itertoolsimport jsonfrom collections.abc import Sequencefrom typing import Any, Optionalfrom sqlalchemy import Connection, Row, Update, bindparam, delete, insert, select, update-from invokeai.app.services.shared.database.queries.base import QueryModule, mapped, read, write+from invokeai.app.services.shared.database.queries.base import IN_CHUNK, QueryModule, mapped, read, writefrom invokeai.app.services.shared.database.schema.wildcards import wildcardsfrom invokeai.app.services.wildcard_records.wildcard_records_common import (WildcardChanges,@@ -23,6 +24,12 @@ _GET = select(*_COLUMNS).where(_W.id == bindparam("wildcard_id"))_OWNED = select(*_COLUMNS).where(_W.user_id == bindparam("user_id")).order_by(_W.name)_INSERT = insert(wildcards)_DELETE = delete(wildcards).where(_W.id == bindparam("wildcard_id"))+_OWNED_AMONG = select(_W.id).where(+ _W.user_id == bindparam("user_id"), _W.id.in_(bindparam("wildcard_ids", expanding=True))+)+_DELETE_OWNED = delete(wildcards).where(+ _W.user_id == bindparam("user_id"), _W.id.in_(bindparam("wildcard_ids", expanding=True))+)@functools.cache@@ -82,3 +89,15 @@ class WildcardQueries(QueryModule):@writedef delete(self, conn: Connection, wildcard_id: str) -> None:conn.execute(_DELETE, {"wildcard_id": wildcard_id})++ @write+ def delete_owned(self, conn: Connection, user_id: str, wildcard_ids: Sequence[str]) -> list[str]:+ """Deletes those of the wildcards that the account owns and returns their ids; the others are left alone."""+ deleted: list[str] = []+ for chunk in itertools.batched(wildcard_ids, IN_CHUNK):+ params = {"user_id": user_id, "wildcard_ids": list(chunk)}+ owned = [row[0] for row in conn.execute(_OWNED_AMONG, params).all()]+ if owned:+ conn.execute(_DELETE_OWNED, {"user_id": user_id, "wildcard_ids": owned})+ deleted.extend(owned)+ return deleteddiff --git a/invokeai/app/services/wildcard_records/wildcard_records_base.py b/invokeai/app/services/wildcard_records/wildcard_records_base.pyindex 0898a6452f..59aeaec114 100644--- a/invokeai/app/services/wildcard_records/wildcard_records_base.py+++ b/invokeai/app/services/wildcard_records/wildcard_records_base.py@@ -36,6 +36,14 @@ class WildcardRecordsStorageBase(ABC):"""Deletes a wildcard. Authorization is the caller's responsibility."""pass+ @abstractmethod+ def delete_many(self, user_id: str, wildcard_ids: list[str]) -> list[str]:+ """Deletes the wildcards among wildcard_ids that user_id owns, in one transaction, and returns their ids.++ Unknown ids and other accounts' ids are skipped, so the result never confirms that they exist.+ """+ pass+@abstractmethoddef get_many(self, user_id: str) -> list[WildcardRecordDTO]:"""Gets every wildcard owned by user_id, ordered by name."""diff --git a/invokeai/app/services/wildcard_records/wildcard_records_common.py b/invokeai/app/services/wildcard_records/wildcard_records_common.pyindex 41b7430225..eb386a88b6 100644--- a/invokeai/app/services/wildcard_records/wildcard_records_common.py+++ b/invokeai/app/services/wildcard_records/wildcard_records_common.py@@ -107,6 +107,10 @@ class WildcardRecordDTO(WildcardWithoutId):WildcardRecordDTOValidator = TypeAdapter(WildcardRecordDTO)+class DeleteWildcardsResult(BaseModel):+ deleted_ids: list[str] = Field(description="The ids of the wildcards that were deleted.")++def build_wildcard_manager(wildcards: list[WildcardRecordDTO]) -> "WildcardManager":"""Builds the manager that resolves `__name__` against a user's wildcards.diff --git a/invokeai/app/services/wildcard_records/wildcard_records_default.py b/invokeai/app/services/wildcard_records/wildcard_records_default.pyindex f444eb266d..d8819dc809 100644--- a/invokeai/app/services/wildcard_records/wildcard_records_default.py+++ b/invokeai/app/services/wildcard_records/wildcard_records_default.py@@ -56,5 +56,8 @@ class WildcardRecordsStorage(WildcardRecordsStorageBase):def delete(self, wildcard_id: str) -> None:self._queries.wildcards.delete(wildcard_id)+ def delete_many(self, user_id: str, wildcard_ids: list[str]) -> list[str]:+ return self._queries.wildcards.delete_owned(user_id, list(dict.fromkeys(wildcard_ids)))+def get_many(self, user_id: str) -> list[WildcardRecordDTO]:return self._queries.wildcards.owned_by(user_id)diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 24bd51ec87..d18a018f29 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -9757,10 +9757,10 @@"type": "null"}],- "description": "The board id to filter by. Use 'none' to find items without a board.",+ "description": "The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read.","title": "Board Id"},- "description": "The board id to filter by. Use 'none' to find items without a board."+ "description": "The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read."},{"name": "offset",@@ -10033,10 +10033,10 @@"type": "null"}],- "description": "The board id to filter by. Use 'none' to find items without a board.",+ "description": "The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read.","title": "Board Id"},- "description": "The board id to filter by. Use 'none' to find items without a board."+ "description": "The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read."},{"name": "order_dir",@@ -10249,10 +10249,10 @@"type": "null"}],- "description": "The board id to filter by. Use 'none' to find items without a board.",+ "description": "The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read.","title": "Board Id"},- "description": "The board id to filter by. Use 'none' to find items without a board."+ "description": "The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read."},{"name": "created_date",@@ -10496,10 +10496,10 @@"type": "null"}],- "description": "The board id to filter by. Use 'none' to find items without a board.",+ "description": "The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read.","title": "Board Id"},- "description": "The board id to filter by. Use 'none' to find items without a board."+ "description": "The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read."},{"name": "order_dir",@@ -15757,6 +15757,51 @@}}},+ "/api/v1/wildcards/delete": {+ "post": {+ "tags": ["wildcards"],+ "summary": "Delete Wildcards",+ "description": "Deletes those of the wildcards that the current user owns.\n\nUnknown ids and other users' ids are skipped and left out of the result, as the single delete answers 404\nfor both, so the result never confirms that someone else's id exists.",+ "operationId": "delete_wildcards",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Body_delete_wildcards"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/DeleteWildcardsResult"+ }+ }+ }+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "security": [+ {+ "HTTPBearer": []+ }+ ]+ }+ },"/api/v1/system_prompts/": {"get": {"tags": ["system_prompts"],@@ -21862,7 +21907,7 @@"video_count": {"type": "integer","title": "Video Count",- "description": "The number of videos in the board.",+ "description": "The number of videos in the board that the gallery's Media or Uploads view lists.","default": 0},"asset_count": {@@ -21873,7 +21918,7 @@"asset_video_count": {"type": "integer","title": "Asset Video Count",- "description": "The number of asset-category (non-'general') videos in the board.",+ "description": "The number of asset-category videos in the board, which the Uploads view lists.","default": 0},"owner_username": {@@ -22192,6 +22237,24 @@"required": ["image_names"],"title": "Body_delete_images_from_list"},+ "Body_delete_wildcards": {+ "properties": {+ "wildcard_ids": {+ "items": {+ "type": "string",+ "maxLength": 255+ },+ "type": "array",+ "maxItems": 1000,+ "minItems": 1,+ "title": "Wildcard Ids",+ "description": "The ids of the wildcards to delete"+ }+ },+ "type": "object",+ "required": ["wildcard_ids"],+ "title": "Body_delete_wildcards"+ },"Body_do_hf_login": {"properties": {"token": {@@ -31676,6 +31739,21 @@"required": ["affected_boards", "deleted_videos", "failed_videos"],"title": "DeleteVideosResult"},+ "DeleteWildcardsResult": {+ "properties": {+ "deleted_ids": {+ "items": {+ "type": "string"+ },+ "type": "array",+ "title": "Deleted Ids",+ "description": "The ids of the wildcards that were deleted."+ }+ },+ "type": "object",+ "required": ["deleted_ids"],+ "title": "DeleteWildcardsResult"+ },"DenoiseLatentsInvocation": {"category": "latents","class": "invocation",diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 49c0e64c1e..ffcda85d1e 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -3897,6 +3897,29 @@ export type paths = {patch: operations["update_wildcard"];trace?: never;};+ "/api/v1/wildcards/delete": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Delete Wildcards+ * @description Deletes those of the wildcards that the current user owns.+ *+ * Unknown ids and other users' ids are skipped and left out of the result, as the single delete answers 404+ * for both, so the result never confirms that someone else's id exists.+ */+ post: operations["delete_wildcards"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/api/v1/system_prompts/": {parameters: {query?: never;@@ -6326,7 +6349,7 @@ export type components = {image_count: number;/*** Video Count- * @description The number of videos in the board.+ * @description The number of videos in the board that the gallery's Media or Uploads view lists.* @default 0*/video_count?: number;@@ -6337,7 +6360,7 @@ export type components = {asset_count: number;/*** Asset Video Count- * @description The number of asset-category (non-'general') videos in the board.+ * @description The number of asset-category videos in the board, which the Uploads view lists.* @default 0*/asset_video_count?: number;@@ -6518,6 +6541,14 @@ export type components = {*/image_names: string[];};+ /** Body_delete_wildcards */+ Body_delete_wildcards: {+ /**+ * Wildcard Ids+ * @description The ids of the wildcards to delete+ */+ wildcard_ids: string[];+ };/** Body_do_hf_login */Body_do_hf_login: {/**@@ -11538,6 +11569,14 @@ export type components = {*/failed_videos: string[];};+ /** DeleteWildcardsResult */+ DeleteWildcardsResult: {+ /**+ * Deleted Ids+ * @description The ids of the wildcards that were deleted.+ */+ deleted_ids: string[];+ };/*** Denoise - SD1.5, SDXL* @description Denoises noisy latents to decodable images@@ -58402,7 +58441,7 @@ export interface operations {categories?: components["schemas"]["ImageCategory"][] | null;/** @description Whether to list intermediate items. */is_intermediate?: boolean | null;- /** @description The board id to filter by. Use 'none' to find items without a board. */+ /** @description The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read. */board_id?: string | null;/** @description The page offset */offset?: number;@@ -58462,7 +58501,7 @@ export interface operations {categories?: components["schemas"]["ImageCategory"][] | null;/** @description Whether to list intermediate items. */is_intermediate?: boolean | null;- /** @description The board id to filter by. Use 'none' to find items without a board. */+ /** @description The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read. */board_id?: string | null;/** @description The order of sort */order_dir?: components["schemas"]["SQLiteDirection"];@@ -58512,7 +58551,7 @@ export interface operations {categories?: components["schemas"]["ImageCategory"][] | null;/** @description Whether to list intermediate items. */is_intermediate?: boolean | null;- /** @description The board id to filter by. Use 'none' to find items without a board. */+ /** @description The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read. */board_id?: string | null;/** @description Restrict to items created on this ISO date, e.g. '2026-03-18'. Used by date-based virtual boards. */created_date?: string | null;@@ -58566,7 +58605,7 @@ export interface operations {categories?: components["schemas"]["ImageCategory"][] | null;/** @description Whether to list intermediate items. */is_intermediate?: boolean | null;- /** @description The board id to filter by. Use 'none' to find items without a board. */+ /** @description The board id to filter by. Use 'none' for items on no board (the current user's, unless an administrator), or 'all' for those items plus the items on every non-archived board the current user may read. */board_id?: string | null;/** @description The order of sort */order_dir?: components["schemas"]["SQLiteDirection"];@@ -61861,6 +61900,39 @@ export interface operations {};};};+ delete_wildcards: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": components["schemas"]["Body_delete_wildcards"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["DeleteWildcardsResult"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };list_system_prompts: {parameters: {query?: never;diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex be67df269e..edcdf69039 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -1095,6 +1095,7 @@"source:src/workbench/widgets/queue-status/manifest.ts","source:src/workbench/widgets/queue/manifest.ts","source:src/workbench/widgets/server-status/manifest.ts",+ "source:src/workbench/widgets/shared/AutoSwitchMenu.tsx","source:src/workbench/widgets/shortcuts/manifest.ts","source:src/workbench/widgets/upscale/manifest.ts","source:src/workbench/widgets/video/manifest.ts",diff --git a/invokeai/frontend/webv2/performance/architecture-fixtures.json b/invokeai/frontend/webv2/performance/architecture-fixtures.jsonindex ab8b9c795e..de7ca1c410 100644--- a/invokeai/frontend/webv2/performance/architecture-fixtures.json+++ b/invokeai/frontend/webv2/performance/architecture-fixtures.json@@ -105,7 +105,7 @@"path": "/#/app?new=true","readyMark": "invokeai:ready:widget:center:workflow","expectedScriptPattern": "WorkbenchApp-",- "layoutPreset": "Automate",+ "layoutPreset": "Workflow","layoutPresetId": "automate","layoutReturnPreset": "Compose","layoutReturnPresetId": "compose",@@ -122,7 +122,7 @@"path": "/#/app?project=fixture-project-001","readyMark": "invokeai:ready:widget:center:workflow","expectedScriptPattern": "WorkbenchApp-",- "layoutPreset": "Automate",+ "layoutPreset": "Workflow","layoutPresetId": "automate","layoutReturnPreset": "Compose","layoutReturnPresetId": "compose",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 17b61cdd7e..71f8467abc 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -939,6 +939,7 @@"source:src/features/gallery/ui/GalleryLayout.tsx","source:src/features/gallery/ui/GalleryLoadError.tsx","source:src/features/gallery/ui/GalleryProgressSection.tsx",+ "source:src/features/gallery/ui/GalleryProjectGroup.tsx","source:src/features/gallery/ui/GallerySearchField.tsx","source:src/features/gallery/ui/GallerySearchHelp.tsx","source:src/features/gallery/ui/GallerySelectionBar.tsx",@@ -1002,8 +1003,6 @@"source:src/features/generation/core/settings.ts","source:src/features/generation/core/supportedBases.ts","source:src/features/generation/core/systemPrompts.ts",- "source:src/features/generation/core/wildcardCatalog.ts",- "source:src/features/generation/core/wildcardTransfer.ts","source:src/features/generation/data/architectureCapabilitiesApi.ts","source:src/features/generation/data/architectureCapabilitiesStore.ts","source:src/features/generation/data/dynamicPromptsQueries.ts",@@ -1056,9 +1055,6 @@"source:src/features/generation/ui/promptFields/PromptTextarea.tsx","source:src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx","source:src/features/generation/ui/promptFields/SystemPromptsField.tsx",- "source:src/features/generation/ui/promptFields/WildcardImportDialog.tsx",- "source:src/features/generation/ui/promptFields/WildcardTransferActions.tsx",- "source:src/features/generation/ui/promptFields/WildcardsPanel.tsx","source:src/features/generation/ui/promptFields/index.ts","source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts","source:src/features/generation/ui/promptFields/promptCaret.ts",@@ -1091,7 +1087,6 @@"source:src/features/generation/ui/useDynamicPrompts.ts","source:src/features/generation/ui/usePromptTemplates.ts","source:src/features/generation/ui/useWildcards.ts",- "source:src/features/generation/ui/wildcardFiles.ts","source:src/features/generation/widget.ts","source:src/features/identity/capabilities.ts","source:src/features/identity/core/schemas.ts",@@ -1812,6 +1807,7 @@"source:src/workbench/widgets/preview/PreviewFrame.tsx","source:src/workbench/widgets/preview/PreviewHeaderActions.tsx","source:src/workbench/widgets/preview/PreviewMetadataPanel.tsx",+ "source:src/workbench/widgets/preview/PreviewNavButtons.tsx","source:src/workbench/widgets/preview/PreviewStage.tsx","source:src/workbench/widgets/preview/PreviewSwipeNeighbor.tsx","source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx",@@ -1842,6 +1838,7 @@"source:src/workbench/widgets/server-status/ServerStatusWidgetView.tsx","source:src/workbench/widgets/server-status/implementation.ts","source:src/workbench/widgets/server-status/manifest.ts",+ "source:src/workbench/widgets/shared/AutoSwitchMenu.tsx","source:src/workbench/widgets/shortcuts/ShortcutGuide.tsx","source:src/workbench/widgets/shortcuts/implementation.ts","source:src/workbench/widgets/shortcuts/manifest.ts",@@ -2033,6 +2030,7 @@"source:src/features/gallery/ui/GalleryLayout.tsx","source:src/features/gallery/ui/GalleryLoadError.tsx","source:src/features/gallery/ui/GalleryProgressSection.tsx",+ "source:src/features/gallery/ui/GalleryProjectGroup.tsx","source:src/features/gallery/ui/GallerySearchField.tsx","source:src/features/gallery/ui/GallerySearchHelp.tsx","source:src/features/gallery/ui/GallerySelectionBar.tsx",@@ -2103,8 +2101,6 @@"source:src/features/generation/core/settings.ts","source:src/features/generation/core/supportedBases.ts","source:src/features/generation/core/systemPrompts.ts",- "source:src/features/generation/core/wildcardCatalog.ts",- "source:src/features/generation/core/wildcardTransfer.ts","source:src/features/generation/data/architectureCapabilitiesApi.ts","source:src/features/generation/data/architectureCapabilitiesStore.ts","source:src/features/generation/data/dynamicPromptsQueries.ts",@@ -2157,9 +2153,6 @@"source:src/features/generation/ui/promptFields/PromptTextarea.tsx","source:src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx","source:src/features/generation/ui/promptFields/SystemPromptsField.tsx",- "source:src/features/generation/ui/promptFields/WildcardImportDialog.tsx",- "source:src/features/generation/ui/promptFields/WildcardTransferActions.tsx",- "source:src/features/generation/ui/promptFields/WildcardsPanel.tsx","source:src/features/generation/ui/promptFields/index.ts","source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts","source:src/features/generation/ui/promptFields/promptCaret.ts",@@ -2192,7 +2185,6 @@"source:src/features/generation/ui/useDynamicPrompts.ts","source:src/features/generation/ui/usePromptTemplates.ts","source:src/features/generation/ui/useWildcards.ts",- "source:src/features/generation/ui/wildcardFiles.ts","source:src/features/generation/widget.ts","source:src/features/identity/capabilities.ts","source:src/features/identity/core/schemas.ts",@@ -2937,6 +2929,7 @@"source:src/workbench/widgets/canvas/engineStoreHooks.ts","source:src/workbench/widgets/canvas/executeCanvasImageDropImport.ts","source:src/workbench/widgets/canvas/fitBbox.ts",+ "source:src/workbench/widgets/canvas/gallerySaveToast.ts","source:src/workbench/widgets/canvas/implementation.ts","source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts","source:src/workbench/widgets/canvas/invoke/canvasScaling.ts",@@ -3068,6 +3061,7 @@"source:src/workbench/widgets/preview/PreviewFrame.tsx","source:src/workbench/widgets/preview/PreviewHeaderActions.tsx","source:src/workbench/widgets/preview/PreviewMetadataPanel.tsx",+ "source:src/workbench/widgets/preview/PreviewNavButtons.tsx","source:src/workbench/widgets/preview/PreviewStage.tsx","source:src/workbench/widgets/preview/PreviewSwipeNeighbor.tsx","source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx",@@ -3098,6 +3092,7 @@"source:src/workbench/widgets/server-status/ServerStatusWidgetView.tsx","source:src/workbench/widgets/server-status/implementation.ts","source:src/workbench/widgets/server-status/manifest.ts",+ "source:src/workbench/widgets/shared/AutoSwitchMenu.tsx","source:src/workbench/widgets/shortcuts/ShortcutGuide.tsx","source:src/workbench/widgets/shortcuts/implementation.ts","source:src/workbench/widgets/shortcuts/manifest.ts",@@ -3300,6 +3295,7 @@"source:src/features/gallery/ui/GalleryLayout.tsx","source:src/features/gallery/ui/GalleryLoadError.tsx","source:src/features/gallery/ui/GalleryProgressSection.tsx",+ "source:src/features/gallery/ui/GalleryProjectGroup.tsx","source:src/features/gallery/ui/GallerySearchField.tsx","source:src/features/gallery/ui/GallerySearchHelp.tsx","source:src/features/gallery/ui/GallerySelectionBar.tsx",@@ -3363,8 +3359,6 @@"source:src/features/generation/core/settings.ts","source:src/features/generation/core/supportedBases.ts","source:src/features/generation/core/systemPrompts.ts",- "source:src/features/generation/core/wildcardCatalog.ts",- "source:src/features/generation/core/wildcardTransfer.ts","source:src/features/generation/data/architectureCapabilitiesApi.ts","source:src/features/generation/data/architectureCapabilitiesStore.ts","source:src/features/generation/data/dynamicPromptsQueries.ts",@@ -3417,9 +3411,6 @@"source:src/features/generation/ui/promptFields/PromptTextarea.tsx","source:src/features/generation/ui/promptFields/PromptTriggerAutocomplete.tsx","source:src/features/generation/ui/promptFields/SystemPromptsField.tsx",- "source:src/features/generation/ui/promptFields/WildcardImportDialog.tsx",- "source:src/features/generation/ui/promptFields/WildcardTransferActions.tsx",- "source:src/features/generation/ui/promptFields/WildcardsPanel.tsx","source:src/features/generation/ui/promptFields/index.ts","source:src/features/generation/ui/promptFields/promptAttentionHotkeys.ts","source:src/features/generation/ui/promptFields/promptCaret.ts",@@ -3452,7 +3443,6 @@"source:src/features/generation/ui/useDynamicPrompts.ts","source:src/features/generation/ui/usePromptTemplates.ts","source:src/features/generation/ui/useWildcards.ts",- "source:src/features/generation/ui/wildcardFiles.ts","source:src/features/generation/widget.ts","source:src/features/identity/capabilities.ts","source:src/features/identity/core/schemas.ts",@@ -4249,6 +4239,7 @@"source:src/workbench/widgets/preview/PreviewFrame.tsx","source:src/workbench/widgets/preview/PreviewHeaderActions.tsx","source:src/workbench/widgets/preview/PreviewMetadataPanel.tsx",+ "source:src/workbench/widgets/preview/PreviewNavButtons.tsx","source:src/workbench/widgets/preview/PreviewStage.tsx","source:src/workbench/widgets/preview/PreviewSwipeNeighbor.tsx","source:src/workbench/widgets/preview/PreviewWidgetChrome.tsx",@@ -4279,6 +4270,7 @@"source:src/workbench/widgets/server-status/ServerStatusWidgetView.tsx","source:src/workbench/widgets/server-status/implementation.ts","source:src/workbench/widgets/server-status/manifest.ts",+ "source:src/workbench/widgets/shared/AutoSwitchMenu.tsx","source:src/workbench/widgets/shortcuts/ShortcutGuide.tsx","source:src/workbench/widgets/shortcuts/implementation.ts","source:src/workbench/widgets/shortcuts/manifest.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 0b3d4377f4..7b54e34e52 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -364,6 +364,9 @@"addingImagesTo": "Adding images to {{destination}}","expandingPrompts": "Expanding prompts…","invoke": "Invoke",+ "invokeFront": "Invoke (front of queue)",+ "invokeFrontHint": "{{shortcut}} or Shift+click: add to the front of the queue",+ "invokeFrontHintNoShortcut": "Shift+click: add to the front of the queue","noNodes": "No nodes in graph","preparing": "Preparing generation…","unavailable": "Invoke unavailable: {{reason}}",@@ -377,6 +380,12 @@},"presets": {"builtIn": "Built-in",+ "builtInLabels": {+ "automate": "Workflow",+ "compose": "Compose",+ "edit": "Edit",+ "video": "Video"+ },"custom": "Custom","customLayouts": "Custom layouts","defaultDestination": "Default destination",@@ -2512,6 +2521,16 @@"dropReferenceImages": "Drop Reference Images","dynamicButton": "Dynamic","dynamicPrompts": {+ "bulkDeleteWildcardsBody_one": "Delete {{count}} selected wildcard and its values? This cannot be undone.",+ "bulkDeleteWildcardsBody_other": "Delete {{count}} selected wildcards and their values? This cannot be undone.",+ "bulkDeleteWildcardsConfirm_one": "Delete {{count}} Wildcard",+ "bulkDeleteWildcardsConfirm_other": "Delete {{count}} Wildcards",+ "clearWildcardSelection": "Clear selection",+ "couldNotDeleteWildcards": "Deleted {{deleted}} of {{count}} wildcards. The rest could not be deleted.",+ "deleteSelectedWildcardsTitle": "Delete selected wildcards",+ "selectAllWildcards": "Select all",+ "selectedWildcardCount_one": "{{count}} selected",+ "selectedWildcardCount_other": "{{count}} selected","title": "Dynamic Prompts","showPrompts": "Show dynamic prompts","noDynamicSyntax": "Wrap alternatives in braces to generate one image per combination, e.g. a {red|green} ball",@@ -3030,7 +3049,6 @@"graphJsonLabel": "Video graph JSON","hideFilmstrip": "Hide filmstrip","exitCompare": "Exit Compare",- "hideInProgressDiffusion": "Hide in-progress diffusion","imageCount_one": "{{count}} image","imageCount_other": "{{count}} images","itemCount_one": "{{count}} item",@@ -3041,7 +3059,6 @@"metadataJsonLabel": "Video metadata JSON","noGallerySelection": "No gallery selection","showFilmstrip": "Show filmstrip",- "showInProgressDiffusion": "Show in-progress diffusion","sideBySide": "Side by Side","slider": "Slider","hover": "Hover",@@ -3302,17 +3319,15 @@"saveError": "Couldn't save to gallery","saveToGallery": "Save to Gallery","saved": "Saved to gallery",- "savedDescription": "{{name}} was added to your gallery.","stale": "The canvas changed while saving. Try again."},"controls": {+ "clearCanvas": "Clear canvas","fitBboxToLayers": "Fit frame to layers","fitBboxToMasks": "Fit frame to masks","fitToView": "Fit to view","moreSaveOptions": "More save options",- "newCanvas": "New canvas","newCanvasConfirm": "Clear all layers and start a fresh canvas? This cannot be undone.",- "newSession": "New session","zoomLevel": "Zoom level"},"hideStagedResultPreview": "Hide staged result preview",@@ -3376,6 +3391,7 @@"acceptStopMessage": "Stopping the rest of its batch, which shows as cancelled in the queue.","acceptStopTitle": "Result accepted","autoSwitch": "Auto-switch",+ "autoSwitchCurrent": "Auto-switch: {{mode}}","autoSwitchLatest": "Newest","autoSwitchOff": "Off","autoSwitchProgress": "In progress",@@ -4335,6 +4351,9 @@"autoAddBadgeTooltip": "New generations, canvas saves and pasted uploads land here, as do workflow nodes whose board is Auto.","autoAddRedirectedTooltip": "You can only view {{name}}, so new generations, canvas saves and pasted uploads land here instead, as do workflow nodes whose board is Auto.","autoAddToBoard": "Auto-add to this board",+ "searchScopeAll": "All boards",+ "searchScopeBoard": "This board",+ "searchScopeCurrent": "Search in: {{scope}}","stopAutoAdd": "Stop auto-adding here","assetCount_one": "{{count}} upload","assetCount_other": "{{count}} uploads",@@ -4693,6 +4712,7 @@"uploadSuccessTitle_one": "Uploaded {{count}} file","uploadSuccessTitle_other": "Uploaded {{count}} files","uploadSummary": "{{images}} and {{videos}} uploaded to {{board}}. {{failed}} failed.",+ "uploadsUnavailableForAllBoards": "Uploads are unavailable while searching all boards","uploadsUnavailableForBoard": "Uploads can't go to {{name}}: it is no longer available.","uploadsUnavailableForDateBoards": "Uploads are unavailable for date boards","uploadsUnavailableForUnlistedBoard": "Uploads can't go to the selected board: it is no longer available.",@@ -4750,7 +4770,7 @@"maxFrames": "Max frames","framesDuration": "{{seconds}} s at the current frame rate","mainModel": "Model",- "modelRequired": "Select a Wan 2.2 or MiniMax H3 model.",+ "modelRequired": "Select a Wan 2.2, LTX-2 or MiniMax H3 model.","render": "Render","seed": "Seed","selectModel": "Select a video model…",@@ -4879,7 +4899,7 @@"imageDisplaced": "The image can't be used with the panel's conditioning clip or initial video, so that was cleared.","imageFull": "The selected video model's image slots are already in use. Send the image instead of appending it to replace them.","imageNotPlaced": "Image not placed",- "imageUnsupported": "The selected video model doesn't take images. Choose one that does, such as Wan 2.2 I2V or MiniMax H3 Ref2VA.",+ "imageUnsupported": "The selected video model doesn't take images. Choose one that does, such as Wan 2.2 I2V, LTX-2 or MiniMax H3 Ref2VA.","initialVideoFull": "All video reference slots are in use, so there is no room for the continuity reference this clip needs. Remove a video reference and try again.","initialVideoSet": "Initial video set","initialVideoUnused": "The selected video model can't extend a clip, so it won't use this initial video until you choose one that can.",diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex 8f4d1fbcb5..b67f1adcfb 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -1403,3 +1403,97 @@ test('runtime config PATCH keeps the other writable field and validates the queuassert.equal((await getJson(backend, '/api/v1/app/invocation_cache/status')).enabled, false);});});++test('board_id=all lists unboarded items and those on active readable boards, alike in items, names and location', async () => {+ await withRepresentativeBackend(async (backend) => {+ const query = 'categories=general&is_intermediate=false';+ const everything = await getJson(backend, `/api/v1/gallery/items/?${query}&limit=5000`);+ // A board of no project: a project's boards take their archived state from the project.+ const looseBoards = new Set(+ (await getJson(backend, '/api/v1/boards/?all=true'))+ .filter((board) => board.project_id === null)+ .map((board) => board.board_id)+ );+ const archivedBoardId = everything.items.find((item) => looseBoards.has(item.board_id)).board_id;+ const archive = await fetch(`${backend.origin}/api/v1/boards/${archivedBoardId}`, {+ body: JSON.stringify({ archived: true }),+ headers: { 'content-type': 'application/json' },+ method: 'PATCH',+ });+ assert.equal(archive.ok, true);++ const all = await getJson(backend, `/api/v1/gallery/items/?${query}&board_id=all&limit=5000`);+ const names = await getJson(backend, `/api/v1/gallery/items/names?${query}&board_id=all`);+ const expected = everything.items.filter((item) => item.board_id !== archivedBoardId);++ assert.ok(expected.some((item) => item.board_id === null));+ assert.ok(expected.some((item) => item.board_id !== null));+ assert.deepEqual(all.items.map((item) => item.name).sort(), expected.map((item) => item.name).sort());+ assert.equal(names.total_count, all.total);++ const hidden = everything.items.find((item) => item.board_id === archivedBoardId);+ const shown = all.items.at(-1);+ const location = (item) =>+ fetch(+ `${backend.origin}/api/v1/gallery/items/location?${query}&board_id=all&kind=${item.kind}&name=${encodeURIComponent(item.name)}`+ );+ assert.equal((await location(hidden)).status, 404);+ const found = await (await location(shown)).json();+ assert.equal(found.total, all.total);+ });+});++test('wildcards are stateful: create, rename, delete one, and delete a batch of up to 1000', async () => {+ const backend = await startMockBackend(0, { profile: 'representative' });+ const call = (path, init) =>+ fetch(`${backend.origin}${path}`, {+ ...init,+ headers: { 'content-type': 'application/json' },+ ...(init?.body === undefined ? {} : { body: JSON.stringify(init.body) }),+ });++ try {+ const seeded = await getJson(backend, '/api/v1/wildcards/');+ assert.deepEqual(+ seeded.map((wildcard) => wildcard.name),+ ['animals', 'colors', 'styles/painting']+ );++ const created = await (+ await call('/api/v1/wildcards/', { body: { name: 'moods', values: ['calm'] }, method: 'POST' })+ ).json();+ assert.equal(+ (await call('/api/v1/wildcards/', { body: { name: 'moods', values: [] }, method: 'POST' })).status,+ 409+ );+ const renamed = await (+ await call(`/api/v1/wildcards/${created.id}`, { body: { name: 'feelings' }, method: 'PATCH' })+ ).json();+ assert.deepEqual(renamed.values, ['calm']);+ assert.equal((await call(`/api/v1/wildcards/${created.id}`, { method: 'DELETE' })).status, 204);+ assert.equal((await call(`/api/v1/wildcards/${created.id}`, { method: 'DELETE' })).status, 404);++ await call('/__reset?wildcards=720', { method: 'POST' });+ const many = await getJson(backend, '/api/v1/wildcards/');+ assert.equal(many.length, 720);++ const ids = many.map((wildcard) => wildcard.id);+ const tooMany = await call('/api/v1/wildcards/delete', {+ body: { wildcard_ids: Array.from({ length: 1001 }, (_, index) => `id-${String(index)}`) },+ method: 'POST',+ });+ assert.equal(tooMany.status, 422);+ assert.equal((await call('/api/v1/wildcards/delete', { body: { wildcard_ids: [] }, method: 'POST' })).status, 422);++ const deleted = await (+ await call('/api/v1/wildcards/delete', { body: { wildcard_ids: [...ids, ids[0], 'unknown'] }, method: 'POST' })+ ).json();+ assert.deepEqual(deleted.deleted_ids, ids);+ assert.deepEqual(await getJson(backend, '/api/v1/wildcards/'), []);++ await call('/__reset?profile=empty', { method: 'POST' });+ assert.deepEqual(await getJson(backend, '/api/v1/wildcards/'), []);+ } finally {+ await backend.close();+ }+});diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 7d101a6cbd..61d90eaad2 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import { readFileSync } from 'node:fs';import { createServer } from 'node:http';import { resolve } from 'node:path';@@ -249,6 +250,29 @@ const STARTER_MODELS_RESPONSE = {const DELIVERY_CLAIM_TTL_MS = 120_000;+/** The wildcard the server stores; the caller owns every wildcard the mock holds. */+const SEEDED_WILDCARD_NAMES = ['animals', 'colors', 'styles/painting'];++/** Most ids one `POST /api/v1/wildcards/delete` takes, as `MAX_WILDCARD_BATCH_SIZE` on the server. */+const MAX_WILDCARD_BATCH_SIZE = 1000;++/** `count` wildcards: the seeded names first, then numbered ones, as `?wildcards=<count>` on a reset asks. */+const createWildcards = (count) =>+ new Map(+ Array.from({ length: count }, (_, index) => {+ const name = SEEDED_WILDCARD_NAMES[index] ?? `wildcard-${String(index + 1).padStart(4, '0')}`;+ const id = `wildcard-id-${String(index + 1).padStart(4, '0')}`;++ return [id, { id, name, user_id: MOCK_USER_ID, values: [`${name} one`, `${name} two`] }];+ })+ );++const sortedWildcards = (state) =>+ [...state.wildcards.values()].sort((left, right) => left.name.localeCompare(right.name)).map(clone);++const wildcardNameTaken = (state, name, exceptId = null) =>+ [...state.wildcards.values()].some((wildcard) => wildcard.name === name && wildcard.id !== exceptId);+const createState = (profile) => {const fixture = assertMockBackendFixture(createMockBackendFixture(profile));@@ -281,6 +305,7 @@ const createState = (profile) => {runtimeConfig: { generation_devices: 'auto', max_queue_history: null },invocationCache: { enabled: true, hits: 0, max_size: 1000, misses: 0, size: 0 },videos: new Map(fixture.videos.map((video) => [video.video_name, clone(video)])),+ wildcards: createWildcards(profile === 'empty' ? 0 : SEEDED_WILDCARD_NAMES.length),workflows: new Map(fixture.workflows.map((workflow) => [workflow.workflow_id, clone(workflow)])),nextWorkflowNumber: fixture.workflows.length + 1,/** Custom workflow thumbnails by workflow id; the version stands in for the server's cache-busting query. */@@ -562,7 +587,17 @@ const compareGalleryItems = (left, right, orderDir, starredFirst) => {);};-const filterGalleryItems = (state, url, { createdDate, starredFirst } = {}) => {+/**+ * Whether `board_id=all` lists the board's items, as the server's listing of every readable board: an active board the+ * caller may read.+ */+const isListedBoard = (state, faults, boardId) => {+ const board = state.boards.get(boardId);++ return board !== undefined && !board.archived && boardAccessFor(state, faults, board).readable;+};++const filterGalleryItems = (state, url, faults, { createdDate, starredFirst } = {}) => {const boardId = url.searchParams.get('board_id');const categories = getRequestedCategories(url);const createdFrom = url.searchParams.get('created_from');@@ -578,7 +613,11 @@ const filterGalleryItems = (state, url, { createdDate, starredFirst } = {}) => {if (mediaKind && item.kind !== mediaKind) {return false;}- if (boardId && (boardId === 'none' ? item.board_id !== null : item.board_id !== boardId)) {+ if (boardId === 'all') {+ if (item.board_id !== null && !isListedBoard(state, faults, item.board_id)) {+ return false;+ }+ } else if (boardId && (boardId === 'none' ? item.board_id !== null : item.board_id !== boardId)) {return false;}if (origin && itemOrigin !== origin) {@@ -623,19 +662,19 @@ const filterGalleryItems = (state, url, { createdDate, starredFirst } = {}) => {);};-const getGalleryItemLocation = (state, url) => {+const getGalleryItemLocation = (state, url, faults) => {const kind = url.searchParams.get('kind');const name = url.searchParams.get('name');- const items = filterGalleryItems(state, url, { starredFirst: false });+ const items = filterGalleryItems(state, url, faults, { starredFirst: false });const index = items.findIndex((item) => item.kind === kind && item.name === name);return index === -1 ? null : { kind, name, index, total: items.length };};-const listGalleryItems = (state, url) => {+const listGalleryItems = (state, url, faults) => {const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0) || 0);const limit = Math.max(0, Number(url.searchParams.get('limit') ?? 10) || 0);- const filtered = filterGalleryItems(state, url);+ const filtered = filterGalleryItems(state, url, faults);return {items: limit === 0 ? [] : filtered.slice(offset, offset + limit),@@ -645,8 +684,8 @@ const listGalleryItems = (state, url) => {};};-const listGalleryItemNames = (state, url, options) => {- const items = filterGalleryItems(state, url, options);+const listGalleryItemNames = (state, url, faults, options) => {+ const items = filterGalleryItems(state, url, faults, options);return {items: items.map(({ kind, name }) => ({ kind, name })),@@ -957,6 +996,15 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {faults = createFaults();+ const wildcardCount = url.searchParams.get('wildcards') ?? body.wildcards;+ if (wildcardCount !== undefined && wildcardCount !== null) {+ const count = Number(wildcardCount);+ if (!Number.isInteger(count) || count < 0) {+ return json(400, { detail: `Invalid wildcard count: ${String(wildcardCount)}` });+ }+ state.wildcards = createWildcards(count);+ }+const collisions = [...url.searchParams.getAll('collide'), ...(body.collide ?? [])].flatMap((value) => String(value).split(',')).map((value) => value.trim())@@ -1778,7 +1826,59 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {}if (method === 'GET' && (path === '/api/v1/wildcards' || path === '/api/v1/wildcards/')) {- return json(200, []);+ return json(200, sortedWildcards(state));+ }++ if (method === 'POST' && (path === '/api/v1/wildcards' || path === '/api/v1/wildcards/')) {+ const body = await readJsonBody(request);+ const name = typeof body.name === 'string' ? body.name.trim() : '';+ if (!name || !Array.isArray(body.values)) {+ return json(422, { detail: 'A wildcard needs a name and values' });+ }+ if (wildcardNameTaken(state, name)) {+ return json(409, { detail: `A wildcard named '${name}' already exists` });+ }+ const id = `wildcard-id-${randomUUID()}`;+ const wildcard = { id, name, user_id: MOCK_USER_ID, values: body.values.map(String) };+ state.wildcards.set(id, wildcard);+ return json(201, clone(wildcard));+ }++ if (method === 'POST' && path === '/api/v1/wildcards/delete') {+ // Mirrors the server: 1 to 1000 ids, duplicates once, unknown ids skipped and left out of the result.+ const body = await readJsonBody(request);+ const ids = body.wildcard_ids;+ if (!Array.isArray(ids) || ids.length === 0 || ids.length > MAX_WILDCARD_BATCH_SIZE) {+ return json(422, { detail: `wildcard_ids takes 1 to ${String(MAX_WILDCARD_BATCH_SIZE)} ids` });+ }+ const deletedIds = [...new Set(ids)].filter((id) => state.wildcards.delete(id));+ return json(200, { deleted_ids: deletedIds });+ }++ const wildcardMatch = /^\/api\/v1\/wildcards\/([^/]+)$/.exec(path);+ if (wildcardMatch && (method === 'PATCH' || method === 'DELETE')) {+ const id = decodeURIComponent(wildcardMatch[1]);+ const wildcard = state.wildcards.get(id);+ if (!wildcard) {+ return json(404, { detail: 'Wildcard not found' });+ }+ if (method === 'DELETE') {+ state.wildcards.delete(id);+ response.writeHead(204);+ return response.end();+ }+ const body = await readJsonBody(request);+ const name = typeof body.name === 'string' ? body.name.trim() : wildcard.name;+ if (wildcardNameTaken(state, name, id)) {+ return json(409, { detail: `A wildcard named '${name}' already exists` });+ }+ const updated = {+ ...wildcard,+ name,+ values: Array.isArray(body.values) ? body.values.map(String) : wildcard.values,+ };+ state.wildcards.set(id, updated);+ return json(200, clone(updated));}if ((method === 'PUT' || method === 'DELETE') && /^\/api\/v1\/intermediates\/holds\/[^/]+$/.test(path)) {@@ -2209,7 +2309,7 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {if (method === 'GET' && virtualBoardItemNamesMatch) {const date = decodeURIComponent(virtualBoardItemNamesMatch[1]);- return json(200, listGalleryItemNames(state, url, { createdDate: date }));+ return json(200, listGalleryItemNames(state, url, faults, { createdDate: date }));}const virtualBoardNamesMatch = /^\/api\/v1\/virtual_boards\/by_date\/([^/]+)\/image_names$/.exec(path);@@ -2392,17 +2492,17 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {}if (method === 'GET' && path === '/api/v1/gallery/items/') {- return json(200, listGalleryItems(state, url));+ return json(200, listGalleryItems(state, url, faults));}if (method === 'GET' && path === '/api/v1/gallery/items/location') {- const location = getGalleryItemLocation(state, url);+ const location = getGalleryItemLocation(state, url, faults);return location ? json(200, location) : json(404, { detail: 'Gallery item not found' });}if (method === 'GET' && path === '/api/v1/gallery/items/names') {- return json(200, listGalleryItemNames(state, url));+ return json(200, listGalleryItemNames(state, url, faults));}const imageAssetMatch = /^\/api\/v1\/images\/i\/([^/]+)\/(full|thumbnail)$/.exec(path);diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex a2eb1b911b..d70677d2bb 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -248,7 +248,7 @@ const surfaces = [path: representativeProjectPath,ready: async (page) => {await waitForWorkbench(page);- await selectLayoutPreset(page, 'Automate', 'Workflow');+ await selectLayoutPreset(page, 'Workflow', 'Workflow');await page.getByText('Fixture Node 001', { exact: true }).waitFor();// Pan the y=0 fixture clear of the floating toolbar before measuring targets.const pane = await page.locator('.react-flow__pane').boundingBox();@@ -910,7 +910,7 @@ const runKeepAliveStateJourney = async (browser) => {assert.equal((await zoomTrigger.textContent())?.trim(), '200%', 'The zoom control must report the chosen zoom.');// Away and back, which is the whole point of keeping the widgets mounted.- await selectLayoutPreset(page, 'Automate', 'Workflow');+ await selectLayoutPreset(page, 'Workflow', 'Workflow');await waitForSettledDocument(page);await selectLayoutPreset(page, 'Edit', 'Canvas');await waitForSettledDocument(page);diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjsindex 4da577bc72..70a62a9bf3 100644--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs@@ -629,7 +629,7 @@ const runWorkflowCollection = async ({ browser, contexts, errors, imported }) =>await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();await page.goto(`${origin}/#/app?project=${encodeURIComponent(projectId)}`, { waitUntil: 'domcontentloaded' });await page.getByRole('main', { exact: true, name: imported.name }).waitFor();- await selectLayoutPreset(page, 'Automate', 'Workflow');+ await selectLayoutPreset(page, 'Workflow', 'Workflow');const workflowName = () => page.getByRole('button', { name: /^Open this project's workflows\. Current workflow: / });const dialog = page.getByRole('dialog', { exact: true, name: 'Workflows' });@@ -739,7 +739,7 @@ const runWorkflowCollection = async ({ browser, contexts, errors, imported }) =>// Restart: both workflows and the active selection come back from the server.await page.reload({ waitUntil: 'domcontentloaded' });await page.getByRole('main', { exact: true, name: imported.name }).waitFor();- await selectLayoutPreset(page, 'Automate', 'Workflow');+ await selectLayoutPreset(page, 'Workflow', 'Workflow');assert.equal(await currentWorkflowName(), 'Journey Saved');await openProjectWorkflows();assert.equal(await cards.count(), 2);@@ -809,7 +809,7 @@ const runUnloadRecovery = async ({ browser, contexts, errors, imported }) => {waitUntil: 'domcontentloaded',});await main.waitFor();- await selectLayoutPreset(page, 'Automate', 'Workflow');+ await selectLayoutPreset(page, 'Workflow', 'Workflow');};const rename = (name) => renameActiveWorkflow(page, name);@@ -981,7 +981,7 @@ const runSecondOrigin = async ({ browser, contexts, errors, imported, importedBoassert.equal(unchanged.workspace.revision, opened.workspace.revision);// One edit in each half: the workflow's name is content, the layout preset is the caller's workspace.- await selectLayoutPreset(page, 'Automate', 'Workflow');+ await selectLayoutPreset(page, 'Workflow', 'Workflow');await renameActiveWorkflow(page, 'Second origin');await page.keyboard.press('Escape');await selectLayoutPreset(page, 'Compose', 'Preview');diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsxindex 16b612b4fb..1120e97be0 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.test.tsx@@ -70,6 +70,15 @@ describe('Gallery live-follow adapter', () => {expect(openWorkbenchWidget).toHaveBeenCalledExactlyOnceWith('preview');});+ it('shows live frames in the Gallery only while Auto-switch is In progress', () => {+ const modes = (['progress', 'latest', 'off'] as const).map((mode) => {+ store.commands.account.updateProjectPreferences({ viewerAutoSwitch: mode });+ return renderAdapter().liveFollowEnabled;+ });++ expect(modes).toEqual([true, false, false]);+ });+it('ignores a follow retained across an account change', () => {const owner = renderAdapter();diff --git a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsxindex 38fd8ba671..51aaef96ae 100644--- a/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GalleryUiAdapter.tsx@@ -53,7 +53,7 @@ export const GalleryUiAdapterProvider = ({ children }: { children: ReactNode })galleryValues: getProjectWidgetInstance(project, 'gallery')?.state?.values ?? EMPTY_WIDGET_VALUES,generateValues: getProjectWidgetInstance(project, 'generate')?.state?.values ?? EMPTY_WIDGET_VALUES,antialiasProgressImages: project.settings.antialiasProgressImages,- liveFollowEnabled: project.settings.showProgressImagesInViewer,+ liveFollowEnabled: project.settings.viewerAutoSwitch === 'progress',}));const livePreview = useLivePreviewFollow();const boardSharing = useAuthSession().multiuserEnabled;diff --git a/invokeai/frontend/webv2/src/features/gallery/README.md b/invokeai/frontend/webv2/src/features/gallery/README.mdindex 2a6d34549a..645dda294c 100644--- a/invokeai/frontend/webv2/src/features/gallery/README.md+++ b/invokeai/frontend/webv2/src/features/gallery/README.md@@ -2,7 +2,7 @@Paths are relative to the webv2 `src/` directory.-Gallery ordinary listings are Query-owned sparse pages shared by grid, picker, Preview, and deep-reveal flows. The Gallery widget's media kind (both, images, or videos) is part of the canonical listing filter, present only when restricted; the picker always lists both kinds. Page key = account lifetime + canonical listing filters + aligned absolute offset; each result keeps its authoritative total and absolute item positions so hydrated gaps never compact. Consumers own separate visible ranges and scroll anchors. Cold numbered page after page zero first requests count-only metadata, then reads only its clamped 60-item page; virtual scrolling discovers count from its first item page. Recent local completions use a temporary overlay, with listing-scoped membership evidence bounded by recent-item limit so an authoritative item does not reappear in overlay when its page is evicted. Query layer retains at most ten inactive idle pages per listing while protecting observed pages, and schedules at most four distinct page reads per QueryClient. Deep reveal resolves an item's filtered listing rank, reads its containing page, verifies item at returned absolute position, and retries that rank/page check at most once if offsets shifted. Persisted Preview selection keeps listing identity, media kind included, from when item was selected (a stamp without a media kind lists both); changing active Gallery filters does not rewrite that cursor. Preview re-resolves a stale item page after listing mutations; its async navigation is fenced by captured account epoch so a late page cannot stamp selection into a newer account lifetime.+Gallery ordinary listings are Query-owned sparse pages shared by grid, picker, Preview, and deep-reveal flows. The Gallery widget's media kind (both, images, or videos) is part of the canonical listing filter, present only when restricted; the picker always lists both kinds. Page key = account lifetime + canonical listing filters + aligned absolute offset; each result keeps its authoritative total and absolute item positions so hydrated gaps never compact. Consumers own separate visible ranges and scroll anchors. Cold numbered page after page zero first requests count-only metadata, then reads only its clamped 60-item page; virtual scrolling discovers count from its first item page. Recent local completions use a temporary overlay, with listing-scoped membership evidence bounded by recent-item limit so an authoritative item does not reappear in overlay when its page is evicted. Query layer retains at most ten inactive idle pages per listing while protecting observed pages, and schedules at most four distinct page reads per QueryClient. Deep reveal resolves an item's filtered listing rank, reads its containing page, verifies item at returned absolute position, and retries that rank/page check at most once if offsets shifted. Persisted Preview selection keeps listing identity, media kind included, from when item was selected (a stamp without a media kind lists both); changing active Gallery filters does not rewrite that cursor. While a search is active, the Gallery's `searchScope` setting can widen the listing from the selected board to `ALL_READABLE_BOARDS_ID` (`all`): the caller's own unboarded items plus every non-archived board they may read, as the backend's `board_id=all` defines it. Only the listing's board id changes (`getGalleryListingBoardId`); the selected board, the auto-add board and upload destinations stay put, uploads are refused while it applies, and a selection made in it is stamped `all`, so Preview steps through the search's results. Clearing the search returns the scope to `board`. Preview re-resolves a stale item page after listing mutations; its async navigation is fenced by captured account epoch so a late page cannot stamp selection into a newer account lifetime.## Realtime refresh and external revealdiff --git a/invokeai/frontend/webv2/src/features/gallery/contracts.ts b/invokeai/frontend/webv2/src/features/gallery/contracts.tsindex 6ee8c7df4d..c4dc783967 100644--- a/invokeai/frontend/webv2/src/features/gallery/contracts.ts+++ b/invokeai/frontend/webv2/src/features/gallery/contracts.ts@@ -73,12 +73,14 @@ export {getGalleryMediaFilterMenuProps,getGalleryDestinationBoardId,getGalleryPage,+ getGalleryListingBoardId,getGallerySelectedBoardId,getGallerySelectionBoardId,getGallerySelectedImagePage,getGallerySelectedImageQuery,getGallerySemanticImageQuery,getGalleryView,+ settleGallerySearchScope,type GallerySelectedImageQuery,} from './ui/galleryStateView';export {diff --git a/invokeai/frontend/webv2/src/features/gallery/core/items.ts b/invokeai/frontend/webv2/src/features/gallery/core/items.tsindex ce4b7b0b35..a050b603db 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/items.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/items.ts@@ -283,4 +283,10 @@ export const classifyGalleryUpload = (file: Pick<File, 'name' | 'type'>): { kind/** Virtual "by date" boards (`by_date:<YYYY-MM-DD>`) list items but can never receive them. */export const DATE_BOARD_ID_PREFIX = 'by_date:';+/**+ * The listing scope of every board the caller may read plus their Uncategorized items, as the gallery endpoints take+ * it for `board_id`. A scope, not a board: nothing is ever stored on it.+ */+export const ALL_READABLE_BOARDS_ID = 'all';+export const isDateBoardId = (boardId: string): boolean => boardId.startsWith(DATE_BOARD_ID_PREFIX);diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.test.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.test.tsindex 13737a5c1c..4865670ab7 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { getGallerySettings, isGalleryBoardSectionOpen, toggleGalleryBoardSection } from './settings';+import {+ getGallerySettings,+ isGalleryBoardSectionOpen,+ toggleGalleryBoardSection,+ toggleGalleryProjectGroup,+} from './settings';describe('board panel sections', () => {it('starts other users’ boards collapsed, even for a panel that saved its collapsed groups before', () => {@@ -22,3 +27,65 @@ describe('board panel sections', () => {expect(closed).toMatchObject({ collapsedBoardSections: ['shared'], expandedBoardSections: ['other-users'] });});});++describe('project groups under Other projects', () => {+ it('starts with every group expanded', () => {+ expect(getGallerySettings({}).collapsedProjectGroupIds).toEqual([]);+ });++ it('keeps distinct project ids only, dropping anything that is not a string', () => {+ const settings = getGallerySettings({ collapsedProjectGroupIds: ['a', 7, null, 'b', 'a', { id: 'c' }] });++ expect(settings.collapsedProjectGroupIds).toEqual(['b', 'a']);+ expect(getGallerySettings({ collapsedProjectGroupIds: 'a' }).collapsedProjectGroupIds).toEqual([]);+ });++ it('remembers at most 200 groups, keeping the most recently collapsed', () => {+ const ids = Array.from({ length: 205 }, (_, index) => `project-${String(index)}`);++ const stored = getGallerySettings({ collapsedProjectGroupIds: ids }).collapsedProjectGroupIds;+ const collapsedOneMore = toggleGalleryProjectGroup(+ getGallerySettings({ collapsedProjectGroupIds: ids }),+ 'new',+ false+ );++ expect(stored).toHaveLength(200);+ expect(stored[0]).toBe('project-5');+ expect(collapsedOneMore.collapsedProjectGroupIds).toHaveLength(200);+ expect(collapsedOneMore.collapsedProjectGroupIds.at(-1)).toBe('new');+ expect(collapsedOneMore.collapsedProjectGroupIds).not.toContain('project-5');+ });++ it('keeps the newest 200 of a huge imported list without scanning it per entry', () => {+ const ids = Array.from({ length: 50_000 }, (_, index) => `project-${String(index)}`);+ // An id counts at its last occurrence: an old one collapsed again is new, and a repeat takes no second slot.+ ids.push('project-7', 'project-49995');++ const started = performance.now();+ const stored = getGallerySettings({ collapsedProjectGroupIds: ids }).collapsedProjectGroupIds;+ const elapsedMs = performance.now() - started;++ expect(stored).toHaveLength(200);+ expect(stored[0]).toBe('project-49801');+ expect(stored.slice(-3)).toEqual(['project-49999', 'project-7', 'project-49995']);+ // A per-entry scan of the whole list takes seconds here.+ expect(elapsedMs).toBeLessThan(500);+ });++ it('collapses and expands one group without touching the others', () => {+ const settings = getGallerySettings({ collapsedProjectGroupIds: ['a'] });++ expect(toggleGalleryProjectGroup(settings, 'b', false).collapsedProjectGroupIds).toEqual(['a', 'b']);+ expect(toggleGalleryProjectGroup(settings, 'a', true).collapsedProjectGroupIds).toEqual([]);+ });+});++describe('search scope', () => {+ it('searches the selected board unless all boards were chosen', () => {+ expect(getGallerySettings({}).searchScope).toBe('board');+ expect(getGallerySettings({ searchScope: 'all' }).searchScope).toBe('all');+ expect(getGallerySettings({ searchScope: 'everywhere' }).searchScope).toBe('board');+ expect(getGallerySettings({ searchScope: null }).searchScope).toBe('board');+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts b/invokeai/frontend/webv2/src/features/gallery/core/settings.tsindex 3cecbdc8c9..14f3cfefe7 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/settings.ts@@ -16,6 +16,15 @@ export const getGalleryMediaFilter = (values: Record<string, unknown>): GalleryMexport const toGalleryMediaKind = (filter: GalleryMediaFilter): GalleryItemKind | undefined =>filter === 'all' ? undefined : filter;+/**+ * Where a search looks: the selected board, or every board the caller may read plus their Uncategorized items. It+ * applies only while a search is active; clearing the search returns it to `board`.+ */+export type GallerySearchScope = 'board' | 'all';++/** The most project groups under Other projects whose collapse is remembered; the newest are kept. */+export const GALLERY_COLLAPSED_PROJECT_GROUPS_LIMIT = 200;+/** The collapsible groups in the board panel, in render order. */export const GALLERY_BOARD_SECTION_IDS = ['project',@@ -59,6 +68,8 @@ export interface GallerySettings {boardPanelHeightPx: number;boardPanelWidthPx: number;collapsedBoardSections: GalleryBoardSectionId[];+ /** Project groups under Other projects that are collapsed, by project id; oldest first. */+ collapsedProjectGroupIds: string[];/** The groups that start collapsed which have been opened. */expandedBoardSections: GalleryBoardSectionId[];imageDensityPercent: number;@@ -74,6 +85,7 @@ export interface GallerySettings {showOtherProjectBoards: boolean;showPendingItems: boolean;progressSectionCollapsed: boolean;+ searchScope: GallerySearchScope;/** Disclosure of the starred strip at the top of the grid. */starredSectionCollapsed: boolean;thumbnailFit: GalleryThumbnailFit;@@ -87,6 +99,7 @@ export const DEFAULT_GALLERY_SETTINGS: GallerySettings = {boardPanelHeightPx: 280,boardPanelWidthPx: 240,collapsedBoardSections: [],+ collapsedProjectGroupIds: [],expandedBoardSections: [],imageDensityPercent: 50,imageOrderDir: 'DESC',@@ -99,6 +112,7 @@ export const DEFAULT_GALLERY_SETTINGS: GallerySettings = {showOtherProjectBoards: false,showPendingItems: true,progressSectionCollapsed: false,+ searchScope: 'board',starredSectionCollapsed: false,thumbnailFit: 'square',};@@ -123,6 +137,41 @@ const getBoardSections = (value: unknown, candidates: readonly GalleryBoardSecti? candidates.filter((sectionId) => value.some((entry) => isBoardSectionId(entry) && entry === sectionId)): [];+/**+ * Distinct strings, each at its last occurrence, at most the limit's newest. One pass from the end stops at the+ * limit, so an imported workspace with a huge list costs no more than the ids it keeps.+ */+const getCollapsedProjectGroupIds = (value: unknown): string[] => {+ if (!Array.isArray(value)) {+ return [];+ }++ const kept = new Set<string>();++ for (let index = value.length - 1; index >= 0 && kept.size < GALLERY_COLLAPSED_PROJECT_GROUPS_LIMIT; index--) {+ const entry: unknown = value[index];++ if (typeof entry === 'string') {+ kept.add(entry);+ }+ }++ return [...kept].reverse();+};++/** The settings change that collapses or expands one project's group under Other projects. */+export const toggleGalleryProjectGroup = (+ settings: GallerySettings,+ projectId: string,+ isOpen: boolean+): Pick<GallerySettings, 'collapsedProjectGroupIds'> => {+ const others = settings.collapsedProjectGroupIds.filter((id) => id !== projectId);++ return {+ collapsedProjectGroupIds: isOpen ? others : [...others, projectId].slice(-GALLERY_COLLAPSED_PROJECT_GROUPS_LIMIT),+ };+};+export const isGalleryBoardSectionOpen = (settings: GallerySettings, sectionId: GalleryBoardSectionId): boolean =>GALLERY_BOARD_SECTIONS_COLLAPSED_BY_DEFAULT.includes(sectionId)? settings.expandedBoardSections.includes(sectionId)@@ -172,6 +221,7 @@ export const getGallerySettings = (values: Record<string, unknown>): GallerySettvalues.collapsedBoardSections,GALLERY_BOARD_SECTION_IDS.filter((sectionId) => !GALLERY_BOARD_SECTIONS_COLLAPSED_BY_DEFAULT.includes(sectionId))),+ collapsedProjectGroupIds: getCollapsedProjectGroupIds(values.collapsedProjectGroupIds),expandedBoardSections: getBoardSections(values.expandedBoardSections, GALLERY_BOARD_SECTIONS_COLLAPSED_BY_DEFAULT),imageDensityPercent:typeof values.imageDensityPercent === 'number' && Number.isFinite(values.imageDensityPercent)@@ -200,6 +250,7 @@ export const getGallerySettings = (values: Record<string, unknown>): GallerySett? values.showPendingItems: DEFAULT_GALLERY_SETTINGS.showPendingItems,progressSectionCollapsed: values.progressSectionCollapsed === true,+ searchScope: values.searchScope === 'all' ? 'all' : DEFAULT_GALLERY_SETTINGS.searchScope,starredSectionCollapsed:typeof values.starredSectionCollapsed === 'boolean'? values.starredSectionCollapseddiff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.tsindex 6818e46672..a10e2e5165 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts@@ -20,6 +20,7 @@ vi.mock('@platform/transport/http', async (importOriginal) => ({import { ApiError } from '@platform/transport/http';import {+ ALL_READABLE_BOARDS_ID,addImagesToGalleryBoard,createGalleryBoard,galleryBoardExists,@@ -243,6 +244,41 @@ describe('media kind restriction', () => {});});+describe('all-boards scope', () => {+ beforeEach(() => {+ accountLifecycle.activate('user-a');+ mocks.apiFetchJson.mockReset();+ mocks.apiFetchJson.mockResolvedValue({+ index: 0,+ items: [],+ kind: 'image',+ name: 'a.png',+ total: 0,+ total_count: 0,+ });+ });++ it('sends the all-boards scope as-is to the items, names and location reads', async () => {+ const scope = { boardId: ALL_READABLE_BOARDS_ID, galleryView: 'images', searchTerm: 'cat' } as const;++ await listGalleryItems(scope);+ await listGalleryItemNames({ ...scope, orderDir: 'DESC' });+ await getGalleryItemLocation({ ...scope, kind: 'image', name: 'a.png', orderDir: 'DESC' });++ const requests = mocks.apiFetchJson.mock.calls.map(([url]) => String(url));+ expect(requests.map((url) => url.split('?')[0])).toEqual([+ '/api/v1/gallery/items/',+ '/api/v1/gallery/items/names',+ '/api/v1/gallery/items/location',+ ]);+ expect(requests.map((url) => new URLSearchParams(url.split('?')[1]).get('board_id'))).toEqual([+ 'all',+ 'all',+ 'all',+ ]);+ });+});+describe('getGalleryImageByName', () => {beforeEach(() => {mocks.apiFetchJson.mockReset();@@ -842,6 +878,25 @@ describe('board media counts and covers', () => {expect(boards[0]).toMatchObject({ id: 'none', kind: 'uncategorized', videoCount: 7 });});+ it('counts only the uncategorized videos the Media and Uploads views list', async () => {+ mocks.apiFetchJson.mockImplementation((path: string) =>+ Promise.resolve(path.startsWith('/api/v1/boards/') ? [] : { total: 0 })+ );++ await listGalleryBoards();++ const videoTotals = mocks.apiFetchJson.mock.calls+ .map(([path]) => String(path))+ .filter((path) => path.startsWith('/api/v1/videos/'))+ .map((path) => new URLSearchParams(path.slice(path.indexOf('?') + 1)));+ // An OTHER video is in neither view, so neither total may include it.+ expect(videoTotals.map((query) => query.getAll('categories').sort())).toEqual([+ ['control', 'general', 'mask', 'user'],+ ['control', 'mask', 'user'],+ ]);+ expect(videoTotals.every((query) => query.get('board_id') === 'none')).toBe(true);+ });+it('treats a board with only videos as non-empty even though image_count is 0', async () => {mocks.apiFetchJson.mockImplementation((path: string) => {if (path.startsWith('/api/v1/boards/')) {diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 309c67e2ab..171a3d8ab7 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -22,7 +22,12 @@ import type {GalleryView,} from '@features/gallery/core/types';-import { DATE_BOARD_ID_PREFIX, isDateBoardId, parseGalleryItemKey } from '@features/gallery/core/items';+import {+ ALL_READABLE_BOARDS_ID,+ DATE_BOARD_ID_PREFIX,+ isDateBoardId,+ parseGalleryItemKey,+} from '@features/gallery/core/items';import { getExternalImageFile, getImageCluster } from '@features/gallery/core/semanticImageQuery';import { isTimestampInRange } from '@platform/search/dateTokens';import {@@ -44,14 +49,7 @@ import { getGalleryVideoThumbnailUrl } from './videoUrls';type BackendBoardDTO = components['schemas']['BoardDTO'];-/**- * 'board' is a real backend board; 'uncategorized' is the pseudo-board for- * unassigned images (board_id 'none'); 'date' is a read-only virtual board- * grouping images by creation date (id 'by_date:YYYY-MM-DD').- */-export const ALL_READABLE_BOARDS_ID = 'all';--export { isDateBoardId };+export { ALL_READABLE_BOARDS_ID, isDateBoardId };const getDateFromBoardId = (boardId: string): string => boardId.slice(DATE_BOARD_ID_PREFIX.length);@@ -347,9 +345,9 @@ export const listGalleryBoards = async ({boardsBodyPromise,getGalleryTotal({ boardId: 'none', categories: imageCategories, signal }),getGalleryTotal({ boardId: 'none', categories: assetCategories, signal }),- // Real boards carry `video_count` in their DTO, but the uncategorized pseudo-board is- // assembled here, so its video totals need their own requests.- getGalleryVideoTotal({ boardId: 'none', signal }),+ // Real boards carry `video_count` in their DTO, but the uncategorized pseudo-board is assembled here, so its+ // video totals need their own requests. Like a board's, they count only what the Media and Uploads views list.+ getGalleryVideoTotal({ boardId: 'none', categories: [...imageCategories, ...assetCategories], signal }),getGalleryVideoTotal({ boardId: 'none', categories: assetCategories, signal }),]);const boards = Array.isArray(body) ? body : (body.items ?? []);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 fe09c9ba54..1c4414e3a9 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@@ -84,12 +84,15 @@ const createGallery = (settings: Partial<GallerySettings> = {}): GalleryStateViecompareImageKey: null,galleryView: 'images',isComparisonActive: false,+ isSearchActive: false,items: [],+ listingBoardId: 'dogs',page: 0,pendingPlaceholders: [],primarySelectedItemKey: null,projectBoardId: 'mine',revealTargetPage: null,+ searchScope: 'board',searchTerm: '',selectedBoardId: 'dogs',semanticImageQuery: null,@@ -157,7 +160,7 @@ const renderPanel = async (gallery: GalleryStateView = createGallery(), { withDrconst getBoardRows = (): HTMLElement[] =>Array.from(host?.querySelectorAll<HTMLElement>(- '[data-scope="collapsible"][data-part="content"] button[type="button"]:not(.board-row-actions)'+ '[data-scope="collapsible"][data-part="content"] button[type="button"]:not(.board-row-actions):not([data-gallery-project-group])') ?? []);@@ -171,7 +174,7 @@ const getRowsBySection = (): Record<string, string[]> => {// 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)'+ '[data-scope="collapsible"][data-part="content"] button[type="button"]:not(.board-row-actions):not([data-gallery-project-group])')).map((row) =>(row.textContent ?? '')@@ -454,6 +457,16 @@ describe('GalleryBoardsPanel', () => {expect(actions.moveBoard).not.toHaveBeenCalled();});+ it("takes a drop on a collapsed project's group, by its heading", async () => {+ await renderPanel(createGallery({ collapsedProjectGroupIds: ['p2'], showOtherProjectBoards: true }), {+ withDrag: true,+ });++ await dragWithMouse(row('dogs'), heading('Harbor Tower'));++ expect(actions.moveBoard).toHaveBeenCalledExactlyOnceWith('dogs', 'p2', 'Harbor Tower');+ });+it('takes a drop on a collapsed tier, by its heading', async () => {await renderPanel(createGallery({ collapsedBoardSections: ['library'] }), { withDrag: true });@@ -682,6 +695,50 @@ describe('GalleryBoardsPanel', () => {expect(actions.updateSettings).toHaveBeenCalledWith({ collapsedBoardSections: ['project'] });});+ describe('a project group under Other projects', () => {+ const toggle = () => host!.querySelector<HTMLButtonElement>('button[data-gallery-project-group="p2"]')!;++ it('collapses on its own, saved through the gallery settings', async () => {+ await renderPanel(createGallery({ collapsedProjectGroupIds: ['p9'], showOtherProjectBoards: true }));++ expect(toggle().getAttribute('aria-expanded')).toBe('true');+ expect(document.getElementById(toggle().getAttribute('aria-controls')!)?.textContent).toContain('Stripes');++ await click(toggle());++ expect(actions.updateSettings).toHaveBeenCalledExactlyOnceWith({ collapsedProjectGroupIds: ['p9', 'p2'] });+ });++ it('shows no rows while collapsed, and expands again by keyboard', async () => {+ await renderPanel(createGallery({ collapsedProjectGroupIds: ['p2'], showOtherProjectBoards: true }));++ expect(toggle().getAttribute('aria-expanded')).toBe('false');+ expect(getRowsBySection()['Other projects']).toEqual([]);+ // The section still says what it holds while its only group is closed.+ expect(host?.textContent).toContain('Harbor Tower');++ toggle().focus();+ await userEvent.keyboard('{Enter}');+ await userEvent.keyboard(' ');++ expect(actions.updateSettings).toHaveBeenNthCalledWith(1, { collapsedProjectGroupIds: [] });+ expect(actions.updateSettings).toHaveBeenNthCalledWith(2, { collapsedProjectGroupIds: [] });+ });++ it("shows a search's matches in a collapsed group without changing what is saved", async () => {+ await renderPanel(createGallery({ collapsedProjectGroupIds: ['p2'], showOtherProjectBoards: true }));++ await type(getSearchInput(), 'Strip');++ expect(getRowsBySection()['Other projects']).toEqual(['Stripes']);+ expect(toggle().getAttribute('aria-expanded')).toBe('true');++ await click(toggle());++ expect(actions.updateSettings).not.toHaveBeenCalled();+ });+ });+it('toggles every board group and the sort order from the one options menu', async () => {await renderPanel();diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsxindex 1f93558bfb..de9a2f26a5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardsPanel.tsx@@ -6,7 +6,11 @@ import { Box, HStack, Icon, ScrollArea, Stack, Text } from '@chakra-ui/react';import { useDndContext, useDroppable } from '@dnd-kit/core';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';import { toGalleryItemKey } from '@features/gallery/core/items';-import { isGalleryBoardSectionOpen, toggleGalleryBoardSection } from '@features/gallery/core/settings';+import {+ isGalleryBoardSectionOpen,+ toggleGalleryBoardSection,+ toggleGalleryProjectGroup,+} from '@features/gallery/core/settings';import { usePreservedScrollOffset } from '@platform/react/usePreservedScrollOffset';import { IconButton } from '@platform/ui/Button';import { RenameDialog } from '@platform/ui/RenameDialog';@@ -29,6 +33,7 @@ import {getGalleryBoardTierDropId,} from './galleryDnd';import { focusVisibleOperable, GalleryLoadNotice } from './GalleryLoadError';+import { GalleryProjectGroup } from './GalleryProjectGroup';import { getGalleryRedirectedDestination } from './galleryStateView';import { useGalleryWidget } from './GalleryWidgetContext';@@ -161,6 +166,15 @@ export const GalleryBoardsPanel = () => {);const isSectionOpen = (sectionId: GalleryBoardSectionId) => isGalleryBoardSectionOpen(gallery.settings, sectionId);+ const collapsedProjectGroupIds = useMemo(+ () => new Set(gallery.settings.collapsedProjectGroupIds),+ [gallery.settings.collapsedProjectGroupIds]+ );+ const handleToggleProjectGroup = useCallback(+ (groupProjectId: string, isOpen: boolean) =>+ actions.updateSettings(toggleGalleryProjectGroup(gallery.settings, groupProjectId, isOpen)),+ [actions, gallery.settings]+ );// 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. While it loads, the fixed rows alone would read as empty tiers.const isBoardListUnavailable = boardsState.status === 'error';@@ -345,20 +359,13 @@ export const GalleryBoardsPanel = () => {{renderDropTier(group.projectId,group.label,- <Stack gap="0.5">- <Text- color="fg.muted"- fontSize="xs"- fontWeight="600"- pe="2"- ps="2"- pt="1"- role="heading"- aria-level={4}- truncate- >- {group.label}- </Text>+ <GalleryProjectGroup+ isCollapsed={collapsedProjectGroupIds.has(group.projectId)}+ isSearching={trimmedSearchTerm !== ''}+ label={group.label}+ projectId={group.projectId}+ onToggle={handleToggleProjectGroup}+ >{group.boards.map((board) =>// Every other project's inbox is called "Inbox"; assistive tech needs the project in the name.renderRow(@@ -366,7 +373,7 @@ export const GalleryBoardsPanel = () => {board.isInbox ? t('widgets.gallery.inboxOf', { project: group.label }) : undefined))}- </Stack>+ </GalleryProjectGroup>)}</Fragment>))}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryGridFocus.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryGridFocus.browser.test.tsxindex 6a0329dc21..0e56e6331c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryGridFocus.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryGridFocus.browser.test.tsx@@ -164,10 +164,13 @@ const createGallery = (items: GalleryItem[], selected: GalleryItem | null): GallcompareImageKey: null,galleryView: 'images',isComparisonActive: false,+ isSearchActive: false,items,+ listingBoardId: 'board-a',page: 0,projectBoardId: null,revealTargetPage: null,+ searchScope: 'board',searchTerm: '',selectedBoardId: 'board-a',...selectionOf(selected),@@ -690,7 +693,13 @@ describe('Gallery grid keyboard focus', () => {);await act(() =>setState({- gallery: { ...state.gallery, items: createItems(6, 'other'), selectedBoardId: 'board-b', ...selectionOf(null) },+ gallery: {+ ...state.gallery,+ items: createItems(6, 'other'),+ listingBoardId: 'board-b',+ selectedBoardId: 'board-b',+ ...selectionOf(null),+ },galleryValues: { ...state.galleryValues, selectedBoardId: 'board-b', selectedImageNames: [] },strip: stripB,})@@ -711,7 +720,7 @@ describe('Gallery grid keyboard focus', () => {await act(() =>setState({- gallery: { ...state.gallery, items: [], selectedBoardId: 'board-b' },+ gallery: { ...state.gallery, items: [], listingBoardId: 'board-b', selectedBoardId: 'board-b' },listing: { ...READY_LISTING, status: 'loading' },}));diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsxindex ddcc5fd681..797235515b 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.browser.test.tsx@@ -332,12 +332,15 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateVcompareImageKey: null,galleryView: 'images',isComparisonActive: false,+ isSearchActive: false,items,+ listingBoardId: overrides.selectedBoardId ?? board.id,page: 0,// A visible selection is the persisted primary; tests whose primary is off-page name it explicitly.primarySelectedItemKey: overrides.selectedItemKey === undefined ? 'image:first.png' : overrides.selectedItemKey,revealTargetPage: null,projectBoardId: null,+ searchScope: 'board',searchTerm: '',selectedBoardId: board.id,selectedItemKey: 'image:first.png',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 9e948655e8..7713a4f48b 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@@ -1,5 +1,6 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';+import type { GallerySearchScope } from '@features/gallery/core/settings';import type { GalleryBoard } from '@features/gallery/core/types';import type { ImageIndexAvailability } from '@features/gallery/data/backend';import type { GalleryUiAdapter } from '@features/gallery/react';@@ -11,7 +12,7 @@ import { system } from '@theme/system';import { act, useMemo, useState, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { page } from 'vitest/browser';+import { page, userEvent } from 'vitest/browser';import type { GalleryWidgetContextValue } from './GalleryWidgetContext';@@ -86,6 +87,7 @@ const adapter: GalleryUiAdapter = {const actions = {clearSearch: vi.fn(),commitSemanticSearch: vi.fn(),+ setSearchScope: vi.fn(),setSearchTerm: vi.fn(),setSemanticImageQuery: vi.fn(),setSemanticSearchMode: vi.fn(),@@ -96,6 +98,7 @@ const archivedBoards = [{ archived: true, id: 'old-board' }];interface HarnessGallery {boards: Array<Pick<GalleryBoard, 'archived' | 'id'>>;+ searchScope: GallerySearchScope;searchTerm: string;selectedBoardId: string;semanticImageQuery: GallerySemanticReference | null;@@ -106,6 +109,7 @@ interface HarnessGallery {const Harness = ({ initial }: { initial: Partial<HarnessGallery> }) => {const [gallery, setGallery] = useState<HarnessGallery>({boards: [],+ searchScope: 'board',searchTerm: '',selectedBoardId: 'none',semanticImageQuery: null,@@ -117,6 +121,21 @@ const Harness = ({ initial }: { initial: Partial<HarnessGallery> }) => {({actions: {...actions,+ // As the Gallery's actions do: clearing the search clears its scope too.+ clearSearch: () => {+ actions.clearSearch();+ setGallery((current) => ({+ ...current,+ searchScope: 'board',+ searchTerm: '',+ semanticImageQuery: null,+ semanticSearchText: null,+ }));+ },+ setSearchScope: (searchScope: GallerySearchScope) => {+ actions.setSearchScope(searchScope);+ setGallery((current) => ({ ...current, searchScope }));+ },setSearchTerm: (searchTerm: string) => {actions.setSearchTerm(searchTerm);setGallery((current) => ({ ...current, searchTerm }));@@ -126,7 +145,13 @@ const Harness = ({ initial }: { initial: Partial<HarnessGallery> }) => {setGallery((current) => ({ ...current, semanticSearchText }));},},- gallery,+ gallery: {+ ...gallery,+ isSearchActive:+ gallery.searchTerm.trim() !== '' ||+ gallery.semanticImageQuery !== null ||+ (gallery.semanticSearchText ?? '').trim() !== '',+ },}) as unknown as GalleryWidgetContextValue,[gallery]);@@ -436,3 +461,61 @@ describe('GalleryItemSearch semantic mode', () => {expect(actions.clearSearch).toHaveBeenCalledOnce();});});++describe('GalleryItemSearch scope', () => {+ const getScope = () => host?.querySelector<HTMLButtonElement>('button[data-gallery-search-scope]') ?? null;++ it('offers a scope only while a search is active, inside the search row', async () => {+ await renderSearch();+ const height = host!.getBoundingClientRect().height;++ expect(getScope()).toBeNull();++ await typeInto('cat');++ expect(page.getByRole('button', { name: 'widgets.gallery.searchScopeAll' }).element()).toBe(getScope());+ expect(getScope()?.getAttribute('aria-pressed')).toBe('false');+ // Typing never grows the header row, so the grid below stays put.+ expect(host!.getBoundingClientRect().height).toBe(height);+ });++ it('offers it for a semantic search, and for an image similarity search', async () => {+ await renderSearch({ semanticSearchText: 'sunset' });+ expect(getScope()).not.toBeNull();++ await act(() => root?.unmount());+ root = createRoot(host!);+ await renderSearch({ semanticImageQuery: { imageName: 'ref.png', kind: 'image' } });+ expect(getScope()).not.toBeNull();+ });++ it('switches to every board by keyboard', async () => {+ await renderSearch({ searchTerm: 'cat' });++ getScope()?.focus();+ await userEvent.keyboard('{Enter}');++ expect(actions.setSearchScope).toHaveBeenCalledExactlyOnceWith('all');+ expect(getScope()?.getAttribute('aria-pressed')).toBe('true');+ });++ it('leaves with the search when it is cleared', async () => {+ await renderSearch({ searchScope: 'all', searchTerm: 'cat' });++ await act(() => host?.querySelector<HTMLButtonElement>('button[aria-label="common.clearSearch"]')?.click());++ expect(actions.clearSearch).toHaveBeenCalledOnce();+ expect(getScope()).toBeNull();+ });++ it('does not blame an archived selected board for an empty search of every board', async () => {+ await renderSearch({+ boards: archivedBoards,+ searchScope: 'all',+ selectedBoardId: 'old-board',+ semanticSearchText: 'sunset',+ });++ expect(host?.textContent).not.toContain('widgets.gallery.semanticSearchArchivedBoard');+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsxindex 4ec4a54493..e0d0ab0cdf 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryItemSearch.tsx@@ -1,6 +1,6 @@import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';-import { Box, HStack, Icon, Text } from '@chakra-ui/react';+import { Box, HStack, Icon, Stack, Text } from '@chakra-ui/react';import { semanticReferenceFromDataTransfer } from '@features/gallery/core/semanticImageQuery';import { imageIndexAvailabilityOptions } from '@features/gallery/data/queries';import { isImeComposing } from '@platform/browser/imeComposition';@@ -9,7 +9,7 @@ import { describeDateRange, findInvalidDateToken, formatIsoDate, parseDateTokensimport { CloseButton, ToggleIconButton } from '@platform/ui/Button';import { InputShell } from '@platform/ui/InputShell';import { useQuery } from '@tanstack/react-query';-import { ImageIcon, MapIcon, SparklesIcon } from 'lucide-react';+import { ImageIcon, LibraryBigIcon, MapIcon, SparklesIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';import { flushSync } from 'react-dom';import { useTranslation } from 'react-i18next';@@ -154,6 +154,31 @@ export const GalleryItemSearch = () => {actions.clearSearch();}, [actions, cancelPendingCommit]);const handleClearSemantic = useCallback(() => actions.setSemanticImageQuery(null), [actions]);+ const handleSearchScopeChange = useCallback(+ (searchAllBoards: boolean) => actions.setSearchScope(searchAllBoards ? 'all' : 'board'),+ [actions]+ );+ const isSearchingAllBoards = gallery.searchScope === 'all';+ // Only a search has a scope, and it sits inside the search row so choosing one never moves the grid. The selected+ // board and where results go stay as they are.+ const scopeToggle = useMemo(+ () =>+ gallery.isSearchActive ? (+ <ToggleIconButton+ checked={isSearchingAllBoards}+ color={isSearchingAllBoards ? 'accent.fg' : 'fg.muted'}+ data-gallery-search-scope=""+ icon={LibraryBigIcon}+ label={t('widgets.gallery.searchScopeAll')}+ tooltip={t('widgets.gallery.searchScopeCurrent', {+ scope: isSearchingAllBoards ? t('widgets.gallery.searchScopeAll') : t('widgets.gallery.searchScopeBoard'),+ })}+ variant="ghost"+ onCheckedChange={handleSearchScopeChange}+ />+ ) : null,+ [gallery.isSearchActive, handleSearchScopeChange, isSearchingAllBoards, t]+ );// In-app drags (dnd-kit) resolve through GalleryBoardDragMonitor; this hook// only registers the drop target and reports hover for the highlight.@@ -220,7 +245,10 @@ export const GalleryItemSearch = () => {// explicit member lists, not rankings, so they are exempt.const isRankedSearch =isSemanticMode || (gallery.semanticImageQuery !== null && gallery.semanticImageQuery.kind !== 'cluster');- const isArchivedBoard = gallery.boards.some((board) => board.id === gallery.selectedBoardId && board.archived);+ // A search of every board leaves archived boards out by design, so the selected board's state says nothing then.+ const isArchivedBoard =+ gallery.searchScope === 'board' &&+ gallery.boards.some((board) => board.id === gallery.selectedBoardId && board.archived);const semanticHint =isSemanticMode && indexAvailability?.state === 'model_missing'? t('widgets.gallery.semanticSearchModelMissing', { model: indexAvailability.modelName ?? '' })@@ -275,9 +303,20 @@ export const GalleryItemSearch = () => {[handleToggleSemanticMode, isSemanticMode, showSemanticToggle, t]);+ const chipToggles = useMemo(+ () => (+ <>+ {scopeToggle}+ {semanticToggle}+ </>+ ),+ [scopeToggle, semanticToggle]+ );+const endElement = useMemo(() => (<HStack flexShrink={0} gap="0">+ {scopeToggle}{semanticToggle}{isSemanticMode || gallery.searchTerm ? (<CloseButton@@ -290,7 +329,7 @@ export const GalleryItemSearch = () => {{isSemanticMode ? null : <GallerySearchHelp />}</HStack>),- [gallery.searchTerm, handleClearSearch, isSemanticMode, semanticToggle, t]+ [gallery.searchTerm, handleClearSearch, isSemanticMode, scopeToggle, semanticToggle, t]);return (@@ -306,36 +345,38 @@ export const GalleryItemSearch = () => {onDragOver={handleNativeDragOver}onDrop={handleNativeDrop}>- {/*- * Image/file/cluster chips replace semantic text mode. Legacy text chips remain readable; toggling switches- * a chip to typed search.- */}- {!isSemanticMode && gallery.semanticImageQuery ? (- <GallerySemanticChip- reference={gallery.semanticImageQuery}- toggle={semanticToggle}- onClear={handleClearSemantic}- />- ) : (- <GallerySearchField- ref={inputRef}- ariaLabel={- isSemanticMode ? t('widgets.gallery.semanticSearchAriaLabel') : t('widgets.gallery.searchImagesAriaLabel')- }- describedById={hint ? SEARCH_HINT_ID : undefined}- endElement={endElement}- isInvalid={invalidHint !== null}- mode={isSemanticMode ? 'semantic' : 'metadata'}- placeholder={- isSemanticMode- ? t('widgets.gallery.semanticSearchPlaceholder')- : t('widgets.gallery.searchImagesPlaceholder')- }- value={isSemanticMode ? semanticText : gallery.searchTerm}- onChange={handleChange}- onKeyDown={handleKeyDown}- />- )}+ <Stack gap="1" minW="0">+ {/*+ * Image/file/cluster chips replace semantic text mode. Legacy text chips remain readable; toggling switches+ * a chip to typed search.+ */}+ {!isSemanticMode && gallery.semanticImageQuery ? (+ <GallerySemanticChip+ reference={gallery.semanticImageQuery}+ toggle={chipToggles}+ onClear={handleClearSemantic}+ />+ ) : (+ <GallerySearchField+ ref={inputRef}+ ariaLabel={+ isSemanticMode ? t('widgets.gallery.semanticSearchAriaLabel') : t('widgets.gallery.searchImagesAriaLabel')+ }+ describedById={hint ? SEARCH_HINT_ID : undefined}+ endElement={endElement}+ isInvalid={invalidHint !== null}+ mode={isSemanticMode ? 'semantic' : 'metadata'}+ placeholder={+ isSemanticMode+ ? t('widgets.gallery.semanticSearchPlaceholder')+ : t('widgets.gallery.searchImagesPlaceholder')+ }+ value={isSemanticMode ? semanticText : gallery.searchTerm}+ onChange={handleChange}+ onKeyDown={handleKeyDown}+ />+ )}+ </Stack>{hint ? (<Textcolor={invalidHint ? 'fg.error' : 'fg.warning'}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsxindex 0304116b36..cd11daace2 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryLayout.browser.test.tsx@@ -70,8 +70,10 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}) =>compareImageKey: null,galleryView: 'images',items: [createItem('a.png'), createItem('b.png')],+ listingBoardId: overrides.selectedBoardId ?? 'dogs',pendingPlaceholders: [],projectBoardId: null,+ searchScope: 'board',searchTerm: '',selectedBoardId: 'dogs',selectedItemKey: 'image:a.png',diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProjectGroup.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProjectGroup.tsxnew file mode 100644index 0000000000..32d8a293b6--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProjectGroup.tsx@@ -0,0 +1,74 @@+import { Box, chakra, Icon, Stack, Text } from '@chakra-ui/react';+import { ChevronRightIcon } from 'lucide-react';+import { useCallback, useId, type ReactNode } from 'react';++const TOGGLE_HOVER_STYLES = { color: 'fg' } as const;+const TOGGLE_DISABLED_STYLES = { cursor: 'default' } as const;++/**+ * One project's boards under Other projects, behind a disclosure named by the project. While the board search has+ * text the group shows its matches whatever its saved state, so a search never hides one; the saved state is left+ * as it is. A collapsed group renders no rows: the boards panel is not virtualized.+ */+export const GalleryProjectGroup = ({+ children,+ isCollapsed,+ isSearching,+ label,+ projectId,+ onToggle,+}: {+ children: ReactNode;+ isCollapsed: boolean;+ isSearching: boolean;+ label: string;+ projectId: string;+ onToggle: (projectId: string, isOpen: boolean) => void;+}) => {+ const contentId = useId();+ const isOpen = isSearching || !isCollapsed;+ const handleClick = useCallback(() => onToggle(projectId, !isOpen), [isOpen, onToggle, projectId]);++ return (+ <Stack gap="0.5">+ <Box aria-level={4} role="heading">+ <chakra.button+ alignItems="center"+ aria-controls={contentId}+ aria-expanded={isOpen}+ color="fg.muted"+ data-gallery-project-group={projectId}+ disabled={isSearching}+ display="flex"+ gap="1"+ minW="0"+ pe="2"+ ps="2"+ pt="1"+ rounded="sm"+ textAlign="start"+ transition="color var(--wb-motion-duration-fast) ease"+ type="button"+ w="full"+ _disabled={TOGGLE_DISABLED_STYLES}+ _hover={TOGGLE_HOVER_STYLES}+ onClick={handleClick}+ >+ <Icon+ as={ChevronRightIcon}+ boxSize="3"+ flexShrink={0}+ transform={isOpen ? 'rotate(90deg)' : undefined}+ transition="transform var(--wb-motion-duration-medium)"+ />+ <Text as="span" fontSize="xs" fontWeight="600" truncate>+ {label}+ </Text>+ </chakra.button>+ </Box>+ <Stack display={isOpen ? undefined : 'none'} gap="0.5" id={contentId}>+ {isOpen ? children : null}+ </Stack>+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsxindex 9a956cd333..e4546d1480 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryStackedLayout.tsx@@ -147,7 +147,7 @@ export const GalleryStackedLayout = () => {<GalleryItemSortMenu /><GalleryUploadButtonboards={gallery.boards}- selectedBoardId={gallery.selectedBoardId}+ selectedBoardId={gallery.listingBoardId}onUploadFiles={actions.uploadFiles}/></HStack>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.tsindex 75fd18436e..cb55087299 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.test.ts@@ -36,6 +36,13 @@ describe('getGalleryUploadTargetLabel', () => {});});+ it('is unavailable while a search looks in every board, which has no board of its own to upload to', () => {+ expect(getGalleryUploadTargetLabel([board], 'all', t)).toEqual({+ isAvailable: false,+ label: 'widgets.gallery.uploadsUnavailableForAllBoards',+ });+ });+it('marks date boards unavailable', () => {expect(getGalleryUploadTargetLabel([board], 'by_date:2026-09-04', t)).toEqual({isAvailable: false,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.tsxindex a71afcf975..5b9384d394 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUploadButton.tsx@@ -4,6 +4,7 @@ import type { TFunction } from 'i18next';import { Icon } from '@chakra-ui/react';import { canOnBoard } from '@features/gallery/core/boardAccess';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';+import { ALL_READABLE_BOARDS_ID } from '@features/gallery/core/items';import { isDateBoardId } from '@features/gallery/data/backend';import { IconButton } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';@@ -12,12 +13,19 @@ import { useTranslation } from 'react-i18next';import { useGalleryUploadInput } from './useGalleryUploadInput';-/** Tooltip/aria text for an upload control; null when the board cannot receive uploads. */+/**+ * Tooltip/aria text for an upload control, given the board the listing reads; unavailable when it cannot receive+ * uploads.+ */export const getGalleryUploadTargetLabel = (boards: readonly GalleryBoard[],selectedBoardId: string,t: TFunction): { isAvailable: boolean; label: string } => {+ if (selectedBoardId === ALL_READABLE_BOARDS_ID) {+ return { isAvailable: false, label: t('widgets.gallery.uploadsUnavailableForAllBoards') };+ }+if (isDateBoardId(selectedBoardId)) {return { isAvailable: false, label: t('widgets.gallery.uploadsUnavailableForDateBoards') };}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsxindex 0d0a496471..d6fc25dba7 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx@@ -87,7 +87,7 @@ export const GalleryWideLayout = () => {<GalleryItemSortMenu /><GalleryUploadButtonboards={gallery.boards}- selectedBoardId={gallery.selectedBoardId}+ selectedBoardId={gallery.listingBoardId}onUploadFiles={actions.uploadFiles}/></HStack>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsxindex e87dcde440..cafb568d70 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetContext.tsx@@ -1,6 +1,6 @@import type { GalleryImageItem, GalleryItem, GalleryItemRef } from '@features/gallery/contracts';import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';-import type { GallerySettings } from '@features/gallery/core/settings';+import type { GallerySearchScope, GallerySettings } from '@features/gallery/core/settings';import type { GalleryGeneralAccess, GalleryView } from '@features/gallery/core/types';import type { GalleryItemsFilter } from '@features/gallery/data/queries';import type { GalleryItemStarPatchEvent } from '@features/gallery/data/queryCache';@@ -40,6 +40,8 @@ export interface GalleryActions {selectItemRange: (items: GalleryItemRef[], primaryItem: GalleryItem, selectionPage?: number) => void;setCompareItem: (image: GalleryImageItem | null) => void;setSearchTerm: (searchTerm: string) => void;+ /** Where a search looks: the selected board, or every readable board; resets the page like a search. */+ setSearchScope: (searchScope: GallerySearchScope) => void;/** Restricts (or releases) the listing to starred items; resets the page like a search. */setStarredOnly: (starredOnly: boolean) => void;/** Clears the search field: its text, any ranking, and semantic mode. */diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsxindex c4fd3cfd6d..b6b0fca33f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetView.tsx@@ -25,6 +25,7 @@ import {getGalleryPage,getGalleryProjectBoardId,getGalleryRawSelectedBoardId,+ getGallerySearchScope,getGallerySearchTerm,getGallerySemanticImageQuery,getGalleryStarredOnly,@@ -115,6 +116,7 @@ export const GalleryWidgetView = ({ presentation, region, runtime }: GalleryWidgpage,projectBoardId: getGalleryProjectBoardId(galleryValues),recentImages,+ searchScope: getGallerySearchScope(galleryValues),searchTerm,selectedBoardId: getGalleryRawSelectedBoardId(galleryValues),semanticQuery,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex 0184798ebe..ad4c86b2b7 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -9,7 +9,9 @@ import {getGalleryAutoAddBoardId,getGalleryRedirectedDestination,getGalleryDestinationBoardId,+ getGalleryListingBoardId,getGallerySelectedBoardId,+ getGallerySelectionBoardId,getGallerySelectedImageQuery,getGallerySemanticImageQuery,getGalleryListing,@@ -173,6 +175,7 @@ describe('gallery state view', () => {boardPanelHeightPx: 280,boardPanelWidthPx: 240,collapsedBoardSections: [],+ collapsedProjectGroupIds: [],expandedBoardSections: [],imageDensityPercent: 50,imageOrderDir: 'DESC',@@ -185,6 +188,7 @@ describe('gallery state view', () => {showOtherProjectBoards: false,showPendingItems: true,progressSectionCollapsed: false,+ searchScope: 'board',starredSectionCollapsed: false,thumbnailFit: 'square',});@@ -260,6 +264,48 @@ describe('gallery state view', () => {)).toBe(2);expect(pageOf({ semanticImageQuery: { imageName: 'ref.png', kind: 'image' } })).toBeNull();+ // A search of every board is its own listing: a stamp made there names it rather than the selected board.+ expect(pageOf({ searchScope: 'all', searchTerm: 'cats' }, { searchTerm: 'cats' })).toBeNull();+ expect(pageOf({ searchScope: 'all', searchTerm: 'cats' }, { boardId: 'all', searchTerm: 'cats' })).toBe(2);+ expect(pageOf({ searchTerm: 'cats' }, { boardId: 'all', searchTerm: 'cats' })).toBeNull();+ });++ it('searches every board only while a search is active, leaving the selected board as it is', () => {+ const view = (values: Record<string, unknown>) =>+ getGalleryStateView({ searchScope: 'all', selectedBoardId: 'board-1', ...values }, boards, []);+ const searching = [+ { searchTerm: 'cat' },+ { semanticSearchText: 'sunset' },+ { semanticImageQuery: { imageName: 'ref.png', kind: 'image' } },+ ];++ for (const search of searching) {+ expect(view(search)).toMatchObject({+ isSearchActive: true,+ listingBoardId: 'all',+ searchScope: 'all',+ selectedBoardId: 'board-1',+ });+ expect(getGallerySelectionBoardId({ searchScope: 'all', selectedBoardId: 'board-1', ...search })).toBe('all');+ expect(getGalleryListingBoardId({ searchScope: 'all', selectedBoardId: 'board-1', ...search }, boards)).toBe(+ 'all'+ );+ }++ // No search, or only blank text: the scope does not apply.+ for (const idle of [{}, { searchTerm: ' ' }, { semanticSearchText: '' }]) {+ expect(view(idle)).toMatchObject({ isSearchActive: false, listingBoardId: 'board-1', searchScope: 'board' });+ expect(getGallerySelectionBoardId({ searchScope: 'all', selectedBoardId: 'board-1', ...idle })).toBe('board-1');+ }++ expect(view({ searchScope: 'board', searchTerm: 'cat' })).toMatchObject({+ listingBoardId: 'board-1',+ searchScope: 'board',+ });+ // Where pasted or generated media lands is not the listing's scope.+ expect(getGalleryDestinationBoardId({ searchScope: 'all', searchTerm: 'cat', selectedBoardId: 'board-1' })).toBe(+ 'board-1'+ );});it('reads the starred-only filter as a strict boolean and stamps it on the selection query', () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex a0d7a23508..c624a8fe84 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -4,6 +4,7 @@ import type { TFunction } from 'i18next';import { canOnBoard } from '@features/gallery/core/boardAccess';import {+ ALL_READABLE_BOARDS_ID,isDateBoardId,toGalleryItemKey,type GalleryItem,@@ -24,6 +25,7 @@ import {getGallerySettings,toGalleryMediaKind,type GalleryMediaFilter,+ type GallerySearchScope,type GallerySettings,} from '@features/gallery/core/settings';import { FilmIcon, ImageIcon, LayersIcon } from 'lucide-react';@@ -88,8 +90,15 @@ export interface GalleryStateView {galleryView: GalleryView;/** A compare image is set and differs from the visible image selection. */isComparisonActive: boolean;+ /** A text, date or semantic search narrows the listing, so the search scope applies. */+ isSearchActive: boolean;/** The current scope's listing only; how it stands (loading, failed, ...) is the listing read state's to say. */items: GalleryItem[];+ /**+ * The board id the listing reads: the selected board, or `ALL_READABLE_BOARDS_ID` while a search looks in every+ * board. A selection made in the grid is stamped with it.+ */+ listingBoardId: string;/** The grid's current page in paginated mode; the window anchor otherwise. */page: number;projectBoardId: string | null;@@ -98,7 +107,10 @@ export interface GalleryStateView {* the grid is showing; null otherwise. Reveals follow it across pages.*/revealTargetPage: number | null;+ /** Where the current search looks; `board` whenever no search is active. */+ searchScope: GallerySearchScope;searchTerm: string;+ /** The board the panel shows as selected; a search of every board leaves it as it is. */selectedBoardId: string;/** The persisted primary selection, retained while its sparse page is not loaded. */primarySelectedItemKey: GalleryItemKey | null;@@ -134,16 +146,37 @@ export const getGallerySemanticImageQuery = (values: Record<string, unknown>): Gexport const getGallerySemanticSearchText = (values: Record<string, unknown>): string | null =>typeof values.semanticSearchText === 'string' ? values.semanticSearchText : null;+/** A text, date or semantic search narrows the listing: the only time the search scope applies. */+export const isGallerySearchActive = (values: Record<string, unknown>): boolean =>+ getGallerySearchTerm(values).trim() !== '' ||+ getGallerySemanticImageQuery(values) !== null ||+ (getGallerySemanticSearchText(values) ?? '').trim() !== '';++/**+ * Gallery values with the search scope settled: with no active search the scope returns to 'board', so the next+ * search starts on the selected board whatever cleared the last one (the field, a reveal, a load-time strip). The+ * values themselves when nothing changes. Every write of gallery values goes through it.+ */+export const settleGallerySearchScope = (values: Record<string, unknown>): Record<string, unknown> =>+ values.searchScope === 'all' && !isGallerySearchActive(values) ? { ...values, searchScope: 'board' } : values;++/** Where the current search looks: every readable board only while a search is active and that scope is chosen. */+export const getGallerySearchScope = (values: Record<string, unknown>): GallerySearchScope =>+ getGallerySettings(values).searchScope === 'all' && isGallerySearchActive(values) ? 'all' : 'board';+/** The saved board choice as persisted, before any resolution against loaded boards. */export const getGalleryRawSelectedBoardId = (values: Record<string, unknown>): string | null =>typeof values.selectedBoardId === 'string' ? values.selectedBoardId : null;/**- * The board a selection made in the grid is stamped with: the saved choice, else the project board the grid falls- * back to showing. Stamping Uncategorized instead points Preview at a listing the selection is not in.+ * The board a selection made in the grid is stamped with: the scope of every board while a search looks there, else+ * the saved choice, else the project board the grid falls back to showing. Stamping Uncategorized instead points+ * Preview at a listing the selection is not in.*/export const getGallerySelectionBoardId = (values: Record<string, unknown>): string =>- getGalleryRawSelectedBoardId(values) ?? getGalleryProjectBoardId(values) ?? 'none';+ getGallerySearchScope(values) === 'all'+ ? ALL_READABLE_BOARDS_ID+ : (getGalleryRawSelectedBoardId(values) ?? getGalleryProjectBoardId(values) ?? 'none');/*** Use the chosen destination or project board; date buckets defer to the project, while explicit none remains@@ -224,6 +257,13 @@ export const getGallerySelectedBoardId = (values: Record<string, unknown>, backebackendBoards);+/**+ * The board id the Gallery's listing reads: `ALL_READABLE_BOARDS_ID` while a search looks in every board, else the+ * selected board. Not a destination: uploads and results never go to it.+ */+export const getGalleryListingBoardId = (values: Record<string, unknown>, backendBoards: GalleryBoard[]): string =>+ getGallerySearchScope(values) === 'all' ? ALL_READABLE_BOARDS_ID : getGallerySelectedBoardId(values, backendBoards);+export const getGalleryPage = (values: Record<string, unknown>): number =>typeof values.galleryPage === 'number' && Number.isFinite(values.galleryPage)? Math.max(0, Math.floor(values.galleryPage))@@ -287,15 +327,15 @@ export const getGallerySelectedImageQuery = (values: Record<string, unknown>): G};/**- * The selection was made in the listing the view shows: its stamp names the same board, view, order, search,- * starred filter and media kind. A selection stamped elsewhere (another board, or before a search or filter changed) is not this- * listing's, though it persists across those switches.+ * The selection was made in the listing the view shows: its stamp names the same board (or the scope of every board),+ * view, order, search, starred filter and media kind. A selection stamped elsewhere (another board, or before a search+ * or filter changed) is not this listing's, though it persists across those switches.*/export const isGallerySelectionInScope = (selectedImageQuery: GallerySelectedImageQuery,- scope: Pick<GalleryStateView, 'galleryView' | 'searchTerm' | 'selectedBoardId' | 'settings' | 'starredOnly'>+ scope: Pick<GalleryStateView, 'galleryView' | 'listingBoardId' | 'searchTerm' | 'settings' | 'starredOnly'>): boolean =>- selectedImageQuery.boardId === scope.selectedBoardId &&+ selectedImageQuery.boardId === scope.listingBoardId &&selectedImageQuery.galleryView === scope.galleryView &&selectedImageQuery.imageOrderDir === scope.settings.imageOrderDir &&selectedImageQuery.mediaKind === (toGalleryMediaKind(scope.settings.mediaFilter) ?? null) &&@@ -432,6 +472,8 @@ export const getGalleryStateView = (},];const selectedBoardId = getGallerySelectedBoardId(values, backendBoards);+ const searchScope = getGallerySearchScope(values);+ const listingBoardId = searchScope === 'all' ? ALL_READABLE_BOARDS_ID : selectedBoardId;const compareImage = getGalleryCompareImage(values);const compareImageKey = compareImage ? toGalleryItemKey({ kind: 'image', name: compareImage.imageName }) : null;const isComparisonActive =@@ -447,8 +489,8 @@ export const getGalleryStateView = (semanticImageQuery === null &&isGallerySelectionInScope(selectedImageQuery, {galleryView,+ listingBoardId,searchTerm,- selectedBoardId,settings,starredOnly,}) &&@@ -464,10 +506,13 @@ export const getGalleryStateView = (compareImageKey,galleryView,isComparisonActive,+ isSearchActive: isGallerySearchActive(values),items,+ listingBoardId,page,projectBoardId: getGalleryProjectBoardId(values),revealTargetPage,+ searchScope,searchTerm,selectedBoardId,primarySelectedItemKey: persistedSelectedItemKey,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 70f09dc7a1..3b6822d5e0 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@@ -1105,3 +1105,25 @@ describe('setSemanticImageQuery', () => {});});});++describe('search scope', () => {+ it('starts a newly scoped listing from its first page', () => {+ actionsRef.current?.setSearchScope('all');++ expect(patchGalleryValues).toHaveBeenCalledExactlyOnceWith({ galleryPage: 0, searchScope: 'all' });+ });++ it('refuses uploads while a search looks in every board, before any request', async () => {+ galleryValues = { searchScope: 'all', searchTerm: 'cat' };+ await renderProbe();++ const uploaded = await actionsRef.current?.uploadFiles([new File(['x'], 'a.png', { type: 'image/png' })]);++ expect(uploaded).toEqual([]);+ expect(mocks.ensureGalleryBoardDestinations).not.toHaveBeenCalled();+ expect(mocks.uploadGalleryImage).not.toHaveBeenCalled();+ expect(mocks.notificationsReportError).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'widgets.gallery.uploadsUnavailableForAllBoards' })+ );+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.tsindex b33c6c5bfe..646661648a 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryActions.ts@@ -1,7 +1,7 @@import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';-import { toGalleryItemKey } from '@features/gallery/core/items';+import { ALL_READABLE_BOARDS_ID, toGalleryItemKey } from '@features/gallery/core/items';import { GALLERY_AUTO_ADD_FOLLOW, getGallerySettings } from '@features/gallery/core/settings';import {createGalleryBoard,@@ -23,6 +23,7 @@ import { useTranslation } from 'react-i18next';import type { GalleryActions } from './GalleryWidgetContext';+import { getGallerySearchScope } from './galleryStateView';import { useGalleryUi } from './GalleryUiContext';import { useGalleryUploadAction } from './useGalleryUploadAction';@@ -47,9 +48,15 @@ export const useGalleryActions = ({const { ensureProjectOnServer, exportProject, gallery, galleryValues, notifications, projectId, widgets } =useGalleryUi();const { autoAddBoardId, showOtherProjectBoards } = getGallerySettings(galleryValues);+ const isSearchingAllBoards = getGallerySearchScope(galleryValues) === 'all';const queryClient = useQueryClient();const { t } = useTranslation();- const uploadFiles = useGalleryUploadAction({ boards, getCurrentGalleryLocation, selectedBoardId });+ // A search of every board has no board to upload to; the upload action refuses it.+ const uploadFiles = useGalleryUploadAction({+ boards,+ getCurrentGalleryLocation,+ selectedBoardId: isSearchingAllBoards ? ALL_READABLE_BOARDS_ID : selectedBoardId,+ });return useMemo<GalleryActions>(() => {const recordError = (error: unknown) =>@@ -334,6 +341,8 @@ export const useGalleryActions = ({? gallery.setItemMultiSelection(items.map(toGalleryItemKey), primaryItem): gallery.setItemMultiSelection(items.map(toGalleryItemKey), primaryItem, selectionPage),setCompareItem: gallery.setCompareItem,+ setSearchScope: (scope) => widgets.patchGalleryValues({ galleryPage: 0, searchScope: scope }),+ // Clearing the search returns its scope to the selected board; the gallery values' writer keeps that rule.setSearchTerm: gallery.setSearchTerm,setStarredOnly: gallery.setStarredOnly,setSemanticSearchMode: gallery.setSemanticSearchMode,@@ -342,13 +351,14 @@ export const useGalleryActions = ({clearSearch: gallery.clearSearch,// Store references in widget values, reset pagination, and clear replaced text/mode so hidden filters cannot// affect listing or Preview navigation.- setSemanticImageQuery: (reference) =>+ setSemanticImageQuery: (reference) => {widgets.patchGalleryValues({galleryPage: 0,searchTerm: '',semanticImageQuery: reference,semanticSearchText: null,- }),+ });+ },setView: gallery.setView,toggleItemInSelection: gallery.toggleItemSelection,updateSettings: gallery.updateSettings,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.tsindex 75d2719a1b..66e60b66d5 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryData.ts@@ -1,6 +1,6 @@import type { GalleryItem, GalleryItemKind } from '@features/gallery/core/items';import type { GallerySemanticReference } from '@features/gallery/core/semanticImageQuery';-import type { GallerySettings } from '@features/gallery/core/settings';+import type { GallerySearchScope, GallerySettings } from '@features/gallery/core/settings';import type { GalleryBoard, GalleryView, GeneratedImageContract } from '@features/gallery/core/types';import { compareGalleryItems, legacyGeneratedImageToGalleryItem, toGalleryItemKey } from '@features/gallery/core/items';@@ -48,7 +48,7 @@ export interface GalleryData {filter: GalleryItemsFilter;hasMore: boolean;isLoadingItems: boolean;- /** The resolved board the items were fetched for. */+ /** The resolved selected board; the items came from it unless the search looks in every board. */selectedBoardId: string;/** Distinguish reaching the window cap from reaching the board end; only truncation needs an explanation. */isWindowTruncated: boolean;@@ -261,6 +261,7 @@ export const useGalleryData = ({page,projectBoardId,recentImages,+ searchScope = 'board',searchTerm,selectedBoardId,semanticQuery = null,@@ -279,6 +280,8 @@ export const useGalleryData = ({page: number;projectBoardId: string | null;recentImages: readonly GeneratedImageContract[];+ /** `all` lists every readable board instead of the selected one; consumers without a search scope omit it. */+ searchScope?: GallerySearchScope;searchTerm: string;selectedBoardId: string | null;/** When set, items come from semantic search (similarity order) instead of the board listing. */@@ -294,7 +297,8 @@ export const useGalleryData = ({sparseViewport?: boolean;}): GalleryData => {const { boards, boardsState } = useGalleryBoards({ settings });- const boardId = resolveGallerySelectedBoardId({ projectBoardId, selectedBoardId }, boards);+ const resolvedSelectedBoardId = resolveGallerySelectedBoardId({ projectBoardId, selectedBoardId }, boards);+ const boardId = searchScope === 'all' ? ALL_READABLE_BOARDS_ID : resolvedSelectedBoardId;const queryClient = useQueryClient();const isPaginated = settings.paginationMode === 'paginated';const dateParse = useMemo(() => parseDateTokens(searchTerm), [searchTerm]);@@ -898,7 +902,7 @@ export const useGalleryData = ({loadMore,queryError: sparseViewport ? (pageError ?? firstPageError ?? (hasUnresolvedTotalError ? totalError : null)) : error,previousScopeItems,- selectedBoardId: boardId,+ selectedBoardId: resolvedSelectedBoardId,pinRevealIndex: sparseViewport && !isPaginated ? pinRevealIndex : undefined,setVisibleRange: sparseViewport ? setVisibleRange : undefined,sparseListing,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.tsindex 88b867070e..3b6c2317cf 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts@@ -4,6 +4,7 @@ import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';import { canOnBoard } from '@features/gallery/core/boardAccess';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';import {+ ALL_READABLE_BOARDS_ID,classifyGalleryUpload,compareGalleryItems,legacyGeneratedImageToGalleryItem,@@ -71,6 +72,16 @@ export const useGalleryUploadAction = ({typeof selectedBoardIdOrGetter === 'function' ? selectedBoardIdOrGetter() : selectedBoardIdOrGetter;let selectedBoardId = readSelectedBoardId();+ // A search of every board has no board of its own to upload to; Uncategorized would be a guess.+ if (selectedBoardId === ALL_READABLE_BOARDS_ID) {+ notifications.reportError({+ area: 'gallery-upload',+ message: t('widgets.gallery.uploadsUnavailableForAllBoards'),+ namespace: 'gallery',+ });+ return [];+ }+// A board is judged from the listing of every readable board, never trusted as given: an upload to a board// that was deleted, archived out of reach or shared read-only since the panel listed it would only fail.// Uncategorized and virtual boards need no listing.diff --git a/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts b/invokeai/frontend/webv2/src/features/generation/data/wildcards.tsindex b076f4ad68..e045a4e1fb 100644--- a/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts+++ b/invokeai/frontend/webv2/src/features/generation/data/wildcards.ts@@ -47,6 +47,23 @@ export const deleteWildcard = async (id: string): Promise<void> => {await apiFetch(`/api/v1/wildcards/${encodeURIComponent(id)}`, { method: 'DELETE' });};+/** The most ids one batch delete takes (`MAX_WILDCARD_BATCH_SIZE` on the server). */+export const WILDCARD_DELETE_BATCH_SIZE = 1000;++/**+ * Deletes those of the ids the caller owns; the result names them. Ids the server does not know as the caller's are+ * absent from it, so a wildcard deleted meanwhile reads as not deleted here.+ */+export const deleteWildcards = async (ids: readonly string[], signal?: AbortSignal): Promise<string[]> => {+ const result = await apiFetchJson<{ deleted_ids: string[] }>('/api/v1/wildcards/delete', {+ body: JSON.stringify({ wildcard_ids: ids }),+ method: 'POST',+ signal,+ });++ return result.deleted_ids;+};+/** Infinite staleTime and request-only keys require dependent invalidation and staleness-aware readers. */export const invalidateWildcardDependents = async (queryClient: QueryClient): Promise<void> => {await Promise.all([diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsxindex c114af7608..c87ba92501 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.browser.test.tsx@@ -14,7 +14,9 @@ const parseDynamicPrompts = vi.hoisted(() => vi.fn());vi.mock('@features/generation/data/promptUtilities', () => ({ parseDynamicPrompts }));-vi.mock('@features/generation/data/wildcards', () => ({+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({+ // Partial: the real module's other exports (constants, mappers) stay available to what imports them.+ ...(await importOriginal<Record<string, unknown>>()),createWildcard: vi.fn(),deleteWildcard: vi.fn(),invalidateWildcardDependents: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsxindex 583f4bc498..2db18803cd 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx@@ -2,7 +2,6 @@ import type { DynamicPromptsFieldConfig } from '@features/generation/ui/promptFiimport { Popover, Portal, Stack, Text } from '@chakra-ui/react';import { DynamicPromptsPanel } from '@features/generation/ui/promptFields/DynamicPromptsPanel';-import { WildcardsPanel } from '@features/generation/ui/promptFields/WildcardsPanel';import { useDynamicPrompts } from '@features/generation/ui/useDynamicPrompts';import { useWildcards } from '@features/generation/ui/useWildcards';import { IconButton } from '@platform/ui/Button';@@ -10,10 +9,14 @@ import { PopoverContent } from '@platform/ui/Popover';import { SegmentTabs, segmentTabsPanelId, segmentTabsTabId } from '@platform/ui/SegmentTabs';import { Tooltip } from '@platform/ui/Tooltip';import { BracesIcon } from 'lucide-react';-import { useCallback, useId, useMemo, useState } from 'react';+import { lazy, Suspense, useCallback, useId, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';const POPOVER_POSITIONING_BOTTOM_END = { placement: 'bottom-end' } as const;++// The wildcard manager and its list load with the popover, not with every prompt field at editor boot.+const loadWildcardsPanel = () => import('@features/generation/ui/promptFields/WildcardsPanel');+const WildcardsPanel = lazy(() => loadWildcardsPanel().then((module) => ({ default: module.WildcardsPanel })));const TABULAR_NUMS = { fontVariantNumeric: 'tabular-nums' } as const;interface DynamicPromptsButtonProps {@@ -45,7 +48,13 @@ export const DynamicPromptsButton = ({const catalog = useWildcards();const popoverIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);- const handleOpenChange = useCallback((event: { open: boolean }) => setIsOpen(event.open), []);+ const handleOpenChange = useCallback((event: { open: boolean }) => {+ if (event.open) {+ // Ready before the Wildcards tab is chosen, so it opens without a loading gap.+ void loadWildcardsPanel();+ }+ setIsOpen(event.open);+ }, []);const handleTabChange = useCallback((value: 'preview' | 'wildcards') => setTab(value), []);const closeWith = useCallback((apply: (value: string) => void) => (value: string) => {@@ -130,11 +139,13 @@ export const DynamicPromptsButton = ({onUsePrompt={handleUsePrompt}/>) : (- <WildcardsPanel- catalog={catalog}- showSyntaxHighlighting={showSyntaxHighlighting}- onInsert={handleInsert}- />+ <Suspense fallback={null}>+ <WildcardsPanel+ catalog={catalog}+ showSyntaxHighlighting={showSyntaxHighlighting}+ onInsert={handleInsert}+ />+ </Suspense>)}</Stack></Stack>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsxindex 18e29a759b..1a14c29d7b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsControls.browser.test.tsx@@ -18,7 +18,9 @@ vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) =>...(await importOriginal<object>()),useGenerationUi: () => ({ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() } }),}));-vi.mock('@features/generation/data/wildcards', () => ({+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({+ // Partial: the real module's other exports (constants, mappers) stay available to what imports them.+ ...(await importOriginal<Record<string, unknown>>()),createWildcard: vi.fn(),deleteWildcard: vi.fn(),invalidateWildcardDependents: vi.fn(),@@ -292,7 +294,7 @@ describe('dynamic prompts popover controls', () => {await userEvent.click(tabButton('wildcards')!);});- // Header geometry must remain equal across tabs.- expect(headerControl()).toBe(summaryHeight);+ // Header geometry must remain equal across tabs, once the lazily loaded wildcard manager is in.+ await vi.waitFor(() => expect(headerControl()).toBe(summaryHeight));});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ExpandPromptSuggestion.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ExpandPromptSuggestion.browser.test.tsxindex 01c85b81fc..e4b0eb8821 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ExpandPromptSuggestion.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ExpandPromptSuggestion.browser.test.tsx@@ -145,7 +145,9 @@ vi.mock('@features/generation/data/promptUtilities', async (importOriginal) => (imageToPrompt: vi.fn(() => Promise.resolve({ prompt: 'described' })),}));-vi.mock('@features/generation/data/wildcards', () => ({+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({+ // Partial: the real module's other exports (constants, mappers) stay available to what imports them.+ ...(await importOriginal<Record<string, unknown>>()),createWildcard: vi.fn(),deleteWildcard: vi.fn(),invalidateWildcardDependents: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsxindex a5e02b8466..5208a3ea4b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.browser.test.tsx@@ -21,7 +21,9 @@ vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) =>useGenerationUi: () => ({ models: { catalog: MODEL_CATALOG, ensureLoaded: vi.fn() } }),}));-vi.mock('@features/generation/data/wildcards', () => ({+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({+ // Partial: the real module's other exports (constants, mappers) stay available to what imports them.+ ...(await importOriginal<Record<string, unknown>>()),createWildcard: vi.fn(),deleteWildcard: vi.fn(),invalidateWildcardDependents: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsxindex 67b0f44cfe..8d01dbc28b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.browser.test.tsx@@ -29,7 +29,9 @@ vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) =>}),}));-vi.mock('@features/generation/data/wildcards', () => ({+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({+ // Partial: the real module's other exports (constants, mappers) stay available to what imports them.+ ...(await importOriginal<Record<string, unknown>>()),createWildcard: vi.fn(),deleteWildcard: vi.fn(),invalidateWildcardDependents: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsxindex 976ad1e47a..d307815205 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTriggerPicker.browser.test.tsx@@ -27,7 +27,9 @@ const WILDCARDS = [{ id: 'w2', name: 'moods', values: ['calm'] },];-vi.mock('@features/generation/data/wildcards', () => ({+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({+ // Partial: the real module's other exports (constants, mappers) stay available to what imports them.+ ...(await importOriginal<Record<string, unknown>>()),createWildcard: vi.fn(),deleteWildcard: vi.fn(),invalidateWildcardDependents: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsxindex ea47ae91d6..519f885a7c 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.browser.test.tsx@@ -1,7 +1,8 @@import type { WildcardCatalog } from '@features/generation/ui/useWildcards';-import { ChakraProvider } from '@chakra-ui/react';+import { ChakraProvider, Field, Input } from '@chakra-ui/react';import { WildcardsPanel } from '@features/generation/ui/promptFields/WildcardsPanel';+import { WildcardDeleteError } from '@features/generation/ui/useWildcards';import { WILDCARD_COLLECTION_FORMATS } from '@features/generation/ui/wildcardFiles';import { accountLifecycle } from '@platform/state/accountLifecycle';import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';@@ -11,9 +12,11 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';+const { reportError } = vi.hoisted(() => ({ reportError: vi.fn() }));+vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({...(await importOriginal<object>()),- useGenerationUi: () => ({ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() } }),+ useGenerationUi: () => ({ notifications: { error: vi.fn(), info: vi.fn(), reportError } }),}));let host: HTMLDivElement | null = null;@@ -26,10 +29,14 @@ const catalog: WildcardCatalog = {isLoading: false,knownNames: new Set(['colors']),remove: vi.fn(),+ removeMany: vi.fn(),update: vi.fn(),wildcards: [{ id: 'w1', name: 'colors', values: ['red', 'green'] }],};+/** The catalog once everything is deleted. */+const emptyCatalog: WildcardCatalog = { ...catalog, wildcards: [] };+const renderPanel = async (showSyntaxHighlighting = true,panelCatalog: WildcardCatalog = catalog,@@ -206,6 +213,7 @@ describe('finding a wildcard', () => {isLoading: false,knownNames: new Set(['colors']),remove: vi.fn(),+ removeMany: vi.fn(),update: vi.fn(),wildcards: [{ id: 'w1', name: 'colors', values: ['red', 'green'] },@@ -242,7 +250,7 @@ describe('finding a wildcard', () => {describe('wildcard list interactions', () => {const selectableWildcardButton = () =>- host!.querySelector<HTMLButtonElement>('button[title="widgets.generate.dynamicPrompts.insertWildcard"]')!;+ host!.querySelector<HTMLButtonElement>('[data-list-row="w1"] [data-list-primary]')!;it('keeps the edit controls outside the selectable row button', async () => {const onInsert = vi.fn();@@ -254,6 +262,8 @@ describe('wildcard list interactions', () => {expect(row.contains(edit)).toBe(false);expect(row.contains(remove)).toBe(false);+ // The row's name says what pressing it does, not only which wildcard it is.+ expect(row.getAttribute('aria-label')).toBe('widgets.generate.dynamicPrompts.insertWildcard: __colors__');await act(async () => {await userEvent.click(row);@@ -287,3 +297,214 @@ describe('deleting a wildcard', () => {expect(catalog.remove).toHaveBeenCalledWith('w1');});});++describe('selecting several wildcards', () => {+ const wildcards = [+ { id: 'w1', name: 'colors', values: ['red', 'green'] },+ { id: 'w2', name: 'animals/dogs', values: ['corgi'] },+ { id: 'w3', name: 'animals/cats', values: ['tabby'] },+ { id: 'w4', name: 'moods', values: ['serene'] },+ ];+ const selectingCatalog = (removeMany: WildcardCatalog['removeMany'] = vi.fn(() => Promise.resolve([]))) => ({+ ...catalog,+ knownNames: new Set(wildcards.map((wildcard) => wildcard.name)),+ removeMany,+ wildcards,+ });+ const rowCheckbox = (id: string) =>+ host!.querySelector<HTMLInputElement>(`[data-list-row="${id}"] input[type="checkbox"]`)!;+ const selectAll = () =>+ host!.querySelector<HTMLInputElement>(+ '[aria-label="widgets.generate.dynamicPrompts.selectAllWildcards"] input[type="checkbox"]'+ )!;+ const selectAllState = () =>+ host!+ .querySelector('[aria-label="widgets.generate.dynamicPrompts.selectAllWildcards"]')!+ .getAttribute('data-state');+ const checkedIds = () => wildcards.map((wildcard) => wildcard.id).filter((id) => rowCheckbox(id)?.checked);+ const toggle = async (input: HTMLInputElement) => {+ await act(() => input.click());+ };+ const search = async (term: string) => {+ const input = host!.querySelector<HTMLInputElement>(+ 'input[aria-label="widgets.generate.dynamicPrompts.searchWildcards"]'+ )!;++ await act(async () => {+ await userEvent.fill(input, term);+ });+ };+ const button = (label: string, scope: ParentNode = host!) =>+ [...scope.querySelectorAll<HTMLButtonElement>('button')].find(+ (candidate) => candidate.textContent === label || candidate.getAttribute('aria-label') === label+ );+ const confirmButton = () => button('widgets.generate.dynamicPrompts.bulkDeleteWildcardsConfirm', document);++ it('gives every row a checkbox while a press on the row still inserts it', async () => {+ const onInsert = vi.fn();+ await renderPanel(true, selectingCatalog(), onInsert);++ expect(wildcards.every((wildcard) => rowCheckbox(wildcard.id) !== null)).toBe(true);+ expect(button('common.delete')).not.toBeUndefined(); // the row's own trash action+ expect(button('widgets.generate.dynamicPrompts.clearWildcardSelection')).toBeUndefined();++ await act(async () => {+ await userEvent.click(host!.querySelector<HTMLElement>('[data-list-row="w4"] [data-list-primary]')!);+ });++ expect(onInsert).toHaveBeenCalledWith('__moods__');+ expect(checkedIds()).toEqual([]);+ });++ it('selects all of the filtered list, adding to what an earlier search selected', async () => {+ await renderPanel(true, selectingCatalog());++ await toggle(rowCheckbox('w4'));+ expect(selectAllState()).toBe('indeterminate');++ await search('animals');+ await toggle(selectAll());+ expect(selectAllState()).toBe('checked');++ await search('');+ expect(checkedIds()).toEqual(['w2', 'w3', 'w4']);+ expect(selectAllState()).toBe('indeterminate');+ });++ it('deletes every selected wildcard after one confirm', async () => {+ const removeMany = vi.fn((ids: readonly string[]) => Promise.resolve([...ids]));+ await renderPanel(true, selectingCatalog(removeMany));++ await toggle(selectAll());+ await act(async () => {+ await userEvent.click(+ button(+ 'common.delete',+ host!.querySelector('[aria-label="widgets.generate.dynamicPrompts.selectAllWildcards"]')!.parentElement!+ )!+ );+ });+ await act(async () => {+ await userEvent.click(confirmButton()!);+ });++ expect(removeMany).toHaveBeenCalledOnce();+ expect([...removeMany.mock.calls[0]![0]].sort()).toEqual(['w1', 'w2', 'w3', 'w4']);+ expect(checkedIds()).toEqual([]);+ });++ it('keeps what could not be deleted selected and reports how many were', async () => {+ const removeMany = vi.fn(() => Promise.reject(new WildcardDeleteError(['w1'], new Error('offline'))));+ await renderPanel(true, selectingCatalog(removeMany));++ await toggle(rowCheckbox('w1'));+ await toggle(rowCheckbox('w2'));+ await act(async () => {+ await userEvent.click(+ button(+ 'common.delete',+ host!.querySelector('[aria-label="widgets.generate.dynamicPrompts.selectAllWildcards"]')!.parentElement!+ )!+ );+ });+ await act(async () => {+ await userEvent.click(confirmButton()!);+ });++ expect(checkedIds()).toEqual(['w2']);+ expect(reportError).toHaveBeenCalledWith(expect.objectContaining({ area: 'delete-wildcard' }));+ });++ it('clears the selection', async () => {+ await renderPanel(true, selectingCatalog());++ await toggle(selectAll());+ await act(async () => {+ await userEvent.click(button('widgets.generate.dynamicPrompts.clearWildcardSelection')!);+ });++ expect(checkedIds()).toEqual([]);+ expect(selectAllState()).toBe('unchecked');+ // The Clear selection button is gone; focus stays in the panel, on select all.+ expect(document.activeElement).toBe(selectAll());+ });++ it('moves focus to the search field when clearing a selection the search hides', async () => {+ await renderPanel(true, selectingCatalog());++ await toggle(rowCheckbox('w1'));+ await search('no such wildcard');+ await act(async () => {+ await userEvent.click(button('widgets.generate.dynamicPrompts.clearWildcardSelection')!);+ });++ expect(document.activeElement).toBe(+ host!.querySelector('input[aria-label="widgets.generate.dynamicPrompts.searchWildcards"]')+ );+ });++ it('returns focus into the panel after deleting every wildcard, not to the page', async () => {+ // As the real catalog does, the refetch that follows the delete lands before it resolves: nothing is left to+ // list, select or search.+ const removeMany = vi.fn((ids: readonly string[]) => {+ root?.render(+ <ChakraProvider value={system}>+ <WildcardsPanel catalog={emptyCatalog} showSyntaxHighlighting onInsert={vi.fn()} />+ </ChakraProvider>+ );+ return Promise.resolve([...ids]);+ });+ await renderPanel(true, selectingCatalog(removeMany));++ await toggle(selectAll());+ await act(async () => {+ await userEvent.click(+ button(+ 'common.delete',+ host!.querySelector('[aria-label="widgets.generate.dynamicPrompts.selectAllWildcards"]')!.parentElement!+ )!+ );+ });+ await act(async () => {+ await userEvent.click(confirmButton()!);+ });++ await vi.waitFor(() => expect(document.activeElement).toBe(button('widgets.generate.dynamicPrompts.newWildcard')));+ });++ it('selects a row from the keyboard', async () => {+ await renderPanel(true, selectingCatalog());++ rowCheckbox('w1').focus();+ await act(async () => {+ await userEvent.keyboard(' ');+ });++ expect(checkedIds()).toEqual(['w1']);+ });+});++it('gives its search box a field of its own inside the prompt field it opens from', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <Field.Root invalid>+ <Input aria-label="Prompt" />+ <WildcardsPanel catalog={catalog} showSyntaxHighlighting onInsert={vi.fn()} />+ </Field.Root>+ </ChakraProvider>+ );+ });++ const prompt = host.querySelector<HTMLInputElement>('input[aria-label="Prompt"]')!;+ const search = host.querySelector<HTMLInputElement>(+ 'input[aria-label="widgets.generate.dynamicPrompts.searchWildcards"]'+ )!;++ expect(search.id).not.toBe(prompt.id);+ expect(search.getAttribute('aria-invalid')).toBeNull();+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsxindex dbe31153d7..b58b34022a 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/WildcardsPanel.tsx@@ -1,9 +1,11 @@-/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop */import type { WildcardRecord } from '@features/generation/data/wildcards';import type { WildcardCatalog } from '@features/generation/ui/useWildcards';+import type { ListRowProps } from '@platform/ui/list/List';+import type { ListRow } from '@platform/ui/list/listRows';import type { ChangeEvent } from 'react';-import { HStack, Input, Separator, Stack, Text } from '@chakra-ui/react';+import { Box, Field as ChakraField, HStack, Input, Separator, Stack, Text } from '@chakra-ui/react';import {getWildcardNameError,getWildcardValuesError,@@ -14,15 +16,17 @@ import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';import { PANEL_HEADER_CONTROL_HEIGHT, PromptPanelHeader } from '@features/generation/ui/promptFields/PromptPanelHeader';import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';import { WildcardTransferActions } from '@features/generation/ui/promptFields/WildcardTransferActions';+import { WildcardDeleteError } from '@features/generation/ui/useWildcards';import { getApiErrorMessage } from '@platform/transport/http';import { Button, IconButton } from '@platform/ui/Button';import { ConfirmDialog } from '@platform/ui/ConfirmDialog';import { Field } from '@platform/ui/Field';-import { Row } from '@platform/ui/Row';-import { Scrollable } from '@platform/ui/Scrollable';+import { List } from '@platform/ui/list/List';+import { ListItem } from '@platform/ui/list/ListItem';+import { ListSelectionBar } from '@platform/ui/list/ListSelectionBar';import { Tooltip } from '@platform/ui/Tooltip';import { CheckIcon, PencilIcon, PlusIcon, TrashIcon, XIcon } from 'lucide-react';-import { useCallback, useId, useMemo, useState } from 'react';+import { memo, useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';/** One value per line: the same shape the user is editing a variant in. */@@ -41,6 +45,17 @@ const NAME_ERROR_KEY = {tooLong: 'widgets.generate.dynamicPrompts.wildcardNameTooLong',} as const;+const NO_SELECTION: ReadonlySet<string> = new Set();++/** Ungrouped names first and unheaded, then each prefix under its header, as one row sequence for the List. */+const toRows = (groups: ReturnType<typeof groupWildcardsByPrefix<WildcardRecord>>): ListRow<WildcardRecord>[] =>+ groups.flatMap((group) => [+ ...(group.label === null+ ? []+ : [{ count: group.wildcards.length, key: `header:${group.label}`, kind: 'header' as const, label: group.label }]),+ ...group.wildcards.map((wildcard) => ({ item: wildcard, key: wildcard.id, kind: 'item' as const })),+ ]);+interface WildcardDraft {id: string | null;name: string;@@ -63,10 +78,26 @@ export const WildcardsPanel = ({const [draft, setDraft] = useState<WildcardDraft | null>(null);const [error, setError] = useState<string | null>(null);const [pendingDelete, setPendingDelete] = useState<WildcardRecord | null>(null);+ const [isBulkDeleteOpen, setIsBulkDeleteOpen] = useState(false);+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<string>>(NO_SELECTION);const [searchTerm, setSearchTerm] = useState('');- const groups = useMemo(- () => groupWildcardsByPrefix(filterWildcards(catalog.wildcards, searchTerm)),- [catalog.wildcards, searchTerm]+ const selectionBarRef = useRef<HTMLDivElement>(null);+ const searchInputRef = useRef<HTMLInputElement>(null);+ const newWildcardRef = useRef<HTMLButtonElement>(null);+ const filtered = useMemo(() => filterWildcards(catalog.wildcards, searchTerm), [catalog.wildcards, searchTerm]);+ const rows = useMemo(() => toRows(groupWildcardsByPrefix(filtered)), [filtered]);+ // Ids the catalog no longer returns (deleted here, elsewhere, or by another tab) drop out of the selection.+ const selection = useMemo(() => {+ const liveIds = new Set(catalog.wildcards.map((wildcard) => wildcard.id));++ return [...selectedIds].every((id) => liveIds.has(id))+ ? selectedIds+ : new Set([...selectedIds].filter((id) => liveIds.has(id)));+ }, [catalog.wildcards, selectedIds]);+ const hasSelection = selection.size > 0;+ const hasUnselectedFiltered = useMemo(+ () => filtered.some((wildcard) => !selection.has(wildcard.id)),+ [filtered, selection]);// Exclude the current wildcard from rename collision checks.const nameError = draft@@ -119,6 +150,73 @@ export const WildcardsPanel = ({);const closeDeleteDialog = useCallback(() => setPendingDelete(null), []);+ const closeBulkDeleteDialog = useCallback(() => setIsBulkDeleteOpen(false), []);++ const toggleSelected = useCallback((id: string) => {+ setSelectedIds((previous) => {+ const next = new Set(previous);++ if (!next.delete(id)) {+ next.add(id);+ }++ return next;+ });+ }, []);++ const handleToggleSelectAll = useCallback(() => {+ if (hasSelection && !hasUnselectedFiltered) {+ setSelectedIds(NO_SELECTION);++ return;+ }++ // Union: selections made under an earlier search survive, so the delete confirm counts every selected wildcard.+ setSelectedIds(new Set([...selection, ...filtered.map((wildcard) => wildcard.id)]));+ }, [filtered, hasSelection, hasUnselectedFiltered, selection]);++ /**+ * Where focus goes once the selection's own controls are gone: select all, or, with no rows left to select, the+ * search field, then New wildcard. Never the page body.+ */+ const getSelectionFocusTarget = useCallback((): HTMLElement | null => {+ const selectAll = selectionBarRef.current?.querySelector<HTMLInputElement>('input[type="checkbox"]');++ return selectAll && !selectAll.disabled ? selectAll : (searchInputRef.current ?? newWildcardRef.current);+ }, []);++ const clearSelection = useCallback(() => {+ setSelectedIds(NO_SELECTION);+ // The Clear selection button leaves with the selection; keep focus in the panel. With nothing listed, select all+ // turns disabled once the selection is gone, so the search field takes focus instead.+ (filtered.length === 0 ? (searchInputRef.current ?? newWildcardRef.current) : getSelectionFocusTarget())?.focus();+ }, [filtered.length, getSelectionFocusTarget]);++ /** Keeps what was not deleted selected, so a retry acts on exactly that. */+ const confirmBulkDelete = useCallback(async () => {+ const ids = [...selection];+ const keepUndeleted = (deletedIds: readonly string[]) => {+ const deleted = new Set(deletedIds);++ setSelectedIds(new Set(ids.filter((id) => !deleted.has(id))));+ };++ try {+ keepUndeleted(await catalog.removeMany(ids));+ } catch (caught) {+ const deletedIds = caught instanceof WildcardDeleteError ? caught.deletedIds : [];++ keepUndeleted(deletedIds);+ notifications.reportError({+ area: 'delete-wildcard',+ message: t('widgets.generate.dynamicPrompts.couldNotDeleteWildcards', {+ count: ids.length,+ deleted: deletedIds.length,+ }),+ namespace: 'generation',+ });+ }+ }, [catalog, notifications, selection, t]);/** Notify on failure because the confirmation dialog closes. */const confirmDelete = useCallback(async () => {@@ -200,7 +298,7 @@ export const WildcardsPanel = ({return (<Stack gap="2"><PromptPanelHeader label={t('widgets.generate.dynamicPrompts.wildcards')}>- <Button h={PANEL_HEADER_CONTROL_HEIGHT} size="sm" variant="ghost" onClick={startCreate}>+ <Button ref={newWildcardRef} h={PANEL_HEADER_CONTROL_HEIGHT} size="sm" variant="ghost" onClick={startCreate}><PlusIcon />{t('widgets.generate.dynamicPrompts.newWildcard')}</Button>@@ -208,47 +306,81 @@ export const WildcardsPanel = ({{catalog.wildcards.length > 0 ? (<>- <Input- aria-label={t('widgets.generate.dynamicPrompts.searchWildcards')}- placeholder={t('widgets.generate.dynamicPrompts.searchWildcards')}- value={searchTerm}- onChange={handleSearchChange}- />+ {/* Its own field: the panel opens from the prompt's label, whose Field would otherwise lend this input its id,+ description and invalid state. */}+ <ChakraField.Root>+ <Input+ ref={searchInputRef}+ aria-label={t('widgets.generate.dynamicPrompts.searchWildcards')}+ placeholder={t('widgets.generate.dynamicPrompts.searchWildcards')}+ value={searchTerm}+ onChange={handleSearchChange}+ />+ </ChakraField.Root><Separator /></>) : null}- <Scrollable h="14rem" label={t('widgets.generate.dynamicPrompts.wildcards')}>- {groups.length === 0 ? (- <Text color="fg.subtle" fontSize="xs" px="2" py="1.5">- {catalog.wildcards.length === 0- ? t('widgets.generate.dynamicPrompts.noWildcardsYet')- : t('widgets.generate.dynamicPrompts.noMatchingWildcards')}- </Text>- ) : (- <Stack gap="2">- {groups.map((group) => (- <Stack gap="0" key={group.label ?? ''}>- {group.label === null ? null : (- <Text color="fg.subtle" fontSize="xs" fontWeight="700" px="2" textTransform="uppercase">- {group.label}- </Text>- )}- {group.wildcards.map((wildcard) => (- // Show full wildcard paths because rows display exact insertion syntax.- <WildcardRow- key={wildcard.id}- wildcard={wildcard}- onDelete={setPendingDelete}- onEdit={startEdit}- onInsert={onInsert}- />- ))}- </Stack>- ))}- </Stack>- )}- </Scrollable>+ <Box ref={selectionBarRef}>+ <ListSelectionBar+ // No visible matches means indeterminate, not all selected; clicking clears the hidden selection.+ checked={hasSelection ? (hasUnselectedFiltered || filtered.length === 0 ? 'indeterminate' : true) : false}+ isDisabled={filtered.length === 0 && !hasSelection}+ label={t('widgets.generate.dynamicPrompts.selectAllWildcards')}+ summary={+ hasSelection+ ? t('widgets.generate.dynamicPrompts.selectedWildcardCount', { count: selection.size })+ : undefined+ }+ onCheckedChange={handleToggleSelectAll}+ >+ {hasSelection ? (+ <>+ <Button colorPalette="red" size="sm" variant="ghost" onClick={() => setIsBulkDeleteOpen(true)}>+ <TrashIcon />+ {t('common.delete')}+ </Button>+ <Tooltip content={t('widgets.generate.dynamicPrompts.clearWildcardSelection')}>+ <IconButton+ aria-label={t('widgets.generate.dynamicPrompts.clearWildcardSelection')}+ size="sm"+ variant="ghost"+ onClick={clearSelection}+ >+ <XIcon />+ </IconButton>+ </Tooltip>+ </>+ ) : null}+ </ListSelectionBar>+ </Box>++ <Box h="14rem">+ <List+ density="snug"+ emptyState={+ <Text color="fg.subtle" fontSize="xs">+ {catalog.wildcards.length === 0+ ? t('widgets.generate.dynamicPrompts.noWildcardsYet')+ : t('widgets.generate.dynamicPrompts.noMatchingWildcards')}+ </Text>+ }+ label={t('widgets.generate.dynamicPrompts.wildcards')}+ renderItem={(wildcard: WildcardRecord, rowProps: ListRowProps) => (+ // Show full wildcard paths because rows display exact insertion syntax.+ <WildcardRow+ {...rowProps}+ isSelected={selection.has(wildcard.id)}+ wildcard={wildcard}+ onDelete={setPendingDelete}+ onEdit={startEdit}+ onInsert={onInsert}+ onToggleSelected={toggleSelected}+ />+ )}+ rows={rows}+ />+ </Box><Separator /><WildcardTransferActions catalog={catalog} />@@ -262,74 +394,74 @@ export const WildcardsPanel = ({onClose={closeDeleteDialog}onConfirm={confirmDelete}/>+ <ConfirmDialog+ body={t('widgets.generate.dynamicPrompts.bulkDeleteWildcardsBody', { count: selection.size })}+ confirmLabel={t('widgets.generate.dynamicPrompts.bulkDeleteWildcardsConfirm', { count: selection.size })}+ isOpen={isBulkDeleteOpen}+ finalFocusEl={getSelectionFocusTarget}+ title={t('widgets.generate.dynamicPrompts.deleteSelectedWildcardsTitle')}+ onClose={closeBulkDeleteDialog}+ onConfirm={confirmBulkDelete}+ /></Stack>);};-const WildcardRow = ({- onDelete,- onEdit,- onInsert,- wildcard,-}: {+interface WildcardRowProps extends ListRowProps {wildcard: WildcardRecord;+ isSelected: boolean;onDelete: (wildcard: WildcardRecord) => void;onEdit: (wildcard: WildcardRecord) => void;onInsert: (reference: string) => void;-}) => {+ onToggleSelected: (id: string) => void;+}++/** Memoized on its record and selection, so selecting all re-renders only the rows whose check changed. */+const WildcardRow = memo(function WildcardRow({+ isSelected,+ onDelete,+ onEdit,+ onInsert,+ onToggleSelected,+ wildcard,+ ...rowProps+}: WildcardRowProps) {const { t } = useTranslation();+ const reference = `__${wildcard.name}__`;return (- <HStack align="start" gap="1" pr="1">- <Row- alignItems="start"- asChild- borderColor="transparent"- borderWidth="1px"- flex="1"- fontWeight="medium"- h="auto"- justifyContent="start"- minW="0"- px="2"- py="1.5"- textStyle="md"- title={t('widgets.generate.dynamicPrompts.insertWildcard')}- whiteSpace="nowrap"- >- <button- aria-label={`${t('widgets.generate.dynamicPrompts.insertWildcard')}: __${wildcard.name}__`}- type="button"- onClick={() => onInsert(`__${wildcard.name}__`)}- >- <Stack align="start" gap="0" minW="0">- <Text as="span" color="fg" fontFamily="mono" fontSize="0.72rem">- __{wildcard.name}__- </Text>- <Text as="span" color="fg.subtle" fontSize="xs" truncate>- {wildcard.values.length > 0- ? wildcard.values.join(', ')- : t('widgets.generate.dynamicPrompts.wildcardHasNoValues')}- </Text>- </Stack>- </button>- </Row>- <Tooltip content={t('common.edit')}>- <IconButton aria-label={t('common.edit')} size="sm" variant="ghost" onClick={() => onEdit(wildcard)}>- <PencilIcon />- </IconButton>- </Tooltip>- <Tooltip content={t('common.delete')}>- <IconButton- aria-label={t('common.delete')}- colorPalette="red"- size="sm"- variant="ghost"- onClick={() => onDelete(wildcard)}- >- <TrashIcon />- </IconButton>- </Tooltip>- </HStack>+ <ListItem+ {...rowProps}+ actions={+ <>+ <Tooltip content={t('common.edit')}>+ <IconButton aria-label={t('common.edit')} size="sm" variant="ghost" onClick={() => onEdit(wildcard)}>+ <PencilIcon />+ </IconButton>+ </Tooltip>+ <Tooltip content={t('common.delete')}>+ <IconButton+ aria-label={t('common.delete')}+ colorPalette="red"+ size="sm"+ variant="ghost"+ onClick={() => onDelete(wildcard)}+ >+ <TrashIcon />+ </IconButton>+ </Tooltip>+ </>+ }+ description={+ wildcard.values.length > 0+ ? wildcard.values.join(', ')+ : t('widgets.generate.dynamicPrompts.wildcardHasNoValues')+ }+ isChecked={isSelected}+ title={reference}+ onCheckedChange={() => onToggleSelected(wildcard.id)}+ pressLabel={`${t('widgets.generate.dynamicPrompts.insertWildcard')}: ${reference}`}+ onPress={() => onInsert(reference)}+ />);-};+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsxindex 10c53963b4..f57b9b6637 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptImageDrop.browser.test.tsx@@ -38,7 +38,9 @@ vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) =>}),}));-vi.mock('@features/generation/data/wildcards', () => ({+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({+ // Partial: the real module's other exports (constants, mappers) stay available to what imports them.+ ...(await importOriginal<Record<string, unknown>>()),createWildcard: vi.fn(),deleteWildcard: vi.fn(),invalidateWildcardDependents: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsxindex 10d53f8762..7d02d609aa 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.browser.test.tsx@@ -1,5 +1,8 @@-import { useWildcards, WildcardWriteError } from '@features/generation/ui/useWildcards';-import { captureAccountScope } from '@platform/state/accountLifecycle';+import type * as WildcardsModule from '@features/generation/data/wildcards';++import { dynamicPromptsKeys } from '@features/generation/data/dynamicPromptsQueries';+import { useWildcards, WildcardDeleteError, WildcardWriteError } from '@features/generation/ui/useWildcards';+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { act, createRef, type Ref, useImperativeHandle } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -7,18 +10,46 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const createWildcard = vi.fn(() => Promise.resolve());const updateWildcard = vi.fn(() => Promise.resolve());-const invalidateWildcardDependents = vi.fn(() => Promise.resolve());+// Records each call; the real invalidation still runs against the test's query client.+const invalidateWildcardDependents = vi.fn();+// Answers as the server does: every id it was sent was the caller's.+const deleteWildcards = vi.fn((ids: readonly string[], _signal?: AbortSignal) => Promise.resolve([...ids]));+const listWildcards = vi.fn<() => Promise<WildcardsModule.WildcardRecord[]>>();++vi.mock('@features/generation/data/wildcards', async (importOriginal) => {+ // Partial: the real module's other exports (constants, mappers) stay available to what imports them.+ const actual = await importOriginal<typeof WildcardsModule>();++ return {+ ...actual,+ createWildcard: (...args: unknown[]) => createWildcard(...(args as [])),+ deleteWildcard: vi.fn(),+ deleteWildcards: (ids: readonly string[], signal?: AbortSignal) => deleteWildcards(ids, signal),+ invalidateWildcardDependents: (queryClient: QueryClient) => {+ invalidateWildcardDependents(queryClient);++ return actual.invalidateWildcardDependents(queryClient);+ },+ updateWildcard: (...args: unknown[]) => updateWildcard(...(args as [])),+ wildcardsQueryOptions: () => ({ queryFn: () => listWildcards(), queryKey: actual.wildcardKeys.all }),+ };+});++/** Holds the catalog's refetches until released, as a refresh retrying against an outage would. */+const holdCatalogRefetch = (answer: () => WildcardsModule.WildcardRecord[] = () => []): (() => void) => {+ let release = () => {};+ const held = new Promise<void>((resolve) => {+ release = resolve;+ });++ listWildcards.mockImplementation(() => held.then(answer));-vi.mock('@features/generation/data/wildcards', () => ({- createWildcard: (...args: unknown[]) => createWildcard(...(args as [])),- deleteWildcard: vi.fn(),- invalidateWildcardDependents: (...args: unknown[]) => invalidateWildcardDependents(...(args as [])),- updateWildcard: (...args: unknown[]) => updateWildcard(...(args as [])),- wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve([]), queryKey: ['generation', 'wildcards'] }),-}));+ return release;+};let host: HTMLDivElement | null = null;let root: Root | null = null;+let queryClient: QueryClient;const catalogRef = createRef<ReturnType<typeof useWildcards>>();(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -32,13 +63,15 @@ const Probe = ({ ref }: { ref: Ref<ReturnType<typeof useWildcards>> }) => {beforeEach(async () => {vi.clearAllMocks();+ listWildcards.mockImplementation(() => Promise.resolve([]));host = document.createElement('div');document.body.append(host);root = createRoot(host);+ queryClient = new QueryClient();await act(() => {root?.render(- <QueryClientProvider client={new QueryClient()}>+ <QueryClientProvider client={queryClient}><Probe ref={catalogRef} /></QueryClientProvider>);@@ -88,13 +121,174 @@ describe('applyWrites', () => {expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);});- it('does not invalidate when the very first write fails', async () => {- createWildcard.mockImplementationOnce(() => Promise.reject(new Error('nope')));+ it('invalidates when the very first write loses its answer, since the server may have committed it', async () => {+ createWildcard.mockImplementationOnce(() => Promise.reject(new TypeError('Failed to fetch')));++ let caught: unknown;++ await act(async () => {+ caught = await catalogRef.current!.applyWrites(WRITES, captureAccountScope()).catch((error: unknown) => error);+ });++ expect((caught as WildcardWriteError).done).toBe(0);+ expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);+ });++ it('does not invalidate when there was nothing to write', async () => {+ await act(async () => {+ await catalogRef.current!.applyWrites([], captureAccountScope());+ });++ expect(invalidateWildcardDependents).not.toHaveBeenCalled();+ });+});++describe('single writes', () => {+ it('invalidates when a create loses its answer, and reports that failure without waiting on the refresh', async () => {+ createWildcard.mockImplementationOnce(() => Promise.reject(new TypeError('Failed to fetch')));+ holdCatalogRefetch();++ let caught: unknown;++ await act(async () => {+ caught = await catalogRef.current!.create({ name: 'a', values: ['1'] }).catch((error: unknown) => error);+ });++ expect(caught).toMatchObject({ message: 'Failed to fetch' });+ expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);+ });++ it('reports only the write failure when the refresh behind it fails too', async () => {+ const unhandled = vi.fn();+ window.addEventListener('unhandledrejection', unhandled);+ createWildcard.mockImplementationOnce(() => Promise.reject(new TypeError('Failed to fetch')));+ vi.spyOn(queryClient, 'invalidateQueries').mockRejectedValueOnce(new Error('refresh failed'));++ let caught: unknown;++ try {+ await act(async () => {+ caught = await catalogRef.current!.create({ name: 'a', values: ['1'] }).catch((error: unknown) => error);+ // Let a rejection nobody handled reach the window.+ await new Promise((resolve) => {+ globalThis.setTimeout(resolve, 20);+ });+ });+ } finally {+ window.removeEventListener('unhandledrejection', unhandled);+ }++ expect(caught).toMatchObject({ message: 'Failed to fetch' });+ expect(unhandled).not.toHaveBeenCalled();+ });+});++describe('removeMany', () => {+ const ids = (count: number) => Array.from({ length: count }, (_, index) => `w${String(index)}`);++ afterEach(() => {+ accountLifecycle.invalidate();+ });++ it('sends a large selection in sequential batches of at most 1000 and invalidates once', async () => {+ let deleted: string[] = [];++ await act(async () => {+ deleted = await catalogRef.current!.removeMany(ids(2500));+ });++ expect(deleteWildcards.mock.calls.map(([batch]) => batch.length)).toEqual([1000, 1000, 500]);+ expect(deleted).toEqual(ids(2500));+ expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);+ });++ it('sends 720 ids in one request', async () => {+ await act(async () => {+ await catalogRef.current!.removeMany(ids(720));+ });++ expect(deleteWildcards).toHaveBeenCalledOnce();+ });++ it('refreshes the catalog when the server deleted none of them, as when another tab already had', async () => {+ deleteWildcards.mockImplementationOnce(() => Promise.resolve([]));++ await act(async () => {+ await catalogRef.current!.removeMany(ids(3));+ });++ expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);+ });++ it('drops the deleted row and cached expansions when the server committed the delete but its answer was lost', async () => {+ let server: WildcardsModule.WildcardRecord[] = [+ { id: 'w0', name: 'animal', values: ['cat'] },+ { id: 'w1', name: 'color', values: ['red'] },+ ];+ listWildcards.mockImplementation(() => Promise.resolve(server));+ const expansionKey = dynamicPromptsKeys.expansion({ prompt: 'a __animal__' });+ queryClient.setQueryData(expansionKey, { prompts: ['a cat'] });+ await act(() => queryClient.refetchQueries({ queryKey: ['generation', 'wildcards'] }));+ expect(catalogRef.current!.wildcards.map(({ id }) => id)).toEqual(['w0', 'w1']);++ deleteWildcards.mockImplementationOnce((batch) => {+ server = server.filter(({ id }) => !batch.includes(id));++ return Promise.reject(new TypeError('Failed to fetch'));+ });+ const releaseRefetch = holdCatalogRefetch(() => server);++ let caught: unknown;++ await act(async () => {+ caught = await catalogRef.current!.removeMany(['w0']).catch((error: unknown) => error);+ });++ // The failure is reported while the refresh is still out.+ expect(caught).toBeInstanceOf(WildcardDeleteError);+ expect((caught as WildcardDeleteError).deletedIds).toEqual([]);+ expect(queryClient.getQueryState(expansionKey)?.isInvalidated).toBe(true);+ expect(catalogRef.current!.wildcards.map(({ id }) => id)).toEqual(['w0', 'w1']);++ await act(async () => {+ releaseRefetch();+ await vi.waitFor(() => expect(queryClient.isFetching({ queryKey: ['generation', 'wildcards'] })).toBe(0));+ });++ expect(catalogRef.current!.wildcards.map(({ id }) => id)).toEqual(['w1']);+ });++ it('invalidates after a partial failure and names the ids deleted before it', async () => {+ deleteWildcards.mockImplementationOnce((batch) => Promise.resolve([...batch]));+ deleteWildcards.mockImplementationOnce(() => Promise.reject(new Error('offline')));++ let caught: unknown;++ await act(async () => {+ caught = await catalogRef.current!.removeMany(ids(1500)).catch((error: unknown) => error);+ });++ expect(caught).toBeInstanceOf(WildcardDeleteError);+ expect((caught as WildcardDeleteError).deletedIds).toEqual(ids(1000));+ expect(invalidateWildcardDependents).toHaveBeenCalledTimes(1);+ });++ it('stops, and leaves the next account alone, once the account it started under is gone', async () => {+ accountLifecycle.activate('wildcards-delete-a', ':user:wildcards-delete-a');+ deleteWildcards.mockImplementationOnce((batch) => {+ accountLifecycle.activate('wildcards-delete-b', ':user:wildcards-delete-b');++ return Promise.resolve([...batch]);+ });++ let caught: unknown;await act(async () => {- await catalogRef.current!.applyWrites(WRITES, captureAccountScope()).catch(() => undefined);+ caught = await catalogRef.current!.removeMany(ids(1500)).catch((error: unknown) => error);});+ expect(caught).toBeInstanceOf(Error);+ expect(deleteWildcards).toHaveBeenCalledOnce();expect(invalidateWildcardDependents).not.toHaveBeenCalled();});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.tsindex 564b53b050..fa860cd61c 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/useWildcards.ts@@ -1,11 +1,14 @@import type { WildcardRecord } from '@features/generation/data/wildcards';import type { AccountScope } from '@platform/state/accountLifecycle';+import type { QueryClient } from '@tanstack/react-query';import {createWildcard,deleteWildcard,+ deleteWildcards,invalidateWildcardDependents,updateWildcard,+ WILDCARD_DELETE_BATCH_SIZE,wildcardsQueryOptions,} from '@features/generation/data/wildcards';import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';@@ -31,6 +34,17 @@ export class WildcardWriteError extends Error {}}+/** Report the ids a failed batch delete removed before it failed, so the selection keeps only the rest. */+export class WildcardDeleteError extends Error {+ constructor(+ readonly deletedIds: readonly string[],+ override readonly cause: unknown+ ) {+ super(cause instanceof Error ? cause.message : String(cause));+ this.name = 'WildcardDeleteError';+ }+}+export interface WildcardCatalog {wildcards: WildcardRecord[];/** Names the backend can resolve, for the highlighter's known/unknown split. */@@ -39,10 +53,37 @@ export interface WildcardCatalog {create: (wildcard: { name: string; values: string[] }) => Promise<void>;update: (id: string, changes: { name?: string; values?: string[] }) => Promise<void>;remove: (id: string) => Promise<void>;+ /**+ * Deletes the wildcards in batches the server accepts, one request at a time, and invalidates once at the end;+ * resolves with the deleted ids. A failure rejects with a `WildcardDeleteError` naming those deleted before it.+ */+ removeMany: (ids: readonly string[]) => Promise<string[]>;/** Invalidate once after the batch; failures include the completed-write count. */applyWrites: (writes: readonly WildcardWrite[], owner: AccountScope) => Promise<number>;}+/**+ * Invalidate after an attempted write, fenced to the account it started under: a write whose answer was lost may still+ * have committed. A success waits for the refreshed catalog; a failure reports at once while the refresh, which may+ * retry against the same outage, runs behind it.+ */+const invalidateAfterAttempt = async (+ queryClient: QueryClient,+ owner: AccountScope,+ failed: boolean+): Promise<void> => {+ assertAccountScopeCurrent(owner);+ const invalidation = invalidateWildcardDependents(queryClient);++ if (failed) {+ // The write's own failure is what gets reported; the refresh failing too adds nothing to it.+ invalidation.catch(() => undefined);+ return;+ }++ await invalidation;+};+/** Wildcard edits invalidate otherwise permanent expansion entries. */export const useWildcards = (): WildcardCatalog => {const queryClient = useQueryClient();@@ -59,9 +100,14 @@ export const useWildcards = (): WildcardCatalog => {async (run: () => Promise<unknown>): Promise<void> => {const owner = captureAccountScope();- await run();- assertAccountScopeCurrent(owner);- await invalidateWildcardDependents(queryClient);+ try {+ await run();+ } catch (error) {+ await invalidateAfterAttempt(queryClient, owner, true);+ throw error;+ }++ await invalidateAfterAttempt(queryClient, owner, false);},[queryClient]);@@ -78,14 +124,51 @@ export const useWildcards = (): WildcardCatalog => {const remove = useCallback((id: string) => runAndInvalidate(() => deleteWildcard(id)), [runAndInvalidate]);+ const removeMany = useCallback(+ async (ids: readonly string[]): Promise<string[]> => {+ const owner = captureAccountScope();+ const deleted: string[] = [];+ let attempted = false;+ let failure: unknown;++ try {+ for (let start = 0; start < ids.length; start += WILDCARD_DELETE_BATCH_SIZE) {+ assertAccountScopeCurrent(owner);+ attempted = true;+ const batch = await deleteWildcards(ids.slice(start, start + WILDCARD_DELETE_BATCH_SIZE), owner.signal);++ assertAccountScopeCurrent(owner);+ deleted.push(...batch);+ }+ } catch (caught) {+ failure = caught;+ }++ // Any attempt can change the catalog: a batch whose answer was lost may still have committed, and ids an answer+ // leaves out may have gone in another tab.+ if (attempted) {+ await invalidateAfterAttempt(queryClient, owner, Boolean(failure));+ }++ if (failure) {+ throw new WildcardDeleteError(deleted, failure);+ }++ return deleted;+ },+ [queryClient]+ );+const applyWrites = useCallback(async (writes: readonly WildcardWrite[], owner: AccountScope): Promise<number> => {let done = 0;+ let attempted = false;let failure: unknown;try {for (const write of writes) {assertAccountScopeCurrent(owner);+ attempted = true;if (write.id === undefined) {await createWildcard({ name: write.name, values: write.values });@@ -100,10 +183,8 @@ export const useWildcards = (): WildcardCatalog => {failure = caught;}- // Invalidate after partial success, fenced to the originating account.- if (done > 0) {- assertAccountScopeCurrent(owner);- await invalidateWildcardDependents(queryClient);+ if (attempted) {+ await invalidateAfterAttempt(queryClient, owner, Boolean(failure));}if (failure) {@@ -115,5 +196,5 @@ export const useWildcards = (): WildcardCatalog => {[queryClient]);- return { applyWrites, create, isLoading: query.isPending, knownNames, remove, update, wildcards };+ return { applyWrites, create, isLoading: query.isPending, knownNames, remove, removeMany, update, wildcards };};diff --git a/invokeai/frontend/webv2/src/features/queue/data/mappers.test.ts b/invokeai/frontend/webv2/src/features/queue/data/mappers.test.tsindex 866b2770cd..700ec37301 100644--- a/invokeai/frontend/webv2/src/features/queue/data/mappers.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/mappers.test.ts@@ -77,6 +77,24 @@ describe('queue transport mappers', () => {expect(item).not.toHaveProperty('session');});+ it('reads naive server timestamps as UTC, keeping null and ISO values', () => {+ const item = mapQueueItemDTO({+ batch_id: 'batch-3',+ completed_at: '2026-10-19 08:05:30.5',+ created_at: '2026-10-19 08:00:00.123',+ item_id: 9,+ session_id: 'session-3',+ started_at: null,+ status: 'completed',+ updated_at: '2026-10-19T08:05:30.500Z',+ });++ expect(item.createdAt).toBe('2026-10-19T08:00:00.123Z');+ expect(item.completedAt).toBe('2026-10-19T08:05:30.500Z');+ expect(item.startedAt).toBeNull();+ expect(item.updatedAt).toBe('2026-10-19T08:05:30.500Z');+ });+it('maps status and id-list response names at the adapter boundary', () => {expect(mapQueueItemIdsDTO({ item_ids: [9, 8] })).toEqual({ itemIds: [9, 8] });expect(diff --git a/invokeai/frontend/webv2/src/features/queue/data/mappers.ts b/invokeai/frontend/webv2/src/features/queue/data/mappers.tsindex f23edf7371..2a097c9410 100644--- a/invokeai/frontend/webv2/src/features/queue/data/mappers.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/mappers.ts@@ -8,6 +8,7 @@ import type {} from '@features/queue/core/types';import { getOutputImageNames } from '@platform/core/outputImages';+import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';import type {QueueAndProcessorStatusDTO,@@ -22,14 +23,18 @@ const mapNodeFieldValue = (dto: QueueNodeFieldValueDTO): QueueNodeFieldValue =>value: dto.value && typeof dto.value === 'object' ? { imageName: dto.value.image_name } : dto.value,});+/** The server sends naive UTC; absent and null stay as they are. */+const normalizeOptionalTimestamp = <T extends string | null | undefined>(value: T): T =>+ (typeof value === 'string' ? normalizeServerTimestamp(value) : value) as T;+const getResultImageNames = (dto: QueueServerItemDTO): string[] => {return Object.values(dto.session?.results ?? {}).flatMap(getOutputImageNames);};export const mapQueueItemDTO = (dto: QueueServerItemDTO): QueueItemReadModel => ({batchId: dto.batch_id,- completedAt: dto.completed_at,- createdAt: dto.created_at,+ completedAt: normalizeOptionalTimestamp(dto.completed_at),+ createdAt: normalizeServerTimestamp(dto.created_at),destination: dto.destination,device: dto.device,errorMessage: dto.error_message,@@ -45,9 +50,9 @@ export const mapQueueItemDTO = (dto: QueueServerItemDTO): QueueItemReadModel =>resultImageNames: getResultImageNames(dto),retriedFromItemId: dto.retried_from_item_id,sessionId: dto.session_id,- startedAt: dto.started_at,+ startedAt: normalizeOptionalTimestamp(dto.started_at),status: dto.status,- updatedAt: dto.updated_at,+ updatedAt: normalizeServerTimestamp(dto.updated_at),userDisplayName: dto.user_display_name,userEmail: dto.user_email,userId: dto.user_id,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsxindex 4f28ceeefd..bb99756db0 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx@@ -2182,6 +2182,11 @@ describe('WorkflowFieldInput scalar collections', () => {});describe('WorkflowFieldInput record pickers', () => {+ // The pickers are a lazy chunk; load it up front so the first test is not timing a cold transform.+ beforeAll(async () => {+ await import('./RecordPickerInput');+ });+const STYLE_PRESET = fullTemplate('StringField', {title: 'Style Preset',type: { batch: false, cardinality: 'SINGLE', name: 'StylePresetField' },diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.browser.test.tsxindex 2d02e01a5c..89af4ec851 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.browser.test.tsx@@ -1,5 +1,5 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop */-import { ChakraProvider } from '@chakra-ui/react';+import { ChakraProvider, Field, Input } from '@chakra-ui/react';import { system } from '@theme/system';import { act, type ReactElement } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -7,6 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';import { ListItem } from './ListItem';+import { ListSelectionBar } from './ListSelectionBar';vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));@@ -182,3 +183,31 @@ describe('ListItem', () => {expect(title.textContent).toContain('third line');});});++describe('list checkboxes inside a form Field', () => {+ // A popover opened from a field's label keeps the Field's context; its list must not bind to the Field's input.+ it('toggle their own rows on a click and leave the Field input alone', async () => {+ const onSelectAll = vi.fn();+ const onRow = vi.fn();++ await render(+ <Field.Root>+ <Input aria-label="Field input" />+ <ListSelectionBar checked={false} label="Select all" onCheckedChange={onSelectAll} />+ <ListItem title="first" onCheckedChange={onRow} />+ <ListItem title="second" onCheckedChange={vi.fn()} />+ </Field.Root>+ );+ const input = host.querySelector<HTMLInputElement>('input[aria-label="Field input"]')!;+ const controls = host.querySelectorAll<HTMLElement>('[data-scope="checkbox"][data-part="control"]');+ const ids = [...host.querySelectorAll('input')].map((element) => element.id);++ expect(new Set(ids).size).toBe(ids.length);+ await act(() => userEvent.click(controls[0]!));+ await act(() => userEvent.click(controls[1]!));++ expect(onSelectAll).toHaveBeenCalledOnce();+ expect(onRow).toHaveBeenCalledOnce();+ expect(document.activeElement).not.toBe(input);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsxindex 029ad68d4e..07453c08b9 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx@@ -3,7 +3,7 @@ import type { MouseEvent, PointerEvent, ReactNode } from 'react';import { Checkbox, chakra, useSlotRecipe } from '@chakra-ui/react';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { listItemSlotRecipe } from '@theme/recipes';-import { useCallback, useMemo, useRef } from 'react';+import { useCallback, useId, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';export type ListDensity = 'compact' | 'regular' | 'comfortable' | 'snug';@@ -62,6 +62,8 @@ export interface ListItemProps {setSize?: number;/** Makes a standalone row a button; without it, and without a context menu, the row is static content. */onPress?: (event: MouseEvent<HTMLButtonElement>) => void;+ /** Accessible name of the row's button when its text alone does not say what pressing it does. */+ pressLabel?: string;/** Fires on hover and focus, ahead of a press, to warm what the press will need. */onIntent?: () => void;/** Renders the leading checkbox. */@@ -105,7 +107,12 @@ export const ListItem = ({onContextMenu,onIntent,onPress,+ pressLabel,}: ListItemProps) => {+ // Its own ids, so a row inside a form Field (a popover opened from a field's label, say) never takes the Field's+ // control id: that would point the checkbox's label at the Field's input instead of this checkbox.+ const checkInputId = useId();+ const checkIds = useMemo(() => ({ hiddenInput: checkInputId }), [checkInputId]);const { t } = useTranslation();const recipe = useSlotRecipe({ recipe: listItemSlotRecipe });const tone = isActive ? 'accent' : isChecked ? 'selected' : 'none';@@ -241,6 +248,7 @@ export const ListItem = ({<Checkbox.Rootaria-label={checkLabel ?? t('common.list.selectItem', { name: title })}checked={isChecked}+ ids={checkIds}colorPalette="accent"disabled={isBusy}size="sm"@@ -257,6 +265,7 @@ export const ListItem = ({aria-disabled={isBusy || undefined}aria-expanded={onContextMenu && !onPress ? isMenuOpen : isExpanded}aria-haspopup={onContextMenu && !onPress ? 'menu' : undefined}+ aria-label={pressLabel}css={styles.primary}data-list-primary=""tabIndex={tabIndex}diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListSelectionBar.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListSelectionBar.tsxindex 329ecce9f4..cf101c4339 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/ListSelectionBar.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListSelectionBar.tsx@@ -1,7 +1,7 @@import type { ReactNode } from 'react';import { Checkbox, HStack, Separator, Text, type StackProps } from '@chakra-ui/react';-import { Children } from 'react';+import { Children, useId, useMemo } from 'react';import { LIST_CHECK_INSET, LIST_ROW_INSET } from './listLayout';@@ -33,40 +33,47 @@ export const ListSelectionBar = ({summaryId,onCheckedChange,...stackProps-}: ListSelectionBarProps) => (- <HStack- borderBottomWidth="1px"- borderColor="border.subtle"- flexShrink={0}- gap="2"- minH="8"- pe={LIST_ROW_INSET}- ps={LIST_CHECK_INSET}- py="1.5"- {...stackProps}- >- <Checkbox.Root- aria-label={label}- checked={checked}- colorPalette="accent"- disabled={isDisabled}- size="sm"- onCheckedChange={onCheckedChange}+}: ListSelectionBarProps) => {+ // Its own ids, so a list inside a form Field never binds the select-all control to the Field's input.+ const inputId = useId();+ const checkboxIds = useMemo(() => ({ hiddenInput: inputId }), [inputId]);++ return (+ <HStack+ borderBottomWidth="1px"+ borderColor="border.subtle"+ flexShrink={0}+ gap="2"+ minH="8"+ pe={LIST_ROW_INSET}+ ps={LIST_CHECK_INSET}+ py="1.5"+ {...stackProps}>- <Checkbox.HiddenInput />- <Checkbox.Control />- <Checkbox.Label color="fg.muted" fontSize="xs" fontWeight="600">- {label}- </Checkbox.Label>- </Checkbox.Root>- <Text color="fg.muted" flex="1" fontSize="xs" id={summaryId} minW="0" textAlign="end" truncate>- {summary}- </Text>- {Children.toArray(children).length > 0 ? (- <>- <Separator borderColor="border.subtle" h="4" orientation="vertical" />- {children}- </>- ) : null}- </HStack>-);+ <Checkbox.Root+ aria-label={label}+ checked={checked}+ ids={checkboxIds}+ colorPalette="accent"+ disabled={isDisabled}+ size="sm"+ onCheckedChange={onCheckedChange}+ >+ <Checkbox.HiddenInput />+ <Checkbox.Control />+ <Checkbox.Label color="fg.muted" fontSize="xs" fontWeight="600">+ {label}+ </Checkbox.Label>+ </Checkbox.Root>+ <Text color="fg.muted" flex="1" fontSize="xs" id={summaryId} minW="0" textAlign="end" truncate>+ {summary}+ </Text>+ {Children.toArray(children).length > 0 ? (+ <>+ <Separator borderColor="border.subtle" h="4" orientation="vertical" />+ {children}+ </>+ ) : null}+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.tsindex e9f52792a9..5c81599b71 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.test.ts@@ -1,7 +1,6 @@import type { Vec2 } from '@workbench/canvas-engine/types';import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';-import { ZOOM_PRESETS } from '@workbench/canvas-engine/math/snapping';import { describe, expect, it, vi } from 'vitest';import { createViewport } from './viewport';@@ -42,14 +41,61 @@ describe('createViewport', () => {closeTo(vp.documentToScreen(docUnderAnchorBefore), anchor);});- it('wheelZoom is continuous and does not snap to a preset', () => {- // Small zoom steps must move instead of sticking inside preset capture bands.+ it('wheelZoom notches that would pass 87% → 101% → 118% rest on 100% first', () => {+ const vp = createViewport({ pan: { x: 0, y: 0 }, zoom: 0.87 });+ const anchor: Vec2 = { x: 120, y: 80 };+ const docUnderAnchor = vp.screenToDocument(anchor);+ const zooms: number[] = [];++ for (let notch = 0; notch < 3; notch += 1) {+ vp.wheelZoom(-100, anchor);+ zooms.push(vp.getZoom());+ }++ expect(zooms[0]).toBe(1);+ // Leaving 100%, zoom continues from where the wheel would have been: 87% after two notches.+ expect(zooms[1]).toBeCloseTo(0.87 * Math.exp(0.3), 9);+ expect(zooms[2]).toBeCloseTo(0.87 * Math.exp(0.45), 9);+ closeTo(vp.documentToScreen(docUnderAnchor), anchor);+ });++ it('wheelZoom starts afresh after any other zoom change, even one to the same zoom', () => {+ const vp = createViewport({ pan: { x: 0, y: 0 }, zoom: 1 });+ // Resting on 100% with the intended zoom at about 101.8%, just inside the tolerance.+ vp.wheelZoom(-12, { x: 0, y: 0 });+ expect(vp.getZoom()).toBe(1);++ // Fit lands on exactly 100%. Had the remembered intended zoom survived it, this small step would leave 100%.+ vp.fitToView({ height: 100, width: 100, x: 0, y: 0 }, { height: 200, width: 200 }, 50);+ vp.wheelZoom(-2, { x: 0, y: 0 });++ expect(vp.getZoom()).toBe(1);+ });++ it('wheelZoom starts a new gesture from the zoom shown after a pause in wheel events', () => {+ const now = vi.spyOn(performance, 'now').mockReturnValue(1_000);+ try {+ const vp = createViewport({ pan: { x: 0, y: 0 }, zoom: 1 });+ // Resting on 100% with the intended zoom at about 101.8%, just inside the tolerance.+ vp.wheelZoom(-12, { x: 0, y: 0 });+ expect(vp.getZoom()).toBe(1);++ // A pause ends the gesture: this small step starts from 100% and stays on it, where it would otherwise leave.+ now.mockReturnValue(1_400);+ vp.wheelZoom(-2, { x: 0, y: 0 });++ expect(vp.getZoom()).toBe(1);+ } finally {+ now.mockRestore();+ }+ });++ it('wheelZoom leaves a snap point once leftover movement in the same gesture crosses its tolerance', () => {const vp = createViewport({ pan: { x: 0, y: 0 }, zoom: 1 });- const anchor: Vec2 = { x: 0, y: 0 };+ vp.wheelZoom(-12, { x: 0, y: 0 });+ vp.wheelZoom(-2, { x: 0, y: 0 });- vp.wheelZoom(-1, anchor);expect(vp.getZoom()).toBeGreaterThan(1);- expect(ZOOM_PRESETS).not.toContain(vp.getZoom());});it('wheelZoom crosses a preset instead of parking on it', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.tsindex 3fb186dffb..4ec64d1f20 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts@@ -8,8 +8,9 @@ import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';import { clampZoom } from '@workbench/canvas-engine/math/snapping';import {panBy as calculatePanBy,- wheelZoomAtPoint as calculateWheelZoomAtPoint,+ snapWheelZoom,zoomAtPoint as calculateZoomAtPoint,+ type WheelZoomSnap,} from '@workbench/panZoom';export { WHEEL_ZOOM_STEP } from '@workbench/panZoom';@@ -47,7 +48,10 @@ export interface Viewport {documentToScreen(p: Vec2): Vec2;/** Sets zoom while keeping the document point under `screenAnchor` fixed. */zoomAtPoint(newZoom: number, screenAnchor: Vec2): void;- /** Exponential wheel zoom about `screenAnchor`. Continuous — never snaps to a preset. */+ /**+ * Exponential wheel zoom about `screenAnchor` that rests on the wheel snap points (`snapWheelZoom`): sticky across+ * consecutive wheel steps; any other zoom change starts the next wheel step afresh.+ */wheelZoom(deltaY: number, screenAnchor: Vec2): void;/** Pans by a CSS-pixel screen delta. */panBy(screenDelta: Vec2): void;@@ -68,6 +72,8 @@ export const createViewport = (initial?: Partial<ViewState>): Viewport => {let zoom = clampZoom(initial?.zoom ?? 1);let size: Size = { height: 0, width: 0 };let dpr = 1;+ /** Wheel zoom's snap memory; only `wheelZoom` keeps it, every other zoom change drops it. */+ let wheelSnap: WheelZoomSnap | null = null;const listeners = new Set<() => void>();@@ -87,6 +93,7 @@ export const createViewport = (initial?: Partial<ViewState>): Viewport => {zoom === 0 ? { x: 0, y: 0 } : { x: (p.x - pan.x) / zoom, y: (p.y - pan.y) / zoom };const zoomAtPoint = (newZoom: number, screenAnchor: Vec2): void => {+ wheelSnap = null;const next = calculateZoomAtPoint({ pan, zoom }, newZoom, screenAnchor, clampZoom);zoom = next.zoom;pan = next.pan;@@ -94,7 +101,8 @@ export const createViewport = (initial?: Partial<ViewState>): Viewport => {};const wheelZoom = (deltaY: number, screenAnchor: Vec2): void => {- const next = calculateWheelZoomAtPoint({ pan, zoom }, deltaY, screenAnchor, { constrainZoom: clampZoom });+ wheelSnap = snapWheelZoom(wheelSnap, zoom, deltaY, { constrainZoom: clampZoom, now: performance.now() });+ const next = calculateZoomAtPoint({ pan, zoom }, wheelSnap.zoom, screenAnchor, clampZoom);zoom = next.zoom;pan = next.pan;emit();@@ -113,6 +121,7 @@ export const createViewport = (initial?: Partial<ViewState>): Viewport => {return;}const fitZoom = clampZoom(Math.min(availWidth / documentRect.width, availHeight / documentRect.height));+ wheelSnap = null;const docCenter: Vec2 = {x: documentRect.x + documentRect.width / 2,y: documentRect.y + documentRect.height / 2,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.tsindex ab62a20157..d338a83449 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.test.ts@@ -157,7 +157,7 @@ describe('saveCanvasToGallery', () => {region: 'canvas',uploadImage: harness.uploadImage,})- ).resolves.toEqual({ imageName: 'saved.png', status: 'saved' });+ ).resolves.toEqual({ boardId: 'board-1', imageName: 'saved.png', status: 'saved' });expect(harness.order).toEqual(['flush', 'document', 'export', 'upload']);expect(harness.exportRasterComposite).toHaveBeenCalledWith({ bounds: 'content' });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.tsindex 1aef2ef1f6..8f34f0616a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/saveCanvasToGallery.ts@@ -25,8 +25,8 @@ import { exportCanvasComposite } from './exportCanvasComposite';export type CanvasGallerySaveRegion = CanvasCompositeRegion;export type SaveCanvasToGalleryResult =- | { status: 'saved'; imageName: string }- | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' };+ /** `boardId` is where the image went: a board id, or `none` for Uncategorized. */+ { status: 'saved'; boardId: string; imageName: string } | { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' };const buildCanvasSaveMetadata = (project: Project, rect: Rect): Record<string, unknown> => {const generateValues = normalizeGenerateWidgetValues(getProjectWidgetValues(project, 'generate'));@@ -103,7 +103,7 @@ export const saveCanvasToGallery = async (options: {});assertAccountScopeCurrent(owner);- return { imageName: uploaded.imageName, status: 'saved' };+ return { boardId: boardId ?? 'none', imageName: uploaded.imageName, status: 'saved' };} catch (error) {if (!isAccountScopeCurrent(owner)) {return { status: 'stale' };diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsxindex 2203d10de6..7fb824f47f 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx@@ -14,7 +14,7 @@ import type { RegisteredHotkey } from './types';import { firstPartyHotkeyCatalog } from './catalog';import { useExtensionHotkeyDefinitions } from './extensionHotkeys';import { useRegisterFirstPartyCommands } from './firstPartyCommands';-import { toTinykeysBinding } from './keys';+import { acceptsHotkeyPress, toTinykeysBinding } from './keys';import { applyCustomHotkeys, resolveHotkey } from './resolve';import { getHotkeyTargetWidget, resolveHotkeyTarget } from './targetWidget';@@ -91,7 +91,11 @@ export const WorkbenchHotkeyRuntime = () => {const tinykeysBinding = toTinykeysBinding(key);if (tinykeysBinding) {- bindings[tinykeysBinding] = (event) => handleHotkey(event, key);+ bindings[tinykeysBinding] = (event) => {+ if (acceptsHotkeyPress(event, key)) {+ handleHotkey(event, key);+ }+ };}}}diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.tsindex c8fe41f0db..4201a01202 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts@@ -29,6 +29,18 @@ describe('firstPartyHotkeyCatalog', () => {expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.selectVideoPreset');});+ it('clears the canvas on Mod+Alt+N, keeping the command id that saved bindings use', () => {+ const clearCanvas = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'canvas.newSession');++ expect(clearCanvas).toMatchObject({ defaultKeys: ['mod+alt+n'], title: 'Clear Canvas' });+ });++ it('names the automate preset Workflow, keeping its id', () => {+ const selectWorkflow = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'app.selectAutomatePreset');++ expect(selectWorkflow).toMatchObject({ defaultKeys: ['alt+4'], title: 'Select Workflow Preset' });+ });+it('uses the exported command-palette definition as the catalog entry', () => {expect(firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'app.openCommandPalette')).toBe(OPEN_COMMAND_PALETTE_HOTKEYdiff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.tsindex 9db3d0b247..8f02378bcf 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts@@ -229,7 +229,7 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [hotkey('app', 'selectComposePreset', ['alt+1']),hotkey('app', 'selectEditPreset', ['alt+2']),hotkey('app', 'selectVideoPreset', ['alt+3']),- hotkey('app', 'selectAutomatePreset', ['alt+4']),+ hotkey('app', 'selectAutomatePreset', ['alt+4'], { title: 'Select Workflow Preset' }),hotkey('app', 'cancelQueueItem', ['shift+x']),hotkey('app', 'clearQueue', ['mod+shift+x']),hotkey('app', 'selectGenerateTab', ['1']),@@ -288,8 +288,9 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [hotkey('canvas', 'toggleNonRasterLayers', ['shift+h']),hotkey('canvas', 'fitBboxToMasks', ['shift+b']),hotkey('canvas', 'toggleBbox', ['shift+o']),- // New canvas session and the gallery saves: no default keys — assignable via the hotkeys settings.- hotkey('canvas', 'newSession', []),+ // Clear canvas keeps its saved-binding id, `newSession`.+ hotkey('canvas', 'newSession', ['mod+alt+n'], { title: 'Clear Canvas' }),+ // The gallery saves have no default keys; they are assignable through the hotkeys settings.hotkey('canvas', 'saveToGallery', []),hotkey('canvas', 'saveBboxToGallery', []),hotkey('workflows', 'addNode', ['shift+a', 'space']),diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.tsindex d012c93860..4dc2125883 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts@@ -5,11 +5,25 @@ import {eventToHotkeyString,formatHotkeyAriaLabel,formatHotkeyForPlatform,+ acceptsHotkeyPress,formatHotkeyLabel,+ isHotkeyPress,normalizeHotkeyString,toTinykeysBinding,} from './keys';+/** A keydown as a browser reports it, with the modifier state tinykeys reads. */+const press = (init: { key: string; code: string; altKey?: boolean; metaKey?: boolean }): KeyboardEvent =>+ ({+ altKey: false,+ ctrlKey: false,+ metaKey: false,+ shiftKey: false,+ ...init,+ getModifierState: (modifier: string) =>+ (modifier === 'Alt' && init.altKey === true) || (modifier === 'Meta' && init.metaKey === true),+ }) as unknown as KeyboardEvent;+describe('hotkey keys', () => {it('normalizes modifier order and aliases', () => {expect(normalizeHotkeyString('Shift+Mod+Enter')).toBe('mod+shift+enter');@@ -23,6 +37,75 @@ describe('hotkey keys', () => {expect(toTinykeysBinding('.')).toBe('Period');});+ it('names an Alt chord with Cmd, Ctrl or Meta by its character or its position, every other binding by character', () => {+ expect(toTinykeysBinding('mod+alt+n')).toBe('$mod+Alt+(n|KeyN)');+ expect(toTinykeysBinding('ctrl+alt+1')).toBe('Control+Alt+(1|Digit1)');+ expect(toTinykeysBinding('alt+a')).toBe('Alt+a');+ expect(toTinykeysBinding('alt+1')).toBe('Alt+1');+ expect(toTinykeysBinding('mod+n')).toBe('$mod+n');+ expect(toTinykeysBinding('alt+]')).toBe('Alt+BracketRight');+ });++ it('fires Cmd+Option+N on macOS, where Option turns the key into a dead key', () => {+ expect(isHotkeyPress(press({ altKey: true, code: 'KeyN', key: 'Dead', metaKey: true }), 'meta+alt+n')).toBe(true);+ expect(isHotkeyPress(press({ altKey: true, code: 'KeyN', key: '˜', metaKey: true }), 'meta+alt+n')).toBe(true);+ expect(isHotkeyPress(press({ altKey: true, code: 'KeyM', key: 'µ', metaKey: true }), 'meta+alt+n')).toBe(false);+ });++ it('leaves Option+A to type å: an Alt chord alone matches only its character', () => {+ expect(isHotkeyPress(press({ altKey: true, code: 'KeyA', key: 'å' }), 'alt+a')).toBe(false);+ expect(isHotkeyPress(press({ altKey: true, code: 'KeyA', key: 'a' }), 'alt+a')).toBe(true);+ });++ it('keeps a letter on the key that types it on other layouts', () => {+ // AZERTY: the key labelled A sits where QWERTY has Q.+ expect(isHotkeyPress(press({ altKey: true, code: 'KeyQ', key: 'a' }), 'alt+a')).toBe(true);+ expect(isHotkeyPress(press({ altKey: true, code: 'KeyA', key: 'q' }), 'alt+a')).toBe(false);+ // Dvorak: the key at QWERTY N types b; with Cmd+Alt it is still b, not n.+ expect(isHotkeyPress(press({ altKey: true, code: 'KeyN', key: 'b', metaKey: true }), 'meta+alt+n')).toBe(false);+ // On a Cyrillic layout, the key at N's position types т: the plain `n` binding is not it.+ expect(isHotkeyPress(press({ code: 'KeyN', key: 'т' }), 'n')).toBe(false);+ });++ it('reads AltGr as Alt, as tinykeys does, except for a press matched by position', () => {+ // Browsers report AltGr for Ctrl+Alt on AltGr layouts.+ const withAltGr = (init: Parameters<typeof press>[0] & { ctrlKey?: boolean }) =>+ ({+ ...press(init),+ ctrlKey: init.ctrlKey === true,+ getModifierState: (modifier: string) =>+ modifier === 'AltGraph' ||+ modifier === 'Alt' ||+ (modifier === 'Control' && init.ctrlKey === true) ||+ (modifier === 'Meta' && init.metaKey === true),+ }) as unknown as KeyboardEvent;++ expect(+ acceptsHotkeyPress(withAltGr({ altKey: true, code: 'Enter', ctrlKey: true, key: 'Enter' }), 'alt+mod+enter')+ ).toBe(true);+ expect(acceptsHotkeyPress(withAltGr({ altKey: true, code: 'Digit1', key: '1' }), 'alt+1')).toBe(true);+ expect(isHotkeyPress(withAltGr({ altKey: true, code: 'Digit1', key: '1' }), 'alt+1')).toBe(true);+ // AltGr+N types ń: not Cmd/Ctrl+Alt+N by position.+ expect(isHotkeyPress(withAltGr({ altKey: true, code: 'KeyN', key: 'ń', metaKey: true }), 'meta+alt+n')).toBe(false);+ });++ it('records a typed letter as typed, and a dead key or symbol by its position', () => {+ expect(eventToHotkeyString(press({ altKey: true, code: 'KeyN', key: 'Dead', metaKey: true }), true)).toBe(+ 'mod+alt+n'+ );+ expect(eventToHotkeyString(press({ altKey: true, code: 'KeyQ', key: 'a' }), false)).toBe('alt+a');+ // Ctrl+Alt+N on a Polish layout is AltGr+N, which types ń: recorded as typed, it matches again.+ const polish = {+ ...press({ altKey: true, code: 'KeyN', key: 'ń' }),+ ctrlKey: true,+ getModifierState: (modifier: string) => modifier === 'AltGraph' || modifier === 'Alt' || modifier === 'Control',+ } as unknown as KeyboardEvent;+ expect(eventToHotkeyString(polish, false)).toBe('mod+alt+ń');+ expect(acceptsHotkeyPress(polish, 'mod+alt+ń')).toBe(true);+ // Option alone matches only by character, so it records the character it types.+ expect(eventToHotkeyString(press({ altKey: true, code: 'KeyA', key: 'å' }), true)).toBe('alt+å');+ });+it('ignores IME composition events when recording hotkeys', () => {expect(eventToHotkeyString({ isComposing: true, key: 'a' } as KeyboardEvent)).toBe('');expect(eventToHotkeyString({ key: 'Process', keyCode: 229 } as KeyboardEvent)).toBe('');diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/keys.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.tsindex 74b9ed9f79..339b6f5f23 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/keys.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.ts@@ -65,6 +65,12 @@ export const normalizeHotkeyString = (hotkey: string): string => {return key ? [...modifiers, key].join('+') : '';};+/** A Latin letter or digit, as a binding names a key. */+const isLatinKey = (key: string): boolean => /^[a-z0-9]$/i.test(key);++/** The physical key of a Latin letter or digit (`KeyN`, `Digit1`). */+const toPhysicalKeyCode = (key: string): string => (/^[0-9]$/.test(key) ? `Digit${key}` : `Key${key.toUpperCase()}`);+/** `mod` is the platform's primary modifier (Cmd on macOS, Ctrl elsewhere); the other one, when held too, is kept. */export const eventToHotkeyString = (event: KeyboardEvent, isMacOs = IS_MAC_OS): string => {if (event.isComposing || event.keyCode === 229 || ['Alt', 'Control', 'Meta', 'Shift'].includes(event.key)) {@@ -86,14 +92,71 @@ export const eventToHotkeyString = (event: KeyboardEvent, isMacOs = IS_MAC_OS):modifiers.push('alt');}- return normalizeHotkeyString([...modifiers, event.key].join('+'));+ // A key is recorded as typed, so the binding keeps its meaning on any layout. Only a chord the matching falls back+ // to position for (Alt with Cmd, Ctrl or Meta) records a dead key or symbol by its position: there macOS's Option+ // reports `Dead` or `˜` for N. Option alone keeps the typed character (`alt+å`), as it matches only by character.+ // AltGr typed a character of the layout (`ń`): that character is the binding, as matching refuses position under it.+ const fallsBackToPosition =+ event.altKey &&+ modifiers.some((modifier) => modifier !== 'shift' && modifier !== 'alt') &&+ event.getModifierState?.('AltGraph') !== true;+ const physical =+ fallsBackToPosition && !isLatinKey(event.key) ? /^(?:Key([A-Z])|Digit([0-9]))$/.exec(event.code ?? '') : null;+ const key = physical ? (physical[1] ?? physical[2]!).toLowerCase() : event.key;++ return normalizeHotkeyString([...modifiers, key].join('+'));+};++/**+ * Whether a binding may also match its letter or digit by position: an Alt chord with Cmd, Ctrl or Meta, which types+ * no character. macOS's Option still changes the key such a chord reports (`Dead`, `˜`), so `mod+alt+n` would never+ * fire by character. An Alt chord alone keeps to the character, so Option+A still types `å` in a text field.+ */+const hasPositionFallback = (parts: readonly string[]): boolean => {+ const key = parts.at(-1) ?? '';++ return (+ parts.includes('alt') &&+ (parts.includes('mod') || parts.includes('ctrl') || parts.includes('meta')) &&+ isLatinKey(key) &&+ key.length === 1+ );};export const toTinykeysBinding = (hotkey: string): string => {const normalized = normalizeHotkeyString(hotkey);const parts = normalized.split('+').filter(Boolean);+ const key = parts.at(-1) ?? '';+ // The character, or its position (tinykeys tests a `(…)` pattern against both the key and the code);+ // `acceptsHotkeyPress` admits the position only when the press typed no Latin character.+ const positional = hasPositionFallback(parts) ? `(${key}|${toPhysicalKeyCode(key)})` : null;++ return parts+ .map((part, index) =>+ index === parts.length - 1 && positional+ ? positional+ : (TINY_MODIFIER_ALIASES[part] ?? TINY_KEY_ALIASES[part] ?? part)+ )+ .join('+');+};++/**+ * The checks a press must pass beyond the tinykeys match, for a binding matched by its key's position: the press must+ * have typed no Latin character, so a non-QWERTY layout's letters keep their meaning; and it must not hold AltGr, which+ * some layouts need to type a character at that position (`ń`). Every other match stands as tinykeys made it,+ * including its reading of AltGr as Alt (browsers report AltGr for Ctrl+Alt on those layouts).+ */+export const acceptsHotkeyPress = (event: KeyboardEvent, hotkey: string): boolean => {+ const parts = normalizeHotkeyString(hotkey).split('+').filter(Boolean);+ const key = parts.at(-1) ?? '';- return parts.map((part) => TINY_MODIFIER_ALIASES[part] ?? TINY_KEY_ALIASES[part] ?? part).join('+');+ if (!hasPositionFallback(parts) || event.key.toLowerCase() === key) {+ return true;+ }++ return (+ !isLatinKey(event.key) && event.code === toPhysicalKeyCode(key) && event.getModifierState?.('AltGraph') !== true+ );};/**@@ -103,7 +166,7 @@ export const toTinykeysBinding = (hotkey: string): string => {export const isHotkeyPress = (event: KeyboardEvent, hotkey: string): boolean => {const binding = toTinykeysBinding(hotkey);const [press] = binding ? parseKeybinding(binding) : [];- return press !== undefined && matchKeybindingPress(event, press);+ return press !== undefined && matchKeybindingPress(event, press) && acceptsHotkeyPress(event, hotkey);};/** The `mod` key's platform name; a bare modifier normalizes to nothing, so use this rather than formatting 'mod'. */diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/intents.test.ts b/invokeai/frontend/webv2/src/workbench/launchpad/intents.test.tsindex 7ecbd21d74..86724b9f93 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/intents.test.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/intents.test.ts@@ -17,7 +17,7 @@ describe('launchpad intents', () => {}});- it('opens text-to-image in Compose and node work in Automate', () => {+ it('opens text-to-image in Compose and node work in Workflow', () => {expect(resolveLaunchpadIntent('generate')).toEqual({ id: 'generate', presetId: 'compose', sourceId: 'generate' });expect(resolveLaunchpadIntent('workflow')).toEqual({ id: 'workflow', presetId: 'automate', sourceId: 'workflow' });});diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/intents.ts b/invokeai/frontend/webv2/src/workbench/launchpad/intents.tsindex e49e4abf79..e46a315378 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/intents.ts+++ b/invokeai/frontend/webv2/src/workbench/launchpad/intents.ts@@ -33,9 +33,20 @@ const INTENTS: Record<LaunchpadIntentId, LaunchpadIntent> = {export const isLaunchpadIntentId = (value: unknown): value is LaunchpadIntentId =>typeof value === 'string' && LAUNCHPAD_INTENT_IDS.includes(value as LaunchpadIntentId);-/** Share built-in labels without loading widget-region snapshots; layoutPresets derives its labels from this map. */+/**+ * Share built-in labels without loading widget-region snapshots; layoutPresets derives its labels from these maps.+ * The keys name what a preset is called in the UI; the English labels are the shipped defaults that a stored rename+ * is compared with. Ids stay as they were (`automate`): layouts and saved bindings persist them.+ */+export const BUILT_IN_LAYOUT_PRESET_LABEL_KEYS: Record<BuiltInLayoutPresetId, string> = {+ automate: 'topbar.presets.builtInLabels.automate',+ compose: 'topbar.presets.builtInLabels.compose',+ edit: 'topbar.presets.builtInLabels.edit',+ video: 'topbar.presets.builtInLabels.video',+};+export const BUILT_IN_LAYOUT_PRESET_LABELS: Record<BuiltInLayoutPresetId, string> = {- automate: 'Automate',+ automate: 'Workflow',compose: 'Compose',edit: 'Edit',video: 'Video',diff --git a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts b/invokeai/frontend/webv2/src/workbench/layoutContracts.tsindex 3eef417c6e..11998d71e2 100644--- a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutContracts.ts@@ -92,6 +92,11 @@ export interface LayoutPresetRoute {export interface LayoutPreset {id: LayoutPresetId;label: string;+ /**+ * The i18n key a built-in preset is shown by while the account has not renamed it; `label` is then its English+ * default. Never on a custom preset, and never persisted.+ */+ labelKey?: string;isBuiltIn?: boolean;/** Missing only on legacy or source-less custom presets. */defaultRoute?: LayoutPresetRoute;diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.tsindex e9e5f95dbd..e9bd74176f 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts@@ -26,9 +26,12 @@ export const getLayoutPresetCommandTitleOverrides = (): Readonly<Record<string, string>> =>Object.fromEntries(builtInLayoutPresetDescriptors.flatMap(({ hotkeyId, preset }) => {- const savedLabel = resolveSavedLayoutPreset(account, preset.id).label;+ const saved = resolveSavedLayoutPreset(account, preset.id);- return savedLabel === preset.label ? [] : [[`app.${hotkeyId}`, formatTitle(savedLabel)]];+ // Only a rename: a preset still on its shipped name keeps the catalog title.+ return saved.labelKey !== undefined || saved.label === preset.label+ ? []+ : [[`app.${hotkeyId}`, formatTitle(saved.label)]];}));@@ -48,9 +51,23 @@ export const resolveSavedLayoutPreset = (account: AccountState, presetId: Layoutconst override = account.layoutPresetOverrides?.[builtInPreset.id];const defaultRoute = account.layoutPresetRouteOverrides?.[builtInPreset.id] ?? builtInPreset.defaultRoute;- return metadata || override || defaultRoute !== builtInPreset.defaultRoute- ? { ...builtInPreset, ...metadata, defaultRoute, snapshot: override ?? builtInPreset.snapshot }- : builtInPreset;+ if (!metadata && !override && defaultRoute === builtInPreset.defaultRoute) {+ return builtInPreset;+ }++ const resolved: LayoutPreset = {+ ...builtInPreset,+ ...metadata,+ defaultRoute,+ snapshot: override ?? builtInPreset.snapshot,+ };++ // A renamed preset is shown by the name the account gave it, in every language.+ if (metadata?.label !== undefined) {+ delete resolved.labelKey;+ }++ return resolved;};/** Built-in presets always exist; a custom one exists while the account still has it. */diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.tsindex 27fd65b92e..6602bd9eca 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { builtInLayoutPresetDescriptors, layoutPresets } from './layoutPresets';+import { builtInLayoutPresetDescriptors, getLayoutPresetLabel, layoutPresets } from './layoutPresets';describe('built-in layout preset descriptors', () => {it('has a widget instance for every instance id a preset places', () => {@@ -53,13 +53,25 @@ describe('built-in layout preset descriptors', () => {defaultRoute: { destination: 'gallery', sourceId: 'workflow' },hotkeyId: 'selectAutomatePreset',iconId: 'workflow',- label: 'Automate',+ label: 'Workflow',presetId: 'automate',},]);expect(layoutPresets).toEqual(builtInLayoutPresetDescriptors.map(({ preset }) => preset));});+ it('names each built-in preset through the locale, Automate as Workflow', () => {+ const t = (key: string) => `t:${key}`;++ expect(layoutPresets.map((preset) => getLayoutPresetLabel(preset, t))).toEqual([+ 't:topbar.presets.builtInLabels.compose',+ 't:topbar.presets.builtInLabels.edit',+ 't:topbar.presets.builtInLabels.video',+ 't:topbar.presets.builtInLabels.automate',+ ]);+ expect(getLayoutPresetLabel({ label: 'My layout' }, t)).toBe('My layout');+ });+it('ships task-focused widget sets in interaction-priority order', () => {const summaries = Object.fromEntries(layoutPresets.map(({ id, snapshot }) => [diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.tsindex 483b7c92e4..5fe9ec2ef1 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts@@ -11,7 +11,7 @@ import type {} from '@workbench/layoutContracts';import type { WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';-import { BUILT_IN_LAYOUT_PRESET_LABELS } from '@workbench/launchpad/intents';+import { BUILT_IN_LAYOUT_PRESET_LABEL_KEYS, BUILT_IN_LAYOUT_PRESET_LABELS } from '@workbench/launchpad/intents';// Notifications read as ambient status, not a tool: they live on the right.const defaultBottomAlignEndInstanceIds: WidgetInstanceId[] = ['shortcuts', 'notifications'];@@ -146,6 +146,7 @@ const createPresetDescriptor = ({id,isBuiltIn: true,label,+ labelKey: BUILT_IN_LAYOUT_PRESET_LABEL_KEYS[id],snapshot: createSnapshot({ centerViewId, panels, presetId: id, widgetRegions }),},});@@ -312,5 +313,11 @@ export const resolveLayoutPresetId = (presetId: string): string => legacyLayoutPexport const getLayoutPreset = (presetId: string): BuiltInLayoutPreset =>layoutPresets.find((preset) => preset.id === resolveLayoutPresetId(presetId)) ?? defaultLayoutPreset;+/** What a preset is called in the UI: a built-in one the account has not renamed in the current language. */+export const getLayoutPresetLabel = (+ preset: Pick<LayoutPreset, 'label' | 'labelKey'>,+ t: (key: string) => string+): string => (preset.labelKey ? t(preset.labelKey) : preset.label);+export const isBuiltInLayoutPresetId = (presetId: string): presetId is BuiltInLayoutPresetId =>layoutPresets.some((preset) => preset.id === presetId);diff --git a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsxindex ba65348228..004d6c08d0 100644--- a/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx+++ b/invokeai/frontend/webv2/src/workbench/palette/LaunchpadCommandPalette.tsx@@ -1,7 +1,7 @@import { useExitPresence } from '@platform/react/useExitRetainedValue';import { useMountEffect } from '@platform/react/useMountEffect';import { OPEN_COMMAND_PALETTE_HOTKEY } from '@workbench/hotkeys/catalog';-import { MOD_KEY_LABEL, toTinykeysBinding } from '@workbench/hotkeys/keys';+import { acceptsHotkeyPress, MOD_KEY_LABEL, toTinykeysBinding } from '@workbench/hotkeys/keys';import { applyCustomHotkeys } from '@workbench/hotkeys/resolve';import { useWorkbenchPreferences, useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { lazy, Suspense } from 'react';@@ -18,11 +18,19 @@ const LaunchpadCommandPaletteHotkeys = ({ keys }: { keys: readonly string[] }) =return;}- const onHotkey = (event: KeyboardEvent): void => {- event.preventDefault();- toggleCommandPalette();- };- const bindings = Object.fromEntries(keys.map((key) => [toTinykeysBinding(key), onHotkey]));+ const bindings = Object.fromEntries(+ keys.map((key) => [+ toTinykeysBinding(key),+ (event: KeyboardEvent): void => {+ // The same checks as the editor's hotkey runtime, so a binding fires alike on both routes.+ if (!acceptsHotkeyPress(event, key)) {+ return;+ }+ event.preventDefault();+ toggleCommandPalette();+ },+ ])+ );return tinykeys(window, bindings, { ignore: () => false });});diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.test.tsindex aad3d8dad9..46d57234f9 100644--- a/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.test.ts@@ -28,6 +28,7 @@ const translations: Record<string, string> = {'commandPalette.actions.openInSettings': 'Open in Settings','commandPalette.groups.app': 'App','commandPalette.groups.canvas': 'Canvas',+ 'topbar.invoke.invokeFront': 'Invoke (front of queue)','commandPalette.groups.generation': 'Generation','commandPalette.groups.navigation': 'Navigation','commandPalette.groups.settings': 'Settings',@@ -86,6 +87,12 @@ describe('buildCatalogCommandEntries', () => {expect(generateTab).toMatchObject({ group: 'Navigation', showInEmptyState: true, title: 'Go to Generate' });});+ it('titles front-of-queue invoke from the topbar catalog', () => {+ const invokeFront = build(new Set()).find((entry) => entry.id === 'app.invokeFront');++ expect(invokeFront).toMatchObject({ group: 'Generation', title: 'Invoke (front of queue)' });+ });+it('uses account-renamed layout preset titles in palette rows', () => {const initial = createInitialWorkbenchState();const account = {diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.tsindex bc3007d399..ef37111b92 100644--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts@@ -211,8 +211,12 @@ const APP_COMMAND_GROUPS: Record<string, string> = {'app.toggleRightPanel': 'Layout',};+/** Titles the app already words in its own catalog, so the palette reads like the control it runs. */+const TITLE_KEYS: Record<string, string> = {+ 'app.invokeFront': 'topbar.invoke.invokeFront',+};+const TITLE_OVERRIDES: Record<string, string> = {- 'app.invokeFront': 'Invoke (Front of Queue)','app.promptHistoryNext': 'Next Prompt from History','app.promptHistoryPrev': 'Previous Prompt from History','app.selectCanvasTab': 'Go to Canvas',@@ -288,6 +292,7 @@ export const buildCatalogCommandEntries = ({showInEmptyState: rawGroup === 'Navigation',title:titleOverrides?.[definition.commandId] ??+ (TITLE_KEYS[definition.commandId] ? t(TITLE_KEYS[definition.commandId]!) : undefined) ??t(`commandPalette.commands.${definition.commandId.replace('.', '_')}`, {defaultValue: TITLE_OVERRIDES[definition.commandId] ?? definition.title,}),diff --git a/invokeai/frontend/webv2/src/workbench/panZoom.test.ts b/invokeai/frontend/webv2/src/workbench/panZoom.test.tsindex dbc7b16783..3708958c42 100644--- a/invokeai/frontend/webv2/src/workbench/panZoom.test.ts+++ b/invokeai/frontend/webv2/src/workbench/panZoom.test.ts@@ -1,6 +1,14 @@import { describe, expect, it } from 'vitest';-import { panBy, pinchZoomAtPoints, wheelZoomAtPoint, zoomAtPoint } from './panZoom';+import {+ panBy,+ pinchZoomAtPoints,+ snapWheelZoom,+ WHEEL_ZOOM_SNAP_IDLE_MS,+ WHEEL_ZOOM_SNAP_POINTS,+ zoomAtPoint,+ type WheelZoomSnap,+} from './panZoom';const clamp = (min: number, max: number) => (zoom: number) => Math.max(min, Math.min(max, zoom));@@ -28,21 +36,6 @@ describe('panZoom', () => {expect(next).toBe(atMaximum);});- it('applies wheel sensitivity through the constrained transition', () => {- const next = wheelZoomAtPoint(- { pan: { x: 0, y: 0 }, zoom: 1 },- -1,- { x: 100, y: 50 },- {- constrainZoom: clamp(0.1, 20),- }- );-- // A one-unit wheel delta is a small continuous step, not a jump to a preset.- expect(next.zoom).toBeGreaterThan(1);- expect(next.zoom).toBeLessThan(1.01);- });-it('pans in screen space without changing zoom', () => {expect(panBy({ pan: { x: 5, y: 5 }, zoom: 2 }, { x: 10, y: -4 })).toEqual({pan: { x: 15, y: 1 },@@ -90,3 +83,75 @@ describe('panZoom', () => {).toBe(start);});});++describe('snapWheelZoom', () => {+ const options = { constrainZoom: clamp(0.1, 20), now: 0 };+ /** Wheel steps from `zoom`, each fed the previous result, as consecutive wheel events 16 ms apart are. */+ const wheel = (zoom: number, deltas: number[], snap: WheelZoomSnap | null = null, start = 0): WheelZoomSnap[] => {+ const steps: WheelZoomSnap[] = [];+ let state = snap;+ let current = zoom;+ for (const [index, deltaY] of deltas.entries()) {+ state = snapWheelZoom(state, current, deltaY, { ...options, now: start + index * 16 });+ current = state.zoom;+ steps.push(state);+ }+ return steps;+ };++ it('rests on 100% when a notch lands within tolerance of it, from below and from above', () => {+ // One mouse notch is a factor of about 1.16: 87% → 101.1% and 117% → 100.7%.+ expect(wheel(0.87, [-100])[0]!.zoom).toBe(1);+ expect(wheel(1.17, [100])[0]!.zoom).toBe(1);+ });++ it('stays on the snap point across small deltas until the intended zoom leaves its tolerance', () => {+ // Each trackpad step asks for about 0.75% more.+ const steps = wheel(1, [-5, -5, -5]);++ expect(steps.map((step) => step.zoom).slice(0, 2)).toEqual([1, 1]);+ // The third step takes the intended zoom past 102%, and zoom continues from there rather than from 100%.+ expect(steps[2]!.activeSnapPoint).toBeNull();+ expect(steps[2]!.zoom).toBeCloseTo(Math.exp(0.0015 * 15), 9);+ });++ it('lets a pause release the wheel movement left over inside a snap point', () => {+ // Two steps ask for about 101.5% while resting on 100%.+ const resting = wheel(1, [-5, -5]).at(-1)!;+ expect(resting).toMatchObject({ activeSnapPoint: 1, zoom: 1 });++ // Without a pause, one more step crosses 102% and leaves the snap point...+ expect(wheel(1, [-5], resting, resting.at + 16)[0]!.activeSnapPoint).toBeNull();+ // ...after a pause, the gesture starts again from the 100% shown, and the same step stays on it.+ expect(wheel(1, [-5], resting, resting.at + WHEEL_ZOOM_SNAP_IDLE_MS + 1)[0]).toMatchObject({+ activeSnapPoint: 1,+ zoom: 1,+ });+ });++ it('rests on every snap point', () => {+ for (const point of WHEEL_ZOOM_SNAP_POINTS) {+ expect(wheel(point * 0.99, [-1])[0]).toMatchObject({ activeSnapPoint: point, zoom: point });+ }+ });++ it('passes a snap point that a single step jumps over', () => {+ expect(wheel(0.9, [-150])[0]!.zoom).toBeCloseTo(0.9 * Math.exp(0.225), 9);+ });++ it('starts afresh when another change moved the zoom since the last step', () => {+ const [snapped] = wheel(1, [-1]);++ // Resting on 100%, then a preset set 130%: the next step starts from 130%, not from the remembered 100%.+ const next = snapWheelZoom(snapped!, 1.3, -1, { ...options, now: 16 });++ expect(next.activeSnapPoint).toBeNull();+ expect(next.zoom).toBeCloseTo(1.3 * Math.exp(0.0015), 9);+ });++ it('never rests on a snap point outside the zoom limits', () => {+ const next = snapWheelZoom(null, 0.26, 10, { constrainZoom: clamp(0.26, 20), now: 0 });++ expect(next.zoom).toBe(0.26);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/panZoom.ts b/invokeai/frontend/webv2/src/workbench/panZoom.tsindex 3aa9b6bb72..bf569dc3c8 100644--- a/invokeai/frontend/webv2/src/workbench/panZoom.ts+++ b/invokeai/frontend/webv2/src/workbench/panZoom.ts@@ -54,16 +54,68 @@ export const zoomAtPoint = (};};-/** Applies exponential wheel zoom around `screenAnchor`. */-export const wheelZoomAtPoint = (- transform: PanZoomTransform,+/** Zoom levels wheel zoom rests on (1 = 100%), as the v6 canvas did. */+export const WHEEL_ZOOM_SNAP_POINTS: readonly number[] = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 5];++/** How near a snap point, as a fraction of it, wheel zoom must come to rest on it, and how far to leave it. */+export const WHEEL_ZOOM_SNAP_TOLERANCE = 0.02;++/**+ * A pause in wheel events longer than this ends a wheel gesture: the next event starts from the zoom shown, so wheel+ * movement left over inside a snap point's tolerance never carries into a later gesture (v6's snap timeout).+ */+export const WHEEL_ZOOM_SNAP_IDLE_MS = 300;++/**+ * Wheel zoom's memory between events. The zoom the wheel asks for (`intendedZoom`) is tracked apart from the zoom+ * shown, so a resting snap point holds until the accumulated wheel movement leaves its tolerance, then zoom continues+ * from where the wheel would have been. Any other zoom change (fit, preset, hotkey, pinch) discards it.+ */+export interface WheelZoomSnap {+ /** The snap point the zoom rests on, or null. */+ activeSnapPoint: number | null;+ intendedZoom: number;+ /** The zoom this state produced; a current zoom that differs means another change intervened. */+ zoom: number;+ /** When the wheel event that produced it arrived, in the caller's clock (milliseconds). */+ at: number;+}++/** Relative difference within which two zooms are the same one, such as a zoom converted through a fit ratio and back. */+const SAME_ZOOM_EPSILON = 1e-9;++/**+ * One exponential wheel step (`zoom *= exp(-deltaY * step)`) with sticky snapping: resting on a snap point once the+ * intended zoom comes within tolerance of it, until the intended zoom leaves that tolerance. Pass the previous+ * result's `snap`, or null to start from `currentZoom`, and the event's time as `now`. After a pause longer than+ * {@link WHEEL_ZOOM_SNAP_IDLE_MS} the intended zoom starts again from `currentZoom`, still resting on its snap point.+ * Zoom values are actual zoom (1 = 100%).+ */+export const snapWheelZoom = (+ snap: WheelZoomSnap | null,+ currentZoom: number,deltaY: number,- screenAnchor: PanZoomPoint,- { constrainZoom, step = WHEEL_ZOOM_STEP }: { constrainZoom: ConstrainZoom; step?: number }-): PanZoomTransform => {- const target = constrainZoom(transform.zoom * Math.exp(-deltaY * step));+ { constrainZoom, now, step = WHEEL_ZOOM_STEP }: { constrainZoom: ConstrainZoom; now: number; step?: number }+): WheelZoomSnap => {+ const current = snap !== null && Math.abs(snap.zoom - currentZoom) <= currentZoom * SAME_ZOOM_EPSILON ? snap : null;+ const isSameGesture = current !== null && now - current.at <= WHEEL_ZOOM_SNAP_IDLE_MS;+ const fromZoom = isSameGesture ? current.intendedZoom : currentZoom;+ const intendedZoom = constrainZoom(fromZoom * Math.exp(-deltaY * step));+ const active = current?.activeSnapPoint ?? null;++ if (active !== null && Math.abs(intendedZoom - active) <= active * WHEEL_ZOOM_SNAP_TOLERANCE) {+ return { activeSnapPoint: active, at: now, intendedZoom, zoom: active };+ }++ const snapPoint = WHEEL_ZOOM_SNAP_POINTS.find(+ (point) =>+ Math.abs(constrainZoom(point) - point) <= point * SAME_ZOOM_EPSILON &&+ Math.abs(intendedZoom - point) < point * WHEEL_ZOOM_SNAP_TOLERANCE+ );- return zoomAtPoint(transform, target, screenAnchor, constrainZoom);+ return snapPoint === undefined+ ? { activeSnapPoint: null, at: now, intendedZoom, zoom: intendedZoom }+ : { activeSnapPoint: snapPoint, at: now, intendedZoom, zoom: snapPoint };};/** Pans by a screen-space delta. */diff --git a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.tsindex ab6951db68..4cde7b365d 100644--- a/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/durableSyncedPersistence.test.ts@@ -4060,7 +4060,12 @@ describe('recovering a project whose halves were acknowledged apart', () => {updatedAt: Date.parse(now),writerToken: 'old-writer',});- const elsewhere = { ...project, promptHistory: [{ negativePrompt: null, positivePrompt: 'from another tab' }] };+ // Another tab saved its workspace, Auto-switch included: project settings travel only with the workspace half.+ const elsewhere = {+ ...project,+ promptHistory: [{ negativePrompt: null, positivePrompt: 'from another tab' }],+ settings: { ...project.settings, viewerAutoSwitch: 'latest' as const },+ };api.records.set(project.id, toSplitRecord(elsewhere, 1, 2));const { conflicts, service } = await openWith(api, project.id, draftStore);expect(conflicts).toMatchObject([{ half: 'workspace' }]);@@ -4073,6 +4078,7 @@ describe('recovering a project whose halves were acknowledged apart', () => {await service.saveWorkbench(stateWith([resolved.project]));expect(resolved.project).toMatchObject({ name: 'Edited here', promptHistory: elsewhere.promptHistory });+ expect(resolved.project.settings.viewerAutoSwitch).toBe('latest');expect(api.records.get(project.id)).toMatchObject({ name: 'Edited here', revision: 2, workspace: { revision: 2 } });});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex 861d0095e0..ded7b9e26e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -728,6 +728,60 @@ describe('importProjectFile', () => {expect(createRequest.data.id).toBe(createRequest.project_id);});+ describe('Auto-switch of an imported project', () => {+ /** A project as a build before Auto-switch saved it: the old progress toggle, no mode. */+ const legacySettingsProject = () => {+ const project = createDraftProject([]);+ const { viewerAutoSwitch: _mode, ...settings } = project.settings;++ return {+ ...project,+ settings: { ...settings, showProgressImagesInViewer: false } as unknown as typeof project.settings,+ };+ };++ it('starts an archive from before the mode on In progress, as a new project', async () => {+ acceptCreate();+ await projectFile.exportOpenProject(legacySettingsProject());++ await projectFile.importProjectFile(capturedArchive());++ expect(createdWorkspace()).toMatchObject({ settings: { viewerAutoSwitch: 'progress' } });+ });++ it('keeps the mode an archive carries', async () => {+ const project = createDraftProject([]);+ acceptCreate();+ await projectFile.exportOpenProject({+ ...project,+ settings: { ...project.settings, viewerAutoSwitch: 'latest' },+ });++ await projectFile.importProjectFile(capturedArchive());++ expect(createdWorkspace()).toMatchObject({ settings: { viewerAutoSwitch: 'latest' } });+ });++ it('starts a whole-document file on In progress', async () => {+ acceptCreate();+ const file = new File(+ [+ JSON.stringify({+ document: persistence.serializeProjectDocument(legacySettingsProject()),+ kind: 'invokeai-project',+ version: 1,+ }),+ ],+ 'legacy.invokeproject.json',+ { type: 'application/json' }+ );++ await projectFile.importProjectFile(file);++ expect(createdWorkspace()).toMatchObject({ settings: { viewerAutoSwitch: 'progress' } });+ });+ });+/** Strip installation state on import too; skipped references cannot be remapped or reported. */it('strips a stranger’s gallery selection from a document it did not write', async () => {acceptCreate();diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.tsindex 399053698a..5b987786e7 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.ts@@ -9,6 +9,7 @@ import {isAccountScopeCurrent,} from '@platform/state/accountLifecycle';import { getProjectCanvasSchemaRequirement } from '@workbench/canvasSchemaVersion';+import { isViewerAutoSwitchMode } from '@workbench/settings/store';import type { ProjectTransferIssues } from './invk/transfer';import type { ProjectDocumentV3 } from './projectDocument';@@ -265,6 +266,16 @@ export const exportOpenProject = async ();};+/**+ * An imported project is new to this library, so it starts on a new project's Auto-switch (In progress) unless the+ * file names a mode of its own; a file from before the mode existed would otherwise read as a stored project's Off.+ */+const withImportedViewerAutoSwitch = (settings: unknown): Record<string, unknown> => {+ const record = settings !== null && typeof settings === 'object' ? (settings as Record<string, unknown>) : {};++ return isViewerAutoSwitchMode(record.viewerAutoSwitch) ? record : { ...record, viewerAutoSwitch: 'progress' };+};+/*** Project creation commits remapped/staged media. Every import stages an inbox board first, an empty one for a file* without board entries, so the create claims it and carries the importer's workspace, open on it, in one request.@@ -296,7 +307,8 @@ export const importProjectFile = async (? projectDocument.name.trim(): 'Imported project';// Strip selection on import because skipped references cannot be restored or reported.- const candidate = { ...stripInstallationState(projectDocument), id, name };+ const stripped = stripInstallationState(projectDocument);+ const candidate = { ...stripped, id, name, settings: withImportedViewerAutoSwitch(stripped.settings) };// Validate through the reducer lazily to keep editor aggregates out of Launchpad imports.const { deserializeProjectDocument } = await import('./syncedPersistence');diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectHalves.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectHalves.test.tsindex deedbe09fb..1189c415f2 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectHalves.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectHalves.test.ts@@ -141,6 +141,19 @@ describe('joining a project for a member', () => {expect(loaded.workflows.activeWorkflowId).toBe(project.workflows.entries[0]!.document.id);expect(loaded.workflows.entries.some((entry) => entry.lastRun)).toBe(false);expect(loaded.name).toBe(project.name);+ // A member's first open is a new workspace: Auto-switch starts In progress, not a stored project's Off.+ expect(loaded.settings.viewerAutoSwitch).toBe('progress');+ });++ it('keeps the Auto-switch mode a workspace saved, across a split and a join', () => {+ const project = workedOnProject();+ const { content, workspace } = splitProjectDocument(+ serializeProjectDocumentV3({ ...project, settings: { ...project.settings, viewerAutoSwitch: 'latest' } })+ );++ const joined = join({ content, workspace });++ expect(load((joined as { document: Record<string, unknown> }).document).settings.viewerAutoSwitch).toBe('latest');});it('falls back to the first workflow when the open one was deleted meanwhile', () => {diff --git a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsxindex 255ea0d991..2d9ea998fd 100644--- a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx@@ -80,4 +80,12 @@ describe('HotkeysSettingsSection conflicts', () => {await expect.element(conflictText('Recall Seed')).not.toBeInTheDocument();await expect.element(page.getByText(/^Conflicts with /)).not.toBeInTheDocument();});++ it('lists Clear Canvas on its own default shortcut, which meets no other default', async () => {+ await render();++ await act(() => search().fill('clear canvas'));+ await expect.element(page.getByText('Clear Canvas', { exact: true })).toBeVisible();+ await expect.element(page.getByText(/^Conflicts with /)).not.toBeInTheDocument();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsxindex 7a50c542a6..e128aac2d6 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx@@ -37,7 +37,7 @@ vi.mock('./CustomSettingsEditors', () => ({const testProject = {id: 'settings-test-project',- settings: { antialiasProgressImages: true, showProgressImagesInViewer: true, useCpuNoise: false },+ settings: { antialiasProgressImages: true, useCpuNoise: false },widgetInstances: { 'settings-test-widget': { id: 'settings-test-widget', typeId: 'queue' } },};diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsindex b173db5d85..f17c801f54 100644--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -20,10 +20,19 @@ export interface ProjectSettings {/** Stamp an invisible watermark into every saved image. */useWatermark: boolean;antialiasProgressImages: boolean;- /** Preview owns this live toggle; persist it per project rather than exposing it in Settings. */- showProgressImagesInViewer: boolean;+ /**+ * What the Preview switches to while work runs; the Preview owns this control, so it is not in Settings. Projects+ * saved before it existed read as `off`, so an upgrade never starts moving a selection the user had settled on.+ */+ viewerAutoSwitch: ViewerAutoSwitchMode;}+/**+ * `latest`: each finished result takes the selection. `progress`: the same, and live frames show while it runs.+ * `off`: results land in the Gallery only (one still takes an empty selection). The canvas staging bar's values.+ */+export type ViewerAutoSwitchMode = 'off' | 'latest' | 'progress';+/*** Store the RebalancePreset shape locally to keep generation out of Launchpad's bundle. Generation owns and* revalidates weights on read.diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex b04734654e..a52fae11db 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -340,13 +340,29 @@ describe('clearWorkbenchSettings', () => {});describe('normalizeProjectSettings', () => {- it('defaults progress-image behavior for older project payloads', () => {- expect(store.normalizeProjectSettings({}).showProgressImagesInViewer).toBe(true);- expect(store.normalizeProjectSettings({ showProgressImagesInViewer: false }).showProgressImagesInViewer).toBe(- false+ it('starts a project saved before Auto-switch Off, whatever its old progress toggle said', () => {+ type Legacy = Parameters<typeof store.normalizeProjectSettings>[0] & { showProgressImagesInViewer?: boolean };+ const legacy = (settings: Legacy) => store.normalizeProjectSettings(settings);++ expect(legacy({}).viewerAutoSwitch).toBe('off');+ expect(legacy({ showProgressImagesInViewer: true }).viewerAutoSwitch).toBe('off');+ expect(legacy({ showProgressImagesInViewer: false }).viewerAutoSwitch).toBe('off');+ expect(legacy({ showProgressImagesInViewer: true })).not.toHaveProperty('showProgressImagesInViewer');+ });++ it('keeps a saved Auto-switch mode and reads anything else as Off', () => {+ for (const mode of ['off', 'latest', 'progress'] as const) {+ expect(store.normalizeProjectSettings({ viewerAutoSwitch: mode }).viewerAutoSwitch).toBe(mode);+ }+ expect(store.normalizeProjectSettings({ viewerAutoSwitch: 'always' as unknown as 'off' }).viewerAutoSwitch).toBe(+ 'off');});+ it('starts new projects on In progress', () => {+ expect(store.normalizeProjectSettings(store.DEFAULT_PROJECT_SETTINGS).viewerAutoSwitch).toBe('progress');+ });+it('defaults the output filters off for projects saved before them', () => {expect(store.normalizeProjectSettings({})).toMatchObject({ useNsfwChecker: false, useWatermark: false });expect(store.normalizeProjectSettings({ useNsfwChecker: true, useWatermark: true })).toMatchObject({diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex 7bf67bbeda..28b1b2093e 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -5,6 +5,7 @@ import type {ProjectsViewId,StoredGeneratePreset,StoredRebalancePreset,+ ViewerAutoSwitchMode,WorkbenchPreferences,} from '@workbench/settings/contracts';@@ -37,10 +38,11 @@ export const DEVELOPER_LOG_NAMESPACES: readonly LogNamespace[] = LOG_NAMESPACES;export const DEFAULT_PROJECT_SETTINGS: ProjectSettings = {antialiasProgressImages: false,- showProgressImagesInViewer: true,useCpuNoise: true,useNsfwChecker: false,useWatermark: false,+ // New projects; a stored project without the field reads as `off` (see normalizeProjectSettings).+ viewerAutoSwitch: 'progress',};export const DEFAULT_PREFERENCES: WorkbenchPreferences = {@@ -256,20 +258,21 @@ const normalizeGeneratePresets = (values: unknown): StoredGeneratePreset[] => {return presets;};+export const isViewerAutoSwitchMode = (value: unknown): value is ViewerAutoSwitchMode =>+ value === 'off' || value === 'latest' || value === 'progress';+export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): ProjectSettings => ({antialiasProgressImages:typeof settings?.antialiasProgressImages === 'boolean'? settings.antialiasProgressImages: DEFAULT_PROJECT_SETTINGS.antialiasProgressImages,- showProgressImagesInViewer:- typeof settings?.showProgressImagesInViewer === 'boolean'- ? settings.showProgressImagesInViewer- : DEFAULT_PROJECT_SETTINGS.showProgressImagesInViewer,useCpuNoise: typeof settings?.useCpuNoise === 'boolean' ? settings.useCpuNoise : DEFAULT_PROJECT_SETTINGS.useCpuNoise,useNsfwChecker:typeof settings?.useNsfwChecker === 'boolean' ? settings.useNsfwChecker : DEFAULT_PROJECT_SETTINGS.useNsfwChecker,useWatermark:typeof settings?.useWatermark === 'boolean' ? settings.useWatermark : DEFAULT_PROJECT_SETTINGS.useWatermark,+ // Absent means a project saved before the mode existed, whatever its old progress toggle said: it starts `off`.+ viewerAutoSwitch: isViewerAutoSwitchMode(settings?.viewerAutoSwitch) ? settings.viewerAutoSwitch : 'off',});type WorkbenchPreferencesInput = Omit<diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsxindex c5a4461375..abaa3d74b6 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx@@ -5,7 +5,7 @@ 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 { page, userEvent } from 'vitest/browser';import type { InvocationState } from './useInvocationState';import type * as UseTopbarShortcutModule from './useTopbarShortcut';@@ -13,6 +13,7 @@ import type * as UseTopbarShortcutModule from './useTopbarShortcut';// Verify progress returns after hover ends unless focus-visible remains; mouse click-focus must not pin the play// icon. Mock queue plumbing to isolate that gate.const harness = vi.hoisted(() => ({+ bindings: {} as Record<string, { aria: string; display: string; parts: string[] }>,progress: { activeItemIndex: 1, completedItemCount: 0, message: '', percentage: 0.42 as number | null },summary: { current: 1, remaining: 1, runningQueueItemId: 'item-1', total: 1 },}));@@ -23,9 +24,13 @@ vi.mock('@workbench/queue-integration/useActiveQueueProgress', () => ({vi.mock('@workbench/invocation', () => ({ getDestinationLabel: () => 'Gallery' }));vi.mock('./useTopbarShortcut', async (importOriginal) => ({...(await importOriginal<typeof UseTopbarShortcutModule>()),- useTopbarShortcutBinding: () => null,+ useTopbarShortcutBinding: (commandId: string) => harness.bindings[commandId] ?? null,+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { shortcut?: string }) => (options?.shortcut ? `${key}: ${options.shortcut}` : key),+ }),}));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));import { InvokeButton } from './InvokeButton';@@ -76,6 +81,7 @@ const hasProgressRing = (button: HTMLButtonElement): boolean => button.querySeleconst hasSpinner = (button: HTMLButtonElement): boolean => button.querySelector('.chakra-spinner') !== null;beforeEach(() => {+ harness.bindings = {};harness.progress.percentage = 0.42;harness.summary.total = 1;harness.summary.runningQueueItemId = 'item-1';@@ -142,3 +148,56 @@ describe('InvokeButton icon slot', () => {expect(invoke).not.toHaveBeenCalled();});});++describe('InvokeButton front of queue', () => {+ const frontBinding = { aria: 'Control+Shift+Enter', display: 'Ctrl+Shift+Enter', parts: ['ctrl', 'shift', 'enter'] };++ it('queues at the front on Shift+click and normally on a plain click', async () => {+ const invoke = vi.fn(() => Promise.resolve());+ const { button } = await renderInvokeButton({ invoke });++ await act(() => userEvent.click(button));+ await userEvent.keyboard('{Shift>}');+ await act(() => userEvent.click(button));+ await userEvent.keyboard('{/Shift}');++ expect(invoke).toHaveBeenNthCalledWith(1, undefined);+ expect(invoke).toHaveBeenNthCalledWith(2, { prepend: true });+ });++ it('ignores both clicks while Invoke is blocked', async () => {+ const invoke = vi.fn(() => Promise.resolve());+ const { button } = await renderInvokeButton({+ blockingReasons: ['The backend is disconnected.'],+ invoke,+ isValid: false,+ });++ // Dispatched: a blocked Invoke is not actionable for a pointer driver.+ await act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })));+ await act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true, shiftKey: true })));++ expect(invoke).not.toHaveBeenCalled();+ });++ it('names the live front-of-queue binding and Shift+click, and lists both bindings as shortcuts', async () => {+ harness.bindings = {+ 'app.invoke': { aria: 'Control+Enter', display: 'Ctrl+Enter', parts: ['ctrl', 'enter'] },+ 'app.invokeFront': frontBinding,+ };+ const { button } = await renderInvokeButton();++ expect(button.getAttribute('aria-keyshortcuts')).toBe('Control+Enter Control+Shift+Enter');+ await act(() => userEvent.hover(button));++ await expect.element(page.getByText('topbar.invoke.invokeFrontHint: Ctrl+Shift+Enter')).toBeVisible();+ });++ it('names only Shift+click when the front-of-queue binding is cleared', async () => {+ const { button } = await renderInvokeButton();++ await act(() => userEvent.hover(button));++ await expect.element(page.getByText('topbar.invoke.invokeFrontHintNoShortcut')).toBeVisible();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsxindex 0534d227ad..b69721a6a9 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx@@ -1,4 +1,4 @@-import type { FocusEvent } from 'react';+import type { FocusEvent, MouseEvent } from 'react';import { Box, HStack, Icon, Kbd, ProgressCircle, Separator, Spinner, Stack, Text } from '@chakra-ui/react';import { getDeterminateProgressFraction } from '@features/queue/contracts';@@ -46,10 +46,14 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {const { t } = useTranslation();const { blockingReasons, invoke, isPreparing, isValid } = state;const shortcutBinding = useTopbarShortcutBinding('app.invoke');+ const frontBinding = useTopbarShortcutBinding('app.invokeFront');const shortcutParts = shortcutBinding?.parts ?? null;+ const frontShortcut = frontBinding?.display ?? null;+ const ariaKeyShortcuts =+ [shortcutBinding?.aria, frontBinding?.aria].filter((value) => value !== undefined).join(' ') || undefined;const tooltipContent = useMemo(- () => <InvokeTooltipContent shortcutParts={shortcutParts} state={state} />,- [shortcutParts, state]+ () => <InvokeTooltipContent frontShortcut={frontShortcut} shortcutParts={shortcutParts} state={state} />,+ [frontShortcut, shortcutParts, state]);const { progress: runningProgress, summary } = useActiveQueueProgress();@@ -66,7 +70,11 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {}}, []);const handleBlur = useCallback(() => setIsFocused(false), []);- const handleClick = useCallback(() => void invoke(), [invoke]);+ // Shift+click is the pointer path to the front of the queue, beside the app.invokeFront shortcut.+ const handleClick = useCallback(+ (event: MouseEvent<HTMLButtonElement>) => void invoke(event.shiftKey ? { prepend: true } : undefined),+ [invoke]+ );const canInvoke = isValid && !isPreparing;const iconMode = isPreparing@@ -81,7 +89,7 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {<Tooltip content={tooltipContent} contentProps={TOOLTIP_CONTENT_PROPS} openDelay={200} showArrow><Buttonaria-disabled={!canInvoke}- aria-keyshortcuts={shortcutBinding?.aria}+ aria-keyshortcuts={ariaKeyShortcuts}aria-label={canInvoke? t('topbar.invoke.invoke')@@ -130,7 +138,15 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {);};-const InvokeTooltipContent = ({ shortcutParts, state }: { shortcutParts: string[] | null; state: InvocationState }) => {+const InvokeTooltipContent = ({+ frontShortcut,+ shortcutParts,+ state,+}: {+ frontShortcut: string | null;+ shortcutParts: string[] | null;+ state: InvocationState;+}) => {const { t } = useTranslation();const { batchCount, blockingReasons, invocation, isPreparing, isValid, promptExpansion, workflowBatchSize } = state;const destination = getDestinationLabel(invocation.destination);@@ -188,6 +204,11 @@ const InvokeTooltipContent = ({ shortcutParts, state }: { shortcutParts: string[{t('topbar.invoke.addingImagesTo', { destination })}</Text>)}+ <Text color="fg.subtle" fontSize="sm">+ {frontShortcut === null+ ? t('topbar.invoke.invokeFrontHintNoShortcut')+ : t('topbar.invoke.invokeFrontHint', { shortcut: frontShortcut })}+ </Text></Stack>);};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsxindex e1f71d4b8f..92e796df00 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx@@ -3,7 +3,7 @@ import type { LayoutPreset } from '@workbench/layoutContracts';import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';import { ConfirmDialog } from '@platform/ui/ConfirmDialog';import { getLayoutPresetSourceOptions } from '@workbench/layoutPresetRouting';-import { layoutPresets } from '@workbench/layoutPresets';+import { getLayoutPresetLabel, layoutPresets } from '@workbench/layoutPresets';import { resolveSavedLayoutPreset } from '@workbench/layoutPresetSnapshots';import { useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';@@ -40,12 +40,14 @@ export const LayoutPresetAdminDialogs = () => {const submitEdit = useCallback(({ defaultRoute, iconId, name }: LayoutPresetDialogValue) => {if (editTarget) {+ const shipped = layoutPresets.find((preset) => preset.id === editTarget.id);+layout.setPresetRoute(editTarget.id, defaultRoute);- layout.renamePreset(editTarget.id, name);+ layout.renamePreset(editTarget.id, name, shipped ? getLayoutPresetLabel(shipped, t) : undefined);layout.setPresetIcon(editTarget.id, iconId);}},- [editTarget, layout]+ [editTarget, layout, t]);const confirmDelete = useCallback(() => {if (deleteTarget) {@@ -61,7 +63,7 @@ export const LayoutPresetAdminDialogs = () => {defaultRoute={editTarget.defaultRoute}iconId={editTarget.iconId}isOpen={editDialog.isOpen}- name={editTarget.label}+ name={getLayoutPresetLabel(editTarget, t)}sourceOptions={sourceOptions}submitLabel={t('topbar.presets.save')}title={t('topbar.presets.edit')}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.browser.test.tsxindex bce4886386..c0b8d940f1 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetDialog.browser.test.tsx@@ -54,7 +54,7 @@ describe('LayoutPresetDialog', () => {defaultRoute={BUILT_IN_DEFAULT_ROUTE}iconId="workflow"isOpen- name="Automate"+ name="Workflow"sourceOptions={BUILT_IN_SOURCE_OPTIONS}submitLabel="Save preset"title="Edit layout preset"diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsxindex 8b8b7d5054..2d175387ac 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx@@ -16,6 +16,7 @@ import { Dialog } from '@platform/ui/Dialog';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { Tooltip } from '@platform/ui/Tooltip';import { getOrderedLayoutPresets } from '@workbench/layoutPresetCollection';+import { getLayoutPresetLabel } from '@workbench/layoutPresets';import { useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';import { GripVerticalIcon, PencilIcon, RotateCcwIcon, Trash2Icon } from 'lucide-react';import { useCallback, useMemo } from 'react';@@ -44,7 +45,11 @@ export const LayoutPresetManagerDialogBody = ({const { t } = useTranslation();const { layout } = useWorkbenchCommands();const account = useWorkbenchSelector((snapshot) => snapshot.account);- const presets = useMemo(() => getOrderedLayoutPresets(account), [account]);+ // Labels as shown: a built-in preset not renamed by the account reads in the current language.+ const presets = useMemo(+ () => getOrderedLayoutPresets(account).map((preset) => ({ ...preset, label: getLayoutPresetLabel(preset, t) })),+ [account, t]+ );const presetIds = useMemo(() => presets.map(({ id }) => id), [presets]);const overriddenPresetIds = useMemo(() =>diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsxindex e9bc6040ec..b01e0bfb76 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.browser.test.tsx@@ -17,6 +17,8 @@ vi.mock('react-i18next', () => ({useTranslation: () => ({t: (key: string) =>({+ // A translated default, as another language shows the Workflow preset.+ 'topbar.presets.builtInLabels.automate': 'Arbeitsablauf','topbar.presets.layoutPreset': 'Layout preset','topbar.presets.reorderInstructions':'To reorder a layout preset, press Space. Use the Left and Right arrow keys to move it, then press Space to drop or Escape to cancel.',@@ -248,6 +250,27 @@ describe('LayoutPresetStrip', () => {expect(presetTabIds()).not.toContain('custom-1');});+ it('shows a built-in preset by its translated name and keeps it a default when saved unchanged', async () => {+ await renderStrip({ withAdminDialogs: true });++ expect(presetTab('automate')).toHaveAttribute('aria-label', 'Arbeitsablauf');++ await openPresetMenuItem('automate', 'edit-preset');+ const editDialog = document.querySelector<HTMLElement>('[role="dialog"]')!;+ expect(editDialog.querySelector<HTMLInputElement>('input[name="layout-preset-name"]')!.value).toBe('Arbeitsablauf');+ await act(() =>+ userEvent.click(+ Array.from(editDialog.querySelectorAll('button')).find(+ (button) => button.textContent === 'topbar.presets.save'+ )!+ )+ );+ await act(() => settle());++ expect(store.getSnapshot().account.layoutPresetMetadataOverrides?.automate).toBeUndefined();+ expect(presetTab('automate')).toHaveAttribute('aria-label', 'Arbeitsablauf');+ });+// Desktop tabs activate on press, including the press that begins reordering.it('selects a dragged tab on the press and reorders it in the same gesture', async () => {await renderStrip();diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsxindex f6b5a88a00..d2f7add3bc 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx@@ -30,6 +30,7 @@ import { Tooltip, TooltipGroup } from '@platform/ui/Tooltip';import { getPlacedWidgetTypeIds, graphWidgetSources } from '@workbench/graphWidgets';import { preloadLayoutPresetWidgets } from '@workbench/layoutPresetActivation';import { getOrderedLayoutPresets } from '@workbench/layoutPresetCollection';+import { getLayoutPresetLabel } from '@workbench/layoutPresets';import { findLayoutPresetWorkingCopy } from '@workbench/layoutPresetSnapshots';import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';import {@@ -90,7 +91,11 @@ export const LayoutPresetStrip = () => {const invocation = useActiveProjectSelector((project) => project.invocation);const presetWorkingLayouts = useActiveProjectSelector(selectPresetWorkingLayouts, Object.is);const sourceOptions = useActiveProjectSelector(selectPlacedGraphWidgetSources);- const presets = useMemo(() => getOrderedLayoutPresets(account), [account]);+ // Labels as shown: a built-in preset not renamed by the account reads in the current language.+ const presets = useMemo(+ () => getOrderedLayoutPresets(account).map((preset) => ({ ...preset, label: getLayoutPresetLabel(preset, t) })),+ [account, t]+ );const presetIds = useMemo(() => presets.map(({ id }) => id), [presets]);const { hasDrifted } = useLayoutDrift();const activePresetId = useActiveLayoutPresetId();diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsxindex 82b1f3168a..d0e5bdcaad 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.browser.test.tsx@@ -12,7 +12,10 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';-const harness = vi.hoisted(() => ({ project: null as unknown }));+const harness = vi.hoisted(() => ({+ project: null as unknown,+ submit: vi.fn((_args: Record<string, unknown>) => Promise.resolve()),+}));// A controllable stand-in for the node-template store, so a test can decide which of the two stores// the route depends on finishes loading last.@@ -54,7 +57,7 @@ vi.mock('@features/workflow/react', async (importOriginal) => ({getInvocationTemplatesSnapshot: () => templates.get(),subscribeInvocationTemplates: templates.subscribe,}));-vi.mock('@workbench/activeInvocationSubmission', () => ({ submitActiveInvocation: () => Promise.resolve() }));+vi.mock('@workbench/activeInvocationSubmission', () => ({ submitActiveInvocation: harness.submit }));vi.mock('@workbench/invocationPreparation', () => ({ useIsInvocationPreparing: () => false }));vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project as Project),@@ -99,9 +102,17 @@ const Probe = (): ReactNode => {const state = useInvocationState();return (- <span data-batch-count={state.batchCount} data-testid="reasons">- {state.blockingReasons.join(' | ')}- </span>+ <>+ <span data-batch-count={state.batchCount} data-testid="reasons">+ {state.blockingReasons.join(' | ')}+ </span>+ <button data-testid="invoke-front" type="button" onClick={() => void state.invoke({ prepend: true })}>+ Invoke front+ </button>+ <button data-testid="invoke" type="button" onClick={() => void state.invoke()}>+ Invoke+ </button>+ </>);};@@ -172,3 +183,16 @@ describe('useInvocationState and the workflow node templates', () => {expect(host?.querySelector('[data-testid="reasons"]')?.getAttribute('data-batch-count')).toBe('3');});});++describe('useInvocationState invoke', () => {+ it('forwards a front-of-queue request to the submission, and leaves it out otherwise', async () => {+ harness.submit.mockClear();+ await renderProbe(buildGenerateProject());++ await act(() => host!.querySelector<HTMLButtonElement>('[data-testid="invoke-front"]')!.click());+ await act(() => host!.querySelector<HTMLButtonElement>('[data-testid="invoke"]')!.click());++ expect(harness.submit.mock.calls[0]![0]).toMatchObject({ prepend: true });+ expect(harness.submit.mock.calls[1]![0].prepend).toBeUndefined();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.tsindex 08039f6d35..15f743ee10 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts@@ -99,7 +99,13 @@ export interface InvocationState {placedTypeIds: ReadonlySet<WidgetTypeId>;promptExpansion: DynamicPromptsExpansion;sourceValues: Record<string, unknown>;- invoke: (destinationOverride?: ResultDestination) => Promise<void>;+ invoke: (options?: InvokeOptions) => Promise<void>;+}++export interface InvokeOptions {+ destinationOverride?: ResultDestination;+ /** Queue ahead of the user's other pending work, as Invoke Front does. */+ prepend?: boolean;}export const useInvocationState = (): InvocationState => {@@ -163,10 +169,11 @@ export const useInvocationState = (): InvocationState => {const isValid = isInvocationRouteValid(resolvedRoute) && isConnected && expansionReason === null;const invoke = useCallback(- (destinationOverride?: ResultDestination) =>+ ({ destinationOverride, prepend }: InvokeOptions = {}) =>submitActiveInvocation({commands,destinationOverride,+ prepend,formatControlLayerError: (rejection) => describeControlLayerIssue(t, rejection),getModels: () => availabilityModels,queries,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsxnew file mode 100644index 0000000000..efa9907177--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsx@@ -0,0 +1,203 @@+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';+import type { Project } from '@workbench/projectContracts';+import type { WidgetViewProps } from '@workbench/widgetContracts';+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';+import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';++import type * as EngineStoreHooks from './engineStoreHooks';++/** The actions read the real store and drive a real engine; only the editing lock and gallery save are stubbed. */+const harness = vi.hoisted(() => ({+ editingLocked: false,+ engine: null as CanvasEngine | null,+ store: null as ReturnType<typeof createWorkbenchStore> | null,+}));+const activeProject = () => harness.store!.getState().projects[0]!;++vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useActiveProjectId: () => activeProject().id,+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(activeProject()),+ useOptionalWorkbenchCommands: () => harness.store!.commands,+ useWorkbenchCommands: () => harness.store!.commands,+}));+vi.mock('./engineStoreHooks', async (importOriginal) => ({+ ...(await importOriginal<typeof EngineStoreHooks>()),+ useCanvasDocumentEditingLocked: () => harness.editingLocked,+}));+vi.mock('@workbench/canvas-operations/react', () => ({ useCanvasEngine: () => harness.engine }));+vi.mock('./useCanvasGallerySave', () => ({+ useCanvasGallerySave: () => ({ isSaving: false, save: () => Promise.resolve() }),+}));++import { CanvasHeaderActions } from './CanvasHeaderActions';++const i18n = createInstance();+let root: Root | null = null;+let host: HTMLDivElement | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++beforeAll(async () => {+ const translation = await fetch('/locales/en.json').then((response) => response.json());+ await i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation } } });+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ harness.engine?.lifecycle.dispose();+ Object.assign(harness, { editingLocked: false, engine: null, store: null });+ root = null;+ host = null;+});++interface Registration {+ defaultKeys?: string[];+ handler?: () => void;+ id: string;+ title: string;+}++/** A painted layer, so a cleared document differs from the one it replaced. */+const paintedLayer = {+ blendMode: 'normal' as const,+ id: 'painted',+ isEnabled: true,+ isLocked: false,+ name: 'Painted',+ opacity: 1,+ source: { image: { height: 1, imageName: 'painted.png', width: 1 }, type: 'image' as const },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster' as const,+};++/**+ * Renders the actions on a fresh project, whose canvas is empty unless `withLayer`, recording the commands and+ * hotkeys they register.+ */+const renderActions = async ({ withLayer = false }: { withLayer?: boolean } = {}) => {+ const initial = createInitialWorkbenchState();+ const base = initial.projects[0]!;+ const store = createWorkbenchStore(+ withLayer+ ? {+ ...initial,+ projects: [+ {+ ...base,+ canvas: {+ ...base.canvas,+ document: { ...base.canvas.document, stacks: stacksFrom([paintedLayer]) },+ },+ },+ ],+ }+ : initial+ );+ const projectId = store.getState().activeProjectId;+ harness.store = store;+ harness.engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ ensureProjectOnServer: () => Promise.resolve(),+ imageResolver: () => Promise.resolve(new Blob()),+ mutationPort: createCanvasProjectMutationPort(store, projectId),+ projectId,+ reportError: () => undefined,+ });+ const commands: Registration[] = [];+ const hotkeys: Registration[] = [];+ const runtime = {+ commands: {+ register: (command: Registration) => {+ commands.push(command);+ return () => undefined;+ },+ },+ hotkeys: {+ register: (hotkey: Registration) => {+ hotkeys.push(hotkey);+ return () => undefined;+ },+ },+ };+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root!.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <CanvasHeaderActions {...({ runtime } as unknown as WidgetViewProps)} />+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ return { commands, hotkeys, store };+};++const clearButton = () => page.getByRole('button', { exact: true, name: 'Clear canvas' });+const confirmDialog = () => page.getByRole('alertdialog');++describe('CanvasHeaderActions clear canvas', () => {+ it('asks to clear the canvas on one click, without a menu, even when the canvas is empty', async () => {+ await renderActions();++ await clearButton().click();++ await expect.element(confirmDialog()).toBeVisible();+ await expect.element(confirmDialog().getByRole('heading', { name: 'Clear canvas' })).toBeVisible();+ await expect.element(confirmDialog().getByRole('button', { exact: true, name: 'Clear canvas' })).toBeVisible();+ await expect+ .element(confirmDialog().getByText('Clear all layers and start a fresh canvas? This cannot be undone.'))+ .toBeVisible();+ expect(document.querySelector('[role="menu"]')).toBeNull();+ });++ it('replaces the document once confirmed, layers and all', async () => {+ const { store } = await renderActions({ withLayer: true });+ const before = store.getState().projects[0]!.canvas.documentRevision;+ expect(store.getState().projects[0]!.canvas.document.stacks.raster).toHaveLength(1);++ await clearButton().click();+ await confirmDialog().getByRole('button', { exact: true, name: 'Clear canvas' }).click();++ await expect.element(confirmDialog()).not.toBeInTheDocument();+ expect(store.getState().projects[0]!.canvas.documentRevision).toBeGreaterThan(before);+ expect(store.getState().projects[0]!.canvas.document.stacks.raster).toHaveLength(0);+ });++ it('is disabled while editing is locked, and its command opens nothing then', async () => {+ harness.editingLocked = true;+ const { commands } = await renderActions();++ await expect.element(clearButton()).toBeDisabled();+ await act(() => commands.find((command) => command.id === 'canvas.newSession')!.handler!());+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();+ });++ it('registers Clear canvas on Mod+Alt+N under its saved command id, opening the same confirm', async () => {+ const { commands, hotkeys } = await renderActions();++ expect(hotkeys.find((hotkey) => hotkey.id === 'canvas.newSession')).toMatchObject({+ defaultKeys: ['mod+alt+n'],+ title: 'Clear canvas',+ });+ await act(() => commands.find((command) => command.id === 'canvas.newSession')!.handler!());++ await expect.element(confirmDialog()).toBeVisible();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsxindex 7f68f686a7..ee63b3483e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx@@ -142,10 +142,11 @@ const CanvasHeaderActionsInner = ({const entries = [['canvas.fitBboxToLayers', t('widgets.canvas.controls.fitBboxToLayers'), ['shift+n']],['canvas.fitBboxToMasks', t('widgets.canvas.controls.fitBboxToMasks'), ['shift+b']],- // No default keys — assignable through the hotkeys settings.+ // The gallery saves have no default keys; they are assignable through the hotkeys settings.['canvas.saveToGallery', t('widgets.canvas.contextMenu.saveCanvasToGallery'), []],['canvas.saveBboxToGallery', t('widgets.canvas.contextMenu.saveBboxToGallery'), []],- ['canvas.newSession', t('widgets.canvas.controls.newSession'), []],+ // Clear canvas keeps its saved-binding id, `newSession`.+ ['canvas.newSession', t('widgets.canvas.controls.clearCanvas'), ['mod+alt+n']],] as const;const disposers = entries.flatMap(([id, title, defaultKeys]) => [runtime.commands.register({ handler: () => executeHeaderCommand(id), id, title }),@@ -289,39 +290,24 @@ const CanvasHeaderActionsInner = ({</Portal></Menu.Root>- <Menu.Root positioning={MENU_POSITIONING}>- <Tooltip content={t('widgets.canvas.controls.newSession')}>- <span style={{ display: 'inline-flex' }}>- <Menu.Trigger asChild>- <IconButton- aria-label={t('widgets.canvas.controls.newSession')}- color="fg.muted"- disabled={editingLocked}- size="sm"- variant="ghost"- >- <FilePlusIcon />- </IconButton>- </Menu.Trigger>- </span>- </Tooltip>- <Portal>- <Menu.Positioner>- <MenuContent minW="11rem" py="1">- <Menu.Item value="new-canvas" onClick={openNewCanvas}>- <Icon as={FilePlusIcon} boxSize="3.5" color="fg.subtle" />- <Menu.ItemText>{t('widgets.canvas.controls.newCanvas')}</Menu.ItemText>- </Menu.Item>- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>+ <Tooltip content={t('widgets.canvas.controls.clearCanvas')}>+ <IconButton+ aria-label={t('widgets.canvas.controls.clearCanvas')}+ color="fg.muted"+ disabled={editingLocked}+ size="sm"+ variant="ghost"+ onClick={openNewCanvas}+ >+ <FilePlusIcon />+ </IconButton>+ </Tooltip><ConfirmDialogbody={t('widgets.canvas.controls.newCanvasConfirm')}- confirmLabel={t('widgets.canvas.controls.newCanvas')}+ confirmLabel={t('widgets.canvas.controls.clearCanvas')}isOpen={isNewCanvasOpen}- title={t('widgets.canvas.controls.newCanvas')}+ title={t('widgets.canvas.controls.clearCanvas')}onClose={closeNewCanvas}onConfirm={confirmNewCanvas}/>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsxindex 5502819cf8..792a7a4b55 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx@@ -23,6 +23,7 @@ import { progressImageToStreamingSource } from '@platform/ui/streaming-image/strimport { wheelScrollsHorizontally } from '@platform/ui/wheelScrollsHorizontally';import { getCancelableCanvasStagingQueueItemId } from '@workbench/canvasStagingView';import { CanvasOptionsBar } from '@workbench/widgets/canvas/tool-options/CanvasOptionsBar';+import { AutoSwitchMenu } from '@workbench/widgets/shared/AutoSwitchMenu';import {CheckIcon,ChevronDownIcon,@@ -32,7 +33,6 @@ import {EyeIcon,EyeOffIcon,SaveIcon,- SparklesIcon,Trash2Icon,XIcon,} from 'lucide-react';@@ -45,7 +45,6 @@ import { StagingItemContextMenu, type StagingItemContextMenuTarget } from './Statype AutoSwitchMode = CanvasStagingAreaContractV2['autoSwitchMode'];const THUMBNAIL_STRIP_HEIGHT = '5rem';-const AUTO_SWITCH_MODES: AutoSwitchMode[] = ['off', 'progress', 'latest'];const MENU_POSITIONING = { placement: 'top-end' } as const;/*** Below this bar width the "Generating" text and "Discard All" collapse to icons, so the accept split button (the@@ -293,7 +292,14 @@ export const StagingBar = ({<CanvasFloatingBarDivider css={NARROW_HIDDEN_CSS} />- <AutoSwitchMenu mode={autoSwitchMode} onSelect={onSetAutoSwitch} />+ <AutoSwitchMenu+ density="full"+ positioning={MENU_POSITIONING}+ triggerCss={NARROW_ICON_BUTTON_CSS}+ value={autoSwitchMode}+ valueCss={NARROW_SR_ONLY_CSS}+ onChange={onSetAutoSwitch}+ />{cancelableQueueItemId ? (<>@@ -424,56 +430,6 @@ export const StagingBar = ({);};-const AutoSwitchMenu = ({ mode, onSelect }: { mode: AutoSwitchMode; onSelect: (mode: AutoSwitchMode) => void }) => {- const { t } = useTranslation();- const label = (value: AutoSwitchMode): string =>- t(- value === 'off'- ? 'widgets.canvas.staging.autoSwitchOff'- : value === 'progress'- ? 'widgets.canvas.staging.autoSwitchProgress'- : 'widgets.canvas.staging.autoSwitchLatest'- );-- return (- <Menu.Root positioning={MENU_POSITIONING}>- <Tooltip content={t('widgets.canvas.staging.autoSwitch')}>- <span style={{ display: 'inline-flex' }}>- <Menu.Trigger asChild>- <Button- aria-label={`${t('widgets.canvas.staging.autoSwitch')}: ${label(mode)}`}- css={NARROW_ICON_BUTTON_CSS}- minW="unset"- px="2"- variant="ghost"- >- <SparklesIcon size={13} />- <Text css={NARROW_SR_ONLY_CSS} fontSize="md">- {label(mode)}- </Text>- </Button>- </Menu.Trigger>- </span>- </Tooltip>- <Portal>- <Menu.Positioner>- <MenuContent minW="8rem" py="1">- <Menu.ItemGroup>- <Menu.ItemGroupLabel>{t('widgets.canvas.staging.autoSwitch')}</Menu.ItemGroupLabel>- {AUTO_SWITCH_MODES.map((value) => (- <Menu.Item key={value} value={value} onClick={() => onSelect(value)}>- <CheckIcon size={12} opacity={mode === value ? 1 : 0} />- <Menu.ItemText fontSize="md">{label(value)}</Menu.ItemText>- </Menu.Item>- ))}- </Menu.ItemGroup>- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- );-};-const StagingThumbnail = ({antialiasProgressImages,index,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/gallerySaveToast.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/gallerySaveToast.tsnew file mode 100644index 0000000000..83de35a135--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/gallerySaveToast.ts@@ -0,0 +1,89 @@+/**+ * Feedback for a canvas save to the Gallery, shared by the canvas header save and the staged-result save: the board+ * the image went to, named as the Gallery names it, in a toast fenced to the account that saved.+ */+import type { AccountScope } from '@platform/state/accountLifecycle';+import type { QueryClient } from '@tanstack/react-query';+import type { Project } from '@workbench/projectContracts';+import type { TFunction } from 'i18next';++import { getGalleryBoardLabel, getGallerySettings, type GalleryBoard } from '@features/gallery/contracts';+import { galleryBoardsOptions, getGalleryListingBoardsQuery, type GalleryBoardsQuery } from '@features/gallery/queries';+import { createActionToast, toaster, type ActionToastOptions } from '@platform/ui/toaster';+import { getProjectWidgetValues } from '@workbench/widgetState';++/** Actionable toasts stay long enough to reach the button; hovering or focusing them pauses the timer. */+export const ACTION_TOAST_DURATION_MS = 8000;+/** How long a settled save waits for a boards listing it does not have before it reports without a name. */+const BOARD_LABEL_WAIT_MS = 600;++type BoardDescription = { kind: 'named'; label: string } | { kind: 'missing' } | { kind: 'unknown' };++/**+ * The board as the Gallery names it. Each listing is read from the cache at once, otherwise fetched, all within one+ * bound so feedback never waits on a slow request. Archiving a board keeps it the auto-add destination, so a board+ * absent from a listing that hides archived boards is looked for once more among them; `missing` only when a listing+ * that includes archived boards lacks it.+ */+export const describeBoard = async (+ queryClient: QueryClient,+ project: Project,+ boardId: string,+ t: TFunction+): Promise<BoardDescription> => {+ if (boardId === 'none') {+ return { kind: 'named', label: t('widgets.gallery.uncategorized') };+ }++ const deadline = new Promise<null>((resolve) => {+ globalThis.setTimeout(() => resolve(null), BOARD_LABEL_WAIT_MS);+ });+ const readBoards = (query: GalleryBoardsQuery): Promise<GalleryBoard[] | null> => {+ const options = galleryBoardsOptions(query);+ const cached = queryClient.getQueryData<GalleryBoard[]>(options.queryKey);++ return cached+ ? Promise.resolve(cached)+ : Promise.race([queryClient.fetchQuery(options).catch(() => null), deadline]);+ };+ const describe = (boards: GalleryBoard[]): BoardDescription | null => {+ const board = boards.find((candidate) => candidate.id === boardId);++ return board ? { kind: 'named', label: getGalleryBoardLabel(board, t) } : null;+ };+ const listingQuery = getGalleryListingBoardsQuery(getGallerySettings(getProjectWidgetValues(project, 'gallery')));+ const listing = await readBoards(listingQuery);+ const listed = listing && describe(listing);++ if (listed) {+ return listed;+ }++ const everything = listingQuery.includeArchived+ ? listing+ : await readBoards({ ...listingQuery, includeArchived: true });++ if (!everything) {+ return { kind: 'unknown' };+ }++ return describe(everything) ?? { kind: 'missing' };+};++/**+ * Report to the account that saved. The toast names that account's image and board, so it leaves with the account's+ * scope rather than outlive it with buttons that would act for nobody.+ */+export const announce = (owner: AccountScope, options: ActionToastOptions): void => {+ const shown = new AbortController();+ const id = createActionToast({+ ...options,+ onStatusChange: ({ status }) => {+ if (status === 'unmounted') {+ shown.abort();+ }+ },+ });++ owner.signal.addEventListener('abort', () => toaster.dismiss(id), { once: true, signal: shown.signal });+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsxindex a6229154a2..22eb49b7c1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.browser.test.tsx@@ -1,9 +1,12 @@import type { CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';+import { ChakraProvider } from '@chakra-ui/react';import { invalidateGallery, invalidateGalleryBoardDestinations } from '@features/gallery/queries';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';+import { AppToaster } from '@platform/ui/toaster';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';import { act, createRef, type Ref, useImperativeHandle } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -11,6 +14,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useCanvasGallerySave } from './useCanvasGallerySave';const mocks = vi.hoisted(() => ({+ activeProjectId: 'project-1',+ findGalleryItem: vi.fn(),reportError: vi.fn(),saveCanvasToGallery: vi.fn<(options: { region: CanvasGallerySaveRegion }) => Promise<unknown>>(),}));@@ -20,14 +25,28 @@ vi.mock('@workbench/canvas-operations/api', () => ({}));vi.mock('@workbench/WorkbenchContext', () => ({useWorkbenchCommands: () => ({ notifications: { reportError: mocks.reportError } }),- useWorkbenchQueries: () => ({ getSnapshot: () => ({ activeProject: { id: 'project-1' } }) }),+ useWorkbenchQueries: () => ({+ getSnapshot: () => ({ activeProject: { id: 'project-1', widgetInstances: {} } }),+ isActiveProject: (id: string) => id === mocks.activeProjectId,+ }),}));+vi.mock('@workbench/image-actions/useFindGalleryItem', () => ({ useFindGalleryItem: () => mocks.findGalleryItem }));vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }) }));-vi.mock('@features/gallery/queries', () => ({+vi.mock('@features/gallery/queries', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ // The auto-add board, B, as the Gallery's board listing names it.+ galleryBoardsOptions: (query: { includeArchived?: boolean }) => ({+ queryFn: () => Promise.resolve([{ archived: false, id: 'board-b', kind: 'board', name: 'Board B' }]),+ queryKey: ['test-boards', query.includeArchived === true],+ }),invalidateGallery: vi.fn(() => Promise.resolve()),invalidateGalleryBoardDestinations: vi.fn(() => Promise.resolve()),}));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { board?: string }) => (options?.board ? `${key}: ${options.board}` : key),+ }),+}));type Handle = ReturnType<typeof useCanvasGallerySave>;const engine = { projectId: 'project-1' } as unknown as Parameters<typeof useCanvasGallerySave>[0];@@ -57,16 +76,20 @@ const deferred = () => {beforeEach(async () => {vi.clearAllMocks();+ mocks.activeProjectId = 'project-1';accountLifecycle.activate('user-a');host = document.createElement('div');document.body.append(host);root = createRoot(host);await act(() =>root?.render(- <QueryClientProvider client={new QueryClient()}>- <Probe ref={header} />- <Probe ref={menu} />- </QueryClientProvider>+ <ChakraProvider value={system}>+ <QueryClientProvider client={new QueryClient()}>+ <Probe ref={header} />+ <Probe ref={menu} />+ <AppToaster />+ </QueryClientProvider>+ </ChakraProvider>));});@@ -94,7 +117,7 @@ describe('useCanvasGallerySave across surfaces', () => {expect(mocks.saveCanvasToGallery).toHaveBeenCalledTimes(1);await act(async () => {- inFlight.resolve({ imageName: 'saved.png', status: 'saved' });+ inFlight.resolve({ boardId: 'board-b', imageName: 'saved.png', status: 'saved' });await first;});expect(header.current!.isSaving).toBe(false);@@ -107,7 +130,7 @@ describe('useCanvasGallerySave across surfaces', () => {expect(mocks.reportError).toHaveBeenCalledOnce();expect(menu.current!.isSaving).toBe(false);- mocks.saveCanvasToGallery.mockResolvedValueOnce({ imageName: 'saved.png', status: 'saved' });+ mocks.saveCanvasToGallery.mockResolvedValueOnce({ boardId: 'board-b', imageName: 'saved.png', status: 'saved' });await act(() => menu.current!.save('canvas'));expect(mocks.saveCanvasToGallery).toHaveBeenCalledTimes(2);});@@ -129,3 +152,32 @@ describe('useCanvasGallerySave across surfaces', () => {expect(invalidateGallery).not.toHaveBeenCalled();});});++const toastRoot = () => document.querySelector<HTMLElement>('[data-part="root"][data-scope="toast"]');+const toastButton = (label: string) =>+ [...(toastRoot()?.querySelectorAll('button') ?? [])].find((button) => button.textContent === label) ?? null;+const until = (assertion: () => void) => act(() => vi.waitFor(assertion, { interval: 20, timeout: 3000 }));++describe('useCanvasGallerySave feedback', () => {+ it('names the board the image went to and shows it in a Gallery panel, leaving the center alone', async () => {+ mocks.saveCanvasToGallery.mockResolvedValueOnce({ boardId: 'board-b', imageName: 'saved.png', status: 'saved' });++ await act(() => header.current!.save('canvas'));++ await until(() => expect(toastRoot()?.textContent).toContain('widgets.canvas.staging.savedToBoard: Board B'));+ await act(() => toastButton('widgets.canvas.staging.showInGallery')!.click());+ expect(mocks.findGalleryItem).toHaveBeenCalledWith({ kind: 'image', name: 'saved.png' }, { revealPreview: false });+ });++ it('offers no Gallery action once another project is active', async () => {+ mocks.saveCanvasToGallery.mockImplementationOnce(() => {+ mocks.activeProjectId = 'project-2';+ return Promise.resolve({ boardId: 'board-b', imageName: 'saved.png', status: 'saved' });+ });++ await act(() => header.current!.save('canvas'));++ await until(() => expect(toastRoot()?.textContent).toContain('Board B'));+ expect(toastButton('widgets.canvas.staging.showInGallery')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.tsindex 268bb20d5c..f7c7c4d370 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasGallerySave.ts@@ -1,3 +1,4 @@+import type { ToastAction } from '@platform/ui/toaster';import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import { invalidateGallery, invalidateGalleryBoardDestinations } from '@features/gallery/queries';@@ -11,12 +12,14 @@ import { createKeyedTransientStore } from '@platform/state/externalStore';import { ApiError } from '@platform/transport/http';import { useQueryClient } from '@tanstack/react-query';import { saveCanvasToGallery, type CanvasGallerySaveRegion } from '@workbench/canvas-operations/api';+import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';import { useNotify } from '@workbench/useNotify';import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { getCanvasGallerySaveErrorAction, withMatchingCanvasProject } from './canvasGallerySaveState';+import { ACTION_TOAST_DURATION_MS, announce, describeBoard } from './gallerySaveToast';type CanvasGallerySaveEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'lifecycle' | 'projectId'>;@@ -32,6 +35,7 @@ export const useCanvasGallerySave = (const queries = useWorkbenchQueries();const { notifications } = useWorkbenchCommands();const queryClient = useQueryClient();+ const findGalleryItem = useFindGalleryItem();const isSaving = savingProjects.useValue(engine?.projectId ?? '') === true;const save = useCallback(@@ -51,10 +55,34 @@ export const useCanvasGallerySave = (assertAccountScopeCurrent(owner);if (result.status === 'saved') {void invalidateGallery(queryClient, owner);- notify.success(- t('widgets.canvas.contextMenu.saved'),- t('widgets.canvas.contextMenu.savedDescription', { name: result.imageName })- );+ const board = await describeBoard(queryClient, project, result.boardId, t);++ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ // Reveals and selects the image in a Gallery panel (its board, Media, cleared filters) and leaves the+ // center on the Canvas, while the project that saved it is still open.+ const showInGallery: ToastAction = {+ label: t('widgets.canvas.staging.showInGallery'),+ onClick: () => {+ if (isAccountScopeCurrent(owner) && queries.isActiveProject(project.id)) {+ findGalleryItem({ kind: 'image', name: result.imageName }, { revealPreview: false });+ }+ },+ };+ const showActions = queries.isActiveProject(project.id) ? [showInGallery] : [];++ announce(owner, {+ actions: showActions,+ description: t('widgets.canvas.staging.savedDescription', { name: result.imageName }),+ ...(showActions.length > 0 ? { duration: ACTION_TOAST_DURATION_MS } : {}),+ title:+ board.kind === 'named'+ ? t('widgets.canvas.staging.savedToBoard', { board: board.label })+ : t('widgets.canvas.contextMenu.saved'),+ type: 'success',+ });} else if (result.status === 'empty') {notify.info(t('widgets.canvas.contextMenu.empty'));} else if (result.status === 'stale') {@@ -80,7 +108,7 @@ export const useCanvasGallerySave = (}});},- [engine, notifications, notify, queries, queryClient, t]+ [engine, findGalleryItem, notifications, notify, queries, queryClient, t]);return { isSaving, save };diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStagedResultGallerySave.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStagedResultGallerySave.tsindex 36b06b59fa..0e419e0daf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStagedResultGallerySave.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStagedResultGallerySave.ts@@ -1,22 +1,14 @@import type { AccountScope } from '@platform/state/accountLifecycle';-import type { QueryClient } from '@tanstack/react-query';+import type { ToastAction } from '@platform/ui/toaster';import type { Project } from '@workbench/projectContracts';-import type { TFunction } from 'i18next';-import { getGalleryBoardLabel, getGallerySettings, type GalleryBoard } from '@features/gallery/contracts';-import {- galleryBoardsOptions,- getGalleryListingBoardsQuery,- invalidateGallery,- type GalleryBoardsQuery,-} from '@features/gallery/queries';+import { invalidateGallery } from '@features/gallery/queries';import {captureAccountScope,isAccountScopeCurrent,registerAccountOwnedResource,} from '@platform/state/accountLifecycle';import { createKeyedTransientStore } from '@platform/state/externalStore';-import { createActionToast, toaster, type ActionToastOptions, type ToastAction } from '@platform/ui/toaster';import { useQueryClient } from '@tanstack/react-query';import {retryStagedResultBoard,@@ -24,97 +16,22 @@ import {type SaveStagedResultOutcome,} from '@workbench/canvas-operations/api';import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';-import { getProjectWidgetValues } from '@workbench/widgetState';import { useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { ACTION_TOAST_DURATION_MS, announce, describeBoard } from './gallerySaveToast';+/** Staged images with a save or board retry in flight; the bar and the thumbnail menu share the gate. */const savingImages = createKeyedTransientStore<string, true>();registerAccountOwnedResource({ clear: () => savingImages.clear(), name: 'staged-result-gallery-saves' });-/** Actionable toasts stay long enough to reach the button; hovering or focusing them pauses the timer. */-const ACTION_TOAST_DURATION_MS = 8000;-/** How long a settled save waits for a boards listing it does not have before it reports without a name. */-const BOARD_LABEL_WAIT_MS = 600;--type BoardDescription = { kind: 'named'; label: string } | { kind: 'missing' } | { kind: 'unknown' };--/**- * The board as the Gallery names it. Each listing is read from the cache at once, otherwise fetched, all within one- * bound so feedback never waits on a slow request. Archiving a board keeps it the auto-add destination, so a board- * absent from a listing that hides archived boards is looked for once more among them; `missing` only when a listing- * that includes archived boards lacks it.- */-const describeBoard = async (- queryClient: QueryClient,- project: Project,- boardId: string,- t: TFunction-): Promise<BoardDescription> => {- if (boardId === 'none') {- return { kind: 'named', label: t('widgets.gallery.uncategorized') };- }-- const deadline = new Promise<null>((resolve) => {- globalThis.setTimeout(() => resolve(null), BOARD_LABEL_WAIT_MS);- });- const readBoards = (query: GalleryBoardsQuery): Promise<GalleryBoard[] | null> => {- const options = galleryBoardsOptions(query);- const cached = queryClient.getQueryData<GalleryBoard[]>(options.queryKey);-- return cached- ? Promise.resolve(cached)- : Promise.race([queryClient.fetchQuery(options).catch(() => null), deadline]);- };- const describe = (boards: GalleryBoard[]): BoardDescription | null => {- const board = boards.find((candidate) => candidate.id === boardId);-- return board ? { kind: 'named', label: getGalleryBoardLabel(board, t) } : null;- };- const listingQuery = getGalleryListingBoardsQuery(getGallerySettings(getProjectWidgetValues(project, 'gallery')));- const listing = await readBoards(listingQuery);- const listed = listing && describe(listing);-- if (listed) {- return listed;- }-- const everything = listingQuery.includeArchived- ? listing- : await readBoards({ ...listingQuery, includeArchived: true });-- if (!everything) {- return { kind: 'unknown' };- }-- return describe(everything) ?? { kind: 'missing' };-};-/** What a save, or a board retry, belongs to: the account and project current when the user asked for it. */interface SaveOrigin {owner: AccountScope;project: Project;}-/**- * Report to the account that saved. The toast names that account's image and board, so it leaves with the account's- * scope rather than outlive it with buttons that would act for nobody.- */-const announce = (owner: AccountScope, options: ActionToastOptions): void => {- const shown = new AbortController();- const id = createActionToast({- ...options,- onStatusChange: ({ status }) => {- if (status === 'unmounted') {- shown.abort();- }- },- });-- owner.signal.addEventListener('abort', () => toaster.dismiss(id), { once: true, signal: shown.signal });-};-/*** Save a staged canvas result to the Gallery and say where it went. The account and project are captured when the* save starts and every toast action is fenced to them: nothing runs for an account that has since signed out, anddiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsxindex afd5bbd2f9..3a6ca556db 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.browser.test.tsx@@ -184,7 +184,6 @@ const Widget = ({ item }: { item: GalleryImageItem | GalleryVideoItem }) => {data-hotkey-widget-instance-id="preview-instance"data-hotkey-widget-region="center"data-hotkey-widget-type-id="preview"- role="region"style={{ display: 'flex', flexDirection: 'column', height: 360, width: 640 }}><div style={{ display: 'flex', height: 32, justifyContent: 'flex-end' }}>@@ -212,7 +211,26 @@ const render = async (item: GalleryImageItem | GalleryVideoItem) => {<ChakraProvider value={system}><FocusRegionProvider controller={createTestFocusController()}><WorkbenchHotkeyRuntime />- <Widget item={item} />+ {/* As a docked Preview sits in the workbench: the nearest region is the whole project. */}+ <div aria-label="Project" role="region">+ <Widget item={item} />+ <div+ data-hotkey-widget-instance-id="gallery-instance"+ data-hotkey-widget-region="left"+ data-hotkey-widget-type-id="gallery"+ >+ <button data-testid="gallery-tile" type="button">+ Tile+ </button>+ </div>+ <div+ data-hotkey-widget-instance-id="canvas-instance"+ data-hotkey-widget-region="right"+ data-hotkey-widget-type-id="canvas"+ data-testid="canvas"+ style={{ height: 40 }}+ />+ </div></FocusRegionProvider></ChakraProvider></I18nextProvider>@@ -421,4 +439,23 @@ describe('PreviewDetailsPopover', () => {await settle(100);expect(onOpenChange).toHaveBeenCalledWith(false);});++ it('stays open while a Gallery elsewhere changes the selection, and closes for another widget', async () => {+ await render(imageItem);+ await expect.element(page.getByText('a tall prompt')).toBeVisible();+ const pointAt = (element: HTMLElement) =>+ act(() => {+ element.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType: 'mouse' }));+ element.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerType: 'mouse' }));+ });++ await pointAt(host.querySelector<HTMLElement>('[data-testid="gallery-tile"]')!);+ await settle(100);+ expect(onOpenChange).not.toHaveBeenCalled();++ // Another widget in the same project region.+ await pointAt(host.querySelector<HTMLElement>('[data-testid="canvas"]')!);+ await settle(100);+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsxindex dd8276ba24..fe940aca87 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPopover.tsx@@ -75,6 +75,11 @@ const PreviewImageTags = ({ accountEpoch, item }: { accountEpoch: number; item:* Bound Details to the media stage so long metadata scrolls without covering the filmstrip; images offer parsed* details alongside raw payload tabs.*/+const WIDGET_INSTANCE_ATTRIBUTE = 'data-hotkey-widget-instance-id';+const WIDGET_TYPE_ATTRIBUTE = 'data-hotkey-widget-type-id';+/** Every widget's root (and the center header chrome) carries its instance and type for hotkey targeting. */+const WIDGET_SELECTOR = `[${WIDGET_INSTANCE_ATTRIBUTE}][${WIDGET_TYPE_ATTRIBUTE}]`;+export const PreviewDetailsPopover = ({actions,image,@@ -105,13 +110,21 @@ export const PreviewDetailsPopover = ({[stageElement]);const handleOpenChange = useCallback(({ open }: { open: boolean }) => onOpenChange(open), [onOpenChange]);- // Keep Details open while stage/filmstrip selection changes and preserve Preview keyboard navigation.+ // Details follow the selection, so they stay open while it changes: in this Preview (stage, filmstrip, its header+ // chrome) or in any Gallery, wherever either is docked. Anywhere else closes them.const handleInteractOutside = useCallback<InteractOutsideHandler>((event) => {- const widget = stageElement?.closest('[role="region"]');const target = event.detail.originalEvent.target;+ const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null;+ const targetWidget = element?.closest(WIDGET_SELECTOR);+ const previewInstanceId = stageElement?.closest(WIDGET_SELECTOR)?.getAttribute(WIDGET_INSTANCE_ATTRIBUTE);- if (widget && target instanceof Node && widget.contains(target)) {+ if (+ targetWidget &&+ (targetWidget.getAttribute(WIDGET_TYPE_ATTRIBUTE) === 'gallery' ||+ (previewInstanceId !== undefined &&+ targetWidget.getAttribute(WIDGET_INSTANCE_ATTRIBUTE) === previewInstanceId))+ ) {event.preventDefault();}},diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsxindex 7da908f3a1..caa9344166 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.browser.test.tsx@@ -11,6 +11,8 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { page } from 'vitest/browser';+import type * as PreviewHeaderStoreModule from './previewHeaderStore';+import { PreviewHeaderActions } from './PreviewHeaderActions';const i18n = createInstance();@@ -22,11 +24,18 @@ void i18n.use(initReactI18next).init({en: {translation: {widgets: {+ canvas: {+ staging: {+ autoSwitch: 'Auto-switch',+ autoSwitchCurrent: 'Auto-switch: {{mode}}',+ autoSwitchLatest: 'Newest',+ autoSwitchOff: 'Off',+ autoSwitchProgress: 'In progress',+ },+ },preview: {hideFilmstrip: 'Hide filmstrip',- hideInProgressDiffusion: 'Hide in-progress diffusion',showFilmstrip: 'Show filmstrip',- showInProgressDiffusion: 'Show in-progress diffusion',details: 'Details',editOnCanvas: 'Edit on Canvas',imageActions: 'Image actions',@@ -46,7 +55,7 @@ void i18n.use(initReactI18next).init({const state = vi.hoisted(() => ({actionItem: null as null | Record<string, unknown>,filmstripVisible: true,- showProgressImagesInViewer: true,+ viewerAutoSwitch: 'progress' as 'latest' | 'off' | 'progress',zoom: null as null | {fitPercent: number | null;isZoomed: boolean;@@ -57,13 +66,16 @@ const state = vi.hoisted(() => ({}));const patchValues = vi.hoisted(() => vi.fn());const updateProjectPreferences = vi.hoisted(() => vi.fn());+const showAll = vi.hoisted(() => vi.fn());vi.mock('@features/queue/react', () => ({ useProgressImage: () => null }));vi.mock('@features/identity', async (importOriginal) => ({...(await importOriginal<typeof IdentityModule>()),useAuthSession: () => ({ accountEpoch: 1 }),}));-vi.mock('./previewHeaderStore', () => ({+// Partial: the real zoom limits decide which presets the menu offers.+vi.mock('./previewHeaderStore', async (importOriginal) => ({+ ...(await importOriginal<typeof PreviewHeaderStoreModule>()),usePreviewStageContext: () => ({stageElement: null,zoom: state.zoom && {@@ -91,7 +103,7 @@ vi.mock('@workbench/widgetState', () => ({vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({...(await importOriginal<typeof WorkbenchContextModule>()),useActiveProjectSelector: (select: (project: unknown) => unknown) =>- select({ settings: { showProgressImagesInViewer: state.showProgressImagesInViewer } }),+ select({ settings: { viewerAutoSwitch: state.viewerAutoSwitch } }),useWorkbenchCommands: () => ({account: { updateProjectPreferences },widgets: { patchValues },@@ -132,9 +144,10 @@ const button = (label: string): HTMLButtonElement =>beforeEach(() => {state.actionItem = null;state.filmstripVisible = true;- state.showProgressImagesInViewer = true;+ state.viewerAutoSwitch = 'progress';state.zoom = null;patchValues.mockClear();+ showAll.mockClear();updateProjectPreferences.mockClear();});@@ -145,42 +158,77 @@ afterEach(async () => {root = null;});-describe('preview header toggles', () => {- it('states both on/off positions the same way', async () => {+describe('preview header filmstrip toggle', () => {+ it('states its position and toggles the setting it owns', async () => {await render();- const bothOn = [button('Hide filmstrip'), button('Hide in-progress diffusion')];- for (const control of bothOn) {- expect(control.getAttribute('aria-pressed'), control.ariaLabel ?? '').toBe('true');- }+ expect(button('Hide filmstrip').getAttribute('aria-pressed')).toBe('true');+ await settle(() => button('Hide filmstrip').click());+ expect(patchValues).toHaveBeenCalledWith('preview', { filmstripVisible: false });state.filmstripVisible = false;- state.showProgressImagesInViewer = false;await render();- const bothOff = [button('Show filmstrip'), button('Show in-progress diffusion')];+ expect(button('Show filmstrip').getAttribute('aria-pressed')).toBe('false');+ });+});++describe('preview header Auto-switch', () => {+ it('offers the staging bar modes and writes the chosen one, letting go of a pinned session', async () => {+ await render();- for (const control of bothOff) {- expect(control.getAttribute('aria-pressed'), control.ariaLabel ?? '').toBe('false');- }+ await settle(() => button('Auto-switch: In progress').click());+ const option = (name: string) => page.getByRole('menuitemradio', { name });+ await expect.element(option('In progress')).toHaveAttribute('aria-checked', 'true');+ await expect.element(option('Off')).toHaveAttribute('aria-checked', 'false');+ await option('Newest').click();++ expect(updateProjectPreferences).toHaveBeenCalledExactlyOnceWith({ viewerAutoSwitch: 'latest' });+ expect(showAll).toHaveBeenCalledOnce();});- it('still toggles the setting each one owns', async () => {+ it('shows the mode on the trigger, Off as soon as a selection turns it off', async () => {await render();+ expect(button('Auto-switch: In progress').textContent).toContain('In progress');- await settle(() => button('Hide filmstrip').click());- expect(patchValues).toHaveBeenCalledWith('preview', { filmstripVisible: false });+ // A Gallery selection writes Off; the trigger reads it from the project on the next render.+ state.viewerAutoSwitch = 'off';+ await settle(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <PreviewHeaderActions {...({ region: 'center', runtime: {} } as unknown as WidgetViewProps)} />+ </ChakraProvider>+ </I18nextProvider>+ );+ });- await settle(() => button('Hide in-progress diffusion').click());- expect(updateProjectPreferences).toHaveBeenCalledWith({ showProgressImagesInViewer: false });+ expect(button('Auto-switch: Off').textContent).toContain('Off');+ });++ it('is the icon alone in a compact region, naming the mode in its tooltip and dimming for Off', async () => {+ await render('right');+ const trigger = button('Auto-switch: In progress');+ const icon = () =>+ button(`Auto-switch: ${state.viewerAutoSwitch === 'off' ? 'Off' : 'In progress'}`).querySelector('svg')!;++ expect(trigger.textContent).toBe('');+ const onOpacity = getComputedStyle(icon()).opacity;+ await settle(() => trigger.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' })));+ await expect.element(page.getByRole('tooltip')).toHaveTextContent('Auto-switch: In progress');++ // A selection turns it Off: the trigger says so and its icon dims.+ state.viewerAutoSwitch = 'off';+ await render('right');+ expect(Number(getComputedStyle(icon()).opacity)).toBeLessThan(Number(onOpacity));});});vi.mock('./livePreviewFollow', () => ({- useLivePreviewFollow: () => ({ sessions: [], pinnedSessionId: null, pin: vi.fn(), showAll: vi.fn() }),+ useLivePreviewFollow: () => ({ sessions: [], pinnedSessionId: null, pin: vi.fn(), showAll }),}));describe('preview zoom menu', () => {- it('reads the fitted percent, offers only presets above fit, and routes fit/presets to the loupe', async () => {+ it('reads the fitted percent, offers every preset but the current level, and routes them to the loupe', async () => {const reset = vi.fn();const zoomTo = vi.fn();state.zoom = { fitPercent: 88, isZoomed: false, percent: 88, reset, zoomTo };@@ -200,13 +248,43 @@ describe('preview zoom menu', () => {state.zoom = { fitPercent: 120, isZoomed: true, percent: 200, reset, zoomTo };await render();await settle(() => button('Zoom 200%').click());- // A fit above 100% leaves the 100% preset nowhere to go; the current level is not re-offered.- await expect.element(item('100%')).toHaveAttribute('aria-disabled', 'true');+ // 100% is below a 120% fit yet still offered, so an enlarged image can be seen at its own size; the current+ // level is not re-offered.+ await expect.element(item('100%')).not.toHaveAttribute('aria-disabled');await expect.element(item('200%')).toHaveAttribute('aria-disabled', 'true');await item('Fit to view').click();expect(reset).toHaveBeenCalledOnce();});+ it('offers the presets between 100% and a fit that enlarges the image, since zoom goes down to 100%', async () => {+ const zoomTo = vi.fn();+ const item = (label: string) => page.getByRole('menuitem', { name: label });++ state.zoom = { fitPercent: 250, isZoomed: false, percent: 250, reset: vi.fn(), zoomTo };+ await render();+ await settle(() => button('Zoom 250%').click());+ await expect.element(item('100%')).not.toHaveAttribute('aria-disabled');+ await expect.element(item('400%')).not.toHaveAttribute('aria-disabled');+ await item('200%').click();+ expect(zoomTo).toHaveBeenCalledExactlyOnceWith(2);+ });++ it('offers 100% at a fit just past it, though both read as 100%, and not at an exact 100% fit', async () => {+ const zoomTo = vi.fn();+ const item = (label: string) => page.getByRole('menuitem', { name: label });++ state.zoom = { fitPercent: 100.2, isZoomed: false, percent: 100, reset: vi.fn(), zoomTo };+ await render();+ await settle(() => button('Zoom 100%').click());+ await item('100%').click();+ expect(zoomTo).toHaveBeenCalledExactlyOnceWith(1);++ state.zoom = { fitPercent: 100, isZoomed: false, percent: 100, reset: vi.fn(), zoomTo };+ await render();+ await settle(() => button('Zoom 100%').click());+ await expect.element(item('100%')).toHaveAttribute('aria-disabled', 'true');+ });+it('shows the zoom control in compact regions only while zoomed', async () => {state.zoom = { fitPercent: 88, isZoomed: false, percent: 88, reset: vi.fn(), zoomTo: vi.fn() };await render('right');@@ -236,7 +314,7 @@ describe('preview header details toggle', () => {await render();const labels = [...host!.querySelectorAll<HTMLButtonElement>('button')].map((b) => b.getAttribute('aria-label'));- expect(labels.slice(-3)).toEqual(['Hide in-progress diffusion', 'Hide filmstrip', 'Details']);+ expect(labels.slice(-3)).toEqual(['Auto-switch: In progress', 'Hide filmstrip', 'Details']);expect(labels[0]).toBe('Edit on Canvas');expect(button('Details').getAttribute('aria-pressed')).toBe('false');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsxindex 33f9dc6688..7ba4793781 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx@@ -1,11 +1,13 @@+import type { ViewerAutoSwitchMode } from '@workbench/settings/contracts';import type { WidgetViewProps } from '@workbench/widgetContracts';import { Box, HStack } from '@chakra-ui/react';import { galleryImageItemToGalleryImage, isGalleryImageItem } from '@features/gallery/contracts';import { ToggleIconButton } from '@platform/ui';+import { AutoSwitchMenu } from '@workbench/widgets/shared/AutoSwitchMenu';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';-import { GalleryThumbnailsIcon, HourglassIcon } from 'lucide-react';+import { GalleryThumbnailsIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -18,11 +20,12 @@ import { PreviewZoomMenu } from './PreviewZoomMenu';const Divider = () => <Box bg="border.subtle" flexShrink={0} h="4" w="1px" />;+const AUTO_SWITCH_POSITIONING = { placement: 'bottom-end' } as const;+export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {const { t } = useTranslation();const livePreview = useLivePreviewFollow();- const showProgressImagesInViewer = useActiveProjectSelector((project) => project.settings.showProgressImagesInViewer);- const hasProgressImage = livePreview.sessions.length > 0;+ const autoSwitch = useActiveProjectSelector((project) => project.settings.viewerAutoSwitch);const { actionItem, actions, copyCurrentVideoFrame, isVideoFrameCopyAvailable, openItemMenu, position, zoom } =usePreviewHeaderContext();const { stageElement, zoom: zoomReadout } = usePreviewStageContext();@@ -37,14 +40,15 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {});const { account, widgets } = useWorkbenchCommands();const isFull = region === 'center';- const label = showProgressImagesInViewer- ? t('widgets.preview.hideInProgressDiffusion')- : t('widgets.preview.showInProgressDiffusion');const filmstripLabel = isFilmstripVisible ? t('widgets.preview.hideFilmstrip') : t('widgets.preview.showFilmstrip');- const toggleProgressImages = useCallback(() => {- livePreview.showAll();- account.updateProjectPreferences({ showProgressImagesInViewer: !showProgressImagesInViewer });- }, [account, livePreview, showProgressImagesInViewer]);+ // A chosen mode follows the newest work again, so a session pinned from a tile lets go.+ const setAutoSwitch = useCallback(+ (mode: ViewerAutoSwitchMode) => {+ livePreview.showAll();+ account.updateProjectPreferences({ viewerAutoSwitch: mode });+ },+ [account, livePreview]+ );const toggleFilmstrip = useCallback(() => widgets.patchValues('preview', { filmstripVisible: !isFilmstripVisible }),[isFilmstripVisible, widgets]@@ -78,13 +82,11 @@ export const PreviewHeaderActions = ({ region }: WidgetViewProps) => {</>) : null}- <ToggleIconButton- checked={showProgressImagesInViewer}- icon={HourglassIcon}- label={label}- // Apply dimming after primitive props so idle-state styling survives.- opacity={hasProgressImage || showProgressImagesInViewer ? 1 : 0.7}- onCheckedChange={toggleProgressImages}+ <AutoSwitchMenu+ density={isFull ? 'full' : 'compact'}+ positioning={AUTO_SWITCH_POSITIONING}+ value={autoSwitch}+ onChange={setAutoSwitch}/><ToggleIconButtonchecked={isFilmstripVisible}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.tsxnew file mode 100644index 0000000000..640ddd86d8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.tsx@@ -0,0 +1,129 @@+import type { MouseEvent } from 'react';++import { Box } from '@chakra-ui/react';+import { IconButton } from '@platform/ui/Button';+import { Tooltip } from '@platform/ui/Tooltip';+import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { PreviewSwipeNavigation } from './usePreviewSwipe';++/** Marks the arrows so the stage can reveal them on hover or focus within it. */+export const PREVIEW_NAV_ATTRIBUTE = 'data-preview-nav';++/**+ * The stage shows its arrows while the pointer is over it or focus is within it. Hidden arrows take no pointer events,+ * so a click at the stage edge still reaches the image. The fade is opacity alone, and none under reduced motion.+ */+export const PREVIEW_NAV_STAGE_CSS = {+ [`& [${PREVIEW_NAV_ATTRIBUTE}]`]: {+ opacity: 0,+ pointerEvents: 'none',+ transitionDuration: '120ms',+ transitionProperty: 'opacity',+ transitionTimingFunction: 'ease-out',+ '@media (prefers-reduced-motion: reduce)': { transitionDuration: '0ms' },+ },+ [`&:hover [${PREVIEW_NAV_ATTRIBUTE}], &:focus-within [${PREVIEW_NAV_ATTRIBUTE}]`]: {+ opacity: 1,+ pointerEvents: 'auto',+ },+} as const;++/** Keeps the Preview's focus where it is, so the arrow keys still step after a click. */+const keepFocus = (event: MouseEvent) => event.preventDefault();++/**+ * Previous and next over the stage: a pointer path to the same steps the arrow keys take. A side with nothing to step+ * to has no button. Out of the tab order, since the keys already reach both steps.+ */+export const PreviewNavButtons = ({+ isVideo,+ navigation,+}: {+ isVideo: boolean;+ navigation: PreviewSwipeNavigation;+}) => {+ const { t } = useTranslation();+ const [isPending, setIsPending] = useState(false);+ const { neighbors, onNavigate } = navigation;+ const step = useCallback(+ (offset: -1 | 1) => {+ setIsPending(true);+ void onNavigate(offset).finally(() => setIsPending(false));+ },+ [onNavigate]+ );+ const stepPrevious = useCallback(() => step(-1), [step]);+ const stepNext = useCallback(() => step(1), [step]);++ return (+ <>+ {neighbors.previous ? (+ <NavButton+ isDisabled={isPending}+ isVideo={isVideo}+ keyShortcut="ArrowLeft"+ label={t('widgets.preview.commands.previousItem')}+ side="start"+ onStep={stepPrevious}+ />+ ) : null}+ {neighbors.next ? (+ <NavButton+ isDisabled={isPending}+ isVideo={isVideo}+ keyShortcut="ArrowRight"+ label={t('widgets.preview.commands.nextItem')}+ side="end"+ onStep={stepNext}+ />+ ) : null}+ </>+ );+};++const NavButton = ({+ isDisabled,+ isVideo,+ keyShortcut,+ label,+ side,+ onStep,+}: {+ isDisabled: boolean;+ isVideo: boolean;+ keyShortcut: string;+ label: string;+ side: 'end' | 'start';+ onStep: () => void;+}) => (+ <Box+ {...{ [PREVIEW_NAV_ATTRIBUTE]: side }}+ insetInlineEnd={side === 'end' ? '2' : undefined}+ insetInlineStart={side === 'start' ? '2' : undefined}+ position="absolute"+ // A video's controls run along the bottom of the stage; center over what is left above them.+ top={isVideo ? 'calc(50% - 1.5rem)' : '50%'}+ transform="translateY(-50%)"+ zIndex="1"+ >+ <Tooltip content={label}>+ <IconButton+ aria-keyshortcuts={keyShortcut}+ aria-label={label}+ bg="bg.panel/80"+ disabled={isDisabled}+ rounded="full"+ size="sm"+ tabIndex={-1}+ variant="outline"+ onClick={onStep}+ onMouseDown={keepFocus}+ >+ {side === 'start' ? <ChevronLeftIcon /> : <ChevronRightIcon />}+ </IconButton>+ </Tooltip>+ </Box>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsxindex fb3b3df792..e313f9d98e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavigation.browser.test.tsx@@ -113,7 +113,7 @@ const mocks = vi.hoisted(() => {// Preview is the center region's active widget, as the shell places it.widgetRegions: { center: { activeInstanceId: 'preview-instance', instanceIds: ['preview-instance'] } },queue: { items: [] as unknown[] },- settings: { antialiasProgressImages: false, showProgressImagesInViewer: false },+ settings: { antialiasProgressImages: false, viewerAutoSwitch: 'off' },widgetInstances: {gallery: {state: {@@ -445,6 +445,7 @@ await i18n.use(initReactI18next).init({common: { countOfTotal: '{{count}} of {{total}}', generating: 'Generating' },widgets: {preview: {+ commands: { nextItem: 'Show next item', previousItem: 'Show previous item' },framesPerSecond: '{{count}} fps',itemCount_one: '{{count}} item',itemCount_other: '{{count}} items',@@ -756,7 +757,7 @@ beforeEach(() => {mocks.commands.gallery.selectItem.mockClear();vi.mocked(requestGalleryItemReveal).mockClear();mocks.project.queue.items = [];- mocks.project.settings.showProgressImagesInViewer = false;+ mocks.project.settings.viewerAutoSwitch = 'off';delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).compareImage;delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).galleryPage;delete (mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>).imageOrderDir;@@ -824,6 +825,89 @@ afterEach(async () => {const selectedThumb = (): string | null | undefined =>host?.querySelector<HTMLButtonElement>('button[aria-current]')?.getAttribute('aria-label');+describe('preview arrow buttons', () => {+ const arrow = (name: 'Show next item' | 'Show previous item') =>+ host!.querySelector<HTMLButtonElement>(`button[aria-label="${name}"]`);+ // The arrows show, and take the pointer, while it is over the stage.+ const click = (button: HTMLButtonElement) =>+ act(async () => {+ await userEvent.hover(button.closest('[data-preview-nav]')!.parentElement!);+ await userEvent.click(button);+ await Promise.resolve();+ });++ it('steps to the item the arrow key would, and leaves focus with Preview so the keys still work', async () => {+ await render();+ const before = document.activeElement;++ expect(arrow('Show previous item')).toBeNull();+ expect(arrow('Show next item')).toHaveAttribute('aria-keyshortcuts', 'ArrowRight');+ expect(arrow('Show next item')).toHaveAttribute('tabindex', '-1');+ await click(arrow('Show next item')!);++ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ kind: 'image', name: 'oldest' }),+ undefined,+ expect.any(Number),+ true+ );+ expect(document.activeElement).toBe(before);++ await commitLastSelection();+ await pressArrow('ArrowLeft');+ expect(mocks.commands.gallery.selectItem).toHaveBeenLastCalledWith(+ expect.objectContaining({ name: 'newest' }),+ undefined,+ expect.any(Number),+ true+ );+ });++ it('crosses a page boundary as the arrow key does', async () => {+ const selected = createImageItem('boundary-reordered', '2026-07-20T00:00:01.000Z');+ const neighbor = createImageItem('boundary-reordered-neighbor', '2026-07-19T00:00:00.000Z');+ setGalleryValues({+ galleryPage: 0,+ recentImages: [],+ selectedImage: legacyImage('boundary-reordered', selected.createdAt),+ selectedImageName: 'boundary-reordered',+ selectedImageQuery: { ...deepQuery, page: 5 },+ });+ mocks.galleryItemPages = Array.from({ length: 6 }, (_unused, index) => ({+ items: index === 2 ? [neighbor] : [],+ total: 180,+ }));+ mocks.verifiedGalleryPage = {+ index: 119,+ offset: 60,+ page: { items: [selected], offset: 60, total: 180 },+ total: 180,+ };++ await render();+ await vi.waitFor(() => expect(arrow('Show next item')).not.toBeNull());+ await click(arrow('Show next item')!);++ await vi.waitFor(() =>+ expect(mocks.commands.gallery.selectItem).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'image', name: 'boundary-reordered-neighbor' }),+ undefined,+ 2,+ true+ )+ );+ });++ it('shows no arrows while comparing', async () => {+ setGalleryValues({ compareImage: legacyImage('oldest', '2026-07-19T00:00:00.000Z') });++ await render();++ expect(arrow('Show next item')).toBeNull();+ expect(arrow('Show previous item')).toBeNull();+ });+});+describe('preview keyboard navigation boundary', () => {it.each(['starred strip', 'local recent'] as const)('waits for a missing preceding page before stepping to a %s item',@@ -2795,7 +2879,7 @@ describe('preview keyboard navigation boundary', () => {await render();await pressArrow('ArrowLeft');expect(mocks.commands.account.updateProjectPreferences).toHaveBeenCalledExactlyOnceWith({- showProgressImagesInViewer: true,+ viewerAutoSwitch: 'progress',});await rerender();expect(followControls.pinnedSessionId).toBe('queue-item-live:1');@@ -2804,7 +2888,7 @@ describe('preview keyboard navigation boundary', () => {it('steps right off the followed session onto the first saved item, and never onto waiting slots', async () => {mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2, 3], completedBackendItemIds: [1, 2] }];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.project.widgetInstances.gallery.state.values.recentImages = mocks.recentImages.map((image) => ({...image,sourceQueueItemId: 'queue-item-live',@@ -2836,7 +2920,7 @@ describe('preview keyboard navigation boundary', () => {];// A batch of three: the first slot finished, the second runs, the third waits.mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2, 3], completedBackendItemIds: [1] }];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.runningProgressTargets = [{ itemIndex: 2, queueItemId: queueItem.id }];await render();@@ -2866,7 +2950,7 @@ describe('preview keyboard navigation boundary', () => {);// Stepping away pauses live-follow, as any deliberate selection does in the workbench.- mocks.project.settings.showProgressImagesInViewer = false;+ mocks.project.settings.viewerAutoSwitch = 'off';await commitLastSelection();// The batch hands off between presses: the second slot finishes and the third starts.mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2, 3], completedBackendItemIds: [1, 2] }];@@ -2899,7 +2983,7 @@ describe('preview keyboard navigation boundary', () => {selectedImageQuery: { ...deepQuery, page: 5 },});mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2], completedBackendItemIds: [1] }];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.runningProgressTargets = [{ itemIndex: 2, queueItemId: queueItem.id }];await render();@@ -2918,7 +3002,7 @@ describe('preview keyboard navigation boundary', () => {it('renders the live frame with the standard media chrome: footer up, no badge, item border', async () => {mocks.project.queue.items = [queueItem];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });mocks.useProgressImage.mockReturnValue({dataUrl: 'data:image/png;base64,',@@ -2945,7 +3029,7 @@ describe('preview keyboard navigation boundary', () => {};mocks.project.widgetInstances.gallery.state.values.recentImages = [...mocks.recentImages, liveBoardImage];mocks.project.queue.items = [{ ...queueItem, snapshot: { ...queueItem.snapshot, galleryBoardId: 'board-live' } }];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });await render();@@ -2965,7 +3049,7 @@ describe('preview keyboard navigation boundary', () => {// Keep settling results in the single live frame after backend completion and before gallery arrival; do not// tile them.mocks.project.queue.items = [queueItem];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });mocks.runningProgressTargets = [];mocks.useProgressImage.mockReturnValue({@@ -2984,7 +3068,7 @@ describe('preview keyboard navigation boundary', () => {it('keeps the same-root preview through child gaps and browser focus changes until the next denoising step', async () => {mocks.project.queue.items = [queueItem];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';const visibilityStateDescriptor = Object.getOwnPropertyDescriptor(document, 'visibilityState');const listeners = new Map<string, Set<(payload: never) => void>>();@@ -3215,7 +3299,7 @@ describe('preview keyboard navigation boundary', () => {it("shows the followed slot's own frame even when the store-wide latest frame is gone", async () => {// Retain another live slot's frame when a neighboring batch releases its latest frame.mocks.project.queue.items = [queueItem];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });mocks.useProgressImage.mockReturnValue(null);mocks.slotProgressImage = { dataUrl: 'data:image/png;base64,video-step', height: 64, width: 64 };@@ -3227,7 +3311,7 @@ describe('preview keyboard navigation boundary', () => {it('keeps the selected gallery image when no root is followed and latest frame belongs to another root', async () => {mocks.project.queue.items = [queueItem];- mocks.project.settings.showProgressImagesInViewer = false;+ mocks.project.settings.viewerAutoSwitch = 'off';mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: queueItem.id });mocks.useProgressImage.mockReturnValue({dataUrl: 'data:image/png;base64,other-root',@@ -3248,7 +3332,7 @@ describe('preview keyboard navigation boundary', () => {// Multi-GPU: slot 1 completed and is settling, slot 2 is still streaming.// The single-frame preview must show slot 2 live, not slot 1's static frame.mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2] }];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });mocks.runningProgressTargets = [{ itemIndex: 2, queueItemId: 'queue-item-live' }];mocks.useProgressImage.mockReturnValue({@@ -3268,7 +3352,7 @@ describe('preview keyboard navigation boundary', () => {it("bridges to the next slot of a batch with the previous slot's last frame", async () => {// Bridge a newly followed frameless slot with the previous frame until its first progress arrives.mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2], completedBackendItemIds: [1] }];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 2, queueItemId: 'queue-item-live' });mocks.useProgressImage.mockReturnValue({dataUrl: 'data:image/png;base64,slot-one',@@ -3286,7 +3370,7 @@ describe('preview keyboard navigation boundary', () => {it('keeps every concurrent session in the filmstrip, follows the newest session, and pins on request', async () => {mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2] }];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.runningProgressTargets = [{ queueItemId: queueItem.id, itemIndex: 1 },{ queueItemId: queueItem.id, itemIndex: 2 },@@ -3334,7 +3418,7 @@ describe('preview keyboard navigation boundary', () => {it('keeps live previews available during similarity search and temporary comparison override', async () => {mocks.project.queue.items = [queueItem];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.runningProgressTargets = [{ queueItemId: queueItem.id, itemIndex: 1 }];mocks.slotProgressImage = { dataUrl: 'data:image/png;base64,live', width: 64, height: 64 };const values = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;@@ -3368,7 +3452,7 @@ describe('preview keyboard navigation boundary', () => {it('restores comparison after live activity ends and allows comparison with live preference enabled while idle', async () => {const values = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;values.compareImage = mocks.recentImages[1];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';await render();expect(host!.textContent).toContain('widgets.preview.exitCompare');mocks.project.queue.items = [queueItem];@@ -3382,7 +3466,7 @@ describe('preview keyboard navigation boundary', () => {});it('keeps pinned live controls and footer inside the widget without saved-image arrows or zero count', async () => {mocks.project.queue.items = [queueItem];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.runningProgressTargets = [{ queueItemId: queueItem.id, itemIndex: 1 }];await render();await act(() => followControls.pin('queue-item-live:1'));@@ -3655,7 +3739,7 @@ describe('preview deletion confirmation', () => {const confirmation = dialog.textContent;mocks.project.queue.items = [queueItem];- mocks.project.settings.showProgressImagesInViewer = true;+ mocks.project.settings.viewerAutoSwitch = 'progress';mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });mocks.useProgressImage.mockReturnValue({dataUrl: 'data:image/png;base64,',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 61346aab0e..052dacd5b4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -17,7 +17,7 @@ import {getGalleryPage,getGallerySelectedImageQuery,getGallerySemanticImageQuery,- getGallerySelectedBoardId,+ getGalleryListingBoardId,getGallerySettings,getSelectedGalleryItemFromValues,getBoundedRecentImages,@@ -90,6 +90,7 @@ import {type PreviewVideoFrameCopyResult,} from './PreviewFrame';import { previewHeaderStore, previewStageStore, type PreviewZoomCommands } from './previewHeaderStore';+import { PREVIEW_NAV_STAGE_CSS, PreviewNavButtons } from './PreviewNavButtons';import {getPreviewComparisonMode,getPreviewFilmstripVisible,@@ -242,7 +243,7 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {...galleryBoardsOptions(getGalleryListingBoardsQuery(gallerySettings)),enabled: gallerySemanticQuery !== null,});- const galleryBoardId = getGallerySelectedBoardId(galleryValues, galleryBoardsQuery.data ?? EMPTY_BOARDS);+ const galleryBoardId = getGalleryListingBoardId(galleryValues, galleryBoardsQuery.data ?? EMPTY_BOARDS);const hostBoards = useHostGalleryBoards(boardsQuery.data);const boards = boardsQuery.data === undefined ? fallbackBoards : hostBoards;const boardName = getBoardName(@@ -847,7 +848,7 @@ const SelectedMediaPreview = ({<PreviewMediaScaffold>{/* The stage wrapper is the Details popover's boundary for images andvideos alike; the frame inside fills it, so their rects coincide. */}- <Flex ref={setStageElement} direction="column" flex="1" minH="0">+ <Flex ref={setStageElement} css={PREVIEW_NAV_STAGE_CSS} direction="column" flex="1" minH="0" position="relative"><PreviewFramedragItem={dragItem}frameHeight={frameHeight}@@ -868,6 +869,7 @@ const SelectedMediaPreview = ({videoControllerRef={videoControllerRef}onContextMenu={onContextMenu}/>+ {swipe ? <PreviewNavButtons isVideo={item.kind === 'video'} navigation={swipe} /> : null}</Flex>{filmstrip ? <PreviewFilmstrip {...filmstrip} density={density} selectedItemKey={toGalleryItemKey(item)} /> : null}</PreviewMediaScaffold>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsxindex 04c1144f14..66b29e7e9a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewZoomMenu.tsx@@ -6,7 +6,7 @@ import { ChevronDownIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-import type { PreviewZoomControls } from './previewHeaderStore';+import { getActualZoomLimits, type PreviewZoomControls } from './previewHeaderStore';const ZOOM_PRESETS = [100, 200, 400] as const;const MENU_POSITIONING = { placement: 'bottom-start' } as const;@@ -55,8 +55,7 @@ export const PreviewZoomMenu = ({ zoom }: { zoom: PreviewZoomControls }) => {{ZOOM_PRESETS.map((preset) => (<ZoomPresetItemkey={preset}- // A preset the fit already exceeds would only snap back to fit.- disabled={zoom.fitPercent !== null && preset <= zoom.fitPercent}+ disabled={isPresetUnreachable(preset, zoom.fitPercent)}isCurrent={zoom.isZoomed && percent === preset}percent={preset}onZoomTo={zoom.zoomTo}@@ -69,6 +68,22 @@ export const PreviewZoomMenu = ({ zoom }: { zoom: PreviewZoomControls }) => {);};+/**+ * A preset outside the loupe's zoom limits cannot be reached, and the preset equal to fit is fit itself, its own menu+ * item. Below an enlarging fit, presets down to 100% stay offered. Judged on the unrounded fit: a 100.2% fit reads as+ * 100% yet is not the image's own size.+ */+const isPresetUnreachable = (preset: number, fitPercent: number | null): boolean => {+ if (fitPercent === null) {+ return false;+ }++ const { max, min } = getActualZoomLimits(fitPercent / 100);+ const actualZoom = preset / 100;++ return preset === fitPercent || actualZoom < min || actualZoom > max;+};+const ZoomPresetItem = ({disabled,isCurrent,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsxindex 8d4ad57fa2..52967ee2a5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx@@ -20,7 +20,7 @@ interface LivePreviewFollow {* else null.*/followedSessionId: string | null;- /** Turns live-follow on and pins `sessionId`: a tile click, or an arrow step onto a tile. */+ /** Sets Auto-switch to In progress and pins `sessionId`: a tile click, or an arrow step onto a tile. */follow(sessionId: string): void;pin(sessionId: string): void;showAll(): void;@@ -33,7 +33,8 @@ export const LivePreviewFollowProvider = ({ children }: { children: ReactNode })const { projectId, items, enabled } = useActiveProjectSelector((project) => ({projectId: project.id,items: project.queue.items,- enabled: project.settings.showProgressImagesInViewer,+ // Live frames show only on In progress; Newest switches to finished results alone.+ enabled: project.settings.viewerAutoSwitch === 'progress',}));const running = useActiveProgressTargets();const followed = useFollowedProgressTargets();@@ -72,7 +73,7 @@ export const LivePreviewFollowProvider = ({ children }: { children: ReactNode })pinnedSessionId,followedSessionId,follow: (sessionId) => {- account.updateProjectPreferences({ showProgressImagesInViewer: true });+ account.updateProjectPreferences({ viewerAutoSwitch: 'progress' });setSelection({ projectId, sessionId });},pin: (sessionId) => setSelection({ projectId, sessionId }),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.tsindex a2d8ddd6e7..d50b8ec144 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts@@ -7,7 +7,7 @@ import { createExternalStore } from '@platform/state/externalStore';/** The loupe's commands, published once per selection; the readout lives in `previewStageStore`. */export interface PreviewZoomCommands {reset: () => void;- /** Zoom to a fraction of the image's own pixels (1 = 100%), never below fit. */+ /** Zoom to a fraction of the image's own pixels (1 = 100%), within `getActualZoomLimits`. */zoomTo: (actualZoom: number) => void;}@@ -16,13 +16,26 @@ export type PreviewZoomControls = PreviewZoomCommands & PreviewZoomReadout;/** What the loupe shows, as percents of the image's own pixels. */export interface PreviewZoomReadout {- /** What the fitted image shows, for the menu's presets. */+ /** What the fitted image shows, unrounded, for the menu's presets. */fitPercent: number | null;isZoomed: boolean;/** What is on screen right now. */percent: number | null;}+/** Max zoom, as a fraction of the image's actual pixel size. */+const MAX_ACTUAL_ZOOM = 8;++/**+ * The zoom range, as fractions of the image's own pixels, for a fit showing it at `fitRatio`: never below the smaller+ * of fit and 100%, so an image the fit enlarges can still be seen at its own size, and never past `MAX_ACTUAL_ZOOM` or+ * fit, whichever is larger. The loupe enforces it; the zoom menu offers only presets inside it.+ */+export const getActualZoomLimits = (fitRatio: number): { max: number; min: number } => ({+ max: Math.max(fitRatio, MAX_ACTUAL_ZOOM),+ min: Math.min(fitRatio, 1),+});+/** Where the selection sits in its board, for the Details popover's header line. */export interface PreviewItemPosition {boardItemCount: number;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsxindex 168e2c973c..d2fd68395d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx@@ -1,10 +1,10 @@/* eslint-disable react/refs */-import { WHEEL_ZOOM_STEP } from '@workbench/panZoom';-import { act } from 'react';+import { WHEEL_ZOOM_SNAP_IDLE_MS, WHEEL_ZOOM_STEP } from '@workbench/panZoom';+import { act, createRef, type RefObject } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';-import { usePreviewLoupe } from './usePreviewLoupe';+import { usePreviewLoupe, type PreviewLoupeControls, type PreviewZoomState } from './usePreviewLoupe';let host: HTMLDivElement | null = null;let root: Root | null = null;@@ -18,8 +18,23 @@ const interact = (action: () => void): Promise<void> =>});});-const Harness = ({ naturalWidth = 200, token = 'a' }: { naturalWidth?: number; token?: string }) => {- const loupe = usePreviewLoupe({ enabled: true, naturalWidth });+const nextFrame = (): Promise<void> =>+ new Promise((resolve) => {+ requestAnimationFrame(() => resolve());+ });++const Harness = ({+ controlsRef,+ naturalWidth = 200,+ onZoomChange,+ token = 'a',+}: {+ controlsRef?: RefObject<PreviewLoupeControls | null>;+ naturalWidth?: number;+ onZoomChange?: (state: PreviewZoomState) => void;+ token?: string;+}) => {+ const loupe = usePreviewLoupe({ controlsRef, enabled: true, naturalWidth, onZoomChange });loupe.syncDisplayedSource(token);return (@@ -54,11 +69,24 @@ afterEach(async () => {* box's origin sits at (100, 75) in stage space. Coordinates below are given in* stage space and converted to client space against the live rect.*/-const mountHarness = async (): Promise<{ content: HTMLElement; stage: HTMLElement }> => {+const mountHarness = async ({+ controlsRef,+ naturalWidth,+ onZoomChange,+}: {+ controlsRef?: RefObject<PreviewLoupeControls | null>;+ naturalWidth?: number;+ onZoomChange?: (state: PreviewZoomState) => void;+} = {}): Promise<{+ content: HTMLElement;+ stage: HTMLElement;+}> => {host = document.createElement('div');document.body.append(host);root = createRoot(host);- await interact(() => root?.render(<Harness />));+ await interact(() =>+ root?.render(<Harness controlsRef={controlsRef} naturalWidth={naturalWidth} onZoomChange={onZoomChange} />)+ );return {content: host.querySelector<HTMLElement>('[data-testid="content"]')!,@@ -245,3 +273,130 @@ describe('usePreviewLoupe across image swaps', () => {expect(content.style.imageRendering).toBe('');});});++const wheelAt = (stage: HTMLElement, deltaY: number, { ctrlKey = false }: { ctrlKey?: boolean } = {}): void => {+ const rect = stage.getBoundingClientRect();++ stage.dispatchEvent(+ new WheelEvent('wheel', {+ bubbles: true,+ cancelable: true,+ clientX: rect.left + stage.clientWidth / 2,+ clientY: rect.top + stage.clientHeight / 2,+ ctrlKey,+ deltaY,+ })+ );+};++/** The wheel delta that takes actual zoom from `from` to `to`, unsnapped. */+const deltaBetween = (from: number, to: number): number => -Math.log(to / from) / WHEEL_ZOOM_STEP;++describe('usePreviewLoupe below fit', () => {+ // A 100px-wide image fitted into the 200px content box shows at 200%.+ it('shows an image the fit enlarges at its own size, centred, when asked for 100%', async () => {+ const controlsRef = createRef<PreviewLoupeControls>();+ const { content } = await mountHarness({ controlsRef, naturalWidth: 100 });++ await interact(() => controlsRef.current?.zoomTo(1));++ // Half the fitted size, so 100×75 in the 400×300 stage: its origin at (150, 112.5), from the box's (100, 75).+ expect(content.style.transform).toBe('translate(50px, 37.5px) scale(0.5)');+ expect(content.getBoundingClientRect().width).toBeCloseTo(100, 6);+ });++ // A 199.6px-wide image fitted into the 200px content box shows at 100.2%.+ it('reports a fit just past 100% unrounded, and reaches the image at its own size from it', async () => {+ const controlsRef = createRef<PreviewLoupeControls>();+ const onZoomChange = vi.fn<(state: PreviewZoomState) => void>();+ await mountHarness({ controlsRef, naturalWidth: 199.6, onZoomChange });++ await vi.waitFor(() => expect(onZoomChange.mock.lastCall?.[0]).toMatchObject({ isZoomed: false, percent: 100 }));+ expect(onZoomChange.mock.lastCall?.[0].fitPercent).toBeCloseTo(100.2, 2);++ await interact(() => controlsRef.current?.zoomTo(1));++ await vi.waitFor(() => expect(onZoomChange.mock.lastCall?.[0]).toMatchObject({ isZoomed: true, percent: 100 }));+ });++ // A 4000px-wide image fitted into the 200px content box shows at 5%, so each pixel of width is 0.025%.+ it('republishes the fit once a resize moves it by 0.1%, not on every pixel', async () => {+ const onZoomChange = vi.fn<(state: PreviewZoomState) => void>();+ const { content } = await mountHarness({ naturalWidth: 4000, onZoomChange });+ await vi.waitFor(() => expect(onZoomChange).toHaveBeenCalled());+ const published = onZoomChange.mock.calls.length;++ // The resize is observed in one frame and its readout batched into the next.+ await act(async () => {+ content.style.width = '201px';+ await nextFrame();+ await nextFrame();+ await nextFrame();+ });+ expect(onZoomChange).toHaveBeenCalledTimes(published);++ await act(async () => {+ content.style.width = '204px';+ await vi.waitFor(() => expect(onZoomChange).toHaveBeenCalledTimes(published + 1));+ });+ expect(onZoomChange.mock.lastCall?.[0].fitPercent).toBeCloseTo(5.1, 6);+ });++ it('lets wheel zoom-out go below fit but stop at 100%', async () => {+ const { content, stage } = await mountHarness({ naturalWidth: 100 });++ await interact(() => wheelAt(stage, 2000));++ expect(content.style.transform).toBe('translate(50px, 37.5px) scale(0.5)');+ });++ it('still stops at fit when the fit shows the image below its own size', async () => {+ const { content, stage } = await mountHarness({ naturalWidth: 400 });++ await interact(() => wheelAt(stage, 2000));++ expect(content.style.transform).toBe('');+ });+});++describe('usePreviewLoupe wheel snapping', () => {+ // A 400px-wide image fitted into the 200px content box shows at 50%, so scale 2 is 100%.+ it('rests on 100% of the image across small wheel steps, then continues from the wheel', async () => {+ const { content, stage } = await mountHarness({ naturalWidth: 400 });++ await interact(() => wheelAt(stage, deltaBetween(0.5, 0.99)));+ expect(content.style.transform).toContain('scale(2)');++ await interact(() => wheelAt(stage, -5));+ expect(content.style.transform).toContain('scale(2)');++ // The intended zoom is now 99% × e^(0.0015 × 25) ≈ 102.8%, outside the 2% tolerance.+ await interact(() => wheelAt(stage, -20));+ const scale = Number(/scale\(([^)]+)\)/.exec(content.style.transform)?.[1]);+ expect(scale / 2).toBeCloseTo(0.99 * Math.exp(WHEEL_ZOOM_STEP * 25), 6);+ });++ it('starts a new wheel gesture from 100% after a pause, releasing the movement left over on it', async () => {+ const { content, stage } = await mountHarness({ naturalWidth: 400 });++ // Rests on 100% with the wheel asking for 101%.+ await interact(() => wheelAt(stage, deltaBetween(0.5, 1.01)));+ expect(content.style.transform).toContain('scale(2)');++ // Within the gesture, -8 would ask for 101% × e^0.012 ≈ 102.2% and leave 100%; after a pause it starts from the+ // 100% shown, asks for about 101.2%, and stays.+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, WHEEL_ZOOM_SNAP_IDLE_MS + 50);+ });+ await interact(() => wheelAt(stage, -8));+ expect(content.style.transform).toContain('scale(2)');+ });++ it('does not snap a trackpad pinch', async () => {+ const { content, stage } = await mountHarness({ naturalWidth: 400 });++ await interact(() => wheelAt(stage, deltaBetween(0.5, 0.99) / 4, { ctrlKey: true }));++ expect(content.style.transform).not.toContain('scale(2)');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.tsindex 6af119bdfa..fd727b6f2f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts@@ -3,7 +3,9 @@ import {midpointOf,panBy,pinchZoomAtPoints,+ snapWheelZoom,WHEEL_ZOOM_STEP,+ type WheelZoomSnap,zoomAtPoint as calculateZoomAtPoint,type PanZoomPoint,} from '@workbench/panZoom';@@ -18,26 +20,28 @@ import {} from 'react';import { capturePointer, releasePointer, trackPointerDown } from './loupeGestures';+import { getActualZoomLimits } from './previewHeaderStore';/*** Use the whole stage for wheel zoom, drag pan, fit/100% toggle, and touch pinch. Apply rAF-batched CSS transforms- * outside React; publish only rounded actual-pixel zoom, with scale 1 meaning fit.+ * outside React; publish rounded actual-pixel zoom and the exact fit, with scale 1 meaning fit, and re-render only when+ * zooming starts or ends. Zoom never goes below the smaller of fit and 100%, so an image the fit enlarges can still be+ * seen at its own size.*/-/** Max zoom, as a fraction of the image's actual pixel size. */-const MAX_ACTUAL_ZOOM = 8;/** Switch to pixelated rendering at/above this actual-pixel zoom. */const PIXELATED_ACTUAL_ZOOM = 2;export interface PreviewLoupeControls {reset(): void;- /** Zoom to a fraction of the image's own pixels (1 = 100%) about the stage centre, never below fit. */+ /** Zoom to a fraction of the image's own pixels (1 = 100%) about the stage centre, within the zoom limits. */zoomTo(actualZoom: number): void;zoomToActual(): void;}/** What the loupe shows, for a readout outside the stage: percents of the image's own pixels. */export interface PreviewZoomState {+ /** Unrounded, so a preset just past fit is still told apart from fit itself. */fitPercent: number | null;isZoomed: boolean;percent: number | null;@@ -94,7 +98,9 @@ export const usePreviewLoupe = ({/** Whether the touch session's first pointer landed on the draggable image. */const dragCandidateRef = useRef(false);const lastSourceTokenRef = useRef<string | null | undefined>(undefined);- const [zoomState, setZoomState] = useState<PreviewZoomState>(FIT_UNMEASURED);+ /** Wheel zoom's snap memory, in actual zoom, with the fit ratio it was measured at; other zoom changes drop it. */+ const wheelSnapRef = useRef<{ fitRatio: number; snap: WheelZoomSnap } | null>(null);+ const [isZoomed, setIsZoomed] = useState(false);const publishedRef = useRef<PreviewZoomState>(FIT_UNMEASURED);// Keep gesture/ref identity stable across images; callback cleanup must not cancel the frame clearing an old// transform.@@ -118,14 +124,14 @@ export const usePreviewLoupe = ({(scale: number) => {const fitRatio = measureFitRatio();const next: PreviewZoomState = {- fitPercent: fitRatio === null ? null : Math.round(fitRatio * 100),+ fitPercent: fitRatio === null ? null : fitRatio * 100,isZoomed: scale !== 1,percent: fitRatio === null ? null : Math.round(fitRatio * scale * 100),};const previous = publishedRef.current;if (- previous.fitPercent === next.fitPercent &&+ getFitStep(previous.fitPercent) === getFitStep(next.fitPercent) &&previous.isZoomed === next.isZoomed &&previous.percent === next.percent) {@@ -133,7 +139,7 @@ export const usePreviewLoupe = ({}publishedRef.current = next;- setZoomState(next);+ setIsZoomed(next.isZoomed);onZoomChangeRef.current?.(next);},[measureFitRatio]@@ -190,6 +196,7 @@ export const usePreviewLoupe = ({// Discard old-image gestures even at fit so remaining touches cannot transform the new image.panPointerRef.current = null;pinchRef.current = null;+ wheelSnapRef.current = null;transformRef.current = { scale: 1, tx: 0, ty: 0 };// Schedule reset through apply so intervening wheel updates win and fitted percent uses current layout.apply();@@ -219,12 +226,19 @@ export const usePreviewLoupe = ({[apply]);- /** Never below fit, never past `MAX_ACTUAL_ZOOM` of the image's own pixels. */+ /** Keeps the scale, where 1 is fit, within the zoom limits. */const constrainScale = useCallback((scale: number): number => {const renderedWidth = contentRef.current?.clientWidth ?? 0;- const maxScale = renderedWidth > 0 ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidthRef.current) / renderedWidth) : 1;+ const naturalWidth = naturalWidthRef.current;- return Math.max(1, Math.min(scale, maxScale));+ if (renderedWidth <= 0 || naturalWidth <= 0) {+ return 1;+ }++ const fitRatio = renderedWidth / naturalWidth;+ const { max, min } = getActualZoomLimits(fitRatio);++ return Math.max(min / fitRatio, Math.min(scale, max / fitRatio));}, []);/** Zoom keeping the content point under the given stage-space coordinates fixed. */@@ -257,6 +271,7 @@ export const usePreviewLoupe = ({// from the transform it started on, so its next move would undo the command.const reset = useCallback(() => {pinchRef.current = null;+ wheelSnapRef.current = null;setTransform({ scale: 1, tx: 0, ty: 0 });}, [setTransform]);@@ -270,10 +285,11 @@ export const usePreviewLoupe = ({}pinchRef.current = null;+ wheelSnapRef.current = null;zoomAroundPoint(stage.clientWidth / 2,stage.clientHeight / 2,- Math.max(1, (actualZoom * naturalWidthRef.current) / content.clientWidth)+ (actualZoom * naturalWidthRef.current) / content.clientWidth);},[zoomAroundPoint]@@ -337,6 +353,7 @@ export const usePreviewLoupe = ({const center = midpointOf(first, second);panPointerRef.current = null;+ wheelSnapRef.current = null;pinchRef.current = {originLeft,originTop,@@ -382,7 +399,7 @@ export const usePreviewLoupe = ({const last = remaining[0];const lastPoint = last === undefined ? undefined : pointers.get(last);- if (last !== undefined && lastPoint && transformRef.current.scale !== 1) {+ if (last !== undefined && lastPoint && transformRef.current.scale > 1) {beginPan(last, lastPoint);}@@ -411,14 +428,31 @@ export const usePreviewLoupe = ({event.preventDefault();const rect = node.getBoundingClientRect();const { scale } = transformRef.current;- // Trackpad pinch arrives as ctrl+wheel with finer deltas.- const sensitivity = event.ctrlKey ? WHEEL_ZOOM_STEP * 4 : WHEEL_ZOOM_STEP;+ const fitRatio = measureFitRatio();+ const stageX = event.clientX - rect.left;+ const stageY = event.clientY - rect.top;++ // Trackpad pinch arrives as ctrl+wheel with finer deltas; like a touch pinch, it does not snap.+ if (event.ctrlKey || fitRatio === null) {+ wheelSnapRef.current = null;+ zoomAroundPoint(stageX, stageY, scale * Math.exp(-event.deltaY * WHEEL_ZOOM_STEP * 4));+ return;+ }- zoomAroundPoint(- event.clientX - rect.left,- event.clientY - rect.top,- scale * Math.exp(-event.deltaY * sensitivity)+ // Snap points are actual zoom (100% = the image's own pixels), so convert from and to fit-relative scale.+ const remembered = wheelSnapRef.current;+ const snap = snapWheelZoom(+ remembered?.fitRatio === fitRatio ? remembered.snap : null,+ scale * fitRatio,+ event.deltaY,+ {+ constrainZoom: (actualZoom) => constrainScale(actualZoom / fitRatio) * fitRatio,+ now: event.timeStamp,+ });++ wheelSnapRef.current = { fitRatio, snap };+ zoomAroundPoint(stageX, stageY, snap.zoom / fitRatio);};// Track pointer positions/releases document-wide so off-stage movement cannot leave phantom pinch origins;@@ -450,7 +484,7 @@ export const usePreviewLoupe = ({}};},- [endPointer, zoomAroundPoint]+ [constrainScale, endPointer, measureFitRatio, zoomAroundPoint]);/**@@ -494,7 +528,8 @@ export const usePreviewLoupe = ({return;}- if (pointers.size !== 1 || transformRef.current.scale === 1) {+ // At or below fit the image fits the stage, so there is nothing to pan to.+ if (pointers.size !== 1 || transformRef.current.scale <= 1) {return;}@@ -566,11 +601,8 @@ export const usePreviewLoupe = ({const rect = stage.getBoundingClientRect();- zoomAroundPoint(- event.clientX - rect.left,- event.clientY - rect.top,- Math.max(1, naturalWidth / content.clientWidth)- );+ wheelSnapRef.current = null;+ zoomAroundPoint(event.clientX - rect.left, event.clientY - rect.top, naturalWidth / content.clientWidth);};if (!enabled) {@@ -586,7 +618,7 @@ export const usePreviewLoupe = ({return {contentRefCallback,- isZoomed: zoomState.isZoomed,+ isZoomed,reset,stageProps: {onDoubleClick: handleDoubleClick,@@ -599,3 +631,10 @@ export const usePreviewLoupe = ({};const FIT_UNMEASURED: PreviewZoomState = { fitPercent: null, isZoomed: false, percent: null };++/**+ * A resize republishes the fit only once it moves by 0.1%, not on every pixel, which still tells a 100.2% fit from an+ * exact 100%.+ */+const getFitStep = (fitPercent: number | null): number | null =>+ fitPercent === null ? null : Math.round(fitPercent * 10);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/shared/AutoSwitchMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/shared/AutoSwitchMenu.tsxnew file mode 100644index 0000000000..5467f1ffe5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/shared/AutoSwitchMenu.tsx@@ -0,0 +1,102 @@+import type { SystemStyleObject } from '@chakra-ui/react';+import type { ViewerAutoSwitchMode } from '@workbench/settings/contracts';++import { Icon, Menu, Portal, Text } from '@chakra-ui/react';+import { Button } from '@platform/ui/Button';+import { MenuContent } from '@platform/ui/Menu';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { CheckIcon, SparklesIcon } from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++/** The Preview's modes, which the Canvas staging bar shares. */+type AutoSwitchMode = ViewerAutoSwitchMode;++const AUTO_SWITCH_MODES: readonly AutoSwitchMode[] = ['off', 'progress', 'latest'];++/** Both widgets name the modes with the staging bar's keys, so existing translations carry over. */+const MODE_LABEL_KEYS: Record<AutoSwitchMode, string> = {+ latest: 'widgets.canvas.staging.autoSwitchLatest',+ off: 'widgets.canvas.staging.autoSwitchOff',+ progress: 'widgets.canvas.staging.autoSwitchProgress',+};++interface AutoSwitchMenuProps {+ value: AutoSwitchMode;+ onChange: (mode: AutoSwitchMode) => void;+ positioning: { placement: 'bottom-end' | 'top-end' };+ /** `full` shows the current mode beside the icon; `compact` is the icon alone, named by its tooltip. */+ density: 'compact' | 'full';+ /** A host's container rules for the trigger and its mode text, such as the staging bar's narrow collapse. */+ triggerCss?: SystemStyleObject;+ valueCss?: SystemStyleObject;+}++/** What switches the view to new work: a menu of the modes, with the current one checked. */+export const AutoSwitchMenu = ({+ density,+ positioning,+ triggerCss,+ value,+ valueCss,+ onChange,+}: AutoSwitchMenuProps) => {+ const { t } = useTranslation();+ const ids = useTooltipTriggerIds();+ const title = t('widgets.canvas.staging.autoSwitch');+ // Names the current mode on the trigger and its tooltip, so a compact, icon-only trigger still says it.+ const currentLabel = t('widgets.canvas.staging.autoSwitchCurrent', { mode: t(MODE_LABEL_KEYS[value]) });+ const isOff = value === 'off';+ const handleValueChange = useCallback(+ ({ value }: { value: string }) => {+ const mode = AUTO_SWITCH_MODES.find((candidate) => candidate === value);++ if (mode) {+ onChange(mode);+ }+ },+ [onChange]+ );++ return (+ <Menu.Root ids={ids} positioning={positioning}>+ <Tooltip content={currentLabel} ids={ids}>+ <Menu.Trigger asChild>+ <Button+ aria-label={currentLabel}+ css={triggerCss}+ data-auto-switch={value}+ minW="unset"+ px="2"+ variant="ghost"+ >+ {/* Off dims the icon too, so a selection turning Auto-switch off shows on a compact trigger. */}+ <Icon as={SparklesIcon} boxSize="3.5" color={isOff ? 'fg.subtle' : undefined} opacity={isOff ? 0.5 : 1} />+ {density === 'full' ? (+ <Text css={valueCss} fontSize="md">+ {t(MODE_LABEL_KEYS[value])}+ </Text>+ ) : null}+ </Button>+ </Menu.Trigger>+ </Tooltip>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="8rem" py="1">+ <Menu.RadioItemGroup value={value} onValueChange={handleValueChange}>+ <Menu.ItemGroupLabel>{title}</Menu.ItemGroupLabel>+ {AUTO_SWITCH_MODES.map((mode) => (+ <Menu.RadioItem key={mode} value={mode}>+ <Menu.ItemIndicator>+ <CheckIcon size={12} />+ </Menu.ItemIndicator>+ <Menu.ItemText fontSize="md">{t(MODE_LABEL_KEYS[mode])}</Menu.ItemText>+ </Menu.RadioItem>+ ))}+ </Menu.RadioItemGroup>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex ec38b4694f..4abf6dc11a 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -35,7 +35,7 @@ import type { CanvasProjectMutation } from './canvasProjectMutations';import { createEmptyCanvasDocument } from './canvasMigration';import { getCanvasStagingCandidateFingerprint, getCanvasStagingSlots } from './canvasStagingView';-import { layoutPresets } from './layoutPresets';+import { getLayoutPresetLabel, layoutPresets } from './layoutPresets';import { resolveSavedLayoutPreset } from './layoutPresetSnapshots';import { PROJECT_EVENT_LIMIT } from './projectEvents';import { getActiveProjectGraph } from './projectWorkflows';@@ -1195,6 +1195,49 @@ describe('adopting a project from another realm', () => {expect(normalized.queue.items).toEqual([]);});+ it('loads a gallery saved with an all-boards scope but no search on the selected board', () => {+ const project = createInitialWorkbenchState().projects[0]!;+ const galleryInstance = Object.values(project.widgetInstances).find((instance) => instance.typeId === 'gallery')!;+ const saved = {+ ...project,+ widgetInstances: {+ ...project.widgetInstances,+ [galleryInstance.id]: {+ ...galleryInstance,+ state: { ...galleryInstance.state, values: { ...galleryInstance.state.values, searchScope: 'all' } },+ },+ },+ } as Project;++ expect(getProjectWidgetValues(normalizeWorkbenchProject(saved), 'gallery').searchScope).toBe('board');+ });++ it('loads a project saved before Auto-switch with it Off and without the retired pause stamp', () => {+ const project = createInitialWorkbenchState().projects[0]!;+ const { viewerAutoSwitch: _mode, ...settings } = project.settings;+ const galleryInstance = Object.values(project.widgetInstances).find((instance) => instance.typeId === 'gallery')!;+ const legacyProject = {+ ...project,+ settings: { ...settings, showProgressImagesInViewer: true },+ widgetInstances: {+ ...project.widgetInstances,+ [galleryInstance.id]: {+ ...galleryInstance,+ state: {+ ...galleryInstance.state,+ values: { ...galleryInstance.state.values, liveFollowPausedAt: '2026-06-10T00:00:00.000Z' },+ },+ },+ },+ } as unknown as Project;++ const normalized = normalizeWorkbenchProject(legacyProject);++ expect(normalized.settings.viewerAutoSwitch).toBe('off');+ expect(normalized.settings).not.toHaveProperty('showProgressImagesInViewer');+ expect(getProjectWidgetValues(normalized, 'gallery')).not.toHaveProperty('liveFollowPausedAt');+ });+it('carries the iteration count workflow runs borrowed from Generate over to the workflow widget once', () => {const workflowValuesOf = (candidate: Project) => getProjectWidgetValues(candidate, 'workflow');const withoutWorkflowCount = (candidate: Project): Project => {@@ -2131,6 +2174,36 @@ describe('workbench layout presets', () => {expect(state.account.layoutPresetOrder).toBe(layoutPresetOrder);});+ it('stores no name for a built-in preset saved under its default name in the language shown', () => {+ let state = createInitialWorkbenchState();++ // The edit dialog in German shows Automate as "Arbeitsablauf", its translated default.+ state = workbenchReducer(state, {+ label: 'Arbeitsablauf',+ localizedDefaultLabel: 'Arbeitsablauf',+ presetId: 'automate',+ type: 'renameLayoutPreset',+ });++ expect(state.account.layoutPresetMetadataOverrides?.automate).toBeUndefined();+ expect(resolveSavedLayoutPreset(state.account, 'automate')).toMatchObject({+ label: 'Workflow',+ labelKey: 'topbar.presets.builtInLabels.automate',+ });++ state = workbenchReducer(state, {+ label: 'Nodes',+ localizedDefaultLabel: 'Arbeitsablauf',+ presetId: 'automate',+ type: 'renameLayoutPreset',+ });++ // A renamed preset reads as named in every language.+ expect(state.account.layoutPresetMetadataOverrides?.automate).toEqual({ label: 'Nodes' });+ expect(resolveSavedLayoutPreset(state.account, 'automate')).not.toHaveProperty('labelKey');+ expect(getLayoutPresetLabel(resolveSavedLayoutPreset(state.account, 'automate'), () => 'translated')).toBe('Nodes');+ });+it('moves every project off a deleted custom layout preset', () => {let state = createInitialWorkbenchState();const firstProjectId = state.activeProjectId;@@ -5440,18 +5513,37 @@ describe('workbenchReducer Phase 5 generation flow', () => {);});- it('pauses live-follow when the user selects a saved Gallery image', () => {- let state = createInitialWorkbenchState();+ it.each(['latest', 'progress'] as const)(+ 'turns Auto-switch Off in the same step when the user selects a saved Gallery image under %s',+ (mode) => {+ let state = workbenchReducer(createInitialWorkbenchState(), {+ settings: { viewerAutoSwitch: mode },+ type: 'setActiveProjectSettings',+ });- expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(true);+ state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });- state = workbenchReducer(state, {- item: createGalleryImageItem('selected.png'),- type: 'selectGalleryItem',+ expect(getActiveProject(state).settings.viewerAutoSwitch).toBe('off');+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');+ }+ );++ it('changes only the selection when Auto-switch is already Off', () => {+ let state = workbenchReducer(createInitialWorkbenchState(), {+ settings: { viewerAutoSwitch: 'off' },+ type: 'setActiveProjectSettings',});+ const settings = getActiveProject(state).settings;- expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');+ state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });++ expect(getActiveProject(state).settings).toBe(settings);+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery')).not.toHaveProperty('liveFollowPausedAt');+ });++ it('starts a new project on In progress', () => {+ expect(getActiveProject(createInitialWorkbenchState()).settings.viewerAutoSwitch).toBe('progress');+ expect(createDraftProject([]).settings.viewerAutoSwitch).toBe('progress');});it('clears the Gallery selection while keeping the compare image and navigation stamp', () => {@@ -5492,48 +5584,78 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');});- it('selects a result whose generation was submitted after the manual selection', () => {- vi.useFakeTimers({ now: new Date('2026-06-10T00:00:00.000Z') });-- try {- let state = primeGenerate();- state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });- state = submitGenerate(state);- const earlierItem = getActiveProject(state).queue.items[0];-- vi.setSystemTime(new Date('2026-06-10T00:00:01.000Z'));- state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });- expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);-- // Invoking again is the counter-signal: the user wants to see what they just asked for.- vi.setSystemTime(new Date('2026-06-10T00:00:02.000Z'));- state = submitGenerate(state);- const laterItem = getActiveProject(state).queue.items[0];- expect(laterItem.id).not.toBe(earlierItem.id);- expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(true);-- // The batch already running when the user picked stays out of the way…- state = workbenchReducer(state, {- images: [createImage('earlier.png', earlierItem.id)],- projectId: getActiveProject(state).id,- queueItemId: earlierItem.id,- type: 'routeQueueItemResults',- });- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');+ it.each(['latest', 'progress'] as const)('selects each finished result under %s', (mode) => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { settings: { viewerAutoSwitch: mode }, type: 'setActiveProjectSettings' });+ state = submitGenerate(state);+ const first = getActiveProject(state).queue.items[0]!;+ state = submitGenerate(state);+ const second = getActiveProject(state).queue.items[0]!;+ const projectId = getActiveProject(state).id;- // …while the one submitted after the pick takes the preview when it lands.+ for (const [name, item] of [+ ['first.png', first],+ ['second.png', second],+ ] as const) {state = workbenchReducer(state, {- images: [createImage('later.png', laterItem.id)],- projectId: getActiveProject(state).id,- queueItemId: laterItem.id,+ images: [createImage(name, item.id)],+ projectId,+ queueItemId: item.id,type: 'routeQueueItemResults',});- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:later.png');- } finally {- vi.useRealTimers();+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe(`image:${name}`);}});+ it('leaves a selection alone under Off, and selects a result only when nothing is selected', () => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { settings: { viewerAutoSwitch: 'off' }, type: 'setActiveProjectSettings' });+ state = submitGenerate(state);+ state = submitGenerate(state);+ const [second, first] = getActiveProject(state).queue.items;+ const projectId = getActiveProject(state).id;++ state = workbenchReducer(state, {+ images: [createImage('first.png', first!.id)],+ projectId,+ queueItemId: first!.id,+ type: 'routeQueueItemResults',+ });+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:first.png');++ state = workbenchReducer(state, {+ images: [createImage('second.png', second!.id)],+ projectId,+ queueItemId: second!.id,+ type: 'routeQueueItemResults',+ });+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:first.png');+ });++ it('keeps a manual selection through a later submission and its results', () => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });+ const settings = getActiveProject(state).settings;++ state = submitGenerate(state);+ const queueItem = getActiveProject(state).queue.items[0]!;+ state = workbenchReducer(state, {+ images: [createImage('later.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ videos: [createVideo('later.mp4', queueItem.id)],+ });++ // Submitting no longer touches settings, so the selection the user settled on stays.+ expect(getActiveProject(state).settings).toBe(settings);+ expect(getActiveProject(state).settings.viewerAutoSwitch).toBe('off');+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');+ });+it('selects a finished Gallery video once, so a later result keeps the preview', () => {let state = primeGenerate();state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });@@ -5578,49 +5700,11 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:later.png');});- it('selects only videos from runs submitted after a manual selection', () => {- vi.useFakeTimers({ now: new Date('2026-06-10T00:00:00.000Z') });-- try {- let state = primeGenerate();- state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });- state = submitGenerate(state);- const earlierItem = getActiveProject(state).queue.items[0];-- vi.setSystemTime(new Date('2026-06-10T00:00:01.000Z'));- state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });- vi.setSystemTime(new Date('2026-06-10T00:00:02.000Z'));- state = submitGenerate(state);- const laterItem = getActiveProject(state).queue.items[0];- const projectId = getActiveProject(state).id;-- state = workbenchReducer(state, {- images: [],- projectId,- queueItemId: earlierItem.id,- type: 'routeQueueItemResults',- videos: [createVideo('earlier.mp4', earlierItem.id)],- });- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');-- state = workbenchReducer(state, {- images: [],- projectId,- queueItemId: laterItem.id,- type: 'routeQueueItemResults',- videos: [createVideo('later.mp4', laterItem.id)],- });- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('video:later.mp4');- } finally {- vi.useRealTimers();- }- });-it("selects a run's video over images routed with it", () => {let state = primeGenerate();state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });state = workbenchReducer(state, {- settings: { showProgressImagesInViewer: false },+ settings: { viewerAutoSwitch: 'off' },type: 'setActiveProjectSettings',});state = submitGenerate(state);@@ -5644,7 +5728,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {const projectId = getActiveProject(state).id;state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });state = workbenchReducer(state, {- settings: { showProgressImagesInViewer: true },+ settings: { viewerAutoSwitch: 'progress' },type: 'setActiveProjectSettings',});state = workbenchReducer(state, {@@ -5664,52 +5748,6 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getProjectWidgetValues(getActiveProject(state), 'gallery').selectedImageName).toBe('image:selected.png');});- it('leaves an explicit live-follow opt-out alone when submitting', () => {- let state = primeGenerate();- state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });- state = workbenchReducer(state, {- settings: { showProgressImagesInViewer: false },- type: 'setActiveProjectSettings',- });-- state = submitGenerate(state);-- expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);- });-- it('keeps an explicit live-follow opt-out through later Gallery selections and submissions', () => {- let state = primeGenerate();- state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });- state = workbenchReducer(state, {- settings: { showProgressImagesInViewer: false },- type: 'setActiveProjectSettings',- });- state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });- state = workbenchReducer(state, {- image: createGalleryImageItem('compare.png'),- type: 'setGalleryCompareImage',- });-- state = submitGenerate(state);-- const project = getActiveProject(state);- expect(project.settings.showProgressImagesInViewer).toBe(false);- expect(getProjectWidgetValues(project, 'gallery').selectedImageName).toBe('image:selected.png');- });-- it('lifts the selection pause when live-follow is toggled explicitly', () => {- let state = createInitialWorkbenchState();- state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });- expect(typeof getProjectWidgetValues(getActiveProject(state), 'gallery').liveFollowPausedAt).toBe('string');-- state = workbenchReducer(state, {- settings: { showProgressImagesInViewer: true },- type: 'setActiveProjectSettings',- });-- expect(getProjectWidgetValues(getActiveProject(state), 'gallery').liveFollowPausedAt).toBeUndefined();- });-it('stamps a host page into the navigation query already on a multi-selection', () => {// Host navigation uses the selection's query and page, which may differ from the gallery's current// board/search.@@ -5995,7 +6033,46 @@ describe('workbenchReducer Phase 5 generation flow', () => {});});- it('pauses live-follow for saved Gallery multi-selection and comparison intents', () => {+ it('returns the search scope to the selected board whatever clears the search, so the next search starts there', () => {+ let state = workbenchReducer(createInitialWorkbenchState(), {+ type: 'patchWidgetValues',+ values: { searchScope: 'all', searchTerm: 'cat' },+ widgetId: 'gallery',+ });+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').searchScope).toBe('all');++ // Find in Gallery clears the search with this write, outside the search field.+ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: { searchTerm: '', semanticImageQuery: null, semanticSearchText: null, starredOnly: false },+ widgetId: 'gallery',+ });+ state = workbenchReducer(state, { type: 'patchWidgetValues', values: { searchTerm: 'dog' }, widgetId: 'gallery' });++ expect(getProjectWidgetValues(getActiveProject(state), 'gallery')).toMatchObject({+ searchScope: 'board',+ searchTerm: 'dog',+ });+ });++ it('keeps the search scope while semantic text alone still searches', () => {+ let state = workbenchReducer(createInitialWorkbenchState(), {+ type: 'patchWidgetValues',+ values: { searchScope: 'all', semanticSearchText: 'a red car', searchTerm: '' },+ widgetId: 'gallery',+ });+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').searchScope).toBe('all');++ // Semantic mode left with no text is no search.+ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: { semanticSearchText: '' },+ widgetId: 'gallery',+ });+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery').searchScope).toBe('board');+ });++ it('turns Auto-switch Off for saved Gallery multi-selection and comparison intents', () => {const primaryImage = createGalleryImageItem('primary.png');const compareImage = createGalleryImageItem('compare.png');let state = createInitialWorkbenchState();@@ -6006,15 +6083,12 @@ describe('workbenchReducer Phase 5 generation flow', () => {type: 'setGalleryMultiSelection',});- expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);+ expect(getActiveProject(state).settings.viewerAutoSwitch).toBe('off');- state = workbenchReducer(state, {- settings: { showProgressImagesInViewer: true },- type: 'setActiveProjectSettings',- });+ state = workbenchReducer(state, { settings: { viewerAutoSwitch: 'latest' }, type: 'setActiveProjectSettings' });state = workbenchReducer(state, { image: compareImage, type: 'setGalleryCompareImage' });- expect(getActiveProject(state).settings.showProgressImagesInViewer).toBe(false);+ expect(getActiveProject(state).settings.viewerAutoSwitch).toBe('off');});it('resets the page and stamps the selection query when the starred-only filter changes', () => {@@ -6650,12 +6724,20 @@ describe('workbench account and project settings', () => {expect(getActiveProject(state).settings).toEqual({antialiasProgressImages: true,- showProgressImagesInViewer: true,useCpuNoise: false,useNsfwChecker: false,useWatermark: false,+ viewerAutoSwitch: 'progress',});});++ it('leaves the state alone when a project setting is set to the value it has', () => {+ const state = createInitialWorkbenchState();++ expect(+ workbenchReducer(state, { settings: { viewerAutoSwitch: 'progress' }, type: 'setActiveProjectSettings' })+ ).toBe(state);+ });});describe('workbench backend connection recovery', () => {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 257a73739a..134072012d 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -84,6 +84,7 @@ import {type GeneratedImageContract,type GeneratedVideoContract,generatedVideoToGalleryItem,+ settleGallerySearchScope,} from '@features/gallery/contracts';import { planSeedSubmission } from '@platform/core/seed';import { describeError } from '@platform/logging/normalize';@@ -235,7 +236,7 @@ import {normalizeLayoutPresetSnapshot,resolveSavedLayoutPreset,} from './layoutPresetSnapshots';-import { normalizeProjectSettings } from './settings/store';+import { DEFAULT_PROJECT_SETTINGS, normalizeProjectSettings } from './settings/store';interface QueueGenerateSnapshot {negativePromptNodeId: string;@@ -268,7 +269,13 @@ type WorkbenchReducerAction =| { type: 'setLayoutPresetRoute'; presetId: LayoutPresetId; defaultRoute: LayoutPresetRoute | null }| { type: 'saveLayoutPreset'; presetId: LayoutPresetId }| { type: 'restoreLayoutPresetDefault'; presetId: LayoutPresetId }- | { type: 'renameLayoutPreset'; presetId: LayoutPresetId; label: string }+ | {+ type: 'renameLayoutPreset';+ presetId: LayoutPresetId;+ label: string;+ /** A built-in preset's default name in the language the user sees, which is no rename either. */+ localizedDefaultLabel?: string;+ }| { type: 'deleteLayoutPreset'; presetId: LayoutPresetId }| { type: 'resetActiveLayout' }/** Drop a preset's unsaved arrangement: the active one reapplies its saved layout, an inactive one forgets its copy. */@@ -1245,13 +1252,17 @@ const updateProjectWidgetState = (};};+/** Widget-owned rules every write of a widget type's values keeps; the values themselves when none applies. */+const settleWidgetValues = (typeId: WidgetTypeId, values: Record<string, unknown>): Record<string, unknown> =>+ typeId === 'gallery' ? settleGallerySearchScope(values) : values;+const updateProjectWidgetValues = (project: Project,widgetId: WidgetTypeId,getValues: (values: Record<string, unknown>) => Record<string, unknown>): Project =>updateProjectWidgetState(project, widgetId, (widgetState) => {- const values = getValues(widgetState.values);+ const values = settleWidgetValues(widgetId, getValues(widgetState.values));return values === widgetState.values ? widgetState : { ...widgetState, values };});@@ -1267,7 +1278,7 @@ const updateProjectWidgetInstanceValues = (return project;}- const values = getValues(instance.state.values);+ const values = settleWidgetValues(instance.typeId, getValues(instance.state.values));if (values === instance.state.values) {return project;@@ -1746,12 +1757,16 @@ const assembleWorkbenchProject = (? (stripInfiniteWindowAnchor(strippedSearchValues ?? instance.state.values) ?? strippedSearchValues): strippedSearchValues;const hasRecentImages = 'recentImages' in instance.state.values;+ // The retired live-follow pause stamp; Auto-switch replaced it, so it leaves stored workspaces on the next save.+ const hasRetiredPause = 'liveFollowPausedAt' in instance.state.values;+ // A search stripped here (or saved without one) leaves no scope behind for the next search.+ const settledValues = settleGallerySearchScope(strippedValues ?? instance.state.values);- if (strippedValues === null && !hasRecentImages) {+ if (settledValues === instance.state.values && !hasRecentImages && !hasRetiredPause) {continue;}- const values = strippedValues ?? instance.state.values;+ const { liveFollowPausedAt: _retiredPause, ...values } = settledValues;widgetInstances[instanceId] = {...instance,@@ -1863,7 +1878,8 @@ const createProject = (index: number, id: string, preset: LayoutPreset): Projectname: `Project Name #${index}`,promptHistory: [],queue: { items: [] },- settings: normalizeProjectSettings(),+ // A new project starts on the defaults (Auto-switch In progress); only a stored one lacks the mode.+ settings: normalizeProjectSettings(DEFAULT_PROJECT_SETTINGS),undoRedo: { future: [], past: [] },widgetGraphs: {},widgetInstances: createWidgetInstances(),@@ -2504,15 +2520,21 @@ const updateActiveLayout = (const getAvailableLayoutPreset = (state: WorkbenchState, presetId: LayoutPresetId): LayoutPreset =>resolveSavedLayoutPreset(state.account, presetId);+/**+ * Store what differs from the shipped preset. A label equal to the shipped one, or to its translation the user saw+ * (`localizedDefaultLabel`), is no rename: storing it would freeze one language's name for every other.+ */const setBuiltInLayoutPresetMetadata = (state: WorkbenchState,presetId: BuiltInLayoutPresetId,- metadata: Required<LayoutPresetMetadataOverride>+ metadata: Required<LayoutPresetMetadataOverride>,+ localizedDefaultLabel?: string): WorkbenchState => {const shippedPreset = getLayoutPreset(presetId);+ const isDefaultLabel = metadata.label === shippedPreset.label || metadata.label === localizedDefaultLabel;const override: LayoutPresetMetadataOverride = {...(metadata.iconId !== shippedPreset.iconId ? { iconId: metadata.iconId } : {}),- ...(metadata.label !== shippedPreset.label ? { label: metadata.label } : {}),+ ...(isDefaultLabel ? {} : { label: metadata.label }),};const layoutPresetMetadataOverrides: LayoutPresetMetadataOverrides = {...state.account.layoutPresetMetadataOverrides,@@ -3159,52 +3181,25 @@ const reconcileDeletedGalleryBoard = (return didChangeQueue ? { ...withBoardReferencesCleared, projects } : withBoardReferencesCleared;};-const getLiveFollowPausedAt = (project: Project): string | null => {- const pausedAt = getWidgetValues(project, 'gallery').liveFollowPausedAt;-- return typeof pausedAt === 'string' ? pausedAt : null;-};-/**- * A deliberate selection pauses live-follow; only generations submitted after that selection may take the preview.- * With live-follow explicitly off there is nothing to pause, and a pause recorded then would let the next submission- * turn it back on.+ * A deliberate selection settles the Preview on it: Auto-switch turns Off in the same step, so the control reads Off+ * at once and later results stay in the Gallery. With Auto-switch already Off only the selection changes.*/-const updateGalleryValuesAndPauseLiveFollow = (+const updateGalleryValuesAndStopAutoSwitch = (state: WorkbenchState,getValues: (values: Record<string, unknown>) => Record<string, unknown>,projectId = state.activeProjectId): WorkbenchState =>updateProjectById(state, projectId, (project) =>- !project.settings.showProgressImagesInViewer && getLiveFollowPausedAt(project) === null- ? updateProjectWidgetValues(project, 'gallery', getValues)- : updateProjectWidgetValues(- {- ...project,- settings: { ...project.settings, showProgressImagesInViewer: false },- },- 'gallery',- (values) => ({ ...getValues(values), liveFollowPausedAt: now() })- )+ updateProjectWidgetValues(+ project.settings.viewerAutoSwitch === 'off'+ ? project+ : { ...project, settings: { ...project.settings, viewerAutoSwitch: 'off' } },+ 'gallery',+ getValues+ ));-/** Submission resumes selection-paused live-follow, but preserves an explicit opt-out. */-const shouldResumeLiveFollowOnSubmit = (project: Project): boolean =>- !project.settings.showProgressImagesInViewer && getLiveFollowPausedAt(project) !== null;--/** Only generations submitted after the deliberate selection may replace it. */-const isSubmittedAfterLiveFollowPause = (project: Project, sourceQueueItemId: string): boolean => {- const pausedAt = getLiveFollowPausedAt(project);-- if (pausedAt === null) {- return true;- }-- const submittedAt = project.queue.items.find((item) => item.id === sourceQueueItemId)?.snapshot.submittedAt;-- return submittedAt !== undefined && submittedAt > pausedAt;-};-const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => {let didChange = false;const items = project.queue.items.map((item) => {@@ -3308,13 +3303,8 @@ const getQueueItemStatusAfterBackendCancellation = (};/** Whether a newly routed result may take the Gallery selection (and so the settled Preview). */-const shouldSelectGalleryResult = (- project: Project,- galleryValues: Record<string, unknown>,- sourceQueueItemId: string-): boolean =>- typeof galleryValues.selectedImageName !== 'string' ||- (project.settings.showProgressImagesInViewer && isSubmittedAfterLiveFollowPause(project, sourceQueueItemId));+const shouldSelectGalleryResult = (project: Project, galleryValues: Record<string, unknown>): boolean =>+ typeof galleryValues.selectedImageName !== 'string' || project.settings.viewerAutoSwitch !== 'off';const getGalleryResultSelectionValues = (galleryValues: Record<string, unknown>,@@ -3360,9 +3350,7 @@ const updateGalleryWithResultImages = (project: Project, images: GeneratedImageC.filter((image) => !previousImageNames.has(image.imageName)).map((image) => normalizeGalleryImage(image, queueBoardIds.get(image.sourceQueueItemId)));const nextSelectedImage =- newImages[0] && shouldSelectGalleryResult(project, galleryValues, newImages[0].sourceQueueItemId)- ? newImages[0]- : undefined;+ newImages[0] && shouldSelectGalleryResult(project, galleryValues) ? newImages[0] : undefined;return updateProjectWidgetValues(project, 'gallery', () => ({...galleryValues,recentImages: getBoundedRecentImages([...newImages, ...previousImages]),@@ -3395,7 +3383,7 @@ const routeGalleryResultVideos = (...item,resultVideoNames: [...(item.resultVideoNames ?? []), ...newVideos.map((newVideo) => newVideo.videoName)],}));- if (!shouldSelectGalleryResult(policyProject, getWidgetValues(policyProject, 'gallery'), video.sourceQueueItemId)) {+ if (!shouldSelectGalleryResult(policyProject, getWidgetValues(policyProject, 'gallery'))) {return nextProject;}@@ -3778,9 +3766,6 @@ const enqueueCompiledSnapshot = (sourceId: route.sourceId,},queue: { items: [queueItem, ...project.queue.items] },- ...(shouldResumeLiveFollowOnSubmit(project)- ? { settings: { ...project.settings, showProgressImagesInViewer: true } }- : {}),widgetGraphs:route.sourceId === 'generate' || route.sourceId === 'upscale' || route.sourceId === 'video'? { ...project.widgetGraphs, [route.sourceId]: cloneGraph(graph) }@@ -4175,10 +4160,12 @@ export const __workbenchReducerInternal = (if (isBuiltInLayoutPresetId(action.presetId)) {const preset = resolveSavedLayoutPreset(state.account, action.presetId);- return setBuiltInLayoutPresetMetadata(state, action.presetId, {- iconId: preset.iconId ?? '',- label,- });+ return setBuiltInLayoutPresetMetadata(+ state,+ action.presetId,+ { iconId: preset.iconId ?? '', label },+ action.localizedDefaultLabel+ );}return {@@ -5141,7 +5128,7 @@ export const __workbenchReducerInternal = ();}case 'selectGalleryItem': {- return updateGalleryValuesAndPauseLiveFollow(+ return updateGalleryValuesAndStopAutoSwitch(state,(values) => {// A selection navigated within its own board has no known page there; Preview locates it.@@ -5189,7 +5176,7 @@ export const __workbenchReducerInternal = ();}case 'toggleGalleryItemInSelection': {- return updateGalleryValuesAndPauseLiveFollow(+ return updateGalleryValuesAndStopAutoSwitch(state,(values) => {const itemKey = toGalleryItemKey(action.item);@@ -5258,7 +5245,7 @@ export const __workbenchReducerInternal = ();}case 'setGalleryMultiSelection': {- return updateGalleryValuesAndPauseLiveFollow(+ return updateGalleryValuesAndStopAutoSwitch(state,(values) => {const semanticKey = gallerySemanticReferenceKey(parseGallerySemanticReference(values.semanticImageQuery));@@ -5293,7 +5280,7 @@ export const __workbenchReducerInternal = (const updateValues = (values: Record<string, unknown>) => ({ ...values, compareImage: action.image });return action.image- ? updateGalleryValuesAndPauseLiveFollow(state, updateValues, action.projectId)+ ? updateGalleryValuesAndStopAutoSwitch(state, updateValues, action.projectId): updateGalleryValues(state, updateValues, action.projectId);}case 'selectGalleryBoard': {@@ -5889,11 +5876,6 @@ export const __workbenchReducerInternal = (case 'setActiveProjectSettings': {return updateActiveProject(state, (project) => {const settings = normalizeProjectSettings({ ...project.settings, ...action.settings });- // Explicit live-follow clears any selection-imposed pause.- const withoutPause =- action.settings.showProgressImagesInViewer !== undefined && getLiveFollowPausedAt(project) !== null- ? updateProjectWidgetValues(project, 'gallery', ({ liveFollowPausedAt: _pausedAt, ...values }) => values)- : project;return Object.entries(settings).every(([key, value]) => {const settingKey = key as keyof ProjectSettings;@@ -5903,8 +5885,8 @@ export const __workbenchReducerInternal = (value as ProjectSettings[typeof settingKey]);})- ? withoutPause- : { ...withoutPause, settings };+ ? project+ : { ...project, settings };});}}diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex f7351e169d..6b1b25c643 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -345,7 +345,11 @@ const createCommands = (recover: command('recoverShellLayout'),renamePreset: command('renameLayoutPreset',- (presetId: ActionPayload<'renameLayoutPreset'>['presetId'], label: string) => ({ label, presetId })+ (presetId: ActionPayload<'renameLayoutPreset'>['presetId'], label: string, localizedDefaultLabel?: string) => ({+ label,+ presetId,+ ...(localizedDefaultLabel === undefined ? {} : { localizedDefaultLabel }),+ })),reset: command('resetActiveLayout'),/** Discards the named preset's unsaved arrangement in the active project. */diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex dbc0653d4f..111a46c196 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -149,6 +149,8 @@ const EDITOR_BOOT_SHARED_MODULES = ['/workbench/shell/topbar/ProjectSwitcher.tsx',// The canvas dims sync reads the render-size keys at boot; the lazy canvas slots and compiler share them.'/workbench/widgets/canvas/invoke/canvasScaling.ts',+ // The Preview (open at boot) and the Canvas staging bar share the Auto-switch menu; alone it costs a boot request.+ '/workbench/widgets/shared/AutoSwitchMenu.tsx',] as const;// The workflow core, its UI barrel and the project workflow collection are one chunk: the editor boots with all ofdiff --git a/tests/app/routers/test_gallery.py b/tests/app/routers/test_gallery.pyindex 971d4575d6..524ab46230 100644--- a/tests/app/routers/test_gallery.py+++ b/tests/app/routers/test_gallery.py@@ -1,5 +1,6 @@"""Router contracts for polymorphic gallery filtering."""+from collections.abc import Callablefrom typing import Anyfrom unittest.mock import MagicMock@@ -8,8 +9,11 @@ from fastapi.testclient import TestClientfrom invokeai.app.api.dependencies import ApiDependenciesfrom invokeai.app.services.gallery.gallery_common import GalleryItemNames, GalleryItemNamesResult+from invokeai.app.services.image_records.image_records_common import ImageCategory, ResourceOriginfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.shared.pagination import OffsetPaginatedResults+from invokeai.app.services.urls.urls_default import LocalUrlService+from tests.app.routers.conftest import _auth, _create_boardclass MockApiDependencies(ApiDependencies):@@ -139,3 +143,69 @@ def test_gallery_listings_reject_an_unknown_media_kind(response = client.get(path, params={"media_kind": "audio"})assert response.status_code == 422+++def _save_general_image(mock_invoker: Invoker, image_name: str, user_id: str) -> None:+ mock_invoker.services.image_records.save(+ image_name=image_name,+ image_origin=ResourceOrigin.INTERNAL,+ image_category=ImageCategory.GENERAL,+ width=10,+ height=10,+ has_workflow=False,+ user_id=user_id,+ )+++ ("path", "names_of"),+ [+ ("/api/v1/gallery/items/", lambda body: {item["name"] for item in body["items"]}),+ ("/api/v1/gallery/items/names", lambda body: {item["name"] for item in body["items"]}),+ ("/api/v1/gallery/item_names", lambda body: set(body["item_names"])),+ ],+)+def test_the_all_boards_scope_lists_readable_items_without_a_board_check(+ monkeypatch: Any,+ mock_invoker: Invoker,+ client: TestClient,+ user1_token: str,+ user2_token: str,+ path: str,+ names_of: Callable[[Any], set[str]],+) -> None:+ def no_board_check(*args: Any, **kwargs: Any) -> None:+ raise AssertionError("'all' is a scope, not a board")++ monkeypatch.setattr("invokeai.app.api.routers.gallery._assert_board_read_access", no_board_check)+ # A page carries each item's URLs.+ monkeypatch.setattr(mock_invoker.services, "urls", LocalUrlService())+ user1, user2 = (mock_invoker.services.users.get_by_email(f"user{n}@test.com") for n in (1, 2))+ assert user1 is not None and user2 is not None+ own_board, private_board = _create_board(client, user1_token, "Mine"), _create_board(client, user2_token, "Theirs")+ for name, owner, board_id in (+ ("own-unboarded.png", user1.user_id, None),+ ("own-boarded.png", user1.user_id, own_board),+ ("other-unboarded.png", user2.user_id, None),+ ("other-private.png", user2.user_id, private_board),+ ):+ _save_general_image(mock_invoker, name, owner)+ if board_id is not None:+ mock_invoker.services.board_image_records.add_image_to_board(board_id, name)++ response = client.get(path, params={"board_id": "all"}, headers=_auth(user1_token))+ own = client.get(+ "/api/v1/gallery/items/location",+ params={"board_id": "all", "kind": "image", "name": "own-boarded.png"},+ headers=_auth(user1_token),+ )+ foreign = client.get(+ "/api/v1/gallery/items/location",+ params={"board_id": "all", "kind": "image", "name": "other-private.png"},+ headers=_auth(user1_token),+ )++ assert response.status_code == 200+ assert names_of(response.json()) == {"own-unboarded.png", "own-boarded.png"}+ assert own.status_code == 200 and own.json()["total"] == 2+ assert foreign.status_code == 404diff --git a/tests/app/routers/test_wildcards.py b/tests/app/routers/test_wildcards.pyindex 0441783449..d29a7f8ab9 100644--- a/tests/app/routers/test_wildcards.py+++ b/tests/app/routers/test_wildcards.py@@ -10,6 +10,9 @@ import pytestfrom fastapi import statusfrom fastapi.testclient import TestClient+from invokeai.app.services.invoker import Invoker+from invokeai.app.services.wildcard_records.wildcard_records_common import WildcardWithoutId+def _auth(token: str) -> dict[str, str]:return {"Authorization": f"Bearer {token}"}@@ -26,6 +29,7 @@ def _create(client: TestClient, token: str, name: str, values: list[str]):("post", "/api/v1/wildcards/"),("patch", "/api/v1/wildcards/some-id"),("delete", "/api/v1/wildcards/some-id"),+ ("post", "/api/v1/wildcards/delete"),],)def test_routes_require_auth(enable_multiuser: Any, client: TestClient, method: str, path: str):@@ -92,6 +96,73 @@ def test_update_and_delete(client: TestClient, user1_token: str):assert client.get("/api/v1/wildcards/", headers=_auth(user1_token)).json() == []+def _delete_many(client: TestClient, token: str, wildcard_ids: list[str]):+ return client.post("/api/v1/wildcards/delete", json={"wildcard_ids": wildcard_ids}, headers=_auth(token))+++def _names(client: TestClient, token: str) -> list[str]:+ return [w["name"] for w in client.get("/api/v1/wildcards/", headers=_auth(token)).json()]+++def test_batch_delete_removes_the_callers_wildcards_and_returns_their_ids(client: TestClient, user1_token: str):+ colors = _create(client, user1_token, "colors", ["red"]).json()["id"]+ animals = _create(client, user1_token, "animals", ["cat"]).json()["id"]+ _create(client, user1_token, "kept", ["x"])++ response = _delete_many(client, user1_token, [colors, animals])++ assert response.status_code == status.HTTP_200_OK+ assert sorted(response.json()["deleted_ids"]) == sorted([colors, animals])+ assert _names(client, user1_token) == ["kept"]+++def test_batch_delete_skips_another_users_wildcards_without_revealing_them(+ client: TestClient, user1_token: str, user2_token: str+):+ mine = _create(client, user1_token, "colors", ["red"]).json()["id"]+ theirs = _create(client, user2_token, "colors", ["blue"]).json()["id"]++ response = _delete_many(client, user1_token, [mine, theirs])++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["deleted_ids"] == [mine]+ assert _names(client, user2_token) == ["colors"]+++def test_batch_delete_ignores_unknown_and_repeated_ids_and_is_idempotent(client: TestClient, user1_token: str):+ colors = _create(client, user1_token, "colors", ["red"]).json()["id"]++ first = _delete_many(client, user1_token, [colors, "no-such-id", colors])+ again = _delete_many(client, user1_token, [colors])++ assert first.json()["deleted_ids"] == [colors]+ assert again.status_code == status.HTTP_200_OK+ assert again.json()["deleted_ids"] == []++[email protected]("count", [0, 1001])+def test_batch_delete_rejects_an_empty_or_oversized_list(client: TestClient, user1_token: str, count: int):+ response = _delete_many(client, user1_token, [f"id-{i}" for i in range(count)])++ assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT+++def test_batch_delete_removes_a_selection_larger_than_one_query_chunk(+ client: TestClient, mock_invoker: Invoker, user1_token: str+):+ # 720 ids span two IN-list chunks. Created through the service: 720 HTTP round trips would only add time.+ first = _create(client, user1_token, "w-0", ["x"]).json()+ store = mock_invoker.services.wildcard_records+ ids = [first["id"]] + [+ store.create(WildcardWithoutId(name=f"w-{i}", values=["x"]), user_id=first["user_id"]).id for i in range(1, 720)+ ]++ response = _delete_many(client, user1_token, ids)++ assert sorted(response.json()["deleted_ids"]) == sorted(ids)+ assert _names(client, user1_token) == []++def test_dynamicprompts_expands_the_callers_wildcards(client: TestClient, user1_token: str, user2_token: str):_create(client, user1_token, "colors", ["red", "green", "blue"])diff --git a/tests/app/services/boards/test_boards_default.py b/tests/app/services/boards/test_boards_default.pyindex 2be328644c..169a74c7e1 100644--- a/tests/app/services/boards/test_boards_default.py+++ b/tests/app/services/boards/test_boards_default.py@@ -156,15 +156,16 @@ def test_a_board_dto_counts_each_kind_of_media(mock_invoker: Invoker, mock_sqlit)cursor.executemany("INSERT INTO videos (video_name, video_origin, video_category, width, height) VALUES (?, 'internal', ?, 1, 1)",- [("first.mp4", "general"), ("second.mp4", "general"), ("asset.mp4", "user")],+ [("first.mp4", "general"), ("second.mp4", "general"), ("asset.mp4", "user"), ("other.mp4", "other")],)for name in ("general.png", "control.png", "mask.png"):services.board_image_records.add_image_to_board(board_id, name)- for name in ("first.mp4", "second.mp4", "asset.mp4"):+ for name in ("first.mp4", "second.mp4", "asset.mp4", "other.mp4"):services.board_video_records.add_video_to_board(board_id, name)dto = services.boards.get_dto(board_id, viewer=BoardViewer(user_id="system", is_admin=True))+ # Neither the Media nor the Uploads view lists an OTHER video, so neither count includes it.assert (dto.image_count, dto.asset_count, dto.video_count, dto.asset_video_count) == (1, 2, 3, 1)diff --git a/tests/app/services/gallery/test_gallery_default.py b/tests/app/services/gallery/test_gallery_default.pyindex b31a2d3e65..962f500817 100644--- a/tests/app/services/gallery/test_gallery_default.py+++ b/tests/app/services/gallery/test_gallery_default.py@@ -20,7 +20,7 @@ from types import SimpleNamespacefrom typing import Any, TypeVarimport pytest-from sqlalchemy import update+from sqlalchemy import insert, updatefrom invokeai.app.services.board_image_records.board_image_records_default import BoardImageRecordStoragefrom invokeai.app.services.board_records.board_records_common import BoardChanges, BoardVisibility@@ -32,7 +32,9 @@ from invokeai.app.services.image_records.image_records_common import ImageCategofrom invokeai.app.services.image_records.image_records_default import ImageRecordStoragefrom invokeai.app.services.shared.database.database import Databasefrom invokeai.app.services.shared.database.queries import gallery as gallery_queries+from invokeai.app.services.shared.database.schema.boards import board_membersfrom invokeai.app.services.shared.database.schema.images import images+from invokeai.app.services.shared.database.schema.users import usersfrom invokeai.app.services.shared.database.schema.videos import videosfrom invokeai.app.services.shared.pagination import SQLiteDirectionfrom invokeai.app.services.urls.urls_default import LocalUrlService@@ -958,9 +960,14 @@ class TestMediaOriginOnListedItems:}+_MEDIA_VIEW = [ImageCategory.GENERAL]+_UPLOADS_VIEW = [ImageCategory.CONTROL, ImageCategory.MASK, ImageCategory.USER]++class TestCanvasOwnedImagesAreNotCounted:- """OTHER is the category of images a canvas layer owns: neither the images view nor the assets view lists them,- so neither a day's nor a board's counts may include them, or a badge disagrees with what it opens."""+ """OTHER is the category of images a canvas layer owns (and of some uploaded or generated videos): neither the+ Media view nor the Uploads view lists them, so neither a day's nor a board's counts may include them, or a badge+ disagrees with what it opens."""def test_a_day_counts_only_what_its_views_list(self, services) -> None:for name, category in (@@ -970,10 +977,17 @@ class TestCanvasOwnedImagesAreNotCounted:):_save_image(services["images"], name, user_id="alice", category=category)_backdate(services, "images", "image_name", name, "2026-01-05 12:00:00.000")+ for name, category in (("generated.mp4", ImageCategory.GENERAL), ("other.mp4", ImageCategory.OTHER)):+ _save_video(services["videos"], name, user_id="alice", category=category)+ _backdate(services, "videos", "video_name", name, "2026-01-05 12:00:00.000")+ # A day holding only an OTHER video is no day of the gallery's.+ _save_video(services["videos"], "only-other.mp4", user_id="alice", category=ImageCategory.OTHER)+ _backdate(services, "videos", "video_name", "only-other.mp4", "2026-01-06 12:00:00.000")(day,) = services["gallery"].get_dates(user_id="alice", is_admin=False)- assert (day.image_count, day.asset_count) == (1, 1)+ assert day.virtual_board_id == "by_date:2026-01-05"+ assert (day.image_count, day.asset_count, day.video_count) == (1, 1, 1)def test_a_board_counts_only_what_its_views_list(self, services) -> None:board = services["boards"].save("Project", "alice")@@ -984,12 +998,27 @@ class TestCanvasOwnedImagesAreNotCounted:):_save_image(services["images"], name, user_id="alice", category=category)services["board_images"].add_image_to_board(board.board_id, name)+ for name, category in (+ ("generated-1.mp4", ImageCategory.GENERAL),+ ("generated-2.mp4", ImageCategory.GENERAL),+ ("uploaded.mp4", ImageCategory.USER),+ ("other.mp4", ImageCategory.OTHER),+ ):+ _save_video(services["videos"], name, user_id="alice", category=category)+ services["board_videos"].add_video_to_board(board.board_id, name)summary = services["gallery"].get_board_media_summaries([board.board_id])[board.board_id]+ media = services["gallery"].list_items(limit=50, board_id=board.board_id, categories=_MEDIA_VIEW, is_admin=True)+ uploads = services["gallery"].list_items(+ limit=50, board_id=board.board_id, categories=_UPLOADS_VIEW, is_admin=True+ )- assert (summary.image_count, summary.asset_count) == (1, 1)+ # The badges' formulas: Media is images plus the videos that are not assets, Uploads assets plus asset videos.+ assert summary.image_count + summary.video_count - summary.asset_video_count == media.total == 3+ assert summary.asset_count + summary.asset_video_count == uploads.total == 2# The same counts as the board's own badge.assert services["board_images"].get_counts_for_board(board.board_id) == (1, 1)+ assert services["board_videos"].get_counts_for_board(board.board_id) == (3, 1)class TestFilters:@@ -1358,3 +1387,122 @@ class TestMediaKindFilter:sql = " ".join(statement for statement, _ in statements)assert "UNION" not in sqlassert "videos" not in sql+++class TestAllReadableBoardsScope:+ """`board_id="all"`, as the gallery's search across boards uses it: the caller's own items on no board (every one+ for an administrator) and the items on every active board the caller may read, alike for images and videos, and+ the same in pages, names and locations."""++ def _seed(self, services) -> None:+ def on_board(stem: str, *, owner: str, visibility=BoardVisibility.Private, archived: bool = False) -> str:+ board = services["boards"].save(stem, owner)+ services["boards"].update(board.board_id, BoardChanges(board_visibility=visibility, archived=archived))+ _save_image(services["images"], f"{stem}.png", user_id=owner)+ _save_video(services["videos"], f"{stem}.mp4", user_id=owner)+ services["board_images"].add_image_to_board(board.board_id, f"{stem}.png")+ services["board_videos"].add_video_to_board(board.board_id, f"{stem}.mp4")+ return board.board_id++ on_board("own-private", owner="user1")+ shared_with_user1 = on_board("explicit-share", owner="user2")+ on_board("shared-visibility", owner="user2", visibility=BoardVisibility.Shared)+ on_board("public-visibility", owner="user2", visibility=BoardVisibility.Public)+ on_board("other-private", owner="user2")+ on_board("own-archived", owner="user1", archived=True)+ on_board("other-archived-public", owner="user2", visibility=BoardVisibility.Public, archived=True)+ for stem, owner in (("own-unboarded", "user1"), ("other-unboarded", "user2")):+ _save_image(services["images"], f"{stem}.png", user_id=owner)+ _save_video(services["videos"], f"{stem}.mp4", user_id=owner)+ with services["db"].begin(write=True) as conn:+ conn.execute(insert(users).values(user_id="user1", email="[email protected]", password_hash="unused"))+ conn.execute(insert(board_members).values(board_id=shared_with_user1, user_id="user1", role="viewer"))++ @pytest.mark.parametrize(+ ("user_id", "is_admin", "expected"),+ [+ (+ "user1",+ False,+ {"own-private", "explicit-share", "shared-visibility", "public-visibility", "own-unboarded"},+ ),+ ("user3", False, {"shared-visibility", "public-visibility"}),+ *(+ (+ caller,+ True,+ {+ "own-private",+ "explicit-share",+ "shared-visibility",+ "public-visibility",+ "other-private",+ "own-unboarded",+ "other-unboarded",+ },+ )+ # An administrator, and the single-user install's caller.+ for caller in ("admin", "system")+ ),+ ],+ )+ def test_pages_names_and_locations_list_exactly_the_readable_items(+ self, services, user_id: str, is_admin: bool, expected: set[str]+ ) -> None:+ self._seed(services)+ gallery = services["gallery"]+ expected_items = {f"{stem}.{ext}" for stem in expected for ext in ("png", "mp4")}+ every_item = {+ f"{stem}.{ext}"+ for stem in (+ "own-private",+ "explicit-share",+ "shared-visibility",+ "public-visibility",+ "other-private",+ "own-archived",+ "other-archived-public",+ "own-unboarded",+ "other-unboarded",+ )+ for ext in ("png", "mp4")+ }+ scope = {"board_id": "all", "user_id": user_id, "is_admin": is_admin}++ page = gallery.list_items(limit=100, **scope)+ names = gallery.get_item_names(**scope)+ refs = gallery.list_item_names(**scope)++ assert {item.name for item in page.items} == expected_items+ assert set(names.item_names) == {ref.name for ref in refs.items} == expected_items+ assert page.total == names.total_count == len(expected_items)+ for name in sorted(every_item):+ kind = GalleryItemKind.VIDEO if name.endswith(".mp4") else GalleryItemKind.IMAGE+ location = gallery.get_item_location(kind=kind, name=name, **scope)+ if name in expected_items:+ assert location is not None and location.total == len(expected_items)+ assert names.item_names[location.index] == name+ else:+ assert location is None, name++ def test_a_page_shows_each_items_board(self, services) -> None:+ self._seed(services)++ page = services["gallery"].list_items(limit=100, board_id="all", user_id="user1", is_admin=False)++ boards = {item.name: item.board_id for item in page.items}+ assert boards["own-unboarded.mp4"] is None+ assert boards["own-private.png"] is not None and boards["own-private.png"] == boards["own-private.mp4"]++ def test_the_other_filters_still_apply(self, services) -> None:+ self._seed(services)+ _star(services, "images", "image_name", "public-visibility.png")+ _star(services, "videos", "video_name", "own-unboarded.mp4")++ starred = services["gallery"].get_item_names(board_id="all", user_id="user1", is_admin=False, starred=True)+ videos_only = services["gallery"].get_item_names(+ board_id="all", user_id="user3", is_admin=False, media_kind="video"+ )++ assert set(starred.item_names) == {"public-visibility.png", "own-unboarded.mp4"}+ assert set(videos_only.item_names) == {"shared-visibility.mp4", "public-visibility.mp4"}diff --git a/tests/app/services/test_wildcard_records.py b/tests/app/services/test_wildcard_records.pyindex d759f00b71..793ec010d7 100644--- a/tests/app/services/test_wildcard_records.py+++ b/tests/app/services/test_wildcard_records.py@@ -192,3 +192,16 @@ def test_one_users_wildcards_do_not_resolve_for_another(store: WildcardRecordsSt)assert other.error == "No values found for wildcard(s): colors"+++def test_delete_many_deletes_only_the_owners_wildcards_across_query_chunks(store: WildcardRecordsStorage) -> None:+ # More ids than one IN list binds, with the other account's ids in both chunks.+ mine = [store.create(WildcardWithoutId(name=f"mine-{i}", values=["x"]), user_id="user-1").id for i in range(600)]+ theirs = [store.create(WildcardWithoutId(name=f"theirs-{i}", values=["x"]), user_id="user-2").id for i in range(4)]+ requested = [theirs[0], *mine[:300], theirs[1], *mine[300:], theirs[2], "missing", theirs[3]]++ deleted = store.delete_many("user-1", requested)++ assert sorted(deleted) == sorted(mine)+ assert store.get_many("user-1") == []+ assert sorted(w.id for w in store.get_many("user-2")) == sorted(theirs)