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(ui): workbench polish: desktop file drops, compare waiting state, reference image rows, Upscale prompt tools, compact dropdowns (#10136)
Josh Corbett22f97966551c
diff --git a/docs/plugins/theme-tokens.mjs b/docs/plugins/theme-tokens.mjsindex 2f12d77369..8ab99da1f3 100644--- a/docs/plugins/theme-tokens.mjs+++ b/docs/plugins/theme-tokens.mjs@@ -59,8 +59,8 @@ export const extractThemeTokens = (themesModule) => {const DERIVED_TOKENS = {// `bg.subtle`: the panel surface the fills below are mixed into.surface: 'var(--invoke-neutral-900)',- // `gray.hoverTint`: the foreground pulled toward the accent, applied at low alpha for hover fills.- 'hover-tint': 'color-mix(in oklab, var(--invoke-accent) 55%, var(--invoke-neutral-50))',+ // `gray.hoverTint`: the foreground leaned toward the accent by Classic's `interactionTint`, applied at low alpha.+ 'hover-tint': 'color-mix(in oklab, var(--invoke-accent) 15%, var(--invoke-neutral-50))',// `bg.hover` (`gray.hoverTint/10`): the hovered fill of tabs, rows and ghost buttons.'bg-hover': 'color-mix(in oklab, var(--invoke-hover-tint) 10%, transparent)',// The shown tab's fill: `gray.hoverTint/22`, the app's subtle button fill. The segment tabs' own `/15`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 244f060d55..27ba4bcf25 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@@ -20,7 +20,7 @@ Hover over a numbered circle, or tap it on a touchscreen, for a short descriptio| | Part | What it does || --- | --- | --- |-| 1 | **App menu** | Links to Projects, the Model Manager, Fonts, the Queue, **Widgets…**, Settings and help. The search button beside the project switcher opens the command palette. |+| 1 | **App menu** | Links to the Launchpad, **Settings** and the command palette, then Projects, the Model Manager, Fonts, the Queue, **Widgets…** and help. The search button beside the project switcher also opens the command palette. || 2 | **Project switcher** | Shows the active project and switches between projects. See [Working with Projects](/users-guide/projects/introduction/). || 3 | **Layout preset tabs** | One tab per saved layout. A dot on a tab's icon means that layout has unsaved changes in this project; the active tab's arrow opens the preset menu. When there are more tabs than fit, the row fades at its edge and an arrow scrolls to the rest. || 4 | **Save as new preset** | Saves the current arrangement as a new preset. |@@ -57,14 +57,18 @@ Press <kbd>Z</kbd> to swap the Preview into the center and back to the view youThe Preview's **Auto-switch** button, in its header, shows the current mode as its icon (hover over it to see the name) and opens a menu that chooses what the Preview shows while work runs:-- **In progress**: each image as it is being generated, then the finished result. New projects start here.+- **In progress**: each image as it is being generated, then the finished result. The finished result stays on screen until the next image shows its first preview; until then, while the image loads its model or prepares, a note at the top of the Preview reads *Starting…*, or shows the progress message the run reports. 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**.+Choosing a finished item yourself, in the Gallery or with the Preview's arrows, turns Auto-switch **Off** so your choice stays on screen, until you choose a mode again. Choosing an image that is still generating, a generating tile in the Gallery or the filmstrip, turns it to **In progress** and keeps that image on screen while it generates, even when another one starts beside it. The canvas staging area's own Auto-switch follows the same rules. The setting is saved with the project. Projects created before this setting existed open with it **Off**.The Preview's header holds the next steps for the image it shows. Click the board and item name at its start to open a mini gallery and jump to another image or video. **Edit** opens Edit on Canvas, Upscale, Send to Video, Add to Canvas as… and New project from image; **Use** offers the image as a reference, a control or a prompt template, and reuses its settings: **Remix image** (<kbd>R</kbd>), **All settings** (<kbd>A</kbd>), **Use prompt** (<kbd>P</kbd>), **Use seed** (<kbd>S</kbd>), **Use size** (<kbd>D</kbd>) and **Use CLIP skip**. Each item says what it does. The **⋮** menu holds the rest: copy, download, Load workflow, Select for compare, Move to board, Delete and more. A Preview narrower than 560 pixels, and a Preview in a side rail at any width, shows **Edit** and **Use** as icons and moves **Select for compare** into **⋮**. Below 280 pixels only the star and **⋮** remain, and **⋮** holds everything.+**Select for compare** keeps the shown image to compare with the next image you select. While it waits, the button stays pressed, the Preview says *Pick another image to compare with this one*, and the image's Gallery thumbnail is labelled **Compare**. Select another image in the Gallery or the filmstrip, or step to one with the arrow keys, and the comparison opens. To call it off, click the button again, click **Cancel** in the Preview, or press <kbd>Esc</kbd>; selecting several items, clearing the selection, or a new result that Auto-switch shows calls it off too. <kbd>Esc</kbd> also closes an open comparison, and selecting the **Compare** image while comparing swaps the two.++To open media from your computer in the Preview, drag image or video files from your file manager or the desktop onto it and drop them on **Drop to show**. They are uploaded to the Gallery, to the board new results go to, and the newest one is shown. While the Preview shows an image, a second zone, **Drop to compare**, compares it with the first image you drop there, as dragging a Gallery image onto the Preview does. Files the Gallery cannot hold are refused with a notice. A slow upload shows its progress as a notice; until it finishes, another drop on the Preview is refused.+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. To show or hide the filmstrip along the Preview's bottom edge, turn **Show filmstrip** on or off in the settings behind the gear in the Preview's header, or press <kbd>T</kbd>.### The status bar and bottom panel@@ -120,7 +124,7 @@ A panel can appear in more than one place at once, for example the Gallery in th### Adding and removing panels-Click the **…** button at the bottom of a rail, or right-click an empty part of the rail, to open its menu (**Create widgets** on the left, **Inspect widgets** on the right). It lists every panel that rail can hold, with a check mark beside those already placed. Choose a panel to add it, or choose a checked panel to remove it.+Click the **…** button at the bottom of a rail, or right-click an empty part of the rail, to open its menu (**Left panel widgets** or **Right panel widgets**). The **…** button after the status bar chips opens the same menu for the status bar (**Status bar widgets**). Each menu lists every panel its rail or the status bar can hold, with a check mark beside those already placed. Choose a panel to add it, or choose a checked panel to remove it.To remove a panel quickly, right-click its rail icon and choose **Remove**. Removing a panel only takes it out of the layout. Its contents and settings are kept, and it comes back as you left it when you add it again. A notice confirms the removal with an **Undo** button.@@ -163,7 +167,7 @@ Invoke comes with four presets:| Preset | Center | Left rail | Right rail || --- | --- | --- | --- || **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 |+| **Edit**: edit and refine images | Canvas (Preview also available) | Generate, Upscale | Layers, Preview || **Video**: generate video | Preview | Video, Upscale | Gallery, Queue || **Workflow**: build and run workflows | Workflow editor (Preview also available) | Workflow | Queue, Preview, Gallery, Image Map |diff --git a/docs/src/content/docs/Users Guide/01.Workbench/02.hotkeys.mdx b/docs/src/content/docs/Users Guide/01.Workbench/02.hotkeys.mdxindex a264d42697..ab2e1700a4 100644--- a/docs/src/content/docs/Users Guide/01.Workbench/02.hotkeys.mdx+++ b/docs/src/content/docs/Users Guide/01.Workbench/02.hotkeys.mdx@@ -1,7 +1,7 @@---title: Keyboard shortcutsdescription: Every default keyboard shortcut in Invoke, where each one works, and how to change, add, disable or reset shortcuts in Settings.-lastUpdated: 2026-10-30+lastUpdated: 2026-11-14---import { Steps } from '@astrojs/starlight/components';@@ -13,7 +13,7 @@ In the tables, <kbd>Mod</kbd> means <kbd>Ctrl</kbd> on Windows and Linux and <kb## Where shortcuts work- **App** shortcuts work anywhere in the workbench.-- **Panel** shortcuts (Canvas, Workflows, Viewer, Gallery) work only while that panel has keyboard focus. Click in a panel, or move focus to it, to give its keys priority. The center panel has focus when a project opens, and gets it back when a focused window docks or closes. The Viewer shortcuts belong to the **Preview** panel.+- **Panel** shortcuts (Canvas, Workflows, Viewer, Gallery, Queue) work only while that panel has keyboard focus. Click in a panel, or move focus to it, to give its keys priority. The center panel has focus when a project opens, and gets it back when a focused window docks or closes. The Viewer shortcuts belong to the **Preview** panel.- When a panel shortcut uses the same key as an App shortcut, the panel's shortcut wins while that panel has focus, and the App shortcut works everywhere else. For example, <kbd>T</kbd> selects the Text tool on the Canvas and collapses the left panel elsewhere.- While you type in a text field, single-key shortcuts do nothing so your typing is never interrupted. Shortcuts that make sense while writing a prompt still work there: Invoke, Invoke Front, Invoke To Other Destination, Focus Prompt, the prompt history and prompt weight keys, Open Project Switcher, Open Settings, the command palette, and the region and widget focus keys.- While a dialog is open, only the command palette shortcut works.@@ -27,7 +27,7 @@ The **Shortcuts** chip in the status bar lists the keys for whatever has focus,Open **Settings** (<kbd>Mod</kbd>+<kbd>,</kbd>, or the app menu) and choose **Keyboard shortcuts**. You can also choose **Keyboard Shortcuts** in the [command palette](#app), or **Keyboard shortcut settings** in the status bar's **Shortcuts** chip.-The **Hotkeys** list groups every shortcut under App, Canvas, Workflows, Viewer and Gallery, whether or not that panel is in your layout. **Search hotkeys** filters the list by command name or default key. Your shortcuts are saved with your account and apply in every project.+The **Hotkeys** list groups every shortcut under App, Canvas, Workflows, Viewer, Gallery and Queue, whether or not that panel is in your layout. **Search hotkeys** filters the list by command name or default key. Your shortcuts are saved with your account and apply in every project.<Steps>1. Click a key chip on a row to change it. The chip reads **Press keys**: press the new combination. Press <kbd>Esc</kbd> to stop recording without changing the chip, or click the trash button to remove that key.@@ -54,7 +54,7 @@ These work anywhere in the workbench.| <kbd>Mod</kbd>+<kbd>Enter</kbd> | Invoke | Queues the active route || <kbd>Mod</kbd>+<kbd>Shift</kbd>+<kbd>Enter</kbd> | Invoke Front | Queues ahead of your pending items || <kbd>Mod</kbd>+<kbd>Alt</kbd>+<kbd>Enter</kbd> | Invoke To Other Destination | Queues once with results sent to the other destination (Gallery instead of Canvas, or Canvas instead of Gallery). The saved route does not change. |-| <kbd>Shift</kbd>+<kbd>X</kbd> | Cancel Queue Item | Cancels the item that is running |+| <kbd>Shift</kbd>+<kbd>X</kbd> | Cancel current or next queue item | Cancels the item that is running, or, between two items, the next one waiting. Holding the key cancels one item || <kbd>Mod</kbd>+<kbd>Shift</kbd>+<kbd>X</kbd> | Cancel all queue items | Cancels every unfinished item, after you confirm || <kbd>Alt</kbd>+<kbd>A</kbd> | Focus Prompt | Opens Generate and puts the cursor in the prompt || <kbd>Alt</kbd>+<kbd>↑</kbd> / <kbd>Alt</kbd>+<kbd>↓</kbd> | Prompt History Prev / Prompt History Next | Steps through your prompt history |@@ -92,7 +92,7 @@ These work while the Canvas has focus. The tool, brush size, color and undo keys| Keys | Command | What it does || --- | --- | --- |-| <kbd>H</kbd> | Select view tool | View tool |+| <kbd>H</kbd> | Select pan tool | Pan tool || <kbd>V</kbd> | Select move tool | Move tool || <kbd>Shift</kbd>+<kbd>T</kbd> | Transform selected layer | Starts transforming the selected layer, or selects the Transform tool when no layer is selected || <kbd>B</kbd> | Select brush tool | Brush tool |@@ -117,7 +117,7 @@ These work while the Canvas has focus. The tool, brush size, color and undo keys| --- | --- | --- || <kbd>Alt</kbd>+<kbd>[</kbd> / <kbd>Alt</kbd>+<kbd>]</kbd> | Previous canvas entity / Next canvas entity | With more than one staged or generating result, steps through the results. Otherwise selects the previous or next layer. || <kbd>Q</kbd> | Quick switch to bookmarked or previous layer | Selects the bookmarked layer, or the layer you had selected before |-| Arrow keys | Nudge layer left, right, up, down | Moves the selected layer 1 px |+| Arrow keys | Nudge layer left, right, up, down | Moves the selected layer 1 px. With more than one staged or generating result, <kbd>←</kbd> and <kbd>→</kbd> step through the results instead, unless the Move or Transform tool is active. || <kbd>Shift</kbd>+arrow keys | Nudge layer left, right, up, down 10px | Moves the selected layer 10 px || <kbd>Delete</kbd> or <kbd>Backspace</kbd> | Delete selected canvas item | Erases the selected pixels when there is a selection; otherwise deletes the selected layers || <kbd>Shift</kbd>+<kbd>C</kbd> | Clear selected mask | Clears the selected mask layer |@@ -186,6 +186,7 @@ These work while the Preview has focus. The recall keys and **Load Workflow** al| <kbd>F</kbd> | Zoom preview to fit | Fits an image to the Preview || <kbd>C</kbd> | Swap comparison images | Swaps the two images being compared || <kbd>M</kbd> | Next comparison mode | Switches to the next comparison mode while comparing |+| <kbd>Esc</kbd> | Cancel or exit compare | Cancels **Select for compare** while it waits for a second image, or closes the comparison || <kbd>R</kbd> | Remix | Recalls the image's settings, except the seed || <kbd>A</kbd> | Recall All | Recalls all of the image's settings || <kbd>S</kbd> | Recall Seed | Recalls the seed |@@ -206,9 +207,14 @@ These work while the Gallery has focus. See [Gallery reference](/users-guide/gal| <kbd>Delete</kbd> or <kbd>Backspace</kbd> | Delete gallery selection | Deletes the selected items || <kbd>R</kbd> | Remix | Recalls the selected image's settings, except the seed || <kbd>.</kbd> | Toggle gallery image star | Stars or unstars the selected items |+| <kbd>Esc</kbd> | Cancel or exit compare | Cancels **Select for compare** while it waits for a second image, or closes the comparison |**Clear gallery selection**, **Add or remove the focused gallery item from the selection** and **Toggle gallery starred-only filter** have no default keys.+## Queue++While a row in the Queue panel has focus, <kbd>A</kbd> runs **Recall All**: it recalls all of that job's settings into the Generate panel, or into the Video panel for a video job. Elsewhere in the Queue the key does nothing. See [Generating and modifying still images](/users-guide/image-generation/introduction/) for what a job can recall.+## Image MapWhile the Image Map has focus, <kbd>Esc</kbd> runs **Clear cluster selection**. It is listed under App in Settings while an Image Map is open.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdxindex f1f41dcb8d..bf4ca39f49 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx@@ -68,7 +68,7 @@ and generation needs it. Its starter model (~4.8 GB) installs together with Animonly Qwen3.5 4B encoders: MOSS-Image's Qwen3.5 9B installs under the same type but does not work with Anima-3.8B. The connectorruns once per denoising step, so Anima-3.8B is slower per step than Anima-2.9B (about 1.3 against 1.7iterations per second at 832×1216 on an RTX 4090), and its Qwen3.5 encoder adds memory while the prompt-is encoded. **Reset all to model defaults** sets 40 steps at CFG 6, the settings of the author's reference+is encoded. **Apply model defaults** sets 40 steps at CFG 6, the settings of the author's referenceworkflow.[FP8 Storage](/configuration/optimization/fp8-storage/) changes Anima-3.8B's images more than Anima's: at@@ -179,8 +179,8 @@ multi-user mode only an administrator's generation does, and anyone else is askefrom the Model Manager.To use it, select an Anima model and add a reference image in the **Guidance** section; the first installed-Anima IP-Adapter is selected for it. The card has one main control, **Strength**, from 0 to 2 (default 1),-and **Active steps** under **Advanced**. There is no **Mode** or CLIP Vision choice as there is for SD+Anima IP-Adapter is selected for it. The reference's row has one main control, **Strength**, from 0 to 2+(default 1), and the **Steps** range in its settings (the chevron beside **Strength**). There is no **Mode** or CLIP Vision choice as there is for SDIP-Adapters.- **Strength** scales how much of the reference the image carries. **0** turns the reference off, and thediff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdxindex 3f496eb68f..69da32bed2 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-1.mdx@@ -122,8 +122,8 @@ also carry a FLUX Redux reference image.A FLUX.1 model accepts up to **five** reference images. Three kinds are available:-- **FLUX Redux** — image variation from a reference. Pick a FLUX Redux model on the reference image card- and set **Image influence** from *Lowest* to *Highest* (default). Redux needs the SigLIP image encoder,+- **FLUX Redux** — image variation from a reference. Pick a FLUX Redux model in the reference's settings+ and set **Image influence** on its row from *Lowest* to *Highest* (default). Redux needs the SigLIP image encoder,which installs with it.- **IP-Adapter** — the *Standard Reference (XLabs FLUX IP-Adapter v2)* starter model references an imagemore loosely. It uses the CLIP ViT-L image encoder, installed as a dependency.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdxindex 9b3ab4d493..ff9c709127 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdx@@ -15,8 +15,8 @@ and edits or combines up to ten reference images. InvokeAI supports both publishprompt. It is meant mainly for fine-tuning and LoRA training, but generates normally too.The variant is detected on install. A new FLUX.3 model starts with the defaults of its variant (steps, CFG,-1024×1024); when you switch from one variant to the other, use **Reset all to model defaults** in the-Generate panel header to take over the new defaults.+1024×1024); when you switch from one variant to the other, use **Apply model defaults** in the+Generate panel header's ↺ menu to take over the new defaults.## License@@ -137,9 +137,9 @@ Add up to **ten** reference images on the Generate tab or the Canvas and describmodel is needed. A single reference is used at up to 4 MP; with several, each is limited to 1 MP.FLUX.3 names its references in the prompt as `<ref_image_0>`, `<ref_image_1>` and so on, for example-`The fox from <ref_image_0> sitting next to the fox from <ref_image_1>`. Each reference card shows its tag; click-the tag to copy it. Only enabled cards with an image are numbered, so turning a card off renumbers the cards below-it.+`The fox from <ref_image_0> sitting next to the fox from <ref_image_1>`. Each reference row shows its tag; click+the tag to copy it. Only enabled references with an image are numbered, so turning one off renumbers the ones below+it. A reference's name is only a label: the tag follows its position.In the workflow editor, wrap each image in a **Kontext Conditioning - FLUX** node and connect them, or a collectionof them, to the **Reference Images** input of **Denoise - FLUX.3**.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdxindex 65bd547390..5d6b588956 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx@@ -236,8 +236,8 @@ the colors hidden under its transparent areas, not a background.as **Edit**. A single first reference starts as **Style**; adding a second image turns it into **Edit** aslong as its strength is still the default. For a LoRA that takes one reference, such as a pose skeleton,switch its **Mode** to **Edit** yourself. A Style reference at strength 0 is not active. The enabled- references are read in card order, which is the order the LoRA's prompt refers to ("Picture 1",- "Picture 2", ...); use the arrows on each card to reorder them.+ references are read in list order, which is the order the LoRA's prompt refers to ("Picture 1",+ "Picture 2", ...); use **Move up** and **Move down** in a reference's menu to reorder them.3. Describe the result in the prompt, as the LoRA's model card suggests, and press **Invoke**.To make a control image from a photo, put the photo on the Canvas as a raster layer and filter it withdiff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdxindex 1574ec8116..10c9d7176c 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx@@ -65,7 +65,7 @@ The VAE needs about 8 GB of working memory to decode a 1024×1024 image, and isWith a Qwen-Image-2.1 model, add up to four images with **Add reference image** in the Guidance section (see [Adding reference images](/users-guide/image-generation/generate-panel/#adding-reference-images)) and say in the prompt what to do with them, for example *put the jacket from the first image on the person in the second* or *the same cat, as a watercolor*. The model reads each reference twice: its Qwen3-VL encoder looks at it alongside the prompt, and the transformer sees it as clean latents next to the image it generates.- **The encoder needs a vision tower.** The Qwen3-VL vision tower reads the images. The Diffusers model's own encoder has one, and so does a non-GGUF Qwen3-VL 8B encoder such as the starter **Qwen3-VL 8B Encoder**, so a single-file, int8 or GGUF transformer offers reference images once that encoder is selected under **Components**. A GGUF Qwen3-VL encoder has none of its own: llama.cpp keeps the tower in a separate `mmproj-*.gguf` file (from `Qwen/Qwen3-VL-8B-Instruct-GGUF`, `mmproj-Qwen3VL-8B-Instruct-F16.gguf`, about 1.1 GB). Install that file as a model, where it appears as a **Qwen3 VL Vision Tower** (the **Qwen3-VL 8B Vision Tower** starter model installs it), and select it as the **Vision Tower** under **Components** beside the GGUF encoder. Without it Generate shows why the section is unavailable, and on a Diffusers model the references refuse to run while a GGUF **Qwen3-VL Encoder** is selected. Only the 8B tower pairs with the 8B encoder, and the tower runs on the encoder's device, so when the encoder is set to CPU Only in the Model Manager, set the tower to CPU Only too, and the field is refused beside any other encoder, which brings its own tower. If an encoder file turns out to carry no vision tower, the run stops and says so.-- **Size.** Each reference is read at about one megapixel at its own aspect ratio, whatever its size. The generated image takes the size set in the panel; **Use size** on a reference's thumbnail matches it.+- **Size.** Each reference is read at about one megapixel at its own aspect ratio, whatever its size. The generated image takes the size set in the panel; **Use size** in a reference's menu matches it.- **Transparency.** The encoder sees a transparent reference over white, as the model was trained; its latents keep the transparency.- **At most four.** A graph or API request with more than four references is refused with an error.- **Memory.** The encoder's vision tower, about 1.1 GB, is loaded only for generations with references and joins the encoder while it reads them; plain prompts never load it, and the encoder itself is not loaded again when you switch between edits and plain prompts. Each reference adds about 4,100 tokens to the start of the sequence, which the model keeps for the whole generation: about 2 GB per reference, twice that with **CFG** above 1. Where that would take more than half of the GPU, Invoke reprocesses the references at every step instead of keeping them, which uses less memory but takes noticeably longer. Reading the references also needs encoder memory that grows quickly with their number: about 7 GB beyond its weights for four, so on a 24 GB card part of the encoder then runs from system memory.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/sdxl.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/sdxl.mdxindex 31e562e42e..6dcfa82b9e 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/sdxl.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/sdxl.mdx@@ -146,9 +146,9 @@ SDXL supports up to **five reference images**, using IP-Adapter models:- **Standard Reference (IP Adapter ViT-H)**- **Precise Reference (IP Adapter Plus ViT-H)** — references the image with higher precision.-Each reference image has a **Mode** — **Style**, **Composition** or **Both** — and a **Weight**. Under-**Advanced**, you can set the range of steps the reference is active for and, in Style mode, choose a-**Style variant** (Standard, Strong or Precise).+Each reference image has a **Weight** on its row and, in its settings (the chevron beside **Weight**), a+**Mode** — **Style**, **Composition** or **Both** — the range of steps the reference is active for and, in+Style mode, a **Style variant** (Standard, Strong or Precise).The starter IP-Adapters carry their own image encoder. The **CLIP Vision** selector next to the modelmatters only for IP-Adapters installed from a single checkpoint file; if the chosen encoder is notdiff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/stable-diffusion-1-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/stable-diffusion-1-2.mdxindex a8f830293c..de6a84c4c2 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/stable-diffusion-1-2.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/stable-diffusion-1-2.mdx@@ -138,9 +138,9 @@ SD 1.5 supports up to **five reference images**, using IP-Adapter models:- **Precise Reference** — references an image more precisely.- **Face Reference** — a precise reference adapted for faces.-Each reference image has a **Mode** — **Style**, **Composition** or **Both** — and a **Weight**. Under-**Advanced**, you can set the range of steps the reference is active for and, in Style mode, choose a-**Style variant** (Standard, Strong or Precise).+Each reference image has a **Weight** on its row and, in its settings (the chevron beside **Weight**), a+**Mode** — **Style**, **Composition** or **Both** — the range of steps the reference is active for and, in+Style mode, a **Style variant** (Standard, Strong or Precise).The starter IP-Adapters carry their own image encoder. The **CLIP Vision** selector next to the modelmatters only for IP-Adapters installed from a single checkpoint file; if the chosen encoder is notdiff --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 fd0c8fe7c2..a2914bb967 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@@ -25,7 +25,7 @@ The panel is divided into sections: the model picker and prompts at the top, folThe **Model** picker at the top of the panel lists the image generation models you have installed, grouped by model family. Type in **Search models…** to find one by name, family or description, or use the family chips to narrow the list. If the list is empty, install a model first; see [Managing media generation models](/users-guide/models/introduction/).-When you switch models, the panel keeps your prompt and settings and adjusts only what the new model cannot use. It snaps the size to the new model's grid and turns off the concepts and reference images the model cannot use. They stay listed, marked **Incompatible**, and run again when you switch back to a model that can use them. A switch that loses nothing applies at once, and a notification with **Undo** lists what it turned off. If the switch would remove a component or reset an option the new model does not have, a **Switch model?** dialog lists what is removed, reset or turned off before you confirm; that switch can be undone too. If your model is no longer installed, the picker says so and generation waits until you choose another model; reinstalling the same file selects it again. Switching does not load the new model's recommended settings; use [Reset all to model defaults](/users-guide/image-generation/generate-panel/#resetting-to-defaults) for that.+When you switch models, the panel keeps your prompt and settings and adjusts only what the new model cannot use. It snaps the size to the new model's grid and turns off the concepts and reference images the model cannot use. They stay listed, marked **Incompatible**, and run again when you switch back to a model that can use them. A switch that loses nothing applies at once, and a notification with **Undo** lists what it turned off. If the switch would remove a component or reset an option the new model does not have, a **Switch model?** dialog lists what is removed, reset or turned off before you confirm; that switch can be undone too. If your model is no longer installed, the picker says so and generation waits until you choose another model; reinstalling the same file selects it again. Switching does not load the new model's recommended settings; use [Apply model defaults](/users-guide/image-generation/generate-panel/#resetting-to-defaults) for that.### Model components@@ -43,13 +43,13 @@ If a required component is missing, **Invoke** is disabled and its tooltip names3. **Press Invoke** in the top bar, or press **Ctrl+Enter** (**Cmd+Enter** on macOS). The job joins the queue, and the top bar shows its progress. The first run with a model takes longer while the model loads.-4. **See the result.** The finished image appears in the Preview and is saved to the Gallery. To stop a run, click the cancel button in the queue area of the top bar, or press **Shift+X**.+4. **See the result.** The finished image appears in the Preview and is saved to the Gallery. To stop the image being generated, click the cancel button in the queue area of the top bar, or press **Shift+X**; between two images it stops the next one, and the button's name says which it will stop. Shift-click the button to cancel all unfinished items, after you confirm: those of the active project, or of all projects, as **Show jobs from** in Settings is set.</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, **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. The **Cache** button in the panel header opens the server caches: **Models** shows how much of the model cache is in use and how often a model was already loaded, with **Clear** to unload unlocked models; **Invocations**, the cache of node outputs reused when a node runs again unchanged, can be cleared, disabled or re-enabled. On a server shared by several people, only administrators see the **Cache** button.+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. To start again from a job's settings, right-click its row and choose **Recall all**, **Remix image**, **Use prompt**, **Use seed**, **Use size** or **Use CLIP skip** under **Recall settings**; an expanded row offers **Recall all** and the same **Recall settings** menu, and <kbd>A</kbd> recalls all of a focused row's settings, as it does in the Gallery. This works whatever the job's state, pending, running, failed or canceled included. Only the browser that queued a job keeps its full settings: for a job queued from another browser, only the prompt and seed the server recorded can be recalled. A workflow job offers nothing to recall, and neither does an Upscale job queued from this browser. Actions a job cannot offer stay listed, unavailable, with the reason beside them. 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. The **Cache** button in the panel header opens the server caches: **Models** shows how much of the model cache is in use and how often a model was already loaded, with **Clear** to unload unlocked models; **Invocations**, the cache of node outputs reused when a node runs again unchanged, can be cleared, disabled or re-enabled. On a server shared by several people, only administrators see the **Cache** button.To see what a panel would run, choose **View graph** from the actions menu in its header (Generate, Canvas, Upscale, Video or Workflow). **Nodes** draws it as the [workflow library](/users-guide/workflows/editor-reference/#your-workflows) previews a workflow: small value nodes fold into labels on the nodes they feed (**Show all** draws every node), markers show the nodes whose values you set and the result, and selecting a node opens a card with its values. A value set in Generate is named for its setting and links to it, such as **Generate → Steps**, which closes the preview and takes you there. **Graph** shows the compiled graph, the JSON the server is sent, which is what a bug report needs; when the panel's settings cannot be compiled, both views say why. For the Workflow panel, **Nodes** shows your node names and notes, even while the workflow does not compile, and **Inputs** shows its form. Beside the nodes are the panel's main settings and where results go, then notices such as a seed drawn afresh for each run, with **Show node**. The bottom of the preview says whether the run can go: **Ready to invoke** or **Can't invoke yet**. Its **Invoke** is the top bar's, for this panel: when something is in the way it counts the issues and opens the same list, each issue with its fix or a way to where it is fixed, which closes the preview. Invoking from there queues this panel's graph and closes the preview. For every panel but Workflow, **Edit as workflow** opens the graph in the workflow editor. Generate's and the Workflow panel's views follow your changes while open, keeping an open card while its node remains; Canvas, Upscale and Video show the graph they last compiled. The **⋯** menu copies or downloads the graph's JSON and opens the workflow in the workflow editor, saves it to the library or forks it into a new project. <kbd>Esc</kbd> closes an open card, then the preview, as does the close button at its top.@@ -77,7 +77,7 @@ The route is saved with the project, so each project remembers where its resultsThe [Generate Panel Reference](/users-guide/image-generation/generate-panel/) describes the rest of the panel in detail:* **[Image size](/users-guide/image-generation/generate-panel/#setting-the-image-size)** — width, height, aspect ratio and the model's optimal size.-* **[Render settings](/users-guide/image-generation/generate-panel/#render-settings)** — steps, CFG or guidance, scheduler, seed, the negative prompt, advanced options, and **Reset all to model defaults**.+* **[Render settings](/users-guide/image-generation/generate-panel/#render-settings)** — steps, CFG or guidance, scheduler, seed, the negative prompt, advanced options, and **Apply model defaults**.* **[Concepts](/users-guide/image-generation/generate-panel/#adding-concepts)** — add LoRAs that teach the model a style, character or object.* **[Reference images](/users-guide/image-generation/generate-panel/#adding-reference-images)** — guide the image by example instead of by words.* **[Prompt tools](/users-guide/image-generation/generate-panel/#prompt-tools)** — expand a prompt, write one from an image, and reuse earlier prompts.diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdxindex 6009fc021b..43c94aca8e 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx@@ -1,7 +1,7 @@---title: Generate Panel Referencedescription: Every section of the Generate panel in detail — size, render settings, negative prompts, advanced options, resetting to defaults, concepts, reference images and the prompt tools.-lastUpdated: 2026-10-29+lastUpdated: 2026-11-12sidebar:order: 1---@@ -10,6 +10,20 @@ import { Steps } from '@astrojs/starlight/components';This page describes each section of the **Generate** panel in detail. For a first walkthrough — choosing a model, generating a first image, and sending results to the Gallery or the Canvas — see [Generating and modifying still images](/users-guide/image-generation/introduction/).+## Working with sections++Below the model and prompt, the panel's settings are grouped into sections, such as **Size**, **Guidance**, **Render** and **Advanced**. The **Upscale** and **Video** panels use the same sections.++* **Open and fold** a section by clicking its title, the tab with the chevron. The panel remembers which sections you keep open. While you scroll through an open section, its title stays pinned at the top of the panel.+* **Alt-click** a title to open that section and fold every other section in the panel. **Shift-click** a title to open every section, or to fold them all when they are all open already.+* With a title focused, **↑** and **↓** move to the previous and next title, **Home** and **End** to the first and last, **→** opens the section, **←** folds it, and **Enter** or **Space** toggles it.+* A folded section shows a summary of its values after its title, such as the size, or the steps, CFG and seed. Open, it shows its fields instead. Badges that flag something, such as **Incompatible** in Guidance or **Shared** in Upscale, show either way.+* A section whose settings differ from their defaults has a dot on its title. A section holding a problem that stops Invoke from running turns its title red and shows how many problems it holds.+* **Right-click** a title (or press the menu key or Shift+F10 while it has focus) for **Fold others**, **Expand all** or **Fold all**, **Copy summary**, which copies the title and its summary, and, where the section can reset its settings, a reset item that names what it resets and where the values come from: **Reset size to model defaults** in Size (*to SDXL defaults*, or another family, when the model sets no size; *to model and SDXL defaults* when it sets only a width or a height), **Reset steps, CFG and scheduler to model defaults** in Render (*to SDXL defaults*, or another family, when the model sets none of them; *to model and SDXL defaults* when it sets some), **Reset to provider defaults** in a hosted model's options, and **Reset section to defaults** in the Canvas compositing section.+* **Jump to section**, the list button in the panel's title bar, lists the sections in order. Choosing one opens it and brings it to the top of the panel.++A field whose value differs from its default shows a small dot in the margin to its left. Click the dot to reset the field; the field keeps the keyboard focus. You can also right-click the field (or press the menu key or Shift+F10 while it has focus) and choose its reset item, or **Copy value**. The reset names where its value comes from: **Reset to model default** when the model's default settings set that value, **Reset to SDXL default** (or the model's family) when they do not, and **Reset to default** for settings no model sets, such as HiDiffusion. Fields show the dot in Size, Render, Refiner and Advanced, including the VAE, VAE precision and the on/off settings there; a setting that is switched off or not used shows no dot.+## Setting the image sizeThe **Size** section sets the width and height of the image.@@ -20,11 +34,11 @@ The **Size** section sets the width and height of the image.* **Swap width and height** turns a landscape image into a portrait one and back.* Each model has an optimal image area, typically about one megapixel for newer models and less for SD 1.5. The line under the fields shows the image's size in megapixels, marks the recommended size, and estimates the run time from your recent runs.* **Reset size**, the button beside **Swap width and height**, opens a menu. Each item shows the size it sets, and the item matching the current size is checked; choosing it again changes nothing:- * **Optimal size for** the current ratio — the model's optimal area at the current aspect ratio, named by its saved name when it has one. It is absent at 1:1, where it would be the native square.- * **Model defaults** — the size set in the model's default settings. It appears only when the model sets one. A locked ratio stays locked and takes the default size's ratio; an unlocked one stays unlocked.- * **Square at native size** — a 1:1 square at the model's native size, such as 1024×1024 for SDXL and FLUX or 512×512 for SD 1.5, with the ratio locked.+ * **Optimal for** the current ratio — the model's optimal area at the current aspect ratio, named by its saved name when it has one. It is absent at 1:1, where it would be the native square.+ * **Model default** — the size set in the model's default settings. It appears only when the model sets one. A locked ratio stays locked and takes the default size's ratio; an unlocked one stays unlocked.+ * **Native square** — a 1:1 square at the model's native size, such as 1024×1024 for SDXL and FLUX or 512×512 for SD 1.5, with the ratio locked.- Right-clicking the width and height and choosing **Reset to model default** also resets the size this way.+ Right-clicking the width and height and choosing **Reset to model default** also resets the size this way; for a model that sets no size the item reads **Reset to** its family's **default** and sets the family's native size, and for one that sets only a width or a height it reads **Reset to model and** family **default** and sets the model's side with the family's value for the other.When the Canvas is where you generate, the section says *Linked to the canvas frame*: the width, height and aspect lock are the generation frame's, and the frame's aspect lock is this one. Any change here, typed, dragged or reset, resizes the frame around its center, and while the canvas is open that resize is a canvas step, so undoing it on the canvas puts the frame and the size back. Resizing the frame on the canvas changes these fields; a frame you resize freely leaves the ratio **Free** even when it happens to match a preset, so only a ratio you choose or lock holds.@@ -32,7 +46,7 @@ Models produce their best results near their optimal size. Much larger images ca## Render settings-The **Render** section controls how the image is generated. Each slider has a mark at the model's recommended value. A field you have changed shows a small dot to its left; click the dot to reset the field to the model default. You can also double-click the field, or open its menu by right-clicking it (or with the menu key or Shift+F10 while it has focus) and choose **Reset to model default**.+The **Render** section controls how the image is generated. Each slider has a mark at the model's recommended value. A field you have changed shows the reset dot to its left (see [Working with sections](#working-with-sections)); you can also double-click a slider to reset it.### Steps@@ -44,7 +58,7 @@ The **Render** section controls how the image is generated. Each slider has a ma### Scheduler-The **Scheduler** is the algorithm that decides how much noise to remove at each step. Schedulers differ in speed, in how many steps they need, and in the character of the result. Euler, the DPM++ family and UniPC are good general-purpose choices; LCM is only for LCM and similar distilled models. The list of schedulers depends on the model, and some models use a fixed schedule and do not show this field. When you have picked another scheduler, the dot to the left of the field switches back to the model's own choice.+The **Scheduler** is the algorithm that decides how much noise to remove at each step. Schedulers differ in speed, in how many steps they need, and in the character of the result. Euler, the DPM++ family and UniPC are good general-purpose choices; LCM is only for LCM and similar distilled models. The list of schedulers depends on the model, and some models use a fixed schedule and do not show this field. When you have picked another scheduler, the dot to the left of the field switches back to the default: the model's own choice when it sets one, otherwise its family's.### Seed@@ -78,9 +92,9 @@ The **Refiner** section appears for SDXL models. Pick an **SDXL Refiner** model### Advanced settings-The **Advanced** section appears for models with extra options, and its header counts the settings you have changed. Depending on the model it can include:+The **Advanced** section appears for models with extra options. Each setting you have changed from the model's default shows the reset dot, and while the section is folded its title shows how many of them there are. Depending on the model it can include:-* **VAE** and **VAE precision** — for SD 1.5 and SDXL, choose a different VAE or decode at FP32 precision. Other families set their VAE in the Components section.+* **VAE** and **VAE precision** — for SD 1.5 and SDXL, choose a different VAE or decode at FP32 precision. The VAE's dot, **Use the bundled VAE**, returns to the VAE bundled with the model. The VAE the model's default settings name counts as unchanged, so it shows no dot and adds no override; to use the bundled VAE instead, clear the VAE field with its × button. Other families set their VAE in the Components section.* **CLIP skip** and **CFG rescale** — SD 1.5 and SD 2.x only.* **HiDiffusion** — improves structure at large sizes for SD 1.5 and SDXL; see [HiDiffusion](/users-guide/image-generation/advanced-topics/hidiffusion/).* **Color compensation** — SDXL only.@@ -93,7 +107,14 @@ Two output filters live in the Generate widget's settings (the cog in its header### Resetting to defaults-Each model has recommended settings, which you can change in the Model Manager. **Reset all to model defaults**, the ↺ button in the Generate panel's title bar, applies them: size, steps, CFG or guidance, scheduler and VAE settings. Your prompts and concepts are left alone, and a notification offers **Undo** to bring your earlier values back. The button is disabled when your settings already match the defaults.+Each model can have default settings, which you set in the Model Manager. The ↺ button in the Generate panel's title bar, **Reset settings**, opens a menu with two choices, each saying under its name what it would change, such as *Steps 30 → 8, CFG 7 → 1*:++* **Apply model defaults** applies only the values the model sets there: any of size, steps, CFG or guidance, scheduler, VAE, VAE precision and CFG rescale. A setting the model leaves unset keeps your value, so a model with no default size leaves your size alone; the menu lists what the model does not set. When the model sets only a width or only a height, that side is applied as if you typed it: a locked aspect ratio carries the other side along, an unlocked one leaves it. The choice is unavailable when the model's values already hold or the model sets no defaults, and it says which.+* **Reset everything to defaults** resets all of those settings: to the model's values where it sets them, and to Invoke's defaults for its family everywhere else, size included. Your VAE stays unless the model sets one; a reset that locks the aspect ratio says so (*Aspect ratio Free → 1:1*).++A default VAE set to the model's own ("Default VAE" in the Model Manager) means the VAE bundled with the model, and either choice returns to it, except for families such as FLUX.1 whose VAE is a separate, required component. A VAE the model names but that is not installed, or does not fit the model, is never applied: both choices keep your VAE, and the menu says so. Recalling an image or parameters that switch to such a model uses the bundled VAE instead, so an image made with it is reproduced; only where a VAE is required and none is bundled does your VAE stay. Newly installed models come with their family's recommended values filled in as their default settings, size included, so **Apply model defaults** sets the size for them until you clear Width and Height under **Default Settings** in the Model Manager.++Either way your prompts and concepts are left alone, and a notification lists what changed and offers **Undo** to bring your earlier values back.To return to the settings of an earlier image instead, open **Use** in the Preview's header, or right-click the image in the Gallery or Preview and open **Reuse from image**. **All settings** restores its model, concepts, prompts, seed, size, render and refiner settings; **Remix image** does the same with a new seed; and **Use prompt**, **Use seed** and **Use size** recall one thing at a time. Recalled concepts replace the ones in the panel at the weights the image used; any that are not installed or do not fit the model are listed in a notice. If the image's model is not installed, or the image was saved from the canvas, your current concepts are kept.@@ -105,7 +126,7 @@ Concepts, also called LoRAs, are small add-on models that teach the main model a<Steps>-1. Click **Add concept** and choose a LoRA. The list only shows LoRAs made for the selected model's family.+1. Under **Concepts**, click the search field and choose a LoRA. The list only shows LoRAs made for the selected model's family.2. Adjust its **Weight**, which sets how strongly it acts. The default is the LoRA's own recommended weight, or 0.75. Values between 0.5 and 1 are typical; higher values can overpower the image, and negative values push the image away from the concept.@@ -113,15 +134,22 @@ Concepts, also called LoRAs, are small add-on models that teach the main model a</Steps>-You can add as many concepts as you like and combine them. Use the switch on each row to turn a concept off without removing it, and the trash button to remove it. If you change to a model from a different family, the concepts it cannot use stay in the list, marked **Incompatible** and switched off; they run again when you switch back to a model they fit. A concept that is no longer installed is marked **Not installed**. CogView4 and external API models don't support concepts, so with one of them selected the section says so instead of offering LoRAs.+You can add as many concepts as you like and combine them. Use the switch on each row to turn a concept off without removing it, and the trash button to remove it. If you change to a model from a different family, the concepts it cannot use stay in the list, marked **Incompatible** and switched off; they run again when you switch back to a model they fit. A concept that is no longer installed is marked **Not installed**, with a warning icon beside its switch: hover it to read the problem, or click it for **Remove**. CogView4 and external API models don't support concepts, so with one of them selected the section says so instead of offering LoRAs.## Adding reference imagesA reference image guides the new image by example rather than by words: its style, its composition, a person or an object in it. Reference images are added at the top of the **Guidance** section, and only appear for models that support them.-To add one, click **Add reference image** and pick images from the Gallery or upload new ones, or drag images from the Gallery onto the section. You can also right-click any image and choose **Use as reference image**. Most models accept up to five. The order of the references matters to some models; use the arrow buttons on each card to reorder them.+To add one, click **Add reference image**, the last row of the **Reference images** list, and pick images from the Gallery or upload new ones, or drag images from the Gallery onto the list. You can also right-click any image and choose **Use as reference image**. Most models accept up to five; the add row counts how many are in use.++Each reference is a row like a concept's: a thumbnail of the image as it will be used (a crop mark shows when it is cropped), its name, a summary of its settings, a switch, and a **⋯** menu. The row's main control, such as **Weight**, sits on the row; the chevron beside it opens the rest of its settings. The switch turns a reference off without removing it; an off reference keeps its settings and shows a grey thumbnail.-Hovering over a reference's thumbnail offers **Crop**, to use only part of the image, and **Use size**, to set the generation's size to match the reference. The switch on each card turns a reference off without removing it.+- **Rename** a reference by double-clicking its name, pressing <kbd>F2</kbd>, or choosing **Rename** in its menu. <kbd>Enter</kbd> or clicking elsewhere keeps the name, <kbd>Esc</kbd> cancels. An empty name, or one that reads like a default, goes back to the default, *Reference image 1*, *Reference image 2* and so on by position. Warnings about a reference use its name. Names are saved with the project and in the metadata of the images they make, and come back when you reuse an image's settings.+- **Reorder** with **Move up** and **Move down** in the menu, or <kbd>Alt</kbd>+<kbd>↑</kbd> and <kbd>Alt</kbd>+<kbd>↓</kbd> while the row has keyboard focus. The order matters to some models.+- **Crop…**, to use only part of the image, **Use size**, to set the generation's size to match the reference, and **Find in Gallery** are in the menu, and as buttons at the foot of a row's open settings.+- **Remove** a reference from its menu, or press <kbd>Delete</kbd> while its row has keyboard focus. A notification offers **Undo**, which puts it back where it was, with its name, crop and settings.+- The menu opens with a right-click, the **⋯** button, or <kbd>Enter</kbd> on a focused row. <kbd>→</kbd> and <kbd>←</kbd> open and close a row's settings.+- A reference that stops Invoke from running shows a warning icon beside its switch, for example when it still needs an IP-Adapter model. Hover the icon to read why, or click it: **Choose model** opens the row's settings at its model picker, and **Turn off** switches the reference off.In the crop dialog, drag the crop box or its handles, or pick an **Aspect ratio** (16:9, 3:2, 4:3, 1:1, 3:4, 2:3 or 9:16) to keep the box in proportion while you resize it. Scroll to zoom in on the image, hold **Space** (or use the middle mouse button) and drag to move the view, and use the **Fit image**, **Actual size**, **Zoom in** and **Zoom out** buttons. **Apply** uses the crop for the reference; **Save to Uploads** also stores the cropped image as an upload in the Gallery without changing the reference.@@ -129,19 +157,19 @@ What a reference does, and what options it has, depends on the model family:| Model family | How references work | Options ||---|---|---|-| **SD 1.5, SDXL** | An IP-Adapter model carries the reference's look into the image. | **Mode**: **Style**, **Composition** or **Both**. **Weight**. Under **Advanced**: the IP-Adapter model, a **Style variant** and the **Active steps** range. |-| **FLUX.1** | An IP-Adapter, or a **FLUX Redux** model, which transfers the reference's content. | IP-Adapter options as above, or **Image influence** (Lowest to Highest) for Redux. |-| **Anima** (not Anima-3.8B) | An Anima IP-Adapter carries a character's appearance (hair, outfit, accessories) into the image. Up to four references (experimental); images of one character combine well, different characters blend. | **Strength** (0 to 2; 0 turns it off), per reference. Under **Advanced**: the IP-Adapter model and the **Active steps** range. |-| **FLUX.1 Kontext** | Kontext edits or recombines the reference images according to your prompt. | None beyond the model. |+| **SD 1.5, SDXL** | An IP-Adapter model carries the reference's look into the image. | **Weight** on the row. In its settings: **Mode** (**Style**, **Composition** or **Both**), a **Style variant** for Style, the **Steps** range it is active for, and the IP-Adapter model with its CLIP Vision encoder. |+| **FLUX.1** | An IP-Adapter, or a **FLUX Redux** model, which transfers the reference's content. | IP-Adapter options as above, or **Image influence** (Lowest to Highest) on the row for Redux, with the Redux model in its settings. |+| **Anima** (not Anima-3.8B) | An Anima IP-Adapter carries a character's appearance (hair, outfit, accessories) into the image. Up to four references (experimental); images of one character combine well, different characters blend. | **Strength** (0 to 2; 0 turns it off) on the row. In its settings: the **Steps** range and the IP-Adapter model. |+| **FLUX.1 Kontext** | Kontext edits or recombines the reference images according to your prompt. | The Kontext model, on the row. || **FLUX.2, Qwen Image Edit, Qwen-Image-2.1** | The model reads the references directly and uses them as your prompt instructs, for example *put the jacket from the first image on the person in the second*. | None. |-| **FLUX.3** | As FLUX.2, with up to ten references. The prompt names them by the tag on each card, such as `<ref_image_0>`; click the tag to copy it. | None. |-| **Krea-2** | **Style**: one reference's look — palette, texture, rendering — is transferred into the image while the prompt keeps driving the content. **Edit**: up to three references for an edit LoRA, such as a pose skeleton or a depth map, read in card order. See [Krea-2 style reference](/users-guide/models/local-models/krea-2/#style-reference) and [edit LoRAs](/users-guide/models/local-models/krea-2/#edit-loras-and-reference-images). | **Mode**: **Style** or **Edit**. **Style strength** (0–2; 0 turns the reference off) for Style. |+| **FLUX.3** | As FLUX.2, with up to ten references. The prompt names them by the tag on each row, such as `<ref_image_0>`; click the tag to copy it. The tag follows the row's position, not its name. | None. |+| **Krea-2** | **Style**: one reference's look — palette, texture, rendering — is transferred into the image while the prompt keeps driving the content. **Edit**: up to three references for an edit LoRA, such as a pose skeleton or a depth map, read in list order. See [Krea-2 style reference](/users-guide/models/local-models/krea-2/#style-reference) and [edit LoRAs](/users-guide/models/local-models/krea-2/#edit-loras-and-reference-images). | **Style strength** (0–2; 0 turns the reference off) on the row for Style, with **Mode** (**Style** or **Edit**) in its settings; an Edit reference has **Mode** on the row. |Reference images require an extra model for SD 1.5, SDXL, FLUX.1 and Anima (an IP-Adapter or FLUX Redux model). These are available as starter models in the Model Manager, and an installed IP-Adapter is selected automatically.Qwen-Image-2.1 reads its references through the Qwen3-VL vision tower, so it needs a Diffusers model, a non-GGUF Qwen3-VL 8B encoder, or a GGUF 8B encoder together with its **Vision Tower** (the `mmproj` file) under **Components**. Without one (a single-file model with no encoder selected, or a GGUF encoder with no Vision Tower) the Guidance section says so instead of offering references. See [Qwen-Image-2.1 reference images](/users-guide/models/local-models/qwen-image-2-1/#reference-images).-A new Krea-2 reference starts as **Style** when it is the only active one; added beside other active references, or several at once, it starts as **Edit**. A Style reference at strength 0 is not active. Adding an image beside a lone Style reference still at its default strength turns that card into **Edit** too; one whose strength was changed keeps its mode. Krea-2 runs either one Style reference or up to three Edit references, never both; Invoke stays disabled and says why until the active references fit. The **Mode** can be changed while a card is switched off. Switching a card back to Style resets its strength to 1.+A new Krea-2 reference starts as **Style** when it is the only active one; added beside other active references, or several at once, it starts as **Edit**. A Style reference at strength 0 is not active. Adding an image beside a lone Style reference still at its default strength turns that reference into **Edit** too; one whose strength was changed keeps its mode. Krea-2 runs either one Style reference or up to three Edit references, never both; Invoke stays disabled and says why until the active references fit. The **Mode** can be changed while a reference is switched off. Switching a reference back to Style resets its strength to 1.## Prompt toolsdiff --git a/docs/src/content/docs/Users Guide/04.Image Generation/parameters.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/parameters.mdxindex eb177a62e3..042d144b8f 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/parameters.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/parameters.mdx@@ -12,7 +12,7 @@ The right settings depend far more on the model than on any general rule. This g## Start from the model's defaults-Each model has recommended settings, which are shown as marks on the sliders and which you can edit in the Model Manager. When you change models, InvokeAI keeps your current settings if they are compatible, so after switching models click **Reset all to model defaults** (the ↺ button in the Generate panel's title bar) to start from the new model's recommendations. Each model family's page under [Local Models](/users-guide/models/model-families/#model-families) lists its typical values.+Each model has recommended settings, which are shown as marks on the sliders and which you can edit in the Model Manager. When you change models, InvokeAI keeps your current settings if they are compatible, so after switching models open **Reset settings** (the ↺ button in the Generate panel's title bar) and choose **Apply model defaults** to take the values the new model sets in its default settings, or **Reset everything to defaults** to start over from the model's and its family's defaults. Each model family's page under [Local Models](/users-guide/models/model-families/#model-families) lists its typical values.## Steps@@ -55,7 +55,7 @@ The seed sets the starting noise, so the same model, prompt, seed and settings r## Size-Each model has an optimal image area, around one megapixel for most current models and less for SD 1.5. Results are best near that size; much larger images can repeat subjects or distort anatomy. Use **Reset size → Optimal size for** *ratio* (for example **Optimal size for 3:2**) in the Size section, and upscale afterwards for larger images. At 1:1 that item is absent; use **Square at native size**, the model's optimal square.+Each model has an optimal image area, around one megapixel for most current models and less for SD 1.5. Results are best near that size; much larger images can repeat subjects or distort anatomy. Use **Reset size → Optimal for** *ratio* (for example **Optimal for 3:2**) in the Size section, and upscale afterwards for larger images. At 1:1 that item is absent; use **Native square**, the model's optimal square.## Denoising strengthdiff --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 284e7a9150..f394d2b272 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@@ -130,7 +130,7 @@ Negative: `photorealistic, dull colors, low detail`## Prompt templates-A prompt template is a reusable piece of prompt text, such as a photographic or artistic style, that wraps whatever you type. Apply **Photography (General)** once, and every prompt you write is sent as a photograph without you retyping the style words. Templates are available in the **Generate** panel.+A prompt template is a reusable piece of prompt text, such as a photographic or artistic style, that wraps whatever you type. Apply **Photography (General)** once, and every prompt you write is sent as a photograph without you retyping the style words. Templates are available in the **Generate** panel and in the [**Upscale**](/users-guide/image-generation/upscale/) panel's **Detail guidance**, which share the project's prompt and its template: a template applied in one applies in the other.### Applying a template@@ -214,7 +214,7 @@ An image's metadata records the prompt that was actually used, with the templateDynamic prompts expand a single prompt into many variations. Write the parts you want to vary as a list of alternatives, and one press of **Invoke** generates an image for each variation. They are useful for brainstorming, exploring styles and subjects, and testing a model without rewriting the same prompt by hand.-Dynamic prompts work in the **Generate** panel, on the Canvas and in the [**Video** panel](/users-guide/video-generation/introduction/#prompt). Only the positive prompt is expanded; the negative prompt is used as written for every variation.+Dynamic prompts work in the **Generate** panel, on the Canvas, in the [**Upscale**](/users-guide/image-generation/upscale/) panel's Refine mode, which shares Generate's prompt and dynamic prompts settings, and in the [**Video** panel](/users-guide/video-generation/introduction/#prompt). Only the positive prompt is expanded; the negative prompt is used as written for every variation.In the **Video** panel each variation queues a full video, so **Max prompts** starts at 10 there instead of 100. Projects saved before Video supported dynamic prompts open with them off, so their prompts keep running as typed; switch on **Use dynamic prompts** to expand them.diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdxindex b505092295..e7d614e694 100644--- a/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx+++ b/docs/src/content/docs/Users Guide/04.Image Generation/upscale.mdx@@ -76,7 +76,7 @@ Switching modes keeps your Refine settings, so switching back restores them. Mod<Callout x={46.72} y={90.26} labelSide="right" label="More settings">Refine only, collapsed until you open them.- - **Detail guidance**: the prompt, marked **Shared** because Generate uses the same project prompt. Describe the medium, texture and style rather than new content.+ - **Detail guidance**: the prompt, marked **Shared** because Generate uses the same project prompt, along with its [prompt template](/users-guide/image-generation/prompting-guide/#prompt-templates) and [dynamic prompts](/users-guide/image-generation/prompting-guide/#dynamic-prompts) settings. Describe the medium, texture and style rather than new content. Each expanded prompt queues its own upscale.- **Generation**: the **Main model** for the detail pass, **Steps**, **CFG scale**, **Scheduler**, **Seed**, and concepts (LoRAs) that match the main model.- **Advanced**: the Tile ControlNet and encoders the main model needs, **Tile size**, **Tile overlap**, **VAE**, **VAE precision**, and **CLIP skip** for SD1.5.</Callout>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 7508701e01..9327ebb4b8 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@@ -72,7 +72,7 @@ If you pick a model that can't run the current combination, the Invoke button te### Prompt-The prompt toolbar carries most of the helpers from the image Generate panel — prompt triggers, prompt expansion, image-to-prompt, history and [dynamic prompts](/users-guide/image-generation/prompting-guide/#dynamic-prompts) (prompt templates are only available in Generate). Each expanded prompt queues a full video, and **Max prompts** defaults to 10 here. Projects saved before Video supported dynamic prompts open with them off. On LTX-2, **Expand Prompt** starts from the enhancer LTX-2.5 was released with and, when a first frame is set, describes the video from that frame — see [prompt enhancement for LTX-2.5](/users-guide/image-generation/prompt-tools/#prompt-enhancement-for-ltx-25). The **negative prompt** behaves per family:+The prompt toolbar carries most of the helpers from the image Generate panel — prompt triggers, prompt expansion, image-to-prompt, history and [dynamic prompts](/users-guide/image-generation/prompting-guide/#dynamic-prompts) (prompt templates are only available in Generate and Upscale). Each expanded prompt queues a full video, and **Max prompts** defaults to 10 here. Projects saved before Video supported dynamic prompts open with them off. On LTX-2, **Expand Prompt** starts from the enhancer LTX-2.5 was released with and, when a first frame is set, describes the video from that frame — see [prompt enhancement for LTX-2.5](/users-guide/image-generation/prompt-tools/#prompt-enhancement-for-ltx-25). The **negative prompt** behaves per family:* **Wan** — used only when CFG is greater than 1 (the field says so). With the Lightning fast path on (CFG 1), it is ignored by the graph.* **MiniMax H3** — hidden entirely. H3 is guidance-distilled and has no CFG, so a negative prompt has nothing to act on.diff --git a/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx b/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdxindex f94c0ad78b..2c973d4245 100644--- a/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx+++ b/docs/src/content/docs/Users Guide/06.Gallery/gallery-reference.mdx@@ -22,7 +22,7 @@ Hover over a board and click its **⋮** button, or right-click it, to open its<Image src={boardMenu} alt="The board menu with Save new results here, Download board, Rename board, Archive board and Delete board." width={420} />-* **Save new results here** — makes this the board that receives new results, marked with a crosshair-style icon in the board list, whichever board you are viewing; it also turns off **Follow the selected board**. On that board, the item is **Stop saving new results here**, which sends results back to the project's Inbox. Not offered for the Inbox itself, date boards, archived boards or boards you can only view. See [Choosing where new media goes](/users-guide/gallery/introduction/#choosing-where-new-media-goes).+* **Save new results here** — makes this the board that receives new results, marked in the board list with the same icon as **Saving to**, whichever board you are viewing; it also turns off **Follow the selected board**. On that board, the item is **Stop saving new results here**, which sends results back to the project's Inbox. Not offered for the Inbox itself, date boards, archived boards or boards you can only view. See [Choosing where new media goes](/users-guide/gallery/introduction/#choosing-where-new-media-goes).* **Download Board** — downloads the board (see [below](#downloading-a-board)).* **Rename board** — opens a dialog to change the name.* **Access** — on a multi-user installation, who else can open the board: **Restricted**, **Everyone can view** or **Everyone can contribute**. Only the board's owner and administrators see it. See [Image Boards](/configuration/multi-user-mode/user-guide/#image-boards).@@ -71,12 +71,12 @@ For an image, the menu offers:* **Load workflow** — open the workflow that made the image. Unavailable for images without one.* **Continue working** — **Edit on Canvas** adds the image to the open project's canvas as an image layer and opens Canvas; **Upscale** sends it to the Upscale panel or upscales it at once; **Send to Video** uses it as the first frame in the Video panel; **Add to Canvas as…** adds it as a layer of the kind you choose; **New project from image** starts a new project whose canvas holds the image, sized to fit it.* **Use image as** — **Use as reference image**, **Use as control** and **Use as prompt template**. Its **Reuse from image** submenu restores the settings that made the image: **Remix image**, **All settings**, **Use prompt**, **Use seed**, **Use size** and **Use CLIP skip**; see [Resetting to defaults](/users-guide/image-generation/generate-panel/#resetting-to-defaults). Settings an image does not record are unavailable.-* **Select for compare** — compare the image with the selected one; **Alt**-click (**Option**-click on macOS) on a thumbnail does the same.+* **Select for compare** — compare the image with the selected one; **Alt**-click (**Option**-click on macOS) on a thumbnail does the same. On the selected image itself, it waits for the next image you select, and reads **Cancel compare** until then.* **Generate PBR maps** — queue normal, roughness and displacement maps of the image. They are saved to the board new results go to, or to the project's Inbox if you can't add to that board (Uncategorized when there is neither), and a notice reports when they are ready. The first run downloads the PBR models.* **Find in Gallery** — select the image in its own board and scroll the grid to it, clearing a search or filter that would hide it.* **Move to board** and **Delete image**.-A video's menu has the equivalent actions for video, including **Extend in Video**, **Use as reference video** and **Use as conditioning clip**. With several items selected, the menu offers the actions that apply to all of them, such as **Star selection**, **Download selection**, **Move to board** and **Delete selection**; for several images it also leads with **Add to Canvas as…** and **New project from images**.+A video's menu has the equivalent actions for video, including **Extend in Video**, **Use as reference video** and **Use as conditioning clip**. With several items selected, the menu offers the actions that apply to all of them, such as **Star selection**, **Download selection**, **Move to board** and **Delete selection**; for several images it also leads with **Add to Canvas as…** and **New project from images**. **Download selection** saves the selected images as a `.zip` file and each video on its own; a selection of more than 1,000 images downloads as several `.zip` files of up to 1,000 images each, and a notice says how many are coming. Your browser may ask you to allow several downloads from the site.Every image generated by InvokeAI also stores its generation metadata inside the file, so the prompt and settings travel with it when you download it.diff --git a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdxindex 8da5ae836d..ea77606fac 100644--- a/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx+++ b/docs/src/content/docs/Users Guide/06.Gallery/introduction.mdx@@ -46,7 +46,7 @@ The new board is selected straight away, so it also becomes the destination for### Choosing where new media goes-**New results go to the board named under Saving to in the Gallery header**, by default the open project's **Inbox**, which the board list marks with a crosshair-style icon. While **Follow the selected board** is off, browsing other boards, **Find in Gallery**, a picker's **Open Gallery** and results revealed from other apps never change it. The destination is fixed when you press Invoke, so you can change it and queue more work while earlier jobs are still running, without redirecting them.+**New results go to the board named under Saving to in the Gallery header**, by default the open project's **Inbox**, which the board list marks with the same icon as **Saving to**. While **Follow the selected board** is off, browsing other boards, **Find in Gallery**, a picker's **Open Gallery** and results revealed from other apps never change it. The destination is fixed when you press Invoke, so you can change it and queue more work while earlier jobs are still running, without redirecting them.* To send results somewhere else, open **Saving to** and choose a board, or choose **Save new results here** from a board's menu. New generations, Canvas saves, pasted media and the results of workflow nodes whose **Board** is set to **Auto** all go there. **Stop saving new results here** on that board's menu goes back to the Inbox.* To have results follow whichever board you are viewing, turn on **Follow the selected board** in the **Saving to** menu or in the [Gallery settings](/users-guide/gallery/gallery-reference/#gallery-settings). While it is on, a date board sends results to the project's Inbox, because date boards are only a view. Choosing a board under **Saving to** turns it off.@@ -136,7 +136,7 @@ Starred items are gathered in a **Starred** section at the top of the board, abo## Uploading media-Click the upload button at the right of the tab bar (**Upload media to …**) and choose files, or drag files from your computer onto the media grid. An empty board also shows **Drop media here or click to upload**. Uploads go to the selected board. Uploaded images appear on its **Uploads** tab and uploaded videos on **Media**; if nothing you uploaded lands on the tab you are viewing, the Gallery switches to the tab that received it and selects the newest upload. You cannot upload to a date board.+Click the upload button at the right of the tab bar (**Upload media to …**) and choose files, or drag files from your computer onto the media grid. An empty board also shows **Drop media here or click to upload**. Uploads go to the selected board. Uploaded images appear on its **Uploads** tab and uploaded videos on **Media**; if nothing you uploaded lands on the tab you are viewing, the Gallery switches to the tab that received it and selects the newest upload. You cannot upload to a date board. Files dropped onto the [Canvas](/users-guide/canvas/introduction/#adding-a-gallery-image-to-a-layer) or the Preview are uploaded too, to the board new results go to.You can upload:@@ -171,7 +171,7 @@ Before deleting, InvokeAI checks what still uses the items, and the confirmation* Your queued or running jobs that use the items. Those jobs fail if you delete the media.* **Other accounts' work**, on a server with several accounts: how many items other people's projects, workflows or jobs use, without saying whose.-When something uses the items, the confirmation always appears, even if you turned confirmations off; deleting a single visible item without confirmation waits a few seconds for the check and still asks when it finds a use or cannot finish. **Delete** stays available, so you can delete anyway, and anything that used the media then points at a missing file. In the projects InvokeAI opens to check, a Gallery selection or image search, the recent results strip, the compare image, a workflow's last run and the last submitted Generate, Upscale or Video graph do not count as uses; neither do this session's queue, run log and undo history. A project open in this tab is checked as you have it now, unsaved changes included; if it was saved from another tab or device since this tab last loaded or saved it, the saved version is checked as well, and a use in either counts; if the saved version cannot be checked, the project keeps every item the server found in it, with a note saying so. A project it could not open to check (it is very large, could not be read, or is past the few it opens) is listed with every item it mentions, these included, and so is other accounts' work. If the check cannot reach the server, or too many items are selected to check them all, the confirmation says so: only the projects open in this tab were checked. When the check fails, **Retry** runs it again. With confirmations off, a deletion that needs to ask while another confirmation is open is not carried out, and a notice says to answer the open one first, or to wait for a deletion already under way.+When something uses the items, the confirmation always appears, even if you turned confirmations off; deleting a single visible item without confirmation waits a few seconds for the check and still asks when it finds a use or cannot finish. **Delete** stays available, so you can delete anyway, and anything that used the media then points at a missing file. In the projects InvokeAI opens to check, a Gallery selection or image search, the recent results strip, the compare image, a workflow's last run and the last submitted Generate, Upscale or Video graph do not count as uses; neither do this session's queue, run log and undo history. A project open in this tab is checked as you have it now, unsaved changes included; if it was saved from another tab or device since this tab last loaded or saved it, the saved version is checked as well, and a use in either counts; if the saved version cannot be checked, the project keeps every item the server found in it, with a note saying so. A project it could not open to check (it is very large, could not be read, or is past the few it opens) is listed with every item it mentions, these included, and so is other accounts' work. If the check cannot reach the server, the confirmation says so: only the projects open in this tab were checked. When the check fails, **Retry** runs it again. With confirmations off, a deletion that needs to ask while another confirmation is open is not carried out, and a notice says to answer the open one first, or to wait for a deletion already under way.If deleting is interrupted, InvokeAI cleans up any leftover files the next time it starts.diff --git a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdxindex 1ad6c84c7c..3ec2f83377 100644--- a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx@@ -39,7 +39,7 @@ The Layers panel groups layers by type, in the stacks **Inpaint Masks**, **Regio<Image src={addLayerMenu} alt="The Add layer menu with Inpaint mask, Regional guidance, Regional reference image, Control layer, Raster layer and New group." width={500} />-Each layer row has an eye button on the right. A hidden layer is off the canvas and takes no part in generation. To only get a mask, regional guidance or control layer out of view while it still affects generation, choose **Hide on canvas only** in its right-click menu. **Shift+H** does that for all of them at once so you can see the image underneath.+Each raster layer row has an eye button on the right: a hidden raster layer is off the canvas and takes no part in generation. Mask, regional guidance and control layer rows have a dot before the eye as well. The dot decides whether the layer takes part in generation, and the eye only gets the layer out of view while it still affects generation. **Shift+H** does that for all of them at once so you can see the image underneath.### Settings live in the Properties pane@@ -120,7 +120,7 @@ Regional guidance gives one area of the image its own prompt. For example, keep2. **Paint the region** with the **Brush**, or draw it with the **Shape** tool. It shows as a tinted overlay.-3. **Enter the region's prompt.** With the layer selected, open **Properties** and scroll down to its **Layer** section. Type in **Positive prompt**, and optionally **Negative prompt**. The prompt is saved when you click away from the field.+3. **Enter the region's prompt.** With the layer selected, open **Properties** and scroll down to its **Layer** section. Type in **Positive prompt**. To keep something out of the region as well, click **+ Negative prompt…** and type in **Negative prompt**. Each prompt is saved when you click away from its field.4. **Press Invoke.** The main prompt still describes the whole image; the regional prompt applies inside the region.@@ -143,7 +143,7 @@ A control layer shapes the composition with a guide image: the edges of a sketch* Right-click an image in the Gallery and choose **Use as Control**. It fills the selected control layer if that layer has no image yet, and otherwise adds a new control layer.* Right-click a raster layer and choose **Use as control layer**, which copies its pixels to a new control layer.* Drag an image from the Gallery onto the canvas and drop it on **Add as control layer**. As with **Use as Control**, it fills the selected control layer if that layer is still empty.- * Select an empty control layer and drop an image file from your computer onto the canvas, where the layer shows *Drop an image here*. The file is uploaded into that layer.+ * Drag an image file from your computer onto the canvas and drop it on **Add as control layer**. It is uploaded to the Gallery first, then fills the selected control layer if that layer is still empty, as a Gallery image does.2. **Choose the Type**: **Pose**, **Depth**, **Edges**, **Soft edges**, **Line art**, **Sketch**, **Color** or **Tile**. Next to each type, the menu says how many installed models are made for it, *via Union* when only a Union model covers it, or *Not installed*.@@ -173,9 +173,10 @@ The tool strip also has shape, gradient and text tools, which are described in t## Adding a gallery image to a layer-There are three ways to bring an existing image onto the canvas:+There are four ways to bring an existing image onto the canvas:* **Drag it from the Gallery.** With the Gallery and the Canvas both on screen (for example, the Compose layout with its center view switched to Canvas), drag an image onto the canvas. Drop zones appear: **Add as raster layer**, **Add as control layer**, **Add as regional reference image**, **Add as inpaint mask** and **Add as resized control layer**, which scales the image to the model's optimal size.+* **Drag it from your computer.** Drag one or more image files (PNG, JPEG or WebP) from your file manager or the desktop onto the canvas. The same drop zones appear. The files are uploaded to the Gallery, to the board new results go to, and then added as the zone says. Other kinds of files are refused with a notice. While an operation such as a filter is running, the canvas says it is busy and takes no drop, and until an upload finishes, another drop is refused. An image dragged from a web page often arrives as a link rather than a file; save it first, then drag the file.* **Use the image's menu.** Right-click an image in the Gallery or Preview, or open **Edit** in the Preview's header. **Edit on Canvas** adds it as an image layer and opens Canvas; **Add to Canvas as…** lets you choose the kind of layer. **New project from image** instead starts a new project whose canvas holds the image, sized to fit it; the current project is left as it is.* **Paste it.** Copy an image, click the canvas and press **Ctrl+V** (**Cmd+V** on macOS). It is added as a new raster layer at the generation frame.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 810c78fc7c..cbd17f550f 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@@ -18,13 +18,13 @@ Each project has one canvas. It opens in the center of the **Edit** layout (**Al## Tools-The tool strip on the left edge of the canvas holds the drawing and editing tools; hover a tool to see its key. A tool's options appear in the **Tool** section of the **Properties** tab in the Layers panel, not on the canvas. A new canvas opens on the Brush (an older project whose empty inpaint mask is selected opens on View, so a first stroke never paints the mask by surprise); after that, each project remembers the tool you were using.+The tool strip on the left edge of the canvas holds the drawing and editing tools; hover a tool to see its key. A tool's options appear in the **Tool** section of the **Properties** tab in the Layers panel, not on the canvas. A new canvas opens on the Brush (an older project whose empty inpaint mask is selected opens on Pan, so a first stroke never paints the mask by surprise); after that, each project remembers the tool you were using.-A tool that cannot change the selected layer says so instead of doing nothing: the pointer shows a no-entry sign over the canvas, and a press explains that the layer is hidden or locked, or still loading. With a locked or hidden image layer selected, the Brush offers **Paint on a new layer** rather than adding one unasked. The new layer goes above that layer, or above the group that locks or hides it, and is selected; pressing again replaces the offer instead of adding another.+A tool that cannot change the selected layer says so instead of doing nothing: the pointer shows a no-entry sign over the canvas, and a press explains that the layer is hidden, left out of generation, locked, or still loading. The Brush, Eraser, Shape and the selection's **Fill** and **Erase** also refuse a layer hidden with **Hide on canvas**, so nothing is painted out of sight. The Eraser works on paint layers, images, control layers and masks: with a group, text, shape or gradient layer selected, or nothing, it says so rather than adding an empty layer. The Gradient tool does not add a gradient while an inpaint mask or regional guidance layer is selected. With a locked or hidden image layer selected, the Brush offers **Paint on a new layer** rather than adding one unasked. The new layer goes above that layer, or above the group that locks or hides it, and is selected; pressing again replaces the offer instead of adding another.| Tool | Key | What it does ||---|---|---|-| **View** | **H** | Pan by dragging. Hold **Space** to pan from any tool. |+| **Pan** | **H** | Pan by dragging. Hold **Space** to pan from any tool. || **Move** | **V** | Move the selected layers. **Shift** locks the direction. Dragging inside a selection lifts the selected pixels so you can move them; **Enter** places them. || **Transform** | **Shift+T** | Scale and rotate the selected layer with handles. See [Transforming layers](#transforming-layers). || **Generation frame** | **C** | Move and resize the generation frame. Tap **C** to switch to it, or hold **C** to use it briefly. |@@ -36,7 +36,7 @@ A tool that cannot change the selected layer says so instead of doing nothing: t| **Marquee select** / **Lasso select** | **M** / **L** | Select an area of pixels. Press **M** again to switch between rectangle and ellipse, or **L** again for freehand and polygon. || **Color picker** | **I** | Pick a color from the canvas (see below). |-The Shape and Select buttons hold several tools. Click to use the current one, or press and hold (or right-click, or press **→** on) the button to choose another from a menu that lists each tool with its shortcut. To pick a color from the canvas, hold **Alt** with the Brush, Eraser, Gradient, Text or View tool and click, or press **I** for the Color picker tool. Move, Transform, the Generation frame, Shape and the selection tools use **Alt** themselves, so holding it there changes their drag instead. While you pick, a round **loupe** follows the pointer: it magnifies the pixels around it, boxes the pixel that will be picked in the center, and shows that pixel's RGB values. The pointer itself is hidden, so aim with the boxed pixel. You can drag to sample as you go; the color is set when you release, and **Escape** cancels the pick and restores the previous color. The picked color goes to what you are editing:+The Shape and Select buttons hold several tools. Click to use the current one, or press and hold (or right-click, or press **→** on) the button to choose another from a menu that lists each tool with its shortcut. To pick a color from the canvas, hold **Alt** with the Brush, Eraser, Gradient, Text or Pan tool and click, or press **I** for the Color picker tool. Move, Transform, the Generation frame, Shape and the selection tools use **Alt** themselves, so holding it there changes their drag instead. While you pick, a round **loupe** follows the pointer: it magnifies the pixels around it, boxes the pixel that will be picked in the center, and shows that pixel's RGB values. The pointer itself is hidden, so aim with the boxed pixel. You can drag to sample as you go; the color is set when you release, and **Escape** cancels the pick and restores the previous color. The picked color goes to what you are editing:* the selected mask's tint, while **Mask tint** is chosen in the [Color](/users-guide/canvas/layers-panel/#color) tab;* the selected shape layer's fill when the foreground chip is active, or its stroke when the background chip is active. A pick never turns on a fill or stroke the shape doesn't have; it sets the active color instead;@@ -54,7 +54,7 @@ The Brush, Eraser, Shape and Text options are remembered for your account, so th* **Shape** — settings for the next shape: its **Kind**, a row of buttons showing each shape (point at one for its name), and **Place on**, which draws on the **Selected layer** or on a **New layer** of its own. Only a paint layer, an inpaint mask or a regional guidance layer takes shape pixels. With anything else selected, or nothing selected, **Selected layer** is unavailable and **New layer** shows where the shape will go; a note below explains why. Your placement preference returns when you select a paint layer or mask. Under the tool's **Appearance** group, **Fill**, **Stroke** and stroke **Width** set the next shape's defaults. To edit an existing shape's appearance, use the **Layer** section below the tool options; those controls stay available with any tool active and each gesture is one undoable step. **Shift** constrains the proportions, **Alt** draws from the center, and **Shift+Alt** does both. **Ctrl** (**Cmd** on macOS) cuts the shape out of the selected paint layer or mask instead of drawing it, whatever **Place on** says: it erases like the Eraser and never adds a layer. With no paint layer or mask selected, a notice says so and nothing is drawn. For polygons, click to place points and double-click, press **Enter** or click the first point to close the shape; **Escape** drops the points without drawing anything. With an inpaint mask or regional guidance layer selected, the shape is added to the mask or region, which makes shapes a quick way to mark rectangular or geometric areas; the colors are ignored.* **Gradient** — **Kind** (Linear or Radial), **Angle**, and the color **Stops**, which can be added and removed or follow the foreground and background colors. Dragging creates a gradient layer the size of the generation frame, or repositions the selected gradient layer.* **Text** — the font **Family**, **Style** or **Weight**, **Size**, **Line height**, **Align** and **Fill** color. Click the canvas to start typing; **Ctrl+Enter** or clicking elsewhere finishes the text, and **Escape** cancels it. The text stays editable as a text layer.-* **Marquee select** and **Lasso select** — the **Shape** and the selection **Mode** (Replace, Add, Subtract or Intersect). **Shift** adds to the selection and **Alt** subtracts from it. A polygon lasso closes like a polygon shape, and **Escape** drops its points while keeping the current selection. The **Actions** fill or erase the selection, lift it to a **New layer**, **Invert** it, select everything, or **Deselect**.+* **Marquee select** and **Lasso select** — the **Shape** and the selection **Mode** (Replace, Add, Subtract or Intersect). **Shift** adds to the selection and **Alt** subtracts from it. A polygon lasso closes like a polygon shape, and **Escape** drops its points while keeping the current selection. The **Actions** fill or erase the selection on the selected paint layer, image, control layer or mask (a mask gets full coverage), lift it to a **New layer**, **Invert** it, select everything, or **Deselect**.### Fonts@@ -67,13 +67,13 @@ If a project uses a font that is not installed, a dialog lets you retry, uploadSelections restrict painting: while an area is selected, brush strokes stay inside it. **Ctrl+A** selects all, **Ctrl+D** deselects and **Ctrl+Shift+I** inverts the selection.:::note[Changed from v6]-In InvokeAI 6, the Lasso drew directly into an inpaint mask, and created one if needed. In v7, the Lasso and Marquee make pixel selections on any layer instead, and the selection's **Fill** and **Erase** actions apply to raster layers only. To mask an irregular area, select it with the Lasso, select the inpaint mask or regional guidance layer, and paint over the area with a large Brush: the strokes stay inside the selection.+In InvokeAI 6, the Lasso drew directly into an inpaint mask, and created one if needed. In v7, the Lasso and Marquee make pixel selections on any layer instead. To mask an irregular area, select it with the Lasso, select the inpaint mask or regional guidance layer, and choose **Fill** in the selection's actions (or paint over the area: brush strokes stay inside the selection).:::## Navigating the canvas* **Zoom** with the mouse wheel, which zooms around the pointer, or choose a level from the zoom menu in the header (25% to 500%). **Ctrl+1**, **Ctrl+2**, **Ctrl+3** and **Ctrl+4** zoom to 100%, 200%, 400% and 800% around the center of the view. Many browsers use these keys to switch tabs and do not pass them to the page; there, choose **Zoom to 100%**, **Zoom to 200%**, **Zoom to 400%** or **Zoom to 800%** from the command palette (**Ctrl+K**), or assign other keys in **Settings → Hotkeys**.-* **Pan** with the View tool, by holding **Space**, or by dragging with the middle mouse button.+* **Pan** with the Pan tool, by holding **Space**, or by dragging with the middle mouse button.* **Fit to view**, at the top of the header's zoom menu, fits the generation frame and all layers into the window.## The header@@ -109,13 +109,13 @@ The frame is not a mask: everything inside it can change in image-to-image. To r### Frame size and processing size-The frame is the final footprint of the generation on the canvas. With **Render at** (at the bottom of the Generate panel's **Size** section; legacy versions called it *Scale before processing*) set to **Optimal for model** or **Custom**, InvokeAI generates at a different resolution, such as the model's optimal size, and then resizes the result to fit the frame. When the two differ, the Size section's badge shows both, frame first, and its preview outlines the render size with a dashed line. **Optimal for model** only enlarges a frame smaller than the model's optimal size; it never shrinks a larger one. Choose a frame large enough to include the context the model needs, while keeping it within a size the model and your GPU memory handle well.+The frame is the final footprint of the generation on the canvas. With **Render at** (at the bottom of the Generate panel's **Size** section; legacy versions called it *Scale before processing*) set to **Optimal for model** or **Custom**, InvokeAI generates at a different resolution, such as the model's optimal size, and then resizes the result to fit the frame. When the two differ, the Size section's badge shows both, frame first, and its preview outlines the render size with a dashed line. The canvas's top-right corner shows them too: **Frame** is the frame's size, and **Render**, shown only when it differs, is the size the model generates at. It follows the frame while you drag it, and hides when the canvas is too small to fit it. **Optimal for model** only enlarges a frame smaller than the model's optimal size; it never shrinks a larger one. Choose a frame large enough to include the context the model needs, while keeping it within a size the model and your GPU memory handle well.**Optimal for model** is the default, including for older projects that never saved a choice. Those projects previously generated at the frame's size. Processing at a different resolution can change the result for the same seed, generation time, and GPU memory use. To generate at the frame's exact size, choose **Frame size**; saved choices are preserved.## Transforming layers-Choose **Transform** from a layer's menu, or press **Shift+T**, to scale and rotate the selected layer. The handles appear at once, even when the Transform tool is already active; if a brush stroke is still being saved, the tool switches straight away and the handles appear when the stroke is saved. Transform works on enabled raster and control layers with content.+Choose **Transform** from a layer's menu, or press **Shift+T**, to scale and rotate the selected layer. The handles appear at once, even when the Transform tool is already active; if a brush stroke is still being saved, the tool switches straight away and the handles appear when the stroke is saved. Transform works on any enabled layer with content, inpaint masks and regional guidance included. Painted pixels (a paint layer, or a control layer you have painted on) are redrawn at their new size; every other layer, inpaint masks and regional guidance included, keeps its pixels and only its placement changes. A transformed mask's fill pattern and new brush strokes follow its scale and rotation, and **Invert mask** on a rotated mask inverts the generation frame's bounding box as the mask sees it; generation reads the mask through its transform, so results are unaffected.* Drag a corner or edge handle to scale. **Shift** scales proportionally and **Alt**, held before or during the drag, scales from the center.* Drag just outside a corner to rotate. **Shift** rotates in 15° steps.@@ -136,9 +136,9 @@ To crop a layer to the generation frame, choose **Crop layer to frame** from its* **Blur & noise** — Content shuffle, Blur and Noise.* **Upscale** — an upscaling model.-Choose a filter and its settings in Properties, click **Process** (or turn on **Process automatically**) to preview the result, then **Apply** it. The arrow next to Apply offers **Apply as** a new raster or control layer instead. Edge, depth and pose filters produce the guide images that control layers need.+Choose a filter and its settings in Properties, click **Process** (or turn on **Auto-update preview**) to preview the result, then **Apply** it. When a preview fails, **Process** appears with the error even while auto-update is on, so you can run the same settings again. The arrow next to Apply offers **Apply as** a new raster or control layer instead. Edge, depth and pose filters produce the guide images that control layers need.-**Select object**, in a layer's menu, finds an object automatically with a segmentation model. Its settings open in the **Properties** tab, headed *Operation: Select Object*. Click the object to add points (Shift-click marks areas to exclude), or describe it by text, then **Process** and **Apply**, or save the result as a selection or a new layer.+**Select object**, in a layer's menu, finds an object automatically with a segmentation model. Its settings open in the **Properties** tab, headed *Operation: Select Object*. Under **Select by**, choose **Points & box** and click the object to add points (Shift-click marks areas to exclude) or drag a box around it, or choose **Prompt** and describe it by text; switching between the two keeps what you entered in each. With **Auto-update preview** on (the default, under **Settings**), the preview follows every change; with it off, click **Find object**. When a run fails, **Find object** appears with the error either way, so you can try the same points, box or prompt again. Pressing Enter in the prompt finds the object at once. Then **Apply** the result, or use the arrow next to Apply to save it as a selection or a new layer. **Reset** clears the points, box and prompt, and puts **Invert**, **Model**, **Refine edges** and **Show only the object** back to their defaults; **Auto-update preview** stays as you set it.## Running a workflow on a layer@@ -154,7 +154,7 @@ Then click **Run**. If the workflow has no image input and output it can connectWhen the Canvas is the destination, results appear in the staging area at the bottom of the canvas, not directly on it. The staging bar lets you:-* Step through the results with the arrows in the bar, with **Alt+[** and **Alt+]** on the canvas, or with **←** and **→** while the staging bar has focus (moving between thumbnails selects them), and show or hide the result thumbnails.+* Step through the results with the arrows in the bar, with **Alt+[** and **Alt+]** on the canvas, or with **←** and **→** on the canvas or in the staging bar (the arrow keys move between thumbnails and select them, while <kbd>Tab</kbd> passes the thumbnails in one stop, on the selected one; with the Move or Transform tool active, **←** and **→** on the canvas nudge the selected layer instead), and show or hide the result thumbnails.* **Accept to layer** — add the current result as a new raster layer at the top of the raster layers and close the staging area.* A selected inpaint mask, regional guidance or control layer that you can still edit stays selected, so you can carry on painting it. Otherwise the new layer is selected.* The other staged results are set aside; the notice says how many and its **Review the other** button brings them back for review. Undoing the accepted layer on the canvas removes the layer but does not return the result to staging.@@ -162,14 +162,14 @@ When the Canvas is the destination, results appear in the staging area at the bo* The arrow next to it offers **Keep as hidden layer**, which adds the result as a hidden layer (left out of generation) and keeps staging open and the batch running.* **Save to gallery** the current result, **Discard** it (**Delete** while the staging bar has focus), or **Discard all**. Each discard has **Undo**. **Discard all** also stops what is still generating for this canvas (Undo brings back the results, not the stopped generation), and keeps a restore point in the History tab.* Hide the preview of the current result to compare it with the canvas underneath.-* **Auto-switch** — show each new result as it arrives (**Newest**), follow the one in progress (**In progress**), or stay on the current one (**Off**).-* **Cancel** the running generation.+* **Auto-switch** — show each new result as it arrives (**Newest**), follow the one in progress (**In progress**), or stay on the current one (**Off**). It works as the Preview's does. **In progress** keeps each finished result selected until the next image shows its first preview, so the canvas never goes blank between images. Choosing a result yourself — clicking or right-clicking its thumbnail, or stepping to it with the arrows in the bar or the arrow keys — steers Auto-switch; moving focus with <kbd>Tab</kbd> does not. Choosing a finished result turns Auto-switch **Off** until you choose a mode again; choosing an image that is still generating turns it to **In progress** and keeps that image selected while it generates, even when another one starts beside it. Choosing **In progress** from the menu shows an image already generating at once.+* **Stop generating** — stop every generation still running for this canvas, while any image is still to come. The results already staged stay for review.Right-click a result's thumbnail to recall its settings into the Generate panel. The bar also says how many results are pending, counting the ones still generating.The canvas stays editable while results are staged or a canvas generation runs: every tool, layer action and shortcut works as usual. Each result keeps its place. It lands where the generation frame was when you pressed **Invoke**, and the canvas outlines that spot with a dashed amber frame for each pending result (thicker for the selected one). Moving or resizing the generation frame afterwards only affects the next **Invoke**; the results, and the live progress image, stay where they were. **Accept to layer** adds the result above all raster layers as they are at that moment, whatever you painted, added or deleted meanwhile, and first places any pixels you are still moving and applies a transform you have not applied yet.-While a progress image or a staged result is shown, inpaint masks, regional guidance and regenerate regions are hidden from view so they do not cover the result. They still take part in generation. They reappear when you hide the preview or accept or discard the results. While you paint, erase, drag out a shape on or move an inpaint mask or regional guidance layer, they show over the result so you can see what you change, and hide again when you let go. Panning, zooming and picking colors keep them hidden.+While a progress image or a staged result is shown, only raster layers are drawn: control layers, inpaint masks, regional guidance and regenerate regions are hidden from view so they do not cover the result. They still take part in generation. They stay hidden while you hide the preview with the eye button to compare the result with the canvas under it, and reappear when you accept or discard the results. While you change a control layer (paint, erase, move or transform it, or move a selection of its pixels), or paint, erase, move, transform or drag out a shape on an inpaint mask or regional guidance layer, the hidden layers show over the result, and regenerate regions around it, so you can see what you change. They hide again when you let go, or when you apply or cancel the transform or the moved pixels. Panning, zooming, picking colors and nudging a layer with the arrow keys keep them hidden. So do the selection's **Fill** and **Erase**, **Delete** on a selection, and **Cut** (**Ctrl+X**, **Cmd+X** on macOS): on a control layer, inpaint mask or regional guidance layer they make their change out of sight, and you see it once you accept or discard the results. While a result hides a control layer, the canvas does not offer its Original, Map and Overlay views.## The canvas menu@@ -209,7 +209,7 @@ The canvas belongs to its project and is saved with it automatically. To keep a## Copying and pasting-* **Ctrl+C** copies the selected pixels, and **Ctrl+X** cuts them.+* **Ctrl+C** copies the selected pixels, and **Ctrl+X** cuts them: it copies them, then removes them from the selected paint layer, image, control layer or mask. When the layer cannot give them up (a group, a text or shape layer, a locked layer), Cut copies nothing and says why.* **Ctrl+V** pastes an image from the clipboard as a new raster layer at the generation frame.* **Ctrl+J** duplicates the selected layer, or copies the selected pixels to a new layer.diff --git a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdxindex 6a286ae7fe..07fe754ca0 100644--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx@@ -17,7 +17,7 @@ The **Layers** panel sits to the right of the Canvas in the **Edit** layout. ItDrag the dividers between the parts to resize them, and use the chevron at the right of the Color and Properties tabs to collapse them. The sizes are saved with the project.-<Image src={layersPanel} alt="The Layers panel: the color wheel at the top; the layer list with Inpaint Masks, Regional Guidance, Control Layers and Raster Layers, each row ending in an eye and a lock in one column; an Exposure adjustment as a child row under the City raster layer, joined to it by a connector line, its eye in the same column; and the Properties pane showing the selected depth control layer's settings." width={420} />+<Image src={layersPanel} alt="The Layers panel: the color wheel at the top; the layer list with Inpaint Masks, Regional Guidance, Control Layers and Raster Layers, the mask, regional guidance and control rows ending in a dot, an eye and a lock and the raster rows in an eye and a lock, the eyes and locks each in one column; an Exposure adjustment as a child row under the City raster layer, joined to it by a connector line, its eye in the same column; and the Properties pane showing the selected depth control layer's settings." width={420} />For an introduction to the layer types, see [Crafting images with the Canvas](/users-guide/canvas/introduction/#canvas-concepts).@@ -27,7 +27,7 @@ The **Color** tab edits the two painting colors: the **Foreground color**, which* The color wheel, or a box picker via **Switch to box picker**, and the hex value, always shown. The format button next to it cycles through hex only, RGB, HSB and HSL, adding a field for each channel.* **Swap foreground and background colors** (**X**) and **Reset colors to black and white** (**D**).-* **Pick a color from the canvas** — the eyedropper. You can also hold **Alt** on the canvas with the Brush, Eraser, Gradient, Text or View tool. A magnifying loupe shows the pixel under the pointer and its RGB values; see the [Canvas guide](/users-guide/canvas/canvas-guide/#tools).+* **Pick a color from the canvas** — the eyedropper. You can also hold **Alt** on the canvas with the Brush, Eraser, Gradient, Text or Pan tool. A magnifying loupe shows the pixel under the pointer and its RGB values; see the [Canvas guide](/users-guide/canvas/canvas-guide/#tools).* When an inpaint mask or regional guidance layer is selected, a third chip, **Mask tint**, edits the color of its overlay.Picking with **Alt** on the canvas writes to what you are editing: the mask tint while **Mask tint** is chosen, the selected shape layer's fill (foreground chip) or stroke (background chip), the selected text layer's color, and otherwise the active foreground or background color. A pick never turns on a fill or stroke the shape does not have: on such a shape it sets the active foreground or background color instead. A pick that changes a layer is one undoable step. The eyedropper button sets the mask tint while **Mask tint** is chosen, and otherwise the active foreground or background color.@@ -46,13 +46,15 @@ Each row shows, from left to right:* A colored stripe, if you gave the layer a color label.* A thumbnail, the layer type and the name.-* On masks, regional guidance and control layers hidden with **Hide on canvas only** (in the layer menu), a closed-eye button: the layer is off the canvas but still affects generation. Click it to show the layer again.-* An eye button (**Show or hide layer**). A hidden layer is off the canvas and takes no part in generation.+* On inpaint masks, regional guidance and control layers, two buttons, so a layer can be out of view yet still shape the image:+ * A dot (**Use in generation**). Filled, the layer takes part in generation; click it to leave the layer out, and it is then neither drawn on the canvas nor used. A dashed ring means the layer is on but a group above it is left out.+ * An eye (**Show on canvas**), which only takes the layer off the canvas: it still affects generation. While the dot is off, the eye is dimmed but keeps its setting for when the layer is used again.+* On raster layers, one eye button (**Show or hide layer**). A hidden raster layer is off the canvas and takes no part in generation.* A lock button (**Toggle lock**), which prevents editing. Painting, moving or transforming a locked layer is refused with a notice that says so.-Rows can have child rows, shown with a chevron: adjustments and regenerate regions on raster layers, noise and denoise limits on inpaint masks, and reference images on regional guidance layers. A child row shows its icon (or the reference image), its name, its value where it has one, and its own eye button (**Enable/disable**), which turns it off without removing it. While its layer is hidden, a child row's eye is dimmed and the child has no effect. Select a child row to edit it in Properties. Thin lines run from each expanded layer or group down to its child rows and the layers inside it, so you can see what belongs where.+Rows can have child rows, shown with a chevron: adjustments and regenerate regions on raster layers, noise and denoise limits on inpaint masks, and reference images on regional guidance layers. A child row shows its icon (or the reference image), its name, its value where it has one, and its own eye button (**Enable/disable**), which turns it off without removing it. While its layer takes no part in generation, a child row's eye is dimmed and the child has no effect. Select a child row to edit it in Properties. Thin lines run from each expanded layer or group down to its child rows and the layers inside it, so you can see what belongs where.-The eye buttons of layers and child rows line up in one column at the right edge of the list, with the lock buttons in a column beside them, however deeply a layer is nested in groups.+The eye buttons of layers and child rows line up in one column at the right edge of the list, with the lock buttons in a column beside them and the dots of mask, regional guidance and control rows in a column before them, however deeply a layer is nested in groups.Drag an adjustment to reorder it, or drop it on another raster layer or group, or among that layer's adjustments, to move it there as one undoable step. Reference images move between regional guidance layers the same way. A child row's right-click menu also has a **Move to layer** submenu listing the layers that can take it.@@ -63,7 +65,7 @@ Drag an adjustment to reorder it, or drop it on another raster layer or group, o* **Rename** a layer by double-clicking its name or pressing **F2**. **Enter** saves and **Escape** cancels.* **Reorder** layers by dragging them, or with **Alt+↑** and **Alt+↓**. Layers can only move within their own stack.* **Blend mode** and **Opacity**, in the row above the list, apply to the selected layer. There are 16 blend modes, from Normal and Multiply to Color and Luminosity.-* **Group** layers into folders with **Group selected layers**, or **Ctrl+G** on the canvas. **Alt+→** moves a layer into the group above it and **Alt+←** moves it out. A group's eye and lock, and its **Hide group on canvas only**, apply to everything in it.+* **Group** layers into folders with **Group selected layers**, or **Ctrl+G** on the canvas. **Alt+→** moves a layer into the group above it and **Alt+←** moves it out. A group's buttons apply to everything in it: a raster group's eye and lock, and a mask, regional guidance or control group's dot, eye and lock.* **Filter layers** at the bottom of the list shows only the layers whose names match.* The buttons beside the filter **Duplicate selected layers**, **Group selected layers** and **Delete selected layers**.@@ -91,20 +93,20 @@ The icons at the top **Arrange** the layer (move it to the front, forward, backw* **Copy to** — including **Copy layer to clipboard**, and copies to other layer types.* **Crop layer to frame** — keeps only the part of the layer inside the generation frame. It refuses, saying why, a layer that is locked or inside a locked group, a layer that lies entirely outside the frame (cropping would leave it empty), and a layer whose image could not be read, for example because it was deleted from the Gallery. A cropped control layer keeps its **Type**, but its cropped map becomes its image: the original it was detected from is no longer kept, and **Detection** changes to **None**.* **Save layer to board** — saves the layer to the Gallery as an upload, in Uncategorized or a board you pick from its submenu.- * **Hide layer**, **Lock layer**, **Bookmark for quick switch** and **Color label**. A bookmarked layer is where **Q** switches on the canvas; press **Q** again to return. The bookmark is not saved in the project: it lasts while the project is open in your browser and resets on reload.+ * **Hide layer** (on inpaint masks, regional guidance and control layers, **Exclude from generation**, as the row's dot; with both kinds selected, **Turn off selected**), **Lock layer**, **Bookmark for quick switch** and **Color label**. A bookmarked layer is where **Q** switches on the canvas; press **Q** again to return. The bookmark is not saved in the project: it lasts while the project is open in your browser and resets on reload.* **Remove from group** — for a layer inside a group: moves it out, directly above the group. With several layers selected, it appears when they are all in the same group, and moves them together in their current order. The emptied group stays.* **Delete layer**.* **Raster layers:**- * **Transform** (**Shift+T**) — shows the transform handles at once. It works on enabled raster and control layers with content.+ * **Transform** (**Shift+T**) — shows the transform handles at once. It works on any enabled layer with content: raster and control layers, inpaint masks and regional guidance.* **Add adjustment** — Brightness/Contrast, Exposure, Levels, Curves, Saturation, Hue, Invert, Texture, Clarity, Dehaze or Noise. Adjustments are non-destructive and appear as child rows. Texture, Clarity and Dehaze change detail and contrast; Noise adds film grain.- * **Add regenerate region** — regenerates where the layer has content, as a live inpaint mask: everything on the layer marks the area to regenerate, and it follows the layer as you keep editing it. The menu shows this description under the item.+ * **Add regenerate region** — regenerates where the layer has content, as a live inpaint mask: everything on the layer marks the area to regenerate, and it follows the layer as you keep editing it. The menu sums this up under the item as "Inpaint where this layer has content."* **Filter**, **Select object** and **Run workflow** — process the layer; see the [Canvas guide](/users-guide/canvas/canvas-guide/#filters-and-object-selection).* **Use as control layer** — copies the layer's pixels to a new control layer, whose Properties then ask for its **Type**.* **Boolean operations** — combine the layer with the one below: intersect, cut out, cut away or exclude.* **Convert to** — make it a control layer, inpaint mask or regional guidance layer. Text, shape and gradient layers can also be rasterized into plain pixels. Control layers have no adjustments, so converting a layer with adjustments to a control layer, or using it as one, bakes them, with the layer's scaling and rotation, into its pixels; undo restores the raster layer with its adjustments.-* **Control layers:** **Transform**, **Select object**, **Run workflow**, **Enable transparent preview**, **Convert to raster layer**, and **Hide on canvas only**. A control layer's map comes from its **Detection** row in Properties, so it has no **Filter**.-* **Inpaint masks:** **Add noise**, **Add denoise limit**, **Extract masked area** (copy the masked part of the image to a new layer), and **Hide on canvas only**.-* **Regional guidance:** **Enable auto-negative**, **Add reference image**, and **Hide on canvas only**.+* **Control layers:** **Transform**, **Select object**, **Run workflow**, **Enable transparent preview**, **Convert to raster layer**, and **Hide on canvas**, as the row's eye. A control layer's map comes from its **Detection** row in Properties, so it has no **Filter**.+* **Inpaint masks:** **Transform**, **Add noise**, **Add denoise limit**, **Extract masked area** (copy the masked part of the image to a new layer), and **Hide on canvas**.+* **Regional guidance:** **Transform**, **Enable auto-negative**, **Add reference image**, and **Hide on canvas**.When several layers are selected, the menu also offers **Merge selected layers**. When only inpaint masks are selected, it offers **Merge masks** instead: the masks are combined into one new inpaint mask, named after the topmost one with "merged" added. It covers everywhere any of the masks did, at full strength whatever each mask's opacity, and takes the topmost mask's fill color and style. The new mask is placed where the topmost one was, even when the masks are in different groups, and replaces them. Merge masks needs two or more enabled, unlocked inpaint masks with content, whose noise and denoise limit settings match, since the new mask applies one setting to all of its area. When the item is unavailable, highlighting it shows why. One undo brings the original masks back.@@ -114,7 +116,7 @@ A heading at the top of the **Properties** tab names what it is editing: **LayerBelow the heading, the tab shows up to three sections, in this order:-1. The running operation's settings — while a **Filter** or **Select Object** operation is running. Starting either from a layer's menu opens the Layers panel on this tab.+1. The running operation's settings — while a **Filter** or **Select Object** operation is running. Starting either from a layer's menu opens the Layers panel on this tab. The section's header shows what the operation is doing while it works, and hovering the operation's name shows the layer it runs on. Its buttons follow its settings, and an error appears below them.2. **Tool** — the options of the active canvas tool; see the [Canvas guide](/users-guide/canvas/canvas-guide/#tool-options).3. **Layer** — the settings of the selected layer.@@ -176,7 +178,7 @@ Things to know about Texture, Clarity and Dehaze:A control layer's Layer section always has the same rows, in this order: **Image**, **Type**, **Detection** and **Model**, then **Weight**, **Steps** and **Priority**. The rows stay in place; only their values change.-* **Image** — the picture the guide comes from. On an empty layer, the row has three buttons: **Upload** an image from your computer, use the **Frame** (what is visible inside the generation frame), or **Draw** the control image yourself on the layer. You can also drop an image file from your computer onto the canvas while the empty layer is selected: the canvas shows *Drop an image here* over the layer, and the file is uploaded into it. Once the layer has an image, the row shows its thumbnail and a label, such as the file name, and **Replace** offers the same three choices. The layer keeps this original image beside the detected map, so detection can run again on it.+* **Image** — the picture the guide comes from. On an empty layer, the row has three buttons: **Upload** an image from your computer, use the **Frame** (what is visible inside the generation frame), or **Draw** the control image yourself on the layer. You can also drag an image file from your computer onto the canvas and drop it on **Add as control layer**: it is uploaded to the Gallery and fills the selected layer while that layer is still empty. Once the layer has an image, the row shows its thumbnail and a label, such as the file name, and **Replace** offers the same three choices. The layer keeps this original image beside the detected map, so detection can run again on it.* **Type** — what the layer controls: **Pose**, **Depth**, **Edges**, **Soft edges**, **Line art**, **Sketch**, **Color** or **Tile**. In the menu, each type shows how many installed models are made for it, *via Union* when only a Union model covers it, or *Not installed*. Changing the type sets **Model** back to automatic, and on a layer with an image it runs the new type's default detector unless the current one also belongs to the new type.* **Detection** — the detector that turns the image into the type's map, for example Depth Anything or a normal map for Depth, Canny or MLSD for Edges, and DW Openpose or Mediapipe Face for Pose. The **None** option, such as *None: image is already a depth map*, uses the image as it is. Until the layer has an image, the row reads *Chosen when an image is added* and its detectors cannot be chosen; the first image gets the type's default detector. **Sketch**, and an image you draw yourself, use **None**; a drawn image counts once it has a stroke. **Tile** has no detector and uses the image directly.* The **Detector settings** button next to it opens the detector's options. Changing the detector or its settings runs detection again in the background. A spinner shows while it is waiting, with *Waiting to run* and the detector's name, and while it runs, with *Running* and the detector's name.@@ -203,7 +205,7 @@ Its child rows, added from the layer menu, set **Noise** (noise added inside the### Regional guidance-* **Positive prompt** and **Negative prompt** — the prompts for this region. Each is saved when you click away from the field. The negative prompt is shown only for models that use one.+* **Positive prompt** and **Negative prompt** — the prompts for this region. Each is saved when you click away from the field. A region starts without a negative prompt: click **+ Negative prompt…** to add one, and **Remove negative prompt** (the **X** beside its label) to take it out of the region, text included. When the selected model does not use regional negatives, the negative prompt and its button are hidden, and any text it has is kept for other models.* **Auto-Negative** — also uses the region's positive prompt as a negative prompt outside the region.* **Fill color**, **Fill style** and **Invert mask**, as for inpaint masks.diff --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 24d7ade5ac..8544f57892 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@@ -56,7 +56,7 @@ Hover over a numbered circle, or tap it on a touchscreen, for a short descriptio| 2 | **View** / **Edit** | **View** uses the form. **Edit** lets you design the form, edit the workflow's details (name, description, author, tags, notes), and inspect the selected node. || 3 | **Editor toolbar** | Tools for panning, box and lasso selection, and erasing nodes or connections; **Zoom in**, **Zoom out** and **Fit view**; **Arrange nodes**, which lays out the whole graph, or just the selected nodes in place, as one undoable step; **Download workflow as PNG**; and **Node opacity**. || 4 | **Workflow name** | The active workflow. Click it to switch to another of the project's workflows, start a **New workflow**, or choose **Workflow library…** to open the **Workflows** library. |-| 5 | **Workflow actions** | **Add node** (**+**), **Save to library…**, the save status, settings, and the **⋯** menu with **Rename…**, **Details…** and **Save to library…** for this workflow, **Import from JSON…**, and **Export** (**Export JSON**, **Copy JSON**, **Download as PNG**). |+| 5 | **Workflow actions** | **Add node** (**+**), **Undo** and **Redo** (in the **⋯** menu instead when the header is narrow), **Save to library…**, the save status, settings, and the **⋯** menu with **Rename…**, **Details…** and **Save to library…** for this workflow, **Import from JSON…**, and **Export** (**Export JSON**, **Copy JSON**, **Download as PNG**). || 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. |diff --git a/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx b/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdxindex eed291af77..3c7000b043 100644--- a/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx+++ b/docs/src/content/docs/configuration/Multi-User Mode/admin-guide.mdx@@ -90,7 +90,7 @@ Board visibility becomes general access: private boards become **Restricted**, s<Tabs><TabItem label="Web UI">-Open the Launchpad's **Users** page, or choose **Manage users** in your account menu (your name in the Launchpad's top bar, or the app menu in a project).+Open the Launchpad's **Users** page, or choose **Manage users** in your account menu (your name at the bottom of the Launchpad's sidebar). From inside a project, choose **Launchpad** in the app menu first.| To | Do this || --- | --- |diff --git a/docs/src/content/docs/configuration/Multi-User Mode/user-guide.mdx b/docs/src/content/docs/configuration/Multi-User Mode/user-guide.mdxindex 18bfd21172..7d8f24670b 100644--- a/docs/src/content/docs/configuration/Multi-User Mode/user-guide.mdx+++ b/docs/src/content/docs/configuration/Multi-User Mode/user-guide.mdx@@ -20,7 +20,7 @@ You stay signed in for 24 hours after your last change, or a week with **Keep me### Your account-Open the account menu: your name in the Launchpad's top bar, or the app menu in a project. It has:+Open the account menu: your name at the bottom of the Launchpad's sidebar (only your initials when the sidebar is narrow). From inside a project, go to the Launchpad first: open the app menu (the Invoke logo at the top left) and choose **Launchpad**. The menu has:- **Account settings**: change your display name, which other users see instead of your email, and your password. Changing the password needs your current one, and signs out your other browsers and devices. Your email cannot be changed.- **Manage users**: shown only to administrators, who also see an **Admin** badge under their name.diff --git a/docs/src/content/docs/contributing/new-model-integration.mdx b/docs/src/content/docs/contributing/new-model-integration.mdxindex c2d542ba22..86c2b65969 100644--- a/docs/src/content/docs/contributing/new-model-integration.mdx+++ b/docs/src/content/docs/contributing/new-model-integration.mdx@@ -1010,7 +1010,7 @@ Anima-2.9B (40 blocks instead of 28) needed only the second row. Anima-3.8B (522. **Config and migration.** A required `variant` field, detection from the checkpoint, `override_fields.pop("variant", None)` before detection, and a [migration](#persisted-records-and-migrations) for installed records. A model installed before the variant existed may already be the new kind; read its header in the migration rather than assume.-3. **Declaration.** `VariantFacet`, per-variant `DefaultSettingsFacet` entries, the regenerated capabilities fixture. The model's defaults reach the UI through **Reset all to model defaults**; switching models keeps the user's settings.+3. **Declaration.** `VariantFacet`, per-variant `DefaultSettingsFacet` entries, the regenerated capabilities fixture. The model's defaults reach the UI through **Apply model defaults**; switching models keeps the user's settings.4. **Invocations.** New inputs optional, so existing workflows keep validating; node version bumps. The model loader checks the main model's variant and fails with a message naming what is missing, rather than letting the denoise node meet a `None`.diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex a359bd5cf7..ecf4851dda 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -41,6 +41,7 @@ Ownership follows invariants, not the first caller:- The authenticated route applies the account's startup destination preference (`app/startupRedirect.ts`) once per page load. Only opening the bare URL is a launch (not a deep link, reload or history return); its first authenticated arrival at Home may redirect to the editor, and later visits to Home never do. While a launch decides or opens, the splash offers "Stay on the Launchpad". A launch that redirects into the editor leaves a mark in the account's browser storage (`workbench/launchpad/startupLaunch.ts`), naming the project it opened; any editor render clears it, whichever page or tab rendered, and so does deleting that project. If the mark survives to the next launch (the editor failed to load or crashed first), that one launch stays on the Launchpad with a notice instead of reopening the same work.- Signed-out arrivals go to `/login`; an expired session carries `returnTo`, the in-app path it was on, and a sign-in by the same account, on this page or followed from another tab, returns there (any other account starts at Home). Following another tab's sign-in to a different account shows "Switching account…", then lands on Home. Addresses no route answers open Home, and Launchpad managers the account may not use open Projects, each with a notice (never on a hover preload).- `patches/@[email protected]` keeps controlled Chakra props synchronized when React Activity reconnects a retained section. The upstream watcher skips reconnect reconciliation, which can reopen a confirmation already completed while hidden; `ConfirmDialog.browser.test.tsx` covers that lifecycle. Both dependency module formats receive the same patch, without changing package versions. Remove the pinned patch once upstream reconciles controlled values changed while Activity is hidden without replaying unchanged watchers on reconnect; rerun the focused ConfirmDialog Activity regression and the production workbench keep-alive scroll/zoom journey before removing it.+- `patches/@[email protected]` and `patches/@[email protected]` reconcile Zag machines when a hidden React Activity reconnects. A machine stops while hidden and drops what arrives meanwhile, such as the end of an exit animation or the pointer leaving its trigger; restarting resumes the stored state. Presence unmounts content that should be gone, and Tooltip forgets a pointer open and closes an uncontrolled tip left open, so a tip closed by the click that hid its section neither returns stuck nor ignores the next hover. Both module formats receive each patch. `src/platform/ui/Tooltip.browser.test.tsx` ("shows a tip again only when hovered after its section was hidden mid-fade") fails without either patch; `src/platform/ui/Menu.browser.test.tsx` ("stay closed when their section returns after it was hidden while they faded out") fails without the presence patch, which every Zag presence (menus, popovers) shares. Zag 1.47.0 still has both faults: an upgrade must port both patches (the tooltip patch no longer applies as is) and rerun those tests. Remove them once upstream reconciles state on reconnect and the tests pass unpatched.- Platform State owns reusable projections of broad external stores into referentially stable read-only stores. App may build them for a feature port. Listener, caching, equality mechanics stay domain-neutral Platform code.`pnpm architecture:check` is the executable source of truth for dependency direction. It parses TypeScript and classifies static imports, type imports, dynamic imports, re-exports, inline imported types, after resolving aliases and relative paths. Temporary violations go in `src/architecture/migrationExceptions.ts` with owner and removal ticket. Architecture is complete only when that registry is empty.diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.jsonindex 28615ad05f..d362a0cd53 100644--- a/invokeai/frontend/webv2/package.json+++ b/invokeai/frontend/webv2/package.json@@ -69,7 +69,7 @@"i18next": "^26.5.6","i18next-http-backend": "^4.0.4","idb": "^8.0.4",- "lucide-react": "^1.61.0",+ "lucide-react": "^1.69.0","perfect-freehand": "^1.2.3","plotly.js-gl2d-dist-min": "^4.1.2","react": "^19.3.1",diff --git a/invokeai/frontend/webv2/patches/@[email protected] b/invokeai/frontend/webv2/patches/@[email protected]new file mode 100644index 0000000000..8390da2917--- /dev/null+++ b/invokeai/frontend/webv2/patches/@[email protected]@@ -0,0 +1,46 @@+diff --git a/dist/menu.machine.js b/dist/menu.machine.js+index f35618ace4d14616c45ea4d874c167fb8b9ca721..1a89e6d4dbd5e3bfd94c601878901ddac7d48c47 100644+--- a/dist/menu.machine.js++++ b/dist/menu.machine.js+@@ -581,14 +581,16 @@ var machine = (0, import_core.createMachine)({+ trackFocusVisible({ scope }) {+ return (0, import_focus_visible.trackFocusVisible)({ root: scope.getRootNode?.() });+ },+- trackPositioning({ context, prop, scope, refs }) {++ trackPositioning({ context, event, prop, scope, refs }) {+ const hasContextTrigger = dom.getContextTriggerEl(scope) || dom.getContextTriggerEls(scope).length > 0;+ if (hasContextTrigger) return;+ const positioning = {+ ...prop("positioning"),+ ...refs.get("positioningOverride")+ };+- context.set("currentPlacement", positioning.placement);++ // Re-entering a closing submenu restarts this effect while its content is still shown. Keep its resolved++ // placement: resetting a flipped submenu to the configured side restarts its placement-keyed open animation.++ if (event.type !== "MENU_POINTERENTER") context.set("currentPlacement", positioning.placement);+ const getPositionerEl2 = () => dom.getPositionerEl(scope);+ const getTriggerEl2 = () => dom.getActiveTriggerEl(scope, context.get("triggerValue"));+ return (0, import_popper.getPlacement)(getTriggerEl2, getPositionerEl2, {+diff --git a/dist/menu.machine.mjs b/dist/menu.machine.mjs+index b8facff3003d0f0d72352b323352956a7e898853..88d51b58f7b2c4135a8635d263c13e0dbb72995e 100644+--- a/dist/menu.machine.mjs++++ b/dist/menu.machine.mjs+@@ -566,14 +566,16 @@ var machine = createMachine({+ trackFocusVisible({ scope }) {+ return trackFocusVisible({ root: scope.getRootNode?.() });+ },+- trackPositioning({ context, prop, scope, refs }) {++ trackPositioning({ context, event, prop, scope, refs }) {+ const hasContextTrigger = dom.getContextTriggerEl(scope) || dom.getContextTriggerEls(scope).length > 0;+ if (hasContextTrigger) return;+ const positioning = {+ ...prop("positioning"),+ ...refs.get("positioningOverride")+ };+- context.set("currentPlacement", positioning.placement);++ // Re-entering a closing submenu restarts this effect while its content is still shown. Keep its resolved++ // placement: resetting a flipped submenu to the configured side restarts its placement-keyed open animation.++ if (event.type !== "MENU_POINTERENTER") context.set("currentPlacement", positioning.placement);+ const getPositionerEl2 = () => dom.getPositionerEl(scope);+ const getTriggerEl2 = () => dom.getActiveTriggerEl(scope, context.get("triggerValue"));+ return getPlacement(getTriggerEl2, getPositionerEl2, {diff --git a/invokeai/frontend/webv2/patches/@[email protected] b/invokeai/frontend/webv2/patches/@[email protected]new file mode 100644index 0000000000..e3a3d69b1f--- /dev/null+++ b/invokeai/frontend/webv2/patches/@[email protected]@@ -0,0 +1,52 @@+diff --git a/dist/presence.machine.js b/dist/presence.machine.js+index 9b104c4..4e2b701 100644+--- a/dist/presence.machine.js++++ b/dist/presence.machine.js+@@ -49,6 +49,10 @@ var machine = (0, import_core.createMachine)({+ }))+ };+ },++ // Starting again after React Activity hid the subtree resumes the stored state, but the machine was stopped while++ // hidden and dropped what was sent meanwhile: the frame that suspends an exit, the animation events that finish it,++ // the node. A closed tip or menu then stays shown until it opens and closes again. Hidden content showed no exit.++ entry: ["reconcilePresence"],+ exit: ["cleanupNode"],+ watch({ track, prop, send }) {+ track([() => prop("present")], () => {+@@ -150,6 +154,10 @@ var machine = (0, import_core.createMachine)({+ },+ clearPrevAnimationName: ({ context }) => {+ context.set("prevAnimationName", null);++ },++ reconcilePresence: ({ prop, send, state }) => {++ if (prop("present") || state.matches("unmounted")) return;++ send({ type: "UNMOUNT", src: "reconnect" });+ }+ },+ effects: {+diff --git a/dist/presence.machine.mjs b/dist/presence.machine.mjs+index 5c11a9e..9d66955 100644+--- a/dist/presence.machine.mjs++++ b/dist/presence.machine.mjs+@@ -25,6 +25,10 @@ var machine = createMachine({+ }))+ };+ },++ // Starting again after React Activity hid the subtree resumes the stored state, but the machine was stopped while++ // hidden and dropped what was sent meanwhile: the frame that suspends an exit, the animation events that finish it,++ // the node. A closed tip or menu then stays shown until it opens and closes again. Hidden content showed no exit.++ entry: ["reconcilePresence"],+ exit: ["cleanupNode"],+ watch({ track, prop, send }) {+ track([() => prop("present")], () => {+@@ -126,6 +130,10 @@ var machine = createMachine({+ },+ clearPrevAnimationName: ({ context }) => {+ context.set("prevAnimationName", null);++ },++ reconcilePresence: ({ prop, send, state }) => {++ if (prop("present") || state.matches("unmounted")) return;++ send({ type: "UNMOUNT", src: "reconnect" });+ }+ },+ effects: {diff --git a/invokeai/frontend/webv2/patches/@[email protected] b/invokeai/frontend/webv2/patches/@[email protected]new file mode 100644index 0000000000..0d425337ce--- /dev/null+++ b/invokeai/frontend/webv2/patches/@[email protected]@@ -0,0 +1,54 @@+diff --git a/dist/tooltip.machine.js b/dist/tooltip.machine.js+index 7ed1884..2a3e4de 100644+--- a/dist/tooltip.machine.js++++ b/dist/tooltip.machine.js+@@ -67,6 +67,10 @@ var machine = (0, import_core.createMachine)({+ };+ },+ effects: ["trackFocusVisible", "trackStore"],++ // Starting again after React Activity hid the subtree resumes the stored state, but the machine was stopped while++ // hidden and dropped what was sent meanwhile, such as the pointer leaving as the trigger was hidden. A tip left open++ // would then show with nothing to close it, and a pointer open still on record would ignore the next hover.++ entry: ["reconcileReconnect"],+ context: ({ bindable, prop, scope }) => ({+ currentPlacement: bindable(() => ({ defaultValue: void 0 })),+ hasPointerMoveOpened: bindable(() => ({ defaultValue: null })),+@@ -357,6 +361,11 @@ var machine = (0, import_core.createMachine)({+ clearPointerMoveOpened: ({ context }) => {+ context.set("hasPointerMoveOpened", null);+ },++ reconcileReconnect: ({ context, prop, send, state }) => {++ context.set("hasPointerMoveOpened", null);++ if (prop("open") !== void 0 || prop("defaultOpen") || state.matches("closed")) return;++ send({ type: "close", src: "reconnect" });++ },+ setTriggerValue: ({ context, event }) => {+ if (event.value === void 0) return;+ context.set("triggerValue", event.value);+diff --git a/dist/tooltip.machine.mjs b/dist/tooltip.machine.mjs+index 03c6f04..188679d 100644+--- a/dist/tooltip.machine.mjs++++ b/dist/tooltip.machine.mjs+@@ -33,6 +33,10 @@ var machine = createMachine({+ };+ },+ effects: ["trackFocusVisible", "trackStore"],++ // Starting again after React Activity hid the subtree resumes the stored state, but the machine was stopped while++ // hidden and dropped what was sent meanwhile, such as the pointer leaving as the trigger was hidden. A tip left open++ // would then show with nothing to close it, and a pointer open still on record would ignore the next hover.++ entry: ["reconcileReconnect"],+ context: ({ bindable, prop, scope }) => ({+ currentPlacement: bindable(() => ({ defaultValue: void 0 })),+ hasPointerMoveOpened: bindable(() => ({ defaultValue: null })),+@@ -323,6 +327,11 @@ var machine = createMachine({+ clearPointerMoveOpened: ({ context }) => {+ context.set("hasPointerMoveOpened", null);+ },++ reconcileReconnect: ({ context, prop, send, state }) => {++ context.set("hasPointerMoveOpened", null);++ if (prop("open") !== void 0 || prop("defaultOpen") || state.matches("closed")) return;++ send({ type: "close", src: "reconnect" });++ },+ setTriggerValue: ({ context, event }) => {+ if (event.value === void 0) return;+ context.set("triggerValue", event.value);diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex d0efccc54f..e85cd08fe5 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -2,15 +2,15 @@"build": {"launchpad": {"baseline": {- "brotliBytes": 816542,+ "brotliBytes": 820663,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 815312,+ "gzipBytes": 820232,"imageRawBytes": 44398,- "initialRawBytes": 2108233,- "largestAssetRawBytes": 751084,+ "initialRawBytes": 2121306,+ "largestAssetRawBytes": 751511,"otherAssetRawBytes": 0,- "ownedRawBytes": 115499,+ "ownedRawBytes": 116590,"requestCount": 34,"scriptRequestCount": 18,"sourceOwners": [@@ -149,7 +149,6 @@"source:src/features/identity/launchpad.tsx","source:src/features/identity/session.ts","source:src/features/identity/ui/AccountMenu.tsx",- "source:src/features/identity/ui/AccountMenuSection.tsx","source:src/features/identity/ui/AuthScreen.tsx","source:src/features/identity/ui/AuthUnavailableScreen.tsx","source:src/features/identity/ui/LoginScreen.tsx",@@ -186,6 +185,7 @@"source:src/features/nodes/ui/NodesPage.tsx","source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts",+ "source:src/platform/browser/fileDropNavigation.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts","source:src/platform/browser/randomUuid.ts",@@ -272,6 +272,7 @@"source:src/platform/ui/list/listLayout.ts","source:src/platform/ui/list/virtualSections.ts","source:src/platform/ui/modalPresence.ts",+ "source:src/platform/ui/scrollStripEdges.ts","source:src/platform/ui/settings/contracts.ts","source:src/platform/ui/theme/applyTheme.ts","source:src/platform/ui/theme/rebase.ts",@@ -281,6 +282,7 @@"source:src/platform/ui/theme/themes.ts","source:src/platform/ui/toaster.tsx","source:src/platform/ui/useScrollAreaPhantomHeal.ts",+ "source:src/platform/ui/wheelScrollsHorizontally.ts","source:src/platform/ui/widgetOverlayRegistry.ts","source:src/platform/ui/widgetOverlays.ts","source:src/workbench/canvasSchemaVersion.ts",@@ -361,15 +363,15 @@},"editor": {"baseline": {- "brotliBytes": 1273806,+ "brotliBytes": 1291929,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 1266186,+ "gzipBytes": 1285044,"imageRawBytes": 44398,- "initialRawBytes": 3520316,- "largestAssetRawBytes": 751084,+ "initialRawBytes": 3579319,+ "largestAssetRawBytes": 751511,"otherAssetRawBytes": 0,- "ownedRawBytes": 178002,+ "ownedRawBytes": 174909,"requestCount": 70,"scriptRequestCount": 54,"sourceOwners": [@@ -535,6 +537,7 @@"source:src/features/gallery/data/queries.ts","source:src/features/gallery/data/queryCache.ts","source:src/features/gallery/data/realtimeRuntime.ts",+ "source:src/features/gallery/data/uploadDestination.ts","source:src/features/gallery/data/videoUrls.ts","source:src/features/gallery/picker.ts","source:src/features/gallery/queries.ts",@@ -629,7 +632,6 @@"source:src/features/identity/launchpad.tsx","source:src/features/identity/session.ts","source:src/features/identity/ui/AccountMenu.tsx",- "source:src/features/identity/ui/AccountMenuSection.tsx","source:src/features/identity/ui/AuthScreen.tsx","source:src/features/identity/ui/AuthUnavailableScreen.tsx","source:src/features/identity/ui/LoginScreen.tsx",@@ -705,6 +707,7 @@"source:src/features/queue/runtime/deliveryClaims.ts","source:src/features/queue/runtime/receiptAcknowledgements.ts","source:src/features/queue/ui/QueueUiContext.tsx",+ "source:src/features/queue/ui/cancelCurrent.ts","source:src/features/queue/ui/currentBatchItems.ts","source:src/features/queue/ui/queueActionRequests.ts","source:src/features/queue/ui/queueConfirmationStore.ts",@@ -750,6 +753,8 @@"source:src/features/workflow/widget.ts","source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts",+ "source:src/platform/browser/dropZones.ts",+ "source:src/platform/browser/fileDropNavigation.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts","source:src/platform/browser/randomUuid.ts",@@ -770,10 +775,12 @@"source:src/platform/query/client.ts","source:src/platform/react/composeProviders.tsx","source:src/platform/react/draftRegistry.ts",+ "source:src/platform/react/isEventFromOwnDom.ts","source:src/platform/react/useDebouncedValue.ts","source:src/platform/react/useExitRetainedValue.ts","source:src/platform/react/useModifierHeld.ts","source:src/platform/react/useMountEffect.ts",+ "source:src/platform/react/useNativeFileDrag.ts","source:src/platform/react/usePreservedScrollOffset.ts","source:src/platform/react/useZodForm.ts","source:src/platform/runtime/appMetadata.ts",@@ -819,6 +826,7 @@"source:src/platform/ui/Row.tsx","source:src/platform/ui/Scrollable.tsx","source:src/platform/ui/ScrollableMenuContent.tsx",+ "source:src/platform/ui/ScrubberField.tsx","source:src/platform/ui/SeedInput.tsx","source:src/platform/ui/SegmentTabs.tsx","source:src/platform/ui/SegmentedControl.tsx",@@ -847,6 +855,7 @@"source:src/platform/ui/list/listLayout.ts","source:src/platform/ui/list/virtualSections.ts","source:src/platform/ui/modalPresence.ts",+ "source:src/platform/ui/scrollStripEdges.ts","source:src/platform/ui/settings/contracts.ts","source:src/platform/ui/theme/applyTheme.ts","source:src/platform/ui/theme/rebase.ts",@@ -990,9 +999,7 @@"source:src/workbench/projectWorkflows.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts",- "source:src/workbench/projects/components/OpenProjectDialog.tsx","source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx",- "source:src/workbench/projects/components/index.ts","source:src/workbench/projects/covers.ts","source:src/workbench/projects/draftStore.ts","source:src/workbench/projects/durableSyncedPersistence.ts",@@ -1161,6 +1168,8 @@"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/shared/DropZoneLabel.tsx",+ "source:src/workbench/widgets/shared/useDroppedFileUpload.ts","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/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex af7d5b7138..09cca801ff 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -29,12 +29,12 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 0,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,"requestCount": 28,- "scriptRawBytes": 1932580,+ "scriptRawBytes": 1948773,"scriptRequestCount": 24,- "totalRawBytes": 2276142+ "totalRawBytes": 2304701},"routeReadyMedianMs": 241.90000000223517,"scriptSourceOwnerSet": "launchpad-static",@@ -67,12 +67,12 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 0,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,"requestCount": 28,- "scriptRawBytes": 1932580,+ "scriptRawBytes": 1948773,"scriptRequestCount": 24,- "totalRawBytes": 2276142+ "totalRawBytes": 2304701},"routeReadyMedianMs": 261.30000000074506,"scriptSourceOwnerSet": "launchpad-static",@@ -105,12 +105,12 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,"requestCount": 84,- "scriptRawBytes": 4575582,+ "scriptRawBytes": 4680491,"scriptRequestCount": 79,- "totalRawBytes": 4963542+ "totalRawBytes": 5080817},"routeReadyMedianMs": 421.19999999925494,"scriptSourceOwnerSet": "editor-minimal-static",@@ -143,12 +143,12 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,"requestCount": 84,- "scriptRawBytes": 4575582,+ "scriptRawBytes": 4680491,"scriptRequestCount": 79,- "totalRawBytes": 4963542+ "totalRawBytes": 5080817},"routeReadyMedianMs": 423.19999999925494,"scriptSourceOwnerSet": "editor-minimal-static",@@ -159,12 +159,12 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 342634,+ "largestAssetRawBytes": 344531,"otherRawBytes": 0,- "requestCount": 8,- "scriptRawBytes": 598467,- "scriptRequestCount": 8,- "totalRawBytes": 598467+ "requestCount": 7,+ "scriptRawBytes": 602771,+ "scriptRequestCount": 7,+ "totalRawBytes": 602771},"domContentLoadedMedianMs": 117.5,"id": "editor-canvas",@@ -181,12 +181,12 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,- "requestCount": 92,- "scriptRawBytes": 5174049,- "scriptRequestCount": 87,- "totalRawBytes": 5562009+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,+ "requestCount": 91,+ "scriptRawBytes": 5283262,+ "scriptRequestCount": 86,+ "totalRawBytes": 5683588},"routeReadyMedianMs": 1158.2999999970198,"scriptSourceOwnerSet": "editor-canvas-static",@@ -197,12 +197,12 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 342634,+ "largestAssetRawBytes": 344531,"otherRawBytes": 0,- "requestCount": 8,- "scriptRawBytes": 598467,- "scriptRequestCount": 8,- "totalRawBytes": 598467+ "requestCount": 7,+ "scriptRawBytes": 602771,+ "scriptRequestCount": 7,+ "totalRawBytes": 602771},"domContentLoadedMedianMs": 117.60000000149012,"id": "editor-canvas",@@ -219,12 +219,12 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,- "requestCount": 92,- "scriptRawBytes": 5174049,- "scriptRequestCount": 87,- "totalRawBytes": 5562009+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,+ "requestCount": 91,+ "scriptRawBytes": 5283262,+ "scriptRequestCount": 86,+ "totalRawBytes": 5683588},"routeReadyMedianMs": 1150.699999999255,"scriptSourceOwnerSet": "editor-canvas-static",@@ -235,12 +235,12 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 220580,+ "largestAssetRawBytes": 221166,"otherRawBytes": 0,"requestCount": 6,- "scriptRawBytes": 459562,+ "scriptRawBytes": 442660,"scriptRequestCount": 5,- "totalRawBytes": 474975+ "totalRawBytes": 458073},"domContentLoadedMedianMs": 117.90000000223517,"id": "editor-workflow",@@ -257,12 +257,12 @@"cssRawBytes": 17572,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,"requestCount": 90,- "scriptRawBytes": 5035144,+ "scriptRawBytes": 5123151,"scriptRequestCount": 84,- "totalRawBytes": 5438517+ "totalRawBytes": 5538890},"routeReadyMedianMs": 1151.300000000745,"scriptSourceOwnerSet": "editor-workflow-static",@@ -273,12 +273,12 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 220580,+ "largestAssetRawBytes": 221166,"otherRawBytes": 0,"requestCount": 6,- "scriptRawBytes": 459562,+ "scriptRawBytes": 442660,"scriptRequestCount": 5,- "totalRawBytes": 474975+ "totalRawBytes": 458073},"domContentLoadedMedianMs": 116.19999999925494,"id": "editor-workflow",@@ -295,12 +295,12 @@"cssRawBytes": 17572,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,"requestCount": 90,- "scriptRawBytes": 5035144,+ "scriptRawBytes": 5123151,"scriptRequestCount": 84,- "totalRawBytes": 5438517+ "totalRawBytes": 5538890},"routeReadyMedianMs": 1185.5,"scriptSourceOwnerSet": "editor-workflow-static",@@ -333,12 +333,12 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,"requestCount": 84,- "scriptRawBytes": 4575582,+ "scriptRawBytes": 4680491,"scriptRequestCount": 79,- "totalRawBytes": 4963542+ "totalRawBytes": 5080817},"routeReadyMedianMs": 1400.199999999255,"scriptSourceOwnerSet": "editor-minimal-static",@@ -371,12 +371,12 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751084,- "otherRawBytes": 317739,+ "largestAssetRawBytes": 751511,+ "otherRawBytes": 330105,"requestCount": 84,- "scriptRawBytes": 4575582,+ "scriptRawBytes": 4680491,"scriptRequestCount": 79,- "totalRawBytes": 4963542+ "totalRawBytes": 5080817},"routeReadyMedianMs": 1382.699999999255,"scriptSourceOwnerSet": "editor-minimal-static",@@ -543,7 +543,6 @@"source:src/features/identity/launchpad.tsx","source:src/features/identity/session.ts","source:src/features/identity/ui/AccountMenu.tsx",- "source:src/features/identity/ui/AccountMenuSection.tsx","source:src/features/identity/ui/AuthScreen.tsx","source:src/features/identity/ui/AuthUnavailableScreen.tsx","source:src/features/identity/ui/LoginScreen.tsx",@@ -606,6 +605,7 @@"source:src/features/queue/ui/queueOwnership.ts","source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts",+ "source:src/platform/browser/fileDropNavigation.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts","source:src/platform/browser/randomUuid.ts",@@ -692,6 +692,7 @@"source:src/platform/ui/list/listLayout.ts","source:src/platform/ui/list/virtualSections.ts","source:src/platform/ui/modalPresence.ts",+ "source:src/platform/ui/scrollStripEdges.ts","source:src/platform/ui/settings/contracts.ts","source:src/platform/ui/theme/applyTheme.ts","source:src/platform/ui/theme/rebase.ts",@@ -701,6 +702,7 @@"source:src/platform/ui/theme/themes.ts","source:src/platform/ui/toaster.tsx","source:src/platform/ui/useScrollAreaPhantomHeal.ts",+ "source:src/platform/ui/wheelScrollsHorizontally.ts","source:src/platform/ui/widgetOverlayRegistry.ts","source:src/platform/ui/widgetOverlays.ts","source:src/workbench/canvasSchemaVersion.ts",@@ -939,6 +941,7 @@"source:src/features/gallery/data/queries.ts","source:src/features/gallery/data/queryCache.ts","source:src/features/gallery/data/realtimeRuntime.ts",+ "source:src/features/gallery/data/uploadDestination.ts","source:src/features/gallery/data/videoUrls.ts","source:src/features/gallery/index.ts","source:src/features/gallery/mediaSlot.ts",@@ -1078,6 +1081,7 @@"source:src/features/generation/ui/promptFields/GeneratePromptFields.tsx","source:src/features/generation/ui/promptFields/LLMTaskProgressDisplay.tsx","source:src/features/generation/ui/promptFields/NegativePromptField.tsx",+ "source:src/features/generation/ui/promptFields/NegativePromptToggle.tsx","source:src/features/generation/ui/promptFields/PositivePromptActions.tsx","source:src/features/generation/ui/promptFields/PositivePromptField.tsx","source:src/features/generation/ui/promptFields/PromptHighlight.tsx",@@ -1104,9 +1108,9 @@"source:src/features/generation/ui/promptFields/useSystemPrompts.ts","source:src/features/generation/ui/promptTemplateDraftStore.ts","source:src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx",- "source:src/features/generation/ui/reference-images/ReferenceImageCard.tsx","source:src/features/generation/ui/reference-images/ReferenceImageControls.tsx","source:src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx",+ "source:src/features/generation/ui/reference-images/ReferenceImageRow.tsx","source:src/features/generation/ui/reference-images/referenceImageConfig.ts","source:src/features/generation/ui/shared/AspectRatioPicker.tsx","source:src/features/generation/ui/shared/AspectRatioPreview.tsx",@@ -1119,8 +1123,10 @@"source:src/features/generation/ui/shared/GenerateFieldContextMenu.tsx","source:src/features/generation/ui/shared/GenerateIssues.tsx","source:src/features/generation/ui/shared/GenerateToggleSwitch.tsx",+ "source:src/features/generation/ui/shared/GenerationSectionJumpMenu.tsx","source:src/features/generation/ui/shared/SeedField.tsx","source:src/features/generation/ui/shared/modelDefaultSettings.ts",+ "source:src/features/generation/ui/shared/sectionPanel.tsx","source:src/features/generation/ui/useDebouncedDraftValue.ts","source:src/features/generation/ui/useDynamicPrompts.ts","source:src/features/generation/ui/usePromptTemplates.ts",@@ -1136,7 +1142,6 @@"source:src/features/identity/launchpad.tsx","source:src/features/identity/session.ts","source:src/features/identity/ui/AccountMenu.tsx",- "source:src/features/identity/ui/AccountMenuSection.tsx","source:src/features/identity/ui/AuthScreen.tsx","source:src/features/identity/ui/AuthUnavailableScreen.tsx","source:src/features/identity/ui/LoginScreen.tsx",@@ -1219,6 +1224,7 @@"source:src/features/queue/runtime/utilityGraph.ts","source:src/features/queue/ui/QueueDataRuntime.tsx","source:src/features/queue/ui/QueueUiContext.tsx",+ "source:src/features/queue/ui/cancelCurrent.ts","source:src/features/queue/ui/currentBatchItems.ts","source:src/features/queue/ui/modelCacheStore.ts","source:src/features/queue/ui/queueActionRequests.ts",@@ -1290,6 +1296,8 @@"source:src/features/workflow/widget.ts","source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts",+ "source:src/platform/browser/dropZones.ts",+ "source:src/platform/browser/fileDropNavigation.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts","source:src/platform/browser/randomUuid.ts",@@ -1312,10 +1320,12 @@"source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts",+ "source:src/platform/react/isEventFromOwnDom.ts","source:src/platform/react/useDebouncedValue.ts","source:src/platform/react/useExitRetainedValue.ts","source:src/platform/react/useModifierHeld.ts","source:src/platform/react/useMountEffect.ts",+ "source:src/platform/react/useNativeFileDrag.ts","source:src/platform/react/usePreservedScrollOffset.ts","source:src/platform/react/useZodForm.ts","source:src/platform/runtime/appMetadata.ts",@@ -1349,7 +1359,6 @@"source:src/platform/ui/LoadError.tsx","source:src/platform/ui/Menu.tsx","source:src/platform/ui/MiddleTruncate.tsx",- "source:src/platform/ui/ModelDefaultButton.tsx","source:src/platform/ui/PageShell.tsx","source:src/platform/ui/Panel.tsx","source:src/platform/ui/PanelHeader.tsx",@@ -1392,6 +1401,7 @@"source:src/platform/ui/list/listLayout.ts","source:src/platform/ui/list/virtualSections.ts","source:src/platform/ui/modalPresence.ts",+ "source:src/platform/ui/scrollStripEdges.ts","source:src/platform/ui/settings/contracts.ts","source:src/platform/ui/streaming-image/StreamingImageFrame.tsx","source:src/platform/ui/streaming-image/streamingImageSource.ts",@@ -1717,9 +1727,7 @@"source:src/workbench/projectWorkflows.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts",- "source:src/workbench/projects/components/OpenProjectDialog.tsx","source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx",- "source:src/workbench/projects/components/index.ts","source:src/workbench/projects/covers.ts","source:src/workbench/projects/draftStore.ts","source:src/workbench/projects/durableSyncedPersistence.ts",@@ -1891,6 +1899,7 @@"source:src/workbench/widgets/preview/PreviewCompare.tsx","source:src/workbench/widgets/preview/PreviewCompareDropZone.tsx","source:src/workbench/widgets/preview/PreviewDetailsPanel.tsx",+ "source:src/workbench/widgets/preview/PreviewDropSurface.tsx","source:src/workbench/widgets/preview/PreviewFilmstrip.tsx","source:src/workbench/widgets/preview/PreviewFrame.tsx","source:src/workbench/widgets/preview/PreviewHeaderActions.tsx",@@ -1907,6 +1916,7 @@"source:src/workbench/widgets/preview/manifest.ts","source:src/workbench/widgets/preview/previewCompareDnd.ts","source:src/workbench/widgets/preview/previewDensity.ts",+ "source:src/workbench/widgets/preview/previewDockBar.ts","source:src/workbench/widgets/preview/previewHeaderStore.ts","source:src/workbench/widgets/preview/previewMetadata.ts","source:src/workbench/widgets/preview/previewSettings.ts",@@ -1926,6 +1936,8 @@"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/shared/DropZoneLabel.tsx",+ "source:src/workbench/widgets/shared/useDroppedFileUpload.ts","source:src/workbench/widgets/shortcuts/ShortcutGuide.tsx","source:src/workbench/widgets/shortcuts/implementation.ts","source:src/workbench/widgets/shortcuts/manifest.ts",@@ -2099,6 +2111,7 @@"source:src/features/gallery/data/queries.ts","source:src/features/gallery/data/queryCache.ts","source:src/features/gallery/data/realtimeRuntime.ts",+ "source:src/features/gallery/data/uploadDestination.ts","source:src/features/gallery/data/videoUrls.ts","source:src/features/gallery/index.ts","source:src/features/gallery/mediaSlot.ts",@@ -2245,6 +2258,7 @@"source:src/features/generation/ui/promptFields/GeneratePromptFields.tsx","source:src/features/generation/ui/promptFields/LLMTaskProgressDisplay.tsx","source:src/features/generation/ui/promptFields/NegativePromptField.tsx",+ "source:src/features/generation/ui/promptFields/NegativePromptToggle.tsx","source:src/features/generation/ui/promptFields/PositivePromptActions.tsx","source:src/features/generation/ui/promptFields/PositivePromptField.tsx","source:src/features/generation/ui/promptFields/PromptHighlight.tsx",@@ -2271,9 +2285,9 @@"source:src/features/generation/ui/promptFields/useSystemPrompts.ts","source:src/features/generation/ui/promptTemplateDraftStore.ts","source:src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx",- "source:src/features/generation/ui/reference-images/ReferenceImageCard.tsx","source:src/features/generation/ui/reference-images/ReferenceImageControls.tsx","source:src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx",+ "source:src/features/generation/ui/reference-images/ReferenceImageRow.tsx","source:src/features/generation/ui/reference-images/referenceImageConfig.ts","source:src/features/generation/ui/shared/AspectRatioPicker.tsx","source:src/features/generation/ui/shared/AspectRatioPreview.tsx",@@ -2286,8 +2300,10 @@"source:src/features/generation/ui/shared/GenerateFieldContextMenu.tsx","source:src/features/generation/ui/shared/GenerateIssues.tsx","source:src/features/generation/ui/shared/GenerateToggleSwitch.tsx",+ "source:src/features/generation/ui/shared/GenerationSectionJumpMenu.tsx","source:src/features/generation/ui/shared/SeedField.tsx","source:src/features/generation/ui/shared/modelDefaultSettings.ts",+ "source:src/features/generation/ui/shared/sectionPanel.tsx","source:src/features/generation/ui/useDebouncedDraftValue.ts","source:src/features/generation/ui/useDynamicPrompts.ts","source:src/features/generation/ui/usePromptTemplates.ts",@@ -2303,7 +2319,6 @@"source:src/features/identity/launchpad.tsx","source:src/features/identity/session.ts","source:src/features/identity/ui/AccountMenu.tsx",- "source:src/features/identity/ui/AccountMenuSection.tsx","source:src/features/identity/ui/AuthScreen.tsx","source:src/features/identity/ui/AuthUnavailableScreen.tsx","source:src/features/identity/ui/LoginScreen.tsx",@@ -2376,7 +2391,6 @@"source:src/features/queue/index.ts","source:src/features/queue/menu.ts","source:src/features/queue/publicApi.ts",- "source:src/features/queue/queries.ts","source:src/features/queue/react.ts","source:src/features/queue/reveal.ts","source:src/features/queue/runtime.ts",@@ -2387,6 +2401,7 @@"source:src/features/queue/runtime/utilityGraph.ts","source:src/features/queue/ui/QueueDataRuntime.tsx","source:src/features/queue/ui/QueueUiContext.tsx",+ "source:src/features/queue/ui/cancelCurrent.ts","source:src/features/queue/ui/currentBatchItems.ts","source:src/features/queue/ui/modelCacheStore.ts","source:src/features/queue/ui/queueActionRequests.ts",@@ -2459,6 +2474,8 @@"source:src/features/workflow/widget.ts","source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts",+ "source:src/platform/browser/dropZones.ts",+ "source:src/platform/browser/fileDropNavigation.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts","source:src/platform/browser/randomUuid.ts",@@ -2481,10 +2498,12 @@"source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts",+ "source:src/platform/react/isEventFromOwnDom.ts","source:src/platform/react/useDebouncedValue.ts","source:src/platform/react/useExitRetainedValue.ts","source:src/platform/react/useModifierHeld.ts","source:src/platform/react/useMountEffect.ts",+ "source:src/platform/react/useNativeFileDrag.ts","source:src/platform/react/usePreservedScrollOffset.ts","source:src/platform/react/useZodForm.ts","source:src/platform/runtime/appMetadata.ts",@@ -2520,7 +2539,6 @@"source:src/platform/ui/LoadError.tsx","source:src/platform/ui/Menu.tsx","source:src/platform/ui/MiddleTruncate.tsx",- "source:src/platform/ui/ModelDefaultButton.tsx","source:src/platform/ui/PageShell.tsx","source:src/platform/ui/Panel.tsx","source:src/platform/ui/PanelHeader.tsx",@@ -2564,6 +2582,7 @@"source:src/platform/ui/list/listLayout.ts","source:src/platform/ui/list/virtualSections.ts","source:src/platform/ui/modalPresence.ts",+ "source:src/platform/ui/scrollStripEdges.ts","source:src/platform/ui/settings/contracts.ts","source:src/platform/ui/streaming-image/StreamingImageFrame.tsx","source:src/platform/ui/streaming-image/streamingImageSource.ts",@@ -2893,9 +2912,7 @@"source:src/workbench/projectWorkflows.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts",- "source:src/workbench/projects/components/OpenProjectDialog.tsx","source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx",- "source:src/workbench/projects/components/index.ts","source:src/workbench/projects/covers.ts","source:src/workbench/projects/draftStore.ts","source:src/workbench/projects/durableSyncedPersistence.ts",@@ -2928,7 +2945,6 @@"source:src/workbench/queue-integration/QueueProgressRail.tsx","source:src/workbench/queue-integration/QueueRecoveryNotice.tsx","source:src/workbench/queue-integration/activeQueueRuns.ts",- "source:src/workbench/queue-integration/queueRecall.ts","source:src/workbench/queue-integration/queueRecallCache.ts","source:src/workbench/queue-integration/queueRecovery.ts","source:src/workbench/queue-integration/queueRunJournal.ts",@@ -2936,8 +2952,6 @@"source:src/workbench/queue-integration/queueRunPersistence.ts","source:src/workbench/queue-integration/queueRunRestoration.ts","source:src/workbench/queue-integration/useActiveQueueProgress.ts",- "source:src/workbench/queue-integration/useLocalRecallSnapshot.ts",- "source:src/workbench/queue-integration/useQueueItemRecall.ts","source:src/workbench/queue-integration/useQueueRecoveryProjectIds.ts","source:src/workbench/settings/SettingsDialogHost.tsx","source:src/workbench/settings/WidgetSettingsButton.tsx",@@ -3048,6 +3062,7 @@"source:src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx","source:src/workbench/widgets/canvas/CanvasFloatingBar.tsx","source:src/workbench/widgets/canvas/CanvasFrameLockFeed.tsx",+ "source:src/workbench/widgets/canvas/CanvasFrameSizeReadout.tsx","source:src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsx","source:src/workbench/widgets/canvas/CanvasHeaderActions.tsx","source:src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx",@@ -3105,7 +3120,7 @@"source:src/workbench/widgets/canvas/tool-options/CanvasOptionsBar.tsx","source:src/workbench/widgets/canvas/tool-options/FilterOptions.tsx","source:src/workbench/widgets/canvas/tool-options/GradientOptions.tsx",- "source:src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx",+ "source:src/workbench/widgets/canvas/tool-options/OperationActions.tsx","source:src/workbench/widgets/canvas/tool-options/SamOptions.tsx","source:src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx","source:src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx",@@ -3143,6 +3158,7 @@"source:src/workbench/widgets/layers/ControlSourceRow.tsx","source:src/workbench/widgets/layers/ControlTypeRow.tsx","source:src/workbench/widgets/layers/InpaintMaskSettings.tsx",+ "source:src/workbench/widgets/layers/LayerActiveDot.tsx","source:src/workbench/widgets/layers/LayerBlendRow.tsx","source:src/workbench/widgets/layers/LayerChildMenu.tsx","source:src/workbench/widgets/layers/LayerChildRow.tsx",@@ -3201,6 +3217,7 @@"source:src/workbench/widgets/layers/panes/HistoryPane.tsx","source:src/workbench/widgets/layers/panes/LayerEditorPanes.tsx","source:src/workbench/widgets/layers/panes/LayerSection.tsx",+ "source:src/workbench/widgets/layers/panes/OperationSection.tsx","source:src/workbench/widgets/layers/panes/OverviewPane.tsx","source:src/workbench/widgets/layers/panes/PropertiesPane.tsx","source:src/workbench/widgets/layers/panes/PropertiesSection.tsx",@@ -3227,6 +3244,7 @@"source:src/workbench/widgets/preview/PreviewCompare.tsx","source:src/workbench/widgets/preview/PreviewCompareDropZone.tsx","source:src/workbench/widgets/preview/PreviewDetailsPanel.tsx",+ "source:src/workbench/widgets/preview/PreviewDropSurface.tsx","source:src/workbench/widgets/preview/PreviewFilmstrip.tsx","source:src/workbench/widgets/preview/PreviewFrame.tsx","source:src/workbench/widgets/preview/PreviewHeaderActions.tsx",@@ -3243,6 +3261,7 @@"source:src/workbench/widgets/preview/manifest.ts","source:src/workbench/widgets/preview/previewCompareDnd.ts","source:src/workbench/widgets/preview/previewDensity.ts",+ "source:src/workbench/widgets/preview/previewDockBar.ts","source:src/workbench/widgets/preview/previewHeaderStore.ts","source:src/workbench/widgets/preview/previewMetadata.ts","source:src/workbench/widgets/preview/previewSettings.ts",@@ -3262,6 +3281,8 @@"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/shared/DropZoneLabel.tsx",+ "source:src/workbench/widgets/shared/useDroppedFileUpload.ts","source:src/workbench/widgets/shortcuts/ShortcutGuide.tsx","source:src/workbench/widgets/shortcuts/implementation.ts","source:src/workbench/widgets/shortcuts/manifest.ts",@@ -3446,6 +3467,7 @@"source:src/features/gallery/data/queries.ts","source:src/features/gallery/data/queryCache.ts","source:src/features/gallery/data/realtimeRuntime.ts",+ "source:src/features/gallery/data/uploadDestination.ts","source:src/features/gallery/data/videoUrls.ts","source:src/features/gallery/index.ts","source:src/features/gallery/mediaSlot.ts",@@ -3585,6 +3607,7 @@"source:src/features/generation/ui/promptFields/GeneratePromptFields.tsx","source:src/features/generation/ui/promptFields/LLMTaskProgressDisplay.tsx","source:src/features/generation/ui/promptFields/NegativePromptField.tsx",+ "source:src/features/generation/ui/promptFields/NegativePromptToggle.tsx","source:src/features/generation/ui/promptFields/PositivePromptActions.tsx","source:src/features/generation/ui/promptFields/PositivePromptField.tsx","source:src/features/generation/ui/promptFields/PromptHighlight.tsx",@@ -3611,9 +3634,9 @@"source:src/features/generation/ui/promptFields/useSystemPrompts.ts","source:src/features/generation/ui/promptTemplateDraftStore.ts","source:src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx",- "source:src/features/generation/ui/reference-images/ReferenceImageCard.tsx","source:src/features/generation/ui/reference-images/ReferenceImageControls.tsx","source:src/features/generation/ui/reference-images/ReferenceImageCropDialog.tsx",+ "source:src/features/generation/ui/reference-images/ReferenceImageRow.tsx","source:src/features/generation/ui/reference-images/referenceImageConfig.ts","source:src/features/generation/ui/shared/AspectRatioPicker.tsx","source:src/features/generation/ui/shared/AspectRatioPreview.tsx",@@ -3626,8 +3649,10 @@"source:src/features/generation/ui/shared/GenerateFieldContextMenu.tsx","source:src/features/generation/ui/shared/GenerateIssues.tsx","source:src/features/generation/ui/shared/GenerateToggleSwitch.tsx",+ "source:src/features/generation/ui/shared/GenerationSectionJumpMenu.tsx","source:src/features/generation/ui/shared/SeedField.tsx","source:src/features/generation/ui/shared/modelDefaultSettings.ts",+ "source:src/features/generation/ui/shared/sectionPanel.tsx","source:src/features/generation/ui/useDebouncedDraftValue.ts","source:src/features/generation/ui/useDynamicPrompts.ts","source:src/features/generation/ui/usePromptTemplates.ts",@@ -3643,7 +3668,6 @@"source:src/features/identity/launchpad.tsx","source:src/features/identity/session.ts","source:src/features/identity/ui/AccountMenu.tsx",- "source:src/features/identity/ui/AccountMenuSection.tsx","source:src/features/identity/ui/AuthScreen.tsx","source:src/features/identity/ui/AuthUnavailableScreen.tsx","source:src/features/identity/ui/LoginScreen.tsx",@@ -3742,6 +3766,7 @@"source:src/features/queue/ui/QueueWidgetView.tsx","source:src/features/queue/ui/RecentSection.tsx","source:src/features/queue/ui/RetryQueueItemButton.tsx",+ "source:src/features/queue/ui/cancelCurrent.ts","source:src/features/queue/ui/currentBatchItems.ts","source:src/features/queue/ui/formatDuration.ts","source:src/features/queue/ui/index.ts",@@ -3863,6 +3888,8 @@"source:src/features/workflow/widget.ts","source:src/platform/browser/clipboard.ts","source:src/platform/browser/downloadBlob.ts",+ "source:src/platform/browser/dropZones.ts",+ "source:src/platform/browser/fileDropNavigation.ts","source:src/platform/browser/imeComposition.ts","source:src/platform/browser/knownBrowserIssues.ts","source:src/platform/browser/randomUuid.ts",@@ -3885,10 +3912,12 @@"source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts",+ "source:src/platform/react/isEventFromOwnDom.ts","source:src/platform/react/useDebouncedValue.ts","source:src/platform/react/useExitRetainedValue.ts","source:src/platform/react/useModifierHeld.ts","source:src/platform/react/useMountEffect.ts",+ "source:src/platform/react/useNativeFileDrag.ts","source:src/platform/react/usePreservedScrollOffset.ts","source:src/platform/react/useZodForm.ts","source:src/platform/runtime/appMetadata.ts",@@ -3922,7 +3951,6 @@"source:src/platform/ui/LoadError.tsx","source:src/platform/ui/Menu.tsx","source:src/platform/ui/MiddleTruncate.tsx",- "source:src/platform/ui/ModelDefaultButton.tsx","source:src/platform/ui/PageShell.tsx","source:src/platform/ui/Panel.tsx","source:src/platform/ui/PanelHeader.tsx",@@ -3965,6 +3993,7 @@"source:src/platform/ui/list/listLayout.ts","source:src/platform/ui/list/virtualSections.ts","source:src/platform/ui/modalPresence.ts",+ "source:src/platform/ui/scrollStripEdges.ts","source:src/platform/ui/settings/contracts.ts","source:src/platform/ui/streaming-image/StreamingImageFrame.tsx","source:src/platform/ui/streaming-image/streamingImageSource.ts",@@ -4290,9 +4319,7 @@"source:src/workbench/projectWorkflows.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts",- "source:src/workbench/projects/components/OpenProjectDialog.tsx","source:src/workbench/projects/components/ProjectFileOptionsProvider.tsx",- "source:src/workbench/projects/components/index.ts","source:src/workbench/projects/covers.ts","source:src/workbench/projects/draftStore.ts","source:src/workbench/projects/durableSyncedPersistence.ts",@@ -4464,6 +4491,7 @@"source:src/workbench/widgets/preview/PreviewCompare.tsx","source:src/workbench/widgets/preview/PreviewCompareDropZone.tsx","source:src/workbench/widgets/preview/PreviewDetailsPanel.tsx",+ "source:src/workbench/widgets/preview/PreviewDropSurface.tsx","source:src/workbench/widgets/preview/PreviewFilmstrip.tsx","source:src/workbench/widgets/preview/PreviewFrame.tsx","source:src/workbench/widgets/preview/PreviewHeaderActions.tsx",@@ -4480,6 +4508,7 @@"source:src/workbench/widgets/preview/manifest.ts","source:src/workbench/widgets/preview/previewCompareDnd.ts","source:src/workbench/widgets/preview/previewDensity.ts",+ "source:src/workbench/widgets/preview/previewDockBar.ts","source:src/workbench/widgets/preview/previewHeaderStore.ts","source:src/workbench/widgets/preview/previewMetadata.ts","source:src/workbench/widgets/preview/previewSettings.ts",@@ -4499,6 +4528,8 @@"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/shared/DropZoneLabel.tsx",+ "source:src/workbench/widgets/shared/useDroppedFileUpload.ts","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/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yamlindex f333dc0231..4e50201392 100644--- a/invokeai/frontend/webv2/pnpm-lock.yaml+++ b/invokeai/frontend/webv2/pnpm-lock.yaml@@ -5,9 +5,18 @@ settings:excludeLinksFromLockfile: falsepatchedDependencies:+ '@zag-js/[email protected]':+ hash: 53908275123b086ad52831e6cdb0d7ca9287a8d5c6ce4ef0db32325fdcb702a5+ path: patches/@[email protected]+ '@zag-js/[email protected]':+ hash: b319eca1789a28218bc00f5f40d956f34051458f8c17c3567b9a24e6419bcf72+ path: patches/@[email protected]'@zag-js/[email protected]':hash: a0448ebf0273ebd3cc9b57d2f1421568477fd5e4c673fa13180dfe6e8de2d3b5path: patches/@[email protected]+ '@zag-js/[email protected]':+ hash: 182087e83699346544bb4068991997edc5e0424f807a9c7e0abf759e4f41eea0+ path: patches/@[email protected]react-hook-tanstack-virtual:hash: a650424c322ec56178110e945f70d9e11d270c144f2c0df5527ba7d327ccb285path: patches/react-hook-tanstack-virtual.patch@@ -71,8 +80,8 @@ importers:specifier: ^8.0.4version: 8.0.4lucide-react:- specifier: ^1.61.0- version: 1.61.0(@types/[email protected])([email protected])+ specifier: ^1.69.0+ version: 1.69.0(@types/[email protected])([email protected])perfect-freehand:specifier: ^1.2.3version: 1.2.3@@ -1894,8 +1903,8 @@ packages:resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}- resolution: {integrity: sha512-v2SQPPPNjnr+BlhL9Spuzmo5yR+hLkftfuE4E3jaxdNPgSH0hJKPcLJBP7yAta87jQNPsSERS59PJjCJ/CorBA==}+ resolution: {integrity: sha512-UTFECm4yEgkgMN0kfLuxWcmlk+4u02Jrqehgk3ZXRx/Ud68OpP7hjkp67bvkBHmIpMaZCIveF1QDYeupO7XmYQ==}peerDependencies:'@types/react': '*'react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0@@ -2424,14 +2433,14 @@ snapshots:'@zag-js/json-tree-utils': 1.43.3'@zag-js/listbox': 1.43.3'@zag-js/marquee': 1.43.3- '@zag-js/menu': 1.43.3+ '@zag-js/menu': 1.43.3(patch_hash=53908275123b086ad52831e6cdb0d7ca9287a8d5c6ce4ef0db32325fdcb702a5)'@zag-js/navigation-menu': 1.43.3'@zag-js/number-input': 1.43.3'@zag-js/pagination': 1.43.3'@zag-js/password-input': 1.43.3'@zag-js/pin-input': 1.43.3'@zag-js/popover': 1.43.3- '@zag-js/presence': 1.43.3+ '@zag-js/presence': 1.43.3(patch_hash=b319eca1789a28218bc00f5f40d956f34051458f8c17c3567b9a24e6419bcf72)'@zag-js/progress': 1.43.3'@zag-js/qr-code': 1.43.3'@zag-js/radio-group': 1.43.3@@ -2451,7 +2460,7 @@ snapshots:'@zag-js/toc': 1.43.3'@zag-js/toggle': 1.43.3'@zag-js/toggle-group': 1.43.3- '@zag-js/tooltip': 1.43.3+ '@zag-js/tooltip': 1.43.3(patch_hash=182087e83699346544bb4068991997edc5e0424f807a9c7e0abf759e4f41eea0)'@zag-js/tour': 1.43.3'@zag-js/tree-view': 1.43.3'@zag-js/types': 1.43.3@@ -3655,7 +3664,7 @@ snapshots:'@zag-js/types': 1.43.3'@zag-js/utils': 1.43.3- '@zag-js/[email protected]':+ '@zag-js/[email protected](patch_hash=53908275123b086ad52831e6cdb0d7ca9287a8d5c6ce4ef0db32325fdcb702a5)':dependencies:'@zag-js/anatomy': 1.43.3'@zag-js/core': 1.43.3@@ -3728,7 +3737,7 @@ snapshots:'@zag-js/dom-query': 1.43.3'@zag-js/utils': 1.43.3- '@zag-js/[email protected]':+ '@zag-js/[email protected](patch_hash=b319eca1789a28218bc00f5f40d956f34051458f8c17c3567b9a24e6419bcf72)':dependencies:'@zag-js/core': 1.43.3'@zag-js/dom-query': 1.43.3@@ -3914,7 +3923,7 @@ snapshots:'@zag-js/types': 1.43.3'@zag-js/utils': 1.43.3- '@zag-js/[email protected]':+ '@zag-js/[email protected](patch_hash=182087e83699346544bb4068991997edc5e0424f807a9c7e0abf759e4f41eea0)':dependencies:'@zag-js/anatomy': 1.43.3'@zag-js/core': 1.43.3@@ -4307,7 +4316,7 @@ snapshots:dependencies:yallist: 3.1.1dependencies:react: 19.3.1optionalDependencies:diff --git a/invokeai/frontend/webv2/pnpm-workspace.yaml b/invokeai/frontend/webv2/pnpm-workspace.yamlindex 1eab0c4e5f..9b96a25e99 100644--- a/invokeai/frontend/webv2/pnpm-workspace.yaml+++ b/invokeai/frontend/webv2/pnpm-workspace.yaml@@ -1,3 +1,6 @@patchedDependencies:react-hook-tanstack-virtual: patches/react-hook-tanstack-virtual.patch'@zag-js/[email protected]': patches/@[email protected]+ '@zag-js/[email protected]': patches/@[email protected]+ '@zag-js/[email protected]': patches/@[email protected]+ '@zag-js/[email protected]': patches/@[email protected]diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 9201199006..ef23207dea 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -178,6 +178,8 @@"donateToInvokeAI": "Donate to Invoke","actions": "Actions","active": "Active",+ "activeFilterCount_one": "{{count}} filter active",+ "activeFilterCount_other": "{{count}} filters active","add": "Add","all": "All","apply": "Apply",@@ -213,6 +215,12 @@"editValue": "Edit {{label}}: {{value}}"},"list": {+ "reorderCancelled": "Reorder cancelled. {{name}} is back at position {{position}} of {{count}}.",+ "reorderDropped": "{{name}} dropped at position {{position}} of {{count}}.",+ "reorderInstructions": "To pick up a row, press Space or Enter. Use the Up and Down arrow keys to move it, then press Space or Enter to drop it, or Escape to cancel.",+ "reorderMoved": "{{name}} moved to position {{position}} of {{count}}.",+ "reorderPickedUp": "Picked up {{name}} at position {{position}} of {{count}}.",+ "reorderRole": "sortable","selectItem": "Select {{name}}"},"configure": "Configure",@@ -267,12 +275,12 @@"refresh": "Refresh","reload": "Reload","reset": "Reset",+ "resetFilters": "Reset filters","retry": "Retry","saved": "Saved","save": "Save","seed": "Seed","settings": "Settings",- "settingsWithShortcut": "Settings ({{hotkey}})","nextPage": "Next page","somethingWentWrong": "Something went wrong.","swap": "Swap",@@ -288,6 +296,9 @@"viewJson": "View JSON","widgetViewUnavailable": "Widget view unavailable.","loading": "Loading…",+ "menuPartLoadFailed": "Couldn't load these items",+ "menuPartLoadFailedReason": "Open the menu again to retry. If it fails again, reload the page.",+ "menuPartLoading": "These items are still loading.","seedMode": {"label": "Seed mode","random": "Random",@@ -343,6 +354,7 @@},"auth": {"account": "Account",+ "accountMenu": "Account: {{name}}","accountSettings": "Account settings","accountUpdated": "Account updated","administrator": "Administrator",@@ -395,6 +407,7 @@},"notifications": {"empty": "Successful operations, errors, and system messages appear here.",+ "emptyTitle": "No notifications","labelWithCount": "Notifications: {{label}}","newCount_one": "{{count}} new","newCount_other": "{{count}} new",@@ -406,6 +419,7 @@"success": "Success"},"markRead": "Mark read",+ "unread": "Unread","actions": {"openWidget": "Open {{widget}}","showInQueue": "Show in queue"@@ -515,6 +529,12 @@},"presets": {"builtIn": "Built-in",+ "builtInDescriptions": {+ "automate": "Build and run workflows",+ "compose": "Generate images from text",+ "edit": "Edit and refine images",+ "video": "Generate video"+ },"builtInLabels": {"automate": "Workflow","compose": "Compose",@@ -537,6 +557,7 @@"icon": "Icon","iconPicker": "Layout preset icon","layoutPreset": "Layout preset",+ "list": "Layout presets","manage": "Manage presets","more": "More layout presets","moreAvailable": "More layout presets, {{count}} available",@@ -932,6 +953,7 @@"app": "App","canvas": "Canvas","gallery": "Gallery",+ "queue": "Queue","viewer": "Viewer","workflows": "Workflows"},@@ -2564,7 +2586,7 @@"description": "Highlight the region receiving keyboard shortcuts."},"autoSwitchInvocationRoute": {- "label": "Invoke follows what you edit",+ "label": "Auto-switch Invoke to what you're editing","description": "When you edit in Generate, Canvas, Upscale, Video or a workflow, the Invoke button switches to run that. A route you locked never changes."},"enableInformationalPopovers": {@@ -2932,12 +2954,14 @@"panelLabel": "{{region}} widget panel","resizePanel": "Resize {{region}} widget panel","settingsLabel": "{{label}} settings",- "visibilityLabel": "{{region}} widget visibility",+ "regionWidgets": {+ "bottom": "Status bar widgets",+ "left": "Left panel widgets",+ "right": "Right panel widgets"+ },"rail": {- "create": "Create",- "inspect": "Inspect",- "createWidgets": "Create widgets",- "inspectWidgets": "Inspect widgets"+ "left": "Left rail",+ "right": "Right rail"},"properties": {"noCanvas": "Open a canvas to edit its properties.",@@ -3020,7 +3044,7 @@"activeCount_other": "{{count}} active","activeOfTotal": "{{active}}/{{total}} active","activeSteps": "Active steps",- "addConcept": "Add concept",+ "activeStepsShort": "Steps","addConceptsHelp": "Add LoRAs/concepts here to blend them into this generation.","addPromptTrigger": "Add prompt trigger","addReferenceImage": "Add reference image",@@ -3035,6 +3059,7 @@"aspectRatioHeightTerm": "Ratio height","aspectRatioListFull": "You can keep up to {{count}} ratios. Delete one to add another.","aspectRatioListFullNotice": "Your ratios list is full.",+ "aspectRatioLocked": "Aspect ratio locked","aspectRatioName": "Ratio name","aspectRatioNameRequired": "Enter a name.","aspectRatioOutOfRange": "Use a ratio between 1:8 and 8:1.",@@ -3053,7 +3078,7 @@"cfgRescale": "CFG rescale","clearReferenceImages": "Remove all","clipSkip": "CLIP skip",- "collapseReferenceImage": "Collapse reference image",+ "clipVisionModel": "CLIP Vision","colorCompensation": "Color compensation","compatibleEmbeddings": "Compatible embeddings","completionSuggestions": "Completions",@@ -3096,6 +3121,7 @@"cropFitView": "Fit image","cropReferenceImage": "Crop reference image","cropReferenceImageHelp": "Drag the crop box to move it, or drag its handles to resize. Scroll to zoom and hold Space to drag the view. Apply to create a cropped reference image.",+ "cropReferenceImageNamed": "Crop {{name}}","cropSaveToAssets": "Save to Uploads","cropSavedToAssets": "The crop was saved to Uploads.","cropZoomIn": "Zoom in",@@ -3104,7 +3130,7 @@"deletePromptHistoryItem": "Delete prompt history item","denoisingStrength": "Denoising strength","disableConcept": "Disable {{name}}",- "disableReferenceImage": "Disable reference image",+ "disableReferenceImageNamed": "Disable {{name}}","dropImageToPrompt": "Describe this image","dynamicButton": "Dynamic","dynamicPrompts": {@@ -3202,8 +3228,8 @@"selectToUse": "Select a prompt to replace yours with it."},"enableConcept": "Enable {{name}}",+ "enableReferenceImageNamed": "Enable {{name}}","enableNegativePrompt": "Enable negative prompt",- "enableReferenceImage": "Enable reference image","enabled": "Enabled","enterPromptToExpand": "Enter a prompt to expand.","expand": "Expand",@@ -3214,7 +3240,6 @@"expandUseSuggestedModel": "Use it","expandUseSuggestedModelLabel": "Use {{model}}","expandSuggestedModelMissing": "{{model}}, the prompt enhancer recommended for this model, isn't installed. It is among the starter models.",- "expandReferenceImage": "Expand reference image","generatePrompt": "Generate Prompt","guidance": "Guidance","height": "Height",@@ -3303,8 +3328,6 @@"modeStyle": "Style","model": "Model","modelDefault": "Model default",- "moveReferenceImageDown": "Move reference image down",- "moveReferenceImageUp": "Move reference image up","moreRatios": "More aspect ratios","negativePrompt": "Negative prompt","negativePromptAdd": "Negative prompt…",@@ -3344,6 +3367,10 @@"width": "Render width"},"resetToModelDefault": "Reset to model default",+ "resetToBaseDefault": "Reset to {{base}} default",+ "resetToModelAndBaseDefault": "Reset to model and {{base}} default",+ "bundledVae": "Bundled VAE",+ "useBundledVae": "Use the bundled VAE","resetToConceptDefault": "Reset to concept default","resetToDefault": "Reset to default","retry": "Retry",@@ -3352,6 +3379,25 @@"selectSupportedModelFirst": "Select a supported Generate model first.","searchPresets": "Search presets","secondsPerRun": "~{{value}}s/run",+ "sectionChanged": "Changed from defaults",+ "sectionMenu": {+ "copySummary": "Copy summary",+ "expandAll": "Expand all",+ "foldAll": "Fold all",+ "foldOthers": "Fold others",+ "reset": "Reset section to defaults",+ "resetProviderOptions": "Reset to provider defaults",+ "resetSize": "Reset size to model defaults",+ "resetSizeBase": "Reset size to {{base}} defaults",+ "resetSizeMixed": "Reset size to model and {{base}} defaults",+ "resetStepsAndGuidance": "Reset steps and {{guidance}} to model defaults",+ "resetStepsAndGuidanceBase": "Reset steps and {{guidance}} to {{base}} defaults",+ "resetStepsAndGuidanceMixed": "Reset steps and {{guidance}} to model and {{base}} defaults",+ "resetStepsGuidanceAndScheduler": "Reset steps, {{guidance}} and scheduler to model defaults",+ "resetStepsGuidanceAndSchedulerBase": "Reset steps, {{guidance}} and scheduler to {{base}} defaults",+ "resetStepsGuidanceAndSchedulerMixed": "Reset steps, {{guidance}} and scheduler to model and {{base}} defaults",+ "summaryText": "{{label}}: {{summary}}"+ },"sizePreviewHandle": "Drag to resize the generation size","switchModelBody": "Switching to {{name}}:","switchModelConfirm": "Switch model",@@ -3430,24 +3476,54 @@"readyWithIterations_one": "Ready · {{count}} iteration","readyWithIterations_other": "Ready · {{count}} iterations","referenceImageNumbered": "Reference image {{index}}",- "referenceImageModel": "Reference image model",+ "referenceImageRemoved": "Removed {{name}}",+ "referenceImageChooseModel": "Choose model",+ "referenceImageCropped": "cropped",+ "referenceImageMenu": {+ "crop": "Crop…",+ "moveDown": "Move down",+ "moveUp": "Move up",+ "remove": "Remove",+ "rename": "Rename",+ "renameHint": "Or double-click the name",+ "turnOff": "Turn off",+ "turnOn": "Turn on"+ },+ "referenceImageMoreActions": "More actions for {{name}}",+ "referenceImageNameReserved": "{{name}} is another reference's default name. Choose a different one.",+ "referenceImageNoImage": "No image",+ "referenceImageNoModel": "No model","referenceImagePromptTagCopied": "Copied {{tag}}","referenceImagePromptTagExplanation": "Write {{tag}} in the prompt to refer to this image.","referenceImagePromptTagHint": "Write {{tag}} in the prompt to refer to this image. Click to copy.",+ "referenceImageSettings": "{{name}} settings",+ "referenceImageSize": "{{width}} × {{height}}","referenceImages": "Reference images","referenceImagesNeedGgufVisionTower": "Reference images need this encoder's Vision Tower (the mmproj file). Select it under Components.","referenceImagesNeedVisionTower": "Reference images need a Qwen3-VL 8B encoder with a vision tower. Select one under Components, or use a Diffusers Qwen-Image-2.1 model.","referenceImagesUnsupported": "Reference images are not supported by the selected model.","removeConcept": "Remove concept","removeConceptNamed": "Remove {{name}}",- "removeReferenceImage": "Remove reference image","render": "Render","resetSize": "Reset size",- "resetSizeModelDefaults": "Model defaults",- "resetSizeOptimalForCurrentRatio": "Optimal size for current ratio",- "resetSizeOptimalForRatio": "Optimal size for {{ratio}}",- "resetSizeSquareNative": "Square at native size",- "resetAllToModelDefaults": "Reset all to model defaults",+ "resetSizeModelDefaults": "Model default",+ "resetSizeOptimalForCurrentRatio": "Optimal for ratio",+ "resetSizeOptimalForRatio": "Optimal for {{ratio}}",+ "resetSizeSquareNative": "Native square",+ "applyModelDefaults": "Apply model defaults",+ "modelDefaultsChange": "{{setting}} {{from}} → {{to}}",+ "modelDefaultsUnset": "Left as is, not set for this model: {{settings}}",+ "modelDefaultsApplyHint": "{{changes}}. Left as is, not set for this model: {{settings}}",+ "modelDefaultsVaeMissing": "The model's VAE is not installed or does not fit it, so your VAE stays.",+ "modelDefaultsWithVaeMissing": "{{hint}}. The model's VAE is not installed or does not fit it, so your VAE stays.",+ "modelDefaultsOnlyVaeMissing": "{{name}} sets only a VAE, which is not installed or does not fit it, so your VAE stays.",+ "modelDefaultsAppliedExceptVae": "Already using {{name}}'s defaults, except its VAE, which is not installed or does not fit it, so your VAE stays.",+ "modelDefaultsNoneSet": "{{name}} has no default settings of its own. Add them in the Model Manager.",+ "modelDefaultsAlreadyApplied": "Already using {{name}}'s defaults.",+ "resetSettings": "Reset settings",+ "resetEverythingToDefaults": "Reset everything to defaults",+ "resetEverythingToDefaultsHint": "The model's values where it sets them, Invoke's defaults for the rest, size included. The VAE changes only to a default VAE the model sets that can be used.",+ "resetEverythingAlreadyDone": "Already at defaults.","resizeNegativePrompt": "Resize negative prompt","resizePositivePrompt": "Resize positive prompt","scheduler": "Scheduler",@@ -3467,6 +3543,7 @@"size": "Size","sizeRecommended": "Recommended ✓","steps": "Steps",+ "stepRangeValue": "{{begin}}–{{end}}%","strength": "Strength","styleVariant": "Style variant","styleVariantPrecise": "Precise",@@ -3479,11 +3556,10 @@"templatesButton": "Templates","unlockAspectRatio": "Unlock aspect ratio","upload": "Upload",- "useModelDefaultVae": "Use model default VAE",- "useModelDefaultVaePrecision": "Use model default VAE precision","usePrompt": "Use prompt","useSeed": "Use seed {{seed}}","useSize": "Use size",+ "useSizeOfReferenceImage": "Use the size of {{name}}","usingBundledVae": "Using the VAE bundled with the model.","vae": "VAE","vaePrecision": "VAE precision",@@ -3564,7 +3640,8 @@"switchedModel": "Switched to {{name}}","modelMissingPlaceholder": "{{name}} (not installed)","chooseAnotherModel": "Choose another model",- "resetToModelDefaultsDone": "Reset to {{name}} defaults",+ "applyModelDefaultsDone": "Applied {{name}} defaults",+ "resetEverythingToDefaultsDone": "Reset everything to defaults","presetApplied": "Applied preset {{name}}","presetIncludePrompts": "Include prompts","issueCount_one": "{{count}} issue",@@ -3592,13 +3669,13 @@"providerMaxSize": "{{name}} supports at most {{width}}×{{height}}.","referenceImageLimit_one": "{{name}} supports at most {{count}} reference image. Turn off or remove the extra ones.","referenceImageLimit_other": "{{name}} supports at most {{count}} reference images. Turn off or remove the extra ones.",- "referenceImageNeedsImage": "Reference image {{index}} needs an image.",- "referenceImageNeedsIpAdapter": "Reference image {{index}} needs an IP Adapter model for {{name}}.",- "referenceImageNeedsKontext": "Reference image {{index}} needs the selected FLUX Kontext model.",- "referenceImageNeedsRedux": "Reference image {{index}} needs a FLUX Redux model for {{name}}.",- "referenceImageStrength": "Reference image {{index}} strength must be between 0 and 2.",- "referenceImageUnsupported": "{{name}} cannot use reference image {{index}}. Turn it off, or remove it.",- "referenceModelNotInstalled": "Reference image {{index}} uses \"{{name}}\", which is not installed. Turn it off, or choose another model for it.",+ "referenceImageNeedsImage": "{{reference}} needs an image.",+ "referenceImageNeedsIpAdapter": "{{reference}} needs an IP Adapter model for {{name}}.",+ "referenceImageNeedsKontext": "{{reference}} needs the selected FLUX Kontext model.",+ "referenceImageNeedsRedux": "{{reference}} needs a FLUX Redux model for {{name}}.",+ "referenceImageStrength": "{{reference}} strength must be between 0 and 2.",+ "referenceImageUnsupported": "{{name}} cannot use {{reference}}. Turn it off, or remove it.",+ "referenceModelNotInstalled": "{{reference}} uses \"{{name}}\", which is not installed. Turn it off, or choose another model for it.","refinerNotInstalled": "Refiner \"{{name}}\" is not installed. Choose another, or clear it.","widthGrid": "Width must be a multiple of {{grid}}.","widthRange": "Width must be between {{min}} and {{max}}."@@ -3650,6 +3727,9 @@},"switchUndoStale": "The model changed after switching to {{name}}, so nothing was undone.","issueFixNamed": "{{fix}}: {{issue}}",+ "issuesNamed_one": "{{count}} issue: {{messages}}",+ "issuesNamed_other": "{{count}} issues: {{messages}}",+ "jumpToSection": "Jump to section","resetFieldNamed": "{{reset}}: {{field}}","notInstalled": "Not installed","conceptWeightNamed": "{{name}} weight",@@ -3813,6 +3893,7 @@"chooseAnotherItem": "{{label}}. Choose another item","commands": {"deletePreviewImage": "Delete preview image",+ "exitCompare": "Cancel or exit compare","nextComparisonMode": "Next comparison mode","nextItem": "Show next item","previousItem": "Show previous item",@@ -3822,7 +3903,10 @@"zoomToActual": "Zoom preview to 100%","zoomToFit": "Zoom preview to fit"},+ "cancelCompare": "Cancel compare","compare": "Compare",+ "compareArmedHint": "Pick another image to compare with this one",+ "compareArmedTooltip": "Pick another image to compare · click to cancel","copyCurrentFrame": "Copy current frame","copyCurrentFrameDrawFailed": "Could not read the current video frame","copyCurrentFrameEncodeFailed": "Could not encode the current video frame",@@ -3834,6 +3918,10 @@"details": "Details","dragVideo": "Drag video","dropToCompare": "Drop to compare",+ "dropToShow": "Drop to show",+ "dropPending": "The files you dropped are still uploading. Try again when they are done.",+ "dropUploading_one": "Uploading the dropped file…",+ "dropUploading_other": "Uploading {{count}} dropped files…","editOnCanvas": "Edit on Canvas","editThisImage": "Edit this image","emptyDescription": "Select an image or video in the Gallery to see it here.",@@ -3875,6 +3963,8 @@"imageTags": "Image tags:","hoverComparisonAriaLabel": "Reveal comparison image on hover, focus, or touch","sourceRun": "Source run {{id}}",+ "starting": "Starting…",+ "startingAnnouncement": "The next image is starting","videoDuration": "Duration {{duration}}","videoDetails": "Video details","videoFailed": "Video could not be loaded",@@ -4033,6 +4123,7 @@"cancelAllItems": "Cancel all items","cancelCurrentItem": "Cancel current item","cancelItem": "Cancel queue item #{{id}}",+ "cancelNextItem": "Cancel next item","cancellationRequested": "Cancellation requested","clearAllItems": "Clear all items","clearFailedItems": "Clear failed items",@@ -4085,6 +4176,7 @@"off": "Off","unavailable": "Unavailable"},+ "itemAlreadyFinished": "Already finished","itemJsonLabel": "Queue item {{id}} JSON","itemProgress": "Queue item progress","itemTitle": "Queue item #{{id}}",@@ -4100,7 +4192,8 @@"noModelsCleared": "No cached models cleared","noModelsClearedDescription": "No unlocked cached models were available to clear. Active models stay loaded until they are no longer in use."},- "noCurrentItem": "No current item",+ "noCurrentItem": "Nothing to cancel",+ "nothingRecalled": "Nothing recalled","openQueue": "Open queue","pauseProcessor": "Pause processor","processorPaused": "Processor paused",@@ -4110,6 +4203,9 @@"queued_one": "{{count}} queued","queued_other": "{{count}} queued","recallAll": "Recall all",+ "recallNotForVideo": "Not offered for video jobs; Recall all restores every setting.",+ "recallRandomSeed": "This job used a random seed the server has not reported.",+ "recallSettingsNotKept": "This browser did not keep this item's settings, so only a prompt or seed the server recorded can be recalled.","recallUnavailable": "Nothing recallable for this item — select a supported Generate model first.","recallUnavailableCapabilities": "Nothing recallable yet — model capabilities have not loaded. If loading failed, retry from the Generate panel.","recallUnavailableForItem": "Nothing recallable for this item.",@@ -4272,10 +4368,10 @@"mine": "Deleted your items across all your projects."},"noCurrentItemDescription": {- "project": "Nothing is running in {{project}}.",- "all": "Nothing is running across all projects.",- "allUsers": "Nothing is running across all projects.",- "mine": "None of your items is running."+ "project": "Nothing is running or waiting in {{project}}.",+ "all": "Nothing is running or waiting across all projects.",+ "allUsers": "Nothing is running or waiting across all projects.",+ "mine": "None of your items is running or waiting."},"actionHasNothingToDo": "There is nothing for this to act on right now.","revealUnavailable": "Queue item #{{id}} is not in this list",@@ -4347,7 +4443,7 @@"selectShapeTool": "Select shape tool","selectTextTool": "Select text tool","selectTransformTool": "Transform selected layer",- "selectViewTool": "Select view tool",+ "selectViewTool": "Select pan tool","toggleNonRasterLayers": "Hide control, guidance and mask layers","undo": "Undo canvas edit","groupLayers": "Group selected layers",@@ -4432,6 +4528,12 @@"operationRunning": "Finish or cancel the current canvas operation first.","clearFailedMessage": "The canvas didn’t take the change, so nothing was cleared. Try again in a moment."},+ "frameReadout": {+ "frame": "Frame",+ "label": "Frame and render size",+ "render": "Render",+ "size": "{{width}}×{{height}}"+ },"hideStagedResultPreview": "Hide staged result preview","hideStagingThumbnails": "Hide staging thumbnails","import": {@@ -4522,6 +4624,7 @@"discardedAllKept": "History keeps a restore point of them.","discardedAllStopped_one": "Also stopped the queue item still running. Undo brings back the results, not the stopped item.","discardedAllStopped_other": "Also stopped {{count}} queue items still running. Undo brings back the results, not the stopped items.",+ "stopGenerating": "Stop generating","stoppedGenerating_one": "Stopped the queue item still running","stoppedGenerating_other": "Stopped {{count}} queue items still running","acceptedOthers_one": "Set aside {{count}} other result. Undoing on the canvas removes only the new layer.",@@ -4595,6 +4698,8 @@"selectionIntersect": "Intersect","selectionMode": "Selection mode","selectionNeedsPaintLayer": "Select an unlocked, visible paint layer first",+ "selectionNeedsPixelLayer": "Select a paint layer, image, control layer or mask first",+ "refusalReason": "{{title}}. {{message}}","selectionNeedsSelection": "Make a selection first","selectionReplace": "Replace","selectionSubtract": "Subtract",@@ -4653,19 +4758,20 @@"shape": "Shape","text": "Text","transform": "Transform",- "view": "View",+ "view": "Pan","withHotkey": "{{label}} ({{hotkey}})","bboxHoldHelp": "Hold C to use it until you let go; tap C to stay on it."},"controlHint": {- "title": "Drop an image here",- "body": "or pick one in Properties",+ "title": "Add an image",+ "body": "Drag one onto Add as control layer, or pick one in Properties","uploading": "Uploading…"},"fileDrop": {- "oneFile": "Drop one image at a time.","notImage": "Only image files can be dropped on the canvas.",- "noTarget": "Select an empty control layer to drop an image on it."+ "pending": "The files you dropped are still uploading. Try again when they are done.",+ "uploading_one": "Uploading the dropped image…",+ "uploading_other": "Uploading {{count}} dropped images…"},"controlView": {"label": "Control layer view",@@ -4679,6 +4785,15 @@"hidden": "“{{name}}” is hidden","hiddenMessage": "Show the layer to edit it.","hiddenOfferMessage": "Show the layer to paint on it, or paint on a new layer above it.",+ "excluded": "“{{name}}” is left out of generation",+ "excludedMessage": "Use it in generation to edit it.",+ "displayHidden": "“{{name}}” is hidden on the canvas",+ "displayHiddenMessage": "Show it on the canvas to edit it.",+ "displayHiddenOfferMessage": "Show it on the canvas to paint on it, or paint on a new layer above it.",+ "eraseUnsupported": "“{{name}}” can’t be erased",+ "eraseUnsupportedMessage": "The eraser works on paint layers, images, control layers and masks.",+ "gradientUnsupported": "Can’t add a gradient to “{{name}}”",+ "gradientUnsupportedMessage": "A gradient is a raster layer of its own. Select a raster layer, or nothing, to add one.","locked": "“{{name}}” is locked","lockedMessage": "Unlock the layer to edit it.","lockedOfferMessage": "Unlock the layer to paint on it, or paint on a new layer above it.",@@ -4688,6 +4803,16 @@"loadingMessage": "Its pixels are on their way. Try again in a moment.","noCutoutTarget": "Nothing to cut the shape out of","noCutoutTargetMessage": "Select a paint layer or mask to cut the shape out of it.",+ "noEraseTarget": "Nothing to erase",+ "noEraseTargetMessage": "Select a paint layer, image, control layer or mask to erase from it.",+ "selectionEraseUnsupported": "Can’t remove the selection from “{{name}}”",+ "selectionEraseUnsupportedMessage": "Erase, Delete and Cut remove pixels from paint layers, images, control layers and masks.",+ "noSelectionEraseTarget": "No layer to remove the selection from",+ "noSelectionEraseTargetMessage": "Select a paint layer, image, control layer or mask, then try again.",+ "unpaintable": "“{{name}}” has no pixels to edit",+ "unpaintableMessage": "Its shape is empty, so there is nothing to paint on or erase.",+ "transformSession": "“{{name}}” is being transformed",+ "transformSessionMessage": "Apply or cancel the transform first.","paintOnNewLayer": "Paint on a new layer"},"restorePoints": {@@ -4974,6 +5099,7 @@"moveToFront": "Move to front","notReady": "The layer content is still loading. Try again shortly.","opacity": "Opacity",+ "opacitySlider": "Opacity slider","operationFailed": "The canvas could not apply this change, so nothing was changed.","overBudget": "There is not enough canvas memory to make this change undoable, so nothing was changed.","stale": "The layer changed before this action finished, so nothing was changed. Try again.",@@ -5005,7 +5131,8 @@"outdent": "Move out of the group","groupLocked": "Locked by a group","groupDisabled": "Hidden by a group. Show the group to bring it back.",- "groupHidden": "Hidden on the canvas by a group. Generation still uses it.",+ "groupHidden": "Hidden on the canvas by a group. Show the group on the canvas to bring it back.",+ "groupExcluded": "Left out of generation by a group. Use the group in generation to bring it back.","duplicateCount_one": "Duplicate layer","duplicateCount_other": "Duplicate {{count}} layers","groupCount_one": "Group layer",@@ -5018,29 +5145,47 @@"addDenoiseLimit": "Add denoise limit","addNoise": "Add noise","addRegenerateRegion": "Add regenerate region",- "addRegenerateRegionDescription": "Regenerate where this layer has content, as a live inpaint mask.",+ "addRegenerateRegionDescription": "Inpaint where this layer has content.","canvasNotReady": "The canvas is still starting. Try again in a moment.","operationLocked": "Unavailable while Filter or Select Object is running on the canvas.","mergeMasks": "Merge masks","mergeMasksIneligible": "Merge masks needs two or more enabled, unlocked inpaint masks with content.","mergeMasksSettingsDiffer": "The masks have different noise or denoise settings. Match them to merge.",+ "mergeDownRefused": "Can’t merge “{{name}}” down",+ "mergeDownNoLayerBelow": "There is no layer below it to merge into.",+ "mergeDownBottomOfGroup": "It is the bottom layer of its group, so there is no layer below it to merge into.",+ "mergeDownGroupBelow": "“{{name}}” below it is a group. Merge down joins two layers.",+ "mergeDownGroupSelected": "Merge down works on a layer, not a group.",+ "mergeDownMaskSelected": "To combine inpaint masks, select them and choose Merge masks.",+ "mergeDownNotMergeable": "Only paint and image layers merge. Rasterize “{{name}}” first.",+ "mergeDownHidden": "“{{name}}” is hidden. Show it to merge.",+ "mergeDownLocked": "“{{name}}” is locked. Unlock it to merge.",+ "mergeDownWrongType": "Merge down joins a raster layer with the raster layer directly below it.","removeFromGroup": "Remove from group","removeFromGroupLocked": "Unlock the layer and the groups that contain it first.",- "transformIneligible": "Transform works on enabled raster and control layers with content.",+ "transformIneligible": "Transform works on enabled layers with content.",+ "transformUnavailable": "Can’t transform “{{name}}”","useAsControlLayer": "Use as control layer","hideSelected": "Hide selected","showSelected": "Show selected",- "hideOnCanvas": "Hide on canvas only",+ "hideOnCanvas": "Hide on canvas","showOnCanvas": "Show on canvas",- "hideSelectedOnCanvas": "Hide selected on canvas only",+ "hideSelectedOnCanvas": "Hide selected on canvas","showSelectedOnCanvas": "Show selected on canvas","hideGroup": "Hide group","showGroup": "Show group",- "hideGroupOnCanvas": "Hide group on canvas only",+ "hideGroupOnCanvas": "Hide group on canvas","showGroupOnCanvas": "Show group on canvas","hideLayerTooltip": "Hide layer. A hidden layer is also left out of generation.","showLayerTooltip": "Show layer. While hidden, it is left out of generation.",- "canvasHiddenTooltip": "Hidden on the canvas only; generation still uses it. Click to show it."+ "excludeFromGeneration": "Exclude from generation",+ "useInGeneration": "Use in generation",+ "excludeSelectedFromGeneration": "Exclude selected from generation",+ "useSelectedInGeneration": "Use selected in generation",+ "turnOffSelected": "Turn off selected",+ "turnOnSelected": "Turn on selected",+ "excludeGroupFromGeneration": "Exclude group from generation",+ "useGroupInGeneration": "Use group in generation"},"control": {"apply": "Apply",@@ -5336,7 +5481,7 @@"aborted": "The filter was cancelled before it was applied.","applyAs": "Apply as","applyFailed": "The filter could not be applied.",- "autoProcess": "Process automatically",+ "autoProcess": "Auto-update preview","categories": {"edge": "Edge detection","depth": "Depth & normal",@@ -5358,9 +5503,9 @@"notReady": "The canvas is not ready for the filter yet. Try again in a moment.","overBudget": "The filtered layer is too large to undo, so it was not applied.","preview": "Preview",+ "process": "Process","processFailed": "The filter could not run.","replace": "Replace",- "resetSettings": "Reset settings","running": "Running filter…","sourceAdjustmentError": "Clarity, Texture or Dehaze failed on this layer, so it was not filtered. Change a setting or disable them, then try again.","sourceAdjustmentOverBudget": "Not enough canvas memory to apply this layer’s Clarity, Texture or Dehaze before filtering it. Delete layers you no longer need, then try again.",@@ -5368,16 +5513,17 @@"sourceOverBudget": "Not enough memory is free to read this layer for the filter.","sourceUnreadable": "The layer's image could not be read, so it cannot be filtered.","statusCommitting": "Applying filter…",- "statusError": "Filter needs attention.","stale": "The layer changed while filtering. Preview it again.","title": "Filter","unsupported": "This layer content cannot be filtered."},"selectObject": {- "autoProcess": "Auto Process",+ "autoProcess": "Auto-update preview","bbox": "Box",- "bboxActive": "Box prompt set",- "bboxInactive": "No box prompt",+ "bboxActive": "Set",+ "bboxInactive": "Drag on the canvas",+ "clearBox": "Clear box",+ "errorCommitFailed": "Select Object could not apply or save the result.","errorDecode": "The object preview could not be decoded.","errorEmpty": "The layer has no visible content to select.","errorInvalid": "Add an object prompt, point, or box before processing.",@@ -5395,40 +5541,36 @@"errorUpload": "The layer source could not be uploaded for Select Object.","exclude": "Exclude","excludeCount": "Exclude {{count}}",+ "findObject": "Find object","include": "Include","includeCount": "Include {{count}}","invert": "Invert",- "isolatedPreview": "Isolated Preview",+ "isolatedPreview": "Show only the object","model": "Model","modelHuge": "SAM Huge","modelSam2Large": "SAM 2 Large",- "mode": "Selection mode",- "prompt": "Object prompt",+ "mode": "Select by",+ "prompt": "Prompt","promptGuidance": "Describe the object you want to select.","promptMode": "Prompt",- "pointType": "Point type",- "process": "Process",- "refine": "Refine",- "reset": "Reset",- "saveAs": "Save As",+ "pointType": "Points",+ "refine": "Refine edges",+ "saveAs": "Save as","saveAs_control": "Control layer","saveAs_inpaint_mask": "Inpaint mask","saveAs_raster": "Raster layer","saveAs_regional_guidance": "Regional guidance","saveAs_selection": "Selection",- "settings": "Select Object settings","sourceLayerLabel": "{{name}} · {{type}} · {{width}} × {{height}}","statusCommitting": "Applying object result…",- "statusError": "Select Object needs attention.","statusPreparingSource": "Preparing layer source…","statusProcessingSam": "Finding object…",- "statusReady": "Ready","statusRenderingPreview": "Rendering object preview…","statusScheduled": "Waiting to process object…","statusUploading": "Uploading layer source…","technicalDetails": "Technical details","title": "Select Object",- "visual": "Visual",+ "visual": "Points & box","visualGuidance": "Click to add · drag to move · Shift flips type"},"runWorkflow": {@@ -5626,6 +5768,7 @@},"options": "Layer options","regionalGuidance": {+ "addNegativePrompt": "Add negative prompt","addReferenceImage": "Add reference image","autoNegative": "Auto-Negative","clearReferenceImage": "Clear reference image",@@ -5650,7 +5793,6 @@"model": "Model","negativePrompt": "Negative prompt","negativePromptAdd": "Negative prompt…",- "negativePromptHide": "Turn off negative prompt","negativePromptPlaceholder": "Region negative prompt","negativesNeedCfg": "Negative prompts and Auto-Negative take effect only when CFG Scale is above 1.","positivePrompt": "Positive prompt",@@ -5658,6 +5800,7 @@"referenceImage": "Reference image","referenceImageHelp": "Choose an image from the gallery, drop one here, or upload a file.","referenceImages": "Reference images",+ "removeNegativePrompt": "Remove negative prompt","removeReferenceImage": "Remove reference image","selectModel": "Select a model","unsupportedModel": "The selected model does not support regional guidance. This layer is skipped during generation.",@@ -5758,6 +5901,7 @@"disable": "Disable","enable": "Enable","parentDisabled": "The layer is hidden, so this has no effect.",+ "parentExcluded": "The layer is left out of generation, so this has no effect.","toggleActive": "Enable/disable","denoise": "Denoise limit","denoiseHelp": "Caps how strongly generation may repaint the masked area.",@@ -5929,6 +6073,8 @@"workflow": "Library workflow “{{name}}”","workflowUnnamed": "Untitled library workflow"},+ "itemCountAtLeast_one": "at least {{count}} item",+ "itemCountAtLeast_other": "at least {{count}} items","itemCount_one": "{{count}} item","itemCount_other": "{{count}} items","listLabel": "Where the media is used",@@ -5957,7 +6103,6 @@"video": "Video panel","workflow": "Workflow “{{name}}”"},- "tooManyItems": "Too many items to check them all: only projects open here were checked. Select fewer to check all.","unchecked": "Other projects, workflows and jobs weren’t checked. Retry to complete the list.","uncheckedNone_one": "Nothing open here uses it. Other projects, workflows and jobs weren’t checked: retry to check them.","uncheckedNone_other": "Nothing open here uses them. Other projects, workflows and jobs weren’t checked: retry to check them.",@@ -6026,7 +6171,11 @@},"download": {"partial": "{{succeeded}} of {{count}} items downloaded; {{failed}} failed or were skipped.",- "success": "Download ready"+ "preparingArchives_one": "Preparing {{count}} .zip file of images.",+ "preparingArchives_other": "Preparing {{count}} .zip files: one holds at most 1,000 images, so this selection downloads in parts.",+ "success": "Download ready",+ "successArchives_one": "{{count}} download ready",+ "successArchives_other": "{{count}} downloads ready"},"move": {"failure_one": "Could not move {{count}} item to {{board}}.",@@ -6048,6 +6197,7 @@"nothingRecalledVideo": "No recallable video data","nothingRecalledVideoSize": "Size not recalled","partiallyRecalled": "Some image data was not recalled",+ "recallInProgress": "Another recall is still under way. Try again once it finishes.","unnamedConcept": "unnamed concept","unnamedRefiner": "unnamed refiner","videoMetadataUnsupported": "This video does not include supported Video metadata.",@@ -6412,6 +6562,8 @@"idle": "Queue idle","paused": "Paused · {{count}} waiting","queued": "{{count}} queued",+ "loadingModel": "Loading {{model}} · {{count}} queued",+ "loadingModelUnnamed": "Loading model · {{count}} queued","offline": "{{count}} queued · reconnecting…"},"serverStatus": {diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex 13e1f36072..917271b12f 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -275,7 +275,7 @@ const surfaces = [// The new layer's Properties panel and the canvas hint over its empty source are both scanned.const type = page.getByRole('combobox', { exact: true, name: 'Type' });await type.waitFor();- await page.getByRole('note').filter({ hasText: 'Drop an image here' }).waitFor();+ await page.getByRole('note').filter({ hasText: 'Add an image' }).waitFor();await waitForSettledDocument(page);await assertNoAxeViolations(page, 'workbench-canvas-control-layer-untyped');// Typed as Depth: the seed holds two depth models, so the panel asks for one; the runner scans this state.@@ -393,7 +393,7 @@ const runShortcutGuideJourney = async (browser) => {await waitForRenderedMedia(page, { canvas: true });const viewTool = page.getByRole('toolbar', { exact: true, name: 'Tools' })- .getByRole('button', { exact: true, name: 'View' });+ .getByRole('button', { exact: true, name: 'Pan' });await viewTool.click();const guide = page.locator('footer').getByRole('button', { exact: true, name: 'Shortcuts' });await guide.waitFor();@@ -438,7 +438,7 @@ const runStatusBarNamesJourney = async (browser) => {try {await waitForWorkbench(page);const footer = page.locator('footer');- await footer.getByRole('button', { exact: true, name: 'Bottom widget visibility' }).click();+ await footer.getByRole('button', { exact: true, name: 'Status bar widgets' }).click();const menu = page.getByRole('menu');await menu.waitFor();const items = menu.getByRole('menuitemcheckbox');@@ -690,7 +690,7 @@ const runTopbarMenuJourney = async (browser) => {await centerViewTrigger(page, 'Workflow').waitFor();await selectCenterView(page, 'Workflow', 'Preview');- const leftWidgetRail = page.getByRole('navigation', { exact: true, name: 'Create widget visibility' });+ const leftWidgetRail = page.getByRole('navigation', { exact: true, name: 'Left rail' });const upscaleWidget = leftWidgetRail.getByRole('button', { exact: true, name: 'Upscale' });await upscaleWidget.click({ button: 'right' });await page.getByRole('menuitem', { exact: true, name: 'Remove Upscale' }).click();@@ -786,16 +786,22 @@ const runTopbarMenuJourney = async (browser) => {await invokeCard.waitFor({ state: 'hidden' });await expectFocused(invokeButton, 'Closing the Invoke card should return focus to Invoke.');- await page.getByRole('button', { exact: true, name: 'Open menu' }).click();+ const appMenuButton = page.getByRole('button', { exact: true, name: 'Open menu' });+ await appMenuButton.click();const appMenu = page.getByRole('menu', { exact: true, name: 'Open menu' });- const commandPaletteItem = page.getByRole('menuitem', { name: /^Command palette/ });- const settingsItem = appMenu.getByRole('menuitem', { name: /^Settings(?: \(.+\))?$/ });+ // App-level items lead the menu as full rows; their keycaps stay out of the name, and aria-keyshortcuts says them.+ const launchpadItem = appMenu.getByRole('menuitem', { exact: true, name: 'Launchpad' });+ const settingsItem = appMenu.getByRole('menuitem', { exact: true, name: 'Settings' });+ const commandPaletteItem = appMenu.getByRole('menuitem', { exact: true, name: 'Command palette' });const whatsNewItem = page.getByRole('menuitem', { exact: true, name: "What's New in Invoke" });const documentationItem = page.getByRole('menuitem', { exact: true, name: 'Documentation' });const discordItem = page.getByRole('menuitem', { exact: true, name: 'Discord' });const donationItem = appMenu.getByRole('menuitem', { exact: true, name: 'Donate to Invoke' });+ await launchpadItem.waitFor();await commandPaletteItem.waitFor();await settingsItem.waitFor();+ assert.equal(await settingsItem.getAttribute('aria-keyshortcuts'), 'Control+,');+ assert.equal(await commandPaletteItem.getAttribute('aria-keyshortcuts'), 'Control+K');await whatsNewItem.waitFor();await documentationItem.waitFor();await discordItem.waitFor();@@ -805,42 +811,58 @@ const runTopbarMenuJourney = async (browser) => {const footerMetrics = await appMenu.evaluate((menu) => {const menuBounds = menu.getBoundingClientRect();- const footerValues = ['command-palette', 'settings', 'whats-new', 'documentation', 'discord'];- const footerItems = [...menu.querySelectorAll('[role="menuitem"]')].filter((item) =>- footerValues.includes(item.getAttribute('data-value'))+ const items = [...menu.querySelectorAll('[role="menuitem"]')];+ const footerValues = ['whats-new', 'documentation', 'discord'];+ const footerItems = items.filter((item) => footerValues.includes(item.getAttribute('data-value')));+ const leadingItems = items.filter((item) =>+ ['launchpad', 'settings', 'command-palette'].includes(item.getAttribute('data-value')));+ const fits = (bounds) => bounds.left >= menuBounds.left && bounds.right <= menuBounds.right;return {+ footerCount: footerItems.length,itemsFit: footerItems.every((item) => {const bounds = item.getBoundingClientRect();- return bounds.left >= menuBounds.left && bounds.right <= menuBounds.right && bounds.width <= 32.5;+ return fits(bounds) && bounds.width <= 32.5;+ }),+ // Full rows: as wide as the menu's other items, label and keycaps inside.+ leadingRowsFit: leadingItems.every((item) => {+ const bounds = item.getBoundingClientRect();+ const label = item.querySelector('[data-part="item-text"]')?.getBoundingClientRect();++ return fits(bounds) && bounds.width > 32.5 && label !== undefined && label.right <= bounds.right;}),menuClientWidth: menu.clientWidth,menuScrollWidth: menu.scrollWidth,};});+ assert.equal(footerMetrics.footerCount, 3);assert.equal(footerMetrics.itemsFit, true);+ assert.equal(footerMetrics.leadingRowsFit, true);assert.equal(footerMetrics.menuScrollWidth, footerMetrics.menuClientWidth);+ // Opening by pointer highlights nothing, so no footer tooltip shows on its own.await expectFocused(appMenu, 'Opening the app menu should focus its composite.');- assert.notEqual(await appMenu.getAttribute('aria-activedescendant'), await commandPaletteItem.getAttribute('id'));+ assert.equal(await appMenu.locator('[role="menuitem"][data-highlighted]').count(), 0);await new Promise((resolveWait) => {setTimeout(resolveWait, 750);});- assert.equal(await page.getByRole('tooltip', { name: /^Command palette/ }).count(), 0);+ assert.equal(+ await page.getByRole('tooltip', { name: /^(?:What's New in Invoke|Documentation|Discord)$/ }).count(),+ 0+ );- // Donate is its own group right after Manage (ending with Queue and Widgets), above the footer icon row; this mock journey- // is single-user, so no account section sits between them.+ // Launchpad, Settings and the command palette lead; Donate is its own group right after Manage (ending with Queue+ // and Widgets), directly above the footer icon row. The app menu holds no account section.const menuItemValues = await appMenu.evaluate((menu) =>[...menu.querySelectorAll('[role="menuitem"]')].map((item) => item.getAttribute('data-value')));+ assert.deepEqual(menuItemValues.slice(0, 3), ['launchpad', 'settings', 'command-palette']);assert.deepEqual(menuItemValues.slice(menuItemValues.indexOf('queue')), ['queue','widgets','donate',- 'command-palette',- 'settings','whats-new','documentation','discord',@@ -850,19 +872,43 @@ const runTopbarMenuJourney = async (browser) => {await appMenu.press('End');assert.equal(await appMenu.getAttribute('aria-activedescendant'), await discordItem.getAttribute('id'));- for (const item of [- documentationItem,- whatsNewItem,- settingsItem,- commandPaletteItem,- donationItem,- widgetsItem,- queueItem,- ]) {+ for (const item of [documentationItem, whatsNewItem, donationItem, widgetsItem, queueItem]) {await appMenu.press('ArrowUp');assert.equal(await appMenu.getAttribute('aria-activedescendant'), await item.getAttribute('id'));}+ await appMenu.press('Home');+ assert.equal(await appMenu.getAttribute('aria-activedescendant'), await launchpadItem.getAttribute('id'));+ await appMenu.press('ArrowDown');+ assert.equal(await appMenu.getAttribute('aria-activedescendant'), await settingsItem.getAttribute('id'));+ await appMenu.press('ArrowDown');+ assert.equal(await appMenu.getAttribute('aria-activedescendant'), await commandPaletteItem.getAttribute('id'));++ // Each opens from the keyboard and closes back to the menu's button: the item that opened it is gone by then.+ await appMenu.press('Enter');+ const paletteDialog = page.getByRole('dialog', { exact: true, name: 'Command palette' });+ await paletteDialog.waitFor();+ await expectFocused(+ page.getByRole('combobox', { exact: true, name: 'Search commands and settings' }),+ 'Opening the command palette from the app menu should focus its search field.'+ );+ await page.keyboard.press('Escape');+ await paletteDialog.waitFor({ state: 'hidden' });+ await expectFocused(appMenuButton, 'Closing the command palette should return focus to the app menu button.');++ await appMenuButton.press('Enter');+ await launchpadItem.waitFor();+ // Keys pressed before the reopened menu holds focus are lost.+ await expectFocused(appMenu, 'Reopening the app menu from the keyboard should focus its composite.');+ await appMenu.press('Home');+ await appMenu.press('ArrowDown');+ assert.equal(await appMenu.getAttribute('aria-activedescendant'), await settingsItem.getAttribute('id'));+ await appMenu.press('Enter');+ const settingsDialog = page.getByRole('dialog', { name: /^Settings:/ });+ await settingsDialog.waitFor();+ await waitForSettledDocument(page);await page.keyboard.press('Escape');+ await settingsDialog.waitFor({ state: 'hidden' });+ await expectFocused(appMenuButton, 'Closing Settings should return focus to the app menu button.');const projectSwitcher = page.getByRole('button', { name: /^Switch project\./ });await projectSwitcher.click();@@ -959,10 +1005,13 @@ const runVideoPreviewJourney = async (browser) => {const rightPanel = page.getByRole('complementary', { exact: true, name: 'right widget panel' });await rightPanel.locator('button:not([aria-expanded])').filter({ hasText: 'Uncategorized' }).click();const gallery = rightPanel.getByRole('list', { exact: true, name: 'Gallery items' });- const selectVideo = rightPanel.getByRole('button', {- exact: true,- name: `Select video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}, duration 0:01, for preview`,- });+ const selectVideoName = `Select video ${MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME}, duration 0:01, for preview`;+ const selectVideo = rightPanel.getByRole('button', { exact: true, name: selectVideoName });+ // Tile badges sit on the cell's corners, outside the bordered image box that holds the button. The panel-wide+ // lookup covers both the starred strip and the main list.+ const videoTile = rightPanel+ .getByRole('listitem')+ .filter({ has: page.getByRole('button', { exact: true, name: selectVideoName }) });try {await gallery.waitFor();@@ -975,7 +1024,7 @@ const runVideoPreviewJourney = async (browser) => {await selectVideo.waitFor();await selectVideo.focus();await expectFocused(selectVideo, 'The video gallery item must be keyboard focusable.');- assert.equal(await selectVideo.locator('xpath=..').locator('svg.lucide-play').getAttribute('aria-hidden'), 'true');+ assert.equal(await videoTile.locator('svg.lucide-play').getAttribute('aria-hidden'), 'true');await selectVideo.press('Enter');const player = centerRegion(page).getByRole('group', {@@ -1211,7 +1260,7 @@ const runLayersPanesJourney = async (browser) => {.getByRole('tabpanel', { exact: true, name: 'Properties' }).getByRole('slider', { exact: true, name: 'Brush size' }).waitFor();- await tools.getByRole('button', { exact: true, name: 'View' }).click();+ await tools.getByRole('button', { exact: true, name: 'Pan' }).click();await page.getByRole('tabpanel', { exact: true, name: 'Properties' }).waitFor();// Pointer: activate every non-default pane across the three blocks.@@ -1261,12 +1310,12 @@ const runFloatingWindowJourney = async (browser) => {await waitForWorkbench(page);await selectLayoutPreset(page, 'Video', 'Preview');- const rail = page.getByRole('navigation', { exact: true, name: 'Inspect widget visibility' });+ const rail = page.getByRole('navigation', { exact: true, name: 'Right rail' });const center = centerRegion(page);const floatingWindow = page.locator('[data-hotkey-widget-region="floating"]');const marker = rail.getByRole('button', { exact: true, name: 'Preview, floating window' });const floatPreviewFromRail = async () => {- await rail.getByRole('button', { exact: true, name: 'Inspect widgets' }).click();+ await rail.getByRole('button', { exact: true, name: 'Right panel widgets' }).click();await page.getByRole('menuitemcheckbox', { exact: true, name: 'Preview' }).click();await page.keyboard.press('Escape');await page.getByRole('button', { exact: true, name: 'Float Window' }).click();@@ -1392,26 +1441,26 @@ const runFloatingWindowJourney = async (browser) => {await waitForFocusedRegion(focusedRegionAfter);};- await floatImageMapFrom(rail, 'Inspect widgets');+ await floatImageMapFrom(rail, 'Right panel widgets');await removeImageMapFrom(rail, 'right');- await floatImageMapFrom(rail, 'Inspect widgets');+ await floatImageMapFrom(rail, 'Right panel widgets');await rail.getByRole('button', { pressed: true }).click();await page.getByRole('complementary', { exact: true, name: 'right widget panel' }).waitFor({ state: 'detached' });await removeImageMapFrom(rail, 'center');- const leftRail = page.getByRole('navigation', { exact: true, name: 'Create widget visibility' });+ const leftRail = page.getByRole('navigation', { exact: true, name: 'Left rail' });for (const name of ['Video', 'Upscale']) {await leftRail.getByRole('button', { exact: true, name }).click({ button: 'right' });await page.getByRole('menuitem', { exact: true, name: `Remove ${name}` }).click();}- await floatImageMapFrom(leftRail, 'Create widgets');+ await floatImageMapFrom(leftRail, 'Left panel widgets');await page.getByRole('complementary', { exact: true, name: 'left widget panel' }).waitFor({ state: 'detached' });await removeImageMapFrom(leftRail, 'center');// The enable menu stays open across a toggle and keeps focus; removing a window from it moves none.- await floatImageMapFrom(leftRail, 'Create widgets');- await leftRail.getByRole('button', { exact: true, name: 'Create widgets' }).click();+ await floatImageMapFrom(leftRail, 'Left panel widgets');+ await leftRail.getByRole('button', { exact: true, name: 'Left panel widgets' }).click();await page.getByRole('menuitemcheckbox', { exact: true, name: 'Image Map' }).click();await floatingWindow.waitFor({ state: 'detached' });// A focus move would have landed within a frame of the removal.diff --git a/invokeai/frontend/webv2/scripts/run-browser-smoke.mjs b/invokeai/frontend/webv2/scripts/run-browser-smoke.mjsindex 2fde7935bc..036f1e95b4 100644--- a/invokeai/frontend/webv2/scripts/run-browser-smoke.mjs+++ b/invokeai/frontend/webv2/scripts/run-browser-smoke.mjs@@ -182,8 +182,36 @@ for (const [engine, type] of Object.entries({ chromium, firefox, webkit })) {assert.ok(!(await server.text()).includes(marker), 'Server must not explain A recovery');report.journalAttribution = recovery;await page.unroute('**/api/v1/projects/**', holdSaves);+ // Wait for the recovered document's Gallery bodies, not just Preview's ready prompt, before Edit+ // unmounts Gallery. Its lazy grid can otherwise begin and cancel both reads during the layout change.+ const initialGalleryReads = Promise.all(+ [+ page.waitForResponse((response) => {+ const url = new URL(response.url());+ return (+ response.request().method() === 'GET' &&+ url.origin === origin &&+ url.pathname === '/api/v1/gallery/items/' &&+ url.searchParams.get('board_id') === 'fixture-project-board-02' &&+ url.searchParams.get('limit') === '60'+ );+ }),+ page.waitForResponse(+ (response) =>+ response.request().method() === 'GET' && response.url() === `${origin}/api/v1/image_map/status`+ ),+ ].map(async (pending) => {+ const response = await pending;+ assert.equal(await response.finished(), null, `Gallery startup body failed: ${response.url()}`);+ })+ );+ void initialGalleryReads.catch(() => {});await open();await expect(prompt, 'Journal-only held field must survive actual unload').toHaveValue(marker);+ await initialGalleryReads;+ await waitForRenderedMedia(page, {+ allImagesSelector: '[data-hotkey-widget-type-id="gallery"] [data-gallery-tile-media] img',+ });report.heldFieldRecovery = 'passed';// Canvas and layer thumbnails must contain fixture colour, in all three engines.await pagediff --git a/invokeai/frontend/webv2/src/app/ConceptDraftCommits.browser.test.tsx b/invokeai/frontend/webv2/src/app/ConceptDraftCommits.browser.test.tsxindex b50b811f29..39464e01d6 100644--- a/invokeai/frontend/webv2/src/app/ConceptDraftCommits.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/ConceptDraftCommits.browser.test.tsx@@ -51,7 +51,7 @@ const modelSnapshot = { models, status: 'loaded' };const { notify, picker } = vi.hoisted(() => ({ notify: vi.fn(), picker: { pick: null as unknown } }));const noop = () => undefined;const generationAdapter = {- sectionPreferences: { sectionsOpen: {}, setSectionOpen: noop },+ sectionPreferences: { sectionsOpen: {}, setSectionsOpen: noop },} as unknown as GenerationUiAdapter;let store: WorkbenchInternalStore;diff --git a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsxindex da183563a6..c3e5b343e3 100644--- a/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/GenerationUiAdapter.tsx@@ -19,6 +19,7 @@ import {getModelBaseColorPalette,getModelBaseLabel,getModelImageUrl,+ getModelsSnapshot,openModelManager,useModelsSelector,useOpenModelInManager,@@ -311,6 +312,7 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodegetImageUrl: getModelImageUrl,openInModelManager: openInModelManager ?? undefined,openManager: (options) => openModelManager({ modelType: options?.modelType, projectId: project.activeProjectId }),+ readCatalog: () => getModelsSnapshot().models,status: modelsStatus,}),[modelsCatalog, modelsError, modelsStatus, openInModelManager, project.activeProjectId]@@ -451,9 +453,9 @@ export const GenerationUiAdapterProvider = ({ children }: { children: ReactNodeconst sectionPreferencesGroup = useMemo<GenerationUiAdapter['sectionPreferences']>(() => ({sectionsOpen: generateSectionsOpen,- setSectionOpen: (sectionId, open) => {+ setSectionsOpen: (changes) => {void patchWorkbenchPreferences({- generateSectionsOpen: { ...getWorkbenchPreferences().generateSectionsOpen, [sectionId]: open },+ generateSectionsOpen: { ...getWorkbenchPreferences().generateSectionsOpen, ...changes },});},}),diff --git a/invokeai/frontend/webv2/src/app/PromptHistoryRecallUndo.browser.test.tsx b/invokeai/frontend/webv2/src/app/PromptHistoryRecallUndo.browser.test.tsxindex 6420a8c822..df6beb17ab 100644--- a/invokeai/frontend/webv2/src/app/PromptHistoryRecallUndo.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/PromptHistoryRecallUndo.browser.test.tsx@@ -44,7 +44,7 @@ const RECALLED: PromptHistoryItem = {} as PromptHistoryItem;const noop = () => undefined;const generationAdapter = {- sectionPreferences: { sectionsOpen: {}, setSectionOpen: noop },+ sectionPreferences: { sectionsOpen: {}, setSectionsOpen: noop },} as unknown as GenerationUiAdapter;let store: WorkbenchInternalStore;diff --git a/invokeai/frontend/webv2/src/app/QueueItemRecall.browser.test.tsx b/invokeai/frontend/webv2/src/app/QueueItemRecall.browser.test.tsxnew file mode 100644index 0000000000..77d8664c46--- /dev/null+++ b/invokeai/frontend/webv2/src/app/QueueItemRecall.browser.test.tsx@@ -0,0 +1,413 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';+import type * as ModelsModule from '@features/models';+import type { QueueItemReadModel } from '@features/queue/contracts';+import type * as QueuePublicApi from '@features/queue/publicApi';+import type { ExtensionRegistry } from '@workbench/extensions/extensionRegistry';+import type { Project } from '@workbench/projectContracts';+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';+import type { WorkbenchSnapshot } from '@workbench/workbenchStore';++import { ChakraProvider } from '@chakra-ui/react';+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';+import { getDefaultGenerateSettings } from '@features/generation/settings';+import { buildQueueItemOrigin } from '@features/queue/contracts';+import { loadQueueWidgetImplementation } from '@features/queue/widget';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { shallowEqual, useExternalStoreSelector } from '@platform/state/selectors';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { createExtensionRegistry } from '@workbench/extensions/extensionRegistry';+import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';+import { WorkbenchFocusProvider } from '@workbench/WorkbenchRuntime';+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, beforeEach, describe, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';++import { QueueUiAdapterProvider } from './QueueUiAdapter';++/**+ * Queue entry recall end to end: the Queue widget's real rows, menus and details, the App adapter that wires the+ * Workbench's recall into them, a real Workbench store and the real hotkey runtime. Only context plumbing, notices,+ * panel opening and the model catalog are replaced.+ */++const mocks = vi.hoisted(() => ({+ extensions: null as unknown as ExtensionRegistry,+ notify: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ openWidget: vi.fn(),+ main: { base: 'sdxl', key: 'main', name: 'SDXL', type: 'main' } as MainModelConfig & ModelsModule.ModelConfig,+ store: null as unknown as ReturnType<typeof createWorkbenchStore>,+}));+const { main } = mocks;++vi.mock('@features/models', async (importOriginal) => {+ const original = await importOriginal<typeof ModelsModule>();+ const snapshot = { ...original.getModelsSnapshot(), models: [mocks.main], status: 'loaded' as const };++ return {+ ...original,+ ensureModelsLoaded: () => Promise.resolve(),+ getModelsSnapshot: () => snapshot,+ useModelsSelector: <Selected,>(selector: (state: typeof snapshot) => Selected) => selector(snapshot),+ };+});+vi.mock('@features/queue/publicApi', async (importOriginal) => ({+ ...(await importOriginal<typeof QueuePublicApi>()),+ getQueueItemDetailOptions: (itemId: number) => ({ queryFn: () => null, queryKey: ['queue', 'item-detail', itemId] }),+ getQueueReadModelOptions: () => ({ queryFn: () => null, queryKey: ['queue'], staleTime: Number.POSITIVE_INFINITY }),+}));+// The first-party commands need the whole application; the Gallery's recall stands in for them below.+vi.mock('@workbench/hotkeys/firstPartyCommands', () => ({ useRegisterFirstPartyCommands: () => {} }));+vi.mock('@workbench/useNotify', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useNotify: () => mocks.notify,+}));+vi.mock('@workbench/useOpenWorkbenchWidget', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useOpenWorkbenchWidget: () => mocks.openWidget,+}));+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => {+ const useStoreSelector = <Selected,>(+ selector: (snapshot: WorkbenchSnapshot) => Selected,+ isEqual: (left: Selected, right: Selected) => boolean = shallowEqual+ ) => useExternalStoreSelector(mocks.store.subscribe, mocks.store.getSnapshot, selector, isEqual);++ return {+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useActiveProjectSelector: <Selected,>(selector: (project: Project) => Selected, isEqual?: never) =>+ useStoreSelector((snapshot) => selector(snapshot.activeProject), isEqual),+ useOptionalWorkbenchExtensions: () => mocks.extensions,+ useWidgetValuesSelector: <Selected,>(+ widgetId: string,+ selector: (values: Record<string, unknown>) => Selected,+ isEqual?: never+ ) =>+ useStoreSelector(+ (snapshot) =>+ selector(getResolvedProjectWidgetValues(snapshot.activeProject, widgetId, snapshot.scopedDefaults)),+ isEqual+ ),+ useWorkbenchCommands: () => mocks.store.commands,+ useWorkbenchExtensions: () => mocks.extensions,+ useWorkbenchInternalStore: () => mocks.store,+ useWorkbenchLiveCanvasEngines: () => ({ commitFrame: () => false }),+ useWorkbenchQueries: () => mocks.store.queries,+ useWorkbenchSelector: useStoreSelector,+ useWorkbenchSubscription: () => mocks.store.subscribe,+ };+});++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ fallbackNS: 'translation',+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++seedArchitectureCapabilities();++const submitted = (positivePrompt: string): GenerateWidgetValues => ({+ ...getDefaultGenerateSettings(main),+ model: main,+ positivePrompt,+ steps: 33,+});++/** A run this tab submitted and the backend accepted, with the snapshot its recall restores. */+const localRun = (id: string, positivePrompt: string): Project['queue']['items'][number] =>+ ({+ backendItemIds: [1],+ cancellable: false,+ id,+ snapshot: {+ presentation: { batchCount: 1, height: 1024, positivePrompt, width: 1024 },+ recall: { generateValues: submitted(positivePrompt) },+ sourceId: 'generate',+ submittedAt: '2026-01-01T00:00:00.000Z',+ },+ status: 'completed',+ }) as unknown as Project['queue']['items'][number];++/** A workflow run this tab submitted: its snapshot records no Generate settings. */+const localWorkflowRun = (id: string): Project['queue']['items'][number] =>+ ({+ backendItemIds: [5],+ cancellable: false,+ id,+ snapshot: { presentation: { batchCount: 1 }, sourceId: 'workflow', submittedAt: '2026-01-01T00:00:00.000Z' },+ status: 'completed',+ }) as unknown as Project['queue']['items'][number];++const backendItem = (overrides: Partial<QueueItemReadModel> & Pick<QueueItemReadModel, 'id'>): QueueItemReadModel => ({+ batchId: `batch-${overrides.id}`,+ createdAt: '2026-01-01T00:00:00Z',+ fieldValues: [{ fieldName: 'value', nodePath: 'positive_prompt', value: `Session prompt ${overrides.id}` }],+ resultImageNames: [],+ sessionId: `session-${overrides.id}`,+ status: 'completed',+ updatedAt: '2026-01-01T00:00:00Z',+ userId: 'user-1',+ ...overrides,+});++let host: HTMLDivElement;+let root: Root;+let projectId: string;+const galleryRecallAll = vi.fn();+const NOT_KEPT =+ "This browser did not keep this item's settings, so only a prompt or seed the server recorded can be recalled.";+let promptBefore: unknown;++const generateValues = () => {+ const snapshot = mocks.store.queries.getSnapshot();+ return getResolvedProjectWidgetValues(snapshot.activeProject, 'generate', snapshot.scopedDefaults);+};++beforeEach(() => {+ vi.clearAllMocks();+ accountLifecycle.activate(`queue-item-recall-${crypto.randomUUID()}`);+ const state = createInitialWorkbenchState();+ const project = state.projects[0]!;+ projectId = project.id;+ project.queue = {+ items: [+ localRun('run-done', 'A recalled castle'),+ localRun('run-failed', 'A failed lighthouse'),+ localRun('run-pending', 'A pending harbour'),+ localWorkflowRun('run-workflow'),+ ],+ };+ mocks.store = createWorkbenchStore(state);+ mocks.store.commands.queue.setConnectionStatus({ status: 'connected' });+ mocks.store.commands.generation.setSettings({ ...getDefaultGenerateSettings(main), model: main }, projectId);+ promptBefore = generateValues().positivePrompt;+ mocks.extensions = createExtensionRegistry();+ mocks.extensions.commands.register({ handler: galleryRecallAll, id: 'viewer.recallAll', title: 'Recall all' });+ host = document.createElement('div');+ host.style.cssText = 'width:360px;height:700px;';+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ accountLifecycle.invalidate();+});++const renderQueue = async () => {+ const pending = backendItem({+ id: 4,+ origin: buildQueueItemOrigin('run-pending', projectId),+ status: 'pending',+ });+ const client = new QueryClient();+ client.setQueryData(['queue'], {+ current: null,+ items: [+ pending,+ backendItem({ completedAt: '2026-01-01T00:01:00Z', id: 1, origin: buildQueueItemOrigin('run-done', projectId) }),+ backendItem({+ errorMessage: 'Out of memory',+ id: 2,+ origin: buildQueueItemOrigin('run-failed', projectId),+ status: 'failed',+ }),+ // Queued from another browser: this one kept no snapshot of it.+ backendItem({ id: 3, origin: buildQueueItemOrigin('elsewhere', 'other-project') }),+ // A workflow's text field, which type-and-order matching of session values would read as a prompt.+ backendItem({+ fieldValues: [{ fieldName: 'value', nodePath: 'caption_node', value: 'A workflow caption' }],+ id: 5,+ origin: buildQueueItemOrigin('run-workflow', projectId),+ }),+ ],+ next: pending,+ scope: {},+ status: {+ processor: { isProcessing: false, isStarted: true },+ queue: {+ canceled: 0,+ completed: 3,+ failed: 1,+ inProgress: 0,+ pending: 1,+ queueId: 'default',+ total: 5,+ waiting: 0,+ },+ },+ });+ const { view: QueueWidgetView } = await loadQueueWidgetImplementation();+ const source = { instanceId: 'queue', projectId, region: 'right' as const, typeId: 'queue' };+ const runtime = {+ commands: {+ register: (command: { handler: () => unknown; id: string; title: string }) =>+ mocks.extensions.commands.register({ ...command, source }),+ },+ };++ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueryClientProvider client={client}>+ <WorkbenchFocusProvider>+ <WorkbenchHotkeyRuntime />+ <QueueUiAdapterProvider>+ <div+ data-hotkey-widget-instance-id="queue"+ data-hotkey-widget-region="right"+ data-hotkey-widget-type-id="queue"+ style={{ height: 600 }}+ >+ <QueueWidgetView region="right" runtime={runtime} />+ </div>+ </QueueUiAdapterProvider>+ <div+ data-hotkey-widget-instance-id="gallery"+ data-hotkey-widget-region="right"+ data-hotkey-widget-type-id="gallery"+ >+ <button type="button">Gallery tile</button>+ </div>+ </WorkbenchFocusProvider>+ </QueryClientProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );+};++const row = (itemId: number) => host.querySelector<HTMLElement>(`[data-queue-recall-item="${itemId}"]`)!;+const rowButton = (itemId: number) => row(itemId).querySelector<HTMLButtonElement>('[data-list-primary]')!;+const openRowMenu = async (itemId: number) => {+ await act(() =>+ rowButton(itemId).dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 40, clientY: 40 })+ )+ );+ await vi.waitFor(() => expect(menuItem('Recall all')).not.toBeNull(), { timeout: 5_000 });+};+/** By its label line: an unavailable item also holds its reason's hidden text. */+const menuItem = (label: string) =>+ [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(+ (candidate) => candidate.querySelector('p')?.textContent === label+ ) ?? null;+const description = (element: HTMLElement) =>+ (element.getAttribute('aria-describedby') ?? '')+ .split(' ')+ .map((id) => document.getElementById(id)?.textContent ?? '')+ .join(' ')+ .trim();+/** Presses A on the target and returns the press, whose `defaultPrevented` says whether a shortcut claimed it. */+const pressA = async (target: HTMLElement): Promise<KeyboardEvent> => {+ const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, code: 'KeyA', key: 'a' });+ await act(async () => {+ target.dispatchEvent(event);+ await Promise.resolve();+ });+ return event;+};++describe('Queue entry recall', () => {+ it("recalls every setting of a finished entry from its row's context menu, and says so", async () => {+ await renderQueue();+ await openRowMenu(1);++ expect(menuItem('Recall all')?.getAttribute('aria-disabled')).not.toBe('true');+ await act(() => page.getByRole('menuitem', { exact: true, name: 'Recall all' }).click());++ await vi.waitFor(() => expect(generateValues()).toMatchObject({ positivePrompt: 'A recalled castle', steps: 33 }));+ expect(mocks.openWidget).toHaveBeenCalledWith('generate', { preferredRegions: ['left'] });+ expect(mocks.notify.success).toHaveBeenCalledWith(+ 'Recalled image metadata',+ 'Loaded these settings into Generate.'+ );+ });++ it('keeps the recall of an entry queued from another browser listed, unavailable and saying why', async () => {+ await renderQueue();+ // Recalling all anyway, with A, explains and writes nothing: the notice ends a recall that does not run.+ rowButton(3).focus();+ await pressA(rowButton(3));+ await vi.waitFor(() => expect(mocks.notify.info).toHaveBeenCalledWith('Nothing recalled', NOT_KEPT));+ expect(mocks.notify.success).not.toHaveBeenCalled();+ expect(generateValues().positivePrompt).toBe(promptBefore);++ await openRowMenu(3);++ // Unavailable while this browser's durable snapshots are searched, then with the reason once none is found.+ await vi.waitFor(() => expect(description(menuItem('Recall all')!)).toBe(NOT_KEPT));+ expect(menuItem('Recall all')!.getAttribute('aria-disabled')).toBe('true');+ // The server recorded the prompt it ran, and the Generate panel's model can take it.+ expect(menuItem('Use prompt')?.getAttribute('aria-disabled')).not.toBe('true');+ });++ it("offers nothing from a workflow run, whose session values are not Generate's", async () => {+ await renderQueue();+ rowButton(5).focus();+ await pressA(rowButton(5));+ await vi.waitFor(() =>+ expect(mocks.notify.info).toHaveBeenCalledWith('Nothing recalled', 'Nothing recallable for this item.')+ );+ expect(generateValues().positivePrompt).toBe(promptBefore);++ await openRowMenu(5);+ await vi.waitFor(() => expect(description(menuItem('Use prompt')!)).toBe('Nothing recallable for this item.'));+ expect(menuItem('Use prompt')!.getAttribute('aria-disabled')).toBe('true');+ expect(description(menuItem('Recall all')!)).toBe('Nothing recallable for this item.');+ });++ it('recalls a failed entry from its expanded details', async () => {+ await renderQueue();+ await act(() => rowButton(2).click());++ const detailButton = () =>+ [...row(2).querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === 'Recall all');+ await vi.waitFor(() => expect(detailButton()?.getAttribute('aria-disabled')).not.toBe('true'), { timeout: 5_000 });+ await vi.waitFor(() => expect(detailButton()?.disabled).toBe(false));+ await act(() => detailButton()!.click());++ await vi.waitFor(() => expect(generateValues()).toMatchObject({ positivePrompt: 'A failed lighthouse' }));+ expect(mocks.notify.success).toHaveBeenCalledWith(+ 'Recalled image metadata',+ 'Loaded these settings into Generate.'+ );+ });++ it('recalls all from the focused row on A, a pending one included, leaving A to the Gallery elsewhere', async () => {+ await renderQueue();+ const pendingRow = rowButton(4);++ // A queue control that is no row keeps the key.+ const filterTab = host.querySelector<HTMLElement>('[role="tab"]')!;+ filterTab.focus();+ expect((await pressA(filterTab)).defaultPrevented).toBe(false);++ pendingRow.focus();+ expect((await pressA(pendingRow)).defaultPrevented).toBe(true);++ await vi.waitFor(() => expect(generateValues()).toMatchObject({ positivePrompt: 'A pending harbour' }));+ expect(mocks.notify.success).toHaveBeenCalledOnce();+ expect(galleryRecallAll).not.toHaveBeenCalled();++ const galleryTile = [...document.querySelectorAll<HTMLButtonElement>('button')].find(+ (button) => button.textContent === 'Gallery tile'+ )!;+ galleryTile.focus();+ await pressA(galleryTile);++ expect(galleryRecallAll).toHaveBeenCalledOnce();+ expect(mocks.notify.success).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/app/QueueUiAdapter.browser.test.tsx b/invokeai/frontend/webv2/src/app/QueueUiAdapter.browser.test.tsxindex 374d5304ef..4f323512ad 100644--- a/invokeai/frontend/webv2/src/app/QueueUiAdapter.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/QueueUiAdapter.browser.test.tsx@@ -1,7 +1,6 @@import type * as QueuePublicApi from '@features/queue/publicApi';import type { Project } from '@workbench/projectContracts';import type { WorkbenchSnapshot } from '@workbench/workbenchStore';-import type { ComponentType } from 'react';import { ChakraProvider } from '@chakra-ui/react';import { loadQueueWidgetImplementation } from '@features/queue/widget';@@ -37,6 +36,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({isEqual),useWorkbenchCommands: () => store.commands,+ useWorkbenchQueries: () => store.queries,useWorkbenchSelector: (selector: (snapshot: WorkbenchSnapshot) => unknown, isEqual = shallowEqual) =>useExternalStoreSelector(store.subscribe, store.getSnapshot, selector, isEqual),}));@@ -51,6 +51,7 @@ await i18n.use(initReactI18next).init({(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const RUN_ID = 'local-run';+const NO_COMMANDS_RUNTIME = { commands: { register: () => () => undefined } };let projectId: string;let host: HTMLDivElement;let root: Root;@@ -110,9 +111,7 @@ const recordServerError = (failureCount: number) =>);it("lists the Workbench's unaccepted run, follows each recorded retry, and drops it once the backend accepts it", async () => {- const { view: QueueWidgetView } = (await loadQueueWidgetImplementation()) as {- view: ComponentType<{ region: 'right' }>;- };+ const { view: QueueWidgetView } = await loadQueueWidgetImplementation();const client = new QueryClient();client.setQueryData(['queue'], {current: null,@@ -140,7 +139,7 @@ it("lists the Workbench's unaccepted run, follows each recorded retry, and drops<ChakraProvider value={system}><QueryClientProvider client={client}><QueueUiAdapterProvider>- <QueueWidgetView region="right" />+ <QueueWidgetView region="right" runtime={NO_COMMANDS_RUNTIME} /></QueueUiAdapterProvider></QueryClientProvider></ChakraProvider>diff --git a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsxindex a78b0d0c9d..b0210a17b1 100644--- a/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/QueueUiAdapter.tsx@@ -5,16 +5,29 @@ import { useAuthSession, useCapabilities } from '@features/identity';import { getModelLoads, subscribeModelLoads } from '@features/models';import { getQueueItemSnapshotLabel } from '@features/queue/contracts';import { getQueueItemAccess, QueueUiProvider, type QueueLocalRun, type QueueUiAdapter } from '@features/queue/react';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { areArraysEqual, shallowEqual } from '@platform/state/selectors';+import { createMenuPartLoader } from '@platform/ui/Menu';+import { useQueryClient } from '@tanstack/react-query';import { isUnsubmittedQueueItem } from '@workbench/canvasStagingView';import { useWorkbenchPreferences } from '@workbench/settings/store';import { useNotify } from '@workbench/useNotify';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import {+ useActiveProjectSelector,+ useWorkbenchCommands,+ useWorkbenchQueries,+ useWorkbenchSelector,+} from '@workbench/WorkbenchContext';import { lazy, useMemo, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';const importQueueItemActions = () => import('@workbench/queue-integration/QueueItemActions');const QueueItemActions = lazy(() => importQueueItemActions().then((module) => ({ default: module.QueueItemActions })));+// The row menu's recall entries share the details' chunk: one request warms both.+const queueItemRecallMenuGroup = createMenuPartLoader(() =>+ importQueueItemActions().then((module) => module.QueueItemRecallMenuGroup)+);const toQueueLocalRun = (projectId: string, item: QueueItem): QueueLocalRun => {const retry = item.submissionRetry;@@ -52,8 +65,12 @@ const loadingModel = {};export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) => {+ const { t } = useTranslation();const notify = useNotify();- const { queue } = useWorkbenchCommands();+ const commands = useWorkbenchCommands();+ const { queue } = commands;+ const queries = useWorkbenchQueries();+ const queryClient = useQueryClient();const activeProjectId = useActiveProjectSelector((project) => project.id);const activeProjectName = useActiveProjectSelector((project) => project.name);const { canManageAppConfig, canManageModels } = useCapabilities();@@ -86,12 +103,36 @@ export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) =>cancelLocalRuns: (projectId) => queue.cancelUnsubmitted(projectId ?? undefined),isConnected,isProjectOpen: (projectId) => openProjectIds.includes(projectId),+ itemRecallMenuGroup: queueItemRecallMenuGroup,loadingModel,localRuns,notify,openQueue: () => openWorkbenchWidget('queue'),- preloadItemActions: () => void importQueueItemActions(),+ // A failed warm-up is no error: the details' own load reports it when they open.+ preloadItemActions: () => void importQueueItemActions().catch(() => undefined),queueJobsScope,+ recallAllFromItem: (item) => {+ // Taken at the press: the recall's module may still be loading when the account or project changes.+ const owner = captureAccountScope();+ const projectId = queries.getSnapshot().activeProject.id;++ import('@workbench/queue-integration/recallQueueItem')+ .then(({ recallQueueItem }) =>+ recallQueueItem({+ context: { commands, notify, openWidget: openWorkbenchWidget, queries, t },+ item,+ kind: 'all',+ owner,+ projectId,+ queryClient,+ })+ )+ .catch((error: unknown) => {+ if (isAccountScopeCurrent(owner)) {+ notify.error(t('widgets.queue.recallAll'), error instanceof Error ? error.message : undefined);+ }+ });+ },viewer: !viewer.multiuserEnabled ? 'single' : viewer.isAdmin ? 'admin' : 'member',};}, [@@ -99,14 +140,18 @@ export const QueueUiAdapterProvider = ({ children }: { children: ReactNode }) =>activeProjectName,canManageAppConfig,canManageModels,+ commands,isConnected,localRuns,notify,openProjectIds,openWorkbenchWidget,+ queries,+ queryClient,queue,queueJobsScope,session,+ t,]);return <QueueUiProvider adapter={adapter}>{children}</QueueUiProvider>;diff --git a/invokeai/frontend/webv2/src/app/RouterErrorScreen.browser.test.tsx b/invokeai/frontend/webv2/src/app/RouterErrorScreen.browser.test.tsxindex 87748ca3d2..ee661e7bfa 100644--- a/invokeai/frontend/webv2/src/app/RouterErrorScreen.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/RouterErrorScreen.browser.test.tsx@@ -1,3 +1,5 @@+import type * as SessionModule from '@features/identity/session';+import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { createInstance } from 'i18next';@@ -7,6 +9,43 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';import { page, userEvent } from 'vitest/browser';+/** Single-user unless a test signs someone in; sign-out is the session's own, observed. */+const auth = vi.hoisted(() => ({ logout: vi.fn(() => Promise.resolve()), signedIn: false }));+vi.mock('@features/identity/session', async (importOriginal) => {+ const original = await importOriginal<typeof SessionModule>();+ const singleUser: SessionModule.AuthSession = {+ accountEpoch: 1,+ expiredUserId: null,+ multiuserEnabled: false,+ phase: 'ready',+ sessionExpired: false,+ setupRequired: false,+ strictPasswordChecking: false,+ switchingAccount: false,+ user: null,+ };+ const signedIn: SessionModule.AuthSession = {+ ...singleUser,+ multiuserEnabled: true,+ user: {+ created_at: '2026-01-01T00:00:00Z',+ display_name: 'Ada',+ email: '[email protected]',+ is_active: true,+ is_admin: false,+ last_login_at: null,+ updated_at: '2026-01-01T00:00:00Z',+ user_id: 'ada',+ },+ };++ return {+ ...original,+ logoutSession: auth.logout,+ useAuthSession: () => (auth.signedIn ? signedIn : singleUser),+ };+});+import { RouterErrorScreen } from './RouterErrorScreen';const i18n = createInstance();@@ -50,6 +89,8 @@ const render = async (onGoHome = vi.fn()) => {};afterEach(() => {+ auth.signedIn = false;+ auth.logout.mockClear();act(() => root?.unmount());host?.remove();root = undefined;@@ -78,6 +119,23 @@ describe('RouterErrorScreen', () => {await expect.element(page.getByRole('button', { name: 'Reload' })).toBeVisible();});+ it('offers Sign out to a signed-in account, which signs out and leaves the failed page', async () => {+ auth.signedIn = true;+ const onGoHome = await render();++ await userEvent.click(page.getByRole('button', { name: 'Sign out' }));++ expect(auth.logout).toHaveBeenCalledOnce();+ expect(onGoHome).toHaveBeenCalledOnce();+ });++ it('offers no Sign out in single-user mode', async () => {+ await render();++ await expect.element(page.getByRole('button', { name: 'Go to Home' })).toBeVisible();+ expect(page.getByRole('button', { name: 'Sign out' }).query()).toBeNull();+ });+it('copies the error and where it happened', async () => {const writeText = vi.fn<(text: string) => Promise<void>>().mockResolvedValue(undefined);stubClipboard(writeText);diff --git a/invokeai/frontend/webv2/src/app/RouterErrorScreen.tsx b/invokeai/frontend/webv2/src/app/RouterErrorScreen.tsxindex 8ce23f1bac..7aa19fbd91 100644--- a/invokeai/frontend/webv2/src/app/RouterErrorScreen.tsx+++ b/invokeai/frontend/webv2/src/app/RouterErrorScreen.tsx@@ -1,4 +1,5 @@import { Box, Flex, Heading, HStack, Stack, Text } from '@chakra-ui/react';+import { logoutSession, useHasAccountMenu } from '@features/identity';import { canCopyText, copyText } from '@platform/browser/clipboard';import { Button } from '@platform/ui/Button';import { InvokeMark } from '@platform/ui/InvokeMark';@@ -20,8 +21,10 @@ const formatErrorDetails = (error: unknown, location: string): string => {};/**- * The screen a route that failed to render or load leaves behind: ways back (reload, Home) and the details for a- * report. It sits in the router's eager chunk, so it reads only semantic tokens and small platform controls.+ * The screen a route that failed to render or load leaves behind: ways back (reload, Home, and signing out of a+ * multi-user session, whose only other control lives in the Launchpad that may be what failed) and the details for a+ * report. It sits in the router's eager chunk, so it reads only semantic tokens and small platform controls. The+ * session is a module store, so it reads the same with the route tree down.*/export const RouterErrorScreen = ({ error, onGoHome }: { error: unknown; onGoHome: () => void }) => {const { t } = useTranslation();@@ -42,6 +45,13 @@ export const RouterErrorScreen = ({ error, onGoHome }: { error: unknown; onGoHomwindow.setTimeout(() => setCopyStatus(null), COPY_STATUS_MS);}, [details]);const toggleDetails = useCallback(() => setIsShowingDetails((isShowing) => !isShowing), []);+ const isSignedIn = useHasAccountMenu();+ // The signed-out layout redirects to sign-in, but a failure above it leaves this screen up; leaving it reaches the+ // authenticated route's guard, which does.+ const signOut = useCallback(() => {+ void logoutSession();+ onGoHome();+ }, [onGoHome]);return (<Flex align="center" bg="bg" color="fg" justify="center" minH="100dvh" p="6">@@ -64,6 +74,11 @@ export const RouterErrorScreen = ({ error, onGoHome }: { error: unknown; onGoHom<Button size="lg" variant="outline" onClick={onGoHome}>{t('errorScreen.goHome')}</Button>+ {isSignedIn ? (+ <Button size="lg" variant="outline" onClick={signOut}>+ {t('auth.signOut')}+ </Button>+ ) : null}{canCopyText() ? (<Button size="lg" variant="outline" onClick={copyDetails}>{t('errorScreen.copyDetails')}diff --git a/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx b/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsxindex 157ba2ec2a..6677d85c21 100644--- a/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/UpscaleCapabilityGate.browser.test.tsx@@ -41,7 +41,7 @@ const getArchitectureCapabilities = vi.fn<() => Promise<ArchitectureCapabilitiesconst modelManager = vi.hoisted(() => ({ open: null as ((modelKey: string) => void) | null }));const noop = () => undefined;const generationAdapter = {- sectionPreferences: { sectionsOpen: {}, setSectionOpen: noop },+ sectionPreferences: { sectionsOpen: {}, setSectionsOpen: noop },} as unknown as GenerationUiAdapter;let store: WorkbenchInternalStore;@@ -52,7 +52,9 @@ vi.mock('@features/generation/data/architectureCapabilitiesApi', () => ({getArchitectureCapabilities: () => getArchitectureCapabilities(),}));vi.mock('react-i18next', () => {- const t = (key: string) => key;+ // A count shows after its key, so a section's issue count can be read.+ const t = (key: string, values?: { count?: number }) =>+ values?.count === undefined ? key : `${key}:${values.count}`;return { useTranslation: () => ({ i18n: { resolvedLanguage: 'en' }, t }) };});vi.mock('@features/models', async (importOriginal) => ({@@ -195,6 +197,141 @@ describe('Upscale Refine and Model only modes', () => {});});+describe('Upscale section issues', () => {+ const title = (label: string) =>+ [...host.querySelectorAll<HTMLElement>('.generate-section > [data-part="trigger"]')].find((trigger) =>+ trigger.textContent?.startsWith(label)+ )!;+ const chip = (label: string) => title(label).querySelector<HTMLElement>('[data-section-chip]')!;+ const issueCount = (label: string) => {+ const count = title(label).querySelector('[data-section-issues]');++ return count+ ? { shown: count.querySelector(':scope > span[aria-hidden]')?.textContent, spoken: count.textContent }+ : null;+ };++ it("counts and tints the sections holding Invoke's issues, and leaves the rest plain", async () => {+ getArchitectureCapabilities.mockResolvedValue(architectureCapabilitiesFixture);+ store.commands.widgets.patchValues('upscale', {+ ...createDefaultUpscaleWidgetValues(),+ inputImage: null,+ scale: 99,+ upscaleModel: modelSnapshot.models[1] as never,+ });++ await renderUpscale();++ // No input image and a Scale past its range, both fixed under Source & treatment.+ expect(issueCount('widgets.upscale.sourceAndTreatment')).toEqual({+ shown: '2',+ spoken: '2widgets.generate.issueCount:2',+ });+ expect(chip('widgets.upscale.sourceAndTreatment').hasAttribute('data-issues')).toBe(true);+ expect(issueCount('widgets.upscale.detailGuidance')).toBeNull();+ expect(chip('widgets.upscale.detailGuidance').hasAttribute('data-issues')).toBe(false);+ expect(getComputedStyle(chip('widgets.upscale.sourceAndTreatment')).backgroundColor).not.toBe(+ getComputedStyle(chip('widgets.upscale.detailGuidance')).backgroundColor+ );++ // Fixing one leaves the other counted.+ await settle(() => store.commands.widgets.patchValues('upscale', { scale: 2 }));++ expect(issueCount('widgets.upscale.sourceAndTreatment')?.shown).toBe('1');+ });++ it('counts as soon as the served table arrives, while the model list is still loading', async () => {+ let serveTable: (rows: ArchitectureCapabilitiesRow[]) => void = noop;+ getArchitectureCapabilities.mockReturnValue(+ new Promise((resolve) => {+ serveTable = resolve;+ })+ );+ store.commands.widgets.patchValues('upscale', {+ ...createDefaultUpscaleWidgetValues(),+ inputImage: null,+ upscaleModel: modelSnapshot.models[1] as never,+ });+ modelSnapshot.status = 'loading';++ try {+ await renderUpscale();+ await settle(() => serveTable(architectureCapabilitiesFixture));++ // Invoke lists the missing input image now, so Source & treatment counts it now.+ expect(issueCount('widgets.upscale.sourceAndTreatment')?.shown).toBe('1');+ } finally {+ modelSnapshot.status = 'loaded';+ }+ });+});++describe('Upscale field limits from the served table', () => {+ it("bounds CFG by the model's served cap as soon as the table arrives, while the model list is still loading", async () => {+ let serveTable: (rows: ArchitectureCapabilitiesRow[]) => void = noop;+ getArchitectureCapabilities.mockReturnValue(+ new Promise((resolve) => {+ serveTable = resolve;+ })+ );+ // `flux2_denoise` takes guidance up to 20.+ const flux2Dev = {+ base: 'flux2',+ format: 'diffusers',+ hash: 'f',+ key: 'flux2-dev',+ name: 'FLUX.2 dev',+ type: 'main',+ variant: 'dev',+ };+ store.commands.widgets.patchValues('upscale', {+ ...createDefaultUpscaleWidgetValues(),+ cfgScale: 25,+ model: flux2Dev as never,+ });+ modelSnapshot.status = 'loading';++ try {+ await renderUpscale();+ await settle(() => serveTable(architectureCapabilitiesFixture));++ expect(host.textContent).toContain('widgets.upscale.cfgScale must be between 1 and 20.');+ } finally {+ modelSnapshot.status = 'loaded';+ }+ });+});++describe('Upscale scheduler options from the served table', () => {+ it("lists the model's served schedulers as soon as the table arrives, while the model list is still loading", async () => {+ let serveTable: (rows: ArchitectureCapabilitiesRow[]) => void = noop;+ getArchitectureCapabilities.mockReturnValue(+ new Promise((resolve) => {+ serveTable = resolve;+ })+ );+ // FLUX.1 runs the flow schedulers, whose Heun is the second-order one.+ const flux = { base: 'flux', format: 'diffusers', hash: 'x', key: 'flux-dev', name: 'FLUX.1 dev', type: 'main' };+ store.commands.widgets.patchValues('upscale', {+ ...createDefaultUpscaleWidgetValues(),+ model: flux as never,+ scheduler: 'heun',+ });+ modelSnapshot.status = 'loading';++ try {+ await renderUpscale();+ await settle(() => serveTable(architectureCapabilitiesFixture));++ expect(host.querySelector<HTMLInputElement>('input[aria-label="widgets.upscale.scheduler"]')?.value).toBe(+ 'Heun (2nd order)'+ );+ } finally {+ modelSnapshot.status = 'loaded';+ }+ });+});+describe('Upscale without the served architecture table', () => {it('keeps Model only usable, since it reads no main-model capabilities, and holds back only Refine', async () => {store.commands.widgets.patchValues('upscale', {diff --git a/invokeai/frontend/webv2/src/app/UpscaleSharedPrompt.browser.test.tsx b/invokeai/frontend/webv2/src/app/UpscaleSharedPrompt.browser.test.tsxnew file mode 100644index 0000000000..7b3747a6ca--- /dev/null+++ b/invokeai/frontend/webv2/src/app/UpscaleSharedPrompt.browser.test.tsx@@ -0,0 +1,478 @@+import type { PromptTemplateRecord } from '@features/generation/data/promptTemplates';+import type { GenerationUiAdapter } from '@features/generation/ui/GenerationUiContext';+import type * as IdentityModule from '@features/identity';+import type { ModelConfig } from '@features/models';+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { Project } from '@workbench/projectContracts';+import type * as ProjectsApiModule from '@workbench/projects/api';+import type { InvokeIssueAction } from '@workbench/shell/topbar/invokeIssueActions';+import type { InvocationIssue } from '@workbench/shell/topbar/invokeIssueTargets';+import type * as OpenWidgetModule from '@workbench/useOpenWorkbenchWidget';+import type { RegisteredWidget } from '@workbench/widgetContracts';+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';+import type { ReactNode } from 'react';++import { ChakraProvider } from '@chakra-ui/react';+import { DndContext } from '@dnd-kit/core';+import { PositivePromptField } from '@features/generation/components';+import {+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities';+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import { promptTemplatesQueryOptions } from '@features/generation/queries';+import { GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';+import { createDefaultUpscaleWidgetValues } from '@features/upscale';+import { UpscaleWidgetView } from '@features/upscale/ui/UpscaleWidgetView';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { captureInvocationRuntimeInputs } from '@workbench/invocationPreparation';+import {+ DEFAULT_PREFERENCES,+ patchWorkbenchPreferences,+ useWorkbenchPreferenceSelector,+} from '@workbench/settings/store';+import { runNotificationUndo } from '@workbench/shell/notifications/undoRegistry';+import { useInvokeIssueActions } from '@workbench/shell/topbar/invokeIssueActions';+import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';+import { getProjectWidgetValues, getResolvedProjectWidgetValues } from '@workbench/widgetState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegistryContext';+import { act, useMemo, useSyncExternalStore } 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 { UpscaleUiAdapterProvider } from './UpscaleUiAdapter';++const model = (key: string, base: string, type: string): ModelConfig => ({+ base,+ file_size: 1,+ format: 'checkpoint',+ hash: key,+ key,+ name: key,+ path: key,+ source: key,+ source_type: 'path',+ type,+});+const models = [+ model('upscale-main', 'sdxl', 'main'),+ model('spandrel', 'any', 'spandrel_image_to_image'),+ { ...model('tile', 'sdxl', 'controlnet'), name: 'SDXL Tile ControlNet' },+];+const modelSnapshot = { models, status: 'loaded' };+const CINEMATIC: PromptTemplateRecord = {+ hasImage: false,+ id: 'cinematic',+ isDefault: false,+ isPublic: false,+ name: 'Cinematic',+ negativePrompt: '{prompt}, lowres',+ positivePrompt: '{prompt}, film grain',+ userId: 'user-1',+};+const noop = () => undefined;+const generationAdapterBase = {+ account: { currentUserId: null, multiuserEnabled: false },+ capabilities: { canManagePromptTemplates: false, canManageSharedSystemPrompts: false },+ gallery: { findImage: noop, selectedImage: null, touchImages: noop },+ models: { catalog: [], ensureLoaded: noop, openManager: noop, status: 'loaded' },+ notifications: { error: noop, info: noop, reportError: noop, undoable: noop },+ project: { activeProjectId: 'project', invocationSourceId: 'upscale', showPromptSyntaxHighlighting: false },+ promptHistory: { clear: noop, items: [], remove: noop, restore: noop },+};++/** Section open state comes from the user's preferences, as the App adapter reads it. */+const GenerationUi = ({ children }: { children: ReactNode }) => {+ const sectionsOpen = useWorkbenchPreferenceSelector((preferences) => preferences.generateSectionsOpen);+ const adapter = useMemo(+ () =>+ ({+ ...generationAdapterBase,+ sectionPreferences: {+ sectionsOpen,+ setSectionsOpen: (changes: Readonly<Record<string, boolean>>) =>+ void patchWorkbenchPreferences({ generateSectionsOpen: { ...sectionsOpen, ...changes } }),+ },+ }) as unknown as GenerationUiAdapter,+ [sectionsOpen]+ );++ return <GenerationUiProvider adapter={adapter}>{children}</GenerationUiProvider>;+};++let store: WorkbenchInternalStore;+let host: HTMLDivElement;+let root: Root;++vi.mock('react-i18next', () => {+ // A count shows after its key, so a summary's numbers can be read.+ const t = (key: string, values?: { count?: number }) =>+ values?.count === undefined ? key : `${key}:${values.count}`;+ return { useTranslation: () => ({ i18n: { resolvedLanguage: 'en' }, t }) };+});+vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ ensureModelsLoaded: () => Promise.resolve(),+ getModelImageUrl: () => '',+ useModelsSelector: (selector: (snapshot: typeof modelSnapshot) => unknown) => selector(modelSnapshot),+ useOpenModelInManager: () => undefined,+}));+vi.mock('@features/models/react', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ ModelSelect: () => null,+}));+vi.mock('@features/gallery/mediaSlot', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ GalleryMediaSlot: () => null,+}));+// The wildcard catalog is the backend's; the prompt field only reads its names.+vi.mock('@features/generation/data/wildcards', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ wildcardsQueryOptions: () => ({ queryFn: () => Promise.resolve([]), queryKey: ['generation', 'wildcards'] }),+}));+// Expansion is the backend's: a prompt with an unbalanced group fails to expand, as the parser would refuse it.+vi.mock('@features/generation/data/promptUtilities', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ parseDynamicPrompts: ({ prompt }: { prompt: string }) =>+ Promise.resolve(+ prompt.includes('{{')+ ? { error: 'Unbalanced braces', prompts: [prompt] }+ : { error: null, prompts: ['a red fox', 'a green fox'] }+ ),+}));+// Preferences save to the server; here they stay in memory.+vi.mock('@workbench/projects/api', async (importOriginal) => ({+ ...(await importOriginal<typeof ProjectsApiModule>()),+ setClientStateValue: async () => {},+}));+vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<typeof IdentityModule>()),+ useCapabilities: () => ({ canManageModels: false }),+}));+vi.mock('@workbench/image-actions/useFindGalleryItem', () => ({ useFindGalleryItem: () => noop }));+vi.mock('@workbench/useOpenWorkbenchWidget', async (importOriginal) => ({+ ...(await importOriginal<typeof OpenWidgetModule>()),+ useOpenWorkbenchWidget: () => noop,+}));+vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectSelector: (selector: (project: Project) => unknown) =>+ selector(useSyncExternalStore(store.subscribe, store.getSnapshot).activeProject),+ useWidgetValuesSelector: (widgetId: string, selector: (values: Record<string, unknown>) => unknown) => {+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot);+ return selector(getResolvedProjectWidgetValues(snapshot.activeProject, widgetId, snapshot.scopedDefaults));+ },+ useOptionalWorkbenchCommands: () => store.commands,+ useWorkbenchCommands: () => store.commands,+ useWorkbenchQueries: () => store.queries,+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const generateValues = () => getProjectWidgetValues(store.getSnapshot().activeProject, 'generate');+const button = (label: string) => document.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);++/** The real registry, minus chunk preloading: revealing a widget changes the layout and loads nothing. */+const withoutPreload = (widget: RegisteredWidget): RegisteredWidget => ({+ ...widget,+ implementation: { ...widget.implementation, preload: () => {} },+});+const getQuietWidgetById = (typeId: string) => {+ const widget = getWidgetById(typeId);++ return widget ? withoutPreload(widget) : undefined;+};+const getQuietWidgetsForRegion = (region: WidgetRegion) => getWidgetsForRegion(region).map(withoutPreload);+const NO_LORAS: [] = [];++let getIssueActions: ((issue: InvocationIssue) => InvokeIssueAction[]) | null = null;+const publishIssueActions = (actions: (issue: InvocationIssue) => InvokeIssueAction[]) => {+ getIssueActions = actions;+};+/** Publishes the Invoke issue actions as the Invoke popover reads them. */+const IssueActionsProbe = ({+ onActions,+}: {+ onActions: (actions: (issue: InvocationIssue) => InvokeIssueAction[]) => void;+}) => {+ onActions(useInvokeIssueActions());++ return null;+};++const detailGuidanceTrigger = () =>+ [...host.querySelectorAll<HTMLButtonElement>('button')].find((candidate) =>+ candidate.textContent?.includes('widgets.upscale.detailGuidance')+ )!;+const upscalePrompt = () =>+ host.querySelector<HTMLTextAreaElement>(+ '[data-testid="upscale"] textarea[aria-label="widgets.generate.positivePrompt"]'+ )!;++const render = async ({+ openDetailGuidance = true,+ withGenerateField = false,+}: { openDetailGuidance?: boolean; withGenerateField?: boolean } = {}) => {+ const queryClient = new QueryClient();+ // Fresh for the query's stale time, so the catalog the panel lists is this one and no request leaves the test.+ queryClient.setQueryData(promptTemplatesQueryOptions().queryKey, [CINEMATIC]);+ store.commands.widgets.patchValues('upscale', {+ ...createDefaultUpscaleWidgetValues(models),+ inputImage: { height: 100, image_name: 'input.png', width: 200 },+ });+ store.commands.generation.patchPromptDraft(+ { negativePrompt: 'blur', positivePrompt: 'fine detail' },+ 'upscale',+ store.getSnapshot().activeProject.id+ );++ await act(() =>+ root.render(+ <QueryClientProvider client={queryClient}>+ <ChakraProvider value={system}>+ <WorkbenchWidgetRegistryProvider+ getWidgetById={getQuietWidgetById}+ getWidgetsForRegion={getQuietWidgetsForRegion}+ >+ <GenerationUi>+ <UpscaleUiAdapterProvider>+ <DndContext>+ <div data-testid="upscale">+ <UpscaleWidgetView />+ </div>+ {/* Generate's own prompt field, mounted after Upscale's. */}+ {withGenerateField ? (+ <div data-testid="generate">+ <PositivePromptField+ heightPx={96}+ loras={NO_LORAS}+ projectId="project"+ selectedModel={undefined}+ showSyntaxHighlighting={false}+ value="a generate prompt"+ onChange={noop}+ onResizeEnd={noop}+ onUsePrompt={noop}+ />+ </div>+ ) : null}+ <IssueActionsProbe onActions={publishIssueActions} />+ </DndContext>+ </UpscaleUiAdapterProvider>+ </GenerationUi>+ </WorkbenchWidgetRegistryProvider>+ </ChakraProvider>+ </QueryClientProvider>+ )+ );+ // The prompts live in the collapsed detail guidance section.+ if (openDetailGuidance) {+ await act(async () => {+ await userEvent.click(detailGuidanceTrigger());+ });+ }+};++/** Queues the Upscale as Invoke does once nothing is left to expand. */+const queueUpscale = () => {+ act(() =>+ store.commands.generation.submitResolved({+ backendSupportsCancellation: true,+ models,+ projectId: store.getSnapshot().activeProject.id,+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'upscale', sourceLocked: false },+ runtime: captureInvocationRuntimeInputs('upscale'),+ })+ );++ return store.getSnapshot().activeProject.queue.items[0]?.snapshot.backendSubmission;+};++beforeEach(async () => {+ accountLifecycle.activate('upscale-shared-prompt-test');+ await patchWorkbenchPreferences(DEFAULT_PREFERENCES);+ // The account lifecycle owns the capability table, so it is seeded once the account is active.+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ store = createWorkbenchStore();+ host = document.createElement('div');+ host.style.width = '420px';+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ getIssueActions = null;+ resetArchitectureCapabilities();+ accountLifecycle.invalidate();+});++describe("Upscale's prompt templates and dynamic prompts", () => {+ it('applies a template to the prompt it shares with Generate, queues the prompt inside it, and undoes', async () => {+ await render();++ const templates = button('widgets.generate.promptTemplates.title');++ expect(templates).not.toBeNull();++ await act(async () => {+ await userEvent.click(templates!);+ });+ await act(async () => {+ await userEvent.click(+ [...document.querySelectorAll<HTMLButtonElement>('[data-scope="popover"][data-part="content"] button')].find(+ (candidate) => candidate.textContent?.includes('Cinematic')+ )!+ );+ });++ expect(generateValues().promptTemplate).toEqual({+ id: 'cinematic',+ name: 'Cinematic',+ negativePrompt: '{prompt}, lowres',+ positivePrompt: '{prompt}, film grain',+ });+ // The trigger names what is applied.+ expect(button('widgets.generate.promptTemplates.title')?.textContent).toContain('Cinematic');+ expect(queueUpscale()).toMatchObject({+ negativePrompt: 'blur, lowres',+ positivePrompt: 'fine detail, film grain',+ });++ const undo = store+ .getSnapshot()+ .notifications.flatMap((notification) => notification.actions ?? [])+ .find((action) => action.kind === 'undo') as { undoId: string } | undefined;++ expect(undo).toBeDefined();+ act(() => runNotificationUndo(undo!.undoId));++ expect(generateValues().promptTemplate).toBeNull();+ });++ it('shows the merged prompt read-only and goes back to the prompt as written', async () => {+ await render();+ act(() =>+ store.commands.generation.patchPromptDraft(+ { promptTemplate: { ...CINEMATIC }, promptTemplateViewMode: false },+ 'upscale',+ store.getSnapshot().activeProject.id+ )+ );++ await act(async () => {+ await userEvent.click(button('widgets.generate.promptTemplates.viewMerged')!);+ });++ const prompt = host.querySelector<HTMLTextAreaElement>('textarea[aria-label="widgets.generate.positivePrompt"]')!;++ expect(generateValues().promptTemplateViewMode).toBe(true);+ expect(prompt.readOnly).toBe(true);+ expect(prompt.value).toBe('fine detail, film grain');++ await act(async () => {+ await userEvent.click(button('widgets.generate.promptTemplates.editAuthored')!);+ });++ expect(prompt.readOnly).toBe(false);+ expect(prompt.value).toBe('fine detail');+ });++ it('turns dynamic prompts off for the shared prompt, which then queues as typed', async () => {+ await render();+ act(() =>+ store.commands.generation.patchPromptDraft(+ { positivePrompt: 'a {red|green} fox' },+ 'upscale',+ store.getSnapshot().activeProject.id+ )+ );++ await act(async () => {+ await userEvent.click(button('widgets.generate.dynamicPrompts.showPrompts')!);+ });+ await act(async () => {+ await userEvent.click(+ document.querySelector<HTMLElement>(+ '[data-scope="popover"][data-part="content"] [data-scope="switch"][data-part="root"]'+ )!+ );+ });++ expect(generateValues().dynamicPromptsEnabled).toBe(false);+ expect(button('widgets.generate.dynamicPrompts.offLabel')).not.toBeNull();++ const submission = queueUpscale();++ expect(submission).toMatchObject({ positivePrompt: 'a {red|green} fox' });+ expect(submission).not.toHaveProperty('positivePrompts');+ });++ it("shows an Upscale prompt that cannot expand: opens Detail guidance, focuses Upscale's field and its note", async () => {+ await render({ openDetailGuidance: false, withGenerateField: true });+ act(() =>+ store.commands.generation.patchPromptDraft(+ { positivePrompt: 'a {{red|green} fox' },+ 'upscale',+ store.getSnapshot().activeProject.id+ )+ );+ const generatePrompt = host.querySelector<HTMLTextAreaElement>('[data-testid="generate"] textarea')!;++ expect(detailGuidanceTrigger().getAttribute('aria-expanded')).toBe('false');+ expect(upscalePrompt().checkVisibility()).toBe(false);++ const show = getIssueActions!({+ message: 'The prompt could not be expanded.',+ target: { kind: 'prompt', widgetId: 'upscale' },+ }).find((action) => action.id === 'show')!;+ await act(() => show.run());++ await expect.poll(() => document.activeElement).toBe(upscalePrompt());+ expect(document.activeElement).not.toBe(generatePrompt);+ expect(detailGuidanceTrigger().getAttribute('aria-expanded')).toBe('true');+ // The note under the field says why the prompt cannot expand and offers the way out.+ await expect+ .poll(+ () =>+ [...host.querySelectorAll<HTMLButtonElement>('[data-testid="upscale"] button')]+ .find((candidate) => candidate.textContent === 'widgets.generate.dynamicPrompts.turnOff')+ ?.checkVisibility() ?? false,+ { timeout: 3000 }+ )+ .toBe(true);+ });+});++describe('Upscale Detail guidance, folded', () => {+ const summary = () => detailGuidanceTrigger().querySelector('[data-section-summary]')?.textContent ?? null;+ const patchPrompt = (patch: Parameters<WorkbenchInternalStore['commands']['generation']['patchPromptDraft']>[0]) =>+ act(() => store.commands.generation.patchPromptDraft(patch, 'upscale', store.getSnapshot().activeProject.id));++ it('names the prompt template Generate wraps around the shared prompt', async () => {+ await render({ openDetailGuidance: false });+ patchPrompt({ promptTemplate: { ...CINEMATIC } });++ expect(detailGuidanceTrigger().getAttribute('aria-expanded')).toBe('false');+ expect(summary()).toBe('Cinematic');+ // The shared badge stays beside it.+ expect(detailGuidanceTrigger().textContent).toContain('widgets.upscale.shared');+ });++ it('counts the prompts dynamic prompts expand the shared prompt to', async () => {+ await render({ openDetailGuidance: false });+ patchPrompt({ positivePrompt: 'a {red|green} fox' });++ await expect.poll(summary, { timeout: 3000 }).toBe('topbar.invoke.summary.promptCount:2');+ });++ it('says nothing for a plain prompt without a template', async () => {+ await render({ openDetailGuidance: false });++ expect(summary()).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/app/VideoModelSwitch.browser.test.tsx b/invokeai/frontend/webv2/src/app/VideoModelSwitch.browser.test.tsxindex 5f963479f3..591e6c115d 100644--- a/invokeai/frontend/webv2/src/app/VideoModelSwitch.browser.test.tsx+++ b/invokeai/frontend/webv2/src/app/VideoModelSwitch.browser.test.tsx@@ -174,7 +174,7 @@ seedArchitectureCapabilities();(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const generationAdapter = {- sectionPreferences: { sectionsOpen: {}, setSectionOpen: () => undefined },+ sectionPreferences: { sectionsOpen: {}, setSectionsOpen: () => undefined },} as unknown as GenerationUiAdapter;const SOURCE_VIDEO = {@@ -472,6 +472,62 @@ describe('video model switch confirmation', () => {});});+describe('Video section issues', () => {+ const section = (id: string) => host.querySelector<HTMLElement>(`.generate-section[data-generate-section="${id}"]`)!;+ const chip = (id: string) =>+ section(id).querySelector<HTMLElement>(':scope > [data-part="trigger"] [data-section-chip]')!;+ const issues = (id: string) => section(id).querySelector(':scope > [data-part="trigger"] [data-section-issues]');+ /** The number on the title, which assistive tech skips. */+ const shownCount = (id: string) => issues(id)?.querySelector(':scope > span[aria-hidden]')?.textContent ?? null;+ /** What assistive tech reads in its place. */+ const spokenCount = (id: string) => issues(id)?.querySelector(':scope > :not([aria-hidden])')?.textContent ?? null;++ it('counts an issue in each section that can fix it, tints those, and leaves the rest plain', async () => {+ await render();+ // The extension opens with 17 frames of the initial video, so 17 frames continue nothing: raise Frames under+ // Dimensions, or lower the context under Initial video.+ await act(() => store.commands.widgets.patchValues('video', { numFrames: 17 }));++ for (const id of ['video-dimensions', 'video-source']) {+ expect(shownCount(id), id).toBe('1');+ expect(spokenCount(id), id).toBe('1 issue');+ expect(chip(id).hasAttribute('data-issues'), id).toBe(true);+ }+ expect(issues('video-render')).toBeNull();+ expect(chip('video-render').hasAttribute('data-issues')).toBe(false);+ // The chip eases into its tint.+ await expect+ .poll(() => getComputedStyle(chip('video-dimensions')).backgroundColor)+ .not.toBe(getComputedStyle(chip('video-render')).backgroundColor);++ // A render-only issue counts there alone.+ await act(() => store.commands.widgets.patchValues('video', { numFrames: 121, steps: 0 }));++ expect(issues('video-dimensions')).toBeNull();+ expect(issues('video-source')).toBeNull();+ expect(shownCount('video-render')).toBe('1');+ });++ it('counts nothing in a section whose control for the issue is hidden', async () => {+ const ti2v = model('wan-ti2v', 'wan', 'main', 'Wan 2.2 TI2V 5B', { variant: 'ti2v_5b' });+ modelStore.set([...catalog, ti2v]);+ await render();+ // TI2V-5B cannot aim an extension at an end frame, and shows no last-frame field to clear it from.+ await act(() =>+ store.commands.widgets.patchValues('video', {+ ...getDefaultVideoSettings(ti2v as never, [...catalog, ti2v] as never),+ lastFrameImage: LAST_FRAME,+ model: ti2v,+ modelKey: ti2v.key,+ sourceVideo: SOURCE_VIDEO,+ })+ );++ expect(shownCount('video-source')).toBe('1');+ expect(issues('video-frames')).toBeNull();+ });+});+describe('video model field without a model', () => {// The picker's install action reads the library itself; the field's message has to agree with it.const renderEmpty = () =>diff --git a/invokeai/frontend/webv2/src/app/main.tsx b/invokeai/frontend/webv2/src/app/main.tsxindex 487d506128..9ebaefcad1 100644--- a/invokeai/frontend/webv2/src/app/main.tsx+++ b/invokeai/frontend/webv2/src/app/main.tsx@@ -1,6 +1,7 @@import '@fontsource/inter/index.css';import '@platform/i18n/client';import { identityTransportAuthAdapter, startIdentityCredentialSync } from '@features/identity';+import { preventFileDropNavigation } from '@platform/browser/fileDropNavigation';import { registerServiceWorker } from '@platform/pwa/registerServiceWorker';import { configureHttpAuth } from '@platform/transport/http';import { StrictMode } from 'react';@@ -17,6 +18,8 @@ configureHttpAuth(identityTransportAuthAdapter);// Follows other tabs' sign-in, sign-out and token renewals for the page's lifetime.startIdentityCredentialSync();registerServiceWorker();+// A file dropped where nothing takes it must not navigate away from the app, for the page's lifetime.+preventFileDropNavigation();const rootElement = document.getElementById('root');diff --git a/invokeai/frontend/webv2/src/architecture/browserTestViewport.browser.test.ts b/invokeai/frontend/webv2/src/architecture/browserTestViewport.browser.test.tsindex fc6e26862c..201299e77c 100644--- a/invokeai/frontend/webv2/src/architecture/browserTestViewport.browser.test.ts+++ b/invokeai/frontend/webv2/src/architecture/browserTestViewport.browser.test.ts@@ -3,13 +3,20 @@ import { expect, it } from 'vitest';/** Playwright judges hover and click targets against the runner's outer page. If that page can scroll, a* scrollIntoView or focus() in one test leaves it offset for later files, and their pointer actions on elements at- * the iframe's top edge time out (FeatureHint's suite fails this way). The runner keeps that page unscrollable by- * laying the test iframe out as a block exactly filling it; an inline iframe leaves a few pixels of overflow below.+ * the iframe's top edge time out. A viewport change can temporarily make the iframe taller than its parent;+ * the runner must clip that overflow without preventing scrolling inside the test document.*/-it('keeps the outer page unscrolled when the test iframe scrolls', () => {+it.each([0, 176])('keeps the outer page unscrolled with %ipx of iframe overflow', (overflow) => {const below = document.createElement('input');+ const frame = window.frameElement as HTMLIFrameElement;+ const previousHeight = frame.style.height;+ expect(window.innerWidth).toBe(window.parent.innerWidth);+ expect(window.innerHeight).toBe(window.parent.innerHeight);+ if (overflow > 0) {+ frame.style.height = `${window.parent.innerHeight + overflow}px`;+ }below.style.cssText = 'position:absolute;left:0;top:5000px';document.body.append(below);@@ -21,5 +28,6 @@ it('keeps the outer page unscrolled when the test iframe scrolls', () => {} finally {below.remove();window.scrollTo(0, 0);+ frame.style.height = previousHeight;}});diff --git a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsxindex 2e3b39fb97..1e6f4ae3bd 100644--- a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx+++ b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx@@ -25,13 +25,20 @@ import {isAccountScopeCurrent,} from '@platform/state/accountLifecycle';import { getApiErrorMessage } from '@platform/transport/http';-import { Button, ConfirmDialog, IconButton, Scrollable, SegmentedControl, Tabs } from '@platform/ui';+import { Button, ConfirmDialog, Scrollable, SegmentedControl, Tabs } from '@platform/ui';import { EmptyState } from '@platform/ui/EmptyState';import { List } from '@platform/ui/list/List';import { ListItem } from '@platform/ui/list/ListItem';import { ListPager } from '@platform/ui/list/ListPager';import { listRowsFromItems } from '@platform/ui/list/listRows';-import { ManagerColumn, ManagerDetailHeader, ManagerLayout, ManagerSearchField } from '@platform/ui/ManagerLayout';+import {+ ManagerColumn,+ ManagerDetailHeader,+ ManagerFilterMenu,+ ManagerFilterResetItem,+ ManagerLayout,+ ManagerSearchField,+} from '@platform/ui/ManagerLayout';import { MenuContent } from '@platform/ui/Menu';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { useQuery, useQueryClient } from '@tanstack/react-query';@@ -42,7 +49,6 @@ import {PlusIcon,RefreshCwIcon,SearchIcon,- SlidersHorizontalIcon,Trash2Icon,TypeIcon,UploadIcon,@@ -622,16 +628,12 @@ const FontLibrary = () => {setOffset(0);}}/>- <Menu.Root closeOnSelect={false} positioning={FILTER_POSITION}>- <Menu.Trigger asChild>- <IconButton- aria-label={t('fonts.filterMenu')}- color={filter !== 'all' ? 'accent.solid' : 'fg.muted'}- variant="outline"- >- <Icon as={SlidersHorizontalIcon} boxSize="4" />- </IconButton>- </Menu.Trigger>+ <ManagerFilterMenu+ activeCount={Number(filter !== 'all')}+ closeOnSelect={false}+ label={t('fonts.filterMenu')}+ positioning={FILTER_POSITION}+ ><Portal><Menu.Positioner><MenuContent minW="13rem">@@ -652,10 +654,17 @@ const FontLibrary = () => {</Menu.RadioItem>))}</Menu.RadioItemGroup>+ <ManagerFilterResetItem+ activeCount={Number(filter !== 'all')}+ onReset={() => {+ setFilter('all');+ setOffset(0);+ }}+ /></MenuContent></Menu.Positioner></Portal>- </Menu.Root>+ </ManagerFilterMenu></HStack><Listkey={listKey}diff --git a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.visual.browser.test.tsx b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.visual.browser.test.tsxindex 3fb57e1e78..624593a590 100644--- a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.visual.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.visual.browser.test.tsx@@ -139,7 +139,7 @@ it('renders the font library with the real English locale', async () => {.element(page.getByRole('menuitemradio', { name: 'My fonts', exact: true })).toHaveAttribute('aria-checked', 'true');await userEvent.keyboard('{Escape}');- await expect.element(page.getByRole('button', { name: 'Filter fonts' })).toHaveFocus();+ await expect.element(page.getByRole('button', { name: 'Filter fonts, 1 filter active' })).toHaveFocus();await page.getByRole('tab', { name: 'Add Fonts' }).click();await expect.element(page.getByRole('button', { name: 'Upload fonts' })).toBeVisible();await settleAnimations();diff --git a/invokeai/frontend/webv2/src/features/gallery/README.md b/invokeai/frontend/webv2/src/features/gallery/README.mdindex d82886c3ba..9bc6d55ff8 100644--- a/invokeai/frontend/webv2/src/features/gallery/README.md+++ b/invokeai/frontend/webv2/src/features/gallery/README.md@@ -6,12 +6,14 @@ Gallery ordinary listings are Query-owned sparse pages shared by grid, picker, P## Selection and destination-The multi-selection belongs to the listing on screen. `settleGalleryValues` (`ui/galleryStateView.ts`), applied to every write of gallery values, drops `selectedImageNames` when a write changes what the listing holds (board, view, search, search scope, starred or media filter) without setting the selection itself; the primary item stays for Preview, and the grid acts on it only while it is listed. A deletion that reaches an item no loaded page holds, or more than one item, always confirms, listing the items, whatever the user's "Don't ask again". Item deletion and "Delete board and media" both report where the media is still used before it goes (`mediaUsage` entry: `POST /api/v1/gallery/usage` and the report types; `react` entry: `GalleryMediaUsagePanel`, the section both dialogs render, which loads the report view only once a check settles). The server's answer is conservative: it counts every media name a project document holds, Gallery selection, recents and workflow last runs included. The host narrows it (`workbench/image-actions/mediaUsageReport.ts`): projects loaded in the tab are scanned from memory, a few other named projects (up to 4 MiB each, measured decoded) are read and scanned, the rest stay as the server counts them. Each project entry carries the content and caller's workspace revisions its names were read at, from the same transaction. A loaded project's scan stands when it reports every name the server found, or when those revisions are the ones the tab's copy builds on (the sync store's `revision` and `workspaceRevision`; never while the copy is in conflict or schema-refused, since it then holds local work beside revisions it does not build on): an unsaved edit then removed what it dropped, and nothing is read. Otherwise (the server is ahead, or either side's revisions are unknown) the server's copy is read, ahead of closed projects and within the same cap, and a name either copy uses counts; when the read fails or is skipped, the project keeps what its copy uses and the server's count, with "Its saved version couldn’t be checked." The scan (`workbench/image-actions/mediaUsage.ts`) names the surfaces it knows (live work, staged canvas results, canvas snapshots) and fails safe: a name anywhere else in the project counts as "Elsewhere in the project", except in fields listed there as only showing or recording media (Gallery state, workflow last runs, last submitted graphs) or as session state never saved (queue, run log, undo histories). An item request counts the items asked about: the server checks only those the caller may delete, without naming them; workflows, the legacy editor, projects kept for repair, queued jobs and other accounts pass through. A use, or a check that could not finish, always asks; a silent deletion first looks again at the projects in this tab, for a use added while the check ran. A second deletion that needs asking while a dialog is open is refused with a notice; a deletion already under way for an item (checking, asking or deleting) drops a repeated request for it; the board dialog checks only once deleting the media is ticked, once per opening, through the adapter's `getBoardMediaUsage`, stops a running check when the box is unticked or the dialog closes by any path (closing leaves the opening's query key), and keeps the opening's answer while unticked. Once the check answers, the checkbox, description, button and typed-name threshold count the items the server says go: on a shared board only the caller's own ("your N items"), and none at all when they added none.+The multi-selection belongs to the listing on screen. `settleGalleryValues` (`ui/galleryStateView.ts`), applied to every write of gallery values, drops `selectedImageNames` when a write changes what the listing holds (board, view, search, search scope, starred or media filter) without setting the selection itself; the primary item stays for Preview, and the grid acts on it only while it is listed. It also ends a comparison when a write moves the primary item onto the comparison image it already holds (a Ctrl/Cmd-click, a range, a deletion's successor): Select for compare waits for its second image only while the comparison image is set on the selected one. A deletion that reaches an item no loaded page holds, or more than one item, always confirms, listing the items, whatever the user's "Don't ask again". Item deletion and "Delete board and media" both report where the media is still used before it goes (`mediaUsage` entry: `POST /api/v1/gallery/usage` and the report types; `react` entry: `GalleryMediaUsagePanel`, the section both dialogs render, which loads the report view only once a check settles). The server's answer is conservative: it counts every media name a project document holds, Gallery selection, recents and workflow last runs included. The host narrows it (`workbench/image-actions/mediaUsageReport.ts`): projects loaded in the tab are scanned from memory, a few other named projects (up to 4 MiB each, measured decoded) are read and scanned, the rest stay as the server counts them. Each project entry carries the content and caller's workspace revisions its names were read at, from the same transaction. A loaded project's scan stands when it reports every name the server found, or when those revisions are the ones the tab's copy builds on (the sync store's `revision` and `workspaceRevision`; never while the copy is in conflict or schema-refused, since it then holds local work beside revisions it does not build on): an unsaved edit then removed what it dropped, and nothing is read. Otherwise (the server is ahead, or either side's revisions are unknown) the server's copy is read, ahead of closed projects and within the same cap, and a name either copy uses counts; when the read fails or is skipped, the project keeps what its copy uses and the server's count, with "Its saved version couldn’t be checked." The scan (`workbench/image-actions/mediaUsage.ts`) names the surfaces it knows (live work, staged canvas results, canvas snapshots) and fails safe: a name anywhere else in the project counts as "Elsewhere in the project", except in fields listed there as only showing or recording media (Gallery state, workflow last runs, last submitted graphs) or as session state never saved (queue, run log, undo histories). An item request counts the items asked about: the server checks only those the caller may delete, without naming them; workflows, the legacy editor, projects kept for repair, queued jobs and other accounts pass through. A use, or a check that could not finish, always asks; a silent deletion first looks again at the projects in this tab, for a use added while the check ran. A second deletion that needs asking while a dialog is open is refused with a notice; a deletion already under way for an item (checking, asking or deleting) drops a repeated request for it; the board dialog checks only once deleting the media is ticked, once per opening, through the adapter's `getBoardMediaUsage`, stops a running check when the box is unticked or the dialog closes by any path (closing leaves the opening's query key), and keeps the opening's answer while unticked. Once the check answers, the checkbox, description, button and typed-name threshold count the items the server says go: on a shared board only the caller's own ("your N items"), and none at all when they added none.New results without a board of their own go to `autoAddBoardId` when one is chosen, else to the project's inbox (Uncategorized for a gallery without one); only `followSelectedBoard`, off by default, makes them follow the selected board. While following is off, selecting a board, Find in Gallery and reveals therefore never move the destination; while it is on, anything that selects a board moves it, by definition. Earlier builds stored `autoAddBoardId: 'follow'` for following, their default; it reads as the default destination. The header's Saving to control and the board list's destination marker name it as submissions resolve it (`useGalleryDestination`), redirection to the inbox included.Move, star and archive report an Undo (`notify.undoable`). Undo puts back each item's own board or star flag as known before the action, leaving out items whose prior value was not known; it is last write wins, so a change made to the same items since is overwritten. An archive's Undo restores the destination in the project that archived, by its id, only while that project has chosen no other since.+The server refuses a request body naming more than 1,000 images or videos (`GALLERY_REQUEST_MAX_NAMES`, mirroring `invokeai/app/api/routers/_limits.py`), so the transports in `data/backend.ts` send longer name lists in batches of that size, one after another: delete, star, unstar, adding images to a board and removing them from one, and resolving images by name. Their answers merge. A batch that fails, or an abort, after earlier batches succeeded stops the run, records the failure as a debug breadcrumb (`gallery.batch-request-failed`; the caller's partial-failure notice reports it) and reports the earlier batches' items as done and the rest as failed; a failure or abort before anything succeeded rejects as one request would, and an account change rejects whatever succeeded. The usage check (`data/mediaUsage.ts`) batches the same way, gives each request its own share of the check's time budget, and fails whole when any batch fails. Name lists join and per-name counts add exactly. A document listed by several batches keeps its revisions only when they agree. A batch past the server's 100-document listing cap may leave out a document another batch lists: that document is marked `namesIncomplete`. A project open in this tab is then always checked against its saved copy as well; any other flagged document is listed unread with its count shown as "at least". The server's in-use total stands whenever documents went unlisted, even after a scan narrowed a project, since the unlisted documents' uses count nowhere else. Counts that cannot be deduplicated across batches err high: documents a batch left unlisted each count as another ("N more projects or workflows"), and queued jobs and other accounts' documents count once per batch that found them. A selection download makes one archive per 1,000 images, with a notice saying how many are coming.+## Realtime refresh and external revealUploads, reconnects, and all of the signed-in user's completed queue items refresh the listings, including completions from other frontend tabs and devices. Gallery owns socket-completion invalidation; Queue does not also refresh for those events. Bursts coalesce for 250 ms and passes stay at least 1 second apart, with a trailing pass for later events. Hidden tabs keep one pending refresh until shown. Query invalidations serialize and await active refetches, so a slow listing read lands before a later pass begins. Frontend origins (`webv2:`) refresh only: they never select an item, change filters, board or page, or request external reveal. Image and video results share this completion path.diff --git a/invokeai/frontend/webv2/src/features/gallery/core/mediaUsage.ts b/invokeai/frontend/webv2/src/features/gallery/core/mediaUsage.tsindex d988e6ddc2..302d4dc7fa 100644--- a/invokeai/frontend/webv2/src/features/gallery/core/mediaUsage.ts+++ b/invokeai/frontend/webv2/src/features/gallery/core/mediaUsage.ts@@ -34,6 +34,11 @@ export interface GalleryMediaUsageDocument extends GalleryMediaUsageNames {* caller has none there. Null for other kinds.*/workspaceRevision: number | null;+ /**+ * A check sent in several requests could not list this document in all of them: its names and counts are only+ * some of what it uses.+ */+ namesIncomplete?: true;}export interface GalleryMediaUsage {@@ -73,31 +78,36 @@ export interface GalleryMediaUsageSurfaceRow {surface: GalleryMediaUsageSurface;}-/** One line of the report; `count` is how many checked items the source uses. */-export type GalleryMediaUsageGroup =+/**+ * One line of the report; `count` is how many checked items the source uses, at least that many when `countAtLeast`+ * (the server could not name all of the source's uses).+ */+export type GalleryMediaUsageGroup = { countAtLeast?: true } &/** The project the deletion is made from; `savedCopyUnchecked` as for `project`. */- | { count: number; kind: 'openProject'; savedCopyUnchecked?: true; surfaces: GalleryMediaUsageSurfaceRow[] }- | {- count: number;- kind: 'project';- name: string | null;- /**- * The project is open, but its saved version, which the server says uses more of the media, could not be- * checked; `count` includes those uses, `surfaces` only what the open copy uses.- */- savedCopyUnchecked?: true;- surfaces: GalleryMediaUsageSurfaceRow[];- }- /** A project the host could not open to see where it uses the media. */- | { count: number; kind: 'projectUnchecked'; name: string | null }- | { count: number; kind: 'quarantinedProject'; name: string | null }- | { count: number; kind: 'workflow'; name: string | null }- | { count: number; kind: 'legacyEditor' }- | { count: number; kind: 'otherDocument'; name: string | null }- /** Documents past the server's listing cap. */- | { documentCount: number; kind: 'moreDocuments' }- | { count: number; jobCount: number; kind: 'queue' }- | { count: number; kind: 'otherAccounts' };+ (+ | { count: number; kind: 'openProject'; savedCopyUnchecked?: true; surfaces: GalleryMediaUsageSurfaceRow[] }+ | {+ count: number;+ kind: 'project';+ name: string | null;+ /**+ * The project is open, but its saved version, which the server says uses more of the media, could not be+ * checked; `count` includes those uses, `surfaces` only what the open copy uses.+ */+ savedCopyUnchecked?: true;+ surfaces: GalleryMediaUsageSurfaceRow[];+ }+ /** A project the host could not open to see where it uses the media. */+ | { count: number; kind: 'projectUnchecked'; name: string | null }+ | { count: number; kind: 'quarantinedProject'; name: string | null }+ | { count: number; kind: 'workflow'; name: string | null }+ | { count: number; kind: 'legacyEditor' }+ | { count: number; kind: 'otherDocument'; name: string | null }+ /** Documents past the server's listing cap. */+ | { documentCount: number; kind: 'moreDocuments' }+ | { count: number; jobCount: number; kind: 'queue' }+ | { count: number; kind: 'otherAccounts' }+ );export interface GalleryMediaUsageReport {/** Items checked: the requested items, or the board's as the server counted them (the items deleting it removes). */@@ -109,12 +119,11 @@ export interface GalleryMediaUsageReport {onlyImages: boolean;scope: 'board' | 'items';/**- * Whether the server check ran: `unavailable` when it did not finish (offline, an older server, a timeout),- * `tooManyItems` when the selection is past what one check takes. Either way only projects open in this tab were- * checked, not other projects, workflows, the legacy editor, queued jobs or other accounts. A board's report always- * has the server's answer, which alone knows the board's items.+ * Whether the server check ran: `unavailable` when it did not finish (offline, an older server, a timeout), so only+ * projects open in this tab were checked, not other projects, workflows, the legacy editor, queued jobs or other+ * accounts. A board's report always has the server's answer, which alone knows the board's items.*/- serverCheck: 'complete' | 'tooManyItems' | 'unavailable';+ serverCheck: 'complete' | 'unavailable';}/** What a deletion dialog shows while the check runs, when it failed outright, and once it has a report. */diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.tsindex 15eec7ba04..dfdca8606f 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.test.ts@@ -1,6 +1,8 @@+import openapi from '@api/openapi.json';import { galleryItems } from '@features/gallery';+import { configureLogging, getLoggingConfig, getLogSnapshot, resetLogging } from '@platform/logging/logger';import { accountLifecycle } from '@platform/state/accountLifecycle';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';const mocks = vi.hoisted(() => ({apiFetchJson: vi.fn(),@@ -21,8 +23,8 @@ import { ApiError } from '@platform/transport/http';import {ALL_READABLE_BOARDS_ID,+ GALLERY_REQUEST_MAX_NAMES,addImagesToGalleryBoard,- checkGalleryMediaUsage,createGalleryBoard,galleryBoardExists,deleteGalleryBoard,@@ -106,152 +108,6 @@ describe('deleteGalleryBoard outcomes', () => {});});-describe('checkGalleryMediaUsage', () => {- const usageBody = (overrides: Record<string, unknown> = {}) => ({- checked_image_count: 2,- checked_video_count: 1,- documents: [- {- id: 'legacy_editor',- image_count: 1,- image_names: ['a.png'],- kind: 'legacy_editor',- name: null,- revision: null,- video_count: 0,- video_names: [],- workspace_revision: null,- },- {- id: 'project-1',- image_count: 1200,- image_names: ['a.png', 'b.png'],- kind: 'project',- name: 'Harbor Tower',- revision: 7,- video_count: 1,- video_names: ['c.mp4'],- workspace_revision: 3,- },- {- id: 'later-kind',- image_count: 1,- image_names: ['b.png'],- kind: 'storyboard',- name: ' ',- // Revisions are only a hint: a malformed one reads as unknown rather than failing the check.- revision: '2',- video_count: 0,- video_names: [],- workspace_revision: -1,- },- ],- documents_total: 140,- in_use_image_count: 2,- in_use_video_count: 1,- other_accounts: { document_count: 3, image_count: 1, queue_item_count: 2, video_count: 0 },- queue: { image_count: 1, image_names: ['a.png'], item_count: 2, video_count: 0, video_names: [] },- ...overrides,- });-- beforeEach(() => {- accountLifecycle.activate('user-a');- mocks.apiFetchJson.mockReset();- });-- it('asks about the items by kind, or about a whole board, and maps the answer', async () => {- mocks.apiFetchJson.mockResolvedValue(usageBody());-- const usage = await checkGalleryMediaUsage({- kind: 'items',- refs: [- { kind: 'image', name: 'a.png' },- { kind: 'video', name: 'c.mp4' },- { kind: 'image', name: 'b.png' },- ],- });- await checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' });-- expect(JSON.parse(String(mocks.apiFetchJson.mock.calls[0]?.[1]?.body))).toEqual({- image_names: ['a.png', 'b.png'],- video_names: ['c.mp4'],- });- expect(mocks.apiFetchJson.mock.calls[0]?.[0]).toBe('/api/v1/gallery/usage');- expect(mocks.apiFetchJson.mock.calls[0]?.[1]?.method).toBe('POST');- expect(JSON.parse(String(mocks.apiFetchJson.mock.calls[1]?.[1]?.body))).toEqual({ board_id: 'board-1' });- expect(usage).toEqual({- checkedImageCount: 2,- checkedVideoCount: 1,- documents: [- {- id: 'legacy_editor',- imageCount: 1,- imageNames: ['a.png'],- kind: 'legacyEditor',- name: null,- revision: null,- videoCount: 0,- videoNames: [],- workspaceRevision: null,- },- {- id: 'project-1',- imageCount: 1200,- imageNames: ['a.png', 'b.png'],- kind: 'project',- name: 'Harbor Tower',- revision: 7,- videoCount: 1,- videoNames: ['c.mp4'],- workspaceRevision: 3,- },- // A kind this build does not know still uses the media; a blank name reads as none.- {- id: 'later-kind',- imageCount: 1,- imageNames: ['b.png'],- kind: 'other',- name: null,- revision: null,- videoCount: 0,- videoNames: [],- workspaceRevision: null,- },- ],- documentsTotal: 140,- inUseImageCount: 2,- inUseVideoCount: 1,- otherAccounts: { documentCount: 3, imageCount: 1, queueItemCount: 2, videoCount: 0 },- queue: { imageCount: 1, imageNames: ['a.png'], itemCount: 2, videoCount: 0, videoNames: [] },- });- });-- it('fails on a malformed answer rather than reading it as nothing in use', async () => {- mocks.apiFetchJson.mockResolvedValue(usageBody({ in_use_image_count: undefined }));-- await expect(checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' })).rejects.toThrow(TypeError);- });-- it('drops an answer that arrives after the account changed', async () => {- let answer: (value: unknown) => void = () => {};- mocks.apiFetchJson.mockReturnValue(- new Promise((resolve) => {- answer = resolve;- })- );-- const check = checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' });- const signal = mocks.apiFetchJson.mock.calls[0]?.[1]?.signal as AbortSignal;-- accountLifecycle.invalidate();- accountLifecycle.activate('user-b');- answer(usageBody());-- await expect(check).rejects.toThrow('no longer active');- expect(signal.aborted).toBe(true);- });-});-describe('image mutation outcomes', () => {beforeEach(() => {accountLifecycle.activate('user-a');@@ -1105,6 +961,179 @@ describe('deleteGalleryImages partial failures', () => {});});+type SchemaNode = { anyOf?: SchemaNode[]; maxItems?: number; properties?: Record<string, SchemaNode> };++/** `maxItems` of every media-name list a request body carries, by schema and property. */+const capsOnNameLists = (): Record<string, number> =>+ Object.fromEntries(+ Object.entries(openapi.components.schemas as Record<string, SchemaNode>).flatMap(([schema, { properties }]) =>+ Object.entries(properties ?? {})+ .filter(([property]) => property.endsWith('_names'))+ .flatMap(([property, node]) =>+ [node, ...(node.anyOf ?? [])]+ .filter((variant) => variant.maxItems !== undefined)+ .map((variant) => [`${schema}.${property}`, variant.maxItems!] as const)+ )+ )+ );++describe('name lists past the server’s per-request cap', () => {+ it('batches by the cap the server publishes for every name list', () => {+ const caps = capsOnNameLists();++ // The star, delete, board, copy, download and lookup bodies, among others.+ expect(Object.keys(caps).length).toBeGreaterThan(5);+ expect(Object.entries(caps).filter(([, cap]) => cap !== GALLERY_REQUEST_MAX_NAMES)).toEqual([]);+ });++ const names = (count: number) => Array.from({ length: count }, (_, index) => `image-${index}.png`);+ const sentNames = () =>+ mocks.apiFetchJson.mock.calls.map(+ ([, init]) => (JSON.parse(String(init.body)) as { image_names: string[] }).image_names+ );+ // Deletes what it is sent, except that it reports every name ending in 7 as failed.+ const deleteServer = (_url: string, init: { body: string }) => {+ const sent = (JSON.parse(init.body) as { image_names: string[] }).image_names;++ if (sent.length > 1000) {+ return Promise.reject(new ApiError('List should have at most 1000 items', 422));+ }++ return Promise.resolve({+ affected_boards: [`board-${sent[0]}`],+ deleted_images: sent.filter((name) => !name.endsWith('7.png')),+ failed_images: sent.filter((name) => name.endsWith('7.png')),+ });+ };++ beforeEach(() => {+ accountLifecycle.activate('user-a');+ mocks.apiFetchJson.mockReset();+ });++ it('sends 2,500 names as 1,000, 1,000 and 500, in order, and merges the answers', async () => {+ mocks.apiFetchJson.mockImplementation(deleteServer);+ const requested = names(2500);++ const result = await deleteGalleryImages(requested);++ expect(sentNames()).toEqual([requested.slice(0, 1000), requested.slice(1000, 2000), requested.slice(2000)]);+ expect(result).toEqual({+ deletedImageNames: requested.filter((name) => !name.endsWith('7.png')),+ failedImageNames: requested.filter((name) => name.endsWith('7.png')),+ });+ });++ it('sends exactly 1,000 names as one request', async () => {+ mocks.apiFetchJson.mockImplementation(deleteServer);++ await deleteGalleryImages(names(1000));++ expect(sentNames()).toEqual([names(1000)]);+ });++ it('reports the earlier batches’ successes when a later batch fails, and the rest as failed', async () => {+ configureLogging({ ...getLoggingConfig(), level: 'debug' });+ onTestFinished(resetLogging);+ mocks.apiFetchJson+ .mockImplementationOnce(deleteServer)+ .mockRejectedValueOnce(new ApiError('{"detail":"Server error"}', 500));+ const requested = names(2500);++ const result = await deleteGalleryImages(requested);++ // The third batch is never sent, and the cause is kept in the log.+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);+ expect(getLogSnapshot().entries).toContainEqual(+ expect.objectContaining({ level: 'debug', name: 'gallery.batch-request-failed' })+ );+ expect(result).toEqual({+ deletedImageNames: requested.slice(0, 1000).filter((name) => !name.endsWith('7.png')),+ failedImageNames: [+ ...requested.slice(0, 1000).filter((name) => name.endsWith('7.png')),+ ...requested.slice(1000),+ ],+ });+ });++ it('rejects as one request would when the first batch fails', async () => {+ const failure = new ApiError('{"detail":"Server error"}', 500);+ mocks.apiFetchJson.mockRejectedValueOnce(failure);++ await expect(deleteGalleryImages(names(2500))).rejects.toBe(failure);+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);+ });++ it('rejects as one request would when the caller aborts during the first batch', async () => {+ const controller = new AbortController();+ mocks.apiFetchJson.mockImplementationOnce((url: string, init: { body: string }) => {+ controller.abort();+ return deleteServer(url, init);+ });++ await expect(starGalleryImages(names(2500), controller.signal)).rejects.toMatchObject({ name: 'AbortError' });+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);+ });++ it('reports what earlier batches did when the caller aborts later, and sends nothing after', async () => {+ const controller = new AbortController();+ const requested = names(2500);+ mocks.apiFetchJson.mockImplementation((url: string, init: { body: string }) => {+ if (mocks.apiFetchJson.mock.calls.length === 2) {+ controller.abort();+ }+ return deleteServer(url, init);+ });++ const result = await deleteGalleryImages(requested, controller.signal);++ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);+ // The aborted batch's answer is never read, so its names are unconfirmed.+ expect(result).toEqual({+ deletedImageNames: requested.slice(0, 1000).filter((name) => !name.endsWith('7.png')),+ failedImageNames: [+ ...requested.slice(0, 1000).filter((name) => name.endsWith('7.png')),+ ...requested.slice(1000),+ ],+ });+ });++ it('sends no further batch once the account changes', async () => {+ mocks.apiFetchJson.mockImplementationOnce(() => {+ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');+ return Promise.resolve({ affected_boards: [], removed_images: names(1000) });+ });++ await expect(removeImagesFromGalleryBoard(names(2500))).rejects.toThrow('no longer active');+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);+ });++ it('resolves 1,500 images by name in two requests, in the requested order', async () => {+ const requested = names(1500);+ mocks.apiFetchJson.mockImplementation((_url: string, init: { body: string }) =>+ Promise.resolve(+ (JSON.parse(init.body) as { image_names: string[] }).image_names.map((imageName) => ({+ board_id: 'none',+ created_at: '2026-07-09T12:00:00.000Z',+ height: 512,+ image_category: 'general',+ image_name: imageName,+ image_url: `/images/${imageName}`,+ is_intermediate: false,+ thumbnail_url: `/thumbnails/${imageName}`,+ width: 512,+ }))+ )+ );++ const images = await getGalleryImagesByNames(requested);++ expect(sentNames()).toEqual([requested.slice(0, 1000), requested.slice(1000)]);+ expect(images.map((image) => image.imageName)).toEqual(requested);+ });+});+describe('gallery uploads', () => {beforeEach(() => {accountLifecycle.activate('user-a');diff --git a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts b/invokeai/frontend/webv2/src/features/gallery/data/backend.tsindex 1e638536d1..b14c39d99b 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/backend.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/backend.ts@@ -8,12 +8,6 @@ import type {GalleryItemsPage,GalleryVideoItem,} from '@features/gallery/core/items';-import type {- GalleryMediaUsage,- GalleryMediaUsageDocumentKind,- GalleryMediaUsageNames,- GalleryMediaUsageRequest,-} from '@features/gallery/core/mediaUsage';import type { GallerySemanticQuery } from '@features/gallery/core/semanticImageQuery';import type {GalleryBoard,@@ -36,11 +30,13 @@ import {parseGalleryItemKey,} from '@features/gallery/core/items';import { getExternalImageFile, getImageCluster } from '@features/gallery/core/semanticImageQuery';+import { createLogger } from '@platform/logging/logger';import { isTimestampInRange } from '@platform/search/dateTokens';import {AccountScopeExpiredError,assertAccountScopeCurrent,captureAccountScope,+ isAccountScopeCurrent,} from '@platform/state/accountLifecycle';import {absolutizeApiUrl,@@ -58,6 +54,26 @@ type BackendBoardDTO = components['schemas']['BoardDTO'];export { ALL_READABLE_BOARDS_ID, isDateBoardId };+/**+ * The most media names one request body may carry: the server's `MAX_IMAGE_BATCH_SIZE` and `MAX_VIDEO_BATCH_SIZE`+ * (`invokeai/app/api/routers/_limits.py`) refuse a longer list whole. Longer selections go in batches of this size.+ */+export const GALLERY_REQUEST_MAX_NAMES = 1000;++const batchLogger = createLogger({ area: 'batch-requests', namespace: 'gallery' });++/** Distinct names in request order, split into consecutive batches the server accepts. */+export const toNameBatches = (names: readonly string[]): string[][] => {+ const distinct = [...new Set(names)];+ const batches: string[][] = [];++ for (let offset = 0; offset < distinct.length; offset += GALLERY_REQUEST_MAX_NAMES) {+ batches.push(distinct.slice(offset, offset + GALLERY_REQUEST_MAX_NAMES));+ }++ return batches;+};+const getDateFromBoardId = (boardId: string): string => boardId.slice(DATE_BOARD_ID_PREFIX.length);const getUploadBoardId = (boardId: string): string | undefined =>@@ -412,17 +428,32 @@ export const listGalleryDateBoards = async (signal?: AbortSignal): Promise<Galle}));};+/** The DTOs of the named images the caller may read, any number of names, one batch after another. */+const fetchImagesByNames = async (imageNames: readonly string[], signal?: AbortSignal): Promise<BackendImageDTO[]> => {+ const owner = captureAccountScope();+ const images: BackendImageDTO[] = [];++ for (const batch of toNameBatches(imageNames)) {+ signal?.throwIfAborted();+ assertAccountScopeCurrent(owner);+ images.push(+ ...(await apiFetchJson<BackendImageDTO[]>('/api/v1/images/images_by_names', {+ body: JSON.stringify({ image_names: batch }),+ method: 'POST',+ signal,+ }))+ );+ }++ return images;+};+export const getGalleryImagesByNames = async (imageNames: string[], signal?: AbortSignal): Promise<GalleryImage[]> => {if (imageNames.length === 0) {return [];}- const body = await apiFetchJson<BackendImageDTO[]>('/api/v1/images/images_by_names', {- body: JSON.stringify({ image_names: imageNames }),- method: 'POST',- signal,- });-+ const body = await fetchImagesByNames(imageNames, signal);const imagesByName = new Map(body.map((image) => [image.image_name, mapImage(image)]));return imageNames.flatMap((imageName) => {@@ -440,11 +471,7 @@ export const getGalleryImageItemsByNames = async (return [];}- const body = await apiFetchJson<BackendImageDTO[]>('/api/v1/images/images_by_names', {- body: JSON.stringify({ image_names: imageNames }),- method: 'POST',- signal,- });+ const body = await fetchImagesByNames(imageNames, signal);const imagesByName = new Map(body.map((image) => [image.image_name, mapBackendImageToGalleryItem(image)]));return imageNames.flatMap((imageName) => {@@ -1179,116 +1206,13 @@ export const deleteGalleryBoard = async (};};-type GalleryMediaUsageWire = components['schemas']['GalleryMediaUsage'];-type GalleryMediaUsageNamesWire = Pick<- components['schemas']['GalleryMediaUsageQueue'],- 'image_count' | 'image_names' | 'video_count' | 'video_names'->;-type GalleryMediaUsageRequestWire = components['schemas']['GalleryMediaUsageRequest'];--const GALLERY_MEDIA_USAGE_DOCUMENT_KINDS: Readonly<Record<string, GalleryMediaUsageDocumentKind>> = {- legacy_editor: 'legacyEditor',- project: 'project',- quarantined_project: 'quarantinedProject',- workflow: 'workflow',-};--/** A malformed answer must fail the check, never read as "nothing uses it". */-const readUsageCount = (value: unknown, field: string): number => {- if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {- throw new TypeError(`Gallery media usage field "${field}" must be a non-negative integer.`);- }-- return value;-};--const readUsageNames = (value: unknown, field: string): string[] => {- if (!Array.isArray(value) || !value.every((name): name is string => typeof name === 'string')) {- throw new TypeError(`Gallery media usage field "${field}" must be an array of strings.`);- }-- return value;-};--/** A revision is only a hint for narrowing: one that is not a non-negative integer reads as unknown. */-const readUsageRevision = (value: unknown): number | null =>- typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;--const mapGalleryMediaUsageNames = (wire: GalleryMediaUsageNamesWire, field: string): GalleryMediaUsageNames => ({- imageCount: readUsageCount(wire.image_count, `${field}.image_count`),- imageNames: readUsageNames(wire.image_names, `${field}.image_names`),- videoCount: readUsageCount(wire.video_count, `${field}.video_count`),- videoNames: readUsageNames(wire.video_names, `${field}.video_names`),-});--const mapGalleryMediaUsage = (body: GalleryMediaUsageWire): GalleryMediaUsage => {- if (!Array.isArray(body.documents) || typeof body.queue !== 'object' || typeof body.other_accounts !== 'object') {- throw new TypeError('Gallery media usage response is malformed.');- }-- return {- checkedImageCount: readUsageCount(body.checked_image_count, 'checked_image_count'),- checkedVideoCount: readUsageCount(body.checked_video_count, 'checked_video_count'),- documents: body.documents.map((document, index) => ({- ...mapGalleryMediaUsageNames(document, `documents[${index}]`),- id: String(document.id),- // A kind added after this build still uses the media: it is listed, not dropped.- kind: GALLERY_MEDIA_USAGE_DOCUMENT_KINDS[document.kind] ?? 'other',- name: typeof document.name === 'string' && document.name.trim() !== '' ? document.name : null,- revision: readUsageRevision(document.revision),- workspaceRevision: readUsageRevision(document.workspace_revision),- })),- documentsTotal: readUsageCount(body.documents_total, 'documents_total'),- inUseImageCount: readUsageCount(body.in_use_image_count, 'in_use_image_count'),- inUseVideoCount: readUsageCount(body.in_use_video_count, 'in_use_video_count'),- otherAccounts: {- documentCount: readUsageCount(body.other_accounts.document_count, 'other_accounts.document_count'),- imageCount: readUsageCount(body.other_accounts.image_count, 'other_accounts.image_count'),- queueItemCount: readUsageCount(body.other_accounts.queue_item_count, 'other_accounts.queue_item_count'),- videoCount: readUsageCount(body.other_accounts.video_count, 'other_accounts.video_count'),- },- queue: {- ...mapGalleryMediaUsageNames(body.queue, 'queue'),- itemCount: readUsageCount(body.queue.item_count, 'queue.item_count'),- },- };-};--/**- * What still uses these items, or a board's items, per the server: the caller's projects, workflows and legacy editor- * state, their waiting or running queue work, and other accounts' use without identities. Names the caller may not- * delete are left out, as the delete endpoints skip them.- */-export const checkGalleryMediaUsage = async (- request: GalleryMediaUsageRequest,- signal?: AbortSignal-): Promise<GalleryMediaUsage> => {- const owner = captureAccountScope();- const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;- const payload: GalleryMediaUsageRequestWire =- request.kind === 'board'- ? { board_id: request.boardId }- : {- image_names: request.refs.filter((ref) => ref.kind === 'image').map((ref) => ref.name),- video_names: request.refs.filter((ref) => ref.kind === 'video').map((ref) => ref.name),- };- const body = await apiFetchJson<GalleryMediaUsageWire>('/api/v1/gallery/usage', {- body: JSON.stringify(payload),- method: 'POST',- signal: requestSignal,- });-- assertAccountScopeCurrent(owner);-- return mapGalleryMediaUsage(body);-};-export interface GalleryItemOrganizationTransportResult {affectedBoardIds: string[];succeededNames: string[];}-interface GalleryImageDeleteTransportResult extends GalleryItemOrganizationTransportResult {+interface GalleryNameBatchResult extends GalleryItemOrganizationTransportResult {+ /** Names the server reported failing, and every name of a batch that failed or was never sent. */failedNames: string[];}@@ -1347,27 +1271,75 @@ const emptyGalleryItemOrganizationTransportResult = (): GalleryItemOrganizationTsucceededNames: [],});+/**+ * Sends a name-list mutation in batches the server accepts, one at a time (each name costs the server database work),+ * and merges their answers. A batch failing or the caller aborting after earlier batches succeeded ends the run: those+ * earlier items did change, so they are reported, and this batch's and the unsent batches' names are reported failed.+ * A failure or abort before anything succeeded rejects as a single request would. An account change rejects whatever+ * succeeded: the answers belong to an account no longer signed in.+ */+const mutateInNameBatches = async (+ names: readonly string[],+ signal: AbortSignal | undefined,+ send: (batch: string[]) => Promise<GalleryItemOrganizationTransportResult & { failedNames?: string[] }>+): Promise<GalleryNameBatchResult> => {+ const owner = captureAccountScope();+ const batches = toNameBatches(names);+ const affectedBoardIds = new Set<string>();+ const failedNames: string[] = [];+ const succeededNames: string[] = [];++ for (const [index, batch] of batches.entries()) {+ try {+ // Callers fence the last answer themselves; these stop the batches not yet sent.+ signal?.throwIfAborted();+ assertAccountScopeCurrent(owner);+ const result = await send(batch);++ succeededNames.push(...result.succeededNames);+ failedNames.push(...(result.failedNames ?? []));+ result.affectedBoardIds.forEach((boardId) => affectedBoardIds.add(boardId));+ } catch (error: unknown) {+ if (succeededNames.length === 0 || !isAccountScopeCurrent(owner)) {+ throw error;+ }+ // A breadcrumb: the caller reports the partial outcome.+ batchLogger.debug({+ context: { batch: index + 1, batches: batches.length, unconfirmed: batches.slice(index).flat().length },+ error,+ message: 'A gallery batch request failed after earlier batches succeeded',+ name: 'gallery.batch-request-failed',+ });+ failedNames.push(...batches.slice(index).flat());+ break;+ }+ }++ return { affectedBoardIds: [...affectedBoardIds], failedNames, succeededNames };+};+export const isInvalidGalleryBoardDestination = (boardId: string): boolean =>boardId === 'generated' || boardId === 'assets' || isDateBoardId(boardId);-export const addGalleryImageItemsToBoard = async (+export const addGalleryImageItemsToBoard = (boardId: string,imageNames: string[],signal?: AbortSignal): Promise<GalleryItemOrganizationTransportResult> => {- if (boardId === 'none' || isInvalidGalleryBoardDestination(boardId) || imageNames.length === 0) {- return emptyGalleryItemOrganizationTransportResult();+ if (boardId === 'none' || isInvalidGalleryBoardDestination(boardId)) {+ return Promise.resolve(emptyGalleryItemOrganizationTransportResult());}- signal?.throwIfAborted();- const body = await apiFetchJson<unknown>('/api/v1/board_images/batch', {- body: JSON.stringify({ board_id: boardId, image_names: imageNames }),- method: 'POST',- signal,- });- signal?.throwIfAborted();+ return mutateInNameBatches(imageNames, signal, async (batch) => {+ const body = await apiFetchJson<unknown>('/api/v1/board_images/batch', {+ body: JSON.stringify({ board_id: boardId, image_names: batch }),+ method: 'POST',+ signal,+ });+ signal?.throwIfAborted();- return mapGalleryItemOrganizationTransportResult(body, 'added_images');+ return mapGalleryItemOrganizationTransportResult(body, 'added_images');+ });};export const addImagesToGalleryBoard = async (@@ -1376,47 +1348,39 @@ export const addImagesToGalleryBoard = async (signal?: AbortSignal): Promise<string[]> => (await addGalleryImageItemsToBoard(boardId, imageNames, signal)).succeededNames;-export const removeGalleryImageItemsFromBoard = async (+export const removeGalleryImageItemsFromBoard = (imageNames: string[],signal?: AbortSignal-): Promise<GalleryItemOrganizationTransportResult> => {- if (imageNames.length === 0) {- return emptyGalleryItemOrganizationTransportResult();- }+): Promise<GalleryItemOrganizationTransportResult> =>+ mutateInNameBatches(imageNames, signal, async (batch) => {+ const body = await apiFetchJson<unknown>('/api/v1/board_images/batch/delete', {+ body: JSON.stringify({ image_names: batch }),+ method: 'POST',+ signal,+ });+ signal?.throwIfAborted();- signal?.throwIfAborted();- const body = await apiFetchJson<unknown>('/api/v1/board_images/batch/delete', {- body: JSON.stringify({ image_names: imageNames }),- method: 'POST',- signal,+ return mapGalleryItemOrganizationTransportResult(body, 'removed_images');});- signal?.throwIfAborted();-- return mapGalleryItemOrganizationTransportResult(body, 'removed_images');-};export const removeImagesFromGalleryBoard = async (imageNames: string[], signal?: AbortSignal): Promise<string[]> =>(await removeGalleryImageItemsFromBoard(imageNames, signal)).succeededNames;-export const setGalleryImageItemsStarred = async (+export const setGalleryImageItemsStarred = (imageNames: string[],starred: boolean,signal?: AbortSignal-): Promise<GalleryItemOrganizationTransportResult> => {- if (imageNames.length === 0) {- return emptyGalleryItemOrganizationTransportResult();- }+): Promise<GalleryItemOrganizationTransportResult> =>+ mutateInNameBatches(imageNames, signal, async (batch) => {+ const body = await apiFetchJson<unknown>(`/api/v1/images/${starred ? 'star' : 'unstar'}`, {+ body: JSON.stringify({ image_names: batch }),+ method: 'POST',+ signal,+ });+ signal?.throwIfAborted();- signal?.throwIfAborted();- const body = await apiFetchJson<unknown>(`/api/v1/images/${starred ? 'star' : 'unstar'}`, {- body: JSON.stringify({ image_names: imageNames }),- method: 'POST',- signal,+ return mapGalleryItemOrganizationTransportResult(body, starred ? 'starred_images' : 'unstarred_images');});- signal?.throwIfAborted();-- return mapGalleryItemOrganizationTransportResult(body, starred ? 'starred_images' : 'unstarred_images');-};export const starGalleryImages = (imageNames: string[], signal?: AbortSignal): Promise<string[]> =>setGalleryImageItemsStarred(imageNames, true, signal).then((result) => result.succeededNames);@@ -1424,27 +1388,20 @@ export const starGalleryImages = (imageNames: string[], signal?: AbortSignal): Pexport const unstarGalleryImages = (imageNames: string[], signal?: AbortSignal): Promise<string[]> =>setGalleryImageItemsStarred(imageNames, false, signal).then((result) => result.succeededNames);-export const deleteGalleryImageItems = async (- imageNames: string[],- signal?: AbortSignal-): Promise<GalleryImageDeleteTransportResult> => {- if (imageNames.length === 0) {- return { ...emptyGalleryItemOrganizationTransportResult(), failedNames: [] };- }+export const deleteGalleryImageItems = (imageNames: string[], signal?: AbortSignal): Promise<GalleryNameBatchResult> =>+ mutateInNameBatches(imageNames, signal, async (batch) => {+ const body = await apiFetchJson<unknown>('/api/v1/images/delete', {+ body: JSON.stringify({ image_names: batch }),+ method: 'POST',+ signal,+ });+ signal?.throwIfAborted();- signal?.throwIfAborted();- const body = await apiFetchJson<unknown>('/api/v1/images/delete', {- body: JSON.stringify({ image_names: imageNames }),- method: 'POST',- signal,+ return {+ ...mapGalleryItemOrganizationTransportResult(body, 'deleted_images'),+ failedNames: getOptionalStringArray(body, 'failed_images'),+ };});- signal?.throwIfAborted();-- return {- ...mapGalleryItemOrganizationTransportResult(body, 'deleted_images'),- failedNames: getOptionalStringArray(body, 'failed_images'),- };-};/** Deletion can partially succeed. Evict only deletedImageNames; other names may still exist on the server. */export const deleteGalleryImages = async (@@ -1459,26 +1416,22 @@ export const deleteGalleryImages = async (};};-const mutateGalleryVideoItems = async (+const mutateGalleryVideoItems = (videoNames: string[],operation: 'delete' | 'star' | 'unstar',succeededField: 'deleted_videos' | 'starred_videos' | 'unstarred_videos',signal?: AbortSignal-): Promise<GalleryItemOrganizationTransportResult> => {- if (videoNames.length === 0) {- return emptyGalleryItemOrganizationTransportResult();- }+): Promise<GalleryItemOrganizationTransportResult> =>+ mutateInNameBatches(videoNames, signal, async (batch) => {+ const body = await apiFetchJson<unknown>(`/api/v1/videos/${operation}`, {+ body: JSON.stringify({ video_names: batch }),+ method: 'POST',+ signal,+ });+ signal?.throwIfAborted();- signal?.throwIfAborted();- const body = await apiFetchJson<unknown>(`/api/v1/videos/${operation}`, {- body: JSON.stringify({ video_names: videoNames }),- method: 'POST',- signal,+ return mapGalleryVideoOrganizationTransportResult(body, succeededField);});- signal?.throwIfAborted();-- return mapGalleryVideoOrganizationTransportResult(body, succeededField);-};export const deleteGalleryVideoItems = (videoNames: string[],diff --git a/invokeai/frontend/webv2/src/features/gallery/data/mediaUsage.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/mediaUsage.test.tsnew file mode 100644index 0000000000..53dd3f6623--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/data/mediaUsage.test.ts@@ -0,0 +1,365 @@+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ apiFetchJson: vi.fn() }));++vi.mock('@platform/transport/http', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ apiFetchJson: mocks.apiFetchJson,+}));++import { checkGalleryMediaUsage } from './mediaUsage';++describe('checkGalleryMediaUsage', () => {+ const usageBody = (overrides: Record<string, unknown> = {}) => ({+ checked_image_count: 2,+ checked_video_count: 1,+ documents: [+ {+ id: 'legacy_editor',+ image_count: 1,+ image_names: ['a.png'],+ kind: 'legacy_editor',+ name: null,+ revision: null,+ video_count: 0,+ video_names: [],+ workspace_revision: null,+ },+ {+ id: 'project-1',+ image_count: 1200,+ image_names: ['a.png', 'b.png'],+ kind: 'project',+ name: 'Harbor Tower',+ revision: 7,+ video_count: 1,+ video_names: ['c.mp4'],+ workspace_revision: 3,+ },+ {+ id: 'later-kind',+ image_count: 1,+ image_names: ['b.png'],+ kind: 'storyboard',+ name: ' ',+ // Revisions are only a hint: a malformed one reads as unknown rather than failing the check.+ revision: '2',+ video_count: 0,+ video_names: [],+ workspace_revision: -1,+ },+ ],+ documents_total: 140,+ in_use_image_count: 2,+ in_use_video_count: 1,+ other_accounts: { document_count: 3, image_count: 1, queue_item_count: 2, video_count: 0 },+ queue: { image_count: 1, image_names: ['a.png'], item_count: 2, video_count: 0, video_names: [] },+ ...overrides,+ });++ beforeEach(() => {+ accountLifecycle.activate('user-a');+ mocks.apiFetchJson.mockReset();+ });++ it('asks about the items by kind, or about a whole board, and maps the answer', async () => {+ mocks.apiFetchJson.mockResolvedValue(usageBody());++ const usage = await checkGalleryMediaUsage({+ kind: 'items',+ refs: [+ { kind: 'image', name: 'a.png' },+ { kind: 'video', name: 'c.mp4' },+ { kind: 'image', name: 'b.png' },+ ],+ });+ await checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' });++ expect(JSON.parse(String(mocks.apiFetchJson.mock.calls[0]?.[1]?.body))).toEqual({+ image_names: ['a.png', 'b.png'],+ video_names: ['c.mp4'],+ });+ expect(mocks.apiFetchJson.mock.calls[0]?.[0]).toBe('/api/v1/gallery/usage');+ expect(mocks.apiFetchJson.mock.calls[0]?.[1]?.method).toBe('POST');+ expect(JSON.parse(String(mocks.apiFetchJson.mock.calls[1]?.[1]?.body))).toEqual({ board_id: 'board-1' });+ expect(usage).toEqual({+ checkedImageCount: 2,+ checkedVideoCount: 1,+ documents: [+ {+ id: 'legacy_editor',+ imageCount: 1,+ imageNames: ['a.png'],+ kind: 'legacyEditor',+ name: null,+ revision: null,+ videoCount: 0,+ videoNames: [],+ workspaceRevision: null,+ },+ {+ id: 'project-1',+ imageCount: 1200,+ imageNames: ['a.png', 'b.png'],+ kind: 'project',+ name: 'Harbor Tower',+ revision: 7,+ videoCount: 1,+ videoNames: ['c.mp4'],+ workspaceRevision: 3,+ },+ // A kind this build does not know still uses the media; a blank name reads as none.+ {+ id: 'later-kind',+ imageCount: 1,+ imageNames: ['b.png'],+ kind: 'other',+ name: null,+ revision: null,+ videoCount: 0,+ videoNames: [],+ workspaceRevision: null,+ },+ ],+ documentsTotal: 140,+ inUseImageCount: 2,+ inUseVideoCount: 1,+ otherAccounts: { documentCount: 3, imageCount: 1, queueItemCount: 2, videoCount: 0 },+ queue: { imageCount: 1, imageNames: ['a.png'], itemCount: 2, videoCount: 0, videoNames: [] },+ });+ });++ it('fails on a malformed answer rather than reading it as nothing in use', async () => {+ mocks.apiFetchJson.mockResolvedValue(usageBody({ in_use_image_count: undefined }));++ await expect(checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' })).rejects.toThrow(TypeError);+ });++ it('drops an answer that arrives after the account changed', async () => {+ let answer: (value: unknown) => void = () => {};+ mocks.apiFetchJson.mockReturnValue(+ new Promise((resolve) => {+ answer = resolve;+ })+ );++ const check = checkGalleryMediaUsage({ boardId: 'board-1', kind: 'board' });+ const signal = mocks.apiFetchJson.mock.calls[0]?.[1]?.signal as AbortSignal;++ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');+ answer(usageBody());++ await expect(check).rejects.toThrow('no longer active');+ expect(signal.aborted).toBe(true);+ });++ describe('past one request’s cap', () => {+ const names = (prefix: string, count: number) => Array.from({ length: count }, (_, index) => `${prefix}-${index}`);+ const document = (kind: string, id: string, imageNames: string[], revision: number | null = null) => ({+ id,+ image_count: imageNames.length,+ image_names: imageNames,+ kind,+ name: id,+ revision,+ video_count: 0,+ video_names: [],+ workspace_revision: revision === null ? null : 3,+ });+ const refs = [+ ...names('img', 1500).map((name) => ({ kind: 'image' as const, name })),+ ...names('clip', 200).map((name) => ({ kind: 'video' as const, name })),+ ];++ it('asks in batches of at most the cap per kind, one after another, and merges the answers', async () => {+ mocks.apiFetchJson+ .mockResolvedValueOnce(+ usageBody({+ checked_image_count: 1000,+ checked_video_count: 200,+ // A third document past the listing cap.+ documents: [document('workflow', 'wf-1', ['img-2']), document('project', 'project-1', ['img-1'], 7)],+ documents_total: 3,+ in_use_image_count: 2,+ in_use_video_count: 0,+ other_accounts: { document_count: 1, image_count: 1, queue_item_count: 0, video_count: 0 },+ queue: { image_count: 1, image_names: ['img-3'], item_count: 2, video_count: 0, video_names: [] },+ })+ )+ .mockResolvedValueOnce(+ usageBody({+ checked_image_count: 500,+ checked_video_count: 0,+ // Saved between the two requests: its revisions no longer describe all of its names.+ documents: [document('project', 'project-1', ['img-1200'], 8)],+ documents_total: 1,+ in_use_image_count: 1,+ in_use_video_count: 0,+ other_accounts: { document_count: 1, image_count: 1, queue_item_count: 1, video_count: 0 },+ queue: { image_count: 1, image_names: ['img-1100'], item_count: 1, video_count: 0, video_names: [] },+ })+ );++ const usage = await checkGalleryMediaUsage({ kind: 'items', refs });++ expect(mocks.apiFetchJson.mock.calls.map(([, init]) => JSON.parse(String(init.body)))).toEqual([+ { image_names: names('img', 1500).slice(0, 1000), video_names: names('clip', 200) },+ { image_names: names('img', 1500).slice(1000), video_names: [] },+ ]);+ expect(usage).toEqual({+ checkedImageCount: 1500,+ checkedVideoCount: 200,+ documents: [+ {+ id: 'project-1',+ imageCount: 2,+ imageNames: ['img-1', 'img-1200'],+ kind: 'project',+ name: 'project-1',+ revision: null,+ videoCount: 0,+ videoNames: [],+ workspaceRevision: null,+ },+ {+ id: 'wf-1',+ imageCount: 1,+ imageNames: ['img-2'],+ kind: 'workflow',+ name: 'wf-1',+ revision: null,+ videoCount: 0,+ videoNames: [],+ workspaceRevision: null,+ },+ ],+ documentsTotal: 3,+ inUseImageCount: 3,+ inUseVideoCount: 0,+ // Jobs and other accounts' documents are counted once per batch that found them: never fewer than there are.+ otherAccounts: { documentCount: 2, imageCount: 2, queueItemCount: 1, videoCount: 0 },+ queue: { imageCount: 2, imageNames: ['img-3', 'img-1100'], itemCount: 3, videoCount: 0, videoNames: [] },+ });+ });++ it('marks a document one batch left out past its listing cap as naming only some of its uses', async () => {+ const images = names('img', 2000).map((name) => ({ kind: 'image' as const, name }));+ // Project X uses 500 images of the first batch, but that batch names only the first 100 of its 150 documents.+ const listedFirst = Array.from({ length: 100 }, (_, index) => document('workflow', `wf-${index}`, ['img-1']));+ mocks.apiFetchJson+ .mockResolvedValueOnce(usageBody({ documents: listedFirst, documents_total: 150 }))+ .mockResolvedValueOnce(+ usageBody({+ documents: [+ document('project', 'project-x', ['img-1001', 'img-1002', 'img-1003'], 9),+ // Only this batch found it, and no batch hid anything from it but the first, which lists it.+ document('workflow', 'wf-0', ['img-1500']),+ ],+ documents_total: 2,+ })+ );++ const usage = await checkGalleryMediaUsage({ kind: 'items', refs: images });++ expect(usage.documents.find((entry) => entry.id === 'project-x')).toEqual({+ id: 'project-x',+ imageCount: 3,+ imageNames: ['img-1001', 'img-1002', 'img-1003'],+ kind: 'project',+ name: 'project-x',+ namesIncomplete: true,+ revision: null,+ videoCount: 0,+ videoNames: [],+ workspaceRevision: null,+ });+ expect(usage.documents.find((entry) => entry.id === 'wf-0')).toMatchObject({+ imageCount: 2,+ imageNames: ['img-1', 'img-1500'],+ });+ expect(usage.documents.find((entry) => entry.id === 'wf-0')).not.toHaveProperty('namesIncomplete');+ // The first batch's 50 unlisted documents are counted as further documents.+ expect(usage.documentsTotal).toBe(101 + 50);+ });++ it('keeps revisions every batch agrees on, and a document only one batch found as it was found', async () => {+ mocks.apiFetchJson+ .mockResolvedValueOnce(+ usageBody({ documents: [document('project', 'same', ['img-1'], 7)], documents_total: 1 })+ )+ .mockResolvedValueOnce(+ usageBody({+ documents: [document('project', 'same', ['img-1001'], 7), document('project', 'late', ['img-1002'], 4)],+ documents_total: 2,+ })+ );++ const usage = await checkGalleryMediaUsage({ kind: 'items', refs });++ expect(+ usage.documents.map(({ id, imageNames, revision, workspaceRevision }) => ({+ id,+ imageNames,+ revision,+ workspaceRevision,+ }))+ ).toEqual([+ { id: 'late', imageNames: ['img-1002'], revision: 4, workspaceRevision: 3 },+ { id: 'same', imageNames: ['img-1', 'img-1001'], revision: 7, workspaceRevision: 3 },+ ]);+ });++ it('keeps documents of different unknown kinds with the same id apart', async () => {+ mocks.apiFetchJson+ .mockResolvedValueOnce(+ usageBody({ documents: [document('storyboard', 'shared-id', ['img-1'])], documents_total: 1 })+ )+ .mockResolvedValueOnce(+ usageBody({ documents: [document('moodboard', 'shared-id', ['img-1001'])], documents_total: 1 })+ );++ const usage = await checkGalleryMediaUsage({ kind: 'items', refs });++ expect(usage.documents.map(({ imageNames, kind }) => ({ imageNames, kind }))).toEqual([+ { imageNames: ['img-1'], kind: 'other' },+ { imageNames: ['img-1001'], kind: 'other' },+ ]);+ });++ it('fails the whole check when a later batch fails', async () => {+ mocks.apiFetchJson+ .mockResolvedValueOnce(usageBody())+ .mockRejectedValueOnce(new ApiError('{"detail":"Server error"}', 500));++ await expect(checkGalleryMediaUsage({ kind: 'items', refs })).rejects.toBeInstanceOf(ApiError);+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);+ });++ it('asks no further once the caller aborts between batches', async () => {+ const controller = new AbortController();+ mocks.apiFetchJson.mockImplementationOnce(() => {+ controller.abort();+ return Promise.resolve(usageBody());+ });++ await expect(checkGalleryMediaUsage({ kind: 'items', refs }, controller.signal)).rejects.toMatchObject({+ name: 'AbortError',+ });+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);+ });++ it('asks no further once the account changes between batches', async () => {+ mocks.apiFetchJson.mockImplementationOnce(() => {+ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');+ return Promise.resolve(usageBody());+ });++ await expect(checkGalleryMediaUsage({ kind: 'items', refs })).rejects.toThrow('no longer active');+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/data/mediaUsage.ts b/invokeai/frontend/webv2/src/features/gallery/data/mediaUsage.tsnew file mode 100644index 0000000000..a9b7690961--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/data/mediaUsage.ts@@ -0,0 +1,227 @@+/**+ * The server's media usage check (`POST /api/v1/gallery/usage`), loaded only by the deletion dialogs. A request names+ * at most the server's per-kind cap, so a larger selection is checked in batches whose answers merge into one.+ */++import type { components } from '@api/schema';+import type {+ GalleryMediaUsage,+ GalleryMediaUsageDocument,+ GalleryMediaUsageDocumentKind,+ GalleryMediaUsageNames,+ GalleryMediaUsageRequest,+} from '@features/gallery/core/mediaUsage';++import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';+import { apiFetchJson } from '@platform/transport/http';++import { toNameBatches } from './backend';++type GalleryMediaUsageWire = components['schemas']['GalleryMediaUsage'];+type GalleryMediaUsageNamesWire = Pick<+ components['schemas']['GalleryMediaUsageQueue'],+ 'image_count' | 'image_names' | 'video_count' | 'video_names'+>;+type GalleryMediaUsageRequestWire = components['schemas']['GalleryMediaUsageRequest'];++const GALLERY_MEDIA_USAGE_DOCUMENT_KINDS: Readonly<Record<string, GalleryMediaUsageDocumentKind>> = {+ legacy_editor: 'legacyEditor',+ project: 'project',+ quarantined_project: 'quarantinedProject',+ workflow: 'workflow',+};++/** A malformed answer must fail the check, never read as "nothing uses it". */+const readUsageCount = (value: unknown, field: string): number => {+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {+ throw new TypeError(`Gallery media usage field "${field}" must be a non-negative integer.`);+ }++ return value;+};++const readUsageNames = (value: unknown, field: string): string[] => {+ if (!Array.isArray(value) || !value.every((name): name is string => typeof name === 'string')) {+ throw new TypeError(`Gallery media usage field "${field}" must be an array of strings.`);+ }++ return value;+};++/** A revision is only a hint for narrowing: one that is not a non-negative integer reads as unknown. */+const readUsageRevision = (value: unknown): number | null =>+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;++const mapGalleryMediaUsageNames = (wire: GalleryMediaUsageNamesWire, field: string): GalleryMediaUsageNames => ({+ imageCount: readUsageCount(wire.image_count, `${field}.image_count`),+ imageNames: readUsageNames(wire.image_names, `${field}.image_names`),+ videoCount: readUsageCount(wire.video_count, `${field}.video_count`),+ videoNames: readUsageNames(wire.video_names, `${field}.video_names`),+});++const mapGalleryMediaUsage = (body: GalleryMediaUsageWire): GalleryMediaUsage => {+ if (!Array.isArray(body.documents) || typeof body.queue !== 'object' || typeof body.other_accounts !== 'object') {+ throw new TypeError('Gallery media usage response is malformed.');+ }++ return {+ checkedImageCount: readUsageCount(body.checked_image_count, 'checked_image_count'),+ checkedVideoCount: readUsageCount(body.checked_video_count, 'checked_video_count'),+ documents: body.documents.map((document, index) => ({+ ...mapGalleryMediaUsageNames(document, `documents[${index}]`),+ id: String(document.id),+ // A kind added after this build still uses the media: it is listed, not dropped.+ kind: GALLERY_MEDIA_USAGE_DOCUMENT_KINDS[document.kind] ?? 'other',+ name: typeof document.name === 'string' && document.name.trim() !== '' ? document.name : null,+ revision: readUsageRevision(document.revision),+ workspaceRevision: readUsageRevision(document.workspace_revision),+ })),+ documentsTotal: readUsageCount(body.documents_total, 'documents_total'),+ inUseImageCount: readUsageCount(body.in_use_image_count, 'in_use_image_count'),+ inUseVideoCount: readUsageCount(body.in_use_video_count, 'in_use_video_count'),+ otherAccounts: {+ documentCount: readUsageCount(body.other_accounts.document_count, 'other_accounts.document_count'),+ imageCount: readUsageCount(body.other_accounts.image_count, 'other_accounts.image_count'),+ queueItemCount: readUsageCount(body.other_accounts.queue_item_count, 'other_accounts.queue_item_count'),+ videoCount: readUsageCount(body.other_accounts.video_count, 'other_accounts.video_count'),+ },+ queue: {+ ...mapGalleryMediaUsageNames(body.queue, 'queue'),+ itemCount: readUsageCount(body.queue.item_count, 'queue.item_count'),+ },+ };+};++const byDocumentOrder = (left: GalleryMediaUsageDocument, right: GalleryMediaUsageDocument): number =>+ left.kind.localeCompare(right.kind) ||+ (left.name ?? '').toLowerCase().localeCompare((right.name ?? '').toLowerCase()) ||+ left.id.localeCompare(right.id);++/** One batch's answer, and each listed document's identity as the server sent it (`kind:id`, kind unmapped). */+interface BatchAnswer {+ documentKeys: readonly string[];+ usage: GalleryMediaUsage;+}++/**+ * One answer for a check sent in batches. The batches check disjoint names, so name lists join and per-name counts+ * add. A document merges by the server's kind and id, keeping its revisions only when every batch that listed it read+ * the same ones (a save between batches leaves them unknown, so the host reads the server's copy). A batch past the+ * server's document listing cap may have left out a document another batch lists: such a document is marked+ * `namesIncomplete`, its revisions unknown. Counts that cannot be deduplicated across batches err high: documents a+ * batch left unlisted each count as another, and a job or another account's document naming media of several+ * batches counts once per batch.+ */+const mergeGalleryMediaUsage = (answers: readonly BatchAnswer[]): GalleryMediaUsage => {+ const documents = new Map<string, { batches: Set<number>; document: GalleryMediaUsageDocument }>();+ const overflowedBatches: number[] = [];+ let unlistedDocuments = 0;++ answers.forEach(({ documentKeys, usage }, batch) => {+ const unlisted = usage.documentsTotal - usage.documents.length;++ if (unlisted > 0) {+ overflowedBatches.push(batch);+ unlistedDocuments += unlisted;+ }+ usage.documents.forEach((document, index) => {+ const key = documentKeys[index]!;+ const entry = documents.get(key);++ if (!entry) {+ documents.set(key, {+ batches: new Set([batch]),+ document: { ...document, imageNames: [...document.imageNames], videoNames: [...document.videoNames] },+ });+ return;+ }++ const merged = entry.document;++ entry.batches.add(batch);+ merged.imageCount += document.imageCount;+ merged.imageNames.push(...document.imageNames);+ merged.videoCount += document.videoCount;+ merged.videoNames.push(...document.videoNames);+ merged.name ??= document.name;+ if (merged.revision !== document.revision || merged.workspaceRevision !== document.workspaceRevision) {+ merged.revision = null;+ merged.workspaceRevision = null;+ }+ });+ });++ const listed = [...documents.values()]+ .map(({ batches, document }) =>+ overflowedBatches.some((batch) => !batches.has(batch))+ ? { ...document, namesIncomplete: true as const, revision: null, workspaceRevision: null }+ : document+ )+ .sort(byDocumentOrder);+ const sum = (read: (usage: GalleryMediaUsage) => number) =>+ answers.reduce((total, { usage }) => total + read(usage), 0);++ return {+ checkedImageCount: sum((usage) => usage.checkedImageCount),+ checkedVideoCount: sum((usage) => usage.checkedVideoCount),+ documents: listed,+ documentsTotal: listed.length + unlistedDocuments,+ inUseImageCount: sum((usage) => usage.inUseImageCount),+ inUseVideoCount: sum((usage) => usage.inUseVideoCount),+ otherAccounts: {+ documentCount: sum((usage) => usage.otherAccounts.documentCount),+ imageCount: sum((usage) => usage.otherAccounts.imageCount),+ queueItemCount: sum((usage) => usage.otherAccounts.queueItemCount),+ videoCount: sum((usage) => usage.otherAccounts.videoCount),+ },+ queue: {+ imageCount: sum((usage) => usage.queue.imageCount),+ imageNames: answers.flatMap(({ usage }) => usage.queue.imageNames),+ itemCount: sum((usage) => usage.queue.itemCount),+ videoCount: sum((usage) => usage.queue.videoCount),+ videoNames: answers.flatMap(({ usage }) => usage.queue.videoNames),+ },+ };+};++/**+ * What still uses these items, or a board's items, per the server: the caller's projects, workflows and legacy editor+ * state, their waiting or running queue work, and other accounts' use without identities. Names the caller may not+ * delete are left out, as the delete endpoints skip them. Items past one request's cap are checked in batches, one+ * after another; any batch failing fails the check.+ */+export const checkGalleryMediaUsage = async (+ request: GalleryMediaUsageRequest,+ signal?: AbortSignal+): Promise<GalleryMediaUsage> => {+ const owner = captureAccountScope();+ const requestSignal = signal ? AbortSignal.any([signal, owner.signal]) : owner.signal;+ const ask = async (payload: GalleryMediaUsageRequestWire): Promise<BatchAnswer> => {+ requestSignal.throwIfAborted();+ const body = await apiFetchJson<GalleryMediaUsageWire>('/api/v1/gallery/usage', {+ body: JSON.stringify(payload),+ method: 'POST',+ signal: requestSignal,+ });++ assertAccountScopeCurrent(owner);+ const usage = mapGalleryMediaUsage(body);++ return { documentKeys: body.documents.map((document) => `${document.kind}:${document.id}`), usage };+ };++ if (request.kind === 'board') {+ return (await ask({ board_id: request.boardId })).usage;+ }++ const imageBatches = toNameBatches(request.refs.filter((ref) => ref.kind === 'image').map((ref) => ref.name));+ const videoBatches = toNameBatches(request.refs.filter((ref) => ref.kind === 'video').map((ref) => ref.name));+ const answers: BatchAnswer[] = [];++ // At least one request: an empty selection is still answered by the server.+ for (let index = 0; index < Math.max(1, imageBatches.length, videoBatches.length); index += 1) {+ answers.push(await ask({ image_names: imageBatches[index] ?? [], video_names: videoBatches[index] ?? [] }));+ }++ return answers.length === 1 ? answers[0]!.usage : mergeGalleryMediaUsage(answers);+};diff --git a/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts b/invokeai/frontend/webv2/src/features/gallery/data/organization.test.tsindex e8f5c12ee6..78ae21016d 100644--- a/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/data/organization.test.ts@@ -549,6 +549,126 @@ describe('galleryItemOrganization transport and confirmed outcomes', () => {);});+describe('galleryItemOrganization past the server’s per-request name cap', () => {+ // As the server answers: a body naming more than 1,000 items is refused whole, before any item is touched.+ const SERVER_MAX_NAMES = 1000;+ const fields: Record<string, string> = {+ '/api/v1/board_images/batch': 'added_images',+ '/api/v1/board_images/batch/delete': 'removed_images',+ '/api/v1/images/delete': 'deleted_images',+ '/api/v1/images/star': 'starred_images',+ '/api/v1/images/unstar': 'unstarred_images',+ '/api/v1/videos/delete': 'deleted_videos',+ '/api/v1/videos/star': 'starred_videos',+ '/api/v1/videos/unstar': 'unstarred_videos',+ };+ const serve = (url: string, init: { body: string }) => {+ const body = JSON.parse(init.body) as { image_names?: string[]; video_names?: string[] };+ const names = body.image_names ?? body.video_names ?? [];++ if (names.length > SERVER_MAX_NAMES) {+ return Promise.reject(new MockApiError('List should have at most 1000 items', 422));+ }++ return Promise.resolve({ affected_boards: ['board-1'], failed_videos: [], [fields[url]!]: names });+ };+ const refs = (kind: 'image' | 'video', count: number): GalleryItemRef[] =>+ Array.from({ length: count }, (_, index) => ({ kind, name: `${kind}-${index}` }));+ const names = (items: readonly GalleryItemRef[]) => items.map((item) => item.name);+ /** The name lists sent to one endpoint, in the order sent. */+ const sentTo = (endpoint: string): string[][] =>+ mocks.apiFetchJson.mock.calls+ .filter(([url]) => url === endpoint)+ .map(([, init]) => Object.values(JSON.parse(String(init.body)) as Record<string, string[]>)[0]!);++ beforeEach(() => {+ accountLifecycle.activate('organization-test-user');+ mocks.apiFetchJson.mockReset();+ mocks.apiFetchJson.mockImplementation(serve);+ });++ it('deletes every item of a selection larger than one request may name', async () => {+ const selection = [...refs('image', 1500), ...refs('video', 1200)];++ const result = await galleryItemOrganization.delete(selection);++ expect(result).toEqual({ affectedBoardIds: ['board-1'], failed: [], succeeded: selection });+ expect(sentTo('/api/v1/images/delete')).toEqual([+ names(refs('image', 1500).slice(0, 1000)),+ names(refs('image', 1500).slice(1000)),+ ]);+ expect(sentTo('/api/v1/videos/delete')).toEqual([+ names(refs('video', 1200).slice(0, 1000)),+ names(refs('video', 1200).slice(1000)),+ ]);+ });++ it('sends 1,000 items of a kind in one request and 1,001 in two', async () => {+ await galleryItemOrganization.delete(refs('image', 1000));+ await galleryItemOrganization.delete(refs('video', 1001));++ expect(sentTo('/api/v1/images/delete').map((batch) => batch.length)).toEqual([1000]);+ expect(sentTo('/api/v1/videos/delete').map((batch) => batch.length)).toEqual([1000, 1]);+ });++ it('sends a repeated item once, whichever batch it would fall in', async () => {+ const selection = [...refs('image', 1200), ...refs('image', 1200)];++ const result = await galleryItemOrganization.delete(selection);++ expect(sentTo('/api/v1/images/delete').map((batch) => batch.length)).toEqual([1000, 200]);+ expect(new Set(sentTo('/api/v1/images/delete').flat()).size).toBe(1200);+ expect(result).toEqual({ affectedBoardIds: ['board-1'], failed: [], succeeded: refs('image', 1200) });+ });++ it('confirms what earlier batches deleted when a later one fails, for images and videos alike', async () => {+ mocks.apiFetchJson.mockImplementation((url: string, init: { body: string }) =>+ sentTo(url).length === 2 ? Promise.reject(new MockApiError('Server error', 500)) : serve(url, init)+ );+ const images = refs('image', 2500);+ const videos = refs('video', 2500);++ const result = await galleryItemOrganization.delete([...images, ...videos]);++ expect(result).toEqual({+ affectedBoardIds: ['board-1'],+ failed: [...images.slice(1000), ...videos.slice(1000)],+ succeeded: [...images.slice(0, 1000), ...videos.slice(0, 1000)],+ });+ // Nothing is sent after a failed batch.+ expect(sentTo('/api/v1/images/delete')).toHaveLength(2);+ expect(sentTo('/api/v1/videos/delete')).toHaveLength(2);+ });++ it('stops and confirms nothing once the account changes mid-run', async () => {+ mocks.apiFetchJson.mockImplementation((url: string, init: { body: string }) => {+ if (mocks.apiFetchJson.mock.calls.length === 1) {+ accountLifecycle.activate('replacement-user');+ }+ return serve(url, init);+ });+ const images = refs('image', 2500);++ const result = await galleryItemOrganization.delete(images);++ expect(result).toEqual({ affectedBoardIds: [], failed: images, succeeded: [] });+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['star', () => galleryItemOrganization.setStarred(refs('image', 2500), true)],+ ['unstar', () => galleryItemOrganization.setStarred(refs('image', 2500), false)],+ ['move to a board', () => galleryItemOrganization.moveToBoard(refs('image', 2500), 'board-1')],+ ['remove from its board', () => galleryItemOrganization.moveToBoard(refs('image', 2500), 'none')],+ ])('confirms every image when asked to %s 2,500 at once', async (_operation, run) => {+ const result = await run();++ expect(result.failed).toEqual([]);+ expect(result.succeeded).toEqual(refs('image', 2500));+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(3);+ });+});+describe('isGalleryBoardAttachable', () => {it.each(['by_date:2026-08-14', 'generated', 'assets', 'none'])('rejects the virtual destination %s', (boardId) => {expect(isGalleryBoardAttachable(boardId)).toBe(false);diff --git a/invokeai/frontend/webv2/src/features/gallery/data/uploadDestination.ts b/invokeai/frontend/webv2/src/features/gallery/data/uploadDestination.tsnew file mode 100644index 0000000000..7e4cc4c1f1--- /dev/null+++ b/invokeai/frontend/webv2/src/features/gallery/data/uploadDestination.ts@@ -0,0 +1,19 @@+import type { QueryClient } from '@tanstack/react-query';++import { getGalleryAutoAddBoardId } from '@features/gallery/ui/galleryStateView';++import { canAddToCachedGalleryBoard, ensureGalleryBoardDestinations } from './queryCache';++/**+ * Where media uploaded from outside the Gallery lands, such as a file dropped on Canvas or Preview: the project's+ * auto-add board, as generation results do, judged from the listing of every readable board, which is read first+ * when none is cached; Uncategorized when no board takes it. An auto-add board is never redirected for want of a+ * listing.+ */+export const resolveGalleryUploadBoardId = async (+ galleryValues: Record<string, unknown>,+ client: QueryClient+): Promise<string> => {+ await ensureGalleryBoardDestinations(client);+ return getGalleryAutoAddBoardId(galleryValues, (boardId) => canAddToCachedGalleryBoard(boardId, client)) ?? 'none';+};diff --git a/invokeai/frontend/webv2/src/features/gallery/index.ts b/invokeai/frontend/webv2/src/features/gallery/index.tsindex 1547d60865..b2e53c73b4 100644--- a/invokeai/frontend/webv2/src/features/gallery/index.ts+++ b/invokeai/frontend/webv2/src/features/gallery/index.ts@@ -66,6 +66,9 @@ import {uploadGalleryVideo,} from './data/backend';+/** The most media names one gallery request may carry; the gallery's own transports batch past it. */+export { GALLERY_REQUEST_MAX_NAMES } from './data/backend';+/** Resolve backend Gallery images without exposing transport DTOs or endpoints. */export const galleryImages = {metadata: getGalleryImageMetadata,diff --git a/invokeai/frontend/webv2/src/features/gallery/mediaUsage.ts b/invokeai/frontend/webv2/src/features/gallery/mediaUsage.tsindex bec08cdf33..b858e46899 100644--- a/invokeai/frontend/webv2/src/features/gallery/mediaUsage.ts+++ b/invokeai/frontend/webv2/src/features/gallery/mediaUsage.ts@@ -11,4 +11,5 @@ export {type GalleryMediaUsageSurface,type GalleryMediaUsageSurfaceRow,} from './core/mediaUsage';-export { checkGalleryMediaUsage } from './data/backend';+export { GALLERY_REQUEST_MAX_NAMES } from './data/backend';+export { checkGalleryMediaUsage } from './data/mediaUsage';diff --git a/invokeai/frontend/webv2/src/features/gallery/picker.ts b/invokeai/frontend/webv2/src/features/gallery/picker.tsindex b8d4bed277..d08901667e 100644--- a/invokeai/frontend/webv2/src/features/gallery/picker.ts+++ b/invokeai/frontend/webv2/src/features/gallery/picker.ts@@ -8,4 +8,4 @@ export {export { GalleryPickerPopover, type GalleryPickerPopoverProps } from './ui/picker/GalleryPickerPopover';export type { GalleryPickerOpeningScope } from './ui/picker/useGalleryPickerScope';export { GalleryHostProvider, type GalleryHost } from './ui/GalleryUiContext';-export { useGalleryUploadAction } from './ui/useGalleryUploadAction';+export { uploadGalleryFiles, useGalleryUploadAction } from './ui/useGalleryUploadAction';diff --git a/invokeai/frontend/webv2/src/features/gallery/queries.ts b/invokeai/frontend/webv2/src/features/gallery/queries.tsindex f71ce60fb5..aa2c0e7e23 100644--- a/invokeai/frontend/webv2/src/features/gallery/queries.ts+++ b/invokeai/frontend/webv2/src/features/gallery/queries.ts@@ -54,4 +54,5 @@ export {} from './data/queryCache';export type { GalleryItemCachePatch } from './data/queryCache';export { createGalleryRealtimeRuntime } from './data/realtimeRuntime';+export { resolveGalleryUploadBoardId } from './data/uploadDestination';export { galleryBoardExists } from './data/backend';diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsxindex 6317052f41..5d5cae8aaf 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardFilters.tsx@@ -165,7 +165,7 @@ const BoardVisibilityItem = ({value: string;}) => (<Menu.Item aria-checked={isChecked} closeOnSelect={false} role="menuitemcheckbox" value={value} onClick={onSelect}>- <Icon as={CheckIcon} boxSize="3" opacity={isChecked ? 1 : 0} />+ <Icon as={CheckIcon} boxSize="3" color="fg" opacity={isChecked ? 1 : 0} /><Icon as={icon} boxSize="3.5" color="fg.subtle" /><Menu.ItemText>{label}</Menu.ItemText></Menu.Item>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsxindex 2b6cb47d04..2486a3b13f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardMenu.tsx@@ -418,14 +418,7 @@ const BoardDeleteDialog = ({return (// Cancel takes focus, not the checkbox that would delete the media.- // Top-anchored: the usage report arrives after the dialog opens, and grows it downward instead of moving it.- <Dialog.Root- initialFocusEl={getInitialFocus}- open={board !== null}- placement="top"- role="alertdialog"- onOpenChange={onOpenChange}- >+ <Dialog.Root initialFocusEl={getInitialFocus} open={board !== null} role="alertdialog" onOpenChange={onOpenChange}><Portal><Dialog.Backdrop /><Dialog.Positioner>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsxindex c2a789ce68..7391963b68 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRow.tsx@@ -10,7 +10,7 @@ import { formatGalleryMediaCounts } from '@features/gallery/core/mediaCounts';import { IconButton } from '@platform/ui/Button';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { Tooltip } from '@platform/ui/Tooltip';-import { LocateIcon, MoreVerticalIcon } from 'lucide-react';+import { MoreVerticalIcon, SquareArrowDownIcon } from 'lucide-react';import { useCallback, useMemo, type MouseEvent, type PointerEvent } from 'react';import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';@@ -280,7 +280,7 @@ export const GalleryBoardRow = ({><Iconaria-label={t('widgets.gallery.autoAddTarget')}- as={LocateIcon}+ as={SquareArrowDownIcon}boxSize="3.5"color={isSelected ? 'inherit' : 'accent.fg'}flexShrink={0}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsxindex 6070674f73..28e9671392 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryBoardRowShell.tsx@@ -92,7 +92,13 @@ export const GalleryBoardRowShell = ({>{cover}<Stack align="stretch" flex="1" gap="0" minW="0" textAlign="start">- <MiddleTruncate fontWeight={labelWeight ?? (isSelected ? '600' : '500')} minW="0" text={label} />+ {/* Sized here, not inherited: popover content (the Gallery picker) sets a larger text style. */}+ <MiddleTruncate+ fontSize="md"+ fontWeight={labelWeight ?? (isSelected ? '600' : '500')}+ minW="0"+ text={label}+ />{subtitle}</Stack>{children}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 aed3862b97..9ea8f26e16 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@@ -86,6 +86,7 @@ const createGallery = (settings: Partial<GallerySettings> = {}): GalleryStateViecompareImageKey: null,galleryView: 'images',isComparisonActive: false,+ isCompareArmed: false,isSearchActive: false,items: [],listingBoardId: 'dogs',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 ddfd2b763a..0ec04d8311 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@@ -165,6 +165,7 @@ const createGallery = (items: GalleryItem[], selected: GalleryItem | null): GallcompareImageKey: null,galleryView: 'images',isComparisonActive: false,+ isCompareArmed: false,isSearchActive: false,items,listingBoardId: 'board-a',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 d5a7744a1b..41debcc4cd 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@@ -29,17 +29,20 @@ import { invalidateGalleryItems, patchGalleryItemCaches } from '@features/gallerimport { GalleryUiProvider, type GalleryUiAdapter } from '@features/gallery/react';import { GALLERY_PINNED_FOOTER_PX } from '@features/gallery/ui/galleryGridLayout';import { isGalleryImageDragData } from '@features/gallery/utility';-import { getFollowedProgressSession } from '@features/queue/contracts';+import { getAutoSwitchFollowedLive } from '@features/queue/contracts';+import { dragWithMouse } from '@platform/browser/mouseDrag.testing';import { parseDateTokens } from '@platform/search/dateTokens';import { accountLifecycle } from '@platform/state/accountLifecycle';import { getContrastRatio } from '@platform/ui/theme/contrastRatio.testing';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';+import { PrimaryMouseSensor } from '@workbench/shell/holdToDragSensor';import { workbenchAutoScroll } from '@workbench/widgetDnd';import { PreviewFilmstrip } from '@workbench/widgets/preview/PreviewFilmstrip';import { PreviewFrame } from '@workbench/widgets/preview/PreviewFrame';import { createInstance } from 'i18next';import { act, type ReactNode } from 'react';+import { createPortal } from 'react-dom';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -329,6 +332,7 @@ const createGallery = (overrides: Partial<GalleryStateView> = {}): GalleryStateVcompareImageKey: null,galleryView: 'images',isComparisonActive: false,+ isCompareArmed: false,isSearchActive: false,items,listingBoardId: overrides.selectedBoardId ?? board.id,@@ -445,6 +449,8 @@ const ContextMenuProbe = ({ target }: { target: CanonicalContextTarget }) => (<button data-testid="context-return-focus" type="button" onClick={() => target?.returnFocus?.()?.focus()}>Close dialog</button>+ {/* The open menu's portalled layer: a React child of the grid, outside its DOM. */}+ {target ? createPortal(<div data-testid="context-menu-layer">Menu</div>, document.body) : null}</>);const NoopProvider = ({ children }: { children: ReactNode }) => children;@@ -483,7 +489,16 @@ const createAdapter = (progressSessions,pinnedProgressSessionId,followedProgressSessionId: liveFollowEnabled- ? (getFollowedProgressSession(progressSessions, pinnedProgressSessionId)?.id ?? null)+ ? // Every live session in these fixtures is running and has shown a frame of its own.+ (getAutoSwitchFollowedLive(+ 'progress',+ progressSessions.map((session) => ({+ hasOwnFrame: true,+ id: session.id,+ state: session.state,+ })),+ pinnedProgressSessionId+ )?.id ?? null): null,followProgressSession,notifications: { add: noop, reportError: noop },@@ -515,6 +530,8 @@ const READY_LISTING: GalleryListingState = {};let currentListing = READY_LISTING;let onDragStart = vi.fn();+/** The shell's primary-button mouse sensor instead of the pointer sensor most tests drive. */+let withShellMouseSensor = false;/** The strip the next renders show; `total` defaults to the item count. */const setStrip = (items: GalleryItem[], total = items.length) => {@@ -546,7 +563,7 @@ const Harness = ({progressSessions: QueueProgressSession[];}) => {const sensors = useSensors(- useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),+ useSensor(withShellMouseSensor ? PrimaryMouseSensor : PointerSensor, { activationConstraint: { distance: 6 } }),useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }));const contextValue: GalleryWidgetContextValue = {@@ -781,6 +798,7 @@ beforeEach(() => {document.body.append(host);root = createRoot(host);onDragStart = vi.fn();+ withShellMouseSensor = false;});afterEach(async () => {@@ -1293,6 +1311,49 @@ describe('GalleryImageGrid mixed item cells', () => {);});+ it('starts a thumbnail drag through the shell mouse sensor', async () => {+ withShellMouseSensor = true;+ await renderGallery(createGallery({ items: [createItem('image', 'a.png'), createItem('image', 'b.png')] }));++ await dragWithMouse(getButton('Select a.png for preview'), getButton('Select b.png for preview'));++ expect(onDragStart).toHaveBeenCalledWith(expect.objectContaining({ id: 'gallery-grid#right:image:a.png' }));+ // Let dnd-kit's post-drag click guard expire before the next test.+ await interact(noop, 300);+ });++ it('selects and focuses a tile from a click beside its image, so Enter opens that tile', async () => {+ const first = createItem('image', 'a.png', { height: 192, width: 96 });+ const second = createItem('image', 'b.png', { height: 192, width: 96 });+ const gallery = createGallery({ items: [first, second], selectedItemKey: null, selectedItemKeys: [] });+ await renderGallery({ ...gallery, settings: { ...gallery.settings, thumbnailFit: 'aspect' } });+ const firstButton = getButton('Select a.png for preview');+ const secondButton = getButton('Select b.png for preview');+ const secondCell = secondButton.closest<HTMLElement>('[role="listitem"]')!;++ await act(() => userEvent.click(firstButton));+ // The portrait image is half the cell's width, centred: its left edge is beside the image.+ await act(() => userEvent.click(secondCell, { position: { x: 3, y: secondCell.clientHeight / 2 } }));++ expect(actionMocks.selectItem).toHaveBeenLastCalledWith(second);+ expect(document.activeElement).toBe(secondButton);+ expect([firstButton.tabIndex, secondButton.tabIndex]).toEqual([-1, 0]);++ await act(() => userEvent.keyboard('{Enter}'));++ expect(imageActionMocks.openItemInPreview).toHaveBeenCalledExactlyOnceWith(second);+ });++ it("keeps the star toggle's middle click from opening the item in a new tab", async () => {+ const gallery = createGallery();+ await renderGallery({ ...gallery, settings: { ...gallery.settings, middleClickOpensInNewTab: true } });++ await act(() => userEvent.click(getButton('Star first.png'), { button: 'middle' }));++ expect(imageActionMocks.openItemInNewTab).not.toHaveBeenCalled();+ expect(imageActionMocks.openItemInPreview).not.toHaveBeenCalled();+ });+it('toggles the star on each click of a double-click without selecting or opening the item', async () => {await renderGallery();await act(() => userEvent.dblClick(getButton('Star first.png')));@@ -1384,6 +1445,54 @@ describe('GalleryImageGrid mixed item cells', () => {});});+ it('marks the image Select for compare waits with as the comparison, and only it', async () => {+ const tileText = (name: string) =>+ getButton(`Select ${name} for preview`).closest('[role="listitem"]')?.textContent ?? '';+ await renderGallery(+ createGallery({+ compareImageKey: 'image:first.png',+ isCompareArmed: true,+ items: [createItem('image', 'first.png'), createItem('image', 'second.png')],+ selectedItemKey: 'image:first.png',+ selectedItemKeys: ['image:first.png'],+ })+ );++ expect(tileText('first.png')).toContain('Compare');+ expect(tileText('second.png')).not.toContain('Compare');+ expect(host!.textContent).not.toContain('Viewing');++ // Esc calls it off from the Gallery too, where the second image is picked.+ registeredCommands.get('gallery.exitCompare')?.();+ expect(actionMocks.setCompareItem).toHaveBeenLastCalledWith(null);++ // Live frames on screen do not hide it here: the next click would still pick the second image.+ currentProgressSessions = [+ {+ backendItemId: 10,+ height: 768,+ id: 'run:1',+ itemCount: 1,+ itemIndex: 1,+ label: 'Workflow A',+ queueItemId: 'run',+ sourceId: 'workflow',+ state: 'running',+ width: 512,+ },+ ];+ currentLiveFollowEnabled = true;+ await renderGallery();+ expect(tileText('first.png')).toContain('Compare');+ expect(registeredCommands.has('gallery.exitCompare')).toBe(true);+ });++ it('leaves Esc unclaimed while nothing is compared', async () => {+ await renderGallery(createGallery({ items: [createItem('image', 'first.png')] }));++ expect(registeredCommands.has('gallery.exitCompare')).toBe(false);+ });+it('keeps Alt comparison image-only and forms a one-video context target outside selection', async () => {const image = createItem('image', 'first.png');const video = createItem('video', 'clip.mp4', { durationSeconds: 2 });@@ -1567,7 +1676,7 @@ describe('GalleryImageGrid mixed item cells', () => {describe('GalleryImageGrid image-map labels', () => {const getTile = (name: string): HTMLElement => {- const tile = getButton(`Select ${name} for preview`).parentElement;+ const tile = getButton(`Select ${name} for preview`).closest<HTMLElement>('[role="listitem"]');if (!tile) {throw new Error(`Expected tile for ${name}`);@@ -1799,6 +1908,35 @@ describe('GalleryImageGrid upload drop zone', () => {expect(host?.textContent).toContain('Drop media to Uncategorized');});+ it('takes no files dragged over a context menu it opened, and shows no drop zone after passing through it', async () => {+ await renderGallery(createGallery({ items: [createItem('image', 'menu.png')] }));+ await interact(() =>+ getButton('Select menu.png for preview').dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 23, clientY: 41 })+ )+ );+ const menu = document.querySelector('[data-testid="context-menu-layer"]')!;+ const gridRoot = host!.querySelector('[role="list"]')!.closest('[data-scope="scroll-area"]')!.parentElement!;+ const dataTransfer = new DataTransfer();+ dataTransfer.items.add(new File(['image'], 'image.png', { type: 'image/png' }));+ const send = async (type: string, target: Element, relatedTarget: Element | null = null) => {+ const event = new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer, relatedTarget });+ await interact(() => target.dispatchEvent(event));+ return event;+ };+ const dropZoneShown = () => host!.textContent!.includes('Drop media to');++ await send('dragenter', gridRoot);+ expect(dropZoneShown()).toBe(true);+ // Onto the menu: React bubbles its drag events to the grid, which neither counts nor takes them.+ await send('dragenter', menu, gridRoot);+ await send('dragleave', gridRoot, menu);+ expect(dropZoneShown()).toBe(false);+ expect((await send('dragover', menu)).defaultPrevented).toBe(false);+ expect((await send('drop', menu)).defaultPrevented).toBe(false);+ expect(actionMocks.uploadFiles).not.toHaveBeenCalled();+ });+it('turns a true-empty, non-searching, non-virtual board into a click/drop upload target', async () => {await renderGallery(createGallery({ items: [] }));@@ -4010,16 +4148,19 @@ describe('shared gallery progress section', () => {expect(indicator?.classList.contains('chakra-spinner')).toBe(true);expect(indicator?.getAttribute('aria-label')).toBe('Preparing');});- it('letterboxes placeholders to the output aspect only in aspect thumbnail mode', async () => {+ it('sizes placeholders to the output aspect only in aspect thumbnail mode and for sized sources', async () => {currentProgressSessions = [- { ...session, width: 1024, height: 512, state: 'queued' },- { ...session, id: 'run:2', width: 512, height: 1024 },- { ...session, id: 'run:3', width: 0, height: 1024, state: 'queued' },+ { ...session, sourceId: 'generate', width: 1024, height: 512, state: 'queued' },+ { ...session, id: 'run:2', sourceId: 'upscale', width: 512, height: 1024 },+ { ...session, id: 'run:3', sourceId: 'generate', width: 0, height: 1024, state: 'queued' },+ // A workflow's recorded size is Generate's, not necessarily its output's.+ { ...session, id: 'run:4', width: 1024, height: 512 },];const placeholderRatios = () =>[...host!.querySelectorAll<HTMLElement>('[aria-label="In progress"] button[aria-pressed]')].map((tile) => {- const cell = tile.firstElementChild!.getBoundingClientRect();- const placeholder = tile.firstElementChild!.firstElementChild!.getBoundingClientRect();+ // The tile is the square cell; the bordered media box inside it takes the output's ratio.+ const cell = tile.getBoundingClientRect();+ const placeholder = tile.querySelector('[data-gallery-tile-media]')!.getBoundingClientRect();return [placeholder.width / cell.width, placeholder.height / cell.height].map((ratio) => ratio.toFixed(2));});@@ -4028,6 +4169,7 @@ describe('shared gallery progress section', () => {['1.00', '0.50'],['0.50', '1.00'],['1.00', '1.00'],+ ['1.00', '1.00'],]);await renderGallery(createGallery({ settings: { ...DENSE_SETTINGS, thumbnailFit: 'square' } }));@@ -4035,6 +4177,7 @@ describe('shared gallery progress section', () => {['1.00', '1.00'],['1.00', '1.00'],['1.00', '1.00'],+ ['1.00', '1.00'],]);});it('updates tile spacing when density changes without changing the batch', async () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsxindex f22ce4d625..84002c3db1 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryImageGrid.tsx@@ -16,6 +16,8 @@ import {imageIndexAvailabilityOptions,type GalleryItemsFilter,} from '@features/gallery/data/queries';+import { isEventFromOwnDom } from '@platform/react/isEventFromOwnDom';+import { useMountEffect } from '@platform/react/useMountEffect';import { getApiErrorMessage } from '@platform/transport/http';import { Button, DropZone } from '@platform/ui';import { LoadError, RetryButton } from '@platform/ui/LoadError';@@ -89,7 +91,10 @@ const EMPTY_GALLERY_ITEMS: GalleryItem[] = [];// Module-scoped so a grid remount cannot replay an already-followed reveal.let lastPageFollowedRevealToken = 0;-const dragEventContainsFiles = (event: DragEvent): boolean => Array.from(event.dataTransfer.types).includes('Files');+// React also bubbles drags over portalled content the grid opens, such as a tile's context menu; those are not over+// the grid, so it neither counts nor takes them.+const isFileDragOnGrid = (event: DragEvent): boolean =>+ isEventFromOwnDom(event) && Array.from(event.dataTransfer.types).includes('Files');const GalleryPageError = ({onFocusLost,@@ -405,6 +410,37 @@ const focusVisibleGridContent = (viewport: HTMLElement | null, edge: 'first' | '}};+const GALLERY_EXIT_COMPARE_COMMAND = 'gallery.exitCompare';++/**+ * Esc ends a comparison from the Gallery, where its second image is picked: one waiting for that image, or one open in+ * Preview. Mounted only meanwhile, so Esc keeps its other meanings the rest of the time; the grid keys it by project and+ * language, which its registration's source and title follow.+ */+const GalleryExitCompareHotkey = () => {+ const { t } = useTranslation();+ const { actions, runtime } = useGalleryWidget();++ // The host's compare command clears the open project's comparison, the same for the mount's lifetime.+ useMountEffect(() => {+ const exitCompare = () => actions.setCompareItem(null);+ const title = t('widgets.preview.commands.exitCompare');+ const disposers = [+ runtime.commands.register({ handler: exitCompare, id: GALLERY_EXIT_COMPARE_COMMAND, title }),+ runtime.hotkeys.register({+ commandId: GALLERY_EXIT_COMPARE_COMMAND,+ defaultKeys: ['esc'],+ id: GALLERY_EXIT_COMPARE_COMMAND,+ title,+ }),+ ];++ return () => disposers.forEach((dispose) => dispose());+ });++ return null;+};+/** Measure viewport width for columns so both layouts share the same grid. */export const GalleryImageGrid = ({mediaFilterTriggerRef,@@ -412,7 +448,7 @@ export const GalleryImageGrid = ({/** The layout's media filter trigger, which takes focus when "Show all media" removes itself. */mediaFilterTriggerRef?: RefObject<HTMLButtonElement | null>;} = {}) => {- const { t } = useTranslation();+ const { i18n, t } = useTranslation();const {actions,filter,@@ -420,6 +456,7 @@ export const GalleryImageGrid = ({itemActions,listing,pinRevealIndex,+ projectId,region,setVisibleRange,sparseListing,@@ -509,6 +546,8 @@ export const GalleryImageGrid = ({: 0;const isFollowingLive = followedProgressSessionId !== null;const isComparisonActive = gallery.isComparisonActive && !isFollowingLive;+ // Not hidden while live frames show: the waiting image stays marked where the second image is picked.+ const isCompareArmed = gallery.isCompareArmed;const selectedBoard = gallery.boards.find((board) => board.id === gallery.selectedBoardId);const selectedBoardName = selectedBoard? getGalleryBoardLabel(selectedBoard, t)@@ -1606,7 +1645,7 @@ export const GalleryImageGrid = ({}, [actions, lastVisibleRowIndex, paginationMode, rowCount, usesSparseListing]);const handleDragEnter = useCallback((event: DragEvent) => {- if (!dragEventContainsFiles(event)) {+ if (!isFileDragOnGrid(event)) {return;}@@ -1616,7 +1655,7 @@ export const GalleryImageGrid = ({}, []);const handleDragLeave = useCallback((event: DragEvent) => {- if (!dragEventContainsFiles(event)) {+ if (!isFileDragOnGrid(event)) {return;}@@ -1628,13 +1667,16 @@ export const GalleryImageGrid = ({}, []);const handleDragOver = useCallback((event: DragEvent) => {- if (dragEventContainsFiles(event)) {+ if (isFileDragOnGrid(event)) {event.preventDefault();}}, []);const handleDrop = useCallback((event: DragEvent) => {+ if (!isEventFromOwnDom(event)) {+ return;+ }event.preventDefault();dragDepthRef.current = 0;setIsDropActive(false);@@ -1709,7 +1751,8 @@ export const GalleryImageGrid = ({compareRole={isComparisonActive && itemKey === gallery.selectedItemKey? t('widgets.preview.viewing')- : isComparisonActive && itemKey === gallery.compareImageKey+ : // Waiting for the second image, the base already carries the side it will take.+ (isComparisonActive || isCompareArmed) && itemKey === gallery.compareImageKey? t('widgets.preview.compare'): null}@@ -1740,6 +1783,7 @@ export const GalleryImageGrid = ({handleThumbnailClick,handleThumbnailContextMenu,handleToggleStarred,+ isCompareArmed,isComparisonActive,isFollowingLive,middleClickOpensInNewTab,@@ -1757,6 +1801,7 @@ export const GalleryImageGrid = ({const sparseErrorPageOffset = [...(sparseListing?.pageStates ?? [])].find(([, pageState]) => pageState.error)?.[0];return (<Stack flex="1" gap="0" h="full" minH="0" minW="0" w="full">+ {isComparisonActive || isCompareArmed ? <GalleryExitCompareHotkey key={`${projectId}:${i18n.language}`} /> : null}{listing.status === 'stale-error' &&(!usesSparseListing || (Boolean(sparseListing?.pageStates.get(0)?.error) && !sparsePageStatusOffsets.has(0))) ? (<GalleryLoadNoticediff --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 da05019ef7..8a656f43bd 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@@ -17,8 +17,10 @@ import type { GalleryStateView } from './galleryStateView';import type { GalleryWidgetContextValue } from './GalleryWidgetContext';import { GALLERY_PINNED_FOOTER_PX, GALLERY_STARRED_HEADER_HEIGHT_PX } from './galleryGridLayout';+import { GalleryLayout } from './GalleryLayout';import { GalleryStackedLayout } from './GalleryStackedLayout';import { GalleryWideLayout } from './GalleryWideLayout';+import { GalleryWidgetLabel } from './GalleryWidgetChrome';import { GalleryWidgetContext } from './GalleryWidgetContext';import { EMPTY_GALLERY_STARRED_STRIP } from './useGalleryStarredStrip';@@ -27,6 +29,16 @@ vi.mock('@features/queue/react', () => ({useQueueItemProgressImage: () => null,}));+// The header label lists boards itself; the shells read them from the widget context.+vi.mock('@features/gallery/data/queries', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ galleryBoardsOptions: () => ({+ queryFn: () => Promise.resolve([board]),+ queryKey: ['test-gallery-boards'],+ staleTime: Infinity,+ }),+}));+vi.mock('react-i18next', () => ({useTranslation: () => ({i18n: { language: 'en' },@@ -165,13 +177,16 @@ let root: Root | null = null;let queryClient: QueryClient | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const renderLayout = async (Layout: typeof GalleryStackedLayout | typeof GalleryWideLayout) => {+const renderLayout = async (+ Layout: typeof GalleryStackedLayout | typeof GalleryWideLayout,+ region: GalleryWidgetContextValue['region'] = 'center'+) => {await act(() =>root?.render(<ChakraProvider value={system}><QueryClientProvider client={queryClient!}><GalleryUiProvider adapter={adapter}>- <GalleryWidgetContext value={createContextValue()}>+ <GalleryWidgetContext value={{ ...createContextValue(), region }}><DndContext><Layout /></DndContext>@@ -183,6 +198,28 @@ const renderLayout = async (Layout: typeof GalleryStackedLayout | typeof Gallery);};+/** Header and body as the workbench places them: siblings under one Gallery UI host. */+const renderBottomPlacement = async ({ withBody = true }: { withBody?: boolean } = {}) => {+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient!}>+ <GalleryUiProvider adapter={adapter}>+ <GalleryWidgetLabel region="bottom" />+ {withBody ? (+ <GalleryWidgetContext value={{ ...createContextValue(), region: 'bottom' }}>+ <DndContext>+ <GalleryLayout region="bottom" />+ </DndContext>+ </GalleryWidgetContext>+ ) : null}+ </GalleryUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ )+ );+};+beforeEach(() => {vi.clearAllMocks();setGallery(gallery);@@ -568,3 +605,69 @@ describe('gallery layout shells', () => {}});});++describe('wide shell board divider', () => {+ const getDividerEdges = () => {+ const divider = host!.querySelector<HTMLElement>('[role="separator"][aria-orientation="vertical"]')!;+ const { bottom, top } = divider.getBoundingClientRect();+ const frame = host!.getBoundingClientRect();+ return { bottom: frame.bottom - bottom, top: top - frame.top };+ };++ it('runs from the header rule to the bottom edge of a docked body', async () => {+ await renderLayout(GalleryWideLayout, 'bottom');++ expect(getDividerEdges()).toEqual({ bottom: 0, top: 0 });+ const boardSearch = host!.querySelector<HTMLElement>('input[aria-label="widgets.gallery.searchOrCreateBoards"]')!;+ expect(boardSearch.getBoundingClientRect().top, 'the board panel keeps its inner padding').toBeGreaterThan(0);+ });++ it('stays below the floating chrome in the center', async () => {+ host!.style.setProperty('--wb-center-chrome-inset', '48px');+ await renderLayout(GalleryWideLayout, 'center');++ const { bottom, top } = getDividerEdges();+ expect(top).toBeGreaterThan(48);+ expect(bottom).toBeGreaterThan(0);+ });+});++describe('gallery header boards toggle', () => {+ const getToggle = () => host!.querySelector<HTMLButtonElement>('button[aria-expanded]')!;+ const getToggleIcon = () =>+ getToggle().querySelector('svg.lucide-panel-left-close')+ ? 'sidebar'+ : getToggle().querySelector('svg.lucide-chevrons-down-up')+ ? 'stacked'+ : null;+ const getBoardsSeparatorOrientation = () =>+ host!.querySelector<HTMLElement>('[role="separator"]')?.getAttribute('aria-orientation');++ it('follows the layout the bottom panel renders as it narrows and widens again', async () => {+ await renderBottomPlacement();++ // The wide shell divides boards from the grid with a column handle; the stacked one with a row handle.+ await expect.poll(getBoardsSeparatorOrientation).toBe('vertical');+ expect(getToggleIcon()).toBe('sidebar');++ host!.style.width = '400px';+ await expect.poll(getBoardsSeparatorOrientation).toBe('horizontal');+ await expect.poll(getToggleIcon).toBe('stacked');+ expect(getToggle().getAttribute('aria-expanded')).toBe('true');++ host!.style.width = '900px';+ await expect.poll(getBoardsSeparatorOrientation).toBe('vertical');+ await expect.poll(getToggleIcon).toBe('sidebar');+ });++ it('returns the header to the placement default once the body unmounts', async () => {+ host!.style.width = '400px';+ await renderBottomPlacement();+ await expect.poll(getToggleIcon).toBe('stacked');++ await renderBottomPlacement({ withBody: false });++ expect(getBoardsSeparatorOrientation()).toBeUndefined();+ await expect.poll(getToggleIcon).toBe('sidebar');+ });+});diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsageSection.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsageSection.tsxindex 7c21dc185d..1925978f86 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsageSection.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryMediaUsageSection.tsx@@ -126,7 +126,10 @@ const SurfaceRows = ({const UsageGroup = ({ group, showCounts }: { group: GalleryMediaUsageGroup; showCounts: boolean }) => {const { t } = useTranslation();- const count = showCounts && group.kind !== 'moreDocuments' ? t(`${KEY}.itemCount`, { count: group.count }) : null;+ const count =+ showCounts && group.kind !== 'moreDocuments'+ ? t(group.countAtLeast ? `${KEY}.itemCountAtLeast` : `${KEY}.itemCount`, { count: group.count })+ : null;return (<List.Item>@@ -192,16 +195,10 @@ const UsageReport = ({) : report.serverCheck === 'complete' ? null : (<UsageWarningisRetryDisabled={isRetryDisabled}- message={t(- report.serverCheck === 'tooManyItems'- ? `${KEY}.tooManyItems`- : report.groups.length === 0- ? `${KEY}.uncheckedNone`- : `${KEY}.unchecked`,- { count: report.checkedCount }- )}- // Retrying cannot shrink a selection past the limit.- onRetry={report.serverCheck === 'unavailable' ? onRetry : undefined}+ message={t(report.groups.length === 0 ? `${KEY}.uncheckedNone` : `${KEY}.unchecked`, {+ count: report.checkedCount,+ })}+ onRetry={onRetry}/>);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsxindex 564a1e5941..e7b0cef3f3 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryProgressSection.tsx@@ -1,5 +1,5 @@import type { GalleryThumbnailFit } from '@features/gallery/core/settings';-import type { QueueProgressSession } from '@features/queue/contracts';+import type { QueueProgressSession, QueueSourceId } from '@features/queue/contracts';import { Box, chakra, Icon, Skeleton, Text } from '@chakra-ui/react';import { getDeterminateProgressPercent } from '@features/queue/contracts';@@ -16,7 +16,7 @@ import { useTranslation } from 'react-i18next';import type { GalleryProgressLayout } from './galleryGridLayout';import { GALLERY_TAB_STOP_SELECTOR } from './GalleryThumbnail';-import { SELECTED_TILE_CSS } from './GalleryTileFrame';+import { GalleryTileMedia, getGalleryTileMediaRatio } from './GalleryTileFrame';import { useGalleryUi } from './GalleryUiContext';import { useGalleryWidget } from './GalleryWidgetContext';@@ -182,13 +182,25 @@ const GalleryProgressGrid = ({);};-const FILL_CELL = { h: 'full', w: 'full' } as const;-const FILL_WIDTH = { w: 'full' } as const;-const FILL_HEIGHT = { h: 'full' } as const;+/**+ * Like a completed thumbnail: hover tints the square cell, while the border, selection and focus ring wrap the media+ * box sized to the job's target ratio, so the finished item takes the same rect. The progress badge stays on the cell.+ */+const PROGRESS_CELL_CSS = {+ _focusVisible: { outline: 'none' },+ // Queued and settling tiles are inert; only a followable one answers hover.+ '&:not([aria-disabled=true]):hover': { bg: 'bg.hover' },+ '&:focus-visible [data-gallery-tile-media]': {+ outline: '2px solid {colors.accent.solid}',+ outlineOffset: '-2px',+ },+} as const;-/** The output's width-to-height ratio, for letterboxing a placeholder like an aspect-fit thumbnail. */-const getPlaceholderAspectRatio = ({ width, height }: QueueProgressSession): number | null =>- width > 0 && height > 0 && Number.isFinite(width / height) ? width / height : null;+/**+ * Sources whose snapshot records the size they will output. Workflows take Generate's size, which their graph need+ * not use, so their tiles stay square and letterbox the live image.+ */+const SIZED_PROGRESS_SOURCES: ReadonlySet<QueueSourceId> = new Set(['canvas', 'generate', 'upscale', 'video']);const GalleryProgressTile = ({session,@@ -246,51 +258,49 @@ const GalleryProgressTile = ({);const isShownSelected = selected && session.state !== 'queued';- // Aspect fit letterboxes the placeholder inside the square cell, as completed thumbnails are: the longer side fills- // the cell and the other follows the output's ratio.- const placeholderAspectRatio = fit === 'aspect' ? getPlaceholderAspectRatio(session) : null;- const placeholderSize =- placeholderAspectRatio === null ? FILL_CELL : placeholderAspectRatio >= 1 ? FILL_WIDTH : FILL_HEIGHT;+ const mediaRatio = SIZED_PROGRESS_SOURCES.has(session.sourceId) ? getGalleryTileMediaRatio(session, fit) : null;return (<Tooltip content={`${label} · ${status}`}><chakra.buttonref={buttonRef}type="button"- focusVisibleRing="inside"aria-label={`${label} · ${status}`}aria-pressed={isShownSelected}aria-disabled={session.state !== 'running'}data-gallery-session-id={session.id}tabIndex={session.state === 'running' ? 0 : -1}- borderColor={isShownSelected ? 'accent.solid' : 'border.subtle'}- borderWidth="2px"- css={isShownSelected ? SELECTED_TILE_CSS : undefined}+ alignItems="center"+ aspectRatio={1}+ css={PROGRESS_CELL_CSS}+ display="flex"flexShrink={0}+ justifyContent="center"minW="0"- overflow="hidden"rounded="md"textAlign="start"position="relative"+ transition="background-color var(--wb-motion-duration-fast) ease"w={`${size}px`}onClick={follow}>- <StreamingImageFrame- alignItems="center"- aspectRatio={1}- display="flex"- fit={fit === 'aspect' ? 'contain' : 'cover'}- justifyContent="center"- liveImage={progressImageToStreamingSource(image)}- shouldAntialiasLiveImage={antialiasProgressImages}- w="full"+ <GalleryTileMedia+ fit={mediaRatio === null ? 'square' : fit}+ height={session.height}+ isSelected={isShownSelected}+ width={session.width}>- {session.state === 'queued' ? (- <Box bg="bg.subtle" aspectRatio={placeholderAspectRatio ?? undefined} {...placeholderSize} />- ) : (- <Skeleton aspectRatio={placeholderAspectRatio ?? undefined} {...placeholderSize} />- )}- </StreamingImageFrame>+ <StreamingImageFrame+ // A box sized to the target ratio is filled exactly; an unsized aspect fit letterboxes in the square.+ fit={fit === 'aspect' && mediaRatio === null ? 'contain' : 'cover'}+ h="full"+ liveImage={progressImageToStreamingSource(image)}+ shouldAntialiasLiveImage={antialiasProgressImages}+ w="full"+ >+ {session.state === 'queued' ? <Box bg="bg.subtle" h="full" w="full" /> : <Skeleton h="full" w="full" />}+ </StreamingImageFrame>+ </GalleryTileMedia><ProgressBadgelabel={status}percentage={percentage}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsxindex 0c9e2325f0..5c13eedc4f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryThumbnail.tsx@@ -26,7 +26,12 @@ import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';import { getGalleryItemDragData, getGalleryItemDragId } from './galleryDnd';-import { GalleryTileFrame } from './GalleryTileFrame';+import {+ GALLERY_TILE_MEDIA_SELECTOR,+ GalleryTileFrame,+ GalleryTileMedia,+ getGalleryTileMediaRatio,+} from './GalleryTileFrame';import { useGalleryImageRecovery } from './useGalleryImageRecovery';/** Desaturate armed and active touch drags, including the portalled preview. */@@ -43,6 +48,9 @@ const THUMBNAIL_ARMED_CSS = { '&[data-drag-armed=true]': { filter: 'saturate(0)'const isModified = (event: KeyboardEvent | MouseEvent) =>event.ctrlKey || event.metaKey || event.altKey || event.shiftKey;+/** Keeps the star's own double and middle clicks from reaching the cell's open handlers. */+const stopPropagation = (event: MouseEvent) => event.stopPropagation();+const PREVIEW_IMAGE_STYLE = {borderRadius: '0.375rem',boxShadow: '0 8px 24px rgb(0 0 0 / 45%)',@@ -153,7 +161,10 @@ const GalleryThumbnail = ({const [dragOrigin, setDragOrigin] = useState<DOMRect | null>(null);useLayoutEffect(() => {- setDragOrigin(isDragging ? (tileRef.current?.getBoundingClientRect() ?? null) : null);+ // The preview lifts the media's own rect, not the square cell around it.+ const media = tileRef.current?.querySelector(GALLERY_TILE_MEDIA_SELECTOR) ?? tileRef.current;++ setDragOrigin(isDragging ? (media?.getBoundingClientRect() ?? null) : null);}, [isDragging]);const itemKey = toGalleryItemKey(item);@@ -197,6 +208,8 @@ const GalleryThumbnail = ({[dragOrigin, transform]);+ // A media box sized to the item's ratio is filled exactly; without dimensions, aspect fit letterboxes in the square.+ const letterbox = fit === 'aspect' && getGalleryTileMediaRatio(item, fit) === null;const imageStyle = useMemo(() =>({@@ -204,11 +217,11 @@ const GalleryThumbnail = ({height: '100%',inset: 0,maxWidth: 'none',- objectFit: fit === 'aspect' ? 'contain' : 'cover',+ objectFit: letterbox ? 'contain' : 'cover',position: 'absolute',width: '100%',}) as const,- [fit]+ [letterbox]);const handleContextMenu = useCallback(@@ -226,7 +239,20 @@ const GalleryThumbnail = ({[isDragging, item, onContextMenu]);- const handleClick = useCallback((event: MouseEvent) => onClick(item, event), [item, onClick]);+ const buttonRef = useRef<HTMLButtonElement | null>(null);+ const handleClick = useCallback(+ (event: MouseEvent) => {+ const button = buttonRef.current;++ // A click beside the image takes focus to the tile like one on it, so the grid's focused tile, its Tab stop and+ // Enter/Space follow the item just selected.+ if (button && !button.contains(event.target as Node)) {+ button.focus({ preventScroll: true });+ }+ onClick(item, event);+ },+ [item, onClick]+ );// The clicks before it have already selected the item.const handleDoubleClick = useCallback((event: MouseEvent) => {@@ -237,18 +263,20 @@ const GalleryThumbnail = ({[item, onOpen]);- // Middle button only; the primary button's click/double-click stay selection and open. Its mousedown default- // (autoscroll on some platforms) is suppressed so the release reliably delivers the auxclick.- const handleMiddleMouseDown = useCallback(- (event: MouseEvent<HTMLButtonElement>) => {+ // Composes with the drag sensor's own mousedown, which starts primary-button drags from the same cell. Middle+ // button only: the primary button's click/double-click stay selection and open. Its mousedown default (autoscroll+ // on some platforms) is suppressed so the release reliably delivers the auxclick.+ const handleMouseDown = useCallback(+ (event: MouseEvent) => {if (onOpenInNewTab && event.button === 1) {event.preventDefault();}+ listeners?.onMouseDown?.(event);},- [onOpenInNewTab]+ [listeners, onOpenInNewTab]);const handleAuxClick = useCallback(- (event: MouseEvent<HTMLButtonElement>) => {+ (event: MouseEvent) => {if (onOpenInNewTab && event.button === 1) {event.preventDefault();event.stopPropagation();@@ -301,47 +329,50 @@ const GalleryThumbnail = ({ref={setTileRef}{...dragListeners}alwaysShowDimensions={alwaysShowDimensions}- boxShadow={isCompared ? 'inset 0 0 0 1px {colors.accent.solid}' : undefined}css={isDragging ? THUMBNAIL_DRAG_CSS : THUMBNAIL_ARMED_CSS}- isSelected={isSelected || isCompared}item={item}opacity={isDragging ? 0.4 : undefined}role="listitem"// Allow touch panning; the hold sensor yields to scrolling and arms drag only after a sustained hold.touchAction="pan-y"+ // Pointer handlers sit on the whole cell so its letterbox gutter selects and opens like the media; the button's+ // own clicks (Space included) bubble here.+ onAuxClick={handleAuxClick}+ onClick={handleClick}onContextMenu={handleContextMenu}+ onDoubleClick={handleDoubleClick}onFocus={handleRevealLabel}+ onMouseDown={handleMouseDown}onPointerEnter={handleRevealLabel}>- <button- aria-current={isPrimary ? 'true' : undefined}- // Enter opens the item in Preview; Space keeps the button's own activation, which selects.- aria-keyshortcuts="Enter"- aria-label={- item.kind === 'video'- ? t('widgets.gallery.selectVideoForPreview', { duration, name: item.name })- : t('widgets.gallery.selectImageForPreview', { name: item.name })- }- aria-pressed={isSelected}- data-gallery-item-key={itemKey}- style={THUMBNAIL_BUTTON_STYLE}- tabIndex={isTabStop ? 0 : -1}- type="button"- onAuxClick={handleAuxClick}- onClick={handleClick}- onDoubleClick={handleDoubleClick}- onKeyDown={handleActivationKeyDown}- onMouseDown={handleMiddleMouseDown}- >- <img- alt={item.name}- decoding={item.kind === 'video' ? 'async' : undefined}- draggable={false}- src={thumbnailUrl}- style={imageStyle}- onError={handleImageError}- />- </button>+ <GalleryTileMedia fit={fit} height={item.height} isSelected={isSelected || isCompared} width={item.width}>+ <button+ aria-current={isPrimary ? 'true' : undefined}+ // Enter opens the item in Preview; Space keeps the button's own activation, which selects.+ aria-keyshortcuts="Enter"+ aria-label={+ item.kind === 'video'+ ? t('widgets.gallery.selectVideoForPreview', { duration, name: item.name })+ : t('widgets.gallery.selectImageForPreview', { name: item.name })+ }+ aria-pressed={isSelected}+ data-gallery-item-key={itemKey}+ ref={buttonRef}+ style={THUMBNAIL_BUTTON_STYLE}+ tabIndex={isTabStop ? 0 : -1}+ type="button"+ onKeyDown={handleActivationKeyDown}+ >+ <img+ alt={item.name}+ decoding={item.kind === 'video' ? 'async' : undefined}+ draggable={false}+ src={thumbnailUrl}+ style={imageStyle}+ onError={handleImageError}+ />+ </button>+ </GalleryTileMedia>{/* The compare role owns this corner while comparing. */}{label && getItemLabel && !compareRole ? (<Badge@@ -387,7 +418,9 @@ const GalleryThumbnail = ({transition="opacity var(--wb-motion-duration-medium) ease"variant="solid"zIndex="1"+ onAuxClick={stopPropagation}onClick={handleToggleStarred}+ onDoubleClick={stopPropagation}><StarIcon fill={item.starred ? 'currentColor' : 'none'} /></IconButton>diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.browser.test.tsxindex a52b0c3054..9956cc36f0 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.browser.test.tsx@@ -4,9 +4,15 @@ import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { GalleryTileFrame, type GalleryTileFrameProps } from './GalleryTileFrame';+import {+ GALLERY_TILE_MEDIA_SELECTOR,+ GalleryTileFrame,+ type GalleryTileFrameProps,+ GalleryTileMedia,+ type GalleryTileMediaProps,+} from './GalleryTileFrame';let host: HTMLDivElement | null = null;let root: Root | null = null;@@ -41,11 +47,16 @@ const video: GalleryItem = {width: 128,};-const renderFrame = async (props: Partial<GalleryTileFrameProps> = {}) => {+const renderFrame = async (props: Partial<GalleryTileFrameProps> = {}, media: Partial<GalleryTileMediaProps> = {}) => {+ const item = props.item ?? image;+await act(() =>root?.render(<ChakraProvider value={system}>- <GalleryTileFrame data-testid="frame" item={image} {...props} />+ <GalleryTileFrame data-testid="frame" item={item} {...props}>+ <GalleryTileMedia fit="square" height={item.height} isSelected={false} width={item.width} {...media} />+ {props.children}+ </GalleryTileFrame></ChakraProvider>));@@ -59,6 +70,16 @@ const renderFrame = async (props: Partial<GalleryTileFrameProps> = {}) => {return frame;};+const mediaOf = (frame: HTMLElement) => {+ const media = frame.querySelector<HTMLElement>(GALLERY_TILE_MEDIA_SELECTOR);++ if (!media) {+ throw new Error('media box did not render');+ }++ return media;+};+const accentBorder = () => {const probe = document.createElement('div');@@ -85,36 +106,58 @@ afterEach(async () => {});describe('GalleryTileFrame', () => {- it('flips the border to accent when selected and keeps the shell props as invariants', async () => {+ it('flips the media border to accent when selected and keeps the shell props as invariants', async () => {const unselected = await renderFrame({ rounded: 'none', w: '10px' });- expect(getComputedStyle(unselected).borderTopColor).not.toBe(accentBorder());+ expect(getComputedStyle(mediaOf(unselected)).borderTopColor).not.toBe(accentBorder());expect(getComputedStyle(unselected).aspectRatio).toBe('1 / 1');expect(getComputedStyle(unselected).width).not.toBe('10px');- const selected = await renderFrame({ isSelected: true });+ const selected = await renderFrame({}, { isSelected: true });- expect(getComputedStyle(selected).borderTopColor).toBe(accentBorder());+ expect(getComputedStyle(mediaOf(selected)).borderTopColor).toBe(accentBorder());});it('hides the dimensions badge until hovered, and composes caller css on top of its own', async () => {- const frame = await renderFrame({- children: <button type="button">focus me</button>,- css: { opacity: 0.5 },- });+ const frame = await renderFrame({ css: { opacity: 0.5 } }, { children: <button type="button">focus me</button> });const badge = frame.querySelector<HTMLElement>('.gallery-thumb-overlay');expect(badge?.textContent).toBe('128x96');expect(badge && getComputedStyle(badge).opacity).toBe('0');expect(getComputedStyle(frame).opacity).toBe('0.5');- expect(getComputedStyle(frame).outlineStyle).toBe('none');+ expect(getComputedStyle(mediaOf(frame)).outlineStyle).toBe('none');await act(() => frame.querySelector('button')?.focus());- // The focus ring comes from the frame's own css, so it proves the caller's- // css was composed rather than substituted.- expect(getComputedStyle(frame).outlineWidth).toBe('2px');- expect(getComputedStyle(frame).outlineColor).toBe(accentBorder());+ // The focus reveal comes from the frame's own css while the caller's opacity still applies, so the caller's css+ // was composed rather than substituted.+ // The reveal fades in.+ await vi.waitFor(() => expect(badge && getComputedStyle(badge).opacity).toBe('1'));+ expect(getComputedStyle(frame).opacity).toBe('0.5');+ // The focus ring is drawn on the media box, not the square cell.+ expect(getComputedStyle(frame).outlineStyle).toBe('none');+ expect(getComputedStyle(mediaOf(frame)).outlineWidth).toBe('2px');+ expect(getComputedStyle(mediaOf(frame)).outlineColor).toBe(accentBorder());+ });++ it('sizes the media box to the item ratio in aspect fit, clamped, and to the square otherwise', async () => {+ host!.style.width = '120px';+ const sizeOf = async (width: number, height: number, fit: 'aspect' | 'square' = 'aspect') => {+ const rect = mediaOf(await renderFrame({}, { fit, height, width })).getBoundingClientRect();++ return [rect.width, rect.height].map((value) => value.toFixed(1));+ };++ // Landscape fills the width; portrait narrows to ratio x width and keeps the cell's height.+ expect(await sizeOf(1920, 1080)).toEqual(['120.0', '67.5']);+ expect(await sizeOf(1024, 1536)).toEqual(['80.0', '120.0']);+ // Missing dimensions, and Fill mode, keep the square.+ expect(await sizeOf(0, 1536)).toEqual(['120.0', '120.0']);+ expect(await sizeOf(1024, 0)).toEqual(['120.0', '120.0']);+ expect(await sizeOf(1024, 1536, 'square')).toEqual(['120.0', '120.0']);+ // A panorama stops at 3:1 rather than shrinking to a sliver.+ expect(await sizeOf(8000, 1000)).toEqual(['120.0', '40.0']);+ expect(await sizeOf(1000, 8000)).toEqual(['40.0', '120.0']);});it('pins the dimensions badge when asked', async () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.tsxindex fc7ef3fac6..f8e937b5ea 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryTileFrame.tsx@@ -1,5 +1,6 @@import type { BoxProps, SystemStyleObject } from '@chakra-ui/react';import type { GalleryItem } from '@features/gallery/core/items';+import type { GalleryThumbnailFit } from '@features/gallery/core/settings';import type { ReactNode, Ref } from 'react';import { Badge, Box } from '@chakra-ui/react';@@ -7,13 +8,35 @@ import { formatGalleryVideoDuration } from '@features/gallery/core/items';import { PlayIcon } from 'lucide-react';import { useMemo } from 'react';+/**+ * Hover tints the whole square cell; the media box keeps the border, selection and focus ring. Overlays stay on the+ * cell's corners, on solid badge fills that read over the tint as well as over the image.+ */const TILE_CSS: SystemStyleObject = {- '&:focus-within': { outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' },+ _hover: { bg: 'bg.hover' },'&:hover .gallery-thumb-overlay, &:focus-within .gallery-thumb-overlay': { opacity: 1 },};-/** An inner ring over the image thickens the selected edge without resizing the tile content; shared by every tile. */-export const SELECTED_TILE_CSS: SystemStyleObject = {+/** The box drawn around the media's own rect, inside the square cell. */+export const GALLERY_TILE_MEDIA_SELECTOR = '[data-gallery-tile-media]';++/** Panoramas and strips stop here and cover-crop, so a dense cell never shrinks them to a sliver. */+const MAX_MEDIA_RATIO = 3;++/**+ * Aspect fit sizes the media box to the media's own ratio, clamped, when its dimensions are known; otherwise the box+ * fills the square cell and the media letterboxes inside it.+ */+export const getGalleryTileMediaRatio = (+ { height, width }: { height: number; width: number },+ fit: GalleryThumbnailFit+): number | null =>+ fit === 'aspect' && width > 0 && height > 0+ ? Math.min(MAX_MEDIA_RATIO, Math.max(1 / MAX_MEDIA_RATIO, width / height))+ : null;++/** An inner ring over the image thickens the selected edge without resizing the tile content. */+const SELECTED_TILE_CSS: SystemStyleObject = {_after: {borderRadius: 'sm',boxShadow: 'inset 0 0 0 2px {colors.accent.solid}',@@ -25,13 +48,56 @@ export const SELECTED_TILE_CSS: SystemStyleObject = {},};+const MEDIA_CSS: SystemStyleObject = {+ '&:focus-within': { outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' },+};+const SELECTED_MEDIA_CSS: SystemStyleObject = { ...MEDIA_CSS, ...SELECTED_TILE_CSS };++export interface GalleryTileMediaProps {+ children?: ReactNode;+ fit: GalleryThumbnailFit;+ height: number;+ isSelected: boolean;+ width: number;+}++/**+ * The bordered box around the media's own rect, inside a tile's square cell; it carries the border, selection ring+ * and focus ring. Centred in the flex cell, its width alone fixes its rect: a portrait box narrows to the ratio and+ * its aspect-ratio brings the height back to the cell's, so it is sized before the media loads, without a jump.+ */+export const GalleryTileMedia = ({ children, fit, height, isSelected, width }: GalleryTileMediaProps) => {+ const ratio = getGalleryTileMediaRatio({ height, width }, fit) ?? 1;+ // Inline: per-item ratios would otherwise each add stylesheet rules on the virtualized grid's hot path.+ const style = useMemo(+ () => ({ aspectRatio: String(ratio), width: ratio >= 1 ? '100%' : `${String(ratio * 100)}%` }),+ [ratio]+ );++ return (+ <Box+ bg="bg"+ borderColor={isSelected ? 'accent.solid' : 'border.subtle'}+ borderWidth="2px"+ css={isSelected ? SELECTED_MEDIA_CSS : MEDIA_CSS}+ data-gallery-tile-media=""+ flexShrink={0}+ overflow="hidden"+ position="relative"+ rounded="md"+ style={style}+ >+ {children}+ </Box>+ );+};+const BADGE_TRANSITION = 'opacity var(--wb-motion-duration-medium) ease';export interface GalleryTileFrameProps extends Omit<BoxProps, 'children'> {alwaysShowDimensions?: boolean;- /** The interactive layer (image button, drag listeners, extra badges). */+ /** A `GalleryTileMedia` with the image, then overlays (badges, star toggle) on the square cell's corners. */children?: ReactNode;- isSelected?: boolean;item: GalleryItem;ref?: Ref<HTMLDivElement>;}@@ -41,28 +107,26 @@ export const GalleryTileFrame = ({alwaysShowDimensions = false,children,css,- isSelected = false,item,...boxProps}: GalleryTileFrameProps) => {const duration = item.kind === 'video' ? formatGalleryVideoDuration(item.durationSeconds) : null;- const tileCss = useMemo(- () => [TILE_CSS, isSelected ? SELECTED_TILE_CSS : undefined, css].filter((entry) => entry !== undefined),- [css, isSelected]- );+ const tileCss = useMemo(() => [TILE_CSS, css].filter((entry) => entry !== undefined), [css]);return (<Box{...boxProps}+ alignItems="center"aspectRatio={1}- bg="bg"- borderColor={isSelected ? 'accent.solid' : 'border.subtle'}- borderWidth="2px"css={tileCss}+ display="flex"+ justifyContent="center"minW="0"- overflow="hidden"position="relative"rounded="md"+ transition="background-color var(--wb-motion-duration-fast) ease"+ // A shift-click beside the image extends the selection; it must not select badge or nearby text.+ userSelect="none"w="full">{children}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex a8c7ee4406..7fc35c432c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -11,7 +11,8 @@ import type {import type { QueueProgressSession } from '@features/queue/contracts';import { asSingleAccountBoards } from '@features/gallery/core/boardAccess';-import { createContext, use, useMemo, type ComponentType, type ReactNode } from 'react';+import { createKeyedTransientStore, type KeyedTransientStore } from '@platform/state/externalStore';+import { createContext, use, useMemo, useState, type ComponentType, type ReactNode } from 'react';export interface GalleryItemActions {/**@@ -195,9 +196,29 @@ export const useGalleryItemActions = (): GalleryItemActions => {return actions;};-export const GalleryUiProvider = ({ adapter, children }: { adapter: GalleryUiAdapter; children: ReactNode }) => (- <GalleryUiContext value={adapter}>{children}</GalleryUiContext>-);+export type GalleryLayoutMode = 'stacked' | 'wide';++/**+ * The layout each placement's gallery body measured (`galleryDensity` measures and reads it). The workbench renders the+ * header label apart from the body, so the label reads the arrangement here rather than guessing it from the region.+ * Keyed by region: a gallery moving to another placement never reads the one it left. Lives beside the provider, which+ * boots with the editor, so the lazily loaded gallery keeps the measuring hooks out of startup.+ */+export const GalleryLayoutStoreContext = createContext<KeyedTransientStore<+ GalleryWidgetProps['region'],+ GalleryLayoutMode+> | null>(null);++export const GalleryUiProvider = ({ adapter, children }: { adapter: GalleryUiAdapter; children: ReactNode }) => {+ // The workbench renders the header label apart from the body; both sit under this provider.+ const [layoutStore] = useState(() => createKeyedTransientStore<GalleryWidgetProps['region'], GalleryLayoutMode>());++ return (+ <GalleryUiContext value={adapter}>+ <GalleryLayoutStoreContext value={layoutStore}>{children}</GalleryLayoutStoreContext>+ </GalleryUiContext>+ );+};export const useGalleryUi = (): GalleryUiAdapter => {const adapter = use(GalleryUiContext);diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsxindex 5da8eb7a61..60b182c82f 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWideLayout.tsx@@ -16,10 +16,11 @@ import { GalleryViewTabs } from './GalleryViewTabs';import { useGalleryWidget } from './GalleryWidgetContext';const CHROME_INSET_PADDING_TOP = 'calc(var(--chakra-spacing-2) + var(--wb-center-chrome-inset, 0px))';+const CENTER_HANDLE_INSET = { pb: '2', pt: CHROME_INSET_PADDING_TOP } as const;export const GalleryWideLayout = () => {const { t } = useTranslation();- const { actions, gallery } = useGalleryWidget();+ const { actions, gallery, region } = useGalleryWidget();const { boardPanelCollapsed, boardPanelWidthPx } = gallery.settings;const viewTabsIdBase = useId();const boardPanelRef = useRef<HTMLDivElement>(null);@@ -49,9 +50,10 @@ export const GalleryWideLayout = () => {><GalleryBoardsPanel /></Flex>- {/* Inset like the panel: the handle paints above the center chrome islands, so a full-height line would- cross them. */}- <Flex flexShrink={0} pb="2" pt={CHROME_INSET_PADDING_TOP}>+ {/* The handle is the sidebar's edge. A docked or floating frame closes its header with a rule, so the line+ runs from that rule to the bottom edge. In the center it paints above the floating chrome islands, so+ it is inset like the panel instead of crossing them. */}+ <Flex flexShrink={0} {...(region === 'center' ? CENTER_HANDLE_INSET : null)}><ResizeHandlelabel={t('widgets.gallery.resizeBoardPanel')}max={GALLERY_BOARD_PANEL_MAX_WIDTH_PX}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsxindex a5c27727d5..9630479f26 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryWidgetChrome.tsx@@ -24,6 +24,7 @@ import { useTranslation } from 'react-i18next';import type { GalleryWidgetProps } from './GalleryUiContext';import { BoardCover, BoardCoverIcon } from './GalleryBoardCover';+import { useGalleryLayoutMode } from './galleryDensity';import { getGalleryProjectBoardId, getGallerySelectedBoardId } from './galleryStateView';import { useGalleryUi, useHostGalleryBoards } from './GalleryUiContext';import { useGalleryDestination } from './useGalleryDestination';@@ -89,6 +90,7 @@ export const GalleryWidgetLabel = ({ region }: GalleryChromeProps) => {? t('widgets.gallery.inboxOf', { project: selectedBoard.name }): getGalleryBoardLabel(selectedBoard, t);const isCollapsed = settings.boardPanelCollapsed;+ const layout = useGalleryLayoutMode(region);const toggleBoards = useCallback(() => gallery.updateSettings({ boardPanelCollapsed: !isCollapsed }),@@ -122,8 +124,8 @@ export const GalleryWidgetLabel = ({ region }: GalleryChromeProps) => {>{selectedBoard ? <BoardCover board={selectedBoard} /> : <BoardCoverIcon icon={ImageIcon} />}<MiddleTruncate fontWeight="600" minW="0" text={boardName} />- {/* The center view shows the boards as a sidebar beside the grid; the rails stack them above it. */}- {region === 'center' ? (+ {/* The icon follows the body's measured layout: a sidebar beside the grid, or a panel stacked above it. */}+ {layout === 'wide' ? (<Icon_rtl={MIRRORED_IN_RTL}as={isCollapsed ? PanelLeftOpenIcon : PanelLeftCloseIcon}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.tsindex 9b80ef82b3..fa99e1b148 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDensity.ts@@ -1,14 +1,14 @@-import { useCallback, useLayoutEffect, useRef, useState, type Ref } from 'react';+import type { KeyedTransientStore } from '@platform/state/externalStore';-import type { GalleryWidgetProps } from './GalleryUiContext';+import { use, useCallback, useSyncExternalStore, type Ref } from 'react';++import { GalleryLayoutStoreContext, type GalleryLayoutMode, type GalleryWidgetProps } from './GalleryUiContext';type GalleryRegion = GalleryWidgetProps['region'];/** Only shells interpret arrangement; shared slots must work in either placement. */const isRailRegion = (region: string): boolean => region === 'left' || region === 'right';-export type GalleryLayoutMode = 'stacked' | 'wide';-/** Below this the board column's ~240px leaves too little grid to scan. */export const GALLERY_WIDE_MIN_WIDTH_PX = 560;@@ -27,38 +27,61 @@ export const getGalleryLayout = ({return widthPx >= GALLERY_WIDE_MIN_WIDTH_PX ? 'wide' : 'stacked';};-/** State only changes when the layout flips, not on every measured pixel. */-export const useGalleryLayout = (- region: GalleryRegion-): { layout: GalleryLayoutMode; rootRef: Ref<HTMLDivElement> } => {- const [layout, setLayout] = useState<GalleryLayoutMode>(() => (isRailRegion(region) ? 'stacked' : 'wide'));- const regionRef = useRef(region);+/** What a placement shows before its gallery has measured, or while none is mounted there. */+const getUnmeasuredGalleryLayout = (region: GalleryRegion): GalleryLayoutMode =>+ isRailRegion(region) ? 'stacked' : 'wide';++const useGalleryLayoutStore = (): KeyedTransientStore<GalleryRegion, GalleryLayoutMode> => {+ const store = use(GalleryLayoutStoreContext);- useLayoutEffect(() => {- regionRef.current = region;- }, [region]);+ if (!store) {+ throw new Error('Gallery layout requires an App-composed GalleryUiProvider.');+ }- const applyMeasuredWidth = useCallback((widthPx: number) => {- setLayout(getGalleryLayout({ region: regionRef.current, widthPx }));- }, []);+ return store;+};- const [rootRef] = useState(() => (node: HTMLDivElement | null) => {- if (!node) {- return;- }+/**+ * The layout the gallery body in `region` renders, for chrome drawn outside it. Subscribes by key rather than through+ * `store.useValue`: the store comes from context, and hooks must be statically known.+ */+export const useGalleryLayoutMode = (region: GalleryRegion): GalleryLayoutMode => {+ const store = useGalleryLayoutStore();+ const subscribe = useCallback((listener: () => void) => store.subscribeKey(region, listener), [region, store]);+ const getSnapshot = () => store.get(region) ?? getUnmeasuredGalleryLayout(region);- const observer = new ResizeObserver((entries) => {- const widthPx = entries[0]?.contentRect.width;+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);+};- if (typeof widthPx === 'number' && widthPx > 0) {- applyMeasuredWidth(widthPx);+/** Measures the body's width and publishes its layout for the placement; the entry goes when the body unmounts. */+export const useGalleryLayout = (+ region: GalleryRegion+): { layout: GalleryLayoutMode; rootRef: Ref<HTMLDivElement> } => {+ const store = useGalleryLayoutStore();+ const layout = useGalleryLayoutMode(region);+ const rootRef = useCallback(+ (node: HTMLDivElement | null) => {+ if (!node) {+ return;}- });- observer.observe(node);+ const observer = new ResizeObserver((entries) => {+ const widthPx = entries[0]?.contentRect.width;++ if (typeof widthPx === 'number' && widthPx > 0) {+ store.set(region, getGalleryLayout({ region, widthPx }));+ }+ });++ observer.observe(node);- return () => observer.disconnect();- });+ return () => {+ observer.disconnect();+ store.delete(region);+ };+ },+ [region, store]+ );return { layout, rootRef };};diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.tsindex e6753ccabe..c4c90b10e3 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.test.ts@@ -210,9 +210,12 @@ describe('gallery state view', () => {};expect(getGalleryStateView(values, boards, [selected]).isComparisonActive).toBe(true);+ expect(getGalleryStateView(values, boards, [selected]).isCompareArmed).toBe(false);expect(getGalleryStateView({ ...values, compareImage: selected }, boards, [selected]).isComparisonActive).toBe(false);+ // The same image on both sides: Select for compare is waiting for the second one.+ expect(getGalleryStateView({ ...values, compareImage: selected }, boards, [selected]).isCompareArmed).toBe(true);expect(getGalleryStateView(values, boards, []).isComparisonActive).toBe(false);const video = createVideoItem('clip');diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.tsindex 87538f1e36..013a1df509 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryStateView.ts@@ -5,6 +5,7 @@ import type { TFunction } from 'i18next';import {ALL_READABLE_BOARDS_ID,isDateBoardId,+ parseGalleryItemKey,toGalleryItemKey,type GalleryItem,type GalleryItemKey,@@ -90,6 +91,8 @@ export interface GalleryStateView {galleryView: GalleryView;/** A compare image is set and differs from the visible image selection. */isComparisonActive: boolean;+ /** Select for compare is waiting for a second image: the compare image is the visible image selection itself. */+ isCompareArmed: 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. */@@ -171,19 +174,50 @@ const isSameGalleryListing = (left: Record<string, unknown>, right: Record<stringallerySemanticReferenceKey(getGallerySemanticImageQuery(left)) ===gallerySemanticReferenceKey(getGallerySemanticImageQuery(right));+const getPrimaryGalleryItemKey = (values: Record<string, unknown>): GalleryItemKey | null => {+ if (typeof values.selectedImageName === 'string') {+ return toGalleryItemKey(parseGalleryItemKey(values.selectedImageName));+ }++ const selectedItem = getSelectedGalleryItemFromValues(values);++ return selectedItem ? toGalleryItemKey(selectedItem) : null;+};++/**+ * Whether a write moved the primary item onto the comparison image the values already held. Select for compare waits+ * for its second image only when the comparison image is set on the selected one; a selection landing on it (a+ * Ctrl/Cmd-click, a range, a deletion's successor) would compare it with itself, so the comparison ends instead.+ */+const movesPrimaryOntoComparison = (previous: Record<string, unknown>, next: Record<string, unknown>): boolean => {+ if (!next.compareImage || next.compareImage !== previous.compareImage) {+ return false;+ }++ const compareImage = getGalleryCompareImage(next);+ const primaryKey = getPrimaryGalleryItemKey(next);++ return (+ compareImage !== null &&+ primaryKey === toGalleryItemKey({ kind: 'image', name: compareImage.imageName }) &&+ primaryKey !== getPrimaryGalleryItemKey(previous)+ );+};+/**- * Gallery values as every write leaves them: the search scope settled, and a selection the write left in place- * dropped when the write changed which items the listing holds (board, view, search, scope, starred or media filter).- * Selection acts on what is on screen, so Delete never reaches items another board or filter hides; clearing a search- * drops it too. The primary item stays for Preview; the grid acts on it only while it is listed. A write that sets the- * selection itself (its list, or the listing stamp every selection writes), such as a reveal landing on its item,- * keeps it. The values themselves when nothing changes.+ * Gallery values as every write leaves them: the search scope settled, a comparison ended by a selection that lands on+ * its comparison image, and a selection the write left in place dropped when the write changed which items the listing+ * holds (board, view, search, scope, starred or media filter). Selection acts on what is on screen, so Delete never+ * reaches items another board or filter hides; clearing a search drops it too. The primary item stays for Preview; the+ * grid acts on it only while it is listed. A write that sets the selection itself (its list, or the listing stamp every+ * selection writes), such as a reveal landing on its item, keeps it. The values themselves when nothing changes.*/export const settleGalleryValues = (previous: Record<string, unknown>,next: Record<string, unknown>): Record<string, unknown> => {- const settled = settleGallerySearchScope(next);+ const scoped = settleGallerySearchScope(next);+ const settled = movesPrimaryOntoComparison(previous, scoped) ? { ...scoped, compareImage: null } : scoped;const setsSelection =settled.selectedImageNames !== previous.selectedImageNames ||settled.selectedImageQuery !== previous.selectedImageQuery;@@ -520,6 +554,7 @@ export const getGalleryStateView = (visibleSelectedItemKey?.startsWith('image:') === true &&compareImageKey !== null &&compareImageKey !== visibleSelectedItemKey;+ const isCompareArmed = compareImageKey !== null && compareImageKey === visibleSelectedItemKey;const semanticImageQuery = getGallerySemanticImageQuery(values);const page = getGalleryPage(values);const selectedImageQuery = getGallerySelectedImageQuery(values);@@ -546,6 +581,7 @@ export const getGalleryStateView = (compareImageKey,galleryView,isComparisonActive,+ isCompareArmed,isSearchActive: isGallerySearchActive(values),items,listingBoardId,diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsxindex 61ce14c16a..66ee4786f8 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerGrid.tsx@@ -7,7 +7,7 @@ import { Box, Icon, Skeleton, Stack, Text } from '@chakra-ui/react';import { toGalleryItemKey } from '@features/gallery/core/items';import { GALLERY_PAGE_SIZE } from '@features/gallery/data/queries';import { getGalleryColumnCountForCell } from '@features/gallery/ui/galleryGridLayout';-import { GalleryTileFrame } from '@features/gallery/ui/GalleryTileFrame';+import { GalleryTileFrame, GalleryTileMedia } from '@features/gallery/ui/GalleryTileFrame';import { Button } from '@platform/ui/Button';import { Scrollable } from '@platform/ui/Scrollable';import { CheckIcon } from 'lucide-react';@@ -91,19 +91,25 @@ const GalleryPickerTile = memo(function GalleryPickerTile({data-item-index={index}data-item-key={key}id={galleryPickerOptionId(idBase, index)}- isSelected={key === currentKey || state === 'added'}item={item}role="option"title={unsupportedLabel}>- <img- alt=""- decoding="async"- draggable={false}- loading="lazy"- src={item.thumbnailUrl || item.fullUrl}- style={IMG_STYLE}- />+ <GalleryTileMedia+ fit="square"+ height={item.height}+ isSelected={key === currentKey || state === 'added'}+ width={item.width}+ >+ <img+ alt=""+ decoding="async"+ draggable={false}+ loading="lazy"+ src={item.thumbnailUrl || item.fullUrl}+ style={IMG_STYLE}+ />+ </GalleryTileMedia>{state === 'added' ? (<BoxalignItems="center"diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsxindex 185997a51a..9bfafc6df3 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.browser.test.tsx@@ -8,11 +8,13 @@ import { ChakraProvider } from '@chakra-ui/react';import { getGalleryUploadAccept, legacyGeneratedImageToGalleryItem } from '@features/gallery/core/items';import { GalleryUiProvider } from '@features/gallery/react';import { GalleryHostProvider } from '@features/gallery/ui/GalleryUiContext';+import { Row } from '@platform/ui/Row';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act, useCallback, useState } 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 { getGalleryPickerSelectionAfterPick, type GalleryPickerSelection } from './galleryPicker';import { GalleryPickerPopover } from './GalleryPickerPopover';@@ -301,6 +303,39 @@ afterEach(async () => {});describe('GalleryPickerPopover', () => {+ it('keeps its trigger in the hover look while the picker is open, and lets it go on close', async () => {+ // A list-row trigger, as Generate's "Add reference image" is: its hover look is the row fill.+ const trigger = await renderPicker(+ <GalleryPickerPopover accept={['image']} label="Choose image" onPick={onPick}>+ <Row asChild>+ <button type="button">Choose image</button>+ </Row>+ </GalleryPickerPopover>+ );+ // Read once the row's background transition has finished, so no reading is a frame between two looks.+ const background = async () => {+ await vi.waitFor(() => expect(trigger.getAnimations()).toHaveLength(0));+ return getComputedStyle(trigger).backgroundColor;+ };+ const resting = await background();++ await userEvent.hover(trigger);+ const hovered = await background();+ expect(hovered).not.toBe(resting);+ await userEvent.unhover(trigger);+ expect(await background()).toBe(resting);++ await act(() => trigger.click());+ await vi.waitFor(() => expect(document.querySelector(OPEN_DIALOG)).not.toBeNull());+ expect(trigger.hasAttribute('data-hover')).toBe(true);+ expect(await background()).toBe(hovered);++ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.querySelector(OPEN_DIALOG)).toBeNull());+ expect(trigger.hasAttribute('data-hover')).toBe(false);+ expect(await background()).toBe(resting);+ });+it('opens with the search focused and the gallery selection ready to pick with Enter', async () => {const { dialog, trigger } = await openPicker();const input = getSearchInput(dialog);@@ -880,6 +915,20 @@ describe('GalleryPickerPopover', () => {expect(galleryCommands.selectBoard).not.toHaveBeenCalled();});+ // Popover content sets a larger text style than the workbench body the Gallery widget's rows sit in.+ it("lists boards at the Gallery widget's board label size", async () => {+ const { dialog } = await openPicker();++ await act(() => dialog.querySelector<HTMLButtonElement>('[aria-expanded]')?.click());+ const label = await vi.waitFor(() => {+ const found = getBoardRow(dialog, 'Dogs')?.querySelector('p');+ expect(found).toBeTruthy();+ return found!;+ });++ expect(getComputedStyle(label).fontSize).toBe(getComputedStyle(document.body).fontSize);+ });+// Assert video acceptance through the rendered picker; the regression was view wiring rather than the// accept-list builder.it('offers the full video and audio list on a video-kind picker', async () => {diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsxindex ab84af8186..aecfc1c9ee 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerPopover.tsx@@ -28,7 +28,7 @@ const SINGLE_SELECTION: GalleryPickerSelection = { mode: 'single' };export interface GalleryPickerPopoverProps {accept: GalleryPickerAccept;- /** The trigger element; must accept a ref and a click handler. */+ /** The trigger element; must accept a ref and a click handler. It takes `data-hover` while the picker is open. */children: ReactElement;/** Shared with a Tooltip wrapping an icon-only trigger (see `useTooltipTriggerIds`). */ids?: { trigger: string };@@ -74,7 +74,11 @@ export const GalleryPickerPopover = ({unmountOnExitonOpenChange={handleOpenChange}>- <Popover.Trigger asChild>{children}</Popover.Trigger>+ {/* Pointed while its picker is open: `data-hover` is what the theme's hover styles (buttons, rows, drop zones)+ already match, so each trigger keeps its own hover look rather than a new one. */}+ <Popover.Trigger asChild data-hover={isOpen ? '' : undefined}>+ {children}+ </Popover.Trigger><Portal><Popover.Positioner><PopoverContentdiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsxindex 5ac1e90682..79d8acdb2e 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/picker/GalleryPickerView.tsx@@ -521,7 +521,8 @@ export const GalleryPickerView = ({</IconButton></Tooltip></HStack>- <Box pt="1.5" px="2">+ {/* The same space below as above: the grid's own padding scrolls away, which would leave tiles under the field. */}+ <Box pb="1.5" pt="1.5" px="2"><GallerySearchFieldref={attachSearchInput}ariaLabel={searchLabel}diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.tsindex 9c2db96278..6e48a6b34c 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/useGalleryUploadAction.ts@@ -1,5 +1,7 @@import type { GalleryItem } from '@features/gallery/core/items';import type { GalleryBoard, GalleryView } from '@features/gallery/core/types';+import type { QueryClient } from '@tanstack/react-query';+import type { TFunction } from 'i18next';import { canOnBoard } from '@features/gallery/core/boardAccess';import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';@@ -35,6 +37,7 @@ import { useQueryClient } from '@tanstack/react-query';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';+import type { GalleryCommandsPort, GalleryNotificationsPort } from './GalleryUiContext';import type { GalleryActions } from './GalleryWidgetContext';import { useGalleryHost, useOptionalGalleryUi } from './GalleryUiContext';@@ -44,18 +47,17 @@ const toErrorMessage = (error: unknown): string => (error instanceof Error ? errconst isGalleryBoardId = (boardId: string): boolean => boardId !== 'none' && !isInvalidGalleryBoardDestination(boardId);const uploadLogger = createLogger({ area: 'upload', namespace: 'gallery' });-export const useGalleryUploadAction = ({- boards,- getCurrentGalleryLocation,- revealInReceivingTab = false,- selectedBoardId: selectedBoardIdOrGetter,-}: {- boards: GalleryBoard[];+export interface GalleryUploadOptions {+ boards: readonly GalleryBoard[];+ /** Selects the newest upload where the Gallery shows it; absent hosts leave the selection alone. */+ gallery?: Pick<GalleryCommandsPort, 'selectItem' | 'setView'>;/*** Where the Gallery widget is showing on completion; the newest upload visible there gets selected. Omit to leave* the selection alone, as hosts without a workbench must.*/getCurrentGalleryLocation?: () => { galleryView: GalleryView; selectedBoardId: string };+ notifications: GalleryNotificationsPort;+ queryClient: QueryClient;/*** The upload was made in the Gallery itself: when none of it landed on the tab showing, switch to the tab that* received it so it is seen. Uploads made elsewhere (a paste bound for Canvas) leave the Gallery's tab alone.@@ -67,240 +69,270 @@ export const useGalleryUploadAction = ({* must not re-render on board changes.*/selectedBoardId: string | (() => string);-}): GalleryActions['uploadFiles'] => {- const { notifications } = useGalleryHost();- const gallery = useOptionalGalleryUi()?.gallery;- const queryClient = useQueryClient();- const { t } = useTranslation();+ t: TFunction;+}- return useCallback(- async (files) => {- const owner = captureAccountScope();- // Where the Gallery was when the upload started: only while it is still there may the upload switch its tab.- const launchLocation = getCurrentGalleryLocation?.();- const readSelectedBoardId = () =>- 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 [];- }+/**+ * Uploads media files to a board and reports how it went: refusals before anything is sent, then a summary of what+ * landed or why nothing did. Resolves to the uploaded items, empty when nothing landed or the account changed on the+ * way. For callers outside React (a file dropped on Canvas); components use {@link useGalleryUploadAction}.+ */+export const uploadGalleryFiles = async (+ files: File[],+ {+ boards,+ gallery,+ getCurrentGalleryLocation,+ notifications,+ queryClient,+ revealInReceivingTab = false,+ selectedBoardId: selectedBoardIdOrGetter,+ t,+ }: GalleryUploadOptions+): Promise<GalleryItem[]> => {+ const owner = captureAccountScope();+ // Where the Gallery was when the upload started: only while it is still there may the upload switch its tab.+ const launchLocation = getCurrentGalleryLocation?.();+ const readSelectedBoardId = () =>+ typeof selectedBoardIdOrGetter === 'function' ? selectedBoardIdOrGetter() : selectedBoardIdOrGetter;+ let selectedBoardId = readSelectedBoardId();- // 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.- if (isGalleryBoardId(selectedBoardId)) {- await ensureGalleryBoardDestinations(queryClient);- if (!isAccountScopeCurrent(owner)) {- return [];- }- 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 [];+ }- if (isDateBoardId(selectedBoardId)) {- notifications.reportError({- area: 'gallery-upload',- message: t('widgets.gallery.uploadDateBoardUnavailable'),- 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.+ if (isGalleryBoardId(selectedBoardId)) {+ await ensureGalleryBoardDestinations(queryClient);+ if (!isAccountScopeCurrent(owner)) {+ return [];+ }+ selectedBoardId = readSelectedBoardId();+ }- const accepted = files.flatMap((file) => {- const classification = classifyGalleryUpload(file);+ if (isDateBoardId(selectedBoardId)) {+ notifications.reportError({+ area: 'gallery-upload',+ message: t('widgets.gallery.uploadDateBoardUnavailable'),+ namespace: 'gallery',+ });+ return [];+ }- return classification ? [{ file, kind: classification.kind }] : [];- });+ const accepted = files.flatMap((file) => {+ const classification = classifyGalleryUpload(file);- if (accepted.length === 0) {- notifications.reportError({- area: 'gallery-upload',- message: t('widgets.gallery.uploadUnsupported'),- namespace: 'gallery',- });- return [];- }+ return classification ? [{ file, kind: classification.kind }] : [];+ });- const getBoard = (boardId: string) => boards.find((board) => board.id === boardId);- const selectedBoard = getBoard(selectedBoardId);- const targetBoardName = selectedBoard- ? getGalleryBoardLabel(selectedBoard, t)- : t('widgets.gallery.uncategorized');-- // Refused before any upload: the server would refuse each file, leaving nothing but errors. The reason comes- // from the listing that decided, not the panel's older view of the board. The listing is read again at once,- // so the panel stops offering the board and the next upload is judged afresh.- if (isGalleryBoardId(selectedBoardId) && !canAddToCachedGalleryBoard(selectedBoardId, queryClient)) {- const cachedBoard = getCachedGalleryBoard(selectedBoardId, queryClient);- const cachedBoardName = cachedBoard ? getGalleryBoardLabel(cachedBoard, t) : targetBoardName;-- notifications.reportError({- area: 'gallery-upload',- message:- cachedBoard && !canOnBoard(cachedBoard, 'add_media')- ? t('widgets.gallery.uploadsUnavailableForViewOnlyBoard', { name: cachedBoardName })- : cachedBoard || selectedBoard- ? t('widgets.gallery.uploadsUnavailableForBoard', { name: cachedBoardName })- : t('widgets.gallery.uploadsUnavailableForUnlistedBoard'),- namespace: 'gallery',- });- void invalidateGalleryBoardDestinations(queryClient, owner);- return [];- }- const recordError = (error: unknown) =>- notifications.reportError({ area: 'gallery-actions', message: toErrorMessage(error), namespace: 'gallery' });-- try {- // A virtual board holds no uploads; a real board was judged above.- const targetBoardId = isGalleryBoardId(selectedBoardId) ? selectedBoardId : 'none';- const imageUploads = accepted.filter((upload) => upload.kind === 'image');- const videoUploads = accepted.filter((upload) => upload.kind === 'video');- const imageResultsPromise = Promise.allSettled(- imageUploads.map(({ file }) => uploadGalleryImage(file, targetBoardId, { signal: owner.signal }))- );- const videoResultsPromise = (async () => {- const results: PromiseSettledResult<GalleryItem>[] = [];-- for (const { file } of videoUploads) {- owner.signal.throwIfAborted();-- try {- results.push({- status: 'fulfilled',- value: await uploadGalleryVideo(file, targetBoardId, { signal: owner.signal }),- });- } catch (reason: unknown) {- if (owner.signal.aborted) {- throw reason;- }-- results.push({ reason, status: 'rejected' });- }- }+ if (accepted.length === 0) {+ notifications.reportError({+ area: 'gallery-upload',+ message: t('widgets.gallery.uploadUnsupported'),+ namespace: 'gallery',+ });+ return [];+ }- return results;- })();- const [imageResults, videoResults] = await Promise.all([imageResultsPromise, videoResultsPromise]);-- assertAccountScopeCurrent(owner);- const uploadedImages = imageResults.flatMap((result) =>- result.status === 'fulfilled' ? [legacyGeneratedImageToGalleryItem(result.value)] : []- );- const uploadedVideos = videoResults.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []));- const uploadedItems = [...uploadedImages, ...uploadedVideos];- const failedCount = files.length - uploadedItems.length;- const firstRejection = [...imageResults, ...videoResults].find((result) => result.status === 'rejected');-- // A total failure is reported once, by the notification path below.- if (uploadedItems.length > 0) {- uploadLogger[failedCount > 0 ? 'warn' : 'info']({- context: {- boardId: targetBoardId,- failed: failedCount,- images: uploadedImages.length,- requested: files.length,- videos: uploadedVideos.length,- },- error: firstRejection?.reason,- message:- failedCount > 0- ? `Uploaded ${uploadedItems.length} of ${files.length} files`- : `Uploaded ${uploadedItems.length} files`,- name: failedCount > 0 ? 'gallery.upload-partial' : 'gallery.upload-completed',- });- }+ // A caller without the panel's listing names the board from the cached listing that decided.+ const selectedBoard =+ boards.find((board) => board.id === selectedBoardId) ?? getCachedGalleryBoard(selectedBoardId, queryClient);+ const targetBoardName = selectedBoard ? getGalleryBoardLabel(selectedBoard, t) : t('widgets.gallery.uncategorized');- // What landed is listed; a board that refused a file leaves the listing's view of it stale. Either way the- // gallery, boards included, reads again.- void invalidateGallery(queryClient);+ // Refused before any upload: the server would refuse each file, leaving nothing but errors. The reason comes+ // from the listing that decided, not the panel's older view of the board. The listing is read again at once,+ // so the panel stops offering the board and the next upload is judged afresh.+ if (isGalleryBoardId(selectedBoardId) && !canAddToCachedGalleryBoard(selectedBoardId, queryClient)) {+ const cachedBoard = getCachedGalleryBoard(selectedBoardId, queryClient);+ const cachedBoardName = cachedBoard ? getGalleryBoardLabel(cachedBoard, t) : targetBoardName;- if (uploadedItems.length === 0) {- const fallback = t('widgets.gallery.uploadFailed', { failed: failedCount });+ notifications.reportError({+ area: 'gallery-upload',+ message:+ cachedBoard && !canOnBoard(cachedBoard, 'add_media')+ ? t('widgets.gallery.uploadsUnavailableForViewOnlyBoard', { name: cachedBoardName })+ : cachedBoard || selectedBoard+ ? t('widgets.gallery.uploadsUnavailableForBoard', { name: cachedBoardName })+ : t('widgets.gallery.uploadsUnavailableForUnlistedBoard'),+ namespace: 'gallery',+ });+ void invalidateGalleryBoardDestinations(queryClient, owner);+ return [];+ }+ const recordError = (error: unknown) =>+ notifications.reportError({ area: 'gallery-actions', message: toErrorMessage(error), namespace: 'gallery' });- notifications.reportError({- area: 'gallery-upload',- message: firstRejection ? getApiErrorMessage(firstRejection.reason, fallback) : fallback,- namespace: 'gallery',+ try {+ // A virtual board holds no uploads; a real board was judged above.+ const targetBoardId = isGalleryBoardId(selectedBoardId) ? selectedBoardId : 'none';+ const imageUploads = accepted.filter((upload) => upload.kind === 'image');+ const videoUploads = accepted.filter((upload) => upload.kind === 'video');+ const imageResultsPromise = Promise.allSettled(+ imageUploads.map(({ file }) => uploadGalleryImage(file, targetBoardId, { signal: owner.signal }))+ );+ const videoResultsPromise = (async () => {+ const results: PromiseSettledResult<GalleryItem>[] = [];++ for (const { file } of videoUploads) {+ owner.signal.throwIfAborted();++ try {+ results.push({+ status: 'fulfilled',+ value: await uploadGalleryVideo(file, targetBoardId, { signal: owner.signal }),});- return [];- }+ } catch (reason: unknown) {+ if (owner.signal.aborted) {+ throw reason;+ }- const currentGalleryLocation = getCurrentGalleryLocation?.();- const uploadsOnBoard = currentGalleryLocation- ? uploadedItems.filter((item) => item.boardId === currentGalleryLocation.selectedBoardId)- : [];- const visibleUploads = uploadsOnBoard.filter(- (item) => getGalleryItemView(item) === currentGalleryLocation?.galleryView- );- // Uploaded images and videos land on different tabs; when nothing landed on the one showing, switch to the- // one that received them, so the upload is seen. A mixed upload always has some on the tab showing. A Gallery- // the user moved while the upload ran keeps where they took it.- const isGalleryWhereLaunched =- revealInReceivingTab &&- launchLocation !== undefined &&- currentGalleryLocation?.galleryView === launchLocation.galleryView &&- currentGalleryLocation.selectedBoardId === launchLocation.selectedBoardId;- const receivingView =- visibleUploads.length === 0 && isGalleryWhereLaunched && uploadsOnBoard[0]- ? getGalleryItemView(uploadsOnBoard[0])- : null;- const shownUploads = receivingView- ? uploadsOnBoard.filter((item) => getGalleryItemView(item) === receivingView)- : visibleUploads;- const newestShownUpload = shownUploads.reduce<GalleryItem | undefined>(- (newest, item) =>- newest === undefined || compareGalleryItems(item, newest, { orderDir: 'DESC' }) < 0 ? item : newest,- undefined- );-- if (gallery && receivingView) {- gallery.setView(receivingView);- }- if (newestShownUpload) {- gallery?.selectItem(newestShownUpload);+ results.push({ reason, status: 'rejected' });}+ }- const media = formatGalleryMediaCounts(t, { images: uploadedImages.length, videos: uploadedVideos.length });- const message = [- t('widgets.gallery.uploadSummary', { board: targetBoardName, media }),- failedCount > 0 ? t('widgets.gallery.uploadFailedCount', { count: failedCount }) : '',- uploadedImages.length > 0 && uploadedVideos.length > 0 ? t('widgets.gallery.uploadSplit') : '',- ]- .filter(Boolean)- .join(' ');- notifications.add({- kind: 'success',- message,- title: t(- failedCount > 0 ? 'widgets.gallery.uploadPartialTitle' : 'widgets.gallery.uploadSuccessTitle',- failedCount > 0 ? { succeeded: uploadedItems.length, total: files.length } : { count: uploadedItems.length }- ),- });-- return uploadedItems;- } catch (error: unknown) {- if (isAccountScopeCurrent(owner)) {- recordError(error);- }+ return results;+ })();+ const [imageResults, videoResults] = await Promise.all([imageResultsPromise, videoResultsPromise]);- return [];- }- },- [- boards,- gallery,- getCurrentGalleryLocation,- notifications,- queryClient,- revealInReceivingTab,- selectedBoardIdOrGetter,- t,+ assertAccountScopeCurrent(owner);+ const uploadedImages = imageResults.flatMap((result) =>+ result.status === 'fulfilled' ? [legacyGeneratedImageToGalleryItem(result.value)] : []+ );+ const uploadedVideos = videoResults.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []));+ const uploadedItems = [...uploadedImages, ...uploadedVideos];+ const failedCount = files.length - uploadedItems.length;+ const firstRejection = [...imageResults, ...videoResults].find((result) => result.status === 'rejected');++ // A total failure is reported once, by the notification path below.+ if (uploadedItems.length > 0) {+ uploadLogger[failedCount > 0 ? 'warn' : 'info']({+ context: {+ boardId: targetBoardId,+ failed: failedCount,+ images: uploadedImages.length,+ requested: files.length,+ videos: uploadedVideos.length,+ },+ error: firstRejection?.reason,+ message:+ failedCount > 0+ ? `Uploaded ${uploadedItems.length} of ${files.length} files`+ : `Uploaded ${uploadedItems.length} files`,+ name: failedCount > 0 ? 'gallery.upload-partial' : 'gallery.upload-completed',+ });+ }++ // What landed is listed; a board that refused a file leaves the listing's view of it stale. Either way the+ // gallery, boards included, reads again.+ void invalidateGallery(queryClient);++ if (uploadedItems.length === 0) {+ const fallback = t('widgets.gallery.uploadFailed', { failed: failedCount });++ notifications.reportError({+ area: 'gallery-upload',+ message: firstRejection ? getApiErrorMessage(firstRejection.reason, fallback) : fallback,+ namespace: 'gallery',+ });+ return [];+ }++ const currentGalleryLocation = getCurrentGalleryLocation?.();+ const uploadsOnBoard = currentGalleryLocation+ ? uploadedItems.filter((item) => item.boardId === currentGalleryLocation.selectedBoardId)+ : [];+ const visibleUploads = uploadsOnBoard.filter(+ (item) => getGalleryItemView(item) === currentGalleryLocation?.galleryView+ );+ // Uploaded images and videos land on different tabs; when nothing landed on the one showing, switch to the+ // one that received them, so the upload is seen. A mixed upload always has some on the tab showing. A Gallery+ // the user moved while the upload ran keeps where they took it.+ const isGalleryWhereLaunched =+ revealInReceivingTab &&+ launchLocation !== undefined &&+ currentGalleryLocation?.galleryView === launchLocation.galleryView &&+ currentGalleryLocation.selectedBoardId === launchLocation.selectedBoardId;+ const receivingView =+ visibleUploads.length === 0 && isGalleryWhereLaunched && uploadsOnBoard[0]+ ? getGalleryItemView(uploadsOnBoard[0])+ : null;+ const shownUploads = receivingView+ ? uploadsOnBoard.filter((item) => getGalleryItemView(item) === receivingView)+ : visibleUploads;+ const newestShownUpload = shownUploads.reduce<GalleryItem | undefined>(+ (newest, item) =>+ newest === undefined || compareGalleryItems(item, newest, { orderDir: 'DESC' }) < 0 ? item : newest,+ undefined+ );++ if (gallery && receivingView) {+ gallery.setView(receivingView);+ }+ if (newestShownUpload) {+ gallery?.selectItem(newestShownUpload);+ }++ const media = formatGalleryMediaCounts(t, { images: uploadedImages.length, videos: uploadedVideos.length });+ const message = [+ t('widgets.gallery.uploadSummary', { board: targetBoardName, media }),+ failedCount > 0 ? t('widgets.gallery.uploadFailedCount', { count: failedCount }) : '',+ uploadedImages.length > 0 && uploadedVideos.length > 0 ? t('widgets.gallery.uploadSplit') : '',]+ .filter(Boolean)+ .join(' ');+ notifications.add({+ kind: 'success',+ message,+ title: t(+ failedCount > 0 ? 'widgets.gallery.uploadPartialTitle' : 'widgets.gallery.uploadSuccessTitle',+ failedCount > 0 ? { succeeded: uploadedItems.length, total: files.length } : { count: uploadedItems.length }+ ),+ });++ return uploadedItems;+ } catch (error: unknown) {+ if (isAccountScopeCurrent(owner)) {+ recordError(error);+ }++ return [];+ }+};++export const useGalleryUploadAction = ({+ boards,+ getCurrentGalleryLocation,+ revealInReceivingTab = false,+ selectedBoardId,+}: Pick<+ GalleryUploadOptions,+ 'boards' | 'getCurrentGalleryLocation' | 'revealInReceivingTab' | 'selectedBoardId'+>): GalleryActions['uploadFiles'] => {+ const { notifications } = useGalleryHost();+ const gallery = useOptionalGalleryUi()?.gallery;+ const queryClient = useQueryClient();+ const { t } = useTranslation();++ return useCallback(+ (files) =>+ uploadGalleryFiles(files, {+ boards,+ gallery,+ getCurrentGalleryLocation,+ notifications,+ queryClient,+ revealInReceivingTab,+ selectedBoardId,+ t,+ }),+ [boards, gallery, getCurrentGalleryLocation, notifications, queryClient, revealInReceivingTab, selectedBoardId, t]);};diff --git a/invokeai/frontend/webv2/src/features/generation/components.ts b/invokeai/frontend/webv2/src/features/generation/components.tsindex 29acfb22f7..6a8e3b4664 100644--- a/invokeai/frontend/webv2/src/features/generation/components.ts+++ b/invokeai/frontend/webv2/src/features/generation/components.ts@@ -5,11 +5,16 @@ export {type AspectRatioPickerProps,} from './ui/shared/AspectRatioPicker';export { NegativePromptField } from './ui/promptFields/NegativePromptField';+export { AddNegativePromptButton, RemoveNegativePromptButton } from './ui/promptFields/NegativePromptToggle';export { PositivePromptField } from './ui/promptFields/PositivePromptField';+export type { PromptTemplateChange } from './ui/promptFields/PromptTemplatesButton';export { PromptTextarea } from './ui/promptFields/PromptTextarea';export { SeedField, type SeedFieldProps } from './ui/shared/SeedField';export { FluxReduxControls } from './ui/reference-images/ReferenceImageControls';export { GenerateCollapsibleSection as GenerationSettingsSection } from './ui/shared/GenerateCollapsibleSection';+export { GenerationSectionIssuesProvider } from './ui/shared/GenerateIssues';+export { GenerationSectionJumpMenu } from './ui/shared/GenerationSectionJumpMenu';+export { GenerationSectionPanel } from './ui/shared/sectionPanel';export { CapabilitiesGate, type CapabilitiesGateProps } from './ui/shared/CapabilitiesGate';export { ConceptList, ConceptRow, type ConceptModelPort, type ConceptRowProps } from './ui/shared/ConceptRow';// Only lazy widget UIs edit concept lists; exporting it from `settings` would put it in the editor's startup graph.diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.tsindex 726f871ca5..f89d4e9aa8 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts@@ -41,6 +41,8 @@ import {getPromptPolicy,getSchedulerOptions,getSettingsWithModelDefaults,+ getRecallDefaultVae,+ resolveModelDefaultVae,isReferenceImageSupported,isComponentCompatibleWithModel,isGenerateModelSelectable,@@ -52,7 +54,7 @@ import {QWEN_IMAGE_21_NO_VISION_TOWER_REASON,withAddedReferenceImages,} from './baseGenerationPolicies';-import { describeGenerationIssue, getGenerationIssueFixPatch } from './generationIssues';+import { describeGenerationIssue, type GenerationIssue, getGenerationIssueFixPatch } from './generationIssues';import { collectGenerationIssueScenarios } from './generationIssues.testing';import { getActiveRefiner } from './sdxlRefiner';import { SUPPORTED_GENERATE_BASES } from './supportedBases';@@ -792,7 +794,7 @@ describe('component policies', () => {vae: qwenImageVae,}))- ).toEqual(['qwen-image model cannot use reference image 1. Turn it off, or remove it.']);+ ).toEqual(['qwen-image model cannot use Reference image 1. Turn it off, or remove it.']);});it('allows text-only prompts, which is what the GGUF encoder is for', () => {@@ -1014,7 +1016,7 @@ describe('component policies', () => {settings,'img2img');- expect(reasons).toContain('External Model cannot use reference image 1. Turn it off, or remove it.');+ expect(reasons).toContain('External Model cannot use Reference image 1. Turn it off, or remove it.');expect(reasons.filter((reason) => reason.includes('images total'))).toEqual([]);});@@ -1437,6 +1439,43 @@ describe('component policies', () => {).toBe(loras);});+ describe('a default VAE', () => {+ const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };+ const resolve = (base: string, vae: string | null | undefined, vaeModels: VaeModelConfig[] = [fluxVae]) => {+ const model = createModel(base, vae === undefined ? {} : { default_settings: { vae } });++ return resolveModelDefaultVae(model, createSettings(model), vaeModels);+ };++ it('applies one that is installed and fits, by shared VAE compatibility', () => {+ // Cross-base by the shared rule: Z-Image takes the FLUX VAE.+ expect(resolve('z-image', 'flux-vae')).toEqual({ kind: 'apply', vae: fluxVae });+ expect(resolve('sdxl', undefined)).toEqual({ kind: 'none' });+ expect(resolve('sdxl', null)).toEqual({ kind: 'none' });+ });++ // Bundled: SDXL has no VAE slot; SD3's is an optional override. Required: FLUX.1's VAE is a component.+ it.each([+ ['sdxl', 'default', { kind: 'apply', vae: null }],+ ['sd-3', 'default', { kind: 'apply', vae: null }],+ ['flux', 'default', { kind: 'none' }],+ ['sdxl', 'gone', { hasBundledVae: true, kind: 'missing' }],+ // Installed, but for another family.+ ['sdxl', 'flux-vae', { hasBundledVae: true, kind: 'missing' }],+ ['sd-3', 'gone', { hasBundledVae: true, kind: 'missing' }],+ ['flux', 'gone', { hasBundledVae: false, kind: 'missing' }],+ ] as const)('classifies %s with %s by whether a VAE is bundled', (base, vae, expected) => {+ expect(resolve(base, vae)).toEqual(expected);+ });++ it('recalls the bundled VAE for one that cannot apply, and keeps the current VAE only where one is required', () => {+ expect(getRecallDefaultVae({ kind: 'apply', vae: fluxVae })).toBe(fluxVae);+ expect(getRecallDefaultVae({ hasBundledVae: true, kind: 'missing' })).toBeNull();+ expect(getRecallDefaultVae({ hasBundledVae: false, kind: 'missing' })).toBeUndefined();+ expect(getRecallDefaultVae({ kind: 'none' })).toBeUndefined();+ });+ });+it('keeps selected VAE when applying model defaults without a VAE override', () => {const model = createModel('sdxl', { default_settings: { steps: 12 } });const settings = createSettings(model, { vae: sdxlVae });@@ -1773,7 +1812,7 @@ describe('component policies', () => {expect(getGenerationValidationReasons(krea2, styleSettings)).toEqual([]);expect(getGenerationValidationReasons(createModel('sd-3'), styleSettings)).toEqual([- 'sd-3 model cannot use reference image 1. Turn it off, or remove it.',+ 'sd-3 model cannot use Reference image 1. Turn it off, or remove it.',]);});@@ -2379,7 +2418,7 @@ describe('component policies', () => {],}))- ).toContain('sd-3 model cannot use reference image 1. Turn it off, or remove it.');+ ).toContain('sd-3 model cannot use Reference image 1. Turn it off, or remove it.');});it('blocks Qwen-Image-2.1 references whose encoder has no vision tower', () => {@@ -3513,6 +3552,42 @@ describe('generation issues', () => {}});+ it('names a reference image in its issues as its row does: its own name, else its position', async () => {+ const instance = i18n.createInstance();+ await instance.init({+ initAsync: false,+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: englishCatalog } },+ });+ const t = (key: string, values?: Record<string, unknown>) => instance.t(key, values);+ const aboutOneReference = (issues: GenerationIssue[]) =>+ issues.filter((issue) => issue.target.referenceImageId !== undefined);+ const named = aboutOneReference(collectGenerationIssueScenarios({ namedReferences: true }));++ // Every kind: a missing image, adapter, Redux or Kontext model, a strength, an unsupported kind, a model not+ // installed. Unnamed references keep their positional default, which the test above words.+ expect(new Set(named.map(({ messageKey }) => messageKey?.replace('widgets.generate.issues.', '')))).toEqual(+ new Set([+ 'referenceImageNeedsImage',+ 'referenceImageNeedsIpAdapter',+ 'referenceImageNeedsKontext',+ 'referenceImageNeedsRedux',+ 'referenceImageStrength',+ 'referenceImageUnsupported',+ 'referenceModelNotInstalled',+ ])+ );++ for (const issue of named) {+ const name = `Name of ${issue.target.referenceImageId}`;++ expect(issue.message).toContain(name);+ expect(issue.message).not.toMatch(/reference image \d/i);+ expect(describeGenerationIssue(t, issue)).toBe(issue.message);+ }+ });+it('names every subject a switch can report, and no others, in the locale', () => {expect(new Set(Object.keys(localeGroup('switchSubjects')).map(withoutPluralSuffix))).toEqual(new Set(GENERATE_MODEL_SWITCH_SUBJECTS)diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.tsindex f62fe5b836..b05f804ab5 100644--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts@@ -29,6 +29,7 @@ import type {GenerateSettings,MainModelConfig,PidMode,+ VaeModelConfig,} from './types';import {@@ -57,6 +58,7 @@ import {isQwen3Vl4bEncoder,isSelfContainedSDNQFlux1Pipeline,isVaeAcceptedByBase,+ isVaeCompatibleWithGenerateModel,isZImageQwen3Encoder,type GenerateComponentFilter,} from './componentCompatibility';@@ -684,6 +686,67 @@ export const getSettingsWithModelDefaults = (};};+/** The VAE a model's defaults choose, classified; each context states what it does with `missing`. */+export type ModelDefaultVae =+ /** Sets none, or the "default" sentinel where the VAE is a required component with nothing bundled. */+ | { kind: 'none' }+ /**+ * Names a VAE that is not installed or does not fit the model. `hasBundledVae` says whether the model and settings+ * have a bundled VAE to fall back to (the VAE component is not required).+ */+ | { kind: 'missing'; hasBundledVae: boolean }+ /** `null` is the bundled VAE, which the "default" sentinel asks for wherever there is one. */+ | { kind: 'apply'; vae: VaeModelConfig | null };++/** Whether the model and settings need a VAE component, having no bundled VAE (or component source) to use. */+const isVaeComponentRequired = (model: MainModelConfig, settings: GenerateSettings): boolean => {+ const vaeSlotPolicy = getComponentSectionPolicy(model, settings).slots.find((slotPolicy) => slotPolicy.key === 'vae');++ return Boolean(vaeSlotPolicy?.required?.(getComponentPolicyContext(model, settings)));+};++/**+ * The one classification of a model's default VAE. The Model Manager stores "default" when the VAE default is on with+ * no VAE picked: that is the bundled VAE, which only a model whose VAE is a required component lacks. Requiredness+ * follows the component policy, so it reads the settings (a component source can bundle one).+ */+export const resolveModelDefaultVae = (+ model: GenerateModelConfig,+ settings: GenerateSettings,+ vaeModels: readonly VaeModelConfig[]+): ModelDefaultVae => {+ const key = (model.default_settings as { vae?: unknown } | null | undefined)?.vae;++ if (model.type !== 'main' || typeof key !== 'string') {+ return { kind: 'none' };+ }++ const hasBundledVae = !isVaeComponentRequired(model, settings);++ if (key === '' || key === 'default') {+ return hasBundledVae ? { kind: 'apply', vae: null } : { kind: 'none' };+ }++ const vae = vaeModels.find(+ (candidate) => candidate.key === key && isVaeCompatibleWithGenerateModel(model, candidate)+ );++ return vae ? { kind: 'apply', vae } : { kind: 'missing', hasBundledVae };+};++/**+ * Recall's policy (a model switch from recalled parameters or an image, and graph export): the model's default VAE,+ * else the bundled VAE when the default cannot apply, as recall always did, so an image made with the bundled VAE is+ * reproduced. Only where the VAE is required and nothing is bundled does the current VAE stay (`undefined`), since+ * clearing it would leave the form unable to run.+ */+export const getRecallDefaultVae = (defaultVae: ModelDefaultVae): VaeModelConfig | null | undefined =>+ defaultVae.kind === 'apply'+ ? defaultVae.vae+ : defaultVae.kind === 'missing' && defaultVae.hasBundledVae+ ? null+ : undefined;+export type GenerateComponentValueKey =| 't5EncoderModel'| 'clipEmbedModel'@@ -2069,6 +2132,46 @@ export const getCompatibleReferenceImages = (});};+/**+ * References as a switch to `model` leaves them, for every path that puts references in front of a model they were+ * not set up for (a model switch, an Undo that brings removed ones back). Incompatible ones are retargeted (see+ * `getCompatibleReferenceImages`); enabled ones the family cannot run together are switched off rather than deleted,+ * so Invoke is not left blocked, the first enabled ones keep running, and a model that takes the rest can turn them on+ * again. A model without references keeps them as they are, all switched off, for the next model that takes them.+ * `retargetedReferenceImages` is the list before the switch-off, for reporting what each step changed. No changes+ * return the same array.+ */+export const reconcileReferenceImagesWithModel = (+ referenceImages: GenerateReferenceImage[],+ model: GenerateModelConfig,+ models: readonly ReferenceModelCandidate[]+): { referenceImages: GenerateReferenceImage[]; retargetedReferenceImages: GenerateReferenceImage[] } => {+ const referencesSupported = takesReferenceImages(model);+ const retargetedReferenceImages = referencesSupported+ ? getCompatibleReferenceImages(referenceImages, model, models)+ : referenceImages;+ const enabledKept: GenerateReferenceImage[] = [];+ let didSwitchOff = false;+ const keptOrSwitchedOff = retargetedReferenceImages.map((referenceImage) => {+ if (!isReferenceImageActive(referenceImage)) {+ return referenceImage;+ }++ if (referencesSupported && canRunWithEnabledReferenceImages(model, enabledKept, referenceImage)) {+ enabledKept.push(referenceImage);+ return referenceImage;+ }++ didSwitchOff = true;+ return { ...referenceImage, isEnabled: false };+ });++ return {+ referenceImages: didSwitchOff ? keptOrSwitchedOff : retargetedReferenceImages,+ retargetedReferenceImages,+ };+};+const getSettingsWithCompatibleModelSelections = (settings: GenerateSettings,model: GenerateModelConfig,@@ -2140,29 +2243,11 @@ const getSettingsWithCompatibleModelSelections = (change('concepts', 'turnedOff', stoppedConcepts);}- // Enabled references the new family cannot run together are switched off rather than deleted: Invoke is not left- // blocked, the first enabled ones keep running, and switching back can turn the rest on again. A model without- // references keeps them as they are, all switched off, for the next model that takes them.- const referencesSupported = takesReferenceImages(model);- const retargetedReferenceImages = referencesSupported- ? getCompatibleReferenceImages(settings.referenceImages, model, models)- : settings.referenceImages;- const enabledKept: GenerateReferenceImage[] = [];- let didSwitchOff = false;- const keptOrSwitchedOff = retargetedReferenceImages.map((referenceImage) => {- if (!isReferenceImageActive(referenceImage)) {- return referenceImage;- }-- if (referencesSupported && canRunWithEnabledReferenceImages(model, enabledKept, referenceImage)) {- enabledKept.push(referenceImage);- return referenceImage;- }-- didSwitchOff = true;- return { ...referenceImage, isEnabled: false };- });- const compatibleReferenceImages = didSwitchOff ? keptOrSwitchedOff : retargetedReferenceImages;+ const { referenceImages: compatibleReferenceImages, retargetedReferenceImages } = reconcileReferenceImagesWithModel(+ settings.referenceImages,+ model,+ models+ );if (compatibleReferenceImages !== settings.referenceImages) {nextSettings.referenceImages = compatibleReferenceImages;@@ -2186,7 +2271,7 @@ const getSettingsWithCompatibleModelSelections = ((referenceImage, index) => retargetedReferenceImages[index] !== referenceImage);const tunedRetargets = retargeted.filter((referenceImage) => !isPreviousDefault(referenceImage)).length;- const switchedOff = keptOrSwitchedOff.filter(+ const switchedOff = compatibleReferenceImages.filter((referenceImage, index) => referenceImage.isEnabled !== retargetedReferenceImages[index]?.isEnabled).length;@@ -2337,6 +2422,20 @@ const issue = (});const MODEL_TARGET: GenerationIssue['target'] = { section: 'model' };++/**+ * How an issue names one reference: its own name, else its position. `describeGenerationIssue` turns the position+ * into the localized default ("Reference image 2"), so the message reads as the reference's row does.+ */+const referenceNameValues = (+ referenceImage: Pick<GenerateReferenceImage, 'name'>,+ position: number+): Record<string, number | string> => ({+ index: position,+ ...(referenceImage.name === undefined ? {} : { referenceName: referenceImage.name }),+});+const englishReferenceName = (referenceImage: Pick<GenerateReferenceImage, 'name'>, position: number): string =>+ referenceImage.name ?? `Reference image ${position}`;/** The reference images as a group (their count, or a rule over all of them); the section lists it above the cards. */const REFERENCE_IMAGES_TARGET: GenerationIssue['target'] = { field: 'referenceImages', section: 'guidance' };/** One reference image: its card shows the issue. */@@ -2445,9 +2544,9 @@ export const getGenerationModelAvailabilityIssues = (issue(`referenceImages:modelNotInstalled:${referenceImage.id}`,'referenceModelNotInstalled',- `Reference image ${index + 1} uses "${config.model.name}", which is not installed. Turn it off, or choose another model for it.`,+ `${englishReferenceName(referenceImage, index + 1)} uses "${config.model.name}", which is not installed. Turn it off, or choose another model for it.`,referenceImageTarget(referenceImage.id),- { index: index + 1, name: config.model.name },+ { ...referenceNameValues(referenceImage, index + 1), name: config.model.name },{ kind: 'turnOffReferenceImages', referenceImageIds: [referenceImage.id] }));@@ -2625,9 +2724,9 @@ const getReferenceImageValidationIssues = (issue(`referenceImages:unsupported:${id}`,'referenceImageUnsupported',- `${model.name} cannot use reference image ${index}. Turn it off, or remove it.`,+ `${model.name} cannot use ${englishReferenceName(referenceImage, index)}. Turn it off, or remove it.`,referenceImageTarget(id),- { index, name: model.name },+ { ...referenceNameValues(referenceImage, index), name: model.name },turnOff));@@ -2639,9 +2738,9 @@ const getReferenceImageValidationIssues = (issue(`referenceImages:needsImage:${id}`,'referenceImageNeedsImage',- `Reference image ${index} needs an image.`,+ `${englishReferenceName(referenceImage, index)} needs an image.`,referenceImageTarget(id),- { index },+ referenceNameValues(referenceImage, index),turnOff));@@ -2653,9 +2752,9 @@ const getReferenceImageValidationIssues = (issue(`referenceImages:needsIpAdapter:${id}`,'referenceImageNeedsIpAdapter',- `Reference image ${index} needs an IP Adapter model for ${model.name}.`,+ `${englishReferenceName(referenceImage, index)} needs an IP Adapter model for ${model.name}.`,referenceImageTarget(id),- { index, name: model.name },+ { ...referenceNameValues(referenceImage, index), name: model.name },turnOff));@@ -2668,9 +2767,9 @@ const getReferenceImageValidationIssues = (issue(`referenceImages:strength:${id}`,'referenceImageStrength',- `Reference image ${index} strength must be between 0 and 2.`,+ `${englishReferenceName(referenceImage, index)} strength must be between 0 and 2.`,referenceImageTarget(id),- { index },+ referenceNameValues(referenceImage, index),turnOff));@@ -2685,9 +2784,9 @@ const getReferenceImageValidationIssues = (issue(`referenceImages:needsRedux:${id}`,'referenceImageNeedsRedux',- `Reference image ${index} needs a FLUX Redux model for ${model.name}.`,+ `${englishReferenceName(referenceImage, index)} needs a FLUX Redux model for ${model.name}.`,referenceImageTarget(id),- { index, name: model.name },+ { ...referenceNameValues(referenceImage, index), name: model.name },turnOff));@@ -2701,9 +2800,9 @@ const getReferenceImageValidationIssues = (issue(`referenceImages:needsKontext:${id}`,'referenceImageNeedsKontext',- `Reference image ${index} needs the selected FLUX Kontext model.`,+ `${englishReferenceName(referenceImage, index)} needs the selected FLUX Kontext model.`,referenceImageTarget(id),- { index },+ referenceNameValues(referenceImage, index),turnOff));diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.tsindex 651311029e..ebf09d7e38 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts@@ -395,6 +395,12 @@ describe('addRegionalGuidance — SD1', () => {expect(hasEdge(g, 'clip_skip', 'clip', 'rg_neg_cond_r1', 'clip')).toBe(true);});+ it.each([null, ''])('adds no negative conditioning for a region whose negative prompt is %j', (negativePrompt) => {+ const g = run(sdBaseGraph(), { base: 'sd-1', regions: [region({ negativePrompt })] });+ expect(g.nodes.rg_neg_cond_r1).toBeUndefined();+ expect(g.edges.some((e) => e.destination.node_id === 'neg_cond_collect')).toBe(false);+ });+it('autoNegative inverts the mask and re-encodes the positive prompt into the negative collector', () => {const g = run(sdBaseGraph(), { base: 'sd-1', regions: [region({ autoNegative: true })] });const invert = nodesOfType(g, 'invert_tensor_mask');@@ -598,6 +604,10 @@ describe('getRegionalGuidanceRejectionReason', () => {it('rejects a region with no prompt and no reference images', () => {expect(getRegionalGuidanceRejectionReason({ ...params, positivePrompt: null })).toMatch(/no prompt or reference/);+ // An added negative prompt left empty carries nothing either.+ expect(getRegionalGuidanceRejectionReason({ ...params, negativePrompt: '', positivePrompt: null })).toMatch(+ /no prompt or reference/+ );});it('accepts an SD region that only carries a negative prompt or a reference image', () => {diff --git a/invokeai/frontend/webv2/src/features/generation/core/generationIssues.testing.ts b/invokeai/frontend/webv2/src/features/generation/core/generationIssues.testing.tsindex c84b786afa..7415b18191 100644--- a/invokeai/frontend/webv2/src/features/generation/core/generationIssues.testing.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/generationIssues.testing.ts@@ -24,10 +24,13 @@ const settingsFor = (main: GenerateModelConfig, overrides: Partial<GenerateSetti...overrides,});const image = { original: { image: { height: 768, image_name: 'reference.png', width: 512 } } };+/** Set while collecting named scenarios: every reference then carries `Name of <id>`. */+let nameReferences = false;const reference = (id: string, config: Record<string, unknown>): GenerateReferenceImage => ({config: { image, ...config } as GenerateReferenceImage['config'],id,isEnabled: true,+ ...(nameReferences ? { name: `Name of ${id}` } : {}),});const ipAdapter = (base: string) => ({base,@@ -48,9 +51,11 @@ const ipAdapterReference = (id: string, overrides: Record<string, unknown> = {})/*** Scenarios that together raise every translated Generate issue, for tests that check each against the locale and- * its renderer. Needs the capability table seeded; leaves it seeded.+ * its renderer. `namedReferences` gives every reference image a name. Needs the capability table seeded; leaves it+ * seeded.*/-export const collectGenerationIssueScenarios = (): GenerationIssue[] => {+export const collectGenerationIssueScenarios = ({ namedReferences = false } = {}): GenerationIssue[] => {+ nameReferences = namedReferences;const sdxl = model('sdxl');const flux = model('flux');const anima = model('anima', { format: 'checkpoint', variant: 'anima_qwen3' });@@ -139,5 +144,7 @@ export const collectGenerationIssueScenarios = (): GenerationIssue[] => {issues.push(...getGenerationValidationIssues(sdxl, sdxlSettings));seedArchitectureCapabilities();+ nameReferences = false;+return issues;};diff --git a/invokeai/frontend/webv2/src/features/generation/core/generationIssues.ts b/invokeai/frontend/webv2/src/features/generation/core/generationIssues.tsindex 3026308c35..8b7ffa9b71 100644--- a/invokeai/frontend/webv2/src/features/generation/core/generationIssues.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/generationIssues.ts@@ -62,11 +62,32 @@ export interface GenerationIssue {fix?: GenerationIssueFix;}-/** The issue text in the active language; issues without a locale entry fall back to their English. */+/** The localized default name of the reference image at a 1-based position, as its row shows it. */+const REFERENCE_IMAGE_DEFAULT_NAME_KEY = 'widgets.generate.referenceImageNumbered';++/**+ * The issue text in the active language; issues without a locale entry fall back to their English. An issue about one+ * reference image names it as its row does (`reference`): its own name, else the localized positional default.+ */export const describeGenerationIssue = (t: (key: string, values?: Record<string, unknown>) => string,issue: Pick<GenerationIssue, 'message' | 'messageKey' | 'messageValues'>-): string => (issue.messageKey ? t(issue.messageKey, { ...issue.messageValues }) : issue.message);+): string => {+ if (!issue.messageKey) {+ return issue.message;+ }++ const values = issue.messageValues ?? {};+ const { referenceName } = values;+ const reference =+ typeof referenceName === 'string'+ ? referenceName+ : typeof values.index === 'number'+ ? t(REFERENCE_IMAGE_DEFAULT_NAME_KEY, { index: values.index })+ : undefined;++ return t(issue.messageKey, reference === undefined ? { ...values } : { ...values, reference });+};/** What applying `fix` does, in the active language: the label of a one-step fix button. */export const describeGenerationIssueFix = (diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex 53bee1f3d7..07c0528903 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -856,7 +856,7 @@ describe('compileGenerateGraph', () => {referenceImages: [animaReference()],vae: qwenImageVae,})- ).toThrow('cannot use reference image 1');+ ).toThrow('cannot use Reference image 1');});});@@ -1061,7 +1061,7 @@ describe('compileGenerateGraph', () => {expect(getEdge(graph, 'denoise_latents', 'ip_adapter')?.source.node_id).toContain('ip_adapter_collector');});- it('generates from the crop while serializing complete original and crop metadata', () => {+ it('generates from the crop while serializing complete original and crop metadata, with the name', () => {const croppedReferenceImage = {crop: {box: { height: 256, width: 320, x: 40, y: 50 },@@ -1084,6 +1084,7 @@ describe('compileGenerateGraph', () => {},id: 'cropped-ref',isEnabled: true,+ name: 'Hero pose',},],});@@ -1095,6 +1096,8 @@ describe('compileGenerateGraph', () => {config: { image: croppedReferenceImage },id: 'cropped-ref',isEnabled: true,+ // The user's label travels with the record so recall can restore it.+ name: 'Hero pose',},]);});diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts b/invokeai/frontend/webv2/src/features/generation/core/graphExport.tsindex 3ea9a30ee6..349fde1ad3 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graphExport.ts@@ -29,6 +29,8 @@ import {isGenerateModelSelectable,isLoraSupported,isReferenceImageSupported,+ getRecallDefaultVae,+ resolveModelDefaultVae,withAddedReferenceImages,} from './baseGenerationPolicies';import { compileCanvasGraph } from './canvas/compileCanvasGraph';@@ -44,8 +46,6 @@ import { resolveGenerateWidgetValues } from './resolveGenerateWidgetValues';import {deriveAspectRatioId,GENERATE_UI_STATE_KEYS,- getModelDefaultVae,- hasModelDefaultVae,isLoraCompatibleWithModel,isLoraModelConfig,isMainModelConfig,@@ -153,16 +153,16 @@ const getSelectableModel = (key: string, models: readonly ModelConfig[]): Generareturn model;};-/** Selecting the model, then "Reset to model defaults", which also applies the model's default VAE. */+/** Selecting the model, then its default VAE by recall's policy (`getRecallDefaultVae`); otherwise the selection's. */const getModelDefaultValues = (model: GenerateModelConfig, models: readonly ModelConfig[]): GenerateWidgetValues => {const { settings } = getGenerateModelSelectionResult({currentValues: getDefaultGenerateSettings(model),model,models,});- const vae = hasModelDefaultVae(model) ? getModelDefaultVae(model, models.filter(isVaeModelConfig)) : settings.vae;+ const vae = getRecallDefaultVae(resolveModelDefaultVae(model, settings, models.filter(isVaeModelConfig)));- return { ...settings, model, vae };+ return { ...settings, model, vae: vae === undefined ? settings.vae : vae };};const withCaseValues = (values: GenerateWidgetValues, input: GraphExportCase): GenerateWidgetValues => ({diff --git a/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.test.ts b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.test.tsindex 39467b31eb..6728548a50 100644--- a/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.test.ts@@ -5,12 +5,66 @@ import { applyProjectPromptDraft, getPromptDraftFromValues, migrateProjectPromptdescribe('project prompt draft', () => {it('normalizes missing prompt values', () => {expect(getPromptDraftFromValues({})).toEqual({+ dynamicPromptsCombinatorial: true,+ dynamicPromptsEnabled: true,+ dynamicPromptsMaxPrompts: 100,+ dynamicPromptsResample: true,+ dynamicPromptsSampleSeed: 0,+ dynamicPromptsSeedBehaviour: 'per-iteration',negativePrompt: '',negativePromptEnabled: true,positivePrompt: '',+ promptTemplate: null,+ promptTemplateViewMode: false,});});+ it('reads the template and its merged view as Generate stores them', () => {+ const template = { id: 'cinematic', name: 'Cinematic', negativePrompt: '', positivePrompt: '{prompt}, film' };++ expect(getPromptDraftFromValues({ promptTemplate: template, promptTemplateViewMode: true })).toMatchObject({+ promptTemplate: template,+ promptTemplateViewMode: true,+ });+ // Nothing to show merged without a template.+ expect(getPromptDraftFromValues({ promptTemplate: { name: 'no id' }, promptTemplateViewMode: true })).toMatchObject(+ { promptTemplate: null, promptTemplateViewMode: false }+ );+ });++ it('applies a template and dynamic prompts setting without touching the other values', () => {+ const template = { id: 'cinematic', name: 'Cinematic', negativePrompt: 'blur', positivePrompt: '{prompt}, film' };+ const values = { dynamicPromptsMaxPrompts: 20, positivePrompt: 'a fox', positivePromptHeightPx: 120 };+ const applied = applyProjectPromptDraft(values, { dynamicPromptsCombinatorial: false, promptTemplate: template });++ expect(applied).toEqual({+ dynamicPromptsCombinatorial: false,+ dynamicPromptsMaxPrompts: 20,+ negativePrompt: '',+ negativePromptEnabled: true,+ positivePrompt: 'a fox',+ positivePromptHeightPx: 120,+ promptTemplate: template,+ promptTemplateViewMode: false,+ });+ });++ it('leaves the merged view when the template is cleared', () => {+ const template = { id: 'cinematic', name: 'Cinematic', negativePrompt: '', positivePrompt: '{prompt}, film' };+ const values = { positivePrompt: 'a fox', promptTemplate: template, promptTemplateViewMode: true };++ expect(applyProjectPromptDraft(values, { promptTemplate: null })).toMatchObject({+ promptTemplate: null,+ promptTemplateViewMode: false,+ });+ });++ it('returns the same values when a patch changes nothing', () => {+ const values = { dynamicPromptsEnabled: false, positivePrompt: 'a fox' };++ expect(applyProjectPromptDraft(values, { dynamicPromptsEnabled: false, positivePrompt: 'a fox' })).toBe(values);+ });+it('patches only shared prompt fields', () => {const values = { negativePrompt: 'old', positivePrompt: 'old', positivePromptHeightPx: 120 };@@ -36,6 +90,17 @@ describe('project prompt draft', () => {});});+ it("moves only the legacy prompt text, leaving Generate's template in place", () => {+ const template = { id: 'cinematic', name: 'Cinematic', negativePrompt: '', positivePrompt: '{prompt}, film' };++ expect(+ migrateProjectPromptDraft(+ { dynamicPromptsEnabled: false, promptTemplate: template },+ { positivePrompt: 'detail' }+ )+ ).toMatchObject({ dynamicPromptsEnabled: false, positivePrompt: 'detail', promptTemplate: template });+ });+it('keeps a non-empty Generate prompt during migration', () => {const generateValues = { negativePrompt: '', positivePrompt: 'generate prompt' };diff --git a/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.ts b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.tsindex d14c15ba2f..9abfad1e99 100644--- a/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/projectPromptDraft.ts@@ -1,41 +1,101 @@-export interface ProjectPromptDraft {+import type { PromptTemplateSnapshot } from './promptTemplates';+import type { DynamicPromptsSettings } from './types';++import { isCanonicalPromptTemplateSnapshot, sanitizePromptTemplateSnapshot } from './promptTemplates';+import { normalizeDynamicPromptsSettings } from './settings';++/**+ * The prompt Generate and Upscale share, stored in Generate's values: the text, the template that wraps it, and how+ * it expands. They travel together because a shared prompt that generated differently on each surface would not be+ * shared.+ */+export interface ProjectPromptDraft extends DynamicPromptsSettings {negativePrompt: string;negativePromptEnabled: boolean;positivePrompt: string;+ promptTemplate: PromptTemplateSnapshot | null;+ /** Whether the prompt boxes show the template-merged prompt instead of the authored text. */+ promptTemplateViewMode: boolean;}export type ProjectPromptDraftPatch = Partial<ProjectPromptDraft>;-export const getPromptDraftFromValues = (values: Record<string, unknown>): ProjectPromptDraft => ({- negativePrompt: typeof values.negativePrompt === 'string' ? values.negativePrompt : '',- negativePromptEnabled: values.negativePromptEnabled !== false,- positivePrompt: typeof values.positivePrompt === 'string' ? values.positivePrompt : '',-});+const TEXT_KEYS = ['negativePrompt', 'negativePromptEnabled', 'positivePrompt'] as const;+const DRAFT_KEYS = [+ ...TEXT_KEYS,+ 'promptTemplate',+ 'promptTemplateViewMode',+ 'dynamicPromptsCombinatorial',+ 'dynamicPromptsEnabled',+ 'dynamicPromptsMaxPrompts',+ 'dynamicPromptsResample',+ 'dynamicPromptsSampleSeed',+ 'dynamicPromptsSeedBehaviour',+] as const satisfies readonly (keyof ProjectPromptDraft)[];++/** Read as Generate normalizes the same fields, so both surfaces see one prompt. */+export const getPromptDraftFromValues = (values: Record<string, unknown>): ProjectPromptDraft => {+ // Keep a canonical snapshot's identity so repeated reads compare cheaply.+ const promptTemplate = isCanonicalPromptTemplateSnapshot(values.promptTemplate)+ ? values.promptTemplate+ : sanitizePromptTemplateSnapshot(values.promptTemplate);++ return {+ ...normalizeDynamicPromptsSettings(values),+ negativePrompt: typeof values.negativePrompt === 'string' ? values.negativePrompt : '',+ negativePromptEnabled: values.negativePromptEnabled !== false,+ positivePrompt: typeof values.positivePrompt === 'string' ? values.positivePrompt : '',+ promptTemplate,+ promptTemplateViewMode: promptTemplate !== null && values.promptTemplateViewMode === true,+ };+};++const arePromptTemplatesEqual = (left: PromptTemplateSnapshot | null, right: PromptTemplateSnapshot | null) =>+ left === right ||+ (left !== null &&+ right !== null &&+ left.id === right.id &&+ left.name === right.name &&+ left.negativePrompt === right.negativePrompt &&+ left.positivePrompt === right.positivePrompt);export const areProjectPromptDraftsEqual = (left: ProjectPromptDraft, right: ProjectPromptDraft): boolean =>- left.positivePrompt === right.positivePrompt &&- left.negativePrompt === right.negativePrompt &&- left.negativePromptEnabled === right.negativePromptEnabled;+ DRAFT_KEYS.every((key) =>+ key === 'promptTemplate'+ ? arePromptTemplatesEqual(left.promptTemplate, right.promptTemplate)+ : Object.is(left[key], right[key])+ );+/** Writes the text fields and whichever others the patch names, each read as the draft reads it. */export const applyProjectPromptDraft = (values: Record<string, unknown>,patch: ProjectPromptDraftPatch): Record<string, unknown> => {const current = getPromptDraftFromValues(values);- const next: ProjectPromptDraft = {- negativePrompt: typeof patch.negativePrompt === 'string' ? patch.negativePrompt : current.negativePrompt,- negativePromptEnabled:- typeof patch.negativePromptEnabled === 'boolean' ? patch.negativePromptEnabled : current.negativePromptEnabled,- positivePrompt: typeof patch.positivePrompt === 'string' ? patch.positivePrompt : current.positivePrompt,- };+ const patchedKeys = DRAFT_KEYS.filter((key) => patch[key] !== undefined);+ const next = getPromptDraftFromValues({+ ...current,+ ...Object.fromEntries(patchedKeys.map((key) => [key, patch[key]])),+ });++ if (areProjectPromptDraftsEqual(current, next)) {+ return values;+ }++ const written = new Set<keyof ProjectPromptDraft>([...TEXT_KEYS, ...patchedKeys]);++ // Clearing the template also leaves its merged view.+ if (written.has('promptTemplate')) {+ written.add('promptTemplateViewMode');+ }- return areProjectPromptDraftsEqual(current, next) ? values : { ...values, ...next };+ return { ...values, ...Object.fromEntries([...written].map((key) => [key, next[key]])) };};const hasPromptContent = (draft: ProjectPromptDraft): boolean =>draft.positivePrompt.trim().length > 0 || draft.negativePrompt.trim().length > 0;-/** Seed Generate from Upscale only when Generate has no prompt. */+/** Seed Generate's prompt text from Upscale only when Generate has none; Upscale never stored the rest. */export const migrateProjectPromptDraft = (generateValues: Record<string, unknown>,legacyUpscaleValues: Record<string, unknown>@@ -47,5 +107,8 @@ export const migrateProjectPromptDraft = (return generateValues;}- return applyProjectPromptDraft(generateValues, legacyUpscaleDraft);+ return applyProjectPromptDraft(+ generateValues,+ Object.fromEntries(TEXT_KEYS.map((key) => [key, legacyUpscaleDraft[key]]))+ );};diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.tsindex 39d0840095..dc2db51f8b 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts@@ -25,13 +25,14 @@ import {cloneGenerateWidgetValues,deriveAspectRatioId,getDefaultLoraWeight,- getModelDefaultVae,- hasModelDefaultVae,isLoraCompatibleWithModel,isGenerateSettings,isValidMossImageSkipLayers,+ MAX_REFERENCE_IMAGE_NAME_LENGTH,moveReferenceImage,normalizeGenerateSettings,+ normalizeReferenceImages,+ renameReferenceImage,parseMossImageSkipLayers,syncGenerateWidgetValuesWithModels,syncGenerateLorasWithModels,@@ -861,31 +862,6 @@ describe('LoRA settings helpers', () => {});});-describe('model defaults', () => {- it('uses shared VAE compatibility for cross-base default VAEs', () => {- const zImageModel: MainModelConfig = {- base: 'z-image',- default_settings: { vae: 'flux-vae' },- key: 'z-image',- name: 'Z-Image',- type: 'main',- };- const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };-- expect(getModelDefaultVae(zImageModel, [fluxVae])).toBe(fluxVae);- });-- it('distinguishes absent VAE defaults from explicit VAE defaults', () => {- expect(hasModelDefaultVae({ base: 'sdxl', key: 'sdxl', name: 'SDXL', type: 'main' })).toBe(false);- expect(- hasModelDefaultVae({ base: 'sdxl', default_settings: { vae: null }, key: 'sdxl', name: 'SDXL', type: 'main' })- ).toBe(false);- expect(- hasModelDefaultVae({ base: 'sdxl', default_settings: { vae: 'vae' }, key: 'sdxl', name: 'SDXL', type: 'main' })- ).toBe(true);- });-});-describe('dimension helpers', () => {it('derives the closest preset aspect ratio', () => {expect(deriveAspectRatioId(1024, 1024)).toBe('1:1');@@ -950,6 +926,59 @@ describe('dimension helpers', () => {expect(moveReferenceImage([], 'a', 1)).toEqual([]);});+ it('keeps a reference name through normalizing, trimmed and capped, and drops one that is empty or not text', () => {+ const config = { image: null, type: 'flux2_reference_image' as const };+ const long = `${'é'.repeat(MAX_REFERENCE_IMAGE_NAME_LENGTH)}tail`;+ const [named, untouched, blank, wrongType, capped] = normalizeReferenceImages([+ { config, id: 'named', isEnabled: true, name: ' Hero pose ' },+ { config, id: 'untouched', isEnabled: true },+ { config, id: 'blank', isEnabled: true, name: ' ' },+ { config, id: 'wrong-type', isEnabled: true, name: 7 },+ { config, id: 'capped', isEnabled: true, name: long },+ ]);++ expect(named?.name).toBe('Hero pose');+ // Data without names reads back exactly as before, with no name key added.+ expect(untouched).toEqual({ config, id: 'untouched', isEnabled: true });+ expect(blank && 'name' in blank).toBe(false);+ expect(wrongType && 'name' in wrongType).toBe(false);+ expect(capped?.name).toBe('é'.repeat(80));+ });++ it('renames one reference, storing nothing for an empty name or any positional default', () => {+ const config = { image: null, type: 'flux2_reference_image' as const };+ const referenceImages = [+ { config, id: 'a', isEnabled: true },+ { config, id: 'b', isEnabled: false, name: 'Palette' },+ ];+ const isDefaultName = (name: string) => /^reference image \d+$/i.test(name);++ const renamed = renameReferenceImage(referenceImages, 'a', ' Hero pose ', isDefaultName);+ expect(renamed[0]).toEqual({ config, id: 'a', isEnabled: true, name: 'Hero pose' });+ expect(renamed[1]).toBe(referenceImages[1]);++ // Its own default, another row's default, or nothing: the row keeps following its position.+ for (const cleared of ['', ' ', 'Reference image 2', 'Reference image 1', 'reference image 7']) {+ const result = renameReferenceImage(referenceImages, 'b', cleared, isDefaultName);+ expect(result[1]).toEqual({ config, id: 'b', isEnabled: false });+ expect(result[1] && 'name' in result[1]).toBe(false);+ }++ // The cap is in characters (code points), whatever the field allowed.+ const long = renameReferenceImage(+ referenceImages,+ 'a',+ '😀'.repeat(MAX_REFERENCE_IMAGE_NAME_LENGTH + 5),+ isDefaultName+ );+ expect(Array.from(long[0]?.name ?? '')).toHaveLength(MAX_REFERENCE_IMAGE_NAME_LENGTH);++ // No change, or no such reference, returns the same array so callers can skip the commit.+ expect(renameReferenceImage(referenceImages, 'b', 'Palette ', isDefaultName)).toBe(referenceImages);+ expect(renameReferenceImage(referenceImages, 'a', 'Reference image 1', isDefaultName)).toBe(referenceImages);+ expect(renameReferenceImage(referenceImages, 'missing', 'Name', isDefaultName)).toBe(referenceImages);+ });+it('uses larger dimension grids for model families that require them', () => {expect(getGenerationDimensions({ base: 'sdxl', type: 'main' }).grid).toBe(8);expect(getGenerationDimensions({ base: 'anima', type: 'main' }).grid).toBe(8);diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.tsindex 8b8fa8acbd..12bab14a89 100644--- a/invokeai/frontend/webv2/src/features/generation/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.ts@@ -24,7 +24,6 @@ import type {} from './types';import { sanitizeBatchCount } from './batch';-import { isVaeCompatibleWithGenerateModel } from './componentCompatibility';import {DEFAULT_KREA2_REBALANCE_MULTIPLIER,DEFAULT_KREA2_REBALANCE_WEIGHTS,@@ -206,6 +205,16 @@ export const isAspectRatioLocked = (settings: Pick<GenerateSettings, 'aspectRatioId' | 'aspectRatioIsLocked'>): boolean => settings.aspectRatioId !== 'Free' || settings.aspectRatioIsLocked;+/** The ratio a lock enforces, preferring the stored value and falling back to the current dimensions. */+export const getActiveAspectRatio = (+ settings: Pick<GenerateSettings, 'aspectRatioValue' | 'height' | 'width'>+): number =>+ settings.aspectRatioValue > 0+ ? settings.aspectRatioValue+ : settings.height > 0+ ? settings.width / settings.height+ : 1;+/** How far apart two ratios may be and still count as the same one. */export const ASPECT_RATIO_TOLERANCE = 0.0001;@@ -481,6 +490,51 @@ const normalizeReferenceImageConfig = (value: unknown): GenerateReferenceImageCoreturn null;};+/** Long enough for a descriptive label, short enough to stay one line in metadata and recall notices. */+export const MAX_REFERENCE_IMAGE_NAME_LENGTH = 80;++/** A reference's stored name: trimmed and capped by code point; empty or not a string is no name. */+export const normalizeReferenceImageName = (value: unknown): string | undefined => {+ if (typeof value !== 'string') {+ return undefined;+ }++ const characters = Array.from(value.trim());+ const name = (+ characters.length > MAX_REFERENCE_IMAGE_NAME_LENGTH+ ? characters.slice(0, MAX_REFERENCE_IMAGE_NAME_LENGTH).join('')+ : characters.join('')+ ).trim();++ return name.length > 0 ? name : undefined;+};++/**+ * Names one reference. A name that normalizes to nothing, or reads as a positional default (`isDefaultName`: its own+ * or another position's, "Reference image 2" on the first row), stores no name: the default keeps following the+ * reference's position, and no row can borrow another's default. No change returns the same array.+ */+export const renameReferenceImage = (+ referenceImages: readonly GenerateReferenceImage[],+ id: string,+ name: string,+ isDefaultName: (name: string) => boolean+): readonly GenerateReferenceImage[] => {+ const normalized = normalizeReferenceImageName(name);+ const next = normalized === undefined || isDefaultName(normalized) ? undefined : normalized;+ const index = referenceImages.findIndex((referenceImage) => referenceImage.id === id);+ const current = referenceImages[index];++ if (!current || current.name === next) {+ return referenceImages;+ }++ const { name: _previous, ...unnamed } = current;+ const renamed: GenerateReferenceImage = next === undefined ? unnamed : { ...unnamed, name: next };++ return referenceImages.map((referenceImage, position) => (position === index ? renamed : referenceImage));+};+export const normalizeReferenceImages = (value: unknown): GenerateReferenceImage[] => {if (!Array.isArray(value)) {return [];@@ -499,7 +553,9 @@ export const normalizeReferenceImages = (value: unknown): GenerateReferenceImagecontinue;}- images.push({ config, id: item.id, isEnabled: item.isEnabled !== false });+ const name = normalizeReferenceImageName(item.name);++ images.push({ config, id: item.id, isEnabled: item.isEnabled !== false, ...(name === undefined ? {} : { name }) });}return images;@@ -656,20 +712,6 @@ const syncModelIdentifierWithModels = <T extends ComponentModelConfig | null>(: value;};-export const getModelDefaultVae = (- model: GenerateModelConfig,- vaeModels: readonly VaeModelConfig[]-): VaeModelConfig | null => {- const defaultVaeKey = (model.default_settings as { vae?: string | null } | null | undefined)?.vae;-- return defaultVaeKey- ? (vaeModels.find((vae) => vae.key === defaultVaeKey && isVaeCompatibleWithGenerateModel(model, vae)) ?? null)- : null;-};--export const hasModelDefaultVae = (model: GenerateModelConfig): boolean =>- typeof (model.default_settings as { vae?: unknown } | null | undefined)?.vae === 'string';-export const cloneGenerateWidgetValues = (values: GenerateWidgetValues): GenerateWidgetValues & Record<string, unknown> => ({diff --git a/invokeai/frontend/webv2/src/features/generation/core/types.ts b/invokeai/frontend/webv2/src/features/generation/core/types.tsindex 9e7d4acc8a..7ccb4116e5 100644--- a/invokeai/frontend/webv2/src/features/generation/core/types.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/types.ts@@ -179,6 +179,11 @@ export type GenerateReferenceImageConfig =export interface GenerateReferenceImage {id: string;+ /**+ * The user's name for the reference: trimmed, at most MAX_REFERENCE_IMAGE_NAME_LENGTH characters, never empty.+ * Absent shows the positional default ("Reference image 2"). A label only: prompt tags stay positional.+ */+ name?: string;isEnabled: boolean;config: GenerateReferenceImageConfig;}diff --git a/invokeai/frontend/webv2/src/features/generation/react.ts b/invokeai/frontend/webv2/src/features/generation/react.tsindex d7d5e3cbc5..9765e956ce 100644--- a/invokeai/frontend/webv2/src/features/generation/react.ts+++ b/invokeai/frontend/webv2/src/features/generation/react.ts@@ -16,7 +16,7 @@ export {requestGenerateModelSwitchConfirmation,} from './ui/modelSelectionNotice';export { adjustFocusedPromptAttention } from './ui/promptFields/promptAttentionHotkeys';-export { focusPositivePrompt } from './ui/promptFields/promptFocus';+export { focusPositivePrompt, revealPositivePrompt } from './ui/promptFields/promptFocus';export { revealGenerateIssue } from './ui/revealGenerateIssue';export { getGeneratePromptUndoKey } from './ui/generateUndo';export { promptHistoryNavigation } from './ui/promptFields/promptHistoryNavigation';diff --git a/invokeai/frontend/webv2/src/features/generation/settings.ts b/invokeai/frontend/webv2/src/features/generation/settings.tsindex e8d34d42b9..5c8ff332fd 100644--- a/invokeai/frontend/webv2/src/features/generation/settings.ts+++ b/invokeai/frontend/webv2/src/features/generation/settings.ts@@ -14,8 +14,6 @@ export {getDynamicPromptsConfig,getDynamicPromptsSettingsPatch,getGenerateValuesRevertPatch,- getModelDefaultVae,- hasModelDefaultVae,isAspectRatioLocked,isFluxDypePreset,isIdeogram4SamplerPreset,@@ -45,6 +43,7 @@ export {normalizeGenerateSettings,normalizeMossImageSkipLayers,normalizeGenerateWidgetValues,+ normalizeReferenceImageName,normalizeReferenceImages,syncGenerateWidgetValuesWithModels,} from './core/settings';@@ -66,6 +65,8 @@ export {getReferenceImageLimit,getSchedulerOptions,getSettingsWithModelDefaults,+ getRecallDefaultVae,+ resolveModelDefaultVae,isArchitectureDescribed,isGenerateModelSelectable,isKnownScheduler,@@ -160,8 +161,13 @@ export {sanitizeSampleSeed,type DynamicPromptsConfig,type DynamicPromptsSeedBehaviour,+ type GenerateSubmissionSource,} from './core/dynamicPrompts';-export { getEffectivePrompts } from './core/promptTemplates';+export {+ flattenPromptTemplateExpansion,+ getEffectivePrompts,+ type PromptTemplateSnapshot,+} from './core/promptTemplates';export {addPromptHistoryItem,getPromptHistoryItemFromGenerateSettings,diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsxindex 8bfb363b24..0a5c7f4c86 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.browser.test.tsx@@ -2,6 +2,7 @@import type { GenerateSettings, MainModelConfig } from '@features/generation/core/types';import { ChakraProvider } from '@chakra-ui/react';+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';import { normalizeGenerateSettings } from '@features/generation/core/settings';import { createExternalStoreCore } from '@platform/state/externalStoreCore';@@ -18,7 +19,8 @@ import { GenerateAdvancedFields } from './GenerateAdvancedFields';vi.mock('./GenerationUiContext', () => ({GenerationModelSelect: () => null,useGenerationUi: () => ({- sectionPreferences: { sectionsOpen: { advanced: true }, setSectionOpen: vi.fn() },+ models: { getBaseLabel: (base: string) => ({ 'sd-1': 'SD 1.x', sdxl: 'SDXL' })[base] ?? base },+ sectionPreferences: { sectionsOpen: { advanced: true }, setSectionsOpen: vi.fn() },}),}));@@ -32,6 +34,7 @@ await i18n.use(initReactI18next).init({const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1', name: 'SD 1.5', type: 'main' };const sd2Model: MainModelConfig = { base: 'sd-2', key: 'sd2', name: 'SD 2', type: 'main' };+const sdxlModel: MainModelConfig = { base: 'sdxl', key: 'sdxl', name: 'SDXL', type: 'main' };const fluxModel: MainModelConfig = { base: 'flux', key: 'flux', name: 'FLUX.1 dev', type: 'main' };const qwenImageModel: MainModelConfig = {base: 'qwen-image',@@ -48,6 +51,7 @@ const krea2Model: MainModelConfig = {type: 'main',};let host: HTMLDivElement | null = null;+let onCommitImmediate = vi.fn();let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -70,12 +74,18 @@ const render = async (const settings = { ...getDefaultGenerateSettings(model), hiDiffusionEnabled, ...overrides };const draft = createExternalStoreCore(settings);const onCommit = vi.fn((patch: Partial<GenerateSettings>) => draft.patchSnapshot(patch));+ onCommitImmediate = vi.fn((patch: Partial<GenerateSettings>) => draft.patchSnapshot(patch));await settle(() => {root?.render(<ChakraProvider value={system}><I18nextProvider i18n={i18n}>- <GenerateAdvancedFields draft={draft} selectedModel={model} onCommit={onCommit} onCommitImmediate={vi.fn()} />+ <GenerateAdvancedFields+ draft={draft}+ selectedModel={model}+ onCommit={onCommit}+ onCommitImmediate={onCommitImmediate}+ /></I18nextProvider></ChakraProvider>);@@ -171,101 +181,89 @@ describe('GenerateAdvancedFields HiDiffusion controls', () => {expect(sliderByLabel('HiDiffusion: T1 Ratio')?.getAttribute('aria-disabled')).toBe('true');});- it.each(- [1, 2].flatMap((ratio) =>- ['manual', 'automatic', 'mixed'].flatMap((mode) => ['menu', 'dot'].map((action) => ({ action, mode, ratio })))- )- )('resets only T$ratio through its $action in $mode mode', async ({ action, mode, ratio }) => {- const t1 = mode === 'automatic' || (mode === 'mixed' && ratio === 1) ? null : 0.7;- const t2 = mode === 'automatic' || (mode === 'mixed' && ratio === 2) ? null : 0.2;- const onCommit = await render(sd1Model, true, {- hiDiffusionManualRatios: { t1: 0.8, t2: 0.3 },- hiDiffusionT1Ratio: t1,- hiDiffusionT2Ratio: t2,- });- const label = `HiDiffusion: T${ratio} Ratio`;- const dot = () => host?.querySelector<HTMLElement>(`[data-modified-dot][aria-label$="${label}"]`);- expect(dot()).not.toBeNull();- if (action === 'menu') {- await settle(() =>- sliderByLabel(label)?.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }))- );- const reset = document.querySelector<HTMLElement>('[data-scope="menu"][data-part="item"][data-value="reset"]');- expect(reset).not.toBeNull();- await settle(() => reset?.click());- } else {- await settle(() => dot()?.click());- }- expect(onCommit).toHaveBeenCalledExactlyOnceWith(- mode === 'manual'- ? ratio === 1- ? { hiDiffusionT1Ratio: 0.4 }- : { hiDiffusionT2Ratio: 0 }- : { hiDiffusionManualRatios: ratio === 1 ? { t1: 0.4, t2: 0.3 } : { t1: 0.8, t2: 0 } }- );- expect(sliderByLabel(label)?.getAttribute('aria-valuenow')).toBe(ratio === 1 ? '0.4' : '0');- expect(sliderByLabel(`HiDiffusion: T${ratio === 1 ? 2 : 1} Ratio`)?.getAttribute('aria-valuenow')).toBe(- mode === 'automatic' ? (ratio === 1 ? '0.3' : '0.8') : ratio === 1 ? '0.2' : '0.7'- );- expect(sliderByLabel(label)?.getAttribute('aria-disabled') === 'true').toBe(mode !== 'manual');- expect(switchByLabel('HiDiffusion: Automatic ratios')?.querySelector<HTMLInputElement>('input')?.checked).toBe(- mode === 'automatic'- );- expect(dot()).toBeNull();+ const ratioDot = (ratio: number) =>+ host?.querySelector<HTMLElement>(`[data-modified-dot][aria-label$="HiDiffusion: T${ratio} Ratio"]`) ?? null;+ const ratioMenuReset = async (ratio: number) => {await settle(() =>- sliderByLabel(label)?.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }))+ sliderByLabel(`HiDiffusion: T${ratio} Ratio`)?.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true })+ ));- expect(- document.querySelector('[data-scope="menu"][data-part="item"][data-value="reset"]')?.hasAttribute('data-disabled')- ).toBe(true);- });+ return document.querySelector<HTMLElement>('[data-scope="menu"][data-part="item"][data-value="reset"]');+ };- it.each(['manual', 'automatic'].flatMap((mode) => ['menu', 'dot'].map((action) => ({ mode, action }))))(- 'keeps the manual pair ordered when resetting T1 through its $action in $mode mode',- async ({ mode, action }) => {- const automatic = mode === 'automatic';+ it.each([1, 2].flatMap((ratio) => ['menu', 'dot'].map((action) => ({ action, ratio }))))(+ 'resets only a manual T$ratio through its $action',+ async ({ action, ratio }) => {const onCommit = await render(sd1Model, true, {- hiDiffusionT1Ratio: automatic ? null : 0.8,- hiDiffusionT2Ratio: automatic ? null : 0.6,- hiDiffusionManualRatios: { t1: 0.8, t2: 0.6 },+ hiDiffusionManualRatios: { t1: 0.8, t2: 0.3 },+ hiDiffusionT1Ratio: 0.7,+ hiDiffusionT2Ratio: 0.2,});- const label = 'HiDiffusion: T1 Ratio';- const dot = () => host?.querySelector<HTMLElement>(`[data-modified-dot][aria-label$="${label}"]`);- expect(dot()).not.toBeNull();+ const label = `HiDiffusion: T${ratio} Ratio`;++ expect(ratioDot(ratio)).not.toBeNull();if (action === 'menu') {- await settle(() =>- sliderByLabel(label)?.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }))- );- const reset = document.querySelector<HTMLElement>('[data-scope="menu"][data-part="item"][data-value="reset"]');+ const reset = await ratioMenuReset(ratio);expect(reset).not.toBeNull();await settle(() => reset?.click());} else {- await settle(() => dot()?.click());+ await settle(() => ratioDot(ratio)?.click());}+expect(onCommit).toHaveBeenCalledExactlyOnceWith(- automatic ? { hiDiffusionManualRatios: { t1: 0.6, t2: 0.6 } } : { hiDiffusionT1Ratio: 0.6 }+ ratio === 1 ? { hiDiffusionT1Ratio: 0.4 } : { hiDiffusionT2Ratio: 0 });- expect(sliderByLabel(label)?.getAttribute('aria-valuenow')).toBe('0.6');- expect(sliderByLabel('HiDiffusion: T2 Ratio')?.getAttribute('aria-valuenow')).toBe('0.6');- const automaticSwitch = switchByLabel('HiDiffusion: Automatic ratios');- expect(automaticSwitch?.querySelector<HTMLInputElement>('input')?.checked).toBe(automatic);- expect(dot()).toBeNull();- if (automatic) {- await settle(() => automaticSwitch?.querySelector<HTMLElement>('[data-part="control"]')?.click());- expect(onCommit).toHaveBeenLastCalledWith({ hiDiffusionT1Ratio: 0.6, hiDiffusionT2Ratio: 0.6 });- expect(sliderByLabel(label)?.getAttribute('aria-disabled')).not.toBe('true');- }- await settle(() =>- sliderByLabel(label)?.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }))+ expect(sliderByLabel(label)?.getAttribute('aria-valuenow')).toBe(ratio === 1 ? '0.4' : '0');+ expect(sliderByLabel(`HiDiffusion: T${ratio === 1 ? 2 : 1} Ratio`)?.getAttribute('aria-valuenow')).toBe(+ ratio === 1 ? '0.2' : '0.7');- expect(- document- .querySelector('[data-scope="menu"][data-part="item"][data-value="reset"]')- ?.hasAttribute('data-disabled')- ).toBe(true);+ expect(ratioDot(ratio)).toBeNull();+ expect((await ratioMenuReset(ratio))?.hasAttribute('data-disabled')).toBe(true);});+ // A disabled ratio is not sent, so it shows no dot and its menu offers no reset, whatever value it keeps.+ it.each([+ ['automatic ratios', { hiDiffusionT1Ratio: null, hiDiffusionT2Ratio: null }, [1, 2]],+ ['an automatic T1 beside a manual T2', { hiDiffusionT1Ratio: null, hiDiffusionT2Ratio: 0.2 }, [1]],+ ['RAU-Net off', { hiDiffusionRauNetEnabled: false, hiDiffusionT1Ratio: 0.7, hiDiffusionT2Ratio: 0.2 }, [1, 2]],+ ['HiDiffusion off', { hiDiffusionEnabled: false, hiDiffusionT1Ratio: 0.7, hiDiffusionT2Ratio: 0.2 }, [1, 2]],+ ] as const)('marks no disabled ratio with %s', async (_case, overrides, disabledRatios) => {+ await render(sd1Model, true, { hiDiffusionManualRatios: { t1: 0.8, t2: 0.3 }, ...overrides });++ for (const ratio of disabledRatios) {+ expect(sliderByLabel(`HiDiffusion: T${ratio} Ratio`)?.getAttribute('aria-disabled')).toBe('true');+ expect(ratioDot(ratio)).toBeNull();+ expect((await ratioMenuReset(ratio))?.hasAttribute('data-disabled')).toBe(true);+ await settle(() => document.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' })));+ }+ });++ it.each(['menu', 'dot'])('keeps the manual pair ordered when resetting T1 through its %s', async (action) => {+ const onCommit = await render(sd1Model, true, {+ hiDiffusionT1Ratio: 0.8,+ hiDiffusionT2Ratio: 0.6,+ hiDiffusionManualRatios: { t1: 0.8, t2: 0.6 },+ });+ const label = 'HiDiffusion: T1 Ratio';++ expect(ratioDot(1)).not.toBeNull();+ if (action === 'menu') {+ const reset = await ratioMenuReset(1);+ expect(reset).not.toBeNull();+ await settle(() => reset?.click());+ } else {+ await settle(() => ratioDot(1)?.click());+ }++ expect(onCommit).toHaveBeenCalledExactlyOnceWith({ hiDiffusionT1Ratio: 0.6 });+ expect(sliderByLabel(label)?.getAttribute('aria-valuenow')).toBe('0.6');+ expect(sliderByLabel('HiDiffusion: T2 Ratio')?.getAttribute('aria-valuenow')).toBe('0.6');+ expect(ratioDot(1)).toBeNull();+ expect((await ratioMenuReset(1))?.hasAttribute('data-disabled')).toBe(true);+ });+it.each([1, 2])('keeps a recalled automatic T%s slider disabled without changing its manual companion',async (ratio) => {@@ -387,6 +385,30 @@ describe('GenerateAdvancedFields Krea-2 reference K/V cache', () => {};const kvCacheInput = () => switchByLabel('Reference K/V cache')?.querySelector<HTMLInputElement>('input') ?? null;+ const kvCacheDot = () =>+ host?.querySelector<HTMLElement>('[data-modified-dot][aria-label="Reset to default: Reference K/V cache"]') ?? null;++ it('marks the switch with the dot while it applies and is on, and resets it', async () => {+ const onCommit = await render(krea2Model, false, {+ krea2ReferenceKvCache: true,+ loras: [poseLora],+ referenceImages: [editReference],+ });++ expect(kvCacheDot()).not.toBeNull();+ await settle(() => kvCacheDot()?.click());++ expect(onCommit).toHaveBeenCalledExactlyOnceWith({ krea2ReferenceKvCache: false });+ expect(kvCacheDot()).toBeNull();+ });++ it('shows no dot while the switch does not apply, even with the stored value on', async () => {+ await render(krea2Model, false, { krea2ReferenceKvCache: true });++ expect(kvCacheInput()?.disabled).toBe(true);+ expect(kvCacheDot()).toBeNull();+ });+// Krea-2 has no other advanced field, so the section must not hide itself.it('offers the switch with edit references and a LoRA, and commits it', async () => {const onCommit = await render(krea2Model, false, { loras: [poseLora], referenceImages: [editReference] });@@ -440,3 +462,200 @@ describe('GenerateAdvancedFields Krea-2 reference K/V cache', () => {expect(switchByLabel('Reference K/V cache')).toBeNull();});});++describe('GenerateAdvancedFields alignment', () => {+ // A field that pads itself sits inside the others' edges; the section owns the inset.+ it.each([+ ['SD 1.5', sd1Model, {}],+ ['Qwen Image', qwenImageModel, {}],+ ['Krea-2', krea2Model, {}],+ ] as const)('starts every %s control on the same left edge', async (_name, model, overrides) => {+ await render(model, true, overrides);+ await settle(() => host?.querySelector<HTMLElement>('.generate-section [data-part="trigger"]')?.click());++ // The controls themselves: a wrapper that pads its content still spans the full width.+ const controls = [+ ...(host?.querySelectorAll<HTMLElement>(+ '[data-part="content"] :is([data-scope="select"][data-part="trigger"], [data-scope="scrubber"][data-part="root"], [data-scope="switch"][data-part="label"])'+ ) ?? []),+ ]+ .map((control) => control.getBoundingClientRect())+ .filter((rect) => rect.width > 0);++ expect(controls.length).toBeGreaterThan(0);+ expect(new Set(controls.map((rect) => Math.round(rect.left))).size).toBe(1);+ });+});++describe('GenerateAdvancedFields reset dots', () => {+ // VAE, VAE precision and seamless tiling show per the architecture capabilities.+ seedArchitectureCapabilities();++ // Named by where the reset takes its value from: these models set no defaults of their own.+ const dot = (field: string, reset = 'Reset to default') =>+ host?.querySelector<HTMLElement>(`[data-modified-dot][aria-label="${reset}: ${field}"]`) ?? null;++ it('resets VAE precision from its dot, not a separate button, and hands focus to the select', async () => {+ const defaults = getDefaultGenerateSettings(sd1Model);+ const onCommit = await render(sd1Model, false, {+ vaePrecision: defaults.vaePrecision === 'fp16' ? 'fp32' : 'fp16',+ });++ expect(host?.querySelector('button[aria-label="Use model default VAE precision"]')).toBeNull();+ await settle(() => dot('VAE precision', 'Reset to SD 1.x default')?.click());++ expect(onCommit).toHaveBeenCalledExactlyOnceWith({ vaePrecision: defaults.vaePrecision });+ expect(dot('VAE precision', 'Reset to SD 1.x default')).toBeNull();+ await vi.waitFor(() => expect(document.activeElement).toBe(selectByLabel('VAE precision')));+ });++ it('names the model as the source of a VAE precision it sets', async () => {+ await render({ ...sd1Model, default_settings: { vae_precision: 'fp16' } }, false, { vaePrecision: 'fp32' });++ expect(dot('VAE precision', 'Reset to model default')).not.toBeNull();+ expect(dot('VAE precision', 'Reset to SD 1.x default')).toBeNull();+ });++ it('resets a chosen VAE to the bundled one from its dot', async () => {+ const vae = { base: 'sd-1', key: 'vae-1', name: 'Custom VAE', type: 'vae' } as unknown as GenerateSettings['vae'];+ await render(sd1Model, false, { vae });++ expect(host?.querySelector('button[aria-label="Use model default VAE"]')).toBeNull();+ await settle(() => dot('VAE', 'Use the bundled VAE')?.click());++ expect(onCommitImmediate).toHaveBeenCalledExactlyOnceWith({ vae: null });+ expect(dot('VAE', 'Use the bundled VAE')).toBeNull();+ });++ it("marks no change for the VAE the model's defaults name, as Apply model defaults sets it", async () => {+ const vae = { base: 'sd-1', key: 'vae-1', name: 'Custom VAE', type: 'vae' } as unknown as GenerateSettings['vae'];+ await render({ ...sd1Model, default_settings: { vae: 'vae-1' } }, false, { vae });++ expect(dot('VAE', 'Use the bundled VAE')).toBeNull();+ // The section agrees with the field: no override to count.+ expect(host?.textContent).not.toContain('1 override');++ await settle(() => root?.unmount());+ await render(sd1Model, false, { vae });+ expect(host?.textContent).toContain('1 override');+ });++ it.each([+ ['HiDiffusion', sd1Model, { hiDiffusionEnabled: true }, { hiDiffusionEnabled: false }, false],+ [+ 'HiDiffusion: RAU-Net',+ sd1Model,+ { hiDiffusionEnabled: true, hiDiffusionRauNetEnabled: false },+ { hiDiffusionRauNetEnabled: true },+ true,+ ],+ [+ 'HiDiffusion: Window Attention',+ sd1Model,+ { hiDiffusionEnabled: true, hiDiffusionWindowAttentionEnabled: false },+ { hiDiffusionWindowAttentionEnabled: true },+ true,+ ],+ ['Color compensation', sdxlModel, { colorCompensation: true }, { colorCompensation: false }, false],+ ['X axis', sd1Model, { seamlessXAxis: true }, { seamlessXAxis: false }, false],+ ['Y axis', sd1Model, { seamlessYAxis: true }, { seamlessYAxis: false }, false],+ ] as const)(+ 'marks the %s switch off its default and resets it from the dot',+ async (label, model, changed, reset, on) => {+ const onCommit = await render(model, false, changed);+ const input = () => switchByLabel(label)?.querySelector<HTMLInputElement>('input') ?? null;++ expect(dot(label)).not.toBeNull();+ await settle(() => dot(label)?.click());++ expect(onCommit).toHaveBeenCalledExactlyOnceWith(reset);+ expect(input()?.checked).toBe(on);+ expect(dot(label)).toBeNull();+ await vi.waitFor(() => expect(document.activeElement).toBe(input()));+ }+ );++ it('shows no dot on a switch at its default or one that is not sent', async () => {+ // HiDiffusion off: its sub-switches are disabled, so even changed ones are not marked.+ await render(sd1Model, false, { hiDiffusionRauNetEnabled: false });++ expect(dot('HiDiffusion')).toBeNull();+ expect(dot('X axis')).toBeNull();+ expect(dot('HiDiffusion: RAU-Net')).toBeNull();+ });++ it('keeps a switch row dot and its target in the gutter, centred on the first line, clear of the label', async () => {+ await render(sd1Model, true);+ const button = dot('HiDiffusion')!;+ const label = switchByLabel('HiDiffusion')!.querySelector<HTMLElement>('[data-part="label"]')!;+ const control = switchByLabel('HiDiffusion')!.querySelector<HTMLElement>('[data-part="control"]')!;+ const rowLeft = label.getBoundingClientRect().left;+ const buttonRect = button.getBoundingClientRect();+ const dotRect = () => button.querySelector<HTMLElement>('[data-part="dot"]')!.getBoundingClientRect();+ const controlRect = control.getBoundingClientRect();++ expect(Math.abs((dotRect().top + dotRect().bottom) / 2 - (controlRect.top + controlRect.bottom) / 2)).toBeLessThan(+ 0.5+ );+ // The whole target sits in the 8px gutter, so a click on the label's first letter toggles rather than resets.+ expect(buttonRect.left).toBeGreaterThanOrEqual(rowLeft - 8);+ expect(buttonRect.right).toBeLessThanOrEqual(rowLeft);+ expect(rowLeft - dotRect().right).toBe(3);++ await userEvent.hover(button);+ await vi.waitFor(() => expect(Math.round(dotRect().width)).toBe(6));+ expect(dotRect().left).toBeGreaterThanOrEqual(rowLeft - 8);+ expect(dotRect().right).toBeLessThanOrEqual(rowLeft - 2);+ });++ it('turns manual ratios back to automatic from the dot, keeping the manual values for later', async () => {+ const onCommit = await render(sd1Model, true, {+ hiDiffusionManualRatios: { t1: 0.7, t2: 0.2 },+ hiDiffusionT1Ratio: 0.7,+ hiDiffusionT2Ratio: 0.2,+ });++ await settle(() => dot('HiDiffusion: Automatic ratios')?.click());++ expect(onCommit).toHaveBeenCalledExactlyOnceWith({+ hiDiffusionManualRatios: { t1: 0.7, t2: 0.2 },+ hiDiffusionT1Ratio: null,+ hiDiffusionT2Ratio: null,+ });+ expect(dot('HiDiffusion: Automatic ratios')).toBeNull();+ });++ it('resets PiD steps to the default from its dot', async () => {+ const defaults = getDefaultGenerateSettings(qwenImageModel);+ const onCommit = await render(qwenImageModel, false, { pidMode: 'fit', pidSteps: defaults.pidSteps + 1 });++ await settle(() => dot('PiD steps')?.click());++ expect(onCommit).toHaveBeenCalledExactlyOnceWith({ pidSteps: defaults.pidSteps });+ expect(dot('PiD steps')).toBeNull();+ await vi.waitFor(() => expect(document.activeElement).toBe(sliderByLabel('PiD steps')));+ });++ it('counts only what the section shows: a hidden VAE precision is no override', async () => {+ const defaults = getDefaultGenerateSettings(qwenImageModel);+ await render(qwenImageModel, false, { vaePrecision: defaults.vaePrecision === 'fp16' ? 'fp32' : 'fp16' });++ expect(selectByLabel('VAE precision')).toBeNull();+ expect(host?.textContent).not.toContain('override');+ expect(host?.querySelector('.generate-section [data-section-changed]')).toBeNull();+ });++ it('resets PiD and encoder quantization to the defaults from their dots', async () => {+ const defaults = getDefaultGenerateSettings(qwenImageModel);+ const onCommit = await render(qwenImageModel, false, { pidMode: 'fit', qwenImageEncoderQuantization: 'int8' });++ await settle(() => dot('Encoder quantization')?.click());+ expect(onCommit).toHaveBeenCalledExactlyOnceWith({+ qwenImageEncoderQuantization: defaults.qwenImageEncoderQuantization,+ });++ await settle(() => dot('PiD Decode')?.click());+ expect(onCommitImmediate).toHaveBeenCalledExactlyOnceWith({ pidMode: defaults.pidMode });+ expect(dot('PiD Decode')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsxindex b0e8d0926a..5539101b2d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateAdvancedFields.tsx@@ -5,7 +5,7 @@ import type {QwenImageEncoderQuantization,} from '@features/generation/core/types';-import { Badge, Box, chakra, createListCollection, HStack, Stack, useRecipe } from '@chakra-ui/react';+import { chakra, createListCollection, Stack, useRecipe } from '@chakra-ui/react';import {getDefaultGenerateSettings,getGenerationUiPolicy,@@ -20,19 +20,19 @@ import {} from '@features/generation/core/settings';import { useExternalStoreSelector } from '@platform/state/selectors';import { Field, Select } from '@platform/ui';-import { FEATURE_HINT_FIELD_PROPS, FeatureHint } from '@platform/ui/hints';-import { ModelDefaultButton } from '@platform/ui/ModelDefaultButton';+import { FEATURE_HINT_FIELD_PROPS, FeatureHint, type FeatureHintId } from '@platform/ui/hints';import { ScrubberField } from '@platform/ui/ScrubberField';import { fieldLabelRecipe } from '@theme/recipes';import { useId, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { type GenerateDraft, pickGenerateSettings } from './generateDebounce';-import { GenerationModelSelect as ModelSelect } from './GenerationUiContext';+import { GenerationModelSelect as ModelSelect, useGenerationUi } from './GenerationUiContext';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';import { GenerateFieldContextMenu } from './shared/GenerateFieldContextMenu';import { GenerateIssueNotes } from './shared/GenerateIssues';import { GenerateToggleSwitch } from './shared/GenerateToggleSwitch';+import { getFieldResetLabel, isModelDefaultVae } from './shared/modelDefaultSettings';interface GenerateAdvancedFieldsProps {draft: GenerateDraft;@@ -74,6 +74,16 @@ const selectAdvancedSettings = pickGenerateSettings(['vaePrecision',]);+/** On/off settings whose model default is their reset. */+type DefaultedSwitchKey =+ | 'colorCompensation'+ | 'hiDiffusionEnabled'+ | 'hiDiffusionRauNetEnabled'+ | 'hiDiffusionWindowAttentionEnabled'+ | 'krea2ReferenceKvCache'+ | 'seamlessXAxis'+ | 'seamlessYAxis';+const KREA2_REFERENCE_KV_CACHE_HELP_KEYS = {noEditReferences: 'widgets.generate.krea2ReferenceKvCacheNeedsEditReferences',noLora: 'widgets.generate.krea2ReferenceKvCacheNeedsLora',@@ -87,6 +97,7 @@ export const GenerateAdvancedFields = ({selectedModel,}: GenerateAdvancedFieldsProps) => {const { t } = useTranslation();+ const { models } = useGenerationUi();const fieldLabel = useRecipe({ recipe: fieldLabelRecipe });const seamlessLabelId = useId();const settings = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectAdvancedSettings);@@ -162,7 +173,49 @@ export const GenerateAdvancedFields = ({);};- const customVae = policy.sdVaeVisible && Boolean(settings.vae?.key);+ const hiDiffusionRatiosAutomatic = settings.hiDiffusionT1Ratio === null && settings.hiDiffusionT2Ratio === null;+ const hiDiffusionRatiosDisabled = !settings.hiDiffusionEnabled || !settings.hiDiffusionRauNetEnabled;+ const hiDiffusionT1Disabled = hiDiffusionRatiosDisabled || settings.hiDiffusionT1Ratio === null;+ const hiDiffusionT2Disabled = hiDiffusionRatiosDisabled || settings.hiDiffusionT2Ratio === null;+ const onOff = (value: boolean) => t(value ? 'commandPalette.settings.on' : 'commandPalette.settings.off');+ /** An on/off setting with the model's default value: a changed one shows the dot that puts it back. */+ const defaultedSwitch = ({+ key,+ checked = settings[key],+ disabled = false,+ helpText,+ hint,+ label,+ }: {+ checked?: boolean;+ disabled?: boolean;+ helpText?: string;+ hint?: FeatureHintId;+ key: DefaultedSwitchKey;+ label: string;+ }) => (+ <GenerateFieldContextMenu+ fieldLabel={label}+ copyValue={() => onOff(checked)}+ // A disabled switch is not sent, so it is no change to undo.+ isAtDefault={disabled || modelDefaults === null || checked === modelDefaults[key]}+ placement="switch"+ onReset={modelDefaults ? () => onCommit({ [key]: modelDefaults[key] }) : undefined}+ >+ <GenerateToggleSwitch+ checked={checked}+ disabled={disabled}+ helpText={helpText}+ hint={hint}+ label={label}+ onCheckedChange={(next) => onCommit({ [key]: next })}+ />+ </GenerateFieldContextMenu>+ );++ // The VAE the model's defaults name is no change from them, as Apply model defaults sets it.+ const isVaeAtDefault = !settings.vae || isModelDefaultVae(selectedModel, settings.vae);+ const customVae = policy.sdVaeVisible && !isVaeAtDefault;if (!policy.sdVaeVisible &&@@ -179,10 +232,10 @@ export const GenerateAdvancedFields = ({return null;}- // Count user decisions, not modified settings keys.+ // Count user decisions, not modified settings keys, and only those the section shows (and so can reset).const overrideCount = [customVae,- modelDefaults !== null && settings.vaePrecision !== modelDefaults.vaePrecision,+ policy.vaePrecisionVisible && modelDefaults !== null && settings.vaePrecision !== modelDefaults.vaePrecision,clipSkipMax > 0 && settings.clipSkip !== (modelDefaults?.clipSkip ?? 0),policy.cfgRescaleVisible && settings.cfgRescaleMultiplier !== (modelDefaults?.cfgRescaleMultiplier ?? 0),policy.seamlessVisible && (settings.seamlessXAxis || settings.seamlessYAxis),@@ -194,53 +247,59 @@ export const GenerateAdvancedFields = ({policy.krea2ReferenceKvCacheVisible && krea2ReferenceKvCacheApplies && settings.krea2ReferenceKvCache,].filter(Boolean).length;- const badges =- overrideCount > 0 ? <Badge>{t('widgets.generate.overridesCount', { count: overrideCount })}</Badge> : null;-return (<GenerateCollapsibleSectionlabel={t('widgets.generate.advanced')}defaultOpen={false}- badges={badges}+ isChanged={overrideCount > 0}sectionId="advanced"+ summary={overrideCount > 0 ? [t('widgets.generate.overridesCount', { count: overrideCount })] : undefined}>- <Stack _empty={{ display: 'none' }} p="2" pb="0">+ <Stack _empty={{ display: 'none' }}><GenerateIssueNotes section="advanced" /></Stack>{policy.sdVaeVisible || policy.vaePrecisionVisible ? (- <HStack alignItems="flex-start" gap="2" p="2">+ // Stacked: side by side, two inside labels would leave each value too little room.+ <Stack gap="2.5">{policy.sdVaeVisible ? (- <Field- flex="2"- hint="vae"- label={t('widgets.generate.vae')}- helpText={settings.vae ? undefined : t('widgets.generate.usingBundledVae')}+ <GenerateFieldContextMenu+ fieldLabel={t('widgets.generate.vae')}+ copyValue={() => settings.vae?.name ?? t('widgets.generate.bundledVae')}+ isAtDefault={isVaeAtDefault}+ resetLabel={t('widgets.generate.useBundledVae')}+ onReset={() => onCommitImmediate({ vae: null })}>- <HStack gap="1">+ <Field+ hint="vae"+ label={t('widgets.generate.vae')}+ labelPlacement="inside"+ helpText={settings.vae ? undefined : t('widgets.generate.usingBundledVae')}+ >+ {/* Clearable: at the model's default VAE the reset is off, and clearing is how to reach the bundled one. */}<ModelSelect+ isClearablefilter={(model) => model.base === modelBase}modelTypes={['vae']}- placeholder={t('widgets.generate.modelDefault')}+ placeholder={t('widgets.generate.bundledVae')}relatedTo={selectedModel?.key ?? null}value={settings.vae?.key ?? null}onChange={(model) => onCommitImmediate({ vae: isVaeModelConfig(model) ? model : null })}/>- {settings.vae ? (- <ModelDefaultButton- label={t('widgets.generate.useModelDefaultVae')}- onClick={() => onCommitImmediate({ vae: null })}- />- ) : null}- </HStack>- </Field>+ </Field>+ </GenerateFieldContextMenu>) : null}{policy.vaePrecisionVisible ? (- <Field flex="1" hint="vaePrecision" label={t('widgets.generate.vaePrecision')}>- <HStack gap="1">+ <GenerateFieldContextMenu+ fieldLabel={t('widgets.generate.vaePrecision')}+ copyValue={() => settings.vaePrecision.toUpperCase()}+ isAtDefault={modelDefaults !== null && settings.vaePrecision === modelDefaults.vaePrecision}+ resetLabel={getFieldResetLabel('vaePrecision', selectedModel, models.getBaseLabel, t)}+ onReset={modelDefaults ? () => onCommit({ vaePrecision: modelDefaults.vaePrecision }) : undefined}+ >+ <Field hint="vaePrecision" label={t('widgets.generate.vaePrecision')} labelPlacement="inside"><Selectaria-label={t('widgets.generate.vaePrecision')}collection={VAE_PRECISION_COLLECTION}- flex="1"value={[settings.vaePrecision]}onValueChange={({ value }) => {const vaePrecision = value[0];@@ -250,20 +309,14 @@ export const GenerateAdvancedFields = ({}}}/>- {modelDefaults && settings.vaePrecision !== modelDefaults.vaePrecision ? (- <ModelDefaultButton- label={t('widgets.generate.useModelDefaultVaePrecision')}- onClick={() => onCommit({ vaePrecision: modelDefaults.vaePrecision })}- />- ) : null}- </HStack>- </Field>+ </Field>+ </GenerateFieldContextMenu>) : null}- </HStack>+ </Stack>) : null}{policy.clipSkipMax || policy.cfgRescaleVisible ? (- <Stack gap="2" p="2">+ <Stack gap="2.5">{policy.clipSkipMax ? (<GenerateFieldContextMenufieldLabel={t('widgets.generate.clipSkip')}@@ -290,6 +343,7 @@ export const GenerateAdvancedFields = ({isAtDefault={modelDefaults !== null && settings.cfgRescaleMultiplier === modelDefaults.cfgRescaleMultiplier}+ resetLabel={getFieldResetLabel('cfgRescaleMultiplier', selectedModel, models.getBaseLabel, t)}onReset={modelDefaults ? () => onCommit({ cfgRescaleMultiplier: modelDefaults.cfgRescaleMultiplier }) : undefined}@@ -310,58 +364,50 @@ export const GenerateAdvancedFields = ({) : null}{policy.hiDiffusionVisible ? (- <Stack gap="2" p="2">- <GenerateToggleSwitch- checked={settings.hiDiffusionEnabled}- hint="hidiffusion"- label={t('widgets.generate.hiDiffusion')}- onCheckedChange={(checked) => onCommit({ hiDiffusionEnabled: checked })}- />- <GenerateToggleSwitch- checked={settings.hiDiffusionRauNetEnabled}- disabled={!settings.hiDiffusionEnabled}- hint="hidiffusionRauNet"- label={t('widgets.generate.hiDiffusionRauNet')}- onCheckedChange={(checked) => onCommit({ hiDiffusionRauNetEnabled: checked })}- />- <GenerateToggleSwitch- checked={settings.hiDiffusionWindowAttentionEnabled}- disabled={!settings.hiDiffusionEnabled}- hint="hidiffusionWindowAttn"- label={t('widgets.generate.hiDiffusionWindowAttn')}- onCheckedChange={(checked) => onCommit({ hiDiffusionWindowAttentionEnabled: checked })}- />- <GenerateToggleSwitch- checked={settings.hiDiffusionT1Ratio === null && settings.hiDiffusionT2Ratio === null}- disabled={!settings.hiDiffusionEnabled || !settings.hiDiffusionRauNetEnabled}- hint="hidiffusionRatiosAuto"- label={t('widgets.generate.hiDiffusionRatiosAuto')}- onCheckedChange={setHiDiffusionRatiosAutomatic}- />+ <Stack gap="2.5">+ {defaultedSwitch({+ hint: 'hidiffusion',+ key: 'hiDiffusionEnabled',+ label: t('widgets.generate.hiDiffusion'),+ })}+ {defaultedSwitch({+ disabled: !settings.hiDiffusionEnabled,+ hint: 'hidiffusionRauNet',+ key: 'hiDiffusionRauNetEnabled',+ label: t('widgets.generate.hiDiffusionRauNet'),+ })}+ {defaultedSwitch({+ disabled: !settings.hiDiffusionEnabled,+ hint: 'hidiffusionWindowAttn',+ key: 'hiDiffusionWindowAttentionEnabled',+ label: t('widgets.generate.hiDiffusionWindowAttn'),+ })}+ {/* Automatic is the default: no manual ratios. */}+ <GenerateFieldContextMenu+ fieldLabel={t('widgets.generate.hiDiffusionRatiosAuto')}+ copyValue={() => onOff(hiDiffusionRatiosAutomatic)}+ isAtDefault={hiDiffusionRatiosAutomatic || hiDiffusionRatiosDisabled}+ placement="switch"+ onReset={() => setHiDiffusionRatiosAutomatic(true)}+ >+ <GenerateToggleSwitch+ checked={hiDiffusionRatiosAutomatic}+ disabled={hiDiffusionRatiosDisabled}+ hint="hidiffusionRatiosAuto"+ label={t('widgets.generate.hiDiffusionRatiosAuto')}+ onCheckedChange={setHiDiffusionRatiosAutomatic}+ />+ </GenerateFieldContextMenu><GenerateFieldContextMenufieldLabel={t('widgets.generate.hiDiffusionT1Ratio')}copyValue={() => String(settings.hiDiffusionT1Ratio ?? t('widgets.generate.hiDiffusionRatioAutoValue'))}- isAtDefault={manualHiDiffusionRatios.t1 === defaultHiDiffusionT1Ratio}- onReset={() =>- onCommit(- settings.hiDiffusionT1Ratio === null- ? {- hiDiffusionManualRatios: {- ...(settings.hiDiffusionManualRatios ?? manualHiDiffusionRatios),- t1: defaultHiDiffusionT1Ratio,- },- }- : { hiDiffusionT1Ratio: defaultHiDiffusionT1Ratio }- )- }+ // A disabled ratio is not sent (HiDiffusion or RAU-Net off, or automatic ratios), so it is no change to undo.+ isAtDefault={hiDiffusionT1Disabled || manualHiDiffusionRatios.t1 === defaultHiDiffusionT1Ratio}+ onReset={() => onCommit({ hiDiffusionT1Ratio: defaultHiDiffusionT1Ratio })}><ScrubberFielddefaultValue={defaultHiDiffusionT1Ratio}- disabled={- !settings.hiDiffusionEnabled ||- !settings.hiDiffusionRauNetEnabled ||- settings.hiDiffusionT1Ratio === null- }+ disabled={hiDiffusionT1Disabled}hint="hidiffusionT1Ratio"label={t('widgets.generate.hiDiffusionT1Ratio')}max={MAX_HIDIFFUSION_RATIO}@@ -374,27 +420,12 @@ export const GenerateAdvancedFields = ({<GenerateFieldContextMenufieldLabel={t('widgets.generate.hiDiffusionT2Ratio')}copyValue={() => String(settings.hiDiffusionT2Ratio ?? t('widgets.generate.hiDiffusionRatioAutoValue'))}- isAtDefault={manualHiDiffusionRatios.t2 === 0}- onReset={() =>- onCommit(- settings.hiDiffusionT2Ratio === null- ? {- hiDiffusionManualRatios: {- ...(settings.hiDiffusionManualRatios ?? manualHiDiffusionRatios),- t2: 0,- },- }- : { hiDiffusionT2Ratio: 0 }- )- }+ isAtDefault={hiDiffusionT2Disabled || manualHiDiffusionRatios.t2 === 0}+ onReset={() => onCommit({ hiDiffusionT2Ratio: 0 })}><ScrubberFielddefaultValue={0}- disabled={- !settings.hiDiffusionEnabled ||- !settings.hiDiffusionRauNetEnabled ||- settings.hiDiffusionT2Ratio === null- }+ disabled={hiDiffusionT2Disabled}hint="hidiffusionT2Ratio"label={t('widgets.generate.hiDiffusionT2Ratio')}max={manualHiDiffusionRatios.t1}@@ -407,103 +438,123 @@ export const GenerateAdvancedFields = ({</Stack>) : null}- {policy.colorCompensationVisible ? (- <Box p="2">- <GenerateToggleSwitch- checked={settings.colorCompensation}- hint="colorCompensation"- label={t('widgets.generate.colorCompensation')}- onCheckedChange={(checked) => onCommit({ colorCompensation: checked })}- />- </Box>- ) : null}+ {policy.colorCompensationVisible+ ? defaultedSwitch({+ hint: 'colorCompensation',+ key: 'colorCompensation',+ label: t('widgets.generate.colorCompensation'),+ })+ : null}{policy.pidVisible ? (- <Stack gap="2" p="2">- <Field hint="pidMode" label={t('widgets.generate.pid')} helpText={pidHelpText}>- <Select- aria-label={t('widgets.generate.pid')}- collection={pidModeCollection}- value={[settings.pidMode]}- onValueChange={({ value }) => {- const mode = value[0];+ <Stack gap="2.5">+ <GenerateFieldContextMenu+ fieldLabel={t('widgets.generate.pid')}+ copyValue={() => pidModeCollection.items.find((item) => item.value === settings.pidMode)?.label ?? ''}+ isAtDefault={modelDefaults !== null && settings.pidMode === modelDefaults.pidMode}+ // Immediately, as a pick does: native mode changes the valid dimension grid.+ onReset={modelDefaults ? () => onCommitImmediate({ pidMode: modelDefaults.pidMode }) : undefined}+ >+ <Field hint="pidMode" label={t('widgets.generate.pid')} labelPlacement="inside" helpText={pidHelpText}>+ <Select+ aria-label={t('widgets.generate.pid')}+ collection={pidModeCollection}+ value={[settings.pidMode]}+ onValueChange={({ value }) => {+ const mode = value[0];- if (isPidMode(mode)) {- // Commit immediately because native mode changes the valid dimension grid.- onCommitImmediate({ pidMode: mode });- }- }}- />- </Field>+ if (isPidMode(mode)) {+ // Commit immediately because native mode changes the valid dimension grid.+ onCommitImmediate({ pidMode: mode });+ }+ }}+ />+ </Field>+ </GenerateFieldContextMenu>{settings.pidMode === 'off' ? null : (- <ScrubberField- label={t('widgets.generate.pidSteps')}- max={MAX_PID_STEPS}- min={MIN_PID_STEPS}- step={1}- value={settings.pidSteps}- onChange={(value) => onCommit({ pidSteps: value })}- />+ <GenerateFieldContextMenu+ fieldLabel={t('widgets.generate.pidSteps')}+ copyValue={() => String(settings.pidSteps)}+ isAtDefault={modelDefaults !== null && settings.pidSteps === modelDefaults.pidSteps}+ onReset={modelDefaults ? () => onCommit({ pidSteps: modelDefaults.pidSteps }) : undefined}+ >+ <ScrubberField+ defaultValue={modelDefaults?.pidSteps}+ label={t('widgets.generate.pidSteps')}+ max={MAX_PID_STEPS}+ min={MIN_PID_STEPS}+ step={1}+ value={settings.pidSteps}+ onChange={(value) => onCommit({ pidSteps: value })}+ />+ </GenerateFieldContextMenu>)}</Stack>) : null}{policy.encoderQuantizationVisible ? (- <Field- hint="encoderQuantization"- label={t('widgets.generate.encoderQuantization')}- helpText={t('widgets.generate.encoderQuantizationHelp')}- p="2"+ <GenerateFieldContextMenu+ fieldLabel={t('widgets.generate.encoderQuantization')}+ copyValue={() =>+ encoderQuantizationCollection.items.find((item) => item.value === settings.qwenImageEncoderQuantization)+ ?.label ?? ''+ }+ isAtDefault={+ modelDefaults !== null &&+ settings.qwenImageEncoderQuantization === modelDefaults.qwenImageEncoderQuantization+ }+ onReset={+ modelDefaults+ ? () => onCommit({ qwenImageEncoderQuantization: modelDefaults.qwenImageEncoderQuantization })+ : undefined+ }>- <Select- aria-label={t('widgets.generate.encoderQuantization')}- collection={encoderQuantizationCollection}- value={[settings.qwenImageEncoderQuantization]}- onValueChange={({ value }) => {- const quantization = value[0];+ <Field+ hint="encoderQuantization"+ label={t('widgets.generate.encoderQuantization')}+ labelPlacement="inside"+ helpText={t('widgets.generate.encoderQuantizationHelp')}+ >+ <Select+ aria-label={t('widgets.generate.encoderQuantization')}+ collection={encoderQuantizationCollection}+ value={[settings.qwenImageEncoderQuantization]}+ onValueChange={({ value }) => {+ const quantization = value[0];- if (isQwenImageEncoderQuantization(quantization)) {- onCommit({ qwenImageEncoderQuantization: quantization });- }- }}- />- </Field>+ if (isQwenImageEncoderQuantization(quantization)) {+ onCommit({ qwenImageEncoderQuantization: quantization });+ }+ }}+ />+ </Field>+ </GenerateFieldContextMenu>) : null}- {policy.krea2ReferenceKvCacheVisible ? (- <Box p="2">- {/* Shown off while it is not sent; the stored value stays and is back once it applies again. */}- <GenerateToggleSwitch- checked={krea2ReferenceKvCacheApplies && settings.krea2ReferenceKvCache}- disabled={!krea2ReferenceKvCacheApplies}- helpText={t(KREA2_REFERENCE_KV_CACHE_HELP_KEYS[krea2EditLoraState])}- hint="krea2ReferenceKvCache"- label={t('widgets.generate.krea2ReferenceKvCache')}- onCheckedChange={(checked) => onCommit({ krea2ReferenceKvCache: checked })}- />- </Box>- ) : null}+ {policy.krea2ReferenceKvCacheVisible+ ? // Shown off while it is not sent; the stored value stays and is back once it applies again.+ defaultedSwitch({+ checked: krea2ReferenceKvCacheApplies && settings.krea2ReferenceKvCache,+ disabled: !krea2ReferenceKvCacheApplies,+ helpText: t(KREA2_REFERENCE_KV_CACHE_HELP_KEYS[krea2EditLoraState]),+ hint: 'krea2ReferenceKvCache',+ key: 'krea2ReferenceKvCache',+ label: t('widgets.generate.krea2ReferenceKvCache'),+ })+ : null}{policy.seamlessVisible ? (// A heading over its rows: more room below it than between the rows, so it does not read as a third row.- <Stack aria-labelledby={seamlessLabelId} gap="3" p="2" role="group" {...FEATURE_HINT_FIELD_PROPS}>+ <Stack aria-labelledby={seamlessLabelId} gap="3" role="group" {...FEATURE_HINT_FIELD_PROPS}>{/* The hint trigger takes over its child's id, so it wraps the text inside the named heading. */}<chakra.span css={fieldLabel()} id={seamlessLabelId}><FeatureHint hint="seamlessTiling"><chakra.span>{t('widgets.generate.seamlessTiling')}</chakra.span></FeatureHint></chakra.span>- <Stack gap="2">- <GenerateToggleSwitch- checked={settings.seamlessXAxis}- label={t('widgets.generate.xAxis')}- onCheckedChange={(checked) => onCommit({ seamlessXAxis: checked })}- />- <GenerateToggleSwitch- checked={settings.seamlessYAxis}- label={t('widgets.generate.yAxis')}- onCheckedChange={(checked) => onCommit({ seamlessYAxis: checked })}- />+ <Stack gap="2.5">+ {defaultedSwitch({ key: 'seamlessXAxis', label: t('widgets.generate.xAxis') })}+ {defaultedSwitch({ key: 'seamlessYAxis', label: t('widgets.generate.yAxis') })}</Stack></Stack>) : null}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsxindex 49d64c8ca2..947c0a1522 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateComponentsSection.tsx@@ -125,7 +125,7 @@ const ComponentPicker = ({return (// A fix button carries the issue id itself; without one this wrapper does, so a reveal lands on the slot.<Box data-issue-id={shownIssue && !shownIssue.fix ? shownIssue.id : undefined}>- <Field label={slot.label} helpText={slot.helpText} error={error}>+ <Field label={slot.label} labelPlacement="inside" helpText={slot.helpText} error={error}><ModelSelectfilter={slot.filter ? filter : undefined}invalid={Boolean(error)}@@ -187,7 +187,7 @@ export const GenerateComponentsSection = ({ draft, onCommit, selectedModel }: GedefaultOpen={policy.defaultOpen}sectionId="components">- <Stack gap="2" p="2">+ <Stack gap="2.5">{policy.slots.map((slot) => (<ComponentPickerRow key={slot.key} commitSlotValue={commitSlotValue} ctx={ctx!} slot={slot} />))}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.browser.test.tsxindex 4ff9eb83cd..cbebb54189 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.browser.test.tsx@@ -223,7 +223,7 @@ describe('GenerateConceptsContent', () => {});describe('a concept that is not installed', () => {- it('reads as blocked: its saved state, a locked switch, an error badge, and the issue with its Remove fix', async () => {+ it('reads as blocked: its saved state, a locked switch, an error badge, and an issue icon with its Remove fix', async () => {const missing: LoraModelConfig = { base: 'sdxl', key: 'gone', name: 'Gone', type: 'lora' };const applyFix = vi.fn();const issue = {@@ -262,10 +262,18 @@ describe('a concept that is not installed', () => {expect(missingRow.textContent).toContain('widgets.generate.notInstalled');expect(toggle.matches(':checked') || toggle.getAttribute('aria-checked') === 'true').toBe(true);expect(toggle.matches(':disabled') || toggle.getAttribute('aria-disabled') === 'true').toBe(true);- expect(missingRow.textContent).toContain('widgets.generate.issues.conceptNotInstalled');- expect(installedRow.querySelector('[data-issue-fix]')).toBeNull();-- await act(() => missingRow.querySelector<HTMLButtonElement>('[data-issue-fix]')!.click());+ // The issue is an icon beside the switch, named by its message; its fix waits in the icon's popover.+ const icon = missingRow.querySelector<HTMLButtonElement>('button[data-issue-ids]')!;+ expect(icon.getAttribute('data-issue-ids')).toBe(issue.id);+ expect(icon.getAttribute('aria-label')).toBe('widgets.generate.issuesNamed');+ expect(installedRow.querySelector('[data-issue-ids]')).toBeNull();++ await act(() => icon.click());+ await expect.poll(() => document.querySelector('[data-issue-id] [data-issue-fix]')).not.toBeNull();+ expect(document.querySelector('[data-issue-id]')?.textContent).toContain(+ 'widgets.generate.issues.conceptNotInstalled'+ );+ await act(() => document.querySelector<HTMLButtonElement>('[data-issue-id] [data-issue-fix]')!.click());expect(applyFix).toHaveBeenCalledExactlyOnceWith(issue.fix);});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsxindex cccaa0ac21..892900a836 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConceptsSection.tsx@@ -10,7 +10,7 @@ import {isLoraModelConfig,syncGenerateLorasWithModels,} from '@features/generation/core/settings';-import { Field } from '@platform/ui';+import { Field, FieldLabel } from '@platform/ui/Field';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -18,7 +18,7 @@ import type { GenerateSettingsUpdate } from './generateDebounce';import { GenerationModelSelect as ModelSelect, useGenerationUi } from './GenerationUiContext';import { ConceptList, ConceptRow } from './shared/ConceptRow';-import { GenerateIssueNotes } from './shared/GenerateIssues';+import { GenerateIssueButton } from './shared/GenerateIssues';interface GenerateConceptsContentProps {loraModels: LoraModelConfig[];@@ -92,7 +92,7 @@ export const GenerateConceptsContent = ({// Only a missing concept gets notes, so installed rows keep their memoized props.issue={isConceptInstalled(lora, loraModels, models.status) ? undefined : (- <GenerateIssueNotes conceptKey={lora.model.key} field="concepts" section="guidance" />+ <GenerateIssueButton conceptKey={lora.model.key} field="concepts" section="guidance" />)}lora={lora}@@ -109,6 +109,7 @@ export const GenerateConceptsContent = ({// Rows left from another model stay listed, marked incompatible, so they can still be removed.return (<Stack gap="2">+ <FieldLabel>{t('widgets.generate.concepts')}</FieldLabel><Text color="fg.muted" fontSize="xs">{t('widgets.generate.conceptsUnsupported')}</Text>@@ -121,7 +122,8 @@ export const GenerateConceptsContent = ({<Stack gap="2"><Fieldhint="concepts"- label={t('widgets.generate.addConcept')}+ // Titles the concept list as a whole, as "Reference images" titles the list above it.+ label={t('widgets.generate.concepts')}helpText={selectedModel ? undefined : t('widgets.generate.selectMainModelBeforeConcepts')}><ModelSelectdiff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.browser.test.tsxindex 20a57da06c..7f0056575f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.browser.test.tsx@@ -46,6 +46,8 @@ await i18n.use(initReactI18next).init({krea2RebalanceTapReadout: 'tap {{tap}} · {{value}}',krea2RebalanceWeights: 'Per-tap weights',krea2RebalanceWeightsInvalid: 'Enter exactly {{count}} comma-separated numbers.',+ resetFieldNamed: '{{reset}}: {{field}}',+ resetToDefault: 'Reset to default',},},},@@ -216,24 +218,63 @@ describe('GenerateConditioningRebalanceField', () => {expect(bars()[0]?.getAttribute('aria-label')).toBe('Tap 1, encoder layer 2');});- it('disables reset at the backend defaults and restores them once edited', async () => {+ it('marks the preset with the reset dot once edited, and the dot restores the backend defaults', async () => {await renderField();+ const dot = () => byLabel('Reset to default curve: Rebalance preset');- const reset = byLabel('Reset to default curve');-- expect(reset?.getAttribute('disabled')).not.toBeNull();+ // The dot replaced a separate reset button, and shows only off the defaults.+ expect(document.querySelector('button[aria-label="Reset to default curve"]')).toBeNull();+ expect(dot()).toBeNull();await interact(() => typeInto(weightsInput(), NEUTRAL_KREA2_REBALANCE_WEIGHTS));+ expect(dot()).not.toBeNull();- expect(byLabel('Reset to default curve')?.getAttribute('disabled')).toBeNull();-- await interact(() => byLabel('Reset to default curve')?.click());+ await interact(() => dot()?.click());expect(onCommitImmediate).toHaveBeenLastCalledWith({krea2RebalanceMultiplier: DEFAULT_KREA2_REBALANCE_MULTIPLIER,krea2RebalanceWeights: DEFAULT_KREA2_REBALANCE_WEIGHTS,});expect(weightsInput().value).toBe(DEFAULT_KREA2_REBALANCE_WEIGHTS);+ expect(dot()).toBeNull();+ // Focus moves to the preset select rather than falling to the page with the dot.+ await vi.waitFor(() =>+ expect(document.activeElement?.matches('[data-scope="select"][data-part="trigger"]')).toBe(true)+ );+ });++ describe('with only the gain changed', () => {+ const presetDot = () => byLabel('Reset to default curve: Rebalance preset');+ const gainDot = () => byLabel('Reset to default: Gain');+ const changedGain = DEFAULT_KREA2_REBALANCE_MULTIPLIER + 0.5;++ it('marks both the preset, now custom, and the gain; the gain dot resets the gain alone', async () => {+ await renderField({ krea2RebalanceMultiplier: changedGain });++ expect(presetDot()).not.toBeNull();+ expect(gainDot()).not.toBeNull();++ await interact(() => gainDot()?.click());++ expect(onCommit).toHaveBeenLastCalledWith({ krea2RebalanceMultiplier: DEFAULT_KREA2_REBALANCE_MULTIPLIER });+ expect(onCommitImmediate).not.toHaveBeenCalled();+ // The weights were the default curve all along, so the preset is back at it too.+ expect(gainDot()).toBeNull();+ expect(presetDot()).toBeNull();+ });++ it('resets the whole curve, gain included, from the preset dot', async () => {+ await renderField({ krea2RebalanceMultiplier: changedGain });++ await interact(() => presetDot()?.click());++ expect(onCommitImmediate).toHaveBeenLastCalledWith({+ krea2RebalanceMultiplier: DEFAULT_KREA2_REBALANCE_MULTIPLIER,+ krea2RebalanceWeights: DEFAULT_KREA2_REBALANCE_WEIGHTS,+ });+ expect(presetDot()).toBeNull();+ expect(gainDot()).toBeNull();+ });});it('commits a typed vector the backend would accept', async () => {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.tsxindex 227222f68d..11e86c9cbf 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateConditioningRebalanceField.tsx@@ -2,7 +2,7 @@import type { RebalancePreset } from '@features/generation/core/conditioningRebalance';import type { GenerateSettings } from '@features/generation/core/types';-import { createListCollection, HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { Box, createListCollection, HStack, Icon, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';import {BUILTIN_REBALANCE_PRESETS,DEFAULT_KREA2_REBALANCE_MULTIPLIER,@@ -20,8 +20,8 @@ import { MenuContent } from '@platform/ui/Menu';import { RenameDialog } from '@platform/ui/RenameDialog';import { ScrubberField } from '@platform/ui/ScrubberField';import { Select } from '@platform/ui/Select';-import { Tooltip } from '@platform/ui/Tooltip';-import { MoreHorizontalIcon, RotateCcwIcon } from 'lucide-react';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { MoreHorizontalIcon } from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -64,6 +64,7 @@ export const GenerateConditioningRebalanceField = ({settings,}: GenerateConditioningRebalanceFieldProps) => {const { t } = useTranslation();+ const presetActionsIds = useTooltipTriggerIds();const { notifications, rebalancePresets } = useGenerationUi();const [previewWeights, setPreviewWeights] = useState<number[] | null>(null);const [activeIndex, setActiveIndex] = useState<number | null>(null);@@ -100,6 +101,7 @@ export const GenerateConditioningRebalanceField = ({const isCustomPreset =activePreset !== null && !BUILTIN_REBALANCE_PRESETS.some((preset) => preset.id === activePreset.id);const isAtDefault = activePresetId === REBALANCE_PRESET_DEFAULT_ID;+ const presetLabel = activePreset?.label ?? t('widgets.generate.krea2RebalancePresetCustom');const applyWeights = useCallback((nextWeights: string, multiplier?: number) => {@@ -199,38 +201,36 @@ export const GenerateConditioningRebalanceField = ({{isEnabled ? (<Stack gap="2" w="full"><HStack gap="1">- <Select- aria-label={t('widgets.generate.krea2RebalancePreset')}- collection={presetCollection}- contentProps={SELECT_CONTENT_PROPS}- flex="1"- minW="0"- value={activePresetId === null ? [] : [activePresetId]}- valueText={activePreset?.label ?? t('widgets.generate.krea2RebalancePresetCustom')}- onValueChange={({ value }) => handlePresetChange(value)}- />- <Tooltip content={t('widgets.generate.krea2RebalanceReset')}>- <IconButton- aria-label={t('widgets.generate.krea2RebalanceReset')}- color="fg.muted"- disabled={isAtDefault}- size="sm"- variant="ghost"- onClick={handleReset}+ <Box flex="1" minW="0">+ <GenerateFieldContextMenu+ fieldLabel={t('widgets.generate.krea2RebalancePreset')}+ copyValue={() => presetLabel}+ isAtDefault={isAtDefault}+ resetLabel={t('widgets.generate.krea2RebalanceReset')}+ onReset={handleReset}>- <Icon as={RotateCcwIcon} boxSize="3" />- </IconButton>- </Tooltip>- <Menu.Root lazyMount unmountOnExit>+ <Select+ aria-label={t('widgets.generate.krea2RebalancePreset')}+ collection={presetCollection}+ contentProps={SELECT_CONTENT_PROPS}+ value={activePresetId === null ? [] : [activePresetId]}+ valueText={presetLabel}+ onValueChange={({ value }) => handlePresetChange(value)}+ />+ </GenerateFieldContextMenu>+ </Box>+ <Menu.Root ids={presetActionsIds} lazyMount unmountOnExit><Menu.Trigger asChild>- <IconButton- aria-label={t('widgets.generate.krea2RebalancePresetActions')}- color="fg.muted"- size="sm"- variant="ghost"- >- <Icon as={MoreHorizontalIcon} boxSize="3" />- </IconButton>+ <Tooltip content={t('widgets.generate.krea2RebalancePresetActions')} ids={presetActionsIds}>+ <IconButton+ aria-label={t('widgets.generate.krea2RebalancePresetActions')}+ color="fg.muted"+ size="sm"+ variant="ghost"+ >+ <Icon as={MoreHorizontalIcon} boxSize="3" />+ </IconButton>+ </Tooltip></Menu.Trigger><Portal><Menu.Positioner>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsxindex 1760ac5f20..0e0fc4736a 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx@@ -43,8 +43,9 @@ vi.mock('./GenerationUiContext', () => ({save: vi.fn(),update: vi.fn(),},+ models: { getBaseLabel: (base: string) => ({ 'sd-1': 'SD 1.x', sdxl: 'SDXL' })[base] ?? base },project: { invocationSourceId: harness.invocationSourceId },- sectionPreferences: { sectionsOpen: { dimensions: true }, setSectionOpen: vi.fn() },+ sectionPreferences: { sectionsOpen: { dimensions: true }, setSectionsOpen: vi.fn() },}),}));@@ -71,7 +72,14 @@ void i18n.use(initReactI18next).init({resetSizeOptimalForCurrentRatio: 'Optimal size for current ratio',resetSizeOptimalForRatio: 'Optimal size for {{ratio}}',resetSizeSquareNative: 'Square at native size',+ resetToBaseDefault: 'Reset to {{base}} default',+ resetToModelAndBaseDefault: 'Reset to model and {{base}} default',resetToModelDefault: 'Reset to model default',+ sectionMenu: {+ resetSize: 'Reset size to model defaults',+ resetSizeBase: 'Reset size to {{base}} defaults',+ resetSizeMixed: 'Reset size to model and {{base}} defaults',+ },size: 'Size',sizePreviewHandle: 'Resize',swapWidthAndHeight: 'Swap width and height',@@ -107,11 +115,12 @@ const settle = (action: () => void): Promise<void> =>});});-const render = async (settings: Partial<GenerateSettings>, model: GenerateModelConfig = sd1Model) => {+/** `null` renders the section with no model selected, so with no model defaults. */+const render = async (settings: Partial<GenerateSettings>, model: GenerateModelConfig | null = sd1Model) => {host = document.createElement('div');document.body.append(host);root = createRoot(host);- const draft = createExternalStoreCore({ ...getDefaultGenerateSettings(model), ...settings });+ const draft = createExternalStoreCore({ ...getDefaultGenerateSettings(model ?? undefined), ...settings });// Commits and resets land in the draft, as the panel's draft would show them.const onCommit = vi.fn((patch: Partial<GenerateSettings>) => draft.patchSnapshot(patch));const onResetSize = vi.fn((patch: Partial<GenerateSettings>) => draft.patchSnapshot(patch));@@ -123,7 +132,7 @@ const render = async (settings: Partial<GenerateSettings>, model: GenerateModelC<GenerateDimensionFieldsdraft={draft}projectId="project"- selectedModel={model}+ selectedModel={model ?? undefined}onCommit={onCommit}onResetSize={onResetSize}/>@@ -702,3 +711,57 @@ describe('GenerateDimensionFields Reset size', () => {expect(host?.textContent).not.toContain('Set optimal size');});});++describe('GenerateDimensionFields title defaults', () => {+ const title = () => host!.querySelector<HTMLElement>('.generate-section > [data-part="trigger"]')!;+ const isMarked = () => title().querySelector('[data-section-changed]') !== null;+ const openMenu = async () => {+ await act(() => {+ title().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));+ });+ await expect.element(page.getByRole('menu')).toBeVisible();+ };+ const resetItem = () => page.getByRole('menuitem', { name: 'Reset size to model defaults' });++ it('marks a size off the model default and resets it from the title menu', async () => {+ const portraitModel: MainModelConfig = { ...sd1Model, default_settings: { height: 768, width: 640 } };+ const { onResetSize } = await render({ height: 512, width: 512 }, portraitModel);++ expect(isMarked()).toBe(true);+ await openMenu();+ await userEvent.click(resetItem());++ expect(onResetSize).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ height: 768, width: 640 }));+ await vi.waitFor(() => expect(isMarked()).toBe(false));+ });++ it("names the base as the source of the size for a model that sets none, and resets to the base's size", async () => {+ const { onResetSize } = await render({ height: 768, width: 512 }, sd1Model);++ await openMenu();+ await userEvent.click(page.getByRole('menuitem', { name: 'Reset size to SD 1.x defaults' }));++ const { height, width } = getDefaultGenerateSettings(sd1Model);+ expect(onResetSize).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ height, width }));+ await userEvent.click(page.getByRole('slider', { name: 'Width' }), { button: 'right' });+ await expect.element(page.getByRole('menuitem', { name: 'Reset to SD 1.x default' })).toBeInTheDocument();+ });++ it('names both sources for a model that sets one side of the size', async () => {+ await render({ height: 768, width: 512 }, { ...sd1Model, default_settings: { width: 640 } });++ await openMenu();+ await expect.element(page.getByRole('menuitem', { name: 'Reset size to model and SD 1.x defaults' })).toBeVisible();+ await userEvent.keyboard('{Escape}');+ await userEvent.click(page.getByRole('slider', { name: 'Width' }), { button: 'right' });+ await expect.element(page.getByRole('menuitem', { name: 'Reset to model and SD 1.x default' })).toBeInTheDocument();+ });++ it('neither marks nor offers a reset without a model to take defaults from', async () => {+ await render({ height: 512, width: 768 }, null);++ expect(isMarked()).toBe(false);+ await openMenu();+ await expect.element(resetItem()).not.toBeInTheDocument();+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsxindex 1ab5298857..171f19ab17 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx@@ -1,7 +1,7 @@/* eslint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */import type { AspectRatioId, GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';-import { Badge, Box, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { Box, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';import {formatAspectRatio,getLockedAspectRatioSettings,@@ -14,6 +14,7 @@ import {calculateNewSize,clampDimension,deriveAspectRatioId,+ getActiveAspectRatio,isAspectRatioLocked,} from '@features/generation/core/settings';import { useExternalStoreSelector } from '@platform/state/selectors';@@ -37,6 +38,12 @@ import { ExternalSizeSelect } from './shared/ExternalSizeSelect';import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection';import { GenerateFieldContextMenu } from './shared/GenerateFieldContextMenu';import { GenerateIssueNotes } from './shared/GenerateIssues';+import {+ doesModelSetDefault,+ getDefaultSizePatch,+ getDefaultSource,+ getFieldResetLabel,+} from './shared/modelDefaultSettings';interface GenerateDimensionFieldsProps {draft: GenerateDraft;@@ -49,14 +56,6 @@ interface GenerateDimensionFieldsProps {type Dimensions = Pick<GenerateSettings, 'height' | 'width'>;-/** The ratio to enforce, preferring the stored value and falling back to the current dimensions. */-const getActiveRatio = (settings: Pick<GenerateSettings, 'aspectRatioValue' | 'height' | 'width'>): number =>- settings.aspectRatioValue > 0- ? settings.aspectRatioValue- : settings.height > 0- ? settings.width / settings.height- : 1;-const PREVIEW_STAGE_PX = 108;/** An 8px grip drawn inside a 16px target, so the corner is easy to catch without looking heavier. */const SIZE_HANDLE_CSS = {@@ -108,13 +107,6 @@ const PREVIEW_PAD_PX = 10;const clampToRange = (value: number): number => Math.min(MAX_DIMENSION, Math.max(MIN_DIMENSION, value));-/** Whether the model sets a size of its own; otherwise its defaults are just the architecture's optimal size. */-const hasModelDefaultSize = (model: GenerateModelConfig | undefined): boolean => {- const defaults = model?.default_settings;-- return Number.isFinite(defaults?.width) || Number.isFinite(defaults?.height);-};-const RESET_SIZE_MENU_POSITIONING = { placement: 'bottom-end' } as const;interface ResetSizeChoice {@@ -154,16 +146,17 @@ const ResetSizeMenu = ({ choices }: { choices: readonly ResetSizeChoice[] }) =></Menu.Trigger><Portal><Menu.Positioner>- <MenuContent minW="15rem">+ <MenuContent minW="0"><Menu.RadioItemGroup value={current} onValueChange={onValueChange}>{choices.map((choice) => (- <Menu.RadioItem key={choice.value} value={choice.value}>+ // The row draws its own check, so it drops the indent a radio item keeps for an indicator.+ <Menu.RadioItem key={choice.value} ps="2" value={choice.value}><HStack gap="2" minW="0" w="full"><Iconas={CheckIcon}aria-hiddenboxSize="3.5"- color="fg.subtle"+ color="fg"flexShrink={0}opacity={choice.value === current ? 1 : 0}/>@@ -379,7 +372,7 @@ export const GenerateDimensionFields = ({selectedModel,}: GenerateDimensionFieldsProps) => {const { i18n, t } = useTranslation();- const { aspectRatioPresets, CanvasRenderSize: CanvasRenderSizeSlot, project } = useGenerationUi();+ const { aspectRatioPresets, CanvasRenderSize: CanvasRenderSizeSlot, models, project } = useGenerationUi();const settings = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectDimensionSettings);const secondsPerRun = useGenerationQueueInsights(selectSecondsPerRun);const [draftDimensions, setDraftDimensions] = useState<Dimensions | null>(null);@@ -444,7 +437,7 @@ export const GenerateDimensionFields = ({return { ...displayDimensions, [key]: nextValue };}- const ratio = getActiveRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions });+ const ratio = getActiveAspectRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions });return key === 'width'? { height: shouldSnap ? clampDimension(nextValue / ratio, dimensionGrid) : nextValue / ratio, width: nextValue }@@ -527,7 +520,7 @@ export const GenerateDimensionFields = ({const lockedRatio = isRatioConstrained? settings.aspectRatioId !== 'Free'? ASPECT_RATIO_MAP[settings.aspectRatioId].ratio- : getActiveRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions })+ : getActiveAspectRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions }): null;// The model's pixel budget reshaped to the ratio the section holds.const optimalSize = calculateNewSize(@@ -551,28 +544,27 @@ export const GenerateDimensionFields = ({: formatAspectRatio(lockedRatio, i18n.resolvedLanguage),});- // The ratio follows the size: a lock stays on and holds the default size's ratio, an unlocked ratio stays unlocked.const resetToModelDefaults = () => {- if (!modelDefaults) {- return;+ if (modelDefaults) {+ resetSize(getDefaultSizePatch(settings, modelDefaults));}-- const { height, width } = modelDefaults;- const ratio = height > 0 ? width / height : 1;-- resetSize({- ...(isRatioConstrained- ? getLockedAspectRatioSettings(ratio)- : { aspectRatioId: 'Free', aspectRatioIsLocked: false, aspectRatioValue: ratio }),- height,- width,- });};+ const modelSetsSize = selectedModel !== undefined && doesModelSetDefault(selectedModel, 'size');// Only a size the model sets itself is worth offering; otherwise its defaults are the native square.const modelDefaultSize =- modelDefaults && hasModelDefaultSize(selectedModel)- ? { height: modelDefaults.height, width: modelDefaults.width }- : null;+ modelDefaults && modelSetsSize ? { height: modelDefaults.height, width: modelDefaults.width } : null;+ const baseLabel = selectedModel?.type === 'main' ? models.getBaseLabel(selectedModel.base) : null;+ const sizeSource = selectedModel ? getDefaultSource(selectedModel, ['size']) : 'base';+ // An external model's fallback size belongs to no base, so it is a plain default. One side set by the model takes+ // the other from the base.+ const sizeSectionResetLabel =+ sizeSource === 'model'+ ? t('widgets.generate.sectionMenu.resetSize')+ : baseLabel === null+ ? t('widgets.generate.sectionMenu.reset')+ : sizeSource === 'mixed'+ ? t('widgets.generate.sectionMenu.resetSizeMixed', { base: baseLabel })+ : t('widgets.generate.sectionMenu.resetSizeBase', { base: baseLabel });const resetSizeChoices: readonly ResetSizeChoice[] = [// First, as the choice most reached for. A square ratio's optimal size is the native square, which the square choice@@ -626,6 +618,10 @@ export const GenerateDimensionFields = ({dimensionGrid);const frameLabel = `${displayDimensions.width}×${displayDimensions.height}`;+ // Without model defaults there is nothing to differ from.+ const isAtModelDefaultSize =+ modelDefaults === null ||+ (displayDimensions.width === modelDefaults.width && displayDimensions.height === modelDefaults.height);// The optimal-side stop is scalar; recommended dimensions preserve the live ratio.const dimensionField = (key: 'height' | 'width') => (@@ -669,31 +665,32 @@ export const GenerateDimensionFields = ({return (<GenerateCollapsibleSectionlabel={t('widgets.generate.size')}- badges={- <>- <Badge>{isResized ? `${frameLabel} → ${renderSize.width}×${renderSize.height}` : frameLabel}</Badge>- {isRatioConstrained && (- <Badge>- <Icon as={LockIcon} boxSize="3" />- </Badge>- )}- </>- }+ summary={[+ isResized ? `${frameLabel} → ${renderSize.width}×${renderSize.height}` : frameLabel,+ isRatioConstrained ? (+ <>+ <Icon as={LockIcon} aria-hidden boxSize="3" verticalAlign="-0.125em" />+ <Text as="span" srOnly>+ {t('widgets.generate.aspectRatioLocked')}+ </Text>+ </>+ ) : null,+ ]}defaultOpen+ isChanged={!isAtModelDefaultSize}sectionId="dimensions"+ resetLabel={sizeSectionResetLabel}+ onReset={modelDefaults ? resetToModelDefaults : undefined}>- <Stack gap="2" p="2">+ <Stack gap="2.5"><HStack alignItems="stretch" gap="2"><Stack flex="1" gap="2" minW="0">{/* The lock binds width to height, so it sits between the two values it couples. */}<GenerateFieldContextMenufieldLabel={t('widgets.generate.size')}copyValue={() => `${displayDimensions.width}x${displayDimensions.height}`}- isAtDefault={- modelDefaults !== null &&- displayDimensions.width === modelDefaults.width &&- displayDimensions.height === modelDefaults.height- }+ isAtDefault={isAtModelDefaultSize}+ resetLabel={getFieldResetLabel('size', selectedModel, models.getBaseLabel, t)}onReset={modelDefaults ? resetToModelDefaults : undefined}><HStack alignItems="center" gap="1">@@ -767,7 +764,7 @@ export const GenerateDimensionFields = ({isRatioConstrained={isRatioConstrained}ratio={isRatioConstrained- ? getActiveRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions })+ ? getActiveAspectRatio({ aspectRatioValue: settings.aspectRatioValue, ...displayDimensions }): dimensionRatio}onCancelDrag={() => setDraftDimensions(null)}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.browser.test.tsxindex 26a3c6f387..8646c1c316 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.browser.test.tsx@@ -16,7 +16,7 @@ import { GenerateGuidanceSection } from './GenerateGuidanceSection';vi.mock('./GenerationUiContext', () => ({useGenerationUi: () => ({models: { status: 'loaded' },- sectionPreferences: { sectionsOpen: { guidance: true }, setSectionOpen: vi.fn() },+ sectionPreferences: { sectionsOpen: { guidance: true }, setSectionsOpen: vi.fn() },}),}));// The lists have their own tests; this one covers the note the section shows between them.diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsxindex 087c38fdc1..2c814054d8 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx@@ -1,18 +1,16 @@import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';-import { Badge, Separator, Stack, Text } from '@chakra-ui/react';-import {- getKrea2EditLoraState,- getReferenceImageUnavailableReason,- isReferenceImageSupported,-} from '@features/generation/core/baseGenerationPolicies';+import { Flex, Icon, Stack, Text } from '@chakra-ui/react';+import { getKrea2EditLoraState, isReferenceImageSupported } from '@features/generation/core/baseGenerationPolicies';import {type GenerateDraft,type GenerateSettingsUpdate,pickGenerateSettings,} from '@features/generation/ui/generateDebounce';import { useExternalStoreSelector } from '@platform/state/selectors';+import { TriangleAlertIcon } from 'lucide-react';+import { useMemo } from 'react';import { useTranslation } from 'react-i18next';import { GenerateConceptsContent, isCompatibleLora, isConceptInstalled } from './GenerateConceptsSection';@@ -68,28 +66,48 @@ export const GenerateGuidanceSection = ({const activeCount = activeReferenceImages + activeConcepts;const totalCount = referenceImageCount + settings.loras.length;- const badges = (- <>- {hasIncompatible ? (- <Badge colorPalette="orange" variant="surface">- {t('widgets.generate.incompatible')}- </Badge>- ) : null}- {activeCount > 0 ? (- <Badge variant="surface">- {activeCount === totalCount- ? t('widgets.generate.activeCount', { count: activeCount })- : t('widgets.generate.activeOfTotal', { active: activeCount, total: totalCount })}- </Badge>- ) : totalCount > 0 ? (- <Badge variant="surface">{t('widgets.generate.offCount', { count: totalCount })}</Badge>- ) : null}- </>+ // Whether something here cannot run, or is all switched off, holds open or folded; what is active is a summary.+ // Both read as the title row's own summary text, so a section's state looks the same whichever kind it is.+ const isAllOff = activeCount === 0 && totalCount > 0;+ const status = useMemo(+ () => (+ <Flex align="center" fontSize="sm" gap="2">+ {hasIncompatible ? (+ <Flex as="span" align="center" color="fg.warning" gap="1">+ <Icon as={TriangleAlertIcon} aria-hidden boxSize="3" flexShrink={0} />+ {t('widgets.generate.incompatible')}+ </Flex>+ ) : null}+ {isAllOff ? (+ <Text as="span" color="fg.muted">+ {t('widgets.generate.offCount', { count: totalCount })}+ </Text>+ ) : null}+ </Flex>+ ),+ [hasIncompatible, isAllOff, t, totalCount]+ );+ const summary = useMemo(+ () =>+ activeCount === 0+ ? undefined+ : [+ activeCount === totalCount+ ? t('widgets.generate.activeCount', { count: activeCount })+ : t('widgets.generate.activeOfTotal', { active: activeCount, total: totalCount }),+ ],+ [activeCount, t, totalCount]);return (- <GenerateCollapsibleSection label={t('widgets.generate.guidance')} defaultOpen badges={badges} sectionId="guidance">- <Stack gap="2" p="2">+ <GenerateCollapsibleSection+ label={t('widgets.generate.guidance')}+ defaultOpen+ sectionId="guidance"+ status={status}+ summary={summary}+ >+ <Stack gap="2.5"><GenerateReferenceImagesContentmodels={models}visionComponents={settings}@@ -104,11 +122,6 @@ export const GenerateGuidanceSection = ({{t('widgets.generate.krea2EditReferencesNeedLora')}</Text>) : null}- {referenceImagesSupported ||- referenceImageCount > 0 ||- getReferenceImageUnavailableReason(selectedModel, settings) ? (- <Separator borderColor="bg.subtle" />- ) : null}<GenerateConceptsContentloraModels={loraModels}loras={settings.loras}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.browser.test.tsxindex 3cae671745..8c9d7b2b77 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.browser.test.tsx@@ -1,6 +1,7 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */import type { MainModelConfig } from '@features/generation/core/types';import type { GenerationUiAdapter } from '@features/generation/ui/GenerationUiContext';+import type * as MenuModule from '@platform/ui/Menu';import { ChakraProvider } from '@chakra-ui/react';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';@@ -8,18 +9,56 @@ import { getDefaultGenerateSettings } from '@features/generation/core/baseGeneraimport { GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';import { createExternalStoreCore } from '@platform/state/externalStoreCore';import { system } from '@theme/system';+import { createInstance } from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';import { GenerateHeaderActions } from './GenerateHeaderActions';+// Each test starts with the items unloaded, as a page does: the loaders the module creates are swapped for fresh ones.+const menuParts = vi.hoisted(() => ({+ loaders: [] as { getSnapshot: () => { status: string }; reset: () => void }[],+}));+vi.mock('@platform/ui/Menu', async (importOriginal) => {+ const original = await importOriginal<typeof MenuModule>();++ return {+ ...original,+ createMenuPartLoader: <Part,>(importPart: () => Promise<Part>) => {+ let current = original.createMenuPartLoader(importPart);+ const loader = {+ getSnapshot: () => current.getSnapshot(),+ load: () => current.load(),+ reset: () => {+ current = original.createMenuPartLoader(importPart);+ },+ subscribe: (listener: () => void) => current.subscribe(listener),+ };+ menuParts.loaders.push(loader);+ return loader;+ },+ };+});+seedArchitectureCapabilities();+// The real catalog, so the tooltip and toast read as users see them.+const i18n = createInstance();+await i18n.use(initReactI18next).init({+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});+let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+beforeEach(() => menuParts.loaders.forEach((loader) => loader.reset()));+afterEach(async () => {await act(() => root?.unmount());host?.remove();@@ -27,55 +66,246 @@ afterEach(async () => {root = null;});-const model: MainModelConfig = { base: 'sdxl', key: 'sdxl', name: 'SDXL', type: 'main' };+/** A turbo SDXL model that sets steps and CFG in the Model Manager, and no size. */+const turbo: MainModelConfig = {+ base: 'sdxl',+ default_settings: { cfg_scale: 1, steps: 8 },+ key: 'sdxl-turbo',+ name: 'SDXL Turbo',+ type: 'main',+};-describe('GenerateHeaderActions', () => {- it('resets to the model defaults at once, with an Undo that restores the earlier values', async () => {- const values = createExternalStoreCore<Record<string, unknown>>({- ...getDefaultGenerateSettings(model),- cfgScale: 4,- model,- positivePrompt: 'a lighthouse',- steps: 12,- });- const patchGenerateSettings = vi.fn((patch: Record<string, unknown>) => values.patchSnapshot(patch));- const undoable = vi.fn();- const adapter = {- generateValues: values,- models: { catalog: [model] },- notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn(), undoable },- presets: { includePrompts: true, presets: [], remove: vi.fn(), rename: vi.fn(), save: vi.fn() },- project: { activeProjectId: 'project-1' },- settings: { patchGenerateSettings, readGenerateValues: () => values.getSnapshot() },- } as unknown as GenerationUiAdapter;- host = document.createElement('div');- document.body.append(host);- root = createRoot(host);- await act(() =>- root?.render(- <ChakraProvider value={system}>+const render = async (model: MainModelConfig) => {+ const values = createExternalStoreCore<Record<string, unknown>>({+ ...getDefaultGenerateSettings(model),+ aspectRatioId: 'Free',+ aspectRatioValue: 1216 / 832,+ cfgScale: 7,+ height: 832,+ model,+ positivePrompt: 'a lighthouse',+ steps: 30,+ width: 1216,+ });+ const patchGenerateSettings = vi.fn((patch: Record<string, unknown>) => values.patchSnapshot(patch));+ const undoable = vi.fn();+ const adapter = {+ generateValues: values,+ models: { catalog: [model], getBaseLabel: () => 'SDXL' },+ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn(), undoable },+ presets: { includePrompts: true, presets: [], remove: vi.fn(), rename: vi.fn(), save: vi.fn() },+ project: { activeProjectId: 'project-1' },+ settings: { patchGenerateSettings, readGenerateValues: () => values.getSnapshot() },+ } as unknown as GenerationUiAdapter;+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}><GenerationUiProvider adapter={adapter}><GenerateHeaderActions /></GenerationUiProvider>- </ChakraProvider>- )- );+ </I18nextProvider>+ </ChakraProvider>+ )+ );- await act(() =>- host!.querySelector<HTMLButtonElement>('[aria-label="widgets.generate.resetAllToModelDefaults"]')!.click()- );+ return { patchGenerateSettings, undoable, values };+};++const trigger = () => page.getByRole('button', { name: 'Reset settings' });+const item = (name: string) => page.getByRole('menuitem', { name });+const openMenu = async () => {+ await userEvent.click(trigger());+ await expect.element(page.getByRole('menu')).toBeVisible();+};++/** Waits for the warm-up that pointing at or focusing the button starts, without loading the items itself. */+const settleWarmUp = () =>+ vi.waitFor(() => expect(menuParts.loaders.map((loader) => loader.getSnapshot().status)).toEqual(['loaded']));++/** Records whether the placeholder ever mounts while `open` runs. */+const placeholdersDuring = async (open: () => Promise<unknown>): Promise<Node[]> => {+ const placeholders: Node[] = [];+ const observer = new MutationObserver(() =>+ placeholders.push(...document.querySelectorAll('[data-value="menu-part-placeholder"]'))+ );+ observer.observe(document.body, { childList: true, subtree: true });+ await open();+ observer.disconnect();++ return placeholders;+};- expect(values.getSnapshot()).toMatchObject({ cfgScale: 7, positivePrompt: 'a lighthouse', steps: 30 });- expect(undoable).toHaveBeenCalledExactlyOnceWith('widgets.generate.resetToModelDefaultsDone', {+describe('GenerateHeaderActions', () => {+ it("opens on its items' first frame once pointing at the button has loaded them", async () => {+ await render(turbo);+ await userEvent.hover(trigger());+ await settleWarmUp();++ const placeholders = await placeholdersDuring(async () => {+ await userEvent.click(trigger());+ await expect.element(item('Apply model defaults')).toBeVisible();+ });++ expect(placeholders).toEqual([]);+ expect(page.getByRole('menu').element().getAttribute('aria-busy')).toBe('false');+ });++ it("opens from the keyboard on its items' first frame once focusing the button has loaded them", async () => {+ await render(turbo);+ await act(() => (trigger().element() as HTMLButtonElement).focus());+ await settleWarmUp();++ const placeholders = await placeholdersDuring(async () => {+ await userEvent.keyboard('{Enter}');+ await expect.element(item('Apply model defaults')).toBeVisible();+ });++ expect(placeholders).toEqual([]);+ expect(page.getByRole('menu').element().getAttribute('aria-busy')).toBe('false');+ });++ it("says what applying changes, changes only the model's own values, and undoes them in one step", async () => {+ const { patchGenerateSettings, undoable, values } = await render(turbo);++ await openMenu();+ await expect+ .element(item('Apply model defaults'))+ .toHaveAccessibleDescription(+ 'Steps 30 → 8, CFG 7 → 1. Left as is, not set for this model: Size, Scheduler, VAE, and VAE precision'+ );+ await userEvent.click(item('Apply model defaults'));++ expect(patchGenerateSettings).toHaveBeenCalledExactlyOnceWith({ cfgScale: 1, steps: 8 }, 'project-1');+ expect(values.getSnapshot()).toMatchObject({+ cfgScale: 1,+ height: 832,+ positivePrompt: 'a lighthouse',+ steps: 8,+ width: 1216,+ });+ expect(undoable).toHaveBeenCalledExactlyOnceWith('Applied SDXL Turbo defaults', {+ message: 'Steps 30 → 8, CFG 7 → 1',onUndo: expect.any(Function),projectId: 'project-1',supersedes: 'generate-settings:project-1',});- // Steps were changed again since the reset; the Undo keeps that edit and restores the rest.+ // Nothing is left to apply, and the item says why.+ await openMenu();+ await expect.element(item('Apply model defaults')).toHaveAttribute('aria-disabled', 'true');+ await expect+ .element(item('Apply model defaults'))+ .toHaveAccessibleDescription(expect.stringContaining("Already using SDXL Turbo's defaults."));+ await userEvent.keyboard('{Escape}');++ // Steps were changed again since; the Undo keeps that edit and restores the rest.values.patchSnapshot({ steps: 50 });await act(() => undoable.mock.calls[0]![1].onUndo());- expect(values.getSnapshot()).toMatchObject({ cfgScale: 4, steps: 50 });+ expect(values.getSnapshot()).toMatchObject({ cfgScale: 7, steps: 50 });+ });++ it('resets everything, size included, from the keyboard, returning focus to the button, undone in one step', async () => {+ const { undoable, values } = await render(turbo);++ await act(() => (trigger().element() as HTMLButtonElement).focus());+ await settleWarmUp();+ await userEvent.keyboard('{Enter}');+ await expect+ .element(item('Reset everything to defaults'))+ .toHaveAccessibleDescription('Size 1216×832 → 1024×1024, Aspect ratio Free → 1:1, Steps 30 → 8, CFG 7 → 1');+ // The menu takes focus once open and tracks the highlighted item, the first, by attribute.+ await vi.waitFor(() => expect(document.activeElement?.getAttribute('role')).toBe('menu'));+ await userEvent.keyboard('{ArrowDown}');+ // Zag focuses the menu a frame after each move; Enter in the same frame would race that focus.+ await expect.element(item('Reset everything to defaults')).toHaveAttribute('data-highlighted');+ await new Promise(requestAnimationFrame);+ await userEvent.keyboard('{Enter}');++ expect(values.getSnapshot()).toMatchObject({ cfgScale: 1, height: 1024, steps: 8, width: 1024 });+ expect(undoable).toHaveBeenCalledExactlyOnceWith('Reset everything to defaults', {+ message: 'Size 1216×832 → 1024×1024, Aspect ratio Free → 1:1, Steps 30 → 8, CFG 7 → 1',+ onUndo: expect.any(Function),+ projectId: 'project-1',+ supersedes: 'generate-settings:project-1',+ });+ await vi.waitFor(() => expect(document.activeElement).toBe(trigger().element()));++ await act(() => undoable.mock.calls[0]![1].onUndo());++ expect(values.getSnapshot()).toMatchObject({ cfgScale: 7, height: 832, steps: 30, width: 1216 });+ });++ it('names a ratio lock the full reset sets when the size already matches, in the hint and the toast', async () => {+ const { undoable, values } = await render(turbo);+ values.patchSnapshot({ aspectRatioValue: 1, cfgScale: 1, height: 1024, steps: 8, width: 1024 });++ await openMenu();+ await expect.element(item('Reset everything to defaults')).toHaveAccessibleDescription('Aspect ratio Free → 1:1');+ await userEvent.click(item('Reset everything to defaults'));++ expect(values.getSnapshot()).toMatchObject({ aspectRatioId: '1:1', height: 1024, width: 1024 });+ expect(undoable).toHaveBeenCalledExactlyOnceWith(+ 'Reset everything to defaults',+ expect.objectContaining({ message: 'Aspect ratio Free → 1:1' })+ );+ });++ it('tells a default VAE that is not installed apart from what the model does not set', async () => {+ await render({ ...turbo, default_settings: { steps: 8, vae: 'not-installed' } });++ await openMenu();+ await expect+ .element(item('Apply model defaults'))+ .toHaveAccessibleDescription(+ 'Steps 30 → 8. Left as is, not set for this model: Size, CFG, Scheduler, and VAE precision. ' ++ "The model's VAE is not installed or does not fit it, so your VAE stays."+ );+ });++ it('says why there is nothing to apply when the only default is a VAE that is not installed', async () => {+ await render({ ...turbo, default_settings: { vae: 'not-installed' }, name: 'VAE only' });++ await openMenu();+ await expect.element(item('Apply model defaults')).toHaveAttribute('aria-disabled', 'true');+ // Told once, in the reason.+ await expect+ .element(item('Apply model defaults'))+ .toHaveAccessibleDescription(+ 'Left as is, not set for this model: Size, Steps, CFG, Scheduler, and VAE precision ' ++ 'VAE only sets only a VAE, which is not installed or does not fit it, so your VAE stays.'+ );+ });++ it("agrees that the model's values hold except a VAE that is not installed", async () => {+ await render({ ...turbo, default_settings: { steps: 30, vae: 'not-installed' }, name: 'Steps only' });++ await openMenu();+ await expect.element(item('Apply model defaults')).toHaveAttribute('aria-disabled', 'true');+ await expect+ .element(item('Apply model defaults'))+ .toHaveAccessibleDescription(+ 'Left as is, not set for this model: Size, CFG, Scheduler, and VAE precision ' ++ "Already using Steps only's defaults, except its VAE, which is not installed or does not fit it, so your " ++ 'VAE stays.'+ );+ });++ it('offers no apply, saying why, for a model with no defaults of its own', async () => {+ const { patchGenerateSettings } = await render({ ...turbo, default_settings: null, name: 'Plain SDXL' });++ await openMenu();+ await expect.element(item('Apply model defaults')).toHaveAttribute('aria-disabled', 'true');+ await expect+ .element(item('Apply model defaults'))+ .toHaveAccessibleDescription('Plain SDXL has no default settings of its own. Add them in the Model Manager.');+ // Playwright refuses to click an aria-disabled control, so the click goes to the element itself.+ await act(() => (item('Apply model defaults').element() as HTMLElement).click());++ expect(patchGenerateSettings).not.toHaveBeenCalled();});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.loadFailure.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.loadFailure.browser.test.tsxnew file mode 100644index 0000000000..81bda5a4c7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.loadFailure.browser.test.tsx@@ -0,0 +1,107 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { MainModelConfig } from '@features/generation/core/types';+import type { GenerationUiAdapter } from '@features/generation/ui/GenerationUiContext';+import type * as MenuModule from '@platform/ui/Menu';++import { ChakraProvider } from '@chakra-ui/react';+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';+import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';+import { GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';+import { createExternalStoreCore } from '@platform/state/externalStoreCore';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: {}, t: (key: string) => key }) }));+// The items' import fails as a dropped connection would until `fail` clears. Its own file: a page keeps loaded items.+const load = vi.hoisted(() => ({ fail: true }));+vi.mock('@platform/ui/Menu', async (importOriginal) => {+ const original = await importOriginal<typeof MenuModule>();++ return {+ ...original,+ createMenuPartLoader: <Part,>(importPart: () => Promise<Part>) =>+ original.createMenuPartLoader(() =>+ load.fail ? Promise.reject(new TypeError('Failed to fetch dynamically imported module')) : importPart()+ ),+ };+});++import { GenerateHeaderActions } from './GenerateHeaderActions';++seedArchitectureCapabilities();+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const model: MainModelConfig = {+ base: 'sdxl',+ default_settings: { cfg_scale: 1, steps: 8 },+ key: 'sdxl-turbo',+ name: 'SDXL Turbo',+ type: 'main',+};++const host = document.createElement('div');+const root = createRoot(host);+const unhandled = vi.fn();++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ window.removeEventListener('unhandledrejection', unhandled);+});++it('says the items could not load, leaves the editor standing, and loads them on a later open', async () => {+ window.addEventListener('unhandledrejection', unhandled);+ document.body.append(host);+ const values = createExternalStoreCore<Record<string, unknown>>({ ...getDefaultGenerateSettings(model), model });+ const adapter = {+ generateValues: values,+ models: { catalog: [model], getBaseLabel: () => 'SDXL' },+ notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn(), undoable: vi.fn() },+ presets: { includePrompts: true, presets: [], remove: vi.fn(), rename: vi.fn(), save: vi.fn() },+ project: { activeProjectId: 'project-1' },+ settings: { patchGenerateSettings: vi.fn(), readGenerateValues: () => values.getSnapshot() },+ } as unknown as GenerationUiAdapter;+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <GenerationUiProvider adapter={adapter}>+ <GenerateHeaderActions />+ </GenerationUiProvider>+ </ChakraProvider>+ )+ );+ const trigger = page.getByRole('button', { name: 'widgets.generate.resetSettings' });++ // Pointing at the button warms the items; that load failing is no unhandled rejection.+ await userEvent.hover(trigger);+ await userEvent.click(trigger);+ const failed = page.getByRole('menuitem', { name: 'common.menuPartLoadFailed' });+ await expect.element(failed).toHaveAttribute('aria-disabled', 'true');+ expect(page.getByRole('menu').element().getAttribute('aria-busy')).toBe('false');+ expect(trigger.element().isConnected).toBe(true);++ await userEvent.keyboard('{Escape}');+ await expect.element(page.getByRole('menu')).not.toBeInTheDocument();++ // The keyboard reaches the failed item, and it says how to recover.+ trigger.element().focus();+ await userEvent.keyboard('{Enter}');+ await expect.element(failed).toBeInTheDocument();+ await userEvent.keyboard('{ArrowDown}');+ await expect.element(failed).toHaveAttribute('data-highlighted');+ expect(page.getByRole('menu').element().getAttribute('aria-activedescendant')).toBe(failed.element().id);+ await expect.element(failed).toHaveAccessibleDescription('common.menuPartLoadFailedReason');+ await userEvent.keyboard('{Enter}');+ await expect.element(page.getByRole('menu')).toBeVisible();+ await userEvent.keyboard('{Escape}');+ await expect.element(page.getByRole('menu')).not.toBeInTheDocument();+ load.fail = false;+ await userEvent.click(trigger);++ await expect.element(page.getByRole('menuitem', { name: 'widgets.generate.applyModelDefaults' })).toBeVisible();+ expect(failed.query()).toBeNull();+ expect(unhandled).not.toHaveBeenCalled();+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.tsxindex 4314aef481..0567cca80b 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateHeaderActions.tsx@@ -1,96 +1,90 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';-import type { VaeModelConfig } from '@features/generation/core/types';--import { Icon } from '@chakra-ui/react';+import { Icon, Menu, Portal } from '@chakra-ui/react';import { isSupportedGenerateModel } from '@features/generation/core/baseGenerationPolicies';import { normalizeGenerateSettings } from '@features/generation/core/settings';-import { IconButton, Tooltip } from '@platform/ui';+import { IconButton } from '@platform/ui/Button';+import { createMenuPartLoader, MenuContent, MenuPartPlaceholder, useMenuPart } from '@platform/ui/Menu';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';import { RotateCcwIcon } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { flushGenerateDrafts } from './generateDraftRegistry';+import type { GenerateResetSelection } from './GenerateResetMenuItems';+import { GeneratePresetsPopover } from './GeneratePresetsPopover';-import { offerGenerateUndo } from './generateUndo';import { useGenerateValues, useGenerationUi } from './GenerationUiContext';-import {- getModelDefaultsPatch,- getModelDefaultSettings,- settingsMatchModelDefaults,-} from './shared/modelDefaultSettings';+import { GenerationSectionJumpMenu } from './shared/GenerationSectionJumpMenu';++const RESET_MENU_POSITIONING = { placement: 'bottom-end' } as const;-export const GenerateHeaderActions = () => {+// The items' plan and wording load on demand, off the editor's startup; pointing at or focusing the button warms them.+const resetMenuItems = createMenuPartLoader(() =>+ import('./GenerateResetMenuItems').then((module) => module.GenerateResetMenuItems)+);+// Also on open: assistive technology can press the button without pointing at or focusing it first.+const onResetMenuOpenChange = ({ open }: { open: boolean }) => {+ if (open) {+ resetMenuItems.load();+ }+};++export const GenerateHeaderActions = ({ instance }: { instance?: { id: string } }) => {const { t } = useTranslation();const ui = useGenerationUi();+ const resetMenuIds = useTooltipTriggerIds();+ const items = useMenuPart(resetMenuItems);const models = ui.models.catalog;- const projectId = ui.project.activeProjectId;const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);- const vaeModels = useMemo(- () => models.filter((model): model is ModelConfig & VaeModelConfig => model.type === 'vae'),- [models]- );- const resolveDefaults = (values: Record<string, unknown>) => {+ const resolve = (values: Record<string, unknown>): GenerateResetSelection | null => {const settings = normalizeGenerateSettings(values);const selectedModel = settings && supportedModels.find((model) => model.key === settings.modelKey);return settings && selectedModel ? { selectedModel, settings } : null;};- // Select only what the button shows, so ordinary edits do not re-render the header.- const { hasSelectedModel, isAtModelDefaults } = useGenerateValues((values) => {- const resolved = resolveDefaults(values);-- return {- hasSelectedModel: resolved !== null,- isAtModelDefaults:- resolved !== null &&- settingsMatchModelDefaults(- resolved.settings,- getModelDefaultSettings(resolved.settings, resolved.selectedModel, vaeModels)- ),- };- });-- const resetToModelDefaults = () => {- // Flush before reading so reset preserves pending prompt edits.- flushGenerateDrafts();- const resolved = resolveDefaults(ui.generateValues.getSnapshot());-- if (!resolved) {- return;- }-- const patch = getModelDefaultsPatch(resolved.settings, resolved.selectedModel, vaeModels);-- ui.settings.patchGenerateSettings(patch, projectId);- offerGenerateUndo({- after: { ...resolved.settings, ...patch },- before: resolved.settings,- projectId,- slot: 'settings',- t,- title: t('widgets.generate.resetToModelDefaultsDone', { name: resolved.selectedModel.name }),- ui,- });- };+ // The button needs only whether a model is selected; the menu's items read the rest while it shows.+ const hasSelectedModel = useGenerateValues((values) => resolve(values) !== null);- const resetLabel = t('widgets.generate.resetAllToModelDefaults');+ const label = t('widgets.generate.resetSettings');return (<>+ <GenerationSectionJumpMenu panelId={instance?.id} /><GeneratePresetsPopover />- <Tooltip content={resetLabel}>- <IconButton- aria-label={resetLabel}- color="fg.muted"- disabled={!hasSelectedModel || isAtModelDefaults}- size="sm"- variant="ghost"- onClick={resetToModelDefaults}- >- <Icon as={RotateCcwIcon} boxSize="3.5" />- </IconButton>- </Tooltip>+ <Menu.Root+ ids={resetMenuIds}+ lazyMount+ positioning={RESET_MENU_POSITIONING}+ unmountOnExit+ onOpenChange={onResetMenuOpenChange}+ >+ <Menu.Trigger asChild>+ <Tooltip content={label} ids={resetMenuIds}>+ <IconButton+ aria-label={label}+ color="fg.muted"+ disabled={!hasSelectedModel}+ size="sm"+ variant="ghost"+ // Capture: the Tooltip hands the menu trigger's `onFocus` to the button over its own.+ onFocusCapture={resetMenuItems.load}+ onPointerEnter={resetMenuItems.load}+ >+ <Icon as={RotateCcwIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent aria-busy={items.status === 'loading'} maxW="20rem">+ {items.status === 'loaded' ? (+ <items.part resolve={resolve} />+ ) : (+ <MenuPartPlaceholder status={items.status} />+ )}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root></>);};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateProviderOptionsSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateProviderOptionsSection.browser.test.tsxindex f03e230731..54dd0006f9 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateProviderOptionsSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateProviderOptionsSection.browser.test.tsx@@ -10,14 +10,14 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';-import { userEvent } from 'vitest/browser';+import { page, userEvent } from 'vitest/browser';import { GenerateProviderOptionsSection } from './GenerateProviderOptionsSection';vi.mock('./GenerationUiContext', () => ({useGenerationUi: () => ({project: { invocationSourceId: 'generate' },- sectionPreferences: { sectionsOpen: { providerOptions: true }, setSectionOpen: vi.fn() },+ sectionPreferences: { sectionsOpen: { providerOptions: true }, setSectionsOpen: vi.fn() },}),}));@@ -196,4 +196,29 @@ describe('GenerateProviderOptionsSection', () => {expect(onCommit).toHaveBeenCalledWith({ seedreamOptimizePrompt: true });expect(onCommit).not.toHaveBeenCalledWith({ seedreamWatermark: false });});++ it('marks its title while an option is overridden, and resets them all to the provider defaults from its menu', async () => {+ const onCommit = await render(external('openai', { modes: ['txt2img', 'img2img'] }), {+ openaiInputFidelity: 'high',+ openaiQuality: 'high',+ });+ const title = () => host!.querySelector<HTMLElement>('.generate-section > [data-part="trigger"]')!;++ expect(title().querySelector('[data-section-changed]')).not.toBeNull();++ await act(() => {+ title().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));+ });+ await act(() =>+ userEvent.click(page.getByRole('menuitem', { name: 'widgets.generate.sectionMenu.resetProviderOptions' }))+ );++ expect(onCommit).toHaveBeenLastCalledWith({+ openaiBackground: 'auto',+ openaiInputFidelity: null,+ openaiQuality: 'auto',+ });+ expect(title().querySelector('[data-section-changed]')).toBeNull();+ expect(host?.textContent).not.toContain('override');+ });});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateProviderOptionsSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateProviderOptionsSection.tsxindex 3cad89c592..bc53b393fa 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateProviderOptionsSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateProviderOptionsSection.tsx@@ -1,7 +1,8 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';-import { Badge, createListCollection, Stack } from '@chakra-ui/react';+import { createListCollection, Stack } from '@chakra-ui/react';+import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';import {DEFAULT_GEMINI_TEMPERATURE,GEMINI_TEMPERATURE_MAX,@@ -95,33 +96,27 @@ export const GenerateProviderOptionsSection = ({return null;}- // Count decisions away from the provider defaults, as the Advanced section does.- const overrideCount = optionKeys.filter((key) => {- switch (key) {- case 'openaiQuality':- case 'openaiBackground':- return settings[key] !== 'auto';- case 'seedreamWatermark':- case 'seedreamOptimizePrompt':- return settings[key];- default:- return settings[key] !== null;- }- }).length;+ // Count decisions away from the provider defaults (what the options hold while the provider decides), as the+ // Advanced section does.+ const defaults = getDefaultGenerateSettings(selectedModel);+ const overrideCount = optionKeys.filter((key) => settings[key] !== defaults[key]).length;+ const resetToProviderDefaults = () => onCommit(Object.fromEntries(optionKeys.map((key) => [key, defaults[key]])));return (<GenerateCollapsibleSectionlabel={t('widgets.generate.providerOptions.title')}defaultOpen- badges={- overrideCount > 0 ? <Badge>{t('widgets.generate.overridesCount', { count: overrideCount })}</Badge> : null- }+ isChanged={overrideCount > 0}sectionId="providerOptions"+ summary={overrideCount > 0 ? [t('widgets.generate.overridesCount', { count: overrideCount })] : undefined}+ resetLabel={t('widgets.generate.sectionMenu.resetProviderOptions')}+ onReset={resetToProviderDefaults}>- <Stack gap="2" p="2">+ <Stack gap="2.5">{optionKeys.includes('openaiQuality') ? (<Fieldlabel={t('widgets.generate.providerOptions.openaiQuality')}+ labelPlacement="inside"helpText={t('widgets.generate.providerOptions.openaiQualityHelp')}><Select@@ -139,6 +134,7 @@ export const GenerateProviderOptionsSection = ({{optionKeys.includes('openaiBackground') ? (<Fieldlabel={t('widgets.generate.providerOptions.openaiBackground')}+ labelPlacement="inside"helpText={t('widgets.generate.providerOptions.openaiBackgroundHelp')}><Select@@ -156,6 +152,7 @@ export const GenerateProviderOptionsSection = ({{optionKeys.includes('openaiInputFidelity') ? (<Fieldlabel={t('widgets.generate.providerOptions.openaiInputFidelity')}+ labelPlacement="inside"helpText={t('widgets.generate.providerOptions.openaiInputFidelityHelp')}><Select@@ -204,6 +201,7 @@ export const GenerateProviderOptionsSection = ({{optionKeys.includes('geminiThinkingLevel') ? (<Fieldlabel={t('widgets.generate.providerOptions.geminiThinkingLevel')}+ labelPlacement="inside"helpText={t('widgets.generate.providerOptions.geminiThinkingLevelHelp')}><Selectdiff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRefinerSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRefinerSection.browser.test.tsxindex 782d6fe09c..540bb19b85 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRefinerSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRefinerSection.browser.test.tsx@@ -33,7 +33,7 @@ vi.mock('./GenerationUiContext', () => ({</div>),useGenerationUi: () => ({- sectionPreferences: { sectionsOpen: { refiner: true }, setSectionOpen: vi.fn() },+ sectionPreferences: { sectionsOpen: { refiner: true }, setSectionsOpen: vi.fn() },}),}));diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRefinerSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRefinerSection.tsxindex 5ba49a0319..5f69dd137e 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRefinerSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRefinerSection.tsx@@ -1,8 +1,8 @@-/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop */+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop */import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';import type { GenerateModelConfig, GenerateSettings } from '@features/generation/core/types';-import { Badge, Stack } from '@chakra-ui/react';+import { Stack } from '@chakra-ui/react';import { getGenerationUiPolicy, getSchedulerOptions } from '@features/generation/core/baseGenerationPolicies';import {DEFAULT_REFINER_CFG_SCALE,@@ -141,10 +141,10 @@ export const GenerateRefinerSection = ({<GenerateCollapsibleSectionlabel={t('widgets.generate.refiner')}defaultOpen={false}- badges={refiner ? <Badge>{isActive ? refiner.name : t('commandPalette.settings.off')}</Badge> : null}+ summary={refiner ? [isActive ? refiner.name : t('commandPalette.settings.off')] : undefined}sectionId="refiner">- <Stack gap="2" p="2">+ <Stack gap="2.5"><GenerateIssueNotes section="refiner" /><Field hint="refinerModel" label={t('widgets.generate.refinerModel')}>{/* The picker owns the loading and empty states, so no refiner installed reads as one message. */}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsxindex 47a3788b77..2339e6ae82 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.browser.test.tsx@@ -13,7 +13,7 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';-import { userEvent } from 'vitest/browser';+import { page, userEvent } from 'vitest/browser';import type { CanvasDenoisingStrengthProps } from './GenerationUiContext';@@ -32,11 +32,12 @@ vi.mock('./GenerationUiContext', () => ({// Stands in for the canvas's strength slot, which lays out the section around its badge and field.CanvasDenoisingStrength: ({ children }: CanvasDenoisingStrengthProps) =>children({- badges: <span data-testid="strength-badge">75%</span>,+ summary: <span data-testid="strength-badge">75%</span>,field: <div data-testid="strength-field" />,}),+ models: { getBaseLabel: (base: string) => ({ 'sd-1': 'SD 1.x', sdxl: 'SDXL' })[base] ?? base },project: { invocationSourceId: harness.invocationSourceId },- sectionPreferences: { sectionsOpen: { render: true }, setSectionOpen: vi.fn() },+ sectionPreferences: { sectionsOpen: { render: true }, setSectionsOpen: vi.fn() },}),}));@@ -103,6 +104,14 @@ void i18n.use(initReactI18next).init({render: 'Render',resetToDefault: 'Reset to default',scheduler: 'Scheduler',+ sectionMenu: {+ resetStepsAndGuidance: 'Reset steps and {{guidance}} to model defaults',+ resetStepsAndGuidanceBase: 'Reset steps and {{guidance}} to {{base}} defaults',+ resetStepsGuidanceAndScheduler: 'Reset steps, {{guidance}} and scheduler to model defaults',+ resetStepsGuidanceAndSchedulerBase: 'Reset steps, {{guidance}} and scheduler to {{base}} defaults',+ resetStepsGuidanceAndSchedulerMixed:+ 'Reset steps, {{guidance}} and scheduler to model and {{base}} defaults',+ },seedSummary: '{{mode}} · {{seed}}',steps: 'Steps',useSeed: 'Use seed {{seed}}',@@ -747,3 +756,85 @@ describe('GenerateRenderSection model-family tuning', () => {expect(onEnabledCommit).toHaveBeenCalledWith({ zImageSeedVarianceRandomizePercent: 51 });});});++describe('GenerateRenderSection title defaults', () => {+ // Scheduler visibility comes from the architecture capabilities.+ seedArchitectureCapabilities();++ const title = () => host!.querySelector<HTMLElement>('.generate-section > [data-part="trigger"]')!;+ const isMarked = () => title().querySelector('[data-section-changed]') !== null;+ const otherScheduler = (model: GenerateModelConfig) =>+ getDefaultGenerateSettings(model).scheduler === 'ddim' ? 'euler' : 'ddim';+ const openMenu = () =>+ act(() => {+ title().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));+ });++ it('marks steps, CFG and scheduler off the model defaults, and resets those three only', async () => {+ const defaults = getDefaultGenerateSettings(sd1Model);+ const onCommit = await render(sd1Model, { scheduler: otherScheduler(sd1Model), seed: 42, seedMode: 'fixed' }, true);++ expect(host?.textContent).toContain('Scheduler');+ expect(isMarked()).toBe(true);+ await openMenu();+ await act(() =>+ userEvent.click(page.getByRole('menuitem', { name: 'Reset steps, CFG and scheduler to SD 1.x defaults' }))+ );++ expect(onCommit).toHaveBeenLastCalledWith({+ cfgScale: defaults.cfgScale,+ scheduler: defaults.scheduler,+ steps: defaults.steps,+ });+ expect(draftStore?.getSnapshot()).toMatchObject({ seed: 42, seedMode: 'fixed' });+ expect(isMarked()).toBe(false);+ });++ it('leaves a hidden scheduler out of the mark and the reset', async () => {+ const defaults = getDefaultGenerateSettings(qwenImageModel);+ const onCommit = await render(qwenImageModel, { scheduler: otherScheduler(qwenImageModel) }, true);++ expect(isMarked()).toBe(false);++ await settle(() => draftStore?.patchSnapshot({ steps: defaults.steps + 4 }));+ expect(isMarked()).toBe(true);+ await openMenu();+ await act(() =>+ userEvent.click(page.getByRole('menuitem', { name: 'Reset steps and CFG to qwen-image defaults' }))+ );++ expect(onCommit).toHaveBeenLastCalledWith({ cfgScale: defaults.cfgScale, steps: defaults.steps });+ });++ it('names the guidance field as the model labels it', async () => {+ const defaults = getDefaultGenerateSettings(fluxDevModel);+ const onCommit = await render(fluxDevModel, { steps: defaults.steps + 4 }, true);++ await openMenu();+ const reset = page.getByRole('menuitem', { name: /^Reset steps.* to flux defaults$/ });++ expect(reset.element().textContent).toContain('Guidance');+ expect(reset.element().textContent).not.toContain('CFG');+ await act(() => userEvent.click(reset));++ expect(onCommit).toHaveBeenLastCalledWith(expect.objectContaining({ steps: defaults.steps }));+ });++ it.each([+ [{ steps: 20 }, 'Reset steps, CFG and scheduler to model and SD 1.x defaults'],+ [{ cfg_scale: 5, scheduler: 'ddim', steps: 20 }, 'Reset steps, CFG and scheduler to model defaults'],+ ])('names where the reset takes its values from when the model sets %o', async (defaultSettings, label) => {+ const model: MainModelConfig = { ...sd1Model, default_settings: defaultSettings };+ const onCommit = await render(model, { steps: 33 }, true);++ await openMenu();+ await act(() => userEvent.click(page.getByRole('menuitem', { name: label })));++ // The values are what they were: the model's where it sets them, the base's otherwise.+ expect(onCommit).toHaveBeenLastCalledWith({+ cfgScale: getDefaultGenerateSettings(model).cfgScale,+ scheduler: getDefaultGenerateSettings(model).scheduler,+ steps: 20,+ });+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsxindex 993d5e4fb5..518d11aaa9 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateRenderSection.tsx@@ -7,7 +7,7 @@ import type {} from '@features/generation/core/types';import type { ReactNode } from 'react';-import { Badge, Box, createListCollection, HStack, Image, Input, Separator, Stack, Text } from '@chakra-ui/react';+import { Box, createListCollection, HStack, Image, Input, Stack, Text } from '@chakra-ui/react';import {getDefaultGenerateSettings,getGenerationUiPolicy,@@ -64,6 +64,7 @@ import { GenerateCollapsibleSection } from './shared/GenerateCollapsibleSection'import { GenerateFieldContextMenu } from './shared/GenerateFieldContextMenu';import { GenerateIssueNotes } from './shared/GenerateIssues';import { GenerateToggleSwitch } from './shared/GenerateToggleSwitch';+import { type DefaultSource, getDefaultSource, getFieldResetLabel } from './shared/modelDefaultSettings';import { SeedField as SharedSeedField } from './shared/SeedField';import { useDynamicPrompts } from './useDynamicPrompts';@@ -152,7 +153,7 @@ const Ideogram4SamplingFields = ({ onCommit, settings }: RenderFieldsProps) => {return (<>- <Field label={t('widgets.generate.ideogram4SamplerPreset')}>+ <Field label={t('widgets.generate.ideogram4SamplerPreset')} labelPlacement="inside"><Selectaria-label={t('widgets.generate.ideogram4SamplerPreset')}collection={IDEOGRAM4_PRESET_COLLECTION}@@ -285,7 +286,8 @@ const MossImageSkipLayersField = ({<GenerateFieldContextMenucopyValue={() => formatSkipLayers(stored)}fieldLabel={label}- isAtDefault={isSameSkipLayers(stored, DEFAULT_MOSS_IMAGE_UNCOND_SKIP_LAYERS)}+ // Disabled while CFG is off, when the layers are not used: no change to undo then.+ isAtDefault={isCfgOff || isSameSkipLayers(stored, DEFAULT_MOSS_IMAGE_UNCOND_SKIP_LAYERS)}onReset={() => {setDraft(null);onCommitImmediate({ mossImageUncondSkipLayers: [...DEFAULT_MOSS_IMAGE_UNCOND_SKIP_LAYERS] });@@ -472,7 +474,7 @@ const FluxDypeFields = ({ onCommit, settings }: RenderFieldsProps) => {return (<>- <Field hint="dypePreset" label={t('widgets.generate.dypePreset')}>+ <Field hint="dypePreset" label={t('widgets.generate.dypePreset')} labelPlacement="inside"><Selectaria-label={t('widgets.generate.dypePreset')}collection={presetCollection}@@ -609,6 +611,20 @@ const SeedField = ({ onCommit, settings }: RenderFieldsProps) => {);};+/** The section reset's wording by where its values come from. */+const RENDER_RESET_LABEL_KEYS = {+ withScheduler: {+ base: 'widgets.generate.sectionMenu.resetStepsGuidanceAndSchedulerBase',+ mixed: 'widgets.generate.sectionMenu.resetStepsGuidanceAndSchedulerMixed',+ model: 'widgets.generate.sectionMenu.resetStepsGuidanceAndScheduler',+ },+ withoutScheduler: {+ base: 'widgets.generate.sectionMenu.resetStepsAndGuidanceBase',+ mixed: 'widgets.generate.sectionMenu.resetStepsAndGuidanceMixed',+ model: 'widgets.generate.sectionMenu.resetStepsAndGuidance',+ },+} as const satisfies Record<string, Record<DefaultSource, string>>;+export const GenerateRenderSection = ({draft,onCommit,@@ -616,7 +632,7 @@ export const GenerateRenderSection = ({selectedModel,}: GenerateRenderSectionProps) => {const { t } = useTranslation();- const { CanvasDenoisingStrength: CanvasDenoisingStrengthSlot, project } = useGenerationUi();+ const { CanvasDenoisingStrength: CanvasDenoisingStrengthSlot, models, project } = useGenerationUi();const settings = useExternalStoreSelector(draft.subscribe, draft.getSnapshot, selectRenderSettings);const modelDefaults = selectedModel ? getDefaultGenerateSettings(selectedModel) : null;const uiPolicy = getGenerationUiPolicy(selectedModel);@@ -636,18 +652,44 @@ export const GenerateRenderSection = ({onCommit({ [key]: value });};- const seedBadge = uiPolicy.seedVisible ? (- <Badge>- {settings.seedMode === 'random'- ? t('common.seedMode.random')- : settings.seedMode === 'fixed'- ? settings.seed- : t('widgets.generate.seedSummary', {- mode: t(`common.seedMode.${settings.seedMode}`),- seed: settings.seed,- })}- </Badge>- ) : null;+ const seedSummary = uiPolicy.seedVisible+ ? settings.seedMode === 'random'+ ? t('common.seedMode.random')+ : settings.seedMode === 'fixed'+ ? settings.seed+ : t('widgets.generate.seedSummary', {+ mode: t(`common.seedMode.${settings.seedMode}`),+ seed: settings.seed,+ })+ : null;++ // The model-governed values this section shows, as the header's reset-all restores them.+ const modelDefaultsPatch: Partial<GenerateSettings> | null = modelDefaults+ ? {+ cfgScale: modelDefaults.cfgScale,+ steps: modelDefaults.steps,+ ...(uiPolicy.schedulerVisible ? { scheduler: modelDefaults.scheduler } : {}),+ }+ : null;+ const isAtModelDefaults =+ modelDefaultsPatch !== null &&+ Object.entries(modelDefaultsPatch).every(([key, value]) => settings[key as keyof typeof settings] === value);+ const resetLabel = (setting: 'scheduler' | 'steps' | 'cfgScale') =>+ getFieldResetLabel(setting, selectedModel, models.getBaseLabel, t);+ const sectionSettings: ('scheduler' | 'steps' | 'cfgScale')[] = uiPolicy.schedulerVisible+ ? ['steps', 'cfgScale', 'scheduler']+ : ['steps', 'cfgScale'];+ const sectionSource = selectedModel ? getDefaultSource(selectedModel, sectionSettings) : 'base';+ const baseLabel = selectedModel?.type === 'main' ? models.getBaseLabel(selectedModel.base) : null;+ // An external model's fallbacks belong to no base, so they are plain defaults.+ const sectionResetLabel =+ sectionSource !== 'model' && baseLabel === null+ ? t('widgets.generate.sectionMenu.reset')+ : t(RENDER_RESET_LABEL_KEYS[uiPolicy.schedulerVisible ? 'withScheduler' : 'withoutScheduler'][sectionSource], {+ base: baseLabel,+ // Named as the field is: CFG, or Guidance on distilled-guidance models.+ guidance: uiPolicy.guidanceLabel,+ });const renderFields = (strengthField: ReactNode) => (<>@@ -655,6 +697,7 @@ export const GenerateRenderSection = ({fieldLabel={t('widgets.generate.steps')}copyValue={() => String(settings.steps)}isAtDefault={modelDefaults !== null && settings.steps === modelDefaults.steps}+ resetLabel={resetLabel('steps')}onReset={modelDefaults ? () => onCommit({ steps: modelDefaults.steps }) : undefined}><ScrubberField@@ -674,6 +717,7 @@ export const GenerateRenderSection = ({fieldLabel={uiPolicy.guidanceLabel}copyValue={() => String(settings.cfgScale)}isAtDefault={modelDefaults !== null && settings.cfgScale === modelDefaults.cfgScale}+ resetLabel={resetLabel('cfgScale')}onReset={modelDefaults ? () => onCommit({ cfgScale: modelDefaults.cfgScale }) : undefined}><ScrubberField@@ -697,14 +741,11 @@ export const GenerateRenderSection = ({<MossImageSkipLayersField settings={settings} onCommitImmediate={onCommitImmediate} />) : null}{familyBase === 'krea-2' ? (- <>- <Separator borderColor="border.subtle" />- <GenerateConditioningRebalanceField- settings={settings}- onCommit={onCommit}- onCommitImmediate={onCommitImmediate}- />- </>+ <GenerateConditioningRebalanceField+ settings={settings}+ onCommit={onCommit}+ onCommitImmediate={onCommitImmediate}+ />) : null}{familyBase === 'wan' ? <WanLowNoiseGuidanceField settings={settings} onCommit={onCommit} /> : null}{familyBase === 'z-image' ? (@@ -728,9 +769,10 @@ export const GenerateRenderSection = ({fieldLabel={t('widgets.generate.scheduler')}copyValue={() => settings.scheduler}isAtDefault={modelDefaults !== null && settings.scheduler === modelDefaults.scheduler}+ resetLabel={resetLabel('scheduler')}onReset={modelDefaults ? () => onCommit({ scheduler: modelDefaults.scheduler }) : undefined}>- <Field hint="scheduler" label={t('widgets.generate.scheduler')}>+ <Field hint="scheduler" label={t('widgets.generate.scheduler')} labelPlacement="inside"><Comboboxaria-label={t('widgets.generate.scheduler')}options={getSchedulerOptions(selectedModel, settings.scheduler)}@@ -741,20 +783,9 @@ export const GenerateRenderSection = ({</GenerateFieldContextMenu>) : null}{familyBase === 'ideogram-4' ? <Ideogram4SamplingFields settings={settings} onCommit={onCommit} /> : null}- <Separator borderColor="border.subtle" />{uiPolicy.seedVisible ? <SeedField settings={settings} onCommit={onCommit} /> : null}- {familyBase === 'krea-2' ? (- <>- <Separator borderColor="border.subtle" />- <Krea2SeedVarianceFields settings={settings} onCommit={onCommit} />- </>- ) : null}- {familyBase === 'z-image' ? (- <>- <Separator borderColor="border.subtle" />- <ZImageSeedVarianceFields settings={settings} onCommit={onCommit} />- </>- ) : null}+ {familyBase === 'krea-2' ? <Krea2SeedVarianceFields settings={settings} onCommit={onCommit} /> : null}+ {familyBase === 'z-image' ? <ZImageSeedVarianceFields settings={settings} onCommit={onCommit} /> : null}</>);@@ -762,18 +793,14 @@ export const GenerateRenderSection = ({<GenerateCollapsibleSectionlabel={t('widgets.generate.render')}defaultOpen={false}- badges={- <>- <Badge>- {settings.steps} · {uiPolicy.guidanceLabel} {settings.cfgScale}- </Badge>- {canvas?.badges}- {seedBadge}- </>- }+ isChanged={modelDefaultsPatch !== null && !isAtModelDefaults}sectionId="render"+ summary={[settings.steps, `${uiPolicy.guidanceLabel} ${settings.cfgScale}`, canvas?.summary, seedSummary]}+ onReset={modelDefaultsPatch ? () => onCommit(modelDefaultsPatch) : undefined}+ // The seed, strength and family fields keep their values: only these have model defaults to return to.+ resetLabel={sectionResetLabel}>- <Stack gap="2" p="2">+ <Stack gap="2.5"><GenerateIssueNotes section="render" />{renderFields(canvas?.field ?? null)}</Stack>diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateResetMenuItems.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateResetMenuItems.tsxnew file mode 100644index 0000000000..34c0705e8e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateResetMenuItems.tsx@@ -0,0 +1,186 @@+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';+import type { GenerateModelConfig, GenerateSettings, VaeModelConfig } from '@features/generation/core/types';++import { MenuActionItem } from '@platform/ui/Menu';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { flushGenerateDrafts } from './generateDraftRegistry';+import { offerGenerateUndo } from './generateUndo';+import { useGenerateValues, useGenerationUi } from './GenerationUiContext';+import {+ describeChanges,+ describeUnset,+ getApplyModelDefaultsPlan,+ getChangedSettings,+ getModelDefaultsPatch,+} from './shared/modelDefaultsReset';++export interface GenerateResetSelection {+ selectedModel: GenerateModelConfig;+ settings: GenerateSettings;+}++interface MenuItemState {+ hint: string | undefined;+ unavailableReason: string | undefined;+}++/**+ * The reset menu's items. Mounted only while the menu shows, until its exit animation ends, so edits re-render them+ * only meanwhile.+ */+export const GenerateResetMenuItems = ({+ resolve,+}: {+ resolve: (values: Record<string, unknown>) => GenerateResetSelection | null;+}) => {+ const { i18n, t } = useTranslation();+ const locale = i18n.resolvedLanguage;+ const ui = useGenerationUi();+ const models = ui.models.catalog;+ const projectId = ui.project.activeProjectId;+ const vaeModels = useMemo(+ () => models.filter((model): model is ModelConfig & VaeModelConfig => model.type === 'vae'),+ [models]+ );+ const items = useGenerateValues(+ (values): { apply: MenuItemState; reset: MenuItemState } | null => {+ const resolved = resolve(values);++ if (!resolved) {+ return null;+ }++ const { selectedModel, settings } = resolved;+ const name = selectedModel.name;+ const plan = getApplyModelDefaultsPlan(settings, selectedModel, vaeModels);+ const applyChanges = describeChanges(+ plan.changed,+ settings,+ { ...settings, ...plan.patch },+ selectedModel,+ t,+ locale+ );+ // A model that sets nothing leaves everything as it is; its reason says so without listing it all.+ const setsNothing = plan.defined.length === 0 && !plan.isVaeMissing;+ const unset = setsNothing ? null : describeUnset(plan.unset, selectedModel, t, locale);+ // A VAE the model sets but that cannot apply is no unset setting: it gets its own sentence.+ const withVaeNote = (hint: string | undefined) =>+ !plan.isVaeMissing+ ? hint+ : hint+ ? t('widgets.generate.modelDefaultsWithVaeMissing', { hint })+ : t('widgets.generate.modelDefaultsVaeMissing');+ const resetAfter = { ...settings, ...getModelDefaultsPatch(settings, selectedModel, vaeModels) };+ const resetChanged = getChangedSettings(settings, resetAfter, selectedModel);++ const applyUnavailableReason = setsNothing+ ? t('widgets.generate.modelDefaultsNoneSet', { name })+ : plan.changed.length > 0+ ? undefined+ : !plan.isVaeMissing+ ? t('widgets.generate.modelDefaultsAlreadyApplied', { name })+ : plan.defined.length === 0+ ? t('widgets.generate.modelDefaultsOnlyVaeMissing', { name })+ : t('widgets.generate.modelDefaultsAppliedExceptVae', { name });+ const applyHint =+ applyChanges && unset+ ? t('widgets.generate.modelDefaultsApplyHint', { changes: applyChanges, settings: unset })+ : applyChanges || (unset ? t('widgets.generate.modelDefaultsUnset', { settings: unset }) : undefined);++ return {+ apply: {+ // An unavailable item's reason already tells a missing VAE; the hint tells it only once.+ hint: applyUnavailableReason ? applyHint : withVaeNote(applyHint),+ unavailableReason: applyUnavailableReason,+ },+ reset: {+ hint:+ resetChanged.length > 0+ ? withVaeNote(describeChanges(resetChanged, settings, resetAfter, selectedModel, t, locale))+ : t('widgets.generate.resetEverythingToDefaultsHint'),+ unavailableReason: resetChanged.length === 0 ? t('widgets.generate.resetEverythingAlreadyDone') : undefined,+ },+ };+ },+ (a, b) =>+ a === b ||+ (a !== null &&+ b !== null &&+ a.apply.hint === b.apply.hint &&+ a.apply.unavailableReason === b.apply.unavailableReason &&+ a.reset.hint === b.reset.hint &&+ a.reset.unavailableReason === b.reset.unavailableReason)+ );++ /** One write and one Undo for whatever the patch changes, its toast naming each change. */+ const commitReset = (+ getPatch: (settings: GenerateSettings, model: GenerateModelConfig) => Partial<GenerateSettings>,+ title: (model: GenerateModelConfig) => string+ ) => {+ // Flush before reading so the reset preserves pending prompt edits.+ flushGenerateDrafts();+ const resolved = resolve(ui.generateValues.getSnapshot());++ if (!resolved) {+ return;+ }++ const { selectedModel, settings } = resolved;+ const patch = getPatch(settings, selectedModel);+ const after = { ...settings, ...patch };+ const message = describeChanges(+ getChangedSettings(settings, after, selectedModel),+ settings,+ after,+ selectedModel,+ t,+ locale+ );++ ui.settings.patchGenerateSettings(patch, projectId);+ offerGenerateUndo({+ after,+ before: settings,+ ...(message ? { message } : {}),+ projectId,+ slot: 'settings',+ t,+ title: title(selectedModel),+ ui,+ });+ };++ const applyModelDefaults = () =>+ commitReset(+ (settings, model) => getApplyModelDefaultsPlan(settings, model, vaeModels).patch,+ (model) => t('widgets.generate.applyModelDefaultsDone', { name: model.name })+ );+ const resetEverything = () =>+ commitReset(+ (settings, model) => getModelDefaultsPatch(settings, model, vaeModels),+ () => t('widgets.generate.resetEverythingToDefaultsDone')+ );++ return (+ <>+ <MenuActionItem+ hint={items?.apply.hint}+ label={t('widgets.generate.applyModelDefaults')}+ unavailableReason={items?.apply.unavailableReason}+ value="apply-model-defaults"+ onSelect={applyModelDefaults}+ />+ <MenuActionItem+ hint={items?.reset.hint}+ label={t('widgets.generate.resetEverythingToDefaults')}+ unavailableReason={items?.reset.unavailableReason}+ value="reset-everything"+ onSelect={resetEverything}+ />+ </>+ );+};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsxindex 30758bc349..91fc6c3832 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.browser.test.tsx@@ -212,7 +212,7 @@ const createStableGroups = () => ({},queueInsights: { getSnapshot: () => NO_QUEUE_INSIGHTS, subscribe: () => noop },rebalancePresets: { presets: [], remove: noop, rename: noop, save: noop },- sectionPreferences: { sectionsOpen: ALL_SECTIONS_OPEN, setSectionOpen: noop },+ sectionPreferences: { sectionsOpen: ALL_SECTIONS_OPEN, setSectionsOpen: noop },settings: {readGenerateValues: (projectId: string) => projectValues.get(projectId)?.getSnapshot() ?? null,patchGenerateSettings: (patch: Record<string, unknown>, projectId?: string) => {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsxindex 00db3ed28b..9c89634086 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateSettingsForm.tsx@@ -2,7 +2,7 @@ import type { GenerationModelCatalogItem as ModelConfig } from '@features/generaimport type { GenerationIssue, GenerationIssueFix } from '@features/generation/core/generationIssues';import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';-import { Separator, Stack } from '@chakra-ui/react';+import { Stack } from '@chakra-ui/react';import { getGenerateInvocationIssues } from '@features/generation/core/baseGenerationPolicies';import { getGenerationIssueFixPatch } from '@features/generation/core/generationIssues';import { createExternalStoreCore } from '@platform/state/externalStoreCore';@@ -288,27 +288,27 @@ export const GenerateSettingsForm = ({return (<GenerateIssuesProvider applyFix={applyIssueFix} issues={issues}>- <Stack gap={1} p={1}>- <GenerateModelCard- draft={draft}- isLoadingModels={isLoadingModels}- loadError={loadError}- models={models}- selectedModel={selectedModel}- supportedModels={supportedModels}- onCommitSettings={commitSettingsImmediately}- />-- {/* The same hairline the collapsible sections draw between one another. */}- <Separator />-- <GeneratePromptFields- draft={draft}- projectId={projectId}- selectedModel={selectedModel}- onCommit={commitPromptDraftPatch}- onCommitImmediate={commitPatchImmediately}- />+ <Stack gap={0}>+ {/* The prompt fields carry their own space below, which matches the side inset here. */}+ <Stack gap={1} px={2} pt={2}>+ <GenerateModelCard+ draft={draft}+ isLoadingModels={isLoadingModels}+ loadError={loadError}+ models={models}+ selectedModel={selectedModel}+ supportedModels={supportedModels}+ onCommitSettings={commitSettingsImmediately}+ />++ <GeneratePromptFields+ draft={draft}+ projectId={projectId}+ selectedModel={selectedModel}+ onCommit={commitPromptDraftPatch}+ onCommitImmediate={commitPatchImmediately}+ />+ </Stack><GenerateDimensionFieldsdraft={draft}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsxindex 6469da4afd..5a796a0365 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateWidgetView.tsx@@ -15,8 +15,10 @@ import { getGenerateFormCommitPatch } from './generateFormViewModel';import { GenerateSettingsForm } from './GenerateSettingsForm';import { useGenerateValues, useGenerationUi } from './GenerationUiContext';import { CapabilitiesGate } from './shared/CapabilitiesGate';+import { GenerationSectionPanel } from './shared/sectionPanel';-export const GenerateWidgetView = () => {+/** `instance` ties the form's sections to the header's jump menu; a view rendered outside a widget frame has none. */+export const GenerateWidgetView = ({ instance }: { instance?: { id: string } }) => {const { t } = useTranslation();const ui = useGenerationUi();const capabilitiesStatus = useArchitectureCapabilitiesSelector((snapshot) => snapshot.status);@@ -71,18 +73,20 @@ export const GenerateWidgetView = () => {// Gate the form so edits cannot persist fallback architecture defaults.return (<CapabilitiesGate isReady={capabilitiesStatus === 'loaded'} labels={gateLabels}>- <GenerateSettingsForm- isLoadingModels={status === 'idle' || status === 'loading'}- loadError={error}- loraModels={loraModels}- models={models}- projectId={projectId}- selectedModel={selectedModel}- settings={settings}- supportedModels={supportedModels}- onCommitSettings={commitSettings}- onPatchSettings={ui.settings.patchGenerateSettings}- />+ <GenerationSectionPanel id={instance?.id}>+ <GenerateSettingsForm+ isLoadingModels={status === 'idle' || status === 'loading'}+ loadError={error}+ loraModels={loraModels}+ models={models}+ projectId={projectId}+ selectedModel={selectedModel}+ settings={settings}+ supportedModels={supportedModels}+ onCommitSettings={commitSettings}+ onPatchSettings={ui.settings.patchGenerateSettings}+ />+ </GenerationSectionPanel></CapabilitiesGate>);};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsxindex be054df075..d0eea8297d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerationUiContext.tsx@@ -69,8 +69,8 @@ export interface CanvasRenderSizeProps {/** What the canvas adds to the Render section. */export interface CanvasDenoisingStrength {- /** The strength summary, shown with the section's header badges. */- badges: ReactNode;+ /** The strength summary, shown in the section's title row while it is folded. */+ summary: ReactNode;/** The strength control, laid out under guidance. */field: ReactNode;}@@ -123,6 +123,8 @@ export interface GenerationUiAdapter {openInModelManager?: (key: string) => void;/** Apply the optional model-type filter when opening Add Models. */openManager(options?: { modelType?: string }): void;+ /** The catalog as it is now, for an Undo that runs long after the render that offered it. */+ readCatalog(): readonly GenerationModelCatalogItem[];/** Reads the catalog again, even after a read that half failed; settles when the read does. */refresh(): Promise<void>;status: 'error' | 'idle' | 'loaded' | 'loading';@@ -195,7 +197,8 @@ export interface GenerationUiAdapter {sectionPreferences: {/** Persisted per-user open/closed overrides for panel sections; absent = section default. */sectionsOpen: Readonly<Record<string, boolean>>;- setSectionOpen(sectionId: string, open: boolean): void;+ /** Records several sections' open states as one preference write (a panel-wide fold or expand). */+ setSectionsOpen(changes: Readonly<Record<string, boolean>>): void;};settings: {patchGenerateSettings(values: Partial<GenerateSettings>, projectId?: string, origin?: 'user' | 'system'): void;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/generateUndo.ts b/invokeai/frontend/webv2/src/features/generation/ui/generateUndo.tsindex 5ac9d061cb..da368af5e3 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/generateUndo.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/generateUndo.ts@@ -9,7 +9,7 @@ import { flushGenerateDrafts } from './generateDraftRegistry';/*** Generate's Undo slots, one pair per project. A newer Undo in a slot withdraws the older, since undoing an older step- * after a newer one would leave a mix of both. Whole-form changes (a model switch, a preset, Reset all) share one slot;+ * after a newer one would leave a mix of both. Whole-form changes (a model switch, a preset, Apply model defaults, Reset everything) share one slot;* prompt changes that Ctrl+Z in the prompt cannot undo (a template choice, a history entry, a rewrite) share the other.*/export const getGenerateSettingsUndoKey = (projectId: string): string => `generate-settings:${projectId}`;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsxindex eb96b6cfd1..b5a92348eb 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/DynamicPromptsButton.tsx@@ -134,7 +134,7 @@ export const DynamicPromptsButton = ({<Portal><Popover.Positioner><PopoverContent w="26rem">- <Popover.Body p="2.5">+ <Popover.Body p="1.5"><Stack gap="1.5"><SegmentTabsactiveId={tab}@@ -148,6 +148,8 @@ export const DynamicPromptsButton = ({aria-labelledby={segmentTabsTabId(tabsIdBase, tab)}gap="2.5"id={segmentTabsPanelId(tabsIdBase)}+ pb="1"+ px="1"role="tabpanel">{tab === 'preview' ? (diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsxindex 269dff1966..0e01d2d71d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptField.tsx@@ -2,16 +2,16 @@import type { GenerateLora, GenerateModelConfig } from '@features/generation/core/types';import type { ChangeEvent, KeyboardEvent } from 'react';-import { HStack, Text } from '@chakra-ui/react';+import { HStack } from '@chakra-ui/react';import { supportsPromptAttentionSyntax } from '@features/generation/core/prompt/compel';import { getPromptTemplateChunks } from '@features/generation/core/promptTemplates';import { useRegisterGenerateDraftFlusher } from '@features/generation/ui/generateDraftRegistry';import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';-import { Button, Field, IconButton, Tooltip } from '@platform/ui';-import { PlusIcon, XIcon } from 'lucide-react';+import { Field } from '@platform/ui';import { useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';+import { AddNegativePromptButton, RemoveNegativePromptButton } from './NegativePromptToggle';import { AddPromptTriggerButton, PromptTriggerPopover } from './PositivePromptActions';import { insertPromptText } from './promptFocus';import { promptHistoryNavigation } from './promptHistoryNavigation';@@ -137,17 +137,10 @@ export const NegativePromptField = ({isOpen={triggerPicker.isOpen || isViewingMerged}onOpenPromptTriggerPicker={triggerPicker.open}/>- <Tooltip content={t('widgets.generate.negativePromptHide')}>- <IconButton- aria-label={t('widgets.generate.negativePromptHide')}- color="fg.muted"- size="sm"- variant="ghost"- onClick={() => onEnabledChange(false)}- >- <XIcon />- </IconButton>- </Tooltip>+ <RemoveNegativePromptButton+ label={t('widgets.generate.negativePromptHide')}+ onClick={() => onEnabledChange(false)}+ /></HStack>),[isViewingMerged, onEnabledChange, t, triggerPicker]@@ -162,22 +155,12 @@ export const NegativePromptField = ({// Keep collapsed previews discoverable without changing persisted negativePromptEnabled.if (!isEnabled) {return (- <Button+ <AddNegativePromptButtonaria-label={t('widgets.generate.enableNegativePrompt')}- color="fg.muted"- justifyContent="flex-start"- size="sm"- variant="ghost"+ label={t('widgets.generate.negativePromptAdd')}+ preview={value}onClick={() => onEnabledChange(true)}- >- <PlusIcon />- {t('widgets.generate.negativePromptAdd')}- {value.trim() !== '' ? (- <Text as="span" color="fg.subtle" fontSize="xs" fontWeight="normal" minW="0" truncate>- {value}- </Text>- ) : null}- </Button>+ />);}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptToggle.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptToggle.tsxnew file mode 100644index 0000000000..07687a6edc--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/NegativePromptToggle.tsx@@ -0,0 +1,73 @@+import type { Ref } from 'react';++import { chakra, Text } from '@chakra-ui/react';+import { Button, IconButton } from '@platform/ui/Button';+import { PlusIcon, XIcon } from 'lucide-react';++interface AddNegativePromptButtonProps {+ 'aria-describedby'?: string;+ 'aria-label': string;+ disabled?: boolean;+ /** The visible copy, which the accessible name extends. */+ label: string;+ /** Text a turned-off prompt keeps, shown after the label so the retained prompt stays discoverable. */+ preview?: string;+ ref?: Ref<HTMLButtonElement>;+ onClick: () => void;+}++/** Stands where an absent negative prompt would be; activating it brings the prompt in. */+export const AddNegativePromptButton = ({+ 'aria-describedby': ariaDescribedBy,+ 'aria-label': ariaLabel,+ disabled,+ label,+ onClick,+ preview,+ ref,+}: AddNegativePromptButtonProps) => (+ <Button+ ref={ref}+ aria-describedby={ariaDescribedBy}+ aria-label={ariaLabel}+ color="fg.muted"+ disabled={disabled}+ justifyContent="flex-start"+ px="2"+ variant="outline"+ onClick={onClick}+ >+ <PlusIcon />+ {/* On one baseline: the preview is smaller than the label, so centring their boxes would leave it high. */}+ <chakra.span alignItems="baseline" display="flex" gap="2" minW="0">+ <span>{label}</span>+ {preview && preview.trim() !== '' ? (+ <Text as="span" color="fg.subtle" fontSize="xs" fontWeight="normal" minW="0" truncate>+ {preview}+ </Text>+ ) : null}+ </chakra.span>+ </Button>+);++interface RemoveNegativePromptButtonProps {+ disabled?: boolean;+ /** Names the control and its tooltip. */+ label: string;+ onClick: () => void;+}++/** Sits at the end of the negative prompt's label row and takes the prompt back out. */+export const RemoveNegativePromptButton = ({ disabled, label, onClick }: RemoveNegativePromptButtonProps) => (+ <IconButton+ aria-label={label}+ color="fg.muted"+ disabled={disabled}+ size="sm"+ tooltip={label}+ variant="ghost"+ onClick={onClick}+ >+ <XIcon />+ </IconButton>+);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsxindex 93ab9e8045..13aafe3913 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptActions.tsx@@ -71,8 +71,6 @@ import { useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';const POPOVER_POSITIONING_BOTTOM_END = { placement: 'bottom-end' } as const;-/** Beside the trigger, so the prompt the request rewrites stays in view while it runs. */-const POPOVER_POSITIONING_BESIDE = { placement: 'right-start' } as const;const TEXT_LLM_MODEL_TYPES = ['text_llm'];const LLAVA_MODEL_TYPES = ['llava_onevision'];/** Keep triggers available so missing-model states can explain recovery. */@@ -148,19 +146,21 @@ export interface PromptTemplateState {active: PromptTemplateSnapshot | null;/** Whether the box is showing the merged result rather than the authored text. */isViewMode: boolean;- /** Absent on surfaces with no template concept (Upscale). */+ /** Absent on surfaces with no template concept (Video). */onApply?: (template: PromptTemplateSnapshot | null, change: PromptTemplateChange) => void;/** Absent wherever `onApply` is; view mode has nothing to show without it. */onViewModeChange?: (viewMode: boolean) => void;/** Writes already-merged text into the authored field and drops the template. */onFlatten: (prompt: string) => void;+ /** Whether a template draft handed over from the gallery opens here (Generate's field, not Upscale's). */+ takesPendingDraft: boolean;}interface PositivePromptActionsProps {batchCount: number;/** An image dropped on the prompt box, for the image-to-prompt popover to open on. */droppedImage: DroppedPromptImage;- /** Absent on surfaces whose prompt is not batch-expanded (Upscale). */+ /** Absent on surfaces whose prompt is not batch-expanded. */dynamicPrompts: DynamicPromptsFieldConfig | null;/** Absent on surfaces whose model family has no prompt enhancer of its own. */expandPromptSuggestion?: ExpandPromptSuggestion | null;@@ -255,6 +255,7 @@ const PromptTemplateControls = ({<PromptTemplatesButtonactiveTemplate={template.active}showSyntaxHighlighting={showSyntaxHighlighting}+ takesPendingDraft={template.takesPendingDraft}onApply={template.onApply}/>) : null}@@ -645,7 +646,12 @@ const usePromptRewritePopover = ({isOpen,open,rewrite,- rootProps: { finalFocusEl, onOpenChange: handleOpenChange, open: isOpen, positioning: POPOVER_POSITIONING_BESIDE },+ rootProps: {+ finalFocusEl,+ onOpenChange: handleOpenChange,+ open: isOpen,+ positioning: POPOVER_POSITIONING_BOTTOM_END,+ },};};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsxindex d4f7b30826..46b6be015a 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PositivePromptField.tsx@@ -41,14 +41,19 @@ const PROMPT_INPUT_DEBOUNCE_MS = 250;interface PositivePromptFieldProps {batchCount?: number;- /** Absent on surfaces whose prompt is not batch-expanded (Upscale). */+ /** Absent on surfaces whose prompt is not batch-expanded. */dynamicPrompts?: DynamicPromptsFieldConfig | null;/** Absent on surfaces whose model family has no prompt enhancer of its own. */expandPromptSuggestion?: ExpandPromptSuggestion | null;- /** Whose prompt focus requests reach this field; Upscale shares Generate's. */+ /** Whose prompt focus requests reach this field. */focusOwner?: PositivePromptOwner;- /** Absent on surfaces with no template concept (Upscale). */+ /** Absent on surfaces with no template concept (Video). */promptTemplate?: PromptTemplateSnapshot | null;+ /**+ * Whether a template draft handed over from the gallery opens in this field's templates. The handover reveals+ * Generate, so Upscale, which shares Generate's template, leaves it to Generate's field.+ */+ takesPendingTemplateDraft?: boolean;/** Show the merged prompt read-only instead of the authored text. */isTemplateViewMode?: boolean;onTemplateViewModeChange?: (viewMode: boolean) => void;@@ -91,6 +96,7 @@ export const PositivePromptField = ({savedPromptModels,selectedModel,showSyntaxHighlighting,+ takesPendingTemplateDraft = true,value,}: PositivePromptFieldProps) => {const { t } = useTranslation();@@ -237,8 +243,16 @@ export const PositivePromptField = ({onApply: onApplyPromptTemplate,onFlatten: flattenPromptTemplate,onViewModeChange: onTemplateViewModeChange,+ takesPendingDraft: takesPendingTemplateDraft,}),- [flattenPromptTemplate, isViewingMerged, onApplyPromptTemplate, onTemplateViewModeChange, promptTemplate]+ [+ flattenPromptTemplate,+ isViewingMerged,+ onApplyPromptTemplate,+ onTemplateViewModeChange,+ promptTemplate,+ takesPendingTemplateDraft,+ ]);const labelEnd = useMemo(diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsxindex 607575ed66..e206d5b17f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.browser.test.tsx@@ -3,6 +3,7 @@ import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemimport { ChakraProvider } from '@chakra-ui/react';import { PromptTemplatesButton } from '@features/generation/ui/promptFields/PromptTemplatesButton';+import { setPendingPromptTemplateDraft } from '@features/generation/ui/promptTemplateDraftStore';import { Tooltip } from '@platform/ui/Tooltip';import { system } from '@theme/system';import i18next from 'i18next';@@ -48,6 +49,12 @@ vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) =>}),}));+// The editor's image slot is the gallery's; only which field opens the editor is under test.+vi.mock('@features/gallery/mediaSlot', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ GalleryMediaSlot: () => null,+}));+let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -182,6 +189,41 @@ describe('the prompt templates button', () => {).toBeUndefined();});+ it('leaves a template draft handed over from the gallery to the field that takes it', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);++ // Upscale's field (first, so it would be first to hear) shares Generate's template but leaves the handover to it.+ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <div data-testid="upscale">+ <PromptTemplatesButton+ activeTemplate={null}+ showSyntaxHighlighting={false}+ takesPendingDraft={false}+ onApply={vi.fn()}+ />+ </div>+ <div data-testid="generate">+ <PromptTemplatesButton activeTemplate={null} showSyntaxHighlighting={false} onApply={vi.fn()} />+ </div>+ </ChakraProvider>+ </I18nextProvider>+ );+ });++ await act(() => setPendingPromptTemplateDraft({ negativePrompt: '', positivePrompt: 'a lighthouse' }));++ const triggerState = (testId: string) =>+ host!.querySelector(`[data-testid="${testId}"] button`)?.getAttribute('aria-expanded');++ expect(triggerState('upscale')).toBe('false');+ expect(triggerState('generate')).toBe('true');+ });+it('says nothing while the catalog is unread', async () => {usePromptTemplates.mockReturnValue({ ...catalog, isLoaded: false });await render(applied);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsxindex c689094eb2..4f58a7441c 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/PromptTemplatesButton.tsx@@ -24,6 +24,8 @@ export type PromptTemplateChange = 'chosen' | 'synced';interface PromptTemplatesButtonProps {activeTemplate: PromptTemplateSnapshot | null;showSyntaxHighlighting: boolean;+ /** Whether a template draft handed over from the gallery opens here; it goes to Generate's field, not Upscale's. */+ takesPendingDraft?: boolean;onApply: (template: PromptTemplateSnapshot | null, change: PromptTemplateChange) => void;}@@ -34,6 +36,7 @@ export const PromptTemplatesButton = ({activeTemplate,onApply,showSyntaxHighlighting,+ takesPendingDraft = true,}: PromptTemplatesButtonProps) => {const { t } = useTranslation();const triggerId = useId();@@ -47,7 +50,8 @@ export const PromptTemplatesButton = ({useCallback((prefill: PendingPromptTemplateDraft) => {setEditorTarget({ prefill, record: null });setIsOpen(true);- }, [])+ }, []),+ takesPendingDraft);const handleOpenChange = useCallback((event: { open: boolean }) => {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.browser.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.browser.test.tsindex e44dc66115..d77b04c992 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.browser.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.browser.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it } from 'vitest';-import { editTextareaText, isOtherTextEntry } from './promptFocus';+import { editTextareaText, focusPositivePrompt, isOtherTextEntry, registerPositivePromptElement } from './promptFocus';const mount = (html: string) => {const host = document.createElement('div');@@ -73,3 +73,39 @@ describe('isOtherTextEntry', () => {expect(isOtherTextEntry(byId('search'), prompt)).toBe(false);});});++describe('focusPositivePrompt', () => {+ it("focuses the named surface's field, whichever mounted last", () => {+ const host = mount('<textarea data-owner="generate"></textarea><textarea data-owner="upscale"></textarea>');+ const generate = host.querySelector<HTMLTextAreaElement>('[data-owner="generate"]')!;+ const upscale = host.querySelector<HTMLTextAreaElement>('[data-owner="upscale"]')!;++ registerPositivePromptElement('generate', generate, null);+ // Upscale mounts after Generate; the focus-prompt command still means Generate's.+ registerPositivePromptElement('upscale', upscale, null);++ try {+ expect(focusPositivePrompt()).toBe(true);+ expect(document.activeElement).toBe(generate);+ expect(focusPositivePrompt('upscale')).toBe(true);+ expect(document.activeElement).toBe(upscale);+ } finally {+ registerPositivePromptElement('generate', null, generate);+ registerPositivePromptElement('upscale', null, upscale);+ }+ });++ it('does not take a field a collapsed section hides', () => {+ const host = mount('<div hidden><textarea></textarea></div>');+ const textarea = host.querySelector('textarea')!;++ registerPositivePromptElement('upscale', textarea, null);++ try {+ expect(focusPositivePrompt('upscale')).toBe(false);+ expect(document.activeElement).not.toBe(textarea);+ } finally {+ registerPositivePromptElement('upscale', null, textarea);+ }+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.tsindex 3514b4524a..8129511072 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptFocus.ts@@ -1,7 +1,10 @@import { MAX_WILDCARD_NAME_LENGTH } from '@features/generation/core/dynamicPrompts';-/** Which surface's positive prompt: Generate (shared with Upscale) and Video are mounted side by side. */-export type PositivePromptOwner = 'generate' | 'video';+/**+ * Which surface's positive prompt: Generate, Upscale and Video can be mounted side by side. Upscale shows the prompt+ * it shares with Generate in a field of its own, so a request names the field it means.+ */+export type PositivePromptOwner = 'generate' | 'upscale' | 'video';const positivePromptElements = new Map<PositivePromptOwner, HTMLTextAreaElement>();@@ -20,10 +23,11 @@ export const registerPositivePromptElement = (}};+/** False when that field is not mounted or not shown: a field in a collapsed section stays mounted but hidden. */export const focusPositivePrompt = (owner: PositivePromptOwner = 'generate'): boolean => {const element = positivePromptElements.get(owner);- if (!element) {+ if (!element || element.getClientRects().length === 0) {return false;}@@ -33,6 +37,21 @@ export const focusPositivePrompt = (owner: PositivePromptOwner = 'generate'): boreturn true;};+/** How long a reveal waits for a widget, just opened, to show its prompt field. */+const REVEAL_WAIT_MS = 1500;++/** Focuses the field once it shows, for a caller that has just opened its widget or section; gives up quietly. */+export const revealPositivePrompt = (owner: PositivePromptOwner): void => {+ const deadline = performance.now() + REVEAL_WAIT_MS;+ const attempt = () => {+ if (!focusPositivePrompt(owner) && performance.now() < deadline) {+ requestAnimationFrame(attempt);+ }+ };++ requestAnimationFrame(attempt);+};+export const isPositivePromptFocused = (owner: PositivePromptOwner = 'generate'): boolean => {const element = positivePromptElements.get(owner);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.tsindex 7702f2906a..7c1bed521a 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/promptHistoryNavigation.ts@@ -64,7 +64,8 @@ export const createPromptHistoryNavigation = (): PromptHistoryNavigation => {state = null;}- if (!isPositivePromptFocused() || promptHistory.length === 0) {+ // Upscale's field edits the prompt it shares with Generate, which is what this steps through.+ if (!(isPositivePromptFocused('generate') || isPositivePromptFocused('upscale')) || promptHistory.length === 0) {return;}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.tsindex 768dc28fc9..a3c9f556ea 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptTemplateDraftStore.ts@@ -31,8 +31,16 @@ const takePendingPromptTemplateDraft = (): PendingPromptTemplateDraft | null =>return draft;};-export const useOnPendingPromptTemplateDraft = (onDraft: (draft: PendingPromptTemplateDraft) => void): void => {+/** `isEnabled` false leaves a draft for another field: only the surface the handover reveals takes it. */+export const useOnPendingPromptTemplateDraft = (+ onDraft: (draft: PendingPromptTemplateDraft) => void,+ isEnabled = true+): void => {const deliver = useEffectEvent(() => {+ if (!isEnabled) {+ return;+ }+const draft = takePendingPromptTemplateDraft();if (draft) {diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsxindex 0b6d00c543..4cb3ce60e2 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx@@ -11,7 +11,7 @@ import type {import type { GenerateSettingsUpdate } from '@features/generation/ui/generateDebounce';import type { MouseEvent } from 'react';-import { HStack, Icon, Stack, Text } from '@chakra-ui/react';+import { Box, chakra, HStack, Icon, Stack, Text } from '@chakra-ui/react';import { useDndMonitor } from '@dnd-kit/core';import { galleryImages, toGalleryItemKey } from '@features/gallery';import { GalleryPickerPopover } from '@features/gallery/picker';@@ -22,6 +22,7 @@ import {getMaxReferenceImages,getReferenceImageUnavailableReason,isReferenceImageSupported,+ reconcileReferenceImagesWithModel,withAddedReferenceImages,} from '@features/generation/core/baseGenerationPolicies';import {@@ -34,19 +35,39 @@ import {deriveAspectRatioId,moveReferenceImage,normalizeGenerateWidgetValues,+ renameReferenceImage,} from '@features/generation/core/settings';import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';import { GenerateIssueNotes } from '@features/generation/ui/shared/GenerateIssues';-import { Button, DropTargetOverlay, DropZone } from '@platform/ui';-import { ChevronDownIcon, ImagePlusIcon } from 'lucide-react';+import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';+import { Button } from '@platform/ui/Button';+import { DropTargetOverlay } from '@platform/ui/DropTargetOverlay';+import { FieldLabel } from '@platform/ui/Field';+import { FeatureHint } from '@platform/ui/hints';+import { ListStack } from '@platform/ui/list/ListStack';+import { Row } from '@platform/ui/Row';+import { PlusIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { ReferenceImageCard } from './ReferenceImageCard';+import { getReferenceModelTypes, ReferenceImageRow } from './ReferenceImageRow';-const UPLOAD_ZONE_HOVER_STYLES = { bg: 'bg.muted', color: 'fg' };-/** Display names for the formats the backend can require of reference-image models. */const IMAGE_ONLY = ['image'] as const;+const FOCUS_WAIT_FRAMES = 30;++/** An undone removal brings its row back with the settings store's next render; it takes focus once it is there. */+const focusReferenceWhenRendered = (id: string, framesLeft = FOCUS_WAIT_FRAMES) =>+ requestAnimationFrame(() => {+ const row = document.querySelector<HTMLElement>(+ `[data-reference-image-id="${CSS.escape(id)}"] [data-list-primary]`+ );++ if (row) {+ row.focus();+ } else if (framesLeft > 0) {+ focusReferenceWhenRendered(id, framesLeft - 1);+ }+ });/** The picker's trigger skips a click whose default is prevented, so a full set opens no picker. */const preventPickerOpen = (event: MouseEvent) => event.preventDefault();@@ -69,7 +90,9 @@ export const GenerateReferenceImagesContent = ({visionComponents,}: GenerateReferenceImagesContentProps) => {const { t } = useTranslation();- const { gallery, notifications, project, settings } = useGenerationUi();+ const { gallery, models: uiModels, notifications, project, settings } = useGenerationUi();+ const { openManager, readCatalog } = uiModels;+ const openModelManager = useCallback((modelType: string) => openManager({ modelType }), [openManager]);const isSupported = isReferenceImageSupported(selectedModel, visionComponents);const unavailableReason = getReferenceImageUnavailableReason(selectedModel, visionComponents);const maxReferenceImages = getMaxReferenceImages(selectedModel, visionComponents);@@ -133,12 +156,15 @@ export const GenerateReferenceImagesContent = ({[onCommit]);- const removeReferenceImage = useCallback(- (id: string) => {- onCommit((currentSettings) => ({- ...currentSettings,- referenceImages: currentSettings.referenceImages.filter((referenceImage) => referenceImage.id !== id),- }));+ const handleRenameReferenceImage = useCallback(+ (id: string, name: string, isDefaultName: (name: string) => boolean) => {+ onCommit((currentSettings) => {+ const referenceImages = renameReferenceImage(currentSettings.referenceImages, id, name, isDefaultName);++ return referenceImages === currentSettings.referenceImages+ ? currentSettings+ : { ...currentSettings, referenceImages: [...referenceImages] };+ });},[onCommit]);@@ -157,6 +183,78 @@ export const GenerateReferenceImagesContent = ({[onCommit]);+ /**+ * Puts removed references back at `at` among those there now (any added since stay), each as it was: name, crop and+ * settings. The model and the installed adapters may have changed since, so they then meet the current ones as a+ * switch to that model with them present would leave them: retargeted where their adapter does not fit, and switched+ * off beyond what it runs together.+ */+ const restoreReferenceImages = useCallback(+ (removed: readonly GenerateReferenceImage[], at: number, projectId: string) => {+ const values = normalizeGenerateWidgetValues(settings.readGenerateValues(projectId));+ const removedIds = new Set(removed.map((referenceImage) => referenceImage.id));+ const kept = (values?.referenceImages ?? []).filter((referenceImage) => !removedIds.has(referenceImage.id));+ const position = Math.min(at, kept.length);+ const restored = [...kept.slice(0, position), ...removed, ...kept.slice(position)];++ settings.patchGenerateSettings(+ {+ referenceImages: values+ ? reconcileReferenceImagesWithModel(restored, values.model, readCatalog()).referenceImages+ : restored,+ },+ projectId+ );+ },+ [readCatalog, settings]+ );++ // Undoable, so it does not ask first: the Undo puts the reference back where it was, as it was.+ const removeReferenceImage = useCallback(+ (id: string) => {+ const { activeProjectId: projectId } = project;+ let found: { at: number; referenceImage: GenerateReferenceImage } | null = null;++ // The commit applies the update at once, so `found` is set when it returns; a later replay finds the same.+ onCommit((currentSettings) => {+ const at = currentSettings.referenceImages.findIndex((referenceImage) => referenceImage.id === id);+ const referenceImage = currentSettings.referenceImages[at];++ if (!referenceImage) {+ return currentSettings;+ }++ found ??= { at, referenceImage };+ return {+ ...currentSettings,+ referenceImages: currentSettings.referenceImages.filter((candidate) => candidate.id !== id),+ };+ });++ const removed = found as { at: number; referenceImage: GenerateReferenceImage } | null;++ if (!removed) {+ return;+ }++ notifications.undoable(+ t('widgets.generate.referenceImageRemoved', {+ name: removed.referenceImage.name ?? t('widgets.generate.referenceImageNumbered', { index: removed.at + 1 }),+ }),+ {+ onUndo: () => {+ // The removal may still sit in the form's debounce; it lands before the restore reads the settings.+ flushWorkbenchDrafts();+ restoreReferenceImages([removed.referenceImage], removed.at, projectId);+ focusReferenceWhenRendered(id);+ },+ projectId,+ }+ );+ },+ [notifications, onCommit, project, restoreReferenceImages, t]+ );+// Undoable, so it does not ask first. The Undo puts the removed references back ahead of any added since.const clearReferenceImages = useCallback(() => {const { activeProjectId: projectId } = project;@@ -164,38 +262,10 @@ export const GenerateReferenceImagesContent = ({onCommitImmediate({ referenceImages: [] });notifications.undoable(t('widgets.generate.referenceImagesRemoved', { count: removed.length }), {- onUndo: () => {- const values = normalizeGenerateWidgetValues(settings.readGenerateValues(projectId));- const current = values?.referenceImages ?? [];- const removedIds = new Set(removed.map((referenceImage) => referenceImage.id));- const restored = [...removed, ...current.filter((referenceImage) => !removedIds.has(referenceImage.id))];- // A model that takes references gets no more running than it takes: the rest come back turned off.- const limit =- values && isReferenceImageSupported(values.model, values)- ? getMaxReferenceImages(values.model, values)- : null;- let running = 0;-- settings.patchGenerateSettings(- {- referenceImages:- limit === null- ? restored- : restored.map((referenceImage) => {- if (!referenceImage.isEnabled) {- return referenceImage;- }-- running += 1;- return running > limit ? { ...referenceImage, isEnabled: false } : referenceImage;- }),- },- projectId- );- },+ onUndo: () => restoreReferenceImages(removed, 0, projectId),projectId,});- }, [notifications, onCommitImmediate, project, referenceImages, settings, t]);+ }, [notifications, onCommitImmediate, project, referenceImages, restoreReferenceImages, t]);const pickerSelection = useMemo<GalleryPickerSelection>(() => ({@@ -293,10 +363,44 @@ export const GenerateReferenceImagesContent = ({) : null;}- // Unsupported-model references remain read-only with removal as recovery.+ const referenceModelTypes = getReferenceModelTypes(selectedModel?.base);+ const hasModelChoice = models.some(+ (model) => model.base === selectedModel?.base && referenceModelTypes.includes(model.type)+ );+ const rows = referenceImages.map((referenceImage, index) => (+ <ReferenceImageRow+ key={referenceImage.id}+ count={referenceImageCount}+ hasModelChoice={hasModelChoice}+ onOpenModelManager={openModelManager}+ index={index}+ isSupported={isSupported}+ promptTag={promptTags.get(referenceImage.id)}+ referenceImage={referenceImage}+ selectedModel={selectedModel}+ onFindInGallery={gallery.findImage}+ onMove={handleMoveReferenceImage}+ onPatch={patchReferenceImage}+ onRemove={removeReferenceImage}+ onRename={handleRenameReferenceImage}+ onUseSize={applyReferenceImageSize}+ />+ ));+ const label = (+ <Box>+ <FeatureHint hint="referenceImage">+ <chakra.span>+ <FieldLabel>{t('widgets.generate.referenceImages')}</FieldLabel>+ </chakra.span>+ </FeatureHint>+ </Box>+ );++ // References the model cannot use stay listed, inert, so it is clear what Remove all would clear.if (!isSupported) {return (- <Stack gap="2">+ <Stack gap="1.5">+ {label}<HStack gap="2" justify="space-between"><Text color="fg.muted" fontSize="xs" minW="0">{unsupportedMessage}@@ -305,14 +409,19 @@ export const GenerateReferenceImagesContent = ({{t('widgets.generate.clearReferenceImages')}</Button></HStack>- {/* No cards to show them on: every reference's issue lists here. */}+ {/* The rows are inert here, so every reference's issue lists above them, with its fix. */}<GenerateIssueNotes field="referenceImage" section="guidance" />+ <Box mx={-1}>+ <ListStack dividers label={t('widgets.generate.referenceImages')}>+ {rows}+ </ListStack>+ </Box></Stack>);}return (- <Stack ref={setNodeRef} gap="2" position="relative">+ <Stack ref={setNodeRef} gap="1.5" position="relative"><DropTargetOverlayisActive={acceptsActiveDrag}isOver={isOver}@@ -322,69 +431,72 @@ export const GenerateReferenceImagesContent = ({: t('widgets.generate.referenceSlotsFull', { count: maxReferenceImages })}/>- <GalleryPickerPopover- accept={IMAGE_ONLY}- label={t('widgets.generate.addReferenceImage')}- selection={pickerSelection}- onPick={handlePick}- >- {/* Full, it stays a focusable drop target that says why it adds nothing: `aria-disabled` rather than `disabled`,- since Chrome sends no mouseup to a disabled control and a drag released over one would never end. */}- <DropZone- as="button"- alignItems="center"- aria-disabled={canAdd ? undefined : true}- cursor={canAdd ? undefined : 'not-allowed'}- display="flex"- flexDirection="column"- fontSize="xs"- gap="1"- isDisabled={!canAdd}- isOver={isOver}- justifyContent="center"- minH="14"- minW="0"- opacity={canAdd ? 1 : 0.6}- px="3"- w="full"- _hover={canAdd ? UPLOAD_ZONE_HOVER_STYLES : undefined}- onClickCapture={canAdd ? undefined : preventPickerOpen}- >- <HStack as="span" color="fg" fontSize="md" fontWeight="600" gap="1.5">- <Icon as={ImagePlusIcon} boxSize="4" />- {t('widgets.generate.addReferenceImage')}- <Icon as={ChevronDownIcon} boxSize="3" color="fg.subtle" />- </HStack>- <Text as="span" color="fg.muted" textAlign="center" textWrap="pretty">- {canAdd- ? t('widgets.generate.referenceSlotsHint', { count: referenceImageCount, max: maxReferenceImages })- : t('widgets.generate.referenceSlotsFullZone', { count: maxReferenceImages })}- </Text>- </DropZone>- </GalleryPickerPopover>-- {/* Issues about the references as a group (their count); each card shows its own. */}+ {label}+ {/* Issues about the references as a group (their count); each row shows its own. */}<GenerateIssueNotes field="referenceImages" section="guidance" />-- {referenceImageCount > 0 ? (- <Stack gap="2">- {referenceImages.map((referenceImage, index) => (- <ReferenceImageCard- key={referenceImage.id}- count={referenceImageCount}- index={index}- referenceImage={referenceImage}- selectedModel={selectedModel}- onFindInGallery={gallery.findImage}- onMove={handleMoveReferenceImage}- onPatch={patchReferenceImage}- onRemove={removeReferenceImage}- onUseSize={applyReferenceImageSize}- promptTag={promptTags.get(referenceImage.id)}- />- ))}- </Stack>- ) : null}+ {/* The same bleed as the concept list below it, so both lists' rows share their edges and inner padding. */}+ <Box mx={-1}>+ <ListStack dividers label={t('widgets.generate.referenceImages')}>+ {rows}+ {/* The list's last row, and its whole empty state. */}+ <Box role="listitem">+ <GalleryPickerPopover+ accept={IMAGE_ONLY}+ label={t('widgets.generate.addReferenceImage')}+ selection={pickerSelection}+ onPick={handlePick}+ >+ {/* Full, it stays a focusable drop target that says why it adds nothing: `aria-disabled` rather than+ `disabled`, since Chrome sends no mouseup to a disabled control and a drag released over one would+ never end. */}+ <Row+ asChild+ aria-disabled={canAdd ? undefined : true}+ cursor={canAdd ? undefined : 'not-allowed'}+ data-disabled={canAdd ? undefined : ''}+ data-hover={isOver && canAdd ? '' : undefined}+ data-list-surface=""+ data-reference-add=""+ gap="2.5"+ minH="12"+ px="1.5"+ py="1.5"+ onClickCapture={canAdd ? undefined : preventPickerOpen}+ >+ <chakra.button type="button">+ <Box+ alignItems="center"+ borderColor="border.emphasized"+ borderStyle="dashed"+ borderWidth="1px"+ boxSize="9"+ color="fg.muted"+ display="flex"+ flexShrink={0}+ justifyContent="center"+ rounded="sm"+ >+ <Icon as={PlusIcon} boxSize="3.5" />+ </Box>+ <Stack as="span" flex="1" gap="0.5" minW="0">+ <Text as="span" fontSize="md" fontWeight="600" lineHeight="shorter" truncate>+ {t('widgets.generate.addReferenceImage')}+ </Text>+ <Text as="span" color="fg.muted" fontSize="xs" lineHeight="shorter" textWrap="pretty">+ {canAdd+ ? t('widgets.generate.referenceSlotsHint', {+ count: referenceImageCount,+ max: maxReferenceImages,+ })+ : t('widgets.generate.referenceSlotsFullZone', { count: maxReferenceImages })}+ </Text>+ </Stack>+ </chakra.button>+ </Row>+ </GalleryPickerPopover>+ </Box>+ </ListStack>+ </Box></Stack>);};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsxdeleted file mode 100644index c05ae6caea..0000000000--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageCard.tsx+++ /dev/null@@ -1,588 +0,0 @@-import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';-import type {- GenerateModelConfig,- GenerateReferenceImage,- GenerateReferenceImageAsset,- GenerateReferenceImageConfig,-} from '@features/generation/core/types';-import type { CSSProperties } from 'react';--import { Box, HStack, Icon, Stack, Text, VisuallyHidden } from '@chakra-ui/react';-import { FindInGalleryButton } from '@features/gallery/mediaSlot';-import { isStrengthOnlyIPAdapterBase } from '@features/generation/core/baseGenerationPolicies';-import { getEffectiveReferenceImage } from '@features/generation/core/referenceImage';-import { getReferenceImageUrls } from '@features/generation/data/referenceImageUrls';-import { GenerationModelSelect as ModelSelect } from '@features/generation/ui/GenerationUiContext';-import { GenerateIssueNotes } from '@features/generation/ui/shared/GenerateIssues';-import { canCopyText, copyText } from '@platform/browser/clipboard';-import { useExitPresence } from '@platform/react/useExitRetainedValue';-import { Button, IconButton, toaster, ToggleDot, Tooltip } from '@platform/ui';-import {- ArrowDownIcon,- ArrowUpIcon,- CheckIcon,- ChevronDownIcon,- CropIcon,- ImageIcon,- RulerIcon,- Trash2Icon,-} from 'lucide-react';-import { memo, useCallback, useEffect, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { formatWeight, getModeLabelKey } from './referenceImageConfig';-import {- ClipVisionSelect,- FieldHeader,- FluxReduxControls,- IPAdapterControls,- Krea2ReferenceModeControl,- Krea2StyleReferenceControls,-} from './ReferenceImageControls';-import { ReferenceImageCropDialog } from './ReferenceImageCropDialog';--/** Reference image config variants that carry a selectable model. */-type ModelBackedConfig = Extract<- GenerateReferenceImageConfig,- { type: 'ip_adapter' | 'flux_redux' | 'flux_kontext_reference_image' }->;--const ISSUE_NOTES_CSS = { '&:not(:empty)': { pb: '2' } };--const THUMBNAIL_ACTIONS_CSS = {- '&:focus-within .reference-image-actions, &:hover .reference-image-actions': {- opacity: 1,- },-};--const FLUX_MODEL_TYPES = ['ip_adapter', 'flux_redux'];-const DEFAULT_MODEL_TYPES = ['ip_adapter'];-const COVER_IMG_STYLE: CSSProperties = {- height: '100%',- objectFit: 'cover',- width: '100%',-};-const PROMPT_TAG_COPIED_MS = 1500;-const OVERLAY_GRADIENT_STYLE: CSSProperties = {- background: 'linear-gradient(to top, rgba(0, 0, 0, 0.72), transparent)',-};--interface ReferenceImageCardProps {- count: number;- index: number;- referenceImage: GenerateReferenceImage;- selectedModel: GenerateModelConfig | undefined;- onFindInGallery: (imageName: string) => void;- onMove: (id: string, direction: -1 | 1) => void;- onPatch: (id: string, patch: Partial<GenerateReferenceImage>) => void;- onRemove: (id: string) => void;- onUseSize: (image: GenerateReferenceImageAsset) => void;- /** How the prompt names this reference, for models that address references by tag. */- promptTag?: string;-}--const ReferenceImageCardBase = ({- count,- index,- onFindInGallery,- onMove,- onPatch,- onRemove,- onUseSize,- promptTag,- referenceImage,- selectedModel,-}: ReferenceImageCardProps) => {- const { t } = useTranslation();- const [isCollapsed, setIsCollapsed] = useState(false);- const moveUpRef = useRef<HTMLButtonElement>(null);- const moveDownRef = useRef<HTMLButtonElement>(null);- const canMoveUp = index > 0;- const canMoveDown = index < count - 1;- const config = referenceImage.config;- const isEnabled = referenceImage.isEnabled;- const selectedBase = selectedModel?.base;- const title = t('widgets.generate.referenceImageNumbered', { index: index + 1 });- const collapseLabel = isCollapsed- ? t('widgets.generate.expandReferenceImage')- : t('widgets.generate.collapseReferenceImage');- const toggleLabel = isEnabled- ? t('widgets.generate.disableReferenceImage')- : t('widgets.generate.enableReferenceImage');-- const changeConfig = useCallback(- (nextConfig: GenerateReferenceImageConfig) => onPatch(referenceImage.id, { config: nextConfig }),- [onPatch, referenceImage.id]- );-- const handleToggle = useCallback(- (nextEnabled: boolean) => onPatch(referenceImage.id, { isEnabled: nextEnabled }),- [onPatch, referenceImage.id]- );-- const handleRemove = useCallback(() => onRemove(referenceImage.id), [onRemove, referenceImage.id]);-- // Hand off focus when reordering disables the activated arrow.- const handleMoveUp = useCallback(() => {- onMove(referenceImage.id, -1);-- if (index - 1 === 0) {- moveDownRef.current?.focus();- }- }, [index, onMove, referenceImage.id]);-- const handleMoveDown = useCallback(() => {- onMove(referenceImage.id, 1);-- if (index + 1 === count - 1) {- moveUpRef.current?.focus();- }- }, [count, index, onMove, referenceImage.id]);-- const handleCrop = useCallback(- (image: GenerateReferenceImageAsset) => changeConfig({ ...config, image }),- [changeConfig, config]- );-- const expand = useCallback(() => setIsCollapsed(false), []);-- const toggleCollapsed = useCallback(() => setIsCollapsed((previous) => !previous), []);-- return (- <Stack- bg="bg.subtle"- borderColor={isEnabled ? 'border.emphasized' : 'border.subtle'}- borderWidth="1px"- gap="0"- opacity={isEnabled ? 1 : 0.55}- rounded="md"- transition="opacity var(--wb-motion-duration-slow)"- >- <HStack gap="2" minW="0" px="2" py="1.5">- <ToggleDot checked={isEnabled} label={toggleLabel} onCheckedChange={handleToggle} />-- {isCollapsed ? (- <HStack as="button" flex="1" gap="2" minW="0" textAlign="left" onClick={expand}>- <MiniThumbnail image={config.image} />- <Text color="fg.muted" fontSize="md" minW="0" truncate>- <Text as="span" color={isEnabled ? 'fg' : 'fg.muted'} fontWeight="medium">- {title}- </Text>- {config.type === 'ip_adapter' ? (- <>- {' · '}- {isStrengthOnlyIPAdapterBase(selectedBase)- ? t('widgets.generate.strength')- : t(getModeLabelKey(config.method))}{' '}- <Text as="span" color="fg.subtle" fontFamily="mono">- {formatWeight(config.weight)}- </Text>- </>- ) : config.type === 'krea2_reference_image' ? (- <>- {' · '}- {t('widgets.generate.styleStrength')}{' '}- <Text as="span" color="fg.subtle" fontFamily="mono">- {formatWeight(config.styleStrength)}- </Text>- </>- ) : config.type === 'krea2_edit_reference_image' ? (- <>- {' · '}- {t('widgets.generate.modeEdit')}- </>- ) : null}- </Text>- </HStack>- ) : (- <Text color={isEnabled ? 'fg' : 'fg.muted'} flex="1" fontSize="md" fontWeight="medium" minW="0" truncate>- {title}- </Text>- )}-- {promptTag ? <PromptTagButton tag={promptTag} /> : null}-- <HStack gap="0.5">- {/* Array order is conditioning order. */}- <Tooltip content={t('widgets.generate.moveReferenceImageUp')}>- <IconButton- ref={moveUpRef}- aria-label={t('widgets.generate.moveReferenceImageUp')}- color="fg.muted"- disabled={!canMoveUp}- size="sm"- variant="ghost"- onClick={handleMoveUp}- >- <Icon as={ArrowUpIcon} />- </IconButton>- </Tooltip>- <Tooltip content={t('widgets.generate.moveReferenceImageDown')}>- <IconButton- ref={moveDownRef}- aria-label={t('widgets.generate.moveReferenceImageDown')}- color="fg.muted"- disabled={!canMoveDown}- size="sm"- variant="ghost"- onClick={handleMoveDown}- >- <Icon as={ArrowDownIcon} />- </IconButton>- </Tooltip>- <Tooltip content={collapseLabel}>- <IconButton aria-label={collapseLabel} color="fg.muted" size="sm" variant="ghost" onClick={toggleCollapsed}>- <Box- asChild- transform={isCollapsed ? 'rotate(-90deg)' : undefined}- transition="transform var(--wb-motion-duration-slow)"- >- <ChevronDownIcon size="14" />- </Box>- </IconButton>- </Tooltip>- <Tooltip content={t('widgets.generate.removeReferenceImage')}>- <IconButton- aria-label={t('widgets.generate.removeReferenceImage')}- color="fg.muted"- size="sm"- variant="ghost"- colorPalette="red"- onClick={handleRemove}- >- <Icon as={Trash2Icon} colorPalette="red" />- </IconButton>- </Tooltip>- </HStack>- </HStack>-- {/* Shown collapsed too: a reference that blocks Invoke says so on its own card. */}- <Box css={ISSUE_NOTES_CSS} px="2">- <GenerateIssueNotes field="referenceImage" referenceImageId={referenceImage.id} section="guidance" />- </Box>-- {isCollapsed ? null : (- <HStack align="flex-start" gap="3" pb="2" px="2">- <ReferenceImageThumbnail- disabled={!isEnabled}- image={config.image}- onCrop={handleCrop}- onFindInGallery={onFindInGallery}- onUseSize={onUseSize}- />- <Stack flex="1" gap="2" minW="0">- {config.type === 'ip_adapter' ? (- <IPAdapterControls- key={config.model?.key ?? 'no-model'}- config={config}- disabled={!isEnabled}- strengthOnly={isStrengthOnlyIPAdapterBase(selectedBase)}- onChange={changeConfig}- >- <ReferenceModelSelector- config={config}- disabled={!isEnabled}- relatedTo={selectedModel?.key ?? null}- selectedBase={selectedBase}- onConfigChange={changeConfig}- />- </IPAdapterControls>- ) : config.type === 'flux_redux' ? (- <>- <ReferenceModelSelector- config={config}- disabled={!isEnabled}- relatedTo={selectedModel?.key ?? null}- selectedBase={selectedBase}- onConfigChange={changeConfig}- />- <FluxReduxControls config={config} disabled={!isEnabled} onChange={changeConfig} />- </>- ) : config.type === 'flux_kontext_reference_image' ? (- <ReferenceModelSelector- config={config}- disabled={!isEnabled}- relatedTo={selectedModel?.key ?? null}- selectedBase={selectedBase}- onConfigChange={changeConfig}- />- ) : config.type === 'krea2_reference_image' || config.type === 'krea2_edit_reference_image' ? (- <>- <Krea2ReferenceModeControl config={config} onChange={changeConfig} />- {config.type === 'krea2_reference_image' ? (- <Krea2StyleReferenceControls config={config} disabled={!isEnabled} onChange={changeConfig} />- ) : null}- </>- ) : null}- </Stack>- </HStack>- )}- </Stack>- );-};--export const ReferenceImageCard = memo(ReferenceImageCardBase);--const PromptTagButton = ({ tag }: { tag: string }) => {- const { t } = useTranslation();- const [hasCopied, setHasCopied] = useState(false);- const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);-- useEffect(- () => () => {- if (resetTimerRef.current !== null) {- clearTimeout(resetTimerRef.current);- }- },- []- );-- const copyTag = useCallback(() => {- copyText(tag)- .then(() => {- setHasCopied(true);- if (resetTimerRef.current !== null) {- clearTimeout(resetTimerRef.current);- }- resetTimerRef.current = setTimeout(() => setHasCopied(false), PROMPT_TAG_COPIED_MS);- })- .catch(() =>- toaster.create({ description: t('common.clipboardBlocked'), title: t('common.couldNotCopy'), type: 'error' })- );- }, [t, tag]);-- const canCopy = canCopyText();- // Without a clipboard the button shows its own tooltip, the reason, so the explanation joins it there rather than- // opening a second tooltip; it leaves out the hint's "click to copy", which is untrue then.- const unavailableReason = canCopy- ? undefined- : `${t('widgets.generate.referenceImagePromptTagExplanation', { tag })} ${t('common.copyUnavailable')}`;- const button = (- <Button- aria-label={t('widgets.generate.copyReferenceImagePromptTag', { tag })}- color="fg.muted"- flexShrink="0"- fontFamily="mono"- fontWeight="normal"- size="xs"- unavailableReason={unavailableReason}- variant="subtle"- onClick={copyTag}- >- {hasCopied ? <Icon as={CheckIcon} color="green.solid" /> : null}- {tag}- <VisuallyHidden aria-live="polite">- {hasCopied ? t('widgets.generate.referenceImagePromptTagCopied', { tag }) : ''}- </VisuallyHidden>- </Button>- );-- return canCopy ? (- <Tooltip content={t('widgets.generate.referenceImagePromptTagHint', { tag })}>{button}</Tooltip>- ) : (- button- );-};--const ReferenceModelSelector = ({- config,- disabled,- onConfigChange,- relatedTo,- selectedBase,-}: {- config: ModelBackedConfig;- disabled: boolean;- relatedTo: string | null;- selectedBase: string | undefined;- onConfigChange: (config: GenerateReferenceImageConfig) => void;-}) => {- const { t } = useTranslation();- const modelTypes = selectedBase === 'flux' ? FLUX_MODEL_TYPES : DEFAULT_MODEL_TYPES;-- const filterModel = useCallback((model: ModelConfig) => model.base === selectedBase, [selectedBase]);-- const selectReferenceModel = useCallback(- (model: ModelConfig | null) => {- if (!model || model.base !== selectedBase) {- return;- }-- if (model.type === 'flux_redux') {- onConfigChange({- image: config.image,- imageInfluence: 'highest',- model,- type: 'flux_redux',- });- return;- }-- if (model.type === 'ip_adapter') {- onConfigChange({- beginEndStepPct: [0, 1],- clipVisionModel: selectedBase === 'flux' ? 'ViT-L' : 'ViT-H',- image: config.image,- method: 'full',- model,- type: 'ip_adapter',- weight: 1,- });- }- },- [config.image, onConfigChange, selectedBase]- );-- return (- <Stack gap="1">- <FieldHeader hint="referenceImage" label={t('widgets.generate.referenceImageModel')} />- <HStack gap="2">- <ModelSelect- disabled={disabled}- filter={filterModel}- modelTypes={modelTypes}- placeholder={t('widgets.generate.selectModel')}- relatedTo={relatedTo}- value={config.model?.key ?? null}- onChange={selectReferenceModel}- />- {config.type === 'ip_adapter' && !isStrengthOnlyIPAdapterBase(selectedBase) ? (- <ClipVisionSelect- key={config.model?.key ?? 'no-model'}- config={config}- disabled={disabled}- onChange={onConfigChange}- />- ) : null}- </HStack>- </Stack>- );-};--const MiniThumbnail = ({ image }: { image: GenerateReferenceImageAsset | null }) => {- const effectiveImage = image ? getEffectiveReferenceImage(image) : null;- const urls = image ? getReferenceImageUrls(image) : null;-- return (- <Box bg="bg.muted" borderWidth="1px" flexShrink="0" h="6" overflow="hidden" rounded="sm" w="6">- {effectiveImage && urls ? (- <img alt={effectiveImage.image_name} draggable={false} src={urls.thumbnailUrl} style={COVER_IMG_STYLE} />- ) : (- <Box alignItems="center" color="fg.muted" display="flex" h="full" justifyContent="center" w="full">- <ImageIcon size="12" />- </Box>- )}- </Box>- );-};--const ReferenceImageThumbnail = ({- disabled,- image,- onCrop,- onFindInGallery,- onUseSize,-}: {- disabled: boolean;- image: GenerateReferenceImageAsset | null;- onCrop: (image: GenerateReferenceImageAsset) => void;- onFindInGallery: (imageName: string) => void;- onUseSize: (image: GenerateReferenceImageAsset) => void;-}) => {- const { t } = useTranslation();- const [isCropOpen, setIsCropOpen] = useState(false);- const cropDialog = useExitPresence(isCropOpen);- const effectiveImage = image ? getEffectiveReferenceImage(image) : null;- const urls = image ? getReferenceImageUrls(image) : null;-- const openCrop = useCallback(() => setIsCropOpen(true), []);- const closeCrop = useCallback(() => setIsCropOpen(false), []);-- const handleUseSize = useCallback(() => {- if (image) {- onUseSize(image);- }- }, [image, onUseSize]);-- // Reveal original media; crop intermediates have no gallery cell.- const originalImageName = image?.original.image.image_name;- const handleFindInGallery = useCallback(() => {- if (originalImageName !== undefined) {- onFindInGallery(originalImageName);- }- }, [onFindInGallery, originalImageName]);-- return (- <>- {/* Reserve width for all three buttons and their focus rings. */}- <Box- bg="bg.muted"- borderWidth="1px"- css={THUMBNAIL_ACTIONS_CSS}- flexShrink="0"- h="24"- overflow="hidden"- position="relative"- rounded="md"- w="24"- >- {effectiveImage && urls ? (- <img alt={effectiveImage.image_name} draggable={false} src={urls.thumbnailUrl} style={COVER_IMG_STYLE} />- ) : (- <Box alignItems="center" color="fg.muted" display="flex" h="full" justifyContent="center" w="full">- <ImageIcon size="24" />- </Box>- )}- {image ? (- <HStack- bottom="0"- className="reference-image-actions"- gap="1"- justify="center"- left="0"- opacity="0"- p="1"- position="absolute"- right="0"- style={OVERLAY_GRADIENT_STYLE}- transition="opacity var(--wb-motion-duration-fast)"- >- <FindInGalleryButton name={originalImageName} variant="ghost" onFind={handleFindInGallery} />- <Tooltip content={t('common.crop')}>- <IconButton- aria-label={t('common.crop')}- disabled={disabled}- size="sm"- variant="ghost"- onClick={openCrop}- >- <CropIcon />- </IconButton>- </Tooltip>- <Tooltip content={t('widgets.generate.useSize')}>- <IconButton- aria-label={t('widgets.generate.useSize')}- disabled={disabled}- size="sm"- variant="ghost"- onClick={handleUseSize}- >- <RulerIcon />- </IconButton>- </Tooltip>- </HStack>- ) : null}- </Box>- {image && cropDialog.isMounted ? (- <ReferenceImageCropDialog- key={cropDialog.generation}- image={image}- isOpen={cropDialog.isOpen}- onApply={onCrop}- onClose={closeCrop}- onExitComplete={cropDialog.release}- />- ) : null}- </>- );-};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.browser.test.tsxindex d7994e1396..6a26e23039 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.browser.test.tsx@@ -10,7 +10,7 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { CLIP_VISION_MODELS } from './referenceImageConfig';-import { FluxReduxControls, IPAdapterControls } from './ReferenceImageControls';+import { FluxReduxControls, IPAdapterWeightField } from './ReferenceImageControls';const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({@@ -45,13 +45,13 @@ const FLUX_REDUX_CONFIG: FluxReduxConfig = { image: null, imageInfluence: 'higheconst HINTS_ON = { enabled: true, onDisable: null };/** Track inset the scrubber keeps from its frame edge (see ScrubberField). */-const TRACK_INSET_PX = 10;+const TRACK_INSET_PX = 6;let host: HTMLDivElement;let root: Root;const onChange = vi.fn();-/** Mirrors the real card: each commit lands back on the rendered config. */+/** Mirrors the real row: each commit lands back on the rendered config. */const Harness = () => {const [config, setConfig] = useState<IPAdapterConfig>(CONFIG);const handleChange = useCallback((next: GenerateReferenceImageConfig) => {@@ -59,7 +59,7 @@ const Harness = () => {setConfig(next as IPAdapterConfig);}, []);- return <IPAdapterControls config={config} disabled={false} onChange={handleChange} />;+ return <IPAdapterWeightField config={config} disabled={false} onChange={handleChange} />;};beforeEach(() => {@@ -78,7 +78,7 @@ afterEach(async () => {const pointer = (target: EventTarget, type: string, init: PointerEventInit) =>act(() => target.dispatchEvent(new PointerEvent(type, { bubbles: true, button: 0, ...init })));-describe('IPAdapterControls weight', () => {+describe('IPAdapterWeightField', () => {it('commits every step of a drag, including the one back to where the drag started', async () => {await act(() =>root.render(diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsxindex 69a89e22c1..1b7f3a1833 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageControls.tsx@@ -8,12 +8,13 @@ import type {import type { FeatureHintId } from '@platform/ui/hints';import type { ReactNode } from 'react';-import { Collapsible, createListCollection, HStack, SegmentGroup, Stack, Text } from '@chakra-ui/react';+import { Box, chakra, createListCollection, HStack, SegmentGroup, Stack, Text } from '@chakra-ui/react';import { DEFAULT_KREA2_STYLE_STRENGTH, MAX_KREA2_STYLE_STRENGTH } from '@features/generation/core/settings';-import { Field, Select, Slider } from '@platform/ui';+import { Field, FieldLabel, INSIDE_LABEL_INSET } from '@platform/ui/Field';import { FeatureHint } from '@platform/ui/hints';import { ScrubberField } from '@platform/ui/ScrubberField';-import { ChevronRightIcon } from 'lucide-react';+import { Select } from '@platform/ui/Select';+import { Slider } from '@platform/ui/Slider';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -72,29 +73,29 @@ const renderStyleVariantItem = (option: StyleVariantOption) => (/** The default weight is the one stop a drag can snap to; the track ends stand in for 0 and 2. */const WEIGHT_MARKS = [0, 1, 2];-const DEFAULT_WEIGHT = 1;--const BEGIN_END_MARKS = [- { label: '0%', value: 0 },- { label: '25%', value: 0.25 },- { label: '50%', value: 0.5 },- { label: '75%', value: 0.75 },- { label: '100%', value: 1 },-];+export const DEFAULT_REFERENCE_WEIGHT = 1;++const STEPS_FIELD_DISABLED_CSS = { opacity: 0.5 } as const;-const ADVANCED_TRIGGER_HOVER_STYLES = { color: 'fg' };-const COLLAPSIBLE_INDICATOR_OPEN_STYLES = { transform: 'rotate(90deg)' };+/**+ * Controls on a list row are backed with the widget's surface, as a concept row backs its weight: the row's+ * hover tint would otherwise wash out their transparent fills and faint borders, and their own hover fills with it.+ */+export const ControlSurface = ({ children, ...props }: { children: ReactNode } & Record<`data-${string}`, string>) => (+ <Box+ bg="var(--wb-field-surface, var(--chakra-colors-bg-subtle))"+ data-control-surface=""+ flex="1"+ minW="0"+ rounded="control"+ {...props}+ >+ {children}+ </Box>+);/** Tiny muted label row above a control, with optional right-aligned content. */-export const FieldHeader = ({- children,- hint,- label,-}: {- children?: ReactNode;- hint?: FeatureHintId;- label: string;-}) => {+const FieldHeader = ({ children, hint, label }: { children?: ReactNode; hint?: FeatureHintId; label: string }) => {const labelText = (<Text color="fg.muted" fontSize="xs" fontWeight="medium">{label}@@ -110,10 +111,47 @@ export const FieldHeader = ({};/**- * Render children inside Advanced. `strengthOnly` adapters (Anima) take a strength alone: no mode, and the scale+ * The adapter's weight, its one control on the row. `strengthOnly` adapters (Anima) take a strength alone, which* cannot go negative.*/-export const IPAdapterControls = ({+export const IPAdapterWeightField = ({+ config,+ disabled,+ onChange,+ strengthOnly = false,+}: {+ config: IPAdapterConfig;+ disabled: boolean;+ onChange: (config: GenerateReferenceImageConfig) => void;+ strengthOnly?: boolean;+}) => {+ const { t } = useTranslation();+ // Do not compare against captured drag-start values; returning to the start still needs a commit.+ const handleWeightChange = useCallback((weight: number) => onChange({ ...config, weight }), [config, onChange]);++ return (+ <ScrubberField+ defaultValue={DEFAULT_REFERENCE_WEIGHT}+ disabled={disabled}+ formatValue={formatWeight}+ hint={strengthOnly ? 'referenceImageStrength' : 'referenceImageWeight'}+ inputMin={strengthOnly ? 0 : -1}+ label={strengthOnly ? t('widgets.generate.strength') : t('widgets.generate.weight')}+ marks={WEIGHT_MARKS}+ max={2}+ min={0}+ step={0.05}+ value={config.weight}+ onChange={handleWeightChange}+ />+ );+};++/**+ * The adapter's settings under its row: mode (with the style variant for Style), the active step window, then+ * `children` (the model pickers). `strengthOnly` adapters (Anima) have no mode.+ */+export const IPAdapterSettings = ({children,config,disabled,@@ -127,9 +165,7 @@ export const IPAdapterControls = ({strengthOnly?: boolean;}) => {const { t } = useTranslation();- const [draftBeginEndStepPct, setDraftBeginEndStepPct] = useState<[number, number] | null>(null);const mode = getReferenceMode(config.method);- const beginEndStepPct = draftBeginEndStepPct ?? config.beginEndStepPct;const styleVariantCollection = useMemo(() =>createListCollection<StyleVariantOption>({@@ -146,23 +182,6 @@ export const IPAdapterControls = ({[config.method]);- // Do not compare against captured drag-start values; returning to the start still needs a commit.- const handleWeightChange = useCallback((weight: number) => onChange({ ...config, weight }), [config, onChange]);-- const commitBeginEndStepPct = useCallback(- (nextBeginEndStepPct: [number, number]) => {- setDraftBeginEndStepPct(null);-- if (- nextBeginEndStepPct[0] !== config.beginEndStepPct[0] ||- nextBeginEndStepPct[1] !== config.beginEndStepPct[1]- ) {- onChange({ ...config, beginEndStepPct: nextBeginEndStepPct });- }- },- [config, onChange]- );-const handleModeChange = useCallback(({ value }: SegmentGroup.ValueChangeDetails) => {if (!isReferenceMode(value)) {@@ -190,35 +209,26 @@ export const IPAdapterControls = ({[config, onChange]);- const handleStepsChange = useCallback(({ value }: SliderValueChangeDetails) => {- const begin = value[0];- const end = value[1];-- if (Number.isFinite(begin) && Number.isFinite(end)) {- setDraftBeginEndStepPct([begin as number, end as number]);- }- }, []);-- const handleStepsChangeEnd = useCallback(- ({ value }: SliderValueChangeDetails) => {- const begin = value[0];- const end = value[1];-- if (Number.isFinite(begin) && Number.isFinite(end)) {- commitBeginEndStepPct([begin as number, end as number]);+ const handleStepsChange = useCallback(+ (beginEndStepPct: [number, number]) => {+ if (beginEndStepPct[0] !== config.beginEndStepPct[0] || beginEndStepPct[1] !== config.beginEndStepPct[1]) {+ onChange({ ...config, beginEndStepPct });}},- [commitBeginEndStepPct]+ [config, onChange]);- const stepsAriaLabel = useMemo(() => [t('widgets.generate.activeSteps'), t('widgets.generate.activeSteps')], [t]);-return (- <Stack gap="2">+ <Stack gap="1.5">{strengthOnly ? null : (- <Stack gap="1">- <FieldHeader label={t('widgets.generate.mode')} />- <SegmentGroup.Root disabled={disabled} value={mode} w="full" onValueChange={handleModeChange}>+ <ControlSurface>+ <SegmentGroup.Root+ aria-label={t('widgets.generate.mode')}+ disabled={disabled}+ value={mode}+ w="full"+ onValueChange={handleModeChange}+ ><SegmentGroup.Indicator />{MODE_SEGMENTS.map((segment) => (<SegmentGroup.Item key={segment.value} flex="1" justifyContent="center" value={segment.value}>@@ -227,82 +237,95 @@ export const IPAdapterControls = ({</SegmentGroup.Item>))}</SegmentGroup.Root>- </Stack>+ </ControlSurface>)}+ {mode === 'style' && !strengthOnly ? (+ <ControlSurface>+ <Field disabled={disabled} label={t('widgets.generate.styleVariant')} labelPlacement="inside">+ <Select+ collection={styleVariantCollection}+ deselectable={false}+ renderItem={renderStyleVariantItem}+ value={styleVariantValue}+ w="full"+ onValueChange={handleStyleVariantChange}+ />+ </Field>+ </ControlSurface>+ ) : null}+ <ActiveStepsField disabled={disabled} value={config.beginEndStepPct} onChange={handleStepsChange} />+ {children}+ </Stack>+ );+};- <ScrubberField- defaultValue={DEFAULT_WEIGHT}+/**+ * The step window as one control: its label, a range slider and the window it covers on a single line, the same+ * height and frame as the weight scrubber above it. Every step of a drag commits, so the row's summary follows it.+ */+const ActiveStepsField = ({+ disabled,+ onChange,+ value,+}: {+ disabled: boolean;+ onChange: (value: [number, number]) => void;+ value: [number, number];+}) => {+ const { t } = useTranslation();+ const ariaLabel = useMemo(() => [t('widgets.generate.activeSteps'), t('widgets.generate.activeSteps')], [t]);+ const handleChange = useCallback(+ ({ value: next }: SliderValueChangeDetails) => {+ const begin = next[0];+ const end = next[1];++ if (begin !== undefined && end !== undefined && Number.isFinite(begin) && Number.isFinite(end)) {+ onChange([begin, end]);+ }+ },+ [onChange]+ );++ return (+ <HStack+ aria-disabled={disabled || undefined}+ bg="var(--wb-field-surface, var(--chakra-colors-bg-subtle))"+ borderColor="border"+ data-control-surface=""+ borderWidth="1px"+ css={disabled ? STEPS_FIELD_DISABLED_CSS : undefined}+ gap="3"+ h="control.md"+ minW="0"+ pe="3"+ ps={INSIDE_LABEL_INSET}+ role="group"+ rounded="control"+ >+ <FeatureHint hint="stepRange">+ <chakra.span flexShrink={0}>+ <FieldLabel>{t('widgets.generate.activeStepsShort')}</FieldLabel>+ </chakra.span>+ </FeatureHint>+ <Slider+ aria-label={ariaLabel}disabled={disabled}- formatValue={formatWeight}- hint={strengthOnly ? 'referenceImageStrength' : 'referenceImageWeight'}- inputMin={strengthOnly ? 0 : -1}- label={strengthOnly ? t('widgets.generate.strength') : t('widgets.generate.weight')}- marks={WEIGHT_MARKS}- max={2}+ flex="1"+ formatValue={formatPct}+ max={1}min={0}+ minW="0"step={0.05}- value={config.weight}- onChange={handleWeightChange}+ value={value}+ onValueChange={handleChange}/>-- <Collapsible.Root>- <Collapsible.Trigger- alignItems="center"- color="fg.muted"- display="flex"- fontSize="xs"- fontWeight="medium"- gap="1"- _hover={ADVANCED_TRIGGER_HOVER_STYLES}- >- <Collapsible.Indicator- _open={COLLAPSIBLE_INDICATOR_OPEN_STYLES}- transition="transform var(--wb-motion-duration-slow)"- >- <ChevronRightIcon size="12" />- </Collapsible.Indicator>- {t('widgets.generate.advanced')}- </Collapsible.Trigger>- <Collapsible.Content>- <Stack borderTopWidth="1px" gap="2" mt="2" pt="2">- {children}- {mode === 'style' && !strengthOnly ? (- <Stack gap="1">- <FieldHeader label={t('widgets.generate.styleVariant')} />- <Select- collection={styleVariantCollection}- deselectable={false}- disabled={disabled}- renderItem={renderStyleVariantItem}- value={styleVariantValue}- w="full"- onValueChange={handleStyleVariantChange}- />- </Stack>- ) : null}- <Stack gap="1">- <FieldHeader hint="stepRange" label={t('widgets.generate.activeSteps')}>- <Text color="fg.subtle" fontFamily="mono" fontSize="xs">- {formatPct(beginEndStepPct[0])} – {formatPct(beginEndStepPct[1])}- </Text>- </FieldHeader>- <Slider- aria-label={stepsAriaLabel}- disabled={disabled}- formatValue={formatPct}- marks={BEGIN_END_MARKS}- max={1}- min={0}- step={0.05}- value={beginEndStepPct}- onValueChange={handleStepsChange}- onValueChangeEnd={handleStepsChangeEnd}- />- </Stack>- </Stack>- </Collapsible.Content>- </Collapsible.Root>- </Stack>+ <Text flexShrink={0} fontSize="md" fontVariantNumeric="tabular-nums">+ {t('widgets.generate.stepRangeValue', {+ begin: Math.round(value[0] * 100),+ end: Math.round(value[1] * 100),+ })}+ </Text>+ </HStack>);};@@ -315,6 +338,7 @@ export const ClipVisionSelect = ({disabled: boolean;onChange: (config: GenerateReferenceImageConfig) => void;}) => {+ const { t } = useTranslation();const [draftClipVisionModel, setDraftClipVisionModel] = useState<ClipVisionModel | null>(null);const clipVisionModel = draftClipVisionModel ?? config.clipVisionModel;const selectValue = useMemo(() => [clipVisionModel], [clipVisionModel]);@@ -338,6 +362,7 @@ export const ClipVisionSelect = ({return (<Select+ aria-label={t('widgets.generate.clipVisionModel')}collection={CLIP_VISION_COLLECTION}deselectable={false}disabled={disabled}@@ -352,10 +377,13 @@ export const ClipVisionSelect = ({export const FluxReduxControls = <T extends { imageInfluence: FluxReduxImageInfluence; type: 'flux_redux' }>({config,disabled,+ labelPlacement = 'outside',onChange,}: {config: T;disabled: boolean;+ /** `inside` puts the label in the select's own box, for a single-line row. */+ labelPlacement?: 'inside' | 'outside';onChange: (config: T) => void;}) => {const { t } = useTranslation();@@ -377,16 +405,29 @@ export const FluxReduxControls = <T extends { imageInfluence: FluxReduxImageInfl[config, onChange]);- return (+ const select = (+ <Select+ collection={FLUX_REDUX_IMAGE_INFLUENCE_COLLECTION}+ deselectable={false}+ disabled={disabled}+ value={imageInfluenceValue}+ w="full"+ onValueChange={handleValueChange}+ />+ );++ return labelPlacement === 'inside' ? (+ <Field+ disabled={disabled}+ hint="imageInfluence"+ label={t('widgets.generate.imageInfluence')}+ labelPlacement="inside"+ >+ {select}+ </Field>+ ) : (<Field disabled={disabled} hint="imageInfluence" label={t('widgets.generate.imageInfluence')}>- <Select- collection={FLUX_REDUX_IMAGE_INFLUENCE_COLLECTION}- deselectable={false}- disabled={disabled}- value={imageInfluenceValue}- w="full"- onValueChange={handleValueChange}- />+ {select}</Field>);};@@ -400,7 +441,7 @@ const KREA2_MODE_SEGMENTS = [/*** Switches a Krea-2 reference between Style and Edit; the image stays and Style restarts at its default strength. It- * stays live while the card is off, so switched-off cards can be turned into the set they will join before they run.+ * stays live while the row is off, so switched-off references can be turned into the set they will join before they run.*/export const Krea2ReferenceModeControl = ({config,@@ -429,15 +470,22 @@ export const Krea2ReferenceModeControl = ({return (<Stack gap="1"><FieldHeader hint="krea2ReferenceMode" label={t('widgets.generate.mode')} />- <SegmentGroup.Root aria-label={t('widgets.generate.mode')} value={mode} w="full" onValueChange={handleModeChange}>- <SegmentGroup.Indicator />- {KREA2_MODE_SEGMENTS.map((segment) => (- <SegmentGroup.Item key={segment.value} flex="1" justifyContent="center" value={segment.value}>- <SegmentGroup.ItemText fontSize="xs">{t(segment.labelKey)}</SegmentGroup.ItemText>- <SegmentGroup.ItemHiddenInput />- </SegmentGroup.Item>- ))}- </SegmentGroup.Root>+ <ControlSurface>+ <SegmentGroup.Root+ aria-label={t('widgets.generate.mode')}+ value={mode}+ w="full"+ onValueChange={handleModeChange}+ >+ <SegmentGroup.Indicator />+ {KREA2_MODE_SEGMENTS.map((segment) => (+ <SegmentGroup.Item key={segment.value} flex="1" justifyContent="center" value={segment.value}>+ <SegmentGroup.ItemText fontSize="xs">{t(segment.labelKey)}</SegmentGroup.ItemText>+ <SegmentGroup.ItemHiddenInput />+ </SegmentGroup.Item>+ ))}+ </SegmentGroup.Root>+ </ControlSurface></Stack>);};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageRow.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageRow.tsxnew file mode 100644index 0000000000..710aa04545--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/ReferenceImageRow.tsx@@ -0,0 +1,1132 @@+/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- ListItem slots take JSX; the React Compiler memoizes them. */+import type { GenerationModelCatalogItem as ModelConfig } from '@features/generation/contracts';+import type { GenerationIssue } from '@features/generation/core/generationIssues';+import type {+ GenerateModelConfig,+ GenerateReferenceImage,+ GenerateReferenceImageAsset,+ GenerateReferenceImageConfig,+} from '@features/generation/core/types';+import type { TFunction } from 'i18next';+import type { ChangeEvent, CSSProperties, FocusEvent, KeyboardEvent, MouseEvent, ReactElement } from 'react';++import {+ Badge,+ Box,+ chakra,+ Flex,+ HStack,+ Icon,+ Input,+ Kbd,+ Menu,+ Portal,+ Stack,+ VisuallyHidden,+} from '@chakra-ui/react';+import { FindInGalleryButton } from '@features/gallery/mediaSlot';+import { isStrengthOnlyIPAdapterBase } from '@features/generation/core/baseGenerationPolicies';+import { getEffectiveReferenceImage } from '@features/generation/core/referenceImage';+import { DEFAULT_KREA2_STYLE_STRENGTH } from '@features/generation/core/settings';+import { getReferenceImageUrls } from '@features/generation/data/referenceImageUrls';+import { GenerationModelSelect as ModelSelect } from '@features/generation/ui/GenerationUiContext';+import { GenerateFieldContextMenu } from '@features/generation/ui/shared/GenerateFieldContextMenu';+import { type GenerateIssueAction, GenerateIssueButton } from '@features/generation/ui/shared/GenerateIssues';+import { GenerateRowSwitch } from '@features/generation/ui/shared/GenerateToggleSwitch';+import { canCopyText, copyText } from '@platform/browser/clipboard';+import { isImeComposing } from '@platform/browser/imeComposition';+import { useExitPresence, useExitRetainedValue } from '@platform/react/useExitRetainedValue';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Button, IconButton } from '@platform/ui/Button';+import { Field } from '@platform/ui/Field';+import { type ListContextMenuAnchor, ListItem } from '@platform/ui/list/ListItem';+import { MenuActionItem, MenuContent, useContextMenu } from '@platform/ui/Menu';+import { toaster } from '@platform/ui/toaster';+import { Tooltip } from '@platform/ui/Tooltip';+import {+ ArrowDownIcon,+ ArrowUpIcon,+ CheckIcon,+ ChevronDownIcon,+ CropIcon,+ CrosshairIcon,+ EllipsisIcon,+ ImageIcon,+ PencilIcon,+ PowerIcon,+ PowerOffIcon,+ RulerIcon,+ Trash2Icon,+} from 'lucide-react';+import { memo, useCallback, useId, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { formatWeight, getModeLabelKey } from './referenceImageConfig';+import {+ ClipVisionSelect,+ ControlSurface,+ DEFAULT_REFERENCE_WEIGHT,+ FluxReduxControls,+ IPAdapterSettings,+ IPAdapterWeightField,+ Krea2ReferenceModeControl,+ Krea2StyleReferenceControls,+} from './ReferenceImageControls';+import { ReferenceImageCropDialog } from './ReferenceImageCropDialog';++/** Reference image config variants that carry a selectable model. */+type ModelBackedConfig = Extract<+ GenerateReferenceImageConfig,+ { type: 'ip_adapter' | 'flux_redux' | 'flux_kontext_reference_image' }+>;++const PRIMARY_SELECTOR = '[data-list-primary]';+const FLUX_MODEL_TYPES = ['ip_adapter', 'flux_redux'];+const DEFAULT_MODEL_TYPES = ['ip_adapter'];++/** The model types a reference's picker offers on a base: adapters, and Redux on FLUX. */+export const getReferenceModelTypes = (base: string | undefined): string[] =>+ base === 'flux' ? FLUX_MODEL_TYPES : DEFAULT_MODEL_TYPES;+const COVER_IMG_STYLE: CSSProperties = { display: 'block', height: '100%', objectFit: 'cover', width: '100%' };+/** An off reference keeps its image recognizable but plainly not in use. */+const OFF_IMG_STYLE: CSSProperties = { ...COVER_IMG_STYLE, filter: 'grayscale(1) brightness(0.75)' };+const PROMPT_TAG_COPIED_MS = 1500;+const CHEVRON_OPEN_CSS = { transform: 'rotate(180deg)' } as const;+const MODEL_SELECT_SELECTOR = '[data-reference-model] button, [data-reference-model] input:not([type="hidden"])';+/** Issues fixed by choosing the reference's model; their popover offers that beside Turn off. */+const MODEL_ISSUE_KEYS = new Set(+ ['referenceImageNeedsIpAdapter', 'referenceImageNeedsRedux', 'referenceModelNotInstalled'].map(+ (key) => `widgets.generate.issues.${key}`+ )+);+const INDEX_PLACEHOLDER = '\u0000';++/**+ * Whether a name reads as some position's default ("Reference image 7"), in the active language and any case; null+ * when the locale's template cannot be matched safely (only the number, or a number formatter that drops the+ * placeholder), and then only a row's own default is recognized.+ */+export const getPositionalDefaultNameTest = (t: TFunction): ((name: string) => boolean) | null => {+ const parts = t('widgets.generate.referenceImageNumbered', { index: INDEX_PLACEHOLDER }).split(INDEX_PLACEHOLDER);+ const [before = '', after = ''] = parts.map((part) => part.trim());++ if (parts.length !== 2 || (before === '' && after === '')) {+ return null;+ }++ const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const pattern = new RegExp(`^${escape(before)}\\s*\\d+\\s*${escape(after)}$`, 'iu');++ return (name) => pattern.test(name.trim());+};++const sameName = (left: string, right: string): boolean =>+ left.trim().toLocaleLowerCase() === right.trim().toLocaleLowerCase();++/** The families with a control on the row; the rest are a plain row whose image actions live in its menu. */+const hasRowControl = (config: GenerateReferenceImageConfig): boolean =>+ config.type === 'ip_adapter' ||+ config.type === 'flux_redux' ||+ config.type === 'flux_kontext_reference_image' ||+ config.type === 'krea2_reference_image' ||+ config.type === 'krea2_edit_reference_image';++/** The second line: what the reference does, read live from its settings, in the words its controls use. */+export const describeReferenceImage = (+ config: GenerateReferenceImageConfig,+ strengthOnly: boolean,+ t: TFunction+): string => {+ if (!config.image) {+ return t('widgets.generate.referenceImageNoImage');+ }++ const effective = getEffectiveReferenceImage(config.image);+ const size = t('widgets.generate.referenceImageSize', { height: effective.height, width: effective.width });+ const modelName = (model: { name: string } | null) => model?.name ?? t('widgets.generate.referenceImageNoModel');++ switch (config.type) {+ case 'ip_adapter': {+ const [begin, end] = config.beginEndStepPct;+ const range =+ begin === 0 && end === 1+ ? null+ : t('widgets.generate.stepRangeValue', { begin: Math.round(begin * 100), end: Math.round(end * 100) });++ return [strengthOnly ? null : t(getModeLabelKey(config.method)), range, modelName(config.model)]+ .filter(Boolean)+ .join(' · ');+ }+ case 'flux_redux':+ return modelName(config.model);+ case 'flux_kontext_reference_image':+ return size;+ case 'krea2_reference_image':+ return t('widgets.generate.modeStyle');+ case 'krea2_edit_reference_image':+ return `${t('widgets.generate.modeEdit')} · ${size}`;+ default:+ return config.image.crop ? `${size} · ${t('widgets.generate.referenceImageCropped')}` : size;+ }+};++export interface ReferenceImageRowProps {+ count: number;+ /**+ * An installed model the row's picker could offer. Without one, an issue asking for a model offers the Model+ * Manager instead of a picker with nothing in it.+ */+ hasModelChoice?: boolean;+ /** Opens Add Models filtered to a model type, for an issue no installed model fixes. */+ onOpenModelManager?: (modelType: string) => void;+ index: number;+ /**+ * False lists the row dimmed, badged and inert: the selected model takes no references, and the list above it says+ * so with its one way out.+ */+ isSupported?: boolean;+ /** How the prompt names this reference, for models that address references by tag. */+ promptTag?: string;+ referenceImage: GenerateReferenceImage;+ selectedModel: GenerateModelConfig | undefined;+ onFindInGallery: (imageName: string) => void;+ onMove: (id: string, direction: -1 | 1) => void;+ onPatch: (id: string, patch: Partial<GenerateReferenceImage>) => void;+ onRemove: (id: string) => void;+ /** A name that is empty, or reads as a positional default (`isDefaultName`), clears the custom name. */+ onRename: (id: string, name: string, isDefaultName: (name: string) => boolean) => void;+ onUseSize: (image: GenerateReferenceImageAsset) => void;+}++/**+ * One reference image as a list row, the same construction as a concept row: its image tile, name and live summary,+ * a switch and a menu, with its one main control on the row and the rest of its settings under a disclosure. The+ * row's button opens the menu (Enter, Space, right-click); F2 or a double-click renames; Right and Left open and+ * close the settings; Alt+Up and Alt+Down move it; Delete removes it.+ */+const ReferenceImageRowBase = ({+ count,+ hasModelChoice = true,+ onOpenModelManager,+ index,+ isSupported = true,+ onFindInGallery,+ onMove,+ onPatch,+ onRemove,+ onRename,+ onUseSize,+ promptTag,+ referenceImage,+ selectedModel,+}: ReferenceImageRowProps) => {+ const { t } = useTranslation();+ const { config, id, isEnabled } = referenceImage;+ const image = config.image;+ const selectedBase = selectedModel?.base;+ const strengthOnly = isStrengthOnlyIPAdapterBase(selectedBase);+ const defaultName = t('widgets.generate.referenceImageNumbered', { index: index + 1 });+ const name = referenceImage.name ?? defaultName;+ const hasSettings = isSupported && hasRowControl(config);+ // Closed until asked for: the chevron, Right, or an issue's Choose model.+ const [isOpen, setIsOpen] = useState(false);+ const showSettings = hasSettings && isOpen;+ const [isRenaming, setIsRenaming] = useState(false);+ const [renameStartDefault, setRenameStartDefault] = useState(defaultName);+ const [isCropOpen, setIsCropOpen] = useState(false);+ const cropDialog = useExitPresence(isCropOpen);+ const menu = useContextMenu();+ // Rename from the menu: the menu closing must not hand focus back to the row, which would end the rename at once.+ const keepFocusOnClose = useRef(false);+ const openMenu = useCallback(+ (anchor: ListContextMenuAnchor) => {+ keepFocusOnClose.current = false;+ menu.open({+ ...anchor,+ restoreFocus: () => {+ if (!keepFocusOnClose.current) {+ anchor.restoreFocus();+ }+ },+ });+ },+ [menu]+ );+ // Kept through the exit animation: the anchor clears the moment the menu closes.+ const { release: releaseMenu, value: shownAnchor } = useExitRetainedValue(menu.anchor);+ const rowRef = useRef<HTMLDivElement>(null);+ const settingsId = useId();+ const canMoveUp = index > 0;+ const canMoveDown = index < count - 1;+ const originalImageName = image?.original.image.image_name;++ /** Moving or re-rendering the row's button can drop focus; it goes back to the row once the change has rendered. */+ const focusRowSoon = useCallback(() => {+ requestAnimationFrame(() => rowRef.current?.querySelector<HTMLElement>(PRIMARY_SELECTOR)?.focus());+ }, []);+ const changeConfig = useCallback(+ (nextConfig: GenerateReferenceImageConfig) => onPatch(id, { config: nextConfig }),+ [id, onPatch]+ );+ // A Krea-2 mode switch moves the mode control between the row (Edit) and its settings (Style): the settings open so+ // it stays in view, and keyboard focus follows it to its new place.+ const changeKrea2Mode = useCallback(+ (nextConfig: GenerateReferenceImageConfig) => {+ const group = document.activeElement?.closest('[data-scope="segment-group"]');+ const hadFocus = group !== null && group !== undefined && rowRef.current?.contains(group) === true;++ if (nextConfig.type === 'krea2_reference_image') {+ setIsOpen(true);+ }++ changeConfig(nextConfig);++ if (hadFocus) {+ requestAnimationFrame(() =>+ rowRef.current+ ?.querySelector<HTMLElement>('[data-scope="segment-group"] input[type="radio"]:checked')+ ?.focus()+ );+ }+ },+ [changeConfig]+ );+ const setEnabled = useCallback((nextEnabled: boolean) => onPatch(id, { isEnabled: nextEnabled }), [id, onPatch]);+ const move = useCallback(+ (direction: -1 | 1) => {+ if (direction === -1 ? !canMoveUp : !canMoveDown) {+ return;+ }++ onMove(id, direction);+ focusRowSoon();+ },+ [canMoveDown, canMoveUp, focusRowSoon, id, onMove]+ );+ // The next reference takes focus, else the previous one, else the add row: never the page.+ const remove = useCallback(() => {+ const row = rowRef.current;+ const list = row?.closest('[role="list"]');+ const rows = list ? [...list.querySelectorAll<HTMLElement>('[data-reference-image-id]')] : [];+ const at = row ? rows.indexOf(row) : -1;+ const neighbour = rows[at + 1] ?? rows[at - 1];+ const target =+ neighbour?.querySelector<HTMLElement>(PRIMARY_SELECTOR) ??+ list?.querySelector<HTMLElement>('[data-reference-add]');++ onRemove(id);+ requestAnimationFrame(() => target?.focus());+ }, [id, onRemove]);+ const startRename = useCallback(() => {+ if (isSupported) {+ setRenameStartDefault(defaultName);+ setIsRenaming(true);+ }+ }, [defaultName, isSupported]);+ const renameFromMenu = useCallback(() => {+ keepFocusOnClose.current = true;+ startRename();+ }, [startRename]);+ const endRename = useCallback(+ (refocus: boolean) => {+ setIsRenaming(false);++ if (refocus) {+ focusRowSoon();+ }+ },+ [focusRowSoon]+ );+ // This row's default stores no name, so it keeps following the row's position. The default when editing began+ // counts too: a reorder from another tab while the field is open must not store the untouched text as a name.+ const isPositionalDefault = useMemo(() => getPositionalDefaultNameTest(t), [t]);+ const [renameError, setRenameError] = useState<string | null>(null);+ const renameErrorId = useId();+ // Another position's default would make two rows read alike: the field says so and keeps the name it was given.+ const validateName = useCallback(+ (draft: string): string | null => {+ const name = draft.trim();++ return name !== '' &&+ !sameName(name, defaultName) &&+ !sameName(name, renameStartDefault) &&+ isPositionalDefault?.(name) === true+ ? t('widgets.generate.referenceImageNameReserved', { name })+ : null;+ },+ [defaultName, isPositionalDefault, renameStartDefault, t]+ );+ const commitName = useCallback(+ (draft: string, refocus: boolean) => {+ setRenameError(null);+ endRename(refocus);+ onRename(id, draft, (name) => sameName(name, defaultName) || sameName(name, renameStartDefault));+ },+ [defaultName, endRename, id, onRename, renameStartDefault]+ );+ const cancelRename = useCallback(+ (refocus: boolean) => {+ setRenameError(null);+ endRename(refocus);+ },+ [endRename]+ );+ const openCrop = useCallback(() => setIsCropOpen(true), []);+ const closeCrop = useCallback(() => setIsCropOpen(false), []);+ const handleCrop = useCallback(+ (croppedImage: GenerateReferenceImageAsset) => changeConfig({ ...config, image: croppedImage }),+ [changeConfig, config]+ );+ const useSize = useCallback(() => {+ if (image) {+ onUseSize(image);+ }+ }, [image, onUseSize]);+ // Reveal original media; crop intermediates have no gallery cell.+ const findInGallery = useCallback(() => {+ if (originalImageName !== undefined) {+ onFindInGallery(originalImageName);+ }+ }, [onFindInGallery, originalImageName]);+ const openMenuFrom = useCallback(+ (event: MouseEvent<HTMLButtonElement>) => {+ const button = event.currentTarget;+ const rect = button.getBoundingClientRect();++ openMenu({+ focusTarget: () => (button.isConnected ? button : null),+ restoreFocus: () => button.focus(),+ x: rect.right,+ y: rect.bottom,+ });+ },+ [openMenu]+ );++ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLDivElement>) => {+ const target = event.target as HTMLElement;++ // Only the row's own button: its controls and fields keep their keys.+ if (+ !isSupported ||+ !target.matches(PRIMARY_SELECTOR) ||+ target.closest('[data-reference-image-id]') !== rowRef.current+ ) {+ return;+ }++ const plain = !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey;++ if (event.key === 'F2' && plain) {+ startRename();+ } else if (event.altKey && !event.ctrlKey && !event.metaKey && event.key === 'ArrowUp') {+ move(-1);+ } else if (event.altKey && !event.ctrlKey && !event.metaKey && event.key === 'ArrowDown') {+ move(1);+ } else if (plain && event.key === 'ArrowRight' && hasSettings) {+ setIsOpen(true);+ } else if (plain && event.key === 'ArrowLeft' && hasSettings) {+ setIsOpen(false);+ } else if (plain && event.key === 'Delete') {+ // A held key repeats: only the first press removes, so holding Delete cannot empty the list.+ if (!event.repeat) {+ remove();+ }+ } else {+ return;+ }++ event.preventDefault();+ event.stopPropagation();+ },+ [hasSettings, isSupported, move, remove, startRename]+ );+ const handleDoubleClick = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ const primary = (event.target as HTMLElement).closest(PRIMARY_SELECTOR);++ if (!isRenaming && primary && primary.closest('[data-reference-image-id]') === rowRef.current) {+ startRename();+ }+ },+ [isRenaming, startRename]+ );+ const toggleSettings = useCallback(() => setIsOpen((open) => !open), []);+ // An issue fixed by choosing a model: open the settings that hold the picker and focus it once it has rendered and+ // the closing popover has handed focus back.+ const chooseModel = useCallback(() => {+ setIsOpen(true);+ requestAnimationFrame(() =>+ requestAnimationFrame(() => rowRef.current?.querySelector<HTMLElement>(MODEL_SELECT_SELECTOR)?.focus())+ );+ }, []);+ const modelType = config.type === 'flux_redux' ? 'flux_redux' : 'ip_adapter';+ const chooseModelAction = useMemo<GenerateIssueAction | null>(+ () =>+ hasModelChoice+ ? { label: t('widgets.generate.referenceImageChooseModel'), onSelect: chooseModel }+ : onOpenModelManager+ ? { label: t('widgets.generate.openModelManager'), onSelect: () => onOpenModelManager(modelType) }+ : null,+ [chooseModel, hasModelChoice, modelType, onOpenModelManager, t]+ );+ const getIssueAction = useCallback(+ (issue: GenerationIssue) => (issue.messageKey && MODEL_ISSUE_KEYS.has(issue.messageKey) ? chooseModelAction : null),+ [chooseModelAction]+ );++ const modelSelect = (modelConfig: ModelBackedConfig) => (+ <ReferenceModelSelect+ config={modelConfig}+ disabled={!isEnabled}+ relatedTo={selectedModel?.key ?? null}+ selectedBase={selectedBase}+ strengthOnly={strengthOnly}+ onConfigChange={changeConfig}+ />+ );+ const weightMenu = (label: string, value: number, defaultValue: number, onReset: () => void, field: ReactElement) => (+ <GenerateFieldContextMenu+ copyValue={() => formatWeight(value)}+ fieldLabel={label}+ isAtDefault={value === defaultValue || !isEnabled}+ resetLabel={t('widgets.generate.resetToDefault')}+ onReset={onReset}+ >+ {field}+ </GenerateFieldContextMenu>+ );++ let rowControl: ReactElement | null = null;+ let settings: ReactElement | null = null;++ switch (config.type) {+ case 'ip_adapter':+ rowControl = weightMenu(+ strengthOnly ? t('widgets.generate.strength') : t('widgets.generate.weight'),+ config.weight,+ DEFAULT_REFERENCE_WEIGHT,+ () => changeConfig({ ...config, weight: DEFAULT_REFERENCE_WEIGHT }),+ <IPAdapterWeightField+ config={config}+ disabled={!isEnabled}+ strengthOnly={strengthOnly}+ onChange={changeConfig}+ />+ );+ settings = (+ <IPAdapterSettings+ key={config.model?.key ?? 'no-model'}+ config={config}+ disabled={!isEnabled}+ strengthOnly={strengthOnly}+ onChange={changeConfig}+ >+ {modelSelect(config)}+ </IPAdapterSettings>+ );+ break;+ case 'flux_redux':+ rowControl = (+ <FluxReduxControls config={config} disabled={!isEnabled} labelPlacement="inside" onChange={changeConfig} />+ );+ settings = modelSelect(config);+ break;+ case 'flux_kontext_reference_image':+ rowControl = modelSelect(config);+ break;+ case 'krea2_reference_image':+ rowControl = weightMenu(+ t('widgets.generate.styleStrength'),+ config.styleStrength,+ DEFAULT_KREA2_STYLE_STRENGTH,+ () => changeConfig({ ...config, styleStrength: DEFAULT_KREA2_STYLE_STRENGTH }),+ <Krea2StyleReferenceControls config={config} disabled={!isEnabled} onChange={changeConfig} />+ );+ settings = <Krea2ReferenceModeControl config={config} onChange={changeKrea2Mode} />;+ break;+ case 'krea2_edit_reference_image':+ rowControl = <Krea2ReferenceModeControl config={config} onChange={changeKrea2Mode} />;+ break;+ default:+ break;+ }++ const imageActions = image ? (+ <HStack gap="0.5">+ <IconButton+ aria-label={t('widgets.generate.cropReferenceImageNamed', { name })}+ color="fg.muted"+ disabled={!isEnabled}+ size="sm"+ tooltip={t('common.crop')}+ variant="ghost"+ onClick={openCrop}+ >+ <CropIcon />+ </IconButton>+ <IconButton+ aria-label={t('widgets.generate.useSizeOfReferenceImage', { name })}+ color="fg.muted"+ disabled={!isEnabled || !selectedModel}+ size="sm"+ tooltip={t('widgets.generate.useSize')}+ variant="ghost"+ onClick={useSize}+ >+ <RulerIcon />+ </IconButton>+ <FindInGalleryButton color="fg.muted" name={originalImageName} variant="ghost" onFind={findInGallery} />+ </HStack>+ ) : null;++ const detail = hasSettings ? (+ <Stack gap="1.5">+ <HStack gap="1" minW="0">+ {/* The Krea-2 mode control backs its own segments under its label. */}+ {config.type === 'krea2_edit_reference_image' ? (+ <Box flex="1" minW="0">+ {rowControl}+ </Box>+ ) : (+ <ControlSurface>{rowControl}</ControlSurface>+ )}+ <IconButton+ aria-controls={settingsId}+ aria-expanded={showSettings}+ aria-label={t('widgets.generate.referenceImageSettings', { name })}+ color="fg.muted"+ size="sm"+ tooltip={t('widgets.generate.referenceImageSettings', { name })}+ variant="ghost"+ onClick={toggleSettings}+ >+ <Box+ asChild+ css={showSettings ? CHEVRON_OPEN_CSS : undefined}+ transition="transform var(--wb-motion-duration-fast)"+ >+ <ChevronDownIcon />+ </Box>+ </IconButton>+ </HStack>+ {showSettings ? (+ <Stack gap="1.5" id={settingsId}>+ {settings}+ {imageActions}+ </Stack>+ ) : null}+ </Stack>+ ) : undefined;++ return (+ <Box+ ref={rowRef}+ data-reference-image-id={id}+ role="listitem"+ onDoubleClick={handleDoubleClick}+ onKeyDown={handleKeyDown}+ >+ {/* Naming the group gives the row's controls their reference's context ("Weight", "Hero pose"). An off row+ stays at full opacity, so it is still readable; its text recedes and its tile greys. */}+ <Box aria-label={name} color={isEnabled ? undefined : 'fg.subtle'} role="group">+ <ListItem+ actions={+ <Flex align="center" gap="1">+ {promptTag ? <PromptTagButton tag={promptTag} /> : null}+ {/* A reference that blocks Invoke says so beside its switch, with the fix one press away. */}+ <GenerateIssueButton+ field="referenceImage"+ getAction={getIssueAction}+ referenceImageId={id}+ section="guidance"+ />+ <GenerateRowSwitch+ checked={isEnabled}+ label={+ isEnabled+ ? t('widgets.generate.disableReferenceImageNamed', { name })+ : t('widgets.generate.enableReferenceImageNamed', { name })+ }+ onCheckedChange={setEnabled}+ />+ <IconButton+ aria-expanded={menu.anchor !== null}+ aria-haspopup="menu"+ aria-label={t('widgets.generate.referenceImageMoreActions', { name })}+ color="fg.muted"+ size="sm"+ tooltip={t('widgets.generate.referenceImageMoreActions', { name })}+ variant="ghost"+ onClick={openMenuFrom}+ >+ <EllipsisIcon />+ </IconButton>+ </Flex>+ }+ badges={+ isSupported ? undefined : (+ <Badge colorPalette="orange" flexShrink={0} variant="surface">+ {t('widgets.generate.incompatible')}+ </Badge>+ )+ }+ density="snug"+ description={+ renameError ? (+ <chakra.span color="fg.error" display="block" id={renameErrorId} minW="0" role="alert">+ {renameError}+ </chakra.span>+ ) : (+ <chakra.span color={isEnabled ? 'fg.muted' : 'fg.subtle'} display="block" minW="0" truncate>+ {describeReferenceImage(config, strengthOnly, t)}+ </chakra.span>+ )+ }+ detail={detail}+ isDisabled={!isSupported}+ isMenuOpen={menu.anchor !== null}+ leading={<ReferenceImageTile image={image} isEnabled={isEnabled} />}+ role="presentation"+ title={name}+ titleEditor={+ isRenaming ? (+ <ReferenceImageNameField+ errorId={renameError ? renameErrorId : undefined}+ initialName={name}+ validate={validateName}+ onCancel={cancelRename}+ onCommit={commitName}+ onErrorChange={setRenameError}+ />+ ) : undefined+ }+ titleTruncate="end"+ onContextMenu={openMenu}+ />+ </Box>+ <Menu.Root+ lazyMount+ open={menu.anchor !== null}+ positioning={{+ getAnchorRect: () => (shownAnchor ? { height: 1, width: 1, x: shownAnchor.x, y: shownAnchor.y } : null),+ placement: 'bottom-end',+ }}+ unmountOnExit+ onExitComplete={releaseMenu}+ onOpenChange={(event) => {+ if (!event.open) {+ menu.close();+ }+ }}+ onRequestDismiss={menu.onRequestDismiss}+ >+ <Portal>+ <Menu.Positioner>+ {shownAnchor ? (+ <MenuContent minW="12rem">+ <MenuActionItem+ hint={t('widgets.generate.referenceImageMenu.renameHint')}+ icon={PencilIcon}+ label={t('widgets.generate.referenceImageMenu.rename')}+ // F2 reads the same on every platform, so it needs none of the workbench's key formatting.+ shortcut={<Kbd textTransform="lowercase">F2</Kbd>}+ value="rename"+ onSelect={renameFromMenu}+ />+ <MenuActionItem+ disabled={!image || !isEnabled}+ icon={CropIcon}+ label={t('widgets.generate.referenceImageMenu.crop')}+ value="crop"+ onSelect={openCrop}+ />+ <MenuActionItem+ disabled={!image || !isEnabled || !selectedModel}+ icon={RulerIcon}+ label={t('widgets.generate.useSize')}+ value="use-size"+ onSelect={useSize}+ />+ <MenuActionItem+ disabled={!image}+ icon={CrosshairIcon}+ label={t('widgets.gallery.findInGallery')}+ value="find-in-gallery"+ onSelect={findInGallery}+ />+ <Menu.Separator />+ <MenuActionItem+ disabled={!canMoveUp}+ icon={ArrowUpIcon}+ label={t('widgets.generate.referenceImageMenu.moveUp')}+ value="move-up"+ onSelect={() => move(-1)}+ />+ <MenuActionItem+ disabled={!canMoveDown}+ icon={ArrowDownIcon}+ label={t('widgets.generate.referenceImageMenu.moveDown')}+ value="move-down"+ onSelect={() => move(1)}+ />+ <MenuActionItem+ icon={isEnabled ? PowerOffIcon : PowerIcon}+ label={+ isEnabled+ ? t('widgets.generate.referenceImageMenu.turnOff')+ : t('widgets.generate.referenceImageMenu.turnOn')+ }+ value="toggle"+ onSelect={() => setEnabled(!isEnabled)}+ />+ <Menu.Separator />+ <MenuActionItem+ icon={Trash2Icon}+ label={t('widgets.generate.referenceImageMenu.remove')}+ tone="danger"+ value="remove"+ onSelect={remove}+ />+ </MenuContent>+ ) : null}+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ {image && cropDialog.isMounted ? (+ <ReferenceImageCropDialog+ key={cropDialog.generation}+ image={image}+ isOpen={cropDialog.isOpen}+ onApply={handleCrop}+ onClose={closeCrop}+ onExitComplete={cropDialog.release}+ />+ ) : null}+ </Box>+ );+};++export const ReferenceImageRow = memo(ReferenceImageRowBase);++/** The image as it will be used (the crop, if cropped), marked when cropped and greyed while the reference is off. */+const ReferenceImageTile = ({+ image,+ isEnabled,+}: {+ image: GenerateReferenceImageAsset | null;+ isEnabled: boolean;+}) => {+ const urls = image ? getReferenceImageUrls(image) : null;++ return (+ <Box+ alignItems="center"+ bg="bg.muted"+ borderColor="border"+ borderWidth="1px"+ boxSize="9"+ color="fg.subtle"+ display="flex"+ flexShrink={0}+ justifyContent="center"+ overflow="hidden"+ position="relative"+ rounded="sm"+ >+ {urls ? (+ <img alt="" draggable={false} src={urls.thumbnailUrl} style={isEnabled ? COVER_IMG_STYLE : OFF_IMG_STYLE} />+ ) : (+ <Icon as={ImageIcon} boxSize="4" />+ )}+ {image?.crop ? (+ <Box+ alignItems="center"+ bg="bg/80"+ bottom="0"+ color="fg"+ data-cropped=""+ display="flex"+ insetInlineEnd="0"+ justifyContent="center"+ position="absolute"+ roundedTopLeft="sm"+ boxSize="3.5"+ >+ <Icon as={CropIcon} boxSize="2.5" />+ </Box>+ ) : null}+ </Box>+ );+};++/**+ * Renames in the title's place, as a layer row does: Enter or moving focus away commits, Escape cancels, and Enter or+ * Escape hand focus back to the row. A name left empty, or set to the default, clears the custom name.+ */+const ReferenceImageNameField = ({+ errorId,+ initialName,+ onCancel,+ onCommit,+ onErrorChange,+ validate,+}: {+ /** The message saying why the name cannot be kept, shown in the row's second line while it applies. */+ errorId: string | undefined;+ initialName: string;+ onCancel: (refocus: boolean) => void;+ onCommit: (name: string, refocus: boolean) => void;+ onErrorChange: (error: string | null) => void;+ /** Why a draft cannot be kept, or null. Enter keeps the field open on it; leaving the field keeps the old name. */+ validate: (draft: string) => string | null;+}) => {+ const { t } = useTranslation();+ const input = useRef<HTMLInputElement | null>(null);+ // Refocusing the row blurs the still-mounted field, which would end it a second time; the first end claims it.+ const isDone = useRef(false);+ const finish = useCallback(+ (refocus: boolean, cancelled: boolean) => {+ if (isDone.current) {+ return;+ }++ const draft = input.current?.value ?? '';+ const invalid = !cancelled && validate(draft) !== null;++ isDone.current = true;++ if (cancelled || invalid) {+ onCancel(refocus);+ } else {+ onCommit(draft, refocus);+ }+ },+ [onCancel, onCommit, validate]+ );+ const handleChange = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => onErrorChange(validate(event.currentTarget.value)),+ [onErrorChange, validate]+ );+ const handleBlur = useCallback(+ (event: FocusEvent<HTMLInputElement>) => {+ const next = event.relatedTarget;++ // A menu that just closed (the row menu's Rename) takes focus back to its content while it animates out; the+ // field keeps it instead.+ if (+ next instanceof HTMLElement &&+ next.closest('[data-scope="menu"][data-part="content"][data-state="closed"]')+ ) {+ event.currentTarget.focus();+ return;+ }++ // Leaving the window keeps the field open; it commits when focus moves elsewhere in the page.+ if (next === null && !document.hasFocus()) {+ return;+ }++ finish(next === null, false);+ },+ [finish]+ );+ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLInputElement>) => {+ event.stopPropagation();++ // While an IME composes, Enter confirms a candidate and Escape drops it; neither ends the rename.+ if (isImeComposing(event.nativeEvent)) {+ return;+ }++ if (event.key === 'Enter') {+ event.preventDefault();+ const error = validate(event.currentTarget.value);++ // A name that cannot be kept stays in the field with its reason, rather than changing on its own.+ if (error) {+ onErrorChange(error);+ return;+ }++ finish(true, false);+ } else if (event.key === 'Escape') {+ event.preventDefault();+ finish(true, true);+ }+ },+ [finish, onErrorChange, validate]+ );+ const focusOnMount = useCallback((element: HTMLInputElement | null) => {+ input.current = element;+ element?.focus();+ element?.select();+ }, []);+ const stopPropagation = useCallback((event: { stopPropagation: () => void }) => event.stopPropagation(), []);++ return (+ <Input+ ref={focusOnMount}+ aria-describedby={errorId}+ aria-invalid={errorId ? true : undefined}+ aria-label={t('common.rename')}+ defaultValue={initialName}+ flex="1"+ fontSize="md"+ fontWeight="600"+ h="5"+ minW="0"+ mx="-1"+ px="1"+ size="xs"+ userSelect="text"+ onBlur={handleBlur}+ onChange={handleChange}+ onClick={stopPropagation}+ onDoubleClick={stopPropagation}+ onKeyDown={handleKeyDown}+ onPointerDown={stopPropagation}+ />+ );+};++/** The model a reference runs through, with the CLIP Vision encoder beside it for an SD/FLUX IP-Adapter. */+const ReferenceModelSelect = ({+ config,+ disabled,+ onConfigChange,+ relatedTo,+ selectedBase,+ strengthOnly,+}: {+ config: ModelBackedConfig;+ disabled: boolean;+ /** The active main model, so models linked to it rank first. */+ relatedTo: string | null;+ selectedBase: string | undefined;+ strengthOnly: boolean;+ onConfigChange: (config: GenerateReferenceImageConfig) => void;+}) => {+ const { t } = useTranslation();+ const modelTypes = getReferenceModelTypes(selectedBase);+ const filterModel = useCallback((model: ModelConfig) => model.base === selectedBase, [selectedBase]);+ const selectReferenceModel = useCallback(+ (model: ModelConfig | null) => {+ if (!model || model.base !== selectedBase) {+ return;+ }++ if (model.type === 'flux_redux') {+ onConfigChange({ image: config.image, imageInfluence: 'highest', model, type: 'flux_redux' });+ return;+ }++ if (model.type === 'ip_adapter') {+ onConfigChange({+ beginEndStepPct: [0, 1],+ clipVisionModel: selectedBase === 'flux' ? 'ViT-L' : 'ViT-H',+ image: config.image,+ method: 'full',+ model,+ type: 'ip_adapter',+ weight: 1,+ });+ }+ },+ [config.image, onConfigChange, selectedBase]+ );++ return (+ <HStack gap="1.5" minW="0">+ <ControlSurface data-reference-model="">+ <Field disabled={disabled} label={t('widgets.generate.model')} labelPlacement="inside">+ <ModelSelect+ disabled={disabled}+ filter={filterModel}+ // A Kontext reference may switch to Redux on FLUX, as it always could.+ modelTypes={modelTypes}+ placeholder={t('widgets.generate.selectModel')}+ relatedTo={relatedTo}+ value={config.model?.key ?? null}+ onChange={selectReferenceModel}+ />+ </Field>+ </ControlSurface>+ {config.type === 'ip_adapter' && !strengthOnly ? (+ <Box+ bg="var(--wb-field-surface, var(--chakra-colors-bg-subtle))"+ data-control-surface=""+ flexShrink={0}+ rounded="control"+ >+ <ClipVisionSelect+ key={config.model?.key ?? 'no-model'}+ config={config}+ disabled={disabled}+ onChange={onConfigChange}+ />+ </Box>+ ) : null}+ </HStack>+ );+};++const PromptTagButton = ({ tag }: { tag: string }) => {+ const { t } = useTranslation();+ const [hasCopied, setHasCopied] = useState(false);+ const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ useMountEffect(() => () => {+ if (resetTimerRef.current !== null) {+ clearTimeout(resetTimerRef.current);+ }+ });++ const copyTag = useCallback(() => {+ copyText(tag)+ .then(() => {+ setHasCopied(true);+ if (resetTimerRef.current !== null) {+ clearTimeout(resetTimerRef.current);+ }+ resetTimerRef.current = setTimeout(() => setHasCopied(false), PROMPT_TAG_COPIED_MS);+ })+ .catch(() =>+ toaster.create({ description: t('common.clipboardBlocked'), title: t('common.couldNotCopy'), type: 'error' })+ );+ }, [t, tag]);++ const canCopy = canCopyText();+ // Without a clipboard the button shows its own tooltip, the reason, so the explanation joins it there rather than+ // opening a second tooltip; it leaves out the hint's "click to copy", which is untrue then.+ const unavailableReason = canCopy+ ? undefined+ : `${t('widgets.generate.referenceImagePromptTagExplanation', { tag })} ${t('common.copyUnavailable')}`;+ const button = (+ <Button+ aria-label={t('widgets.generate.copyReferenceImagePromptTag', { tag })}+ color="fg.muted"+ flexShrink="0"+ fontFamily="mono"+ fontWeight="normal"+ size="xs"+ unavailableReason={unavailableReason}+ variant="subtle"+ onClick={copyTag}+ >+ {hasCopied ? <Icon as={CheckIcon} color="green.solid" /> : null}+ {tag}+ <VisuallyHidden aria-live="polite">+ {hasCopied ? t('widgets.generate.referenceImagePromptTagCopied', { tag }) : ''}+ </VisuallyHidden>+ </Button>+ );++ return canCopy ? (+ <Tooltip content={t('widgets.generate.referenceImagePromptTagHint', { tag })}>{button}</Tooltip>+ ) : (+ button+ );+};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageAnimaControls.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageAnimaControls.browser.test.tsxindex 8440f5b0c0..27213f3671 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageAnimaControls.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageAnimaControls.browser.test.tsx@@ -8,8 +8,8 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';-import { ReferenceImageCard } from './ReferenceImageCard';import { getModeLabelKey } from './referenceImageConfig';+import { ReferenceImageRow } from './ReferenceImageRow';vi.mock('react-i18next', () => {const t = (key: string) => key;@@ -32,7 +32,7 @@ const referenceImage = (base: string): GenerateReferenceImage => ({config: {beginEndStepPct: [0, 1],clipVisionModel: 'ViT-H',- image: null,+ image: { original: { image: { height: 512, image_name: 'character.png', width: 512 } } },method: 'style',model: { base, key: `${base}-ip-adapter`, name: `${base} IP-Adapter`, type: 'ip_adapter' },type: 'ip_adapter',@@ -57,7 +57,7 @@ const render = async (selectedModel: GenerateModelConfig) => {root?.render(<ChakraProvider value={system}><GenerationUiProvider adapter={ADAPTER}>- <ReferenceImageCard+ <ReferenceImageRowcount={1}index={0}referenceImage={referenceImage(selectedModel.base)}@@ -66,17 +66,17 @@ const render = async (selectedModel: GenerateModelConfig) => {onMove={vi.fn()}onPatch={onPatch}onRemove={vi.fn()}+ onRename={vi.fn()}onUseSize={vi.fn()}/></GenerationUiProvider></ChakraProvider>));- // Advanced holds the model picker and active steps.- const advanced = [...host.querySelectorAll('button')].find(- (button) => button.textContent === 'widgets.generate.advanced'+ // The settings under the row hold the mode, the model picker and active steps.+ await act(() =>+ host?.querySelector<HTMLButtonElement>('button[aria-label="widgets.generate.referenceImageSettings"]')?.click());- await act(() => advanced?.click());return host;};@@ -88,19 +88,20 @@ afterEach(async () => {root = null;});-describe('Anima IP-Adapter reference card', () => {+describe('Anima IP-Adapter reference row', () => {it('offers strength and active steps, without the SD mode, style variant or CLIP Vision encoder', async () => {const card = await render(ANIMA);const text = card.textContent ?? '';expect(text).toContain('widgets.generate.strength');expect(text).not.toContain('widgets.generate.weight');- expect(text).not.toContain('widgets.generate.mode');+ expect(card.querySelector('[aria-label="widgets.generate.mode"]')).toBeNull();expect(text).not.toContain('widgets.generate.styleVariant');expect(text).not.toContain('ViT-H');- expect(text).toContain('widgets.generate.activeSteps');+ expect(text).toContain('widgets.generate.activeStepsShort');expect(text).toContain('IP-Adapter picker');+ // The row's own control, ahead of the step range under it.const strength = card.querySelector('[role="slider"]');expect(strength?.getAttribute('aria-valuenow')).toBe('1.5');expect(strength?.getAttribute('aria-valuemin')).toBe('0');@@ -123,23 +124,22 @@ describe('Anima IP-Adapter reference card', () => {expect(onPatch).toHaveBeenLastCalledWith('ref-1', { config: expect.objectContaining({ weight: 0 }) });});- it('summarizes the collapsed card by its strength, not an SD mode', async () => {+ it('summarizes the row by its adapter, not an SD mode', async () => {const card = await render(ANIMA);- const collapse = card.querySelector<HTMLButtonElement>(- 'button[aria-label="widgets.generate.collapseReferenceImage"]'- )!;-- await act(() => collapse.click());+ const summary = card.querySelector('[data-list-primary]')?.textContent ?? '';- expect(card.textContent).toContain('widgets.generate.strength 1.50');- expect(card.textContent).not.toContain(getModeLabelKey('style'));+ expect(summary).toContain('anima IP-Adapter');+ expect(summary).not.toContain(getModeLabelKey('style'));});it('keeps the SD controls for an SDXL reference', async () => {const text = (await render(SDXL)).textContent ?? '';+ const card = host!;+expect(text).toContain('widgets.generate.weight');- expect(text).toContain('widgets.generate.mode');+ expect(card.querySelector('[aria-label="widgets.generate.mode"]')).not.toBeNull();+ expect(card.querySelector('[data-list-primary]')?.textContent).toContain(getModeLabelKey('style'));expect(text).toContain('widgets.generate.styleVariant');expect(text).toContain('ViT-H');expect(text).not.toContain('widgets.generate.strength');diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsxindex 695c374ce6..9c98f75939 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageCrop.browser.test.tsx@@ -12,7 +12,7 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { page, userEvent } from 'vitest/browser';-import { ReferenceImageCard } from './ReferenceImageCard';+import { ReferenceImageRow } from './ReferenceImageRow';const mocks = vi.hoisted(() => {// A real decodable image, so the crop export's <img> loads without a backend.@@ -83,7 +83,7 @@ const renderCard = (referenceImage: GenerateReferenceImage) => {<I18nextProvider i18n={i18n}><ChakraProvider value={system}><GenerationUiProvider adapter={ADAPTER}>- <ReferenceImageCard+ <ReferenceImageRowcount={1}index={0}referenceImage={referenceImage}@@ -92,6 +92,7 @@ const renderCard = (referenceImage: GenerateReferenceImage) => {onMove={noop}onPatch={noop}onRemove={noop}+ onRename={noop}onUseSize={noop}/></GenerationUiProvider>@@ -115,8 +116,19 @@ afterEach(async () => {vi.clearAllMocks();});+/** A reference with no settings keeps Crop in its row menu. */+const chooseCrop = async () => {+ await act(() =>+ userEvent.click(+ document.querySelector<HTMLElement>('button[aria-label="widgets.generate.referenceImageMoreActions"]')!+ )+ );+ await expect.poll(() => document.querySelector('[role="menuitem"][data-value="crop"]')).not.toBeNull();+ await act(() => userEvent.click(document.querySelector<HTMLElement>('[role="menuitem"][data-value="crop"]')!));+};+const openCropDialog = async (): Promise<HTMLElement> => {- await act(() => userEvent.click(document.querySelector<HTMLElement>('button[aria-label="common.crop"]')!));+ await chooseCrop();await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;await expect@@ -163,7 +175,7 @@ const spaceKey = (type: 'keydown' | 'keyup', target: EventTarget = window) =>describe('reference image crop dialog', () => {it('animates out instead of unmounting on close', async () => {- await act(() => userEvent.click(document.querySelector<HTMLElement>('button[aria-label="common.crop"]')!));+ await chooseCrop();await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');const dialog = document.querySelector('[role="dialog"]')!;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsxindex 0d5ede2e1b..0e0ff6df88 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFindInGallery.browser.test.tsx@@ -1,30 +1,24 @@-import type { GenerateReferenceImage } from '@features/generation/core/types';+import type { GenerateModelConfig, GenerateReferenceImage } from '@features/generation/core/types';import { ChakraProvider } from '@chakra-ui/react';+import { type GenerationUiAdapter, GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';import { system } from '@theme/system';import i18next from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';-import { ReferenceImageCard } from './ReferenceImageCard';+import { ReferenceImageRow } from './ReferenceImageRow';/** Crop intermediates have separate identities and stay out of the gallery; retain the original for reveal. */const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',+ interpolation: { escapeValue: false },lng: 'en',- resources: {- en: {- translation: {- widgets: {- gallery: { findNamedInGallery: 'Find {{name}} in Gallery' },- generate: { referenceImageNumbered: 'Reference image {{index}}' },- },- },- },- },+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },});let host: HTMLDivElement | null = null;@@ -33,51 +27,75 @@ let root: Root | null = null;const onFindInGallery = vi.fn();const noop = vi.fn();+const ADAPTER = { models: { ModelSelect: () => null } } as unknown as GenerationUiAdapter;+const SDXL: GenerateModelConfig = { base: 'sdxl', key: 'sdxl', name: 'SDXL', type: 'main' };++const CROPPED_IMAGE = {+ crop: {+ box: { height: 128, width: 128, x: 16, y: 16 },+ image: { height: 128, image_name: 'crop-intermediate.png', width: 128 },+ ratio: 1,+ },+ original: { image: { height: 512, image_name: 'original.png', width: 512 } },+};const CROPPED_REFERENCE: GenerateReferenceImage = {+ config: { image: CROPPED_IMAGE, type: 'external_reference_image' },+ id: 'cropped',+ isEnabled: true,+};++const CROPPED_IP_ADAPTER: GenerateReferenceImage = {config: {- image: {- crop: {- box: { height: 128, width: 128, x: 16, y: 16 },- image: { height: 128, image_name: 'crop-intermediate.png', width: 128 },- ratio: 1,- },- original: { image: { height: 512, image_name: 'original.png', width: 512 } },- },- type: 'external_reference_image',+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-H',+ image: CROPPED_IMAGE,+ method: 'full',+ model: { base: 'sdxl', key: 'ip', name: 'IP Adapter SDXL', type: 'ip_adapter' },+ type: 'ip_adapter',+ weight: 1,},- id: 'cropped',+ id: 'cropped-ip',isEnabled: true,};-const renderCard = async (referenceImage: GenerateReferenceImage) => {+const renderRow = async (referenceImage: GenerateReferenceImage, selectedModel?: GenerateModelConfig) => {await act(() =>root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <ReferenceImageCard- count={1}- index={0}- referenceImage={referenceImage}- selectedModel={undefined}- onFindInGallery={onFindInGallery}- onMove={noop}- onPatch={noop}- onRemove={noop}- onUseSize={noop}- />+ <GenerationUiProvider adapter={ADAPTER}>+ <ReferenceImageRow+ count={1}+ index={0}+ referenceImage={referenceImage}+ selectedModel={selectedModel}+ onFindInGallery={onFindInGallery}+ onMove={noop}+ onPatch={noop}+ onRemove={noop}+ onRename={noop}+ onUseSize={noop}+ />+ </GenerationUiProvider></ChakraProvider></I18nextProvider>));};-// Use media-specific action names to distinguish repeated cards accessibly.-const findButton = (): HTMLButtonElement | null =>- document.querySelector<HTMLButtonElement>('button[aria-label="Find original.png in Gallery"]');+const menuItem = (value: string) => document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`);++const openMenu = async () => {+ await act(() =>+ userEvent.click(host!.querySelector<HTMLElement>('button[aria-haspopup="menu"]:not([data-list-primary])')!)+ );+ await expect.poll(() => menuItem('find-in-gallery')).not.toBeNull();+};beforeEach(() => {host = document.createElement('div');+ host.style.width = '360px';document.body.append(host);root = createRoot(host);onFindInGallery.mockClear();@@ -88,22 +106,37 @@ afterEach(async () => {host?.remove();});-describe('reference image find-in-gallery badge', () => {- it('reveals the original image a crop was taken from, not the crop upload', async () => {- await renderCard(CROPPED_REFERENCE);+describe('reference image find in gallery', () => {+ it('reveals the original image a crop was taken from, not the crop upload, from the row menu', async () => {+ await renderRow(CROPPED_REFERENCE);- // The thumbnail is showing the crop, which is what makes this worth pinning.- expect(document.querySelector('img')?.src).toContain('crop-intermediate.png');+ // The tile shows the crop, marked as cropped, which is what makes this worth pinning.+ expect(host!.querySelector('img')?.src).toContain('crop-intermediate.png');+ expect(host!.querySelector('[data-cropped]')).not.toBeNull();+ expect(host!.querySelector('[data-list-primary]')?.textContent).toContain('128 × 128 · cropped');- await act(() => findButton()?.click());+ await openMenu();+ await act(() => userEvent.click(menuItem('find-in-gallery')!));expect(onFindInGallery).toHaveBeenCalledWith('original.png');});- it('stays available while the reference is toggled off', async () => {- await renderCard({ ...CROPPED_REFERENCE, isEnabled: false });+ it('stays available while the reference is off, in the menu and in the open settings, unlike crop and size', async () => {+ await renderRow({ ...CROPPED_IP_ADAPTER, isEnabled: false }, SDXL);+ await openMenu();// Locate stays enabled for disabled references because it does not edit generation.- expect(findButton()?.disabled).toBe(false);+ expect(menuItem('find-in-gallery')?.hasAttribute('data-disabled')).toBe(false);+ expect(menuItem('crop')?.hasAttribute('data-disabled')).toBe(true);+ expect(menuItem('use-size')?.hasAttribute('data-disabled')).toBe(true);+ await act(() => userEvent.keyboard('{Escape}'));++ await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Reference image 1 settings"]')!.click());+ const find = host!.querySelector<HTMLButtonElement>('button[aria-label="Find original.png in Gallery"]');++ expect(find?.disabled).toBe(false);+ expect(host!.querySelector<HTMLButtonElement>('button[aria-label="Crop Reference image 1"]')?.disabled).toBe(true);+ await act(() => find?.click());+ expect(onFindInGallery).toHaveBeenCalledWith('original.png');});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageKrea2Mode.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageKrea2Mode.browser.test.tsxindex 308bfec11b..58258291bb 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageKrea2Mode.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageKrea2Mode.browser.test.tsx@@ -9,7 +9,7 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';-import { ReferenceImageCard } from './ReferenceImageCard';+import { ReferenceImageRow } from './ReferenceImageRow';// The real catalog, so a mistyped key shows up as the key and fails the label lookups below.const i18n = i18next.createInstance();@@ -32,7 +32,7 @@ const STYLE_REFERENCE: GenerateReferenceImage = {};/** Mirrors the section: each patch lands back on the rendered reference. */-const Card = ({ initial }: { initial: GenerateReferenceImage }) => {+const Row = ({ initial }: { initial: GenerateReferenceImage }) => {const [referenceImage, setReferenceImage] = useState(initial);const handlePatch = useCallback((id: string, patch: Partial<GenerateReferenceImage>) => {onPatch(id, patch);@@ -40,7 +40,7 @@ const Card = ({ initial }: { initial: GenerateReferenceImage }) => {}, []);return (- <ReferenceImageCard+ <ReferenceImageRowcount={1}index={0}referenceImage={referenceImage}@@ -49,17 +49,18 @@ const Card = ({ initial }: { initial: GenerateReferenceImage }) => {onMove={vi.fn()}onPatch={handlePatch}onRemove={vi.fn()}+ onRename={vi.fn()}onUseSize={vi.fn()}/>);};-const renderCard = async (initial: GenerateReferenceImage) => {+const renderRow = async (initial: GenerateReferenceImage) => {await act(() =>root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <Card initial={initial} />+ <Row initial={initial} /></ChakraProvider></I18nextProvider>)@@ -81,6 +82,9 @@ const clickMode = async (label: 'Edit' | 'Style') => {});};const hasStrengthControl = () => host?.textContent?.includes('Style strength') ?? false;+/** A Style reference keeps its mode under the row, with its strength on the row. */+const openSettings = () =>+ act(() => host?.querySelector<HTMLButtonElement>('button[aria-label="Reference image 1 settings"]')?.click());beforeEach(() => {host = document.createElement('div');@@ -97,7 +101,9 @@ afterEach(async () => {describe('Krea-2 reference mode switch', () => {it('switches a reference to Edit and back to Style, keeping its image and restarting the strength', async () => {- await renderCard(STYLE_REFERENCE);+ await renderRow(STYLE_REFERENCE);+ expect(modeGroup()).toBeNull();+ await openSettings();expect(modeGroup()?.getAttribute('aria-label')).toBe('Mode');expect(modeRadio('Style')?.checked).toBe(true);@@ -109,7 +115,7 @@ describe('Krea-2 reference mode switch', () => {config: { image, type: 'krea2_edit_reference_image' },});expect(modeRadio('Edit')?.checked).toBe(true);- // Edit references have no strength; the card shows only the mode.+ // Edit references have no strength; the mode is the row's control.expect(hasStrengthControl()).toBe(false);await clickMode('Style');@@ -118,10 +124,13 @@ describe('Krea-2 reference mode switch', () => {config: { image, styleStrength: 1, type: 'krea2_reference_image' },});expect(hasStrengthControl()).toBe(true);+ // Back under the row, which stays open so the mode just chosen is still in view.+ expect(modeRadio('Style')?.checked).toBe(true);});- it('switches with the arrow keys from the focused mode', async () => {- await renderCard(STYLE_REFERENCE);+ it('switches with the arrow keys from the focused mode, focus following the control to the row', async () => {+ await renderRow(STYLE_REFERENCE);+ await openSettings();await act(() => modeRadio('Style')?.focus());await act(async () => {@@ -131,11 +140,12 @@ describe('Krea-2 reference mode switch', () => {expect(onPatch).toHaveBeenLastCalledWith('pose', {config: { image, type: 'krea2_edit_reference_image' },});- expect(document.activeElement).toBe(modeRadio('Edit'));+ await expect.poll(() => document.activeElement).toBe(modeRadio('Edit'));});it('switches the mode of a switched-off reference, so it can join an edit set before it runs', async () => {- await renderCard({ ...STYLE_REFERENCE, isEnabled: false });+ await renderRow({ ...STYLE_REFERENCE, isEnabled: false });+ await openSettings();expect(modeRadio('Edit')?.disabled).toBe(false);diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImagePromptTag.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImagePromptTag.browser.test.tsxindex 6949b9fe98..94ceeac56f 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImagePromptTag.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImagePromptTag.browser.test.tsx@@ -9,9 +9,9 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { page, userEvent } from 'vitest/browser';-import { ReferenceImageCard } from './ReferenceImageCard';+import { ReferenceImageRow } from './ReferenceImageRow';-/** FLUX.3 names its references in the prompt; the card's tag button explains the tag and copies it where it can. */+/** FLUX.3 names its references in the prompt; the row's tag button explains the tag and copies it where it can. */const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -39,12 +39,12 @@ let originalClipboard: PropertyDescriptor | undefined;const noop = vi.fn();-const renderCard = () =>+const renderRow = () =>act(() =>root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <ReferenceImageCard+ <ReferenceImageRowcount={1}index={0}promptTag={TAG}@@ -54,6 +54,7 @@ const renderCard = () =>onMove={noop}onPatch={noop}onRemove={noop}+ onRename={noop}onUseSize={noop}/></ChakraProvider>@@ -88,7 +89,7 @@ describe('reference image prompt tag', () => {it('explains the tag and copies it', async () => {const writeText = vi.fn(() => Promise.resolve());Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } });- await renderCard();+ await renderRow();await expect.element(tagButton()).not.toHaveAttribute('aria-disabled');await act(() => userEvent.hover(tagButton()));@@ -101,7 +102,7 @@ describe('reference image prompt tag', () => {it('still explains the tag, beside why it cannot copy, when the clipboard is unavailable', async () => {Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined });- await renderCard();+ await renderRow();const expected = `${EXPLANATION} Copying needs HTTPS or localhost`;await expect.element(tagButton()).toHaveAttribute('aria-disabled', 'true');diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsxdeleted file mode 100644index 0e415c7d62..0000000000--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageReorder.browser.test.tsx+++ /dev/null@@ -1,171 +0,0 @@-import type { GenerateReferenceImage } from '@features/generation/core/types';--import { ChakraProvider } from '@chakra-ui/react';-import { moveReferenceImage } from '@features/generation/core/settings';-import { system } from '@theme/system';-import i18next from 'i18next';-import { act, useCallback, useState } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { I18nextProvider, initReactI18next } from 'react-i18next';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { ReferenceImageCard } from './ReferenceImageCard';--/** Browser coverage verifies arrow wiring and disabled endpoints beyond pure reorder tests. */-const i18n = i18next.createInstance();-await i18n.use(initReactI18next).init({- fallbackLng: 'en',- lng: 'en',- resources: {- en: {- translation: {- widgets: {- generate: {- collapseReferenceImage: 'Collapse reference image',- disableReferenceImage: 'Disable reference image',- enableReferenceImage: 'Enable reference image',- expandReferenceImage: 'Expand reference image',- moveReferenceImageDown: 'Move reference image down',- moveReferenceImageUp: 'Move reference image up',- referenceImageNumbered: 'Reference image {{index}}',- removeReferenceImage: 'Remove reference image',- },- },- },- },- },-});--let host: HTMLDivElement | null = null;-let root: Root | null = null;-(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;--const onUseSize = vi.fn();-const onFindInGallery = vi.fn();-const onPatch = vi.fn();-const onRemove = vi.fn();--const buildReferenceImage = (id: string): GenerateReferenceImage => ({- config: {- image: { original: { image: { height: 512, image_name: `${id}.png`, width: 512 } } },- type: 'external_reference_image',- },- id,- isEnabled: true,-});--/** Mirrors the section: the move lands back on the rendered list. */-const Stack = ({ ids }: { ids: string[] }) => {- const [referenceImages, setReferenceImages] = useState(() => ids.map(buildReferenceImage));- const handleMove = useCallback((id: string, direction: -1 | 1) => {- setReferenceImages((current) => [...moveReferenceImage(current, id, direction)]);- }, []);-- return (- <>- {referenceImages.map((referenceImage, index) => (- <ReferenceImageCard- key={referenceImage.id}- count={referenceImages.length}- index={index}- referenceImage={referenceImage}- selectedModel={undefined}- onFindInGallery={onFindInGallery}- onMove={handleMove}- onPatch={onPatch}- onRemove={onRemove}- onUseSize={onUseSize}- />- ))}- </>- );-};--const renderStack = async (ids: string[]) => {- await act(() =>- root?.render(- <I18nextProvider i18n={i18n}>- <ChakraProvider value={system}>- <Stack ids={ids} />- </ChakraProvider>- </I18nextProvider>- )- );-};--const buttons = (label: string): HTMLButtonElement[] =>- [...document.querySelectorAll(`button[aria-label="${label}"]`)] as HTMLButtonElement[];--/** Cards are titled by position, so the headings ARE the rendered order. */-const renderedOrder = (): string[] =>- [...document.querySelectorAll('img')].map((image) => (image as HTMLImageElement).src.split('/').at(-2) ?? '');--beforeEach(() => {- host = document.createElement('div');- document.body.append(host);- root = createRoot(host);- onPatch.mockClear();- onRemove.mockClear();- onUseSize.mockClear();-});--afterEach(async () => {- await act(() => root?.unmount());- host?.remove();-});--describe('reference image reorder arrows', () => {- it('moves a card through the stack and disables the arrows at each end', async () => {- await renderStack(['first', 'second', 'third']);-- expect(renderedOrder()).toEqual(['first.png', 'second.png', 'third.png']);-- // Only the ends are frozen: the top card cannot rise, the bottom cannot fall.- expect(buttons('Move reference image up').map((button) => button.disabled)).toEqual([true, false, false]);- expect(buttons('Move reference image down').map((button) => button.disabled)).toEqual([false, false, true]);-- await act(() => {- buttons('Move reference image down')[0]?.click();- });-- expect(renderedOrder()).toEqual(['second.png', 'first.png', 'third.png']);-- // Up from the last slot is the inverse move, not another step down.- await act(() => {- buttons('Move reference image up')[2]?.click();- });-- expect(renderedOrder()).toEqual(['second.png', 'third.png', 'first.png']);- });-- it('hands focus to the arrow that stays live when a move lands on an end', async () => {- await renderStack(['first', 'second', 'third']);-- // Hand off keyboard focus when the activated endpoint arrow becomes disabled.- const up = buttons('Move reference image up')[1];-- await act(() => up?.focus());- await act(() => up?.click());-- expect(renderedOrder()).toEqual(['second.png', 'first.png', 'third.png']);- expect(document.activeElement).toBe(buttons('Move reference image down')[0]);- expect((document.activeElement as HTMLButtonElement).disabled).toBe(false);-- // Same at the far end: the down arrow of the card that lands last.- const down = buttons('Move reference image down')[1];-- await act(() => down?.focus());- await act(() => down?.click());-- expect(renderedOrder()).toEqual(['second.png', 'third.png', 'first.png']);- expect(document.activeElement).toBe(buttons('Move reference image up')[2]);- expect((document.activeElement as HTMLButtonElement).disabled).toBe(false);- });-- it('leaves a lone reference image with both arrows disabled', async () => {- await renderStack(['only']);-- expect(buttons('Move reference image up')[0]?.disabled).toBe(true);- expect(buttons('Move reference image down')[0]?.disabled).toBe(true);- });-});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageRow.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageRow.browser.test.tsxnew file mode 100644index 0000000000..ff15dcadae--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageRow.browser.test.tsx@@ -0,0 +1,818 @@+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+import type { GenerationModelCatalogItem } from '@features/generation/contracts';+import type { GenerationIssue, GenerationIssueFix } from '@features/generation/core/generationIssues';+import type { GenerateModelConfig, GenerateReferenceImage, GenerateSettings } from '@features/generation/core/types';+import type { GenerateSettingsUpdate } from '@features/generation/ui/generateDebounce';++import { ChakraProvider } from '@chakra-ui/react';+import { DndContext } from '@dnd-kit/core';+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';+import { getDefaultGenerateSettings, getMaxReferenceImages } from '@features/generation/core/baseGenerationPolicies';+import { type GenerationUiAdapter, GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';+import { revealGenerateIssue } from '@features/generation/ui/revealGenerateIssue';+import { GenerateIssuesProvider } from '@features/generation/ui/shared/GenerateIssues';+import { system } from '@theme/system';+import i18next from 'i18next';+import { act, createRef, type Ref, useCallback, useImperativeHandle, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { commands, userEvent } from 'vitest/browser';++import { GenerateReferenceImagesContent } from './GenerateReferenceImagesSection';+import { describeReferenceImage, getPositionalDefaultNameTest } from './ReferenceImageRow';++declare module 'vitest/browser' {+ interface BrowserCommands {+ imeCompose: (steps: readonly { kind: 'commit' | 'compose'; text: string }[]) => Promise<void>;+ }+}++const i18n = i18next.createInstance();+// The shipped copy, so names and labels read as a user sees them.+await i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});++seedArchitectureCapabilities();++const SDXL: GenerateModelConfig = { base: 'sdxl', format: 'diffusers', key: 'sdxl', name: 'SDXL', type: 'main' };+const FLUX: GenerateModelConfig = {+ base: 'flux',+ format: 'diffusers',+ key: 'flux-dev',+ name: 'FLUX dev',+ type: 'main',+};+const COGVIEW: GenerateModelConfig = { base: 'cogview4', key: 'cogview4', name: 'CogView4', type: 'main' };+const REDUX = { base: 'flux', key: 'redux', name: 'FLUX Redux', type: 'flux_redux' };+const NO_MODELS: [] = [];+const SDXL_ADAPTERS = [+ { base: 'sdxl', key: 'ip-adapter-sdxl', name: 'IP Adapter SDXL', type: 'ip_adapter' },+] as unknown as GenerationModelCatalogItem[];+const openManager = vi.fn();+const NO_VISION_COMPONENTS = {};+const undoable = vi.fn();+/** The models a model picker last offered; picking from it chooses a Redux model where Redux is offered. */+let offeredModelTypes: readonly string[] = [];+/** The model the picker was last told to rank related models against. */+let offeredRelatedTo: string | null | undefined;+/** The installed models as the store holds them now; each render installs the ones it passes. */+let catalog: readonly GenerationModelCatalogItem[] = NO_MODELS;+const ADAPTER = {+ gallery: { findImage: vi.fn() },+ models: {+ ModelSelect: ({+ modelTypes,+ onChange,+ relatedTo,+ }: {+ modelTypes: string[];+ onChange: (model: unknown) => void;+ relatedTo?: string | null;+ }) => {+ offeredModelTypes = modelTypes;+ offeredRelatedTo = relatedTo;+ return (+ <button type="button" onClick={() => onChange(modelTypes.includes('flux_redux') ? REDUX : null)}>+ Model picker+ </button>+ );+ },+ getBaseLabel: (base: string) => base,+ openManager,+ readCatalog: () => catalog,+ },+ notifications: { info: vi.fn(), undoable },+ project: { activeProjectId: 'project-1' },+ settings: {+ patchGenerateSettings: (patch: Partial<GenerateSettings>) => setStored(patch.referenceImages ?? stored),+ readGenerateValues: () => ({+ ...getDefaultGenerateSettings(SDXL),+ model: SDXL,+ modelKey: SDXL.key,+ referenceImages: stored,+ }),+ },+} as unknown as GenerationUiAdapter;++const reference = (id: string, name?: string): GenerateReferenceImage => ({+ config: {+ beginEndStepPct: [0.2, 0.8],+ clipVisionModel: 'ViT-H',+ image: { original: { image: { height: 768, image_name: `${id}.png`, width: 512 } } },+ method: 'composition',+ model: { base: 'sdxl', key: 'ip-adapter-sdxl', name: 'IP Adapter SDXL', type: 'ip_adapter' },+ type: 'ip_adapter',+ weight: 0.8,+ },+ id,+ isEnabled: true,+ ...(name === undefined ? {} : { name }),+});++/** What the section last committed, read back after each interaction. */+let stored: GenerateReferenceImage[] = [];+/** Replaces the rendered references, as a model switch or another tab would. */+const section = createRef<{ replace: (referenceImages: GenerateReferenceImage[]) => void }>();+const setStored = (referenceImages: GenerateReferenceImage[]) => section.current?.replace(referenceImages);++/** Each enabled reference without an adapter blocks Invoke, worded as Generate validation words it. */+const needsAdapterIssues = (referenceImages: readonly GenerateReferenceImage[]): GenerationIssue[] =>+ referenceImages.flatMap((referenceImage, index) =>+ referenceImage.isEnabled && referenceImage.config.type === 'ip_adapter' && referenceImage.config.model === null+ ? [+ {+ fix: { kind: 'turnOffReferenceImages', referenceImageIds: [referenceImage.id] },+ id: `referenceImages:needsIpAdapter:${referenceImage.id}`,+ message: `${referenceImage.name ?? `Reference image ${index + 1}`} needs an IP Adapter model for SDXL.`,+ messageKey: 'widgets.generate.issues.referenceImageNeedsIpAdapter',+ messageValues: {+ index: index + 1,+ name: 'SDXL',+ ...(referenceImage.name === undefined ? {} : { referenceName: referenceImage.name }),+ },+ target: { field: 'referenceImage', referenceImageId: referenceImage.id, section: 'guidance' },+ } satisfies GenerationIssue,+ ]+ : []+ );++/** The form applies each reference update to its draft at once; this keeps that draft, and validates it. */+const Section = ({+ initial,+ model,+ models,+ ref,+}: {+ initial: GenerateReferenceImage[];+ model: GenerateModelConfig;+ models: readonly GenerationModelCatalogItem[];+ ref: Ref<{ replace: (referenceImages: GenerateReferenceImage[]) => void }>;+}) => {+ const [referenceImages, setReferenceImages] = useState(initial);+ const replace = useCallback((next: GenerateReferenceImage[]) => {+ stored = next;+ setReferenceImages(next);+ }, []);+ useImperativeHandle(ref, () => ({ replace }), [replace]);+ const applyFix = useCallback((fix: GenerationIssueFix) => {+ if (fix.kind === 'turnOffReferenceImages') {+ setReferenceImages((current) => {+ const next = current.map((referenceImage) =>+ fix.referenceImageIds.includes(referenceImage.id) ? { ...referenceImage, isEnabled: false } : referenceImage+ );+ stored = next;+ return next;+ });+ }+ }, []);+ const onCommit = useCallback(+ (update: GenerateSettingsUpdate) => {+ // Applied at once, as the form's draft does, so a caller reading back what it removed finds it.+ const next =+ typeof update === 'function'+ ? update({ referenceImages: stored } as GenerateSettings).referenceImages+ : (update.referenceImages ?? stored);+ replace(next);+ },+ [replace]+ );+ const onCommitImmediate = useCallback(+ (patch: Partial<GenerateSettings>) => (patch.referenceImages ? replace(patch.referenceImages) : undefined),+ [replace]+ );++ return (+ <GenerateIssuesProvider applyFix={applyFix} issues={needsAdapterIssues(referenceImages)}>+ <GenerateReferenceImagesContent+ models={models}+ referenceImages={referenceImages}+ selectedModel={model}+ visionComponents={NO_VISION_COMPONENTS}+ onCommit={onCommit}+ onCommitImmediate={onCommitImmediate}+ />+ </GenerateIssuesProvider>+ );+};++let host: HTMLDivElement;+let root: Root;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const render = async (+ initial: GenerateReferenceImage[],+ model: GenerateModelConfig = SDXL,+ models: readonly GenerationModelCatalogItem[] = NO_MODELS+) => {+ stored = initial;+ catalog = models;+ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <GenerationUiProvider adapter={ADAPTER}>+ <DndContext>+ <div data-hotkey-widget-type-id="generate" data-testid="section">+ <Section ref={section} initial={initial} model={model} models={models} />+ </div>+ </DndContext>+ </GenerationUiProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );+};++const list = () => host.querySelector<HTMLElement>('[role="list"][aria-label="Reference images"]')!;+const row = (id: string) => host.querySelector<HTMLElement>(`[data-reference-image-id="${id}"]`)!;+const rowButton = (id: string) => row(id).querySelector<HTMLElement>('[data-list-primary]')!;+const nameOf = (id: string) => row(id).querySelector('[data-list-primary] [title]')?.textContent;+const renderedOrder = () =>+ [...host.querySelectorAll<HTMLElement>('[data-reference-image-id]')].map(+ (element) => element.dataset.referenceImageId+ );+const nameField = () => host.querySelector<HTMLInputElement>('input[aria-label="Rename"]');+const addRow = () => host.querySelector<HTMLButtonElement>('[data-reference-add]')!;+const menuItem = (value: string) => document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`);+const pressOn = async (element: HTMLElement, keys: string) => {+ await act(() => element.focus());+ await act(() => userEvent.keyboard(keys));+};++beforeEach(() => {+ undoable.mockClear();+ host = document.createElement('div');+ host.style.width = '360px';+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ await userEvent.unhover(document.body);+});++describe('reference image rows', () => {+ it('lists each reference as a List row, with dividers and the add row as the last row', async () => {+ await render([reference('a', 'Hero pose'), reference('b')]);++ const items = [...list().children].filter((child) => child.getAttribute('role') === 'listitem');+ expect(items).toHaveLength(3);+ // Hairlines between rows, the add row included.+ expect(list().querySelectorAll(':scope > [data-list-divider]')).toHaveLength(2);+ expect(items[2]?.contains(addRow())).toBe(true);+ expect(addRow().hasAttribute('data-list-surface')).toBe(true);++ // Each row's controls are named in its reference's context, and its summary reads its settings.+ expect(row('a').querySelector('[role="group"]')?.getAttribute('aria-label')).toBe('Hero pose');+ expect(row('b').querySelector('[role="group"]')?.getAttribute('aria-label')).toBe('Reference image 2');+ expect(rowButton('a').getAttribute('aria-haspopup')).toBe('menu');+ expect(rowButton('a').textContent).toContain('Composition · 20–80% · IP Adapter SDXL');+ expect(row('a').querySelector('[data-scope="switch"]')?.textContent).toBe('Disable Hero pose');+ expect(row('a').querySelector('button[aria-label="More actions for Hero pose"]')).not.toBeNull();+ // The weight is on the row; the rest waits under the disclosure.+ expect(row('a').querySelector('[role="slider"]')?.getAttribute('aria-valuenow')).toBe('0.8');+ expect(row('a').querySelector('[aria-label="Mode"]')).toBeNull();+ });++ it('is the add row alone when empty, counting the slots', async () => {+ await render([]);++ expect(list().querySelectorAll('[role="listitem"]')).toHaveLength(1);+ expect(addRow().textContent).toContain('Add reference image');+ expect(addRow().textContent).toContain(`0 of ${getMaxReferenceImages(SDXL)} used`);+ expect(addRow().getAttribute('aria-disabled')).toBeNull();+ });++ it('opens and closes the settings from the chevron and from Right and Left on the row', async () => {+ await render([reference('a')]);+ const chevron = row('a').querySelector<HTMLButtonElement>('button[aria-label="Reference image 1 settings"]')!;++ expect(chevron.getAttribute('aria-expanded')).toBe('false');+ await act(() => chevron.click());+ expect(chevron.getAttribute('aria-expanded')).toBe('true');+ expect(document.getElementById(chevron.getAttribute('aria-controls')!)).not.toBeNull();+ expect(row('a').querySelector('[aria-label="Mode"]')).not.toBeNull();+ expect(row('a').textContent).toContain('ViT-H');+ expect(row('a').querySelector('button[aria-label="Crop Reference image 1"]')).not.toBeNull();+ // The one level of disclosure: no nested Advanced.+ expect(row('a').textContent).not.toContain('Advanced');++ await pressOn(rowButton('a'), '{ArrowLeft}');+ expect(chevron.getAttribute('aria-expanded')).toBe('false');+ expect(row('a').querySelector('[aria-label="Mode"]')).toBeNull();++ await pressOn(rowButton('a'), '{ArrowRight}');+ expect(chevron.getAttribute('aria-expanded')).toBe('true');+ expect(document.activeElement).toBe(rowButton('a'));+ });++ it('ranks the reference model picker against the active main model', async () => {+ offeredRelatedTo = undefined;+ await render([reference('a')]);+ await act(() =>+ row('a').querySelector<HTMLButtonElement>('button[aria-label="Reference image 1 settings"]')!.click()+ );++ expect(offeredRelatedTo).toBe(SDXL.key);+ });++ it('updates the summary live as the step window changes', async () => {+ await render([reference('a')]);+ await act(() =>+ row('a').querySelector<HTMLButtonElement>('button[aria-label="Reference image 1 settings"]')!.click()+ );++ const [begin] = [...row('a').querySelectorAll<HTMLElement>('[role="slider"][aria-label="Active steps"]')];+ await pressOn(begin!, '{ArrowLeft}');++ expect(stored[0]?.config).toMatchObject({ beginEndStepPct: [0.15, 0.8] });+ expect(rowButton('a').textContent).toContain('Composition · 15–80% · IP Adapter SDXL');+ expect(row('a').textContent).toContain('15–80%');+ });+});++describe('renaming a reference', () => {+ it('renames on a double-click, committing with Enter and handing focus back to the row', async () => {+ await render([reference('a'), reference('b')]);++ await act(() => userEvent.dblClick(rowButton('a')));+ const field = nameField()!;++ expect(field).not.toBeNull();+ expect(document.activeElement).toBe(field);+ // The whole name is selected, ready to be replaced.+ expect([field.selectionStart, field.selectionEnd]).toEqual([0, 'Reference image 1'.length]);+ expect(field.closest('button')).toBeNull();++ await act(() => userEvent.keyboard(' Hero pose {Enter}'));++ expect(nameField()).toBeNull();+ expect(nameOf('a')).toBe('Hero pose');+ expect(stored[0]?.name).toBe('Hero pose');+ await expect.poll(() => document.activeElement).toBe(rowButton('a'));+ });++ it('renames with F2, cancels with Escape, and commits on blur', async () => {+ await render([reference('a', 'Hero pose')]);++ await pressOn(rowButton('a'), '{F2}');+ await act(() => userEvent.keyboard('Something else{Escape}'));++ expect(nameField()).toBeNull();+ expect(nameOf('a')).toBe('Hero pose');+ expect(stored[0]?.name).toBe('Hero pose');+ await expect.poll(() => document.activeElement).toBe(rowButton('a'));++ await pressOn(rowButton('a'), '{F2}');+ await act(() => userEvent.keyboard('Palette'));+ await act(() => addRow().focus());++ expect(nameField()).toBeNull();+ expect(stored[0]?.name).toBe('Palette');+ // Focus stays where it went.+ expect(document.activeElement).toBe(addRow());+ });++ it('renames from the row menu', async () => {+ await render([reference('a')]);++ await act(() =>+ userEvent.click(row('a').querySelector<HTMLElement>('button[aria-label="More actions for Reference image 1"]')!)+ );+ await expect.poll(() => menuItem('rename')).not.toBeNull();+ await act(() => userEvent.click(menuItem('rename')!));++ // The closing menu reclaims focus for its exit animation; the field must keep it.+ await expect.poll(() => document.activeElement).toBe(nameField());+ await act(() => userEvent.keyboard('Lighting{Enter}'));++ expect(stored[0]?.name).toBe('Lighting');+ });++ it("stores no name for an empty name or the row's own default", async () => {+ await render([reference('a', 'Hero pose'), reference('b', 'Palette')]);++ await pressOn(rowButton('a'), '{F2}');+ await act(() => userEvent.keyboard('{Backspace}{Enter}'));+ await pressOn(rowButton('b'), '{F2}');+ await act(() => userEvent.keyboard('reference image 2{Enter}'));++ expect([nameOf('a'), nameOf('b')]).toEqual(['Reference image 1', 'Reference image 2']);+ expect(stored.map((referenceImage) => 'name' in referenceImage)).toEqual([false, false]);+ });++ it("keeps another position's default in the field with its reason, never changing it unseen", async () => {+ await render([reference('a', 'Hero pose'), reference('b'), reference('c')]);++ await pressOn(rowButton('a'), '{F2}');+ await act(() => userEvent.keyboard('Reference image 3'));+ const reason = "Reference image 3 is another reference's default name. Choose a different one.";++ // Said as it is typed, tied to the field, and Enter keeps the field open on it.+ expect(row('a').querySelector('[role="alert"]')?.textContent).toBe(reason);+ expect(nameField()?.getAttribute('aria-invalid')).toBe('true');+ await act(() => userEvent.keyboard('{Enter}'));+ expect(nameField()?.value).toBe('Reference image 3');+ expect(stored[0]?.name).toBe('Hero pose');++ // A name that no longer reads as a default clears the reason and is kept.+ await act(() => userEvent.keyboard(' close-up{Enter}'));+ expect(nameField()).toBeNull();+ expect(stored[0]?.name).toBe('Reference image 3 close-up');+ expect(row('a').querySelector('[role="alert"]')).toBeNull();++ // Leaving the field on a reserved name keeps the name it had.+ await pressOn(rowButton('b'), '{F2}');+ await act(() => userEvent.keyboard('reference image 1'));+ await act(() => addRow().focus());+ expect(nameField()).toBeNull();+ expect(nameOf('b')).toBe('Reference image 2');+ expect('name' in stored[1]!).toBe(false);+ });++ it('leaves Enter and Escape to an IME while it composes, and keeps Escape from reaching the panel', async () => {+ const panelKeys = vi.fn();+ document.body.addEventListener('keydown', panelKeys);+ await render([reference('a', 'Hero pose')]);++ await pressOn(rowButton('a'), '{F2}');+ await act(async () => {+ await commands.imeCompose([{ kind: 'compose', text: 'にほん' }]);+ });+ // The keys that confirm or drop a candidate arrive marked as composing.+ for (const key of ['Enter', 'Escape']) {+ await act(() =>+ nameField()!.dispatchEvent(+ new KeyboardEvent('keydown', { bubbles: true, cancelable: true, isComposing: true, key, keyCode: 229 })+ )+ );+ }+ expect(nameField()).not.toBeNull();++ await act(async () => {+ await commands.imeCompose([{ kind: 'commit', text: '日本' }]);+ });+ await act(() => userEvent.keyboard('{Escape}'));++ expect(nameField()).toBeNull();+ expect(stored[0]?.name).toBe('Hero pose');+ expect(panelKeys).not.toHaveBeenCalledWith(expect.objectContaining({ key: 'Escape' }));+ document.body.removeEventListener('keydown', panelKeys);++ await pressOn(rowButton('a'), '{F2}');+ await act(async () => {+ await commands.imeCompose([{ kind: 'compose', text: 'にほん' }]);+ await commands.imeCompose([{ kind: 'commit', text: '日本' }]);+ });+ await act(() => userEvent.keyboard('{Enter}'));+ expect(stored[0]?.name).toBe('日本');+ });++ it('keeps names with their images through a reorder and the removal of a sibling', async () => {+ await render([reference('a', 'Hero pose'), reference('b'), reference('c', 'Lighting')]);++ await pressOn(rowButton('a'), '{Alt>}{ArrowDown}{/Alt}');+ expect(renderedOrder()).toEqual(['b', 'a', 'c']);+ expect([nameOf('b'), nameOf('a'), nameOf('c')]).toEqual(['Reference image 1', 'Hero pose', 'Lighting']);++ await pressOn(rowButton('b'), '{Delete}');+ expect(renderedOrder()).toEqual(['a', 'c']);+ expect([nameOf('a'), nameOf('c')]).toEqual(['Hero pose', 'Lighting']);+ expect(stored.map(({ id, name }) => [id, name])).toEqual([+ ['a', 'Hero pose'],+ ['c', 'Lighting'],+ ]);+ });+});++describe('reordering and removing references', () => {+ it('moves with Alt+Up and Alt+Down, focus staying on the moved row, and stops at the ends', async () => {+ await render([reference('a'), reference('b'), reference('c')]);++ await pressOn(rowButton('c'), '{Alt>}{ArrowUp}{/Alt}');+ expect(renderedOrder()).toEqual(['a', 'c', 'b']);+ await expect.poll(() => document.activeElement).toBe(rowButton('c'));++ await act(() => userEvent.keyboard('{Alt>}{ArrowUp}{ArrowUp}{/Alt}'));+ expect(renderedOrder()).toEqual(['c', 'a', 'b']);+ await expect.poll(() => document.activeElement).toBe(rowButton('c'));+ });++ it('offers Move up and Move down in the row menu, disabled at the ends', async () => {+ await render([reference('a'), reference('b')]);++ await act(() =>+ userEvent.click(row('a').querySelector<HTMLElement>('button[aria-haspopup="menu"]:not([data-list-primary])')!)+ );+ await expect.poll(() => menuItem('move-up')).not.toBeNull();+ expect(menuItem('move-up')?.hasAttribute('data-disabled')).toBe(true);+ expect(menuItem('move-down')?.hasAttribute('data-disabled')).toBe(false);++ await act(() => userEvent.click(menuItem('move-down')!));+ expect(renderedOrder()).toEqual(['b', 'a']);+ });++ it('removes with Delete only, one row for a held key, and Undo puts it back in place as it was', async () => {+ const cropped = {+ ...reference('b', 'Palette'),+ config: {+ ...reference('b').config,+ image: {+ crop: {+ box: { height: 64, width: 64, x: 0, y: 0 },+ image: { height: 64, image_name: 'b-crop.png', width: 64 },+ ratio: null,+ },+ original: { image: { height: 768, image_name: 'b.png', width: 512 } },+ },+ },+ } as GenerateReferenceImage;+ await render([reference('a'), cropped, reference('c')]);++ // Backspace is for text: on a row it removes nothing.+ await pressOn(rowButton('b'), '{Backspace}');+ expect(renderedOrder()).toEqual(['a', 'b', 'c']);++ // Held, Delete repeats; only its first press removes.+ await pressOn(rowButton('b'), '{Delete>4/}');+ expect(renderedOrder()).toEqual(['a', 'c']);+ expect(undoable).toHaveBeenCalledOnce();+ expect(undoable.mock.calls[0]![0]).toBe('Removed Palette');++ await act(() => undoable.mock.calls[0]![1].onUndo());+ expect(renderedOrder()).toEqual(['a', 'b', 'c']);+ expect(stored[1]).toEqual(cropped);+ await expect.poll(() => document.activeElement).toBe(rowButton('b'));+ });++ it('removes from the row menu, undoably', async () => {+ await render([reference('a'), reference('b')]);++ await act(() =>+ userEvent.click(row('a').querySelector<HTMLElement>('button[aria-haspopup="menu"]:not([data-list-primary])')!)+ );+ await expect.poll(() => menuItem('remove')).not.toBeNull();+ await act(() => userEvent.click(menuItem('remove')!));+ expect(renderedOrder()).toEqual(['b']);+ expect(undoable.mock.calls[0]![0]).toBe('Removed Reference image 1');++ await act(() => undoable.mock.calls[0]![1].onUndo());+ expect(renderedOrder()).toEqual(['a', 'b']);+ });++ it('removes with Delete, focusing the next row, else the previous one, else the add row', async () => {+ await render([reference('a'), reference('b'), reference('c')]);++ await pressOn(rowButton('b'), '{Delete}');+ expect(renderedOrder()).toEqual(['a', 'c']);+ await expect.poll(() => document.activeElement).toBe(rowButton('c'));++ await act(() => userEvent.keyboard('{Delete}'));+ await expect.poll(() => document.activeElement).toBe(rowButton('a'));++ await act(() => userEvent.keyboard('{Delete}'));+ expect(renderedOrder()).toEqual([]);+ await expect.poll(() => document.activeElement).toBe(addRow());+ });+});++describe('references the model cannot use', () => {+ it('stay listed but inert, badged, with Remove all above them', async () => {+ await render([reference('a', 'Hero pose')], COGVIEW);++ const button = rowButton('a');+ expect(row('a').textContent).toContain('Incompatible');+ expect(button.getAttribute('aria-disabled')).toBe('true');+ expect(row('a').querySelector('[inert]')).not.toBeNull();+ expect(host.textContent).toContain('Remove all');+ expect(host.querySelector('[data-reference-add]')).toBeNull();++ // Renaming, moving and removing all wait for a model that takes references.+ await act(() => button.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));+ await pressOn(button, '{F2}');+ await pressOn(button, '{Delete}');+ expect(nameField()).toBeNull();+ expect(stored).toHaveLength(1);+ });+});++describe('a narrow Generate panel', () => {+ it('keeps every control of three references, one of them open, inside 350px', async () => {+ // The Generate panel at its narrowest, with the section's own padding the rows reach into.+ host.style.cssText = 'box-sizing:border-box;padding:0 8px;width:350px;';+ await render([+ reference('a', 'A name long enough to need truncating at this width'),+ reference('b'),+ reference('c'),+ ]);+ await act(() => row('a').querySelector<HTMLButtonElement>('button[aria-label^="A name long"]')!.click());++ const bounds = host.getBoundingClientRect();+ const controls = [+ ...host.querySelectorAll<HTMLElement>(+ 'button, [role="slider"], [role="radio"], input:not([type="hidden"]), [role="combobox"]'+ ),+ ]+ // The changed-value dot sits in the gutter left of its field, as on a concept row, reaching into the panel's edge.+ .filter((element) => element.getClientRects().length > 0 && !element.hasAttribute('data-modified-dot'));++ expect(controls.length).toBeGreaterThan(10);+ for (const control of controls) {+ const rect = control.getBoundingClientRect();+ expect(rect.left).toBeGreaterThanOrEqual(bounds.left - 0.5);+ expect(rect.right).toBeLessThanOrEqual(bounds.right + 0.5);+ }+ expect(list().scrollWidth).toBeLessThanOrEqual(list().clientWidth);+ });+});++describe('a reference that blocks Invoke', () => {+ const unadapted = (id: string): GenerateReferenceImage => {+ const referenceImage = reference(id);+ return referenceImage.config.type === 'ip_adapter'+ ? { ...referenceImage, config: { ...referenceImage.config, model: null } }+ : referenceImage;+ };+ const issueIcon = () => row('a').querySelector<HTMLButtonElement>('button[data-issue-ids]');+ const fixButton = () => document.querySelector<HTMLButtonElement>('[data-issue-id] [data-issue-fix]');++ it('turns off from the issue popover, which resolves the issue and hands focus to the switch', async () => {+ await render([unadapted('a')]);+ // The row grows no line for its issue.+ expect(row('a').querySelector('[data-issue-notes]')).toBeNull();++ await act(() => userEvent.click(issueIcon()!));+ await expect.poll(() => fixButton()?.textContent).toBe('Turn off');+ await act(() => userEvent.click(fixButton()!));++ expect(stored[0]?.isEnabled).toBe(false);+ expect(issueIcon()).toBeNull();+ await expect.poll(() => fixButton()).toBeNull();+ await expect.poll(() => document.activeElement).toBe(row('a').querySelector('[data-scope="switch"] input'));+ });++ it('opens from the Invoke issue list, so the message and its fix show', async () => {+ await render([reference('ok'), unadapted('a')]);+ const [issue] = needsAdapterIssues(stored);++ await act(async () => {+ revealGenerateIssue(issue!);+ await new Promise(requestAnimationFrame);+ });++ await expect.poll(() => fixButton()?.closest('[data-issue-id]')?.textContent).toContain(issue!.message);+ expect(issueIcon()?.getAttribute('aria-expanded')).toBe('true');+ });+});++describe('a reference without its model', () => {+ const unadaptedNamed = (id: string, name?: string): GenerateReferenceImage => {+ const referenceImage = reference(id, name);+ return referenceImage.config.type === 'ip_adapter'+ ? { ...referenceImage, config: { ...referenceImage.config, model: null } }+ : referenceImage;+ };+ const chevron = () => row('a').querySelector<HTMLButtonElement>('button[aria-controls]')!;+ const issueIcon = () => row('a').querySelector<HTMLButtonElement>('button[data-issue-ids]');++ it("names its issue by the reference's name and opens no settings on its own when it loads", async () => {+ await render([unadaptedNamed('a', 'Hero pose')]);++ expect(chevron().getAttribute('aria-expanded')).toBe('false');+ expect(issueIcon()?.getAttribute('aria-label')).toBe('1 issue: Hero pose needs an IP Adapter model for SDXL.');+ });++ it('offers Choose model when a model switch leaves it without one, opening the settings on the picker', async () => {+ await render([reference('a')], SDXL, SDXL_ADAPTERS);+ expect(issueIcon()).toBeNull();++ // A switch to a model whose adapters are not installed leaves the same row without one.+ await act(() => setStored([unadaptedNamed('a')]));+ expect(chevron().getAttribute('aria-expanded')).toBe('false');++ await act(() => userEvent.click(issueIcon()!));+ const action = () => document.querySelector<HTMLButtonElement>('[data-issue-id] [data-issue-action]');+ await expect.poll(() => action()?.textContent).toBe('Choose model');+ expect(document.querySelector('[data-issue-id] [data-issue-fix]')?.textContent).toBe('Turn off');+ await act(() => userEvent.click(action()!));++ expect(chevron().getAttribute('aria-expanded')).toBe('true');+ await expect.poll(() => document.activeElement?.closest('[data-reference-model]')).not.toBeNull();+ expect(stored[0]?.isEnabled).toBe(true);+ });++ it('offers the Model Manager instead when no model it could use is installed', async () => {+ openManager.mockClear();+ await render([unadaptedNamed('a')]);++ await act(() => userEvent.click(issueIcon()!));+ const action = () => document.querySelector<HTMLButtonElement>('[data-issue-id] [data-issue-action]');+ await expect.poll(() => action()?.textContent).toBe('Open Model Manager');+ await act(() => userEvent.click(action()!));++ expect(openManager).toHaveBeenCalledExactlyOnceWith({ modelType: 'ip_adapter' });+ expect(chevron().getAttribute('aria-expanded')).toBe('false');+ });+});++describe('positional default names', () => {+ const translatorFor = async (template: string) => {+ const instance = i18next.createInstance();+ await instance.init({+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: { widgets: { generate: { referenceImageNumbered: template } } } } },+ });+ return instance.t.bind(instance);+ };++ it('match any position in the locale wording, and give up safely on templates they cannot read', async () => {+ const english = getPositionalDefaultNameTest(await translatorFor('Reference image {{index}}'))!;+ expect(['Reference image 3', ' reference image 12 '].map(english)).toEqual([true, true]);+ expect(['Reference image', 'Reference image 3 close-up', 'Hero pose'].map(english)).toEqual([false, false, false]);++ expect(getPositionalDefaultNameTest(await translatorFor('{{index}}. Referenzbild'))!('2. referenzbild')).toBe(true);+ // A bare number, or a formatter that loses the placeholder, would reserve names it should not: no pattern.+ expect(getPositionalDefaultNameTest(await translatorFor('{{index}}'))).toBeNull();+ expect(getPositionalDefaultNameTest(await translatorFor('Image {{index, number}}'))).toBeNull();+ });+});++describe('a FLUX Kontext reference', () => {+ it('can become a Redux reference by picking a Redux model, as before', async () => {+ const kontext: GenerateReferenceImage = {+ config: {+ image: { original: { image: { height: 512, image_name: 'k.png', width: 512 } } },+ model: null,+ type: 'flux_kontext_reference_image',+ },+ id: 'a',+ isEnabled: true,+ };+ await render([kontext], FLUX);++ expect(offeredModelTypes).toEqual(['ip_adapter', 'flux_redux']);+ await act(() => userEvent.click(row('a').querySelector<HTMLButtonElement>('[data-reference-model] button')!));++ expect(stored[0]?.config).toMatchObject({ imageInfluence: 'highest', model: REDUX, type: 'flux_redux' });+ });+});++describe('row summaries and surfaces', () => {+ const t = i18n.t.bind(i18n);+ const image = { original: { image: { height: 768, image_name: 'x.png', width: 512 } } };+ const crop = {+ box: { height: 300, width: 200, x: 0, y: 0 },+ image: { height: 300, image_name: 'c.png', width: 200 },+ ratio: null,+ };++ it('says what each family does, in the words its controls use', () => {+ expect(describeReferenceImage({ image, imageInfluence: 'low', model: null, type: 'flux_redux' }, false, t)).toBe(+ 'No model'+ );+ expect(+ describeReferenceImage(+ {+ image,+ imageInfluence: 'low',+ model: { base: 'flux', key: 'r', name: 'FLUX Redux', type: 'flux_redux' },+ type: 'flux_redux',+ },+ false,+ t+ )+ ).toBe('FLUX Redux');+ expect(describeReferenceImage({ image, model: null, type: 'flux_kontext_reference_image' }, false, t)).toBe(+ '512 × 768'+ );+ expect(describeReferenceImage({ image, type: 'flux2_reference_image' }, false, t)).toBe('512 × 768');+ expect(describeReferenceImage({ image: { ...image, crop }, type: 'flux2_reference_image' }, false, t)).toBe(+ '200 × 300 · cropped'+ );+ expect(describeReferenceImage({ image: null, type: 'flux2_reference_image' }, false, t)).toBe('No image');+ });++ it("backs every control of an open row with its own surface, so the row's hover tint never washes it out", async () => {+ await render([reference('a')]);+ await act(() => row('a').querySelector<HTMLButtonElement>('button[aria-controls]')!.click());++ const controls = [+ ...row('a').querySelectorAll<HTMLElement>(+ '[data-scope="scrubber"], [data-scope="segment-group"][data-part="root"], [data-scope="select"][data-part="trigger"], [data-reference-model] button, [role="slider"][aria-label="Active steps"]'+ ),+ ];++ expect(controls.length).toBeGreaterThanOrEqual(5);+ for (const control of controls) {+ expect(control.closest('[data-control-surface]')).not.toBeNull();+ }+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageSlots.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageSlots.browser.test.tsxindex ee6ab1e88b..7befa8b9e9 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageSlots.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageSlots.browser.test.tsx@@ -6,7 +6,11 @@ import { ChakraProvider } from '@chakra-ui/react';import { DndContext, MouseSensor, pointerWithin, useDraggable, useSensor, useSensors } from '@dnd-kit/core';import { getGalleryItemDragData } from '@features/gallery/utility';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';-import { getDefaultGenerateSettings, getMaxReferenceImages } from '@features/generation/core/baseGenerationPolicies';+import {+ getDefaultGenerateSettings,+ getGenerateInvocationIssues,+ getMaxReferenceImages,+} from '@features/generation/core/baseGenerationPolicies';import { type GenerationUiAdapter, GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';import { GenerateIssuesProvider } from '@features/generation/ui/shared/GenerateIssues';import { dragWithMouse } from '@platform/browser/mouseDrag.testing';@@ -16,7 +20,7 @@ import { act, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { commands } from 'vitest/browser';+import { commands, userEvent } from 'vitest/browser';import { GenerateReferenceImagesContent } from './GenerateReferenceImagesSection';@@ -56,7 +60,8 @@ const reference = (id: string): GenerateReferenceImage => ({clipVisionModel: 'ViT-H',image: { original: { image: { height: 512, image_name: `${id}.png`, width: 512 } } },method: 'full',- model: null,+ // With its adapter chosen, a row starts with its settings closed.+ model: { base: 'sdxl', key: 'ip-adapter-sdxl', name: 'IP Adapter SDXL', type: 'ip_adapter' },type: 'ip_adapter',weight: 1,},@@ -68,9 +73,11 @@ const info = vi.fn();const undoable = vi.fn();const patchGenerateSettings = vi.fn();let storedValues: Record<string, unknown> | null = null;+/** The installed models as the store holds them now, which an Undo reads when it runs. */+let catalog: readonly { base: string; key: string; name: string; type: string }[] = [];const ADAPTER = {gallery: { findImage: vi.fn() },- models: { ModelSelect: () => null, getBaseLabel: (base: string) => base },+ models: { ModelSelect: () => null, getBaseLabel: (base: string) => base, readCatalog: () => catalog },notifications: { info, undoable },project: { activeProjectId: 'project-1' },settings: { patchGenerateSettings, readGenerateValues: () => storedValues },@@ -107,15 +114,19 @@ const Dnd = ({ children }: { children: ReactNode }) => {};const render = async ({+ applyFix = vi.fn(),dragged = 0,issues = [],+ models = NO_MODELS,onCommit = vi.fn(),onCommitImmediate = vi.fn(),referenceImages,selectedModel = SDXL,}: {+ applyFix?: (fix: unknown) => void;dragged?: number;issues?: GenerationIssue[];+ models?: readonly { base: string; key: string; name: string; type: string }[];onCommit?: (update: unknown) => void;onCommitImmediate?: (patch: unknown) => void;referenceImages: GenerateReferenceImage[];@@ -126,12 +137,12 @@ const render = async ({<I18nextProvider i18n={i18n}><ChakraProvider value={system}><GenerationUiProvider adapter={ADAPTER}>- <GenerateIssuesProvider applyFix={vi.fn()} issues={issues}>+ <GenerateIssuesProvider applyFix={applyFix} issues={issues}><Dnd>{dragged > 0 ? <DraggedSelection count={dragged} /> : null}<div data-testid="section"><GenerateReferenceImagesContent- models={NO_MODELS}+ models={models}visionComponents={NO_VISION_COMPONENTS}referenceImages={referenceImages}selectedModel={selectedModel}@@ -165,6 +176,7 @@ beforeEach(() => {undoable.mockClear();patchGenerateSettings.mockClear();storedValues = null;+ catalog = [];});afterEach(async () => {@@ -210,6 +222,83 @@ describe('removing every reference', () => {});});+describe('undoing a removal after a model switch', () => {+ const FLUX: GenerateModelConfig = {+ base: 'flux',+ format: 'diffusers',+ key: 'flux-dev',+ name: 'FLUX.1 dev',+ type: 'main',+ };+ const FLUX_IP_ADAPTER = { base: 'flux', key: 'ip-adapter-flux', name: 'IP Adapter FLUX', type: 'ip_adapter' };+ /** Removes the reference from its row, as Delete does there; the commit applies at once, as the form's does. */+ const renderAndRemove = async (removed: GenerateReferenceImage) => {+ let settings = { ...getDefaultGenerateSettings(SDXL), referenceImages: [removed] };+ const onCommit = (update: unknown) => {+ settings = typeof update === 'function' ? update(settings) : { ...settings, ...(update as object) };+ };++ await render({ onCommit, referenceImages: [removed] });+ await act(() =>+ host!.querySelector<HTMLElement>(`[data-reference-image-id="${removed.id}"] [data-list-primary]`)!.focus()+ );+ await act(() => userEvent.keyboard('{Delete}'));++ expect(settings.referenceImages).toEqual([]);+ expect(undoable).toHaveBeenCalledOnce();+ };+ const restoredAfterSwitchTo = async (model: GenerateModelConfig) => {+ // Since the removal the user switched to `model`, which left no references.+ storedValues = { ...getDefaultGenerateSettings(model), model, modelKey: model.key, referenceImages: [] };+ await act(() => undoable.mock.calls[0]![1].onUndo());++ return (patchGenerateSettings.mock.calls[0] as [{ referenceImages: GenerateReferenceImage[] }])[0].referenceImages;+ };++ it("brings an SDXL IP-Adapter reference back on FLUX's adapter installed since, as the switch would, and Invoke can run", async () => {+ const removed = reference('palette');++ await renderAndRemove(removed);+ // Installed after the removal: the Undo reads the catalog as it is when it runs.+ catalog = [FLUX_IP_ADAPTER];++ const restored = await restoredAfterSwitchTo(FLUX);++ expect(restored).toEqual([+ {+ config: {+ beginEndStepPct: [0, 1],+ clipVisionModel: 'ViT-L',+ image: removed.config.image,+ method: 'full',+ model: FLUX_IP_ADAPTER,+ type: 'ip_adapter',+ weight: 1,+ },+ id: 'palette',+ isEnabled: true,+ },+ ]);+ // Nothing about the references holds Invoke back (the bare FLUX fixture still lacks its encoders).+ expect(+ getGenerateInvocationIssues({+ ...getDefaultGenerateSettings(FLUX),+ model: FLUX,+ referenceImages: restored,+ }).filter((issue) => issue.target.section === 'guidance')+ ).toEqual([]);+ });++ it('brings a reference back switched off on a model that takes none', async () => {+ const COGVIEW: GenerateModelConfig = { base: 'cogview4', key: 'cogview4', name: 'CogView4', type: 'main' };+ const removed = reference('palette');++ await renderAndRemove(removed);++ expect(await restoredAfterSwitchTo(COGVIEW)).toEqual([{ ...removed, isEnabled: false }]);+ });+});+describe('reference image slots', () => {it('counts the slots in use on the add zone, and says why it is disabled once they are full', async () => {expect(max()).toBeGreaterThan(1);@@ -289,8 +378,9 @@ describe('reference image slots', () => {expect(onCommit).not.toHaveBeenCalled();});- it("shows a reference's issue on its own card and the limit above the cards", async () => {+ it("shows a reference's issue as an icon on its own row, which opens it with its fix, and the limit above the list", async () => {const referenceImages = references(2);+ const applyFix = vi.fn();const cardIssue: GenerationIssue = {fix: { kind: 'turnOffReferenceImages', referenceImageIds: ['ref-1'] },id: 'referenceImages:needsIpAdapter:ref-1',@@ -303,21 +393,43 @@ describe('reference image slots', () => {target: { field: 'referenceImages', section: 'guidance' },};- await render({ issues: [cardIssue, limitIssue], referenceImages });-- const cards = [...host!.querySelectorAll<HTMLElement>('[data-issue-notes]')];- // The nearest ancestor of the second card's title holding notes is that card.- let secondCard: HTMLElement | null = [...host!.querySelectorAll('p')].find(- (title) => title.textContent === 'Reference image 2'- )!;- while (secondCard && !secondCard.querySelector('[data-issue-notes]')) {- secondCard = secondCard.parentElement;- }-- expect(cards).toHaveLength(2);- expect(secondCard?.textContent).toContain(cardIssue.message);- expect(secondCard?.textContent).not.toContain(limitIssue.message);- expect(secondCard?.querySelector('[data-issue-fix]')?.textContent).toBe('Turn off');- expect(cards[0]?.textContent).toBe(limitIssue.message);+ await render({ applyFix, issues: [cardIssue, limitIssue], referenceImages });++ const notes = [...host!.querySelectorAll<HTMLElement>('[data-issue-notes]')];+ const firstRow = host!.querySelector<HTMLElement>('[data-reference-image-id="ref-0"]')!;+ const secondRow = host!.querySelector<HTMLElement>('[data-reference-image-id="ref-1"]')!;+ const icon = secondRow.querySelector<HTMLButtonElement>('button[data-issue-ids]')!;++ // Only the row with an issue shows the icon, beside its switch, named by what is wrong.+ expect(firstRow.querySelector('[data-issue-ids]')).toBeNull();+ expect(icon.getAttribute('aria-label')).toBe(`1 issue: ${cardIssue.message}`);+ expect(icon.closest('[role="group"]')?.querySelector('[data-scope="switch"]')).not.toBeNull();+ expect(secondRow.textContent).not.toContain(cardIssue.message);+ // The group's issue sits above the list, outside every row.+ expect(notes).toHaveLength(1);+ expect(notes[0]?.closest('[role="list"]')).toBeNull();+ expect(notes[0]?.textContent).toBe(limitIssue.message);++ // The tooltip reads exactly as the icon's name, so assistive tech says it once.+ await act(() => userEvent.hover(icon));+ await expect+ .poll(() => [...document.querySelectorAll('[role="tooltip"]')].map((tooltip) => tooltip.textContent))+ .toContain(`1 issue: ${cardIssue.message}`);++ await act(() => userEvent.click(icon));+ const popover = () => document.querySelector<HTMLElement>(`[data-issue-id="${cardIssue.id}"]`);+ await expect.poll(() => popover()?.textContent).toContain(cardIssue.message);+ expect(popover()?.querySelector('[data-issue-fix]')?.textContent).toBe('Turn off');++ // Escape closes it and gives focus back to the icon.+ await act(() => userEvent.keyboard('{Escape}'));+ await expect.poll(() => popover()).toBeNull();+ expect(document.activeElement).toBe(icon);++ // The keyboard opens it too; Turn off applies the fix.+ await act(() => userEvent.keyboard('{Enter}'));+ await expect.poll(() => popover()?.querySelector('[data-issue-fix]')).not.toBeNull();+ await act(() => popover()!.querySelector<HTMLButtonElement>('[data-issue-fix]')!.click());+ expect(applyFix).toHaveBeenCalledExactlyOnceWith(cardIssue.fix);});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/revealGenerateIssue.ts b/invokeai/frontend/webv2/src/features/generation/ui/revealGenerateIssue.tsindex 2a94f20662..2ee2e3e6e1 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/revealGenerateIssue.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/revealGenerateIssue.ts@@ -4,10 +4,11 @@ import type { GenerationIssue } from '@features/generation/core/generationIssuesconst REVEAL_WAIT_MS = 1500;/**- * Brings one Generate issue into view once the panel shows it: the note under its field (by `data-issue-id`), else its- * section (by `data-generate-section`), for a control that shows the message itself. Focus goes to the note's- * one-step fix, else the section header, so the next key acts where the problem is. The caller opens the panel and the- * section first; a reveal whose panel never renders gives up quietly.+ * Brings one Generate issue into view once the panel shows it: the note under its field (by `data-issue-id`), else the+ * issue icon on its list row (by `data-issue-ids`), which it opens so the message and fix show, else its section (by+ * `data-generate-section`), for a control that shows the message itself. Focus goes to the note's one-step fix, the+ * icon's popover, else the section header, so the next key acts where the problem is. The caller opens the panel and+ * the section first; a reveal whose panel never renders gives up quietly.*/export const revealGenerateIssue = (issue: Pick<GenerationIssue, 'id' | 'target'>): void => {const deadline = performance.now() + REVEAL_WAIT_MS;@@ -17,9 +18,10 @@ export const revealGenerateIssue = (issue: Pick<GenerationIssue, 'id' | 'target'(element) => element.getClientRects().length > 0);const note = frame?.querySelector<HTMLElement>(`[data-issue-id="${CSS.escape(issue.id)}"]`);+ const icon = note ? null : frame?.querySelector<HTMLElement>(`[data-issue-ids~="${CSS.escape(issue.id)}"]`);const section = frame?.querySelector<HTMLElement>(`[data-generate-section="${CSS.escape(issue.target.section)}"]`);// A section the reveal just opened may not show its notes yet; it stands in only once it is open.- const anchor = note ?? (section?.dataset.state === 'closed' ? undefined : section);+ const anchor = note ?? icon ?? (section?.dataset.state === 'closed' ? undefined : section);if (!anchor) {if (performance.now() < deadline) {@@ -28,7 +30,18 @@ export const revealGenerateIssue = (issue: Pick<GenerationIssue, 'id' | 'target'return;}+ // A section's fields carry a scroll margin, so an anchor above the view stops below its pinned section title.anchor.scrollIntoView({ block: 'nearest' });++ if (icon) {+ icon.focus({ preventScroll: true });+ // The popover takes focus to its fix; an icon already open stays open.+ if (icon.getAttribute('aria-expanded') !== 'true') {+ icon.click();+ }+ return;+ }+(note?.querySelector<HTMLElement>('[data-issue-fix]') ??section?.querySelector<HTMLElement>('[data-scope="collapsible"][data-part="trigger"], button, input')diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.tsxindex 230b162b11..4756d98363 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/ConceptRow.tsx@@ -3,7 +3,7 @@ import type { ConceptUpdate } from '@features/generation/core/conceptList';import type { GenerateLora } from '@features/generation/core/types';import type { MouseEvent, ReactNode } from 'react';-import { Avatar, Badge, Box, Flex, Icon, Menu, Portal } from '@chakra-ui/react';+import { Avatar, Badge, Box, chakra, Flex, Icon, Menu, Portal } from '@chakra-ui/react';import { DEFAULT_LORA_WEIGHT_CONFIG, getDefaultLoraWeight } from '@features/generation/core/settings';import { useDebouncedDraftValue } from '@features/generation/ui/useDebouncedDraftValue';import { useRegisterDraftFlusher } from '@platform/react/draftRegistry';@@ -40,7 +40,7 @@ export interface ConceptRowProps {* saved state but is locked, and `issue` says what blocks and how to fix it.*/isInstalled?: boolean;- /** Shown under the row: the issue that blocks Invoke because of this concept, with its fix. */+ /** Shown beside the switch: the issue that blocks Invoke because of this concept, with its fix (an icon button). */issue?: ReactNode;/** The committed concept. Weight edits stay in a local draft until idle or a workbench flush. */lora: GenerateLora;@@ -213,7 +213,8 @@ const ConceptRowContent = ({<Box aria-label={name} opacity={isCompatibleModel ? 1 : 0.68} role="group"><ListItemactions={- <Flex gap={1}>+ <Flex align="center" gap={1}>+ {issue}<GenerateRowSwitchchecked={isInstalled ? isActive : lora.isEnabled}disabled={!isCompatible}@@ -237,27 +238,32 @@ const ConceptRowContent = ({</Tooltip></Flex>}- badges={- <>- <Badge colorPalette={models.getBaseColorPalette(lora.model.base)} variant="surface">+ // The model type sits under the name, with the trigger phrases beside it on the same line.+ description={+ <Flex align="center" gap="1.5" minW="0">+ <Badge colorPalette={models.getBaseColorPalette(lora.model.base)} flexShrink={0} variant="surface">{models.getBaseLabel(lora.model.base)}</Badge>{isInstalled ? null : (- <Badge colorPalette="red" variant="solid">+ <Badge colorPalette="red" flexShrink={0} variant="solid">{t('widgets.generate.notInstalled')}</Badge>)}{isCompatibleModel ? null : (- <Badge colorPalette="orange" variant="surface">+ <Badge colorPalette="orange" flexShrink={0} variant="surface">{t('widgets.generate.incompatible')}</Badge>)}- </>+ {triggerPhrases?.length ? (+ <chakra.span minW="0" truncate>+ {triggerPhrases.join(', ')}+ </chakra.span>+ ) : null}+ </Flex>}- description={triggerPhrases?.length ? triggerPhrases.join(', ') : undefined}detail={- // Backed with the settings section's surface so the row's hover tint never washes out the track and fill.- <Box bg="bg.muted" rounded="control">+ // Backed with the widget's surface so the row's hover tint never washes out the track and fill.+ <Box bg="var(--wb-field-surface, var(--chakra-colors-bg-subtle))" rounded="control"><GenerateFieldContextMenufieldLabel={t('widgets.generate.conceptWeightNamed', { name })}copyValue={copyWeight}@@ -306,11 +312,6 @@ const ConceptRowContent = ({onContextMenu={menu.open}/></Box>- {issue ? (- <Box pb="1.5" px="2">- {issue}- </Box>- ) : null}<Menu.RootlazyMountopen={menu.anchor !== null}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.browser.test.tsxindex 52f9504a2b..8571c5a6ec 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.browser.test.tsx@@ -1,22 +1,79 @@+/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-new-function-as-prop */+import type { GenerationIssue } from '@features/generation/core/generationIssues';+import { ChakraProvider } from '@chakra-ui/react';+import { revealGenerateIssue } from '@features/generation/ui/revealGenerateIssue';import { system } from '@theme/system';-import { act } from 'react';+import { act, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';import { GenerateCollapsibleSection } from './GenerateCollapsibleSection';+import { GenerateIssueNotes, GenerateIssuesProvider } from './GenerateIssues';+import { GenerationSectionJumpMenu } from './GenerationSectionJumpMenu';+import { GenerationSectionPanel } from './sectionPanel';++/** The user's persisted open states, as the preference port reads and writes them. */+const preferences = vi.hoisted(() => {+ let sectionsOpen: Readonly<Record<string, boolean>> = {};+ const listeners = new Set<() => void>();++ return {+ get: () => sectionsOpen,+ reset: (next: Readonly<Record<string, boolean>>) => {+ sectionsOpen = next;+ },+ setSectionsOpen: (changes: Readonly<Record<string, boolean>>) => {+ sectionsOpen = { ...sectionsOpen, ...changes };+ listeners.forEach((listener) => listener());+ },+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+});+const copied = vi.hoisted(() => ({ text: [] as string[] }));++vi.mock('@features/generation/ui/GenerationUiContext', async () => {+ const { useSyncExternalStore } = await import('react');++ return {+ useGenerationUi: () => ({+ sectionPreferences: {+ sectionsOpen: useSyncExternalStore(preferences.subscribe, preferences.get),+ setSectionsOpen: preferences.setSectionsOpen,+ },+ }),+ };+});-vi.mock('@features/generation/ui/GenerationUiContext', () => ({- useGenerationUi: () => ({- sectionPreferences: { sectionsOpen: {}, setSectionOpen: vi.fn() },+// Keys stand in for copy; values show what each string was built from.+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: Record<string, unknown>) => (values ? `${key} ${JSON.stringify(values)}` : key),}),}));+vi.mock('@platform/browser/clipboard', () => ({+ canCopyText: () => true,+ copyText: (text: string) => {+ copied.text.push(text);+ return Promise.resolve();+ },+}));+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;let host: HTMLDivElement | null = null;let root: Root | null = null;+beforeEach(() => {+ preferences.reset({});+ copied.text = [];+});+afterEach(async () => {await act(() => root?.unmount());host?.remove();@@ -24,7 +81,7 @@ afterEach(async () => {root = null;});-const render = async (children: React.ReactNode) => {+const render = async (children: ReactNode) => {host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -34,18 +91,454 @@ const render = async (children: React.ReactNode) => {});};+const section = (label: string) =>+ [...document.querySelectorAll<HTMLElement>('.generate-section')].find(+ (candidate) => candidate.querySelector('[data-section-chip]')?.textContent?.startsWith(label) ?? false+ )!;+const title = (label: string) => section(label).querySelector<HTMLButtonElement>(':scope > [data-part="trigger"]')!;+const states = (...labels: string[]) => labels.map((label) => section(label).dataset.state);++/** Two panels side by side, as Generate and Upscale can be: persisted and uncontrolled sections in the first. */+const renderTwoPanels = () =>+ render(+ <>+ <GenerationSectionPanel id="generate">+ <GenerateCollapsibleSection defaultOpen label="Size" sectionId="size">+ <input aria-label="Width" />+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection label="Render" sectionId="render">+ <div>steps</div>+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection defaultOpen label="Fill">+ <div>fill</div>+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ <GenerationSectionPanel id="upscale">+ <GenerateCollapsibleSection defaultOpen label="Source" sectionId="source">+ <div>source</div>+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ </>+ );+describe('GenerateCollapsibleSection', () => {- it('styles by DOM state so uncontrolled sections (no sectionId) still read as cards', async () => {+ it('styles by DOM state so uncontrolled sections (no sectionId) still tell open from closed', async () => {// defaultOpen-only consumers require DOM-state styling.await render(- <GenerateCollapsibleSection defaultOpen label="Uncontrolled">+ <>+ <GenerateCollapsibleSection defaultOpen label="Open">+ <div>body</div>+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection label="Closed">+ <div>body</div>+ </GenerateCollapsibleSection>+ </>+ );++ expect(title('Open').dataset.state).toBe('open');+ expect(title('Closed').dataset.state).toBe('closed');+ expect(getComputedStyle(title('Open')).color).not.toBe(getComputedStyle(title('Closed')).color);+ });++ it('solos a section on Alt-click, within its own panel only, persisting the persisted ones in one write', async () => {+ // Spied before rendering, as sections read the port when they render.+ const write = vi.spyOn(preferences, 'setSectionsOpen');+ await renderTwoPanels();++ await act(() => userEvent.click(title('Render'), { modifiers: ['Alt'] }));++ expect(states('Size', 'Render', 'Fill', 'Source')).toEqual(['closed', 'open', 'closed', 'open']);+ expect(write).toHaveBeenCalledOnce();+ expect(write).toHaveBeenCalledWith({ render: true, size: false });+ write.mockRestore();+ });++ it('opens every section on Shift-click while any is folded, then folds them all', async () => {+ await renderTwoPanels();++ await act(() => userEvent.click(title('Fill'), { modifiers: ['Shift'] }));+ expect(states('Size', 'Render', 'Fill', 'Source')).toEqual(['open', 'open', 'open', 'open']);+ expect(preferences.get()).toEqual({ render: true });++ await act(() => userEvent.click(title('Fill'), { modifiers: ['Shift'] }));+ expect(states('Size', 'Render', 'Fill', 'Source')).toEqual(['closed', 'closed', 'closed', 'open']);+ expect(preferences.get()).toEqual({ render: false, size: false });+ });++ it('moves between titles with the arrow, Home and End keys, and opens and folds with right and left', async () => {+ await renderTwoPanels();+ title('Size').focus();++ await userEvent.keyboard('{ArrowDown}');+ expect(document.activeElement).toBe(title('Render'));+ await userEvent.keyboard('{End}');+ expect(document.activeElement).toBe(title('Fill'));+ // The last title in its panel: the next panel's titles are not its rows.+ await userEvent.keyboard('{ArrowDown}');+ expect(document.activeElement).toBe(title('Fill'));+ await userEvent.keyboard('{Home}');+ expect(document.activeElement).toBe(title('Size'));+ await userEvent.keyboard('{ArrowUp}');+ expect(document.activeElement).toBe(title('Size'));++ await userEvent.keyboard('{ArrowLeft}');+ expect(states('Size')).toEqual(['closed']);+ await userEvent.keyboard('{ArrowRight}');+ expect(states('Size')).toEqual(['open']);+ await userEvent.keyboard('{Enter}');+ expect(states('Size')).toEqual(['closed']);+ });++ it('leaves arrow keys typed in a field to the field', async () => {+ await renderTwoPanels();+ const width = page.getByLabelText('Width');++ await userEvent.click(width);+ await userEvent.keyboard('{ArrowDown}{ArrowLeft}');++ expect(document.activeElement).toBe(width.element());+ expect(states('Size')).toEqual(['open']);+ });++ it('shows value summaries only while folded and keeps status badges either way', async () => {+ await render(+ <GenerationSectionPanel>+ <GenerateCollapsibleSection+ defaultOpen+ label="Size"+ sectionId="size"+ status={<span data-testid="status">Shared</span>}+ summary={['1024×1024', null, 'Locked']}+ >+ <div>body</div>+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ );+ const summary = () => title('Size').querySelector<HTMLElement>('[data-section-summary]')!;++ expect(summary().getAttribute('aria-hidden')).toBe('true');+ await expect.poll(() => getComputedStyle(summary()).visibility).toBe('hidden');+ expect(title('Size').querySelector('[data-testid="status"]')).not.toBeNull();++ await act(() => userEvent.click(title('Size')));++ expect(summary().getAttribute('aria-hidden')).toBeNull();+ await expect.poll(() => getComputedStyle(summary()).visibility).toBe('visible');+ // Skipped items leave no empty separator behind.+ expect([...summary().children].map((item) => item.textContent)).toEqual(['1024×1024', 'Locked']);+ await expect.element(page.getByRole('button', { name: /Size.*1024×1024.*Locked.*Shared/ })).toBeVisible();+ });++ it('tints the chip and counts the issues inside it, open or folded', async () => {+ const issue = { id: 'size-grid', message: 'Off the grid', target: { section: 'dimensions' } } as GenerationIssue;+ await render(+ <GenerateIssuesProvider applyFix={() => undefined} issues={[issue, { ...issue, id: 'size-other' }]}>+ <GenerateCollapsibleSection label="Size" sectionId="dimensions">+ <div>body</div>+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection label="Render" sectionId="render">+ <div>body</div>+ </GenerateCollapsibleSection>+ </GenerateIssuesProvider>+ );+ const chip = (label: string) => title(label).querySelector<HTMLElement>('[data-section-chip]')!;++ expect(chip('Size').querySelector('[data-section-issues]')?.textContent).toContain('widgets.generate.issueCount');+ expect(getComputedStyle(chip('Size')).backgroundColor).not.toBe(getComputedStyle(chip('Render')).backgroundColor);+ expect(chip('Render').querySelector('[data-section-issues]')).toBeNull();+ });++ it('marks a changed section with a dot that names itself', async () => {+ await render(+ <>+ <GenerateCollapsibleSection isChanged label="Render">+ <div>body</div>+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection isChanged={false} label="Size">+ <div>body</div>+ </GenerateCollapsibleSection>+ </>+ );++ expect(title('Render').querySelector('[data-section-changed]')?.textContent).toBe(+ 'widgets.generate.sectionChanged'+ );+ expect(title('Size').querySelector('[data-section-changed]')).toBeNull();+ });++ it('offers the panel actions, the summary copy and the reset from the title context menu', async () => {+ const reset = vi.fn();+ await render(+ <GenerationSectionPanel>+ <GenerateCollapsibleSection defaultOpen label="Size" sectionId="size">+ <div>body</div>+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection+ defaultOpen+ isChanged+ label="Render"+ sectionId="render"+ summary={['30', 'CFG 7']}+ onReset={reset}+ >+ <div>body</div>+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection isChanged={false} label="Advanced" sectionId="advanced" onReset={reset}>+ <div>body</div>+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ );+ const openMenu = async (label: string) => {+ await act(() => {+ title(label).dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));+ });+ await expect.element(page.getByRole('menu')).toBeVisible();+ // The menu takes focus once it has registered its dismiss handlers.+ await expect.poll(() => document.activeElement?.getAttribute('role')).toBe('menu');+ };+ const item = (name: string) => page.getByRole('menuitem', { name });++ await openMenu('Render');+ await expect.element(item('widgets.generate.sectionMenu.expandAll')).toBeVisible();+ await act(() => userEvent.click(item('widgets.generate.sectionMenu.copySummary')));+ expect(copied.text).toEqual(['widgets.generate.sectionMenu.summaryText {"label":"Render","summary":"30 · CFG 7"}']);++ await openMenu('Render');+ await act(() => userEvent.click(item('widgets.generate.sectionMenu.reset')));+ expect(reset).toHaveBeenCalledOnce();++ // From the keyboard, as the menu key opens it: focus goes back to the title the menu came from.+ title('Render').focus();+ await openMenu('Render');+ await userEvent.keyboard('{Home}{Enter}');+ expect(states('Size', 'Render', 'Advanced')).toEqual(['closed', 'open', 'closed']);+ await expect.poll(() => document.activeElement).toBe(title('Render'));++ // No summary, no copy; a section already at its defaults offers its reset disabled.+ await openMenu('Advanced');+ await expect.element(item('widgets.generate.sectionMenu.copySummary')).not.toBeInTheDocument();+ await expect.element(item('widgets.generate.sectionMenu.reset')).toHaveAttribute('data-disabled');+ await act(() => userEvent.click(item('widgets.generate.sectionMenu.expandAll')));+ expect(states('Size', 'Render', 'Advanced')).toEqual(['open', 'open', 'open']);++ await openMenu('Size');+ await expect.element(item('widgets.generate.sectionMenu.foldAll')).toBeVisible();+ await expect.element(item('widgets.generate.sectionMenu.reset')).not.toBeInTheDocument();+ });+});++/** A short scroller holding one long open section, as a panel scrolled deep into its fields. */+const renderPinnedSection = (fields: ReactNode) =>+ render(+ <div data-hotkey-widget-type-id="generate">+ <div data-testid="scroller" style={{ height: 200, overflowY: 'auto' }}>+ <GenerationSectionPanel>+ <GenerateCollapsibleSection defaultOpen label="Render" sectionId="render">+ {fields}+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ </div>+ </div>+ );+const scroller = () => page.getByTestId('scroller').element() as HTMLElement;+const nextFrame = () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => resolve());+ });++describe('GenerateCollapsibleSection pinned title', () => {+ it('stays above positioned fields scrolling beneath it', async () => {+ await renderPinnedSection(+ <>+ <div style={{ height: 40 }} />+ {/* Stands in for a segment thumb or a textarea handle: positioned, z-index 2. */}+ <div data-testid="raised" style={{ height: 80, position: 'relative', zIndex: 2 }} />+ <div style={{ height: 600 }} />+ </>+ );+ // The raised field now spans the whole pinned title.+ await act(() => {+ scroller().scrollTop = 100;+ });+ const rect = title('Render').getBoundingClientRect();+ const raised = page.getByTestId('raised').element().getBoundingClientRect();++ expect(raised.top).toBeLessThan(rect.top);+ expect(raised.bottom).toBeGreaterThan(rect.bottom);++ expect(Math.round(rect.top)).toBe(Math.round(scroller().getBoundingClientRect().top));+ expect(+ title('Render').contains(document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2))+ ).toBe(true);+ });++ it('draws its edge only while pinned', async () => {+ await renderPinnedSection(<div style={{ height: 800 }} />);+ const edge = () => getComputedStyle(title('Render'), '::after').opacity;++ await expect.poll(edge).toBe('0');+ await act(() => {+ scroller().scrollTop = 300;+ });+ await expect.poll(edge).toBe('1');+ });++ it('reveals an issue above the view below the pinned title, not under it', async () => {+ const issue = {+ fix: { kind: 'clampGuidance', value: 7 },+ id: 'render-cfg',+ message: 'Guidance out of range',+ target: { section: 'render' },+ } as GenerationIssue;+ await render(+ <div data-hotkey-widget-type-id="generate">+ <div data-testid="scroller" style={{ height: 200, overflowY: 'auto' }}>+ <GenerateIssuesProvider applyFix={() => undefined} issues={[issue]}>+ <GenerationSectionPanel>+ <GenerateCollapsibleSection defaultOpen label="Render" sectionId="render">+ <GenerateIssueNotes section="render" />+ <div style={{ height: 800 }} />+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ </GenerateIssuesProvider>+ </div>+ </div>+ );+ await act(() => {+ scroller().scrollTop = 600;+ });++ revealGenerateIssue(issue);+ const fix = () => document.querySelector<HTMLElement>('[data-issue-fix]')!;+ await expect.poll(() => document.activeElement).toBe(fix());+ await nextFrame();++ const fixRect = fix().getBoundingClientRect();+ expect(fixRect.top).toBeGreaterThanOrEqual(title('Render').getBoundingClientRect().bottom);+ expect(document.elementFromPoint(fixRect.left + 4, fixRect.top + fixRect.height / 2)).toBe(fix());+ });+});++describe('GenerateCollapsibleSection on its own', () => {+ it('is a panel of one: Shift-click toggles it and Fold others has nothing to fold', async () => {+ await render(+ <GenerateCollapsibleSection label="Render" summary={['30']} onReset={() => undefined} resetLabel="Reset steps"><div>body</div></GenerateCollapsibleSection>);- const section = document.querySelector<HTMLElement>('.generate-section');+ await act(() => userEvent.click(title('Render'), { modifiers: ['Shift'] }));+ expect(states('Render')).toEqual(['open']);++ await act(() => {+ title('Render').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));+ });+ await expect+ .element(page.getByRole('menuitem', { name: 'widgets.generate.sectionMenu.foldOthers' }))+ .toHaveAttribute('data-disabled');+ // A consumer whose reset covers part of the section names that part.+ await expect.element(page.getByRole('menuitem', { name: 'Reset steps' })).toBeVisible();+ });+});++describe('GenerateCollapsibleSection open motion', () => {+ const content = (label: string) => section(label).querySelector<HTMLElement>(':scope > [data-part="content"]')!;+ const fields = (label: string) => content(label).firstElementChild as HTMLElement;+ const isScale = (animation: Animation) => (animation as CSSAnimation).animationName.startsWith('wb-section-scale');++ it('scales the fields, not the clipped content, in by the same few pixels for a short and a tall section', async () => {+ await render(+ <GenerationSectionPanel>+ <GenerateCollapsibleSection label="Short" sectionId="short">+ <div style={{ height: 80 }} />+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection label="Tall" sectionId="tall">+ <div style={{ height: 700 }} />+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ );++ for (const label of ['Short', 'Tall']) {+ await act(() => userEvent.click(title(label)));+ // The collapsible measures the content a frame after opening; the scale reads that size.+ await expect.poll(() => content(label).style.getPropertyValue('--height')).not.toBe('0px');+ // Chromium leaves fields unpainted when the element clipping the animating height also runs a transform+ // animation, so the content runs none.+ expect(content(label).getAnimations().some(isScale)).toBe(false);+ const scale = fields(label).getAnimations().find(isScale)!;++ scale.pause();+ scale.currentTime = 0;+ const rect = fields(label).getBoundingClientRect();++ expect(fields(label).offsetWidth - rect.width).toBeCloseTo(8, 1);+ expect(fields(label).offsetHeight - rect.height).toBeCloseTo(4, 1);+ scale.finish();+ }+ });++ it('starts at full size, never an infinite scale, while the size is still unmeasured', async () => {+ const probe = document.createElement('div');+ probe.style.cssText = '--width: 0px; --height: 0px; animation: wb-section-scale-in 1s paused;';+ await render(<div />);+ host!.append(probe);++ expect(getComputedStyle(probe).transform).toBe('matrix(1, 0, 0, 1, 0, 0)');+ });+});++describe('GenerationSectionJumpMenu', () => {+ const jumpButton = () => page.getByRole('button', { name: 'widgets.generate.jumpToSection' });++ it('lists the panel sections in order and opens, scrolls to and focuses the one chosen', async () => {+ await render(+ <>+ <GenerationSectionJumpMenu panelId="generate" />+ <div style={{ height: 160, overflowY: 'auto' }} data-testid="scroller">+ <GenerationSectionPanel id="generate">+ <GenerateCollapsibleSection defaultOpen label="Size" sectionId="size">+ <div style={{ height: 400 }}>size</div>+ </GenerateCollapsibleSection>+ <GenerateCollapsibleSection label="Render" sectionId="render">+ <div style={{ height: 400 }}>render</div>+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ </div>+ <GenerationSectionPanel id="upscale">+ <GenerateCollapsibleSection label="Source" sectionId="source">+ <div>source</div>+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ </>+ );++ await act(() => userEvent.click(jumpButton()));+ const items = page.getByRole('menuitem');+ await expect.element(items.first()).toBeVisible();+ expect(items.elements().map((item) => item.textContent)).toEqual(['Size', 'Render']);++ await act(() => userEvent.click(page.getByRole('menuitem', { name: 'Render' })));++ expect(section('Render').dataset.state).toBe('open');+ await expect.poll(() => document.activeElement).toBe(title('Render'));+ const scroller = page.getByTestId('scroller').element();+ await expect+ .poll(() => Math.round(section('Render').getBoundingClientRect().top - scroller.getBoundingClientRect().top))+ .toBe(0);+ });++ it('stays hidden while its panel shows fewer than two sections', async () => {+ await render(+ <>+ <GenerationSectionJumpMenu panelId="upscale" />+ <GenerationSectionPanel id="upscale">+ <GenerateCollapsibleSection label="Source" sectionId="source">+ <div>source</div>+ </GenerateCollapsibleSection>+ </GenerationSectionPanel>+ </>+ );- expect(section?.dataset.state).toBe('open');- expect(getComputedStyle(section!).backgroundColor).not.toBe('rgba(0, 0, 0, 0)');+ await expect.element(jumpButton()).not.toBeInTheDocument();});});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsxindex 988a0f1ddd..3625571e16 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateCollapsibleSection.tsx@@ -1,97 +1,466 @@-import { Box, Collapsible, Flex, Text } from '@chakra-ui/react';+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- one menu per section;+ its content and items mount only while it is open (lazyMount, unmountOnExit). */+import type { KeyboardEvent, MouseEvent, ReactNode } from 'react';++import { Box, Collapsible, Flex, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';-import { ChevronRightIcon } from 'lucide-react';-import { useCallback } from 'react';+import { canCopyText, copyText } from '@platform/browser/clipboard';+import { MenuContent, MenuItem, useContextMenu } from '@platform/ui/Menu';+import { ChevronRightIcon, CircleAlertIcon } from 'lucide-react';+import { useCallback, useId, useState } from 'react';+import { useTranslation } from 'react-i18next';-import { GenerateSectionIssueBadge } from './GenerateIssues';+import { useGenerateSectionIssueCount } from './GenerateIssues';+import {+ getPanelSections,+ isPanelSectionOpen,+ registerPanelSection,+ soloPanelSection,+ toggleAllPanelSections,+ useSectionPanelId,+} from './sectionPanel';type Props = {label: string;- isOpen?: boolean;defaultOpen?: boolean;/** When set, the open state persists per user across reloads under this id. */sectionId?: string;- badges?: React.ReactNode;- children: React.ReactNode;+ /**+ * What the fields are set to (a size, a seed, an override count), shown after the title only while the section is+ * folded, as muted text joined by middle dots. Falsy items are skipped.+ */+ summary?: readonly ReactNode[];+ /** Badges that hold whether the section is open or not (an incompatibility, a shared setting). */+ status?: ReactNode;+ /** The fields differ from the defaults `onReset` restores; marks the title with a dot. */+ isChanged?: boolean;+ /** Restores the section's fields to their defaults, offered from the title's context menu. */+ onReset?: () => void;+ /** Names what `onReset` restores when it is less than the whole section; "Reset section to defaults" otherwise. */+ resetLabel?: string;+ children: ReactNode;};-const COLLAPSIBLE_INDICATOR_OPEN_STYLES = { transform: 'rotate(90deg)' };--/** Style uncontrolled sections from DOM state; preserve geometry and draw one overlay separator per boundary. */-const SECTION_OPEN_STYLES = { bg: 'bg.muted', rounded: 'sm' };+/**+ * An open section reads as one card: a title bar, dimmer than the panel, over a lighter tray holding the fields, the+ * two a hair apart. A folded section is its title row alone, and hairlines separate the folded rows; the hairlines+ * either side of an open or pointed section hide, since its card or hover fill already bounds it. The title bar+ * spans the row, so its summary and badges sit inside it.+ */+const POINTED = ':has(> [data-part="trigger"]:hover)';const SECTION_STYLES = {- '&::before': {+ '&:last-child': { borderBottomWidth: '1px' },+ // An open section is a card of its own (title bar over tray), and a pointed title fills its row as a list row+ // does, so the hairlines either side of either go.+ [`&:is([data-state="open"], ${POINTED}), .generate-section:is([data-state="open"], ${POINTED}) + &`]: {+ borderTopColor: 'transparent',+ },+ [`&:last-child:is([data-state="open"], ${POINTED})`]: { borderBottomColor: 'transparent' },+ // Anything brought into view inside the fields (a focused control, a revealed issue) stops below the pinned title+ // rather than under it: the title's height plus a little air.+ '& > [data-part="content"] *': { scrollMarginTop: 'calc(var(--chakra-sizes-9) + var(--chakra-spacing-7))' },+} as const;+// Dimmer than the panel while its section shows; the fields' tray below is the lighter surface.+const CHIP_SHOWN_BG = 'color-mix(in oklab, {colors.bg} 50%, {colors.bg.subtle})';+const SEAM_RADIUS = '2px';+const TRAY_BG = 'bg.muted';+const COLLAPSIBLE_INDICATOR_OPEN_STYLES = { transform: 'rotate(90deg)' };+/**+ * The fields grow in by a fixed few pixels while the content opens, and back as it folds, on the recipe's duration+ * (1ms under Reduce motion). On the fields, not the content: the content clips its animating height, and Chromium+ * leaves fields unpainted when one element does both that and a composited transform animation.+ */+const FIELDS_STYLES = {+ // Controls that back themselves with the surface they sit on (a row's weight, a reference image's fields) take+ // the tray's here, not the widget's.+ '--wb-field-surface': '{colors.bg.muted}',+ transformOrigin: 'top',+ '[data-part="content"][data-state="open"] > &': {+ animationDuration: 'moderate',+ animationName: 'wb-section-scale-in',+ },+ // Not held at its end: the content has faded out by then, and a held transform would stay on the folded fields.+ '[data-part="content"][data-state="closed"] > &': {+ animationDuration: 'moderate',+ animationName: 'wb-section-scale-out',+ },+} as const;+const TRIGGER_STYLES = {+ // The open title bar nearly touches its tray, and both square off the corners that face the seam.+ '&[data-state="open"]': { color: 'fg', pb: '2px' },+ '&[data-state="open"] > [data-section-chip]': { bg: CHIP_SHOWN_BG, borderBottomRadius: SEAM_RADIUS },+ // Pointed, the title takes the tray's surface, open or folded.+ '&:hover > [data-section-chip]': { bg: TRAY_BG },+ '&:not([data-state="open"]):hover': { color: 'fg' },+ // A section with issues says so on its chip, open or folded.+ '& > [data-section-chip][data-issues]': { bg: 'bg.error', color: 'fg.error' },+ '&:hover > [data-section-chip][data-issues]': { bg: 'red.hoverTint/20' },+ // The row is full-bleed, so the scroller would clip a ring drawn around it; the chip carries the ring, inset.+ '&:focus-visible': { outline: 'none' },+ '&:focus-visible > [data-section-chip]': {+ outline: '2px solid',+ outlineColor: 'accent.solid',+ outlineOffset: '-2px',+ },+ // Summaries say what a folded section holds; an open one shows its fields instead.+ // They leave downward, toward the fields that open in their place.+ '&[data-state="open"] [data-section-summary]': {+ opacity: 0,+ transform: 'translateY(4px)',+ visibility: 'hidden',+ },+ // A hairline under the title only while it is pinned over the fields scrolling beneath it. Chromium resolves the+ // scroll-state query; elsewhere the title pins without the edge.+ containerType: 'scroll-state',+ '&::after': {+ bg: 'border',+ bottom: 0,content: '""',- position: 'absolute',+ h: '1px',insetInline: 0,- top: 'calc(var(--chakra-spacing-1) / -2)',- borderTopWidth: '1px',- pointerEvents: 'none',opacity: 0,- transition: 'opacity var(--wb-motion-duration-slow) ease',+ pointerEvents: 'none',+ position: 'absolute',+ transition: 'opacity var(--wb-motion-duration-fast)',},- '.generate-section + &::before': { opacity: 1 },- // With equal specificity, open-state rules must follow preceding-section rules.- '&[data-state="open"]::before': { opacity: 0 },- '.generate-section[data-state="open"] + &::before': { opacity: 0 },+ '@container scroll-state(stuck: top)': { '&::after': { opacity: 1 } },} as const;+// Separators are drawn, so the summary reads as its values; the empty alternative keeps them out of the name.+const SUMMARY_STYLES = { '& > * + *::before': { content: '"·" / ""', marginInline: '1.5' } } as const;++const isShownSummary = (item: ReactNode) => item !== null && item !== undefined && item !== false && item !== '';++const getSummaryText = (root: HTMLElement): string =>+ [...root.querySelectorAll<HTMLElement>('[data-section-summary] > *')]+ .map((item) => item.textContent?.trim() ?? '')+ .filter(Boolean)+ .join(' · ');++interface MenuFacts {+ anyFolded: boolean;+ othersOpen: boolean;+ root: HTMLElement;+}-export const GenerateCollapsibleSection = ({ badges, children, defaultOpen, isOpen, label, sectionId }: Props) => {+export const GenerateCollapsibleSection = ({+ children,+ defaultOpen,+ isChanged,+ label,+ onReset,+ resetLabel,+ sectionId,+ status,+ summary,+}: Props) => {+ const { t } = useTranslation();const { sectionPreferences } = useGenerationUi();- const persistedOpen = sectionId === undefined ? undefined : sectionPreferences.sectionsOpen[sectionId];- const resolvedOpen = isOpen ?? (sectionId === undefined ? undefined : (persistedOpen ?? defaultOpen ?? false));- const handleOpenChange = useCallback(- ({ open }: { open: boolean }) => {- if (sectionId !== undefined) {- sectionPreferences.setSectionOpen(sectionId, open);- }+ const key = useId();+ // Outside a panel (a section rendered on its own) the section is its own panel.+ const panelId = useSectionPanelId() ?? key;+ const [localOpen, setLocalOpen] = useState(defaultOpen ?? false);+ const isOpen =+ sectionId === undefined ? localOpen : (sectionPreferences.sectionsOpen[sectionId] ?? defaultOpen ?? false);+ const issueCount = useGenerateSectionIssueCount(sectionId);+ const { anchor, close, onRequestDismiss, open } = useContextMenu();+ const [menuFacts, setMenuFacts] = useState<MenuFacts | null>(null);+ const shownSummary = summary?.filter(isShownSummary) ?? [];+ const persist = sectionPreferences.setSectionsOpen;++ const setOpen = (nextOpen: boolean) => {+ if (sectionId === undefined) {+ setLocalOpen(nextOpen);+ } else {+ persist({ [sectionId]: nextOpen });+ }+ };++ // Joins the panel while mounted; a new label or id re-registers it.+ const registerRoot = useCallback(+ (root: HTMLDivElement | null) => {+ const trigger = root?.querySelector<HTMLElement>(':scope > [data-part="trigger"]');++ return root && trigger+ ? registerPanelSection(panelId, { key, label, root, sectionId, setLocalOpen, trigger })+ : undefined;},- [sectionId, sectionPreferences]+ [key, label, panelId, sectionId]);+ const panelSections = () => getPanelSections(panelId);++ // Alt-click solos the section; Shift-click opens every section in the panel, or folds them all when none is folded.+ const handleClick = (event: MouseEvent<HTMLButtonElement>) => {+ if (!(event.altKey || event.shiftKey)) {+ return;+ }++ event.preventDefault();+ const root = event.currentTarget.parentElement!;++ if (event.altKey) {+ soloPanelSection(panelSections(), root, persist);+ } else {+ toggleAllPanelSections(panelSections(), persist);+ }+ };++ // The titles behave as a tree's rows: up and down move between them, right opens, left folds.+ const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {+ return;+ }++ const triggers = panelSections().map((entry) => entry.trigger);+ const index = triggers.indexOf(event.currentTarget);+ const target =+ event.key === 'ArrowDown'+ ? triggers[index + 1]+ : event.key === 'ArrowUp'+ ? triggers[index - 1]+ : event.key === 'Home'+ ? triggers[0]+ : event.key === 'End'+ ? triggers.at(-1)+ : undefined;++ if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {+ if (isOpen !== (event.key === 'ArrowRight')) {+ setOpen(!isOpen);+ }+ } else if (index !== -1 && ['ArrowDown', 'ArrowUp', 'End', 'Home'].includes(event.key)) {+ // At either end the key stays here rather than scrolling the panel.+ target?.focus();+ } else {+ return;+ }++ event.preventDefault();+ };++ const handleContextMenu = (event: MouseEvent<HTMLButtonElement>) => {+ event.preventDefault();+ const trigger = event.currentTarget;+ const root = trigger.parentElement!;+ const sections = panelSections();+ // A keyboard-opened menu has no pointer position of its own (see `GenerateFieldContextMenu`).+ const native = event.nativeEvent as Partial<PointerEvent>;+ const fromKeyboard =+ event.button === -1 || native.pointerType === '' || (event.clientX === 0 && event.clientY === 0);+ const rect = trigger.getBoundingClientRect();++ setMenuFacts({+ anyFolded: sections.some((entry) => !isPanelSectionOpen(entry)),+ othersOpen: sections.some((entry) => entry.root !== root && isPanelSectionOpen(entry)),+ root,+ });+ open({+ // A frame late: Zag focuses the menu a frame after a highlight, and a pick within that frame would otherwise+ // land focus back in the closing menu.+ restoreFocus: () => requestAnimationFrame(() => trigger.focus()),+ x: fromKeyboard ? rect.left : event.clientX,+ y: fromKeyboard ? rect.bottom : event.clientY,+ });+ };++ const copyUnavailableReason = canCopyText() ? undefined : t('common.copyUnavailable');+return (<Collapsible.Root+ ref={registerRoot}className="generate-section"css={SECTION_STYLES}data-generate-section={sectionId}- _open={SECTION_OPEN_STYLES}- defaultOpen={sectionId === undefined ? defaultOpen : undefined}- open={resolvedOpen}- position="relative"- transition="background var(--wb-motion-duration-slow) ease, border-radius var(--wb-motion-duration-slow) ease"- onOpenChange={sectionId === undefined ? undefined : handleOpenChange}+ borderTopWidth="1px"+ transition="border-color var(--wb-motion-duration-medium)"+ open={isOpen}+ onOpenChange={({ open: nextOpen }) => setOpen(nextOpen)}>- <Collapsible.Trigger display="flex" gap={2} w="full" px={1.5} h="8" alignItems="center">- <Collapsible.Indicator- _open={COLLAPSIBLE_INDICATOR_OPEN_STYLES}- transition="transform var(--wb-motion-duration-slow)"- >- <ChevronRightIcon size="14" />- </Collapsible.Indicator>- <Text+ {/* Pinned while its section scrolls beneath it, so the fields in view always have their title. */}+ <Collapsible.Trigger+ bg="bg.subtle"+ css={TRIGGER_STYLES}+ display="flex"+ gap={2}+ w="full"+ // A pixel of air either side, so the hairline between two folded titles has the same room above and below.+ pb="1px"+ px="0.5"+ pt="1px"+ alignItems="center"+ color="fg.muted"+ position="sticky"+ top={0}+ zIndex={1}+ onClick={handleClick}+ onContextMenu={handleContextMenu}+ onKeyDown={handleKeyDown}+ >+ <Flexas="span"- fontSize="xs"- truncate- letterSpacing="widest"- fontWeight="bold"- textTransform="uppercase"- color="fg.muted"- lineHeight="1"+ alignItems="center"+ data-issues={issueCount > 0 ? '' : undefined}+ data-section-chip=""+ gap={2}+ h="9"+ minW="0"+ // Less on the chevron's side: its glyph is narrower than its box.+ pe="2"+ ps="1.5"+ rounded="control"+ transition="background var(--wb-motion-duration-fast), color var(--wb-motion-duration-fast)"+ w="full">- {label}- </Text>+ <Text+ as="span"+ display="inline-flex"+ alignItems="center"+ flexShrink={0}+ fontSize="md"+ fontWeight="medium"+ gap="1"+ maxW="full"+ minW="0"+ >+ <Collapsible.Indicator+ _open={COLLAPSIBLE_INDICATOR_OPEN_STYLES}+ flexShrink={0}+ transition="transform var(--wb-motion-duration-slow)"+ >+ <ChevronRightIcon size="14" />+ </Collapsible.Indicator>+ <Text as="span" truncate>+ {label}+ </Text>+ {isChanged ? (+ <Box as="span" bg="accent.solid" boxSize="1.5" data-section-changed="" flexShrink={0} rounded="full">+ <Text as="span" srOnly>+ {t('widgets.generate.sectionChanged')}+ </Text>+ </Box>+ ) : null}+ {/* A closed section never hides why Invoke is blocked. */}+ {issueCount > 0 ? (+ <Text+ as="span"+ alignItems="center"+ data-section-issues=""+ display="inline-flex"+ flexShrink={0}+ fontVariantNumeric="tabular-nums"+ gap="0.5"+ ms="0.5"+ >+ <Icon as={CircleAlertIcon} aria-hidden boxSize="3" />+ <span aria-hidden>{issueCount}</span>+ <Text as="span" srOnly>+ {t('widgets.generate.issueCount', { count: issueCount })}+ </Text>+ </Text>+ ) : null}+ </Text>- <Flex gap={1} ml="auto" fontFamily="mono">- {sectionId === undefined ? null : <GenerateSectionIssueBadge section={sectionId} />}- {badges}+ <Flex alignItems="center" gap={2} minW="0" ml="auto">+ {shownSummary.length > 0 ? (+ <Text+ as="span"+ aria-hidden={isOpen || undefined}+ color="fg.muted"+ css={SUMMARY_STYLES}+ data-section-summary=""+ fontSize="sm"+ fontVariantNumeric="tabular-nums"+ minW="0"+ transition="opacity var(--wb-motion-duration-fast), transform var(--wb-motion-duration-fast), visibility var(--wb-motion-duration-fast)"+ truncate+ >+ {shownSummary.map((item, index) => (+ // oxlint-disable-next-line react/no-array-index-key -- positional values with no identity of their own.+ <span key={index}>{item}</span>+ ))}+ </Text>+ ) : null}+ {status ? (+ <Flex flexShrink={0} fontVariantNumeric="tabular-nums" gap={1}>+ {status}+ </Flex>+ ) : null}+ </Flex></Flex></Collapsible.Trigger>- <Collapsible.Content>- <Box borderTopWidth={1} borderColor="bg.subtle">- {children}+ {/* Isolated, so a positioned field (a segment thumb, a textarea handle) never paints over the pinned title. */}+ <Collapsible.Content isolation="isolate">+ {/* The section owns its inset and rhythm, so every widget's sections space their fields alike. */}+ {/* The scaled box spans the content's full width, the width the scale is sized from; the tray sits inside. */}+ <Box css={FIELDS_STYLES} px="0.5">+ <Stack bg={TRAY_BG} gap="2.5" p="2" rounded="l2" borderTopRadius={SEAM_RADIUS}>+ {children}+ </Stack></Box></Collapsible.Content>++ <Menu.Root+ lazyMount+ open={anchor !== null}+ positioning={{+ getAnchorRect: () => (anchor ? { height: 1, width: 1, x: anchor.x, y: anchor.y } : null),+ placement: 'bottom-start',+ }}+ onOpenChange={(event) => {+ if (!event.open) {+ close();+ }+ }}+ onRequestDismiss={onRequestDismiss}+ unmountOnExit+ >+ <Portal>+ <Menu.Positioner>+ <MenuContent>+ <MenuItem+ disabled={!menuFacts?.othersOpen}+ value="fold-others"+ onSelect={() => {+ if (menuFacts) {+ soloPanelSection(panelSections(), menuFacts.root, persist);+ }+ }}+ >+ {t('widgets.generate.sectionMenu.foldOthers')}+ </MenuItem>+ <MenuItem value="toggle-all" onSelect={() => toggleAllPanelSections(panelSections(), persist)}>+ {menuFacts?.anyFolded+ ? t('widgets.generate.sectionMenu.expandAll')+ : t('widgets.generate.sectionMenu.foldAll')}+ </MenuItem>+ {shownSummary.length > 0 ? (+ <MenuItem+ unavailableReason={copyUnavailableReason}+ value="copy-summary"+ onSelect={() => {+ if (menuFacts) {+ void copyText(+ t('widgets.generate.sectionMenu.summaryText', {+ label,+ summary: getSummaryText(menuFacts.root),+ })+ ).catch(() => undefined);+ }+ }}+ >+ {t('widgets.generate.sectionMenu.copySummary')}+ </MenuItem>+ ) : null}+ {onReset ? (+ <MenuItem disabled={isChanged === false} value="reset" onSelect={onReset}>+ {resetLabel ?? t('widgets.generate.sectionMenu.reset')}+ </MenuItem>+ ) : null}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root></Collapsible.Root>);};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.browser.test.tsxindex 38c5954634..e593da6ce2 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.browser.test.tsx@@ -85,6 +85,23 @@ describe('GenerateFieldContextMenu', () => {expect(openMenus()[0]?.textContent).toContain('Reset CFG');});+ it('opens at the pointer with nothing to point at: no arrow, and no arrow-sized gap below the click', async () => {+ await renderFields();+ const steps = field('Steps');++ await rightClick(steps);+ await expect.poll(() => openMenus()[0]?.textContent).toContain('Reset Steps');+ await settle();+ const menu = openMenus()[0]!;++ const arrow = menu.parentElement!.querySelector<HTMLElement>('[data-part="arrow"]');+ expect(arrow?.querySelector<HTMLElement>('[data-part="arrow-tip"]')?.offsetWidth ?? 0).toBe(0);+ // The click lands 8px into the field; the menu opens the default 8px gutter below it, where an arrow would add 6.+ const gap = menu.getBoundingClientRect().top - (steps.getBoundingClientRect().top + 8);+ expect(gap).toBeGreaterThanOrEqual(7);+ expect(gap).toBeLessThan(11);+ });+it('keeps a menu open when right-clicked itself, then still moves to the next field', async () => {await renderFields();@@ -144,4 +161,55 @@ describe('GenerateFieldContextMenu', () => {await expect.poll(() => openMenus()).toHaveLength(0);expect(document.activeElement).toBe(cfg);});++ it('keeps the changed dot inside the 8px gutter at rest, on hover and with its focus ring', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ {/* The panel and its 8px field inset, as a section lays fields out. */}+ <Box data-testid="panel" overflow="hidden" px="2" w="30rem">+ <GenerateFieldContextMenu copyValue={FIELDS[0]!.copyValue} fieldLabel="Steps" onReset={onReset}>+ <Box as="button" borderWidth="1px" data-field="Steps" h="7" w="full">+ Steps+ </Box>+ </GenerateFieldContextMenu>+ </Box>+ </I18nextProvider>+ </ChakraProvider>+ )+ );+ const panel = host.querySelector<HTMLElement>('[data-testid="panel"]')!.getBoundingClientRect();+ const fieldLeft = field('Steps').getBoundingClientRect().left;+ const button = host.querySelector<HTMLElement>('[data-modified-dot]')!;+ const dot = () => button.querySelector<HTMLElement>('[data-part="dot"]')!.getBoundingClientRect();+ /** The dot's extent, with `ring` px of focus ring around it, must clear the panel edge and the field's border. */+ const expectInGutter = (ring: number) => {+ const rect = dot();+ expect(rect.left - ring).toBeGreaterThanOrEqual(panel.left);+ expect(rect.right + ring).toBeLessThanOrEqual(fieldLeft);+ };++ expect(fieldLeft - panel.left).toBe(8);+ expect(dot().width).toBe(4);+ expectInGutter(1);++ await userEvent.hover(button);+ await expect.poll(() => Math.round(dot().width)).toBe(6);+ expectInGutter(0);++ await userEvent.unhover(button);+ // From the keyboard: the ring is drawn on the dot itself, not the 16px button.+ host.querySelector<HTMLElement>('[data-testid="panel"]')!.focus();+ await userEvent.keyboard('{Tab}');+ expect(document.activeElement).toBe(button);+ await expect.poll(() => Math.round(dot().width)).toBe(6);+ // A real outline, which stays in forced colors, 1px around the dot and still inside the gutter.+ const dotStyle = getComputedStyle(button.querySelector<HTMLElement>('[data-part="dot"]')!);+ expect([dotStyle.outlineStyle, dotStyle.outlineWidth, dotStyle.outlineOffset]).toEqual(['solid', '1px', '0px']);+ expectInGutter(1);+ });});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsxindex 7c98e8cbb7..2d22cbb68d 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateFieldContextMenu.tsx@@ -16,26 +16,65 @@ interface GenerateFieldContextMenuProps {/** Disables the reset entry and hides the modified dot; the menu still opens for Copy value. */isAtDefault?: boolean;onReset?: () => void;- /** Reset entry text; defaults to "Reset to model default". */+ /** Reset entry text, naming where the value comes from; defaults to "Reset to default". */resetLabel?: string;+ /**+ * What the dot lines up with: a field's control (28px tall), or a switch row's first line (the switch's height).+ * Either way it stays in the gutter left of the row.+ */+ placement?: 'field' | 'switch';}+/**+ * The dot's button, centred on the first line of what it marks: a control is 28px (`sizes.7`), and a switch row's first+ * line is the height of Generate's switch (16px, `sizes.4`), which its label's line height matches.+ *+ * Beside a field the button is a 16px target centred in the gutter; it may overlap the field's border. A switch row's+ * label is text from its first pixel and a click on it toggles, so there the button stays within the 8px gutter (8x16)+ * and sets the dot 1px further from the text: 4px at rest 3px clear of it, 6px on hover, and on focus the 4px dot with+ * its 1px ring, both ending at the gutter's outer edge.+ */+const DOT_BUTTON_PROPS = {+ field: {+ h: '4',+ insetInlineStart: '-3',+ justifyContent: 'center',+ top: 'calc(var(--chakra-sizes-7) / 2 - var(--chakra-sizes-2))',+ w: '4',+ },+ switch: {+ h: '4',+ insetInlineStart: '-2',+ justifyContent: 'flex-start',+ ps: '1px',+ top: 'calc(var(--chakra-sizes-4) / 2 - var(--chakra-sizes-2))',+ w: '2',+ },+} as const;+const FIELD_CONTROL_SELECTOR ='[role="slider"]:not([aria-disabled="true"]), input:not([type="hidden"]):not(:disabled), button:not([data-modified-dot]):not(:disabled), [role="combobox"]';-/** The dot is drawn small; its button keeps a 16px target in the gutter left of the field. */+/**+ * Fields sit 8px in from the panel's edge, and the dot lives in that gutter: 4px at rest, 6px on hover or focus,+ * centred 4px left of the field so it keeps 1px clear of both the panel's edge and the field's border. Its button keeps+ * a 16px target, which may overlap both, so the button draws nothing itself: focus shows on the dot, as a 1px outline+ * that ends exactly at the gutter's edges (6px dot + 1px either side), where nothing clips it. An outline, not a+ * shadow, so it stays in forced colors.+ */const MODIFIED_DOT_CSS = {- '&::after': {+ '& > [data-part="dot"]': {bg: 'accent.solid',- content: '""',- h: '1.5',+ boxSize: '1',rounded: 'full',transitionDuration: 'var(--wb-motion-duration-fast)',- transitionProperty: 'transform',- w: '1.5',+ transitionProperty: 'transform, width, height',},- '&:hover::after, &:focus-visible::after': { transform: 'scale(1.5)' },- '&:focus-visible': { outline: '2px solid', outlineColor: 'accent.solid', outlineOffset: '-2px' },+ '&:hover:not(:focus-visible) > [data-part="dot"]': { transform: 'scale(1.5)' },+ '&:focus-visible': { outline: 'none' },+ '&:focus-visible > [data-part="dot"]': { boxSize: '1.5', outline: '1px solid', outlineColor: 'fg', outlineOffset: 0 },+ // On a switch row the focused dot keeps its 4px, so with its ring it fits the 7px between the text and the edge.+ '&[data-placement="switch"]:focus-visible > [data-part="dot"]': { boxSize: '1' },} as const;/**@@ -49,12 +88,13 @@ export const GenerateFieldContextMenu = ({fieldLabel,isAtDefault = false,onReset,+ placement = 'field',resetLabel,}: GenerateFieldContextMenuProps) => {const { t } = useTranslation();const { anchor: point, close, onRequestDismiss, open } = useContextMenu();const copyUnavailableReason = canCopyText() ? undefined : t('common.copyUnavailable');- const resetText = resetLabel ?? t('widgets.generate.resetToModelDefault');+ const resetText = resetLabel ?? t('widgets.generate.resetToDefault');const isModified = onReset !== undefined && !isAtDefault;const dotLabel = t('widgets.generate.resetFieldNamed', { field: fieldLabel, reset: resetText });@@ -94,19 +134,18 @@ export const GenerateFieldContextMenu = ({alignItems="center"aria-label={dotLabel}data-modified-dot=""+ data-placement={placement}css={MODIFIED_DOT_CSS}cursor="pointer"display="flex"- h="4"- insetInlineStart="-3"- justifyContent="center"position="absolute"rounded="full"- top="1.5"type="button"- w="4"+ {...DOT_BUTTON_PROPS[placement]}onClick={resetFromDot}- />+ >+ <chakra.span aria-hidden data-part="dot" />+ </chakra.button></Tooltip>) : null}{children}diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateIssues.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateIssues.tsxindex 84daf6e35f..3f928e0fc6 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateIssues.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerateIssues.tsx@@ -7,11 +7,13 @@ import type {} from '@features/generation/core/generationIssues';import type { ReactNode } from 'react';-import { Badge, HStack, Icon, Stack, Text } from '@chakra-ui/react';+import { HStack, Icon, Popover, Portal, Stack, Text } from '@chakra-ui/react';import { describeGenerationIssue, describeGenerationIssueFix } from '@features/generation/core/generationIssues';-import { Button } from '@platform/ui/Button';+import { Button, IconButton } from '@platform/ui/Button';+import { PopoverContent } from '@platform/ui/Popover';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';import { CircleAlertIcon } from 'lucide-react';-import { createContext, use, useMemo } from 'react';+import { createContext, use, useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';interface GenerateIssuesValue {@@ -20,6 +22,43 @@ interface GenerateIssuesValue {}const GenerateIssuesContext = createContext<GenerateIssuesValue | null>(null);+/** How many Invoke-blocking issues each section holds, by section id, for the section titles. */+const SectionIssueCountsContext = createContext<ReadonlyMap<string, number> | null>(null);++/** Section ids are plain identifiers, so a line break separates them. */+const SECTION_KEY_SEPARATOR = '\n';++const countIssuesBySection = (sectionsKey: string): ReadonlyMap<string, number> => {+ const counts = new Map<string, number>();++ for (const section of sectionsKey.split(SECTION_KEY_SEPARATOR)) {+ if (section !== '') {+ counts.set(section, (counts.get(section) ?? 0) + 1);+ }+ }++ return counts;+};++/**+ * The section of each of a form's Invoke-blocking issues (undefined for one no section fixes), so each section's+ * title carries its count; an issue two sections can fix is listed once for each. For forms whose fields word their+ * own errors; Generate's provider sets it from its issues.+ */+export const GenerationSectionIssuesProvider = ({+ children,+ issueSections,+}: {+ children: ReactNode;+ issueSections: readonly (string | undefined)[];+}) => {+ // Keyed by content, as `areGenerationIssuesEqual` keeps Generate's list: a re-validation on every keystroke that finds+ // the same issues keeps the counts' identity, so the section titles re-render only when a count changes.+ const sectionsKey = issueSections.map((section) => section ?? '').join(SECTION_KEY_SEPARATOR);+ const counts = useMemo(() => countIssuesBySection(sectionsKey), [sectionsKey]);++ return <SectionIssueCountsContext value={counts}>{children}</SectionIssueCountsContext>;+};/** The form's Invoke-blocking issues, for its sections' badges and the notes under their fields. */export const GenerateIssuesProvider = ({@@ -28,8 +67,13 @@ export const GenerateIssuesProvider = ({issues,}: GenerateIssuesValue & { children: ReactNode }) => {const value = useMemo(() => ({ applyFix, issues }), [applyFix, issues]);+ const issueSections = useMemo(() => issues.map((issue) => issue.target.section), [issues]);- return <GenerateIssuesContext value={value}>{children}</GenerateIssuesContext>;+ return (+ <GenerateIssuesContext value={value}>+ <GenerationSectionIssuesProvider issueSections={issueSections}>{children}</GenerationSectionIssuesProvider>+ </GenerateIssuesContext>+ );};const NO_ISSUES: readonly GenerationIssue[] = [];@@ -47,18 +91,11 @@ export const areGenerationIssuesEqual = (JSON.stringify(issue.fix) === JSON.stringify(right[index]?.fix));-/** A collapsed section names how many problems it holds, so a closed section never hides why Invoke is blocked. */-export const GenerateSectionIssueBadge = ({ section }: { section: string }) => {- const { t } = useTranslation();- const issues = use(GenerateIssuesContext)?.issues ?? NO_ISSUES;- const count = issues.filter((issue) => issue.target.section === section).length;+/** How many issues a section holds, for its title's count. */+export const useGenerateSectionIssueCount = (section: string | undefined): number => {+ const counts = use(SectionIssueCountsContext);- return count > 0 ? (- <Badge colorPalette="red" variant="surface">- <Icon as={CircleAlertIcon} boxSize="3" />- {t('widgets.generate.issueCount', { count })}- </Badge>- ) : null;+ return section === undefined ? 0 : (counts?.get(section) ?? 0);};/**@@ -81,6 +118,24 @@ export const ISSUE_FIELD_RENDERERS: Record<const FIX_BUTTON_SELECTOR = '[data-issue-fix]';+interface IssueTarget {+ /** Only the issues about this concept, for its row. */+ conceptKey?: string;+ field?: GenerationIssueField;+ /** Only the issues about this reference image, for its row. */+ referenceImageId?: string;+ section: GenerateSectionId;+}++const matchesIssueTarget = (+ issue: GenerationIssue,+ { conceptKey, field, referenceImageId, section }: IssueTarget+): boolean =>+ issue.target.section === section &&+ issue.target.field === field &&+ (conceptKey === undefined || (issue.fix?.kind === 'removeConcept' && issue.fix.modelKey === conceptKey)) &&+ (referenceImageId === undefined || issue.target.referenceImageId === referenceImageId);+/*** After a fix resolves its issue the button unmounts; focus moves to the next fix in the same notes, else to the* section's header, so it never falls to the page.@@ -127,11 +182,8 @@ export const GenerateIssueNotes = ({const context = use(GenerateIssuesContext);const issues = (context?.issues ?? NO_ISSUES).filter((issue) =>- issue.target.section === section &&- issue.target.field === field &&- (!fixesOnly || issue.fix !== undefined) &&- (conceptKey === undefined || (issue.fix?.kind === 'removeConcept' && issue.fix.modelKey === conceptKey)) &&- (referenceImageId === undefined || issue.target.referenceImageId === referenceImageId)+ matchesIssueTarget(issue, { conceptKey, field, referenceImageId, section }) &&+ (!fixesOnly || issue.fix !== undefined));if (!context || issues.length === 0) {@@ -180,11 +232,14 @@ export const GenerateIssueNotes = ({const IssueFixButton = ({fix,label,+ moveFocus = moveFocusAfterFix,name,onFix,}: {fix: GenerationIssueFix;label: string;+ /** Where focus goes once the fix has resolved the issue and removed this button. */+ moveFocus?: (button: HTMLElement) => void;/** The label followed by the issue it fixes, so the button names its target. */name: string;onFix: (fix: GenerationIssueFix) => void;@@ -200,7 +255,7 @@ const IssueFixButton = ({const button = event.currentTarget;onFix(fix);- moveFocusAfterFix(button);+ moveFocus(button);}}>{label}@@ -213,3 +268,163 @@ export const useGenerateSectionIssues = (section: GenerateSectionId): readonly Greturn useMemo(() => issues.filter((issue) => issue.target.section === section), [issues, section]);};++const ISSUE_POPOVER_POSITIONING = { placement: 'bottom-end' } as const;++/** A step an issue's popover offers beside its fix, for a problem fixed in the row itself (choosing its model). */+export interface GenerateIssueAction {+ label: string;+ /** Runs once the popover has closed. */+ onSelect: () => void;+}++/**+ * A list row's issues as one icon beside its switch: the row says something is wrong without a line of its own. Hover+ * or focus shows the messages; pressing it opens them in a popover with their one-step fixes. Renders nothing while+ * the row has no issue. A reveal from the Invoke issue list finds it by `data-issue-ids` and opens it.+ */+export const GenerateIssueButton = ({+ getAction,+ ...target+}: IssueTarget & {+ /** The extra step for one issue, listed ahead of its fix; null when the fix is the only way out. */+ getAction?: (issue: GenerationIssue) => GenerateIssueAction | null;+}) => {+ const { t } = useTranslation();+ const context = use(GenerateIssuesContext);+ const ids = useTooltipTriggerIds();+ const [isOpen, setIsOpen] = useState(false);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const { conceptKey, field, referenceImageId, section } = target;+ const issues = useMemo(+ () =>+ (context?.issues ?? NO_ISSUES).filter((issue) =>+ matchesIssueTarget(issue, { conceptKey, field, referenceImageId, section })+ ),+ [conceptKey, context?.issues, field, referenceImageId, section]+ );+ const handleOpenChange = useCallback(({ open }: { open: boolean }) => setIsOpen(open), []);+ const close = useCallback(() => setIsOpen(false), []);+ // A fix usually resolves every issue here, and this button goes with them: focus moves to the row's switch, else to+ // the section's header, so it never falls to the page.+ const moveFocus = useCallback(() => {+ const trigger = triggerRef.current;+ const row = trigger?.closest('[role="listitem"]');+ const section = trigger?.closest('.generate-section');++ setIsOpen(false);+ requestAnimationFrame(() => {+ if (trigger?.isConnected) {+ trigger.focus();+ return;+ }++ (+ (row?.isConnected ? row.querySelector<HTMLElement>('[data-scope="switch"] input') : null) ??+ section?.querySelector<HTMLElement>('[data-scope="collapsible"][data-part="trigger"]')+ )?.focus();+ });+ }, []);++ const messages = useMemo(() => issues.map((issue) => describeGenerationIssue(t, issue)), [issues, t]);++ if (!context || issues.length === 0) {+ return null;+ }++ // The tooltip shows the name itself, so assistive tech, which drops a description equal to the name, reads it once.+ const label = t('widgets.generate.issuesNamed', { count: issues.length, messages: messages.join(' ') });++ return (+ <Popover.Root+ ids={ids}+ lazyMount+ open={isOpen}+ positioning={ISSUE_POPOVER_POSITIONING}+ unmountOnExit+ onOpenChange={handleOpenChange}+ >+ <Tooltip content={label} ids={ids}>+ <Popover.Trigger asChild>+ <IconButton+ ref={triggerRef}+ aria-label={label}+ color="fg.error"+ data-issue-ids={issues.map((issue) => issue.id).join(' ')}+ size="sm"+ variant="ghost"+ >+ <Icon as={CircleAlertIcon} boxSize="3.5" />+ </IconButton>+ </Popover.Trigger>+ </Tooltip>+ <Portal>+ <Popover.Positioner>+ <PopoverContent maxW="18rem" p="3">+ <Stack gap="2.5">+ {issues.map((issue, index) => (+ <Stack key={issue.id} align="flex-start" data-issue-id={issue.id} gap="2">+ <HStack align="flex-start" gap="1.5">+ <Icon as={CircleAlertIcon} boxSize="3" color="fg.error" flexShrink={0} mt="0.5" />+ <Text fontSize="xs" textWrap="pretty">+ {messages[index]}+ </Text>+ </HStack>+ <IssueActions+ action={getAction?.(issue) ?? null}+ fix={issue.fix}+ message={messages[index] ?? ''}+ moveFocus={moveFocus}+ onClose={close}+ onFix={context.applyFix}+ />+ </Stack>+ ))}+ </Stack>+ </PopoverContent>+ </Popover.Positioner>+ </Portal>+ </Popover.Root>+ );+};++const IssueActions = ({+ action,+ fix,+ message,+ moveFocus,+ onClose,+ onFix,+}: {+ action: GenerateIssueAction | null;+ fix: GenerationIssueFix | undefined;+ message: string;+ moveFocus: () => void;+ onClose: () => void;+ onFix: (fix: GenerationIssueFix) => void;+}) => {+ const { t } = useTranslation();+ const handleAction = useCallback(() => {+ onClose();+ action?.onSelect();+ }, [action, onClose]);++ return action || fix ? (+ <HStack gap="1.5">+ {action ? (+ <Button data-issue-action="" size="xs" variant="outline" onClick={handleAction}>+ {action.label}+ </Button>+ ) : null}+ {fix ? (+ <IssueFixButton+ fix={fix}+ label={describeGenerationIssueFix(t, fix)}+ moveFocus={moveFocus}+ name={t('widgets.generate.issueFixNamed', { fix: describeGenerationIssueFix(t, fix), issue: message })}+ onFix={onFix}+ />+ ) : null}+ </HStack>+ ) : null;+};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerationSectionJumpMenu.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerationSectionJumpMenu.tsxnew file mode 100644index 0000000000..fff064ee15--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/GenerationSectionJumpMenu.tsx@@ -0,0 +1,62 @@+import { Icon, Menu, Portal } from '@chakra-ui/react';+import { useGenerationUi } from '@features/generation/ui/GenerationUiContext';+import { IconButton } from '@platform/ui/Button';+import { MenuContent } from '@platform/ui/Menu';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { TableOfContentsIcon } from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { revealPanelSection, usePanelSections } from './sectionPanel';++const JUMP_MENU_POSITIONING = { placement: 'bottom-end' } as const;++/**+ * A widget header's list of its panel's sections, in order. Choosing one opens it when folded, brings it to the top+ * of the panel and focuses its title. Hidden while the panel shows fewer than two sections.+ */+export const GenerationSectionJumpMenu = ({ panelId }: { panelId: string | undefined }) => {+ const { t } = useTranslation();+ const ids = useTooltipTriggerIds();+ const sections = usePanelSections(panelId);+ const ui = useGenerationUi();+ const handleSelect = useCallback(+ ({ value }: { value: string }) => {+ const section = sections.find((entry) => entry.key === value);++ if (section) {+ revealPanelSection(section, ui.sectionPreferences.setSectionsOpen);+ }+ },+ [sections, ui]+ );++ if (sections.length < 2) {+ return null;+ }++ const label = t('widgets.generate.jumpToSection');++ return (+ <Menu.Root ids={ids} positioning={JUMP_MENU_POSITIONING} onSelect={handleSelect}>+ <Menu.Trigger asChild>+ <Tooltip content={label} ids={ids}>+ <IconButton aria-label={label} color="fg.muted" size="sm" variant="ghost">+ <Icon as={TableOfContentsIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent>+ {sections.map((section) => (+ <Menu.Item key={section.key} value={section.key}>+ {section.label}+ </Menu.Item>+ ))}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.test.tsnew file mode 100644index 0000000000..c694d8dd8a--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.test.ts@@ -0,0 +1,60 @@+import type { ExternalImageGeneratorModelConfig, MainModelConfig } from '@features/generation/core/types';+import type { TFunction } from 'i18next';++import i18n from 'i18next';+import { beforeAll, describe, expect, it } from 'vitest';++import { getDefaultSource, getFieldResetLabel } from './modelDefaultSettings';++const englishCatalog = Object.values(+ import.meta.glob('../../../../../public/locales/en.json', { eager: true, import: 'default' })+)[0] as Record<string, unknown>;+const instance = i18n.createInstance();+const t = ((key: string, values?: Record<string, unknown>) => instance.t(key, values)) as TFunction;++beforeAll(async () => {+ await instance.init({+ initAsync: false,+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: englishCatalog } },+ });+});++const sdxl = (defaults: MainModelConfig['default_settings'] = null): MainModelConfig => ({+ base: 'sdxl',+ default_settings: defaults,+ key: 'sdxl-model',+ name: 'Juggernaut',+ type: 'main',+});++describe('reset labels', () => {+ const getBaseLabel = (base: string) => (base === 'sdxl' ? 'SDXL' : base);+ const external: ExternalImageGeneratorModelConfig = {+ base: 'external',+ format: 'external_api',+ key: 'gpt-image',+ name: 'GPT Image',+ type: 'external_image_generator',+ };++ it("names the model's default where it sets one and the base's where it does not", () => {+ const model = sdxl({ steps: 8 });++ expect(getFieldResetLabel('steps', model, getBaseLabel, t)).toBe('Reset to model default');+ expect(getFieldResetLabel('size', model, getBaseLabel, t)).toBe('Reset to SDXL default');+ // One side from the model, the other from the base.+ expect(getFieldResetLabel('size', sdxl({ width: 896 }), getBaseLabel, t)).toBe('Reset to model and SDXL default');+ // An external model's fallbacks belong to no base.+ expect(getFieldResetLabel('size', external, getBaseLabel, t)).toBe('Reset to default');+ });++ it('tells a section whose settings come from both sources apart', () => {+ const model = sdxl({ steps: 8 });++ expect(getDefaultSource(model, ['steps'])).toBe('model');+ expect(getDefaultSource(model, ['steps', 'cfgScale'])).toBe('mixed');+ expect(getDefaultSource(model, ['size'])).toBe('base');+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.ts b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.tsindex 6be0112f64..9747d17a86 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.ts+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultSettings.ts@@ -1,77 +1,117 @@import type { GenerateModelConfig, GenerateSettings, VaeModelConfig } from '@features/generation/core/types';+import type { TFunction } from 'i18next';-import { getSettingsWithModelDefaults } from '@features/generation/core/baseGenerationPolicies';-import { getModelDefaultVae, hasModelDefaultVae } from '@features/generation/core/settings';--const MODEL_DEFAULT_VALUE_KEYS = [- 'aspectRatioId',- 'aspectRatioIsLocked',- 'aspectRatioValue',- 'cfgRescaleMultiplier',- 'cfgScale',- 'height',- 'modelKey',- 'scheduler',- 'steps',- 'vaePrecision',- 'width',-] as const satisfies readonly (keyof GenerateSettings)[];--/** Settings with the model's defaults applied, including its bundled default VAE when it has one. */-export const getModelDefaultSettings = (- settings: GenerateSettings,- model: GenerateModelConfig,- vaeModels: VaeModelConfig[]-): GenerateSettings => {- const nextSettings = getSettingsWithModelDefaults(settings, model);+import { getLockedAspectRatioSettings } from '@features/generation/core/aspectRatioPresets';+import { isAspectRatioLocked } from '@features/generation/core/settings';- return hasModelDefaultVae(model) ? { ...nextSettings, vae: getModelDefaultVae(model, vaeModels) } : nextSettings;-};+/** A setting the Model Manager can give a main model a default for. Width and height are one decision, size. */+export type ModelDefaultSetting =+ | 'cfgRescaleMultiplier'+ | 'cfgScale'+ | 'scheduler'+ | 'size'+ | 'steps'+ | 'vae'+ | 'vaePrecision';++type OwnDefaults = NonNullable<Extract<GenerateModelConfig, { type: 'main' }>['default_settings']>;++const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);++const getOwnDefaults = (model: GenerateModelConfig): OwnDefaults => (model.default_settings ?? {}) as OwnDefaults;++/** Where a reset takes its values from: the model's own defaults, the base's, or both. */+export type DefaultSource = 'base' | 'mixed' | 'model';/**- * Patch limited to the model-governed keys, so prompts and other fields stay untouched. Concepts are left as they are:- * the model already skips the ones it cannot load, and keeping them lets a compatible model run them again.+ * Where a setting's default comes from, read the way the defaults are applied: guidance falls back to CFG and back,+ * only fp16 or fp32 is a precision, and a size with one side set takes the other from the base. An external model's+ * defaults hold at most a size. The VAE depends on the catalog: see `resolveModelDefaultVae`.*/-export const getModelDefaultsPatch = (- settings: GenerateSettings,+const getSettingDefaultSource = (model: GenerateModelConfig,- vaeModels: VaeModelConfig[]-): Partial<GenerateSettings> => {- const defaults = getModelDefaultSettings(settings, model, vaeModels);- const patch: Partial<GenerateSettings> = { vae: defaults.vae };+ setting: Exclude<ModelDefaultSetting, 'vae'>+): DefaultSource => {+ const own = getOwnDefaults(model);- for (const key of MODEL_DEFAULT_VALUE_KEYS) {- (patch as Record<string, unknown>)[key] = defaults[key];+ switch (setting) {+ case 'size': {+ const sides = [own.width, own.height].filter(isFiniteNumber).length;++ return sides === 2 ? 'model' : sides === 1 ? 'mixed' : 'base';+ }+ case 'steps':+ return isFiniteNumber(own.steps) ? 'model' : 'base';+ case 'cfgScale':+ return isFiniteNumber(own.cfg_scale) || isFiniteNumber(own.guidance) ? 'model' : 'base';+ case 'cfgRescaleMultiplier':+ return isFiniteNumber(own.cfg_rescale_multiplier) ? 'model' : 'base';+ case 'scheduler':+ return typeof own.scheduler === 'string' && own.scheduler !== '' ? 'model' : 'base';+ case 'vaePrecision':+ return own.vae_precision === 'fp16' || own.vae_precision === 'fp32' ? 'model' : 'base';}+};++/** Whether the model's own defaults set the setting, even partly (one side of the size). */+export const doesModelSetDefault = (model: GenerateModelConfig, setting: Exclude<ModelDefaultSetting, 'vae'>) =>+ getSettingDefaultSource(model, setting) !== 'base';- return patch;+export const getDefaultSource = (+ model: GenerateModelConfig,+ settings: readonly Exclude<ModelDefaultSetting, 'vae'>[]+): DefaultSource => {+ const sources = new Set(settings.map((setting) => getSettingDefaultSource(model, setting)));++ return sources.size === 1 ? [...sources][0]! : 'mixed';};-/** Multi-key decisions such as size count as one override. */-const MODEL_DEFAULT_DECISION_GROUPS: readonly (readonly (typeof MODEL_DEFAULT_VALUE_KEYS)[number][])[] = [- ['aspectRatioId', 'aspectRatioIsLocked', 'aspectRatioValue', 'height', 'width'],- ['steps'],- ['cfgScale'],- ['cfgRescaleMultiplier'],- ['scheduler'],- ['vaePrecision'],-];--/** Count a VAE override once. */-export const countModelDefaultOverrides = (- settings: GenerateSettings,- modelDefaultSettings: GenerateSettings-): number => {- let count = MODEL_DEFAULT_DECISION_GROUPS.filter((group) =>- group.some((key) => !Object.is(settings[key], modelDefaultSettings[key]))- ).length;-- if (settings.vae?.key !== modelDefaultSettings.vae?.key) {- count += 1;- }+/** Whether `vae` is the one the model's defaults name, so choosing it is no change from them. */+export const isModelDefaultVae = (model: GenerateModelConfig | undefined, vae: VaeModelConfig | null): boolean =>+ vae !== null && model !== undefined && (getOwnDefaults(model) as { vae?: unknown }).vae === vae.key;- return count;+type Dimensions = Pick<GenerateSettings, 'height' | 'width'>;++/** A whole default size: a lock stays on and takes the size's ratio, an unlocked ratio stays unlocked. */+export const getDefaultSizePatch = (+ settings: Pick<GenerateSettings, 'aspectRatioId' | 'aspectRatioIsLocked'>,+ { height, width }: Dimensions+): Partial<GenerateSettings> => {+ const ratio = height > 0 ? width / height : 1;++ return {+ ...(isAspectRatioLocked(settings)+ ? getLockedAspectRatioSettings(ratio)+ : { aspectRatioId: 'Free', aspectRatioIsLocked: false, aspectRatioValue: ratio }),+ height,+ width,+ };};-export const settingsMatchModelDefaults = (settings: GenerateSettings, modelDefaultSettings: GenerateSettings) =>- countModelDefaultOverrides(settings, modelDefaultSettings) === 0;+/**+ * What a field's reset returns to, named honestly: the model's default when the model sets it, the base's (a main+ * model) when it does not, both for a size with one side set, or a plain default for an external model, whose+ * fallbacks belong to no base.+ */+export const getFieldResetLabel = (+ setting: Exclude<ModelDefaultSetting, 'vae'>,+ model: GenerateModelConfig | undefined,+ getBaseLabel: (base: string) => string,+ t: TFunction+): string => {+ const source = model ? getSettingDefaultSource(model, setting) : 'base';++ if (source === 'model') {+ return t('widgets.generate.resetToModelDefault');+ }++ if (model?.type !== 'main') {+ return t('widgets.generate.resetToDefault');+ }++ const base = getBaseLabel(model.base);++ return source === 'mixed'+ ? t('widgets.generate.resetToModelAndBaseDefault', { base })+ : t('widgets.generate.resetToBaseDefault', { base });+};diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.test.ts b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.test.tsnew file mode 100644index 0000000000..650e3e175f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.test.ts@@ -0,0 +1,257 @@+import type { GenerateSettings, MainModelConfig, VaeModelConfig } from '@features/generation/core/types';+import type { TFunction } from 'i18next';++import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';+import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';+import i18n from 'i18next';+import { beforeAll, describe, expect, it } from 'vitest';++import {+ describeChanges,+ describeUnset,+ getApplyModelDefaultsPlan,+ getChangedSettings,+ getModelDefaultsPatch,+} from './modelDefaultsReset';++seedArchitectureCapabilities();++const englishCatalog = Object.values(+ import.meta.glob('../../../../../public/locales/en.json', { eager: true, import: 'default' })+)[0] as Record<string, unknown>;+const instance = i18n.createInstance();+const t = ((key: string, values?: Record<string, unknown>) => instance.t(key, values)) as TFunction;++beforeAll(async () => {+ await instance.init({+ initAsync: false,+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: englishCatalog } },+ });+});++const sdxl = (defaults: MainModelConfig['default_settings'] = null): MainModelConfig => ({+ base: 'sdxl',+ default_settings: defaults,+ key: 'sdxl-model',+ name: 'Juggernaut',+ type: 'main',+});+const fixVae: VaeModelConfig = { base: 'sdxl', key: 'sdxl-vae-fix', name: 'SDXL VAE fp16 fix', type: 'vae' };+const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };+const customVae: VaeModelConfig = { base: 'sdxl', key: 'custom-vae', name: 'Custom VAE', type: 'vae' };++/** The user's own values: SDXL's base defaults changed everywhere the model's defaults could reach. */+const userSettings = (overrides: Partial<GenerateSettings> = {}): GenerateSettings => ({+ ...getDefaultGenerateSettings(sdxl()),+ aspectRatioId: 'Free',+ aspectRatioIsLocked: false,+ aspectRatioValue: 1216 / 832,+ cfgScale: 4,+ height: 832,+ scheduler: 'dpmpp_2m_k',+ steps: 12,+ vae: customVae,+ vaePrecision: 'fp16',+ width: 1216,+ ...overrides,+});++const after = (settings: GenerateSettings, patch: Partial<GenerateSettings>) => ({ ...settings, ...patch });++describe('getApplyModelDefaultsPlan', () => {+ it('changes only what the model sets: steps and CFG, leaving the size and everything else alone', () => {+ const model = sdxl({ cfg_scale: 1, steps: 8 });+ const plan = getApplyModelDefaultsPlan(userSettings(), model, [fixVae, customVae]);++ expect(plan.patch).toEqual({ cfgScale: 1, steps: 8 });+ expect(plan.changed).toEqual(['steps', 'cfgScale']);+ expect(plan.isVaeMissing).toBe(false);+ expect(plan.unset).toEqual(['size', 'scheduler', 'vae', 'vaePrecision']);+ });++ it('types a lone default width into the field: an unlocked height stays, a locked one follows the ratio', () => {+ const model = sdxl({ width: 896 });++ expect(getApplyModelDefaultsPlan(userSettings(), model, []).patch).toEqual({ height: 832, width: 896 });+ expect(+ getApplyModelDefaultsPlan(+ userSettings({ aspectRatioId: '16:9', aspectRatioValue: 16 / 9, height: 576, width: 1024 }),+ model,+ []+ ).patch+ ).toEqual({ height: 504, width: 896 });+ });++ it('types a lone default height the same way', () => {+ expect(getApplyModelDefaultsPlan(userSettings(), sdxl({ height: 1152 }), []).patch).toEqual({+ height: 1152,+ width: 1216,+ });+ });++ it('applies a whole default size with the ratio following it, keeping the lock as it was', () => {+ const model = sdxl({ height: 1152, width: 768 });++ expect(getApplyModelDefaultsPlan(userSettings(), model, []).patch).toEqual({+ aspectRatioId: 'Free',+ aspectRatioIsLocked: false,+ aspectRatioValue: 768 / 1152,+ height: 1152,+ width: 768,+ });+ expect(+ getApplyModelDefaultsPlan(userSettings({ aspectRatioId: '1:1', aspectRatioValue: 1 }), model, []).patch+ ).toMatchObject({ aspectRatioId: '2:3', aspectRatioIsLocked: true, height: 1152, width: 768 });+ });++ it('has nothing to apply when the model sets no defaults, however far the settings are from the base', () => {+ const plan = getApplyModelDefaultsPlan(userSettings(), sdxl(), [fixVae]);++ expect(plan.patch).toEqual({});+ expect(plan.defined).toEqual([]);+ });++ it('has nothing to apply once the values the model sets hold, whatever the rest is', () => {+ const plan = getApplyModelDefaultsPlan(userSettings({ steps: 8 }), sdxl({ steps: 8 }), []);++ expect(plan.patch).toEqual({});+ expect(plan.defined).toEqual(['steps']);+ });++ it("applies the model's VAE when it sets one, the bundled one for the 'default' sentinel, and none otherwise", () => {+ expect(getApplyModelDefaultsPlan(userSettings(), sdxl({ vae: fixVae.key }), [fixVae]).patch).toEqual({+ vae: fixVae,+ });+ expect(getApplyModelDefaultsPlan(userSettings(), sdxl({ vae: 'default' }), [fixVae]).patch).toEqual({+ vae: null,+ });+ // The same VAE as a different snapshot is no change.+ expect(+ getApplyModelDefaultsPlan(userSettings({ vae: { ...fixVae } }), sdxl({ vae: fixVae.key }), [fixVae]).patch+ ).toEqual({});+ expect(getApplyModelDefaultsPlan(userSettings(), sdxl({ steps: 30 }), [fixVae]).patch).not.toHaveProperty('vae');+ });++ it("applies the bundled VAE for the 'default' sentinel where the VAE is an optional component", () => {+ const sd3: MainModelConfig = { ...sdxl({ vae: 'default' }), base: 'sd-3' };+ const sd3Vae: VaeModelConfig = { base: 'sd-3', key: 'sd3-vae', name: 'SD3 VAE', type: 'vae' };+ const settings = { ...getDefaultGenerateSettings(sd3), vae: sd3Vae };+ const plan = getApplyModelDefaultsPlan(settings, sd3, [sd3Vae]);++ // SD3 has no VAE override field; the default the model sets is applied and told all the same.+ expect(plan.patch).toEqual({ vae: null });+ expect(describeChanges(plan.changed, settings, after(settings, plan.patch), sd3, t, 'en')).toBe(+ 'VAE SD3 VAE → Bundled VAE'+ );+ // With the bundled VAE in use, the model's defaults hold: it does set one.+ expect(getApplyModelDefaultsPlan({ ...settings, vae: null }, sd3, [sd3Vae]).defined).toEqual(['vae']);+ });++ it("keeps the user's VAE when the model names one that is not installed, and says so", () => {+ const model = sdxl({ steps: 8, vae: 'uninstalled-vae' });+ const plan = getApplyModelDefaultsPlan(userSettings(), model, [fixVae]);++ expect(plan.patch).toEqual({ steps: 8 });+ expect(plan.isVaeMissing).toBe(true);+ // The VAE is told apart: the model does set one.+ expect(describeUnset(plan.unset, model, t, 'en')).toBe('Size, CFG, Scheduler, and VAE precision');+ expect(after(userSettings(), getModelDefaultsPatch(userSettings(), model, [fixVae])).vae).toBe(customVae);+ });++ it("never clears a family's required VAE for the 'default' sentinel, which has no bundled VAE there", () => {+ const flux: MainModelConfig = { ...sdxl({ steps: 20, vae: 'default' }), base: 'flux' };+ const settings = { ...getDefaultGenerateSettings(flux), steps: 28, vae: fluxVae };+ const plan = getApplyModelDefaultsPlan(settings, flux, [fluxVae]);++ expect(plan.patch).toEqual({ steps: 20 });+ // No VAE override field, and nothing the model sets: VAE is not even mentioned.+ expect(plan.unset).not.toContain('vae');+ expect(after(settings, getModelDefaultsPatch(settings, flux, [fluxVae])).vae).toBe(fluxVae);+ // A FLUX VAE the model names and the catalog holds still applies.+ expect(+ getApplyModelDefaultsPlan({ ...settings, vae: null }, { ...flux, default_settings: { vae: fluxVae.key } }, [+ fluxVae,+ ]).patch+ ).toEqual({ vae: fluxVae });+ });++ it('leaves out a setting the form does not show for the family, such as a scheduler its graph ignores', () => {+ const qwen: MainModelConfig = { ...sdxl({ scheduler: 'dpmpp_2m_k', steps: 20 }), base: 'qwen-image' };+ const plan = getApplyModelDefaultsPlan(userSettings({ scheduler: 'euler' }), qwen, []);++ expect(plan.patch).toEqual({ steps: 20 });+ expect(plan.unset).not.toContain('scheduler');+ });+});++describe('getModelDefaultsPatch (reset everything)', () => {+ it('tells a ratio the reset locks, even when the size stays, and leaves out what the family hides', () => {+ const model = sdxl();+ // SDXL hides CFG rescale; a leftover value the reset clears is no change worth telling.+ const settings = userSettings({+ cfgRescaleMultiplier: 0.7,+ cfgScale: 7,+ height: 1024,+ scheduler: 'euler_a',+ steps: 30,+ vaePrecision: 'fp32',+ width: 1024,+ });+ const next = after(settings, getModelDefaultsPatch(settings, model, []));+ const changed = getChangedSettings(settings, next, model);++ expect(changed).toEqual(['aspectRatio']);+ expect(describeChanges(changed, settings, next, model, t, 'en')).toBe('Aspect ratio Free → 1:1');+ });++ it("still fills what the model leaves unset from the base, size included, and keeps the user's VAE", () => {+ const settings = userSettings();+ const patch = getModelDefaultsPatch(settings, sdxl({ steps: 8 }), [fixVae]);++ expect(patch).toMatchObject({ cfgScale: 7, height: 1024, scheduler: 'euler_a', steps: 8, width: 1024 });+ expect(after(settings, patch).vae).toBe(customVae);+ });+});++describe('describeChanges', () => {+ it('names each change as its field does, from the old value to the new one', () => {+ const model = sdxl({+ height: 1344,+ scheduler: 'euler_a',+ steps: 8,+ vae: fixVae.key,+ vae_precision: 'fp32',+ width: 768,+ });+ const settings = userSettings();+ const plan = getApplyModelDefaultsPlan(settings, model, [fixVae]);++ expect(describeChanges(plan.changed, settings, after(settings, plan.patch), model, t, 'en')).toBe(+ 'Size 1216×832 → 768×1344, Steps 12 → 8, Scheduler DPM++ 2M Karras → Euler Ancestral, ' ++ 'VAE Custom VAE → SDXL VAE fp16 fix, VAE precision FP16 → FP32'+ );+ });++ it('calls the guidance setting what the family calls it', () => {+ const flux: MainModelConfig = { ...sdxl({ guidance: 2.5 }), base: 'flux' };+ const settings = { ...getDefaultGenerateSettings(flux), cfgScale: 4 };+ const plan = getApplyModelDefaultsPlan(settings, flux, []);++ expect(describeChanges(plan.changed, settings, after(settings, plan.patch), flux, t, 'en')).toBe(+ 'Guidance 4 → 2.5'+ );+ expect(describeUnset(plan.unset, flux, t, 'en')).toBe('Size, Steps, and Scheduler');+ });++ it('writes numbers exactly as the fields show them, so differing values never read the same', () => {+ const model = sdxl({ cfg_scale: 7.125 });+ const settings = userSettings({ cfgScale: 7.1254 });+ const plan = getApplyModelDefaultsPlan(settings, model, []);++ expect(describeChanges(plan.changed, settings, after(settings, plan.patch), model, t, 'en')).toBe(+ 'CFG 7.1254 → 7.125'+ );+ });+});diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.ts b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.tsnew file mode 100644index 0000000000..a4d2e8982c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/modelDefaultsReset.ts@@ -0,0 +1,331 @@+import type { GenerateModelConfig, GenerateSettings, VaeModelConfig } from '@features/generation/core/types';+import type { TFunction } from 'i18next';++import { formatAspectRatio } from '@features/generation/core/aspectRatioPresets';+import {+ getDefaultGenerateSettings,+ getGenerationDimensions,+ getGenerationUiPolicy,+ getSchedulerOptions,+ getSettingsWithModelDefaults,+ resolveModelDefaultVae,+} from '@features/generation/core/baseGenerationPolicies';+import { clampDimension, getActiveAspectRatio, isAspectRatioLocked } from '@features/generation/core/settings';++import {+ doesModelSetDefault,+ getDefaultSizePatch,+ getDefaultSource,+ type ModelDefaultSetting,+} from './modelDefaultSettings';++// The Generate reset menu's plan and wording. Only that menu reads them, and it loads with the menu, off the editor's+// startup; the fields' reset labels read `modelDefaultSettings`.++/** What a reset is described by: the settings, plus the aspect ratio lock a size change can set or release. */+export type DescribedSetting = ModelDefaultSetting | 'aspectRatio';++/** In the order the form shows them: Size, then Render, then Advanced. */+const DESCRIBED_SETTINGS: readonly DescribedSetting[] = [+ 'size',+ 'aspectRatio',+ 'steps',+ 'cfgScale',+ 'scheduler',+ 'vae',+ 'vaePrecision',+ 'cfgRescaleMultiplier',+];++/** Whether the form shows the setting for this family, so a value its graph ignores is neither applied nor told. */+const isShown = (setting: DescribedSetting, model: GenerateModelConfig): boolean => {+ const policy = getGenerationUiPolicy(model);++ switch (setting) {+ case 'scheduler':+ return policy.schedulerVisible;+ case 'cfgRescaleMultiplier':+ return policy.cfgRescaleVisible;+ case 'vaePrecision':+ return policy.vaePrecisionVisible;+ default:+ return true;+ }+};++/**+ * The model's size, as typing its values into the fields would set it. With only one side set, that side is typed: a+ * locked ratio carries the other side along, an unlocked one leaves it.+ */+const getOwnSizePatch = (+ settings: GenerateSettings,+ model: GenerateModelConfig,+ defaults: Pick<GenerateSettings, 'height' | 'width'>+): Partial<GenerateSettings> => {+ if (getDefaultSource(model, ['size']) === 'model') {+ return getDefaultSizePatch(settings, defaults);+ }++ // The model sets one side.+ const hasWidth = Number.isFinite((model.default_settings as { width?: unknown } | null | undefined)?.width);++ const isLocked = isAspectRatioLocked(settings);+ const ratio = getActiveAspectRatio(settings);+ const { grid } = getGenerationDimensions(model);++ return hasWidth+ ? { height: isLocked ? clampDimension(defaults.width / ratio, grid) : settings.height, width: defaults.width }+ : { height: defaults.height, width: isLocked ? clampDimension(defaults.height * ratio, grid) : settings.width };+};++/** The ratio a lock holds, by built-in id or value; one value for every unlocked state, whose stored ratio is unused. */+const getAspectRatioState = (settings: GenerateSettings): string =>+ !isAspectRatioLocked(settings)+ ? 'unlocked'+ : settings.aspectRatioId === 'Free'+ ? `Free:${settings.aspectRatioValue}`+ : settings.aspectRatioId;++const isSettingChanged = (setting: DescribedSetting, before: GenerateSettings, after: GenerateSettings): boolean => {+ switch (setting) {+ case 'size':+ return before.width !== after.width || before.height !== after.height;+ case 'aspectRatio':+ return getAspectRatioState(before) !== getAspectRatioState(after);+ case 'vae':+ return (before.vae?.key ?? null) !== (after.vae?.key ?? null);+ default:+ return !Object.is(before[setting], after[setting]);+ }+};++/**+ * What a change from `before` to `after` does to the settings the family shows, in form order. Both resets are told,+ * offered and toasted from this, so none of those can disagree with what the patch does.+ */+export const getChangedSettings = (+ before: GenerateSettings,+ after: GenerateSettings,+ model: GenerateModelConfig+): DescribedSetting[] =>+ DESCRIBED_SETTINGS.filter((setting) => isShown(setting, model) && isSettingChanged(setting, before, after));++export interface ApplyModelDefaultsPlan {+ /** Only the settings that change; empty when the model's defaults already hold. */+ patch: Partial<GenerateSettings>;+ changed: readonly DescribedSetting[];+ /** Shown settings the model sets a default for, changed or not. */+ defined: readonly ModelDefaultSetting[];+ /** Shown settings the model sets no default for, which applying leaves as they are. */+ unset: readonly ModelDefaultSetting[];+ /** The model names a VAE that is not installed or does not fit; the user's VAE stays. */+ isVaeMissing: boolean;+}++/**+ * Apply model defaults: only the values the model's own defaults set, as the legacy "Use default settings" did. A+ * setting the model leaves unset keeps its value, and a set one that already matches is left out of the patch.+ */+export const getApplyModelDefaultsPlan = (+ settings: GenerateSettings,+ model: GenerateModelConfig,+ vaeModels: readonly VaeModelConfig[]+): ApplyModelDefaultsPlan => {+ const defaults = getDefaultGenerateSettings(model);+ const defaultVae = resolveModelDefaultVae(model, settings, vaeModels);+ // Where the VAE has no field of its own, a default the model sets is still applied and told.+ const isVaeShown = getGenerationUiPolicy(model).sdVaeVisible || defaultVae.kind !== 'none';+ const patch: Partial<GenerateSettings> = {};+ const defined: ModelDefaultSetting[] = [];+ const unset: ModelDefaultSetting[] = [];++ for (const setting of DESCRIBED_SETTINGS) {+ if (setting === 'aspectRatio' || !isShown(setting, model) || (setting === 'vae' && !isVaeShown)) {+ continue;+ }++ const isSet = setting === 'vae' ? defaultVae.kind === 'apply' : doesModelSetDefault(model, setting);++ if (!isSet) {+ // A missing VAE is told apart from an unset one.+ if (!(setting === 'vae' && defaultVae.kind === 'missing')) {+ unset.push(setting);+ }+ continue;+ }++ defined.push(setting);+ const settingPatch: Partial<GenerateSettings> =+ setting === 'size'+ ? getOwnSizePatch(settings, model, defaults)+ : setting === 'vae'+ ? { vae: defaultVae.kind === 'apply' ? defaultVae.vae : null }+ : { [setting]: defaults[setting] };++ if (isSettingChanged(setting, settings, { ...settings, ...settingPatch })) {+ Object.assign(patch, settingPatch);+ }+ }++ return {+ changed: getChangedSettings(settings, { ...settings, ...patch }, model),+ defined,+ isVaeMissing: defaultVae.kind === 'missing',+ patch,+ unset,+ };+};++/**+ * Settings with every model-governed value reset: the model's where it sets one, the base's otherwise. The VAE changes+ * only to one the model's defaults can apply; otherwise the user's stays, since the base has no VAE to return to.+ */+export const getModelDefaultSettings = (+ settings: GenerateSettings,+ model: GenerateModelConfig,+ vaeModels: readonly VaeModelConfig[]+): GenerateSettings => {+ const nextSettings = getSettingsWithModelDefaults(settings, model);+ const defaultVae = resolveModelDefaultVae(model, settings, vaeModels);++ // The menu's policy for a default VAE that cannot apply: the user's VAE stays, and the menu says so.+ return defaultVae.kind === 'apply' ? { ...nextSettings, vae: defaultVae.vae } : nextSettings;+};++const MODEL_DEFAULT_VALUE_KEYS = [+ 'aspectRatioId',+ 'aspectRatioIsLocked',+ 'aspectRatioValue',+ 'cfgRescaleMultiplier',+ 'cfgScale',+ 'height',+ 'modelKey',+ 'scheduler',+ 'steps',+ 'vaePrecision',+ 'width',+] as const satisfies readonly (keyof GenerateSettings)[];++/**+ * Reset everything to defaults, limited to the model-governed keys so prompts and other fields stay untouched.+ * Concepts are left as they are: the model already skips the ones it cannot load, and keeping them lets a compatible+ * model run them again.+ */+export const getModelDefaultsPatch = (+ settings: GenerateSettings,+ model: GenerateModelConfig,+ vaeModels: readonly VaeModelConfig[]+): Partial<GenerateSettings> => {+ const defaults = getModelDefaultSettings(settings, model, vaeModels);+ const patch: Partial<GenerateSettings> = { vae: defaults.vae };++ for (const key of MODEL_DEFAULT_VALUE_KEYS) {+ (patch as Record<string, unknown>)[key] = defaults[key];+ }++ return patch;+};++/** The setting's name as its field shows it: CFG or Guidance per family. */+const getSettingLabel = (setting: DescribedSetting, model: GenerateModelConfig, t: TFunction): string => {+ switch (setting) {+ case 'aspectRatio':+ return t('widgets.generate.aspectRatio');+ case 'cfgRescaleMultiplier':+ return t('widgets.generate.cfgRescale');+ case 'cfgScale':+ return getGenerationUiPolicy(model).guidanceLabel;+ case 'scheduler':+ return t('widgets.generate.scheduler');+ case 'size':+ return t('widgets.generate.size');+ case 'steps':+ return t('widgets.generate.steps');+ case 'vae':+ return t('widgets.generate.vae');+ case 'vaePrecision':+ return t('widgets.generate.vaePrecision');+ }+};++const formatSettingValue = (+ setting: DescribedSetting,+ settings: GenerateSettings,+ model: GenerateModelConfig,+ t: TFunction,+ locale: string | undefined+): string => {+ switch (setting) {+ // Digits as the size fields show them, without grouping.+ case 'size':+ return `${settings.width}×${settings.height}`;+ case 'aspectRatio':+ return !isAspectRatioLocked(settings)+ ? t('widgets.generate.aspectRatioFree')+ : settings.aspectRatioId === 'Free'+ ? formatAspectRatio(settings.aspectRatioValue, locale)+ : settings.aspectRatioId;+ case 'scheduler':+ return (+ getSchedulerOptions(model, settings.scheduler).find((option) => option.value === settings.scheduler)?.label ??+ settings.scheduler+ );+ case 'vae':+ return settings.vae?.name ?? t('widgets.generate.bundledVae');+ case 'vaePrecision':+ return settings.vaePrecision.toUpperCase();+ // Exactly as the fields show them, so two values that differ there never read the same here.+ default:+ return String(settings[setting]);+ }+};++// Constructing a ListFormat costs far more than formatting with one, and the menu formats on every open.+const listFormats = new Map<string, Intl.ListFormat>();+const formatList = (items: readonly string[], locale: string | undefined, type: 'conjunction' | 'unit'): string => {+ const key = `${locale ?? ''}\u0000${type}`;+ let format = listFormats.get(key);++ if (!format) {+ format = new Intl.ListFormat(locale, { style: type === 'unit' ? 'short' : 'long', type });+ listFormats.set(key, format);+ }++ return format.format(items);+};++/** The change as one list, such as "Steps 30 → 8, CFG 7 → 1"; empty when nothing changes. */+export const describeChanges = (+ changed: readonly DescribedSetting[],+ before: GenerateSettings,+ after: GenerateSettings,+ model: GenerateModelConfig,+ t: TFunction,+ locale: string | undefined+): string =>+ formatList(+ changed.map((setting) =>+ t('widgets.generate.modelDefaultsChange', {+ from: formatSettingValue(setting, before, model, t, locale),+ setting: getSettingLabel(setting, model, t),+ to: formatSettingValue(setting, after, model, t, locale),+ })+ ),+ locale,+ 'unit'+ );++/** The settings Apply leaves as they are because the model sets no default, as one list; null for none. */+export const describeUnset = (+ unset: readonly ModelDefaultSetting[],+ model: GenerateModelConfig,+ t: TFunction,+ locale: string | undefined+): string | null =>+ unset.length > 0+ ? formatList(+ unset.map((setting) => getSettingLabel(setting, model, t)),+ locale,+ 'conjunction'+ )+ : null;diff --git a/invokeai/frontend/webv2/src/features/generation/ui/shared/sectionPanel.tsx b/invokeai/frontend/webv2/src/features/generation/ui/shared/sectionPanel.tsxnew file mode 100644index 0000000000..407e0bdea6--- /dev/null+++ b/invokeai/frontend/webv2/src/features/generation/ui/shared/sectionPanel.tsx@@ -0,0 +1,165 @@+import type { ReactNode } from 'react';++import { createKeyedTransientStore } from '@platform/state/externalStore';+import { createContext, use, useId } from 'react';++/** A mounted section, as the panel's group actions, title keys and jump menu reach it. */+export interface SectionPanelEntry {+ /** Stable for the section's mount; keys the jump menu's items. */+ key: string;+ label: string;+ /** The `.generate-section` root; its `data-state` is the section's open state. */+ root: HTMLElement;+ trigger: HTMLElement;+ /** Persisted sections write through the preference port, so a panel-wide change is one write. */+ sectionId: string | undefined;+ /** For a section without `sectionId`, whose open state is its own. */+ setLocalOpen: (open: boolean) => void;+}++type PersistSectionsOpen = (changes: Readonly<Record<string, boolean>>) => void;++const NO_ENTRIES: readonly SectionPanelEntry[] = [];++/**+ * Sections by panel id. A widget's header and body render apart, so the header's jump menu finds the body's sections+ * here under the widget instance id. Entries come and go with their sections' mounts.+ */+const panels = createKeyedTransientStore<string, readonly SectionPanelEntry[]>();++const byDocumentOrder = (left: SectionPanelEntry, right: SectionPanelEntry) =>+ left.root.compareDocumentPosition(right.root) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;++/** Adds a mounted section to its panel, in document order; the returned cleanup removes it. */+export const registerPanelSection = (panelId: string, entry: SectionPanelEntry): (() => void) => {+ panels.set(panelId, [...(panels.get(panelId) ?? NO_ENTRIES), entry].sort(byDocumentOrder));++ return () => {+ const remaining = (panels.get(panelId) ?? NO_ENTRIES).filter((candidate) => candidate !== entry);++ if (remaining.length === 0) {+ panels.delete(panelId);+ } else {+ panels.set(panelId, remaining);+ }+ };+};++export const getPanelSections = (panelId: string): readonly SectionPanelEntry[] => panels.get(panelId) ?? NO_ENTRIES;++/** The panel's sections in document order, for a view that lists them. */+export const usePanelSections = (panelId: string | undefined): readonly SectionPanelEntry[] =>+ panels.useValue(panelId ?? '') ?? NO_ENTRIES;++export const isPanelSectionOpen = (entry: SectionPanelEntry): boolean => entry.root.dataset.state === 'open';++/** Applies several open states at once: one preference write for the persisted sections, local state for the rest. */+export const setPanelSectionsOpen = (+ changes: ReadonlyArray<readonly [SectionPanelEntry, boolean]>,+ persist: PersistSectionsOpen+): void => {+ const persisted: Record<string, boolean> = {};++ for (const [entry, open] of changes) {+ if (isPanelSectionOpen(entry) === open) {+ continue;+ }+ if (entry.sectionId === undefined) {+ entry.setLocalOpen(open);+ } else {+ persisted[entry.sectionId] = open;+ }+ }++ if (Object.keys(persisted).length > 0) {+ persist(persisted);+ }+};++/** Opens `target` and folds every other section in its panel. */+export const soloPanelSection = (+ entries: readonly SectionPanelEntry[],+ target: HTMLElement,+ persist: PersistSectionsOpen+): void =>+ setPanelSectionsOpen(+ entries.map((entry) => [entry, entry.root === target] as const),+ persist+ );++/** Opens every section when any is folded; folds them all otherwise. */+export const toggleAllPanelSections = (entries: readonly SectionPanelEntry[], persist: PersistSectionsOpen): void => {+ const open = entries.some((entry) => !isPanelSectionOpen(entry));++ setPanelSectionsOpen(+ entries.map((entry) => [entry, open] as const),+ persist+ );+};++/** The settle-scroll still waiting on each section's opening, so a newer reveal replaces it. */+const pendingSettles = new WeakMap<HTMLElement, AbortController>();+/** Past any opening animation (reduced motion included); a settle not heard by then is dropped. */+const SETTLE_TIMEOUT_MS = 1000;++/**+ * Brings a section to the top of its panel with its title focused, opening it first when it is folded. The scroll+ * repeats once the opening animation ends: until then the panel may be too short to put the section at the top. A+ * fold, unmount or newer reveal before then drops the repeat.+ */+export const revealPanelSection = (entry: SectionPanelEntry, persist: PersistSectionsOpen): void => {+ const wasOpen = isPanelSectionOpen(entry);++ pendingSettles.get(entry.root)?.abort();+ if (!wasOpen) {+ setPanelSectionsOpen([[entry, true]], persist);+ }++ // After the menu that asked for this has handed focus back to its trigger.+ requestAnimationFrame(() => {+ entry.root.scrollIntoView({ block: 'start' });+ entry.trigger.focus({ preventScroll: true });++ const content = wasOpen ? null : entry.root.querySelector(':scope > [data-part="content"]');++ if (!content) {+ return;+ }++ const settle = new AbortController();+ const timeout = window.setTimeout(() => settle.abort(), SETTLE_TIMEOUT_MS);++ pendingSettles.set(entry.root, settle);+ settle.signal.addEventListener('abort', () => window.clearTimeout(timeout));+ content.addEventListener(+ 'animationend',+ (event) => {+ // Animations inside the fields bubble here too; only the content's own ends the opening.+ if (event.target !== content) {+ return;+ }++ settle.abort();+ if (entry.root.isConnected && isPanelSectionOpen(entry)) {+ entry.root.scrollIntoView({ block: 'start' });+ }+ },+ { signal: settle.signal }+ );+ });+};++const SectionPanelContext = createContext<string | null>(null);++/** The panel id the sections inside belong to, or null outside a panel. */+export const useSectionPanelId = (): string | null => use(SectionPanelContext);++/**+ * Groups the sections inside into one panel: solo and expand-all act on them together, and title arrow keys move+ * between them. Pass the widget instance id so its header's jump menu finds the same sections.+ */+export const GenerationSectionPanel = ({ children, id }: { children: ReactNode; id?: string }) => {+ const fallbackId = useId();++ return <SectionPanelContext value={id ?? fallbackId}>{children}</SectionPanelContext>;+};diff --git a/invokeai/frontend/webv2/src/features/identity/index.ts b/invokeai/frontend/webv2/src/features/identity/index.tsindex 845c91c0c7..650902e714 100644--- a/invokeai/frontend/webv2/src/features/identity/index.ts+++ b/invokeai/frontend/webv2/src/features/identity/index.ts@@ -31,8 +31,7 @@ export {type UserDTO,type UserUpdateRequest,} from './data/api';-export { AccountMenu } from './ui/AccountMenu';-export { AccountMenuSection, AccountProfileDialog, useHasAccountSection } from './ui/AccountMenuSection';+export { AccountMenu, useHasAccountMenu } from './ui/AccountMenu';export { AuthUnavailableScreen } from './ui/AuthUnavailableScreen';export { SessionExpiryNotice } from './ui/SessionExpiryNotice';export { LoginScreen, readLoginReturnPath } from './ui/LoginScreen';diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.browser.test.tsxindex dc334a6a72..aeb358b4cc 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.browser.test.tsx@@ -8,6 +8,7 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';+const account = vi.hoisted(() => ({ displayName: 'Ada' as string | null }));vi.mock('@features/identity/session', async (importOriginal) => {const original = await importOriginal<typeof SessionModule>();const session: SessionModule.AuthSession = {@@ -31,7 +32,10 @@ vi.mock('@features/identity/session', async (importOriginal) => {},};- return { ...original, useAuthSession: () => session };+ return {+ ...original,+ useAuthSession: () => ({ ...session, user: { ...session.user!, display_name: account.displayName } }),+ };});vi.mock('@tanstack/react-router', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),@@ -53,13 +57,77 @@ beforeEach(() => {});afterEach(async () => {+ account.displayName = 'Ada';await act(() => root.unmount());host.remove();});const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');+const renderMenu = (compact = false) =>+ act(() =>+ root.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={new QueryClient()}>+ <AccountMenu compact={compact} />+ </QueryClientProvider>+ </ChakraProvider>+ )+ );++/** How far the initials' ink centre sits from the avatar's centre, from the font's own glyph metrics. */+const initialsOffset = () => {+ const avatar = host.querySelector('[data-scope="avatar"][data-part="root"]')!;+ const initials = avatar.querySelector<HTMLElement>('[data-part="fallback"]')!;+ const style = getComputedStyle(initials);+ const context = document.createElement('canvas').getContext('2d')!;+ context.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;+ const ink = context.measureText(initials.textContent!.toUpperCase());+ // A zero-height inline block rests on the baseline.+ const marker = document.createElement('span');+ marker.style.cssText = 'display: inline-block; height: 0; vertical-align: baseline; width: 0';+ initials.append(marker);+ const baseline = marker.getBoundingClientRect().top;+ marker.remove();+ const range = document.createRange();+ range.selectNodeContents(initials);+ const start = range.getBoundingClientRect().left;+ const circle = avatar.getBoundingClientRect();++ return {+ x: start + (ink.actualBoundingBoxRight - ink.actualBoundingBoxLeft) / 2 - (circle.left + circle.width / 2),+ y: baseline + (ink.actualBoundingBoxDescent - ink.actualBoundingBoxAscent) / 2 - (circle.top + circle.height / 2),+ };+};+describe('AccountMenu', () => {+ // Untrimmed, the font's descender room lifts the capitals half a pixel at this size; trimmed, they sit dead centre.+ it.each([+ ['row', false],+ ['icon-only rail', true],+ ])('centres the initials in the avatar in the %s', async (_width, compact) => {+ await renderMenu(compact);+ await document.fonts.ready;++ const offset = initialsOffset();+ expect(Math.abs(offset.x)).toBeLessThanOrEqual(0.25);+ expect(Math.abs(offset.y)).toBeLessThanOrEqual(0.25);+ });++ it('shows the name over the email, or the role for an account known only by its email', async () => {+ await renderMenu();+ const trigger = () => host.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!;+ const lines = () => [...trigger().querySelectorAll('p')].map((line) => line.textContent);+ // Named by these lines (the avatar is decorative), so the spoken name is what is shown.+ expect(trigger().getAttribute('aria-label')).toBeNull();+ expect(trigger().querySelector('[data-scope="avatar"]')?.getAttribute('aria-hidden')).toBe('true');+ expect(lines()).toEqual(['Ada', '[email protected]']);++ account.displayName = null;+ await renderMenu();+ expect(lines()).toEqual(['[email protected]', 'users.user']);+ });+it('returns focus to the menu button when Account settings closes', async () => {await act(() =>root.render(diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsxindex aa5acef242..79d2da4066 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenu.tsx@@ -1,21 +1,63 @@-import { Avatar, Badge, Box, chakra, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import type { SystemStyleObject } from '@chakra-ui/react';++import { Avatar, Badge, Box, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { logoutSession, useAuthSession } from '@features/identity/session';-import { MenuContent } from '@platform/ui';+import { Button, IconButton } from '@platform/ui/Button';+import { MenuContent } from '@platform/ui/Menu';+import { MiddleTruncate, type MiddleTruncateProps } from '@platform/ui/MiddleTruncate';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';import { useNavigate } from '@tanstack/react-router';-import { ChevronDownIcon, LogOutIcon, UserRoundCogIcon, UsersIcon } from 'lucide-react';+import { ChevronRightIcon, LogOutIcon, UserRoundCogIcon, UsersIcon } from 'lucide-react';import { useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { ProfileDialog } from './ProfileDialog';-const MENU_POSITIONING = { placement: 'bottom-end' } as const;-const TRIGGER_HOVER = { bg: 'bg.subtle' } as const;+// Opens beside a navigation rail's footer, rising from its bottom edge, so it never runs off the window.+const MENU_POSITIONING = { placement: 'right-end' } as const;+/** Two lines need more than a rail link's fixed height; the padding keeps the avatar clear of the hover fill's edge. */+const ROW_TRIGGER: SystemStyleObject = { h: 'auto', justifyContent: 'start', px: '2', py: '1.5' };+/**+ * Trimmed to the capitals' height and baseline, the initials' box is their ink, so the circle's flex centring centres+ * the letters themselves; untrimmed, the font's descender room sits below them and lifts them off centre. Browsers+ * without `text-box` keep that small lift.+ */+const INITIALS: SystemStyleObject = { textBox: 'trim-both cap alphabetic' };++/** 28px: the rail's 32px items with a 2px inset, in both widths. */+/** Decorative: the name beside it, or the icon-only button's label, names the account. */+const AccountAvatar = ({ label }: { label: string }) => (+ <Avatar.Root aria-hidden bg="accent.subtle" boxSize="7" color="fg" flexShrink={0}>+ <Avatar.Fallback css={INITIALS} fontSize="sm" fontWeight="600" name={label} />+ </Avatar.Root>+);++/** An email keeps its domain when it truncates, as the menu header shows it; names and roles truncate at the end. */+const AccountLine = ({ isEmail, text, ...props }: Omit<MiddleTruncateProps, 'tailGraphemes'> & { isEmail: boolean }) =>+ isEmail ? (+ <MiddleTruncate {...props} text={text} />+ ) : (+ <Text {...props} truncate>+ {text}+ </Text>+ );++/** True in multi-user mode with someone signed in: when {@link AccountMenu} renders anything. */+export const useHasAccountMenu = (): boolean => {+ const session = useAuthSession();++ return session.multiuserEnabled && session.user !== null;+};-/** Show account actions only for multi-user sessions; each host places its separate settings control. */-export const AccountMenu = () => {+/**+ * The signed-in account and its actions, for the foot of a navigation rail; nothing in single-user mode. `compact` is+ * the icon-only rail: the trigger shows the avatar, named by a tooltip.+ */+export const AccountMenu = ({ compact = false }: { compact?: boolean }) => {const { t } = useTranslation();const session = useAuthSession();const navigate = useNavigate();+ const ids = useTooltipTriggerIds();const [isProfileOpen, setIsProfileOpen] = useState(false);const openUserManagement = useCallback(() => {@@ -38,48 +80,51 @@ export const AccountMenu = () => {const user = session.user;const label = user.display_name?.trim() || user.email;+ // The email when the name is a display name; an email-only account shows its role instead of repeating itself.+ const detail = label === user.email ? (user.is_admin ? t('users.admin') : t('users.user')) : user.email;+ const triggerLabel = t('auth.accountMenu', { name: label });return (<>- <Menu.Root positioning={MENU_POSITIONING}>- <Menu.Trigger asChild>- <chakra.button- ref={triggerRef}- alignItems="center"- color="fg"- display="flex"- flexShrink={0}- gap="1.5"- px="1.5"- py="1"- rounded="md"- type="button"- _hover={TRIGGER_HOVER}- >- <Avatar.Root bg="accent.subtle" color="fg" size="sm">- <Avatar.Fallback fontSize="xs" name={label} />- </Avatar.Root>- <Text fontSize="md" fontWeight="600">- {label}- </Text>- <Icon as={ChevronDownIcon} boxSize="3" color="fg.muted" />- </chakra.button>- </Menu.Trigger>+ <Menu.Root ids={ids} positioning={MENU_POSITIONING}>+ {compact ? (+ <Tooltip content={label} ids={ids} placement="right">+ <Menu.Trigger asChild>+ <IconButton ref={triggerRef} aria-label={triggerLabel} size="lg" variant="ghost">+ <AccountAvatar label={label} />+ </IconButton>+ </Menu.Trigger>+ </Tooltip>+ ) : (+ <Menu.Trigger asChild>+ {/* Named by its visible lines, so the spoken name matches what is shown. */}+ <Button ref={triggerRef} css={ROW_TRIGGER} gap="2.5" variant="ghost" w="full">+ <AccountAvatar label={label} />+ <Stack flex="1" gap="0" minW="0" textAlign="start">+ <AccountLine fontSize="md" fontWeight="600" isEmail={label === user.email} text={label} />+ <AccountLine+ color="fg.muted"+ fontSize="xs"+ fontWeight="400"+ isEmail={detail === user.email}+ text={detail}+ />+ </Stack>+ <Icon as={ChevronRightIcon} boxSize="3" color="fg.muted" flexShrink={0} />+ </Button>+ </Menu.Trigger>+ )}<Portal><Menu.Positioner>- <MenuContent minW="56">+ <MenuContent maxW="20rem" minW="56"><Box px="3" py="2">- <HStack justify="space-between">- <Stack gap="0">- <Text fontSize="md" fontWeight="600">- {label}- </Text>- <Text color="fg.muted" fontSize="xs">- {user.email}- </Text>+ <HStack gap="2" justify="space-between">+ <Stack gap="0" minW="0">+ <MiddleTruncate fontSize="md" fontWeight="600" text={label} />+ <MiddleTruncate color="fg.muted" fontSize="xs" text={user.email} /></Stack>{user.is_admin ? (- <Badge colorPalette="purple" fontSize="xs" variant="surface">+ <Badge colorPalette="purple" flexShrink={0} fontSize="xs" variant="surface">{t('users.admin')}</Badge>) : null}@@ -88,18 +133,18 @@ export const AccountMenu = () => {<Menu.Separator /><Menu.Item value="account" onClick={openProfile}><Icon as={UserRoundCogIcon} boxSize="3.5" />- {t('auth.accountSettings')}+ <Menu.ItemText>{t('auth.accountSettings')}</Menu.ItemText></Menu.Item>{user.is_admin ? (<Menu.Item value="users" onClick={openUserManagement}><Icon as={UsersIcon} boxSize="3.5" />- {t('users.manageUsers')}+ <Menu.ItemText>{t('users.manageUsers')}</Menu.ItemText></Menu.Item>) : null}<Menu.Separator /><Menu.Item value="sign-out" onClick={signOut}><Icon as={LogOutIcon} boxSize="3.5" />- {t('auth.signOut')}+ <Menu.ItemText>{t('auth.signOut')}</Menu.ItemText></Menu.Item></MenuContent></Menu.Positioner>diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsxdeleted file mode 100644index 2393980565..0000000000--- a/invokeai/frontend/webv2/src/features/identity/ui/AccountMenuSection.tsx+++ /dev/null@@ -1,98 +0,0 @@-import { Avatar, Badge, Box, HStack, Icon, Menu, Stack } from '@chakra-ui/react';-import { logoutSession, useAuthSession } from '@features/identity/session';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { useNavigate } from '@tanstack/react-router';-import { LogOutIcon, UserRoundCogIcon, UsersIcon } from 'lucide-react';-import { useCallback } from 'react';-import { useTranslation } from 'react-i18next';--import { ProfileDialog } from './ProfileDialog';--/**- * Embed account actions directly in host menus to avoid nested popovers; render nothing in single-user mode. The host- * renders {@link AccountProfileDialog} outside its menu: menu content unmounts on close, and would take the dialog along.- */-export const AccountMenuSection = ({ onOpenProfile }: { onOpenProfile: () => void }) => {- const { t } = useTranslation();- const session = useAuthSession();- const navigate = useNavigate();-- const openUserManagement = useCallback(() => {- void navigate({ to: '/users' });- }, [navigate]);-- const signOut = useCallback(() => {- void logoutSession();- }, []);-- if (!session.multiuserEnabled || session.user === null) {- return null;- }-- const user = session.user;- const label = user.display_name?.trim() || user.email;-- return (- <>- <Box px="3" py="2">- <HStack justify="space-between">- <HStack gap="2" minW="0">- <Avatar.Root bg="accent.subtle" color="fg" size="sm">- <Avatar.Fallback fontSize="xs" name={label} />- </Avatar.Root>- <Stack gap="0" minW="0">- <MiddleTruncate fontSize="md" fontWeight="600" text={label} />- <MiddleTruncate color="fg.muted" fontSize="xs" text={user.email} />- </Stack>- </HStack>- {user.is_admin ? (- <Badge colorPalette="purple" fontSize="xs" variant="surface">- {t('users.admin')}- </Badge>- ) : null}- </HStack>- </Box>- <Menu.Item value="account" onClick={onOpenProfile}>- <Icon as={UserRoundCogIcon} boxSize="3.5" />- <Menu.ItemText>{t('auth.accountSettings')}</Menu.ItemText>- </Menu.Item>- {user.is_admin ? (- <Menu.Item value="users" onClick={openUserManagement}>- <Icon as={UsersIcon} boxSize="3.5" />- <Menu.ItemText>{t('users.manageUsers')}</Menu.ItemText>- </Menu.Item>- ) : null}- <Menu.Item value="sign-out" onClick={signOut}>- <Icon as={LogOutIcon} boxSize="3.5" />- <Menu.ItemText>{t('auth.signOut')}</Menu.ItemText>- </Menu.Item>- </>- );-};--/** Account settings for the signed-in user, opened from {@link AccountMenuSection}; nothing once signed out. */-export const AccountProfileDialog = ({- finalFocusEl,- isOpen,- onClose,-}: {- /** The menu's trigger: the item that opened the dialog is gone once the menu closes. */- finalFocusEl: () => HTMLElement | null;- isOpen: boolean;- onClose: () => void;-}) => {- const session = useAuthSession();-- if (!session.multiuserEnabled || session.user === null) {- return null;- }-- return <ProfileDialog finalFocusEl={finalFocusEl} isOpen={isOpen} user={session.user} onClose={onClose} />;-};--/** True when {@link AccountMenuSection} has anything to render. */-export const useHasAccountSection = (): boolean => {- const session = useAuthSession();-- return session.multiuserEnabled && session.user !== null;-};diff --git a/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsx b/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsxindex effa27eea4..b8df07db11 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/AuthScreen.tsx@@ -15,8 +15,9 @@ export const AuthScreen = ({subtitle: string;title: string;}) => (- <Flex align="center" bg="bg" color="fg" justify="center" minH="100dvh" p="6">- <Stack gap="6" maxW="sm" w="full">+ // The dot grid colors its dots through `color`, so the content restores the foreground color.+ <Flex align="center" justify="center" layerStyle="dotGrid" minH="100dvh" p="6">+ <Stack color="fg" gap="6" maxW="sm" w="full"><Stack align="center" gap="4"><InvokeMark /><Stack align="center" gap="1">diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsxindex 6948397d93..0c4b12519e 100644--- a/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx+++ b/invokeai/frontend/webv2/src/features/identity/ui/UserManagement.tsx@@ -1,9 +1,9 @@-import { Avatar, Badge, Box, Center, Flex, HStack, Spinner, Stack, Switch, Table, Text } from '@chakra-ui/react';+import { Avatar, Badge, Box, Center, HStack, Spinner, Stack, Switch, Table, Text } from '@chakra-ui/react';import { deleteUser, listUsers, updateUser, type UserDTO } from '@features/identity/data/api';import { useAuthSession } from '@features/identity/session';import { useIdentityNotify } from '@features/identity/ui/useIdentityNotify';import { getApiErrorMessage } from '@platform/transport/http';-import { Button, IconButton, ConfirmDialog, Scrollable, Tooltip } from '@platform/ui';+import { Button, IconButton, ConfirmDialog, Tooltip } from '@platform/ui';import { BrushCleaningIcon, PencilIcon, Trash2Icon, UserPlusIcon } from 'lucide-react';import { useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -14,18 +14,10 @@ const ROW_HOVER_STYLES = { bg: 'bg.muted' };const SWITCH_CHECKED_STYLES = { bg: 'accent.solid' };const DELETE_BUTTON_HOVER_STYLES = { color: 'fg.error' };-/** Guard admin access inline as well as in the widget manifest to cover stale persisted layouts. */-export const UserManagement = () => {- const { t } = useTranslation();-- return (- <Scrollable flex="1" h="full" label={t('users.management')}>- <UsersManagementPanel />- </Scrollable>- );-};--/** `onManageIntermediates` is supplied by the shell that owns the intermediates manager's home. */+/**+ * The account directory, under a page header that names it. Admin access is checked here as well as by the host.+ * `onManageIntermediates` is supplied by the shell that owns the intermediates manager's home.+ */export const UsersManagementPanel = ({onManageIntermediates,}: {@@ -112,75 +104,68 @@ const UsersDirectory = ({return (<>- <Flex justify="center" px="4" py="6" w="full">- <Stack gap="4" w="full">- <HStack align="flex-start" justify="space-between">- <Stack gap="0.5">- <Text fontSize="xl" fontWeight="700">- {t('users.title')}- </Text>- <Text color="fg.muted" fontSize="md">- {users ? t('users.accountCount', { count: users.length }) : t('users.description')}- </Text>- </Stack>- <Button variant="solid" onClick={openCreateForm}>- <UserPlusIcon />- {t('users.addUser')}- </Button>- </HStack>- <Box bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" overflowX="auto" rounded="lg">- {users === null ? (- <Center minH="40">- {loadError ? (- <Stack align="center" gap="2" p="4">- <Text color="fg.error" fontSize="md" textAlign="center">- {loadError}- </Text>- <Button variant="outline" onClick={retryLoad}>- {t('common.retry')}- </Button>- </Stack>- ) : (- <Spinner color="fg.muted" size="lg" />- )}- </Center>- ) : (- <Table.Root minW="42rem">- <Table.Header>- <Table.Row bg="bg.muted">- <Table.ColumnHeader borderColor="border.subtle" color="fg.muted" ps="4">- {t('users.user')}- </Table.ColumnHeader>- <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">- {t('users.role')}- </Table.ColumnHeader>- <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">- {t('users.lastSignIn')}- </Table.ColumnHeader>- <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">- {t('common.active')}- </Table.ColumnHeader>- <Table.ColumnHeader borderColor="border.subtle" pe="4" />- </Table.Row>- </Table.Header>- <Table.Body>- {users.map((user) => (- <UserRow- onManageIntermediates={onManageIntermediates}- key={user.user_id}- isSelf={user.user_id === currentUserId}- setDeleteTarget={setDeleteTarget}- setFormTarget={setFormTarget}- setUserActive={setUserActive}- user={user}- />- ))}- </Table.Body>- </Table.Root>- )}- </Box>- </Stack>- </Flex>+ <Stack gap="3" w="full">+ <HStack justify="space-between">+ <Text color="fg.muted" fontSize="md">+ {users ? t('users.accountCount', { count: users.length }) : null}+ </Text>+ <Button variant="solid" onClick={openCreateForm}>+ <UserPlusIcon />+ {t('users.addUser')}+ </Button>+ </HStack>+ <Box bg="bg.subtle" borderColor="border.subtle" borderWidth="1px" overflowX="auto" rounded="lg">+ {users === null ? (+ <Center minH="40">+ {loadError ? (+ <Stack align="center" gap="2" p="4">+ <Text color="fg.error" fontSize="md" textAlign="center">+ {loadError}+ </Text>+ <Button variant="outline" onClick={retryLoad}>+ {t('common.retry')}+ </Button>+ </Stack>+ ) : (+ <Spinner color="fg.muted" size="lg" />+ )}+ </Center>+ ) : (+ <Table.Root minW="42rem">+ <Table.Header>+ <Table.Row bg="bg.muted">+ <Table.ColumnHeader borderColor="border.subtle" color="fg.muted" ps="4">+ {t('users.user')}+ </Table.ColumnHeader>+ <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">+ {t('users.role')}+ </Table.ColumnHeader>+ <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">+ {t('users.lastSignIn')}+ </Table.ColumnHeader>+ <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">+ {t('common.active')}+ </Table.ColumnHeader>+ <Table.ColumnHeader borderColor="border.subtle" pe="4" />+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {users.map((user) => (+ <UserRow+ onManageIntermediates={onManageIntermediates}+ key={user.user_id}+ isSelf={user.user_id === currentUserId}+ setDeleteTarget={setDeleteTarget}+ setFormTarget={setFormTarget}+ setUserActive={setUserActive}+ user={user}+ />+ ))}+ </Table.Body>+ </Table.Root>+ )}+ </Box>+ </Stack><UserFormDialog target={formTarget} onClose={closeForm} onSaved={refreshAfterSave} /><ConfirmDialogbody={t('users.deleteBody', { name: deleteTarget ? getUserLabel(deleteTarget) : t('users.thisUser') })}diff --git a/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.browser.test.tsx b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.browser.test.tsxnew file mode 100644index 0000000000..8526e69629--- /dev/null+++ b/invokeai/frontend/webv2/src/features/identity/ui/UsersPage.browser.test.tsx@@ -0,0 +1,112 @@+import type * as ApiModule from '@features/identity/data/api';+import type * as SessionModule from '@features/identity/session';++import { ChakraProvider } from '@chakra-ui/react';+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 { page } from 'vitest/browser';++const admin = vi.hoisted(() => ({+ created_at: '2026-01-01T00:00:00Z',+ display_name: 'Ada',+ email: '[email protected]',+ is_active: true,+ is_admin: true,+ last_login_at: null,+ updated_at: '2026-01-01T00:00:00Z',+ user_id: 'ada',+}));++vi.mock('@features/identity/session', async (importOriginal) => {+ const original = await importOriginal<typeof SessionModule>();+ const session: SessionModule.AuthSession = {+ accountEpoch: 1,+ expiredUserId: null,+ multiuserEnabled: true,+ phase: 'ready',+ sessionExpired: false,+ setupRequired: false,+ strictPasswordChecking: false,+ switchingAccount: false,+ user: admin,+ };++ return { ...original, useAuthSession: () => session };+});+/** Each test answers the directory's loads in turn. */+const directory = vi.hoisted(() => ({ loads: [] as (() => Promise<unknown>)[] }));+vi.mock('@features/identity/data/api', async (importOriginal) => ({+ ...(await importOriginal<typeof ApiModule>()),+ listUsers: () => (directory.loads.shift() ?? (() => Promise.resolve([admin])))(),+}));+// A stable `t`, as react-i18next's is: the directory reloads whenever it changes.+const translation = vi.hoisted(() => ({+ t: (key: string, values?: { count?: number }) => (values?.count === undefined ? key : `${key}:${values.count}`),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => translation }));++import { UsersPage } from './UsersPage';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ directory.loads = [];+ await act(() => root.unmount());+ host.remove();+});++const renderPage = () =>+ act(() =>+ root.render(+ <ChakraProvider value={system}>+ <UsersPage />+ </ChakraProvider>+ )+ );++describe('UsersPage', () => {+ it('names the page once, with the account count above the directory', async () => {+ await renderPage();++ await expect.element(page.getByText('users.accountCount:1')).toBeVisible();+ expect([...host.querySelectorAll('h1, h2, h3, h4, h5, h6')].map((heading) => heading.textContent)).toEqual([+ 'users.title',+ ]);+ expect(host.textContent?.match(/users\.title/g)).toHaveLength(1);+ await expect.element(page.getByText('users.description')).toBeVisible();+ await expect.element(page.getByRole('button', { name: 'users.addUser' })).toBeVisible();+ });++ it('describes the page once while the directory loads, with no count yet', async () => {+ directory.loads.push(() => new Promise(() => {}));+ await renderPage();++ await expect.element(page.getByRole('button', { name: 'users.addUser' })).toBeVisible();+ expect(host.textContent?.match(/users\.description/g)).toHaveLength(1);+ expect(host.textContent).not.toContain('users.accountCount');+ expect(host.querySelector('table')).toBeNull();+ });++ it('offers a retry when the directory fails to load, then shows the count', async () => {+ directory.loads.push(() => Promise.reject(new Error('Backend offline')));+ await renderPage();++ await expect.element(page.getByText('Backend offline')).toBeVisible();+ expect(host.textContent).not.toContain('users.accountCount');+ await page.getByRole('button', { name: 'common.retry' }).click();++ await expect.element(page.getByText('users.accountCount:1')).toBeVisible();+ expect(host.textContent).not.toContain('Backend offline');+ });+});diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsxindex 264d5c554e..f82667eabe 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/AddModelsView.browser.test.tsx@@ -682,7 +682,7 @@ describe('AddModelsView bundle preview decoder', () => {return item!;});await act(() =>- userEvent.click(document.querySelector<HTMLElement>('[aria-label="models.filterAndSortStarterModels"]')!)+ userEvent.click(document.querySelector<HTMLElement>('[aria-label^="models.filterAndSortStarterModels"]')!));await act(async () => userEvent.click(await menuItem(submenu)));await act(async () => userEvent.click(await menuItem(item)));diff --git a/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsxindex 6badb709b7..15c486bed4 100644--- a/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/add-models/StarterFilterMenu.tsx@@ -14,8 +14,8 @@ const STARTER_SORT_FIELDS: readonly ModelFilterSortOption<StarterSortField>[] ={ field: 'format', labelKey: 'models.sort.format' },];-const isFiltering = (filters: StarterModelFilters): boolean =>- filters.typeFilter !== null || filters.baseFilter !== null;+const countActiveFilters = (filters: StarterModelFilters): number =>+ Number(filters.typeFilter !== null) + Number(filters.baseFilter !== null);export const StarterFilterMenu = ({availableBases,@@ -32,16 +32,17 @@ export const StarterFilterMenu = ({return (<ModelFilterMenu+ activeFilterCount={countActiveFilters(filters)}ariaLabel={t('models.filterAndSortStarterModels')}availableBases={availableBases}availableTypes={availableTypes}baseFilter={filters.baseFilter}- isActive={isFiltering(filters)}sortDirection={filters.sortDirection}sortField={filters.sortField}sortFields={STARTER_SORT_FIELDS}typeFilter={filters.typeFilter}onBaseFilterChange={(baseFilter) => onChange({ ...filters, baseFilter })}+ onResetFilters={() => onChange({ ...filters, baseFilter: null, typeFilter: null })}onSortChange={(sortField, sortDirection) => onChange({ ...filters, sortDirection, sortField })}onTypeFilterChange={(typeFilter) => onChange({ ...filters, typeFilter })}/>diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsxindex 20fef86838..89d832e3c9 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.browser.test.tsx@@ -7,6 +7,7 @@ import { ModelsUiProvider, NO_SCHEDULER_POLICY } from '@features/models/ui/Modelimport { getModelsUiSnapshotForTests } from '@features/models/ui/uiStore';import { auditAccessibility, contrastOffenderTexts } from '@platform/browser/auditAccessibility.testing';import { Field } from '@platform/ui/Field';+import { ScrubberField } from '@platform/ui/ScrubberField';import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -488,6 +489,97 @@ describe('ModelSelect loading states', () => {await expect.poll(() => document.activeElement).toBe(trigger());expect(onChange).toHaveBeenCalledOnce();});++ describe('with the label inside', () => {+ const renderInside = (field: { error?: string; helpText?: string }, onChange = vi.fn()) =>+ act(() => {+ root.render(+ <ChakraProvider value={system}>+ <ModelsUiProvider adapter={MODELS_UI_ADAPTER}>+ <Field label="VAE" labelPlacement="inside" {...field}>+ <ModelSelect+ isClearable+ modelTypes={MAIN_MODEL_TYPES}+ showManagerButton={false}+ value="sdxl-main"+ onChange={onChange}+ />+ </Field>+ </ModelsUiProvider>+ </ChakraProvider>+ );+ });+ const insideLabel = () => trigger().querySelector<HTMLElement>('span[id]')!;++ it('shows the label in the trigger, before the end-aligned model, and keeps its name and description', async () => {+ setModelsSnapshotForTests({ error: null, models: [model], status: 'loaded' });+ await renderInside({ helpText: 'Using the bundled VAE' });++ // A span, not a <label>, because it sits inside the trigger button.+ expect(host.querySelector('label')).toBeNull();+ expect(insideLabel().textContent).toBe('VAE');+ const value = insideLabel().nextElementSibling!;+ expect(value.textContent).toBe('SDXL MainSDXL');+ expect(insideLabel().getBoundingClientRect().right).toBeLessThanOrEqual(value.getBoundingClientRect().left);+ expect(getComputedStyle(value).justifyContent).toBe('flex-end');+ await expect+ .element(page.getByRole('button', { exact: true, name: 'VAE SDXL Main SDXL' }))+ .toHaveAccessibleDescription('Using the bundled VAE');+ });++ it('opens from a click on the label and still clears from its clear button', async () => {+ const onChange = vi.fn();+ setModelsSnapshotForTests({ error: null, models: [model, secondSdxlModel], status: 'loaded' });+ await renderInside({}, onChange);++ await userEvent.click(insideLabel());+ await expect.poll(() => document.querySelector('input[role="combobox"]')).not.toBeNull();+ await userEvent.keyboard('{Escape}');+ await expect.poll(() => document.querySelector('input[role="combobox"]')).toBeNull();++ await userEvent.click(page.getByRole('button', { exact: true, name: 'models.clearSelectedModel' }));+ expect(onChange).toHaveBeenLastCalledWith(null);+ });++ it('lines its label up with a stacked ScrubberField and shows the model at regular weight', async () => {+ setModelsSnapshotForTests({ error: null, models: [model], status: 'loaded' });+ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <ModelsUiProvider adapter={MODELS_UI_ADAPTER}>+ <ScrubberField label="Steps" max={100} min={1} step={1} value={30} onChange={vi.fn()} />+ <Field label="VAE" labelPlacement="inside">+ <ModelSelect+ modelTypes={MAIN_MODEL_TYPES}+ showManagerButton={false}+ value="sdxl-main"+ onChange={vi.fn()}+ />+ </Field>+ </ModelsUiProvider>+ </ChakraProvider>+ );+ });+ const textLeft = (element: Element) => {+ const range = document.createRange();+ range.selectNodeContents(element);+ return range.getBoundingClientRect().left;+ };+ const scrubberLabel = host.querySelector<HTMLElement>('[data-part="label"]')!;++ expect(textLeft(insideLabel())).toBeCloseTo(textLeft(scrubberLabel), 0);+ expect(getComputedStyle(insideLabel()).fontWeight).toBe(getComputedStyle(scrubberLabel).fontWeight);+ expect(getComputedStyle(insideLabel().nextElementSibling!).fontWeight).toBe('400');+ });++ it('marks the trigger invalid and describes it with the field error', async () => {+ setModelsSnapshotForTests({ error: null, models: [model], status: 'loaded' });+ await renderInside({ error: 'Pick a compatible VAE' });++ expect(trigger().getAttribute('aria-invalid')).toBe('true');+ await expect.poll(describedText).toBe('Pick a compatible VAE');+ });+ });});});diff --git a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsxindex ce217ff008..d0a4716fd3 100644--- a/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/components/ModelSelect.tsx@@ -28,7 +28,7 @@ import { formatBytes } from '@platform/i18n/languages';import { useMountEffect } from '@platform/react/useMountEffect';import { areArraysEqual } from '@platform/state/selectors';import { Button, CloseButton, IconButton, PopoverContent, Tooltip } from '@platform/ui';-import { useFieldLabelId } from '@platform/ui/Field';+import { FieldInsideLabel, INSIDE_LABEL_INSET, useFieldLabelId, useInsideFieldLabel } from '@platform/ui/Field';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { Picker } from '@platform/ui/Picker';import { Link } from '@tanstack/react-router';@@ -146,7 +146,8 @@ export const ModelSelect = ({// Like Select, an enclosing Field names the trigger and supplies its description, invalid and disabled states.const field = useFieldContext();const fieldControlProps = field?.getInputProps();- const fieldLabelId = useFieldLabelId();+ const insideLabel = useInsideFieldLabel();+ const fieldLabelId = useFieldLabelId() ?? insideLabel?.id ?? null;const valueTextId = useId();const isDisabled = Boolean(disabled || field?.disabled);const isInvalid = Boolean(invalid || field?.invalid);@@ -304,11 +305,15 @@ export const ModelSelect = ({className={className}borderColor={isInvalid ? undefined : isOpen ? 'accent.solid' : 'border'}colorPalette={isInvalid ? 'red' : 'gray'}+ // Opening it puts the caret in a search box, so it points like a combobox's input does.+ cursor={isInert ? undefined : 'text'}disabled={isInert}+ // Under an inside label the value reads at Select's and Combobox's regular weight; the label sets its own.+ fontWeight={insideLabel ? 'normal' : undefined}justifyContent="space-between"minW="0"pe={canClear ? '7' : '2'}- ps="2"+ ps={insideLabel ? INSIDE_LABEL_INSET : '2'}size={size}transitionDuration="fast"transitionProperty="border-color, background"@@ -319,10 +324,19 @@ export const ModelSelect = ({borderColor: isInvalid ? undefined : isOpen ? 'accent.solid' : 'border.emphasized',}}>+ {insideLabel ? <FieldInsideLabel label={insideLabel} /> : null}{selectedModel ? (- <ModelButtonContent id={valueTextId} model={selectedModel} />+ <ModelButtonContent id={valueTextId} isEndAligned={Boolean(insideLabel)} model={selectedModel} />) : (- <Text as="span" id={valueTextId} color="fg.muted" minW="0" truncate>+ <Text+ as="span"+ id={valueTextId}+ color="fg.muted"+ flex={insideLabel ? '1' : undefined}+ minW="0"+ textAlign={insideLabel ? 'end' : undefined}+ truncate+ >{isEmpty ? emptyMessage : (placeholder ?? t('models.scopeSelect', { scope: scopeLabel }))}</Text>)}@@ -532,8 +546,8 @@ const BaseChip = ({</Badge>);-const ModelButtonContent = ({ id, model }: { id: string; model: ModelConfig }) => (- <HStack as="span" id={id} flex="1" gap="2" minW="0">+const ModelButtonContent = ({ id, isEndAligned, model }: { id: string; isEndAligned: boolean; model: ModelConfig }) => (+ <HStack as="span" id={id} flex="1" gap="2" justify={isEndAligned ? 'flex-end' : undefined} minW="0"><MiddleTruncate as="span" minW="0" text={model.name} /><Badge colorPalette={getModelBaseColorPalette(model.base)} flexShrink={0} fontSize="xs" size="lg" variant="surface">{getModelBaseLabel(model.base)}diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsxindex be7c367161..bb0a7b53ff 100644--- a/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelFilterBar.tsx@@ -8,8 +8,9 @@ import { ManagerSearchField } from '@platform/ui/ManagerLayout';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-const isFiltering = (filters: ModelLibraryFilters): boolean =>- filters.typeFilter !== null || filters.baseFilter !== null || filters.missingOnly;+// Missing files is a pseudo-type (choosing it clears the type), so it counts as the type filter.+const countActiveFilters = (filters: ModelLibraryFilters): number =>+ Number(filters.typeFilter !== null || filters.missingOnly) + Number(filters.baseFilter !== null);/** Offer taxonomy filters only for values present in the library. */export const ModelFilterBar = ({@@ -38,6 +39,10 @@ export const ModelFilterBar = ({(baseFilter: string | null) => onChange({ ...filters, baseFilter }),[filters, onChange]);+ const handleResetFilters = useCallback(+ () => onChange({ ...filters, baseFilter: null, missingOnly: false, typeFilter: null }),+ [filters, onChange]+ );const handleSortChange = useCallback((sortField: ModelSortField, sortDirection: 'asc' | 'desc') => onChange({ ...filters, sortDirection, sortField }),[filters, onChange]@@ -67,12 +72,12 @@ export const ModelFilterBar = ({onChange={handleSearchChange}/><ModelFilterMenu+ activeFilterCount={countActiveFilters(filters)}ariaLabel={t('models.filterAndSort')}availableBases={availableBases}availableTypes={availableTypes}baseFilter={filters.baseFilter}extraTypeItems={extraTypeItems}- isActive={isFiltering(filters)}sortDirection={filters.sortDirection}sortField={filters.sortField}sortFields={SORT_FIELD_OPTIONS}@@ -80,6 +85,7 @@ export const ModelFilterBar = ({typeFilter={filters.typeFilter}typeSummary={filters.missingOnly ? t('models.missingFilesCount', { count: missingCount }) : undefined}onBaseFilterChange={handleBaseFilterChange}+ onResetFilters={handleResetFilters}onSortChange={handleSortChange}onTypeFilterChange={handleTypeFilterChange}/>diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsxindex d75b050071..a8b5c01bcf 100644--- a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx@@ -7,15 +7,9 @@ import type { ReactNode } from 'react';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { getModelBaseLabel } from '@features/models/core/baseIdentity';import { getModelTypeLabel } from '@features/models/core/taxonomy';-import { IconButton, MenuContent, Scrollable } from '@platform/ui';-import {- ArrowUpDownIcon,- CheckIcon,- ChevronRightIcon,- LayersIcon,- ShapesIcon,- SlidersHorizontalIcon,-} from 'lucide-react';+import { MenuContent, Scrollable } from '@platform/ui';+import { ManagerFilterMenu, ManagerFilterResetItem } from '@platform/ui/ManagerLayout';+import { ArrowUpDownIcon, CheckIcon, ChevronRightIcon, LayersIcon, ShapesIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -40,13 +34,14 @@ export const SORT_FIELD_OPTIONS: readonly ModelFilterSortOption[] = [/** Narrow sort callbacks to the supplied sort-field subset. */export const ModelFilterMenu = <Field extends ModelSortField>({+ activeFilterCount,ariaLabel,availableBases,availableTypes,baseFilter,extraTypeItems,- isActive,onBaseFilterChange,+ onResetFilters,onSortChange,onTypeFilterChange,sortDirection,@@ -56,13 +51,16 @@ export const ModelFilterMenu = <Field extends ModelSortField>({typeFilter,typeSummary,}: {+ /** Type and base filters in effect; sort order is not counted. */+ activeFilterCount: number;ariaLabel: string;availableBases: string[];availableTypes: ModelTaxonomyType[];baseFilter: string | null;extraTypeItems?: ReactNode;- isActive: boolean;onBaseFilterChange: (base: string | null) => void;+ /** Clears the counted filters; sort order stays. */+ onResetFilters: () => void;onSortChange: (field: Field, direction: 'asc' | 'desc') => void;onTypeFilterChange: (type: ModelTaxonomyType | null) => void;sortDirection: 'asc' | 'desc';@@ -88,12 +86,12 @@ export const ModelFilterMenu = <Field extends ModelSortField>({: undefined;return (- <Menu.Root closeOnSelect={false} positioning={ROOT_POSITIONING}>- <Menu.Trigger asChild>- <IconButton aria-label={ariaLabel} color={isActive ? 'accent.solid' : 'fg.muted'} variant="outline">- <Icon as={SlidersHorizontalIcon} boxSize="4" />- </IconButton>- </Menu.Trigger>+ <ManagerFilterMenu+ activeCount={activeFilterCount}+ closeOnSelect={false}+ label={ariaLabel}+ positioning={ROOT_POSITIONING}+ ><Portal><Menu.Positioner><MenuContent minW="15rem" py="1">@@ -146,10 +144,11 @@ export const ModelFilterMenu = <Field extends ModelSortField>({/>))}</FilterSubMenu>+ <ManagerFilterResetItem activeCount={activeFilterCount} onReset={onResetFilters} /></MenuContent></Menu.Positioner></Portal>- </Menu.Root>+ </ManagerFilterMenu>);};@@ -208,7 +207,7 @@ export const FilterMenuItem = memo(function FilterMenuItem({}: FilterMenuItemProps) {return (<Menu.Item aria-checked={isChecked} closeOnSelect={false} role="menuitemcheckbox" value={value} onClick={onSelect}>- <Icon as={CheckIcon} boxSize="3" opacity={isChecked ? 1 : 0} />+ <Icon as={CheckIcon} boxSize="3" color="fg" opacity={isChecked ? 1 : 0} /><Menu.ItemText fontSize="md">{label}</Menu.ItemText>{trailing ? (<Text color="fg.subtle" fontSize="xs" ms="auto">diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackFilterMenu.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackFilterMenu.tsxindex e853ff5f97..af54b476a7 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackFilterMenu.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/library/NodePackFilterMenu.tsx@@ -1,9 +1,10 @@+import type { NodePackFilters, NodePackSortField } from '@features/nodes/core/library';+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import { Icon, Menu, Portal, Text } from '@chakra-ui/react';-import { DEFAULT_NODE_PACK_FILTERS, type NodePackFilters, type NodePackSortField } from '@features/nodes/core/library';-import { IconButton } from '@platform/ui/Button';+import { ManagerFilterMenu, ManagerFilterResetItem } from '@platform/ui/ManagerLayout';import { MenuContent } from '@platform/ui/Menu';-import { CheckIcon, SlidersHorizontalIcon } from 'lucide-react';+import { CheckIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';const SORT_FIELDS: readonly { field: NodePackSortField; labelKey: string }[] = [@@ -21,10 +22,6 @@ export const NodePackFilterMenu = ({onChange: (next: NodePackFilters) => void;}) => {const { t } = useTranslation();- const isActive =- filters.problemsOnly ||- filters.sortField !== DEFAULT_NODE_PACK_FILTERS.sortField ||- filters.sortDirection !== DEFAULT_NODE_PACK_FILTERS.sortDirection;// Reselecting the active field flips direction (models menu behavior).const reportSort = (field: NodePackSortField) => {@@ -36,16 +33,12 @@ export const NodePackFilterMenu = ({};return (- <Menu.Root closeOnSelect={false} positioning={{ placement: 'bottom-end' }}>- <Menu.Trigger asChild>- <IconButton- aria-label={t('nodes.filterAndSort')}- color={isActive ? 'accent.solid' : 'fg.muted'}- variant="outline"- >- <Icon as={SlidersHorizontalIcon} boxSize="4" />- </IconButton>- </Menu.Trigger>+ <ManagerFilterMenu+ activeCount={Number(filters.problemsOnly)}+ closeOnSelect={false}+ label={t('nodes.filterAndSort')}+ positioning={{ placement: 'bottom-end' }}+ ><Portal><Menu.Positioner><MenuContent minW="13rem">@@ -73,10 +66,14 @@ export const NodePackFilterMenu = ({/>))}</Menu.ItemGroup>+ <ManagerFilterResetItem+ activeCount={Number(filters.problemsOnly)}+ onReset={() => onChange({ ...filters, problemsOnly: false })}+ /></MenuContent></Menu.Positioner></Portal>- </Menu.Root>+ </ManagerFilterMenu>);};@@ -94,7 +91,7 @@ const FilterItem = ({value: string;}) => (<Menu.Item aria-checked={isChecked} closeOnSelect={false} role="menuitemcheckbox" value={value} onClick={onSelect}>- <Icon as={CheckIcon} boxSize="3" opacity={isChecked ? 1 : 0} />+ <Icon as={CheckIcon} boxSize="3" color="fg" opacity={isChecked ? 1 : 0} /><Menu.ItemText>{label}</Menu.ItemText>{trailing ? (<Text color="fg.subtle" fontSize="xs" ms="auto">diff --git a/invokeai/frontend/webv2/src/features/queue/README.md b/invokeai/frontend/webv2/src/features/queue/README.mdindex abafa1dfc9..ca3429f2fe 100644--- a/invokeai/frontend/webv2/src/features/queue/README.md+++ b/invokeai/frontend/webv2/src/features/queue/README.md@@ -4,7 +4,7 @@ Paths are relative to the webv2 `src/` directory.Queue's private `QueueBackendPort` is adapter seam; public callers use domain reads, commands, and production runtime factories from `@features/queue`. Private snake_case HTTP DTOs map explicitly to camelCase Queue read models before crossing that interface. TanStack Query owns global backend queue read model (reads and hydrates only a bounded recent window) and a status-only read for count summaries such as Home; non-React runtimes own reconciliation and realtime orchestration. Persisted per-project queue history stays in Workbench aggregate.-Queue exposes board-independent active backend sessions, including preparation and result settlement. Gallery progress section includes every unfinished batch slot, queued work too; Preview follows executing and settling sessions. Both use gallery-destination projections of active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions take no part in board counts, saved-image selection, or navigation. Saved outputs keep their actual backend board destinations; automatic result selection does not change browsed board or its paging window.+Queue exposes board-independent active backend sessions, including preparation and result settlement. Auto-switch is one policy in `core/activeSessions.ts`, used by Preview (`viewerAutoSwitch`) and Canvas staging (`autoSwitchMode`): `selectsLandedResult` (Newest and In progress select each landed result, Off only while none is selected), `getAutoSwitchFollowedLive` (only In progress shows generating slots: the pinned one while it runs, else the newest running one with a frame of its own, else the first settling one with a frame) and `pickAutoSwitch` (a user picking a finished result turns it Off; picking a generating slot turns it In progress and pins that slot). Staging adapts them in the Workbench (`reconcileCanvasStagingFollow`): it hears which slots have frames from this feature's first-frame signal, and cannot tell a slot waiting to start from one running, so a staging pin holds until its slot is gone where Preview's is released once its session stops running (or never holds on a waiting one). Gallery progress section includes every unfinished batch slot, queued work too; Preview follows executing and settling sessions, each only once it has shown a progress frame of its own (`activeProgressTargetStore` framed slots, marked by the coordinator on a slot's first frame). Until then the previous result stays on screen: a finished slot's last frame while its result routes, then the selected result, swapped in over that frame until it decodes (`progressImageStore` swap frames). Preview shows its run's progress message for a starting session instead of switching to an empty frame (model loads are not named: the server does not say which session they are for), and its status line announces the gap once; it shows the frameless session only when nothing is selected or the user pinned it. The coordinator reports the same first frame to the Workbench (`QueueHistoryCommands.noteFirstProgressFrame`), where Canvas staging follows it. Both use gallery-destination projections of active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions take no part in board counts, saved-image selection, or navigation. Saved outputs keep their actual backend board destinations; automatic result selection does not change browsed board or its paging window.Gallery owns coalesced socket-completion invalidation for the account across tabs; Queue retains its connection reconciliation refresh. Completion invalidation does not depend on whether this tab tracks the run.@@ -26,9 +26,15 @@ Both utility APIs reconcile accepted status every 15 seconds while active, coale`submitUtilityGraph` returns accepted ids and a `settled` promise. Aborting it stops watching and leaves accepted backend work alone. Aborting or explicitly timing out `runUtilityGraph` requests best-effort cancellation, including ids recovered after the caller stopped waiting; cancellation is never represented as confirmed. Account changes stop watches and fence late cancellation from a replacement account. Terminal paths detach listeners and stop periodic and retry timers. Rerun retry waits resolve on abort as before, remove their abort listener after ordinary completion, and clear their timer on abort.+## Live read model++The realtime runtime applies each `queue_item_status_changed` event to every loaded read model at once (`applyQueueItemStatusChange` in `data/queries.ts`) and still invalidates, coalesced, so the next read reconciles. Read models carry each item's `priority` and `statusSequence`; a change applies only when it is newer than the cached item (a higher sequence when both have one, otherwise never to an item already finished), so a late event never undoes a read, and once a read brings in a restarted server's lower sequences its events apply again. The current and next items follow the event: an item leaving progress hands `current` to another item still running, or clears it, and the next waiting item becomes the window's first pending item in run order (highest priority, then oldest) until the read names the server's, when the window can hold it (see Actions). Counts: an unscoped model, and the whole-queue status read, take an event's whole-queue counts, even when the model already shows the item so (after the viewer's own cancel); otherwise a change to an item the model knows, an event or this tab's own assumed cancel, moves it between the aggregate buckets. The server sends the full event, with own-item counts and current-item identifiers computed for the item's owner, to that owner and to every administrator, so the viewer's own counts wait for the read. Only cached data changes; account changes clear the cache with everything else.+## Actions-`ui/queueMenuActions.tsx` is the one queue action model: the top bar's button and menu, the widget header and its menu, and shortcuts (`requestQueueAction` in `@features/queue/reveal`, taken by the queue's always-mounted host once the read model has loaded) all call an action's `trigger`, never its runner. Its policy: cancelling the running item never asks, since Retry brings it back; cancelling all, cancelling all but the current item, and clearing failed, finished or all items always confirm, naming the scope and how many items they reach, with a way out that never reads "Cancel". Results report the same scope and counts. Pause and resume are one toggle that states what waits on the processor.+`ui/queueMenuActions.tsx` is the one queue action model: the top bar's button and menu, the widget header and its menu, and shortcuts (`requestQueueAction` in `@features/queue/reveal`, taken by the queue's always-mounted host once the read model has loaded) all call an action's `trigger`, never its runner. Its policy: cancelling the current item never asks, since Retry brings it back; cancelling all, cancelling all but the current item, and clearing failed, finished or all items always confirm, naming the scope and how many items they reach, with a way out that never reads "Cancel". Results report the same scope and counts. Pause and resume are one toggle that states what waits on the processor.++Cancel-current (the top bar's ×, <kbd>Shift</kbd>+<kbd>X</kbd>, the command palette) runs through one non-React function, `cancelCurrentQueueItem` (`ui/cancelCurrent.ts`). It stops the item in progress the viewer can manage (`getCancelCurrentTarget`), else, only in the gap between two items, the next one waiting in run order. The gap is the processor running (not paused) with nothing in progress anywhere in the queue: the hand-off between items, a cached reading that is behind, or a canceled item's worker still finishing; stopping the next item is then what stops the run from the viewer's side. While the processor is paused, or anything runs that it would not cancel, nothing waiting is stopped and the × is disabled. "Anywhere" is the whole queue whatever the view's scope: an unscoped read model's own counts, else the whole-queue status read (`useWholeQueueStatus`, the key the Launchpad's status band shares, read only while the view is scoped); unknown counts as something running. `processor.isProcessing` is not used: it stays true while a canceled item's worker finishes. The next item is the server's; the read window stands in for it only when it holds exactly the pending items the counts report, since the window is the newest items and the true next may be older (a long batch, a member's items among everyone's); otherwise, or when an item the window does not list starts waiting, it is unknown until the next read. The action's name says which it will stop ("Cancel current item" or "Cancel next item"). One runs at a time per account, and after it stops an item the command stays busy for a settle window (at least 400 ms, until the reconciling read lands, at most 2 s), so a double click, a double tap of the shortcut or a double activation in the palette stops one item, and a deliberate press after the window stops the next; the × also ignores a click's follow-up clicks (`detail > 1`) and a held Enter's auto-repeat, which clicks on every repeat (Space clicks on release), and the shortcut ignores a held key's auto-repeat (`ignoreRepeat`). It picks its target from the loaded read model when it runs, shows the item canceled there and in the whole-queue status at once, and puts both back if the request fails, only where nothing changed them since; when an event reported the item canceled meanwhile, the server did cancel it though its answer was lost, so nothing is put back and the cancel reports as requested. The server answers a cancel of an item that already finished with the item unchanged, which the read models take at once (its higher status sequence wins); the action then reads the queue afresh (its own read, started after the answer and bounded by the cancel's 10-second deadline, so a stalled read cannot hold the command busy; a read already in flight is neither joined nor cancelled, since others such as the palette's queue search may await it), within the same account, and stops what is current now, once, and says there is nothing to cancel when nothing is. When that read fails or times out, it says the item had already finished: nothing failed to cancel. It never reports a cancel that did nothing. Shift-click on the × is cancel-all, within the queue scope setting.Counts and scope follow what the action does for the viewer (`QueueUiAdapter.viewer`). A member's cancels count their own unfinished items; an administrator's count everyone's, since their cancel and clear reach every user. Across all projects the server counts every user's history, so a member's clears confirm without a count. Each scope (one project, all projects, all projects and users, all of a member's projects) has its own whole sentence in the catalog (`translateScoped`), never a fragment stitched into one. Cancel-all also cancels this tab's runs the backend has not accepted (`QueueUiAdapter.localRuns`), so it stays available offline while there are any. The widget lists those runs in its Submitting section above the current batch, under All and Active and within the queue scope setting, and counts them in those tabs (`useShownLocalRuns`). A run shows once its enqueue has failed, while the tab is offline, or once it has gone a second unaccepted, so an ordinary Invoke never flashes a row. Each says whether it is being sent, retried after a server error, waiting on a busy or unreachable server (with the attempt it is on), or held while the tab is offline, and cancels on its own without asking, as any single cancel does. Cancel-all counts every unaccepted run in scope, shown or not. The section's rows load with the first such run; if they cannot load, the section offers Retry and the rest of the widget keeps working.diff --git a/invokeai/frontend/webv2/src/features/queue/contracts.ts b/invokeai/frontend/webv2/src/features/queue/contracts.tsindex b5c810f795..b116543a0e 100644--- a/invokeai/frontend/webv2/src/features/queue/contracts.ts+++ b/invokeai/frontend/webv2/src/features/queue/contracts.ts@@ -58,7 +58,12 @@ export {isBackendSubmittableSourceId,shouldSubmitPendingQueueItem,} from './core/submissionRules';-export { extractGenerationMeta, getResultImageName, type QueueGenerationMeta } from './core/generationMeta';+export {+ extractGenerationMeta,+ extractNamedGenerationMeta,+ getResultImageName,+ type QueueGenerationMeta,+} from './core/generationMeta';export { getQueueItemSnapshotLabel } from './core/itemLabels';export { getQueueActivity, type QueueActivity } from './core/queueActivity';export {@@ -84,10 +89,15 @@ export {} from './data/events';export {- getFollowedProgressSession,+ getAutoSwitchFollowedLive,getQueueActiveSessions,getQueueProgressSessions,+ isAutoSwitchPinHeld,isGalleryProgressItem,+ pickAutoSwitch,+ selectsLandedResult,+ type AutoSwitchLiveSlot,+ type AutoSwitchMode,type QueueActiveSession,type QueueProgressSession,} from './core/activeSessions';diff --git a/invokeai/frontend/webv2/src/features/queue/core/activeSessions.test.ts b/invokeai/frontend/webv2/src/features/queue/core/activeSessions.test.tsindex 6528864f55..f79ee60f4e 100644--- a/invokeai/frontend/webv2/src/features/queue/core/activeSessions.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/activeSessions.test.ts@@ -3,10 +3,15 @@ import { describe, expect, it } from 'vitest';import type { QueueItem } from './historyTypes';import {- getFollowedProgressSession,+ getAutoSwitchFollowedLive,getQueueActiveSessions,getQueueProgressSessions,+ isAutoSwitchPinHeld,isGalleryProgressItem,+ pickAutoSwitch,+ selectsLandedResult,+ type AutoSwitchLiveSlot,+ type AutoSwitchMode,} from './activeSessions';const run = (id: string, backendItemIds: number[], destination: 'gallery' | 'canvas' = 'gallery'): QueueItem => ({@@ -32,34 +37,32 @@ describe('active queue sessions', () => {const items = [run('newer', [20]), run('batch', [10, 11, 12])];const targets = [target('newer', 1), target('batch', 2), target('batch', 1)];expect(- getQueueActiveSessions(items, targets, targets).map(({ id, backendItemId, state }) => ({- id,- backendItemId,- state,- }))+ getQueueActiveSessions(items, targets, targets, [target('batch', 2)]).map(+ ({ id, backendItemId, hasOwnFrame, state }) => ({ id, backendItemId, hasOwnFrame, state })+ )).toEqual([- { id: 'batch:1', backendItemId: 10, state: 'running' },- { id: 'batch:2', backendItemId: 11, state: 'running' },- { id: 'newer:1', backendItemId: 20, state: 'running' },+ { id: 'batch:1', backendItemId: 10, hasOwnFrame: false, state: 'running' },+ { id: 'batch:2', backendItemId: 11, hasOwnFrame: true, state: 'running' },+ { id: 'newer:1', backendItemId: 20, hasOwnFrame: false, state: 'running' },]);});it('keeps a settling session until routing releases it, even after its result enters project state', () => {const item = { ...run('batch', [10, 11]), completedBackendItemIds: [10] };expect(- getQueueActiveSessions([item], [target('batch', 2)], [target('batch', 1), target('batch', 2)])+ getQueueActiveSessions([item], [target('batch', 2)], [target('batch', 1), target('batch', 2)], [])).toMatchObject([{ id: 'batch:1', state: 'settling' },{ id: 'batch:2', state: 'running' },]);- expect(getQueueActiveSessions([item], [], [])).toEqual([]);+ expect(getQueueActiveSessions([item], [], [], [])).toEqual([]);});it('filters destinations through presentation policy and rejects targets outside the project or batch', () => {const items = [run('gallery', [10]), run('canvas', [11], 'canvas')];const targets = [target('gallery', 1), target('canvas', 1), target('other-project', 1), target('gallery', 2)];expect(- getQueueActiveSessions(items.filter(isGalleryProgressItem), targets, targets).map((session) => session.id)+ getQueueActiveSessions(items.filter(isGalleryProgressItem), targets, targets, []).map((session) => session.id)).toEqual(['gallery:1']);- expect(getQueueActiveSessions(items, targets, targets).map((session) => session.id)).toEqual([+ expect(getQueueActiveSessions(items, targets, targets, []).map((session) => session.id)).toEqual(['gallery:1','canvas:1',]);@@ -96,14 +99,14 @@ describe('gallery batch progress slots', () => {]);const item = run('batch', [10, 11, 12]);const targets = [target('batch', 1)];- const sessions = getQueueProgressSessions([item], getQueueActiveSessions([item], targets, targets));+ const sessions = getQueueProgressSessions([item], getQueueActiveSessions([item], targets, targets, []));expect(sessions.map(({ id }) => id)).toEqual(queued.map(({ id }) => id));expect(sessions.map(({ state }) => state)).toEqual(['running', 'queued', 'queued']);});it('removes completed and cancelled slots, retaining only a settling frame until release', () => {const item = { ...run('batch', [10, 11, 12]), completedBackendItemIds: [10], cancelledBackendItemIds: [12] };expect(getQueueProgressSessions([item], []).map(({ id }) => id)).toEqual(['batch:2']);- const active = getQueueActiveSessions([item], [], [target('batch', 1)]);+ const active = getQueueActiveSessions([item], [], [target('batch', 1)], []);expect(getQueueProgressSessions([item], active).map(({ state }) => state)).toEqual(['settling', 'queued']);for (const status of ['completed', 'cancelled', 'failed'] as const) {expect(getQueueProgressSessions([{ ...item, status }], [])).toEqual([]);@@ -111,19 +114,110 @@ describe('gallery batch progress slots', () => {});});-describe('getFollowedProgressSession', () => {- const sessions = [- { id: 'queued', state: 'queued' as const },- { id: 'settling', state: 'settling' as const },- { id: 'running-1', state: 'running' as const },- { id: 'running-2', state: 'running' as const },- ];+describe('Auto-switch policy', () => {+ const live = (id: string, state: AutoSwitchLiveSlot['state'], hasOwnFrame: boolean): AutoSwitchLiveSlot => ({+ hasOwnFrame,+ id,+ state,+ });+ const modes: AutoSwitchMode[] = ['off', 'latest', 'progress'];++ // Each row: the generating slots in start order and the pin, and what In progress shows. Off and Newest never show a+ // generating slot.+ it.each([+ {+ expected: null,+ lives: [live('a', 'running', false)],+ pinned: null,+ pinHeld: false,+ situation: 'a slot starting without a frame of its own (model load): the previous result stays',+ },+ {+ expected: 'a',+ lives: [live('a', 'running', true)],+ pinned: null,+ pinHeld: false,+ situation: "a slot's first frame of its own",+ },+ {+ expected: 'b',+ lives: [live('a', 'running', true), live('b', 'running', true)],+ pinned: null,+ pinHeld: false,+ situation: 'two running with frames: the newest started',+ },+ {+ expected: 'a',+ lives: [live('a', 'settling', true), live('b', 'running', false)],+ pinned: null,+ pinHeld: false,+ situation: 'a finished slot whose result is on its way, while the next has no frame yet',+ },+ {+ expected: 'b',+ lives: [live('a', 'settling', true), live('b', 'running', true)],+ pinned: null,+ pinHeld: false,+ situation: 'the next slot shows its first frame while the finished one settles',+ },+ {+ expected: null,+ lives: [live('a', 'settling', false)],+ pinned: null,+ pinHeld: false,+ situation: 'a settling slot that never showed a frame',+ },+ {+ expected: 'a',+ lives: [live('a', 'running', false), live('b', 'running', true)],+ pinned: 'a',+ pinHeld: true,+ situation: 'a picked slot that runs, over a newer one with a frame, frameless or not',+ },+ {+ expected: 'b',+ lives: [live('a', 'settling', true), live('b', 'running', true)],+ pinned: 'a',+ pinHeld: false,+ situation: 'a picked slot that has finished releases the pin',+ },+ {+ expected: 'b',+ lives: [live('a', 'queued', false), live('b', 'running', true)],+ pinned: 'a',+ pinHeld: false,+ situation: 'a picked slot waiting to start holds no pin',+ },+ {+ expected: null,+ lives: [],+ pinned: 'gone',+ pinHeld: false,+ situation: 'a picked slot that has gone',+ },+ ])('under each mode, $situation', ({ expected, lives, pinHeld, pinned }) => {+ for (const mode of modes) {+ expect(getAutoSwitchFollowedLive(mode, lives, pinned)?.id ?? null).toBe(mode === 'progress' ? expected : null);+ }+ expect(isAutoSwitchPinHeld(lives, pinned)).toBe(pinHeld);+ });++ it.each([+ { hasSelectedResult: true, mode: 'off', selects: false },+ { hasSelectedResult: false, mode: 'off', selects: true },+ { hasSelectedResult: true, mode: 'latest', selects: true },+ { hasSelectedResult: false, mode: 'latest', selects: true },+ { hasSelectedResult: true, mode: 'progress', selects: true },+ { hasSelectedResult: false, mode: 'progress', selects: true },+ ] as const)(+ 'a landed result under $mode, with a result selected: $hasSelectedResult, is selected: $selects',+ ({ hasSelectedResult, mode, selects }) => {+ expect(selectsLandedResult(mode, hasSelectedResult)).toBe(selects);+ }+ );- it('prefers the pinned session, then the first running, then the first settling, never a queued one', () => {- expect(getFollowedProgressSession(sessions, 'running-2')?.id).toBe('running-2');- expect(getFollowedProgressSession(sessions, null)?.id).toBe('running-1');- expect(getFollowedProgressSession(sessions, 'gone')?.id).toBe('running-1');- expect(getFollowedProgressSession(sessions.slice(0, 2), null)?.id).toBe('settling');- expect(getFollowedProgressSession(sessions.slice(0, 1), null)).toBeNull();+ it('picking a result pauses Auto-switch, and picking a generating slot follows and pins it, from any mode', () => {+ expect(pickAutoSwitch({ kind: 'result' })).toEqual({ mode: 'off', pinnedId: null });+ expect(pickAutoSwitch({ id: 'b', kind: 'live' })).toEqual({ mode: 'progress', pinnedId: 'b' });});});diff --git a/invokeai/frontend/webv2/src/features/queue/core/activeSessions.ts b/invokeai/frontend/webv2/src/features/queue/core/activeSessions.tsindex c6acf2320f..100c5416ca 100644--- a/invokeai/frontend/webv2/src/features/queue/core/activeSessions.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/activeSessions.ts@@ -12,19 +12,25 @@ export interface QueueActiveSession extends QueueItemProgressTarget {width: number;height: number;itemCount: number;+ /** The session has shown a frame of its own; live surfaces follow it only from then on. */+ hasOwnFrame: boolean;state: 'running' | 'settling';}/** Presentation policy shared by Gallery and Preview; discovery remains destination-neutral. */export const isGalleryProgressItem = (item: QueueItem): boolean => item.snapshot.destination === 'gallery';+const getTargetKey = (target: QueueItemProgressTarget): string => `${target.queueItemId}:${target.itemIndex}`;+export const getQueueActiveSessions = (items: readonly QueueItem[],running: readonly QueueItemProgressTarget[],- followed: readonly QueueItemProgressTarget[]+ followed: readonly QueueItemProgressTarget[],+ framed: readonly QueueItemProgressTarget[]): QueueActiveSession[] => {const itemsById = new Map(items.map((item) => [item.id, item]));- const runningKeys = new Set(running.map((target) => `${target.queueItemId}:${target.itemIndex}`));+ const runningKeys = new Set(running.map(getTargetKey));+ const framedKeys = new Set(framed.map(getTargetKey));const sessions: QueueActiveSession[] = [];for (const target of followed) {@@ -33,7 +39,7 @@ export const getQueueActiveSessions = (if (!item || backendItemId === undefined) {continue;}- const id = `${target.queueItemId}:${target.itemIndex}`;+ const id = getTargetKey(target);sessions.push({...target,...getQueueItemSnapshotDimensions(item, { width: 1024, height: 1024 }),@@ -42,6 +48,7 @@ export const getQueueActiveSessions = (label: item.snapshot.graph.label,sourceId: item.snapshot.sourceId,itemCount: item.backendItemIds!.length,+ hasOwnFrame: framedKeys.has(id),state: runningKeys.has(id) ? 'running' : 'settling',});}@@ -50,21 +57,65 @@ export const getQueueActiveSessions = (};/**- * The session the live preview shows and the gallery highlights: the pinned- * one, else the first running, else the first still settling; queued work is- * never followed.+ * Auto-switch, one policy for every surface that shows generation results: Preview (`viewerAutoSwitch`) and Canvas+ * staging (`autoSwitchMode`). Each surface keeps its own selected result and adapts its own slots; these rules decide+ * what follows what.+ *+ * - `latest` (Newest) and `progress` (In progress) select each result as it lands; `off` selects one only while+ * nothing else is selected (`selectsLandedResult`).+ * - Only `progress` shows generating slots, and only from their first frame of their own (`getAutoSwitchFollowedLive`):+ * until then the previous result stays on screen.+ * - The user picking something to show steers it (`pickAutoSwitch`): a result pauses Auto-switch (Off) until the mode+ * is set again or a generating slot is picked; a generating slot turns it to In progress and pins that slot while it+ * runs.*/-export const getFollowedProgressSession = <T extends { id: string; state: QueueProgressSession['state'] }>(- sessions: readonly T[],- pinnedSessionId: string | null-): T | null =>- sessions.find((session) => session.id === pinnedSessionId) ??- sessions.find((session) => session.state === 'running') ??- sessions.find((session) => session.state === 'settling') ??- null;+export type AutoSwitchMode = 'latest' | 'off' | 'progress';++/** A generating slot as Auto-switch sees it: waiting to start, running, or finished with its result still on its way. */+export interface AutoSwitchLiveSlot {+ id: string;+ hasOwnFrame: boolean;+ state: 'queued' | 'running' | 'settling';+}++/** A pin holds only while its slot runs; a slot that settles, ends or never started releases it. */+export const isAutoSwitchPinHeld = (lives: readonly AutoSwitchLiveSlot[], pinnedId: string | null): boolean =>+ pinnedId !== null && lives.some((live) => live.id === pinnedId && live.state === 'running');++/**+ * The generating slot Auto-switch shows, or null to show the selected result: under In progress only, the pinned slot+ * while it runs, else the newest running slot with a frame of its own, else the first settling one with a frame (so a+ * finished slot's last frame stays up while its result is on its way). `lives` are in the order they started.+ */+export const getAutoSwitchFollowedLive = <T extends AutoSwitchLiveSlot>(+ mode: AutoSwitchMode,+ lives: readonly T[],+ pinnedId: string | null+): T | null => {+ if (mode !== 'progress') {+ return null;+ }++ return (+ (isAutoSwitchPinHeld(lives, pinnedId) ? lives.find((live) => live.id === pinnedId) : undefined) ??+ lives.filter((live) => live.state === 'running' && live.hasOwnFrame).at(-1) ??+ lives.find((live) => live.state === 'settling' && live.hasOwnFrame) ??+ null+ );+};++/** What the user picking something to show does to Auto-switch. */+export const pickAutoSwitch = (+ pick: { kind: 'live'; id: string } | { kind: 'result' }+): { mode: AutoSwitchMode; pinnedId: string | null } =>+ pick.kind === 'live' ? { mode: 'progress', pinnedId: pick.id } : { mode: 'off', pinnedId: null };++/** Whether a result that just landed becomes the selected one. */+export const selectsLandedResult = (mode: AutoSwitchMode, hasSelectedResult: boolean): boolean =>+ mode !== 'off' || !hasSelectedResult;/** A tile per unfinished batch slot, including work waiting to start. */-export type QueueProgressSession = Omit<QueueActiveSession, 'backendItemId' | 'state'> & {+export type QueueProgressSession = Omit<QueueActiveSession, 'backendItemId' | 'hasOwnFrame' | 'state'> & {backendItemId: number | null;state: 'queued' | 'running' | 'settling';};diff --git a/invokeai/frontend/webv2/src/features/queue/core/generationMeta.ts b/invokeai/frontend/webv2/src/features/queue/core/generationMeta.tsindex 0571cd5656..8f88203729 100644--- a/invokeai/frontend/webv2/src/features/queue/core/generationMeta.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/generationMeta.ts@@ -16,25 +16,33 @@ const POSITIVE_PROMPT_NODE_PATH = 'positive_prompt';const NEGATIVE_PROMPT_NODE_PATH = 'negative_prompt';const SEED_NODE_PATH = 'seed';-export const extractGenerationMeta = (item: QueueItemReadModel): QueueGenerationMeta => {- const fieldValues = item.fieldValues ?? [];+/**+ * The prompts and seed by the node ids webv2's compiled Generate, Canvas, Video and Upscale graphs give them, which+ * every one of their submissions writes. A webv2 item without them ran something else, such as a workflow.+ */+export const extractNamedGenerationMeta = (item: QueueItemReadModel): QueueGenerationMeta => {const meta: QueueGenerationMeta = {};- let namedPrompt = false;- for (const { nodePath, value } of fieldValues) {+ for (const { nodePath, value } of item.fieldValues ?? []) {if (nodePath === POSITIVE_PROMPT_NODE_PATH && typeof value === 'string') {// Recorded verbatim, empty included: an empty positive is a real// submission, not a missing field.meta.positivePrompt = value;- namedPrompt = true;} else if (nodePath === NEGATIVE_PROMPT_NODE_PATH && typeof value === 'string') {meta.negativePrompt = value;- namedPrompt = true;} else if (nodePath === SEED_NODE_PATH && typeof value === 'number') {meta.seed = value;}}+ return meta;+};++export const extractGenerationMeta = (item: QueueItemReadModel): QueueGenerationMeta => {+ const fieldValues = item.fieldValues ?? [];+ const meta = extractNamedGenerationMeta(item);+ const namedPrompt = meta.positivePrompt !== undefined || meta.negativePrompt !== undefined;+if (namedPrompt && meta.seed !== undefined) {return meta;}diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.tsindex 3c32bb8c7d..668dd59cc3 100644--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts@@ -182,11 +182,15 @@ export interface QueueItemReadModel {origin?: string | null;/** The workflow-call parent this item runs for; null or absent on root items. */parentItemId?: number | null;+ /** Pending items run highest priority first, then oldest first; absent when the source did not say. */+ priority?: number | null;resultImageNames: string[];retriedFromItemId?: number | null;sessionId: string;startedAt?: string | null;status: QueueItemStatus;+ /** Rises with every status change of the item; a reading with a lower one is older. Absent when unknown. */+ statusSequence?: number | null;updatedAt: string;userDisplayName?: string | null;userEmail?: string | null;@@ -298,8 +302,8 @@ export interface QueueResultVideoOptions extends QueueResultImageOptions {export interface QueueFeatureCommands {/** Cancels every unfinished item of one batch; resolves with how many the backend canceled. */cancelBatch(batchId: string): Promise<number>;- cancelCurrentItem(): Promise<void>;- cancelItem(itemId: number): Promise<void>;+ /** Resolves with the item as the cancel left it: unchanged, so not canceled, when it had already finished. */+ cancelItem(itemId: number): Promise<QueueItemReadModel>;cancelScopedItems(scope?: QueueQueryScope, options?: { keepCurrent?: boolean }): Promise<void>;clearFailedItems(scope?: QueueQueryScope): Promise<void>;/** Removes completed, canceled and failed items; pending and running work is kept. */diff --git a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.test.ts b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.test.tsindex 71785744de..9be9321dce 100644--- a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.test.ts@@ -4,6 +4,7 @@ import {activeProgressTargetStore,getActiveProgressTargets,getFollowedProgressTargets,+ getFramedProgressTargets,} from './activeProgressTargetStore';const target = (queueItemId: string, itemIndex: number) => ({ itemIndex, queueItemId });@@ -113,4 +114,30 @@ describe('activeProgressTargetStore', () => {expect(getFollowedProgressTargets()).toEqual([]);});++ it('keeps a slot framed through settling, and forgets it with the slot', () => {+ activeProgressTargetStore.set(target('queue-1', 1));+ activeProgressTargetStore.set(target('queue-1', 2));++ activeProgressTargetStore.markFramed(target('queue-1', 1));+ const framed = getFramedProgressTargets();+ activeProgressTargetStore.markFramed(target('queue-1', 1));+ activeProgressTargetStore.settle(target('queue-1', 1));++ // Every frame marks it again; only the first changes anything.+ expect(getFramedProgressTargets()).toBe(framed);+ expect(getFramedProgressTargets()).toEqual([target('queue-1', 1)]);++ activeProgressTargetStore.clear(target('queue-1', 1));++ expect(getFramedProgressTargets()).toEqual([]);+ expect(getActiveProgressTargets()).toEqual([target('queue-1', 2)]);+ });++ it('tracks a slot whose first frame arrives before its start was reported', () => {+ activeProgressTargetStore.markFramed(target('queue-1', 1));++ expect(getActiveProgressTargets()).toEqual([target('queue-1', 1)]);+ expect(getFramedProgressTargets()).toEqual([target('queue-1', 1)]);+ });});diff --git a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.tsindex 6f67106d09..b766a6056d 100644--- a/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/activeProgressTargetStore.ts@@ -5,20 +5,28 @@ import { createExternalStore } from '@platform/state/externalStore';/*** Track concurrent slots in start order. Settling slots preserve the final frame until results land; multi-slot- * surfaces exclude them to avoid transient extra tiles.+ * surfaces exclude them to avoid transient extra tiles. Framed slots have shown a frame of their own: live surfaces+ * follow a slot only from then on, so model loading and text encoding never replace the previous result.*/export interface ActiveProgressTargetSink {clear(target?: QueueItemProgressTarget): void;+ /** The slot's first frame of its own arrived; it stays framed until cleared. */+ markFramed(target: QueueItemProgressTarget): void;set(target: QueueItemProgressTarget): void;settle(target: QueueItemProgressTarget): void;}interface ActiveProgressTargetsSnapshot {+ framedTargets: QueueItemProgressTarget[];settlingTargets: QueueItemProgressTarget[];targets: QueueItemProgressTarget[];}-const store = createExternalStore<ActiveProgressTargetsSnapshot>({ settlingTargets: [], targets: [] });+const store = createExternalStore<ActiveProgressTargetsSnapshot>({+ framedTargets: [],+ settlingTargets: [],+ targets: [],+});const isSameTarget = (left: QueueItemProgressTarget, right: QueueItemProgressTarget): boolean =>left.queueItemId === right.queueItemId && left.itemIndex === right.itemIndex;@@ -31,11 +39,11 @@ const without = (targets: QueueItemProgressTarget[], target: QueueItemProgressTaexport const activeProgressTargetStore: ActiveProgressTargetSink = {clear(target) {- const { settlingTargets, targets } = store.getSnapshot();+ const { framedTargets, settlingTargets, targets } = store.getSnapshot();if (!target) {- if (targets.length > 0 || settlingTargets.length > 0) {- store.patchSnapshot({ settlingTargets: [], targets: [] });+ if (targets.length > 0 || settlingTargets.length > 0 || framedTargets.length > 0) {+ store.patchSnapshot({ framedTargets: [], settlingTargets: [], targets: [] });}return;@@ -43,12 +51,22 @@ export const activeProgressTargetStore: ActiveProgressTargetSink = {const remaining = without(targets, target);const remainingSettling = without(settlingTargets, target);+ const remainingFramed = without(framedTargets, target);store.patchSnapshot({...(remaining.length !== targets.length ? { targets: remaining } : {}),...(remainingSettling.length !== settlingTargets.length ? { settlingTargets: remainingSettling } : {}),+ ...(remainingFramed.length !== framedTargets.length ? { framedTargets: remainingFramed } : {}),});},+ markFramed(target) {+ activeProgressTargetStore.set(target);+ const { framedTargets } = store.getSnapshot();++ if (!includes(framedTargets, target)) {+ store.patchSnapshot({ framedTargets: [...framedTargets, target] });+ }+ },set(target) {const { settlingTargets, targets } = store.getSnapshot();@@ -110,6 +128,12 @@ export const useActiveProgressTargets = (): QueueItemProgressTarget[] =>/** Every followable slot — running ones first, then settling ones. */export const useFollowedProgressTargets = (): QueueItemProgressTarget[] => store.useSelector(selectFollowedTargets);+/** Every running or settling slot that has shown a frame of its own. */+export const useFramedProgressTargets = (): QueueItemProgressTarget[] =>+ store.useSelector((snapshot) => snapshot.framedTargets);+export const getActiveProgressTargets = (): QueueItemProgressTarget[] => store.getSnapshot().targets;export const getFollowedProgressTargets = (): QueueItemProgressTarget[] => selectFollowedTargets(store.getSnapshot());++export const getFramedProgressTargets = (): QueueItemProgressTarget[] => store.getSnapshot().framedTargets;diff --git a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.test.ts b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.test.tsindex 55b04847ae..afbd44c551 100644--- a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.test.ts@@ -1,9 +1,16 @@import { afterEach, describe, expect, it, vi } from 'vitest';-const server = vi.hoisted(() => ({ claimQueueItemDelivery: vi.fn(), retryItemsById: vi.fn() }));+const server = vi.hoisted(() => ({+ cancelQueueItem: vi.fn(),+ claimQueueItemDelivery: vi.fn(),+ retryItemsById: vi.fn(),+}));vi.mock('./serverApi', async (importOriginal) => ({ ...(await importOriginal<object>()), ...server }));-import { queueBackend } from './httpRealtimeQueueBackend';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { RequestDeadlineError } from '@platform/transport/http';++import { CANCEL_ITEM_TIMEOUT_MS, queueBackend } from './httpRealtimeQueueBackend';afterEach(() => {vi.clearAllMocks();@@ -61,3 +68,58 @@ describe('queueBackend delivery claims', () => {expect(server.claimQueueItemDelivery).toHaveBeenCalledWith(99, 'confirm', 'tab:a');});});++describe('queueBackend item cancel', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('gives up on a cancel the server never answers, aborting its request', async () => {+ vi.useFakeTimers();+ let requestSignal: AbortSignal | undefined;+ server.cancelQueueItem.mockImplementation(+ (_itemId: number, signal: AbortSignal) =>+ new Promise((_resolve, reject) => {+ requestSignal = signal;+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });+ })+ );++ const cancel = queueBackend.cancelItem(7);+ const settled = expect(cancel).rejects.toBeInstanceOf(RequestDeadlineError);+ await vi.advanceTimersByTimeAsync(CANCEL_ITEM_TIMEOUT_MS);++ await settled;+ expect(requestSignal?.aborted).toBe(true);+ });++ it('answers for no account once the one that asked has signed out, aborting its request', async () => {+ accountLifecycle.activate('user-a');+ let requestSignal: AbortSignal | undefined;+ let answer!: (dto: unknown) => void;+ // A server that answers whatever happens to the request.+ server.cancelQueueItem.mockImplementation(+ (_itemId: number, signal: AbortSignal) =>+ new Promise((resolve) => {+ requestSignal = signal;+ answer = resolve;+ })+ );++ const cancel = queueBackend.cancelItem(7);+ const settled = expect(cancel).rejects.toThrow('no longer active');+ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');+ answer({+ batch_id: 'batch',+ created_at: '2026-11-14T00:00:00',+ item_id: 7,+ session_id: 's',+ status: 'canceled',+ updated_at: '2026-11-14T00:00:00',+ });++ await settled;+ expect(requestSignal?.aborted).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.tsindex 104264bcbb..221864d95e 100644--- a/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/httpRealtimeQueueBackend.ts@@ -1,6 +1,8 @@import type { QueueBackendPort } from '@features/queue/core/types';import type { QueueItemsRetriedEvent } from '@features/queue/data/events';+import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';+import { withRequestDeadline } from '@platform/transport/http';import { socketHub } from '@platform/transport/socketHub';import {@@ -12,7 +14,6 @@ import {} from './mappers';import {cancelByBatchIds,- cancelCurrentQueueItem,claimQueueItemDelivery,cancelQueueItem,cancelQueueItems,@@ -48,17 +49,31 @@ import {*/const ownRetryHandlers = new Set<(payload: never) => void>();+/**+ * How long one item's cancel may take. A request the server never answers would otherwise hold cancel-current, which+ * runs one at a time, and leave the viewer's cancel button doing nothing.+ */+export const CANCEL_ITEM_TIMEOUT_MS = 10_000;+/** Production adapter for the queue backend port. */export const queueBackend: QueueBackendPort = {acknowledgeEnqueue: acknowledgeQueueEnqueue,cancelBatch: async (batchId) => (await cancelByBatchIds([batchId])).canceled,- cancelCurrentItem: cancelCurrentQueueItem,cancelQueueItems,cancelQueueItemsByBatchIds: async (batchIds) => {await cancelByBatchIds(batchIds);},cancelItem: async (itemId) => {- await cancelQueueItem(itemId);+ const owner = captureAccountScope();+ // An account change aborts the request; either way it ends, the answer belongs to the account that asked or to+ // nobody, and the caller hears that as the account being gone.+ const item = await withRequestDeadline(+ (signal) => cancelQueueItem(itemId, signal),+ CANCEL_ITEM_TIMEOUT_MS,+ owner.signal+ ).finally(() => assertAccountScopeCurrent(owner));++ return mapQueueItemDTO(item);},cancelScopedItems: cancelScopedQueueItems,clearFailedItems: clearFailedQueueItems,diff --git a/invokeai/frontend/webv2/src/features/queue/data/mappers.ts b/invokeai/frontend/webv2/src/features/queue/data/mappers.tsindex e74537b447..3af348186b 100644--- a/invokeai/frontend/webv2/src/features/queue/data/mappers.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/mappers.ts@@ -1,5 +1,6 @@import type {QueueBackendItem,+ QueueCounts,QueueItemDetailReadModel,QueueItemIdsReadModel,QueueItemReadModel,@@ -10,11 +11,14 @@ import type {import { getOutputImageNames } from '@platform/core/outputImages';import { normalizeServerTimestamp } from '@platform/time/serverTimestamp';+import type { QueueItemStatusChangedEvent } from './events';+import type { QueueItemStatusChange } from './queries';import type {QueueAndProcessorStatusDTO,QueueItemIdsResultDTO,QueueNodeFieldValueDTO,QueueServerItemDTO,+ QueueStatusCountsDTO,} from './serverTypes';const mapNodeFieldValue = (dto: QueueNodeFieldValueDTO): QueueNodeFieldValue => ({@@ -47,11 +51,13 @@ export const mapQueueItemDTO = (dto: QueueServerItemDTO): QueueItemReadModel =>id: dto.item_id,origin: dto.origin,parentItemId: dto.parent_item_id,+ priority: dto.priority,resultImageNames: getResultImageNames(dto),retriedFromItemId: dto.retried_from_item_id,sessionId: dto.session_id,startedAt: normalizeOptionalTimestamp(dto.started_at),status: dto.status,+ statusSequence: dto.status_sequence,updatedAt: normalizeServerTimestamp(dto.updated_at),userDisplayName: dto.user_display_name,userEmail: dto.user_email,@@ -87,24 +93,49 @@ export const mapQueueItemIdsDTO = (dto: QueueItemIdsResultDTO): QueueItemIdsReaditemIds: dto.item_ids,});+const mapQueueCountsDTO = (dto: QueueStatusCountsDTO): QueueCounts => ({+ batchId: dto.batch_id,+ canceled: dto.canceled,+ completed: dto.completed,+ failed: dto.failed,+ inProgress: dto.in_progress,+ itemId: dto.item_id,+ pending: dto.pending,+ queueId: dto.queue_id,+ sessionId: dto.session_id,+ total: dto.total,+ userInProgress: dto.user_in_progress,+ userPending: dto.user_pending,+ waiting: dto.waiting,+});+export const mapQueueStatusDTO = (dto: QueueAndProcessorStatusDTO): QueueStatusReadModel => ({processor: {isProcessing: dto.processor.is_processing,isStarted: dto.processor.is_started,},- queue: {- batchId: dto.queue.batch_id,- canceled: dto.queue.canceled,- completed: dto.queue.completed,- failed: dto.queue.failed,- inProgress: dto.queue.in_progress,- itemId: dto.queue.item_id,- pending: dto.queue.pending,- queueId: dto.queue.queue_id,- sessionId: dto.queue.session_id,- total: dto.queue.total,- userInProgress: dto.queue.user_in_progress,- userPending: dto.queue.user_pending,- waiting: dto.queue.waiting,+ queue: mapQueueCountsDTO(dto.queue),+});++/** The item fields a status event carries, and the whole queue's counts after the change. */+export const mapQueueItemStatusChangedEvent = (event: QueueItemStatusChangedEvent): QueueItemStatusChange => ({+ item: {+ batchId: event.batch_id,+ completedAt: normalizeOptionalTimestamp(event.completed_at),+ createdAt: normalizeServerTimestamp(event.created_at),+ destination: event.destination,+ errorMessage: event.error_message,+ errorTraceback: event.error_traceback,+ errorType: event.error_type,+ id: event.item_id,+ origin: event.origin,+ resultImageNames: [],+ sessionId: event.session_id,+ startedAt: normalizeOptionalTimestamp(event.started_at),+ status: event.status,+ statusSequence: event.status_sequence,+ updatedAt: normalizeServerTimestamp(event.updated_at),+ userId: event.user_id,},+ queueCounts: mapQueueCountsDTO(event.queue_status),});diff --git a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.test.ts b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.test.tsindex 20e0740260..795b2a9423 100644--- a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.test.ts@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {consumeQueueItemSwapProgressImage,getLatestProgressImage,- getQueueItemBridgeProgressImage,getQueueItemSwapProgressImage,progressImageStore,SWAP_FRAME_TTL_MS,@@ -23,28 +22,24 @@ describe('progressImageStore held frames', () => {vi.useRealTimers();});- it('copies the slot frame into both held sets and keeps the live frame', () => {+ it('holds the slot frame for the swap and keeps it after the live slot is released', () => {progressImageStore.set(frame('last'), target('queue-1'));progressImageStore.hold(target('queue-1'));progressImageStore.bindSwapImages('queue-1', ['result.png']);+ progressImageStore.clear(target('queue-1'));- expect(getQueueItemBridgeProgressImage('queue-1')).toEqual(frame('last'));expect(getQueueItemSwapProgressImage('queue-1', 'result.png')).toEqual(frame('last'));- // The single-slot preview keeps showing the live frame while routing runs.- progressImageStore.clear(target('queue-1'));- expect(getQueueItemBridgeProgressImage('queue-1')).toEqual(frame('last'));});it('holds nothing for a slot that never produced a frame', () => {progressImageStore.hold(target('queue-1'));progressImageStore.bindSwapImages('queue-1', ['result.png']);- expect(getQueueItemBridgeProgressImage('queue-1')).toBeNull();expect(getQueueItemSwapProgressImage('queue-1', 'result.png')).toBeNull();});- it('bridges only to the last selected output of a multi-output workflow', () => {+ it('swaps only to the last selected output of a multi-output workflow', () => {// Only routed output names may use a held frame; another item in the same batch must not inherit it.progressImageStore.set(frame('third'), target('queue-1', 3));progressImageStore.hold(target('queue-1', 3));@@ -72,8 +67,6 @@ describe('progressImageStore held frames', () => {consumeQueueItemSwapProgressImage('queue-1');expect(getQueueItemSwapProgressImage('queue-1', 'result.png')).toBeNull();- // The bridge to the batch's next slot is still needed.- expect(getQueueItemBridgeProgressImage('queue-1')).toEqual(frame('last'));});it('expires the swap frame so browsing back never replays the low-resolution frame', () => {@@ -86,7 +79,6 @@ describe('progressImageStore held frames', () => {vi.advanceTimersByTime(1);expect(getQueueItemSwapProgressImage('queue-1', 'result.png')).toBeNull();- expect(getQueueItemBridgeProgressImage('queue-1')).toEqual(frame('last'));});it('restarts the expiry when a later slot of the same queue item is held', () => {@@ -109,25 +101,24 @@ describe('progressImageStore held frames', () => {progressImageStore.bindSwapImages(`queue-${index}`, [`image-${index}.png`]);}- expect(getQueueItemBridgeProgressImage('queue-0')).toBeNull();expect(getQueueItemSwapProgressImage('queue-0', 'image-0.png')).toBeNull();- expect(getQueueItemBridgeProgressImage('queue-1')).toEqual(frame('frame-1'));+ expect(getQueueItemSwapProgressImage('queue-1', 'image-1.png')).toEqual(frame('frame-1'));expect(getQueueItemSwapProgressImage('queue-8', 'image-8.png')).toEqual(frame('frame-8'));});it('forgets a queue item on clearHeld and everything on clear', () => {progressImageStore.set(frame('one'), target('queue-1'));progressImageStore.hold(target('queue-1'));+ progressImageStore.bindSwapImages('queue-1', ['one.png']);progressImageStore.set(frame('two'), target('queue-2'));progressImageStore.hold(target('queue-2'));progressImageStore.bindSwapImages('queue-2', ['two.png']);progressImageStore.clearHeld('queue-1');- expect(getQueueItemBridgeProgressImage('queue-1')).toBeNull();+ expect(getQueueItemSwapProgressImage('queue-1', 'one.png')).toBeNull();expect(getQueueItemSwapProgressImage('queue-2', 'two.png')).toEqual(frame('two'));progressImageStore.clear();- expect(getQueueItemBridgeProgressImage('queue-2')).toBeNull();expect(getQueueItemSwapProgressImage('queue-2', 'two.png')).toBeNull();expect(vi.getTimerCount()).toBe(0);});diff --git a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.tsindex d442307058..5de7ce422a 100644--- a/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/progressImageStore.ts@@ -5,8 +5,8 @@ import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore, createKeyedTransientStore } from '@platform/state/externalStore';/**- * Hold bounded bridge frames between batch slots and swap frames until image decode. Retain frames across- * disconnects while HTTP reconciles the continuing run.+ * Hold a finished slot's last frame as a bounded swap frame until its image decodes. Retain frames across disconnects+ * while HTTP reconciles the continuing run.*/export type ProgressImageSnapshot = QueueProgressImage;@@ -37,7 +37,6 @@ interface SwapFrame {const snapshotsByTarget = createKeyedTransientStore<string, ProgressImageSnapshot>();/** Insertion order is recency: `set` re-inserts, so the last entry is the most recently updated slot. */const targetsByKey = new Map<string, ProgressImageTarget>();-const bridgeFrames = createKeyedTransientStore<string, ProgressImageSnapshot>();const swapFrames = createKeyedTransientStore<string, SwapFrame>();const swapExpiryTimers = new Map<string, ReturnType<typeof setTimeout>>();@@ -63,10 +62,6 @@ const evictOldest = <Value>(}};-const dropBridge = (queueItemId: string): void => {- bridgeFrames.delete(queueItemId);-};-const dropSwap = (queueItemId: string): void => {const timer = swapExpiryTimers.get(queueItemId);@@ -78,12 +73,6 @@ const dropSwap = (queueItemId: string): void => {swapFrames.delete(queueItemId);};-const holdBridge = (queueItemId: string, image: ProgressImageSnapshot): void => {- dropBridge(queueItemId);- bridgeFrames.set(queueItemId, image);- evictOldest(bridgeFrames, dropBridge);-};-const holdSwap = (queueItemId: string, image: ProgressImageSnapshot): void => {dropSwap(queueItemId);swapFrames.set(queueItemId, { image, imageNames: null });@@ -100,7 +89,6 @@ export const progressImageStore = {latestSnapshotStore.patchSnapshot({ latestSnapshot: null });snapshotsByTarget.clear();targetsByKey.clear();- bridgeFrames.clear();for (const timer of swapExpiryTimers.values()) {clearTimeout(timer);@@ -130,25 +118,21 @@ export const progressImageStore = {if (entry) {// A workflow may save unrelated images in several boards. One preview- // bridges only to the latest output selected by result routing while it decodes.+ // swaps only to the latest output selected by result routing while it decodes.swapFrames.set(queueItemId, { image: entry.image, imageNames: imageNames.slice(-1) });}},/** Forget a queue item's held frames: its run is gone (detached or canceled). */clearHeld(queueItemId: string): void {- dropBridge(queueItemId);dropSwap(queueItemId);},- /** Hold the final frame for bridging and swapping; retain the live slot until result fetch completes. */+ /** Hold the final frame for swapping; retain the live slot until result fetch completes. */hold(target: ProgressImageTarget): void {const image = snapshotsByTarget.get(getTargetKey(target));- if (!image) {- return;+ if (image) {+ holdSwap(target.queueItemId, image);}-- holdBridge(target.queueItemId, image);- holdSwap(target.queueItemId, image);},set(image: ProgressImageSnapshot, target?: ProgressImageTarget): void {latestSnapshotStore.patchSnapshot({ latestSnapshot: target ? { ...image, target } : image });@@ -190,9 +174,6 @@ export const consumeQueueItemSwapProgressImage = (queueItemId: string): void =>export const getLatestProgressImage = (): LatestProgressImageSnapshot | null =>latestSnapshotStore.getSnapshot().latestSnapshot;-export const getQueueItemBridgeProgressImage = (queueItemId: string): ProgressImageSnapshot | null =>- bridgeFrames.get(queueItemId) ?? null;-const selectSwapProgressImage = (entry: SwapFrame | undefined, imageName: string): ProgressImageSnapshot | null =>entry?.imageNames?.includes(imageName) ? entry.image : null;@@ -205,10 +186,6 @@ export const useProgressImage = (): LatestProgressImageSnapshot | null =>export const useQueueItemProgressImage = (queueItemId: string, itemIndex: number): ProgressImageSnapshot | null =>snapshotsByTarget.useValue(getTargetKey({ itemIndex, queueItemId })) ?? null;-/** The frame to show for a slot of this queue item that has none of its own yet. */-export const useQueueItemBridgeProgressImage = (queueItemId: string): ProgressImageSnapshot | null =>- bridgeFrames.useValue(queueItemId) ?? null;-/*** The frame to show in place of this just-finished image until it has decoded;* null once consumed or expired, for images the held frame did not produce, anddiff --git a/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts b/invokeai/frontend/webv2/src/features/queue/data/queries.test.tsindex ff9518520a..fad236c327 100644--- a/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/queries.test.ts@@ -1,4 +1,10 @@-import type { QueueBackendPort, QueueItemDetailReadModel } from '@features/queue/core/types';+import type {+ QueueBackendPort,+ QueueCounts,+ QueueItemDetailReadModel,+ QueueItemReadModel,+ QueueReadModel,+} from '@features/queue/core/types';import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient } from '@tanstack/react-query';@@ -6,6 +12,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import { queueBackend } from './httpRealtimeQueueBackend';import {+ applyQueueItemStatusChange,invalidateQueueQueries,queueItemDetailOptions,QUEUE_RECENT_WINDOW,@@ -16,7 +23,6 @@ import {import { createQueueItemDTO, createQueueServer } from './queueServer.testing';const createBackend = (): QueueBackendPort => ({- cancelCurrentItem: vi.fn(),cancelQueueItems: vi.fn(),cancelQueueItemsByBatchIds: vi.fn(),cancelBatch: vi.fn(),@@ -228,3 +234,192 @@ describe('queue reads at the transport boundary', () => {expect(status.queue).toMatchObject({ completed: 999, inProgress: 1, total: 1_000 });});});++describe('applyQueueItemStatusChange', () => {+ const PROJECT = 'webv2:p:project-1:q:';+ const item = (+ id: number,+ status: QueueItemReadModel['status'],+ overrides: Partial<QueueItemReadModel> = {}+ ): QueueItemReadModel => ({+ batchId: 'batch-1',+ createdAt: '2026-11-14T00:00:00.000Z',+ id,+ origin: `${PROJECT}run-1`,+ resultImageNames: [],+ sessionId: `session-${id}`,+ status,+ statusSequence: 1,+ updatedAt: '2026-11-14T00:00:00.000Z',+ ...overrides,+ });+ const counts = (overrides: Partial<QueueCounts>): QueueCounts => ({+ canceled: 0,+ completed: 0,+ failed: 0,+ inProgress: 0,+ pending: 0,+ queueId: 'default',+ total: 0,+ waiting: 0,+ ...overrides,+ });+ /** A reading whose counts are its window's unless `queue` says otherwise (more waiting than it lists). */+ const model = (+ overrides: Partial<Omit<QueueReadModel, 'status'>>,+ queue: Partial<QueueCounts> = {}+ ): QueueReadModel => {+ const items = overrides.items ?? [];+ return {+ current: null,+ items,+ next: null,+ scope: { originPrefix: PROJECT },+ ...overrides,+ status: {+ processor: { isProcessing: true, isStarted: true },+ queue: counts({+ inProgress: items.filter((candidate) => candidate.status === 'in_progress').length,+ pending: items.filter((candidate) => candidate.status === 'pending').length,+ ...queue,+ }),+ },+ };+ };++ it("takes only the whole queue's counts, never the owner's own counts an administrator also receives", () => {+ const before = model({ scope: {} }, { userInProgress: 0, userPending: 4 });++ // Another user's item started; the event carries that user's own counts.+ const after = applyQueueItemStatusChange(before, {+ item: item(7, 'in_progress', { origin: 'webv2:p:other:q:run-9', statusSequence: 2, userId: 'someone' }),+ queueCounts: counts({ inProgress: 1, pending: 5, total: 6, userInProgress: 1, userPending: 2 }),+ });++ // An item the model did not list still becomes the current one.+ expect(after.current?.id).toBe(7);+ expect(after.status.queue).toMatchObject({ inProgress: 1, pending: 5, userInProgress: 0, userPending: 4 });+ });++ it("moves a scoped model's known item between its buckets, never taking the whole queue's counts", () => {+ const running = item(1, 'in_progress');+ const before = model({ current: running, items: [running] });+ const wholeQueue = counts({ canceled: 1, inProgress: 3, pending: 9, total: 13 });++ const after = applyQueueItemStatusChange(before, {+ item: { ...running, status: 'canceled', statusSequence: 2 },+ queueCounts: wholeQueue,+ });++ expect(after.current).toBeNull();+ expect(after.status.queue).toMatchObject({ canceled: 1, inProgress: 0, pending: 0 });+ expect(+ applyQueueItemStatusChange(before, {+ item: item(9, 'in_progress', { origin: 'webv2:p:other:q:run-9' }),+ queueCounts: null,+ })+ ).toBe(before);+ });++ it("takes an event's whole-queue counts even when it already shows the item so, as after the viewer's own cancel", () => {+ const running = item(1, 'in_progress', { origin: 'webv2:p:any:q:run' });+ // This tab assumed the cancel; then the server's event says the same.+ const assumed = applyQueueItemStatusChange(model({ current: running, items: [running], scope: {} }), {+ item: { ...running, status: 'canceled', statusSequence: null },+ queueCounts: null,+ });+ expect(assumed.status.queue).toMatchObject({ canceled: 1, inProgress: 0 });++ const confirmed = applyQueueItemStatusChange(assumed, {+ item: { ...running, status: 'canceled', statusSequence: 2 },+ queueCounts: counts({ canceled: 4, inProgress: 2, pending: 6, total: 12 }),+ });++ expect(confirmed.status.queue).toMatchObject({ canceled: 4, inProgress: 2, pending: 6 });+ });++ describe('the window standing in for the next item', () => {+ // Item 2 is next; it starts, and the window's next pending item in run order would stand in.+ const window = () => [item(4, 'pending'), item(3, 'pending'), item(2, 'pending')];+ const start2 = (before: QueueReadModel) =>+ applyQueueItemStatusChange(before, { item: item(2, 'in_progress', { statusSequence: 2 }), queueCounts: null });++ it('stands in when the window holds every pending item the counts report', () => {+ expect(start2(model({ items: window(), next: item(2, 'pending') })).next?.id).toBe(3);+ });++ it('leaves the next item unknown when more wait than the window lists', () => {+ // A long batch: the true next is older than every item the window shows.+ expect(start2(model({ items: window(), next: item(2, 'pending') }, { pending: 40 })).next).toBeNull();+ });++ it('leaves the next item unknown when the counts disagree with the window', () => {+ expect(start2(model({ items: window(), next: item(2, 'pending') }, { pending: 0 })).next).toBeNull();+ expect(start2(model({ items: window(), next: item(2, 'pending') }, { pending: -3 })).next).toBeNull();+ });++ it('leaves it unknown when an item the window does not list starts waiting', () => {+ // The window holds every pending item; then an older item (a retry) waits again, which it does not list.+ const before = model({ items: [item(9, 'pending'), item(8, 'pending')], next: null });++ expect(+ applyQueueItemStatusChange(before, { item: item(5, 'pending', { statusSequence: 3 }), queueCounts: null }).next+ ).toBeNull();+ });+ });++ it('names the next item in the order the server runs them: highest priority first, then oldest', () => {+ // Item 4 was queued at the front of the queue.+ const before = model({+ items: [item(4, 'pending', { priority: 10 }), item(3, 'pending'), item(2, 'pending')],+ next: item(2, 'pending'),+ });++ expect(+ applyQueueItemStatusChange(before, { item: item(2, 'in_progress', { statusSequence: 2 }), queueCounts: null })+ .next?.id+ ).toBe(4);+ });++ it('keeps a read newer than the event, and follows sequences again once a read brings in restarted ones', () => {+ const fetched = model({ current: item(5, 'in_progress', { statusSequence: 3 }), items: [] });++ // A late event from before the read.+ expect(+ applyQueueItemStatusChange(fetched, { item: item(5, 'pending', { statusSequence: 2 }), queueCounts: null })+ ).toBe(fetched);+ // A change this tab assumes, with no sequence, never revives a finished item.+ const finished = model({ items: [item(6, 'completed', { statusSequence: 4 })] });+ expect(+ applyQueueItemStatusChange(finished, { item: item(6, 'canceled', { statusSequence: null }), queueCounts: null })+ ).toBe(finished);+ // An event with a higher sequence does correct it: the item had finished, not been canceled.+ const assumedCanceled = model({ items: [item(6, 'canceled', { statusSequence: 4 })] });+ expect(+ applyQueueItemStatusChange(assumedCanceled, {+ item: item(6, 'completed', { statusSequence: 5 }),+ queueCounts: null,+ }).items[0]?.status+ ).toBe('completed');+ });++ it('keeps the current item while another starts beside it, and hands over to it when the first leaves', () => {+ const before = model({+ current: item(1, 'in_progress'),+ items: [item(3, 'pending'), item(2, 'pending'), item(1, 'in_progress')],+ next: item(2, 'pending'),+ });++ const after = applyQueueItemStatusChange(before, {+ item: item(2, 'in_progress', { statusSequence: 2 }),+ queueCounts: null,+ });++ expect(after.current?.id).toBe(1);+ expect(after.next?.id).toBe(3);+ expect(+ applyQueueItemStatusChange(after, { item: item(1, 'completed', { statusSequence: 2 }), queueCounts: null })+ .current?.id+ ).toBe(2);+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/data/queries.ts b/invokeai/frontend/webv2/src/features/queue/data/queries.tsindex bde291d74f..e6c7e3cdeb 100644--- a/invokeai/frontend/webv2/src/features/queue/data/queries.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/queries.ts@@ -1,5 +1,7 @@import type {QueueBackendPort,+ QueueCounts,+ QueueItemReadModel,QueueItemDetailReadModel,QueueQueryScope,QueueReadModel,@@ -8,7 +10,7 @@ import type {import { isTerminalBackendStatus } from '@features/queue/data/events';import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';-import { queryOptions, type QueryClient } from '@tanstack/react-query';+import { queryOptions, type QueryClient, type QueryKey } from '@tanstack/react-query';export const QUEUE_RECENT_WINDOW = 50;@@ -104,3 +106,239 @@ export const invalidateQueueQueries = async (queryClient: QueryClient): Promise<!isTerminalBackendStatus((state.data as QueueItemDetailReadModel | undefined)?.status ?? 'pending')),});};++/** An item's new status as the server reported it in a status event, or as the viewer's own cancel assumes it. */+export interface QueueItemStatusChange {+ item: QueueItemReadModel;+ /**+ * The whole queue's counts after the change, as a status event carries them; null when unknown. Their own-item+ * fields belong to the item's owner, whoever receives the event (an administrator receives every user's).+ */+ queueCounts: QueueCounts | null;+}++const isFinished = (status: QueueItemReadModel['status']): boolean =>+ status === 'completed' || status === 'failed' || status === 'canceled';++/** The order the server runs pending items in: highest priority first, then oldest first. */+export const compareQueuedItems = (left: QueueItemReadModel, right: QueueItemReadModel): number =>+ (right.priority ?? 0) - (left.priority ?? 0) || left.id - right.id;++/**+ * Whether `change` is newer than the reading the model holds. Both carry a status sequence: the higher one wins, so+ * a late event never undoes a read, and a server that started over (a reset queue reuses item ids) is followed once a+ * read has brought its own sequences in. Without both: a finished item never runs again.+ */+const isNewerReading = (known: QueueItemReadModel, change: QueueItemReadModel): boolean =>+ known.statusSequence !== null &&+ known.statusSequence !== undefined &&+ change.statusSequence !== null &&+ change.statusSequence !== undefined+ ? change.statusSequence > known.statusSequence+ : !isFinished(known.status);++const COUNT_KEYS: Record<QueueItemReadModel['status'], keyof QueueCounts> = {+ canceled: 'canceled',+ completed: 'completed',+ failed: 'failed',+ in_progress: 'inProgress',+ pending: 'pending',+ waiting: 'waiting',+};++/** The whole-queue counts an event carries, over the reading's own counts of the viewer's items. */+const withEventCounts = (counts: QueueCounts, event: QueueCounts): QueueCounts => ({+ ...counts,+ canceled: event.canceled,+ completed: event.completed,+ failed: event.failed,+ inProgress: event.inProgress,+ pending: event.pending,+ total: event.total,+ waiting: event.waiting,+});++/**+ * Moves one item between two count buckets, as a change of an item in the counts' scope does; the viewer's own counts+ * wait for the read, since whose item it is is not known here.+ */+const shiftCounts = (+ counts: QueueCounts,+ from: QueueItemReadModel['status'],+ to: QueueItemReadModel['status']+): QueueCounts =>+ from === to+ ? counts+ : {+ ...counts,+ [COUNT_KEYS[from]]: Math.max(0, (counts[COUNT_KEYS[from]] as number) - 1),+ [COUNT_KEYS[to]]: (counts[COUNT_KEYS[to]] as number) + 1,+ };++/**+ * The read model with one item's status change applied at once, so the current and next items and the counts are+ * right before the read that reconciles them lands. A change outside the model's scope, or not newer than what the+ * model holds, changes no item. Counts: an unscoped model takes an event's whole-queue counts, even when it already+ * shows the item so (as after the viewer's own cancel); otherwise a change to an item the model knows moves it between+ * buckets. The viewer's own counts wait for the read: an event's are the item owner's.+ */+export const applyQueueItemStatusChange = (+ model: QueueReadModel,+ { item, queueCounts }: QueueItemStatusChange+): QueueReadModel => {+ const { originPrefix } = model.scope;++ if (originPrefix && !item.origin?.startsWith(originPrefix)) {+ return model;+ }++ const known = [model.current, model.next, ...model.items].find((candidate) => candidate?.id === item.id) ?? null;+ const eventCounts = queueCounts && !originPrefix ? withEventCounts(model.status.queue, queueCounts) : null;++ if (known && (known.status === item.status || !isNewerReading(known, item))) {+ return eventCounts && known.status === item.status+ ? { ...model, status: { ...model.status, queue: eventCounts } }+ : model;+ }++ const updated: QueueItemReadModel = known+ ? {+ ...known,+ completedAt: item.completedAt ?? known.completedAt,+ errorMessage: item.errorMessage ?? known.errorMessage,+ errorType: item.errorType ?? known.errorType,+ startedAt: item.startedAt ?? known.startedAt,+ status: item.status,+ statusSequence: item.statusSequence ?? known.statusSequence,+ updatedAt: item.updatedAt,+ }+ : item;+ const items = model.items.map((candidate) => (candidate.id === item.id ? updated : candidate));+ const others = items.filter((candidate) => candidate.id !== item.id);+ const current =+ item.status === 'in_progress'+ ? (model.current ?? updated)+ : model.current?.id === item.id+ ? (others.filter((candidate) => candidate.status === 'in_progress').sort(compareQueuedItems)[0] ?? null)+ : model.current;+ const counts =+ eventCounts ?? (known ? shiftCounts(model.status.queue, known.status, item.status) : model.status.queue);+ // Until the read names the server's next item, the window's first pending item in run order stands in, but only+ // when the window holds exactly the pending items the counts report: the window is the newest items, and the true+ // next may be older than all of them (a long batch, or a member's own items among everyone's). An item the window+ // does not list turning pending, or counts that disagree with the window, leave the next item unknown until then.+ const pendingInWindow = items.filter((candidate) => candidate.status === 'pending');+ const standIn =+ (known || item.status !== 'pending') && pendingInWindow.length === counts.pending+ ? (pendingInWindow.sort(compareQueuedItems)[0] ?? null)+ : null;+ const next =+ model.next?.id === item.id+ ? item.status === 'pending'+ ? updated+ : standIn+ : model.next === null && item.status === 'pending'+ ? standIn+ : model.next;++ return { ...model, current, items, next, status: { ...model.status, queue: counts } };+};++/**+ * Guesses awaiting the server's answer. A reported change of the same item to the same status confirms one: it may+ * change nothing in the cache (the item already reads so, and equal data keeps its reference), so the cache alone+ * cannot tell it happened.+ */+const pendingGuesses = new Set<{ client: QueryClient; confirmed: boolean; item: QueueItemReadModel }>();++const readQueueReadModels = (queryClient: QueryClient) =>+ queryClient.getQueriesData<QueueReadModel>({ queryKey: [...queueKeys.all, 'read-model'] });++/**+ * Apply a status change to every loaded read model at once, and to the whole queue's status read, so the current and+ * next items and what runs anywhere are right before the coalesced invalidation's read reconciles them. Only data+ * already in the cache changes.+ */+export const applyQueueItemStatusToReadModels = (queryClient: QueryClient, change: QueueItemStatusChange): void => {+ for (const guess of pendingGuesses) {+ if (guess.client === queryClient && guess.item.id === change.item.id && guess.item.status === change.item.status) {+ guess.confirmed = true;+ }+ }++ const previous = readQueueReadModels(queryClient)+ .flatMap(([, model]) => (model ? [model.current, model.next, ...model.items] : []))+ .find((candidate) => candidate?.id === change.item.id)?.status;++ queryClient.setQueriesData<QueueReadModel>({ queryKey: [...queueKeys.all, 'read-model'] }, (model) =>+ model ? applyQueueItemStatusChange(model, change) : model+ );+ queryClient.setQueryData<QueueStatusReadModel>(queueKeys.status({}), (status) =>+ status+ ? {+ ...status,+ queue: change.queueCounts+ ? withEventCounts(status.queue, change.queueCounts)+ : previous+ ? shiftCounts(status.queue, previous, change.item.status)+ : status.queue,+ }+ : status+ );+};++/** Everything `applyQueueItemStatusToReadModels` writes: every loaded read model and the whole queue's status read. */+const readQueueItemStatusData = (queryClient: QueryClient): Array<[QueryKey, unknown]> => [+ ...readQueueReadModels(queryClient),+ [queueKeys.status({}), queryClient.getQueryData(queueKeys.status({}))],+];++export interface QueueItemStatusGuess {+ /** The request was answered: the guess no longer waits. Apply the answer as any other change. */+ settle: () => void;+ /**+ * The request failed: puts back each read model and the whole queue's status the guess changed, only where nothing+ * changed it since, and nothing once a reported change confirmed the guess. True when one did: the server made the+ * change though its answer was lost.+ */+ revert: () => boolean;+}++/**+ * Applies the viewer's own change at once, ahead of the server (a cancel assumes the item canceled), and returns how+ * to settle it. The caller settles or reverts it once its request ends, whichever way.+ */+export const applyQueueItemStatusGuess = (+ queryClient: QueryClient,+ change: QueueItemStatusChange+): QueueItemStatusGuess => {+ const before = readQueueItemStatusData(queryClient);++ applyQueueItemStatusToReadModels(queryClient, change);++ const written = new Map(+ readQueueItemStatusData(queryClient).map(([queryKey, data]) => [JSON.stringify(queryKey), data])+ );+ const guess = { client: queryClient, confirmed: false, item: change.item };++ pendingGuesses.add(guess);++ return {+ revert: () => {+ pendingGuesses.delete(guess);+ if (guess.confirmed) {+ return true;+ }+ for (const [queryKey, data] of before) {+ const guessed = written.get(JSON.stringify(queryKey));+ if (guessed !== data && queryClient.getQueryData(queryKey) === guessed) {+ queryClient.setQueryData(queryKey, data);+ }+ }+ return false;+ },+ settle: () => {+ pendingGuesses.delete(guess);+ },+ };+};diff --git a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.tsindex 979d81ec30..0417aededc 100644--- a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.test.ts@@ -1,6 +1,12 @@+import type { QueueItemReadModel, QueueReadModel } from '@features/queue/core/types';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient } from '@tanstack/react-query';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { QueueItemStatusChangedEvent } from './events';++import { applyQueueItemStatusToReadModels, queueKeys } from './queries';import { createQueueRealtimeRuntime } from './realtimeRuntime';describe('queue realtime runtime', () => {@@ -20,6 +26,7 @@ describe('queue realtime runtime', () => {return detach;}),};+ const applyStatusChange = vi.fn();const invalidate = vi.fn();const progress = { clear: vi.fn(), clearAll: vi.fn(), set: vi.fn() };const refreshModelCache = vi.fn();@@ -30,6 +37,7 @@ describe('queue realtime runtime', () => {detachers.length = 0;backend.on.mockClear();backend.onConnectionChange.mockClear();+ applyStatusChange.mockReset();invalidate.mockReset();progress.clear.mockReset();progress.clearAll.mockReset();@@ -40,7 +48,7 @@ describe('queue realtime runtime', () => {afterEach(() => vi.useRealTimers());it('attaches once and coalesces a burst of queue events into one invalidation', () => {- const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });+ const runtime = createQueueRealtimeRuntime({ applyStatusChange, backend, invalidate, progress, refreshModelCache });runtime.start();runtime.start();@@ -63,7 +71,7 @@ describe('queue realtime runtime', () => {});it('updates transient progress without invalidating the queue list', () => {- const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });+ const runtime = createQueueRealtimeRuntime({ applyStatusChange, backend, invalidate, progress, refreshModelCache });runtime.start();vi.advanceTimersByTime(50);@@ -86,7 +94,7 @@ describe('queue realtime runtime', () => {});it('forwards the reporting GPU so concurrent sessions can be told apart', () => {- const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });+ const runtime = createQueueRealtimeRuntime({ applyStatusChange, backend, invalidate, progress, refreshModelCache });runtime.start();vi.advanceTimersByTime(50);@@ -109,7 +117,7 @@ describe('queue realtime runtime', () => {});it('keeps completed previews until result hydration and clears failed previews immediately', () => {- const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });+ const runtime = createQueueRealtimeRuntime({ applyStatusChange, backend, invalidate, progress, refreshModelCache });runtime.start();handlers.get('queue_item_status_changed')?.({ item_id: 42, status: 'completed' } as never);@@ -121,7 +129,7 @@ describe('queue realtime runtime', () => {});it('ignores timers and socket callbacks after its account scope expires', () => {- const runtime = createQueueRealtimeRuntime({ backend, invalidate, progress, refreshModelCache });+ const runtime = createQueueRealtimeRuntime({ applyStatusChange, backend, invalidate, progress, refreshModelCache });runtime.start();progress.set.mockClear();@@ -138,4 +146,143 @@ describe('queue realtime runtime', () => {expect(invalidate).not.toHaveBeenCalled();runtime.dispose();});++ describe('live read model', () => {+ const readItem = (id: number, status: QueueItemReadModel['status']): QueueItemReadModel => ({+ batchId: 'batch-1',+ createdAt: '2026-11-14T00:00:00.000Z',+ id,+ origin: 'webv2:p:project-1:q:run-1',+ resultImageNames: [],+ sessionId: `session-${id}`,+ status,+ updatedAt: '2026-11-14T00:00:00.000Z',+ });+ const counts = (inProgress: number, pending: number, completed: number) => ({+ canceled: 0,+ completed,+ failed: 0,+ inProgress,+ pending,+ queueId: 'default',+ total: inProgress + pending + completed,+ waiting: 0,+ });+ const statusEvent = (+ itemId: number,+ status: QueueItemStatusChangedEvent['status'],+ sequence: number,+ queueCounts: ReturnType<typeof counts>+ ) =>+ ({+ batch_id: 'batch-1',+ completed_at: null,+ created_at: '2026-11-14T00:00:00',+ destination: 'gallery',+ error_message: null,+ error_traceback: null,+ error_type: null,+ item_id: itemId,+ origin: 'webv2:p:project-1:q:run-1',+ queue_id: 'default',+ queue_status: {+ canceled: queueCounts.canceled,+ completed: queueCounts.completed,+ failed: queueCounts.failed,+ in_progress: queueCounts.inProgress,+ pending: queueCounts.pending,+ queue_id: 'default',+ total: queueCounts.total,+ user_in_progress: null,+ user_pending: null,+ waiting: 0,+ },+ session_id: `session-${itemId}`,+ started_at: null,+ status,+ status_sequence: sequence,+ timestamp: 0,+ updated_at: '2026-11-14T00:00:01',+ user_id: 'user-1',+ }) as unknown as QueueItemStatusChangedEvent;++ it('moves the current and next items as statuses change, before the reconciling read', () => {+ const client = new QueryClient();+ const scope = {};+ // A batch of three: item 1 running, items 2 and 3 waiting.+ client.setQueryData<QueueReadModel>(queueKeys.readModel(scope), {+ current: readItem(1, 'in_progress'),+ items: [readItem(3, 'pending'), readItem(2, 'pending'), readItem(1, 'in_progress')],+ next: readItem(2, 'pending'),+ scope,+ status: { processor: { isProcessing: true, isStarted: true }, queue: counts(1, 2, 0) },+ });+ const runtime = createQueueRealtimeRuntime({+ applyStatusChange: (change) => applyQueueItemStatusToReadModels(client, change),+ backend,+ invalidate,+ progress,+ refreshModelCache,+ });+ const model = () => client.getQueryData<QueueReadModel>(queueKeys.readModel(scope))!;+ const fire = (event: QueueItemStatusChangedEvent) => handlers.get('queue_item_status_changed')?.(event as never);++ runtime.start();+ vi.advanceTimersByTime(50);+ invalidate.mockClear();++ // Between items: nothing runs, and item 2 is next.+ fire(statusEvent(1, 'completed', 3, counts(0, 2, 1)));+ expect(model().current).toBeNull();+ expect(model().next?.id).toBe(2);+ expect(model().status.queue).toMatchObject({ completed: 1, inProgress: 0, pending: 2 });++ fire(statusEvent(2, 'in_progress', 2, counts(1, 1, 1)));+ expect(model().current).toMatchObject({ id: 2, status: 'in_progress' });+ expect(model().next?.id).toBe(3);+ // The read still follows to reconcile, coalesced.+ expect(invalidate).not.toHaveBeenCalled();+ vi.advanceTimersByTime(50);+ expect(invalidate).toHaveBeenCalledOnce();++ // A replayed older event for item 2 does not move it back to waiting.+ fire(statusEvent(2, 'pending', 1, counts(0, 2, 1)));+ expect(model().current?.id).toBe(2);+ runtime.dispose();+ });++ it("follows a restarted server's lower status sequences once a read has brought them in", () => {+ const client = new QueryClient();+ const scope = {};+ const seed = (items: QueueItemReadModel[]) =>+ client.setQueryData<QueueReadModel>(queueKeys.readModel(scope), {+ current: items.find((item) => item.status === 'in_progress') ?? null,+ items,+ next: items.find((item) => item.status === 'pending') ?? null,+ scope,+ status: { processor: { isProcessing: true, isStarted: true }, queue: counts(0, 1, 0) },+ });+ const runtime = createQueueRealtimeRuntime({+ applyStatusChange: (change) => applyQueueItemStatusToReadModels(client, change),+ backend,+ invalidate,+ progress,+ refreshModelCache,+ });+ const fire = (event: QueueItemStatusChangedEvent) => handlers.get('queue_item_status_changed')?.(event as never);+ const model = () => client.getQueryData<QueueReadModel>(queueKeys.readModel(scope))!;++ runtime.start();+ // Before the restart, item 8 started at its ninth status change.+ seed([{ ...readItem(8, 'pending'), statusSequence: 8 }]);+ fire(statusEvent(8, 'in_progress', 9, counts(1, 0, 0)));+ expect(model().current?.statusSequence).toBe(9);+ // The server came back with a reset queue that reuses the id; the read after reconnecting brings its item in.+ seed([{ ...readItem(8, 'pending'), statusSequence: 1 }]);+ fire(statusEvent(8, 'in_progress', 2, counts(1, 0, 0)));++ expect(model().current).toMatchObject({ id: 8, status: 'in_progress', statusSequence: 2 });+ runtime.dispose();+ });+ });});diff --git a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.tsindex 6c4cdcca07..a376995d7b 100644--- a/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/realtimeRuntime.ts@@ -4,8 +4,10 @@ import type {InvocationStartedEvent,QueueItemStatusChangedEvent,} from '@features/queue/data/events';+import type { QueueItemStatusChange } from '@features/queue/data/queries';import { isTerminalBackendStatus } from '@features/queue/data/events';+import { mapQueueItemStatusChangedEvent } from '@features/queue/data/mappers';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';export interface QueueItemProgressPort {@@ -29,16 +31,19 @@ export interface QueueRealtimeRuntime {}/**- * Own one realtime subscription; coalesce list invalidations while progress frames update transient stores- * directly.+ * Own one realtime subscription. Status changes apply to the read model at once and invalidate it, coalesced, to+ * reconcile; progress frames update transient stores directly.*/export const createQueueRealtimeRuntime = ({+ applyStatusChange,backend,coalesceMs = 50,invalidate,progress,refreshModelCache,}: {+ /** Applies one item's status change to the loaded read models, which fence it against what they already hold. */+ applyStatusChange: (change: QueueItemStatusChange) => void;backend: Pick<QueueBackendPort, 'on' | 'onConnectionChange'>;coalesceMs?: number;invalidate: () => void | Promise<void>;@@ -86,6 +91,10 @@ export const createQueueRealtimeRuntime = ({progress.clear(event.item_id);}+ if (event.queue_status) {+ applyStatusChange(mapQueueItemStatusChangedEvent(event));+ }+scheduleInvalidation();}),backend.on('batch_enqueued', scheduleInvalidation),diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts b/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.tsindex e534aedf8a..3f5fe584c7 100644--- a/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/serverApi.test.ts@@ -8,7 +8,6 @@ const transport = vi.hoisted(() => ({vi.mock('@platform/transport/http', () => transport);import {- cancelCurrentQueueItem,cancelQueueItems,cancelScopedQueueItems,clearFailedQueueItems,@@ -36,11 +35,6 @@ describe('queue command account ownership', () => {resolveFirst: { item_ids: [11], limit: 1, offset: 0 },run: () => clearScopedQueue({ originPrefix: 'webv2:p:a:' }),},- {- name: 'cancel current',- resolveFirst: { item_id: 11, status: 'in_progress' },- run: () => cancelCurrentQueueItem(),- },{name: 'cancel scoped',resolveFirst: { item_ids: [11], limit: 1, offset: 0 },diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts b/invokeai/frontend/webv2/src/features/queue/data/serverApi.tsindex 6c9d76c620..3aa2fe9fb2 100644--- a/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/serverApi.ts@@ -227,19 +227,9 @@ export const cancelAll = (scope: QueueQueryScope = {}, signal?: AbortSignal): Prsignal,});-export const cancelQueueItem = (itemId: number, signal?: AbortSignal): Promise<unknown> =>- apiFetchJson(buildQueueUrl(`i/${itemId}/cancel`), { method: 'PUT', signal });--export const cancelCurrentQueueItem = async (): Promise<void> => {- const owner = captureAccountScope();- const current = await getCurrentQueueItem({}, owner.signal);-- assertAccountScopeCurrent(owner);- if (current) {- await cancelQueueItem(current.item_id, owner.signal);- assertAccountScopeCurrent(owner);- }-};+/** The item as the cancel left it: unchanged, and so not canceled, when it had already finished. */+export const cancelQueueItem = (itemId: number, signal?: AbortSignal): Promise<QueueServerItemDTO> =>+ apiFetchJson<QueueServerItemDTO>(buildQueueUrl(`i/${itemId}/cancel`), { method: 'PUT', signal });/** Cancels the scope in one server-side sweep; `keepCurrent` spares whatever is in progress. */export const cancelScopedQueueItems = async (diff --git a/invokeai/frontend/webv2/src/features/queue/data/serverTypes.ts b/invokeai/frontend/webv2/src/features/queue/data/serverTypes.tsindex b95ebdafb1..b6158fb21b 100644--- a/invokeai/frontend/webv2/src/features/queue/data/serverTypes.ts+++ b/invokeai/frontend/webv2/src/features/queue/data/serverTypes.ts@@ -33,6 +33,7 @@ export interface QueueServerItemDTO {session_id: string;started_at?: string | null;status: QueueItemStatus;+ status_sequence?: number | null;updated_at: string;user_display_name?: string | null;user_email?: string | null;diff --git a/invokeai/frontend/webv2/src/features/queue/publicApi.ts b/invokeai/frontend/webv2/src/features/queue/publicApi.tsindex 7383d96c8c..fe786d44b5 100644--- a/invokeai/frontend/webv2/src/features/queue/publicApi.ts+++ b/invokeai/frontend/webv2/src/features/queue/publicApi.ts@@ -1,4 +1,5 @@import type { QueueFeatureCommands, QueueQueryScope, QueueReadModel } from './core/types';+import type { QueueItemStatusChange } from './data/queries';import type { QueueItemProgressPort, QueueRealtimeRuntime } from './data/realtimeRuntime';import type {QueueHistoryPort,@@ -25,10 +26,7 @@ export const createProductionQueueReceiptAcknowledgements = (store: QueueReceiptexport const queueCommands: QueueFeatureCommands = {cancelBatch: queueBackend.cancelBatch,- cancelCurrentItem: queueBackend.cancelCurrentItem,- cancelItem: async (itemId) => {- await queueBackend.cancelItem(itemId);- },+ cancelItem: queueBackend.cancelItem,cancelScopedItems: queueBackend.cancelScopedItems,clearFailedItems: queueBackend.clearFailedItems,clearFinishedItems: queueBackend.clearFinishedItems,@@ -48,17 +46,26 @@ export const getQueueReadModelOptions = (scope: QueueQueryScope, onRead?: (modelqueueReadModelOptions(queueBackend, scope, onRead);export const createProductionQueueRealtimeRuntime = ({+ applyStatusChange,coalesceMs,invalidate,progress,refreshModelCache,}: {+ applyStatusChange: (change: QueueItemStatusChange) => void;coalesceMs?: number;invalidate: () => void | Promise<void>;progress: QueueItemProgressPort;refreshModelCache: () => void | Promise<void>;}): QueueRealtimeRuntime =>- createQueueRealtimeRuntime({ backend: queueBackend, coalesceMs, invalidate, progress, refreshModelCache });+ createQueueRealtimeRuntime({+ applyStatusChange,+ backend: queueBackend,+ coalesceMs,+ invalidate,+ progress,+ refreshModelCache,+ });export const createProductionQueueRuntime = ({destinations,diff --git a/invokeai/frontend/webv2/src/features/queue/react.ts b/invokeai/frontend/webv2/src/features/queue/react.tsindex 1bec99c61b..b8cd6d9722 100644--- a/invokeai/frontend/webv2/src/features/queue/react.ts+++ b/invokeai/frontend/webv2/src/features/queue/react.ts@@ -5,13 +5,13 @@ export {useActiveProgressTarget,useActiveProgressTargets,useFollowedProgressTargets,+ useFramedProgressTargets,} from './data/activeProgressTargetStore';export { type ItemProgress, useActiveProgressItemIds, useItemProgress } from './data/itemProgressStore';export {consumeQueueItemSwapProgressImage,type LatestProgressImageSnapshot,useProgressImage,- useQueueItemBridgeProgressImage,useQueueItemProgressImage,useQueueItemSwapProgressImage,} from './data/progressImageStore';diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.tsindex eefd69402e..24d81b8638 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts@@ -15,6 +15,7 @@ import { activeProgressTargetStore } from '@features/queue/data/activeProgressTaimport { buildQueueItemOrigin } from '@features/queue/data/events';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';+import { getCanvasStagingSlots } from '@workbench/canvasStagingView';import { createInitialWorkbenchState, type WorkbenchAction, workbenchReducer } from '@workbench/workbenchState.testing';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -60,7 +61,6 @@ const createPendingQueueItem = (): QueueItem => ({});const createTestBackend = (overrides: Partial<QueueBackendPort> = {}): QueueBackendPort => ({- cancelCurrentItem: vi.fn(),cancelItem: vi.fn(),cancelQueueItems: vi.fn(),cancelQueueItemsByBatchIds: vi.fn(),@@ -97,6 +97,7 @@ const createTestBackend = (overrides: Partial<QueueBackendPort> = {}): QueueBackconst createTestCommands = (overrides: Partial<QueueHistoryCommands> = {}): QueueHistoryCommands => ({markBackendCancelled: vi.fn(),+ noteFirstProgressFrame: vi.fn(),markBackendSubmitted: vi.fn(),recordSubmissionRetry: vi.fn(),setCancellationPending: vi.fn(),@@ -457,7 +458,6 @@ describe('queue runtime', () => {},]);const backend: QueueBackendPort = {- cancelCurrentItem: vi.fn(),cancelItem: vi.fn(),cancelQueueItems: vi.fn(),cancelQueueItemsByBatchIds: vi.fn(),@@ -492,6 +492,7 @@ describe('queue runtime', () => {};const commands: QueueHistoryCommands = {markBackendCancelled: vi.fn(),+ noteFirstProgressFrame: vi.fn(),markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {queueItem.backendBatchId = backendBatchId;queueItem.backendItemIds = backendItemIds;@@ -3108,7 +3109,6 @@ describe('queue runtime video board routing', () => {}const project = { id: 'project-1', queue: { items: [queueItem] } };const backend: QueueBackendPort = {- cancelCurrentItem: vi.fn(),cancelItem: vi.fn(),cancelQueueItems: vi.fn(),cancelQueueItemsByBatchIds: vi.fn(),@@ -3169,6 +3169,7 @@ describe('queue runtime video board routing', () => {};const commands: QueueHistoryCommands = {markBackendCancelled: vi.fn(),+ noteFirstProgressFrame: vi.fn(),markBackendSubmitted: ({ backendBatchId, backendItemIds }) => {queueItem.backendBatchId = backendBatchId;queueItem.backendItemIds = backendItemIds;@@ -3936,6 +3937,123 @@ describe('queue runtime retries', () => {await runtime.dispose();});+ it('moves Canvas staging on to the next image of a run on its first frame, not when it starts', async () => {+ let state = createInitialWorkbenchState();+ const projectId = state.activeProjectId;+ const { canvas } = state.projects.find((project) => project.id === projectId)!;+ const queueItem: WorkbenchQueueItem = {+ ...createPendingQueueItem(),+ backendItemIds: [41, 42],+ snapshot: {+ ...createPendingQueueItem().snapshot,+ canvas: {+ document: { bbox: { ...canvas.document.bbox }, height: canvas.document.height, width: canvas.document.width },+ documentRevision: canvas.documentRevision,+ },+ presentation: { batchCount: 2, height: 64, width: 64 },+ },+ status: 'running',+ };+ state = {+ ...state,+ projects: state.projects.map((project) =>+ project.id === projectId ? { ...project, queue: { items: [queueItem] } } : project+ ),+ };+ const listeners = new Set<() => void>();+ const dispatch = (action: WorkbenchAction): void => {+ state = workbenchReducer(state, action);+ listeners.forEach((listener) => listener());+ };+ dispatch({+ mutation: { mode: 'progress', type: 'setCanvasStagingAutoSwitch' },+ projectId,+ type: 'applyCanvasProjectMutation',+ });+ const origin = buildQueueItemOrigin(queueItem.id, projectId);+ const handlers = new Map<string, Set<(payload: never) => void>>();+ const emit = (event: string, payload: unknown) =>+ handlers.get(event)?.forEach((handler) => handler(payload as never));+ const backend = createTestBackend({+ getItem: vi.fn((id: number) =>+ Promise.resolve({+ batchId: 'batch',+ id,+ origin,+ status: id === 41 ? ('in_progress' as const) : ('pending' as const),+ })+ ),+ getResultImages: vi.fn((id: number) =>+ Promise.resolve([+ {+ height: 64,+ imageName: `result-${id}.png`,+ imageUrl: `/result-${id}.png`,+ queuedAt: queueItem.snapshot.submittedAt,+ sourceQueueItemId: queueItem.id,+ thumbnailUrl: `/result-${id}.png`,+ width: 64,+ },+ ])+ ),+ on: vi.fn((event: string, handler: (payload: never) => void) => {+ const eventHandlers = handlers.get(event) ?? new Set();+ eventHandlers.add(handler);+ handlers.set(event, eventHandlers);+ return () => eventHandlers.delete(handler);+ }),+ });+ const runtime = createQueueRuntime({+ ...runtimeServices,+ backend,+ history: {+ commands: createTestCommands({+ markBackendCancelled: (payload) => dispatch({ ...payload, type: 'markQueueItemBackendCancelled' }),+ noteFirstProgressFrame: (payload) => dispatch({ ...payload, type: 'noteQueueItemFirstProgressFrame' }),+ routePartialResults: (payload) => dispatch({ ...payload, type: 'routeQueueItemPartialResults' }),+ routeResults: (payload) => dispatch({ ...payload, type: 'routeQueueItemResults' }),+ setStatus: (payload) => dispatch({ ...payload, type: 'setQueueItemStatus' }),+ }),+ getSnapshot: () => ({ connectionStatus: 'connected', isHydrated: true, projects: state.projects }),+ listStagedResults: () => getQueueStagedResults(state.projects),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ });+ const selectedSlot = () => {+ const project = state.projects.find((candidate) => candidate.id === projectId)!;+ const slot = getCanvasStagingSlots(project.canvas, project.queue.items)[+ project.canvas.stagingArea.selectedImageIndex+ ];+ return slot?.kind === 'candidate' ? slot.imageName : `placeholder ${slot?.itemIndex}`;+ };+ const progress = (itemId: number, withFrame: boolean) => ({+ ...completedEvent(itemId, origin, 'canvas'),+ image: withFrame ? { dataURL: `data:image/png;base64,${itemId}`, height: 64, width: 64 } : null,+ invocation_source_id: 'denoise',+ message: withFrame ? 'Denoising' : 'Loading model',+ percentage: withFrame ? 0.5 : null,+ revision: withFrame ? 1 : null,+ });++ runtime.start();+ await vi.waitFor(() => expect(backend.getItem).toHaveBeenCalledTimes(2));+ emit('queue_item_status_changed', completedEvent(41, origin, 'canvas'));+ await vi.waitFor(() => expect(selectedSlot()).toBe('result-41.png'));++ // The second image starts and loads its model: the first one's result stays on the canvas.+ emit('queue_item_status_changed', { ...completedEvent(42, origin, 'canvas'), status: 'in_progress' });+ emit('invocation_progress', progress(42, false));+ expect(selectedSlot()).toBe('result-41.png');++ emit('invocation_progress', progress(42, true));+ expect(selectedSlot()).toBe('placeholder 2');++ await runtime.dispose();+ });+it("stages what another tab's Workflow rerun produced, and nothing for a rerun that failed", async () => {const queueItem: QueueItem = { ...createPendingQueueItem(), backendItemIds: [7], status: 'completed' };const image = (imageName: string, createdAt: string, isIntermediate = false) =>diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.tsindex 9479d1e0d1..b708b54fd6 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts@@ -101,6 +101,8 @@ export interface QueueHistoryCommands {projectId: string;queueItemId: string;}): void;+ /** A slot of a run showed its first progress frame of its own; Canvas staging following progress moves to it. */+ noteFirstProgressFrame(payload: { itemIndex: number; projectId: string; queueItemId: string }): void;/** Record the latest failed submission of a run the backend has not accepted; acceptance or an ending clears it. */recordSubmissionRetry(payload: { projectId: string; queueItemId: string; retry: QueueSubmissionRetry }): void;setCancellationPending(payload: { pending: boolean; projectId: string; queueItemId: string }): void;@@ -1556,6 +1558,17 @@ export const createQueueRuntime = ({return scheduleResultRoute(target.project.id, target.queueItem, backendItemId, attempt);}},+ onFirstProgressFrame: ({ itemIndex, queueItemId }) => {+ if (!isActive()) {+ return;+ }++ const target = getRouteTarget(history, queueItemId);++ if (target?.queueItem?.snapshot.destination === 'canvas') {+ commands.noteFirstProgressFrame({ itemIndex, projectId: target.project.id, queueItemId });+ }+ },onGalleryRefresh: () => {if (isActive()) {commands.refreshBackendData();diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.tsindex f8bc6c8a36..dc0a63df43 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.test.ts@@ -189,6 +189,7 @@ const workflowRequest: QueueEnqueueWorkflowRequest = {interface Harness {activeProgressTarget: {clear: ReturnType<typeof vi.fn>;+ markFramed: ReturnType<typeof vi.fn>;set: ReturnType<typeof vi.fn>;settle: ReturnType<typeof vi.fn>;};@@ -268,7 +269,12 @@ const createHarness = (options: { galleryRefreshCoalesceMs?: number } = {}): Harstarted: vi.fn(),};const progressImage = { bindSwapImages: vi.fn(), clear: vi.fn(), clearHeld: vi.fn(), hold: vi.fn(), set: vi.fn() };- const activeProgressTarget = { clear: vi.fn(), set: vi.fn(), settle: vi.fn() } satisfies ActiveProgressTargetSink;+ const activeProgressTarget = {+ clear: vi.fn(),+ markFramed: vi.fn(),+ set: vi.fn(),+ settle: vi.fn(),+ } satisfies ActiveProgressTargetSink;const hub = createSocketHub({ createSocket: () => socket });hub.connect();@@ -643,6 +649,74 @@ describe('queueCoordinator', () => {expect(harness.activeProgressTarget.set).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });expect(harness.progressImage.set).not.toHaveBeenCalled();+ expect(harness.activeProgressTarget.markFramed).not.toHaveBeenCalled();+ });++ it("signals each slot's first frame of its own once, after the frame is stored", async () => {+ harness.callbacks.onFirstProgressFrame = vi.fn(() => {+ // Live surfaces follow the slot from here; its frame must already be there to show.+ expect(harness.progressImage.set).toHaveBeenCalled();+ });+ harness.coordinator.connect();+ harness.api.enqueueGenerate.mockResolvedValueOnce({+ batchId: 'batch-1',+ enqueued: 2,+ itemIds: [1, 2],+ requested: 2,+ });+ await harness.coordinator.submitGenerate('local-1', generateRequest);+ const frame = (itemId: number, revision: number) => ({+ ...createStatusEvent({ item_id: itemId }),+ image: { dataURL: `data:image/png;base64,${itemId}-${revision}`, height: 32, width: 64 },+ message: 'Denoising',+ percentage: 0.5,+ revision,+ });++ // Model loading and text encoding report progress without a frame.+ harness.socket.fire('invocation_progress', {+ ...createStatusEvent({ item_id: 1 }),+ message: 'Loading',+ percentage: null,+ });+ expect(harness.callbacks.onFirstProgressFrame).not.toHaveBeenCalled();++ harness.socket.fire('invocation_progress', frame(1, 1));+ harness.socket.fire('invocation_progress', frame(1, 2));+ harness.socket.fire('invocation_progress', frame(2, 1));++ expect(harness.callbacks.onFirstProgressFrame).toHaveBeenCalledTimes(2);+ expect(harness.callbacks.onFirstProgressFrame).toHaveBeenNthCalledWith(1, { itemIndex: 1, queueItemId: 'local-1' });+ expect(harness.callbacks.onFirstProgressFrame).toHaveBeenNthCalledWith(2, { itemIndex: 2, queueItemId: 'local-1' });+ expect(harness.activeProgressTarget.markFramed.mock.calls).toEqual([+ [{ itemIndex: 1, queueItemId: 'local-1' }],+ [{ itemIndex: 2, queueItemId: 'local-1' }],+ ]);+ });++ it('signals a first frame again for a slot sent back to the queue, whose frames start a new leg', async () => {+ harness.callbacks.onFirstProgressFrame = vi.fn();+ harness.coordinator.connect();+ await harness.coordinator.submitGenerate('local-1', generateRequest);+ const frame = (session: string) => ({+ ...createStatusEvent({ item_id: 1, session_id: session }),+ image: { dataURL: `data:image/png;base64,${session}`, height: 32, width: 64 },+ message: 'Denoising',+ percentage: 0.5,+ revision: 1,+ });++ harness.socket.fire('invocation_progress', frame('first-leg'));+ // Requeued (a server restart puts it back): the slot is cleared and shows nothing of its own until its next frame.+ harness.socket.fire(+ 'queue_item_status_changed',+ createStatusEvent({ item_id: 1, status: 'pending', status_sequence: 2 })+ );+ expect(harness.activeProgressTarget.clear).toHaveBeenCalledWith({ itemIndex: 1, queueItemId: 'local-1' });+ harness.socket.fire('invocation_progress', frame('second-leg'));++ expect(harness.callbacks.onFirstProgressFrame).toHaveBeenCalledTimes(2);+ expect(harness.activeProgressTarget.markFramed).toHaveBeenCalledTimes(2);});it('keeps the followed slot and its last frame across a connection drop', async () => {diff --git a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.tsindex 3425edfa22..95051a8a8b 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime/coordinator.ts@@ -4,6 +4,7 @@ import type {QueueEnqueueGenerateRequest,QueueEnqueueResult,QueueEnqueueWorkflowRequest,+ QueueItemProgressTarget,QueueResultImage,QueueResultImageOptions,QueueRunOrigin,@@ -101,6 +102,11 @@ export interface QueueCoordinatorCallbacks {onBackendItemComplete?(localQueueItemId: string, backendItemId: number): void | Promise<void>;/** Fired when one backend item in a local batch is canceled. */onBackendItemCancelled?(localQueueItemId: string, backendItemId: number): void;+ /**+ * Fired once per slot when its first progress frame of its own arrives: what live surfaces wait for before they+ * leave the previous slot's result.+ */+ onFirstProgressFrame?(target: QueueItemProgressTarget): void;/** Coalesced signal that completed generations may have added gallery images. */onGalleryRefresh(): void;}@@ -220,6 +226,8 @@ interface RunProgressState {interface WaitState {frameGates: Map<number, { revision: number | null; sessionId: string }>;+ /** The slot has shown a frame of its own in its current leg. */+ hasOwnFrame: boolean;hasWorkflowCall: boolean;localQueueItemId: string;origin: QueueRunOrigin | null;@@ -623,8 +631,7 @@ export const createQueueCoordinator = (}if (outcome.status === 'completed') {- // Hold the frame before routing so decoded results and the next frameless slot can replace it without- // blanking.+ // Hold the frame before routing so the decoding result can replace it without blanking.progressImage.hold(progressTarget);const routingPromise = callbacks.onBackendItemComplete?.(wait.localQueueItemId, backendItemId);@@ -659,6 +666,7 @@ export const createQueueCoordinator = (if (queueItem.status === 'in_progress' || (queueItem.status === 'waiting' && wait.hasWorkflowCall)) {activeProgressTarget.set(target);} else if ((queueItem.status === 'pending' || queueItem.status === 'waiting') && !wait.hasWorkflowCall) {+ wait.hasOwnFrame = false;activeProgressTarget.clear(target);}}@@ -687,7 +695,7 @@ export const createQueueCoordinator = (}return new Promise<TerminalOutcome>((settle) => {- waits.set(backendItemId, { frameGates: new Map(), ...context, localQueueItemId, settle });+ waits.set(backendItemId, { frameGates: new Map(), hasOwnFrame: false, ...context, localQueueItemId, settle });replayNodeEvents(backendItemId);replayProgressEvent(backendItemId);});@@ -829,6 +837,7 @@ export const createQueueCoordinator = (// their revisions start over.if (event.status === 'pending' || event.status === 'waiting') {if (wait && !wait.hasWorkflowCall) {+ wait.hasOwnFrame = false;activeProgressTarget.clear(getProgressImageTarget(wait.localQueueItemId, event.item_id));}wait?.frameGates.clear();@@ -932,6 +941,12 @@ export const createQueueCoordinator = (if (event.image?.dataURL) {progressImage.set({ dataUrl: event.image.dataURL, height: event.image.height, width: event.image.width }, target);++ if (!wait.hasOwnFrame) {+ wait.hasOwnFrame = true;+ activeProgressTarget.markFramed(target);+ callbacks.onFirstProgressFrame?.(target);+ }}const state = runProgress.get(wait.localQueueItemId);diff --git a/invokeai/frontend/webv2/src/features/queue/runtimeRecovery.browser.test.ts b/invokeai/frontend/webv2/src/features/queue/runtimeRecovery.browser.test.tsindex a5932a0a0b..7695f03e3d 100644--- a/invokeai/frontend/webv2/src/features/queue/runtimeRecovery.browser.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtimeRecovery.browser.test.ts@@ -32,6 +32,7 @@ const openCanvasRuntime = (claimItemDelivery: QueueBackendPort['claimItemDeliver};const commands: QueueHistoryCommands = {markBackendCancelled: vi.fn(),+ noteFirstProgressFrame: vi.fn(),markBackendSubmitted: vi.fn(),recordError: vi.fn(),recordSubmissionRetry: vi.fn(),@@ -52,7 +53,6 @@ const openCanvasRuntime = (claimItemDelivery: QueueBackendPort['claimItemDeliver};const backend: QueueBackendPort = {cancelBatch: vi.fn(),- cancelCurrentItem: vi.fn(),cancelItem: vi.fn(),cancelQueueItems: vi.fn(),cancelQueueItemsByBatchIds: vi.fn(),diff --git a/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.browser.test.tsxindex 46f738192d..b1008db90c 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/LocalRunList.browser.test.tsx@@ -16,7 +16,7 @@ vi.mock('@features/queue/publicApi', () => ({queueCommands: {},}));-import { createTestLocalRun, createTestQueueUiAdapter } from './queueUiAdapter.testing';+import { createTestLocalRun, createTestQueueUiAdapter, createTestQueueWidgetRuntime } from './queueUiAdapter.testing';import { QueueUiProvider, type QueueLocalRun, type QueueUiAdapter } from './QueueUiContext';import { QueueWidgetView } from './QueueWidgetView';@@ -78,7 +78,7 @@ const render = async (overrides: Partial<QueueUiAdapter>, listed?: number) => {<ChakraProvider value={system}><QueryClientProvider client={client}><QueueUiProvider adapter={adapter}>- <QueueWidgetView region="right" />+ <QueueWidgetView region="right" runtime={createTestQueueWidgetRuntime()} /></QueueUiProvider></QueryClientProvider></ChakraProvider>diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsxindex 8f266b942d..fe91139aa0 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueDataRuntime.tsx@@ -1,6 +1,6 @@import { refreshGenerationDevices } from '@features/queue/data/generationDevicesStore';import { itemProgressStore } from '@features/queue/data/itemProgressStore';-import { invalidateQueueQueries } from '@features/queue/data/queries';+import { applyQueueItemStatusToReadModels, invalidateQueueQueries } from '@features/queue/data/queries';import { createProductionQueueRealtimeRuntime } from '@features/queue/publicApi';import { queryClient } from '@platform/query/client';import { useMountEffect } from '@platform/react/useMountEffect';@@ -16,6 +16,7 @@ import { useQueueUi } from './QueueUiContext';export const attachQueueDataRuntime = (): (() => void) => {const runtime = createProductionQueueRealtimeRuntime({+ applyStatusChange: (change) => applyQueueItemStatusToReadModels(queryClient, change),invalidate: () => invalidateQueueQueries(queryClient),progress: itemProgressStore,refreshModelCache: refreshWatchedModelCacheStats,diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsxindex 93e8991c08..9db1be2f27 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueFilterTabs.tsx@@ -12,7 +12,8 @@ export const QUEUE_FILTER_TABS_ID = 'queue-filter';/*** The queue's counts are its filters: each status tab carries how many items the scope holds in it, failures tinted- * while there are any (All · Active · Done · Failed · Canceled).+ * while there are any (All · Active · Done · Failed · Canceled). A narrow widget scrolls the strip rather than clipping+ * labels or counts.*/export const QueueFilterTabs = ({localRunCount,@@ -55,6 +56,7 @@ export const QueueFilterTabs = ({return (<SegmentTabsisCompact+ isScrollableactiveId={value}ariaLabel={t('widgets.queue.filterRecentByStatus')}idBase={QUEUE_FILTER_TABS_ID}diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.browser.test.tsxindex d7cdc83484..af13cf921b 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.browser.test.tsx@@ -157,7 +157,7 @@ describe('QueueHeaderActions', () => {const trigger = (await render())!;expect(host.querySelectorAll('button')).toHaveLength(1);- expect(trigger.getAttribute('aria-label')).toBe('widgets.queue.cache.title');+ expect(trigger.textContent).toBe('widgets.queue.cache.title');expect(trigger.getAttribute('aria-haspopup')).toBe('dialog');await act(() => userEvent.click(trigger));diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsxindex 1e89f72660..4aade355a7 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueHeaderActions.tsx@@ -15,11 +15,10 @@ import { formatCount } from '@platform/i18n/languages';import { queryClient } from '@platform/query/client';import { useMountEffect } from '@platform/react/useMountEffect';import { getApiErrorMessage } from '@platform/transport/http';-import { Button, IconButton } from '@platform/ui/Button';+import { Button } from '@platform/ui/Button';import { PopoverContent } from '@platform/ui/Popover';-import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';import { useQuery } from '@tanstack/react-query';-import { DatabaseIcon } from 'lucide-react';+import { DatabaseZapIcon } from 'lucide-react';import { useCallback, useId, useMemo, useRef, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';@@ -52,23 +51,21 @@ export const QueueHeaderActions = () => {const CachePopover = () => {const { t } = useTranslation();- const triggerIds = useTooltipTriggerIds();const titleId = useId();// Zag names the dialog by its title only when the title exists at mount; lazy content mounts later, so name it here.- const ids = useMemo(() => ({ ...triggerIds, title: titleId }), [titleId, triggerIds]);+ const ids = useMemo(() => ({ title: titleId }), [titleId]);const contentRef = useRef<HTMLDivElement>(null);// Focus lands on the panel, not on its first control: that is a Clear button.const getInitialFocus = useCallback(() => contentRef.current, []);return (<Popover.Root ids={ids} initialFocusEl={getInitialFocus} lazyMount positioning={POSITIONING} unmountOnExit>- <Tooltip content={t('widgets.queue.cache.title')} ids={triggerIds}>- <Popover.Trigger asChild>- <IconButton aria-label={t('widgets.queue.cache.title')} color="fg.muted" size="sm" variant="ghost">- <Icon as={DatabaseIcon} boxSize="3.5" />- </IconButton>- </Popover.Trigger>- </Tooltip>+ <Popover.Trigger asChild>+ <Button color="fg.muted" size="sm" variant="ghost">+ <Icon as={DatabaseZapIcon} boxSize="3.5" />+ {t('widgets.queue.cache.title')}+ </Button>+ </Popover.Trigger><Portal><Popover.Positioner><PopoverContent ref={contentRef} aria-labelledby={titleId} p="3" w="21rem">diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.browser.test.tsxindex cb010934a6..80e986749e 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.browser.test.tsx@@ -3,6 +3,7 @@ import type { QueueItemReadModel } from '@features/queue/core/types';import { ChakraProvider } from '@chakra-ui/react';import { buildQueueItemOrigin } from '@features/queue/data/events';+import { createMenuPartLoader, MenuActionItem } from '@platform/ui/Menu';import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -265,4 +266,81 @@ describe('QueueItemRow', () => {await render(adapter({ canManageItem: () => false }), item({ id: 14, status: 'canceled' }));expect(host.querySelector('button[aria-label="widgets.queue.retryItem"]')).toBeNull();});++ const openMenu = async () => {+ await act(() =>+ primary().dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 20 })+ )+ );++ return vi.waitFor(() => {+ const open = document.querySelector<HTMLElement>('[role="menu"]');+ expect(open).not.toBeNull();+ return open!;+ });+ };+ const RecallEntries = () => <MenuActionItem label="Recall entries" value="recall" onSelect={() => undefined} />;++ it('opens its menu at once and lets Escape close it while the recall entries still load', async () => {+ const itemRecallMenuGroup = createMenuPartLoader(() => new Promise<() => null>(() => {}));+ await render(adapter({ itemRecallMenuGroup }), item());++ const menu = await openMenu();+ // Only menu items while loading: an unavailable one in the entries' place.+ const items = [...menu.children].filter((child) => child.getAttribute('role') !== 'presentation');+ expect(items.map((child) => [child.getAttribute('role'), child.getAttribute('aria-disabled')])).toEqual([+ ['menuitem', 'true'],+ ]);+ expect(menu.textContent).toContain('common.loading');+ expect(menu.getAttribute('aria-busy')).toBe('true');++ await act(() => menu.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' })));+ await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());+ });++ it('opens on the recall entries’ first frame once intent has loaded them', async () => {+ const importer = vi.fn(() => Promise.resolve(RecallEntries));+ await render(adapter({ itemRecallMenuGroup: createMenuPartLoader(importer) }), item());+ await act(async () => {+ primary().dispatchEvent(new FocusEvent('focusin', { bubbles: true }));+ await new Promise(requestAnimationFrame);+ });+ expect(importer).toHaveBeenCalledOnce();+ // Records whether the placeholder ever mounts while the menu opens.+ const placeholders: Node[] = [];+ const observer = new MutationObserver(() =>+ placeholders.push(...document.querySelectorAll('[data-value="menu-part-placeholder"]'))+ );+ observer.observe(document.body, { childList: true, subtree: true });++ const menu = await openMenu();+ observer.disconnect();++ expect(placeholders).toEqual([]);+ expect(menu.textContent).toContain('Recall entries');+ expect(menu.getAttribute('aria-busy')).toBe('false');+ expect(importer).toHaveBeenCalledOnce();+ });++ it('says the recall entries could not load, without unmounting the queue, and loads them on a later open', async () => {+ const importer = vi+ .fn<() => Promise<typeof RecallEntries>>()+ .mockRejectedValueOnce(new TypeError('Failed to fetch dynamically imported module'))+ .mockResolvedValue(RecallEntries);+ await render(adapter({ itemRecallMenuGroup: createMenuPartLoader(importer) }), item());++ let menu = await openMenu();+ await vi.waitFor(() => expect(menu.textContent).toContain('common.menuPartLoadFailed'));+ expect(menu.querySelector('[role="menuitem"]')?.getAttribute('aria-disabled')).toBe('true');+ expect(menu.getAttribute('aria-busy')).toBe('false');+ expect(primary().isConnected).toBe(true);++ await act(() => menu.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' })));+ await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());+ menu = await openMenu();++ await vi.waitFor(() => expect(menu.textContent).toContain('Recall entries'));+ expect(importer).toHaveBeenCalledTimes(2);+ });});diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.tsxindex 3d16c4c887..9f3185ee47 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueItemRow.tsx@@ -1,14 +1,16 @@/* eslint-disable react-perf/jsx-no-jsx-as-prop */import type { QueueItemReadModel } from '@features/queue/core/types';-import { Box, HStack, Icon, Text } from '@chakra-ui/react';+import { Box, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { getResultImageName } from '@features/queue/core/generationMeta';import { getQueueItemReadModelLabel } from '@features/queue/core/itemLabels';import { parseQueueItemOriginProjectId } from '@features/queue/data/events';import { useItemProgress } from '@features/queue/data/itemProgressStore';-import { ListItem } from '@platform/ui/list/ListItem';+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';+import { ListItem, type ListContextMenuAnchor } from '@platform/ui/list/ListItem';+import { MenuContent, MenuPartPlaceholder, useContextMenu, useMenuPart } from '@platform/ui/Menu';import { ChevronRightIcon } from 'lucide-react';-import { memo, useCallback, useMemo, useRef, useState } from 'react';+import { memo, useCallback, useMemo, useRef, useState, type MouseEvent } from 'react';import { useTranslation } from 'react-i18next';import { CancelQueueItemButton } from './CancelQueueItemButton';@@ -29,11 +31,34 @@ const CHEVRON_OPEN = { transform: 'rotate(90deg)' } as const;export const QueueItemRow = memo(({ item, revealRequest }: { item: QueueItemReadModel; revealRequest?: QueueItemRevealRequest | null }) => {const { t } = useTranslation();- const { canManageItem, canViewItemDetails, isProjectOpen, preloadItemActions } = useQueueUi();+ const { canManageItem, canViewItemDetails, isProjectOpen, itemRecallMenuGroup, preloadItemActions } = useQueueUi();const [expanded, setExpanded] = useState(false);- const toggle = useCallback(() => setExpanded((open) => !open), []);- // Warm the actions chunk on intent so the first expand has nothing to wait for.- const preload = useCallback(() => preloadItemActions?.(), [preloadItemActions]);+ // Safari and Firefox on macOS do not focus a clicked button; the row's A key acts on the focused row. A click must+ // not show the keyboard ring: `focusVisible: false` says so where supported (Firefox), and elsewhere script focus+ // matches :focus-visible only when the element focus left from did.+ const toggle = useCallback((event: MouseEvent<HTMLButtonElement>) => {+ if (document.activeElement !== event.currentTarget) {+ event.currentTarget.focus({ focusVisible: false, preventScroll: true });+ }+ setExpanded((open) => !open);+ }, []);+ const menu = useContextMenu();+ // Kept through the exit animation: the anchor clears the moment the menu closes.+ const { release: releaseMenu, value: shownMenuAnchor } = useExitRetainedValue(menu.anchor);+ // Warm the actions and the menu's recall entries on intent, so the first expand or menu has nothing to wait for.+ const preload = useCallback(() => {+ preloadItemActions?.();+ itemRecallMenuGroup.load();+ }, [itemRecallMenuGroup, preloadItemActions]);+ // The keyboard's menu key and assistive technology open the menu without intent first.+ const { open: openContextMenu } = menu;+ const openMenu = useCallback(+ (anchor: ListContextMenuAnchor) => {+ itemRecallMenuGroup.load();+ openContextMenu(anchor);+ },+ [itemRecallMenuGroup, openContextMenu]+ );const consumedRevealRequestIdRef = useRef<number | null>(null);const duration = formatDuration(item.startedAt, item.completedAt);const age = formatCompactAge(item.completedAt ?? item.createdAt);@@ -82,7 +107,16 @@ export const QueueItemRow = memo(// The card is the list item: progress and details belong to the row, not to the list.return (- <Box ref={consumeReveal} borderColor={borderColor} borderWidth={1} overflow="hidden" role="listitem" rounded="md">+ <Box+ ref={consumeReveal}+ borderColor={borderColor}+ borderWidth={1}+ // The `queue.recallAll` hotkey claims its key only on rows that offer recall.+ data-queue-recall-item={canExpand ? item.id : undefined}+ overflow="hidden"+ role="listitem"+ rounded="md"+ ><ListItemactions={isCancellable ? (@@ -111,6 +145,7 @@ export const QueueItemRow = memo(</HStack>}isExpanded={canExpand ? expanded : undefined}+ isMenuOpen={menu.anchor !== null}leading={<QueueItemThumbnail boxSize="8" imageName={resultImageName} liveImage={liveImage} />}role="presentation"title={itemLabel || t('widgets.queue.itemTitle', { id: item.id })}@@ -124,9 +159,20 @@ export const QueueItemRow = memo(/>) : undefined}+ onContextMenu={canExpand ? openMenu : undefined}onIntent={canExpand ? preload : undefined}onPress={canExpand ? toggle : undefined}/>+ {shownMenuAnchor ? (+ <QueueItemContextMenu+ anchor={shownMenuAnchor}+ item={item}+ open={menu.anchor !== null}+ onClose={menu.close}+ onExitComplete={releaseMenu}+ onRequestDismiss={menu.onRequestDismiss}+ />+ ) : null}{item.status === 'in_progress' ? (<Box px="2.5" pb="2">@@ -158,3 +204,59 @@ const RunningItemProgress = ({ message, percentage }: { message: string; percentreturn <QueueStepProgress message={caption} percentage={percentage} />;};++/** Mounted only while open or closing, so a long queue keeps one menu machine, and one recall read, at most. */+const QueueItemContextMenu = ({+ anchor,+ item,+ onClose,+ onExitComplete,+ onRequestDismiss,+ open,+}: {+ anchor: { x: number; y: number };+ item: QueueItemReadModel;+ onClose: () => void;+ onExitComplete: () => void;+ onRequestDismiss: (event: Event) => void;+ open: boolean;+}) => {+ const { itemRecallMenuGroup } = useQueueUi();+ const recall = useMenuPart(itemRecallMenuGroup);+ const positioning = useMemo(+ () => ({+ getAnchorRect: () => ({ height: 1, width: 1, x: anchor.x, y: anchor.y }),+ placement: 'bottom-start' as const,+ }),+ [anchor.x, anchor.y]+ );+ const onOpenChange = useCallback(+ (details: { open: boolean }) => {+ if (!details.open) {+ onClose();+ }+ },+ [onClose]+ );++ return (+ <Menu.Root+ lazyMount+ open={open}+ positioning={positioning}+ unmountOnExit+ onExitComplete={onExitComplete}+ onOpenChange={onOpenChange}+ onRequestDismiss={onRequestDismiss}+ >+ <Portal>+ <Menu.Positioner>+ <MenuContent aria-busy={recall.status === 'loading'} minW="13rem" py="1">+ {/* The menu opens at once, so Escape and an outside press work while its entries load. */}+ {recall.status === 'loaded' ? <recall.part item={item} /> : <MenuPartPlaceholder status={recall.status} />}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsxindex 57be4ef884..3ca2477c12 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueUiContext.tsx@@ -1,5 +1,6 @@import type { QueueSubmissionRetry } from '@features/queue/core/historyTypes';import type { QueueItemReadModel } from '@features/queue/core/types';+import type { MenuPartLoader } from '@platform/ui/Menu';import { createContext, useContext, useSyncExternalStore, type ComponentType, type ReactNode } from 'react';@@ -12,6 +13,11 @@ export interface QueueUiNotificationPort {/** This UI port preserves dependency direction: Queue cannot import Workbench. */export interface QueueUiAdapter {ItemActions: ComponentType<{ item: QueueItemReadModel }>;+ /**+ * A row's context menu entries for recalling its settings, loaded on demand; mounted only while that row's menu is+ * open. The row loads them on intent and on open.+ */+ itemRecallMenuGroup: MenuPartLoader<ComponentType<{ item: QueueItemReadModel }>>;activeProjectId: string | null;/** Names the active-project scope in confirmations and results. */activeProjectName: string | null;@@ -43,6 +49,8 @@ export interface QueueUiAdapter {*/preloadItemActions?(): void;queueJobsScope: 'active-project' | 'all';+ /** Recalls every setting the item records into the active project, as its menus' Recall all does. */+ recallAllFromItem(item: QueueItemReadModel): void;/*** The first model the server is loading now, or null: a running item with no progress yet waits for it. A store, so* only the components that read it (`useLoadingModelLabel`) re-render as loads come and go.diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.browser.test.tsxnew file mode 100644index 0000000000..560393c936--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.browser.test.tsx@@ -0,0 +1,106 @@+import { ChakraProvider } from '@chakra-ui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';++// The filters' English labels, so widths are real; other keys stay as they are.+vi.mock('react-i18next', () => {+ const labels: Record<string, string> = {+ 'common.active': 'Active',+ 'common.all': 'All',+ 'common.canceled': 'Canceled',+ 'common.done': 'Done',+ 'common.failed': 'Failed',+ };+ return { useTranslation: () => ({ i18n: { resolvedLanguage: 'en' }, t: (key: string) => labels[key] ?? key }) };+});+vi.mock('@features/queue/publicApi', () => ({+ getQueueItemDetailOptions: (itemId: number) => ({ queryFn: () => null, queryKey: ['queue', 'item-detail', itemId] }),+ getQueueReadModelOptions: () => ({ queryFn: () => null, queryKey: ['queue'], staleTime: Number.POSITIVE_INFINITY }),+ queueCommands: {},+}));++import { QUEUE_FILTER_TABS_ID } from './QueueFilterTabs';+import { createTestQueueUiAdapter, createTestQueueWidgetRuntime } from './queueUiAdapter.testing';+import { QueueUiProvider } from './QueueUiContext';+import { QueueWidgetView } from './QueueWidgetView';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++interface Counts {+ canceled: number;+ completed: number;+ failed: number;+ inProgress: number;+ pending: number;+}++const renderQueue = async (width: number, counts: Counts) => {+ const client = new QueryClient();+ client.setQueryData(['queue'], {+ current: null,+ items: [],+ next: null,+ scope: {},+ status: {+ processor: { isProcessing: false, isStarted: true },+ queue: {+ ...counts,+ queueId: 'default',+ total: Object.values(counts).reduce((sum, count) => sum + count, 0),+ waiting: 0,+ },+ },+ });+ host = document.createElement('div');+ host.style.height = '400px';+ host.style.width = `${width}px`;+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root!.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={client}>+ <QueueUiProvider adapter={createTestQueueUiAdapter()}>+ <QueueWidgetView region="right" runtime={createTestQueueWidgetRuntime()} />+ </QueueUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ )+ );+ return host.querySelector<HTMLElement>(`[role="tablist"]:has(#${QUEUE_FILTER_TABS_ID}-tab-all)`)!;+};++it('scrolls its filter strip in a narrow widget with large counts', async () => {+ const large = 12_345;+ const strip = await renderQueue(220, {+ canceled: large,+ completed: large,+ failed: large,+ inProgress: large,+ pending: large,+ });++ expect(strip.scrollWidth).toBeGreaterThan(strip.clientWidth);+ expect(strip.getBoundingClientRect().right).toBeLessThanOrEqual(host!.getBoundingClientRect().right);+});++it('fits all five filters without scrolling in a docked rail', async () => {+ // A rail's default width, with a busy session's counts.+ const strip = await renderQueue(450, { canceled: 83, completed: 83, failed: 83, inProgress: 83, pending: 168 });++ expect(strip.querySelectorAll('[role="tab"]')).toHaveLength(5);+ expect(strip.scrollWidth).toBe(strip.clientWidth);+});diff --git a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsxindex f9f6d9be78..0a59a30ca6 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/QueueWidgetView.tsx@@ -1,13 +1,22 @@import type { QueueActivity } from '@features/queue/core/queueActivity';-import { Stack, VisuallyHidden } from '@chakra-ui/react';+import { Box, Stack, VisuallyHidden } from '@chakra-ui/react';import { useMountEffect } from '@platform/react/useMountEffect';+import { LIST_ROW_GAP_PX } from '@platform/ui/list/listLayout';import { ListSectionHeader } from '@platform/ui/list/ListSectionHeader';import { RetryBoundary } from '@platform/ui/RetryBoundary';import { Scrollable } from '@platform/ui/Scrollable';import { StatusWidgetChip } from '@platform/ui/StatusWidgetChip';import { CloudOffIcon, ListOrderedIcon, PauseIcon, type LucideIcon } from 'lucide-react';-import { lazy, Suspense, useState, useSyncExternalStore, type ComponentProps, type ComponentType } from 'react';+import {+ lazy,+ Suspense,+ useEffectEvent,+ useState,+ useSyncExternalStore,+ type ComponentProps,+ type ComponentType,+} from 'react';import { useTranslation } from 'react-i18next';import type * as LocalRunListExports from './LocalRunList';@@ -15,6 +24,7 @@ import type { QueueFilterId } from './queueFilters';import type { QueueLocalRun } from './QueueUiContext';import { CurrentBatchSection } from './NowNextSection';+import { useQueueReadModelData } from './queueDataStore';import { QueueFilterTabs } from './QueueFilterTabs';import { useShownLocalRuns } from './queueScope';import { useQueueUi } from './QueueUiContext';@@ -85,25 +95,73 @@ export const createLocalRunListLoader = (importer: () => Promise<LocalRunListModconst localRunList = createLocalRunListLoader(() => import('./LocalRunList'));+/** The part of the Workbench's widget runtime the queue uses: Queue cannot import Workbench. */+export interface QueueWidgetRuntime {+ commands: {+ register(command: { handler: () => unknown; id: string; title: string }): () => void;+ };+}++type QueueWidgetRegion = 'bottom' | 'center' | 'dialog' | 'floating' | 'left' | 'popover' | 'right';+export const QueueWidgetView = ({presentation,region,+ runtime,}: {presentation?: 'compact' | 'expanded' | 'tooltip';- region: 'bottom' | 'center' | 'dialog' | 'floating' | 'left' | 'popover' | 'right';+ region: QueueWidgetRegion;+ runtime: QueueWidgetRuntime;}) => {if (region === 'bottom' && presentation !== 'expanded') {return <QueueStatusChip />;}- return <QueueContent />;+ return <QueueContent region={region} runtime={runtime} />;};-const QueueContent = () => {+/** The Workbench's hotkey catalog binds `queue.recallAll` (A) to it, claimed only on a row offering recall. */+const QUEUE_RECALL_ALL_COMMAND = 'queue.recallAll';++/**+ * Recalls the focused row's settings. The key goes to the focused element, so that is the row it names. Registered+ * once per mount; the queue keys it by project, region and language, which its source and title follow.+ */+const QueueRecallAllCommand = ({ runtime }: { runtime: QueueWidgetRuntime }) => {const { t } = useTranslation();+ const { recallAllFromItem } = useQueueUi();+ const readModel = useQueueReadModelData();+ const recallFocusedItem = useEffectEvent(() => {+ const itemId = Number(+ document.activeElement?.closest('[data-queue-recall-item]')?.getAttribute('data-queue-recall-item')+ );+ const item = readModel+ ? [readModel.current, readModel.next, ...readModel.items].find((candidate) => candidate?.id === itemId)+ : undefined;++ if (item) {+ recallAllFromItem(item);+ }+ });++ /* eslint-disable react-hooks/rules-of-hooks -- useMountEffect is the repository's explicit useEffect wrapper */+ useMountEffect(() =>+ runtime.commands.register({+ handler: () => recallFocusedItem(),+ id: QUEUE_RECALL_ALL_COMMAND,+ title: t('widgets.queue.recallAll'),+ })+ );+ /* eslint-enable react-hooks/rules-of-hooks */++ return null;+};++const QueueContent = ({ region, runtime }: { region: QueueWidgetRegion; runtime: QueueWidgetRuntime }) => {+ const { i18n, t } = useTranslation();const [filter, setFilter] = useState<QueueFilterId>('all');const revealRequest = usePendingQueueItemReveal();- const { localRuns } = useQueueUi();+ const { activeProjectId, localRuns } = useQueueUi();const shownLocalRuns = useShownLocalRuns();const [handledRevealRequestId, setHandledRevealRequestId] = useState<number | null>(null);@@ -113,15 +171,17 @@ const QueueContent = () => {setFilter('all');}- // The counted filters stay put while the item lists scroll on their own.+ // The counted filters stay put while the item lists scroll on their own. Sections bleed out of the list padding, so+ // the extra row gap keeps row surfaces off the panel edges by the same distance that separates rows.return (- <Stack gap="3" h="full" minH="0" pt="3">+ <Stack gap="2" h="full" minH="0" pt="2">+ <QueueRecallAllCommand key={`${activeProjectId}:${region}:${i18n.language}`} runtime={runtime} />{localRuns.length > 0 ? <LocalRunListPreload rows={localRunList} /> : null}- <Stack flexShrink={0} gap="3" px="3">+ <Box flexShrink={0} px="2"><QueueFilterTabs localRunCount={shownLocalRuns.length} value={filter} onChange={setFilter} />- </Stack>+ </Box><Scrollable flex="1" label={t('widgets.queue.items')} minH="0" overflowX="hidden">- <Stack gap="3" pb="3" px="3">+ <Stack gap="3" pb="2" px={`calc(0.5rem + ${LIST_ROW_GAP_PX}px)`}><LocalRunsSection filter={filter} rows={localRunList} runs={shownLocalRuns} /><CurrentBatchSection filter={filter} revealRequest={revealRequest} /><RecentSection filter={filter} revealRequest={revealRequest} />diff --git a/invokeai/frontend/webv2/src/features/queue/ui/cancelCurrent.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/cancelCurrent.test.tsnew file mode 100644index 0000000000..dd359b520e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/cancelCurrent.test.ts@@ -0,0 +1,422 @@+import type { QueueItemReadModel, QueueReadModel, QueueStatusReadModel } from '@features/queue/core/types';++import { applyQueueItemStatusToReadModels } from '@features/queue/data/queries';+import { accountLifecycle, captureAccountScope, registerAccountOwnedResource } from '@platform/state/accountLifecycle';+import { QueryClient } from '@tanstack/react-query';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const server = vi.hoisted(() => ({+ cancelItem: vi.fn<(id: number) => Promise<unknown>>(),+ /** What a fresh read of the queue finds; a function gives each read its own answer. */+ model: null as unknown,+ reads: 0,+}));++vi.mock('@features/queue/publicApi', () => ({+ getQueueItemDetailOptions: (itemId: number) => ({ queryFn: () => null, queryKey: ['queue', 'item-detail', itemId] }),+ getQueueReadModelOptions: () => ({+ queryFn: () => {+ server.reads += 1;+ return typeof server.model === 'function' ? (server.model as () => unknown)() : server.model;+ },+ queryKey: ['queue', 'read-model', 'all'],+ staleTime: Number.POSITIVE_INFINITY,+ }),+ queueCommands: { cancelItem: (id: number) => server.cancelItem(id) },+}));++const { CANCEL_CURRENT_SETTLE_MS, cancelCurrentQueueItem, getCancelCurrentTarget, getInProgressAnywhere } =+ await import('./cancelCurrent');++const item = (+ id: number,+ status: QueueItemReadModel['status'],+ overrides: Partial<QueueItemReadModel> = {}+): QueueItemReadModel => ({+ batchId: 'batch-1',+ createdAt: '2026-11-14T00:00:00.000Z',+ id,+ resultImageNames: [],+ sessionId: `session-${id}`,+ status,+ statusSequence: 1,+ updatedAt: '2026-11-14T00:00:00.000Z',+ userId: 'me',+ ...overrides,+});++/** A reading of the scope: its counts are the items', unless `pending` says more wait than the window shows. */+const readModel = (+ items: QueueItemReadModel[],+ { isStarted = true, pending }: { isStarted?: boolean; pending?: number } = {}+): QueueReadModel => {+ const waiting = items.filter((candidate) => candidate.status === 'pending').sort((left, right) => left.id - right.id);+ const running = items.filter((candidate) => candidate.status === 'in_progress');+ return {+ current: running[0] ?? null,+ items,+ next: waiting[0] ?? null,+ scope: {},+ status: {+ processor: { isProcessing: running.length > 0, isStarted },+ queue: {+ canceled: 0,+ completed: 0,+ failed: 0,+ inProgress: running.length,+ pending: pending ?? waiting.length,+ queueId: 'default',+ total: items.length,+ waiting: 0,+ },+ },+ };+};++const mine = (candidate: QueueItemReadModel) => candidate.userId === 'me';+const batch = () => readModel([item(9, 'pending'), item(8, 'pending'), item(7, 'in_progress')]);+/** The server's answer to a cancel: the item canceled, or unchanged when it had already finished. */+const answer = (id: number, status: QueueItemReadModel['status'] = 'canceled') =>+ Promise.resolve(item(id, status, { statusSequence: 5 }));++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((onResolve, onReject) => {+ resolve = onResolve;+ reject = onReject;+ });+ return { promise, reject, resolve };+};++let client: QueryClient;+// As the app does with its query client: a sign-out clears the cache before the next account arrives.+registerAccountOwnedResource({ clear: () => client.clear(), name: 'cancel-current-test-query-client' });+/** A cancel the server has not answered, which an account change aborts, as the production adapter's does. */+const unansweredCancel = () => {+ const signal = captureAccountScope().signal;+ return new Promise<never>((_resolve, reject) => {+ signal.addEventListener('abort', () => reject(new Error('Account is no longer active')), { once: true });+ });+};+const cached = () => client.getQueryData<QueueReadModel>(['queue', 'read-model', 'all'])!;+/** The whole queue's counts, from the status read the Launchpad shares. */+const wholeQueue = () => client.getQueryData<QueueStatusReadModel>(['queue', 'status', 'all'])?.queue;+const cancelCurrent = () => cancelCurrentQueueItem({ canManageItem: mine, client, scope: {} });++beforeEach(() => {+ vi.useFakeTimers();+ accountLifecycle.activate('user-a');+ client = new QueryClient();+ client.setQueryData(['queue', 'read-model', 'all'], batch());+ server.cancelItem.mockReset();+ server.cancelItem.mockImplementation((id) => answer(id));+ server.model = batch();+ server.reads = 0;+});++afterEach(async () => {+ // Every test leaves the command free: its settle window ends with its own timers.+ await vi.advanceTimersByTimeAsync(10_000);+ vi.useRealTimers();+});++describe('cancel-current target', () => {+ /** In an unscoped view, whose own counts are the whole queue's. */+ const targetId = (model: Parameters<typeof getCancelCurrentTarget>[0], skippedItemId?: number) =>+ getCancelCurrentTarget(model, {+ canManageItem: mine,+ inProgressAnywhere: getInProgressAnywhere({}, model, null),+ skippedItemId,+ })?.id ?? null;++ it('stops the running item, else between items the next one waiting', () => {+ expect(targetId(batch())).toBe(7);+ // The hand-off between items, or a canceled item's worker still finishing: nothing is in progress.+ expect(targetId(readModel([item(9, 'pending'), item(8, 'pending'), item(7, 'canceled')]))).toBe(8);+ expect(targetId(readModel([item(6, 'completed')]))).toBeNull();+ expect(targetId(null)).toBeNull();+ expect(targetId(batch(), 7)).toBeNull();+ });++ it('stops nothing waiting while the processor is paused', () => {+ expect(targetId(readModel([item(9, 'pending'), item(8, 'pending')], { isStarted: false }))).toBeNull();+ });++ it("stops nothing waiting while someone else's item runs, but the viewer's own item running beside it", () => {+ const theirs = item(20, 'in_progress', { userId: 'someone' });++ expect(targetId(readModel([item(22, 'pending'), item(21, 'pending'), theirs]))).toBeNull();+ // Another GPU runs one of the viewer's items.+ expect(targetId(readModel([item(22, 'pending'), item(21, 'in_progress'), theirs]))).toBe(21);+ });++ it('in a project view, stops nothing waiting while an item runs elsewhere in the queue, however the view counts', () => {+ const projectScope = { originPrefix: 'webv2:p:project-1:q:' };+ // The project's reading: nothing of its own runs, and its next item waits.+ const project = readModel([item(9, 'pending'), item(8, 'pending'), item(7, 'completed')]);+ const wholeQueue = (inProgress: number) => ({ ...project.status, queue: { ...project.status.queue, inProgress } });+ const targetIn = (inProgressAnywhere: number | null) =>+ getCancelCurrentTarget(project, { canManageItem: mine, inProgressAnywhere })?.id ?? null;++ // Another project's item, or another user's, runs.+ expect(targetIn(getInProgressAnywhere(projectScope, project, wholeQueue(1)))).toBeNull();+ // Not known yet: nothing is stopped on a guess.+ expect(targetIn(getInProgressAnywhere(projectScope, project, null))).toBeNull();+ // Nothing runs anywhere: the gap between two of the project's items.+ expect(targetIn(getInProgressAnywhere(projectScope, project, wholeQueue(0)))).toBe(8);+ });++ it("between items, reaches past someone else's next item only when the window holds every pending item", () => {+ const theirs = item(21, 'pending', { userId: 'someone' });+ const window = [item(23, 'pending', { priority: 10 }), item(22, 'pending'), theirs];++ // The viewer's own, in the order the server runs them: the one queued at the front first.+ expect(targetId(readModel(window))).toBe(23);+ // More wait than the window shows: the true next of the viewer's may be older than all of them.+ expect(targetId(readModel(window, { pending: 40 }))).toBeNull();+ });+});++describe('cancelCurrentQueueItem', () => {+ it('stops one item for a double click, a double tap or a held key, and the next on a later press', async () => {+ const first = deferred<QueueItemReadModel>();+ server.cancelItem.mockReturnValueOnce(first.promise);++ const pressed = cancelCurrent();+ // A held key's repeats while the request is out.+ const repeats = await Promise.all([cancelCurrent(), cancelCurrent()]);+ first.resolve(item(7, 'canceled', { statusSequence: 5 }));+ expect(repeats).toEqual([{ kind: 'busy' }, { kind: 'busy' }]);+ expect(await pressed).toMatchObject({ item: { id: 7 }, kind: 'canceled' });++ // The second click of a double click, 150 ms after the first settled.+ await vi.advanceTimersByTimeAsync(150);+ await expect(cancelCurrent()).resolves.toEqual({ kind: 'busy' });++ // The read that reconciles the queue lands (the app's queue views keep the read model observed); then a+ // deliberate press after the settle window stops the next item.+ client.setQueryData(+ ['queue', 'read-model', 'all'],+ readModel([item(9, 'pending'), item(8, 'pending'), item(7, 'canceled', { statusSequence: 5 })])+ );+ await vi.advanceTimersByTimeAsync(CANCEL_CURRENT_SETTLE_MS);+ await expect(cancelCurrent()).resolves.toMatchObject({ item: { id: 8 }, kind: 'canceled' });+ expect(server.cancelItem.mock.calls).toEqual([[7], [8]]);+ });++ it('puts the item back as running when the cancel fails, so the next press tries it again at once', async () => {+ const failure = new Error('Server unavailable');+ server.cancelItem.mockRejectedValueOnce(failure);++ await expect(cancelCurrent()).resolves.toEqual({ error: failure, kind: 'failed' });+ expect(cached().current).toMatchObject({ id: 7, status: 'in_progress' });+ expect(cached().items.find((candidate) => candidate.id === 7)?.status).toBe('in_progress');++ await expect(cancelCurrent()).resolves.toMatchObject({ item: { id: 7 }, kind: 'canceled' });+ });++ it("moves the whole queue's counts at once, and puts them back when the cancel fails", async () => {+ const failure = new Error('Server unavailable');+ const request = deferred<QueueItemReadModel>();+ server.cancelItem.mockReturnValueOnce(request.promise);+ client.setQueryData(['queue', 'status', 'all'], batch().status);++ const pressed = cancelCurrent();++ // What runs anywhere, for the Launchpad's band and a project view's gap, drops with the item before the answer.+ expect(wholeQueue()).toEqual({ ...batch().status.queue, canceled: 1, inProgress: 0 });+ request.reject(failure);+ await expect(pressed).resolves.toEqual({ error: failure, kind: 'failed' });+ expect(wholeQueue()).toEqual(batch().status.queue);+ });++ it('cancels nothing it cannot know is next: a long batch whose oldest waiting items are outside the window', async () => {+ // Items 101 to 200 wait; the window shows the newest 50, and the server names 101 next.+ const window = Array.from({ length: 50 }, (_, index) => item(200 - index, 'pending'));+ client.setQueryData(['queue', 'read-model', 'all'], {+ ...readModel(window, { pending: 100 }),+ next: item(101, 'pending'),+ });++ await expect(cancelCurrent()).resolves.toMatchObject({ item: { id: 101 }, kind: 'canceled' });+ await vi.advanceTimersByTimeAsync(CANCEL_CURRENT_SETTLE_MS);+ // Before a read names 102, the next is unknown: nothing is stopped, rather than 151.+ expect(cached().next).toBeNull();+ await expect(cancelCurrent()).resolves.toEqual({ kind: 'nothing' });+ expect(server.cancelItem.mock.calls).toEqual([[101]]);+ });++ it('stops what is current now when the item it read had already finished, once', async () => {+ server.cancelItem.mockImplementation((id) => answer(id, id === 7 ? 'completed' : 'canceled'));+ server.model = readModel([item(9, 'pending'), item(8, 'in_progress'), item(7, 'completed')]);++ await expect(cancelCurrent()).resolves.toMatchObject({ item: { id: 8 }, kind: 'canceled' });+ expect(server.cancelItem.mock.calls).toEqual([[7], [8]]);+ });++ it("shows the server's answer for an item that had already finished at once, before the read", async () => {+ server.cancelItem.mockImplementation((id) => answer(id, 'completed'));+ const read = deferred<QueueReadModel>();+ server.model = () => read.promise;++ const pressed = cancelCurrent();+ await vi.advanceTimersByTimeAsync(0);++ expect(cached().items.find((candidate) => candidate.id === 7)?.status).toBe('completed');+ read.resolve(readModel([item(7, 'completed')]));+ await expect(pressed).resolves.toEqual({ kind: 'nothing' });+ });++ it('reads afresh after the answer instead of joining a read that started before it', async () => {+ server.cancelItem.mockImplementation((id) => answer(id, id === 7 ? 'completed' : 'canceled'));+ const stale = deferred<QueueReadModel>();+ const fresh = readModel([item(9, 'pending'), item(8, 'in_progress'), item(7, 'completed')]);+ server.model = () => (server.reads === 1 ? stale.promise : fresh);+ // A read from before the cancel is still out: it would say item 7 runs.+ const earlier = client.fetchQuery({+ queryFn: () => {+ server.reads += 1;+ return stale.promise;+ },+ queryKey: ['queue', 'read-model', 'all'],+ staleTime: 0,+ });++ await expect(cancelCurrent()).resolves.toMatchObject({ item: { id: 8 }, kind: 'canceled' });+ expect(server.reads).toBe(2);+ // The earlier read was neither joined nor cancelled: whoever awaits it (the palette's queue search) still gets it.+ stale.resolve(batch());+ await expect(earlier).resolves.toEqual(batch());+ });++ it('offers the next item after the settle window when the read that would reconcile fails', async () => {+ server.model = () => Promise.reject(new Error('Server unavailable'));++ await expect(cancelCurrent()).resolves.toMatchObject({ item: { id: 7 }, kind: 'canceled' });+ await vi.advanceTimersByTimeAsync(CANCEL_CURRENT_SETTLE_MS);++ // The canceled item no longer counts as running, so the gap shows without any read.+ expect(cached().status.queue.inProgress).toBe(0);+ await expect(cancelCurrent()).resolves.toMatchObject({ item: { id: 8 }, kind: 'canceled' });+ });++ it('gives up on a fresh read that stalls, and leaves the command free', async () => {+ server.cancelItem.mockImplementation((id) => answer(id, 'completed'));+ // A read that never answers.+ server.model = () =>+ new Promise<never>(() => {+ // Never settles.+ });++ const pressed = cancelCurrent();+ await vi.advanceTimersByTimeAsync(10_000);++ // Nothing failed to cancel: the server said the item had already finished.+ await expect(pressed).resolves.toMatchObject({ item: { id: 7 }, kind: 'finished' });+ server.model = readModel([item(7, 'completed')]);+ await expect(cancelCurrent()).resolves.not.toEqual({ kind: 'busy' });+ });++ it('says the item had already finished when what is current now cannot be read', async () => {+ server.cancelItem.mockImplementation((id) => answer(id, 'completed'));+ server.model = () => Promise.reject(new Error('Server unavailable'));++ await expect(cancelCurrent()).resolves.toMatchObject({ item: { id: 7 }, kind: 'finished' });+ expect(server.cancelItem.mock.calls).toEqual([[7]]);+ });++ it('reports a failed cancel of what is current now as failed', async () => {+ const failure = new Error('Server unavailable');+ server.cancelItem.mockImplementation((id) => (id === 7 ? answer(id, 'completed') : Promise.reject(failure)));+ server.model = readModel([item(9, 'pending'), item(8, 'in_progress'), item(7, 'completed')]);++ await expect(cancelCurrent()).resolves.toEqual({ error: failure, kind: 'failed' });+ });++ it('says there is nothing to cancel when the fresh read finds nothing either', async () => {+ server.cancelItem.mockImplementation((id) => answer(id, 'completed'));+ server.model = readModel([item(7, 'completed')]);++ await expect(cancelCurrent()).resolves.toEqual({ kind: 'nothing' });+ expect(server.cancelItem.mock.calls).toEqual([[7]]);+ });++ it('puts nothing back, reads nothing and retargets nothing once the account has signed out', async () => {+ server.cancelItem.mockImplementationOnce(unansweredCancel);++ const pressed = cancelCurrent();+ // The sign-out clears the cache, then the request it aborted fails.+ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');++ await expect(pressed).resolves.toEqual({ kind: 'superseded' });+ // The next account must not see this one's queue.+ expect(client.getQueryData(['queue', 'read-model', 'all'])).toBeUndefined();+ expect(server.reads).toBe(0);+ expect(server.cancelItem.mock.calls).toEqual([[7]]);+ });++ it("keeps a fresh read that lands after a sign-out out of the next account's cache", async () => {+ server.cancelItem.mockImplementation((id) => answer(id, 'completed'));+ const read = deferred<QueueReadModel>();+ server.model = () => read.promise;++ const pressed = cancelCurrent();+ await vi.advanceTimersByTimeAsync(0);+ expect(server.reads).toBe(1);+ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');+ await expect(pressed).resolves.toEqual({ kind: 'superseded' });++ // The old account's server answers only now.+ read.resolve(batch());+ await vi.advanceTimersByTimeAsync(0);+ expect(client.getQueryData(['queue', 'read-model', 'all'])).toBeUndefined();+ });++ it("keeps the item canceled when the server's event confirmed it before the request failed", async () => {+ const request = deferred<QueueItemReadModel>();+ server.cancelItem.mockReturnValueOnce(request.promise);+ client.setQueryData(['queue', 'status', 'all'], batch().status);+ const guessed = { ...batch().status.queue, canceled: 1, inProgress: 0 };++ const pressed = cancelCurrent();+ // The server cancels item 7 and says so, exactly as guessed; then its answer to the request is lost.+ applyQueueItemStatusToReadModels(client, {+ item: item(7, 'canceled', { statusSequence: 5 }),+ queueCounts: guessed,+ });+ request.reject(new Error('Connection lost'));++ await expect(pressed).resolves.toMatchObject({ item: { id: 7 }, kind: 'canceled' });+ expect(cached().items.find((candidate) => candidate.id === 7)?.status).toBe('canceled');+ expect(wholeQueue()).toEqual(guessed);+ });++ it('keeps what an event changed while a cancel was waiting, when that cancel then fails', async () => {+ const failure = new Error('Server unavailable');+ let fail!: () => void;+ server.cancelItem.mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ fail = () => reject(failure);+ })+ );++ client.setQueryData(['queue', 'status', 'all'], batch().status);++ const pressed = cancelCurrent();+ // Item 8 starts meanwhile.+ applyQueueItemStatusToReadModels(client, {+ item: item(8, 'in_progress', { statusSequence: 2 }),+ queueCounts: null,+ });+ fail();++ await expect(pressed).resolves.toEqual({ error: failure, kind: 'failed' });+ expect(cached().items.find((candidate) => candidate.id === 8)?.status).toBe('in_progress');+ // The whole queue's counts keep the event too, until the read reconciles them.+ expect(wholeQueue()).toMatchObject({ inProgress: 1, pending: 1 });+ });+});diff --git a/invokeai/frontend/webv2/src/features/queue/ui/cancelCurrent.ts b/invokeai/frontend/webv2/src/features/queue/ui/cancelCurrent.tsnew file mode 100644index 0000000000..4bcc8d65ab--- /dev/null+++ b/invokeai/frontend/webv2/src/features/queue/ui/cancelCurrent.ts@@ -0,0 +1,258 @@+import type {+ QueueItemReadModel,+ QueueQueryScope,+ QueueReadModel,+ QueueStatusReadModel,+} from '@features/queue/core/types';+import type { QueryClient } from '@tanstack/react-query';++import { CANCEL_ITEM_TIMEOUT_MS } from '@features/queue/data/httpRealtimeQueueBackend';+import {+ applyQueueItemStatusGuess,+ applyQueueItemStatusToReadModels,+ compareQueuedItems,+ invalidateQueueQueries,+ queueKeys,+} from '@features/queue/data/queries';+import { getQueueReadModelOptions, queueCommands } from '@features/queue/publicApi';+import { noteQueueCancelRequested } from '@features/queue/runtime/cancelRequests';+import { captureAccountScope, isAccountScopeCurrent, type AccountScope } from '@platform/state/accountLifecycle';+import { sleep, withRequestDeadline } from '@platform/transport/http';++import { readQueueReadModel, readWholeQueueStatus } from './queueDataStore';++/**+ * What runs anywhere in the queue, whatever the view's scope: a scoped reading counts only its scope, so another+ * project's or another user's item running would read as nothing. An unscoped reading's own count is the whole+ * queue's; a scoped one needs the whole-queue status read. Null while that is unknown.+ */+export const getInProgressAnywhere = (+ scope: QueueQueryScope,+ model: Pick<QueueReadModel, 'status'> | null | undefined,+ wholeQueueStatus: QueueStatusReadModel | null | undefined+): number | null =>+ scope.originPrefix ? (wholeQueueStatus?.queue.inProgress ?? null) : (model?.status.queue.inProgress ?? null);++/**+ * What cancel-current stops: the item in progress the viewer can manage (the server's current one, else one of theirs+ * the read window shows running beside someone else's), else, only in the gap between two items, the next one waiting.+ * The gap is the processor running (not paused) with nothing in progress anywhere in the queue (`inProgressAnywhere`,+ * unknown counting as something): the hand-off between items, a cached reading that is behind, or a canceled item's+ * worker still finishing. Stopping the next item is then what stops the run from the viewer's side. While the+ * processor is paused, or anything runs that it would not cancel, nothing waiting is stopped. The next item is the+ * server's; the read window stands in for it (the server's belonging to someone else) only when it holds exactly the+ * pending items the counts report, since the window is the newest items and the true next may be older.+ * `skippedItemId` leaves out an item a cancel just found already finished.+ */+export const getCancelCurrentTarget = (+ model: Pick<QueueReadModel, 'current' | 'items' | 'next' | 'status'> | null | undefined,+ {+ canManageItem,+ inProgressAnywhere,+ skippedItemId,+ }: {+ canManageItem: (item: QueueItemReadModel) => boolean;+ inProgressAnywhere: number | null;+ skippedItemId?: number;+ }+): QueueItemReadModel | null => {+ if (!model) {+ return null;+ }++ const inRunOrder = [...model.items].sort(compareQueuedItems);+ const isTarget = (item: QueueItemReadModel | null, status: 'in_progress' | 'pending'): item is QueueItemReadModel =>+ item?.status === status && item.id !== skippedItemId && canManageItem(item);+ const running = [model.current, ...inRunOrder].find((item) => isTarget(item, 'in_progress'));++ if (running) {+ return running;+ }++ const isBetweenItems =+ model.status.processor.isStarted &&+ model.current === null &&+ model.status.queue.inProgress === 0 &&+ inProgressAnywhere === 0;++ if (!isBetweenItems) {+ return null;+ }++ const windowHoldsEveryPending =+ inRunOrder.filter((item) => item.status === 'pending').length === model.status.queue.pending;++ return (+ (isTarget(model.next, 'pending') ? model.next : null) ??+ (windowHoldsEveryPending ? (inRunOrder.find((item) => isTarget(item, 'pending')) ?? null) : null)+ );+};++export type CancelCurrentOutcome =+ /** Another cancel-current is still in flight; this one did nothing. */+ | { kind: 'busy' }+ | { item: QueueItemReadModel; kind: 'canceled' }+ | { error: unknown; kind: 'failed' }+ /** The item it read as current had already finished, and what is current now could not be read: nothing stopped. */+ | { item: QueueItemReadModel; kind: 'finished' }+ | { kind: 'nothing' }+ /** The account changed meanwhile; nothing is reported for the one that asked. */+ | { kind: 'superseded' };++/**+ * How long a cancel-current that stopped an item keeps the command busy, at least: a double click, a double tap of the+ * shortcut or a double activation in the palette lands well inside it, while a deliberate second press after it stops+ * the next item. It also waits for the read that reconciles the queue, up to `CANCEL_CURRENT_SETTLE_LIMIT_MS`.+ */+export const CANCEL_CURRENT_SETTLE_MS = 400;+const CANCEL_CURRENT_SETTLE_LIMIT_MS = 2_000;++/**+ * The account whose cancel-current is in flight or settling; one at a time, so a held key, a double click or a+ * double tap stops one item.+ */+let inFlightOwner: AccountScope | null = null;++/**+ * Shows the item canceled at once, then asks the server; true when the server canceled it. An item that had already+ * finished comes back unchanged: the cancel did nothing. A failed request takes the guess back, only while the account+ * that made it is still signed in (a sign-out clears the cache first, and the next account must not see this one's+ * queue), unless an event reported the item canceled meanwhile: the server canceled it, though its answer was lost.+ */+const cancelItem = async (client: QueryClient, owner: AccountScope, item: QueueItemReadModel): Promise<boolean> => {+ const dropNote = noteQueueCancelRequested({ itemId: item.id, kind: 'item' });+ const guess = applyQueueItemStatusGuess(client, {+ item: { ...item, status: 'canceled', statusSequence: null },+ queueCounts: null,+ });++ try {+ const answer = await queueCommands.cancelItem(item.id);++ guess.settle();+ // The server's answer, a canceled item or one that had already finished, supersedes the guess.+ applyQueueItemStatusToReadModels(client, { item: answer, queueCounts: null });+ if (answer.status !== 'canceled') {+ dropNote();+ }++ return answer.status === 'canceled';+ } catch (error) {+ if (!isAccountScopeCurrent(owner)) {+ guess.settle();+ } else if (guess.revert()) {+ return true;+ }+ dropNote();+ throw error;+ }+};++/**+ * Cancel-current, for every surface: the top bar, the queue widget, the shortcut and the palette. Picks its target+ * from the loaded read model when it runs, not when a control rendered. When the item it read as current had already+ * finished, it reads the queue afresh and stops what is current now, once. A call while another is in flight, or+ * within the settle window after one stopped an item (`CANCEL_CURRENT_SETTLE_MS`), returns `busy` at once: one+ * mechanism for every entry point, so a double click, a double tap of the shortcut or a double activation in the+ * palette stops one item.+ */+export const cancelCurrentQueueItem = async ({+ canManageItem,+ client,+ scope,+}: {+ canManageItem: (item: QueueItemReadModel) => boolean;+ client: QueryClient;+ scope: QueueQueryScope;+}): Promise<CancelCurrentOutcome> => {+ if (inFlightOwner && isAccountScopeCurrent(inFlightOwner)) {+ return { kind: 'busy' };+ }++ const owner = captureAccountScope();+ inFlightOwner = owner;+ let outcome: CancelCurrentOutcome = { kind: 'nothing' };++ try {+ outcome = await cancelCurrent(client, owner, scope, canManageItem);+ return outcome;+ } finally {+ const reconcile = isAccountScopeCurrent(owner) ? invalidateQueueQueries(client) : Promise.resolve();+ const release = () => {+ if (inFlightOwner === owner) {+ inFlightOwner = null;+ }+ };++ if (outcome.kind === 'canceled') {+ void Promise.race([+ Promise.all([sleep(CANCEL_CURRENT_SETTLE_MS), reconcile.catch(() => undefined)]),+ sleep(CANCEL_CURRENT_SETTLE_LIMIT_MS),+ ]).then(release);+ } else {+ release();+ }+ }+};++const cancelCurrent = async (+ client: QueryClient,+ owner: AccountScope,+ scope: QueueQueryScope,+ canManageItem: (item: QueueItemReadModel) => boolean+): Promise<CancelCurrentOutcome> => {+ try {+ const model = client.getQueryData<QueueReadModel>(getQueueReadModelOptions(scope).queryKey);+ const target = getCancelCurrentTarget(model, {+ canManageItem,+ inProgressAnywhere: getInProgressAnywhere(+ scope,+ model,+ client.getQueryData<QueueStatusReadModel>(queueKeys.status({}))+ ),+ });++ if (!target) {+ return { kind: 'nothing' };+ }+ if (await cancelItem(client, owner, target)) {+ return { item: target, kind: 'canceled' };+ }+ if (!isAccountScopeCurrent(owner)) {+ return { kind: 'superseded' };+ }++ // The reading the target came from was out of date: read afresh, and for a scoped view the whole queue's status+ // too. Bounded, so a stalled read cannot hold the command busy. A read that fails leaves what the server answered:+ // the item had already finished, which is no failure to cancel.+ const reading = await withRequestDeadline(+ (signal) =>+ Promise.all([+ readQueueReadModel(client, scope, signal),+ scope.originPrefix ? readWholeQueueStatus(client, signal) : Promise.resolve(null),+ ]),+ CANCEL_ITEM_TIMEOUT_MS+ ).catch(() => null);++ if (!isAccountScopeCurrent(owner)) {+ return { kind: 'superseded' };+ }+ if (!reading) {+ return { item: target, kind: 'finished' };+ }++ const [fresh, wholeQueueStatus] = reading;++ const retarget = getCancelCurrentTarget(fresh, {+ canManageItem,+ inProgressAnywhere: getInProgressAnywhere(scope, fresh, wholeQueueStatus),+ skippedItemId: target.id,+ });++ return retarget && (await cancelItem(client, owner, retarget))+ ? { item: retarget, kind: 'canceled' }+ : { kind: 'nothing' };+ } catch (error) {+ return isAccountScopeCurrent(owner) ? { error, kind: 'failed' } : { kind: 'superseded' };+ }+};diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.tsindex 686c9cabdd..328a4ff257 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueDataStore.ts@@ -4,10 +4,14 @@ import type {QueueItemDetailReadModel,QueueItemReadModel,QueueQueryScope,+ QueueReadModel,+ QueueStatusReadModel,} from '@features/queue/core/types';+import type { QueryClient, QueryFunction } from '@tanstack/react-query';import { getPersonalQueueActivity } from '@features/queue/core/types';-import { invalidateQueueQueries } from '@features/queue/data/queries';+import { queueBackend } from '@features/queue/data/httpRealtimeQueueBackend';+import { invalidateQueueQueries, queueStatusOptions } from '@features/queue/data/queries';import { getQueueItemDetailOptions, getQueueReadModelOptions } from '@features/queue/publicApi';import { queryClient } from '@platform/query/client';import { useQuery } from '@tanstack/react-query';@@ -17,6 +21,8 @@ import { getCurrentBatchItems } from './currentBatchItems';import { clearProgressForQueueItemsWithResults } from './queueProgressCleanup';import { getQueueOpenWorkElsewhere, useQueueQueryScope } from './queueScope';+const WHOLE_QUEUE_SCOPE: QueueQueryScope = {};+const EMPTY_COUNTS: QueueCounts = {canceled: 0,completed: 0,@@ -67,6 +73,48 @@ export const useQueueOpenWorkElsewhere = (projectItems: QueueItem[]): number =>/** Invalidate queue data; TanStack Query deduplicates concurrent callers. */export const refreshQueue = (): Promise<void> => invalidateQueueQueries(queryClient);+/**+ * Runs a query's read now and stores what it finds. A read already in flight is neither joined (it may have started+ * before what the caller just learned) nor cancelled (others, such as the command palette's queue search, may be+ * awaiting it); if it lands later with an older reading, the next invalidation's read reconciles it.+ */+const readNow = async <T, Key extends readonly unknown[]>(+ client: QueryClient,+ options: { queryFn?: unknown; queryKey: Key },+ signal: AbortSignal+): Promise<T> => {+ const queryFn = options.queryFn as QueryFunction<T, Key>;+ const data = await queryFn({ client, meta: undefined, queryKey: options.queryKey, signal });++ // The caller's signal ends with the account: a reading that lands after a switch must not reach the next account's+ // cleared cache.+ signal.throwIfAborted();+ client.setQueryData<T>(options.queryKey as readonly unknown[], data);+ return data;+};++/** The scope's read model as the server has it now, read after the call. Null when the server cannot say. */+export const readQueueReadModel = (+ client: QueryClient,+ scope: QueueQueryScope,+ signal: AbortSignal+): Promise<QueueReadModel | null> => readNow(client, getQueueReadModelOptions(scope, onQueueRead), signal);++/** The whole queue's status as the server has it now, read after the call, under the key the Launchpad shares. */+export const readWholeQueueStatus = (client: QueryClient, signal: AbortSignal): Promise<QueueStatusReadModel> =>+ readNow(client, queueStatusOptions(queueBackend, WHOLE_QUEUE_SCOPE), signal);++/**+ * The whole queue's status, read only while the view is scoped: an unscoped read model's counts are already the whole+ * queue's. Shares its key with the Launchpad's status band, so it is not a request of its own per view.+ */+export const useWholeQueueStatus = (scope: QueueQueryScope): QueueStatusReadModel | null =>+ useQuery({ ...queueStatusOptions(queueBackend, WHOLE_QUEUE_SCOPE), enabled: Boolean(scope.originPrefix) }).data ??+ null;++/** The scope's loaded read model, for the actions that decide from its whole reading. */+export const useQueueReadModelData = (): QueueReadModel | null => useQueueReadModel().data ?? null;+/** Imperative prefetch for non-React composition roots. */export const ensureQueueLoaded = (scope: QueueQueryScope = {}): void => {void queryClient.ensureQueryData(getQueueReadModelOptions(scope, onQueueRead));diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.test.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.test.tsindex b8167e5f24..62bb222875 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.test.ts@@ -23,6 +23,7 @@ const describeActions = (overrides: Partial<Parameters<typeof getQueueActionDescgetQueueActionDescriptors({canManageProcessor: true,counts,+ cancelCurrentTarget: 'in_progress',hasRunningItem: true,includeOpenQueue: false,isConnected: true,@@ -138,6 +139,14 @@ describe('queue action model', () => {expect(localOnly.confirmation?.body).toContain('"count":1');});+ it('names the item cancel-current will stop: the running one, or between items the next one waiting', () => {+ expect(find(describeActions(), 'cancel-current').label).toBe('widgets.queue.cancelCurrentItem');+ expect(find(describeActions({ cancelCurrentTarget: 'pending' }), 'cancel-current').label).toBe(+ 'widgets.queue.cancelNextItem'+ );+ expect(find(describeActions({ cancelCurrentTarget: null }), 'cancel-current').disabled).toBe(true);+ });+it('disables bulk actions with nothing to reach', () => {const empty = describeActions({counts: {@@ -146,6 +155,7 @@ describe('queue action model', () => {inProgress: 0,pending: 0,},+ cancelCurrentTarget: null,hasRunningItem: false,});diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsx b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsxindex 59481a0b3f..2ff576ba5a 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsx+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueMenuActions.tsx@@ -7,6 +7,7 @@ import { getPersonalQueueActivity } from '@features/queue/core/types';import { queueCommands } from '@features/queue/publicApi';import { noteQueueCancelRequested, type QueueCancelRequest } from '@features/queue/runtime/cancelRequests';import { getApiErrorMessage } from '@platform/transport/http';+import { useQueryClient } from '@tanstack/react-query';import {BrushCleaningIcon,ListOrderedIcon,@@ -22,8 +23,16 @@ import { useTranslation } from 'react-i18next';import type { QueueUiNotificationPort, QueueViewer } from './QueueUiContext';+import { cancelCurrentQueueItem, getCancelCurrentTarget, getInProgressAnywhere } from './cancelCurrent';import { requestQueueConfirmation, type QueueConfirmation } from './queueConfirmationStore';-import { refreshQueue, useIsProcessorPaused, useNowNextItems, useQueueCounts } from './queueDataStore';+import {+ refreshQueue,+ useIsProcessorPaused,+ useNowNextItems,+ useQueueCounts,+ useQueueReadModelData,+ useWholeQueueStatus,+} from './queueDataStore';import {translateScoped,useQueueActionScope,@@ -114,6 +123,7 @@ const withRunningItemKept = (t: TFunction, text: string, keepsRunningItem: booleexport const getQueueActionDescriptors = ({canManageProcessor,counts,+ cancelCurrentTarget,hasRunningItem,includeOpenQueue,isConnected,@@ -124,6 +134,8 @@ export const getQueueActionDescriptors = ({}: {canManageProcessor: boolean;counts: QueueActionCounts;+ /** What cancel-current would stop (`getCancelCurrentTarget`): the running item, the next waiting one, or nothing. */+ cancelCurrentTarget: 'in_progress' | 'pending' | null;hasRunningItem: boolean;includeOpenQueue: boolean;isConnected: boolean;@@ -152,11 +164,13 @@ export const getQueueActionDescriptors = ({{confirmation: null,destructive: true,- disabled: !isConnected || !hasRunningItem,+ disabled: !isConnected || cancelCurrentTarget === null,group: 'cancel',icon: XIcon,id: 'cancel-current',- label: t('widgets.queue.cancelCurrentItem'),+ // Says which it will stop: between items it is the next one waiting.+ label:+ cancelCurrentTarget === 'pending' ? t('widgets.queue.cancelNextItem') : t('widgets.queue.cancelCurrentItem'),},{confirmation: {@@ -287,8 +301,10 @@ const withCancelNote = async (request: QueueCancelRequest, send: () => Promise<v/** The queue's actions for the viewer, bound to the active scope. */export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueue?: boolean } = {}): QueueAction[] => {const { t } = useTranslation();+ const queryClient = useQueryClient();const serverCounts = useQueueCounts();const { current } = useNowNextItems();+ const readModel = useQueueReadModelData();const isPaused = useIsProcessorPaused();const queryScope = useQueueQueryScope();const scope = useQueueActionScope();@@ -304,6 +320,15 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueue} = useQueueUi();const counts = useMemo(() => getQueueActionCounts(serverCounts, scope, viewer), [scope, serverCounts, viewer]);const hasRunningItem = current?.status === 'in_progress' && canManageItem(current);+ const wholeQueueStatus = useWholeQueueStatus(queryScope);+ const cancelCurrentTarget = useMemo(+ () =>+ getCancelCurrentTarget(readModel, {+ canManageItem,+ inProgressAnywhere: getInProgressAnywhere(queryScope, readModel, wholeQueueStatus),+ }),+ [canManageItem, queryScope, readModel, wholeQueueStatus]+ );const localProjectId = scope.kind === 'project' ? activeProjectId : null;const localUnsubmitted = useScopedLocalRuns().length;@@ -352,29 +377,39 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueue)),'cancel-current': async () => {- if (!current || current.status !== 'in_progress' || !canManageItem(current)) {- notify.info(- t('widgets.queue.noCurrentItem'),- translateScoped(t, 'widgets.queue.noCurrentItemDescription', scope)- );- return;- }+ const outcome = await cancelCurrentQueueItem({ canManageItem, client: queryClient, scope: queryScope });- await withCancelNote({ itemId: current.id, kind: 'item' }, () => queueCommands.cancelItem(current.id))- .then(() => refreshQueue())- .then(() =>+ switch (outcome.kind) {+ case 'canceled':notify.success(t('widgets.queue.cancellationRequested'),- getQueueItemReadModelLabel(current) || t('widgets.queue.itemTitle', { id: current.id })- )- )- .catch(+ getQueueItemReadModelLabel(outcome.item) || t('widgets.queue.itemTitle', { id: outcome.item.id })+ );+ return;+ case 'finished':+ notify.info(+ t('widgets.queue.itemAlreadyFinished'),+ getQueueItemReadModelLabel(outcome.item) || t('widgets.queue.itemTitle', { id: outcome.item.id })+ );+ return;+ case 'nothing':+ notify.info(+ t('widgets.queue.noCurrentItem'),+ translateScoped(t, 'widgets.queue.noCurrentItemDescription', scope)+ );+ return;+ case 'failed':reportFailure(notify,t('widgets.queue.failedToCancelCurrentItem'),t('widgets.queue.couldNotCancelCurrentItem')- )- );+ )(outcome.error);+ return;+ // A press while one is in flight, or one an account change overtook, reports nothing.+ case 'busy':+ case 'superseded':+ return;+ }},'clear-failed': async () => {await queueCommands@@ -460,6 +495,7 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueuelocalUnsubmitted,notify,openQueue,+ queryClient,queryScope,scope,t,@@ -470,6 +506,8 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueuegetQueueActionDescriptors({canManageProcessor,counts,+ cancelCurrentTarget:+ cancelCurrentTarget?.status === 'pending' ? 'pending' : cancelCurrentTarget ? 'in_progress' : null,hasRunningItem,includeOpenQueue,isConnected,@@ -491,6 +529,7 @@ export const useQueueActions = ({ includeOpenQueue = false }: { includeOpenQueue};}),[+ cancelCurrentTarget,canManageProcessor,counts,hasRunningItem,diff --git a/invokeai/frontend/webv2/src/features/queue/ui/queueUiAdapter.testing.ts b/invokeai/frontend/webv2/src/features/queue/ui/queueUiAdapter.testing.tsindex 23acc12866..b249849e59 100644--- a/invokeai/frontend/webv2/src/features/queue/ui/queueUiAdapter.testing.ts+++ b/invokeai/frontend/webv2/src/features/queue/ui/queueUiAdapter.testing.ts@@ -1,4 +1,7 @@+import { createMenuPartLoader } from '@platform/ui/Menu';+import type { QueueLocalRun, QueueUiAdapter } from './QueueUiContext';+import type { QueueWidgetRuntime } from './QueueWidgetView';const noLoadingModel = { getLabel: (): string | null => null, subscribe: () => () => undefined };@@ -16,12 +19,14 @@ export const createTestQueueUiAdapter = (overrides: Partial<QueueUiAdapter> = {}cancelLocalRuns: () => undefined,isConnected: true,isProjectOpen: () => true,+ itemRecallMenuGroup: createMenuPartLoader(() => Promise.resolve(() => null)),loadingModel: noLoadingModel,localRuns: [],notify: { error: () => undefined, info: () => undefined, success: () => undefined },openQueue: () => undefined,preloadItemActions: () => undefined,queueJobsScope: 'all',+ recallAllFromItem: () => undefined,viewer: 'single',...overrides,});@@ -35,3 +40,8 @@ export const createTestLocalRun = (overrides: Partial<QueueLocalRun> = {}): QueusubmittedAt: 0,...overrides,});++/** A widget runtime that takes registrations and runs nothing. */+export const createTestQueueWidgetRuntime = (): QueueWidgetRuntime => ({+ commands: { register: () => () => undefined },+});diff --git a/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.tsindex 01b8c719c1..bac71b056a 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/integration.test.ts@@ -1,6 +1,8 @@import type { ModelConfig } from '@features/models';+import type { WorkbenchState } from '@workbench/projectContracts';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';+import { getDynamicPromptsExpansionSource } from '@workbench/invocation';import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { describe, expect, it, vi } from 'vitest';@@ -95,3 +97,138 @@ describe('Upscale snapshot submission', () => {const getProjectPromptValues = (project: ReturnType<typeof createInitialWorkbenchState>['projects'][number]) =>project.widgetInstances.generate?.state.values;++const CINEMATIC = {+ id: 'cinematic',+ name: 'Cinematic',+ negativePrompt: '{prompt}, lowres',+ positivePrompt: '{prompt}, film grain',+};++/** An Upscale ready to Refine, with the shared prompt draft patched as the Upscale widget would. */+const prepareUpscale = (draft: Record<string, unknown>, values: Record<string, unknown> = {}): WorkbenchState => {+ let state = createInitialWorkbenchState();++ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ values: {+ ...createDefaultUpscaleWidgetValues(MODELS),+ inputImage: { height: 100, image_name: 'input.png', width: 200 },+ ...values,+ },+ widgetId: 'upscale',+ });+ state = workbenchReducer(state, { sourceId: 'upscale', type: 'patchProjectPromptDraft', values: draft });++ return workbenchReducer(state, { sourceId: 'upscale', type: 'setInvocationSource' });+};++const activeProject = (state: WorkbenchState) =>+ state.projects.find((candidate) => candidate.id === state.activeProjectId)!;++/** Submits as `submitResolvedInvocation` does: with the expansion of what the project expands from, if anything. */+const submitUpscale = (state: WorkbenchState, expansion?: { prompts: string[]; sampleSeed: number | null }) => {+ const source = getDynamicPromptsExpansionSource(activeProject(state), 'upscale');++ return workbenchReducer(state, {+ backendSupportsCancellation: true,+ ...(source && expansion+ ? {+ expandedFrom: {+ combinatorial: source.combinatorial,+ maxPrompts: source.maxPrompts,+ positivePrompt: source.positivePrompt,+ },+ positivePrompts: expansion.prompts,+ positivePromptsSampleSeed: expansion.sampleSeed,+ }+ : {}),+ models: MODELS,+ projectId: state.activeProjectId,+ route: { destination: 'gallery', destinationLocked: false, sourceId: 'upscale', sourceLocked: false },+ type: 'submitResolvedInvocationSnapshot',+ });+};++describe('Upscale with the prompt template and dynamic prompts it shares with Generate', () => {+ it('queues the prompt inside the template, recording the prompt as written in history', () => {+ const state = submitUpscale(+ prepareUpscale({ negativePrompt: 'blur', positivePrompt: 'fine detail', promptTemplate: CINEMATIC })+ );+ const project = activeProject(state);+ const queueItem = project.queue.items[0]!;++ expect(queueItem.snapshot.backendSubmission).toMatchObject({+ kind: 'generate',+ negativePrompt: 'blur, lowres',+ positivePrompt: 'fine detail, film grain',+ });+ expect(queueItem.snapshot.presentation.positivePrompt).toBe('fine detail, film grain');+ expect(project.promptHistory[0]).toEqual({ negativePrompt: 'blur', positivePrompt: 'fine detail' });+ });++ it('expands the templated prompt and queues one upscale per prompt and iteration', () => {+ const prepared = prepareUpscale(+ { dynamicPromptsMaxPrompts: 10, positivePrompt: 'a {red|green} fox', promptTemplate: CINEMATIC },+ { batchCount: 2 }+ );++ expect(getDynamicPromptsExpansionSource(activeProject(prepared), 'upscale')).toMatchObject({+ combinatorial: true,+ maxPrompts: 10,+ positivePrompt: 'a {red|green} fox, film grain',+ });++ const queueItem = activeProject(+ submitUpscale(prepared, { prompts: ['a red fox, film grain', 'a green fox, film grain'], sampleSeed: null })+ ).queue.items[0]!;++ expect(queueItem.snapshot.backendSubmission).toMatchObject({+ batchCount: 2,+ positivePrompts: ['a red fox, film grain', 'a green fox, film grain'],+ seedBehaviour: 'per-iteration',+ });+ expect(queueItem.snapshot.presentation.batchCount).toBe(4);+ });++ it("rotates Generate's random sample after drawing from it, as a Generate run would", () => {+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.5);++ try {+ const prepared = prepareUpscale({+ dynamicPromptsCombinatorial: false,+ dynamicPromptsSampleSeed: 7,+ positivePrompt: 'a {red|green} fox',+ });+ const project = activeProject(submitUpscale(prepared, { prompts: ['a green fox'], sampleSeed: 7 }));++ expect(project.queue.items[0]!.snapshot.backendSubmission).toMatchObject({ positivePrompts: ['a green fox'] });+ expect(getProjectPromptValues(project)?.dynamicPromptsSampleSeed).toBe(Math.floor(0.5 * 4_294_967_295));+ expect(project.widgetInstances.upscale?.state.values).not.toHaveProperty('dynamicPromptsSampleSeed');+ } finally {+ random.mockRestore();+ }+ });++ it('runs the prompt as typed with dynamic prompts off, template still applied', () => {+ const prepared = prepareUpscale({+ dynamicPromptsEnabled: false,+ positivePrompt: 'a {red|green} fox',+ promptTemplate: CINEMATIC,+ });++ expect(getDynamicPromptsExpansionSource(activeProject(prepared), 'upscale')).toBeNull();+ expect(activeProject(submitUpscale(prepared)).queue.items[0]!.snapshot.backendSubmission).toMatchObject({+ positivePrompt: 'a {red|green} fox, film grain',+ });+ });++ it('leaves Model only, which reads no prompt, unexpanded', () => {+ const prepared = prepareUpscale(+ { positivePrompt: 'a {red|green} fox', promptTemplate: CINEMATIC },+ { mode: 'model-only' }+ );++ expect(getDynamicPromptsExpansionSource(activeProject(prepared), 'upscale')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.tsindex 0c6124bf6a..e09a5430fc 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.test.ts@@ -18,6 +18,7 @@ import {resolveUpscaleSubmissionValues,getSpandrelNativeScale,getUpscaleOutputDimensions,+ getUpscaleValidationIssues,getUpscaleValidationReasons,normalizeUpscaleWidgetValues,spandrelAutoscaleDimension,@@ -161,6 +162,43 @@ describe('upscale settings', () => {expect(clearDeletedUpscaleInput(values, new Set(['delete.png'])).inputImage).toBeNull();});++ it('places each issue in the panel section whose fields fix it', () => {+ const installed = [model('main', 'main', 'sdxl'), model('spandrel', 'spandrel_image_to_image', 'any')];+ const lora = { isEnabled: true, model: model('gone', 'lora', 'sdxl'), weight: 1 } as GenerateLora;+ const values = {+ ...createDefaultUpscaleWidgetValues(installed),+ cfgScale: 0.5,+ inputImage: null,+ loras: [lora],+ scale: 17,+ tileSize: 1,+ };++ expect(getUpscaleValidationIssues(values, installed)).toEqual([+ { message: 'Upscale needs an input image. Upload one or send one from Gallery.', section: 'source' },+ { message: 'Upscale needs a Tile or Union ControlNet compatible with the main model.', section: 'advanced' },+ { message: 'Scale must be between 1 and 16.', section: 'source' },+ { message: expect.stringMatching(/^Tile size must be between/), section: 'advanced' },+ { message: expect.stringMatching(/^CFG scale must be between/), section: 'generation' },+ { message: 'gone is no longer installed.', section: 'generation' },+ ]);+ // Model only shows Source & treatment alone, and its issues land there.+ expect(getUpscaleValidationIssues({ ...values, mode: 'model-only' }, [])).toEqual([+ { message: 'Upscale needs an input image. Upload one or send one from Gallery.', section: 'source' },+ { message: 'Scale must be between 1 and 16.', section: 'source' },+ { message: 'spandrel is no longer installed.', section: 'source' },+ ]);+ });++ it('places no issue in a section while the served table, which holds the whole form back, is missing', () => {+ // Seeded again before the next test.+ resetArchitectureCapabilities();++ expect(getUpscaleValidationIssues(createDefaultUpscaleWidgetValues())).toEqual([+ { message: expect.stringMatching(/^Model capabilities are not available/) },+ ]);+ });});describe('architecture-driven validation', () => {diff --git a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts b/invokeai/frontend/webv2/src/features/upscale/core/settings.tsindex 845276187b..395976b737 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/settings.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/settings.ts@@ -6,6 +6,7 @@ import type {ModelIdentifierConfig,VaePrecision,} from '@features/generation/contracts';+import type { GenerateSubmissionSource, ProjectPromptDraft } from '@features/generation/settings';import type { ModelConfig } from '@features/models';import {@@ -965,9 +966,28 @@ export const selectUpscaleMainModel = (};};-const addRangeReason = (reasons: string[], label: string, value: number, min: number, max: number): void => {+/** The Upscale panel section whose fields fix an issue. */+export type UpscaleSection = 'advanced' | 'generation' | 'source';++/**+ * One reason Upscale cannot run, in English, and the section that fixes it. Without a section the form itself is+ * held back (the served architecture table has not loaded), so no section shows it.+ */+export interface UpscaleValidationIssue {+ message: string;+ section?: UpscaleSection;+}++const addRangeIssue = (+ issues: UpscaleValidationIssue[],+ section: UpscaleSection,+ label: string,+ value: number,+ min: number,+ max: number+): void => {if (!Number.isFinite(value) || value < min || value > max) {- reasons.push(`${label} must be between ${min} and ${max}.`);+ issues.push({ message: `${label} must be between ${min} and ${max}.`, section });}};@@ -975,84 +995,104 @@ const addRangeReason = (reasons: string[], label: string, value: number, min: nu* Model only needs no main model, encoder, ControlNet or served architecture table: just an image, an installed* upscaler and a Scale in range.*/-const getModelOnlyValidationReasons = (values: UpscaleWidgetValues, models?: readonly ModelConfig[]): string[] => {- const reasons: string[] = [];+const getModelOnlyValidationIssues = (+ values: UpscaleWidgetValues,+ models?: readonly ModelConfig[]+): UpscaleValidationIssue[] => {+ const issues: UpscaleValidationIssue[] = [];if (!values.inputImage) {- reasons.push('Upscale needs an input image. Upload one or send one from Gallery.');+ issues.push({ message: 'Upscale needs an input image. Upload one or send one from Gallery.', section: 'source' });}if (!values.upscaleModel) {- reasons.push('Upscale needs a Spandrel image-to-image model.');+ issues.push({ message: 'Upscale needs a Spandrel image-to-image model.', section: 'source' });}- addRangeReason(reasons, 'Scale', values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX);+ addRangeIssue(issues, 'source', 'Scale', values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX);if (models && values.upscaleModel) {const installed = models.find((model) => model.key === values.upscaleModel?.key);if (!installed) {- reasons.push(`${values.upscaleModel.name} is no longer installed.`);+ issues.push({ message: `${values.upscaleModel.name} is no longer installed.`, section: 'source' });} else if (!isSpandrelModelConfig(installed)) {- reasons.push(`${values.upscaleModel.name} is not an installed Spandrel model.`);+ issues.push({ message: `${values.upscaleModel.name} is not an installed Spandrel model.`, section: 'source' });}}- return reasons;+ return issues;};-export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?: readonly ModelConfig[]): string[] => {+/** Why Upscale cannot run, each with the section that fixes it, in the order Invoke lists them. */+export const getUpscaleValidationIssues = (+ values: UpscaleWidgetValues,+ models?: readonly ModelConfig[]+): UpscaleValidationIssue[] => {if (values.mode === 'model-only') {- return getModelOnlyValidationReasons(values, models);+ return getModelOnlyValidationIssues(values, models);}// As in Generate: without the served table every VAE reads as incompatible and the schedulers fall// back, so the other reasons would mislead and the graph would be wrong.if (!hasArchitectureCapabilities()) {return [- 'Model capabilities are not available. Upscale is blocked until they load; if this persists, retry from the Upscale panel.',+ {+ message:+ 'Model capabilities are not available. Upscale is blocked until they load; if this persists, retry from the Upscale panel.',+ },];}- const reasons: string[] = [];+ const issues: UpscaleValidationIssue[] = [];if (!values.inputImage) {- reasons.push('Upscale needs an input image. Upload one or send one from Gallery.');+ issues.push({ message: 'Upscale needs an input image. Upload one or send one from Gallery.', section: 'source' });}if (!values.upscaleModel) {- reasons.push('Upscale needs a Spandrel image-to-image model.');+ issues.push({ message: 'Upscale needs a Spandrel image-to-image model.', section: 'source' });}const architecture = upscaleArchitectureFor(values.model);if (!values.model) {- reasons.push(`Upscale needs a ${supportedUpscaleArchitectureLabels()} main model.`);+ issues.push({+ message: `Upscale needs a ${supportedUpscaleArchitectureLabels()} main model.`,+ section: 'generation',+ });} else if (!architecture) {- reasons.push(`Upscale supports only ${supportedUpscaleArchitectureLabels()} main models.`);+ issues.push({+ message: `Upscale supports only ${supportedUpscaleArchitectureLabels()} main models.`,+ section: 'generation',+ });}// `flux_denoise` refuses a Fill model without fill conditioning, which an upscale never supplies.if (values.model?.base === 'flux' && values.model.variant === 'dev_fill') {- reasons.push('Upscale cannot use a FLUX Fill model.');+ issues.push({ message: 'Upscale cannot use a FLUX Fill model.', section: 'generation' });}// Without a reference image `qwen_image_denoise` gives an Edit model a zero reference the size of the output,// which doubles the image tokens of every transformer call, the negative pass's too: about 2.5 to 3 times the// time, and activation memory the cache does not reserve, for nothing the pass uses.if (values.model?.base === 'qwen-image' && values.model.variant === 'edit') {- reasons.push('Upscale cannot use a Qwen Image Edit model.');+ issues.push({ message: 'Upscale cannot use a Qwen Image Edit model.', section: 'generation' });}const tileControlNet = architecture?.tileControlNet ?? null;if (tileControlNet?.required && !values.tileControlnetModel) {- reasons.push('Upscale needs a Tile or Union ControlNet compatible with the main model.');+ issues.push({+ message: 'Upscale needs a Tile or Union ControlNet compatible with the main model.',+ section: 'advanced',+ });} else if (tileControlNet &&values.tileControlnetModel &&!isTileControlNetCandidate(values.tileControlnetModel, values.model)) {- reasons.push(- tileControlNet.required+ issues.push({+ message: tileControlNet.required? 'The Tile ControlNet must match the main model base and be a Tile or Union model.'- : 'The Tile ControlNet must match the main model base and be a Tile model.'- );+ : 'The Tile ControlNet must match the main model base and be a Tile model.',+ section: 'advanced',+ });}// A bare transformer cannot supply these itself, and its loader refuses to run without them.@@ -1061,40 +1101,52 @@ export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?for (const slot of components.slots) {if (!values[slot.field]) {- reasons.push(`Upscale needs a ${slot.label} for this main model.`);+ issues.push({ message: `Upscale needs a ${slot.label} for this main model.`, section: 'advanced' });} else if (!slot.accepts(values[slot.field] as ModelConfig)) {- reasons.push(`${values[slot.field]?.name} is not a ${slot.label} this main model can use.`);+ issues.push({+ message: `${values[slot.field]?.name} is not a ${slot.label} this main model can use.`,+ section: 'advanced',+ });}}if (components.vae && !values.vae) {- reasons.push('Upscale needs a VAE for this main model.');+ issues.push({ message: 'Upscale needs a VAE for this main model.', section: 'advanced' });}- addRangeReason(reasons, 'Scale', values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX);- addRangeReason(reasons, 'Creativity', values.creativity, UPSCALE_CREATIVITY_MIN, UPSCALE_CREATIVITY_MAX);- addRangeReason(reasons, 'Structure', values.structure, UPSCALE_STRUCTURE_MIN, UPSCALE_STRUCTURE_MAX);- addRangeReason(reasons, 'Tile size', values.tileSize, UPSCALE_TILE_SIZE_MIN, UPSCALE_TILE_SIZE_MAX);- addRangeReason(reasons, 'Tile overlap', values.tileOverlap, UPSCALE_TILE_OVERLAP_MIN, UPSCALE_TILE_OVERLAP_MAX);- addRangeReason(reasons, 'Steps', values.steps, upscaleMinSteps(values.model), 1000);- addRangeReason(reasons, 'CFG scale', values.cfgScale, 1, upscaleMaxCfgScale(values.model));- addRangeReason(reasons, 'Seed', values.seed, 0, SEED_MAX);+ addRangeIssue(issues, 'source', 'Scale', values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX);+ addRangeIssue(issues, 'source', 'Creativity', values.creativity, UPSCALE_CREATIVITY_MIN, UPSCALE_CREATIVITY_MAX);+ addRangeIssue(issues, 'source', 'Structure', values.structure, UPSCALE_STRUCTURE_MIN, UPSCALE_STRUCTURE_MAX);+ addRangeIssue(issues, 'advanced', 'Tile size', values.tileSize, UPSCALE_TILE_SIZE_MIN, UPSCALE_TILE_SIZE_MAX);+ addRangeIssue(+ issues,+ 'advanced',+ 'Tile overlap',+ values.tileOverlap,+ UPSCALE_TILE_OVERLAP_MIN,+ UPSCALE_TILE_OVERLAP_MAX+ );+ addRangeIssue(issues, 'generation', 'Steps', values.steps, upscaleMinSteps(values.model), 1000);+ addRangeIssue(issues, 'generation', 'CFG scale', values.cfgScale, 1, upscaleMaxCfgScale(values.model));+ addRangeIssue(issues, 'generation', 'Seed', values.seed, 0, SEED_MAX);if (models) {const installedByKey = new Map(models.map((model) => [model.key, model]));- const required: ModelIdentifierConfig[] = [- ...(values.model ? [values.model] : []),- ...(values.upscaleModel ? [values.upscaleModel] : []),- ...(values.tileControlnetModel ? [values.tileControlnetModel] : []),+ const required: (readonly [ModelIdentifierConfig, UpscaleSection])[] = [+ ...(values.model ? [[values.model, 'generation'] as const] : []),+ ...(values.upscaleModel ? [[values.upscaleModel, 'source'] as const] : []),+ ...(values.tileControlnetModel ? [[values.tileControlnetModel, 'advanced'] as const] : []),// A deleted encoder must block the run rather than fail mid-graph.- ...UPSCALE_COMPONENT_FIELDS.flatMap((field) => (activeComponents[field] ? [activeComponents[field]] : [])),- ...(values.vae ? [values.vae] : []),+ ...UPSCALE_COMPONENT_FIELDS.flatMap((field) =>+ activeComponents[field] ? [[activeComponents[field], 'advanced'] as const] : []+ ),+ ...(values.vae ? [[values.vae, 'advanced'] as const] : []),];- for (const selected of required) {+ for (const [selected, section] of required) {const installed = installedByKey.get(selected.key);if (!installed) {- reasons.push(`${selected.name} is no longer installed.`);+ issues.push({ message: `${selected.name} is no longer installed.`, section });}}@@ -1105,48 +1157,63 @@ export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?: undefined;if (values.model && installedMain && !isSupportedUpscaleMainModel(installedMain)) {- reasons.push(`${values.model.name} is not an installed ${supportedUpscaleArchitectureLabels()} main model.`);+ issues.push({+ message: `${values.model.name} is not an installed ${supportedUpscaleArchitectureLabels()} main model.`,+ section: 'generation',+ });}if (values.upscaleModel && installedSpandrel && !isSpandrelModelConfig(installedSpandrel)) {- reasons.push(`${values.upscaleModel.name} is not an installed Spandrel model.`);+ issues.push({ message: `${values.upscaleModel.name} is not an installed Spandrel model.`, section: 'source' });}if (values.tileControlnetModel &&installedControlNet &&!isTileControlNetCandidate(installedControlNet, values.model)) {- reasons.push(`${values.tileControlnetModel.name} is not an installed compatible Tile ControlNet.`);+ issues.push({+ message: `${values.tileControlnetModel.name} is not an installed compatible Tile ControlNet.`,+ section: 'advanced',+ });}if (values.vae) {const installedVae = installedByKey.get(values.vae.key);if (!installedVae) {- reasons.push(`${values.vae.name} is no longer installed.`);+ issues.push({ message: `${values.vae.name} is no longer installed.`, section: 'advanced' });} else if (!values.model ||!isVaeModelConfig(installedVae) ||!isVaeCompatibleWithGenerateModel(values.model, installedVae)) {- reasons.push(`${values.vae.name} is not compatible with ${values.model?.name ?? 'the main model'}.`);+ issues.push({+ message: `${values.vae.name} is not compatible with ${values.model?.name ?? 'the main model'}.`,+ section: 'advanced',+ });}}for (const lora of values.loras) {const installedLora = installedByKey.get(lora.model.key);if (!installedLora) {- reasons.push(`${lora.model.name} is no longer installed.`);+ issues.push({ message: `${lora.model.name} is no longer installed.`, section: 'generation' });} else if (!isLoraModelConfig(installedLora) ||(values.model && !isLoraCompatibleWithModel(installedLora, values.model))) {- reasons.push(`${lora.model.name} is not compatible with ${values.model?.name ?? 'the main model'}.`);+ issues.push({+ message: `${lora.model.name} is not compatible with ${values.model?.name ?? 'the main model'}.`,+ section: 'generation',+ });}}}- return reasons;+ return issues;};+export const getUpscaleValidationReasons = (values: UpscaleWidgetValues, models?: readonly ModelConfig[]): string[] =>+ getUpscaleValidationIssues(values, models).map((issue) => issue.message);+/** The upscaler's recorded native scale, or null for a record installed before the probe recorded it. */export const getSpandrelNativeScale = (model: SpandrelModelConfig | null | undefined): number | null =>typeof model?.scale === 'number' && Number.isInteger(model.scale) && model.scale >= 1 ? model.scale : null;@@ -1229,6 +1296,10 @@ export const getUpscaleOutputDimensions = (};};+/** Refine reads the prompt Upscale shares with Generate; Model only reads none, so nothing wraps or expands it. */+export const readsUpscalePrompt = (values: Record<string, unknown>): boolean =>+ normalizeUpscaleMode(values.mode) === 'refine';+/** Model only runs the upscaler alone, which gives the same image every time, so iterations would only repeat it. */export const isUpscaleBatchCountFixed = (values: Record<string, unknown>): boolean =>normalizeUpscaleMode(values.mode) === 'model-only';@@ -1251,7 +1322,7 @@ export const resolveUpscaleSubmissionValues = (promptDraft,sourceImageName,}: {- promptDraft: Pick<UpscaleWidgetValues, 'negativePrompt' | 'negativePromptEnabled' | 'positivePrompt'>;+ promptDraft: Pick<ProjectPromptDraft, 'negativePrompt' | 'negativePromptEnabled' | 'positivePrompt'>;sourceImageName: string | undefined;}): UpscaleWidgetValues | null => {@@ -1259,11 +1330,39 @@ export const resolveUpscaleSubmissionValues = (return null;}- return values.mode === 'model-only'- ? { ...values, batchCount: 1, negativePrompt: '', positivePrompt: '', seedMode: 'fixed' }- : { ...values, ...promptDraft };+ if (values.mode === 'model-only') {+ return { ...values, batchCount: 1, negativePrompt: '', positivePrompt: '', seedMode: 'fixed' };+ }++ const { negativePrompt, negativePromptEnabled, positivePrompt } = promptDraft;++ return { ...values, negativePrompt, negativePromptEnabled, positivePrompt };};+/**+ * What a resolved Upscale run submits its prompts and seeds from: its own iterations and seed, with the shared+ * prompt's template and dynamic prompts, as Generate submits that prompt. Model only reads no prompt, so nothing+ * wraps or expands it.+ */+export const getUpscaleSubmissionSource = (+ values: UpscaleWidgetValues,+ promptDraft: ProjectPromptDraft+): GenerateSubmissionSource => ({+ batchCount: values.batchCount,+ negativePrompt: values.negativePrompt,+ negativePromptEnabled: values.negativePromptEnabled,+ positivePrompt: values.positivePrompt,+ seed: values.seed,+ seedMode: values.seedMode,+ ...(values.mode === 'model-only'+ ? { dynamicPromptsEnabled: false, promptTemplate: null }+ : {+ dynamicPromptsEnabled: promptDraft.dynamicPromptsEnabled,+ dynamicPromptsSeedBehaviour: promptDraft.dynamicPromptsSeedBehaviour,+ promptTemplate: promptDraft.promptTemplate,+ }),+});+export const clearDeletedUpscaleInput = (values: UpscaleWidgetValues,deletedImageNames: ReadonlySet<string>diff --git a/invokeai/frontend/webv2/src/features/upscale/index.ts b/invokeai/frontend/webv2/src/features/upscale/index.tsindex 6d326c08e6..49e191a9e7 100644--- a/invokeai/frontend/webv2/src/features/upscale/index.ts+++ b/invokeai/frontend/webv2/src/features/upscale/index.ts@@ -6,10 +6,12 @@ export {getModelOnlyUpscaleFactors,getSpandrelNativeScale,getUpscaleOutputDimensions,+ getUpscaleSubmissionSource,getUpscaleValidationReasons,isUpscaleBatchCountFixed,isUpscaleSourceMetadataCurrent,normalizeUpscaleWidgetValues,+ readsUpscalePrompt,resolveUpscaleSeed,resolveUpscaleSubmissionValues,syncUpscaleWidgetValuesWithModels,@@ -20,4 +22,4 @@ export type {TileControlNetModelConfig,UpscaleWidgetValues,} from './core/types';-export { UpscaleUiProvider, type UpscaleUiAdapter } from './ui/UpscaleUiContext';+export { UPSCALE_SECTION_IDS, UpscaleUiProvider, type UpscaleUiAdapter } from './ui/UpscaleUiContext';diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsxindex 3951e807d8..c380560711 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleFormFields.tsx@@ -1,32 +1,35 @@+import type { PromptTemplateChange } from '@features/generation/components';import type { GenerateLora, MainModelConfig, PromptHistoryItem } from '@features/generation/contracts';-import type { ProjectPromptDraft, ProjectPromptDraftPatch } from '@features/generation/settings';+import type {+ DynamicPromptsConfig,+ ProjectPromptDraft,+ ProjectPromptDraftPatch,+ PromptTemplateSnapshot,+} from '@features/generation/settings';import type { UpscaleWidgetValues } from '@features/upscale/core/types';import { Stack, Text } from '@chakra-ui/react';import { NegativePromptField, PositivePromptField } from '@features/generation/components';import { getGeneratePromptUndoKey } from '@features/generation/react';-import { areProjectPromptDraftsEqual } from '@features/generation/settings';+import {+ areProjectPromptDraftsEqual,+ flattenPromptTemplateExpansion,+ getDynamicPromptsConfig,+ getDynamicPromptsSettingsPatch,+} from '@features/generation/settings';import { upscaleArchitectureFor } from '@features/upscale/core/settings';+import { areJsonValuesStructurallyEqual } from '@platform/core/json';import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';-import { memo, useCallback } from 'react';+import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { areLorasEquivalent, areModelsEquivalent } from './upscaleComparators';import { useUpscaleUiActions } from './UpscaleUiContext';-const PROMPT_DRAFT_KEYS = ['negativePrompt', 'negativePromptEnabled', 'positivePrompt'] as const;--/** The earlier value of each key a recall changed, where it still holds what the recall wrote; edits since stay. */-const getRecallRevert = (- before: ProjectPromptDraft,- written: ProjectPromptDraft,- current: ProjectPromptDraft-): ProjectPromptDraftPatch =>- Object.fromEntries(- PROMPT_DRAFT_KEYS.filter((key) => before[key] !== written[key] && current[key] === written[key]).map((key) => [- key,- before[key],- ])+/** The draft keys a change sets to something other than what they held. */+const getChangedKeys = (before: ProjectPromptDraft, written: ProjectPromptDraftPatch): (keyof ProjectPromptDraft)[] =>+ (Object.keys(written) as (keyof ProjectPromptDraft)[]).filter(+ (key) => !areJsonValuesStructurallyEqual(before[key], written[key]));/**@@ -36,6 +39,8 @@ const getRecallRevert = (export const UpscalePromptFields = memo(function UpscalePromptFields({+ batchCount,+ isSeedFixed,loras,model,negativePromptHeightPx,@@ -46,6 +51,8 @@ export const UpscalePromptFields = memo(projectId,showSyntaxHighlighting,}: {+ batchCount: number;+ isSeedFixed: boolean;loras: GenerateLora[];model: MainModelConfig | null;negativePromptHeightPx: number;@@ -59,8 +66,48 @@ export const UpscalePromptFields = memo(const { t } = useTranslation();const { notifications, readPromptDraft } = useUpscaleUiActions();const negativePromptUsage = upscaleArchitectureFor(model)?.negativePrompt ?? 'always';++ /**+ * Applies a prompt change that reaches past the prompt text, which Ctrl+Z in the prompt cannot undo, with an Undo+ * toast. The prompt is Generate's too, so this Undo takes Generate's prompt slot. `isWhole` changes undo all or+ * nothing.+ */+ const patchWithUndo = useCallback(+ (written: ProjectPromptDraftPatch, title: string, isWhole = false) => {+ // Typing still inside a draft's debounce lands first, so the Undo restores what the user saw.+ flushWorkbenchDrafts();+ const before = readPromptDraft();+ const changedKeys = getChangedKeys(before, written);++ onPatchPromptDraft(written);++ if (changedKeys.length === 0) {+ return;+ }++ notifications.undoable(title, {+ onUndo: () => {+ flushWorkbenchDrafts();+ const current = readPromptDraft();+ // Each key still holding what the change wrote goes back; a key edited since keeps the edit.+ const stillApplied = changedKeys.filter((key) =>+ areJsonValuesStructurallyEqual(current[key], written[key])+ );++ if (stillApplied.length > 0 && (!isWhole || stillApplied.length === changedKeys.length)) {+ onPatchPromptDraft(Object.fromEntries(stillApplied.map((key) => [key, before[key]])));+ } else {+ notifications.info(t('widgets.generate.undoStale'));+ }+ },+ supersedes: getGeneratePromptUndoKey(projectId),+ });+ },+ [notifications, onPatchPromptDraft, projectId, readPromptDraft, t]+ );+// The positive prompt also lands in the prompt box as an edit (Ctrl+Z); replacing the negative prompt as well- // needs the toast's Undo. The prompt is Generate's too, so this Undo takes Generate's prompt slot.+ // needs the toast's Undo.const handleUsePrompt = useCallback((prompt: PromptHistoryItem) => {// A hidden negative prompt is not this model's to replace.@@ -70,39 +117,110 @@ export const UpscalePromptFields = memo(}const before = readPromptDraft();- const written: ProjectPromptDraft = {+ const written: ProjectPromptDraftPatch = {negativePrompt: prompt.negativePrompt ?? '',negativePromptEnabled: prompt.negativePrompt ? true : before.negativePromptEnabled,positivePrompt: prompt.positivePrompt,};- onPatchPromptDraft(written);-if (written.negativePrompt === before.negativePrompt &&written.negativePromptEnabled === before.negativePromptEnabled) {- return;+ onPatchPromptDraft(written);+ } else {+ patchWithUndo(written, t('widgets.generate.promptHistoryUsed'));}+ },+ [negativePromptUsage, onPatchPromptDraft, patchWithUndo, readPromptDraft, t]+ );- notifications.undoable(t('widgets.generate.promptHistoryUsed'), {- onUndo: () => {- // Typing still inside a draft's debounce counts as an edit since, so it lands before the comparison.- flushWorkbenchDrafts();- const revert = getRecallRevert(before, written, readPromptDraft());+ const { promptTemplate } = promptDraft;- if (Object.keys(revert).length > 0) {- onPatchPromptDraft(revert);- } else {- notifications.info(t('widgets.generate.undoStale'));- }- },- // Upscale shares Generate's prompt, so a recall here and one there undo in one slot.- supersedes: getGeneratePromptUndoKey(projectId),- });+ // View mode resets when the template changes so prompts do not become unexpectedly read-only. Choosing or clearing+ // one changes what generates without touching the prompt text, so it gets an Undo; keeping it in step with the+ // catalog does not.+ const applyPromptTemplate = useCallback(+ (template: PromptTemplateSnapshot | null, change: PromptTemplateChange) => {+ const patch: ProjectPromptDraftPatch = { promptTemplate: template, promptTemplateViewMode: false };++ if (change === 'synced' || template?.id === promptTemplate?.id) {+ onPatchPromptDraft(patch);+ } else if (template) {+ patchWithUndo(patch, t('widgets.generate.promptTemplateApplied', { name: template.name }));+ } else {+ patchWithUndo(patch, t('widgets.generate.promptTemplateCleared', { name: promptTemplate?.name ?? '' }));+ }+ },+ [onPatchPromptDraft, patchWithUndo, promptTemplate, t]+ );++ /** Bake the template into the authored prompt and stop applying it. */+ const flattenPromptTemplate = useCallback(+ (positivePrompt: string) => {+ if (!promptTemplate) {+ onPatchPromptDraft({ positivePrompt, promptTemplateViewMode: false });+ return;+ }++ flushWorkbenchDrafts();+ patchWithUndo(+ flattenPromptTemplateExpansion({+ authoredNegativePrompt: readPromptDraft().negativePrompt,+ selectedPositivePrompt: positivePrompt,+ template: promptTemplate,+ }),+ t('widgets.generate.promptTemplateMerged', { name: promptTemplate.name }),+ // Half a merge (the negative prompt without its positive) would be a prompt nobody wrote.+ true+ );},- [negativePromptUsage, notifications, onPatchPromptDraft, projectId, readPromptDraft, t]+ [onPatchPromptDraft, patchWithUndo, promptTemplate, readPromptDraft, t]+ );++ const setTemplateViewMode = useCallback(+ (promptTemplateViewMode: boolean) => onPatchPromptDraft({ promptTemplateViewMode }),+ [onPatchPromptDraft]+ );++ const handleDynamicPromptsChange = useCallback(+ (patch: Partial<DynamicPromptsConfig>) => onPatchPromptDraft(getDynamicPromptsSettingsPatch(patch)),+ [onPatchPromptDraft]+ );+ const {+ dynamicPromptsCombinatorial,+ dynamicPromptsEnabled,+ dynamicPromptsMaxPrompts,+ dynamicPromptsResample,+ dynamicPromptsSampleSeed,+ dynamicPromptsSeedBehaviour,+ } = promptDraft;+ // The settings are Generate's: the shared prompt expands the same way wherever it runs.+ const dynamicPrompts = useMemo(+ () => ({+ ...getDynamicPromptsConfig({+ dynamicPromptsCombinatorial,+ dynamicPromptsEnabled,+ dynamicPromptsMaxPrompts,+ dynamicPromptsResample,+ dynamicPromptsSampleSeed,+ dynamicPromptsSeedBehaviour,+ }),+ isSeedFixed,+ onChange: handleDynamicPromptsChange,+ }),+ [+ dynamicPromptsCombinatorial,+ dynamicPromptsEnabled,+ dynamicPromptsMaxPrompts,+ dynamicPromptsResample,+ dynamicPromptsSampleSeed,+ dynamicPromptsSeedBehaviour,+ handleDynamicPromptsChange,+ isSeedFixed,+ ]);+const handlePositiveChange = useCallback((positivePrompt: string) => onPatchPromptDraft({ positivePrompt }),[onPatchPromptDraft]@@ -125,19 +243,28 @@ export const UpscalePromptFields = memo();return (- <Stack gap="2" p="2">+ <Stack gap="2.5"><Text color="fg.muted" fontSize="xs" textWrap="pretty">{t('widgets.upscale.sharedPromptDescription')}</Text><PositivePromptField+ batchCount={batchCount}+ dynamicPrompts={dynamicPrompts}+ focusOwner="upscale"heightPx={positivePromptHeightPx}+ isTemplateViewMode={promptDraft.promptTemplateViewMode}loras={loras}projectId={projectId}+ promptTemplate={promptTemplate}selectedModel={model ?? undefined}showSyntaxHighlighting={showSyntaxHighlighting}+ takesPendingTemplateDraft={false}value={promptDraft.positivePrompt}+ onApplyPromptTemplate={applyPromptTemplate}onChange={handlePositiveChange}+ onFlattenPromptTemplate={flattenPromptTemplate}onResizeEnd={handlePositiveResizeEnd}+ onTemplateViewModeChange={setTemplateViewMode}onUsePrompt={handleUsePrompt}/>{negativePromptUsage !== 'never' && (@@ -145,20 +272,25 @@ export const UpscalePromptFields = memo(heightPx={negativePromptHeightPx}helpText={negativePromptUsage === 'cfg-gated' ? t('widgets.upscale.negativePromptCfgGated') : undefined}isEnabled={promptDraft.negativePromptEnabled}+ isTemplateViewMode={promptDraft.promptTemplateViewMode}loras={loras}projectId={projectId}selectedModel={model ?? undefined}showSyntaxHighlighting={showSyntaxHighlighting}+ templateNegativePrompt={promptTemplate?.negativePrompt ?? null}value={promptDraft.negativePrompt}onChange={handleNegativeChange}onEnabledChange={handleNegativeEnabledChange}onResizeEnd={handleNegativeResizeEnd}+ onTemplateViewModeChange={setTemplateViewMode}/>)}</Stack>);},(previous, next) =>+ previous.batchCount === next.batchCount &&+ previous.isSeedFixed === next.isSeedFixed &&previous.negativePromptHeightPx === next.negativePromptHeightPx &&previous.onPatchPromptDraft === next.onPatchPromptDraft &&previous.onPatchValues === next.onPatchValues &&diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleHeaderActions.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleHeaderActions.tsxnew file mode 100644index 0000000000..b5456628ed--- /dev/null+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleHeaderActions.tsx@@ -0,0 +1,5 @@+import { GenerationSectionJumpMenu } from '@features/generation/components';++export const UpscaleHeaderActions = ({ instance }: { instance?: { id: string } }) => (+ <GenerationSectionJumpMenu panelId={instance?.id} />+);diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsxindex 59e96d3bca..2d8b529a50 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleUiContext.tsx@@ -1,9 +1,21 @@import type { ProjectPromptDraft, ProjectPromptDraftPatch } from '@features/generation/settings';+import type { UpscaleSection } from '@features/upscale/core/settings';import type { UpscaleWidgetValues } from '@features/upscale/core/types';import type { ReactNode } from 'react';import { createContext, use, useMemo } from 'react';+/**+ * The persisted open state of each Upscale section, kept with Generate's under the same per-user preference. Detail+ * guidance holds the prompt, which an invoke issue opens to show.+ */+export const UPSCALE_SECTION_IDS = {+ advanced: 'upscaleAdvanced',+ detailGuidance: 'upscaleDetailGuidance',+ generation: 'upscaleGeneration',+ source: 'upscaleSource',+} as const satisfies Record<UpscaleSection | 'detailGuidance', string>;+/** This UI port preserves dependency direction: Upscale cannot import Workbench. */export interface UpscaleUiAdapter {/** Notices about this project; `undoable` reports a change that already happened, with its Undo. */diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsxindex 5987b82cd2..90b18bdeef 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/upscale/ui/UpscaleWidgetView.tsx@@ -5,17 +5,7 @@ import type { UpscaleComponentField, UpscaleComponentSlot } from '@features/upscimport type { UpscaleMode, UpscaleWidgetValues } from '@features/upscale/core/types';import type { FeatureHintId } from '@platform/ui/hints/hintRegistry';-import {- Badge,- Box,- createListCollection,- DataList,- SegmentGroup,- Separator,- SimpleGrid,- Stack,- Text,-} from '@chakra-ui/react';+import { Badge, Box, createListCollection, DataList, SegmentGroup, SimpleGrid, Stack, Text } from '@chakra-ui/react';import {addConcept,CapabilitiesGate,@@ -23,11 +13,14 @@ import {type ConceptModelPort,ConceptRow,type ConceptUpdate,+ GenerationSectionIssuesProvider,+ GenerationSectionPanel,GenerationSettingsSection,removeConcept,SeedField,updateConcept,} from '@features/generation/components';+import { useDynamicPrompts } from '@features/generation/react';import {type ArchitectureCapabilitiesSnapshot,ensureArchitectureCapabilitiesLoaded,@@ -35,6 +28,8 @@ import {subscribeArchitectureCapabilities,} from '@features/generation/runtime';import {+ getDynamicPromptsConfig,+ getEffectivePrompts,isLoraCompatibleWithModel,isLoraModelConfig,isMainModelConfig,@@ -57,6 +52,7 @@ import {getModelOnlyUpscalePlan,getSpandrelNativeScale,getUpscaleOutputDimensions,+ getUpscaleValidationIssues,isSpandrelModelConfig,isSupportedUpscaleMainModel,isTileControlNetCandidate,@@ -94,7 +90,7 @@ import { useTranslation } from 'react-i18next';import { areInputImagesEquivalent, valuesAreEqual } from './upscaleComparators';import { UpscalePromptFields } from './UpscaleFormFields';import { UpscaleImageField } from './UpscaleImageField';-import { useUpscaleUi, useUpscaleUiActions } from './UpscaleUiContext';+import { UPSCALE_SECTION_IDS, useUpscaleUi, useUpscaleUiActions } from './UpscaleUiContext';/** Keep props stable across project patches so memoized form sections do not rerender for unrelated field edits. */@@ -273,7 +269,7 @@ const UpscaleOutputPreflight = memo(const isLargeOutput = outputMegapixels >= LARGE_OUTPUT_MEGAPIXELS;return (- <Stack bg="bg.subtle" gap="2" px="2.5" py="2" rounded="md">+ <Stack bg="bg.muted" gap="2" px="2.5" py="2" rounded="md"><DataList.Root gap="1.5" orientation="horizontal"><DataList.Item><DataList.ItemLabel color="fg.subtle" fontSize="xs">@@ -424,7 +420,67 @@ const UpscaleModelReconciler = ({return null;};-export const UpscaleWidgetView = () => {+/**+ * Each range field's error. CFG and Steps take their bounds from the served table, read when this runs, so its+ * revision is an argument: the React Compiler infers a memo's dependencies from what the callback reads, and a table+ * read through a function call is not one of them, so the bounds would stay those of the table before it loaded.+ */+const getFieldErrors = (t: (key: string) => string, values: UpscaleWidgetValues, _capabilitiesRevision: number) => ({+ cfgScale: getRangeError(t('widgets.upscale.cfgScale'), values.cfgScale, 1, upscaleMaxCfgScale(values.model)),+ creativity: getRangeError(+ t('widgets.upscale.creativity'),+ values.creativity,+ UPSCALE_CREATIVITY_MIN,+ UPSCALE_CREATIVITY_MAX+ ),+ scale: getRangeError(t('widgets.upscale.scale'), values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX),+ seed: getRangeError(t('widgets.upscale.seed'), values.seed, 0, SEED_MAX),+ steps: getRangeError(t('widgets.upscale.steps'), values.steps, upscaleMinSteps(values.model), 1000),+ structure: getRangeError(+ t('widgets.upscale.structure'),+ values.structure,+ UPSCALE_STRUCTURE_MIN,+ UPSCALE_STRUCTURE_MAX+ ),+ tileOverlap: getRangeError(+ t('widgets.upscale.tileOverlap'),+ values.tileOverlap,+ UPSCALE_TILE_OVERLAP_MIN,+ UPSCALE_TILE_OVERLAP_MAX+ ),+ tileSize: getRangeError(t('widgets.upscale.tileSize'), values.tileSize, UPSCALE_TILE_SIZE_MIN, UPSCALE_TILE_SIZE_MAX),+});++/**+ * The scheduler choices, the scheduler the pass runs, and the highest CFG it takes, all read from the served table+ * when this runs; the revision is an argument for the reason `getFieldErrors` gives.+ */+const getServedSamplingFields = (model: MainModelConfig | null, scheduler: string, _capabilitiesRevision: number) => ({+ cfgScaleMax: upscaleMaxCfgScale(model),+ scheduler: coerceUpscaleScheduler(model, scheduler),+ schedulerOptions: upscaleSchedulerOptions(model),+});++/**+ * The section of each issue Invoke lists for these values, so each section's count matches Invoke's. The check reads+ * the served table when it runs, so the table's revision is an argument: the React Compiler infers a memo's+ * dependencies from what its callback reads, and the table read inside the check is not one, so without the argument+ * the memo would not re-run when the table arrives or reloads while `values` holds still (the models still loading).+ * Without the table Refine's form is held back, so no section counts anything.+ */+const getIssueSections = (+ values: UpscaleWidgetValues,+ models: readonly ModelConfig[] | undefined,+ capabilitiesRevision: number+): (string | undefined)[] =>+ capabilitiesRevision === 0 && values.mode === 'refine'+ ? []+ : getUpscaleValidationIssues(values, models).map((issue) =>+ issue.section ? UPSCALE_SECTION_IDS[issue.section] : undefined+ );++/** `instance` ties the sections to the header's jump menu; a view rendered outside a widget frame has none. */+export const UpscaleWidgetView = ({ instance }: { instance?: { id: string } }) => {const { t } = useTranslation();const openInModelManager = useOpenModelInManager();const conceptModels = useMemo<ConceptModelPort>(@@ -466,38 +522,11 @@ export const UpscaleWidgetView = () => {.join('|'),[models]);- const errors = useMemo(- () => ({- cfgScale: getRangeError(t('widgets.upscale.cfgScale'), values.cfgScale, 1, upscaleMaxCfgScale(values.model)),- creativity: getRangeError(- t('widgets.upscale.creativity'),- values.creativity,- UPSCALE_CREATIVITY_MIN,- UPSCALE_CREATIVITY_MAX- ),- scale: getRangeError(t('widgets.upscale.scale'), values.scale, UPSCALE_SCALE_MIN, UPSCALE_SCALE_MAX),- seed: getRangeError(t('widgets.upscale.seed'), values.seed, 0, SEED_MAX),- steps: getRangeError(t('widgets.upscale.steps'), values.steps, upscaleMinSteps(values.model), 1000),- structure: getRangeError(- t('widgets.upscale.structure'),- values.structure,- UPSCALE_STRUCTURE_MIN,- UPSCALE_STRUCTURE_MAX- ),- tileOverlap: getRangeError(- t('widgets.upscale.tileOverlap'),- values.tileOverlap,- UPSCALE_TILE_OVERLAP_MIN,- UPSCALE_TILE_OVERLAP_MAX- ),- tileSize: getRangeError(- t('widgets.upscale.tileSize'),- values.tileSize,- UPSCALE_TILE_SIZE_MIN,- UPSCALE_TILE_SIZE_MAX- ),- }),- [t, values]+ const errors = useMemo(() => getFieldErrors(t, values, capabilitiesRevision), [capabilitiesRevision, t, values]);+ // Installs are checked once models load, as Invoke checks them.+ const issueSections = useMemo(+ () => getIssueSections(values, modelsStatus === 'loaded' ? models : undefined, capabilitiesRevision),+ [capabilitiesRevision, models, modelsStatus, values]);const patch = useCallback((next: Partial<UpscaleWidgetValues>) => patchValues(next), [patchValues]);const patchPromptDraft = useCallback((next: ProjectPromptDraftPatch) => patchDraft(next), [patchDraft]);@@ -665,9 +694,10 @@ export const UpscaleWidgetView = () => {const vaePrecisionValue = useMemo(() => [values.vaePrecision], [values.vaePrecision]);// The architecture's own list, less the schedulers that would ignore Creativity, showing the one the// graph will really run. Where one is left there is nothing to choose, and the field goes.- const schedulerOptions = useMemo(() => upscaleSchedulerOptions(values.model), [values.model]);- const scheduler = coerceUpscaleScheduler(values.model, values.scheduler);- const cfgScaleMax = upscaleMaxCfgScale(values.model);+ const { cfgScaleMax, scheduler, schedulerOptions } = useMemo(+ () => getServedSamplingFields(values.model, values.scheduler, capabilitiesRevision),+ [capabilitiesRevision, values.model, values.scheduler]+ );const gateLabels = useMemo(() => ({loadFailed: t('widgets.upscale.capabilitiesLoadFailed'),@@ -677,7 +707,7 @@ export const UpscaleWidgetView = () => {[t]);- const sharedBadge = useMemo(() => <Badge fontFamily="mono">{t('widgets.upscale.shared')}</Badge>, [t]);+ const sharedBadge = useMemo(() => <Badge>{t('widgets.upscale.shared')}</Badge>, [t]);const modeOptions = useMemo(() =>[@@ -688,6 +718,18 @@ export const UpscaleWidgetView = () => {);// Model only keeps the Refine settings as they are, hidden, so switching back restores them.const isRefine = values.mode === 'refine';+ // Folded, Detail guidance still says what Generate's prompt settings make of the prompt it shares: the template+ // wrapped around it and how many prompts it expands to. The expansion is the one Invoke counts.+ const promptExpansion = useDynamicPrompts(+ getEffectivePrompts(promptDraft).positivePrompt,+ isRefine ? getDynamicPromptsConfig(promptDraft) : null+ );+ const templateName = promptDraft.promptTemplate?.name;+ const promptCount = promptExpansion.count;+ const detailGuidanceSummary = useMemo(+ () => [templateName, promptCount > 1 ? t('topbar.invoke.summary.promptCount', { count: promptCount }) : null],+ [promptCount, t, templateName]+ );// Model only can neither show nor plan the passes of an upscaler installed before Invoke recorded native scales;// the field's description says so, and re-identifying it in the Model Manager records it.const isNativeScaleUnknown =@@ -696,15 +738,19 @@ export const UpscaleWidgetView = () => {getSpandrelNativeScale(values.upscaleModel) === null;const form = (- <Stack gap={1} minW={0}>+ <Stack gap={0} minW={0}><UpscaleModelReconcilerkey={`${projectId}:${modelsStatus}:${capabilitiesRevision}:${modelsFingerprint}`}rawValues={rawValues}values={values}/>- <GenerationSettingsSection label={t('widgets.upscale.sourceAndTreatment')} defaultOpen>- <Stack gap="3" p="2">+ <GenerationSettingsSection+ defaultOpen+ label={t('widgets.upscale.sourceAndTreatment')}+ sectionId={UPSCALE_SECTION_IDS.source}+ >+ <Stack gap="2.5"><UpscaleImageField inputImage={values.inputImage} onChange={set.inputImage} /><UpscaleOutputPreflightinputImage={values.inputImage}@@ -816,8 +862,15 @@ export const UpscaleWidgetView = () => {</GenerationSettingsSection>{isRefine ? (- <GenerationSettingsSection badges={sharedBadge} label={t('widgets.upscale.detailGuidance')}>+ <GenerationSettingsSection+ status={sharedBadge}+ summary={detailGuidanceSummary}+ label={t('widgets.upscale.detailGuidance')}+ sectionId={UPSCALE_SECTION_IDS.detailGuidance}+ ><UpscalePromptFields+ batchCount={values.batchCount}+ isSeedFixed={values.seedMode === 'fixed'}loras={values.loras}model={values.model}negativePromptHeightPx={values.negativePromptHeightPx}@@ -832,8 +885,8 @@ export const UpscaleWidgetView = () => {) : null}{isRefine ? (- <GenerationSettingsSection label={t('widgets.upscale.generation')}>- <Stack gap="3" p="2">+ <GenerationSettingsSection label={t('widgets.upscale.generation')} sectionId={UPSCALE_SECTION_IDS.generation}>+ <Stack gap="2.5"><Fielderror={values.model@@ -855,7 +908,6 @@ export const UpscaleWidgetView = () => {onChange={selectMainModel}/></Field>- <Separator borderColor="border.subtle" />{/* Iterations live in the top bar's invoke cluster, which edits this widget's batch count directly. */}<ScrubberFielderror={errors.steps}@@ -889,7 +941,6 @@ export const UpscaleWidgetView = () => {/></Field>) : null}- <Separator borderColor="border.subtle" /><SeedFieldbatchCount={values.batchCount}error={errors.seed}@@ -898,7 +949,6 @@ export const UpscaleWidgetView = () => {seedMode={values.seedMode}onCommit={patch}/>- <Separator borderColor="border.subtle" /><Field hint="concepts" label={t('widgets.upscale.concepts')}><ModelSelectexcludeKeys={selectedLoraKeys}@@ -931,8 +981,8 @@ export const UpscaleWidgetView = () => {) : null}{isRefine ? (- <GenerationSettingsSection label={t('widgets.upscale.advanced')}>- <Stack gap="3" p="2">+ <GenerationSettingsSection label={t('widgets.upscale.advanced')} sectionId={UPSCALE_SECTION_IDS.advanced}>+ <Stack gap="2.5">{tileControlNet?.required && (<Fielderror={@@ -1054,20 +1104,22 @@ export const UpscaleWidgetView = () => {// The mode sits above the gate: Model only reads no main-model capabilities, so it stays reachable and usable while// the table is loading or has failed, which holds back only Refine's form.return (- <Stack gap={1} minW={0} p="1">- <Box px="2" pt="2">- <Field helpText={t('widgets.upscale.modeHelp')} label={t('widgets.upscale.mode')}>- <SegmentedControl- ariaLabel={t('widgets.upscale.mode')}- options={modeOptions}- value={values.mode}- onChange={set.mode}- />- </Field>- </Box>- <CapabilitiesGate isReady={hasCapabilities || !isRefine} labels={gateLabels}>- {form}- </CapabilitiesGate>- </Stack>+ <GenerationSectionPanel id={instance?.id}>+ <Stack gap={0} minW={0}>+ <Box px="2" pt="3" pb="3">+ <Field helpText={t('widgets.upscale.modeHelp')} label={t('widgets.upscale.mode')}>+ <SegmentedControl+ ariaLabel={t('widgets.upscale.mode')}+ options={modeOptions}+ value={values.mode}+ onChange={set.mode}+ />+ </Field>+ </Box>+ <CapabilitiesGate isReady={hasCapabilities || !isRefine} labels={gateLabels}>+ <GenerationSectionIssuesProvider issueSections={issueSections}>{form}</GenerationSectionIssuesProvider>+ </CapabilitiesGate>+ </Stack>+ </GenerationSectionPanel>);};diff --git a/invokeai/frontend/webv2/src/features/upscale/ui/implementation.ts b/invokeai/frontend/webv2/src/features/upscale/ui/implementation.tsindex e3ad07de6b..fad09f1db7 100644--- a/invokeai/frontend/webv2/src/features/upscale/ui/implementation.ts+++ b/invokeai/frontend/webv2/src/features/upscale/ui/implementation.ts@@ -1,3 +1,4 @@+import { UpscaleHeaderActions } from './UpscaleHeaderActions';import { UpscaleWidgetView } from './UpscaleWidgetView';-export const widgetImplementation = { view: UpscaleWidgetView };+export const widgetImplementation = { headerActions: UpscaleHeaderActions, view: UpscaleWidgetView };diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.tsindex 7576e8c81a..06f481d4b7 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.test.ts@@ -23,11 +23,14 @@ import {getVideoComponentSectionPolicy,getVideoDimensions,getVideoExpandPromptSuggestion,- getVideoModelAvailabilityReasons,+ getVideoIssueSections,+ getVideoModelAvailabilityIssues,getVideoModelPolicy,+ getVideoPanelFields,getVideoModelSelectionResult,getVideoModes,getVideoPromptPolicy,+ getVideoValidationIssues,getVideoValidationReasons,getAutoDurationBounds,isAutoDurationActive,@@ -40,7 +43,11 @@ import {snapVideoNumFrames,WAN_LIGHTNING_ACCELERATOR,} from './videoPolicies';-import { syncVideoWidgetValuesWithModels } from './widgetValues';+import {+ createDefaultVideoWidgetValues,+ getVideoWidgetValidationIssues,+ syncVideoWidgetValuesWithModels,+} from './widgetValues';const wanModel = (variant: string, format = 'gguf_quantized', key = `wan-${variant}-${format}`): MainModelConfig => ({base: 'wan',@@ -1525,7 +1532,9 @@ describe('getVideoValidationReasons', () => {});});-describe('getVideoModelAvailabilityReasons', () => {+describe('getVideoModelAvailabilityIssues', () => {+ const messagesOf = (issues: readonly { message: string }[]) => issues.map((issue) => issue.message);+it('reports uninstalled selections by label', () => {const model = wanModel('i2v_a14b');const settings = settingsFor(model, {@@ -1533,13 +1542,13 @@ describe('getVideoModelAvailabilityReasons', () => {wanT5EncoderModel: { base: 'any', key: 'umt5', name: 'UMT5-XXL', type: 'wan_t5_encoder' },});- const reasons = getVideoModelAvailabilityReasons(model, settings, []);+ const reasons = messagesOf(getVideoModelAvailabilityIssues(model, settings, []));expect(reasons).toContainEqual(expect.stringContaining('is no longer installed'));expect(reasons.some((reason) => reason.includes('UMT5-XXL'))).toBe(true);expect(reasons.some((reason) => reason.includes('Lightning'))).toBe(true);- const installed = getVideoModelAvailabilityReasons(model, settingsFor(model), [model]);+ const installed = messagesOf(getVideoModelAvailabilityIssues(model, settingsFor(model), [model]));expect(installed).toEqual([]);});@@ -1553,7 +1562,7 @@ describe('getVideoModelAvailabilityReasons', () => {],});- expect(getVideoModelAvailabilityReasons(model, settings, [model])).toEqual([]);+ expect(messagesOf(getVideoModelAvailabilityIssues(model, settings, [model]))).toEqual([]);});});@@ -2817,3 +2826,97 @@ describe('what a model switch discards', () => {expect(result.adjustments).toEqual(expect.arrayContaining(['targetResolution', 'frames', 'fps']));});});++describe('the Video sections an issue is fixed from', () => {+ const t2v = wanModel('t2v_a14b', 'diffusers');+ const i2v = wanModel('i2v_a14b', 'diffusers');+ const ti2v = wanModel('ti2v_5b', 'diffusers');+ /** The sections the panel would count `message` in for these settings. */+ const sectionsOf = (model: MainModelConfig, settings: VideoSettings, message: string) => {+ const issue = getVideoValidationIssues(model, settings).find((candidate) => candidate.message.includes(message));++ return issue ? getVideoIssueSections(issue, getVideoPanelFields(model, settings)) : undefined;+ };++ it.each([+ [+ 'a first frame beside an initial video, both shown',+ i2v,+ { firstFrameImage: FIRST_FRAME, sourceVideo: SOURCE_VIDEO },+ 'A first frame and an initial video',+ ['frames', 'source'],+ ],+ // TI2V-5B shows no last-frame field: only the initial video can be cleared from a section.+ [+ 'a destination image while extending',+ ti2v,+ { lastFrameImage: LAST_FRAME, sourceVideo: SOURCE_VIDEO },+ 'cannot target a destination image',+ ['source'],+ ],+ // The fix is adding media the model takes: a first or last frame, or a video to extend.+ ['text-to-video on an image-to-video model', i2v, {}, 'does not support text-to-video', ['frames', 'source']],+ // The first-frame field is hidden on T2V; only the stale-media stub clears it.+ [+ 'a first frame the model cannot start from',+ t2v,+ { firstFrameImage: FIRST_FRAME },+ 'does not support starting from a first frame',+ [],+ ],+ ['an extension the model cannot run', t2v, { sourceVideo: SOURCE_VIDEO }, 'does not support extending a video', []],+ ['a frame count off the grid', t2v, { numFrames: 80 }, '4·n + 1', ['dimensions']],+ ['an editable frame rate out of range', t2v, { fps: 0 }, 'FPS must be a whole number', ['dimensions']],+ ['a fixed frame rate no field sets', h3Model(), { fps: 16 }, 'fixed 24 FPS', []],+ ['too few steps', h3Model(), { steps: 1 }, 'at least 2', ['render']],+ // The distilled checkpoint shows its step count as fixed text.+ ['steps on a fixed schedule', ltx2('ltx2_distilled'), { steps: 0 }, 'Steps must be a whole number', []],+ ['a low-noise CFG under 1', t2v, { cfgScaleLowNoise: 0.5 }, 'CFG (Low Noise)', ['render']],+ [+ 'an initial video at a frame rate Wan cannot extend',+ i2v,+ { sourceVideo: { ...SOURCE_VIDEO, fps: 240 } },+ '1-120 fps',+ ['source'],+ ],+ ] as const)('places %s', (_, model, overrides, message, sections) => {+ expect(sectionsOf(model, settingsFor(model, overrides as Partial<VideoSettings>), message)).toEqual(sections);+ });++ it('places what the components picker lacks under Components', () => {+ const gguf = ltx2('ltx2_distilled', { format: 'gguf_quantized', key: 'ltx2-distilled-gguf' });+ const settings = settingsFor(gguf, { ltx2TextEncoderModel: LTX2_ENCODER });+ const issues = getVideoValidationIssues(gguf, settings);++ expect(issues).not.toEqual([]);+ expect(issues.map((issue) => getVideoIssueSections(issue, getVideoPanelFields(gguf, settings)))).toEqual(+ issues.map(() => ['components'])+ );+ });++ it('places an uninstalled component under Components, and the main model and a LoRA nowhere', () => {+ const model = wanModel('i2v_a14b');+ const settings = settingsFor(model, {+ loras: [{ isEnabled: true, model: LIGHTNING_T2V_HIGH as never, weight: 1 }],+ wanT5EncoderModel: { base: 'any', key: 'umt5', name: 'UMT5-XXL', type: 'wan_t5_encoder' },+ });+ const shown = getVideoPanelFields(model, settings);++ expect(+ getVideoModelAvailabilityIssues(model, settings, []).map((issue) => [+ issue.message,+ getVideoIssueSections(issue, shown),+ ])+ ).toEqual([+ [`Selected model "${model.name}" is no longer installed.`, []],+ ['Wan T5 Encoder "UMT5-XXL" is no longer installed.', ['components']],+ [`LoRA "${LIGHTNING_T2V_HIGH.name}" is no longer installed.`, []],+ ]);+ });++ it('places a missing model nowhere, since the model picker sits above the sections', () => {+ expect(getVideoWidgetValidationIssues(createDefaultVideoWidgetValues())).toEqual([+ { fields: [], message: 'Video needs a Wan 2.2, MiniMax H3 or LTX-2 main model.' },+ ]);+ });+});diff --git a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.tsindex 3d19dc2920..82c298786c 100644--- a/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts+++ b/invokeai/frontend/webv2/src/features/video/core/videoPolicies.ts@@ -2257,22 +2257,151 @@ const VIDEO_MODE_DESCRIPTIONS: Record<VideoGenerationMode, string> = {const hasModelKey = (models: readonly ModelConfig[], key: string, type?: string): boolean =>models.some((model) => model.key === key && (!type || model.type === type));-export const getVideoModelAvailabilityReasons = (+/** The Video panel section whose fields fix an issue. */+export type VideoSection =+ | 'components'+ | 'concepts'+ | 'conditioningClip'+ | 'dimensions'+ | 'frames'+ | 'guidance'+ | 'references'+ | 'render'+ | 'source';++/** A Video panel control an issue can be fixed from. */+export type VideoField =+ | 'accelerator'+ | 'audioCfg'+ | 'cfg'+ | 'cfgLowNoise'+ | 'components'+ | 'concepts'+ | 'conditioningClip'+ | 'extendContext'+ | 'firstFrame'+ | 'fps'+ | 'initialVideo'+ | 'lastFrame'+ | 'modality'+ | 'numFrames'+ | 'references'+ | 'steps'+ | 'stg'+ | 'targetResolution';++/** The section each control sits in. */+const VIDEO_FIELD_SECTIONS: Record<VideoField, VideoSection> = {+ accelerator: 'render',+ audioCfg: 'guidance',+ cfg: 'render',+ cfgLowNoise: 'render',+ components: 'components',+ concepts: 'concepts',+ conditioningClip: 'conditioningClip',+ extendContext: 'source',+ firstFrame: 'frames',+ fps: 'dimensions',+ initialVideo: 'source',+ lastFrame: 'frames',+ modality: 'guidance',+ numFrames: 'dimensions',+ references: 'references',+ steps: 'render',+ stg: 'guidance',+ targetResolution: 'dimensions',+};++/**+ * One reason Video cannot run, in English, and every control that can fix it: a conflict between two media lists+ * both, since clearing either fixes it. None when only the model picker can, or no control sets the value.+ */+export interface VideoValidationIssue {+ fields: readonly VideoField[];+ message: string;+}++const when = (condition: unknown, field: VideoField): VideoField[] => (condition ? [field] : []);++/**+ * The media that put the panel in each mode, which an unsupported mode is fixed by clearing; text-to-video, which has+ * none, is fixed by adding whichever media the model takes.+ */+const VIDEO_MODE_FIELDS: Record<VideoGenerationMode, readonly VideoField[]> = {+ 'audio-to-video': ['conditioningClip'],+ extend: ['initialVideo'],+ 'first-frame': ['firstFrame'],+ 'first-last': ['firstFrame', 'lastFrame'],+ 'last-frame': ['lastFrame'],+ reference: ['references'],+ txt2vid: ['conditioningClip', 'firstFrame', 'initialVideo', 'lastFrame', 'references'],+ 'video-to-audio': ['conditioningClip'],+};++/**+ * The controls the panel shows, and lets the user change, for this model and these settings. The panel renders its+ * media sections and its locked controls from it, and an issue counts only in the sections of the controls listed+ * here, so a count never points at a control the panel hides or holds read-only.+ */+export const getVideoPanelFields = (+ model: MainModelConfig | undefined,+ settings: VideoSettings,+ policy: VideoModelPolicy = getVideoModelPolicy(model, settings)+): ReadonlySet<VideoField> => {+ const { modes, ui } = policy;+ const supportsExtend = modes.includes('extend');+ const fields: [VideoField, boolean][] = [+ ['accelerator', Boolean(model && ui.accelerator)],+ ['audioCfg', ui.audioCfgVisible],+ ['cfg', ui.cfgVisible],+ ['cfgLowNoise', ui.cfgLowNoiseVisible],+ ['components', Boolean(model) && getVideoComponentSectionPolicy(model, settings).slots.length > 0],+ ['concepts', true],+ ['conditioningClip', modes.includes('audio-to-video') || modes.includes('video-to-audio')],+ ['extendContext', ui.extendContext !== null],+ ['firstFrame', modes.includes('first-frame') || modes.includes('first-last')],+ // Locked to the initial video while extending, and to a clip that sets the rate.+ [+ 'fps',+ ui.fpsVisible && resolveVideoMode(settings) !== 'extend' && !getEffectiveVideoTiming(model, settings).fpsFromClip,+ ],+ ['initialVideo', supportsExtend || Boolean(policy.references?.extend)],+ ['lastFrame', modes.includes('first-last') || modes.includes('last-frame')],+ ['modality', ui.modalityVisible],+ ['numFrames', true],+ ['references', modes.includes('reference')],+ ['steps', ui.stepsEditable],+ ['stg', ui.stgVisible],+ ['targetResolution', true],+ ];++ return new Set(fields.flatMap(([field, shown]) => (shown ? [field] : [])));+};++/** The sections whose shown controls can fix `issue`, each once. */+export const getVideoIssueSections = (issue: VideoValidationIssue, shown: ReadonlySet<VideoField>): VideoSection[] => [+ ...new Set(issue.fields.flatMap((field) => (shown.has(field) ? [VIDEO_FIELD_SECTIONS[field]] : []))),+];++export const getVideoModelAvailabilityIssues = (model: MainModelConfig,settings: VideoSettings,models: readonly ModelConfig[]-): string[] => {- const reasons: string[] = [];+): VideoValidationIssue[] => {+ const issues: VideoValidationIssue[] = [];if (!hasModelKey(models, model.key, model.type)) {- reasons.push(`Selected model "${model.name}" is no longer installed.`);+ issues.push({ fields: [], message: `Selected model "${model.name}" is no longer installed.` });}for (const key of Object.keys(VIDEO_COMPONENT_SETTING_LABELS) as VideoComponentValueKey[]) {const value = settings[key];if (value && !hasModelKey(models, value.key, value.type)) {- reasons.push(`${VIDEO_COMPONENT_SETTING_LABELS[key]} "${value.name}" is no longer installed.`);+ issues.push({+ fields: ['components'],+ message: `${VIDEO_COMPONENT_SETTING_LABELS[key]} "${value.name}" is no longer installed.`,+ });}}@@ -2283,16 +2412,19 @@ export const getVideoModelAvailabilityReasons = (isLoraCompatibleWithModel(lora.model, model) &&!hasModelKey(models, lora.model.key, 'lora')) {- reasons.push(`LoRA "${lora.model.name}" is no longer installed.`);+ // The panel's synced list has already dropped the row, so no section can show it.+ issues.push({ fields: [], message: `LoRA "${lora.model.name}" is no longer installed.` });}}- return reasons;+ return issues;};-export const getVideoValidationReasons = (model: MainModelConfig, settings: VideoSettings): string[] => {+/** Why Video cannot run with this model, each with the controls that fix it, in the order Invoke lists them. */+export const getVideoValidationIssues = (model: MainModelConfig, settings: VideoSettings): VideoValidationIssue[] => {+ // The model picker fixes these, and it sits in no section.if (!isSupportedVideoModel(model)) {- return ['Video needs a supported video model before it can be invoked.'];+ return [{ message: 'Video needs a supported video model before it can be invoked.', fields: [] }];}// Give repair guidance for stored supported-but-unselectable configurations.@@ -2300,28 +2432,44 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videconst family = model.base === 'ltx-2' ? 'LTX-2' : 'MiniMax H3';return [- `${model.name} is a components-only install. Select a single-file ${family} transformer as the model; this install then provides its components.`,+ {+ message: `${model.name} is a components-only install. Select a single-file ${family} transformer as the model; this install then provides its components.`,+ fields: [],+ },];}if (model.base === 'minimax-h3' && model.format === 'diffusers' && model.variant === 'ref2va') {return [- `${model.name} is a Ref2VA folder install, whose transformer weights cannot be folder-loaded. Select a single-file Ref2VA transformer as the model; this install can serve as its Model Components.`,+ {+ message: `${model.name} is a Ref2VA folder install, whose transformer weights cannot be folder-loaded. Select a single-file Ref2VA transformer as the model; this install can serve as its Model Components.`,+ fields: [],+ },];}const config = getVideoConfig(model);- const reasons: string[] = [];+ const issues: VideoValidationIssue[] = [];const mode = resolveVideoMode(settings);const referenceOnly = config.modes.length === 1 && config.modes[0] === 'reference';if (settings.firstFrameImage && settings.sourceVideo) {- reasons.push('A first frame and an initial video cannot be combined. Clear one of them.');+ issues.push({+ fields: ['firstFrame', 'initialVideo'],+ message: 'A first frame and an initial video cannot be combined. Clear one of them.',+ });}if (settings.conditioningClip && (settings.sourceVideo || settings.references.length > 0)) {// Both claim the run's conditioning wholesale, and `resolveVideoMode` would silently drop one// rather than run something it cannot express.- reasons.push('A conditioning clip cannot be combined with an initial video or references. Clear one side.');+ issues.push({+ fields: [+ 'conditioningClip',+ ...when(settings.sourceVideo, 'initialVideo'),+ ...when(settings.references.length > 0, 'references'),+ ],+ message: 'A conditioning clip cannot be combined with an initial video or references. Clear one side.',+ });}if (@@ -2330,26 +2478,49 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Vide) {// A clip's picture already fills every frame these would hold. Its soundtrack does not, which is// why the frames stay available in that role.- reasons.push("A conditioning clip's picture cannot be combined with first/last frames. Clear one side.");+ issues.push({+ fields: [+ 'conditioningClip',+ ...when(settings.firstFrameImage, 'firstFrame'),+ ...when(settings.lastFrameImage, 'lastFrame'),+ ],+ message: "A conditioning clip's picture cannot be combined with first/last frames. Clear one side.",+ });}if (settings.references.length > 0 && (settings.firstFrameImage || settings.lastFrameImage)) {- reasons.push('References cannot be combined with first/last frames. Clear one side.');+ issues.push({+ fields: [+ 'references',+ ...when(settings.firstFrameImage, 'firstFrame'),+ ...when(settings.lastFrameImage, 'lastFrame'),+ ],+ message: 'References cannot be combined with first/last frames. Clear one side.',+ });}if (settings.references.length > 0 && settings.sourceVideo && !config.references?.extend) {- reasons.push('References cannot be combined with an initial video on this model. Clear one side.');+ issues.push({+ fields: ['references', 'initialVideo'],+ message: 'References cannot be combined with an initial video on this model. Clear one side.',+ });}if (!config.modes.includes(mode)) {if (referenceOnly && settings.references.length === 0) {// Explain the missing reference rather than implying a defective text-to-video model.- reasons.push('Reference-to-video needs at least one reference.');+ issues.push({ fields: ['references'], message: 'Reference-to-video needs at least one reference.' });} else {- reasons.push(`${model.name} does not support ${VIDEO_MODE_DESCRIPTIONS[mode]}.`);+ issues.push({+ fields: VIDEO_MODE_FIELDS[mode],+ message: `${model.name} does not support ${VIDEO_MODE_DESCRIPTIONS[mode]}.`,+ });}} else if (mode === 'extend' && settings.lastFrameImage && !config.modes.includes('first-last')) {- reasons.push(`${model.name} cannot target a destination image while extending a video.`);+ issues.push({+ fields: ['initialVideo', 'lastFrame'],+ message: `${model.name} cannot target a destination image while extending a video.`,+ });}if (mode === 'reference') {@@ -2357,17 +2528,17 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videconst videoCount = settings.references.filter((reference) => reference.kind === 'video').length;const imageCount = settings.references.length - videoCount;if (caps && videoCount > caps.maxVideos) {- reasons.push(`At most ${caps.maxVideos} video references are supported.`);+ issues.push({ fields: ['references'], message: `At most ${caps.maxVideos} video references are supported.` });}if (caps && imageCount > caps.maxImages) {- reasons.push(`At most ${caps.maxImages} image references are supported.`);+ issues.push({ fields: ['references'], message: `At most ${caps.maxImages} image references are supported.` });}for (const reference of settings.references) {if (reference.kind !== 'video') {continue;}if (!Number.isInteger(reference.clip.startFrame) || !Number.isInteger(reference.clip.endFrame)) {- reasons.push('Reference video trim bounds must be whole frame numbers.');+ issues.push({ fields: ['references'], message: 'Reference video trim bounds must be whole frame numbers.' });break;}if (@@ -2375,7 +2546,7 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videreference.clip.endFrame > reference.clip.numFrames - 1 ||reference.clip.endFrame < reference.clip.startFrame) {- reasons.push('A reference video trim is outside its clip.');+ issues.push({ fields: ['references'], message: 'A reference video trim is outside its clip.' });break;}}@@ -2392,13 +2563,16 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Vide? config.frames.max: (config.frames.choices[config.frames.choices.length - 1] ?? 0);- reasons.push(- timing.numFramesFromClip+ issues.push({+ fields: timing.numFramesFromClip+ ? ['conditioningClip', ...when(settings.conditioningClip?.role === 'audio', 'fps')]+ : ['numFrames'],+ message: timing.numFramesFromClip? `The conditioning clip works out to ${timing.numFrames} frames, outside the ${framesFloor}-${framesCeiling} ${model.name} generates. Use a ${timing.numFrames < framesFloor ? 'longer' : 'shorter'} clip${settings.conditioningClip?.role === 'audio' ? ', or change the frame rate' : ''}.`: config.frames.kind === 'grid'? `Frame count must be between ${config.frames.min} and ${config.frames.max} in steps of ${config.frames.step} (${describeVideoFramesGrid(config.frames)}).`- : `Frame count must be one of the ${model.name} grid values (17·n + 5, ${config.frames.choices[0]}–${config.frames.choices[config.frames.choices.length - 1]}).`- );+ : `Frame count must be one of the ${model.name} grid values (17·n + 5, ${config.frames.choices[0]}–${config.frames.choices[config.frames.choices.length - 1]}).`,+ });}// fps and steps are integer fields on the backend nodes; a fractional value@@ -2410,17 +2584,18 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videtiming.fps < config.fps.min ||timing.fps > config.fps.max) {- reasons.push(- timing.fpsFromClip+ issues.push({+ fields: timing.fpsFromClip ? ['conditioningClip'] : ['fps'],+ message: timing.fpsFromClip? `The conditioning clip runs at ${timing.fps} fps, outside the ${config.fps.min}-${config.fps.max} fps range ${model.name} supports.`: config.fps.editable? `FPS must be a whole number between ${config.fps.min} and ${config.fps.max}.`- : `${model.name} generates at a fixed ${config.fps.defaultValue} FPS.`- );+ : `${model.name} generates at a fixed ${config.fps.defaultValue} FPS.`,+ });}if (!Number.isInteger(settings.steps) || settings.steps < config.minSteps) {- reasons.push(`Steps must be a whole number of at least ${config.minSteps}.`);+ issues.push({ fields: ['steps'], message: `Steps must be a whole number of at least ${config.minSteps}.` });}// A two-stage preset caps the refine pass at the base pass's budget, and a refine of one step can@@ -2432,16 +2607,19 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Vide// every token, so the conditioning would have to be re-encoded at the refine canvas the way a// first frame is. Caught here, before the base pass and the upscale have been paid for.if (preset?.stages === 2 && !isTwoStageSupportedForMode(mode)) {- reasons.push(- `${VIDEO_MODE_DESCRIPTIONS[mode][0]?.toUpperCase()}${VIDEO_MODE_DESCRIPTIONS[mode].slice(1)} does not run a two-stage target resolution. Pick a single-stage resolution, or clear the conditioning clip.`- );+ issues.push({+ fields: ['targetResolution', 'conditioningClip'],+ message: `${VIDEO_MODE_DESCRIPTIONS[mode][0]?.toUpperCase()}${VIDEO_MODE_DESCRIPTIONS[mode].slice(1)} does not run a two-stage target resolution. Pick a single-stage resolution, or clear the conditioning clip.`,+ });}if (preset?.stages === 2 && Number.isInteger(settings.steps) && settings.steps < LTX2_MIN_TWO_STAGE_STEPS) {- reasons.push(- `A two-stage target resolution needs at least ${LTX2_MIN_TWO_STAGE_STEPS} steps; the second pass ` +- `refines what the first produced and cannot run in one.`- );+ issues.push({+ fields: ['targetResolution', 'steps'],+ message:+ `A two-stage target resolution needs at least ${LTX2_MIN_TWO_STAGE_STEPS} steps; the second pass ` ++ `refines what the first produced and cannot run in one.`,+ });}// An LTX-2 continuation replays the front of the source and then joins the two halves by@@ -2453,64 +2631,85 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videconst context = settings.ltx2ExtendContextFrames;if (settings.numFrames <= context) {- reasons.push(- `A continuation opens with ${context} frames of the source, so anything at or ` +- `below that would be all replay and no continuation. Raise Frames above ${context}.`- );+ issues.push({+ fields: ['numFrames', 'extendContext'],+ message:+ `A continuation opens with ${context} frames of the source, so anything at or ` ++ `below that would be all replay and no continuation. Raise Frames above ${context}.`,+ });}const affordable = ltx2MaxExtendContextFrames(settings.sourceVideo.width, settings.sourceVideo.height);if (affordable === 0) {- reasons.push(- `The join blends the held frames of the initial video at its own ` ++ issues.push({+ fields: ['initialVideo'],+ message:+ `The join blends the held frames of the initial video at its own ` +`${settings.sourceVideo.width}x${settings.sourceVideo.height}, which needs more memory than it is ` +- `allowed even at the smallest context. Use a source at or below about 2560x1440.`- );+ `allowed even at the smallest context. Use a source at or below about 2560x1440.`,+ });} else if (context > affordable) {// Reachable by loading a recalled or stored setting against a larger source than it was made// for; the control itself is bounded, so dragging cannot get here.- reasons.push(- `Context Frames is ${context}, but blending that many frames of a ` ++ issues.push({+ fields: ['extendContext'],+ message:+ `Context Frames is ${context}, but blending that many frames of a ` +`${settings.sourceVideo.width}x${settings.sourceVideo.height} source needs more memory than the join ` +- `is allowed. Lower it to ${affordable} or less.`- );+ `is allowed. Lower it to ${affordable} or less.`,+ });}const kept = settings.sourceVideo.endFrame - settings.sourceVideo.startFrame + 1;if (kept < context) {- reasons.push(- `The join blends ${context} frames out of each half, but the initial video's trim ` +- `keeps only ${kept}. Keep at least ${context} frames of it, or lower Context Frames.`- );+ issues.push({+ fields: ['initialVideo', 'extendContext'],+ message:+ `The join blends ${context} frames out of each half, but the initial video's trim ` ++ `keeps only ${kept}. Keep at least ${context} frames of it, or lower Context Frames.`,+ });}}if (config.cfg.visible && (!Number.isFinite(settings.cfgScale) || settings.cfgScale < 1)) {- reasons.push('CFG must be at least 1.');+ issues.push({ fields: ['cfg'], message: 'CFG must be at least 1.' });}if (config.cfg.lowNoiseVisible && settings.cfgScaleLowNoise !== null && settings.cfgScaleLowNoise < 1) {- reasons.push('CFG (Low Noise) must be at least 1.');+ issues.push({ fields: ['cfgLowNoise'], message: 'CFG (Low Noise) must be at least 1.' });}// The floors are the denoise node's own `ge`: a value below one fails// pydantic validation at enqueue, after the graph has been built.const guidanceBounds = [- { floor: 1, label: 'Audio CFG', value: config.guidance.audioVisible ? settings.audioCfgScale : null },- { floor: 0, label: 'STG', value: config.guidance.stgVisible ? settings.stgScale : null },- { floor: 1, label: 'Modality guidance', value: config.guidance.modalityVisible ? settings.modalityScale : null },+ {+ field: 'audioCfg' as const,+ floor: 1,+ label: 'Audio CFG',+ value: config.guidance.audioVisible ? settings.audioCfgScale : null,+ },+ { field: 'stg' as const, floor: 0, label: 'STG', value: config.guidance.stgVisible ? settings.stgScale : null },+ {+ field: 'modality' as const,+ floor: 1,+ label: 'Modality guidance',+ value: config.guidance.modalityVisible ? settings.modalityScale : null,+ },];- for (const { floor, label, value } of guidanceBounds) {+ for (const { field, floor, label, value } of guidanceBounds) {if (value !== null && (!Number.isFinite(value) || value < floor)) {- reasons.push(`${label} must be at least ${floor}.`);+ issues.push({ fields: [field], message: `${label} must be at least ${floor}.` });}}if (settings.acceleratorEnabled && !config.accelerator) {- reasons.push(`${model.name} has no distillation fast path. Turn the accelerator off to generate with it.`);+ issues.push({+ fields: ['accelerator'],+ message: `${model.name} has no distillation fast path. Turn the accelerator off to generate with it.`,+ });}// The trim bounds are integer fields on extract_video_range; a fractional@@ -2519,17 +2718,20 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videsettings.sourceVideo &&(!Number.isInteger(settings.sourceVideo.startFrame) || !Number.isInteger(settings.sourceVideo.endFrame))) {- reasons.push('The initial video trim bounds must be whole frame numbers.');+ issues.push({ fields: ['initialVideo'], message: 'The initial video trim bounds must be whole frame numbers.' });} else if (settings.sourceVideo) {const { endFrame, numFrames, startFrame } = settings.sourceVideo;// Require valid source bounds and at least two frames for crossfade before encoding.if (startFrame < 0 || endFrame > numFrames - 1 || endFrame - startFrame + 1 < MIN_VIDEO_TRIM_FRAMES) {- reasons.push('The initial video trim must keep at least two frames within the clip.');+ issues.push({+ fields: ['initialVideo'],+ message: 'The initial video trim must keep at least two frames within the clip.',+ });}if (numFrames < MIN_VIDEO_TRIM_FRAMES) {- reasons.push('The initial video is too short to extend.');+ issues.push({ fields: ['initialVideo'], message: 'The initial video is too short to extend.' });}// Wan extension inherits source fps; validate the backend's 1–120 range before expensive denoising.@@ -2537,23 +2739,39 @@ export const getVideoValidationReasons = (model: MainModelConfig, settings: Videconst inheritedFps = Math.round(settings.sourceVideo.fps);if (inheritedFps < 1 || inheritedFps > 120) {- reasons.push(- `The initial video's frame rate (${settings.sourceVideo.fps} fps) is outside the 1-120 fps range Wan extension supports.`- );+ issues.push({+ fields: ['initialVideo'],+ message: `The initial video's frame rate (${settings.sourceVideo.fps} fps) is outside the 1-120 fps range Wan extension supports.`,+ });}}}if (!getVideoDimensions(model, settings)) {- reasons.push(- model.base === 'minimax-h3'- ? 'MiniMax H3 supports aspect ratios from 1:4 to 4:1. The conditioning media is outside that range.'- : 'The conditioning media is too small or degenerate to derive video dimensions from.'- );+ issues.push({+ fields: [+ ...when(settings.firstFrameImage, 'firstFrame'),+ ...when(settings.lastFrameImage, 'lastFrame'),+ ...when(settings.references.length > 0, 'references'),+ ...when(settings.sourceVideo, 'initialVideo'),+ ...when(settings.conditioningClip, 'conditioningClip'),+ ],+ message:+ model.base === 'minimax-h3'+ ? 'MiniMax H3 supports aspect ratios from 1:4 to 4:1. The conditioning media is outside that range.'+ : 'The conditioning media is too small or degenerate to derive video dimensions from.',+ });}const componentPolicy = getVideoComponentSectionPolicy(model, settings);- reasons.push(...componentPolicy.validate(getVideoComponentPolicyContext(model, settings)));+ issues.push(+ ...componentPolicy+ .validate(getVideoComponentPolicyContext(model, settings))+ .map((message): VideoValidationIssue => ({ fields: ['components'], message }))+ );- return reasons;+ return issues;};++export const getVideoValidationReasons = (model: MainModelConfig, settings: VideoSettings): string[] =>+ getVideoValidationIssues(model, settings).map((issue) => issue.message);diff --git a/invokeai/frontend/webv2/src/features/video/core/widgetValues.ts b/invokeai/frontend/webv2/src/features/video/core/widgetValues.tsindex 28103e65c4..6e0964d4cc 100644--- a/invokeai/frontend/webv2/src/features/video/core/widgetValues.ts+++ b/invokeai/frontend/webv2/src/features/video/core/widgetValues.ts@@ -13,14 +13,18 @@ import {getAcceleratorLoraChangeResult,getDefaultVideoSettings,getVideoComponentSectionPolicy,- getVideoModelAvailabilityReasons,+ getVideoIssueSections,+ getVideoModelAvailabilityIssues,getVideoModelSelectionResult,getVideoModes,- getVideoValidationReasons,+ getVideoValidationIssues,isSupportedVideoModel,isVideoModelSelectable,type VideoComponentPolicyContext,type VideoComponentValueKey,+ type VideoField,+ type VideoSection,+ type VideoValidationIssue,} from './videoPolicies';// Shared empty array, so clearing already-clear keys keeps its identity.@@ -202,23 +206,43 @@ export const syncVideoWidgetValuesWithModels = (return isUnchanged ? values : next;};-/** The aggregate readiness check the invoke route and the compiler share. */-export const getVideoWidgetValidationReasons = (+/** The aggregate readiness check, each issue with the panel controls that fix it. */+export const getVideoWidgetValidationIssues = (values: VideoWidgetValues,models?: readonly ModelConfig[]-): string[] => {+): VideoValidationIssue[] => {+ // The model picker fixes it, and it sits in no section.if (!values.model) {- return ['Video needs a Wan 2.2, MiniMax H3 or LTX-2 main model.'];+ return [{ fields: [], message: 'Video needs a Wan 2.2, MiniMax H3 or LTX-2 main model.' }];}- const reasons = getVideoValidationReasons(values.model, values);+ const issues = getVideoValidationIssues(values.model, values);if (models) {- reasons.push(...getVideoModelAvailabilityReasons(values.model, values, models));+ issues.push(...getVideoModelAvailabilityIssues(values.model, values, models));}- return reasons;+ return issues;};+/**+ * The section of each issue Invoke lists for `validated` (the values Invoke checks), once for every section whose+ * shown control can fix it, so each section title counts what it can fix. `shown` is the controls the panel renders+ * (see `getVideoPanelFields`). An issue two sections can fix counts in both, so the counts can add up to more than+ * Invoke's total.+ */+export const getVideoPanelIssueSections = (+ validated: VideoWidgetValues | null,+ shown: ReadonlySet<VideoField>,+ models?: readonly ModelConfig[]+): VideoSection[] =>+ validated+ ? getVideoWidgetValidationIssues(validated, models).flatMap((issue) => getVideoIssueSections(issue, shown))+ : [];++/** The aggregate readiness check the invoke route and the compiler share. */+export const getVideoWidgetValidationReasons = (values: VideoWidgetValues, models?: readonly ModelConfig[]): string[] =>+ getVideoWidgetValidationIssues(values, models).map((issue) => issue.message);+export const resolveVideoSeed = (values: Pick<VideoWidgetValues, 'seed' | 'seedMode'>): number =>values.seedMode === 'random' ? Math.floor(Math.random() * SEED_MAX) : values.seed;diff --git a/invokeai/frontend/webv2/src/features/video/index.ts b/invokeai/frontend/webv2/src/features/video/index.tsindex a9f22e02d4..ca0373f28d 100644--- a/invokeai/frontend/webv2/src/features/video/index.ts+++ b/invokeai/frontend/webv2/src/features/video/index.ts@@ -77,7 +77,6 @@ export {getVideoComponentSectionPolicy,getVideoAspectRatioOptions,getVideoDimensions,- getVideoModelAvailabilityReasons,getVideoModelPolicy,getVideoModelSelectionResult,getVideoTargetResolutionOptions,diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoComponentsSection.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoComponentsSection.tsxindex 1b2a2b875c..71011cd450 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoComponentsSection.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoComponentsSection.tsx@@ -24,6 +24,8 @@ import { ScrubberField } from '@platform/ui/ScrubberField';import { Fragment, memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { VIDEO_SECTION_IDS } from './VideoUiContext';+const coerceSlotValue = (slot: VideoComponentSlotPolicy,candidate: ModelConfig | null@@ -171,7 +173,7 @@ const WanExpertWiringNotice = memo(function WanExpertWiringNotice({});return (- <HStack bg="bg.subtle" borderColor="fg.warning" borderWidth="1px" gap="2" p="2" rounded="md">+ <HStack bg="bg.muted" borderColor="fg.warning" borderWidth="1px" gap="2" p="2" rounded="md"><Text color="fg.warning" flex="1" fontSize="xs" textWrap="pretty">{message}</Text>@@ -206,9 +208,9 @@ export const VideoComponentsSection = memo(function VideoComponentsSection({<GenerationSettingsSectiondefaultOpen={policy.defaultOpen}label={t('widgets.video.components')}- sectionId="video-components"+ sectionId={VIDEO_SECTION_IDS.components}>- <Stack gap="3" p="2">+ <Stack gap="2.5">{policy.slots.map((slot) => (<Fragment key={slot.key}><ComponentSlotRowdiff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsxindex 907d99428f..6e334c7735 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoConceptsSection.tsx@@ -19,6 +19,7 @@ import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { areVideoLorasEquivalent, areVideoModelsEquivalent } from './videoComparators';+import { VIDEO_SECTION_IDS } from './VideoUiContext';/** Graph compilation routes LoRAs to experts from their probed tags; the UI supplies no target override. */@@ -71,8 +72,8 @@ export const VideoConceptsSection = memo();return (- <GenerationSettingsSection label={t('widgets.video.concepts')} sectionId="video-concepts" defaultOpen>- <Stack gap="2" p="2">+ <GenerationSettingsSection label={t('widgets.video.concepts')} sectionId={VIDEO_SECTION_IDS.concepts} defaultOpen>+ <Stack gap="2.5"><ModelSelectdisabled={!model}excludeKeys={selectedLoraKeys}diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsxindex 00e0465a9e..02ce5a26df 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoFormFields.tsx@@ -163,7 +163,7 @@ export const VideoPromptFields = memo();return (- <Stack gap="2" p="2">+ <Stack gap="2" px="2" pt="2" pb="3"><PositivePromptFieldbatchCount={batchCount}dynamicPrompts={dynamicPromptsField}diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoHeaderActions.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoHeaderActions.tsxindex f2b7f82b29..834073ff2b 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoHeaderActions.tsx@@ -1,5 +1,6 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import { Icon } from '@chakra-ui/react';+import { GenerationSectionJumpMenu } from '@features/generation/components';import { useModelsSelector } from '@features/models';import { normalizeVideoWidgetValues } from '@features/video/core/settings';import { getVideoSettingsWithModelDefaults } from '@features/video/core/videoPolicies';@@ -14,7 +15,7 @@ import { useVideoUi } from './VideoUiContext';const sortLorasByKey = <T extends { model: { key: string } }>(loras: readonly T[]): T[] =>[...loras].sort((a, b) => a.model.key.localeCompare(b.model.key));-export const VideoHeaderActions = () => {+export const VideoHeaderActions = ({ instance }: { instance?: { id: string } }) => {const { t } = useTranslation();const { patchValues, rawValues } = useVideoUi();const models = useModelsSelector((snapshot) => snapshot.models);@@ -43,16 +44,19 @@ export const VideoHeaderActions = () => {};return (- <Tooltip content={label}>- <IconButton- aria-label={label}- disabled={isAtModelDefaults}- size="sm"- variant="ghost"- onClick={resetToModelDefaults}- >- <Icon as={RotateCcwIcon} boxSize="3.5" />- </IconButton>- </Tooltip>+ <>+ <GenerationSectionJumpMenu panelId={instance?.id} />+ <Tooltip content={label}>+ <IconButton+ aria-label={label}+ disabled={isAtModelDefaults}+ size="sm"+ variant="ghost"+ onClick={resetToModelDefaults}+ >+ <Icon as={RotateCcwIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ </>);};diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsxindex 95158e6c6a..016ccb59d6 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoUiContext.tsx@@ -1,9 +1,23 @@import type { GalleryItemRef, GalleryVideoItem } from '@features/gallery';import type { VideoWidgetValues } from '@features/video/core/types';+import type { VideoSection } from '@features/video/core/videoPolicies';import type { ReactNode } from 'react';import { createContext, use, useMemo } from 'react';+/** The persisted open state of each Video section, kept with Generate's under the same per-user preference. */+export const VIDEO_SECTION_IDS = {+ components: 'video-components',+ concepts: 'video-concepts',+ conditioningClip: 'video-conditioning-clip',+ dimensions: 'video-dimensions',+ frames: 'video-frames',+ guidance: 'video-guidance',+ references: 'video-references',+ render: 'video-render',+ source: 'video-source',+} as const satisfies Record<VideoSection, string>;+/** Workbench supplies this UI port because features cannot import workbench. */export interface VideoUiAdapter {/** Reveal this media's board, page, and cell in Gallery and show Preview. */diff --git a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsxindex f4bf16f746..b439d1677e 100644--- a/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/video/ui/VideoWidgetView.tsx@@ -7,7 +7,13 @@ import type {} from '@features/video/core/types';import { createListCollection, HStack, Stack, Switch, Text } from '@chakra-ui/react';-import { AspectRatioPicker, GenerationSettingsSection, SeedField } from '@features/generation/components';+import {+ AspectRatioPicker,+ GenerationSectionIssuesProvider,+ GenerationSectionPanel,+ GenerationSettingsSection,+ SeedField,+} from '@features/generation/components';import {getDynamicPromptsConfig,getLockedAspectRatioSettings,@@ -44,10 +50,15 @@ import {getAutoDurationBounds,getVideoExpandPromptSuggestion,getVideoModelPolicy,+ getVideoPanelFields,isAutoDurationActive,isAutoDurationSupportedForMode,} from '@features/video/core/videoPolicies';-import { createDefaultVideoWidgetValues, syncVideoWidgetValuesWithModels } from '@features/video/core/widgetValues';+import {+ createDefaultVideoWidgetValues,+ getVideoPanelIssueSections,+ syncVideoWidgetValuesWithModels,+} from '@features/video/core/widgetValues';import { useMountEffect } from '@platform/react/useMountEffect';import { Field, IconButton, Select } from '@platform/ui';import { Button } from '@platform/ui/Button';@@ -67,7 +78,7 @@ import { VideoLengthControls } from './VideoLengthControls';import { VideoModelField } from './VideoModelField';import { VideoReferenceListField } from './VideoReferenceListField';import { VideoSourceClipField } from './VideoSourceClipField';-import { useVideoUi, useVideoUiActions } from './VideoUiContext';+import { useVideoUi, useVideoUiActions, VIDEO_SECTION_IDS } from './VideoUiContext';/** Keep section props stable: project patches rerender this widget on every keystroke. */@@ -91,7 +102,7 @@ const StaleMediaStub = ({ label, onClear }: { label: string; onClear: () => voidconst { t } = useTranslation();return (- <HStack bg="bg.subtle" gap="2" justify="space-between" p="2" rounded="md">+ <HStack bg="bg.muted" gap="2" justify="space-between" p="2" rounded="md"><Text color="fg.muted" fontSize="xs" textWrap="pretty">{label}</Text>@@ -132,7 +143,8 @@ const VideoModelReconciler = ({return null;};-export const VideoWidgetView = () => {+/** `instance` ties the sections to the header's jump menu; a view rendered outside a widget frame has none. */+export const VideoWidgetView = ({ instance }: { instance?: { id: string } }) => {const { t } = useTranslation();const selection = useVideoUi();const models = useModelsSelector((snapshot) => snapshot.models);@@ -156,6 +168,19 @@ export const VideoWidgetView = () => {[models]);const policy = useMemo(() => getVideoModelPolicy(values.model ?? undefined, values), [values]);+ // The controls this panel shows, which its issue counts are limited to.+ const panelFields = useMemo(() => getVideoPanelFields(values.model ?? undefined, values, policy), [policy, values]);+ // The values Invoke validates, unsynced, so a section counts an uninstalled pick while Invoke reports it; installs+ // are checked once models load, as Invoke checks them.+ const issueSections = useMemo(+ () =>+ getVideoPanelIssueSections(+ normalizeVideoWidgetValues(rawValues),+ panelFields,+ modelsStatus === 'loaded' ? models : undefined+ ).map((section) => VIDEO_SECTION_IDS[section]),+ [models, modelsStatus, panelFields, rawValues]+ );const dimensions = useMemo(() => getVideoDimensions(values.model ?? undefined, values), [values]);// What the run will actually use: a conditioning clip decides the length, and in the video role// the frame rate too. The stored values stay put underneath, so clearing the clip restores them.@@ -438,8 +463,8 @@ export const VideoWidgetView = () => {const hasAdvancedGuidance = policy.ui.audioCfgVisible || policy.ui.stgVisible || policy.ui.modalityVisible;const mode = resolveVideoMode(values);- const supportsFirstFrame = policy.modes.includes('first-frame') || policy.modes.includes('first-last');- const supportsLastFrame = policy.modes.includes('first-last') || policy.modes.includes('last-frame');+ const supportsFirstFrame = panelFields.has('firstFrame');+ const supportsLastFrame = panelFields.has('lastFrame');const promptEnhancer = policy.prompt.enhancer;const firstFrameImage = values.firstFrameImage;// Memoized for VideoPromptFields' equality check; both inputs keep their identity between patches.@@ -475,10 +500,9 @@ export const VideoWidgetView = () => {dynamicPromptsSeedBehaviour,]);- const supportsExtend = policy.modes.includes('extend');- const supportsReferences = policy.modes.includes('reference');- const supportsConditioningClip = policy.modes.includes('audio-to-video') || policy.modes.includes('video-to-audio');- const supportsInitialVideo = supportsExtend || referenceExtend;+ const supportsReferences = panelFields.has('references');+ const supportsConditioningClip = panelFields.has('conditioningClip');+ const supportsInitialVideo = panelFields.has('initialVideo');// Use the setter's capacity predicate: recalled unflagged references can be adopted without consuming a slot,// and must not disable clip trimming.const initialVideoCapBlocked =@@ -519,372 +543,400 @@ export const VideoWidgetView = () => {}`: t('widgets.video.derivedSizeUnavailable');const fpsLockedForExtend = policy.ui.fpsVisible && mode === 'extend';- const fpsLocked = fpsLockedForExtend || timing.fpsFromClip;+ const fpsLocked = !panelFields.has('fps');const durationText =durationSeconds === null? undefined: t('widgets.video.framesDuration', { seconds: DURATION_FORMATTER.format(durationSeconds) });return (- <Stack gap="1" minW="0" p="1">- <VideoModelReconciler- key={`${projectId}:${modelsStatus}:${modelsFingerprint}`}- rawValues={rawValues}- values={values}- />-- <Stack gap="1" px="2" py="1">- <VideoModelField- models={models}- modelsLoaded={modelsStatus === 'loaded'}- projectId={projectId}- values={values}- />- </Stack>-- <VideoPromptFields- batchCount={values.batchCount}- dynamicPrompts={dynamicPrompts}- expandPromptSuggestion={expandPromptSuggestion}- isSeedFixed={values.seedMode === 'fixed'}- loras={values.loras}- model={values.model}- negativeHelpText={policy.prompt.negativeHelpTextKey ? t(policy.prompt.negativeHelpTextKey) : undefined}- negativePrompt={values.negativePrompt}- negativePromptEnabled={values.negativePromptEnabled}- negativePromptHeightPx={values.negativePromptHeightPx}- negativeVisible={policy.prompt.negativeVisible}- positivePrompt={values.positivePrompt}- positivePromptHeightPx={values.positivePromptHeightPx}- projectId={projectId}- showSyntaxHighlighting={selection.showPromptSyntaxHighlighting}- onPatchValues={patch}- />-- {supportsFirstFrame || supportsLastFrame ? (- <GenerationSettingsSection label={t('widgets.video.initialFrames')} sectionId="video-frames" defaultOpen>- <Stack gap="3" p="2">- {supportsFirstFrame ? (- <Field- helpText={- values.sourceVideo- ? undefined- : [t('widgets.video.firstFrameHelp'), frameClearsClipText].filter(Boolean).join(' ')- }- label={t('widgets.video.firstFrame')}- >- <VideoFrameImageField- disabled={Boolean(values.sourceVideo)}- disabledReason={values.sourceVideo ? t('widgets.video.firstFrameBlocked') : undefined}- dropId="video-first-frame"- dropLabel={t('widgets.video.dropFirstFrame')}- image={values.firstFrameImage}- onChange={setFirstFrame}- />- </Field>- ) : null}- {supportsLastFrame ? (- <Field- helpText={[- values.sourceVideo ? t('widgets.video.lastFrameExtendHelp') : t('widgets.video.lastFrameHelp'),- frameClearsClipText,- ]- .filter(Boolean)- .join(' ')}- label={t('widgets.video.lastFrame')}- >- <VideoFrameImageField- dropId="video-last-frame"- dropLabel={t('widgets.video.dropLastFrame')}- image={values.lastFrameImage}- onChange={setLastFrame}- />- </Field>- ) : null}- </Stack>- </GenerationSettingsSection>- ) : null}-- {!supportsFirstFrame && values.firstFrameImage ? (- <StaleMediaStub label={t('widgets.video.staleFirstFrame')} onClear={clearFirstFrame} />- ) : null}- {!supportsLastFrame && values.lastFrameImage ? (- <StaleMediaStub label={t('widgets.video.staleLastFrame')} onClear={clearLastFrame} />- ) : null}- {!supportsInitialVideo && values.sourceVideo ? (- <StaleMediaStub label={t('widgets.video.staleSourceVideo')} onClear={clearSourceVideo} />- ) : null}- {!supportsReferences && values.references.length > 0 ? (- <StaleMediaStub label={t('widgets.video.staleReferences')} onClear={clearReferences} />- ) : null}- {!supportsConditioningClip && values.conditioningClip ? (- <StaleMediaStub label={t('widgets.video.staleConditioningClip')} onClear={clearConditioningClip} />- ) : null}-- {supportsReferences ? (- <GenerationSettingsSection label={t('widgets.video.references')} sectionId="video-references" defaultOpen>- <Stack gap="3" p="2">- <VideoReferenceListField- maxImages={policy.references?.maxImages ?? 9}- maxVideos={policy.references?.maxVideos ?? 3}- references={values.references}- targetArea={dimensions ? dimensions.width * dimensions.height : null}- onChange={setReferences}- />- </Stack>- </GenerationSettingsSection>- ) : null}-- {supportsInitialVideo ? (- <GenerationSettingsSection label={t('widgets.video.initialVideo')} sectionId="video-source" defaultOpen>- <Stack gap="3" p="2">- {referenceExtend ? (- <Text color="fg.muted" fontSize="xs" textWrap="pretty">- {t('widgets.video.referenceExtendHelp')}- </Text>- ) : null}- <VideoSourceClipField- disabled={Boolean(values.firstFrameImage) || initialVideoCapBlocked}- disabledReason={- values.firstFrameImage- ? t('widgets.video.initialVideoBlocked')- : initialVideoCapBlocked- ? t('widgets.video.initialVideoCapBlocked')- : undefined- }- sourceVideo={values.sourceVideo}- onChange={setSourceVideo}- />- {policy.ui.extendContext ? (- <ScrubberField- defaultValue={LTX2_EXTEND_CONTEXT_FRAMES}- // The trade this control makes, which Frames alone does not show: the join consumes- // the context from both halves, so every frame held is a frame of new video given up.- // Under auto duration Frames is only a ceiling, so the new material is too.- helpText={t(- autoDurationBounds ? 'widgets.video.extendContextHelpAuto' : 'widgets.video.extendContextHelp',- {- frames: extendNewFrames,- // The continuation plays at the source's rate, not the panel's.- seconds: (extendNewFrames / Math.max(1, values.sourceVideo?.fps ?? values.fps)).toFixed(1),- }- )}- inputMax={policy.ui.extendContext.max}- label={t('widgets.video.extendContext')}- max={policy.ui.extendContext.max}- min={policy.ui.extendContext.min}- step={policy.ui.extendContext.step}- value={policy.ui.extendContext.value}- onChange={set.ltx2ExtendContextFrames}- />- ) : null}- </Stack>- </GenerationSettingsSection>- ) : null}-- {supportsConditioningClip ? (- <GenerationSettingsSection- label={t('widgets.video.conditioningClip')}- sectionId="video-conditioning-clip"- defaultOpen={Boolean(values.conditioningClip)}- >- <Stack gap="3" p="2">- <VideoConditioningClipField- conditioningClip={values.conditioningClip}- derivedText={conditioningDerivedText}- disabled={otherMediaSet}- disabledReason={otherMediaSet ? t('widgets.video.conditioningClipBlocked') : undefined}- pictureRoleDisabledReason={framesSet ? t('widgets.video.conditioningRoleVideoBlocked') : undefined}- onChange={setConditioningClip}+ <GenerationSectionPanel id={instance?.id}>+ <GenerationSectionIssuesProvider issueSections={issueSections}>+ <Stack gap="0" minW="0">+ <VideoModelReconciler+ key={`${projectId}:${modelsStatus}:${modelsFingerprint}`}+ rawValues={rawValues}+ values={values}+ />++ <Stack gap="1" px="2" pt="3" pb="1">+ <VideoModelField+ models={models}+ modelsLoaded={modelsStatus === 'loaded'}+ projectId={projectId}+ values={values}/></Stack>- </GenerationSettingsSection>- ) : null}-- <GenerationSettingsSection label={t('widgets.video.dimensions')} sectionId="video-dimensions" defaultOpen>- <Stack gap="3" p="2">- <Field helpText={derivedSizeText} label={t('widgets.video.aspectRatio')}>- <HStack gap="1">- <AspectRatioPicker- disabled={hasConditioningMedia}- lockedRatio={getAspectRatio(values.aspectRatioId)}- valueText={derivedSourceValueText}- onChange={set.aspectRatio}- />- <IconButton- aria-label={t('widgets.video.swapAspectRatio')}- disabled={hasConditioningMedia}- variant="ghost"- onClick={swapAspectRatio}- >- <ArrowLeftRightIcon />- </IconButton>- </HStack>- </Field>- <Field helpText={twoStageHelpText} label={t('widgets.video.targetResolution')}>- <Select- collection={targetResolutionCollection}- value={targetResolutionValue}- onValueChange={set.targetResolution}- />- </Field>- <VideoLengthControls- autoDuration={values.autoDuration}- autoDurationActive={autoDurationActive}- autoDurationCeiling={autoDurationCeiling}- autoDurationSupported={autoDurationSupported}- durationText={durationText}- framesSlider={framesSlider}- hasDurationHead={Boolean(values.ltx2DurationHeadModel)}- numFrames={timing.numFrames}- numFramesFromClip={timing.numFramesFromClip}- onAutoDurationChange={set.autoDuration}- onNumFramesChange={setNumFrames}++ <VideoPromptFields+ batchCount={values.batchCount}+ dynamicPrompts={dynamicPrompts}+ expandPromptSuggestion={expandPromptSuggestion}+ isSeedFixed={values.seedMode === 'fixed'}+ loras={values.loras}+ model={values.model}+ negativeHelpText={policy.prompt.negativeHelpTextKey ? t(policy.prompt.negativeHelpTextKey) : undefined}+ negativePrompt={values.negativePrompt}+ negativePromptEnabled={values.negativePromptEnabled}+ negativePromptHeightPx={values.negativePromptHeightPx}+ negativeVisible={policy.prompt.negativeVisible}+ positivePrompt={values.positivePrompt}+ positivePromptHeightPx={values.positivePromptHeightPx}+ projectId={projectId}+ showSyntaxHighlighting={selection.showPromptSyntaxHighlighting}+ onPatchValues={patch}/>- {policy.ui.fpsVisible ? (- <ScrubberField- disabled={fpsLocked}- helpText={- timing.fpsFromClip- ? t('widgets.video.fpsFromClip')- : fpsLockedForExtend- ? t('widgets.video.fpsExtendLocked')- : undefined- }- inputMax={policy.fps.max}- label={t('widgets.video.fps')}- max={60}- min={policy.fps.min}- step={1}- value={timing.fps}- onChange={set.fps}- />- ) : (- <Text color="fg.muted" fontSize="xs">- {t('widgets.video.fixedFps', { fps: policy.fps.defaultValue })}- </Text>- )}- </Stack>- </GenerationSettingsSection>-- {/* Sampling and variation — how the model renders, not which model it is. */}- <GenerationSettingsSection label={t('widgets.video.render')} sectionId="video-render" defaultOpen>- <Stack gap="3" p="2">- {policy.ui.accelerator && values.model ? (- <Field- helpText={t('widgets.video.acceleratorHelp', {- label: policy.ui.accelerator.label,- steps: policy.ui.acceleratorSteps ?? policy.ui.accelerator.steps,- })}- label={t('widgets.video.accelerator', { label: policy.ui.accelerator.label })}++ {supportsFirstFrame || supportsLastFrame ? (+ <GenerationSettingsSection+ label={t('widgets.video.initialFrames')}+ sectionId={VIDEO_SECTION_IDS.frames}+ defaultOpen>- <Switch.Root checked={values.acceleratorEnabled} onCheckedChange={toggleAccelerator}>- <Switch.HiddenInput />- <Switch.Control _checked={SWITCH_CHECKED_PROPS}>- <Switch.Thumb />- </Switch.Control>- </Switch.Root>- </Field>+ <Stack gap="2.5">+ {supportsFirstFrame ? (+ <Field+ helpText={+ values.sourceVideo+ ? undefined+ : [t('widgets.video.firstFrameHelp'), frameClearsClipText].filter(Boolean).join(' ')+ }+ label={t('widgets.video.firstFrame')}+ >+ <VideoFrameImageField+ disabled={Boolean(values.sourceVideo)}+ disabledReason={values.sourceVideo ? t('widgets.video.firstFrameBlocked') : undefined}+ dropId="video-first-frame"+ dropLabel={t('widgets.video.dropFirstFrame')}+ image={values.firstFrameImage}+ onChange={setFirstFrame}+ />+ </Field>+ ) : null}+ {supportsLastFrame ? (+ <Field+ helpText={[+ values.sourceVideo ? t('widgets.video.lastFrameExtendHelp') : t('widgets.video.lastFrameHelp'),+ frameClearsClipText,+ ]+ .filter(Boolean)+ .join(' ')}+ label={t('widgets.video.lastFrame')}+ >+ <VideoFrameImageField+ dropId="video-last-frame"+ dropLabel={t('widgets.video.dropLastFrame')}+ image={values.lastFrameImage}+ onChange={setLastFrame}+ />+ </Field>+ ) : null}+ </Stack>+ </GenerationSettingsSection>) : null}- {policy.ui.stepsEditable ? (- <ScrubberField- defaultValue={policy.defaults.steps}- hint="steps"- inputMax={500}- label={t('widgets.video.steps')}- max={100}- min={policy.minSteps}- step={1}- value={values.steps}- onChange={set.steps}- />- ) : (- <Text color="fg.muted" fontSize="xs">- {t('widgets.video.stepsFixed', { steps: policy.defaults.steps })}- </Text>- )}- {policy.ui.cfgVisible ? (- <ScrubberField- hint="cfgScale"- inputMax={100}- label={t('widgets.video.cfg')}- max={15}- min={1}- step={0.1}- value={values.cfgScale}- onChange={set.cfgScale}- />++ {!supportsFirstFrame && values.firstFrameImage ? (+ <StaleMediaStub label={t('widgets.video.staleFirstFrame')} onClear={clearFirstFrame} />) : null}- {policy.ui.cfgLowNoiseVisible ? (- <ScrubberField- helpText={t('widgets.video.cfgLowNoiseHelp')}- inputMax={100}- label={t('widgets.video.cfgLowNoise')}- max={15}- min={1}- step={0.1}- value={values.cfgScaleLowNoise ?? values.cfgScale}- onChange={set.cfgScaleLowNoise}- />+ {!supportsLastFrame && values.lastFrameImage ? (+ <StaleMediaStub label={t('widgets.video.staleLastFrame')} onClear={clearLastFrame} />) : null}- <SeedField- batchCount={values.batchCount}- label={t('widgets.video.seed')}- seed={values.seed}- seedMode={values.seedMode}- onCommit={patch}- />- </Stack>- </GenerationSettingsSection>-- {hasAdvancedGuidance ? (- <GenerationSettingsSection label={t('widgets.video.advancedGuidance')} sectionId="video-guidance">- <Stack gap="3" p="2">- {policy.ui.audioCfgVisible ? (- <ScrubberField- defaultValue={policy.defaults.audioCfgScale ?? undefined}- helpText={t('widgets.video.audioCfgHelp')}- inputMax={100}- label={t('widgets.video.audioCfg')}- max={15}- min={1}- step={0.1}- value={values.audioCfgScale ?? policy.defaults.audioCfgScale ?? 1}- onChange={set.audioCfgScale}- />- ) : null}- {policy.ui.stgVisible ? (- <ScrubberField- defaultValue={policy.defaults.stgScale ?? undefined}- helpText={t('widgets.video.stgHelp')}- inputMax={10}- label={t('widgets.video.stg')}- max={3}- min={0}- step={0.1}- value={values.stgScale ?? policy.defaults.stgScale ?? 0}- onChange={set.stgScale}+ {!supportsInitialVideo && values.sourceVideo ? (+ <StaleMediaStub label={t('widgets.video.staleSourceVideo')} onClear={clearSourceVideo} />+ ) : null}+ {!supportsReferences && values.references.length > 0 ? (+ <StaleMediaStub label={t('widgets.video.staleReferences')} onClear={clearReferences} />+ ) : null}+ {!supportsConditioningClip && values.conditioningClip ? (+ <StaleMediaStub label={t('widgets.video.staleConditioningClip')} onClear={clearConditioningClip} />+ ) : null}++ {supportsReferences ? (+ <GenerationSettingsSection+ label={t('widgets.video.references')}+ sectionId={VIDEO_SECTION_IDS.references}+ defaultOpen+ >+ <Stack gap="2.5">+ <VideoReferenceListField+ maxImages={policy.references?.maxImages ?? 9}+ maxVideos={policy.references?.maxVideos ?? 3}+ references={values.references}+ targetArea={dimensions ? dimensions.width * dimensions.height : null}+ onChange={setReferences}+ />+ </Stack>+ </GenerationSettingsSection>+ ) : null}++ {supportsInitialVideo ? (+ <GenerationSettingsSection+ label={t('widgets.video.initialVideo')}+ sectionId={VIDEO_SECTION_IDS.source}+ defaultOpen+ >+ <Stack gap="2.5">+ {referenceExtend ? (+ <Text color="fg.muted" fontSize="xs" textWrap="pretty">+ {t('widgets.video.referenceExtendHelp')}+ </Text>+ ) : null}+ <VideoSourceClipField+ disabled={Boolean(values.firstFrameImage) || initialVideoCapBlocked}+ disabledReason={+ values.firstFrameImage+ ? t('widgets.video.initialVideoBlocked')+ : initialVideoCapBlocked+ ? t('widgets.video.initialVideoCapBlocked')+ : undefined+ }+ sourceVideo={values.sourceVideo}+ onChange={setSourceVideo}+ />+ {policy.ui.extendContext ? (+ <ScrubberField+ defaultValue={LTX2_EXTEND_CONTEXT_FRAMES}+ // The trade this control makes, which Frames alone does not show: the join consumes+ // the context from both halves, so every frame held is a frame of new video given up.+ // Under auto duration Frames is only a ceiling, so the new material is too.+ helpText={t(+ autoDurationBounds ? 'widgets.video.extendContextHelpAuto' : 'widgets.video.extendContextHelp',+ {+ frames: extendNewFrames,+ // The continuation plays at the source's rate, not the panel's.+ seconds: (extendNewFrames / Math.max(1, values.sourceVideo?.fps ?? values.fps)).toFixed(1),+ }+ )}+ inputMax={policy.ui.extendContext.max}+ label={t('widgets.video.extendContext')}+ max={policy.ui.extendContext.max}+ min={policy.ui.extendContext.min}+ step={policy.ui.extendContext.step}+ value={policy.ui.extendContext.value}+ onChange={set.ltx2ExtendContextFrames}+ />+ ) : null}+ </Stack>+ </GenerationSettingsSection>+ ) : null}++ {supportsConditioningClip ? (+ <GenerationSettingsSection+ label={t('widgets.video.conditioningClip')}+ sectionId={VIDEO_SECTION_IDS.conditioningClip}+ defaultOpen={Boolean(values.conditioningClip)}+ >+ <Stack gap="2.5">+ <VideoConditioningClipField+ conditioningClip={values.conditioningClip}+ derivedText={conditioningDerivedText}+ disabled={otherMediaSet}+ disabledReason={otherMediaSet ? t('widgets.video.conditioningClipBlocked') : undefined}+ pictureRoleDisabledReason={framesSet ? t('widgets.video.conditioningRoleVideoBlocked') : undefined}+ onChange={setConditioningClip}+ />+ </Stack>+ </GenerationSettingsSection>+ ) : null}++ <GenerationSettingsSection+ label={t('widgets.video.dimensions')}+ sectionId={VIDEO_SECTION_IDS.dimensions}+ defaultOpen+ >+ <Stack gap="2.5">+ <Field helpText={derivedSizeText} label={t('widgets.video.aspectRatio')}>+ <HStack gap="1">+ <AspectRatioPicker+ disabled={hasConditioningMedia}+ lockedRatio={getAspectRatio(values.aspectRatioId)}+ valueText={derivedSourceValueText}+ onChange={set.aspectRatio}+ />+ <IconButton+ aria-label={t('widgets.video.swapAspectRatio')}+ disabled={hasConditioningMedia}+ variant="ghost"+ onClick={swapAspectRatio}+ >+ <ArrowLeftRightIcon />+ </IconButton>+ </HStack>+ </Field>+ <Field helpText={twoStageHelpText} label={t('widgets.video.targetResolution')}>+ <Select+ collection={targetResolutionCollection}+ value={targetResolutionValue}+ onValueChange={set.targetResolution}+ />+ </Field>+ <VideoLengthControls+ autoDuration={values.autoDuration}+ autoDurationActive={autoDurationActive}+ autoDurationCeiling={autoDurationCeiling}+ autoDurationSupported={autoDurationSupported}+ durationText={durationText}+ framesSlider={framesSlider}+ hasDurationHead={Boolean(values.ltx2DurationHeadModel)}+ numFrames={timing.numFrames}+ numFramesFromClip={timing.numFramesFromClip}+ onAutoDurationChange={set.autoDuration}+ onNumFramesChange={setNumFrames}/>- ) : null}- {policy.ui.modalityVisible ? (- <ScrubberField- defaultValue={policy.defaults.modalityScale ?? undefined}- helpText={t('widgets.video.modalityHelp')}- inputMax={10}- label={t('widgets.video.modality')}- max={5}- min={1}- step={0.1}- value={values.modalityScale ?? policy.defaults.modalityScale ?? 1}- onChange={set.modalityScale}+ {policy.ui.fpsVisible ? (+ <ScrubberField+ disabled={fpsLocked}+ helpText={+ timing.fpsFromClip+ ? t('widgets.video.fpsFromClip')+ : fpsLockedForExtend+ ? t('widgets.video.fpsExtendLocked')+ : undefined+ }+ inputMax={policy.fps.max}+ label={t('widgets.video.fps')}+ max={60}+ min={policy.fps.min}+ step={1}+ value={timing.fps}+ onChange={set.fps}+ />+ ) : (+ <Text color="fg.muted" fontSize="xs">+ {t('widgets.video.fixedFps', { fps: policy.fps.defaultValue })}+ </Text>+ )}+ </Stack>+ </GenerationSettingsSection>++ {/* Sampling and variation — how the model renders, not which model it is. */}+ <GenerationSettingsSection label={t('widgets.video.render')} sectionId={VIDEO_SECTION_IDS.render} defaultOpen>+ <Stack gap="2.5">+ {policy.ui.accelerator && values.model ? (+ <Field+ helpText={t('widgets.video.acceleratorHelp', {+ label: policy.ui.accelerator.label,+ steps: policy.ui.acceleratorSteps ?? policy.ui.accelerator.steps,+ })}+ label={t('widgets.video.accelerator', { label: policy.ui.accelerator.label })}+ >+ <Switch.Root checked={values.acceleratorEnabled} onCheckedChange={toggleAccelerator}>+ <Switch.HiddenInput />+ <Switch.Control _checked={SWITCH_CHECKED_PROPS}>+ <Switch.Thumb />+ </Switch.Control>+ </Switch.Root>+ </Field>+ ) : null}+ {policy.ui.stepsEditable ? (+ <ScrubberField+ defaultValue={policy.defaults.steps}+ hint="steps"+ inputMax={500}+ label={t('widgets.video.steps')}+ max={100}+ min={policy.minSteps}+ step={1}+ value={values.steps}+ onChange={set.steps}+ />+ ) : (+ <Text color="fg.muted" fontSize="xs">+ {t('widgets.video.stepsFixed', { steps: policy.defaults.steps })}+ </Text>+ )}+ {policy.ui.cfgVisible ? (+ <ScrubberField+ hint="cfgScale"+ inputMax={100}+ label={t('widgets.video.cfg')}+ max={15}+ min={1}+ step={0.1}+ value={values.cfgScale}+ onChange={set.cfgScale}+ />+ ) : null}+ {policy.ui.cfgLowNoiseVisible ? (+ <ScrubberField+ helpText={t('widgets.video.cfgLowNoiseHelp')}+ inputMax={100}+ label={t('widgets.video.cfgLowNoise')}+ max={15}+ min={1}+ step={0.1}+ value={values.cfgScaleLowNoise ?? values.cfgScale}+ onChange={set.cfgScaleLowNoise}+ />+ ) : null}+ <SeedField+ batchCount={values.batchCount}+ label={t('widgets.video.seed')}+ seed={values.seed}+ seedMode={values.seedMode}+ onCommit={patch}/>- ) : null}- </Stack>- </GenerationSettingsSection>- ) : null}+ </Stack>+ </GenerationSettingsSection>- <VideoConceptsSection projectId={projectId} loras={values.loras} model={values.model} onChangeLoras={setLoras} />- <VideoComponentsSection values={values} onPatch={patch} />- </Stack>+ {hasAdvancedGuidance ? (+ <GenerationSettingsSection+ label={t('widgets.video.advancedGuidance')}+ sectionId={VIDEO_SECTION_IDS.guidance}+ >+ <Stack gap="2.5">+ {policy.ui.audioCfgVisible ? (+ <ScrubberField+ defaultValue={policy.defaults.audioCfgScale ?? undefined}+ helpText={t('widgets.video.audioCfgHelp')}+ inputMax={100}+ label={t('widgets.video.audioCfg')}+ max={15}+ min={1}+ step={0.1}+ value={values.audioCfgScale ?? policy.defaults.audioCfgScale ?? 1}+ onChange={set.audioCfgScale}+ />+ ) : null}+ {policy.ui.stgVisible ? (+ <ScrubberField+ defaultValue={policy.defaults.stgScale ?? undefined}+ helpText={t('widgets.video.stgHelp')}+ inputMax={10}+ label={t('widgets.video.stg')}+ max={3}+ min={0}+ step={0.1}+ value={values.stgScale ?? policy.defaults.stgScale ?? 0}+ onChange={set.stgScale}+ />+ ) : null}+ {policy.ui.modalityVisible ? (+ <ScrubberField+ defaultValue={policy.defaults.modalityScale ?? undefined}+ helpText={t('widgets.video.modalityHelp')}+ inputMax={10}+ label={t('widgets.video.modality')}+ max={5}+ min={1}+ step={0.1}+ value={values.modalityScale ?? policy.defaults.modalityScale ?? 1}+ onChange={set.modalityScale}+ />+ ) : null}+ </Stack>+ </GenerationSettingsSection>+ ) : null}++ <VideoConceptsSection+ projectId={projectId}+ loras={values.loras}+ model={values.model}+ onChangeLoras={setLoras}+ />+ <VideoComponentsSection values={values} onPatch={patch} />+ </Stack>+ </GenerationSectionIssuesProvider>+ </GenerationSectionPanel>);};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsxindex 5df928b6f4..921aa44509 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsx@@ -1,5 +1,5 @@import type { ProjectGraphState, ProjectWorkflowSource, WorkflowNode } from '@features/workflow/core/types';-import type { WorkflowRuntimeApi } from '@features/workflow/ui/contracts';+import type { WorkflowRegion, WorkflowRuntimeApi } from '@features/workflow/ui/contracts';import type {WorkflowProjectPersistence,WorkflowReadPort,@@ -95,6 +95,8 @@ const TRANSLATIONS: Record<string, string> = {'widgets.workflow.persistencePendingNoRecovery': 'Project changes waiting to save — no browser recovery available','widgets.workflow.persistenceSaved': 'Project saved to the server','widgets.workflow.persistenceSaving': 'Saving project…',+ 'widgets.workflow.toolbar.redo': 'Redo',+ 'widgets.workflow.toolbar.undo': 'Undo','widgets.workflow.saveToLibraryWithEllipsis': 'Save to library…','widgets.workflow.switchWorkflow': 'Switch workflow','widgets.workflow.linkedTemplateUnnamed': 'Linked to a library template',@@ -163,6 +165,13 @@ const projectSnapshot = (graph: ProjectGraphState, source?: ProjectWorkflowSourcworkflows: [{ document: graph, source }],});+interface HistoryState {+ canRedo: boolean;+ canUndo: boolean;+}++const NO_HISTORY: HistoryState = { canRedo: false, canUndo: false };+const SAVED: WorkflowProjectPersistence = { error: null, hasLocalRecovery: true, lastSavedAt: null, status: 'saved' };const TEST_RUNTIME: WorkflowRuntimeApi = {@@ -500,12 +509,20 @@ describe('WorkflowHeaderActions', () => {clearWorkflowPublicationIntent();});- const renderHeader = async (source?: ProjectWorkflowSource) => {+ let commands: ReturnType<typeof createCommands>;+ let project: ReturnType<typeof createMutablePort<ReturnType<typeof projectSnapshot> & HistoryState>>;++ const renderHeader = async (+ source?: ProjectWorkflowSource,+ { history = NO_HISTORY, region = 'center' }: { history?: HistoryState; region?: WorkflowRegion } = {}+ ) => {const graph = createProjectGraph('workflow-1');- const project = createMutablePort(projectSnapshot(graph, source));+ project = createMutablePort({ ...projectSnapshot(graph, source), ...history });+ commands = createCommands();// eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapterconst adapter = {- commands: createCommands(),+ CommandShortcut: ({ commandId }: { commandId: string }) => <kbd>{commandId}</kbd>,+ commands,getProjectGraph: () => graph,notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },persistence: persistence.port,@@ -517,7 +534,7 @@ describe('WorkflowHeaderActions', () => {root.render(<ChakraProvider value={system}><WorkflowUiProvider adapter={adapter}>- <WorkflowHeaderActions region="center" runtime={TEST_RUNTIME} />+ <WorkflowHeaderActions region={region} runtime={TEST_RUNTIME} /></WorkflowUiProvider></ChakraProvider>);@@ -525,6 +542,164 @@ describe('WorkflowHeaderActions', () => {};const status = () => host.querySelector<HTMLElement>('[role="status"][data-persistence-status]');+ const actionLabels = () =>+ Array.from(host.querySelectorAll<HTMLElement>('button, [role="status"]'), (action) =>+ action.getAttribute('aria-label')+ );+ const historyButton = (label: string) => host.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);++ it('steps the editor history from the header only where the editor is, and only while there is a step', async () => {+ await renderHeader();+ expect(actionLabels()).toEqual(['Add node', 'Undo', 'Redo', 'Save to library…', 'Project saved to the server']);+ expect(historyButton('Undo')?.getAttribute('aria-disabled')).toBe('true');+ expect(historyButton('Redo')?.getAttribute('aria-disabled')).toBe('true');++ await act(() => historyButton('Undo')?.click());+ await act(() => historyButton('Redo')?.click());+ expect(commands.undo).not.toHaveBeenCalled();+ expect(commands.redo).not.toHaveBeenCalled();++ await act(() => project.setSnapshot({ ...project.port.getSnapshot(), canRedo: true, canUndo: true }));+ expect(historyButton('Undo')?.hasAttribute('aria-disabled')).toBe(false);+ await act(() => historyButton('Undo')?.click());+ await act(() => historyButton('Redo')?.click());+ // The click event must not reach the command as a target: no argument means the active workflow.+ expect(commands.undo).toHaveBeenCalledExactlyOnceWith();+ expect(commands.redo).toHaveBeenCalledExactlyOnceWith();++ // The expanded bottom panel shows the editor too; the left region's linear form has no history to step.+ await renderHeader(undefined, { region: 'bottom' });+ expect(actionLabels()).toEqual(['Undo', 'Redo', 'Workflow library']);+ await renderHeader(undefined, { region: 'left' });+ expect(actionLabels()).toEqual(['Workflow library']);+ });++ it('hands Undo and Redo to the ⋯ menu while a narrow header hides them, keys and availability included', async () => {+ const graph = createProjectGraph('workflow-1');+ const history: HistoryState = { canRedo: false, canUndo: true };+ project = createMutablePort({ ...projectSnapshot(graph), ...history });+ commands = createCommands();+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapter+ const adapter = {+ CommandShortcut: ({ commandId }: { commandId: string }) => <kbd>{commandId}</kbd>,+ commands,+ getProjectGraph: () => graph,+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ persistence: persistence.port,+ project: project.port,+ widgets: { open: vi.fn(), patchValues: vi.fn() },+ } as unknown as WorkflowUiAdapter;+ const renderAt = (width: number) =>+ act(() => {+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ {/* The header row is the inline-size container the actions query, as the center chrome is. */}+ <div style={{ containerType: 'inline-size', width }}>+ <WorkflowHeaderActions region="center" runtime={TEST_RUNTIME} />+ </div>+ <Menu.Root open>+ <Menu.Positioner>+ <Menu.Content>+ <WorkflowMenuItems region="center" runtime={TEST_RUNTIME} />+ </Menu.Content>+ </Menu.Positioner>+ </Menu.Root>+ </WorkflowUiProvider>+ </ChakraProvider>+ );+ });+ const menuItem = (value: string) => host.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`);++ await renderAt(480);+ expect(historyButton('Undo')?.checkVisibility()).toBe(true);+ expect(historyButton('Save to library…')?.checkVisibility()).toBe(true);+ expect(menuItem('undo')).toBeNull();++ await renderAt(304);+ // The library action keeps its place; the history steps give way.+ expect(host.querySelector<HTMLElement>('button[aria-label="Save to library…"]')?.checkVisibility()).toBe(true);+ expect(historyButton('Undo')?.checkVisibility()).toBe(false);+ await vi.waitFor(() => expect(menuItem('undo')).not.toBeNull());+ expect(menuItem('undo')?.textContent).toBe('Undoworkflows.undo');+ expect(menuItem('redo')?.textContent).toBe('Redoworkflows.redo');+ expect(menuItem('redo')?.hasAttribute('data-disabled')).toBe(true);++ await userEvent.click(menuItem('undo')!);+ // Pointer tooling refuses a disabled item; forced, the press must still do nothing.+ await userEvent.click(menuItem('redo')!, { force: true });+ expect(commands.undo).toHaveBeenCalledExactlyOnceWith();+ expect(commands.redo).not.toHaveBeenCalled();++ // Room again: the header shows them and the menu stops repeating them.+ await renderAt(480);+ await vi.waitFor(() => expect(menuItem('undo')).toBeNull());+ });++ it('lets each header hand its history to its own ⋯ menu, and leaving forgets only its own', async () => {+ const graph = createProjectGraph('workflow-1');+ project = createMutablePort({ ...projectSnapshot(graph), ...NO_HISTORY });+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapter+ const adapter = {+ CommandShortcut: ({ commandId }: { commandId: string }) => <kbd>{commandId}</kbd>,+ commands: createCommands(),+ getProjectGraph: () => graph,+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ persistence: persistence.port,+ project: project.port,+ widgets: { open: vi.fn(), patchValues: vi.fn() },+ } as unknown as WorkflowUiAdapter;+ /** A header at its own width beside its own open ⋯ menu, as the frame places them. */+ const Surface = ({ region, width }: { region: 'bottom' | 'center'; width: number }) => (+ <div data-surface={region}>+ <div style={{ containerType: 'inline-size', width }}>+ <WorkflowHeaderActions region={region} runtime={TEST_RUNTIME} />+ </div>+ <Menu.Root open>+ <Menu.Positioner>+ <Menu.Content>+ <WorkflowMenuItems region={region} runtime={TEST_RUNTIME} />+ </Menu.Content>+ </Menu.Positioner>+ </Menu.Root>+ </div>+ );+ const renderSurfaces = (withBottom: boolean) =>+ act(() => {+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <Surface region="center" width={304} />+ {withBottom ? <Surface region="bottom" width={720} /> : null}+ </WorkflowUiProvider>+ </ChakraProvider>+ );+ });+ const menuOffersUndo = (region: string) =>+ host.querySelector(`[data-surface="${region}"] [role="menuitem"][data-value="undo"]`) !== null;++ // The wide bottom header mounts last; the narrow center's menu still offers what its own header hides.+ await renderSurfaces(true);+ await vi.waitFor(() => expect(menuOffersUndo('center')).toBe(true));+ expect(menuOffersUndo('bottom')).toBe(false);++ await renderSurfaces(false);+ await vi.waitFor(() => expect(host.querySelector('[data-surface="bottom"]')).toBeNull());+ expect(menuOffersUndo('center')).toBe(true);+ });++ it('keeps keyboard focus on Undo when it steps back over the last edit', async () => {+ await renderHeader(undefined, { history: { canRedo: false, canUndo: true } });+ const undo = historyButton('Undo')!;+ undo.focus();+ await act(() => undo.click());+ // The history is now empty: the button says so but keeps focus, so the keyboard user is not dropped to the page.+ await act(() => project.setSnapshot({ ...project.port.getSnapshot(), canRedo: true, canUndo: false }));++ expect(commands.undo).toHaveBeenCalledOnce();+ expect(undo.getAttribute('aria-disabled')).toBe('true');+ expect(document.activeElement).toBe(undo);+ });it('names the project persistence state, including a pending save with no local safety net', async () => {await renderHeader();diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex 1bc6f0afee..5c6a4b7b79 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -27,12 +27,14 @@ import {import { canCopyText } from '@platform/browser/clipboard';import { createDeferredModule } from '@platform/react/deferredModule';import { useMountEffect } from '@platform/react/useMountEffect';+import { createExternalStore } from '@platform/state/externalStore';import { Button, IconButton, RenameDialog, Tooltip } from '@platform/ui';import { CloseButton } from '@platform/ui/Button';import { Dialog } from '@platform/ui/Dialog';import { LoadError } from '@platform/ui/LoadError';import { MenuActionItem, MenuContent, SCROLLABLE_MENU_CONTENT_PROPS } from '@platform/ui/Menu';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { HeaderActionDivider, HeaderHistoryButton } from '@platform/ui/PanelHeader';import { useTooltipTriggerIds } from '@platform/ui/Tooltip';import { useQuery } from '@tanstack/react-query';import {@@ -55,8 +57,10 @@ import {LockIcon,PencilIcon,PlusIcon,+ Redo2Icon,RefreshCwIcon,TriangleAlertIcon,+ Undo2Icon,UploadIcon,} from 'lucide-react';import { useCallback, useEffect, useId, useMemo, useRef, useState, type ChangeEvent, type ElementType } from 'react';@@ -446,10 +450,96 @@ const WORKFLOW_SWITCHER_POSITIONING = { placement: 'bottom-start' } as const;// Clipped, but with room for the name button's focus ring.const LABEL_CLIP_CSS = { overflow: 'clip', overflowClipMargin: '4px' } as const;+/**+ * Below the width where every header action fits, Undo and Redo give way rather than the library actions: in the+ * default Workflow layout of a 1280px window the center chrome row is 304px, which held the header before they+ * arrived and no more. Their shortcuts keep working, and the ⋯ menu offers them while the header hides them. Queried+ * on the nearest container: the center chrome row, or a panel header.+ */+const HEADER_HISTORY_CSS = { '@container (width < 24rem)': { display: 'none' } } as const;++/**+ * The headers that have hidden their history steps for want of room, by widget instance and region: the widget can show+ * in several regions at once, each header at its own width, and each ⋯ menu (outside that container) asks after its+ * own header only.+ */+const headerHistoryStore = createExternalStore<{ hiddenIn: Readonly<Record<string, true>> }>({ hiddenIn: {} });++const getHeaderKey = ({ region, runtime }: WorkflowWidgetViewProps) => `${runtime.instanceId}\0${region}`;++const setHeaderHistoryHidden = (key: string, hidden: boolean) => {+ const { hiddenIn } = headerHistoryStore.getSnapshot();++ if (Boolean(hiddenIn[key]) === hidden) {+ return;+ }++ const { [key]: _removed, ...rest } = hiddenIn;+ headerHistoryStore.setSnapshot({ hiddenIn: hidden ? { ...rest, [key]: true } : rest });+};++/** Tracks one header's history group: a group the narrow header hides has no width. Leaving forgets only its entry. */+const useHeaderHistoryObserver = (key: string) =>+ useCallback(+ (element: HTMLDivElement | null) => {+ if (!element) {+ return undefined;+ }++ const update = () => setHeaderHistoryHidden(key, element.getBoundingClientRect().width === 0);+ // A group hidden from the start never reports a size, so read it once now.+ update();+ const observer = new ResizeObserver(update);+ observer.observe(element);++ return () => {+ observer.disconnect();+ setHeaderHistoryHidden(key, false);+ };+ },+ [key]+ );++/** Undo and Redo in the ⋯ menu, for a header too narrow to show them. */+const WorkflowHistoryMenuItems = () => {+ const { t } = useTranslation();+ const { CommandShortcut } = useWorkflowUi();+ const canUndo = useWorkflowProjectSelector((project) => project.canUndo);+ const canRedo = useWorkflowProjectSelector((project) => project.canRedo);+ const { redo, undo } = useProjectGraphCommands();+ const undoShortcut = useMemo(() => <CommandShortcut commandId="workflows.undo" />, [CommandShortcut]);+ const redoShortcut = useMemo(() => <CommandShortcut commandId="workflows.redo" />, [CommandShortcut]);+ // The click event must not reach a step that takes an optional target.+ const onUndo = useCallback(() => undo(), [undo]);+ const onRedo = useCallback(() => redo(), [redo]);++ return (+ <>+ <MenuActionItem+ disabled={!canUndo}+ icon={Undo2Icon}+ label={t('widgets.workflow.toolbar.undo')}+ shortcut={undoShortcut}+ value="undo"+ onSelect={onUndo}+ />+ <MenuActionItem+ disabled={!canRedo}+ icon={Redo2Icon}+ label={t('widgets.workflow.toolbar.redo')}+ shortcut={redoShortcut}+ value="redo"+ onSelect={onRedo}+ />+ <Menu.Separator />+ </>+ );+};+const EXPORT_SUBMENU_POSITIONING = { placement: 'right-start' } as const;/** Entries contributed to the shared widget actions menu, under its graph actions. */-export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {+export const WorkflowMenuItems = (props: WorkflowWidgetViewProps) => {const { t } = useTranslation();const session = useAuthSession();const { getProjectGraph } = useWorkflowUi();@@ -466,6 +556,8 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {? undefined: t('widgets.workflow.downloadPngUnavailable');const canUpdateSource = isUpdatableSource(source, session);+ const headerKey = getHeaderKey(props);+ const isHeaderHistoryHidden = headerHistoryStore.useSelector((snapshot) => Boolean(snapshot.hiddenIn[headerKey]));const openDetailsPanel = useCallback(() => {widgets.open({ region: 'left', widgetId: 'workflow' });@@ -510,6 +602,7 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {return (<>+ {isHeaderHistoryHidden ? <WorkflowHistoryMenuItems /> : null}<Menu.ItemGroup><Menu.ItemGroupLabel>{t('widgets.workflow.menuThisWorkflow')}</Menu.ItemGroupLabel><MenuActionItem@@ -600,7 +693,39 @@ const selectPersistenceView = (persistence: WorkflowProjectPersistence) => ({status: persistence.status,});-export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {+/** Undo and redo for the editor's session history, beside the other header actions as in Canvas's header. */+const WorkflowHistoryActions = () => {+ const { t } = useTranslation();+ const { CommandShortcut } = useWorkflowUi();+ const canUndo = useWorkflowProjectSelector((project) => project.canUndo);+ const canRedo = useWorkflowProjectSelector((project) => project.canRedo);+ const { redo, undo } = useProjectGraphCommands();+ const undoShortcut = useMemo(() => <CommandShortcut commandId="workflows.undo" />, [CommandShortcut]);+ const redoShortcut = useMemo(() => <CommandShortcut commandId="workflows.redo" />, [CommandShortcut]);++ return (+ <>+ <HeaderHistoryButton+ available={canUndo}+ icon={Undo2Icon}+ label={t('widgets.workflow.toolbar.undo')}+ shortcut={undoShortcut}+ onStep={undo}+ />+ <HeaderHistoryButton+ available={canRedo}+ icon={Redo2Icon}+ label={t('widgets.workflow.toolbar.redo')}+ shortcut={redoShortcut}+ onStep={redo}+ />+ </>+ );+};++export const WorkflowHeaderActions = (props: WorkflowWidgetViewProps) => {+ const { region } = props;+ const observeHeaderHistory = useHeaderHistoryObserver(getHeaderKey(props));const { t } = useTranslation();const session = useAuthSession();const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);@@ -622,6 +747,9 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {// A pending save without browser recovery has no safety net at all; say so rather than showing the same cloud.const persistenceLabel =status === 'pending' && !hasLocalRecovery ? t('widgets.workflow.persistencePendingNoRecovery') : t(view.labelKey);+ // History steps sit wherever the editor renders, as its toolbar did: the center and the expanded bottom panel (the+ // only bottom presentation with a header). The left region's linear form has no editor and no history keys.+ const showsHistory = region !== 'left';return (<HStack gap="0.5">@@ -638,6 +766,13 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {</IconButton></Tooltip>) : null}+ {showsHistory ? (+ <HStack ref={observeHeaderHistory} css={HEADER_HISTORY_CSS} gap="0.5">+ {region === 'center' ? <HeaderActionDivider /> : null}+ <WorkflowHistoryActions />+ <HeaderActionDivider />+ </HStack>+ ) : null}{/* The center label's menu already opens the library; other regions need this separate trigger and leavepublication and persistence to the editor header. */}{region === 'center' ? null : (diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsxindex f09a6a7867..fcc18547bc 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetView.tsx@@ -1,5 +1,6 @@import { Box, HStack, Icon, VisuallyHidden } from '@chakra-ui/react';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { chipLabelStyles } from '@theme/recipes';import { WorkflowIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -9,17 +10,20 @@ import { WorkflowEditorView } from './editor/WorkflowEditorView';import { WorkflowLinearPanel } from './linear/WorkflowLinearPanel';import { useWorkflowProjectSelector } from './WorkflowUiContext';+// The truncating label is a flex container, so its text sits in the spans it splits the name into.+const STATUS_LABEL_CSS = { '& > span': chipLabelStyles };+const WorkflowStatusBarItem = () => {const { t } = useTranslation();const workflowName = useWorkflowProjectSelector((project) => project.projectGraph.name);const isRunning = useWorkflowProjectSelector((project) => project.isWorkflowRunning);return (- <HStack gap="1" maxW="14rem" minW="0" px="2">+ <HStack fontWeight="500" gap="2" maxW="14rem" minW="0" px="2">{/* The status-bar chip is named by its content; the name alone would not say which widget it is. */}<VisuallyHidden>{t('widgets.labels.workflow')}</VisuallyHidden><Icon as={WorkflowIcon} boxSize="3" color={isRunning ? 'brand.solid' : undefined} flexShrink={0} />- <MiddleTruncate fontSize="xs" minW="0" text={workflowName || 'Untitled Workflow'} />+ <MiddleTruncate css={STATUS_LABEL_CSS} fontSize="xs" minW="0" text={workflowName || 'Untitled Workflow'} />{isRunning ? <Box bg="brand.solid" boxSize="1.5" flexShrink={0} rounded="full" /> : null}</HStack>);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsxindex 74b29b775a..79a407d9fb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx@@ -31,7 +31,6 @@ vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({success: toolbarMocks.success,}),useWorkflowPreferencesSelector: () => false,- useWorkflowUi: () => ({ CommandShortcut: ({ commandId }: { commandId: string }) => <kbd>{commandId}</kbd> }),useWorkflowProjectSelector: (selector: (project: unknown) => unknown) =>selector({ activeWorkflow: { document: { name: toolbarMocks.workflowName } } }),}));@@ -82,11 +81,7 @@ const render = async (nodeOpacity: number,arrangeProps: {arrangeScope?: 'all' | 'selection' | null;- canRedo?: boolean;- canUndo?: boolean;onArrangeNodes?: () => void;- onRedo?: () => void;- onUndo?: () => void;} = {}) => {applyThemeToRoot('mono');@@ -162,65 +157,13 @@ describe('editor toolbar', () => {expect(onArrangeNodes).toHaveBeenCalledTimes(1);});- it('undoes and redoes from the toolbar only while the history has an edit to step over', async () => {- const onRedo = vi.fn();- const onUndo = vi.fn();- const undo = () => host!.querySelector<HTMLButtonElement>('button[aria-label="Undo"]')!;- const redo = () => host!.querySelector<HTMLButtonElement>('button[aria-label="Redo"]')!;-- await render(1, { canRedo: false, canUndo: false, onRedo, onUndo });- expect(undo().getAttribute('aria-disabled')).toBe('true');- expect(redo().getAttribute('aria-disabled')).toBe('true');- await settle(() => undo().click());- await settle(() => redo().click());- expect(onUndo).not.toHaveBeenCalled();- expect(onRedo).not.toHaveBeenCalled();-- await render(1, { canRedo: true, canUndo: true, onRedo, onUndo });- await settle(() => undo().click());- await settle(() => redo().click());- expect(onUndo).toHaveBeenCalledOnce();- expect(onRedo).toHaveBeenCalledOnce();- });-- it('keeps keyboard focus on Undo when it steps back over the last edit', async () => {- const renderHistory = (canUndo: boolean) =>- settle(() => {- root?.render(- <I18nextProvider i18n={i18n}>- <ChakraProvider value={system}>- <EditorToolbar- canRedo={!canUndo}- canUndo={canUndo}- nodeOpacity={1}- tool="pan"- onNodeOpacityChange={vi.fn()}- onRedo={vi.fn()}- onToolChange={vi.fn()}- onUndo={vi.fn()}- />- </ChakraProvider>- </I18nextProvider>- );- });-- await render(1);- await renderHistory(true);- const undo = host!.querySelector<HTMLButtonElement>('button[aria-label="Undo"]')!;- undo.focus();- await settle(() => undo.click());- // The history is now empty: the button says so but keeps focus, so the keyboard user is not dropped to the page.- await renderHistory(false);-- expect(undo.getAttribute('aria-disabled')).toBe('true');- expect(document.activeElement).toBe(undo);- });-it('keeps every button on one shared square toolbar box', async () => {// Match custom control sizing; one wider child stretches every button in the column toolbar.await render(1);expect(new Set(buttonBoxes())).toEqual(new Set(['28x28']));+ // Undo and redo moved to the widget header, beside the other header actions as in Canvas.+ expect(host!.querySelector('button[aria-label="Undo"], button[aria-label="Redo"]')).toBeNull();});it('offers to update outdated nodes only while there are some, without breaking the toolbar grid', async () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsxindex 3c4cec313c..be555a2674 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx@@ -1,7 +1,6 @@-import { Box, HStack, Icon, Popover, Portal, Slider, Stack, Text } from '@chakra-ui/react';+import { Box, Icon, Popover, Portal, Slider, Stack, Text } from '@chakra-ui/react';import {useWorkflowNotifications,- useWorkflowUi,useWorkflowPreferencesSelector,useWorkflowProjectSelector,} from '@features/workflow/ui/WorkflowUiContext';@@ -17,8 +16,6 @@ import {LayoutGridIcon,CircleArrowUpIcon,MaximizeIcon,- Redo2Icon,- Undo2Icon,ZoomInIcon,ZoomOutIcon,} from 'lucide-react';@@ -53,32 +50,23 @@ const EDITOR_TOOLBAR_TOP = 'var(--wb-center-chrome-inset, var(--chakra-spacing-2export const EditorToolbar = ({arrangeScope = null,- canRedo = false,- canUndo = false,nodeOpacity,tool,updatableNodeCount = 0,onArrangeNodes,onNodeOpacityChange,- onRedo,onToolChange,- onUndo,onUpdateNodes,}: {/** What Arrange would lay out: the selection, the whole graph, or nothing (fewer than two nodes). */arrangeScope?: 'all' | 'selection' | null;- /** Whether the workflow's session history has an edit to redo or undo. */- canRedo?: boolean;- canUndo?: boolean;nodeOpacity: number;tool: EditorTool;/** Nodes with a newer same-major template; the update button shows only while there are some. */updatableNodeCount?: number;onArrangeNodes?: () => void;onNodeOpacityChange: (opacity: number) => void;- onRedo?: () => void;onToolChange: (tool: EditorTool) => void;- onUndo?: () => void;onUpdateNodes?: () => void;}) => {const { t } = useTranslation();@@ -133,23 +121,6 @@ export const EditorToolbar = ({/>))}<ToolbarSeparator />- <HistoryButton- commandId="workflows.undo"- disabled={!canUndo}- icon={Undo2Icon}- label={t('widgets.workflow.toolbar.undo')}- tooltip={t('widgets.workflow.commands.undo')}- onClick={onUndo}- />- <HistoryButton- commandId="workflows.redo"- disabled={!canRedo}- icon={Redo2Icon}- label={t('widgets.workflow.toolbar.redo')}- tooltip={t('widgets.workflow.commands.redo')}- onClick={onRedo}- />- <ToolbarSeparator /><ToolbarButton icon={ZoomInIcon} label={t('widgets.workflow.toolbar.zoomIn')} onClick={onZoomInClick} /><ToolbarButton icon={ZoomOutIcon} label={t('widgets.workflow.toolbar.zoomOut')} onClick={onZoomOutClick} /><ToolbarButton@@ -236,49 +207,6 @@ export const EditorToolbar = ({);};-/** A toolbar button whose tooltip also shows the editor command's current shortcut. */-const HistoryButton = ({- commandId,- disabled,- icon,- label,- onClick,- tooltip,-}: {- commandId: string;- disabled: boolean;- icon: typeof HandIcon;- label: string;- onClick?: () => void;- tooltip: string;-}) => {- const { CommandShortcut } = useWorkflowUi();- // The click event must not reach a command that takes an optional target, and an unavailable step does nothing.- const onButtonClick = useCallback(() => {- if (!disabled) {- onClick?.();- }- }, [disabled, onClick]);- const content = useMemo(- () => (- <HStack gap="2">- <span>{tooltip}</span>- <CommandShortcut commandId={commandId} />- </HStack>- ),- [CommandShortcut, commandId, tooltip]- );-- return (- <Tooltip content={content} positioning={TOOLTIP_POSITIONING}>- {/* aria-disabled, not disabled: stepping to the end of the history must not drop the button's focus. */}- <IconButton aria-disabled={disabled || undefined} aria-label={label} variant="ghost" onClick={onButtonClick}>- <Icon as={icon} boxSize="3.5" />- </IconButton>- </Tooltip>- );-};-const EditorToolButton = ({icon,id,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex ddd1816703..16d0a24315 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -327,8 +327,6 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);const projectId = useWorkflowProjectSelector((project) => project.id);const workflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);- const canUndo = useWorkflowProjectSelector((project) => project.canUndo);- const canRedo = useWorkflowProjectSelector((project) => project.canRedo);const ui = useWorkflowUi();const { mark: markWorkbenchPerf, measure: measureWorkbenchPerf, time: timeWorkbenchPerf } = ui.performance;const { editGraph, redo, undo } = useProjectGraphCommands();@@ -1482,16 +1480,12 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {<LoopBodyBoundaryOverlay edges={projectGraph.edges} nodes={projectGraph.nodes} /><EditorToolbararrangeScope={arrangeScope}- canRedo={canRedo}- canUndo={canUndo}nodeOpacity={nodeOpacity}tool={tool}updatableNodeCount={updatableNodeCount}onArrangeNodes={onArrangeNodes}onNodeOpacityChange={setNodeOpacity}- onRedo={redo}onToolChange={setTool}- onUndo={undo}onUpdateNodes={onUpdateNodes}/>{/* An empty graph's minimap is a bare panel that reads as a broken element. */}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 4ac37e3f5b..f465043d95 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@@ -862,6 +862,36 @@ describe('WorkflowFieldInput media inputs', () => {expect(resolveItemMock).not.toHaveBeenCalled();});+ it('keeps the empty image well in its hover look while its picker is open, and not after', async () => {+ const imageTemplate = {+ name: 'image',+ title: 'Image',+ type: { name: 'ImageField' },+ } as unknown as FieldInputTemplate;++ await renderField(imageTemplate, undefined, vi.fn());+ const button = host.querySelector<HTMLButtonElement>('button.nodrag')!;+ const well = button.firstElementChild as HTMLElement;+ // Read once the well's border transition has finished.+ const border = async () => {+ await vi.waitFor(() => expect(well.getAnimations()).toHaveLength(0));+ return getComputedStyle(well).borderColor;+ };+ const resting = await border();++ await userEvent.hover(well);+ const hovered = await border();+ expect(hovered).not.toBe(resting);+ await userEvent.unhover(well);+ expect(await border()).toBe(resting);++ // The gallery picker marks its trigger `data-hover` while open (its own test covers that); the picker is stubbed here.+ button.setAttribute('data-hover', '');+ expect(await border()).toBe(hovered);+ button.removeAttribute('data-hover');+ expect(await border()).toBe(resting);+ });+it('reveals the chosen image in the gallery from the field', async () => {const imageTemplate = {name: 'image',diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex 16beb426c3..07e5a5107a 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -178,10 +178,15 @@ export interface WorkflowFieldInputProps {}// The media well's hover matches DropZone's accent preview; an invalid well keeps its error border and tints instead.-const MEDIA_WELL_PROPS = { _hover: { borderColor: 'accent.solid' } };+// The well draws its button's hover, and keeps it while the button is pointed: the gallery picker marks its trigger+// `data-hover` while it is open.+const MEDIA_WELL_HOVER = { borderColor: 'accent.solid' };+const MEDIA_WELL_INVALID_HOVER = { bg: 'bg.error/60', borderColor: 'border.error' };+const MEDIA_WELL_PROPS = { _hover: MEDIA_WELL_HOVER, css: { '[data-hover] > &': MEDIA_WELL_HOVER } };const MEDIA_WELL_INVALID_PROPS = {borderColor: 'border.error',- _hover: { bg: 'bg.error/60', borderColor: 'border.error' },+ _hover: MEDIA_WELL_INVALID_HOVER,+ css: { '[data-hover] > &': MEDIA_WELL_INVALID_HOVER },};/** A row of a list names itself by position; a scalar field is named by its title. */diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsxindex a3679b061b..92b7ad5e5a 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowse.browser.test.tsx@@ -533,12 +533,20 @@ it.each([onTestFinished(() => clock.mockRestore());await open();const scroll = viewport()!;- for (let top = 0; top <= 39600; top += 1200) {+ // Cross enough listing windows to exercise eviction without repeating every intermediate scroll.+ for (let top = 0; top <= 43200; top += 3600) {await scrollTo(scroll, top);expect(document.querySelectorAll('[data-workflow-card]').length).toBeLessThan(48);expect(browse.getWorkflowLibraryBrowseSnapshot().entries.length).toBeLessThanOrEqual(60);}+ await scrollTo(scroll, 39600);await settle();+ const listedPositions = new Set(+ transport.list.mock.calls.flatMap(([{ page, perPage = 20 }]) =>+ Array.from({ length: perPage }, (_, index) => page * perPage + index)+ )+ );+ expect(listedPositions.size).toBeGreaterThan(540);const before = firstVisibleRow(scroll);expect(Number(before.id?.slice(3))).toBeGreaterThan(400);expect(before.offset).toBeGreaterThan(10);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsxindex 984c5e0828..e7a1572ca6 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/FormBuilderTab.tsx@@ -478,9 +478,11 @@ const BuilderElementBase = ({<BuilderCard element={element} title={title}><Inputaria-label={t('widgets.workflow.formBuilder.headingLabel')}- fontSize="lg"- fontWeight="700"+ fontSize="xs"+ fontWeight="semibold"+ letterSpacing="wider"placeholder={t('widgets.workflow.formBuilder.headingPlaceholder')}+ textTransform="uppercase"value={element.data.content}variant="flushed"onChange={(event: ChangeEvent<HTMLInputElement>) =>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsxindex 42217cd822..8ac6788084 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/LinearFormView.tsx@@ -10,11 +10,30 @@ import { useTranslation } from 'react-i18next';import { LinkifiedText } from './LinkifiedText';import { NodeFieldControl } from './NodeFieldControl';-const ViewElement = ({ element, projectGraph }: { element: WorkflowFormElement; projectGraph: ProjectGraphState }) => {+/**+ * The form reads like the Generate and Upscale sections: a heading is a section title, and a hairline that runs edge+ * to edge starts a section. Only root elements bleed; inside a container a line stays within its column.+ */+const ROOT_INSET = '3';+const ROOT_HEADING_STYLES = {+ '&:not(:first-child)': { borderTopWidth: '1px', mx: `-${ROOT_INSET}`, pt: ROOT_INSET, px: ROOT_INSET },+ // An authored divider already drew the line. With equal specificity, this must follow the rule above.+ '[data-form-divider] + &': { borderTopWidth: 0, mx: 0, pt: 0, px: 0 },+} as const;++const ViewElement = ({+ element,+ isRoot = false,+ projectGraph,+}: {+ element: WorkflowFormElement;+ isRoot?: boolean;+ projectGraph: ProjectGraphState;+}) => {switch (element.type) {case 'container':return (- <Stack direction={element.data.layout === 'row' ? 'row' : 'column'} gap="3">+ <Stack direction={element.data.layout === 'row' ? 'row' : 'column'} gap="2.5">{getFormChildren(projectGraph.form, element.id).map((child) => (<ViewElement key={child.id} element={child} projectGraph={projectGraph} />))}@@ -24,7 +43,13 @@ const ViewElement = ({ element, projectGraph }: { element: WorkflowFormElement;return <NodeFieldControl element={element} projectGraph={projectGraph} />;case 'heading':return (- <Text fontSize="lg" fontWeight="700">+ <Text+ css={isRoot ? ROOT_HEADING_STYLES : undefined}+ fontSize="xs"+ fontWeight="semibold"+ letterSpacing="wider"+ textTransform="uppercase"+ >{element.data.content}</Text>);@@ -35,7 +60,7 @@ const ViewElement = ({ element, projectGraph }: { element: WorkflowFormElement;</LinkifiedText>);case 'divider':- return <Separator borderColor="border.subtle" />;+ return <Separator data-form-divider mx={isRoot ? `-${ROOT_INSET}` : undefined} />;}};@@ -63,9 +88,9 @@ export const LinearFormView = ({ projectGraph }: { projectGraph: ProjectGraphSta}return (- <Stack gap="3" p="3">+ <Stack gap="2.5" p={ROOT_INSET}>{rootChildren.map((element) => (- <ViewElement key={element.id} element={element} projectGraph={projectGraph} />+ <ViewElement key={element.id} element={element} isRoot projectGraph={projectGraph} />))}</Stack>);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsxindex cba6f0d33c..de5111a4fa 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx@@ -176,8 +176,9 @@ export const NodeFieldControl = ({return (<Field.Root invalid={isInvalid} minW="0" w="full"><Stack gap="1" minW="0" w="full">+ {/* The label row is always as tall as the reset button, so the input below never moves when it appears. */}{isLabelEditable ? (- <HStack gap="1" minW="0" w="full">+ <HStack gap="1" minH="6" minW="0" w="full"><Inputaria-label={t('nodes.fieldLabel')}color={isInvalid ? 'fg.error' : 'fg.muted'}@@ -196,7 +197,7 @@ export const NodeFieldControl = ({{resetButton}</HStack>) : (- <HStack gap="1" minW="0" w="full">+ <HStack gap="1" minH="6" minW="0" w="full"><Tooltip content={`${nodeContext} → ${template.title}`}><Stack color={isInvalid ? 'fg.error' : undefined} flex="1" gap="0" minW="0"><FieldLabel>{label}</FieldLabel>@@ -205,11 +206,6 @@ export const NodeFieldControl = ({{resetButton}</HStack>)}- {element.data.showDescription && description ? (- <LinkifiedText color="fg.subtle" fontSize="xs" whiteSpace="pre-wrap">- {description}- </LinkifiedText>- ) : null}{isConnected ? (<Text color="fg.subtle" fontSize="xs">{t('nodes.providedByConnection')}@@ -250,6 +246,12 @@ export const NodeFieldControl = ({) : null}</HStack>)}+ {/* Below the control, as `Field` places helper text: side-by-side fields keep their inputs level. */}+ {element.data.showDescription && description ? (+ <LinkifiedText color="fg.subtle" fontSize="xs" whiteSpace="pre-wrap">+ {description}+ </LinkifiedText>+ ) : null}{invalidReason ? <Field.ErrorText fontSize="xs">{invalidReason}</Field.ErrorText> : null}</Stack></Field.Root>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsxindex 9b8f02a07b..84876118d5 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx@@ -617,6 +617,28 @@ describe('Linear form field entry', () => {expect(scale.getAttribute('aria-invalid')).toBeNull();});+ it('keeps a field input at the same height whether or not its reset button shows', async () => {+ const { field, value } = await renderForm();+ const scale = field('Scale');+ const fieldRoot = scale.closest<HTMLElement>('[data-scope="field"][data-part="root"]')!;+ const resetButton = () => fieldRoot.querySelector('button[aria-label="nodes.resetFieldToDefault"]');+ const inputOffset = () => scale.getBoundingClientRect().top - fieldRoot.getBoundingClientRect().top;++ expect(resetButton()).not.toBeNull();+ const offsetWithReset = inputOffset();++ // Emptying an optional field returns it to its default, which takes the reset button away.+ await act(async () => {+ scale.focus();+ scale.select();+ await userEvent.keyboard('{Backspace}');+ });+ await act(() => scale.blur());+ expect(value('scale')).toBeUndefined();+ expect(resetButton()).toBeNull();+ expect(inputOffset()).toBe(offsetWithReset);+ });+it('edits an exposed scalar list row by row and reports the first empty entry', async () => {const { value } = await renderForm();// Raw i18n keys: every list row shares one accessible name, so rows are found by position.diff --git a/invokeai/frontend/webv2/src/platform/browser/dropZones.ts b/invokeai/frontend/webv2/src/platform/browser/dropZones.tsnew file mode 100644index 0000000000..224d4be40f--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/browser/dropZones.ts@@ -0,0 +1,22 @@+/**+ * The value of `attribute` on the element inside `root` whose rect holds the point, as a pointer drag library's+ * collision finds a droppable: whatever is painted above the zone, and with the zone itself click-through.+ */+export const findDropZoneAt = (+ root: Element,+ attribute: string,+ point: { clientX: number; clientY: number }+): string | null => {+ for (const zone of root.querySelectorAll(`[${attribute}]`)) {+ const rect = zone.getBoundingClientRect();+ if (+ point.clientX >= rect.left &&+ point.clientX < rect.right &&+ point.clientY >= rect.top &&+ point.clientY < rect.bottom+ ) {+ return zone.getAttribute(attribute);+ }+ }+ return null;+};diff --git a/invokeai/frontend/webv2/src/platform/browser/fileDropNavigation.browser.test.ts b/invokeai/frontend/webv2/src/platform/browser/fileDropNavigation.browser.test.tsnew file mode 100644index 0000000000..41fdb9c03d--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/browser/fileDropNavigation.browser.test.ts@@ -0,0 +1,160 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { commands } from 'vitest/browser';++import { preventFileDropNavigation } from './fileDropNavigation';+import { TINY_PNG_BASE64 } from './nativeDrag.testing';++const PNG_FILE = {+ base64: TINY_PNG_BASE64,+ name: 'photo.png',+};+const LINK = 'https://example.com/photo.png';++/*+ * A drop driven through CDP never navigates the headless test frame, guard or not, so these tests read what the+ * guard did to each event: a drag it takes is cancelled (`dragover` prevented, with no drop effect, so the browser+ * dispatches no drop and opens nothing), and one it leaves reaches the browser's default.+ */+describe('preventFileDropNavigation', () => {+ const cleanups: (() => void)[] = [];++ afterEach(() => {+ cleanups.splice(0).forEach((cleanup) => cleanup());+ });++ const mount = <T extends HTMLElement>(element: T): T => {+ Object.assign(element.style, { height: '120px', left: '20px', position: 'fixed', top: '20px', width: '120px' });+ document.body.append(element);+ cleanups.push(() => element.remove());+ return element;+ };+ /**+ * Installs the guard, then a recorder after it noting whether the guard took each drag event (`taken`) or left it to+ * the browser (`open`). The recorder lets everything it sees through, so a text field still takes what it is given.+ */+ const installGuard = () => {+ const seen: string[] = [];+ cleanups.push(preventFileDropNavigation());+ const record = (event: DragEvent) => {+ seen.push(`${event.type}:${event.defaultPrevented ? 'taken' : 'open'}`);+ };+ window.addEventListener('dragover', record);+ window.addEventListener('drop', record);+ cleanups.push(() => {+ window.removeEventListener('dragover', record);+ window.removeEventListener('drop', record);+ });+ return seen;+ };+ const dragOnto = (element: HTMLElement, data: { files?: (typeof PNG_FILE)[]; text?: string; uriList?: string }) => {+ const rect = element.getBoundingClientRect();+ return commands.nativeDrag({+ ...data,+ frameWidth: window.innerWidth,+ points: [{ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }],+ });+ };+ const dragOvers = (seen: string[]) => [...new Set(seen.filter((entry) => entry.startsWith('dragover')))];+ /** A drop the test dispatches itself: whether the guard cancelled it, for a drop a browser would still deliver. */+ const dropTaken = (target: HTMLElement, types: Record<string, string>, file?: File) => {+ const dataTransfer = new DataTransfer();+ if (file) {+ dataTransfer.items.add(file);+ }+ for (const [type, value] of Object.entries(types)) {+ dataTransfer.setData(type, value);+ }+ const event = new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer });+ target.dispatchEvent(event);+ return event.defaultPrevented;+ };+ /** One text field at the drag's point: an input, a textarea (as a prompt field is) or a contenteditable editor. */+ const textField = (kind: 'editor' | 'input' | 'textarea') =>+ mount(+ kind === 'editor'+ ? Object.assign(document.createElement('div'), { contentEditable: 'true' })+ : kind === 'input'+ ? Object.assign(document.createElement('input'), { type: 'text' })+ : document.createElement('textarea')+ );++ it('takes a file or link dragged over the app where nothing takes it, so the browser never opens it in the tab', async () => {+ const seen = installGuard();+ const plain = mount(document.createElement('div'));++ await dragOnto(plain, { files: [PNG_FILE] });+ expect(dragOvers(seen)).toEqual(['dragover:taken']);++ seen.length = 0;+ // An image dragged from another browser window often carries only its address.+ await dragOnto(plain, { uriList: LINK });+ expect(dragOvers(seen)).toEqual(['dragover:taken']);+ });++ it.each(['input', 'textarea', 'editor'] as const)(+ 'takes a file dropped on a text %s, which cannot hold it, even when the drag also carries text',+ async (field) => {+ const seen = installGuard();+ const target = textField(field);++ await dragOnto(target, { files: [PNG_FILE] });+ expect(dragOvers(seen)).toEqual(['dragover:taken']);++ seen.length = 0;+ await dragOnto(target, { files: [PNG_FILE], text: 'photo.png', uriList: LINK });+ expect(dragOvers(seen)).toEqual(['dragover:taken']);+ expect(seen).not.toContain('drop:open');++ const file = new File(['x'], 'photo.png', { type: 'image/png' });+ expect(dropTaken(target, {}, file)).toBe(true);+ expect(dropTaken(target, { 'text/plain': 'photo.png', 'text/uri-list': LINK }, file)).toBe(true);+ }+ );++ it.each(['input', 'textarea', 'editor'] as const)('leaves a link dropped on a text %s to it', async (field) => {+ const seen = installGuard();+ const target = textField(field);++ await dragOnto(target, { uriList: LINK });++ expect(dragOvers(seen)).toEqual(['dragover:open']);+ expect(dropTaken(target, { 'text/uri-list': LINK })).toBe(false);+ });++ it('leaves plain text to the browser, which inserts it into a text field', async () => {+ const seen = installGuard();+ const input = textField('input') as HTMLInputElement;++ await dragOnto(input, { text: 'a red fox' });++ expect(seen).not.toContain('dragover:taken');+ await vi.waitFor(() => expect(input.value).toBe('a red fox'));+ });++ it('leaves a file to a native file input', async () => {+ const seen = installGuard();+ const input = mount(Object.assign(document.createElement('input'), { type: 'file' }));++ await dragOnto(input, { files: [PNG_FILE] });++ expect(dragOvers(seen)).toEqual(['dragover:open']);+ });++ it('leaves a drag a surface takes to that surface: its drop arrives with the file', async () => {+ installGuard();+ const surface = mount(document.createElement('div'));+ const dropped: string[] = [];+ surface.addEventListener('dragover', (event) => {+ event.preventDefault();+ event.dataTransfer!.dropEffect = 'copy';+ });+ surface.addEventListener('drop', (event) => {+ event.preventDefault();+ dropped.push(...[...event.dataTransfer!.files].map((file) => file.name));+ });++ await dragOnto(surface, { files: [PNG_FILE] });++ expect(dropped).toEqual(['photo.png']);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/browser/fileDropNavigation.ts b/invokeai/frontend/webv2/src/platform/browser/fileDropNavigation.tsnew file mode 100644index 0000000000..17f6537b12--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/browser/fileDropNavigation.ts@@ -0,0 +1,54 @@+const carriesFiles = (event: DragEvent): boolean => event.dataTransfer?.types.includes('Files') ?? false;++// A dropped link or web image (`text/uri-list`) also opens in the tab unless the page takes it.+const carriesLink = (event: DragEvent): boolean => event.dataTransfer?.types.includes('text/uri-list') ?? false;++const isFileInput = (target: EventTarget | null): boolean =>+ target instanceof HTMLInputElement && target.type === 'file';++// Text fields and editors insert a dropped link as text.+const isTextTarget = (target: EventTarget | null): boolean =>+ target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement ||+ (target instanceof HTMLElement && target.isContentEditable);++/**+ * Whether the browser would open the drag in the tab, as nothing on the page took it. A drag carrying files is a file+ * drag whatever text it also carries: only a native file input takes those, and a text field dropped on would let the+ * browser open the file. A link without files is left to text fields and editors, which insert it.+ */+const opensUnhandled = (event: DragEvent): boolean => {+ if (event.defaultPrevented) {+ return false;+ }+ if (carriesFiles(event)) {+ return !isFileInput(event.target);+ }+ return carriesLink(event) && !isTextTarget(event.target);+};++/**+ * Keeps a file or link dragged in from the desktop or another window from replacing the app. Surfaces that accept a+ * drop take it first and are left alone, as are native file inputs, and text fields for links; anywhere else the+ * drag shows that it cannot be dropped, and a drop that still arrives is swallowed. Plain text drags never navigate+ * and stay untouched.+ */+export const preventFileDropNavigation = (): (() => void) => {+ const handleDragOver = (event: DragEvent) => {+ if (opensUnhandled(event)) {+ event.preventDefault();+ event.dataTransfer!.dropEffect = 'none';+ }+ };+ const handleDrop = (event: DragEvent) => {+ if (opensUnhandled(event)) {+ event.preventDefault();+ }+ };+ window.addEventListener('dragover', handleDragOver);+ window.addEventListener('drop', handleDrop);+ return () => {+ window.removeEventListener('dragover', handleDragOver);+ window.removeEventListener('drop', handleDrop);+ };+};diff --git a/invokeai/frontend/webv2/src/platform/browser/nativeDrag.testing.ts b/invokeai/frontend/webv2/src/platform/browser/nativeDrag.testing.tsnew file mode 100644index 0000000000..0df7ea8acc--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/browser/nativeDrag.testing.ts@@ -0,0 +1,19 @@+/** A 2×2 PNG, for files a test drags in with `commands.nativeDrag`. */+export const TINY_PNG_BASE64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAEklEQVR4nGP4z8DwHwyBNAMDAC+tBv1+4dL7AAAAAElFTkSuQmCC';++declare module 'vitest/browser' {+ interface BrowserCommands {+ /**+ * Drags files, a link or plain text in from outside the page through Chromium's own drag input and drops it at the+ * last point (the test frame's viewport coordinates); defined in `vitest.browser.config.mts`.+ */+ nativeDrag: (options: {+ files?: readonly { base64: string; name: string }[];+ frameWidth: number;+ points: readonly { x: number; y: number }[];+ text?: string;+ uriList?: string;+ }) => Promise<void>;+ }+}diff --git a/invokeai/frontend/webv2/src/platform/react/isEventFromOwnDom.ts b/invokeai/frontend/webv2/src/platform/react/isEventFromOwnDom.tsnew file mode 100644index 0000000000..01823ca894--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/react/isEventFromOwnDom.ts@@ -0,0 +1,9 @@+import type { SyntheticEvent } from 'react';++/**+ * Whether an event started inside the handling element's own DOM. React bubbles events along the component tree, so+ * one from portalled content a descendant opened (a popover, menu, or tooltip) also reaches ancestors whose DOM does+ * not hold it. A handler acting for its own surface, such as a region's right-click menu, ignores those.+ */+export const isEventFromOwnDom = (event: SyntheticEvent<Element>): boolean =>+ event.target instanceof Node && event.currentTarget.contains(event.target);diff --git a/invokeai/frontend/webv2/src/platform/react/useNativeFileDrag.ts b/invokeai/frontend/webv2/src/platform/react/useNativeFileDrag.tsnew file mode 100644index 0000000000..cfba03b32f--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/react/useNativeFileDrag.ts@@ -0,0 +1,152 @@+import type { DragEvent as ReactDragEvent } from 'react';++import { useCallback, useRef, useState } from 'react';++import { isEventFromOwnDom } from './isEventFromOwnDom';+import { useMountEffect } from './useMountEffect';++/** Files dragged in from outside the page over a drop surface: their MIME types and the zone under the pointer. */+export interface NativeFileDrag<Zone extends string> {+ /** One per dragged file, readable while it hovers (contents are not); empty when the OS gives no type. */+ fileTypes: readonly string[];+ zone: Zone | null;+}++interface DragPoint {+ clientX: number;+ clientY: number;+}++// A file drag over the surface's own elements. React also bubbles drag events from portalled content a descendant+// opened, such as a confirmation dialog or a menu: that content is not the surface wherever it is painted, so the+// surface neither tracks nor takes such a drag. Leaving the surface for it ends the drag (see `onDragLeave`), and+// entering the surface from it starts a new one, so skipping its events keeps enters and leaves balanced.+const isFileDragOnSurface = (event: ReactDragEvent): boolean =>+ isEventFromOwnDom(event) && event.dataTransfer.types.includes('Files');++const fileTypesOf = (event: ReactDragEvent): string[] =>+ [...event.dataTransfer.items].filter((item) => item.kind === 'file').map((item) => item.type);++const isWithin = (event: ReactDragEvent<HTMLElement>): boolean =>+ event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget);++/**+ * Adapts HTML5 file drags from the operating system, which pointer-sensor drag libraries never see, for one drop+ * surface: spread `handlers` on its root, render zones from `drag` that `findZone` locates, and receive a drop on a+ * zone in `onDrop`. Every file drag over the surface's own elements is taken, so the browser never opens the file in+ * place of the app; where no zone is under the pointer the drag shows that it cannot drop. Portalled content the+ * surface's descendants open (a dialog, a menu) is not the surface: a drag over it is left to the page's navigation+ * guard, so a drop on an open confirmation never lands behind it.+ *+ * The drag ends when it leaves the surface for the rest of the page, leaves the window or is cancelled (a leave with+ * no related target), and on any drop or `dragend`. It is not tied to window focus: a window manager that moves focus+ * with the pointer would otherwise end a drag still in progress.+ */+export const useNativeFileDrag = <Zone extends string>({+ findZone,+ onDrop,+}: {+ /** The zone under the point within the surface's root, or null where none takes files. */+ findZone: (root: HTMLElement, point: DragPoint) => Zone | null;+ onDrop: (files: File[], zone: Zone) => void;+}) => {+ const [drag, setDrag] = useState<NativeFileDrag<Zone> | null>(null);+ // The zone the last dragenter or dragover found, as the browser's drop effect reported it. The drop reads this rather+ // than the zones, which an update flushed between the drop's listeners may already have taken down.+ const zoneRef = useRef<Zone | null>(null);+ const pendingEndRef = useRef<number | null>(null);+ const cancelPendingEnd = useCallback(() => {+ if (pendingEndRef.current !== null) {+ window.clearTimeout(pendingEndRef.current);+ pendingEndRef.current = null;+ }+ }, []);+ const end = useCallback(() => {+ cancelPendingEnd();+ zoneRef.current = null;+ setDrag(null);+ }, [cancelPendingEnd]);++ useMountEffect(() => {+ // Bubble phase: a drop on the surface is handled by the surface first; these end a drag that finished elsewhere.+ window.addEventListener('drop', end);+ window.addEventListener('dragend', end);+ return () => {+ window.removeEventListener('drop', end);+ window.removeEventListener('dragend', end);+ cancelPendingEnd();+ };+ });++ const track = useCallback(+ (event: ReactDragEvent<HTMLElement>, entering: boolean) => {+ cancelPendingEnd();+ const zone = findZone(event.currentTarget, event);+ zoneRef.current = zone;+ setDrag((current) =>+ // A drag coming in from outside the surface is a new one: its files' types are read afresh.+ current === null || entering+ ? { fileTypes: fileTypesOf(event), zone }+ : current.zone === zone+ ? current+ : { ...current, zone }+ );+ return zone;+ },+ [cancelPendingEnd, findZone]+ );++ const onDragEnter = useCallback(+ (event: ReactDragEvent<HTMLElement>) => {+ if (!isFileDragOnSurface(event)) {+ return;+ }+ event.preventDefault();+ track(event, !isWithin(event));+ },+ [track]+ );+ const onDragOver = useCallback(+ (event: ReactDragEvent<HTMLElement>) => {+ if (!isFileDragOnSurface(event)) {+ return;+ }+ event.preventDefault();+ event.dataTransfer.dropEffect = track(event, false) === null ? 'none' : 'copy';+ },+ [track]+ );+ const onDragLeave = useCallback(+ (event: ReactDragEvent<HTMLElement>) => {+ if (!isFileDragOnSurface(event) || isWithin(event)) {+ return;+ }+ if (event.relatedTarget === null) {+ // Leaving the window or a cancelled drag; some engines also report a move between the surface's own elements+ // this way, and a dragenter or dragover on the surface follows such a move in the same task, keeping the drag.+ cancelPendingEnd();+ pendingEndRef.current = window.setTimeout(end, 0);+ return;+ }+ end();+ },+ [cancelPendingEnd, end]+ );+ const handleDrop = useCallback(+ (event: ReactDragEvent<HTMLElement>) => {+ if (!isFileDragOnSurface(event)) {+ return;+ }+ event.preventDefault();+ const zone = zoneRef.current;+ const files = [...event.dataTransfer.files];+ end();+ if (zone !== null) {+ onDrop(files, zone);+ }+ },+ [end, onDrop]+ );++ return { drag, handlers: { onDragEnter, onDragLeave, onDragOver, onDrop: handleDrop } };+};diff --git a/invokeai/frontend/webv2/src/platform/ui/Button.tsx b/invokeai/frontend/webv2/src/platform/ui/Button.tsxindex 03a3efe168..964686636d 100644--- a/invokeai/frontend/webv2/src/platform/ui/Button.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Button.tsx@@ -118,7 +118,8 @@ export const IconButton = ({() =>unavailableReason ? (<Stack gap="0">- {tooltip ? <Text>{tooltip}</Text> : null}+ {/* A div, not a paragraph: a caller's tooltip may be a layout (a label beside its keycaps). */}+ {tooltip ? <Text as="div">{tooltip}</Text> : null}<Text color={tooltip ? 'fg.muted' : undefined}>{unavailableReason}</Text></Stack>) : (diff --git a/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsxindex 97a1693d10..62b839bb77 100644--- a/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Combobox.browser.test.tsx@@ -6,8 +6,10 @@ import { act, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';import { Combobox, type ComboboxOption } from './Combobox';+import { Field } from './Field';const options: ComboboxOption[] = [{ label: 'Euler Ancestral', value: 'euler_a' },@@ -45,6 +47,14 @@ const interact = (action: () => void): Promise<void> =>});});+/** Long enough for a dismiss-and-reopen to land, and for the theme's `fast` colour transitions to finish. */+const settleFrames = (): Promise<void> =>+ act(async () => {+ await new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 250);+ });+ });+const Harness = ({disabled = false,filterOptions = false,@@ -250,4 +260,136 @@ describe('Combobox', () => {await interact(() => input.click());expect(input.getAttribute('aria-expanded')).toBe('false');});++ describe('under an inside Field label', () => {+ const renderInField = async (field: { disabled?: boolean; error?: string; helpText?: string }) => {+ host = document.createElement('div');+ host.style.width = '240px';+ document.body.append(host);+ root = createRoot(host);+ const onChange = vi.fn();++ await interact(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <Field id="scheduler-field" label="Scheduler" labelPlacement="inside" {...field}>+ <Combobox options={options} value="euler_a" onValueChange={onChange} />+ </Field>+ </ChakraProvider>+ </I18nextProvider>+ );+ });++ const control = host.querySelector<HTMLElement>('[data-scope="combobox"][data-part="control"]')!;+ return {+ control,+ input: control.querySelector<HTMLInputElement>('input[role="combobox"]')!,+ label: control.querySelector<HTMLLabelElement>('label')!,+ onChange,+ };+ };++ it('names the input with the label at the start of its box and describes it with the help text', async () => {+ const { control, input, label } = await renderInField({ helpText: 'Sampler for each step' });++ expect(label.id).toBe('scheduler-field-label');+ expect(label.getBoundingClientRect().right).toBeLessThanOrEqual(input.getBoundingClientRect().left);+ expect(input.value).toBe('Euler Ancestral');+ expect(getComputedStyle(input).textAlign).toBe('end');+ // The box is the control, so the border runs around the label as well as the input.+ expect(getComputedStyle(control).borderTopWidth).toBe('1px');+ expect(getComputedStyle(input).borderTopWidth).toBe('0px');+ const scheduler = page.getByRole('combobox', { exact: true, name: 'Scheduler' });+ await expect.element(scheduler).toHaveAccessibleDescription('Sampler for each step');+ });++ it('opens from a click on the label, then filters and commits as usual', async () => {+ const { input, label, onChange } = await renderInField({});++ await userEvent.click(label);+ await expect.element(page.getByRole('combobox', { exact: true, name: 'Scheduler' })).toHaveFocus();+ expect(input.getAttribute('aria-expanded')).toBe('true');++ await setInputValue(input, 'dpm');+ expect(document.querySelectorAll('[role="option"]')).toHaveLength(1);+ await interact(() => document.querySelector<HTMLElement>('[role="option"]')?.click());+ expect(onChange).toHaveBeenLastCalledWith('dpmpp_2m');+ });++ it('keeps the list open and its filter when the label is clicked while open', async () => {+ const { input, label } = await renderInField({});++ await userEvent.click(label);+ await expect.poll(() => input.getAttribute('aria-expanded')).toBe('true');+ await userEvent.type(input, 'dpm');+ expect(document.querySelectorAll('[role="option"]')).toHaveLength(1);++ await userEvent.click(label);+ await settleFrames();+ expect(input.getAttribute('aria-expanded')).toBe('true');+ expect(input.value).toBe('dpm');+ expect(document.querySelectorAll('[role="option"]')).toHaveLength(1);+ await expect.element(page.getByRole('combobox', { exact: true, name: 'Scheduler' })).toHaveFocus();+ });++ it('tints only the box, not the input inside it, when an invalid field is hovered', async () => {+ const { control, input } = await renderInField({ error: 'Pick a scheduler' });+ const restingBg = getComputedStyle(control).backgroundColor;++ await userEvent.hover(input);+ await expect.poll(() => getComputedStyle(control).backgroundColor).not.toBe(restingBg);+ await settleFrames();+ expect(getComputedStyle(input).backgroundColor).toBe('rgba(0, 0, 0, 0)');+ });++ it('opens from a click anywhere in the box, its inset and the gap before the value included', async () => {+ const { control, input, label } = await renderInField({});+ const box = control.getBoundingClientRect();+ const labelBox = label.getBoundingClientRect();+ const close = () =>+ interact(() => input.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' })));++ // The strip inside the left border, before the label's text.+ await userEvent.click(control, { position: { x: 3, y: box.height / 2 } });+ await expect.poll(() => input.getAttribute('aria-expanded')).toBe('true');+ await close();+ await expect.poll(() => input.getAttribute('aria-expanded')).toBe('false');++ // The gap between the label's text and the value.+ const range = document.createRange();+ range.selectNodeContents(label);+ const textRight = range.getBoundingClientRect().right;+ expect(labelBox.right - textRight).toBeGreaterThan(4);+ await userEvent.click(control, { position: { x: (textRight + labelBox.right) / 2 - box.left, y: 3 } });+ await expect.poll(() => input.getAttribute('aria-expanded')).toBe('true');+ });++ it('describes the input with an invalid field error and marks the whole box invalid', async () => {+ const valid = await renderInField({});+ const validBorder = getComputedStyle(valid.control).borderTopColor;+ await interact(() => root?.unmount());+ host?.remove();++ const { control, input } = await renderInField({ error: 'Pick a scheduler' });++ expect(input.getAttribute('aria-invalid')).toBe('true');+ expect(input.getAttribute('aria-errormessage')).toBe('scheduler-field-error');+ await expect+ .element(page.getByRole('combobox', { exact: true, name: 'Scheduler' }))+ .toHaveAccessibleDescription('Pick a scheduler');+ expect(control.hasAttribute('data-invalid')).toBe(true);+ expect(getComputedStyle(control).borderTopColor).not.toBe(validBorder);+ });++ it('dims the whole box once when the field is disabled', async () => {+ const { control, input, label } = await renderInField({ disabled: true });++ expect(input.disabled).toBe(true);+ expect(getComputedStyle(control).opacity).toBe('0.5');+ expect(getComputedStyle(input).opacity).toBe('1');+ await interact(() => label.click());+ expect(input.getAttribute('aria-expanded')).toBe('false');+ });+ });});diff --git a/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx b/invokeai/frontend/webv2/src/platform/ui/Combobox.tsxindex 3c4f201232..989b14ea54 100644--- a/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Combobox.tsx@@ -5,19 +5,59 @@ import type {CollectionItem,} from '@chakra-ui/react';-import { Combobox as ChakraCombobox, createListCollection, Portal } from '@chakra-ui/react';+import { Combobox as ChakraCombobox, createListCollection, Portal, useFieldContext } from '@chakra-ui/react';+import { inputShellInteraction } from '@theme/recipes';import { CheckIcon, ChevronDownIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState, type UIEvent } from 'react';import { useTranslation } from 'react-i18next';+import { FieldInsideLabel, INSIDE_LABEL_INSET, useInsideFieldLabel } from './Field';import { Scrollable } from './Scrollable';+type PointerDownOutsideEvent = Parameters<NonNullable<ComboboxRootProps['onPointerDownOutside']>>[0];+const COMBOBOX_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;// Zag scrolls its content element by default; the Scrollable viewport is the scroll container here.const scrollHighlightedIntoView = ({ getElement }: { getElement: () => HTMLElement | null }) =>getElement()?.scrollIntoView({ block: 'nearest' });+/**+ * Under an inside label the control is the box, as InputShell is: it carries the input's border, focus, open, invalid+ * and disabled states around both the label and the input.+ */+const INSIDE_CONTROL_CSS = {+ ...inputShellInteraction,+ alignItems: 'center',+ borderColor: 'border',+ borderRadius: 'l2',+ borderWidth: '1px',+ display: 'flex',+ // The label carries the inset and the gap before the value as its own padding, full height, so a click anywhere left+ // of the input lands on the label and opens the input like the rest of the box.+ '& > label': {+ alignSelf: 'stretch',+ lineHeight: 'calc(var(--combobox-input-height) - 2px)',+ pe: '2',+ ps: INSIDE_LABEL_INSET,+ },+ _open: { borderColor: 'accent.solid' },+ // The box dims once; its input and chevron would otherwise dim again inside it.+ _disabled: { layerStyle: 'disabled', '& [data-part=input], & [data-part=indicator-group]': { opacity: 1 } },+} as const;++/** The selected label sits at the end of the box, after the inside label; typing filters as usual. */+const INSIDE_INPUT_CSS = {+ bg: 'transparent',+ borderWidth: '0',+ flex: '1',+ minW: '0',+ minH: 'calc(var(--combobox-input-height) - 2px)',+ ps: '0',+ textAlign: 'end',+ textOverflow: 'ellipsis',+} as const;+export interface ComboboxOption extends CollectionItem {disabled?: boolean;label: string;@@ -59,14 +99,24 @@ export const Combobox = ({options,onInputValueChange,onListScrollToBottom,+ onPointerDownOutside,searchPlaceholder,value,...rootProps}: ComboboxProps) => {const { t } = useTranslation();+ const field = useFieldContext();+ const insideLabel = useInsideFieldLabel();+ // Ark's input takes only the helper text from Field; an invalid field's error describes it too.+ const fieldInputProps = field?.getInputProps();+ const describedBy =+ [fieldInputProps?.['aria-describedby'], fieldInputProps?.['aria-errormessage'], inputProps?.['aria-describedby']]+ .filter(Boolean)+ .join(' ') || undefined;const [isOpen, setIsOpen] = useState(false);const [query, setQuery] = useState('');const lastNotifiedInputValue = useRef('');+ const controlRef = useRef<HTMLDivElement>(null);const selectedLabel = options.find((option) => option.value === value)?.label ?? '';const normalizedQuery = query.trim().toLocaleLowerCase();const selectedValues = useMemo(() => (value ? [value] : []), [value]);@@ -149,6 +199,18 @@ export const Combobox = ({},[onValueChange]);+ // Zag's dismiss layer spares only the input and the triggers. A press elsewhere in the box, such as on an inside+ // label, would close the list and clear the query, and the label's click would then reopen it unfiltered.+ const handlePointerDownOutside = useCallback(+ (event: PointerDownOutsideEvent) => {+ onPointerDownOutside?.(event);++ if (event.detail.target instanceof Node && controlRef.current?.contains(event.detail.target)) {+ event.preventDefault();+ }+ },+ [onPointerDownOutside]+ );const handleSelect = useCallback(({ itemValue }: { itemValue: string }) => {if (itemValue === value) {@@ -178,12 +240,17 @@ export const Combobox = ({value={selectedValues}onInputValueChange={handleInputValueChange}onOpenChange={handleOpenChange}+ onPointerDownOutside={handlePointerDownOutside}onSelect={onItemReselect ? handleSelect : undefined}onValueChange={handleValueChange}>- <ChakraCombobox.Control>+ <ChakraCombobox.Control ref={controlRef} css={insideLabel ? INSIDE_CONTROL_CSS : undefined}>+ {insideLabel && field ? <FieldInsideLabel htmlFor={field.ids.control} label={insideLabel} /> : null}<ChakraCombobox.Input+ css={insideLabel ? INSIDE_INPUT_CSS : undefined}{...inputProps}+ aria-describedby={describedBy}+ aria-errormessage={inputProps?.['aria-errormessage'] ?? fieldInputProps?.['aria-errormessage']}aria-label={inputProps?.['aria-label'] ?? ariaLabel}placeholder={searchPlaceholder ?? t('common.searchOptions')}/>diff --git a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsxindex 008593e393..b83a709724 100644--- a/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ConfirmDialog.tsx@@ -19,7 +19,6 @@ export const ConfirmDialog = ({onClose,onConfirm,onExitComplete,- placement = 'center',title,}: {body: ReactNode;@@ -44,11 +43,6 @@ export const ConfirmDialog = ({onConfirm: () => Promise<void> | void;/** After the close animation; hosts that retain the dialog's subject release it here. */onExitComplete?: () => void;- /**- * `top` anchors the dialog's top edge, for a body that grows after it opens (an answer still loading): a centered- * dialog would move up by half of every change.- */- placement?: 'center' | 'top';title: string;}) => {const { t } = useTranslation();@@ -131,7 +125,6 @@ export const ConfirmDialog = ({finalFocusEl={finalFocusEl}initialFocusEl={initialFocusEl ?? (text.isDestructive ? getInitialFocus : undefined)}open={isOpen}- placement={placement}role="alertdialog"size="sm"onExitComplete={handleExitComplete}diff --git a/invokeai/frontend/webv2/src/platform/ui/Dialog.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Dialog.browser.test.tsxindex e6cd4e3757..603f336902 100644--- a/invokeai/frontend/webv2/src/platform/ui/Dialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Dialog.browser.test.tsx@@ -1,11 +1,12 @@-import { ChakraProvider, Portal } from '@chakra-ui/react';+import { ChakraProvider, Menu, Portal } from '@chakra-ui/react';import { system } from '@theme/system';-import { act, StrictMode, useCallback, useState } from 'react';+import { act, StrictMode, useCallback, useState, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';-import { userEvent } from 'vitest/browser';+import { page, userEvent } from 'vitest/browser';import { Dialog } from './Dialog';+import { MenuContent, MenuItem } from './Menu';(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -19,58 +20,109 @@ afterEach(async () => {root = null;});-const nextFrame = () =>- new Promise<void>((resolve) => {- requestAnimationFrame(() => resolve());- });+/** As the app mounts it: under StrictMode, with a control outside every dialog. */+const render = async (content: ReactNode) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <button type="button">Outside</button>+ {content}+ </ChakraProvider>+ </StrictMode>+ )+ );+};++const dialogNamed = (title: string) => page.getByRole('dialog', { name: title });+const isOpen = (title: string) => dialogNamed(title).query()?.getAttribute('data-state') === 'open';++const SimpleDialog = ({+ children,+ modal,+ onFocusOutside,+ onOpenChange,+ open,+ title,+}: {+ children?: ReactNode;+ modal?: boolean;+ onFocusOutside?: () => void;+ onOpenChange: (details: Dialog.OpenChangeDetails) => void;+ open: boolean;+ title: string;+}) => (+ <Dialog.Root+ closeOnInteractOutside+ modal={modal}+ open={open}+ onFocusOutside={onFocusOutside}+ onOpenChange={onOpenChange}+ >+ <Portal>+ {modal === false ? null : <Dialog.Backdrop />}+ <Dialog.Positioner>+ <Dialog.Content>+ <Dialog.Header>+ <Dialog.Title>{title}</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>{children}</Dialog.Body>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+);++const getEditInitialFocus = () => document.querySelector<HTMLInputElement>('input[name="item-name"]');/**- * A dialog that opens a sibling dialog from inside itself, the way the workflow library opens its graph preview: the- * child mounts already open and unmounts once it has animated out.+ * A dialog that opens a second one over itself, mounted open and released after it animates out, as the layout preset+ * manager opens its edit dialog.*/-const ParentWithChild = () => {- const [isParentOpen, setIsParentOpen] = useState(true);- const [isChildMounted, setIsChildMounted] = useState(false);- const [isChildOpen, setIsChildOpen] = useState(false);- const handleParentOpenChange = useCallback((details: Dialog.OpenChangeDetails) => setIsParentOpen(details.open), []);- const openChild = useCallback(() => {- setIsChildMounted(true);- setIsChildOpen(true);- }, []);- const handleChildOpenChange = useCallback((details: Dialog.OpenChangeDetails) => setIsChildOpen(details.open), []);- const closeChild = useCallback(() => setIsChildOpen(false), []);- const unmountChild = useCallback(() => setIsChildMounted(false), []);+const StackedDialogs = () => {+ const [isManagerOpen, setIsManagerOpen] = useState(true);+ const [isEditMounted, setIsEditMounted] = useState(false);+ const [isEditOpen, setIsEditOpen] = useState(false);+ const openEdit = () => {+ setIsEditMounted(true);+ setIsEditOpen(true);+ };+ const changeManagerOpen = useCallback((details: Dialog.OpenChangeDetails) => setIsManagerOpen(details.open), []);+ const changeEditOpen = useCallback((details: Dialog.OpenChangeDetails) => setIsEditOpen(details.open), []);+ const releaseEdit = useCallback(() => setIsEditMounted(false), []);return (<>- <Dialog.Root open={isParentOpen} onOpenChange={handleParentOpenChange}>- <Portal>- <Dialog.Backdrop />- <Dialog.Positioner>- <Dialog.Content aria-label="Parent">- <Dialog.Body>- <input aria-label="Search" />- <button type="button" onClick={openChild}>- Open child- </button>- </Dialog.Body>- </Dialog.Content>- </Dialog.Positioner>- </Portal>- </Dialog.Root>- {isChildMounted ? (- <Dialog.Root open={isChildOpen} onExitComplete={unmountChild} onOpenChange={handleChildOpenChange}>+ <SimpleDialog open={isManagerOpen} title="Manager" onOpenChange={changeManagerOpen}>+ <button type="button" onClick={openEdit}>+ Edit+ </button>+ </SimpleDialog>+ {isEditMounted ? (+ <Dialog.Root+ initialFocusEl={getEditInitialFocus}+ lazyMount+ open={isEditOpen}+ unmountOnExit+ onExitComplete={releaseEdit}+ onOpenChange={changeEditOpen}+ ><Portal><Dialog.Backdrop /><Dialog.Positioner>- <Dialog.Content aria-label="Child">+ <Dialog.Content>+ <Dialog.Header>+ <Dialog.Title>Edit item</Dialog.Title>+ </Dialog.Header><Dialog.Body>- {/* The child's first tabbable, where a trap armed after focus entered the child would return it. */}- <button type="button">Graph</button>+ <input aria-label="Name" name="item-name" /></Dialog.Body><Dialog.Footer>- <button type="button" onClick={closeChild}>- Close+ <button type="button" onClick={() => setIsEditOpen(false)}>+ Cancel</button></Dialog.Footer></Dialog.Content>@@ -82,95 +134,122 @@ const ParentWithChild = () => {);};-/** Closes on any dismissal, so a focus-outside dismissal that got through would close it. */-const ModalWithFocusOutside = ({ onFocusOutside }: { onFocusOutside: () => void }) => {- const [isOpen, setIsOpen] = useState(true);- const handleOpenChange = useCallback((details: Dialog.OpenChangeDetails) => setIsOpen(details.open), []);-+/** A modal or non-modal dialog the test opens and observes. */+const Observed = ({+ children,+ modal,+ onFocusOutside,+}: {+ children?: ReactNode;+ modal?: boolean;+ onFocusOutside?: () => void;+}) => {+ const [open, setOpen] = useState(true);+ const changeOpen = useCallback((details: Dialog.OpenChangeDetails) => setOpen(details.open), []);return (- <Dialog.Root open={isOpen} onFocusOutside={onFocusOutside} onOpenChange={handleOpenChange}>- <Portal>- <Dialog.Positioner>- <Dialog.Content aria-label="Modal">- <button type="button">Inside</button>- </Dialog.Content>- </Dialog.Positioner>- </Portal>- </Dialog.Root>+ <SimpleDialog modal={modal} open={open} title="Observed" onFocusOutside={onFocusOutside} onOpenChange={changeOpen}>+ {children ?? <button type="button">Inside</button>}+ </SimpleDialog>);};-const getDialog = (label: string) => document.querySelector<HTMLElement>(`[role="dialog"][aria-label="${label}"]`);-const getButton = (dialog: HTMLElement, text: string) =>- [...dialog.querySelectorAll('button')].find((button) => button.textContent === text)!;--const renderParent = async () => {- host = document.createElement('div');- document.body.append(host);- root = createRoot(host);- await act(() =>- root!.render(- <StrictMode>- <ChakraProvider value={system}>- <ParentWithChild />- </ChakraProvider>- </StrictMode>- )+/** The dialog's Escape and outside handling is armed in the frame after it opens. */+const settled = async (title: string) => {+ await expect.poll(() => isOpen(title)).toBe(true);+ await act(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ }));- await expect.poll(() => getDialog('Parent')?.getAttribute('data-state')).toBe('open');-- return getDialog('Parent')!;};describe('Dialog', () => {- it('stays open when a dialog it opened closes and focus returns to it', async () => {- const parent = await renderParent();-- await act(() => userEvent.click(getButton(parent, 'Open child')));- await expect.poll(() => getDialog('Child')?.getAttribute('data-state')).toBe('open');- await act(() => userEvent.click(getButton(getDialog('Child')!, 'Close')));- await expect.poll(() => getDialog('Child')).toBeNull();- await expect.poll(() => document.activeElement).toBe(getButton(parent, 'Open child'));- // Let the restored focus's outside handler run before checking that it did not dismiss the parent.- await act(nextFrame);-- expect(parent.isConnected).toBe(true);- expect(parent.getAttribute('data-state')).toBe('open');- expect(document.activeElement).toBe(getButton(parent, 'Open child'));+ it.each([+ ['Cancel', () => userEvent.click(page.getByRole('button', { name: 'Cancel' }))],+ ['Escape', () => userEvent.keyboard('{Escape}')],+ ])('closes only a dialog stacked over another on %s, leaving focus in the one below', async (_way, dismiss) => {+ await render(<StackedDialogs />);+ await settled('Manager');++ for (let attempt = 0; attempt < 2; attempt += 1) {+ await act(() => userEvent.click(page.getByRole('button', { name: 'Edit' })));+ await settled('Edit item');+ await expect.poll(() => dialogNamed('Edit item').element().contains(document.activeElement)).toBe(true);++ await act(dismiss);++ await expect.poll(() => dialogNamed('Edit item').query()).toBeNull();+ expect(isOpen('Manager')).toBe(true);+ await expect.poll(() => document.activeElement).toBe(page.getByRole('button', { name: 'Edit' }).element());+ }});- it('still closes on a pointer press outside it', async () => {- const parent = await renderParent();- // The outside handling is set up in the frame after the dialog opens.- await act(nextFrame);+ it('keeps a modal open when focus is moved outside it, still telling its own handler', async () => {+ const onFocusOutside = vi.fn();+ await render(<Observed onFocusOutside={onFocusOutside} />);+ await settled('Observed');- await act(() => userEvent.click(document.body, { position: { x: 4, y: 4 } }));+ await act(() => host!.querySelector<HTMLButtonElement>('button')!.focus());- await expect.poll(() => parent.getAttribute('data-state')).toBe('closed');+ await expect.poll(() => onFocusOutside).toHaveBeenCalled();+ // Two frames on, so a dismissal the handler let through has re-rendered the dialog closed.+ await settled('Observed');+ expect(isOpen('Observed')).toBe(true);});- it('still tells the caller when focus lands outside a modal dialog, which stays open', async () => {- const onFocusOutside = vi.fn();- host = document.createElement('div');- document.body.append(host);- root = createRoot(host);- await act(() =>- root!.render(- <ChakraProvider value={system}>- <button type="button">Outside</button>- <ModalWithFocusOutside onFocusOutside={onFocusOutside} />- </ChakraProvider>- )+ it.each([+ [+ 'a press outside',+ () => userEvent.click(document.querySelector('[data-part="positioner"]')!, { position: { x: 4, y: 4 } }),+ ],+ ['Escape', () => userEvent.keyboard('{Escape}')],+ ])('dismisses a modal on %s', async (_way, dismiss) => {+ await render(<Observed />);+ await settled('Observed');++ await act(dismiss);++ await expect.poll(() => isOpen('Observed')).toBe(false);+ });++ it('dismisses a non-modal dialog when focus moves outside it, as before', async () => {+ await render(<Observed modal={false} />);+ await settled('Observed');++ await act(() => host!.querySelector<HTMLButtonElement>('button')!.focus());++ await expect.poll(() => isOpen('Observed')).toBe(false);+ });++ it('stays open while a menu opened inside it is used', async () => {+ const onSelect = vi.fn();+ await render(+ <Observed>+ <Menu.Root>+ <Menu.Trigger>Actions</Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent>+ <MenuItem value="rename" onSelect={onSelect}>+ Rename+ </MenuItem>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </Observed>);- const dialog = getDialog('Modal')!;- await expect.poll(() => dialog.getAttribute('data-state')).toBe('open');- // The outside handling is set up in the frame after the dialog opens.- await act(nextFrame);+ await settled('Observed');- await act(() => host!.querySelector('button')!.focus());+ await userEvent.click(page.getByRole('button', { name: 'Actions' }));+ // The menu's content is portalled outside the dialog's, yet nested in its layer.+ await expect.poll(() => document.querySelector('[role="menu"]')?.contains(document.activeElement)).toBe(true);+ await userEvent.click(page.getByRole('menuitem', { name: 'Rename' }));- await expect.poll(() => onFocusOutside.mock.calls.length).toBe(1);- await act(nextFrame);- expect(dialog.getAttribute('data-state')).toBe('open');+ expect(onSelect).toHaveBeenCalledOnce();+ await expect.poll(() => document.querySelector('[role="menu"]')?.checkVisibility() ?? false).toBe(false);+ expect(isOpen('Observed')).toBe(true);+ await expect.element(page.getByRole('button', { name: 'Actions' })).toHaveFocus();});});diff --git a/invokeai/frontend/webv2/src/platform/ui/DropZone.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/DropZone.browser.test.tsxnew file mode 100644index 0000000000..42e0794302--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/DropZone.browser.test.tsx@@ -0,0 +1,62 @@+import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import { DropZone } from './DropZone';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++const CALLER_CSS = { outlineStyle: 'solid', outlineWidth: '3px' } as const;++describe('DropZone', () => {+ it('stays in its hover look while the trigger filling it is pointed, keeping a caller css', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <DropZone css={CALLER_CSS} data-testid="zone" h="16" w="16">+ <button style={{ height: '100%', width: '100%' }} type="button">+ Choose+ </button>+ </DropZone>+ </ChakraProvider>+ )+ );+ const zone = host.querySelector<HTMLElement>('[data-testid="zone"]')!;+ const trigger = zone.querySelector('button')!;+ // Read once the zone's border transition has finished.+ const border = async () => {+ await vi.waitFor(() => expect(zone.getAnimations()).toHaveLength(0));+ return getComputedStyle(zone).borderColor;+ };+ const resting = await border();++ await userEvent.hover(zone);+ const hovered = await border();+ expect(hovered).not.toBe(resting);+ await userEvent.unhover(zone);+ expect(await border()).toBe(resting);++ // The gallery picker marks its trigger `data-hover` while it is open.+ trigger.setAttribute('data-hover', '');+ expect(await border()).toBe(hovered);+ trigger.removeAttribute('data-hover');+ expect(await border()).toBe(resting);++ expect(getComputedStyle(zone).outlineWidth).toBe('3px');+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx b/invokeai/frontend/webv2/src/platform/ui/DropZone.tsxindex f8d767270c..09d510e933 100644--- a/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/DropZone.tsx@@ -29,6 +29,7 @@ export const DropZone = ({isOver,variant = 'inline',_hover,+ css,...boxProps}: DropZoneProps) => {// Merge hover styles so they cannot override drag-over fills; overlays use isOver instead of pointer hover.@@ -41,6 +42,9 @@ export const DropZone = ({}),[_hover, isDisabled, isInvalid, isOver, variant]);+ // A trigger filling the zone keeps the zone pointed while the trigger is: the gallery picker marks its trigger+ // `data-hover` while it is open. A caller's own `css` adds to this rather than replacing it.+ const zoneCss = useMemo(() => [{ '&:has(> [data-hover])': hoverProps }, css], [css, hoverProps]);return (<Box@@ -54,6 +58,7 @@ export const DropZone = ({rounded="md"transition={DROP_ZONE_TRANSITION}_hover={hoverProps}+ css={zoneCss}{...boxProps}>{children}diff --git a/invokeai/frontend/webv2/src/platform/ui/Field.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Field.browser.test.tsxindex 5718bd3396..e5d5867fb4 100644--- a/invokeai/frontend/webv2/src/platform/ui/Field.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Field.browser.test.tsx@@ -1,24 +1,51 @@-import { ChakraProvider, Input } from '@chakra-ui/react';+import { ChakraProvider, createListCollection, Input } from '@chakra-ui/react';import { system } from '@theme/system';import { createInstance } from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';-import { Field } from './Field';+import { Combobox } from './Combobox';+import { Field, useFieldLabelId } from './Field';import { FeatureHintsProvider } from './hints';-import { openHintCard } from './hints/featureHint.testing';+import { getHintCard, openHintCard } from './hints/featureHint.testing';+import { ScrubberField } from './ScrubberField';+import { Select } from './Select';const i18n = createInstance();void i18n.use(initReactI18next).init({fallbackLng: 'en',initAsync: false,lng: 'en',- resources: { en: { translation: { hints: { steps: { heading: 'Steps', paragraphs: ['How many steps.'] } } } } },+ resources: {+ en: {+ translation: {+ common: { dontShowMeThese: "Don't show me these", learnMore: 'Learn more' },+ hints: {+ scheduler: { heading: 'Scheduler', paragraphs: ['How noise is removed.'] },+ steps: { heading: 'Steps', paragraphs: ['How many steps.'] },+ },+ },+ },+ },});const HINTS_ENABLED = { enabled: true, onDisable: null };+const DISMISSABLE_HINTS = { enabled: true, onDisable: vi.fn() };+const STEP_COLLECTION = createListCollection({ items: [{ label: '30', value: '30' }] });+const STEP_VALUE = ['30'];+const SCHEDULER_OPTIONS = [{ label: 'Euler', value: 'euler' }];+const noop = () => undefined;+const LabelIdProbe = () => <output>{useFieldLabelId() ?? 'none'}</output>;++/** Where a label's text begins, whatever padding its element carries. */+const textLeft = (element: Element): number => {+ const range = document.createRange();+ range.selectNodeContents(element);+ return range.getBoundingClientRect().left;+};let host: HTMLDivElement | null = null;let root: Root | null = null;@@ -98,3 +125,193 @@ describe('Field with a hint', () => {expect(card.left).toBeGreaterThanOrEqual(control.right);});});++describe('Field with its label inside the control', () => {+ it('keeps the hint on the label text inside the trigger, without replacing the id that names the trigger', async () => {+ host = document.createElement('div');+ host.style.cssText = 'width:200px;margin:120px 0 0 8px';+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <FeatureHintsProvider adapter={HINTS_ENABLED}>+ <Field hint="steps" id="steps-field" label="Steps" labelPlacement="inside">+ <Select collection={STEP_COLLECTION} value={STEP_VALUE} />+ </Field>+ </FeatureHintsProvider>+ </I18nextProvider>+ </ChakraProvider>+ );+ });++ const trigger = host.querySelector<HTMLElement>('[data-scope="select"][data-part="trigger"]')!;+ const hintTarget = trigger.querySelector<HTMLElement>('[data-scope="hover-card"][data-part="trigger"]')!;+ expect(trigger.getAttribute('aria-labelledby')).toBe('steps-field-label');+ expect(hintTarget.textContent).toBe('Steps');+ expect(hintTarget.parentElement?.id).toBe('steps-field-label');+ const card = await openHintCard(hintTarget);+ expect(card.left).toBeGreaterThanOrEqual(trigger.getBoundingClientRect().right);+ });++ /**+ * The card portals out of the control but stays inside it in the React tree, where its events would bubble to the+ * trigger: a press on the card opened the dropdown, and the trigger's keydown took Enter from the card's actions.+ */+ it.each(['select', 'combobox'] as const)(+ 'keeps the %s closed while the hint card inside its label is used, by pointer or keyboard',+ async (scope) => {+ const { onDisable } = DISMISSABLE_HINTS;+ onDisable.mockClear();+ host = document.createElement('div');+ host.style.cssText = 'width:200px;margin:120px 0 0 8px';+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <FeatureHintsProvider adapter={DISMISSABLE_HINTS}>+ <Field hint="scheduler" id="scheduler-field" label="Scheduler" labelPlacement="inside">+ {scope === 'select' ? (+ <Select collection={STEP_COLLECTION} value={STEP_VALUE} />+ ) : (+ <Combobox options={SCHEDULER_OPTIONS} value="euler" onValueChange={noop} />+ )}+ </Field>+ </FeatureHintsProvider>+ </I18nextProvider>+ </ChakraProvider>+ );+ });+ const control = host.querySelector(`[data-scope="${scope}"][aria-expanded]`)!;+ await openHintCard(host.querySelector('[data-scope="hover-card"][data-part="trigger"]')!);+ const card = getHintCard()!;+ const dismiss = [...card.querySelectorAll('button')].find(+ (button) => button.textContent === "Don't show me these"+ )!;+ const learnMore = card.querySelector<HTMLAnchorElement>('a')!;+ // Count the link's activations without opening its page.+ const followed = vi.fn((event: MouseEvent) => event.preventDefault());+ learnMore.addEventListener('click', followed);+ // The dropdown can open and close again within one press, so record every change rather than the end state.+ const expandedStates: (string | null)[] = [];+ const observer = new MutationObserver(() => expandedStates.push(control.getAttribute('aria-expanded')));+ observer.observe(control, { attributeFilter: ['aria-expanded'] });++ await userEvent.click(dismiss);+ expect(onDisable).toHaveBeenCalledTimes(1);++ await act(() => dismiss.focus());+ await userEvent.keyboard('{Enter}');+ expect(onDisable).toHaveBeenCalledTimes(2);++ await act(() => learnMore.focus());+ await userEvent.keyboard('{Enter}');+ expect(followed).toHaveBeenCalledTimes(1);++ await new Promise((resolve) => {+ globalThis.setTimeout(resolve, 100);+ });+ observer.disconnect();+ expect(expandedStates).toEqual([]);+ }+ );++ it('keeps a ScrubberField at its value when a word in its hint card is double-clicked', async () => {+ const onChange = vi.fn();+ host = document.createElement('div');+ host.style.cssText = 'width:200px;margin:120px 0 0 8px';+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <FeatureHintsProvider adapter={HINTS_ENABLED}>+ <ScrubberField+ defaultValue={30}+ hint="steps"+ label="Steps"+ max={100}+ min={1}+ step={1}+ value={40}+ onChange={onChange}+ />+ </FeatureHintsProvider>+ </I18nextProvider>+ </ChakraProvider>+ );+ });+ await openHintCard(host.querySelector('[data-scope="hover-card"][data-part="trigger"]')!);+ const heading = [...getHintCard()!.querySelectorAll('p')].find((paragraph) => paragraph.textContent === 'Steps')!;++ await userEvent.dblClick(heading);++ expect(onChange).not.toHaveBeenCalled();+ });++ it('starts its label where a stacked ScrubberField starts its own, in the same type', async () => {+ host = document.createElement('div');+ host.style.width = '240px';+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <ScrubberField label="Steps" max={100} min={1} step={1} value={30} onChange={noop} />+ <Field id="preset-field" label="Preset" labelPlacement="inside">+ <Select collection={STEP_COLLECTION} value={STEP_VALUE} />+ </Field>+ <Field id="scheduler-field" label="Scheduler" labelPlacement="inside">+ <Combobox options={SCHEDULER_OPTIONS} value="euler" onValueChange={noop} />+ </Field>+ </I18nextProvider>+ </ChakraProvider>+ );+ });++ const scrubberLabel = host.querySelector<HTMLElement>('[data-part="label"]')!;+ const insideLabels = [+ document.getElementById('preset-field-label')!,+ document.getElementById('scheduler-field-label')!,+ ];+ const scrubberStyle = getComputedStyle(scrubberLabel);+ for (const label of insideLabels) {+ expect(textLeft(label)).toBeCloseTo(textLeft(scrubberLabel), 0);+ const style = getComputedStyle(label);+ expect([style.fontSize, style.fontWeight, style.color, style.letterSpacing]).toEqual([+ scrubberStyle.fontSize,+ scrubberStyle.fontWeight,+ scrubberStyle.color,+ scrubberStyle.letterSpacing,+ ]);+ }+ });++ it('reports no rendered label id to a child that does not show the inside label', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <Field id="probe-field" label="Probe" labelPlacement="inside">+ <LabelIdProbe />+ </Field>+ <Field id="outside-field" label="Outside">+ <LabelIdProbe />+ </Field>+ </ChakraProvider>+ );+ });++ expect([...host.querySelectorAll('output')].map((output) => output.textContent)).toEqual([+ 'none',+ 'outside-field-label',+ ]);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Field.tsx b/invokeai/frontend/webv2/src/platform/ui/Field.tsxindex 2377cf1414..438c76201c 100644--- a/invokeai/frontend/webv2/src/platform/ui/Field.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Field.tsx@@ -26,7 +26,8 @@ const RenderedLabelIdProvider = ({ children }: { children: ReactNode }) => {/*** The id of the label naming the nearest field's control, or null when that field renders none. For custom- * controls that reference the label themselves; Chakra controls read Field context directly.+ * controls that reference the label themselves; Chakra controls read Field context directly. An inside Field renders+ * no label of its own: a control that shows it takes the id from `useInsideFieldLabel` along with the label.*/export const useFieldLabelId = (): string | null => {const field = useFieldContext();@@ -35,6 +36,85 @@ export const useFieldLabelId = (): string | null => {return field && field.ids.label === labelId ? labelId : null;};+/** Wraps label text only: the hint trigger overwrites its child's ID and would break aria-labelledby on the label. */+const renderLabelText = (label: string, hint: FeatureHintId | undefined): ReactNode =>+ hint ? (+ <FeatureHint hint={hint}>+ <chakra.span>{label}</chakra.span>+ </FeatureHint>+ ) : (+ label+ );++/** What a `labelPlacement="inside"` Field hands its control. */+export interface InsideFieldLabel {+ /** The Field's label id: the control names itself by the element `FieldInsideLabel` renders with it. */+ id: string;+ text: string;+ hint?: FeatureHintId;+}++const InsideLabelContext = createContext<InsideFieldLabel | null>(null);++const InsideLabelProvider = ({+ children,+ hint,+ text,+}: {+ children: ReactNode;+ hint: FeatureHintId | undefined;+ text: string;+}) => {+ const labelId = useFieldContext()?.ids.label;+ const value = useMemo(() => (labelId ? { hint, id: labelId, text } : null), [hint, labelId, text]);++ return <InsideLabelContext value={value}>{children}</InsideLabelContext>;+};++/**+ * The label the nearest field asks its control to show at the start of the control's own box; null when that field+ * shows its label outside, or is a raw `Field.Root` nested in an inside Field.+ */+export const useInsideFieldLabel = (): InsideFieldLabel | null => {+ const field = useFieldContext();+ const label = useContext(InsideLabelContext);++ return field && label && field.ids.label === label.id ? label : null;+};++/** Inset from a control's inner edge, as ScrubberField's label is, so stacked inside labels start at one x. */+export const INSIDE_LABEL_INSET = '3';++const INSIDE_LABEL_CSS = {+ // The field label's type, as ScrubberField's inside label uses: stacked scrubbers and selects read as one set.+ ...fieldLabelRecipe.base,+ flexShrink: 0,+ // The value gives way first; only a label longer than half the box truncates.+ maxW: '50%',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+} as const;++/**+ * The inside label at the start of a control's box. In a trigger button it is a span the trigger's aria-labelledby+ * points at (a `<label>` may not sit in a button); beside an input, `htmlFor` makes it a native label, so a click on+ * it focuses and opens the input like the rest of the box.+ */+export const FieldInsideLabel = ({ htmlFor, label }: { htmlFor?: string; label: InsideFieldLabel }) => {+ const text = renderLabelText(label.text, label.hint);++ return htmlFor ? (+ <chakra.label css={INSIDE_LABEL_CSS} htmlFor={htmlFor} id={label.id}>+ {text}+ </chakra.label>+ ) : (+ <chakra.span css={INSIDE_LABEL_CSS} id={label.id}>+ {text}+ </chakra.span>+ );+};+export const FieldLabel = ({ children }: { children: ReactNode }) => {const recipe = useRecipe({ recipe: fieldLabelRecipe });@@ -45,12 +125,10 @@ export const FieldLabel = ({ children }: { children: ReactNode }) => {);};-export interface FieldProps extends Omit<StackProps, 'disabled' | 'id' | 'readOnly' | 'required' | 'title'> {+interface FieldBaseProps extends Omit<StackProps, 'disabled' | 'id' | 'readOnly' | 'required' | 'title'> {id?: string;label: string;- labelEnd?: ReactNode;disabled?: boolean;- orientation?: 'horizontal' | 'vertical';invalid?: boolean;readOnly?: boolean;required?: boolean;@@ -62,6 +140,26 @@ export interface FieldProps extends Omit<StackProps, 'disabled' | 'id' | 'readOnchildren: ReactNode;}+export type FieldProps = FieldBaseProps &+ (+ | {+ /** `outside` (default) stacks the label above the control, or beside it when horizontal. */+ labelPlacement?: 'outside';+ labelEnd?: ReactNode;+ orientation?: 'horizontal' | 'vertical';+ }+ | {+ /**+ * `inside` hands the label to the control, which shows it at the start of its own box: one compact row for+ * dense panels. Help and error text stay below the box. Only Select, Combobox and ModelSelect render it; any+ * other child (Input, NumberInput, ScrubberField) is left without a label or an accessible name.+ */+ labelPlacement: 'inside';+ labelEnd?: never;+ orientation?: never;+ }+ );+/** A labelled form field: an uppercase label stacked above its control, with an optional help/error line below. */export const Field = ({children,@@ -73,6 +171,7 @@ export const Field = ({invalid,label,labelEnd,+ labelPlacement = 'outside',orientation = 'vertical',readOnly,required,@@ -93,19 +192,6 @@ export const Field = ({: undefined,[id]);- // Wrap label text only: the hint trigger overwrites its child's ID and would break aria-labelledby on the label- // itself.- const labelContent = (- <ChakraField.Label css={recipe()}>- {hint ? (- <FeatureHint hint={hint}>- <chakra.span>{label}</chakra.span>- </FeatureHint>- ) : (- label- )}- </ChakraField.Label>- );const message = error ? (<ChakraField.ErrorText color="fg.error" fontSize="xs" role="alert">{error}@@ -116,6 +202,30 @@ export const Field = ({</ChakraField.HelperText>) : null;+ if (labelPlacement === 'inside') {+ return (+ <ChakraField.Root+ asChild+ disabled={disabled}+ id={id}+ ids={ids}+ invalid={isInvalid}+ readOnly={readOnly}+ required={required}+ unstyled+ >+ <Stack flex="1" gap="1" minW="0" {...hintFieldProps} {...rest}>+ <InsideLabelProvider hint={hint} text={label}>+ {children}+ </InsideLabelProvider>+ {message}+ </Stack>+ </ChakraField.Root>+ );+ }++ const labelContent = <ChakraField.Label css={recipe()}>{renderLabelText(label, hint)}</ChakraField.Label>;+if (!isHorizontal) {return (<ChakraField.Rootdiff --git a/invokeai/frontend/webv2/src/platform/ui/ManagerLayout.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ManagerLayout.browser.test.tsxindex 1ec5dac31e..4e886f7d4a 100644--- a/invokeai/frontend/webv2/src/platform/ui/ManagerLayout.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ManagerLayout.browser.test.tsx@@ -15,10 +15,22 @@ import { ConfirmDialog } from './ConfirmDialog';import { List } from './list/List';import { ListItem } from './list/ListItem';import { listRowsFromItems } from './list/listRows';-import { ManagerColumn, ManagerDetailHeader, ManagerLayout, ManagerSearchField } from './ManagerLayout';+import {+ ManagerColumn,+ ManagerDetailHeader,+ ManagerFilterMenu,+ ManagerFilterResetItem,+ ManagerLayout,+ ManagerSearchField,+} from './ManagerLayout';import { MenuContent } from './Menu';-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, values?: { count?: number }) =>+ values?.count === undefined ? key : `${String(values.count)} active`,+ }),+}));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -470,4 +482,66 @@ describe('ManagerLayout', () => {expect(focused()).toBe(toggle().element());});});++ it('names the icon-only filter trigger in a tooltip that leaves its menu working', async () => {+ await render(+ WIDE_PX,+ <ManagerFilterMenu activeCount={1} label="Filter items">+ <Portal>+ <Menu.Positioner>+ <MenuContent>+ <ManagerFilterResetItem activeCount={1} onReset={() => undefined} />+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </ManagerFilterMenu>+ );+ const trigger = page.getByRole('button', { name: 'Filter items, 1 active' });++ await trigger.hover();+ await expect.element(page.getByRole('tooltip')).toHaveTextContent('Filter items, 1 active');+ await trigger.click();++ // One trigger id serves both: the menu anchors to the button the tooltip describes.+ const menu = page.getByRole('menu');+ await expect.element(menu).toBeVisible();+ await expect.element(trigger).toHaveAttribute('aria-expanded', 'true');+ await expect.element(trigger).toHaveAttribute('aria-controls', menu.element().id);+ await expect.element(menu).toHaveAttribute('aria-labelledby', trigger.element().id);+ expect(await auditAccessibility(host)).toEqual([]);+ });++ it('badges the filter trigger with the active filter count, which its reset item clears', async () => {+ const FilterHarness = () => {+ const [count, setCount] = useState(2);++ return (+ <ManagerFilterMenu activeCount={count} closeOnSelect={false} label="Filter items">+ <Portal>+ <Menu.Positioner>+ <MenuContent>+ <ManagerFilterResetItem activeCount={count} onReset={() => setCount(0)} />+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </ManagerFilterMenu>+ );+ };+ await render(WIDE_PX, <FilterHarness />);+ const trigger = page.getByRole('button', { name: /^Filter items/ });++ // The visible badge digits are part of the name, which axe's label-in-name rule checks.+ await expect.element(trigger).toHaveAccessibleName('Filter items, 2 active');+ expect((trigger.element() as HTMLElement).innerText).toBe('2');+ expect(await auditAccessibility(host)).toEqual([]);++ await trigger.click();+ const reset = page.getByRole('menuitem', { name: 'common.resetFilters' });+ await reset.click();++ await expect.element(trigger).toHaveAccessibleName('Filter items');+ expect((trigger.element() as HTMLElement).innerText).toBe('');+ // The menu stays open, and the reset has nothing left to clear.+ await expect.element(reset).toHaveAttribute('aria-disabled', 'true');+ });});diff --git a/invokeai/frontend/webv2/src/platform/ui/ManagerLayout.tsx b/invokeai/frontend/webv2/src/platform/ui/ManagerLayout.tsxindex 2978a3b93e..4e5d89ea75 100644--- a/invokeai/frontend/webv2/src/platform/ui/ManagerLayout.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ManagerLayout.tsx@@ -1,14 +1,16 @@import type { ChangeEvent, FocusEvent, ReactNode } from 'react';-import { Box, Flex, HStack, Icon, Input, InputGroup, Kbd, Text, type SystemStyleObject } from '@chakra-ui/react';+import { Box, Flex, HStack, Icon, Input, InputGroup, Kbd, Menu, Text, type SystemStyleObject } from '@chakra-ui/react';import { focusSearchOnSlash } from '@platform/browser/searchShortcut';import { useMountEffect } from '@platform/react/useMountEffect';-import { ArrowLeftIcon, PlusIcon, SearchIcon, XIcon } from 'lucide-react';+import { ArrowLeftIcon, PlusIcon, RotateCcwIcon, SearchIcon, SlidersHorizontalIcon, XIcon } from 'lucide-react';import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';import { Button, IconButton } from './Button';+import { MenuActionItem } from './Menu';import { isModalPresent } from './modalPresence';-import { Tooltip } from './Tooltip';+import { Tooltip, useTooltipTriggerIds } from './Tooltip';/*** The list/detail shell shared by the Launchpad managers (models, nodes, fonts, preferences). Side by side when@@ -430,6 +432,95 @@ export const ManagerSearchField = ({);};+/**+ * Trimmed to the digits' cap height and baseline, the count's box is its ink, so the badge's flex centring centres the+ * digits; untrimmed, the font's descender room lifts them off centre.+ */+const FILTER_COUNT_TEXT: SystemStyleObject = { textBox: 'trim-both cap alphabetic' };++/**+ * The manager toolbar's filter menu: an icon-only trigger, named and tooltipped by `label`, opening `children` (the+ * menu's portalled positioner and content). It owns the menu root so the root and the trigger's tooltip share one+ * trigger id. A count badge on the trigger's corner says how many filters narrow the list, so filtering shows with the+ * menu closed; sort order is not a filter and is not counted. The name ends with the count, so the visible digits stay+ * part of it (label in name; a parenthetical would not count).+ */+export const ManagerFilterMenu = ({+ activeCount,+ children,+ label,+ ...rootProps+}: Omit<Menu.RootProps, 'children' | 'ids'> & {+ activeCount: number;+ children: ReactNode;+ label: string;+}) => {+ const { t } = useTranslation();+ const ids = useTooltipTriggerIds();+ const isFiltered = activeCount > 0;+ const name = isFiltered ? `${label}, ${t('common.activeFilterCount', { count: activeCount })}` : label;++ return (+ <Menu.Root ids={ids} {...rootProps}>+ <Tooltip content={name} ids={ids}>+ <Menu.Trigger asChild>+ <IconButton aria-label={name} color="fg.muted" flexShrink={0} variant="outline">+ <Icon as={SlidersHorizontalIcon} boxSize="4" />+ {isFiltered ? (+ <Box+ aria-hidden+ alignItems="center"+ bg="accent.solid"+ color="accent.contrast"+ display="flex"+ fontSize="xs"+ fontWeight="semibold"+ h="4"+ justifyContent="center"+ minW="4"+ outline="2px solid"+ outlineColor="bg"+ pointerEvents="none"+ position="absolute"+ px="1"+ right="-2.5"+ rounded="full"+ top="-2.5"+ >+ <Box as="span" css={FILTER_COUNT_TEXT}>+ {activeCount}+ </Box>+ </Box>+ ) : null}+ </IconButton>+ </Menu.Trigger>+ </Tooltip>+ {children}+ </Menu.Root>+ );+};++/**+ * The last row of a manager's filter menu, under a separator: clears the filters `ManagerFilterMenu` counts and+ * leaves sort order and search alone. Disabled while none is active.+ */+export const ManagerFilterResetItem = ({ activeCount, onReset }: { activeCount: number; onReset: () => void }) => {+ const { t } = useTranslation();++ return (+ <>+ <Menu.Separator />+ <MenuActionItem+ disabled={activeCount === 0}+ icon={RotateCcwIcon}+ label={t('common.resetFilters')}+ value="reset-filters"+ onSelect={onReset}+ />+ </>+ );+};+export interface ManagerAddAction {/** The Add tab's label, e.g. "Add Models". */label: string;diff --git a/invokeai/frontend/webv2/src/platform/ui/Menu.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Menu.browser.test.tsxindex 58767c9fa9..1d7e04c1c6 100644--- a/invokeai/frontend/webv2/src/platform/ui/Menu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Menu.browser.test.tsx@@ -1,12 +1,14 @@-import { ChakraProvider, Menu } from '@chakra-ui/react';+import { Box, ChakraProvider, Icon, Menu, Portal } from '@chakra-ui/react';+import { applyThemeToRoot } from '@theme/applyTheme';import { system } from '@theme/system';import { CopyIcon } from 'lucide-react';-import { act } from 'react';+import { Activity, act, useCallback, useMemo, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';-import { page, userEvent } from 'vitest/browser';+import { page, server, userEvent } from 'vitest/browser';-import { MenuActionItem, MenuHeadingGroup, MenuIconItem, MenuItem } from './Menu';+import { findArrowJointSeams } from './arrowJoint.testing';+import { MenuActionItem, MenuContent, MenuHeadingGroup, MenuIconItem, MenuItem, useContextMenu } from './Menu';let host: HTMLDivElement | null = null;let root: Root | null = null;@@ -189,3 +191,619 @@ describe('menu heading groups', () => {).toEqual(['Save changes', 'Other']);});});++describe('menu item icons', () => {+ it("sit back from the label by default, keep a danger item's tone, and yield to an explicit color", async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <Menu.Root open>+ <Menu.Positioner>+ <MenuContent>+ <Menu.Item value="plain">+ <CopyIcon data-testid="plain-icon" />+ Copy+ </Menu.Item>+ <Menu.Item data-danger="" value="danger">+ <CopyIcon data-testid="danger-icon" />+ Delete+ </Menu.Item>+ <Menu.Item value="explicit">+ <Icon as={CopyIcon} color="fg" data-testid="explicit-icon" />+ Checked+ </Menu.Item>+ {/* Token references resolved in the same color context as the items. */}+ <Box color="fg.subtle" data-testid="subtle-reference" />+ <Box color="fg" data-testid="fg-reference" />+ </MenuContent>+ </Menu.Positioner>+ </Menu.Root>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+ await vi.waitFor(() => expect(item('plain')).toBeVisible());++ const color = (testId: string) => getComputedStyle(document.querySelector(`[data-testid="${testId}"]`)!).color;+ const subtle = color('subtle-reference');+ const fg = color('fg-reference');+ const danger = getComputedStyle(item('danger')).color;+ // Three distinct colors, so each expectation below tells the rules apart.+ expect(new Set([subtle, fg, danger]).size).toBe(3);++ expect(color('plain-icon')).toBe(subtle);+ expect(color('danger-icon')).toBe(danger);+ expect(color('explicit-icon')).toBe(fg);+ });+});++const ROOT_END = { placement: 'bottom-end' } as const;+const SUBMENU_RIGHT = { placement: 'right-start' } as const;++describe('submenus', () => {+ it('flipped to open left keep their placement and open animation while the pointer crosses into them', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ {/* At the viewport's right edge, so a right-start submenu has no room and flips to the left. */}+ <Box position="fixed" right="1rem" top="2rem">+ <Menu.Root positioning={ROOT_END}>+ <Menu.Trigger>Open</Menu.Trigger>+ <Menu.Positioner>+ <MenuContent minW="12rem">+ <Menu.Item value="rename">Rename</Menu.Item>+ {/* As call sites nest them: right-start, positioned in a portal. */}+ <Menu.Root positioning={SUBMENU_RIGHT}>+ <Menu.TriggerItem>Move to</Menu.TriggerItem>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="12rem">+ <Menu.Item value="inbox">Inbox</Menu.Item>+ <Menu.Item value="archive">Archive</Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </MenuContent>+ </Menu.Positioner>+ </Menu.Root>+ </Box>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+ await act(() => userEvent.click(page.getByRole('button', { name: 'Open' })));+ await vi.waitFor(() => expect(item('rename')).toBeVisible());++ const trigger = page.getByRole('menuitem', { name: 'Move to' }).element() as HTMLElement;+ await act(() => userEvent.hover(trigger));+ await vi.waitFor(() => expect(item('inbox')).toBeVisible());+ const submenu = item('inbox').closest<HTMLElement>('[role="menu"]')!;+ await vi.waitFor(() => expect(submenu.dataset.placement).toMatch(/^left/));+ await Promise.all(submenu.getAnimations().map((animation) => animation.finished));++ const changes: string[] = [];+ const observer = new MutationObserver((records) => {+ for (const record of records) {+ const element = record.target as HTMLElement;+ const name = record.attributeName!;+ changes.push(`${element === trigger ? 'trigger' : 'submenu'} ${name}=${String(element.getAttribute(name))}`);+ }+ });+ for (const target of [trigger, submenu]) {+ observer.observe(target, { attributeFilter: ['data-placement', 'data-state'] });+ }+ const animationStarts: string[] = [];+ const recordAnimation = (event: AnimationEvent) => {+ if (event.target === submenu) {+ animationStarts.push(event.animationName);+ }+ };+ submenu.addEventListener('animationstart', recordAnimation);++ // Real pointer moves a pixel apart, from the trigger item's middle across its left edge to well inside the submenu,+ // so the browser fires pointerleave on the item and pointerenter on the submenu as a hand's crossing does.+ // `userEvent.hover` on an element jumps to its centre in one move. Forced, so Playwright does not wait out two frames+ // of stability before each move, which would leave the pointer in each spot far longer than a hand does.+ const body = document.body.getBoundingClientRect();+ const from = trigger.getBoundingClientRect();+ const y = from.top + from.height / 2;+ const end = submenu.getBoundingClientRect().right - 16;+ expect(end).toBeLessThan(from.left);+ for (let x = from.left + from.width / 2; x >= end; x -= 1) {+ await act(() =>+ userEvent.hover(page.elementLocator(document.body), {+ force: true,+ position: { x: x - body.left, y: y - body.top },+ })+ );+ }+ // Long enough for a restarted open animation, and for the hover the submenu loses with it to come back.+ await new Promise((resolve) => {+ globalThis.setTimeout(resolve, 300);+ });+ observer.disconnect();+ submenu.removeEventListener('animationstart', recordAnimation);++ expect(document.elementFromPoint(end, y)?.closest('[role="menu"]')).toBe(submenu);+ // One assertion, so a failure shows every symptom together.+ expect({ animationStarts, changes, state: submenu.dataset.state }).toEqual({+ animationStarts: [],+ changes: [],+ state: 'open',+ });+ expect(submenu.dataset.placement).toMatch(/^left/);+ });+});++/**+ * A pointer-anchored context menu shaped as call sites build one, opened by buttons outside it: near the bottom edge,+ * where a bottom-start menu has no room and flips to the top, and near the top, where it does not.+ */+const ContextMenuAt = () => {+ const { anchor, close, onRequestDismiss, open } = useContextMenu();+ const openLow = useCallback(() => open({ x: 120, y: window.innerHeight - 4 }), [open]);+ const openHigh = useCallback(() => open({ x: 120, y: 60 }), [open]);+ const positioning = useMemo(+ () => ({+ getAnchorRect: () => (anchor ? { height: 1, width: 1, x: anchor.x, y: anchor.y } : null),+ placement: 'bottom-start' as const,+ }),+ [anchor]+ );+ const handleOpenChange = useCallback(+ (event: { open: boolean }) => {+ if (!event.open) {+ close();+ }+ },+ [close]+ );+ return (+ <>+ <button type="button" onClick={openLow}>+ Open low+ </button>+ <button type="button" onClick={openHigh}>+ Open high+ </button>+ <Menu.Root+ open={anchor !== null}+ positioning={positioning}+ onOpenChange={handleOpenChange}+ onRequestDismiss={onRequestDismiss}+ >+ <Menu.Positioner>+ <MenuContent minW="12rem">+ <Menu.Item value="rename">Rename</Menu.Item>+ <Menu.Item value="duplicate">Duplicate</Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Menu.Root>+ </>+ );+};++describe('reopened menus', () => {+ it('open from their configured side, without a frame on the side a previous opening flipped to', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <ContextMenuAt />+ </ChakraProvider>+ );+ await Promise.resolve();+ });++ await act(() => userEvent.click(page.getByRole('button', { name: 'Open low' })));+ await vi.waitFor(() => expect(item('rename')).toBeVisible());+ const content = item('rename').closest<HTMLElement>('[role="menu"]')!;+ await vi.waitFor(() => expect(content.dataset.placement).toBe('top-start'));+ await Promise.all(content.getAnimations().map((animation) => animation.finished));++ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(content.dataset.state).toBe('closed'));+ await Promise.all(content.getAnimations().map((animation) => animation.finished));++ // The root stays mounted between openings, and so does the placement its machine resolved last; the content+ // element may be replaced, so watch for whichever one is current.+ const currentContent = () => document.querySelector<HTMLElement>('[data-scope="menu"][data-part="content"]');+ const snapshots: string[] = [];+ const observer = new MutationObserver(() => {+ const current = currentContent();+ snapshots.push(`${String(current?.dataset.state)} ${String(current?.dataset.placement)}`);+ });+ observer.observe(document.body, {+ attributeFilter: ['data-placement', 'data-state'],+ childList: true,+ subtree: true,+ });+ // One opening starts its animations together, in one frame; a restarted one starts in a later frame.+ const animationStarts: { name: string; time: CSSNumberish | null }[] = [];+ const recordAnimation = (event: AnimationEvent) => {+ if (event.target === currentContent()) {+ animationStarts.push({ name: event.animationName, time: document.timeline.currentTime });+ }+ };+ document.addEventListener('animationstart', recordAnimation, true);++ await act(() => userEvent.click(page.getByRole('button', { name: 'Open high' })));+ await vi.waitFor(() => expect(currentContent()?.dataset.state).toBe('open'));+ await vi.waitFor(() => expect(currentContent()?.dataset.placement).toBe('bottom-start'));+ const reopened = currentContent()!;+ await Promise.all(reopened.getAnimations().map((animation) => animation.finished));+ // Long enough for a restarted open animation to start.+ await new Promise((resolve) => {+ globalThis.setTimeout(resolve, 200);+ });+ observer.disconnect();+ document.removeEventListener('animationstart', recordAnimation, true);++ expect(animationStarts.length).toBeGreaterThan(0);+ // One assertion, so a failure shows every symptom together.+ expect({+ openOnFlippedSide: snapshots.filter((snapshot) => snapshot.startsWith('open top')),+ startedLater: animationStarts.filter(({ time }) => time !== animationStarts[0]!.time).map(({ name }) => name),+ }).toEqual({ openOnFlippedSide: [], startedLater: [] });+ });+});++const ARROW_PLACEMENTS = {+ 'bottom-start': { placement: 'bottom-start' },+ 'top-end': { placement: 'top-end' },+ 'right-start': { placement: 'right-start' },+ 'left-start': { placement: 'left-start' },+} as const;++// Context menus open at the pointer, anchored to a 1px point; other measured anchors are boxes, such as a tab.+const POINT_START = { height: 1, width: 1, x: 40, y: 200 };+const POINT_END = { height: 1, width: 1, x: 300, y: 200 };+const BOX = { height: 24, width: 40, x: 40, y: 200 };+const ANCHORED = {+ 'point-start': { getAnchorRect: () => POINT_START, placement: 'bottom-start' },+ 'point-end': { getAnchorRect: () => POINT_END, placement: 'bottom-end' },+ box: { getAnchorRect: () => BOX, placement: 'bottom-start' },+} as const;+const END_ALIGNED = { placement: 'bottom-end' } as const;++describe('menu arrows', () => {+ const renderTriggerMenu = async (placement: keyof typeof ARROW_PLACEMENTS, submenu = false) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ {/* Room on the side the menu opens to, so it does not flip. */}+ <Box+ left={placement.startsWith('right') ? '1rem' : placement.startsWith('left') ? 'calc(100vw - 5rem)' : '50vw'}+ position="fixed"+ top="50vh"+ >+ <Menu.Root positioning={ARROW_PLACEMENTS[placement]}>+ <Menu.Trigger>Open</Menu.Trigger>+ <Menu.Positioner>+ <MenuContent minW="12rem">+ <Menu.Item value="rename">Rename</Menu.Item>+ {submenu ? (+ <Menu.Root>+ <Menu.TriggerItem>Move to</Menu.TriggerItem>+ <Menu.Positioner>+ <MenuContent>+ <Menu.Item value="inbox">Inbox</Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Menu.Root>+ ) : null}+ </MenuContent>+ </Menu.Positioner>+ </Menu.Root>+ </Box>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+ await act(() => userEvent.click(page.getByRole('button', { name: 'Open' })));+ await vi.waitFor(() => expect(item('rename')).toBeVisible());+ };++ const arrowsIn = (positioner: Element | null | undefined) =>+ positioner ? [...positioner.querySelectorAll<HTMLElement>('[data-scope="menu"][data-part="arrow"]')] : [];++ it.each([+ ['bottom-start', 'top'],+ ['top-end', 'bottom'],+ ['right-start', 'left'],+ ] as const)('points a %s menu at its trigger from the content edge facing it', async (placement, edge) => {+ await renderTriggerMenu(placement);+ const trigger = page.getByRole('button', { name: 'Open' }).element().getBoundingClientRect();+ const menu = page.getByRole('menu').element();+ const [arrow] = arrowsIn(menu.parentElement);+ const tip = arrow!.querySelector<HTMLElement>('[data-part="arrow-tip"]')!;+ // The arrow slides in with the content once placed; measure both at rest.+ await vi.waitFor(() => expect(menu.dataset.side).toBe(placement.split('-')[0]));+ await Promise.all([...menu.getAnimations(), ...arrow!.getAnimations()].map((animation) => animation.finished));++ // Beside the content, whose scrolling would clip it, not inside it.+ expect(menu.contains(arrow!)).toBe(false);+ const content = menu.getBoundingClientRect();+ const tipBox = tip.getBoundingClientRect();+ if (edge === 'left') {+ expect(tipBox.left).toBeLessThan(content.left);+ expect(tipBox.left).toBeGreaterThanOrEqual(trigger.right);+ expect((tipBox.top + tipBox.bottom) / 2).toBeCloseTo((trigger.top + trigger.bottom) / 2, 0);+ } else {+ if (edge === 'top') {+ expect(tipBox.top).toBeLessThan(content.top);+ expect(tipBox.top).toBeGreaterThanOrEqual(trigger.bottom);+ } else {+ expect(tipBox.bottom).toBeGreaterThan(content.bottom);+ expect(tipBox.bottom).toBeLessThanOrEqual(trigger.top);+ }+ expect((tipBox.left + tipBox.right) / 2).toBeCloseTo((trigger.left + trigger.right) / 2, 0);+ }++ // The tip reads as part of the content: its fill and border are the content's, not a transparent outline.+ const contentStyle = getComputedStyle(menu);+ const tipStyle = getComputedStyle(tip);+ expect(tipStyle.backgroundColor).toBe(contentStyle.backgroundColor);+ expect(tipStyle.borderTopColor).toBe(contentStyle.borderTopColor);+ expect(tipStyle.borderTopWidth).toBe(contentStyle.borderTopWidth);+ });++ it('stays open, with keyboard navigation intact, when its tip is clicked; a click beside the menu still closes it', async () => {+ await renderTriggerMenu('bottom-start', true);+ const trigger = page.getByRole('button', { name: 'Open' }).element();+ const menu = page.getByRole('menu').element();+ const [arrow] = arrowsIn(menu.parentElement);+ await vi.waitFor(() => expect(menu.dataset.side).toBe('bottom'));+ await Promise.all([...menu.getAnimations(), ...arrow!.getAnimations()].map((animation) => animation.finished));+ const tipBox = arrow!.querySelector<HTMLElement>('[data-part="arrow-tip"]')!.getBoundingClientRect();+ const content = menu.getBoundingClientRect();+ const body = document.body.getBoundingClientRect();+ const clickAt = (x: number, y: number) =>+ act(() =>+ userEvent.click(page.elementLocator(document.body), { position: { x: x - body.left, y: y - body.top } })+ );+ await act(() => userEvent.keyboard('{ArrowDown}'));+ await vi.waitFor(() => expect(item('rename').hasAttribute('data-highlighted')).toBe(true));++ // On the tip's outer half, above the content's edge.+ await clickAt((tipBox.left + tipBox.right) / 2, content.top - 3);+ await new Promise((resolve) => {+ globalThis.setTimeout(resolve, 100);+ });+ expect(trigger.getAttribute('aria-expanded')).toBe('true');+ expect(menu.contains(document.activeElement)).toBe(true);+ await act(() => userEvent.keyboard('{ArrowDown}'));+ await vi.waitFor(() =>+ expect(page.getByRole('menuitem', { name: 'Move to' }).element()).toHaveAttribute('data-highlighted')+ );++ // The arrow's transparent clearance beside the tip lets the click through, to the page outside the menu.+ const arrowBox = arrow!.getBoundingClientRect();+ const clearance = { x: tipBox.right + 2, y: content.top - 3 };+ expect(clearance.x).toBeLessThan(arrowBox.right);+ expect(arrow!.contains(document.elementFromPoint(clearance.x, clearance.y))).toBe(false);+ await clickAt(clearance.x, clearance.y);+ await vi.waitFor(() => expect(trigger.getAttribute('aria-expanded')).toBe('false'));+ });++ it('leaves submenus, which open flush beside their item, without one', async () => {+ await renderTriggerMenu('bottom-start', true);+ await act(() => userEvent.click(page.getByRole('menuitem', { name: 'Move to' })));+ await vi.waitFor(() => expect(item('inbox')).toBeVisible());++ const [parentMenu, submenu] = page.getByRole('menu').elements();+ expect(arrowsIn(parentMenu!.parentElement)).toHaveLength(1);+ expect(arrowsIn(submenu!.parentElement)).toHaveLength(0);+ });++ it.each([+ ['a bottom-start context menu has none, and opens right at the pointer', 'point-start', 0, 8],+ ['a bottom-end context menu has none, and opens right at the pointer', 'point-end', 0, 8],+ ['a menu anchored to a measured box points at it', 'box', 12, 8 + 6],+ ] as const)('%s', async (_name, anchor, arrowSize, gap) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <Menu.Root open positioning={ANCHORED[anchor]}>+ <Menu.Positioner>+ <MenuContent>+ <Menu.Item value="rename">Rename</Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Menu.Root>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+ const menu = page.getByRole('menu').element();+ const [arrow] = arrowsIn(menu.parentElement);+ const { getAnchorRect, placement } = ANCHORED[anchor];+ await vi.waitFor(() => expect(menu.dataset.placement).toBe(placement));+ // A point anchor shrinks the arrow once placed; the menu is then placed again without the arrow's height.+ await vi.waitFor(() => {+ expect(arrow!.querySelector<HTMLElement>('[data-part="arrow-tip"]')!.offsetWidth).toBe(arrowSize);+ const rect = getAnchorRect();+ expect(menu.getBoundingClientRect().top - (rect.y + rect.height)).toBeCloseTo(gap, 0);+ });+ if (arrowSize === 0) {+ // Nor does its tip leave a bordered dot, nor its box shift the menu sideways to centre on the pointer: the menu's+ // aligned edge is at the pointer. Floating UI keeps even an arrow of no size its 4px padding from the corner, which+ // moves the menu by up to that, as it did before menus had arrows.+ expect(getComputedStyle(arrow!.querySelector('[data-part="arrow-tip"]')!).borderTopWidth).toBe('0px');+ const rect = getAnchorRect();+ const content = menu.getBoundingClientRect();+ if (placement === 'bottom-start') {+ expect(Math.abs(content.left - rect.x)).toBeLessThanOrEqual(4);+ } else {+ expect(Math.abs(content.right - (rect.x + rect.width))).toBeLessThanOrEqual(4);+ }+ } else {+ const tip = arrow!.querySelector('[data-part="arrow-tip"]')!.getBoundingClientRect();+ expect((tip.left + tip.right) / 2).toBeCloseTo(BOX.x + BOX.width / 2, 0);+ }+ });++ it.each([+ ['clears the corner for a small trigger at the end of a bar, shifting the panel to point at it', '50vw'],+ ['clears the corner for a small trigger at the viewport edge, where the panel cannot shift', '0px'],+ ] as const)('%s', async (_name, right) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <Box position="fixed" right={right} top="40vh">+ <Menu.Root positioning={END_ALIGNED}>+ <Menu.Trigger aria-label="More" h="4" p="0" w="4" />+ <Menu.Positioner>+ <MenuContent minW="12rem">+ <Menu.Item value="rename">Rename</Menu.Item>+ </MenuContent>+ </Menu.Positioner>+ </Menu.Root>+ </Box>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+ await act(() => userEvent.click(page.getByRole('button', { name: 'More' })));+ const menu = page.getByRole('menu').element();+ await vi.waitFor(() => expect(menu.dataset.side).toBe('bottom'));+ await Promise.all(menu.getAnimations().map((animation) => animation.finished));++ const content = menu.getBoundingClientRect();+ const radius = parseFloat(getComputedStyle(menu).borderTopRightRadius);+ const tip = arrowsIn(menu.parentElement)[0]!.querySelector('[data-part="arrow-tip"]')!.getBoundingClientRect();+ // The diamond's widest extent is its base on the content's edge: it stays on the straight part of that edge.+ expect(radius).toBeGreaterThan(0);+ expect(tip.left).toBeGreaterThanOrEqual(content.left + radius);+ expect(tip.right).toBeLessThanOrEqual(content.right - radius);+ if (right !== '0px') {+ const trigger = page.getByRole('button', { name: 'More' }).element().getBoundingClientRect();+ expect((tip.left + tip.right) / 2).toBeCloseTo((trigger.left + trigger.right) / 2, 0);+ }+ });++ it.each([+ ['bottom-start', 'first item, below the arrow'],+ ['top-end', 'last item, above the arrow'],+ ] as const)('lets the pointer through the arrow box to a %s menu: its %s', async (placement, _where) => {+ await renderTriggerMenu(placement);+ const menu = page.getByRole('menu').element();+ await vi.waitFor(() => expect(menu.dataset.side).toBe(placement.split('-')[0]));+ await Promise.all(menu.getAnimations().map((animation) => animation.finished));+ const [arrow] = arrowsIn(menu.parentElement);+ const box = arrow!.getBoundingClientRect();+ const content = menu.getBoundingClientRect();+ // Inside the item, which starts past the content's padding, and inside the arrow box's half over the content.+ const y = placement === 'bottom-start' ? content.top + 9 : content.bottom - 9;+ expect(y).toBeGreaterThan(box.top);+ expect(y).toBeLessThan(box.bottom);++ expect(document.elementFromPoint(box.left + box.width / 2, y)?.closest('[role="menuitem"]')).toBe(item('rename'));+ });++ describe('joint with the content', () => {+ afterEach(async () => {+ await server.commands.emulateDevicePixelRatio(null);+ applyThemeToRoot('classic');+ });++ it.each([+ ['classic', 1, 'top-end'],+ ['classic', 1, 'bottom-start'],+ ['classic', 1.25, 'top-end'],+ ['classic', 1.25, 'bottom-start'],+ ['classic', 1.25, 'right-start'],+ ['classic', 1.25, 'left-start'],+ ['light', 1.25, 'top-end'],+ ] as const)(+ 'reads as one shape, the content border never crossing the arrow (%s theme, DPR %s, %s)',+ async (themeId, ratio, placement) => {+ applyThemeToRoot(themeId);+ await server.commands.emulateDevicePixelRatio(ratio);+ await vi.waitFor(() => expect(globalThis.devicePixelRatio).toBe(ratio));+ await renderTriggerMenu(placement);+ const menu = page.getByRole('menu').element() as HTMLElement;+ const [arrow] = arrowsIn(menu.parentElement);+ await vi.waitFor(() => expect(menu.dataset.placement).toBe(placement));+ await Promise.all([...menu.getAnimations(), ...arrow!.getAnimations()].map((animation) => animation.finished));++ expect(await findArrowJointSeams(menu, arrow!.querySelector<HTMLElement>('[data-part="arrow-tip"]')!)).toEqual(+ []+ );+ }+ );+ });+});++/** Two sections kept alive by Activity, like the launchpad's pages, switched from outside them. */+const MenuSections = () => {+ const [isOtherShown, setIsOtherShown] = useState(false);+ const showOther = useCallback(() => setIsOtherShown(true), []);+ const showFirst = useCallback(() => setIsOtherShown(false), []);++ return (+ <ChakraProvider value={system}>+ <button type="button" onClick={showFirst}>+ First section+ </button>+ <button type="button" onClick={showOther}>+ Other section+ </button>+ <Activity mode={isOtherShown ? 'hidden' : 'visible'}>+ <Menu.Root>+ <Menu.Trigger>Actions</Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent>+ <MenuItem value="rename">Rename</MenuItem>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </Activity>+ </ChakraProvider>+ );+};++describe('menus in a hidden section', () => {+ it('stay closed when their section returns after it was hidden while they faded out', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => root?.render(<MenuSections />));+ const shownMenu = () =>+ [...document.querySelectorAll<HTMLElement>('[data-scope="menu"][data-part="content"]')].find((menu) =>+ menu.checkVisibility()+ );++ await userEvent.click(page.getByRole('button', { name: 'Actions' }));+ await expect.poll(() => shownMenu()?.textContent).toBe('Rename');+ // Escape closes the menu, and a switch hides its section before the fade ends.+ await act(() => userEvent.keyboard('{Escape}'));+ await act(() => userEvent.click(page.getByRole('button', { name: 'Other section' })));+ await act(() => userEvent.click(page.getByRole('button', { name: 'First section' })));++ await expect.poll(shownMenu).toBeUndefined();+ // Fully usable again: the trigger opens it afresh.+ await userEvent.click(page.getByRole('button', { name: 'Actions' }));+ await expect.poll(() => shownMenu()?.textContent).toBe('Rename');+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Menu.test.ts b/invokeai/frontend/webv2/src/platform/ui/Menu.test.tsnew file mode 100644index 0000000000..3b11d31b92--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/Menu.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it, vi } from 'vitest';++import { createMenuPartLoader } from './Menu';++const settle = () =>+ new Promise((resolve) => {+ setTimeout(resolve, 0);+ });++describe('createMenuPartLoader', () => {+ it('imports once however often it is asked, and keeps the part', async () => {+ const importPart = vi.fn(() => Promise.resolve('part'));+ const loader = createMenuPartLoader(importPart);++ loader.load();+ loader.load();+ expect(loader.getSnapshot()).toEqual({ status: 'loading' });+ await settle();+ loader.load();++ expect(loader.getSnapshot()).toEqual({ part: 'part', status: 'loaded' });+ expect(importPart).toHaveBeenCalledOnce();+ });++ it('fails an importer that throws at once like one that rejects, and imports again on the next load', async () => {+ const importPart = vi+ .fn<() => Promise<string>>()+ .mockImplementationOnce(() => {+ throw new Error('Import scheduling failed');+ })+ .mockRejectedValueOnce(new TypeError('Failed to fetch dynamically imported module'))+ .mockResolvedValue('part');+ const loader = createMenuPartLoader(importPart);+ const listener = vi.fn();+ loader.subscribe(listener);++ expect(() => loader.load()).not.toThrow();+ await settle();+ expect(loader.getSnapshot()).toEqual({ status: 'failed' });++ loader.load();+ await settle();+ expect(loader.getSnapshot()).toEqual({ status: 'failed' });++ loader.load();+ await settle();+ expect(loader.getSnapshot()).toEqual({ part: 'part', status: 'loaded' });+ expect(importPart).toHaveBeenCalledTimes(3);+ // loading → failed, twice, then loading → loaded.+ expect(listener).toHaveBeenCalledTimes(6);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx b/invokeai/frontend/webv2/src/platform/ui/Menu.tsxindex 15c9469e49..45154e1519 100644--- a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Menu.tsx@@ -1,5 +1,5 @@import type { LucideIcon } from 'lucide-react';-import type { ComponentProps, ReactNode, Ref } from 'react';+import type { ComponentProps, MouseEvent, ReactNode, Ref } from 'react';import {Box,@@ -14,15 +14,16 @@ import {useMenuItemContext,} from '@chakra-ui/react';import { useMountEffect } from '@platform/react/useMountEffect';-import { createExternalStore } from '@platform/state/externalStore';-import { useCallback, useId, useMemo } from 'react';+import { createExternalStore, createExternalStoreCore } from '@platform/state/externalStore';+import { createContext, useCallback, useContext, useId, useMemo, useRef, useSyncExternalStore } from 'react';+import { useTranslation } from 'react-i18next';import { IconButton, useUnavailableControl } from './Button';import { MiddleTruncate } from './MiddleTruncate';import { Tooltip } from './Tooltip';import { useRegisterWidgetOverlay } from './widgetOverlays';-type MenuContentProps = ComponentProps<typeof Menu.Content>;+type MenuContentProps = Omit<ComponentProps<typeof Menu.Content>, 'ref'>;/*** The layout of menu content whose list scrolls (`ScrollableMenuContent`, or `ScrollableMenuList` inside it): it grows to@@ -36,11 +37,67 @@ export const SCROLLABLE_MENU_CONTENT_PROPS = {overflow: 'hidden',} as const;-/** Menu content closes with its owning widget; the theme recipe owns chrome. */-export const MenuContent = (props: MenuContentProps) => {+/** Zag's cancelable event on the content for a press outside it; cancelling it keeps the menu open. */+const POINTER_DOWN_OUTSIDE_EVENT = 'pointerdown.outside';++/** The arrow takes no focus: a press on its tip would otherwise move focus to the page and end keyboard navigation. */+const keepFocus = (event: MouseEvent<HTMLElement>) => event.preventDefault();++/** A menu rooted inside another menu's content is its submenu, which opens flush beside its item. */+const InsideMenuContentContext = createContext(false);++/**+ * Menu content closes with its owning widget; the theme recipe owns chrome.+ *+ * Every menu but a submenu has an arrow pointing at its anchor. The recipe sizes it from the anchor: a trigger or any+ * other box gets one, and a context menu, anchored to the pointer's point, gets none. The arrow is the content's next+ * sibling, not its child: menu content scrolls, which would clip an arrow poking out of it. Zag finds it in the+ * positioner all the same. It must stay after the content: Zag reads the menu's z-index from the positioner's first+ * child, and the recipe hides it with content kept mounted but hidden through a sibling selector.+ */+export const MenuContent = ({ children, ...props }: MenuContentProps) => {const menu = useMenuContext();+ const isSubmenu = useContext(InsideMenuContentContext);const stale = useRegisterWidgetOverlay(menu.open, menu.setOpen);- return stale ? null : <Menu.Content {...props} />;+ const arrowRef = useRef<HTMLDivElement>(null);+ // Zag dismisses on a press outside the content, and the arrow, a sibling, counts as outside: a click on the visible+ // tip would close the menu. Ark exposes the dismissal hook only on Menu.Root, so this listens for Zag's outside event+ // by name on the content instead. Zag adds its own listener just before dispatching, so this one runs first.+ const keepOpenOnArrow = useCallback((content: HTMLDivElement | null) => {+ const handlePointerDownOutside = (event: Event) => {+ const target = event instanceof CustomEvent ? (event.detail as { target?: unknown } | null)?.target : null;++ if (target instanceof Node && arrowRef.current?.contains(target)) {+ event.preventDefault();+ }+ };++ content?.addEventListener(POINTER_DOWN_OUTSIDE_EVENT, handlePointerDownOutside);+ return () => content?.removeEventListener(POINTER_DOWN_OUTSIDE_EVENT, handlePointerDownOutside);+ }, []);+ if (stale) {+ return null;+ }+ // Zag puts the placement on the content's props; their React type lists only standard attributes.+ const { 'data-placement': placement } = menu.getContentProps() as { 'data-placement'?: string };+ return (+ <>+ <Menu.Content ref={keepOpenOnArrow} {...props}>+ <InsideMenuContentContext value>{children}</InsideMenuContentContext>+ </Menu.Content>+ {isSubmenu ? null : (+ // The content's own state and placement, so the recipe animates the arrow as Chakra animates the content.+ <Menu.Arrow+ ref={arrowRef}+ data-placement={placement}+ data-state={menu.open ? 'open' : 'closed'}+ onMouseDown={keepFocus}+ >+ <Menu.ArrowTip />+ </Menu.Arrow>+ )}+ </>+ );};export interface MenuHeadingGroupProps {@@ -210,6 +267,67 @@ export const MenuActionItem = ({);};+export type MenuPartSnapshot<Part> = { part: Part; status: 'loaded' } | { status: 'failed' | 'idle' | 'loading' };++export interface MenuPartLoader<Part> {+ getSnapshot: () => MenuPartSnapshot<Part>;+ /** Starts the import unless it has loaded or is under way; after a failure, imports again. Never throws or rejects. */+ load: () => void;+ subscribe: (listener: () => void) => () => void;+}++/**+ * Loads part of a menu on demand into state, not through `lazy()`: a lazy boundary suspends on the open's first render+ * even when its module has loaded, and React holds back the reveal, so the menu would open on its placeholder. Once+ * loaded the part stays, so every later open renders it on its first frame. Call `load` on intent and on open.+ */+export const createMenuPartLoader = <Part,>(importPart: () => Promise<Part>): MenuPartLoader<Part> => {+ const store = createExternalStoreCore<MenuPartSnapshot<Part>>({ status: 'idle' });++ return {+ getSnapshot: store.getSnapshot,+ load: () => {+ const { status } = store.getSnapshot();++ if (status === 'idle' || status === 'failed') {+ store.setSnapshot({ status: 'loading' });+ // An importer that throws at once fails like one that rejects, rather than leaving the part loading for good.+ new Promise<Part>((resolve) => {+ resolve(importPart());+ }).then(+ (part) => store.setSnapshot({ part, status: 'loaded' }),+ () => store.setSnapshot({ status: 'failed' })+ );+ }+ },+ subscribe: store.subscribe,+ };+};++export const useMenuPart = <Part,>(loader: MenuPartLoader<Part>): MenuPartSnapshot<Part> =>+ useSyncExternalStore(loader.subscribe, loader.getSnapshot, loader.getSnapshot);++const ignoreSelect = () => undefined;++/**+ * An unavailable item in the place of a part still loading or that failed to, so the menu holds only menu items. Not+ * `disabled`: Zag skips disabled items in keyboard navigation, so a menu holding only this one would leave the+ * keyboard nothing to reach and the state unannounced.+ */+export const MenuPartPlaceholder = ({ status }: { status: MenuPartSnapshot<unknown>['status'] }) => {+ const { t } = useTranslation();+ const failed = status === 'failed';++ return (+ <MenuActionItem+ label={t(failed ? 'common.menuPartLoadFailed' : 'common.loading')}+ unavailableReason={t(failed ? 'common.menuPartLoadFailedReason' : 'common.menuPartLoading')}+ value="menu-part-placeholder"+ onSelect={ignoreSelect}+ />+ );+};+const ICON_ITEM_TOOLTIP_CONTENT_PROPS = { fontSize: 'xs' } as const;const ICON_ITEM_TOOLTIP_POSITIONING_PROPS = { placement: 'top' } as const;diff --git a/invokeai/frontend/webv2/src/platform/ui/ModelDefaultButton.tsx b/invokeai/frontend/webv2/src/platform/ui/ModelDefaultButton.tsxdeleted file mode 100644index 218657fbcc..0000000000--- a/invokeai/frontend/webv2/src/platform/ui/ModelDefaultButton.tsx+++ /dev/null@@ -1,25 +0,0 @@-import { Icon } from '@chakra-ui/react';-import { IconButton } from '@platform/ui/Button';-import { Tooltip } from '@platform/ui/Tooltip';-import { RotateCcwIcon } from 'lucide-react';-import { useCallback } from 'react';--/** Render only for modified values and supply a specific reset label. */-export const ModelDefaultButton = ({ label, onClick }: { label: string; onClick: () => void }) => {- const handleClick = useCallback(- (event: React.MouseEvent<HTMLButtonElement>) => {- event.preventDefault();- event.stopPropagation();- onClick();- },- [onClick]- );-- return (- <Tooltip content={label}>- <IconButton aria-label={label} color="fg.muted" size="sm" variant="ghost" onClick={handleClick}>- <Icon as={RotateCcwIcon} boxSize="2.5" />- </IconButton>- </Tooltip>- );-};diff --git a/invokeai/frontend/webv2/src/platform/ui/PanelHeader.tsx b/invokeai/frontend/webv2/src/platform/ui/PanelHeader.tsxindex 0d1b8c3693..1c3444381e 100644--- a/invokeai/frontend/webv2/src/platform/ui/PanelHeader.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/PanelHeader.tsx@@ -1,6 +1,9 @@-import type { StackProps } from '@chakra-ui/react';+import type { ElementType, ReactNode } from 'react';-import { HStack } from '@chakra-ui/react';+import { Box, HStack, Icon, type StackProps } from '@chakra-ui/react';+import { useCallback, useMemo } from 'react';++import { IconButton } from './Button';/** Shared desktop panel chrome; callers supply identity and surface-specific actions. */export const PanelHeader = (props: StackProps) => (@@ -15,3 +18,63 @@ export const PanelHeader = (props: StackProps) => ({...props}/>);++/** A thin vertical rule between groups of header actions. */+export const HeaderActionDivider = () => <Box bg="border.subtle" flexShrink={0} h="4" mx="1" w="1px" />;++/**+ * An undo or redo step among a header's actions. With nothing to step over it reads as disabled (`aria-disabled`) but+ * keeps focus, so stepping to the end of the history does not drop a keyboard user to the page; it never runs then.+ * `unavailableReason` says why a step that exists cannot run now, in the tooltip and the description.+ */+export const HeaderHistoryButton = ({+ available,+ icon,+ label,+ shortcut,+ unavailableReason,+ onStep,+}: {+ available: boolean;+ icon: ElementType;+ /** The accessible name and the tooltip's text. */+ label: string;+ /** The step's keycaps, after the label in the tooltip; the caller renders them, since key glyphs are not platform. */+ shortcut?: ReactNode;+ unavailableReason?: string;+ onStep: () => void;+}) => {+ // The click event must not reach a step that takes an optional argument.+ const onClick = useCallback(() => {+ if (available && !unavailableReason) {+ onStep();+ }+ }, [available, onStep, unavailableReason]);+ const tooltip = useMemo(+ () =>+ shortcut ? (+ <HStack gap="2">+ <span>{label}</span>+ {shortcut}+ </HStack>+ ) : (+ label+ ),+ [label, shortcut]+ );++ return (+ <IconButton+ aria-disabled={available ? undefined : true}+ aria-label={label}+ color="fg.muted"+ size="sm"+ tooltip={tooltip}+ unavailableReason={unavailableReason}+ variant="ghost"+ onClick={onClick}+ >+ <Icon as={icon} boxSize="3.5" />+ </IconButton>+ );+};diff --git a/invokeai/frontend/webv2/src/platform/ui/Picker.tsx b/invokeai/frontend/webv2/src/platform/ui/Picker.tsxindex aeac78e26b..d62e429c10 100644--- a/invokeai/frontend/webv2/src/platform/ui/Picker.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Picker.tsx@@ -299,7 +299,7 @@ export const Picker = <T,>({return (<Stack gap="0" minH="0">- <Stack gap="2" p="2">+ <Stack gap="1.5" p="1.5"><HStack gap="1"><InputGroup flex="1" minW="0" startElement={SEARCH_ICON}><SearchInputdiff --git a/invokeai/frontend/webv2/src/platform/ui/Popover.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Popover.browser.test.tsxnew file mode 100644index 0000000000..4b89e41de7--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/Popover.browser.test.tsx@@ -0,0 +1,161 @@+import { Box, ChakraProvider, Popover } from '@chakra-ui/react';+import { applyThemeToRoot } from '@theme/applyTheme';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { page, server, userEvent } from 'vitest/browser';++import { findArrowJointSeams } from './arrowJoint.testing';+import { PopoverContent } from './Popover';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ await server.commands.emulateDevicePixelRatio(null);+ applyThemeToRoot('classic');+});++const PLACEMENTS = {+ bottom: { placement: 'bottom' },+ left: { placement: 'left' },+ right: { placement: 'right' },+ top: { placement: 'top' },+} as const;++const renderPopover = async (placement: keyof typeof PLACEMENTS) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <Box left="50vw" position="fixed" top="50vh">+ <Popover.Root positioning={PLACEMENTS[placement]}>+ <Popover.Trigger>Open</Popover.Trigger>+ <Popover.Positioner>+ <PopoverContent w="12rem">+ <Popover.Body p="0">+ <Box as="button" h="8" w="full">+ Inside+ </Box>+ </Popover.Body>+ </PopoverContent>+ </Popover.Positioner>+ </Popover.Root>+ </Box>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+ await act(() => userEvent.click(page.getByRole('button', { name: 'Open' })));+ const content = document.querySelector<HTMLElement>('[data-scope="popover"][data-part="content"]')!;+ await vi.waitFor(() => expect(content.dataset.placement).toBe(placement));+ await Promise.all(content.getAnimations().map((animation) => animation.finished));+ const arrow = content.querySelector<HTMLElement>('[data-part="arrow"]')!;+ return { arrow, content, tip: arrow.querySelector<HTMLElement>('[data-part="arrow-tip"]')! };+};++describe('PopoverContent arrow', () => {+ it.each(['bottom', 'top'] as const)(+ 'centres on the content outer edge facing the trigger, as a menu arrow does (%s)',+ async (placement) => {+ const { content, tip } = await renderPopover(placement);+ const trigger = page.getByRole('button', { name: 'Open' }).element().getBoundingClientRect();+ const edge = content.getBoundingClientRect();+ const tipBox = tip.getBoundingClientRect();++ expect((tipBox.top + tipBox.bottom) / 2).toBeCloseTo(placement === 'bottom' ? edge.top : edge.bottom, 0);+ expect((tipBox.left + tipBox.right) / 2).toBeCloseTo((trigger.left + trigger.right) / 2, 0);+ }+ );++ it('lets the pointer through its transparent box to the content beneath', async () => {+ const { arrow, content } = await renderPopover('bottom');+ const box = arrow.getBoundingClientRect();+ const inside = page.getByRole('button', { name: 'Inside' }).element();+ const y = content.getBoundingClientRect().top + 4;+ expect(y).toBeLessThan(box.bottom);++ expect(document.elementFromPoint(box.left + box.width / 2, y)).toBe(inside);+ });++ it('stays open when its visible tip is clicked, as a click on the content would', async () => {+ const { content, tip } = await renderPopover('bottom');+ const tipBox = tip.getBoundingClientRect();+ // On the tip's outer half, above the content's edge: the part a user sees.+ const point = { x: (tipBox.left + tipBox.right) / 2, y: content.getBoundingClientRect().top - 3 };+ expect(document.elementFromPoint(point.x, point.y)).toBe(tip);++ const body = document.body.getBoundingClientRect();+ await act(() =>+ userEvent.click(page.elementLocator(document.body), {+ position: { x: point.x - body.left, y: point.y - body.top },+ })+ );+ await new Promise((resolve) => {+ globalThis.setTimeout(resolve, 100);+ });++ expect(content.dataset.state).toBe('open');+ expect(page.getByRole('button', { name: 'Open' }).element().getAttribute('aria-expanded')).toBe('true');+ });+});++describe('PopoverContent arrow joint', () => {+ // The status bar's composition: no padding, and the clipped column inside it ends in a footer flush with the edge.+ it.each([+ ['classic', 1, 'top'],+ ['classic', 1, 'bottom'],+ ['classic', 1.25, 'top'],+ ['classic', 1.25, 'bottom'],+ ['classic', 1.25, 'left'],+ ['classic', 1.25, 'right'],+ ['light', 1.25, 'top'],+ ] as const)(+ 'reads as one shape with the content, its border never crossing the arrow (%s theme, DPR %s, %s)',+ async (themeId, ratio, placement) => {+ applyThemeToRoot(themeId);+ await server.commands.emulateDevicePixelRatio(ratio);+ await vi.waitFor(() => expect(globalThis.devicePixelRatio).toBe(ratio));+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(async () => {+ root?.render(+ <ChakraProvider value={system}>+ <Box left="50vw" position="fixed" top="50vh">+ <Popover.Root positioning={PLACEMENTS[placement]}>+ <Popover.Trigger>Open</Popover.Trigger>+ <Popover.Positioner>+ <PopoverContent display="flex" flexDirection="column" p="0" w="8rem">+ <Box display="flex" flexDirection="column" overflow="hidden" rounded="inherit">+ <Box h="16" />+ <Box as="button" bg="bg.emphasized" h="8" w="full">+ Settings+ </Box>+ </Box>+ </PopoverContent>+ </Popover.Positioner>+ </Popover.Root>+ </Box>+ </ChakraProvider>+ );+ await Promise.resolve();+ });+ await act(() => userEvent.click(page.getByRole('button', { name: 'Open' })));+ const content = document.querySelector<HTMLElement>('[data-scope="popover"][data-part="content"]')!;+ await vi.waitFor(() => expect(content.dataset.placement).toBe(placement));+ await Promise.all(content.getAnimations().map((animation) => animation.finished));+ const tip = content.querySelector<HTMLElement>('[data-part="arrow-tip"]')!;++ expect(await findArrowJointSeams(content, tip)).toEqual([]);+ }+ );+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Popover.tsx b/invokeai/frontend/webv2/src/platform/ui/Popover.tsxindex 261407180a..575e7dfe74 100644--- a/invokeai/frontend/webv2/src/platform/ui/Popover.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Popover.tsx@@ -5,7 +5,10 @@ import { Popover, usePopoverContext } from '@chakra-ui/react';import { useRegisterWidgetOverlay } from './widgetOverlays';type PopoverContentProps = ComponentProps<typeof Popover.Content> & {- /** Anchored panels keep the arrow; dropdown-shaped popovers (pickers) opt out. */+ /**+ * Every popover anchored to a trigger points at it, as menus and hover cards do. Only listboxes that sit flush under+ * their field opt out (ModelSelect's picker, as Select and Combobox do).+ */showArrow?: boolean;};diff --git a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsxindex 481e8c94b1..1409d44851 100644--- a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.browser.test.tsx@@ -29,17 +29,17 @@ afterEach(async () => {root = null;});-const TRACK_INSET_PX = 10;+const TRACK_INSET_PX = 6;const HOST_WIDTH_PX = 400;/** Hundredths below 1 (and leaving 1 downwards), whole units above. */const stepFor = (value: number, direction: 1 | -1) => (value < 1 || (direction < 0 && value === 1) ? 0.01 : 1);-const mount = async (props: Partial<ScrubberFieldProps> = {}) => {+const mount = async (props: Partial<ScrubberFieldProps> = {}, width = HOST_WIDTH_PX) => {const onChange = vi.fn();host = document.createElement('div');- host.style.width = `${HOST_WIDTH_PX}px`;+ host.style.width = `${width}px`;document.body.append(host);root = createRoot(host);@@ -160,6 +160,36 @@ describe('ScrubberField', () => {expect(emptyClearance).toBeLessThanOrEqual(3.5);});+ it.each([425, 160])('keeps the thumb clear of the text at either end of a %ipx track', async (width) => {+ const box = (element: Element) => element.getBoundingClientRect();+ // The glyphs' own box, not the padded element.+ const textBox = (element: Element) => {+ const range = document.createRange();++ range.selectNodeContents(element);++ return range.getBoundingClientRect();+ };+ const part = (frame: HTMLElement, name: string) => frame.querySelector(`[data-part="${name}"]`)!;+ // A visible gap rather than a thumb touching the first or last glyph.+ const minGap = 4;++ const empty = await mount({ label: 'HiDiffusion: T2 Ratio', max: 1, min: 0, step: 0.01, value: 0 }, width);+ const label = textBox(part(empty.frame, 'label'));++ expect(label.left - box(part(empty.frame, 'thumb')).right).toBeGreaterThanOrEqual(minGap);+ // The fill's rounded end frames the thumb without reaching under the label.+ expect(box(part(empty.frame, 'fill')).right).toBeLessThanOrEqual(label.left);+ await act(() => root?.unmount());+ host?.remove();++ const full = await mount({ label: 'CFG rescale', max: 1, min: 0, step: 0.01, value: 1 }, width);++ expect(box(part(full.frame, 'thumb')).left - textBox(part(full.frame, 'value')).right).toBeGreaterThanOrEqual(+ minGap+ );+ });+it('scrubs relative to the current value from wherever the press lands, snapped to the step', async () => {const { frame, onChange } = await mount({ step: 5 });diff --git a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsxindex 5a7e7fe11f..e98fb564d2 100644--- a/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ScrubberField.tsx@@ -10,13 +10,17 @@ import type {import { Box, chakra, Stack, Text } from '@chakra-ui/react';import { useMountEffect } from '@platform/react/useMountEffect';+import { INSIDE_LABEL_INSET } from '@platform/ui/Field';import { FEATURE_HINT_FIELD_PROPS, FeatureHint } from '@platform/ui/hints';import { fieldLabelRecipe, scrubberInteraction } from '@theme/recipes';import { useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-/** Track inset from the frame edge; the text padding clears it so the thumb never crosses a glyph. */-const TRACK_INSET_PX = 10;+/**+ * Track inset from the frame edge. The label and value sit 12px in (`INSIDE_LABEL_INSET`, the value's `pe`), so an+ * end thumb lands a stop's text clearance outside them and the fill's rounded end stops short of the first glyph.+ */+const TRACK_INSET_PX = 6;/*** At the track's start the fill ends this far past the thumb's centre, just enough for its rounded end to frame the* 2px thumb without drifting away from it.@@ -174,7 +178,7 @@ const ROOT_CSS = {flexShrink: 1,minW: '0',overflow: 'hidden',- ps: '3',+ ps: INSIDE_LABEL_INSET,position: 'relative',textOverflow: 'ellipsis',textShadow: SCRUBBER_TEXT_SHADOW,diff --git a/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.browser.test.tsxindex 88fdab3bd5..229cf02770 100644--- a/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.browser.test.tsx@@ -156,3 +156,156 @@ it('gives a hovered disabled tab no hover look, and keeps its dividers', async (expect(look()).toEqual(before.look);expect(dividers()).toEqual(before.dividers);});++// Labels as long as a German queue strip's, so five tabs cannot share a narrow rail.+const LONG_TABS: readonly SegmentTab[] = [+ { id: 'all', label: 'Alle 12.345' },+ { id: 'active', label: 'Aktiv 12.345' },+ { id: 'done', label: 'Erledigt 12.345' },+ { id: 'failed', label: 'Fehlgeschlagen 12.345' },+ { id: 'canceled', label: 'Abgebrochen 12.345' },+];+// How far the end fades reach into a scrolling strip; a revealed tab must sit clear of them.+const FADE_PX = 16;++const nextFrame = () =>+ new Promise((resolve) => {+ requestAnimationFrame(resolve);+ });++const renderScrollingTabs = (width: number, activeId = 'all', onSelect: (id: string) => void = noop) => {+ host = document.createElement('div');+ host.style.width = `${width}px`;+ document.body.append(host);+ root = createRoot(host);+ const render = (active: string) =>+ act(() =>+ root!.render(+ <ChakraProvider value={system}>+ <SegmentTabs+ isCompact+ isScrollable+ activeId={active}+ ariaLabel="Status"+ idBase="status"+ tabs={LONG_TABS}+ onSelect={onSelect}+ />+ </ChakraProvider>+ )+ );+ render(activeId);+ const strip = host.querySelector<HTMLElement>('[role="tablist"]')!;+ const tab = (label: string) =>+ [...strip.querySelectorAll<HTMLElement>('[role="tab"]')].find((el) => el.textContent === label)!;+ /** Wholly inside the strip, and clear of the fade at an end that still hides tabs. */+ const isInView = (element: HTMLElement) => {+ const bounds = strip.getBoundingClientRect();+ const rect = element.getBoundingClientRect();+ const hidesStart = strip.scrollLeft > 1;+ const hidesEnd = strip.scrollLeft < strip.scrollWidth - strip.clientWidth - 1;+ return (+ rect.left >= bounds.left + (hidesStart ? FADE_PX : 0) - 1 &&+ rect.right <= bounds.right - (hidesEnd ? FADE_PX : 0) + 1+ );+ };+ return { isInView, render, strip, tab };+};++it('scrolls a scrollable strip sideways instead of squeezing or wrapping tabs that do not fit', () => {+ const { strip } = renderScrollingTabs(200);+ const tabs = [...strip.querySelectorAll<HTMLElement>('[role="tab"]')];++ expect(strip.scrollWidth).toBeGreaterThan(strip.clientWidth);+ expect(host!.scrollWidth).toBe(host!.clientWidth);+ expect(new Set(tabs.map((tab) => tab.offsetTop)).size).toBe(1);+ for (const tab of tabs) {+ // A squeezed tab would clip its label: its content would be wider than its box.+ expect(tab.scrollWidth).toBeLessThanOrEqual(tab.clientWidth);+ }+ // A vertical wheel moves it sideways.+ strip.dispatchEvent(new WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY: 40 }));+ expect(strip.scrollLeft).toBe(40);+});++it('fades out whichever end of a scrolling strip hides tabs', async () => {+ const { strip } = renderScrollingTabs(200);+ const fades = async () => {+ await nextFrame();+ return {+ end: strip.hasAttribute('data-hidden-end'),+ masked: getComputedStyle(strip).maskImage !== 'none',+ start: strip.hasAttribute('data-hidden-start'),+ };+ };++ expect(await fades()).toEqual({ end: true, masked: true, start: false });+ strip.scrollLeft = 60;+ expect(await fades()).toEqual({ end: true, masked: true, start: true });+ strip.scrollLeft = strip.scrollWidth;+ expect(await fades()).toEqual({ end: false, masked: true, start: true });+});++it('brings the focused tab into view as the arrow keys move along a scrolling strip', async () => {+ const { isInView, tab } = renderScrollingTabs(200);+ act(() => tab('Alle 12.345').focus());++ for (const label of ['Aktiv 12.345', 'Erledigt 12.345', 'Fehlgeschlagen 12.345', 'Abgebrochen 12.345']) {+ await act(() => userEvent.keyboard('{ArrowRight}'));+ expect(document.activeElement).toBe(tab(label));+ expect(isInView(tab(label))).toBe(true);+ }+ await act(() => userEvent.keyboard('{Home}'));+ expect(isInView(tab('Alle 12.345'))).toBe(true);+});++it('draws the focused tab ring inside the strip, which clips at the tabs height', async () => {+ const { strip, tab } = renderScrollingTabs(200);+ act(() => tab('Alle 12.345').focus());+ await act(() => userEvent.keyboard('{End}'));+ const focused = tab('Abgebrochen 12.345');+ const style = getComputedStyle(focused);+ // The ring reaches this far past the tab's border box; negative is inside it.+ const reach = Number.parseFloat(style.outlineWidth) + Number.parseFloat(style.outlineOffset);+ const bounds = strip.getBoundingClientRect();+ const rect = focused.getBoundingClientRect();++ expect(focused.matches(':focus-visible')).toBe(true);+ expect(style.outlineStyle).toBe('solid');+ // Sub-pixel tolerance: a fully scrolled strip can leave a fractional remainder.+ expect(rect.top - reach).toBeGreaterThanOrEqual(bounds.top - 0.5);+ expect(rect.bottom + reach).toBeLessThanOrEqual(bounds.bottom + 0.5);+ expect(rect.left - reach).toBeGreaterThanOrEqual(bounds.left - 0.5);+ expect(rect.right + reach).toBeLessThanOrEqual(bounds.right + 0.5);+});++it('brings a clicked, partly hidden tab wholly into view', () => {+ const onSelect = vi.fn();+ const { isInView, tab } = renderScrollingTabs(200, 'all', onSelect);+ const partlyHidden = ['Aktiv 12.345', 'Erledigt 12.345'].map(tab).find((element) => !isInView(element))!;++ // Pointer focus scrolling differs between browsers; the strip must not depend on it.+ act(() => partlyHidden.dispatchEvent(new MouseEvent('click', { bubbles: true })));++ expect(onSelect).toHaveBeenCalledOnce();+ expect(isInView(partlyHidden)).toBe(true);+});++it('brings a tab selected from outside the strip into view', () => {+ const { isInView, render, strip, tab } = renderScrollingTabs(200, 'canceled');++ // Selected on mount, at the far end.+ expect(strip.scrollLeft).toBeGreaterThan(0);+ expect(isInView(tab('Abgebrochen 12.345'))).toBe(true);+ render('all');+ expect(isInView(tab('Alle 12.345'))).toBe(true);+});++it('leaves a scrollable strip still when its tabs fit', () => {+ const { strip } = renderScrollingTabs(1000);++ expect(strip.scrollWidth).toBe(strip.clientWidth);+ expect(strip.hasAttribute('data-hidden-end')).toBe(false);+ strip.dispatchEvent(new WheelEvent('wheel', { bubbles: true, cancelable: true, deltaY: 40 }));+ expect(strip.scrollLeft).toBe(0);+});diff --git a/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.tsx b/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.tsxindex 603f5bbadb..9b4015da13 100644--- a/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/SegmentTabs.tsx@@ -1,13 +1,17 @@-import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react';+import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from 'react';import { Box, chakra, HStack, Text } from '@chakra-ui/react';import { Fragment, useCallback } from 'react';+import { HIDDEN_SCROLLBAR_CSS, markHiddenEdges, SCROLL_EDGE_FADE_CSS, SCROLL_EDGE_FADE_PX } from './scrollStripEdges';import { Tooltip } from './Tooltip';+import { wheelScrollsHorizontally } from './wheelScrollsHorizontally';const TAB_HOVER_PROPS = { bg: 'bg.hover', color: 'fg' };const TAB_SHOWN_BG = 'gray.hoverTint/15';const TAB_DISABLED_PROPS = { layerStyle: 'disabled' } as const;+// Inset: the tablist clips at the tabs' own height, so an outside ring would be cut off.+const TAB_FOCUS_VISIBLE_PROPS = { outline: '2px solid', outlineColor: 'accent.solid', outlineOffset: '-2px' } as const;const ENABLED_TAB = '[role="tab"]:not([aria-disabled="true"])';// A hovered tab's background replaces its neighbouring dividers, as the shown tab's does. The theme's `_hover` condition// already skips `aria-disabled` controls, so a disabled tab gets no hover fill; this raw selector must skip it too.@@ -16,6 +20,24 @@ const TABLIST_CSS = {opacity: 0,},};+const SCROLLING_TABLIST_CSS = { ...TABLIST_CSS, ...HIDDEN_SCROLLBAR_CSS, ...SCROLL_EDGE_FADE_CSS };++const attachScrollingTablist = (element: HTMLElement | null) => {+ if (!element) {+ return;+ }+ const releaseWheel = wheelScrollsHorizontally(element);+ const releaseEdges = markHiddenEdges(element);++ return () => {+ if (typeof releaseWheel === 'function') {+ releaseWheel();+ }+ if (typeof releaseEdges === 'function') {+ releaseEdges();+ }+ };+};/** The strip's fixed height; collapsed blocks and drag snaps size against it. */export const SEGMENT_TABS_HEIGHT_PX = 40;@@ -32,11 +54,40 @@ export interface SegmentTab<T extends string = string> {const isTabEnabled = (tab: HTMLElement): boolean => tab.getAttribute('aria-disabled') !== 'true';+/**+ * Scroll only a scrolling strip, never its ancestors, until `tab` lies wholly inside it and clear of the edge fades. The+ * scroll clamps at either end, where no fade shows. Focus scrolling cannot be relied on: a pointer press does not focus+ * a button in every browser. Physical offsets suit either direction. A strip whose tabs fit is left alone.+ */+const revealInStrip = (tab: HTMLElement): void => {+ const strip = tab.closest<HTMLElement>('[role="tablist"]');+ if (!strip || strip.scrollWidth <= strip.clientWidth) {+ return;+ }+ const bounds = strip.getBoundingClientRect();+ const rect = tab.getBoundingClientRect();+ const left = bounds.left + SCROLL_EDGE_FADE_PX;+ const right = bounds.right - SCROLL_EDGE_FADE_PX;+ if (rect.left < left) {+ strip.scrollLeft -= left - rect.left;+ } else if (rect.right > right) {+ strip.scrollLeft += rect.right - right;+ }+};++/** Keeps a scrolling strip's selected tab in view whenever selection moves, however it moved (and on mount). */+const revealSelectedTab = (tab: HTMLElement | null): void => {+ if (tab) {+ revealInStrip(tab);+ }+};+/*** Roving focus for a horizontal tablist: arrows cycle, Home/End jump, all over enabled tabs. A focused disabled tab (the- * selected one, when it has nothing to show) still steps to its enabled neighbours.+ * selected one, when it has nothing to show) still steps to its enabled neighbours. A scrolling strip brings the focused+ * tab into view itself, so focus never scrolls the strip's ancestors.*/-const focusSibling = (event: ReactKeyboardEvent<HTMLElement>) => {+const focusSibling = (event: ReactKeyboardEvent<HTMLElement>, isScrollable: boolean) => {if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight' && event.key !== 'Home' && event.key !== 'End') {return;}@@ -59,9 +110,20 @@ const focusSibling = (event: ReactKeyboardEvent<HTMLElement>) => {next = isTabEnabled(candidate) ? candidate : undefined;}}- next?.focus();+ if (!next) {+ return;+ }+ if (isScrollable) {+ next.focus({ preventScroll: true });+ revealInStrip(next);+ } else {+ next.focus();+ }};+const focusSiblingInScrollingStrip = (event: ReactKeyboardEvent<HTMLElement>) => focusSibling(event, true);+const focusSiblingInStrip = (event: ReactKeyboardEvent<HTMLElement>) => focusSibling(event, false);+/*** Wire caller-owned panels with segmentTabsPanelId/segmentTabsTabId. Active-tab clicks call onSelect again;* showActivePanel=false retains selection. trailing sits outside the tablist.@@ -71,6 +133,7 @@ export const SegmentTabs = <T extends string>({ariaLabel,idBase,isCompact = false,+ isScrollable = false,onSelect,showActivePanel = true,tabs,@@ -81,6 +144,12 @@ export const SegmentTabs = <T extends string>({idBase: string;/** Embedded strips (popovers, dialog headers) drop the panel-strip height and outer padding. */isCompact?: boolean;+ /**+ * Tabs keep their full labels and the strip scrolls sideways when they do not fit, instead of squeezing every tab.+ * The selected tab and a tab focused by the arrow keys are brought into view; a vertical wheel scrolls the strip, and+ * an end hiding tabs fades out.+ */+ isScrollable?: boolean;onSelect: (id: T) => void;showActivePanel?: boolean;tabs: readonly SegmentTab<T>[];@@ -97,13 +166,15 @@ export const SegmentTabs = <T extends string>({<HStackaria-label={ariaLabel}aria-orientation="horizontal"- css={TABLIST_CSS}+ ref={isScrollable ? attachScrollingTablist : undefined}+ css={isScrollable ? SCROLLING_TABLIST_CSS : TABLIST_CSS}flex="1"gap="0.5"minW="0"- overflow="hidden"+ overflowX={isScrollable ? 'auto' : 'hidden'}+ overflowY="hidden"role="tablist"- onKeyDown={focusSibling}+ onKeyDown={isScrollable ? focusSiblingInScrollingStrip : focusSiblingInStrip}>{tabs.map((tab, index) => (<Fragment key={tab.id}>@@ -126,6 +197,7 @@ export const SegmentTabs = <T extends string>({disabled={tab.disabled ?? false}id={tab.id}idBase={idBase}+ isScrollable={isScrollable}isSelected={tab.id === activeId}isShown={tab.id === activeId && showActivePanel}label={tab.label}@@ -146,6 +218,7 @@ const SegmentTabButton = <T extends string>({disabled,id,idBase,+ isScrollable,isSelected,isShown,label,@@ -155,16 +228,27 @@ const SegmentTabButton = <T extends string>({disabled: boolean;id: T;idBase: string;+ isScrollable: boolean;isSelected: boolean;/** Selected AND its panel is visible; a collapsed block keeps selection without the shown look. */isShown: boolean;label: ReactNode;onSelect: (id: T) => void;}) => {- const select = useCallback(() => onSelect(id), [id, onSelect]);+ const select = useCallback(+ (event: ReactMouseEvent<HTMLElement>) => {+ // A click on the already selected tab does not move selection, so the selected tab's ref cannot reveal it.+ if (isScrollable) {+ revealInStrip(event.currentTarget);+ }+ onSelect(id);+ },+ [id, isScrollable, onSelect]+ );const button = (<chakra.button+ ref={isScrollable && isSelected ? revealSelectedTab : undefined}aria-controls={isShown ? segmentTabsPanelId(idBase) : undefined}// Not native `disabled`: a selected tab with nothing to show keeps the tablist reachable.aria-disabled={disabled || undefined}@@ -173,6 +257,7 @@ const SegmentTabButton = <T extends string>({bg={isShown ? TAB_SHOWN_BG : 'transparent'}color={isShown ? 'fg' : 'fg.muted'}fontSize="md"+ flexShrink={isScrollable ? 0 : undefined}fontWeight="medium"h="7"id={segmentTabsTabId(idBase, id)}@@ -185,6 +270,7 @@ const SegmentTabButton = <T extends string>({transition="background var(--wb-motion-duration-fast), color var(--wb-motion-duration-fast)"type="button"_disabled={TAB_DISABLED_PROPS}+ _focusVisible={TAB_FOCUS_VISIBLE_PROPS}_hover={isShown ? undefined : TAB_HOVER_PROPS}onClick={disabled ? undefined : select}>diff --git a/invokeai/frontend/webv2/src/platform/ui/Select.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Select.browser.test.tsxindex 0d895204ce..301c6e4508 100644--- a/invokeai/frontend/webv2/src/platform/ui/Select.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Select.browser.test.tsx@@ -3,8 +3,9 @@ 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 { Field } from './Field';import { Select } from './Select';const RATIO_ITEMS = [@@ -18,6 +19,12 @@ const DETECTOR_ITEMS = [{ group: 'none', label: 'None: image is already an edge map', value: 'none' },];const DETECTOR_VALUE = ['canny'];+const SCHEDULER_ITEMS = [+ { label: 'Euler', value: 'euler' },+ { label: 'DPM++ 2M Karras with an unusually long descriptive name', value: 'dpmpp_2m_k' },+];+const EULER_VALUE = ['euler'];+const LONG_VALUE = ['dpmpp_2m_k'];const getDetectorGroup = (item: { group: string }) => item.group;const renderDetectorGroupLabel = (group: string) => (group === 'detectors' ? 'Detectors' : null);@@ -148,3 +155,124 @@ describe('Select', () => {expect(listbox.querySelector('[role="option"]')?.textContent).toContain('None');});});++describe('Select under an inside Field label', () => {+ let host: HTMLDivElement;+ let root: Root;+ const trigger = () => host.querySelector<HTMLButtonElement>('[data-scope="select"][data-part="trigger"]')!;+ const insideLabel = () => trigger().querySelector<HTMLElement>('#scheduler-field-label')!;+ const valueText = () => trigger().querySelector<HTMLElement>('[data-part="value-text"]')!;+ const mount = (+ field: { disabled?: boolean; error?: string; helpText?: string },+ value: string[],+ onValueChange = vi.fn()+ ) =>+ act(() => {+ root.render(+ <ChakraProvider value={system}>+ <Field id="scheduler-field" label="Scheduler" labelPlacement="inside" {...field}>+ <Select+ collection={createListCollection({ items: SCHEDULER_ITEMS })}+ value={value}+ onValueChange={onValueChange}+ />+ </Field>+ </ChakraProvider>+ );+ });++ beforeEach(() => {+ host = document.createElement('div');+ host.style.width = '220px';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('shows the label at the start of its box, names the trigger with it and describes it with the help text', async () => {+ await mount({ helpText: 'Sampler for each step' }, EULER_VALUE);++ // One box: no label above it, the label and the value side by side inside the trigger.+ expect(host.querySelector('label')).toBeNull();+ expect(insideLabel().textContent).toBe('Scheduler');+ expect(insideLabel().getBoundingClientRect().right).toBeLessThanOrEqual(valueText().getBoundingClientRect().left);+ expect(getComputedStyle(valueText()).textAlign).toBe('end');+ expect(valueText().textContent).toBe('Euler');+ await expect+ .element(page.getByRole('combobox', { exact: true, name: 'Scheduler' }))+ .toHaveAccessibleDescription('Sampler for each step');+ // The help line sits below the box.+ const help = host.querySelector<HTMLElement>('#scheduler-field-help')!;+ expect(help.getBoundingClientRect().top).toBeGreaterThanOrEqual(trigger().getBoundingClientRect().bottom);+ });++ it('opens from a click on the label and commits a choice', async () => {+ const onValueChange = vi.fn();+ await mount({}, EULER_VALUE, onValueChange);++ await userEvent.click(insideLabel());+ await expect.element(page.getByRole('listbox', { exact: true, name: 'Scheduler' })).toBeVisible();+ await userEvent.click(page.getByRole('option', { name: /^DPM\+\+ 2M Karras/ }));++ expect(onValueChange).toHaveBeenLastCalledWith(expect.objectContaining({ value: ['dpmpp_2m_k'] }));+ });++ it('truncates a long value before its label, short of the chevron', async () => {+ await mount({}, LONG_VALUE);++ const label = insideLabel();+ const value = valueText();+ expect(label.scrollWidth).toBeLessThanOrEqual(label.clientWidth);+ expect(value.scrollWidth).toBeGreaterThan(value.clientWidth);+ expect(getComputedStyle(value).textOverflow).toBe('ellipsis');+ const indicator = trigger().querySelector<HTMLElement>('[data-part="indicator"]')!;+ expect(value.getBoundingClientRect().right).toBeLessThanOrEqual(indicator.getBoundingClientRect().left);+ expect(indicator.getBoundingClientRect().right).toBeLessThanOrEqual(trigger().getBoundingClientRect().right);+ });++ it('caps a label longer than half the box so the value keeps the rest', async () => {+ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <Field label="A very long localized scheduler label that cannot fit" labelPlacement="inside">+ <Select collection={createListCollection({ items: SCHEDULER_ITEMS })} value={EULER_VALUE} />+ </Field>+ </ChakraProvider>+ );+ });++ const label = trigger().querySelector<HTMLElement>('span[id]')!;+ expect(label.scrollWidth).toBeGreaterThan(label.clientWidth);+ expect(label.getBoundingClientRect().width).toBeLessThanOrEqual(trigger().getBoundingClientRect().width / 2);+ expect(valueText().scrollWidth).toBeLessThanOrEqual(valueText().clientWidth);+ });++ it('dims its chevron once with the rest of the trigger when the field is disabled', async () => {+ const indicatorColor = () =>+ getComputedStyle(trigger().querySelector<HTMLElement>('[data-part="indicator"]')!).color;+ await mount({}, EULER_VALUE);+ const restingColor = indicatorColor();++ await mount({ disabled: true }, EULER_VALUE);+ expect(Number(getComputedStyle(trigger()).opacity)).toBeLessThan(1);+ expect(indicatorColor()).toBe(restingColor);+ });++ it('takes the field error as its invalid state and description, and the field disabled state', async () => {+ await mount({ error: 'Pick a scheduler' }, EULER_VALUE);++ expect(trigger().getAttribute('aria-invalid')).toBe('true');+ await expect+ .element(page.getByRole('combobox', { exact: true, name: 'Scheduler' }))+ .toHaveAccessibleDescription('Pick a scheduler');++ await mount({ disabled: true }, EULER_VALUE);+ expect(trigger().disabled).toBe(true);+ await userEvent.click(insideLabel(), { force: true });+ expect(document.querySelector('[role="listbox"]')).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Select.tsx b/invokeai/frontend/webv2/src/platform/ui/Select.tsxindex a41ed05c9b..b272e848ef 100644--- a/invokeai/frontend/webv2/src/platform/ui/Select.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Select.tsx@@ -12,6 +12,7 @@ import type { Key, ReactNode } from 'react';import { Portal, Select as ChakraSelect, Separator, useFieldContext } from '@chakra-ui/react';import { Fragment, useCallback, useRef } from 'react';+import { FieldInsideLabel, INSIDE_LABEL_INSET, useInsideFieldLabel } from './Field';import { Scrollable } from './Scrollable';const getDefaultItemKey = <T extends CollectionItem>(item: T, index: number): Key => {@@ -44,6 +45,26 @@ const partitionByGroup = <T,>(return runs;};+/**+ * With the chevron in the trigger's flow (an inside label, or a trigger sized to its value) the value fills the room+ * left before it, end-aligned and truncating on one line; rich value text (an icon and a name) aligns as one inline box+ * that can still shrink.+ */+const IN_FLOW_VALUE_TEXT_CSS = {+ display: 'block',+ flex: '1',+ maxW: 'none',+ minW: '0',+ overflow: 'hidden',+ textAlign: 'end',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ '& > *': { display: 'inline-flex', maxW: 'full', verticalAlign: 'middle' },+} as const;++/** The trigger already dims when disabled; the chevron inside it keeps its resting colour rather than dimming twice. */+const IN_TRIGGER_INDICATOR_CSS = { _disabled: { color: 'fg.muted' } } as const;+/** Fits the anchor's available space with the same headroom the settings selects use. */const DEFAULT_ITEMS_MAX_H = 'min(20rem, calc(var(--available-height) - 0.5rem))';@@ -64,6 +85,11 @@ export interface SelectProps<T extends CollectionItem> extends Omit<SelectRootPrgetItemKey?: (item: T, index: number) => Key;indicatorGroupProps?: SelectIndicatorGroupProps;itemIndicator?: boolean;+ /**+ * Sizes the select to its value instead of its container's width, for a select trailing its label in a row; cap it+ * with `maxW`. The chevron joins the trigger's flow, so a truncated value stops before it.+ */+ fitContent?: boolean;portalled?: boolean;positionerProps?: SelectPositionerProps;renderItem?: (item: T) => ReactNode;@@ -82,6 +108,7 @@ export const Select = <T extends CollectionItem>({indicatorGroupProps,itemsMaxH = DEFAULT_ITEMS_MAX_H,itemIndicator = true,+ fitContent = false,portalled = true,positionerProps,renderGroupLabel,@@ -93,6 +120,20 @@ export const Select = <T extends CollectionItem>({}: SelectProps<T>) => {// Inside Field, reuse its label ID; rendering another Label would duplicate it.const field = useFieldContext();+ const insideLabel = useInsideFieldLabel();+ // An inside label or a content-sized trigger keeps the chevron in the trigger's flow, so the value truncates+ // before it (or the trigger grows to hold it) instead of running under it.+ const isIndicatorInTrigger = insideLabel !== null || fitContent;+ // Zag names the trigger by the field's label but leaves its help and error text to the hidden select.+ const fieldControlProps = field?.getInputProps();+ const describedBy =+ [+ fieldControlProps?.['aria-describedby'],+ fieldControlProps?.['aria-errormessage'],+ triggerProps?.['aria-describedby'],+ ]+ .filter(Boolean)+ .join(' ') || undefined;const itemsRef = useRef<HTMLDivElement>(null);const scrollToIndexFn = useCallback(({ index }: { index: number }) => {const options = itemsRef.current?.querySelectorAll('[role="option"]');@@ -103,22 +144,35 @@ export const Select = <T extends CollectionItem>({<ChakraSelect.Rootcollection={collection}lazyMount+ minW={fitContent ? '0' : undefined}scrollToIndexFn={itemsMaxH ? scrollToIndexFn : undefined}unmountOnExit+ w={fitContent ? 'auto' : undefined}{...rootProps}// An empty list is nothing to choose from: the trigger disables instead of opening a blank menu.- disabled={rootProps.disabled || collection.items.length === 0}+ // An explicit prop would otherwise override the enclosing Field's disabled state.+ disabled={rootProps.disabled || field?.disabled || collection.items.length === 0}>{/* Materialize the trigger's aria-labelledby target; aria-label on Root would name a generic div instead. */}{ariaLabel && !field ? <ChakraSelect.Label srOnly>{ariaLabel}</ChakraSelect.Label> : null}<ChakraSelect.HiddenSelect /><ChakraSelect.Control>- <ChakraSelect.Trigger {...triggerProps}>- <ChakraSelect.ValueText {...valueTextProps}>{valueText}</ChakraSelect.ValueText>+ <ChakraSelect.Trigger+ ps={insideLabel ? INSIDE_LABEL_INSET : undefined}+ {...triggerProps}+ aria-describedby={describedBy}+ >+ {insideLabel ? <FieldInsideLabel label={insideLabel} /> : null}+ <ChakraSelect.ValueText css={isIndicatorInTrigger ? IN_FLOW_VALUE_TEXT_CSS : undefined} {...valueTextProps}>+ {valueText}+ </ChakraSelect.ValueText>+ {isIndicatorInTrigger ? <ChakraSelect.Indicator css={IN_TRIGGER_INDICATOR_CSS} /> : null}</ChakraSelect.Trigger>- <ChakraSelect.IndicatorGroup {...indicatorGroupProps}>- <ChakraSelect.Indicator />- </ChakraSelect.IndicatorGroup>+ {isIndicatorInTrigger ? null : (+ <ChakraSelect.IndicatorGroup {...indicatorGroupProps}>+ <ChakraSelect.Indicator />+ </ChakraSelect.IndicatorGroup>+ )}</ChakraSelect.Control><Portal disabled={!portalled}><ChakraSelect.Positioner {...positionerProps}>diff --git a/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsx b/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsxindex 2a1bcd653a..9f31c02d0e 100644--- a/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/StatusWidgetChip.tsx@@ -18,11 +18,19 @@ export interface StatusWidgetChipProgress {value: number | null;}+/** Clips the hairline to the chip's rounded corners, which match its host's hover and active fill. */+const PROGRESS_CLIP_SX: SystemStyleObject = {+ borderRadius: 'inherit',+ inset: 0,+ overflow: 'hidden',+ pointerEvents: 'none',+ position: 'absolute',+};+const PROGRESS_TRACK_SX: SystemStyleObject = {bottom: 0,height: '2px',insetInline: 0,- pointerEvents: 'none',position: 'absolute',};@@ -70,15 +78,17 @@ export const StatusWidgetChip = ({<Icon as={icon} boxSize="3" /><Text whiteSpace="nowrap">{children}</Text>{progress ? (- <Box aria-hidden="true" css={PROGRESS_TRACK_SX} overflow="hidden">- {progress.value === null ? (- <>- <Box css={PROGRESS_FILL_SX} opacity={0.35} position="absolute" width="full" />- <Box css={PROGRESS_SWEEP_SX} position="absolute" />- </>- ) : (- <Box css={PROGRESS_FILL_SX} width={`${progress.value * 100}%`} />- )}+ <Box aria-hidden="true" css={PROGRESS_CLIP_SX}>+ <Box css={PROGRESS_TRACK_SX}>+ {progress.value === null ? (+ <>+ <Box css={PROGRESS_FILL_SX} opacity={0.35} position="absolute" width="full" />+ <Box css={PROGRESS_SWEEP_SX} position="absolute" />+ </>+ ) : (+ <Box css={PROGRESS_FILL_SX} width={`${progress.value * 100}%`} />+ )}+ </Box></Box>) : null}</HStack>diff --git a/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsxindex 9080e94c7f..53460d7d48 100644--- a/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Tooltip.browser.test.tsx@@ -1,7 +1,7 @@import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { CameraIcon } from 'lucide-react';-import { act, useCallback, useRef, useState } from 'react';+import { Activity, act, useCallback, useRef, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';@@ -171,3 +171,52 @@ it('lets a click through an open tip to the control under it, such as the next rexpect(onNextClick).toHaveBeenCalledOnce();});++/** Two sections kept alive by Activity, like the launchpad's pages: the tooltipped button switches to the other one. */+const Sections = () => {+ const [isOtherShown, setIsOtherShown] = useState(false);+ const showOther = useCallback(() => setIsOtherShown(true), []);+ const showFirst = useCallback(() => setIsOtherShown(false), []);++ return (+ <>+ <button type="button" onClick={showFirst}>+ First section+ </button>+ <Activity mode={isOtherShown ? 'hidden' : 'visible'}>+ <Tooltip content="Open the other section">+ <button aria-label="Other section" type="button" onClick={showOther}>+ Go+ </button>+ </Tooltip>+ </Activity>+ </>+ );+};++it('shows a tip again only when hovered after its section was hidden mid-fade', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <Sections />+ </ChakraProvider>+ )+ );+ const shownTip = () =>+ [...document.querySelectorAll<HTMLElement>('[role="tooltip"]')].find((tip) => tip.checkVisibility());+ const trigger = host.querySelector<HTMLButtonElement>('button[aria-label="Other section"]')!;++ await userEvent.hover(trigger);+ await expect.poll(() => shownTip()?.textContent).toBe('Open the other section');+ // The press closes the tip and the click hides its section before the fade ends.+ await act(() => userEvent.click(trigger));+ await act(() => userEvent.click(host!.querySelector('button')!));++ await expect.poll(shownTip).toBeUndefined();+ // The pointer left while the section was hidden; the next hover still opens the tip.+ await userEvent.hover(trigger);+ await expect.poll(() => shownTip()?.textContent).toBe('Open the other section');+});diff --git a/invokeai/frontend/webv2/src/platform/ui/VendoredIcon.tsx b/invokeai/frontend/webv2/src/platform/ui/VendoredIcon.tsxindex 7f5d5dfb4c..b86b6ae425 100644--- a/invokeai/frontend/webv2/src/platform/ui/VendoredIcon.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/VendoredIcon.tsx@@ -100,7 +100,8 @@ export const GradientIcon = createVendoredIcon({],slug: 'gradient',title: 'Gradient',- viewBox: '0 0 32 32',+ // Cropped from Carbon's 0 0 32 32 so the glyph fills its box as far as the stroke icons beside it (10/12 of it).+ viewBox: '1.6 1.6 28.8 28.8',});export const LightbulbFilamentIcon = createVendoredIcon({diff --git a/invokeai/frontend/webv2/src/platform/ui/arrowJoint.testing.ts b/invokeai/frontend/webv2/src/platform/ui/arrowJoint.testing.tsnew file mode 100644index 0000000000..a0446381b4--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/arrowJoint.testing.ts@@ -0,0 +1,86 @@+import { server } from 'vitest/browser';++declare module 'vitest/browser' {+ interface BrowserCommands {+ /** Captures a rect of the test frame at device pixels, as base64 PNG; defined in `vitest.browser.config.mts`. */+ captureDevicePixels: (+ rect: { height: number; width: number; x: number; y: number },+ frameWidth: number+ ) => Promise<string>;+ /** Emulates a display's device pixel ratio, `null` restores it; defined in `vitest.browser.config.mts`. */+ emulateDevicePixelRatio: (ratio: number | null) => Promise<void>;+ }+}++/** Per-channel difference two pixels may have and still read as the same colour. */+const TOLERANCE = 4;++const sameColor = (a: readonly number[], b: readonly number[]) =>+ a.slice(0, 3).every((channel, i) => Math.abs(channel - b[i]!) <= TOLERANCE);++const hex = (pixel: readonly number[]) =>+ `#${pixel+ .slice(0, 3)+ .map((channel) => channel.toString(16).padStart(2, '0'))+ .join('')}`;++/**+ * Finds the pixels where an arrowed surface's edge shows through its arrow's base. At device resolution, it scans the+ * content's edge band (its border and the shading just inside it, 3px deep) across the middle of the tip's base. Each+ * pixel there must be the tip's own fill or what the content shows beyond the band at that point: its background, or+ * a child flush with the edge. Past the first device row inside the border, only the latter, so the tip never paints+ * over the content's children. Returns the offending pixels, described; an empty list is a seamless joint.+ */+export const findArrowJointSeams = async (content: HTMLElement, tip: HTMLElement): Promise<string[]> => {+ const side = content.dataset.placement?.split('-')[0] ?? 'bottom';+ const box = content.getBoundingClientRect();+ const tipBox = tip.getBoundingClientRect();+ // A region around the tip whose origin falls on a device pixel at common ratios (1, 1.25, 1.5, 2).+ const region = {+ height: 48,+ width: 48,+ x: Math.floor((tipBox.left + tipBox.right) / 2 / 4) * 4 - 24,+ y: Math.floor((tipBox.top + tipBox.bottom) / 2 / 4) * 4 - 24,+ };+ const png = await server.commands.captureDevicePixels(region, document.documentElement.clientWidth);+ const bitmap = await createImageBitmap(await (await fetch(`data:image/png;base64,${png}`)).blob());+ const scale = bitmap.width / region.width;+ const context = new OffscreenCanvas(bitmap.width, bitmap.height).getContext('2d')!;+ context.drawImage(bitmap, 0, 0);++ const vertical = side === 'top' || side === 'bottom';+ // The content's outer edge facing the trigger and the tip's centre along it, in the region's device pixels.+ const edge = {+ bottom: (box.top - region.y) * scale,+ left: (box.right - region.x) * scale,+ right: (box.left - region.x) * scale,+ top: (box.bottom - region.y) * scale,+ }[side]!;+ const inward = side === 'bottom' || side === 'right' ? 1 : -1;+ const along = vertical+ ? ((tipBox.left + tipBox.right) / 2 - region.x) * scale+ : ((tipBox.top + tipBox.bottom) / 2 - region.y) * scale;+ // Device row `depth` rows inside the edge: 0 is the content's outermost row, negative is out in the tip.+ const across = (depth: number) => Math.round(edge) + (inward === 1 ? depth : -1 - depth);+ const pixel = (depth: number, offset: number) => {+ const a = Math.floor(along + offset);+ const b = across(depth);+ return [...context.getImageData(vertical ? a : b, vertical ? b : a, 1, 1).data];+ };++ const band = Math.round(3 * scale);+ const halfSpan = Math.round(4 * scale);+ const tipFill = pixel(-band, 0);+ const seams: string[] = [];+ for (let depth = 0; depth < band; depth++) {+ for (let offset = -halfSpan; offset <= halfSpan; offset++) {+ const seen = pixel(depth, offset);+ const beyond = pixel(band + 1, offset);+ const allowed = depth <= 1 ? [beyond, tipFill] : [beyond];+ if (!allowed.some((color) => sameColor(seen, color))) {+ seams.push(`depth ${depth}, offset ${offset}: ${hex(seen)}, not ${allowed.map(hex).join(' or ')}`);+ }+ }+ }+ return seams;+};diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsxindex 872821128e..4b5477a62f 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.browser.test.tsx@@ -295,18 +295,18 @@ describe('FeatureHint', () => {it('stays open through a rest on the arrow, which lies outside the card body', async () => {const { trigger } = await renderHint(LEFT_PANEL_CSS);const card = await openHintCard(trigger);- const arrow = document.querySelector<HTMLElement>('[data-scope="hover-card"][data-part="arrow"]')!;- const arrowRect = arrow.getBoundingClientRect();+ const tip = document.querySelector<HTMLElement>('[data-scope="hover-card"][data-part="arrow-tip"]')!;+ const tipRect = tip.getBoundingClientRect();const label = trigger.getBoundingClientRect();const exit = { x: label.right - 2, y: label.top + label.height / 2 };- // The arrow straddles the card's edge: its outer half is clear of the content rect.- const outer = { x: arrowRect.left + 1, y: arrowRect.top + arrowRect.height / 2 };+ // The tip straddles the card's edge, drawn only outside it: a point on its outer half is clear of the content+ // rect, and the tip itself is what the pointer rests on there.+ const outer = { x: tipRect.left + 3, y: tipRect.top + tipRect.height / 2 };expect(outer.x).toBeLessThan(card.left);+ expect(document.elementFromPoint(outer.x, outer.y)).toBe(tip);await movePointerAlong(exit, { x: outer.x - 6, y: outer.y }, MOVE);- await act(() =>- userEvent.hover(arrow, { position: { x: outer.x - arrowRect.left, y: outer.y - arrowRect.top } })- );+ await act(() => userEvent.hover(tip, { position: { x: outer.x - tipRect.left, y: outer.y - tipRect.top } }));// Past the corridor's grace window and the close delay after it.await settle(1500);// The title, the card's first paragraph.diff --git a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.tsx b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.tsxindex cfac5dcea7..c485289f10 100644--- a/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/hints/FeatureHint.tsx@@ -1,4 +1,4 @@-import type { HTMLAttributes, PointerEvent, ReactElement, ReactNode } from 'react';+import type { HTMLAttributes, PointerEvent, ReactElement, ReactNode, SyntheticEvent } from 'react';import {HoverCard,@@ -68,7 +68,7 @@ const HintCard = ({ hint, onDisable }: { hint: FeatureHintId; onDisable: (() =><Separator /><HStack gap="2" minH="4">{onDisable && (- <Button color="fg.subtle" fontSize="xs" h="auto" px="1" size="sm" variant="plain" onClick={onDisable}>+ <Button size="xs" variant="outline" onClick={onDisable}>{t('common.dontShowMeThese')}</Button>)}@@ -86,6 +86,27 @@ const HintCard = ({ hint, onDisable }: { hint: FeatureHintId; onDisable: (() =>);};+const stopPropagation = (event: SyntheticEvent) => event.stopPropagation();++/**+ * The card portals out of its label but stays inside it in the React tree, where its events would bubble on to the+ * label's ancestors: a press on the card would open a Select whose trigger holds the label, the trigger's keydown would+ * take Enter from the card's button and link, and a double-click in it would reset a ScrubberField. Stopping these+ * types also stops their native event at the portal container, so non-capture document and window listeners miss them+ * too: app hotkeys don't fire while focus is in the card. Capture-phase listeners, such as Zag's dismissal, still see+ * them. Release events pass, so a drag or press tracked on the document still ends.+ */+const CARD_EVENT_BOUNDARY = {+ onBlur: stopPropagation,+ onClick: stopPropagation,+ onContextMenu: stopPropagation,+ onDoubleClick: stopPropagation,+ onFocus: stopPropagation,+ onKeyDown: stopPropagation,+ onMouseDown: stopPropagation,+ onPointerDown: stopPropagation,+} satisfies HTMLAttributes<HTMLElement>;+type ExclusionHandlers = Pick<HTMLAttributes<HTMLElement>, 'onPointerEnter' | 'onPointerLeave'>;const ExclusionContext = createContext<ExclusionHandlers | null>(null);@@ -311,7 +332,7 @@ export const FeatureHint = ({ children, hint }: FeatureHintProps) => {</ExclusionProvider><Portal><HoverCard.Positioner>- <HoverCard.Content ref={setCard}>+ <HoverCard.Content ref={setCard} {...CARD_EVENT_BOUNDARY}><HoverCard.Arrow><HoverCard.ArrowTip /></HoverCard.Arrow>diff --git a/invokeai/frontend/webv2/src/platform/ui/list/List.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/list/List.browser.test.tsxindex ca9ba2a70f..d06a7297c6 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/List.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/List.browser.test.tsx@@ -620,3 +620,88 @@ describe('List states', () => {expect(host.querySelector('[role="list"]')).toBeNull();});});++describe('a row editing its title inside a List', () => {+ const EditingHarness = ({ editingKey }: { editingKey: string | null }) => (+ <ChakraProvider value={system}>+ <button type="button">Before the list</button>+ <List+ density="comfortable"+ emptyState={<span>nothing</span>}+ label="subjects"+ renderItem={(item: Item, rowProps: ListRowProps) => (+ <ListItem+ {...rowProps}+ title={item.name}+ titleEditor={item.id === editingKey ? <input aria-label="Rename" defaultValue={item.name} /> : undefined}+ onPress={() => undefined}+ />+ )}+ rows={rowsOf(section('main', 'Main', 5))}+ />+ </ChakraProvider>+ );++ it('leaves the field its own Home, End and arrows, and gives the row its tab stop back after', async () => {+ await render(<EditingHarness editingKey={null} />);+ // The List's tab stop is on the second row, as after using it.+ await act(() => primaryButtons()[1]!.focus());++ await render(<EditingHarness editingKey="main-1" />);+ const field = host.querySelector<HTMLInputElement>('input[aria-label="Rename"]')!;+ await act(() => field.focus());+ field.setSelectionRange(2, 2);++ await act(() => userEvent.keyboard('{End}'));+ expect(field.selectionStart).toBe(field.value.length);+ await act(() => userEvent.keyboard('{Home}'));+ expect(field.selectionStart).toBe(0);+ await act(() => userEvent.keyboard('{ArrowDown}{ArrowUp}'));+ await settleFrame();+ expect(document.activeElement).toBe(field);++ // Editing done, the row's button is back and is the List's one tab stop.+ await render(<EditingHarness editingKey={null} />);+ const stops = primaryButtons().filter((button) => button.tabIndex === 0);+ expect(stops).toHaveLength(1);+ expect(stops[0]?.textContent).toContain('Main 1');++ await act(() => host.querySelector<HTMLButtonElement>('button:not([data-list-primary])')!.focus());+ await act(() => userEvent.tab());+ expect(document.activeElement).toBe(stops[0]);+ });+});++describe('keys from a row selection checkbox', () => {+ it('still move between rows: arrows, Home and End', async () => {+ const onCheckedChange = vi.fn();+ await render(<Harness rows={rowsOf(section('main', 'Main', 5))} onCheckedChange={onCheckedChange} />);+ const checkbox = (index: number) =>+ host+ .querySelectorAll<HTMLElement>('[role="listitem"]')+ [index]!.querySelector<HTMLInputElement>('input[type="checkbox"]')!;++ await act(() => checkbox(0).focus());+ await act(() => userEvent.keyboard(' '));+ expect(onCheckedChange).toHaveBeenCalledOnce();++ await act(() => userEvent.keyboard('{ArrowDown}'));+ await settleFrame();+ expect(document.activeElement).toBe(primaryButtons()[1]);++ await act(() => checkbox(1).focus());+ await act(() => userEvent.keyboard('{End}'));+ await settleFrame();+ expect(document.activeElement?.textContent).toContain('Main 4');++ await act(() => checkbox(4).focus());+ await act(() => userEvent.keyboard('{ArrowUp}'));+ await settleFrame();+ expect(document.activeElement?.textContent).toContain('Main 3');++ await act(() => checkbox(3).focus());+ await act(() => userEvent.keyboard('{Home}'));+ await settleFrame();+ expect(document.activeElement).toBe(primaryButtons()[0]);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/list/List.tsx b/invokeai/frontend/webv2/src/platform/ui/list/List.tsxindex 366ac299c0..77fa4b4bca 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/List.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/List.tsx@@ -106,6 +106,11 @@ export interface ListProps<T> {renderItem: (item: T, rowProps: ListRowProps) => ReactNode;/** Key of the row whose detail is open; it is the initial keyboard target. */activeKey?: string | null;+ /**+ * Keyboard target while no row has been focused and none is active, such as the first row that can be used when+ * earlier ones are disabled; without it, the first row.+ */+ defaultFocusKey?: string | null;/** Row pitch; fixed for the list's lifetime, so change it with a keyed remount. */density?: ListDensity;/**@@ -166,8 +171,25 @@ const primaryOf = (viewport: HTMLElement, key: string): HTMLElement | null =>* Virtualized list with pinned section headers and a roving tabindex. Headers and items share one flat index* space; the header at the top of the visible range renders in flow as a sticky element, pushed out by the next.*/+/** Inputs whose arrows, Home and End do nothing of their own: a row's selection checkbox and button-like inputs. */+const KEYLESS_INPUT_TYPES = new Set(['button', 'checkbox', 'color', 'file', 'image', 'reset', 'submit']);++/**+ * Whether a focused control uses ArrowUp, ArrowDown, Home and End itself: a field in a row (a title editor moves its+ * caret), a select, or a radio or range input. The List leaves those keys to it and moves between rows from anything+ * else, the selection checkbox included.+ */+const usesNavigationKeys = (target: HTMLElement): boolean => {+ if (target.isContentEditable || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement) {+ return true;+ }++ return target instanceof HTMLInputElement && !KEYLESS_INPUT_TYPES.has(target.type);+};+export const List = <T,>({activeKey = null,+ defaultFocusKey = null,density = 'regular',dividers = false,emptyState,@@ -222,14 +244,16 @@ export const List = <T,>({const isMeasured = rowHeight === 'measured';const hasHeaders = headerIndexes.length > 0;- // The roving target survives filtering: fall back to the active row, then the first item.+ // The roving target survives filtering: fall back to the active row, then the default one, then the first item.const focusKeyIsStale = focusKey !== null && !indexByKey.has(focusKey);const resolvedFocusKey =!focusKeyIsStale && focusKey !== null? focusKey: activeKey !== null && indexByKey.has(activeKey)? activeKey- : firstItemKey;+ : defaultFocusKey !== null && indexByKey.has(defaultFocusKey)+ ? defaultFocusKey+ : firstItemKey;const focusIndex = resolvedFocusKey === null ? -1 : (indexByKey.get(resolvedFocusKey) ?? -1);// Keep the pinned header and the focused row mounted whatever the scroll position: focus must never fall off@@ -361,7 +385,9 @@ export const List = <T,>({);const handleKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {- if (event.defaultPrevented || !(event.target as HTMLElement).closest('[data-list-row]')) {+ const target = event.target as HTMLElement;++ if (event.defaultPrevented || !target.closest('[data-list-row]') || usesNavigationKeys(target)) {return;}diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsxindex de8450ddf9..4bdedf34aa 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListChrome.browser.test.tsx@@ -303,6 +303,32 @@ describe('list dividers', () => {expect(hairlines().map((line) => getComputedStyle(line).opacity)).toEqual(['1', '1']);});+ it('keeps a disabled row and its neighbouring dividers unchanged on hover', async () => {+ // Transitions finish within a frame, so hidden hairlines would already read as hidden.+ document.documentElement.dataset.reduceMotion = 'true';+ try {+ await render(+ <ListStack dividers label="subjects">+ <ListItem title="one" onPress={vi.fn()} />+ <ListItem isDisabled title="two" onPress={vi.fn()} />+ <ListItem title="three" onPress={vi.fn()} />+ </ListStack>+ );+ const row = host.querySelectorAll<HTMLElement>('[data-list-surface]')[1]!;+ const background = getComputedStyle(row).backgroundColor;++ // Force past Playwright's actionability check: the row is aria-disabled on purpose.+ await userEvent.hover(row.querySelector('button')!, { force: true });+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ expect(getComputedStyle(row).backgroundColor).toBe(background);+ expect(hairlines().map((line) => getComputedStyle(line).opacity)).toEqual(['1', '1']);+ } finally {+ delete document.documentElement.dataset.reduceMotion;+ }+ });+it('opens a menu-only row from keyboard, assistive-tech, and touch activation, but not a mouse click', async () => {const onContextMenu = vi.fn();await render(diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsxindex d222ea6da5..ade38f17fd 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListDivider.tsx@@ -36,7 +36,7 @@ const IN_SLOT_CSS = {// A row shows its pointed fill while hovered or while its context menu is open; the hairlines either side of it hide// so that fill reads as one surface rather than a band between lines. `:has()` cannot nest, so a row wrapped by its// caller (menu state on a descendant) is matched as "a sibling containing it" instead.-const POINTED = '[data-list-surface]:not([data-static]):is(:hover, [data-menu-open])';+const POINTED = '[data-list-surface]:not([data-static], [data-disabled]):is(:hover, [data-menu-open])';const HIDDEN = { opacity: 0 } as const;/** For a container of in-flow rows and dividers (`ListStack`); rows may be wrapped by their caller. */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 28d73cff10..1566038b4e 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@@ -107,6 +107,81 @@ describe('ListItem', () => {expect(surface()).not.toBe(resting);});+ it('keeps a disabled row focusable but inert: no press, checkbox, menu, intent, actions, or hover fill', async () => {+ const onAction = vi.fn();+ const onCheckedChange = vi.fn();+ const onContextMenu = vi.fn();+ const onIntent = vi.fn();+ const onPress = vi.fn();+ const surface = () => getComputedStyle(primary().parentElement!).backgroundColor;++ // Transitions finish within a frame, so a hover fill would already show when the background is read.+ document.documentElement.dataset.reduceMotion = 'true';+ try {+ await userEvent.unhover(document.body);+ await render(+ <ListItem+ actions={+ <button type="button" onClick={onAction}>+ Install+ </button>+ }+ isDisabled+ title="Too new"+ onCheckedChange={onCheckedChange}+ onContextMenu={onContextMenu}+ onIntent={onIntent}+ onPress={onPress}+ />+ );+ const resting = surface();++ expect(primary().getAttribute('aria-disabled')).toBe('true');+ expect(primary().hasAttribute('aria-haspopup')).toBe(false);+ await act(() => primary().focus());+ expect(document.activeElement).toBe(primary());++ // Force past Playwright's actionability checks: disabled and inert controls are exactly what is under test.+ await userEvent.hover(primary(), { force: true });+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ expect(surface()).toBe(resting);+ await userEvent.click(primary(), { force: true });+ await userEvent.keyboard('{Enter}');+ await act(() => primary().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })));+ await userEvent.click(host.querySelector<HTMLElement>('[data-part="control"]')!, { force: true });+ await userEvent.click(+ [...host.querySelectorAll('button')].find((button) => button.textContent === 'Install')!,+ { force: true }+ );++ expect(onPress).not.toHaveBeenCalled();+ expect(onCheckedChange).not.toHaveBeenCalled();+ expect(onContextMenu).not.toHaveBeenCalled();+ expect(onIntent).not.toHaveBeenCalled();+ expect(onAction).not.toHaveBeenCalled();+ } finally {+ delete document.documentElement.dataset.reduceMotion;+ }+ });++ it('dims a disabled row’s content but draws its keyboard focus ring at full strength', async () => {+ await render(<ListItem isDisabled title="Too new" onCheckedChange={vi.fn()} onPress={vi.fn()} />);+ const row = primary().parentElement!;++ // Tab past the disabled checkbox onto the row button, so the ring is keyboard focus-visible.+ await act(() => (document.activeElement as HTMLElement | null)?.blur());+ await userEvent.keyboard('{Tab}');+ expect(document.activeElement).toBe(primary());++ expect(getComputedStyle(row).outlineStyle).toBe('solid');+ expect(getComputedStyle(row).outlineWidth).toBe('2px');+ expect(getComputedStyle(row).opacity).toBe('1');+ // Checkbox slot and primary button: everything the row shows.+ expect([...row.children].map((slot) => getComputedStyle(slot).opacity)).toEqual(['0.5', '0.5']);+ });+it('names its primary button by id, and the popup it discloses while expanded, for menus opened from outside', async () => {await render(<ListItem controls="row-a-menu" id="row-a" title="A workflow" onPress={vi.fn()} />);@@ -196,6 +271,53 @@ describe('ListItem', () => {expect(title.getBoundingClientRect().height).toBe(singleLineHeight);expect(title.textContent).toContain('third line');});++ it('edits the title in place outside any button, at the same height, without the row menu', async () => {+ const onContextMenu = vi.fn();+ const row = (titleEditor?: ReactElement) => (+ <ListItem+ actions={<button type="button">Toggle</button>}+ density="snug"+ description="Summary"+ leading={<span style={{ display: 'block', height: 36, width: 36 }} />}+ title="Hero pose"+ titleEditor={titleEditor}+ onContextMenu={onContextMenu}+ />+ );++ await render(row());+ const surface = host.querySelector<HTMLElement>('[role="listitem"]')!;+ const restingHeight = surface.getBoundingClientRect().height;++ expect(primary().tagName).toBe('BUTTON');+ expect(primary().getAttribute('aria-haspopup')).toBe('menu');++ await render(row(<input aria-label="Rename" defaultValue="Hero pose" style={{ height: 20, minWidth: 0 }} />));+ const field = host.querySelector<HTMLInputElement>('input[aria-label="Rename"]')!;++ // The field takes the title's place inside the primary area, which no longer announces itself as a button.+ expect(primary().tagName).toBe('DIV');+ expect(primary().hasAttribute('tabindex')).toBe(false);+ expect(primary().hasAttribute('aria-haspopup')).toBe(false);+ expect(primary().contains(field)).toBe(true);+ expect(field.closest('button')).toBeNull();+ expect(host.textContent).not.toContain('Hero pose');+ expect(host.textContent).toContain('Summary');+ expect(host.querySelector('[role="listitem"]')).toBe(surface);+ expect(surface.getBoundingClientRect().height).toBe(restingHeight);++ // A right-click in the field keeps the browser's text menu instead of opening the row's.+ const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 });+ field.dispatchEvent(event);+ expect(event.defaultPrevented).toBe(false);+ expect(onContextMenu).not.toHaveBeenCalled();++ // Done editing, the title and its button come back.+ await render(row());+ expect(primary().tagName).toBe('BUTTON');+ expect(host.textContent).toContain('Hero pose');+ });});describe('list checkboxes inside a form Field', () => {diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsxindex d68b1c6db8..dcf5b15828 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx@@ -22,6 +22,14 @@ export interface ListContextMenuAnchor {export interface ListItemProps {title: string;+ /**+ * An editor shown in place of the title, such as a rename field; it names itself. While set, the primary area is a+ * plain container instead of a button, since a field cannot sit inside a button, and the row opens no context menu,+ * so the field keeps the browser's text menu. Size it to the title's line so the row keeps its height. Inside a `List`+ * the field keeps its own arrows, Home and End; the caller ends the edit (Enter, Escape, blur) and moves focus back+ * to the row, whose button returns with the List's tab stop.+ */+ titleEditor?: ReactNode;/** Identifiers keep their tail visible; prose keeps its start. */titleTruncate?: 'middle' | 'end';/** Media or icon before the text; size it for the density (36px at comfortable and snug). */@@ -46,6 +54,12 @@ export interface ListItemProps {isChecked?: boolean;/** Shown but inert while its page is being replaced; focus is kept so paging does not lose it. */isBusy?: boolean;+ /**+ * Shown dimmed and inert because the item itself cannot be used; say why in the row's text (a badge, say). Only its+ * primary button stays focusable, so a List's arrow keys still reach it and assistive tech reads the reason with its+ * name; press, checkbox, context menu, intent, actions and detail are all off.+ */+ isDisabled?: boolean;/** The row discloses content below itself; announced with aria-expanded. */isExpanded?: boolean;/** This row's context menu is open; the row keeps its hover surface so it is clear what the menu acts on. */@@ -105,6 +119,7 @@ export const ListItem = ({isActive = false,isBusy = false,isChecked = false,+ isDisabled = false,isExpanded,isMenuOpen = false,itemKey,@@ -114,6 +129,7 @@ export const ListItem = ({setSize,tabIndex = 0,title,+ titleEditor,titleTruncate = 'middle',trailing,onCheckedChange,@@ -135,7 +151,10 @@ export const ListItem = ({// A row with actions is pointed like an interactive one, so its buttons read as belonging to it; only a row with// nothing to act on stays static.const isStatic = !isInteractive && (actions === undefined || actions === null);- const isPrimaryExpanded = onContextMenu && !onPress ? isMenuOpen : isExpanded;+ const isEditingTitle = titleEditor !== undefined && titleEditor !== null;+ const menu = isDisabled || isEditingTitle ? undefined : onContextMenu;+ const intent = isDisabled ? undefined : onIntent;+ const isPrimaryExpanded = menu && !onPress ? isMenuOpen : isExpanded;const openContextMenu = useCallback((row: HTMLElement, point?: { x: number; y: number }) => {@@ -202,7 +221,7 @@ export const ListItem = ({const isVirtualClick = (event.nativeEvent as { mozInputSource?: number }).mozInputSource === 0;const isMouseClick = pressPointerType.current === 'mouse' && event.detail > 0 && !isVirtualClick;pressPointerType.current = null;- if (isBusy) {+ if (isBusy || isDisabled) {return;}if (onPress) {@@ -211,7 +230,7 @@ export const ListItem = ({openContextMenu(event.currentTarget.parentElement);}},- [isBusy, onPress, openContextMenu]+ [isBusy, isDisabled, onPress, openContextMenu]);// Plain text keeps to its line; a node (badge row, figures) lays itself out.const descriptionCss = useMemo(@@ -228,12 +247,16 @@ export const ListItem = ({{leading}<chakra.span css={styles.body}><chakra.span css={styles.titleLine}>- <MiddleTruncate- as="span"- css={styles.title}- tailGraphemes={titleTruncate === 'end' ? 0 : undefined}- text={title}- />+ {isEditingTitle ? (+ titleEditor+ ) : (+ <MiddleTruncate+ as="span"+ css={styles.title}+ tailGraphemes={titleTruncate === 'end' ? 0 : undefined}+ text={title}+ />+ )}{badges !== undefined && badges !== null ? <chakra.span css={styles.badges}>{badges}</chakra.span> : null}</chakra.span>{description !== undefined && description !== null ? (@@ -250,12 +273,13 @@ export const ListItem = ({aria-setsize={setSize}css={styles.root}data-busy={isBusy || undefined}+ data-disabled={isDisabled || undefined}data-list-row={itemKey}data-list-surface=""data-menu-open={isMenuOpen || undefined}data-static={isStatic || undefined}role={role}- onContextMenu={onContextMenu ? handleContextMenu : undefined}+ onContextMenu={menu ? handleContextMenu : undefined}>{onCheckedChange ? (<chakra.div css={styles.check}>@@ -264,7 +288,7 @@ export const ListItem = ({checked={isChecked}ids={checkIds}colorPalette="accent"- disabled={isBusy}+ disabled={isBusy || isDisabled}size="sm"onCheckedChange={handleCheckedChange}>@@ -273,13 +297,13 @@ export const ListItem = ({</Checkbox.Root></chakra.div>) : null}- {isInteractive ? (+ {isInteractive && !isEditingTitle ? (<chakra.buttonaria-controls={isPrimaryExpanded ? controls : undefined}aria-current={isActive || undefined}- aria-disabled={isBusy || undefined}+ aria-disabled={isBusy || isDisabled || undefined}aria-expanded={isPrimaryExpanded}- aria-haspopup={onContextMenu && !onPress ? 'menu' : undefined}+ aria-haspopup={menu && !onPress ? 'menu' : undefined}aria-label={pressLabel}css={styles.primary}data-list-primary=""@@ -287,20 +311,28 @@ export const ListItem = ({tabIndex={tabIndex}type="button"onClick={handlePress}- onFocus={onIntent}+ onFocus={intent}onPointerDown={onPress ? undefined : handlePointerDown}- onPointerEnter={onIntent}+ onPointerEnter={intent}>{content}</chakra.button>) : (- // Static rows (nothing to press, no menu) must not announce themselves as buttons.+ // Static rows (nothing to press, no menu) and a row editing its title must not announce themselves as buttons.<chakra.div aria-current={isActive || undefined} css={styles.primary} data-list-primary="">{content}</chakra.div>)}- {actions !== undefined && actions !== null ? <chakra.div css={styles.actions}>{actions}</chakra.div> : null}- {detail !== undefined && detail !== null ? <chakra.div css={styles.detail}>{detail}</chakra.div> : null}+ {actions !== undefined && actions !== null ? (+ <chakra.div css={styles.actions} inert={isDisabled || undefined}>+ {actions}+ </chakra.div>+ ) : null}+ {detail !== undefined && detail !== null ? (+ <chakra.div css={styles.detail} inert={isDisabled || undefined}>+ {detail}+ </chakra.div>+ ) : null}</chakra.div>);};diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListSectionHeader.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListSectionHeader.tsxindex e377e8be10..51148ffe0b 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/ListSectionHeader.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListSectionHeader.tsx@@ -5,9 +5,18 @@ import { useMemo } from 'react';/** Fixed so virtualized lists can place headers without measuring them. */export const LIST_SECTION_HEADER_HEIGHT_PX = 32;-export const ListSectionHeader = ({ count, label }: { count?: number; label: string }) => {+export const ListSectionHeader = ({+ count,+ label,+ placement = 'list',+}: {+ count?: number;+ label: string;+ /** `bar` centres the label for a header row that also holds controls; `list` sits it low, above its rows. */+ placement?: 'bar' | 'list';+}) => {const recipe = useSlotRecipe({ recipe: listSectionHeaderSlotRecipe });- const styles = useMemo(() => recipe({}), [recipe]);+ const styles = useMemo(() => recipe({ placement }), [placement, recipe]);return (<chakra.div css={styles.root}>diff --git a/invokeai/frontend/webv2/src/platform/ui/list/SortableListStack.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/list/SortableListStack.browser.test.tsxnew file mode 100644index 0000000000..9d21a9f679--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/SortableListStack.browser.test.tsx@@ -0,0 +1,227 @@+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop */+import { ChakraProvider, Portal } from '@chakra-ui/react';+import { Dialog } from '@platform/ui/Dialog';+import { system } from '@theme/system';+import { act, useState } 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 { SortableListItem, SortableListStack } from './SortableListStack';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { count?: number; name?: string; position?: number }) =>+ options ? `${key}:${options.name}:${options.position}/${options.count}` : key,+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement;+let root: Root;+const onReorder = vi.fn<(activeId: string, overId: string) => void>();++/** A caller that applies each move, as a store would. */+const Fruit = ({ disabledId }: { disabledId?: string }) => {+ const [items, setItems] = useState(['apple', 'banana', 'cherry']);+ const reorder = (activeId: string, overId: string) => {+ onReorder(activeId, overId);+ setItems((current) => {+ const next = current.filter((id) => id !== activeId);+ next.splice(current.indexOf(overId), 0, activeId);+ return next;+ });+ };++ return (+ <SortableListStack dividers items={items} label="Fruit" onReorder={reorder}>+ {items.map((id) => (+ <SortableListItem+ key={id}+ actions={<button type="button">Edit {id}</button>}+ handleLabel={`Reorder ${id}`}+ id={id}+ isDisabled={id === disabledId}+ title={id}+ />+ ))}+ </SortableListStack>+ );+};++beforeEach(() => {+ onReorder.mockClear();+ host = document.createElement('div');+ host.style.cssText = 'width:320px;';+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+});++const render = async (disabledId?: string) => {+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <Fruit disabledId={disabledId} />+ </ChakraProvider>+ )+ );+};++const renderInDialog = async (onOpenChange: (details: { open: boolean }) => void) => {+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <Dialog.Root open onOpenChange={onOpenChange}>+ <Portal>+ <Dialog.Positioner>+ <Dialog.Content>+ <Fruit />+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ </ChakraProvider>+ )+ );+ // The dialog places its initial focus after mount; focusing a handle before that lands would be undone by it.+ await expect.poll(() => document.querySelector('[role="dialog"]')?.contains(document.activeElement)).toBe(true);+};++const order = () =>+ Array.from(document.querySelectorAll<HTMLElement>('[data-list-row]')).map((row) => row.dataset.listRow);+const row = (id: string) => document.querySelector<HTMLElement>(`[data-list-row="${id}"]`)!;+const handle = (id: string) => document.querySelector<HTMLButtonElement>(`button[aria-label="Reorder ${id}"]`)!;+const announcement = () => document.querySelector('[role="status"][aria-live]')?.textContent ?? '';+const settle = () =>+ act(+ () =>+ new Promise<void>((resolve) => {+ globalThis.setTimeout(resolve, 30);+ })+ );++const pointer = (type: string, target: EventTarget, x: number, y: number) =>+ target.dispatchEvent(new PointerEvent(type, { bubbles: true, button: 0, clientX: x, clientY: y, isPrimary: true }));++describe('SortableListStack', () => {+ it('renders rows as list items whose handle nests in no other control', async () => {+ await render();++ const list = document.querySelector('[role="list"]')!;+ expect(list.getAttribute('aria-label')).toBe('Fruit');+ expect(Array.from(list.querySelectorAll(':scope > [role="listitem"]'), (item) => item.textContent)).toEqual([+ 'appleEdit apple',+ 'bananaEdit banana',+ 'cherryEdit cherry',+ ]);+ expect(handle('apple').parentElement!.closest('button')).toBeNull();+ expect(handle('apple').closest('[data-list-surface]')).toBe(row('apple').querySelector('[data-list-surface]'));+ expect(document.querySelectorAll('[data-list-divider]')).toHaveLength(2);+ });++ it('moves a row dragged by its handle and marks the drag while it lasts', async () => {+ await render();+ const from = handle('apple').getBoundingClientRect();+ const to = row('cherry').getBoundingClientRect();+ const x = from.left + from.width / 2;+ const startY = from.top + from.height / 2;+ const endY = to.top + to.height / 2;++ // Stepped moves, as a hand makes them: the sorting strategy measures rows between moves.+ pointer('pointerdown', handle('apple'), x, startY);+ for (const progress of [0.1, 0.4, 0.7, 1, 1]) {+ pointer('pointermove', document, x, startY + (endY - startY) * progress);+ await settle();+ }++ expect(row('apple').hasAttribute('data-dragging')).toBe(true);+ expect(document.querySelector('[role="list"]')!.hasAttribute('data-sorting')).toBe(true);++ pointer('pointerup', document, x, endY);+ await settle();++ expect(onReorder).toHaveBeenCalledExactlyOnceWith('apple', 'cherry');+ expect(order()).toEqual(['banana', 'cherry', 'apple']);+ expect(row('apple').hasAttribute('data-dragging')).toBe(false);+ expect(document.querySelector('[role="list"]')!.hasAttribute('data-sorting')).toBe(false);+ });++ it('reorders from the keyboard and announces each step by title and position', async () => {+ await render();+ handle('banana').focus();++ await act(() => userEvent.keyboard('{Enter}'));+ await settle();+ expect(handle('banana').getAttribute('aria-pressed')).toBe('true');+ expect(announcement()).toBe('common.list.reorderPickedUp:banana:2/3');++ await act(() => userEvent.keyboard('{ArrowDown}'));+ await settle();+ expect(announcement()).toBe('common.list.reorderMoved:banana:3/3');++ await act(() => userEvent.keyboard('{Enter}'));+ await settle();+ expect(onReorder).toHaveBeenCalledExactlyOnceWith('banana', 'cherry');+ expect(order()).toEqual(['apple', 'cherry', 'banana']);+ expect(announcement()).toBe('common.list.reorderDropped:banana:3/3');+ expect(document.activeElement).toBe(handle('banana'));+ });++ it('puts a keyboard-lifted row back on Escape', async () => {+ await render();+ handle('apple').focus();++ await act(() => userEvent.keyboard('{Enter}'));+ await settle();+ await act(() => userEvent.keyboard('{ArrowDown}'));+ await settle();+ await act(() => userEvent.keyboard('{Escape}'));+ await settle();++ expect(onReorder).not.toHaveBeenCalled();+ expect(order()).toEqual(['apple', 'banana', 'cherry']);+ expect(announcement()).toBe('common.list.reorderCancelled:apple:1/3');+ });++ it('spends Escape on the sort, not on a dialog around the list', async () => {+ const onOpenChange = vi.fn();+ await renderInDialog(onOpenChange);+ handle('apple').focus();++ await act(() => userEvent.keyboard('{Enter}'));+ await settle();+ await act(() => userEvent.keyboard('{Escape}'));+ await settle();++ expect(announcement()).toBe('common.list.reorderCancelled:apple:1/3');+ expect(onOpenChange).not.toHaveBeenCalled();++ await act(() => userEvent.keyboard('{Escape}'));+ expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ open: false }));+ });++ it('does not lift a disabled row', async () => {+ await render('apple');+ const from = handle('apple').getBoundingClientRect();+ const to = row('cherry').getBoundingClientRect();+ const x = from.left + from.width / 2;++ expect(handle('apple').disabled).toBe(true);+ pointer('pointerdown', handle('apple'), x, from.top + from.height / 2);+ for (const y of [to.top, to.top + to.height / 2]) {+ pointer('pointermove', document, x, y);+ await settle();+ }+ pointer('pointerup', document, x, to.top + to.height / 2);+ await settle();++ expect(onReorder).not.toHaveBeenCalled();+ expect(order()).toEqual(['apple', 'banana', 'cherry']);+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/list/SortableListStack.tsx b/invokeai/frontend/webv2/src/platform/ui/list/SortableListStack.tsxnew file mode 100644index 0000000000..48896a54ef--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/list/SortableListStack.tsx@@ -0,0 +1,261 @@+/* oxlint-disable react-perf/jsx-no-jsx-as-prop -- ListItem slots take JSX; the React Compiler memoizes them. */+import type { Announcements, DragEndEvent, KeyboardSensorOptions } from '@dnd-kit/core';+import type { ReactNode } from 'react';++import { chakra, Icon } from '@chakra-ui/react';+import { closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';+import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers';+import {+ SortableContext,+ sortableKeyboardCoordinates,+ useSortable,+ verticalListSortingStrategy,+} from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';+import { useMountEffect } from '@platform/react/useMountEffect';+import { IconButton } from '@platform/ui/Button';+import { Tooltip } from '@platform/ui/Tooltip';+import { GripVerticalIcon } from 'lucide-react';+import { useCallback, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { ListItem, type ListItemProps } from './ListItem';+import { ListStack, type ListStackProps } from './ListStack';++/*+ * Reordering lives apart from ListStack and ListItem, which load with the editor: only lazily loaded lists import this+ * module, so its code stays out of the startup chunks.+ */++const MODIFIERS = [restrictToVerticalAxis, restrictToParentElement];+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } } as const;+const KEYBOARD_SENSOR_OPTIONS = { coordinateGetter: sortableKeyboardCoordinates } satisfies KeyboardSensorOptions;++export interface SortableListStackProps<Id extends string> extends Omit<ListStackProps, 'children'> {+ /** Row ids in their current order; each `SortableListItem` child takes one. */+ items: readonly Id[];+ /** One completed move: the dragged row takes the place of the row it was dropped on. */+ onReorder: (activeId: Id, overId: Id) => void;+ /** `SortableListItem` rows, in `items` order. */+ children: ReactNode;+}++interface RowData {+ label?: string;+ sortable?: { index: number; items: unknown[] };+}++const rowPosition = (entity: { data: { current?: unknown } } | null) => {+ const data = entity?.data.current as RowData | undefined;++ return data?.sortable+ ? { count: data.sortable.items.length, name: data.label ?? '', position: data.sortable.index + 1 }+ : null;+};++/**+ * A short list whose rows the user reorders by a handle, with the pointer or the keyboard (Space or Enter picks a row+ * up, the arrows move it, Space or Enter drops it, Escape cancels). Moves are announced by row title and position.+ */+export const SortableListStack = <Id extends string>({+ children,+ items,+ onReorder,+ ...stackProps+}: SortableListStackProps<Id>) => {+ const { t } = useTranslation();+ const [isSorting, setIsSorting] = useState(false);+ const sensors = useSensors(+ useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),+ useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)+ );+ // dnd-kit reports the row over its own place as the drag starts; only a change of place is news.+ const announcedPosition = useRef(0);+ const accessibility = useMemo(() => {+ const announcements: Announcements = {+ onDragCancel: ({ active }) => {+ const row = rowPosition(active);+ return row ? t('common.list.reorderCancelled', row) : undefined;+ },+ onDragEnd: ({ active, over }) => {+ const row = rowPosition(active);+ const target = rowPosition(over);+ if (!row) {+ return undefined;+ }+ return target+ ? t('common.list.reorderDropped', { ...row, position: target.position })+ : t('common.list.reorderCancelled', row);+ },+ onDragOver: ({ active, over }) => {+ const row = rowPosition(active);+ const target = rowPosition(over);+ if (!row || !target || target.position === announcedPosition.current) {+ return undefined;+ }+ announcedPosition.current = target.position;+ return t('common.list.reorderMoved', { ...row, position: target.position });+ },+ onDragStart: ({ active }) => {+ const row = rowPosition(active);+ announcedPosition.current = row?.position ?? 0;+ return row ? t('common.list.reorderPickedUp', row) : undefined;+ },+ };++ return { announcements, screenReaderInstructions: { draggable: t('common.list.reorderInstructions') } };+ }, [t]);+ const sortableItems = useMemo(() => [...items], [items]);++ const isSortingRef = useRef(false);+ // Escape cancels the sort, and only the sort: claimed ahead of a dialog or popover around the list, whose own+ // capturing Escape listener would otherwise close it. dnd-kit's sensors still see the key.+ useMountEffect(() => {+ const claimEscape = (event: KeyboardEvent) => {+ if (isSortingRef.current && event.key === 'Escape') {+ event.preventDefault();+ }+ };+ window.addEventListener('keydown', claimEscape, true);+ return () => window.removeEventListener('keydown', claimEscape, true);+ });++ const setSorting = useCallback((sorting: boolean) => {+ isSortingRef.current = sorting;+ setIsSorting(sorting);+ }, []);+ const handleDragStart = useCallback(() => setSorting(true), [setSorting]);+ const handleDragCancel = useCallback(() => setSorting(false), [setSorting]);+ const handleDragEnd = useCallback(+ ({ active, over }: DragEndEvent) => {+ setSorting(false);+ if (over && active.id !== over.id) {+ onReorder(active.id as Id, over.id as Id);+ }+ },+ [onReorder, setSorting]+ );++ return (+ <DndContext+ accessibility={accessibility}+ collisionDetection={closestCenter}+ modifiers={MODIFIERS}+ sensors={sensors}+ onDragCancel={handleDragCancel}+ onDragEnd={handleDragEnd}+ onDragStart={handleDragStart}+ >+ <SortableContext items={sortableItems} strategy={verticalListSortingStrategy}>+ <ListStack data-sorting={isSorting || undefined} {...stackProps}>+ {children}+ </ListStack>+ </SortableContext>+ </DndContext>+ );+};++/**+ * The handle sits in the row's leading slot, so the row's primary area must stay a plain container: the props that+ * make it a button (press, menu, List focus key) are left out, and the row acts through its `actions`.+ */+export interface SortableListItemProps extends Omit<+ ListItemProps,+ | 'isExpanded'+ | 'isMenuOpen'+ | 'itemKey'+ | 'onContextMenu'+ | 'onIntent'+ | 'onPress'+ | 'pressLabel'+ | 'role'+ | 'tabIndex'+> {+ id: string;+ /** Accessible name of the drag handle; name the row ("Reorder {title}"). */+ handleLabel: string;+}++const SHADOW_TRANSITION = 'box-shadow var(--wb-motion-duration-fast) ease';++const ROW_CSS = {+ borderRadius: 'sm',+ position: 'relative',+ transition: SHADOW_TRANSITION,+ // Rows slide past the hairlines while sorting, so the hairlines step aside until the drop.+ '[data-sorting] > & + [data-list-divider]': { opacity: 0 },+ // The picked-up row lifts above the rows it passes, by pointer or keyboard alike.+ '&[data-dragging]': { bg: 'bg.panel', boxShadow: 'lg', zIndex: 1 },+} as const;++const HANDLE_CSS = {+ color: 'fg.subtle',+ cursor: 'grab',+ flexShrink: 0,+ // Sits nearer the row's edge than its content does.+ ms: '-1',+ touchAction: 'none',+};+const DRAGGING_HANDLE_CSS = { ...HANDLE_CSS, cursor: 'grabbing' };++/** A `ListItem` with a drag handle at its start, for a `SortableListStack`. */+export const SortableListItem = ({+ handleLabel,+ id,+ isDisabled = false,+ leading,+ ...rowProps+}: SortableListItemProps) => {+ const { t } = useTranslation();+ const { attributes, isDragging, listeners, setActivatorNodeRef, setNodeRef, transform, transition } = useSortable({+ attributes: { roleDescription: t('common.list.reorderRole') },+ data: { label: rowProps.title },+ disabled: isDisabled,+ id,+ });+ const style = useMemo(+ () => ({+ transform: CSS.Translate.toString(transform),+ // dnd-kit's own timing ignores the app's Reduce motion setting; the motion token follows it.+ transition: transition ? `transform var(--wb-motion-duration-slow) ease, ${SHADOW_TRANSITION}` : undefined,+ }),+ [transform, transition]+ );++ return (+ <chakra.div+ ref={setNodeRef}+ css={ROW_CSS}+ data-dragging={isDragging || undefined}+ data-list-row={id}+ role="listitem"+ style={style}+ >+ <ListItem+ {...rowProps}+ isDisabled={isDisabled}+ leading={+ <>+ {/* Quiet while its row moves: the tip would trail the drag. */}+ <Tooltip content={handleLabel} disabled={isDragging} keepsRootWhenDisabled>+ <IconButton+ ref={setActivatorNodeRef}+ {...attributes}+ {...listeners}+ aria-label={handleLabel}+ css={isDragging ? DRAGGING_HANDLE_CSS : HANDLE_CSS}+ disabled={isDisabled}+ size="sm"+ variant="ghost"+ >+ <Icon as={GripVerticalIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ {leading}+ </>+ }+ role="presentation"+ />+ </chakra.div>+ );+};diff --git a/invokeai/frontend/webv2/src/platform/ui/scrollStripEdges.ts b/invokeai/frontend/webv2/src/platform/ui/scrollStripEdges.tsnew file mode 100644index 0000000000..bc3145bdff--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/scrollStripEdges.ts@@ -0,0 +1,78 @@+import type { RefCallback } from 'react';++/**+ * A row that scrolls sideways without a scrollbar: the wheel (`wheelScrollsHorizontally`), focus and the content cut off+ * at its edges carry it.+ */+export const HIDDEN_SCROLLBAR_CSS = { '&::-webkit-scrollbar': { display: 'none' }, scrollbarWidth: 'none' } as const;++/** A fractional zoom can leave a sub-pixel remainder at either end of a fully scrolled row; that hides nothing. */+export const SCROLL_EDGE_TOLERANCE_PX = 1;++export interface HiddenScrollEdges {+ end: boolean;+ start: boolean;+}++/** Which ends of a sideways scroller hide content. Right-to-left rows scroll toward negative offsets. */+export const measureHiddenEdges = (scroller: HTMLElement): HiddenScrollEdges => {+ const offset = Math.abs(scroller.scrollLeft);+ const range = scroller.scrollWidth - scroller.clientWidth;++ return { end: range - offset >= SCROLL_EDGE_TOLERANCE_PX, start: offset >= SCROLL_EDGE_TOLERANCE_PX };+};++/** How far the edge fade reaches into the row; an item revealed at a hiding edge should sit clear of it. */+export const SCROLL_EDGE_FADE_PX = 16;++const fade = (direction: 'left' | 'right', start: boolean, end: boolean) =>+ `linear-gradient(to ${direction}, ${start ? 'transparent' : 'black'}, black ${SCROLL_EDGE_FADE_PX}px, black calc(100% - ${SCROLL_EDGE_FADE_PX}px), ${end ? 'transparent' : 'black'})`;++const fadeCss = (start: boolean, end: boolean) => ({+ maskImage: fade('right', start, end),+ _rtl: { maskImage: fade('left', start, end) },+});++/** Fades the row out at each end `markHiddenEdges` marks as hiding content, whatever the row sits on. */+export const SCROLL_EDGE_FADE_CSS = {+ '&[data-hidden-start]': fadeCss(true, false),+ '&[data-hidden-end]': fadeCss(false, true),+ '&[data-hidden-start][data-hidden-end]': fadeCss(true, true),+} as const;++/**+ * Ref callback marking the ends of a sideways scroller that hide content as `data-hidden-start`/`data-hidden-end`.+ * Re-measured on scroll and whenever the scroller or one of its items resizes: an item can grow without resizing the+ * scroller (a count gaining a digit).+ */+export const markHiddenEdges: RefCallback<HTMLElement> = (element) => {+ if (!element) {+ return;+ }+ const update = () => {+ const { end, start } = measureHiddenEdges(element);+ element.toggleAttribute('data-hidden-start', start);+ element.toggleAttribute('data-hidden-end', end);+ };+ const resizes = new ResizeObserver(update);+ resizes.observe(element);+ for (const item of element.children) {+ resizes.observe(item);+ }+ const mutations = new MutationObserver((records) => {+ for (const record of records) {+ record.removedNodes.forEach((node) => node instanceof Element && resizes.unobserve(node));+ record.addedNodes.forEach((node) => node instanceof Element && resizes.observe(node));+ }+ update();+ });+ mutations.observe(element, { childList: true });+ element.addEventListener('scroll', update, { passive: true });+ update();++ return () => {+ resizes.disconnect();+ mutations.disconnect();+ element.removeEventListener('scroll', update);+ };+};diff --git a/invokeai/frontend/webv2/src/platform/ui/settings/SettingControl.tsx b/invokeai/frontend/webv2/src/platform/ui/settings/SettingControl.tsxindex 2f370d36fc..251f133eff 100644--- a/invokeai/frontend/webv2/src/platform/ui/settings/SettingControl.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/settings/SettingControl.tsx@@ -1,4 +1,5 @@import { createListCollection, Field, HStack, Input, Slider, Stack, Switch, Text } from '@chakra-ui/react';+import { ScrubberField } from '@platform/ui/ScrubberField';import { Select } from '@platform/ui/Select';import { useCallback, useId, useMemo, type ChangeEvent } from 'react';import { useTranslation } from 'react-i18next';@@ -20,6 +21,9 @@ const DIALOG_DIRECTION = { base: 'column', md: 'row' } as const;const DIALOG_ALIGNMENT = { base: 'stretch', md: 'center' } as const;const DIALOG_CONTROL_WIDTH = { base: 'full', md: '52' } as const;const SELECT_POSITIONING = { strategy: 'fixed', sameWidth: true, hideWhenDetached: true } as const;+// The quick select is only as wide as its value, so its menu opens from its end at a width of its own.+const QUICK_SELECT_POSITIONING = { placement: 'bottom-end', strategy: 'fixed', hideWhenDetached: true } as const;+const QUICK_SELECT_CONTENT_PROPS = { minW: '10rem' } as const;/** Presentation only. Normalization, persistence and side effects belong to the binding. */export const SettingControl = ({ field, surface, value, onChange, disabled, layer }: SettingControlProps) => {@@ -99,6 +103,59 @@ export const SettingControl = ({ field, surface, value, onChange, disabled, laye);}+ if (field.kind === 'select' && surface === 'quick') {+ // Laid out like the switch rows it sits among: the label leads, the select trails it at the row's end.+ return (+ <Field.Root+ data-setting-control=""+ disabled={disabled}+ display="flex"+ flexDirection="row"+ alignItems="center"+ justifyContent="space-between"+ gap="4"+ >+ <HStack gap="2" minW="0">+ {/* Names the hidden select, which hands a click's focus on to the trigger as a native label would. */}+ <Field.Label fontSize="md" fontWeight="500">+ {label}+ </Field.Label>+ {layer ? <SettingLayerIndicator label={label} layer={layer} /> : null}+ </HStack>+ <Select+ collection={collection}+ contentProps={QUICK_SELECT_CONTENT_PROPS}+ value={selectValue}+ fitContent+ maxW="60%"+ portalled={false}+ // Fixed positioning escapes scrolling/clipped surfaces; staying inline preserves modal focus and ARIA.+ positioning={QUICK_SELECT_POSITIONING}+ onValueChange={handleSelectChange}+ />+ </Field.Root>+ );+ }++ if (field.kind === 'slider' && surface === 'quick') {+ // One inline row like the switches and selects around it: the scrubber carries its own label and value.+ return (+ <HStack data-setting-control="" gap="2">+ <ScrubberField+ disabled={disabled}+ flex="1"+ label={label}+ max={field.max}+ min={field.min}+ step={field.step ?? 1}+ value={Number(value)}+ onChange={onChange}+ />+ {layer ? <SettingLayerIndicator label={label} layer={layer} /> : null}+ </HStack>+ );+ }+return (<Field.Rootdata-setting-control=""@@ -123,8 +180,8 @@ export const SettingControl = ({ field, surface, value, onChange, disabled, layecollection={collection}value={selectValue}disabled={disabled}- size={surface === 'quick' ? 'md' : 'lg'}- w={surface === 'quick' ? 'full' : DIALOG_CONTROL_WIDTH}+ size="lg"+ w={DIALOG_CONTROL_WIDTH}flexShrink={0}portalled={false}// Fixed positioning escapes scrolling/clipped surfaces; staying inline preserves modal focus and ARIA.diff --git a/invokeai/frontend/webv2/src/platform/ui/settings/SettingLayerIndicator.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/settings/SettingLayerIndicator.browser.test.tsxindex 3dfca5c186..10078e0c0d 100644--- a/invokeai/frontend/webv2/src/platform/ui/settings/SettingLayerIndicator.browser.test.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/settings/SettingLayerIndicator.browser.test.tsx@@ -5,7 +5,7 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { page } from 'vitest/browser';+import { page, userEvent } from 'vitest/browser';import type { SettingDefinition, SettingLayer } from './contracts';@@ -17,7 +17,22 @@ await i18n.use(initReactI18next).init({ lng: 'en', resources: { en: { translatio(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const FIELD: SettingDefinition = { id: 'showGrid', kind: 'boolean', label: 'Show grid', scope: 'project' };+const SELECT_FIELD: SettingDefinition = {+ id: 'gridSize',+ kind: 'select',+ label: 'Grid size',+ options: [+ { label: 'Small', value: 'small' },+ { label: 'Large', value: 'large' },+ ],+ scope: 'project',+};const noop = () => {};+const CHANGED_LAYER: SettingLayer = { onResetToBuiltIn: noop, state: 'default' };+const LONG_SELECT_FIELD: SettingDefinition = {+ ...SELECT_FIELD,+ options: [{ label: 'A deliberately long option label that cannot fit beside its setting', value: 'long' }],+};let host: HTMLDivElement;let root: Root;@@ -88,3 +103,85 @@ describe('setting layer indicator', () => {expect(onChange).not.toHaveBeenCalled();});});++describe('quick settings select', () => {+ const renderQuick = (value: string, layer: SettingLayer, onChange: (value: boolean | number | string) => void) =>+ act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <SettingControl field={SELECT_FIELD} surface="quick" value={value} layer={layer} onChange={onChange} />+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ const select = () => page.getByRole('combobox', { name: 'Grid size', exact: true });++ beforeEach(() => {+ host.style.width = '280px';+ });++ it('leads with its label and dot like a switch row, trailing a bordered select sized to its value', async () => {+ await renderQuick('small', CHANGED_LAYER, noop);++ const trigger = select().element();+ const label = host.querySelector<HTMLElement>('label')!;+ const dot = page.getByRole('button', { name: 'Grid size: changed from Invoke default', exact: true }).element();+ expect(label.textContent).toBe('Grid size');+ expect(trigger.textContent).toBe('Small');+ expect(label.getBoundingClientRect().right).toBeLessThanOrEqual(dot.getBoundingClientRect().left);+ expect(dot.getBoundingClientRect().right).toBeLessThanOrEqual(trigger.getBoundingClientRect().left);+ // At the row's end and only as wide as its value and chevron.+ expect(Math.round(trigger.getBoundingClientRect().right)).toBe(Math.round(host.getBoundingClientRect().right));+ expect(trigger.getBoundingClientRect().width).toBeLessThan(host.getBoundingClientRect().width / 2);+ // The same bordered box as other selects.+ expect(getComputedStyle(trigger).borderTopWidth).toBe('1px');+ expect(getComputedStyle(trigger).borderTopStyle).toBe('solid');+ });++ it('focuses the select from a click on its label and commits a choice from a menu aligned to its end', async () => {+ const onChange = vi.fn();+ await renderQuick('small', CHANGED_LAYER, onChange);++ await userEvent.click(page.elementLocator(host.querySelector('label')!));+ await expect.element(select()).toHaveFocus();+ await userEvent.click(select());+ const listbox = page.getByRole('listbox', { name: 'Grid size', exact: true });+ await expect.element(listbox).toBeVisible();+ const menu = listbox.element().getBoundingClientRect();+ // Wider than the trigger it opens from, and flush with its end.+ expect(menu.width).toBeGreaterThanOrEqual(160);+ expect(Math.abs(menu.right - select().element().getBoundingClientRect().right)).toBeLessThanOrEqual(1);+ await userEvent.click(page.getByRole('option', { name: 'Large', exact: true }));+ expect(onChange).toHaveBeenCalledWith('large');+ });++ it('ellipsizes a long value within 60% of the row', async () => {+ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <SettingControl field={LONG_SELECT_FIELD} surface="quick" value="long" onChange={noop} />+ </ChakraProvider>+ </I18nextProvider>+ )+ );++ const trigger = select().element();+ const valueText = trigger.querySelector<HTMLElement>('[data-part="value-text"]')!;+ expect(trigger.getBoundingClientRect().width).toBeLessThanOrEqual(host.getBoundingClientRect().width * 0.6 + 1);+ expect(valueText.scrollWidth).toBeGreaterThan(valueText.clientWidth);+ expect(getComputedStyle(valueText).textOverflow).toBe('ellipsis');+ const chevron = trigger.querySelector<HTMLElement>('[data-part="indicator"]')!;+ expect(valueText.getBoundingClientRect().right).toBeLessThanOrEqual(chevron.getBoundingClientRect().left);+ });++ it('keeps the dot beside the label working', async () => {+ const onResetToBuiltIn = vi.fn();+ await renderQuick('small', { onResetToBuiltIn, state: 'default' }, noop);++ await userEvent.click(page.getByRole('button', { name: 'Grid size: changed from Invoke default', exact: true }));+ await userEvent.click(page.getByRole('menuitem', { name: 'Reset to Invoke default', exact: true }));+ expect(onResetToBuiltIn).toHaveBeenCalledOnce();+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.test.ts b/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.test.tsindex 0fdb55fbcc..817fbbbc97 100644--- a/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.test.ts+++ b/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.test.ts@@ -15,13 +15,6 @@ const liveImage: StreamingImageSource = {src: 'data:image/png;base64,live',width: 64,};-const heldLiveImage: StreamingImageSource = {- alt: 'Held preview',- height: 32,- kind: 'live',- src: 'data:image/png;base64,held',- width: 64,-};const finalImage: StreamingImageSource = {alt: 'Final image',height: 512,@@ -39,15 +32,11 @@ const fallbackImage: StreamingImageSource = {describe('resolveStreamingImageSource', () => {it('prioritizes final images over live and fallback images', () => {- expect(resolveStreamingImageSource({ fallbackImage, finalImage, heldLiveImage, liveImage })).toBe(finalImage);- });-- it('uses the current live image before a held live image', () => {- expect(resolveStreamingImageSource({ fallbackImage, heldLiveImage, liveImage })).toBe(liveImage);+ expect(resolveStreamingImageSource({ fallbackImage, finalImage, liveImage })).toBe(finalImage);});- it('keeps the held live image while waiting for final image data', () => {- expect(resolveStreamingImageSource({ fallbackImage, heldLiveImage })).toBe(heldLiveImage);+ it('uses the live image before the fallback', () => {+ expect(resolveStreamingImageSource({ fallbackImage, liveImage })).toBe(liveImage);});it('falls back when no final or live image is available', () => {diff --git a/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.ts b/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.tsindex 87de536f6b..ce72c25b6d 100644--- a/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.ts+++ b/invokeai/frontend/webv2/src/platform/ui/streaming-image/streamingImageSource.ts@@ -59,11 +59,9 @@ export const imageUrlToStreamingSource = ({export const resolveStreamingImageSource = ({fallbackImage,finalImage,- heldLiveImage,liveImage,}: {fallbackImage?: StreamingImageSource | null;finalImage?: StreamingImageSource | null;- heldLiveImage?: StreamingImageSource | null;liveImage?: StreamingImageSource | null;-}): StreamingImageSource | null => finalImage ?? liveImage ?? heldLiveImage ?? fallbackImage ?? null;+}): StreamingImageSource | null => finalImage ?? liveImage ?? fallbackImage ?? null;diff --git a/invokeai/frontend/webv2/src/platform/ui/streaming-image/useStreamingImageSource.ts b/invokeai/frontend/webv2/src/platform/ui/streaming-image/useStreamingImageSource.tsindex 6919c97e52..9c84119fc5 100644--- a/invokeai/frontend/webv2/src/platform/ui/streaming-image/useStreamingImageSource.ts+++ b/invokeai/frontend/webv2/src/platform/ui/streaming-image/useStreamingImageSource.ts@@ -3,12 +3,9 @@ import { resolveStreamingImageSource, type StreamingImageSource } from './streamexport const useStreamingImageSource = ({fallbackImage,finalImage,- heldLiveImage,liveImage,}: {fallbackImage?: StreamingImageSource | null;finalImage?: StreamingImageSource | null;- /** The last live frame kept up while no current live frame exists. */- heldLiveImage?: StreamingImageSource | null;liveImage?: StreamingImageSource | null;-}): StreamingImageSource | null => resolveStreamingImageSource({ fallbackImage, finalImage, heldLiveImage, liveImage });+}): StreamingImageSource | null => resolveStreamingImageSource({ fallbackImage, finalImage, liveImage });diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.tsindex 1e931896a8..6a3fc34073 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts@@ -33,6 +33,59 @@ const controlSizes = <T>(CONTROL_SIZES.map((size) => [size, build(stock?.[basis[size]] ?? stock?.xl, `{sizes.control.${size}}`, size)]));+/**+ * Arrowed surfaces (menus, popovers, hover cards) keep the tip clear of the content's rounded corners: the arrow box gets+ * a transparent border of the corner radius plus a margin. Floating UI keeps the whole box within the content's edge,+ * so the tip never lands on a corner curve; a small trigger at the end of a bar shifts the panel instead. Zag's gutter+ * reads the box's inner height, which the border leaves at the visible size. An arrow of no size gets no border either,+ * so Floating UI has nothing to centre on the anchor and leaves the panel where its placement puts it. The box overlaps+ * the content and is transparent, so it lets the pointer through.+ */+const arrowClearOfCorners = (visibleSize: string) => ({+ '--arrow-visible-size': visibleSize,+ '--arrow-clearance': 'min(calc({radii.md} + 2px), calc(var(--arrow-visible-size) * 1000))',+ '--arrow-size': 'calc(var(--arrow-visible-size) + 2 * var(--arrow-clearance))',+ borderColor: 'transparent',+ borderStyle: 'solid',+ borderWidth: 'var(--arrow-clearance)',+ pointerEvents: 'none',+});++/**+ * A popover's or hover card's arrow sits inside its content, which is `position: relative`, so Zag's offset out of the+ * content lands on the padding edge, one border width (1px) inside the outer edge. Moved out by that width, away from+ * the content only, it centres on the outer edge, as a menu's arrow does beside its content. It stacks below the+ * content's children, in the stacking context the content slot isolates: the tip's cover over the content's edge+ * (`arrowTipOutsideContent`) paints over the content's own border and shading but never over a child flush with that+ * edge, such as the footer of a popover without padding.+ */+const arrowInsideContent = {+ zIndex: '-1',+ '[data-placement^=bottom] > &': { translate: '0 -1px' },+ '[data-placement^=top] > &': { translate: '0 1px' },+ '[data-placement^=right] > &': { translate: '-1px 0' },+ '[data-placement^=left] > &': { translate: '1px 0' },+};++/**+ * Zag rotates the tip so its bordered top-left corner points out of the content. Clipped to that outer half plus a+ * band into the content, it covers the content's edge across its base, so tip and panel share one outline. The band+ * spans the 1px border and the 1px inset highlight the dark `lg` shadow paints inside it, with room to spare: a+ * rotated element loses its sub-pixel offset, so at a fractional device pixel ratio (125%) the tip lands up to half a+ * device pixel off its layout position, and the arrow's 1px move outward overshoots a border the browser snapped to+ * one device pixel (0.8px). A band of about 3px (4.5px along each side) absorbs both; one of 1px left part of the+ * border or the highlight as a line across the base. A menu's tip, on top of its content, covers only padding with it.+ * A tip of no size draws no border either. The clip bounds hit testing as well: unlike its click-through arrow box,+ * the visible tip takes the pointer as part of the surface, so resting on it keeps a hover card open and a click on+ * it never reaches whatever lies beneath.+ */+const arrowTipOutsideContent = {+ borderLeftWidth: 'min(1px, var(--arrow-visible-size))',+ borderTopWidth: 'min(1px, var(--arrow-visible-size))',+ clipPath: 'polygon(0 0, calc(100% + 4.5px) 0, 0 calc(100% + 4.5px))',+ pointerEvents: 'auto',+};+/** Extend the tooltip recipe; replacing it drops arrow size/background variables. */export const tooltipSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.tooltip,@@ -77,15 +130,23 @@ export const hoverCardSlotRecipe = defineSlotRecipe({content: {...chakraSlotRecipes.hoverCard.base?.content,'--hovercard-bg': 'colors.bg.muted',+ // The arrow stacks below the content's children, within the content: see `arrowInsideContent`.+ isolation: 'isolate',borderColor: 'border.emphasized',borderWidth: '1px',boxShadow: 'lg',color: 'fg',maxWidth: '18rem',},+ arrow: {+ ...chakraSlotRecipes.hoverCard.base?.arrow,+ ...arrowClearOfCorners('{sizes.3}'),+ ...arrowInsideContent,+ },arrowTip: {...chakraSlotRecipes.hoverCard.base?.arrowTip,borderColor: 'border.emphasized',+ ...arrowTipOutsideContent,},},defaultVariants: { size: 'xs' },@@ -99,6 +160,8 @@ export const popoverSlotRecipe = defineSlotRecipe({content: {...chakraSlotRecipes.popover.base?.content,'--popover-bg': 'colors.bg.muted',+ // The arrow stacks below the content's children, within the content: see `arrowInsideContent`.+ isolation: 'isolate',borderColor: 'border.emphasized',borderWidth: '1px',boxShadow: 'lg',@@ -106,9 +169,15 @@ export const popoverSlotRecipe = defineSlotRecipe({_open: { animationStyle: 'slide-fade-in', animationDuration: 'faster' },_closed: { animationStyle: 'slide-fade-out', animationDuration: 'faster' },},+ arrow: {+ ...chakraSlotRecipes.popover.base?.arrow,+ ...arrowClearOfCorners('{sizes.3}'),+ ...arrowInsideContent,+ },arrowTip: {...chakraSlotRecipes.popover.base?.arrowTip,borderColor: 'border.emphasized',+ ...arrowTipOutsideContent,},},});@@ -562,6 +631,18 @@ export const dropdownGroupLabel = {textTransform: 'uppercase',};+/**+ * A menu's arrow points at its anchor when the anchor is a box: a trigger, or a measured one. A context menu is+ * anchored to the pointer, a point of at most 1px with nothing to point at, so its arrow's visible size is nothing. Zag sets+ * the anchor's size on the positioner as it places the menu; until then, a box is assumed. The placement after that,+ * which Floating UI's auto-update makes as soon as its resize observer reports the content, drops the shrunken arrow's+ * height from the gutter. Zag's one-shot repositions (`listeners: false`: `Menu.ContextTrigger`, an `anchorPoint`+ * prop, `TRIGGER_VALUE.SET`) get no such second placement and would keep a point-anchored menu 6px further out; the app+ * uses none of them.+ */+const MENU_ARROW_SIZE =+ 'min({sizes.3}, max(0px, calc((min(var(--reference-width, 2px), var(--reference-height, 2px)) - 1px) * 1000)))';+export const menuSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.menu,base: {@@ -570,9 +651,29 @@ export const menuSlotRecipe = defineSlotRecipe({...chakraSlotRecipes.menu.base?.content,...dropdownContent,},+ arrow: {+ ...chakraSlotRecipes.menu.base?.arrow,+ ...arrowClearOfCorners(MENU_ARROW_SIZE),+ // Beside the content, the arrow is outside the scope of its `--menu-bg`.+ '--arrow-background': `colors.${dropdownContent.bg}`,+ // MenuContent mirrors the content's state and placement onto the arrow, so it slides and fades with the content.+ _open: chakraSlotRecipes.menu.base?.content?._open,+ // Held at its last frame: it ends with the content's exit, which unmounts both.+ _closed: { ...chakraSlotRecipes.menu.base?.content?._closed, animationFillMode: 'forwards' },+ // Content kept mounted when closed is hidden; the arrow beside it goes with it.+ '[hidden] + &': { display: 'none' },+ },+ arrowTip: {+ ...chakraSlotRecipes.menu.base?.arrowTip,+ borderColor: dropdownContent.borderColor,+ ...arrowTipOutsideContent,+ },item: {...chakraSlotRecipes.menu.base?.item,...dropdownItem,+ // An item's own icon sits back from its label, so every menu reads the same without each caller coloring it. A+ // danger item keeps its tone, and a glyph nested deeper (an indicator, an icon-only item) keeps its own color.+ '&:not([data-danger]) > svg': { color: 'fg.subtle' },},itemGroupLabel: {...chakraSlotRecipes.menu.base?.itemGroupLabel,@@ -941,6 +1042,32 @@ export const colorPickerSlotRecipe = defineSlotRecipe({},});+/**+ * Keycaps sit inside menu items and palette rows, whose hover fill is close to the stock keycap border. The emphasized+ * border keeps the cap's outline readable on that fill; each size is 2px shorter than stock so a cap sits inside a+ * row's text line without crowding it.+ */+const KBD_HEIGHTS: Record<string, string> = { '4.5': '16px', '5': '18px', '6': '22px' };++export const kbdRecipe = defineRecipe({+ ...chakraRecipes.kbd,+ variants: {+ ...chakraRecipes.kbd.variants,+ variant: {+ ...chakraRecipes.kbd.variants?.variant,+ raised: { ...chakraRecipes.kbd.variants?.variant?.raised, borderColor: 'border.emphasized' },+ outline: { ...chakraRecipes.kbd.variants?.variant?.outline, borderColor: 'border.emphasized' },+ },+ // Keyed by stock height, as the size names are already rebased onto the workbench scale.+ size: Object.fromEntries(+ Object.entries(chakraRecipes.kbd.variants?.size ?? {}).map(([name, styles]) => [+ name,+ { ...styles, height: KBD_HEIGHTS[String((styles as { height?: unknown }).height)] ?? styles.height },+ ])+ ),+ } as unknown as typeof chakraRecipes.kbd.variants,+});+/*** Use a linear sweep to avoid endpoint pauses; system.ts disables skeleton motion and gradients under reduced* motion.@@ -993,7 +1120,12 @@ export const panelRecipe = defineRecipe({defaultVariants: { tone: 'surface', density: 'none' },});-const rowFocusRing = {+/**+ * The keyboard focus ring of every row surface, inset so neighbouring rows never clip it. Exported for row-like+ * surfaces that cannot build on `Row` or `ListItem` for their focus target, such as tree items whose focus sits on a+ * wrapper around the row surface.+ */+export const rowFocusRing = {outline: '2px solid',outlineColor: 'accent.solid',outlineOffset: '-2px',@@ -1073,6 +1205,8 @@ export const listItemSlotRecipe = defineSlotRecipe({minW: 0,position: 'relative','&:has([data-list-primary]:focus-visible)': rowFocusRing,+ // A disabled row stays focusable, so its content dims instead of the root: the focus ring keeps full strength.+ _disabled: { cursor: 'not-allowed', '& > *': { opacity: 0.5 } },// Rows of a page being replaced stay readable; only the pointer says the list is working.'&[data-busy]': { cursor: 'progress' },},@@ -1217,12 +1351,37 @@ export const listSectionHeaderSlotRecipe = defineSlotRecipe({lineHeight: 'shorter',},},+ variants: {+ placement: {+ // Above a list: the label sits low in its row, close to the rows it names.+ list: {},+ // In a bar beside centred controls: the label centres with them.+ bar: { root: { alignItems: 'center', pb: '0' } },+ },+ },+ defaultVariants: { placement: 'list' },});+/**+ * A chip label's box trimmed to its cap height, so flex centring lines the letters up with the chip's icon wherever the+ * engine's rounded ascent and descent put the baseline in the line box (about 2 device px high in Linux Chromium at+ * 125%). Equal block padding keeps that centre and leaves room for descenders and accents inside a clipping label.+ * Without `text-box` support the label keeps its full line box.+ */+export const chipLabelStyles = {+ '@supports (text-box: trim-both cap alphabetic)': {+ paddingBlock: '0.3em',+ textBox: 'trim-both cap alphabetic',+ },+} as const;+export const chipRecipe = defineRecipe({base: {alignItems: 'center',- borderRadius: 'sm',+ // Fill the host row, so a progress hairline keeps to its bottom edge however tall the trimmed label is.+ alignSelf: 'stretch',+ // The status bar's hover and active fill radius, which the progress hairline is clipped to.+ borderRadius: 'control',display: 'inline-flex',flexShrink: '0',fontSize: 'xs',@@ -1231,6 +1390,8 @@ export const chipRecipe = defineRecipe({px: '2',py: '0.5',whiteSpace: 'nowrap',+ // The label is the chip's text child.+ '& > p': chipLabelStyles,},variants: {tone: {diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts b/invokeai/frontend/webv2/src/platform/ui/theme/system.tsindex 38e555a777..a29a40e9a4 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/system.ts@@ -10,6 +10,7 @@ import {dialogSlotRecipe,hoverCardSlotRecipe,inputRecipe,+ kbdRecipe,menuSlotRecipe,numberInputSlotRecipe,popoverSlotRecipe,@@ -104,9 +105,9 @@ const brandFg: Compute = (theme) =>? `color-mix(in oklab, ${theme.colors.brand.solid} 50%, ${theme.colors.neutral[950]})`: theme.colors.brand.solid;const accentSolid: Compute = (theme) => theme.colors.accent.solid;-/** Foreground pulled toward accent: the hue of interaction fills, which apply it at low alpha. */+/** Foreground leaned toward accent by the theme's `interactionTint`: the colour interaction fills apply at low alpha. */const hoverTint: Compute = (theme) =>- `color-mix(in oklab, ${theme.colors.accent.solid} 55%, ${+ `color-mix(in oklab, ${theme.colors.accent.solid} ${theme.interactionTint}%, ${theme.colorScheme === 'light' ? theme.colors.neutral[950] : theme.colors.neutral[50]})`;@@ -164,7 +165,7 @@ const semanticColors = {'bg.emphasized': colorToken((theme) => theme.colors.control),'bg.inset': colorToken((theme) => theme.colors.inset),/**- * The pointed or highlighted fill for rows, tabs, and options: a faint accent-tinted foreground, translucent so it+ * The pointed or highlighted fill for rows, tabs, and options: a faint foreground leaned toward the accent, translucent so it* reads on any surface. Matches the ghost/outline button hover (`gray.hoverTint/10`), so an open trigger and its* highlighted option share one fill.*/@@ -261,6 +262,14 @@ const highContrastConditions = {highContrastLight: `:root[data-high-contrast=true]:is(${lightThemeSelectors})`,};+/**+ * `inset / size` as a number (tan(atan2(a, b)) is a / b), and 0 while the collapsible has not measured the size yet+ * (0px): the scale is then 1, never infinite or negative.+ */+const insetRatio = (inset: string, size: string): string =>+ `tan(atan2(min(${inset}, ${size} * 1000), max(${size}, ${inset})))`;+const SECTION_SCALE_INSET = `scale(calc(1 - ${insetRatio('8px', 'var(--width)')}), calc(1 - ${insetRatio('4px', 'var(--height)')}))`;+const motionDurationToken = (base: string): TokenValue => ({ value: { base, _reduceMotion: '1ms' } });const motionAnimationToken = (base: string): TokenValue => ({ value: { base, _reduceMotion: 'none' } });@@ -345,16 +354,33 @@ const config = defineConfig({from: { transform: 'translateX(-100%)' },to: { transform: 'translateX(300%)' },},+ // A settings section's fields growing into place as it opens (and back as it folds), beside the collapsible's own+ // height and fade. The start is a fixed inset, not a percentage, so every section's edges travel alike whatever+ // its size: 4px in from each side and 4px up from the bottom, scaled from the top centre. The ratios come from+ // the `--width` and `--height` the collapsible measures for its height animation. Neither is held after it ends,+ // so no transform stays on the fields; the fold ends with the content faded out. They run on the fields inside+ // the collapsible's content, never on the content itself: Chromium leaves fields unpainted when one element both+ // runs a composited transform animation and animates its height under `overflow: hidden`.+ 'wb-section-scale-in': {+ from: { transform: SECTION_SCALE_INSET },+ to: { transform: 'scale(1)' },+ },+ 'wb-section-scale-out': {+ from: { transform: 'scale(1)' },+ to: { transform: SECTION_SCALE_INSET },+ },},layerStyles: {- // The inset dot-grid surface behind previews and the loading splash.+ // The inset dot-grid surface behind previews, the loading splash and the auth screens. It matches the workflow+ // editor's grid at 100% zoom (1.5px dots every 25px): the ramp from 0.4px to 1px carries the ink of that+ // anti-aliased 0.75px-radius dot, where a wider gradient reads brighter.dotGrid: {value: {backgroundColor: 'bg.inset',- backgroundImage: 'radial-gradient(circle, currentColor 1px, transparent 1.5px)',+ backgroundImage: 'radial-gradient(circle, currentColor 0.4px, transparent 1px)',backgroundPosition: 'center',backgroundRepeat: 'repeat',- backgroundSize: '24px 24px',+ backgroundSize: '25px 25px',color: 'fg.grid',},},@@ -403,6 +429,7 @@ const config = defineConfig({recipes: {button: buttonRecipe,input: inputRecipe,+ kbd: kbdRecipe,skeleton: skeletonRecipe,textarea: textareaRecipe,},diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/themes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/themes.tsindex c6fd9f2bd6..83bed78102 100644--- a/invokeai/frontend/webv2/src/platform/ui/theme/themes.ts+++ b/invokeai/frontend/webv2/src/platform/ui/theme/themes.ts@@ -37,32 +37,41 @@ export interface ThemeDefinition {/** Native color-scheme hint for form controls, scrollbars, and `<select>` popups. */colorScheme: 'dark' | 'light';colors: ThemeColors;+ /**+ * How far interaction fills (hovered rows, ghost buttons, tabs) lean from the foreground toward the accent, 0–100.+ * A fill is this colour at low alpha, so the right amount depends on the surfaces under it: near-grey surfaces want+ * a trace, or the hover reads as coloured beside a neutral selected fill; strongly tinted surfaces want more, or it+ * reads as a white film.+ */+ interactionTint: number;}+// A near-neutral cool grey: enough blue to sit with the accent, not enough to read as a blue interface.const classic: ThemeColors = {neutral: {- 50: 'oklch(96% 0.006 264.5)',- 100: 'oklch(91.5% 0.009 264.5)',- 200: 'oklch(82.5% 0.014 264.5)',- 300: 'oklch(73.5% 0.019 264.4)',- 400: 'oklch(57.5% 0.026 264.3)',- 500: 'oklch(44% 0.024 264.3)',- 600: 'oklch(39% 0.022 264.3)',- 700: 'oklch(34% 0.02 264.3)',- 800: 'oklch(28.8% 0.018 264.3)',- 900: 'oklch(23.8% 0.016 264.35)',- 950: 'oklch(18.8% 0.014 264.4)',+ 50: 'oklch(96% 0.004 264)',+ 100: 'oklch(91.5% 0.005 264)',+ 200: 'oklch(82.5% 0.008 264)',+ 300: 'oklch(73.5% 0.011 264)',+ 400: 'oklch(57.5% 0.015 264)',+ 500: 'oklch(42% 0.014 264)',+ 600: 'oklch(36.5% 0.013 264)',+ 700: 'oklch(31.5% 0.012 264)',+ 800: 'oklch(26.3% 0.011 264)',+ 900: 'oklch(21.3% 0.009 264)',+ 950: 'oklch(16.5% 0.008 264)',},- brand: { solid: 'oklch(92.041% 0.2103 116.59)', contrast: 'oklch(18.8% 0.014 264.4)' },- accent: { solid: 'oklch(77.738% 0.1 231.76)', contrast: 'oklch(18.8% 0.014 264.4)' },- danger: 'oklch(70.61% 0.0841 19.38)',- success: 'oklch(79.8% 0.1132 141.63)',- warning: 'oklch(76.62% 0.0612 62.9)',- inset: 'oklch(18.8% 0.014 264.4)',+ brand: { solid: 'oklch(92.041% 0.2103 116.59)', contrast: 'oklch(16.5% 0.008 264)' },+ accent: { solid: 'oklch(77.738% 0.1 231.76)', contrast: 'oklch(16.5% 0.008 264)' },+ // Status hues carry more colour than the greyer surfaces they sit on, at one shared lightness band.+ danger: 'oklch(71% 0.125 22)',+ success: 'oklch(79% 0.125 150)',+ warning: 'oklch(80% 0.115 78)',+ inset: 'oklch(16.5% 0.008 264)',// Keep fill visibly above control surfaces so ghost hovers do not disappear.- fill: 'oklch(36% 0.021 264.3)',- grid: 'oklch(38.5% 0.022 264.3)',- control: 'oklch(34% 0.02 264.3)',+ fill: 'oklch(33.5% 0.012 264)',+ grid: 'oklch(36% 0.013 264)',+ control: 'oklch(31.5% 0.012 264)',};const light: ThemeColors = {@@ -200,6 +209,7 @@ export const THEMES: ThemeDefinition[] = [description: 'The legacy blue-on-graphite workbench.',colorScheme: 'dark',colors: classic,+ interactionTint: 15,},{id: 'light',@@ -207,6 +217,7 @@ export const THEMES: ThemeDefinition[] = [description: 'Bright, high-contrast surfaces for daylight work.',colorScheme: 'light',colors: light,+ interactionTint: 55,},{id: 'ultradark',@@ -214,6 +225,7 @@ export const THEMES: ThemeDefinition[] = [description: 'Pure-black OLED surfaces for low-light rooms.',colorScheme: 'dark',colors: ultradark,+ interactionTint: 55,},{id: 'mono',@@ -221,6 +233,7 @@ export const THEMES: ThemeDefinition[] = [description: 'Neutral grayscale with no color cast.',colorScheme: 'dark',colors: mono,+ interactionTint: 55,},{id: 'osakaJade',@@ -228,6 +241,7 @@ export const THEMES: ThemeDefinition[] = [description: 'Deep jade stone with a cool green accent.',colorScheme: 'dark',colors: osakaJade,+ interactionTint: 55,},{id: 'catppuccinMocha',@@ -235,6 +249,7 @@ export const THEMES: ThemeDefinition[] = [description: 'Soothing pastel accents on deep violet-gray surfaces.',colorScheme: 'dark',colors: catppuccinMocha,+ interactionTint: 55,},];diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.browser.test.tsxindex b744826b31..1695ec8a4c 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchContext.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchContext.browser.test.tsx@@ -163,7 +163,7 @@ const activeProject = (): { id: string; name: string } | null => {};const generationUi = {- sectionPreferences: { sectionsOpen: {}, setSectionOpen: () => undefined },+ sectionPreferences: { sectionsOpen: {}, setSectionsOpen: () => undefined },} as unknown as GenerationUiAdapter;const mountEditor = async ({ strict = false, withStrength = false } = {}) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 6651730cdd..bbd267592e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -43,7 +43,7 @@ Document mirror reports in leaf terms, in document order. For value edit it fold### Properties and Transform-Tool and operation settings live off the surface, as editor panes of Layers panel (`widgets/layers/panes`). Properties pane renders running operation first, then active tool, each as `ToolPropertyForm` / `OperationPropertyForm` (`widgets/canvas/tool-presentation`): named, collapsible groups of typed rows (optional preview card on top), with ONE sticky footer pinned to pane's bottom edge — running operation's verbs (status chip, Process/Reset, Apply with its save-as menu, Cancel), else tool form's (transform session's Apply/Cancel). Group ids are global so tools sharing a group's component keep its DOM and collapse state across the switch. Transform pane edits selected layer's transform without a tool — each field commits one undoable `patch`, and while Transform tool holds a session same fields drive its preview and Apply / Cancel land or drop it. Forms read engine's option stores and document transactions directly: no state mirror. A running operation locks the tool groups in place (`inert`) and owns the footer, keeping its own controls live with Cancel always reachable; a generation or staged results lock nothing (see "Editing during generation"). Panes are fixed parts of panel — `LayerEditorPanes` owns their tabs, preferred height and collapse, persisted through Layers widget's project state — not movable widgets. Same blocks host Color/Swatches workspace (project foreground/background pair), History pane (engine's labeled undo/redo stack via `history.getEntries()`/`stepBy`: a Start row stands for the canvas before the oldest kept step and notes `evicted` steps or the `dropped` ones a previous engine of the project was disposed with (the registry hands their count, evictions and cooldown trims included, to the next engine's history), both until the history is next cleared; jumps wait while `documentEditingLocked`; Clear history asks first; below the steps, the project's restore points), and Overview navigator (`previews.drawDocumentOverview` plus live viewport handle).+Tool and operation settings live off the surface, as editor panes of Layers panel (`widgets/layers/panes`). Properties pane renders running operation first, then active tool, each as `ToolPropertyForm` / `OperationPropertyForm` (`widgets/canvas/tool-presentation`): named, collapsible groups of typed rows (optional preview card on top), each ending with its form's actions row inline in its section — no sticky footer. A running operation's row (`OperationActions`: Reset, Cancel, the manual run while auto-update is off, Apply with its save-as menu; while auto-update is on, Filter and Select Object also offer it as the retry after a failed run) follows its groups; the transform form's Apply/Cancel close the Tool section. An operation form's `useStatus` hook feeds its section: the busy phase sits beside the section title in a live region mounted for the operation's lifetime, the error comes last, after the actions, so no control moves, and the source layer is the subtitle's tooltip. Group ids are global so tools sharing a group's component keep its DOM and collapse state across the switch. Transform pane edits selected layer's transform without a tool — each field commits one undoable `patch`, and while Transform tool holds a session same fields drive its preview and Apply / Cancel land or drop it. Forms read engine's option stores and document transactions directly: no state mirror. A running operation locks the tool section, its actions included, in place (`inert`) and takes focus to its own Cancel, scrolled into view, keeping its own controls live; a generation or staged results lock nothing (see "Editing during generation"). Panes are fixed parts of panel — `LayerEditorPanes` owns their tabs, preferred height and collapse, persisted through Layers widget's project state — not movable widgets. Same blocks host Color/Swatches workspace (project foreground/background pair), History pane (engine's labeled undo/redo stack via `history.getEntries()`/`stepBy`: a Start row stands for the canvas before the oldest kept step and notes `evicted` steps or the `dropped` ones a previous engine of the project was disposed with (the registry hands their count, evictions and cooldown trims included, to the next engine's history), both until the history is next cleared; jumps wait while `documentEditingLocked`; Clear history asks first; below the steps, the project's restore points), and Overview navigator (`previews.drawDocumentOverview` plus live viewport handle).## Package and capability boundaries@@ -69,7 +69,7 @@ Current extracted ownership includes:- `HistoryController`: engine-owned history, guarded async replay with failure reporting, inactive byte trimming.- `PersistenceController`: dirty-bitmap flush barriers (whole document, or one layer through `applicationHost.flushLayerUploads`) and disposal.- `EditingController`: selection state and exclusive edit-lease lifecycle.-- `TransformEditingController` (under `EditingController`): transform sessions, previews, parameter commits and paint bakes, plus `layers.beginTransform` and the wait of a session requested before its layer's pixels persist. It alone decides when that wait opens a session or ends; `engine.ts` routes it document changes, tool switches, Escape, replays, document replacement and final upload failures.+- `TransformEditingController` (under `EditingController`): transform sessions, previews, parameter commits and paint bakes (an image, shape, gradient, text, mask or region keeps its transform, so Apply is one transform patch; paint pixels are baked), plus `layers.beginTransform` and the wait of a session requested before its layer's pixels persist. It alone decides when that wait opens a session or ends; `engine.ts` routes it document changes, tool switches, Escape, replays, document replacement and final upload failures.- `ColorSampleController`: one-shot color requests and the workbench color router, and which of them receives each pick.- `PaintLineEndController`: where the last brush or eraser stroke ended on each layer, followed through the layer's changes (see "Input ownership and frame scheduling").- `InteractionController`: public tool commands and their disposal boundary.@@ -77,7 +77,8 @@ Current extracted ownership includes:- `RasterExportController`: guarded layer rasterization, transformed copies, encoding, reservations, pin leases. A rasterization that failed because the source cannot be read reports a `LayerUnreadable` refusal (`layerExportGuards.ts`) carrying the layer's id and name, never `not-ready`: waiting cannot fix it, so every consumer (crop, merges, boolean merges, copies, conversion, extraction, duplicate, filter, Select Object, Run Workflow, snapshots for generation and PSD, composite export) refuses with it instead of asking the user to retry, and the message names the layer to disable, delete or replace. An operation reading several layers names the first that failed in its read order; crop all lists each one it skipped. Unreadable means the image resolver threw `CanvasImageMissingError` (the `ImageResolver` contract: the image is missing, or not readable by this user; the production resolver maps 403, 404 and 410 to it), the fetched image did not decode, or rendering threw. Any other resolver failure (network, server, an expired session) is wrapped as `ImageUnavailableError` and is transient: operations and readiness gates report `not-ready`, and crop all refuses the whole crop as `not-ready` instead of skipping the layer. The rasterizer remembers either failure per cache entry, keyed by cache version, document generation and source, with its kind, and a retry of the same source that fails again with the same kind raises no second error notice; a change of kind (a fetch outage that turns out to be a deleted image) is reported, with the `ImageUnavailableError` itself (naming the image, the resolver's error as its cause) for a transient one. Two questions read that record. `getFailure` (the kind recorded for the layer's current key) drives the readiness gates that never rasterize themselves (Merge Down, boolean merges, extraction): they answer unreadable for as long as an `unreadable` failure holds, and `not-ready` for an `unavailable` one. `isBackingOff` (either failure's retry backoff, 3 s doubling per repeated failure up to 60 s, is still running) drives the compositor, which skips the layer meanwhile instead of reading its image every frame; the backoff's end invalidates the layer, so a displayed layer retries on its own. A readiness gate asked about a layer also retries it in the background while it answers from the record (a layer off screen or disabled is never redrawn to do so): at once for an `unavailable` failure, so trying again after an outage ends fetches without waiting out the backoff, and only once the backoff is over for an `unreadable` one. A running job is joined, never duplicated. Explicit operations (crop, export, merges) always try again. A retry that fails again restarts the backoff without a second notice; a success or any change to the layer clears the failure. Thumbnails show `error` for both kinds.- `PsdExportController`: immutable PSD planning, snapshot capture, reservation, execution, cancellation.- `StagedResultController`: guarded staged-candidate acceptance and its history entry.-- `PixelEditController`, `SelectionImageController`, `LayerMutationController`: atomic pixel/document publication at their respective boundaries. Pixel editor materializes control layers and raster-image layers in place before destructive edits (brush and eraser alike), keeping conversion plus pixels in one undoable transaction.+- `PixelEditController`, `SelectionImageController`, `LayerMutationController`: atomic pixel/document publication at their respective boundaries. Pixel editor materializes control layers and raster-image layers in place before destructive edits (brush, eraser and selection Fill/Erase alike), keeping conversion plus pixels in one undoable transaction.+- `SelectionPixelController`: selection Fill and Erase, on the layers the brush and eraser edit in place (paint, raster image, control, inpaint mask, regional guidance), refused as they refuse (`editing/controlPixelEdit.ts` `selectionPixelEditRefusal`, which also decides the Selection actions' disabled reasons). A paint layer or mask is edited in its local space, the document-space selection mapped through the inverse layer transform, one image-patch entry per edit; masks take opaque coverage. Control layers and raster images go through the pixel editor.- `CropLayerController`: crops one layer, or every leaf of every stack, to the frame; crop-all is one entry. Both paths share one eligibility rule: a leaf locked by itself or an ancestor, or with a source the export cannot bake, is never cropped. A single crop refuses such a leaf, an `unreadable` one, and one wholly outside the frame (`outside-frame`: the explicit crop would empty it). Crop all first crosses the paint-upload barrier (`flushPendingPixels`, not waiting for held pixels), so an acknowledgement replacing a just-painted leaf cannot land mid-read and refuse it as `stale`. It skips locked and unreadable leaves when their contract's content reaches past the frame, counting the locked ones (`skippedLocked`) and listing the unreadable ones in document order (`skippedUnreadable`), so the result can say what was left alone, by name, even when nothing was cropped, and one leaf that cannot be read never blocks the rest; a leaf already inside the frame, empty or unsupported is left alone; a leaf wholly outside is emptied in place, so ids, order, groups and flags never change. It reads one leaf at a time through a read lease, copies the cropped pixels into a surface under their own raster reservation and releases the lease before the next leaf, so the peak is the cropped set plus one export; it refuses `stale` when the stacks, frame or any pixel guard moved meanwhile, admits one history entry for every before and after snapshot, and publishes one `replaceCanvasLayers` (same-id, same-type leaves, refused whole when any entry is invalid). `MergeLayerController` merges selected leaves into a new one through one pipeline parameterized by eligibility, result stack, result leaf and label: merge-selected flattens a contiguous raster run into a paint layer, merge-masks unions any inpaint masks' coverage (each at full alpha, since a mask's opacity only tints it on screen) into a mask configured like the topmost source.- `MaskResultController`, `FilterResultController`, `GeneratedResultController`: guarded application-result adoption through narrow host ports.- `ControlDerivationController`: control-layer intent patches and detected-map commits (see "Control derivation").@@ -105,13 +106,15 @@ Rotation or rescaling retains whole-source capture: changing a Canvas2D source's`submitCanvasInvocationSnapshot` carries exact cloned canvas state used for compilation. `enqueueCompiledSnapshot` extracts its bounding box, dimensions, document revision instead of reading live project canvas. Generated candidates are placed from `queueItem.snapshot.canvas.document.bbox`, so later bbox edits do not move result. Progress frames land at the same rect: a placeholder slot carries the submitted bbox origin and the result's size there (`src/workbench/canvasStagingView.ts`), and `StagedPreviewInput` always carries an absolute placement, so neither a candidate nor a progress frame follows the live bbox, and a bbox change repaints only the overlay. `documentRevision` still keeps results from a replaced canvas session out of current staging.+The canvas paints only the selected slot: a candidate's image, or a placeholder's own latest frame. Staging auto-switch follows the policy Preview follows (`getAutoSwitchFollowedLive`, `selectsLandedResult`, `pickAutoSwitch` in `@features/queue/contracts`) and moves the real selection, so accept and discard act on what is shown. A landed result takes the selection by `selectsLandedResult` (`latest` and `progress` always, `off` only while no result is selected). After every reducer action, `reconcileCanvasStagingFollow` (`workbenchState.ts`) shows what the policy follows for each project whose staging, queue or follow state changed: under `progress`, the pinned placeholder while it remains, else the newest placeholder with a frame of its own; otherwise, under `progress` and `latest`, never a placeholder with nothing to show while a result is staged (the newest result takes the selection). That covers frames, results landing, a mode chosen from the menu, and a discard, accept or cancel that leaves a placeholder at the selected index. The follow state is the Workbench's transient `canvasStagingFollow` (placeholders that showed a first frame, from the coordinator's `onFirstProgressFrame` → `noteQueueItemFirstProgressFrame`; and the user's pin), never persisted, synced or undone; entries go with their placeholders and with closed projects, so a slot id a retry brings back starts fresh. Between images (model load, text encoding) the previous result stays selected and painted. A user pick (thumbnail click or right-click, an arrow key from the selected thumbnail, the bar's step buttons, the canvas stepping keys; not Tab focus, which the strip's roving tab stop keeps to the selected thumbnail) is `pickAutoSwitch` (`pickStagedSlotAutoSwitch`): a candidate turns the mode `off`; a placeholder turns it `progress` and pins it; a mode set from the menu releases the pin. The reducer cannot tell a placeholder waiting to start from one running, so every placeholder counts as running and a pin holds until its placeholder is gone. A followed placeholder that ends without a staged image (a single item canceled, or finished with none) hands the selection to the newest candidate rather than to the frameless placeholder that takes its index. The staging bar's Stop generating, first in the bar and apart from the result's actions, stops every run still generating for this canvas (`getInFlightCanvasItems`, one notice for all) while any placeholder remains, whatever kind of slot is selected.+### Editing during generation-Nothing in the document freezes while a generation runs or its results wait for review: tools, Properties, layer menus, canvas keys and history stay live. Only each result's landing rect is fixed: a candidate's `placement`, or the submitted bbox for a result still generating. Moving or resizing the bbox mid-batch changes the next Invoke only. Painting under a staged area is allowed; the shown preview draws above the raster and control stacks, and the staging bar's eye hides it. Deleting, reordering or adding layers leaves staging alone, and accept inserts a new raster layer at the top of the raster stack at accept time. Undo past the submission is allowed and never re-stages or moves a result. What keeps this safe: `documentRevision` fences staging (Clear canvas drops the replaced session's results and offers to stop its queued work; restoring a canvas point waits while the session has pending results, see "Restore points"); an offset `resizeCanvasDocument` is refused while the session has pending results (`hasPendingCanvasResults`), since it would move every leaf but not the pinned rects; acceptance stays engine-guarded (permit, gesture, a live float or open transform landed first, candidate fingerprint; see "Edit leases and staged-result acceptance"). A new Invoke no longer interrupts Filter or Select Object; their own lease and guards hold. The canvas widget outlines where each pending result lands (`previews.setStagedRegions`, see "Composition, damage and overlays") and the staging bar announces the pending count in a `role="status"` pill. From the canvas, Alt+[ and Alt+] step through staged results while more than one slot exists (a placeholder shows its progress frame); with one slot or none there is nothing to step to and they walk the layers. Bare arrows always nudge. With focus in the staging bar, its own key handler owns the arrows and Delete/Backspace and keeps them from the canvas: focus follows selection (focusing a thumbnail selects it, Left/Right move focus between thumbnails, or step the selection from the bar's other controls), Delete or Backspace discards the selected result and leaves focus on the next thumbnail, a step button or the bar, and nothing acts while one of the bar's menus is open.+Nothing in the document freezes while a generation runs or its results wait for review: tools, Properties, layer menus, canvas keys and history stay live. Only each result's landing rect is fixed: a candidate's `placement`, or the submitted bbox for a result still generating. Moving or resizing the bbox mid-batch changes the next Invoke only. Painting under a staged area is allowed; the shown preview draws above the raster stack and below the overlay stacks, and the staging bar's eye hides it. Deleting, reordering or adding layers leaves staging alone, and accept inserts a new raster layer at the top of the raster stack at accept time. Undo past the submission is allowed and never re-stages or moves a result. What keeps this safe: `documentRevision` fences staging (Clear canvas drops the replaced session's results and offers to stop its queued work; restoring a canvas point waits while the session has pending results, see "Restore points"); an offset `resizeCanvasDocument` is refused while the session has pending results (`hasPendingCanvasResults`), since it would move every leaf but not the pinned rects; acceptance stays engine-guarded (permit, gesture, a live float or open transform landed first, candidate fingerprint; see "Edit leases and staged-result acceptance"). A new Invoke no longer interrupts Filter or Select Object; their own lease and guards hold. The canvas widget outlines where each pending result lands (`previews.setStagedRegions`, see "Composition, damage and overlays") and the staging bar announces the pending count in a `role="status"` pill. From the canvas, Alt+[ and Alt+] step through staged results while more than one slot exists (a placeholder shows its progress frame); with one slot or none there is nothing to step to and they walk the layers. Bare arrows always nudge. With focus in the staging bar, its own key handler owns the arrows and Delete/Backspace and keeps them from the canvas: the thumbnail strip is one Tab stop, on the selected thumbnail, so Tab passes it without picking; Left/Right on a thumbnail pick the neighbour and move focus with the pick, and from the bar's other controls step the selection, Delete or Backspace discards the selected result and leaves focus on the next thumbnail, a step button or the bar, and nothing acts while one of the bar's menus is open.## Frame demand before allocation-Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides. The overview composites the same extent fit-to-view fits (the frame joined with every enabled renderable layer's bounds), translated so that extent fills its target, and returns that document-space rect so the Overview pane maps its outline and pointer through it. The screen description also carries which overlay stacks it shows: while a staged or progress preview is shown it hides the inpaint-mask and regional-guidance stacks and the regenerate-region tint, so the result reads untinted, whatever is selected. They show again, drawn above the preview, only while a pointer gesture edits the selected mask or region (or a group in those stacks; `isStagingHiddenStackSelected`), so the user never paints a mask blind. Whether a gesture edits is the active tool's `Tool.editsSelectedLayer` contract, asked once as the pointer pipeline reports the gesture starting (`onGestureChange`): a brush or eraser press that paints the selected leaf in place and is not refused up front; a box or freehand shape drag that draws into the selected leaf's pixels, or cuts out of them under the mod key whatever Place on says. A tool that knows only after it was asked calls `ToolContext.beginSelectedLayerEdit`, which runs the same reveal decision mid-gesture: the shape tool once its press shows the modifiers (the hook is asked before the press reaches the tool), or when the mod key turns a drag into a cutout; a move reveals once its drag crosses the drag threshold as a layer drag, so a click reveals nothing, nor does a drag that a locked or hidden layer refuses or that moves a float. A locked or hidden mask reveals nothing, and a selected group reveals only for a move, since the brush, eraser and shapes paint a new layer instead. Navigation, sampling, bbox, selection, transform, gradient and Select Object gestures, Space and Alt holds included, never reveal, and a polygon's vertex presses do not either, since they write nothing until it closes. Edits that no revealing gesture carries, such as undoing a mask stroke or closing a polygon, change nothing visible while the preview hides the stacks. So that a gesture can edit at once, while its stack is hidden the frame keeps a selected mask or region leaf resident when the screen would otherwise draw it and its bounds meet the viewport (the rule drawn leaves follow): it stays demanded (protected from eviction) and rasterizes when stale; a selected group needs nothing up front. Transform sessions and floating selections never open on masks or regions, so the transform tool has nothing to reveal. The staged preview always lands above the raster and control stacks and below masks and regions, so a shown mask draws over it. A candidate whose preview is toggled off hides nothing. Control layers, isolation targets and every non-screen composite are unaffected. The flag is derived per frame from that per-gesture decision and joins the description's reuse key; publishing or clearing the preview repaints in full, and while a preview is shown so do the reveal's start (the press, or a move's threshold crossing) and the gesture's end (release, cancel or reset); its other pointer moves repaint only their own damage. A progress frame decodes at its own (latent) size and the compositor scales it into its rect, so an upscale's large output rect costs no full-size decode.+Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, isolated group scopes, each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or document size does. Frame demand and screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through layer's cache entry. Color sampler, overview and extraction prepare their own descriptions of committed document without transient overrides. The overview composites the same extent fit-to-view fits (the frame joined with every enabled renderable layer's bounds), translated so that extent fills its target, and returns that document-space rect so the Overview pane maps its outline and pointer through it. The screen description also carries which overlay stacks it shows: while a staged or progress preview is shown it hides every overlay stack (control layers, inpaint masks, regional guidance) and the regenerate-region tint, so only raster layers draw and the result reads uncovered and untinted, whatever is selected. A selected candidate the staging bar's eye toggled off keeps hiding them (the widget publishes it as `hidden`: nothing decodes or draws), so comparing the result with the canvas under it shows the same raster-only canvas on both sides; hiding is canvas-wide, as it is under a shown result. Accept, discard and anything else that clears the preview (selecting a placeholder without a progress frame, cooldown, document replacement) show them again. They show again, drawn above the preview, only while an edit of a control layer, mask or region is under way (or of a group in those stacks; `isInStagingHiddenStack`), so the user never edits blind: a pointer gesture on the selected one, a transform session open on one, or a floating selection lifted from one. The regenerate tint then draws again too, with its raster layer and so under the preview: it shows only outside the result's rect, or everywhere while the eye hides the result. Whether a gesture edits is the active tool's `Tool.editsSelectedLayer` contract, asked once as the pointer pipeline reports the gesture starting (`onGestureChange`): a brush or eraser press that paints the selected leaf in place and is not refused up front; a box or freehand shape drag that draws into the selected leaf's pixels, or cuts out of them under the mod key whatever Place on says. A tool that knows only after it was asked calls `ToolContext.beginSelectedLayerEdit`, which runs the same reveal decision mid-gesture: the shape tool once its press shows the modifiers (the hook is asked before the press reaches the tool), or when the mod key turns a drag into a cutout; a move reveals once its drag crosses the drag threshold as a layer drag, so a click reveals nothing, nor does a drag that a locked or hidden layer refuses; a drag that lifts or moves a float reveals through the float itself. A locked or hidden layer reveals nothing, and a selected group reveals only for a move, since the brush and shapes paint a new layer instead and the eraser refuses it. Navigation, sampling, bbox, selection, gradient and Select Object gestures, Space and Alt holds included, never reveal, and a polygon's vertex presses do not either, since they write nothing until it closes. Edits that no revealing gesture or session carries, such as undoing a mask stroke, closing a polygon, an arrow-key nudge, or the selection commands (Fill, Erase, and the Delete and Cut that erase through `eraseSelection`) on a control layer, mask or region, change nothing visible while the preview hides the stacks: a reveal lasts as long as the gesture or session that carries it, and a one-shot command has none to end it. So that a gesture can edit at once, while its stack is hidden the frame keeps a selected control, mask or region leaf resident when the screen would otherwise draw it and its bounds meet the viewport (the rule drawn leaves follow): it stays demanded (protected from eviction) and rasterizes when stale; a selected group needs nothing up front. Transform sessions open on control layers, masks and regions; floating selections on control layers, never on masks or regions. The reveal follows the `transformSession` and `hasFloatingSelection` stores: it starts when a session opens on, or a float is lifted from, a layer in a hidden stack, and ends when the session is applied or cancelled or the float is banked or dropped. The staged preview always lands above the raster stack and below every overlay stack, so a revealed control layer, mask or region draws over it. Isolation targets and every non-screen composite are unaffected. The flag is derived per frame from that per-gesture decision and the session's, and joins the description's reuse key; publishing, hiding or clearing the preview repaints in full, and while a preview is shown or toggled off so do the reveal's start (the press, a move's threshold crossing, a session opening or a float lifting) and its end (release, cancel or reset; the session or float ending); its other pointer moves repaint only their own damage. The engine publishes whether the preview hides the overlay stacks as the `stagingHidesOverlays` interaction state (a reveal does not change it), so canvas chrome about a hidden layer, such as the control-view switch, can step aside. A progress frame decodes at its own (latent) size and the compositor scales it into its rect, so an upscale's large output rect costs no full-size decode.`calculateActiveFrameLayerIds` is the pure pre-allocation pass over that description: intersects each drawable leaf's bounds with document-space viewport. Explicitly isolated operation target is the one exception to normal document visibility: stays demanded and drawable when disabled or display-hidden, because user acts on that named layer directly.@@ -178,7 +181,7 @@ Group surface is keyed by everything except its members' pixels and float's placA scope whose own stack is spatial keeps its slot surface raw (its own stack key stays out of its shape key, so a parameter edit repaints nothing; a parent still keys it as a child). Each raw repaint bumps the slot's raw version and records its surface-local damage: unknown for a whole rebuild, and only member content damage for an `invalidate` redraw, so the adjusted copy keeps its pixels until the group's own result lands. It tracks each member's and nested group's look (stack, opacity, blend, matrix) apart from its shape: a look change repaints that look's old and new bounds in a same-shaped slot with the same bounds. A spatial stack edited into another spatial stack is redrawn only in the raw composite, not patched in the adjusted copy, since its shown pixels stay until it lands. A move that changes the group's bounds repaints the whole slot. A same-size adjusted surface, counted in group bytes and evicted with its slot, follows the layer rules on that raw composite: the domain is the document-resolution union of member bounds, whose transparent margin the kernel's alpha-bounds domain ignores, and per-pixel runs work at the slot's document origin. Each slot runs its own jobs; the group reports, under its id in `adjustmentStatus`, the status of the slot the canvas frame read last (else of its most recently read slot), so reads by the overview or picking under other keys never flip its row or redraw its ancestors. While a filter preview, float or transform session gives the frame and the overview different keys, each runs its own job on its own inputs: a known cost, not a correctness issue. A raw repaint trail longer than 16 entries folds its oldest entries together, so damage since an older version stays known, only coarser. A job waits (reporting `computing`) while any member's or nested group's displayed pixels are still pending; a member that cannot finish does not block it. Every read returns `state`, `exact`, `pending` or `inexact`, combining the group's own state with its inputs'. The group's settle handler steps the pixel epoch and redraws ancestor groups and the frame, never the landed group. The engine drops the spatial slots of groups that no longer draw a spatial stack (`retainSpatial`), clearing their status.-Overlay renders in CSS pixels. Receives document→CSS view, CSS viewport size and device-pixel ratio, clears backing store in device pixels, then draws every handle, nub, dash and cursor under a DPR base transform (nested image and path transforms compose with it), so chrome keeps its CSS size at any ratio and matches CSS-pixel hit tests. Viewport owns the ratio (capped at `MAX_DPR`, sub-one ratios kept); backing-store size and composite view matrix both derive from it.+Overlay renders in CSS pixels. Receives document→CSS view, CSS viewport size and device-pixel ratio, clears backing store in device pixels, then draws every handle, nub, dash and cursor under a DPR base transform (nested image and path transforms compose with it), so chrome keeps its CSS size at any ratio and matches CSS-pixel hit tests. Viewport owns the ratio (capped at `MAX_DPR`, sub-one ratios kept); backing-store size and composite view matrix both derive from it. The generation frame and its handles draw in device space as filled axis-aligned rects on whole device pixels. Each dash is three bands one hairline wide (a whole number of device pixels, about one CSS pixel): navy outside, the accent core centred on the device pixels nearest the frame's edge, white inside. White contrasts with content up to about 0.30 relative luminance and navy with content from about 0.16, so some band of every dash keeps at least about 3.8:1 contrast (WCAG) with any solid content, both casings over the accent itself. Each edge fits a whole odd number of dashes and gaps (about 4 CSS px, varying by at most a device pixel) between its corners, so every corner is a whole L and every edge and dash end is crisp at any ratio; dashes beyond the backing store are not traced. Handles wrap the same bands around a white face. Snapping moves the frame by under one device pixel and never changes the rect it marks or hit testing.Pending results are outlined by the overlay, not the compositor (which draws staged pixels without an outline). The canvas widget feeds `previews.setStagedRegions` from its staging slots (`widgets/canvas/CanvasStagedRegionsFeed.tsx`): each candidate's placement and each placeholder's submitted rect, the selected slot flagged. `PreviewStateController` keeps each distinct rect once, selected when any result there is, with the selected one last; the overlay draws them as dashed amber outlines over a dark halo, under the bbox frame, the selected one wider and opaque. An equal list invalidates nothing, a changed one only the overlay. The regions are project data, so the feed never clears them on unmount; another canvas on the engine may still show them. The staged preview itself is published by the canvas widget, which clears it when it unmounts; cooldown and document replacement clear it too, but detaching a surface does not, so a remounted surface (a layout change) shows it again without a republish.@@ -198,7 +201,7 @@ Layer controllers build their steps from `controllers/editSteps.ts`: byte accounFloating selection (`FloatingSelectionController`) computes its commit footprint from geometry before it copies or cuts anything: before and after pixels over union of hole and landing, selection alpha before and after, entry overhead. Admitted for that footprint as part of the drag that lifts it; keeps the transaction until it lands or is dropped. Every move, scale or rotation grows admission to the footprint at the new transform, from geometry alone; transform that does not fit keeps last accepted one and reports `over-budget` once per float, so an accepted transform always fits its undo entry while permit stays current; admission never shrinks, so a live float holds its largest accepted footprint until it lands or is dropped. Refused lift is reported and moves nothing (`lift` returns `refused`), including content whose cache is not rebuilt yet; only a lift with nothing to take (`unavailable`) lets Move tool fall back to moving the layer. Cut layer's persistence is suspended while float lives. Commit lands pixels and moved selection as one entry under retained admission, renewed once when its permit went stale (an operation locked and released the document meanwhile); commit that cannot be admitted or published puts pre-lift pixels and selection back. Cancellation refills hole before persistence resumes; hole that cannot be refilled keeps layer suspended rather than uploading it. Every terminal path ends the transaction: commit, cancel, Escape, undo/redo, layer's deletion or replacement, document replacement, cooldown (which banks the float before the flush), disposal, exceptions while cutting or landing.-Live pixel edits (brush, eraser, shapes on paint layers or as opaque mask coverage, pixel transactions on control and image layers) are admitted before their first pixel changes and grow their admission before the stroke's before/after footprint does; refused growth restores layer's pixels and extent and engine reports the refusal through `tools.onEditRefused`, which canvas widget turns into a notice. Tools report a press the selected layer cannot take there too, as a `CanvasLayerEditRefusal` naming the layer: hidden (disabled, itself or through a group), locked, transparency-locked under the eraser or a shape cutout, or its durable pixels not in the cache yet (the press requests them and the next one can edit; nothing is drawn over missing pixels). A shape cutout (the platform's mod key: ⌘ on macOS, where Ctrl-click opens the context menu, Ctrl elsewhere) with no paint layer or mask selected reports a `CanvasShapeCutoutRefusal` and never adds a layer. The Shape tool reports at the press when the press already decides the target, and again at commit if the target changed meanwhile. The Brush never creates a layer above a locked or hidden image on its own; its refusal offers one. Brush, eraser, shape and move cursors read not-allowed over such a selection; the engine refreshes the cursor on every document change. Widget previews of structural edits run in one owned `StructuralPreviewSession` (`useStructuralPreview`), which coalesces live dispatches to one per frame, captures the values its first preview of each field replaces (session's baseline) and records the gesture as a single step from it; refused commit or cancel restores that baseline, even while edits are locked. A commit from elsewhere, a history replay, a newer session or disposal ends an open session first, dropping pending previews and restoring baseline, so previewed values never land over a replayed document or inside another step: every engine edit starts from `CanvasMutationContext.getDocument()`, which ends it first (structural controller's commits and nudges, pixel and layer operations such as merge down and duplicate, result commits); widget-prepared edits (`commitPreparedEdit`, layers tree's child-row commands) end it before reading the model; `HistoryController` ends it (with any live float) before a replay that has a step to land, and a replay with nothing to land disturbs nothing; document replacement drops it without restoring, since the document it previewed on is gone. Widget's next preview starts a new session from changed document, and a commit after engine ended its session records from live values; its refusal as `missing` stays silent, since the document change that ended the gesture also unmounted the editor.+Live pixel edits (brush, eraser, shapes on paint layers or as opaque mask coverage, pixel transactions on control and image layers) are admitted before their first pixel changes and grow their admission before the stroke's before/after footprint does; refused growth restores layer's pixels and extent and engine reports the refusal through `tools.onEditRefused`, which canvas widget turns into a notice. Tools and selection Fill/Erase report an edit the selected layer cannot take there too, as a `CanvasLayerEditRefusal` naming the layer: hidden (disabled, itself or through a group), hidden on the canvas only (`layer-display-hidden`: `leafPaintRefusal` refuses it to every edit that writes pixels, so nothing lands out of sight; moves and transforms still take it), locked, transparency-locked under the eraser, a shape cutout or Erase, its durable pixels not in the cache yet (the edit requests them and the next one can act; nothing is drawn over missing pixels), a control layer whose empty shape has no pixels (`layer-unpaintable`), a layer the eraser cannot erase in place (`erase-unsupported`: a group, text, shape or gradient) or one removing the selection's pixels cannot (`selection-erase-unsupported`, for Erase, Delete and Cut), a mask or region the Gradient tool never adds a raster layer for (`gradient-unsupported`), or an open transform session that selection Fill/Erase waits for (`transform-session`, naming the transformed layer). One predicate (`editing/controlPixelEdit.ts` `editsPixelsInPlace`) says which layers the brush, eraser and selection Fill/Erase edit in place. With no layer to act on, an eraser stroke, removing the selection's pixels and a shape cutout (the platform's mod key: ⌘ on macOS, where Ctrl-click opens the context menu, Ctrl elsewhere) each report a `CanvasNoTargetRefusal` (`erase-no-target`, `selection-erase-no-target`, `cutout-no-target`) and never add a layer. The Shape and Gradient tools report at the press when the press already decides the target, and Shape again at commit if the target changed meanwhile. The Brush never creates a layer above a locked or hidden image on its own; its refusal offers one, worded for its cause. Brush, eraser, shape, gradient and move cursors read not-allowed over a selection the press would refuse, the eraser's included when it has nothing to erase; the engine refreshes the cursor on every document change. Cut asks `selection.admitSelectionErase` before it writes the clipboard, so a refused Cut copies nothing. Widget previews of structural edits run in one owned `StructuralPreviewSession` (`useStructuralPreview`), which coalesces live dispatches to one per frame, captures the values its first preview of each field replaces (session's baseline) and records the gesture as a single step from it; refused commit or cancel restores that baseline, even while edits are locked. A commit from elsewhere, a history replay, a newer session or disposal ends an open session first, dropping pending previews and restoring baseline, so previewed values never land over a replayed document or inside another step: every engine edit starts from `CanvasMutationContext.getDocument()`, which ends it first (structural controller's commits and nudges, pixel and layer operations such as merge down and duplicate, result commits); widget-prepared edits (`commitPreparedEdit`, layers tree's child-row commands) end it before reading the model; `HistoryController` ends it (with any live float) before a replay that has a step to land, and a replay with nothing to land disturbs nothing; document replacement drops it without restoring, since the document it previewed on is gone. Widget's next preview starts a new session from changed document, and a commit after engine ended its session records from live values; its refusal as `missing` stays silent, since the document change that ended the gesture also unmounted the editor.Undo and redo are async and failure-atomic: entry moves to the other stack only after its replay completes, replay that throws leaves it in place and is reported, and edits and new gestures are refused while one runs. Replays apply steps through same verified path (`applyStep`). Pixel replays land only on trustworthy pixels: evicted or stale cache is rasterized first under a read lease, and a layer that no longer exists moves the step as a no-op.@@ -244,7 +247,7 @@ History pairing keeps one undo per user intent. A patch with a `coalesceKey` rep### Control layer view-`previews.setControlLayerView(layerId, 'original' | 'map' | 'overlay')` lets the user compare a control layer's map with the picture it was detected from. `ControlViewController` owns the one view that can exist. It refuses while an operation holds the document (`documentEditingLocked`); a generation or staged results do not affect it. Otherwise it reserves raster memory for the original's decoded pixels, rasterizes the `original` source with the layer rasterizers, and once the surface exists accounts it as detached pixels until the view ends; the reservation ends with the decode. `map` ends the view and resolves `shown`.+`previews.setControlLayerView(layerId, 'original' | 'map' | 'overlay')` lets the user compare a control layer's map with the picture it was detected from. `ControlViewController` owns the one view that can exist. It refuses while an operation holds the document (`documentEditingLocked`); a generation or staged results do not affect it, though while a staged preview hides the control stack the view draws nothing and the canvas widget hides its switch. Otherwise it reserves raster memory for the original's decoded pixels, rasterizes the `original` source with the layer rasterizers, and once the surface exists accounts it as detached pixels until the view ends; the reservation ends with the decode. `map` ends the view and resolves `shown`.| Outcome | Meaning || ------------- | -------------------------------------------------------------------------------------- |diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.tsindex c7b9d3f2b1..86f7b845ef 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts@@ -194,6 +194,8 @@ export interface CanvasInteractionState {bboxGrid: number;bboxOptions: BboxToolOptions;bboxOverlay: boolean;+ /** The generation frame as a Frame tool drag shows it, before it commits; null when no drag is under way. */+ bboxPreview: Rect | null;brushOptions: BrushOptions;canRedo: boolean;canUndo: boolean;@@ -225,6 +227,11 @@ export interface CanvasInteractionState {showBbox: boolean;showGrid: boolean;snapToGrid: boolean;+ /**+ * Whether a staged or progress preview, shown or toggled off with the staging bar's eye, hides control layers, masks+ * and regions from the screen. An edit of one shows them meanwhile; that does not change this.+ */+ stagingHidesOverlays: boolean;textEditSession: TextEditSession | null;textOptions: TextToolOptions;transformSession: TransformSession | null;@@ -420,34 +427,52 @@ export interface CanvasHistoryCapability {export type ColorSamplePhase = 'preview' | 'commit' | 'cancel';/**- * A tool press the selected layer cannot take, named so the notice can say which layer and why: it is hidden (disabled,- * itself or through a group), locked, has its transparency locked against the eraser, or its pixels have not loaded- * yet (the engine has started loading them; the next press can edit).+ * An edit the selected layer cannot take, named so the notice can say which layer and why: it is hidden (disabled,+ * itself or through a group), hidden on the canvas only (refused by edits that write pixels), locked, has its+ * transparency locked against erasing, its pixels have not loaded yet (the engine has started loading them; the next+ * press can edit), or it is a control layer whose empty shape has no pixels (`layer-unpaintable`).+ * `erase-unsupported` names a selection the eraser cannot erase in place (a group, text, shape or gradient), where the+ * brush would paint a new layer instead; `selection-erase-unsupported` the same for removing the selection's pixels+ * (Erase, Delete, Cut); `gradient-unsupported` a mask or region, which the Gradient tool never adds a raster layer+ * for; `transform-session` the layer whose open transform session selection Fill and Erase wait for.*/export interface CanvasLayerEditRefusal {- readonly status: 'layer-hidden' | 'layer-locked' | 'layer-alpha-locked' | 'layer-loading';+ readonly status:+ | 'layer-hidden'+ | 'layer-display-hidden'+ | 'layer-locked'+ | 'layer-alpha-locked'+ | 'layer-loading'+ | 'layer-unpaintable'+ | 'erase-unsupported'+ | 'selection-erase-unsupported'+ | 'gradient-unsupported'+ | 'transform-session';readonly layerId: string;readonly layerName: string;/** The brush would have painted this image layer in place; a new paint layer above it can take the stroke. */readonly canPaintNewLayer?: boolean;}-/** A shape cut out with the mod key found no selected paint layer or mask to erase its footprint from. */-export interface CanvasShapeCutoutRefusal {- readonly status: 'cutout-no-target';+/**+ * An erase found no layer selected to act on: an eraser stroke (`erase-no-target`), removing the selection's pixels+ * (`selection-erase-no-target`), or a shape cut out with the mod key (`cutout-no-target`).+ */+export interface CanvasNoTargetRefusal {+ readonly status: 'cutout-no-target' | 'erase-no-target' | 'selection-erase-no-target';}/*** Why the engine refused an edit the user started without a caller to report to (a stroke, a shape). An* `AdjustmentRefusal` names a layer whose spatial adjustments cannot run, so its pixels cannot be baked for painting;- * a `CanvasLayerEditRefusal` names a layer the active tool cannot edit; a `CanvasShapeCutoutRefusal` has no layer to+ * a `CanvasLayerEditRefusal` names a layer the active tool cannot edit; a `CanvasNoTargetRefusal` has no layer to* name.*/export type CanvasEditRefusal =| SubsetOf<CanvasTransactionOutcome, 'busy' | 'gesture-active' | 'not-ready' | 'over-budget'>| AdjustmentRefusal| CanvasLayerEditRefusal- | CanvasShapeCutoutRefusal;+ | CanvasNoTargetRefusal;export type LayerThumbnailRequestResult =| 'ready'@@ -504,6 +529,11 @@ export type ExportBakedLayerBlobResult =| AdjustmentRefusal;export interface CanvasSelectionCapability {+ /**+ * Whether `eraseSelection` would remove the selection's pixels now; otherwise reports why through+ * `tools.onEditRefused`, as the erase would. Cut asks before it writes the clipboard.+ */+ admitSelectionErase(): boolean;deselect(): void;eraseSelection(): void;fillSelection(): void;@@ -887,9 +917,12 @@ export interface StagedPreviewPlacement extends Rect {/*** A staged preview always lands at absolute document coordinates pinned at submission: a candidate at its placement,* a progress frame (scaled to fill) at the rect its run was submitted with. Later bbox edits never move either.+ * `hidden`: the user toggled the candidate off to compare it with the canvas under it. Nothing decodes or draws, but+ * the screen keeps hiding control layers, masks, regions and the regenerate tint as the shown candidate does, so both+ * sides of the comparison read alike.*/export type StagedPreviewInput =- | { imageName: string; placement: StagedPreviewPlacement }+ | { imageName: string; placement: StagedPreviewPlacement; hidden?: boolean }| { dataUrl: string; placement: StagedPreviewPlacement };/** One pending result's landing rect in document space, for the staged-region overlay. */export interface StagedRegion {@@ -962,7 +995,11 @@ export { documentToExportLocalSamPoint } from './samCoordinates';export { bboxEquals, bboxMinSize, roundBbox } from './tools/bboxHitTest';export { isEmpty, union } from './math/rect';export { ZOOM_PRESETS } from './math/snapping';-export { isLeafPixelEditEligible } from './editing/controlPixelEdit';+export {+ isLeafPixelEditEligible,+ selectionPixelEditRefusal,+ type SelectionPixelEditRefusal,+} from './editing/controlPixelEdit';export {getSiblingOrder,haveSameStructure,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.tsindex f5332ce517..6e6e9d1632 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts@@ -534,6 +534,11 @@ export interface CanvasSnapshotContract {}export interface CanvasStagingAreaContractV2 extends CanvasStagingAreaContract {+ /**+ * Auto-switch, the values of the shared policy's `AutoSwitchMode` (`@features/queue/contracts`). Spelled out here: a+ * persisted canvas schema owns its own values, and the canvas engine does not depend on the queue feature. The+ * staging area's loader (`canvasMigration.ts`) fails to compile while the two unions differ.+ */autoSwitchMode: 'off' | 'latest' | 'progress';}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.tsindex 0699255242..8904cae605 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts@@ -85,7 +85,10 @@ export class BooleanMergeController {const eligibility = mergeDownEligibility(document, upperLayerId);if (eligibility.status !== 'eligible') {return eligibility.status === 'missing' ||- (eligibility.status === 'invalid-target' && eligibility.reason === 'no-layer-below')+ (eligibility.status === 'invalid-target' &&+ (eligibility.reason === 'no-layer-below' ||+ eligibility.reason === 'bottom-of-group' ||+ eligibility.reason === 'group-below'))? 'missing': 'unsupported';}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.tsindex b7679f9755..02b9f3e39a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts@@ -67,6 +67,7 @@ const createSelectionPixelOptions = () => ({deleteDerived: vi.fn(),getDocument: () => null,getFillColor: () => '#000',+ getTransformSessionLayerId: () => null,invalidateLayer: vi.fn(),isRasterCacheReady: () => true,isGestureActive: () => false,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/previewStateController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/previewStateController.tsindex 5b28c5cf2f..50900a8de8 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/previewStateController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/previewStateController.ts@@ -56,6 +56,8 @@ export interface SamPreviewState {/** Owns render-preview surfaces and monotonic async publication guards. */export class PreviewStateController {private staged: StagedPreviewState | null = null;+ /** The user toggled the selected result off to compare it with the canvas under it: nothing draws in its place. */+ private stagedHidden = false;private stagedToken = 0;private stagedRegions: readonly StagedRegionState[] = [];private readonly filters = new Map<string, FilterPreviewState>();@@ -66,6 +68,13 @@ export class PreviewStateController {getStaged(): StagedPreviewState | null {return this.staged;}+ /**+ * Whether the screen hides control layers, masks, regions and the regenerate tint for a staged result: while its+ * preview shows, and while the user toggled it off to compare, so both sides of the comparison read alike.+ */+ hidesStagingOverlays(): boolean {+ return this.staged !== null || this.stagedHidden;+ }nextStagedToken(): number {return ++this.stagedToken;}@@ -77,13 +86,24 @@ export class PreviewStateController {return false;}this.staged = preview;+ this.stagedHidden = false;return true;}+ /** Drops the preview and discards a decode in flight. True when the screen changes: something showed or hid. */clearStaged(): boolean {this.stagedToken += 1;- const hadPreview = this.staged !== null;+ const changed = this.hidesStagingOverlays();+ this.staged = null;+ this.stagedHidden = false;+ return changed;+ }+ /** Drops the preview's pixels but keeps hiding what it hides. True when the screen changes. */+ hideStaged(): boolean {+ this.stagedToken += 1;+ const changed = this.staged !== null || !this.stagedHidden;this.staged = null;- return hadPreview;+ this.stagedHidden = true;+ return changed;}getStagedRegions(): readonly StagedRegionState[] {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.browser.test.tsnew file mode 100644index 0000000000..9a74cf4f64--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.browser.test.ts@@ -0,0 +1,192 @@+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';+import type { Rect } from '@workbench/canvas-engine/types';++import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';+import { documentFrom, layerContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createHistory } from '@workbench/canvas-engine/history/history';+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { describe, expect, it, vi } from 'vitest';++import { SelectionPixelController } from './selectionPixelController';++/** Selection Fill/Erase on `layer`, whose 20×20 cache sits at its local origin, over a document-space selection. */+const setup = (layer: CanvasLayerContract, selectionRect: Rect, prefill?: string | { color: string; rect: Rect }) => {+ const backend = createDomRasterBackend();+ const layers = createLayerCacheStore(backend);+ const entry = layers.getOrCreateRect(layer.id, { height: 20, width: 20, x: 0, y: 0 });+ entry.stale = false;+ if (prefill) {+ const area = typeof prefill === 'string' ? { height: 20, width: 20, x: 0, y: 0 } : prefill.rect;+ entry.surface.ctx.fillStyle = typeof prefill === 'string' ? prefill : prefill.color;+ entry.surface.ctx.fillRect(area.x, area.y, area.width, area.height);+ }+ const mask = backend.createSurface(selectionRect.width, selectionRect.height);+ mask.ctx.fillStyle = '#000';+ mask.ctx.fillRect(0, 0, selectionRect.width, selectionRect.height);+ const selection = {+ bounds: () => selectionRect,+ mask: () => ({ rect: selectionRect, surface: mask }),+ } as unknown as SelectionState;+ const document = documentFrom([layer], layer.id);+ const history = createHistory();+ const ctx = createCanvasMutationContext({+ commitEdit: vi.fn(),+ createLayerId: () => 'unused',+ dispatch: () => true,+ editOwner: Symbol('owner'),+ editingLocked: { get: () => false, subscribe: () => () => undefined },+ getDocument: () => document,+ getReducerDocument: () => document,+ history,+ installPrepared: () => undefined,+ isGestureActive: () => false,+ isGuardCurrent: () => true,+ preparePixels: () => {+ throw new Error('unused');+ },+ projectId: 'p',+ refreshMirror: () => undefined,+ reserveRaster: () => ({ lease: { release: () => undefined }, status: 'ok' }),+ subscribeReducer: () => () => undefined,+ });+ const controller = new SelectionPixelController({+ // History writes the patch back at its layer-local rect, as the engine's bridge does.+ applyImagePatch: (layerId, rect, pixels) => {+ const cache = layers.get(layerId)!;+ cache.surface.ctx.putImageData(pixels, rect.x - cache.rect.x, rect.y - cache.rect.y);+ return Promise.resolve();+ },+ backend,+ beginPixelEdit: () => null,+ canEdit: () => true,+ ctx,+ deleteDerived: vi.fn(),+ getDocument: () => document,+ getFillColor: () => '#ff0000',+ getTransformSessionLayerId: () => null,+ invalidateLayer: vi.fn(),+ isGestureActive: () => false,+ isRasterCacheReady: () => true,+ layers,+ markDirty: vi.fn(),+ notifyPainted: vi.fn(),+ reportRefusal: vi.fn(),+ requestRasterization: vi.fn(),+ selection,+ });+ /** RGBA at a layer-local pixel of the cache; transparent outside it. */+ const pixelAt = (x: number, y: number): number[] => {+ const cache = layers.get(layer.id)!;+ const { rect } = cache;+ if (x < rect.x || y < rect.y || x >= rect.x + rect.width || y >= rect.y + rect.height) {+ return [0, 0, 0, 0];+ }+ return [...cache.surface.ctx.getImageData(x - rect.x, y - rect.y, 1, 1).data];+ };+ const cacheRect = () => ({ ...layers.get(layer.id)!.rect });+ return { cacheRect, controller, history, pixelAt };+};++describe('selection Fill and Erase in Chromium', () => {+ it('fills a moved paint layer where the selection covers it, and undo clears it again', async () => {+ const layer = layerContract('paint', 'raster', { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 5 } });+ // Document 12..16 × 7..11 is local 2..6 × 2..6.+ const { controller, history, pixelAt } = setup(layer, { height: 4, width: 4, x: 12, y: 7 });++ controller.run('fill');++ expect(pixelAt(3, 3)).toEqual([255, 0, 0, 255]);+ expect(pixelAt(1, 3)).toEqual([0, 0, 0, 0]);+ expect(pixelAt(13, 8)).toEqual([0, 0, 0, 0]);+ await history.undo();+ expect(pixelAt(3, 3)).toEqual([0, 0, 0, 0]);+ await history.redo();+ expect(pixelAt(3, 3)).toEqual([255, 0, 0, 255]);+ });++ it('fills a rotated, flipped paint layer beyond its cached pixels, growing the cache to take them', async () => {+ // Flipped, then a quarter turn, at (40, 0): local (x, y) lands at document (40 - y, -x).+ const layer = layerContract('paint', 'raster', {+ transform: { rotation: Math.PI / 2, scaleX: -1, scaleY: 1, x: 40, y: 0 },+ });+ // Document 10..14 × -30..-26 is local 26..30 × 26..30, outside the 20×20 cache.+ const { cacheRect, controller, history, pixelAt } = setup(layer, { height: 4, width: 4, x: 10, y: -30 });++ controller.run('fill');++ // The rotation's rounding may add a pixel; the cache must at least reach local (30, 30).+ const grown = cacheRect();+ expect([grown.x, grown.y, grown.x + grown.width >= 30, grown.y + grown.height >= 30]).toEqual([0, 0, true, true]);+ expect(pixelAt(28, 28)).toEqual([255, 0, 0, 255]);+ expect(pixelAt(25, 28)[3]).toBe(0);+ expect(pixelAt(28, 25)[3]).toBe(0);+ await history.undo();+ expect(pixelAt(28, 28)[3]).toBe(0);+ await history.redo();+ expect(pixelAt(28, 28)).toEqual([255, 0, 0, 255]);+ });++ it('fills only the existing pixels of a transparency-locked paint layer', () => {+ const layer = layerContract('paint', 'raster', { isTransparencyLocked: true } as Partial<CanvasLayerContract>);+ const { cacheRect, controller, pixelAt } = setup(+ layer,+ { height: 30, width: 30, x: -5, y: -5 },+ { color: '#ffffff', rect: { height: 20, width: 10, x: 0, y: 0 } }+ );++ controller.run('fill');++ expect(pixelAt(5, 5)).toEqual([255, 0, 0, 255]);+ expect(pixelAt(15, 5)[3]).toBe(0);+ expect(cacheRect()).toEqual({ height: 20, width: 20, x: 0, y: 0 });+ });++ it('fills a mask, and undo and redo take its coverage away and back', async () => {+ const { controller, history, pixelAt } = setup(layerContract('mask', 'inpaint_mask'), {+ height: 4,+ width: 4,+ x: 2,+ y: 2,+ });++ controller.run('fill');+ expect(pixelAt(3, 3)).toEqual([255, 255, 255, 255]);+ await history.undo();+ expect(pixelAt(3, 3)[3]).toBe(0);+ await history.redo();+ expect(pixelAt(3, 3)).toEqual([255, 255, 255, 255]);+ });++ it('fills a scaled mask with opaque white coverage through its transform', () => {+ const layer = layerContract('mask', 'inpaint_mask', {+ transform: { rotation: 0, scaleX: 2, scaleY: 2, x: 0, y: 0 },+ });+ // Document 4..8 × 0..4 is local 2..4 × 0..2.+ const { controller, pixelAt } = setup(layer, { height: 4, width: 4, x: 4, y: 0 });++ controller.run('fill');++ expect(pixelAt(2, 0)).toEqual([255, 255, 255, 255]);+ expect(pixelAt(3, 1)).toEqual([255, 255, 255, 255]);+ expect(pixelAt(1, 0)[3]).toBe(0);+ expect(pixelAt(4, 0)[3]).toBe(0);+ expect(pixelAt(5, 1)[3]).toBe(0);+ });++ it('erases a rotated mask under the selection only', () => {+ // A quarter turn about the origin: local (x, y) lands at document (-y, x).+ const layer = layerContract('mask', 'inpaint_mask', {+ transform: { rotation: Math.PI / 2, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ });+ // Document -6..-2 × 2..6 is local 2..6 × 2..6.+ const { controller, pixelAt } = setup(layer, { height: 4, width: 4, x: -6, y: 2 }, '#ffffff');++ controller.run('erase');++ expect(pixelAt(4, 4)[3]).toBe(0);+ expect(pixelAt(1, 4)[3]).toBe(255);+ expect(pixelAt(4, 7)[3]).toBe(255);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.tsindex f0d281dfe9..de9398644f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.test.ts@@ -1,10 +1,16 @@import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';+import type { PixelEditTransaction } from '@workbench/canvas-engine/tools/tool';import type { Rect } from '@workbench/canvas-engine/types';import { createCanvasMutationContext } from '@workbench/canvas-engine/controllers/mutationContext';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import {+ documentFrom,+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createHistory } from '@workbench/canvas-engine/history/history';import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';@@ -12,16 +18,21 @@ import { describe, expect, it, vi } from 'vitest';import { SelectionPixelController } from './selectionPixelController';-const paintDocument = (source: Record<string, unknown> = { type: 'paint' }): CanvasDocumentContractV3 =>+const paintDocument = (+ source: Record<string, unknown> = { type: 'paint' },+ layer: Record<string, unknown> = {}+): CanvasDocumentContractV3 =>({stacks: stacksFrom([{id: 'paint',isEnabled: true,isLocked: false,+ name: 'paint',source,transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },type: 'raster',+ ...layer,} as unknown as CanvasLayerContract,]),selectedLayerId: 'paint',@@ -35,9 +46,20 @@ const createHarness = (byteBudget?: number;mirrored?: boolean;cacheReady?: boolean;+ beginPixelEdit?: (layerId: string) => PixelEditTransaction | null;+ transformSessionLayerId?: string;} = {}) => {- const backend = createTestStubRasterBackend();+ const stub = createTestStubRasterBackend();+ const surfaces: StubRasterSurface[] = [];+ const backend = {+ ...stub,+ createSurface: (width: number, height: number) => {+ const surface = stub.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ };const layers = createLayerCacheStore(backend);const cacheRect = options.cacheRect === undefined ? { height: 2, width: 2, x: 0, y: 0 } : options.cacheRect;if (cacheRect) {@@ -90,15 +112,18 @@ const createHarness = (reportRefusal: vi.fn(),requestRasterization: vi.fn(),};+ const beginPixelEdit = vi.fn(options.beginPixelEdit ?? ((_layerId: string): PixelEditTransaction | null => null));+ const applyImagePatch = vi.fn((_layerId: string, _rect: Rect, _pixels: ImageData) => Promise.resolve());const controller = new SelectionPixelController({- applyImagePatch: vi.fn(() => Promise.resolve()),+ applyImagePatch,backend,- beginPixelEdit: () => null,+ beginPixelEdit,canEdit: () => true,ctx,deleteDerived: calls.deleteDerived,getDocument: () => document,getFillColor: () => '#f00',+ getTransformSessionLayerId: () => options.transformSessionLayerId ?? null,invalidateLayer: vi.fn(),isGestureActive: () => false,isRasterCacheReady: () => options.cacheReady ?? true,@@ -109,7 +134,14 @@ const createHarness = (requestRasterization: calls.requestRasterization,selection,});- return { calls, controller, history, layers };+ /** Every color a surface was filled with, in order. */+ const fillColors = () =>+ surfaces.flatMap((surface) =>+ surface.callLog+ .filter((entry) => entry.op === 'set' && entry.args[0] === 'fillStyle')+ .map((entry) => entry.args[1])+ );+ return { applyImagePatch, beginPixelEdit, calls, controller, fillColors, history, layers };};describe('SelectionPixelController', () => {@@ -135,6 +167,11 @@ describe('SelectionPixelController', () => {h.controller.run('fill');expect(h.calls.requestRasterization).toHaveBeenCalledWith('paint');+ expect(h.calls.reportRefusal).toHaveBeenCalledWith({+ layerId: 'paint',+ layerName: 'paint',+ status: 'layer-loading',+ });expect(h.layers.peek('paint')).toBeUndefined();expect(h.calls.markDirty).not.toHaveBeenCalled();expect(h.history.canUndo()).toBe(false);@@ -167,4 +204,178 @@ describe('SelectionPixelController', () => {expect(h.calls.markDirty).not.toHaveBeenCalled();expect(h.history.canUndo()).toBe(false);});++ it("edits a moved layer's pixels under the selection, in its local space", async () => {+ const h = createHarness({+ document: paintDocument({ type: 'paint' }, { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 5 } }),+ selectionRect: { height: 2, width: 2, x: 10, y: 5 },+ });++ h.controller.run('fill');++ // The selection sits over the cached pixels at local (0, 0); the cache does not grow out to document (10, 5).+ expect(h.layers.get('paint')!.rect).toEqual({ height: 2, width: 2, x: 0, y: 0 });+ await h.history.undo();+ expect(h.applyImagePatch).toHaveBeenCalledWith('paint', { height: 2, width: 2, x: 0, y: 0 }, expect.anything());+ });++ it.each([+ ['an inpaint mask', 'inpaint_mask'],+ ['a regional guidance layer', 'regional_guidance'],+ ] as const)('fills %s with opaque mask coverage as one step and persists it', (_, type) => {+ const h = createHarness({ document: documentFrom([layerContract('paint', type)], 'paint') });++ h.controller.run('fill');++ expect(h.calls.reportRefusal).not.toHaveBeenCalled();+ expect(h.fillColors()).toEqual(['#ffffff']);+ expect(h.calls.markDirty).toHaveBeenCalledWith('paint');+ expect(h.history.entries().past).toEqual(['Fill selection']);+ });++ it('erases mask coverage as one step', () => {+ const h = createHarness({ document: documentFrom([layerContract('paint', 'inpaint_mask')], 'paint') });++ h.controller.run('erase');++ expect(h.calls.markDirty).toHaveBeenCalledWith('paint');+ expect(h.history.entries().past).toEqual(['Erase selection']);+ });++ it.each([+ ['fill', 'a disabled paint layer', layerContract('paint', 'raster', { isEnabled: false }), 'layer-hidden'],+ ['erase', 'a locked mask', layerContract('paint', 'inpaint_mask', { isLocked: true }), 'layer-locked'],+ [+ 'fill',+ 'a mask hidden on the canvas',+ layerContract('paint', 'inpaint_mask', { isHidden: true }),+ 'layer-display-hidden',+ ],+ [+ 'erase',+ 'a transparency-locked paint layer',+ layerContract('paint', 'raster', { isTransparencyLocked: true } as never),+ 'layer-alpha-locked',+ ],+ ] as const)('refuses to %s %s as the brush and eraser do', (kind, _, layer, status) => {+ const h = createHarness({ document: documentFrom([layer], 'paint') });++ h.controller.run(kind);++ expect(h.calls.reportRefusal).toHaveBeenCalledWith({ layerId: 'paint', layerName: 'paint', status });+ expect(h.calls.markDirty).not.toHaveBeenCalled();+ expect(h.history.canUndo()).toBe(false);+ });++ it('says what an erase cannot act on, and leaves Fill, which is never offered there, silent', () => {+ const group = createHarness({ document: documentFrom([groupContract('g', [layerContract('paint')])], 'g') });+ group.controller.run('erase');+ group.controller.run('fill');+ expect(group.calls.reportRefusal.mock.calls).toEqual([+ [{ layerId: 'g', layerName: 'g', status: 'selection-erase-unsupported' }],+ ]);++ const none = createHarness({ document: documentFrom([layerContract('paint')], null) });+ none.controller.run('erase');+ expect(none.calls.reportRefusal.mock.calls).toEqual([[{ status: 'selection-erase-no-target' }]]);+ expect(group.history.canUndo() || none.history.canUndo()).toBe(false);+ });++ it('edits a raster image through a pixel-edit transaction, which bakes it in place', () => {+ const transaction: PixelEditTransaction = {+ cancel: vi.fn(),+ commit: vi.fn(() => true),+ commitPatch: vi.fn(() => true),+ grow: vi.fn(() => true),+ layerId: 'paint',+ };+ const image = layerContract('paint', 'raster', {+ source: { image: { height: 2, imageName: 'photo', width: 2 }, type: 'image' },+ } as never);+ const h = createHarness({ beginPixelEdit: () => transaction, document: documentFrom([image], 'paint') });++ h.controller.run('fill');++ expect(transaction.commitPatch).toHaveBeenCalledWith(+ 'Fill selection',+ expect.objectContaining({ rect: expect.anything() })+ );+ expect(transaction.cancel).not.toHaveBeenCalled();+ });++ it('erasing outside a raster image leaves it unbaked', () => {+ const image = layerContract('paint', 'raster', {+ source: { image: { height: 2, imageName: 'photo', width: 2 }, type: 'image' },+ } as never);+ const h = createHarness({+ document: documentFrom([image], 'paint'),+ selectionRect: { height: 2, width: 2, x: 20, y: 20 },+ });++ h.controller.run('erase');++ expect(h.beginPixelEdit).not.toHaveBeenCalled();+ expect(h.history.canUndo()).toBe(false);+ });++ it.each(['fill', 'erase'] as const)('refuses to %s while a transform session previews another placement', (kind) => {+ const transaction: PixelEditTransaction = {+ cancel: vi.fn(),+ commit: vi.fn(() => true),+ commitPatch: vi.fn(() => true),+ grow: vi.fn(() => true),+ layerId: 'paint',+ };+ const h = createHarness({+ beginPixelEdit: () => transaction,+ document: documentFrom([layerContract('paint', 'inpaint_mask')], 'paint'),+ transformSessionLayerId: 'paint',+ });++ h.controller.run(kind);++ expect(h.calls.reportRefusal).toHaveBeenCalledWith({+ layerId: 'paint',+ layerName: 'paint',+ status: 'transform-session',+ });+ expect(h.beginPixelEdit).not.toHaveBeenCalled();+ expect(h.calls.markDirty).not.toHaveBeenCalled();+ expect(h.history.canUndo()).toBe(false);+ });++ it("erases a control layer's pixels that are painted but not saved yet", () => {+ const transaction: PixelEditTransaction = {+ cancel: vi.fn(),+ commit: vi.fn(() => true),+ commitPatch: vi.fn(() => true),+ grow: vi.fn(() => true),+ layerId: 'paint',+ };+ // The contract still has no bitmap; only the live 2×2 cache holds the strokes.+ const h = createHarness({+ beginPixelEdit: () => transaction,+ document: documentFrom([layerContract('paint', 'control')], 'paint'),+ });++ h.controller.run('erase');++ expect(h.beginPixelEdit).toHaveBeenCalledWith('paint');+ expect(transaction.commitPatch).toHaveBeenCalledWith('Erase selection', expect.anything());+ });++ it('admits an erase only where one would run, reporting the refusal as the erase would', () => {+ const group = createHarness({ document: documentFrom([groupContract('g', [layerContract('paint')])], 'g') });+ expect(group.controller.admitErase()).toBe(false);+ expect(group.calls.reportRefusal).toHaveBeenCalledWith({+ layerId: 'g',+ layerName: 'g',+ status: 'selection-erase-unsupported',+ });++ const paint = createHarness();+ expect(paint.controller.admitErase()).toBe(true);+ expect(paint.calls.reportRefusal).not.toHaveBeenCalled();+ expect(paint.history.canUndo()).toBe(false);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.tsindex 5a553e2687..733f4a1e52 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/selectionPixelController.ts@@ -1,25 +1,34 @@import type { CanvasEditRefusal } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type { SelectionPixelEditRefusal } from '@workbench/canvas-engine/editing/controlPixelEdit';import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterBackend } from '@workbench/canvas-engine/render/raster';import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';import type { PixelEditTransaction } from '@workbench/canvas-engine/tools/tool';-import type { Rect } from '@workbench/canvas-engine/types';+import type { Mat2d, Rect } from '@workbench/canvas-engine/types';import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';-import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';-import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';-import { getSourceBounds } from '@workbench/canvas-engine/document/sources';+import { getDocumentLayer, getDocumentNode } from '@workbench/canvas-engine/document/documentIndex';+import { isLayerTransparencyLocked } from '@workbench/canvas-engine/document/layerEligibility';+import { isMaskLayer } from '@workbench/canvas-engine/document/sources';+import { selectionPixelEditRefusal } from '@workbench/canvas-engine/editing/controlPixelEdit';import { createImagePatchEntry } from '@workbench/canvas-engine/history/imagePatch';-import { intersect, isEmpty, roundOut } from '@workbench/canvas-engine/math/rect';+import { invert } from '@workbench/canvas-engine/math/mat2d';+import { intersect, isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { eraseMaskedRegion, fillMaskedRegion } from '@workbench/canvas-engine/selection/selectionOps';+import { hittableLayerRect, layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';+import { MASK_PAINT_COLOR } from '@workbench/canvas-engine/tools/paintConstants';import type { CanvasMutationContext, EditTransaction } from './mutationContext';+/**+ * A paint layer or mask is edited in its own local space, the selection mapped into it. A control layer or raster+ * image edits through a pixel-edit transaction, which bakes its transform first, so the document is its space.+ */type PixelTarget =- | { kind: 'raster'; layerId: string; transparencyLocked: boolean }- | { kind: 'control'; transaction: PixelEditTransaction; transparencyLocked: false };+ | { kind: 'direct'; color: string | null; toLocal: Mat2d; transparencyLocked: boolean; txn: EditTransaction }+ | { kind: 'transaction'; transaction: PixelEditTransaction; transparencyLocked: boolean };export interface SelectionPixelControllerOptions {readonly selection: SelectionState;@@ -32,6 +41,8 @@ export interface SelectionPixelControllerOptions {readonly beginPixelEdit: (layerId: string) => PixelEditTransaction | null;readonly canEdit: () => boolean;readonly isGestureActive: () => boolean;+ /** The layer an open transform session previews, whose placement the selection would not match until it lands. */+ readonly getTransformSessionLayerId: () => string | null;readonly getFillColor: () => string;readonly deleteDerived: (layerId: string) => void;readonly invalidateLayer: (layerId: string) => void;@@ -59,59 +70,108 @@ export class SelectionPixelController {constructor(private readonly deps: SelectionPixelControllerOptions) {}- private target(): PixelTarget | null {- const document = this.deps.getDocument();- if (!document?.selectedLayerId) {- return null;+ /**+ * Says why the selection cannot be edited, as the brush and eraser would. Removing the selection's pixels (Erase,+ * Delete, Cut) names what it could not act on; Fill is only offered for a layer it can fill.+ */+ private reportTargetRefusal(+ document: CanvasDocumentContractV3,+ kind: 'fill' | 'erase',+ refusal: SelectionPixelEditRefusal+ ): void {+ const node = getDocumentNode(document, document.selectedLayerId);+ if (refusal === 'no-target' || refusal === 'unsupported') {+ if (kind === 'erase') {+ this.deps.reportRefusal(+ node+ ? { layerId: node.id, layerName: node.name, status: 'selection-erase-unsupported' }+ : { status: 'selection-erase-no-target' }+ );+ }+ return;}- const leaf = lookupDocumentLeaf(document, document.selectedLayerId);- const layer = leaf?.layer;- if (leaf && layer?.type === 'raster' && layer.source.type === 'paint' && isLeafEditable(leaf)) {- return { kind: 'raster', layerId: layer.id, transparencyLocked: layer.isTransparencyLocked === true };+ if (node) {+ this.deps.reportRefusal({ layerId: node.id, layerName: node.name, status: refusal });}- if (layer?.type === 'control') {- const transaction = this.deps.beginPixelEdit(layer.id);- return transaction ? { kind: 'control', transaction, transparencyLocked: false } : null;- }- return null;}- run(kind: 'fill' | 'erase'): void {+ /**+ * The selection and the layer a Fill or Erase would edit now, or null after reporting why not. Waiting pixels are+ * requested, so a later try can edit them.+ */+ private admit(kind: 'fill' | 'erase') {if (this.disposed || !this.deps.canEdit() || this.deps.isGestureActive()) {- return;+ return null;}const document = this.deps.getDocument();const placedMask = this.deps.selection.mask();const bounds = this.deps.selection.bounds();if (!document || !placedMask || !bounds) {- return;+ return null;}- const selectionRect = roundOut(bounds);- const selectedLayer = getDocumentLayer(document, document.selectedLayerId);- if (- selectedLayer?.type === 'raster' &&- selectedLayer.source.type === 'paint' &&- !this.deps.isRasterCacheReady(selectedLayer, document)- ) {- this.deps.requestRasterization(selectedLayer.id);- return;+ const node = getDocumentNode(document, document.selectedLayerId);+ const refusal = selectionPixelEditRefusal(node ? (lookupDocumentLeaf(document, node.id) ?? 'group') : null, kind);+ const layer = getDocumentLayer(document, document.selectedLayerId);+ if (refusal || !layer) {+ this.reportTargetRefusal(document, kind, refusal ?? 'no-target');+ return null;}- if (- kind === 'erase' &&- selectedLayer?.type === 'control' &&- !intersect(selectionRect, roundOut(getSourceBounds(selectedLayer, document)))- ) {- return;+ const sessionLayerId = this.deps.getTransformSessionLayerId();+ if (sessionLayerId !== null) {+ // The session previews a placement the document does not hold yet; editing now would land elsewhere.+ const sessionLayer = getDocumentNode(document, sessionLayerId);+ this.deps.reportRefusal({+ layerId: sessionLayerId,+ layerName: sessionLayer?.name ?? '',+ status: 'transform-session',+ });+ return null;}- const target = this.target();- if (!target) {+ if (!this.deps.isRasterCacheReady(layer, document)) {+ // Editing now would grow a transparent cache over pixels still on their way.+ this.deps.requestRasterization(layer.id);+ this.deps.reportRefusal({ layerId: layer.id, layerName: layer.name, status: 'layer-loading' });+ return null;+ }+ return { document, layer, placedMask, selectionRect: roundOut(bounds) };+ }++ /** Whether an Erase may run now; otherwise it reports why, as the Erase itself would. Cut asks before it copies. */+ admitErase(): boolean {+ return this.admit('erase') !== null;+ }++ run(kind: 'fill' | 'erase'): void {+ const admitted = this.admit(kind);+ if (!admitted) {return;}- if (kind === 'erase' && target.transparencyLocked) {+ const { document, layer, placedMask, selectionRect } = admitted;+ const transparencyLocked = isLayerTransparencyLocked(layer);+ if (layer.type === 'control' || (layer.type === 'raster' && layer.source.type === 'image')) {+ // Nothing to erase is no reason to bake the layer's transform. The extent includes pixels not saved yet.+ const content = hittableLayerRect(layer, document, this.deps.layers.get(layer.id)?.rect);+ if (+ kind === 'erase' &&+ (!content || !intersect(selectionRect, roundOut(transformBounds(layerMatrix(layer.transform), content))))+ ) {+ return;+ }+ const transaction = this.deps.beginPixelEdit(layer.id);+ if (transaction) {+ this.edit(+ kind,+ transaction.layerId,+ { kind: 'transaction', transaction, transparencyLocked },+ selectionRect,+ placedMask+ );+ }return;}- if (target.kind === 'control') {- this.edit(kind, target.transaction.layerId, target, selectionRect, placedMask);+ const toLocal = invert(layerMatrix(layer.transform));+ if (!toLocal) {+ // A zero-scale layer has no pixels under the selection.return;}const txn = this.deps.ctx.begin({ historyBytes: 0 });@@ -120,7 +180,13 @@ export class SelectionPixelController {return;}try {- this.edit(kind, target.layerId, { ...target, txn }, selectionRect, placedMask);+ this.edit(+ kind,+ layer.id,+ { color: isMaskLayer(layer) ? MASK_PAINT_COLOR : null, kind: 'direct', toLocal, transparencyLocked, txn },+ roundOut(transformBounds(toLocal, selectionRect)),+ placedMask+ );} finally {txn.end();}@@ -133,14 +199,13 @@ export class SelectionPixelController {private edit(kind: 'fill' | 'erase',layerId: string,- target:- | Exclude<PixelTarget, { kind: 'raster' }>- | (Extract<PixelTarget, { kind: 'raster' }> & { txn: EditTransaction }),+ target: PixelTarget,+ /** The selection's bounds in the target's space. */selectionRect: Rect,placedMask: NonNullable<ReturnType<SelectionState['mask']>>): void {const { deps } = this;- const live = target.kind === 'control' ? target.transaction : null;+ const live = target.kind === 'transaction' ? target.transaction : null;const existing = deps.layers.get(layerId);const grows = kind === 'fill' && !target.transparencyLocked;const rect = grows@@ -153,7 +218,7 @@ export class SelectionPixelController {return;}const footprint = rect.width * rect.height * 8;- if (!(live ? live.grow(footprint) : target.kind === 'raster' && target.txn.growHistory(footprint))) {+ if (!(live ? live.grow(footprint) : target.kind === 'direct' && target.txn.growHistory(footprint))) {if (!live) {deps.reportRefusal('over-budget');}@@ -181,13 +246,15 @@ export class SelectionPixelController {const surface = entry.surface;const origin = { x: entry.rect.x, y: entry.rect.y };before = surface.ctx.getImageData(rect.x - origin.x, rect.y - origin.y, rect.width, rect.height);+ const maskToLocal = target.kind === 'direct' ? target.toLocal : undefined;if (kind === 'fill') {fillMaskedRegion({backend: deps.backend,- color: deps.getFillColor(),+ color: (target.kind === 'direct' ? target.color : null) ?? deps.getFillColor(),composite: target.transparencyLocked ? 'source-atop' : 'source-over',mask: placedMask.surface,maskOrigin: placedMask.rect,+ maskToLocal,rect,target: surface,targetOrigin: origin,@@ -197,6 +264,7 @@ export class SelectionPixelController {backend: deps.backend,mask: placedMask.surface,maskOrigin: placedMask.rect,+ maskToLocal,rect,target: surface,targetOrigin: origin,@@ -208,7 +276,7 @@ export class SelectionPixelController {published = live.commitPatch(label, { after, before, rect });return;}- if (target.kind !== 'raster' || imageDataEqual(before, after)) {+ if (target.kind !== 'direct' || imageDataEqual(before, after)) {return;}const result = target.txn.publish(diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.tsindex a6cb872dcb..bfd963a557 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.test.ts@@ -146,6 +146,28 @@ describe('TransformEditingController', () => {expect(h.calls.setOverride).toHaveBeenLastCalledWith('shape', null);});+ it.each([+ ['an inpaint mask', 'inpaint_mask'],+ ['a regional guidance layer', 'regional_guidance'],+ ] as const)('commits %s transform as a structural edit, never baking its coverage', (_, type) => {+ const mask = layerContract('mask', type, {+ mask: { bitmap: { height: 4, imageName: 'mask.png', width: 4 }, fill: { color: '#e07575', style: 'diagonal' } },+ } as Partial<CanvasLayerContract>);+ const h = createHarness(mask);+ expect(h.controller.request('mask')).toBe('started');+ expect(h.session()).toMatchObject({ layerId: 'mask' });+ h.controller.update(MOVED);+ h.controller.apply();++ expect(h.calls.commitStructural).toHaveBeenCalledWith(+ 'Transform layer',+ expect.objectContaining({ id: 'mask', patch: { transform: MOVED } }),+ expect.objectContaining({ id: 'mask', patch: { transform: expect.objectContaining({ x: 0 }) } })+ );+ expect(h.calls.restoreCache).not.toHaveBeenCalled();+ expect(h.session()).toBeNull();+ });+it('keeps the session open and reports a refused commit', () => {const h = createHarness(shape, { commitStatus: 'busy' });h.controller.begin('shape');@@ -326,7 +348,7 @@ describe('TransformEditingController.request', () => {it.each([['a locked leaf', { ...b, isLocked: true }, 'locked'],- ['a mask', layerContract('b', 'inpaint_mask'), 'ineligible'],+ ['an empty mask', layerContract('b', 'inpaint_mask'), 'ineligible'],['a missing leaf', null, 'missing'],] as const)('refuses %s without selecting or switching tools', (_, target, status) => {const h = createHarness(target ? [a, target] : [a]);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.tsindex b4c88675eb..55cb6a916d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/transformEditingController.ts@@ -15,7 +15,7 @@ import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/docuimport { rebaseControlOriginal } from '@workbench/canvas-engine/document/controlDerivation';import { getDocumentLayer } from '@workbench/canvas-engine/document/documentIndex';import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';-import { isRenderableLayer } from '@workbench/canvas-engine/document/sources';+import { isMaskLayer, isRenderableLayer } from '@workbench/canvas-engine/document/sources';import {collectHistoryMediaRefs,HISTORY_ENTRY_OVERHEAD_BYTES,@@ -287,7 +287,9 @@ export class TransformEditingController {return;}const source = layer.type === 'raster' || layer.type === 'control' ? layer.source : null;+ // A mask keeps its transform like an image, so its coverage is resampled only when composited, never baked.if (+ isMaskLayer(layer) ||source?.type === 'image' ||source?.type === 'shape' ||source?.type === 'gradient' ||diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentCommands.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentCommands.tsindex 9981b320a4..6543f21ee2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentCommands.ts@@ -91,7 +91,10 @@ export type InvalidTargetReason =| 'depth-exceeded'| 'node-limit'| 'no-layer-below'- | 'not-mergeable';+ | 'bottom-of-group'+ | 'group-below'+ | 'not-mergeable'+ | 'disabled';export type EditHistoryPolicy = 'record' | 'none';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.tsindex 433808ed6b..476b529423 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts@@ -1260,9 +1260,10 @@ describe('createDocumentModel', () => {const project = projectWith([layer('a'), layer('b'), group('G', [layer('c'), layer('d')]), layer('e')], 'a');const model = modelOf(project);expect(model.canMergeDown('a')).toEqual({ lowerId: 'b', status: 'eligible', upperId: 'a' });- expect(model.canMergeDown('b')).toEqual({ reason: 'no-layer-below', status: 'invalid-target', targetId: 'b' });+ expect(model.canMergeDown('b')).toEqual({ reason: 'group-below', status: 'invalid-target', targetId: 'G' });expect(model.canMergeDown('c')).toEqual({ lowerId: 'd', status: 'eligible', upperId: 'c' });- expect(model.canMergeDown('d')).toEqual({ reason: 'no-layer-below', status: 'invalid-target', targetId: 'd' });+ expect(model.canMergeDown('d')).toEqual({ reason: 'bottom-of-group', status: 'invalid-target', targetId: 'd' });+ expect(model.canMergeDown('e')).toEqual({ reason: 'no-layer-below', status: 'invalid-target', targetId: 'e' });expect(model.canMergeDown('G')).toEqual({ actual: 'group', expected: ['raster'], status: 'wrong-type' });});@@ -1270,11 +1271,8 @@ describe('createDocumentModel', () => {const locked = projectWith([group('G', [layer('a'), layer('b')], { isLocked: true })], null);expect(modelOf(locked).canMergeDown('a')).toEqual({ ids: ['G'], status: 'locked' });const off = projectWith([group('G', [layer('a'), layer('b')], { isEnabled: false })], null);- expect(modelOf(off).canMergeDown('a')).toEqual({- reason: 'not-mergeable',- status: 'invalid-target',- targetId: 'a',- });+ // The group that disables the pair is named, not the layer.+ expect(modelOf(off).canMergeDown('a')).toEqual({ reason: 'disabled', status: 'invalid-target', targetId: 'G' });});it.each<[string, CanvasNodeContract[], string, object]>([@@ -1291,7 +1289,19 @@ describe('createDocumentModel', () => {'a disabled upper layer',[layer('a', 'raster', { isEnabled: false }), layer('b')],'a',- { reason: 'not-mergeable', status: 'invalid-target', targetId: 'a' },+ { reason: 'disabled', status: 'invalid-target', targetId: 'a' },+ ],+ [+ 'paint above a disabled shape layer, for its kind first',+ [+ layer('a'),+ layer('b', 'raster', {+ isEnabled: false,+ source: { fill: '#fff', height: 4, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 4 },+ } as never),+ ],+ 'a',+ { reason: 'not-mergeable', status: 'invalid-target', targetId: 'b' },],])('refuses %s', (_label, nodes, upperId, refusal) => {expect(modelOf(projectWith(nodes, null)).canMergeDown(upperId)).toEqual(refusal);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.tsindex 7369ff3046..806c447e5b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts@@ -267,7 +267,12 @@ export const lookupLayerBelow = (document: DocumentView, id: string): CanvasLayereturn below && !isGroupNode(below) ? below : null;};-/** Merge-down joins a raster leaf with the raster leaf directly below it under the same parent. */+/**+ * Merge-down joins a raster leaf with the raster leaf directly below it under the same parent. A refusal says which:+ * nothing below at the top level (`no-layer-below`) or in a group (`bottom-of-group`), a group below (`group-below`,+ * naming it), a layer of either pair that is not paint or image pixels (`not-mergeable`), a lock (naming each locked+ * node), or a disabled layer or ancestor group (`disabled`, naming it).+ */export const mergeDownEligibility = (document: CanvasDocumentContractV3, upperId: string): MergeDownEligibility => {const index = getDocumentIndex(document);const upper = index.byId.get(upperId);@@ -277,10 +282,18 @@ export const mergeDownEligibility = (document: CanvasDocumentContractV3, upperIdif (isGroupNode(upper.node) || upper.stack !== 'raster') {return { actual: upper.node.type, expected: ['raster'], status: 'wrong-type' };}- const lower = lookupLayerBelow(document, upperId);- if (!lower) {- return { reason: 'no-layer-below', status: 'invalid-target', targetId: upperId };+ const sibling = childrenAt(index, upper.stack, upper.parentId)?.[upper.siblingIndex + 1];+ if (!sibling) {+ return {+ reason: upper.parentId === null ? 'no-layer-below' : 'bottom-of-group',+ status: 'invalid-target',+ targetId: upperId,+ };+ }+ if (isGroupNode(sibling)) {+ return { reason: 'group-below', status: 'invalid-target', targetId: sibling.id };}+ const lower = sibling;const pair = [upper.node, lower];const unmergeable = pair.find((layer) => layer.type !== 'raster' || !isPixelBackedLayer(layer));if (unmergeable) {@@ -293,9 +306,12 @@ export const mergeDownEligibility = (document: CanvasDocumentContractV3, upperIdif (locked.length > 0) {return { ids: locked, status: 'locked' };}- const disabled = pair.find((layer) => !isLayerContributing(layer));- if (disabled || !upper.ancestorsEnabled) {- return { reason: 'not-mergeable', status: 'invalid-target', targetId: disabled?.id ?? upperId };+ // Both share the upper layer's ancestors, so a disabled group gates the pair; name that group.+ const disabledId =+ upper.path.find((id) => !index.byId.get(id)!.node.isEnabled) ??+ pair.find((layer) => !isLayerContributing(layer))?.id;+ if (disabledId) {+ return { reason: 'disabled', status: 'invalid-target', targetId: disabledId };}return { lowerId: lower.id, status: 'eligible', upperId };};diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.tsindex 73acf53b75..69d9129e62 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/screenComposition.test.ts@@ -73,16 +73,16 @@ describe('planScreenComposition', () => {expect(plan.isolationLayerId).toBe('c1');});- it('hides mask and region stacks as staging does, while an isolated mask still draws', () => {+ it('hides every overlay stack as staging does, while an isolated mask still draws', () => {const nodes = [layer('m1', 'inpaint_mask'),groupContract('regions', [layer('g1', 'regional_guidance')]),layer('c1', 'control'),layer('r1', 'raster'),];- const staging = { control: true, inpaint_mask: false, regional_guidance: false };+ const staging = { control: false, inpaint_mask: false, regional_guidance: false };- expect(drawn(planScreenComposition(leaves(nodes), view({ showOverlayStacks: staging })))).toEqual(['r1', 'c1']);+ expect(drawn(planScreenComposition(leaves(nodes), view({ showOverlayStacks: staging })))).toEqual(['r1']);expect(drawn(planScreenComposition(leaves(nodes), view({ isolationLayerId: 'm1', showOverlayStacks: staging })))).toEqual(['m1']);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.tsindex 9e5c000716..23ffdb3c3a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.test.ts@@ -1,7 +1,16 @@-import type { CanvasControlLayerContract, CanvasLayerContract } from '@workbench/canvas-engine/contracts';+import type {+ CanvasControlLayerContract,+ CanvasLayerContract,+ CanvasNodeContract,+} from '@workbench/canvas-engine/contracts';-import { documentFrom, groupContract } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import {+ documentFrom,+ groupContract,+ layerContract,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';+import { leafEditRefusal } from '@workbench/canvas-engine/document/layerEligibility';import { createTestStubRasterBackend, type StubRasterSurface } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it } from 'vitest';@@ -10,6 +19,7 @@ import {buildMaterializedPixelLayer,decidePixelEdit,isLeafPixelEditEligible,+ leafPaintRefusal,} from './controlPixelEdit';const control = (overrides: Partial<CanvasControlLayerContract> = {}): CanvasControlLayerContract => ({@@ -281,3 +291,24 @@ describe('bakePixelEditSurface', () => {]);});});++describe('leafPaintRefusal', () => {+ const leafOf = (node: CanvasNodeContract) => compileDocumentLeaves(documentFrom([node]))[0]!;++ it.each([+ ['an editable mask', {}, null],+ ['a disabled mask', { isEnabled: false }, 'layer-hidden'],+ ['a mask hidden on the canvas', { isHidden: true }, 'layer-display-hidden'],+ ['a locked mask', { isLocked: true }, 'layer-locked'],+ ['a disabled, hidden, locked mask', { isEnabled: false, isHidden: true, isLocked: true }, 'layer-hidden'],+ ['a hidden, locked mask', { isHidden: true, isLocked: true }, 'layer-display-hidden'],+ ] as const)('answers %s with %s', (_, overrides, expected) => {+ expect(leafPaintRefusal(leafOf(layerContract('m', 'inpaint_mask', overrides)))).toBe(expected);+ });++ it('folds a group that hides its children on the canvas, which edit refusals ignore', () => {+ const leaf = leafOf(groupContract('g', [layerContract('m', 'inpaint_mask')], { isHidden: true }));+ expect(leafPaintRefusal(leaf)).toBe('layer-display-hidden');+ expect(leafEditRefusal(leaf)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.tsindex 67b9d59df0..389fac6274 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/editing/controlPixelEdit.ts@@ -1,13 +1,17 @@-/** Policy and pure transforms shared by control and raster-image pixel editing. */+/** Policy and pure transforms shared by control and raster-image pixel editing, and selection Fill/Erase targets. */-import type { CanvasControlLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';+import type {+ CanvasControlLayerContract,+ CanvasLayerContract,+ CanvasRasterLayerContractV2,+} from '@workbench/canvas-engine/contracts';import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Rect } from '@workbench/canvas-engine/types';import { rebaseControlOriginal } from '@workbench/canvas-engine/document/controlDerivation';-import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';-import { isEmptyPolygonShape } from '@workbench/canvas-engine/document/sources';+import { isLayerTransparencyLocked, isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';+import { isEmptyPolygonShape, isMaskLayer } from '@workbench/canvas-engine/document/sources';import { roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';import { bakeMatrix, IDENTITY_TRANSFORM, type LayerTransform } from '@workbench/canvas-engine/transform/transformMath';@@ -46,6 +50,67 @@ export const isLeafPixelEditEligible = (leaf: SemanticLeaf | null | undefined):((leaf.layer.type === 'raster' && leaf.layer.source.type === 'paint') ||(leaf.layer.type === 'control' && isRasterizable(leaf.layer)));+/**+ * `leafEditRefusal` for edits that write pixels (brush, eraser, shapes, selection Fill/Erase), which also refuse a leaf+ * hidden on the canvas only: its pixels would change unseen. Moves and transforms keep `leafEditRefusal`. It lives+ * with the pixel-edit policy rather than `document/layerEligibility.ts` because only lazily loaded editing code uses+ * it, and that module ships in the editor's initial chunk.+ */+export const leafPaintRefusal = (+ leaf: SemanticLeaf+): 'layer-display-hidden' | 'layer-hidden' | 'layer-locked' | null =>+ !leaf.contributionEnabled+ ? 'layer-hidden'+ : leaf.documentHidden+ ? 'layer-display-hidden'+ : leaf.effectiveLocked+ ? 'layer-locked'+ : null;++/** Why selection Fill or Erase cannot edit the selection; `no-target` when nothing is selected. */+export type SelectionPixelEditRefusal =+ | 'no-target'+ | 'unsupported'+ | 'layer-unpaintable'+ | NonNullable<ReturnType<typeof leafPaintRefusal>>+ | 'layer-alpha-locked';++/**+ * Whether the brush, the eraser and selection Fill/Erase edit `layer`'s own pixels: a paint or image raster, a mask or+ * region, or a control layer with pixels. A control layer whose shape is an empty polygon has none and is refused+ * (`layer-unpaintable`); any other layer is not edited in place.+ */+export const editsPixelsInPlace = (layer: CanvasLayerContract): boolean =>+ isMaskLayer(layer) ||+ (layer.type === 'raster'+ ? layer.source.type === 'paint' || layer.source.type === 'image'+ : layer.type === 'control' && isRasterizable(layer));++/**+ * Why selection Fill or Erase cannot edit the selection, refusing as the brush and eraser do; null when it can.+ * `selected` is the selected leaf, `'group'` for a selected group, or null when nothing is selected. Pixels still+ * loading are not predicted: the edit itself waits for them. Callers look the selection up, so this module takes no+ * document lookup: one would place it, through the document model, in the editor's initial chunk.+ */+export const selectionPixelEditRefusal = (+ selected: SemanticLeaf | 'group' | null,+ kind: 'fill' | 'erase'+): SelectionPixelEditRefusal | null => {+ if (selected === null) {+ return 'no-target';+ }+ if (selected === 'group') {+ return 'unsupported';+ }+ const leaf = selected;+ if (!editsPixelsInPlace(leaf.layer)) {+ return leaf.layer.type === 'control' ? 'layer-unpaintable' : 'unsupported';+ }+ return (+ leafPaintRefusal(leaf) ?? (kind === 'erase' && isLayerTransparencyLocked(leaf.layer) ? 'layer-alpha-locked' : null)+ );+};+export const decidePixelEdit = ({contributionEnabled = true,effectiveLocked = false,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 7f5e5e3eb6..da2506fa95 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -15409,6 +15409,8 @@ describe('doc-replace mid-gesture: cancels the active tool gesture', () => {// Start a bbox move-drag (press inside the 100x100 frame, then drag).overlay.fire('pointerdown', pointerAt(40, 40));overlay.fire('pointermove', pointerAt(60, 60));+ // Published to callers too, so canvas chrome can follow the drag.+ expect(engine.interaction.get('bboxPreview')).toEqual(engine.stores.bboxPreview.get());expect(engine.stores.bboxPreview.get()).not.toBeNull();// A wholesale document swap mid-drag (dims change → onDocumentReplaced).@@ -16013,7 +16015,7 @@ describe('masks while a result is staged', () => {composite.mockRestore();engine.lifecycle.dispose();};- return { dispose, engine, expectPressHidden, frame, key, overlay, select, showPreview, update, useTool };+ return { dispose, engine, expectPressHidden, frame, key, overlay, select, showPreview, store, update, useTool };};it('hides masks and region tints under a shown preview, showing them only while a gesture edits a mask', async () => {@@ -16021,7 +16023,7 @@ describe('masks while a result is staged', () => {const { frame, overlay } = h;expect(frame()).toEqual({ ...MASKED, full: 1 });- // A staged candidate whose preview is off hides nothing, so staging it repaints nothing either.+ // Staging data alone repaints nothing: the screen follows only what the canvas widget publishes.h.update({ stagingArea: { ...makeCanvas(makeDoc()).stagingArea, isVisible: false, pendingImages: [candidate] } });expect(frame().drawn).toBeUndefined();@@ -16094,6 +16096,184 @@ describe('masks while a result is staged', () => {h.dispose();});+ it('hides control layers under a shown preview too, showing them while a stroke paints one', async () => {+ const h = setup(stacksFrom([controlLayerForThumbnail('c'), maskLayer('m'), rasterLayer('a')]));+ const { frame, overlay } = h;+ const SHOWN = { drawn: ['a', 'c', 'm'], regionOverlays: true };+ expect(frame()).toEqual({ ...SHOWN, full: 1 });++ // Only raster layers draw under the result; selecting the control layer alone keeps it hidden.+ await h.showPreview();+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+ h.select('c');+ expect(frame().drawn ?? UNMASKED.drawn).toEqual(UNMASKED.drawn);++ // A brush stroke on it shows the overlay stacks for the stroke, and hides them again as it lands.+ h.useTool('brush');+ overlay.fire('pointerdown', pointerAt(5, 5));+ expect(frame()).toEqual({ ...SHOWN, full: 1 });+ overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });++ // Accepting or discarding ends the preview, and the control layer draws again.+ h.engine.previews.setStagedPreview(null);+ expect(frame()).toEqual({ ...SHOWN, full: 1 });+ h.dispose();+ });++ it('shows them while a transform session is open on a control layer, until it is applied or cancelled', async () => {+ const h = setup(stacksFrom([controlLayerForThumbnail('c'), maskLayer('m'), rasterLayer('a')]));+ const { frame } = h;+ const SHOWN = { drawn: ['a', 'c', 'm'], regionOverlays: true };+ await h.showPreview();+ h.select('c');+ await flushMicrotasks();+ frame();++ for (const end of ['cancelTransform', 'applyTransform'] as const) {+ expect(h.engine.layers.beginTransform('c')).toBe('started');+ expect(frame()).toEqual({ ...SHOWN, full: 1 });+ // A step of the session keeps them shown.+ h.engine.layers.updateTransformSession({ ...h.engine.stores.transformSession.get()!.transform, x: 5 });+ expect(frame()).toMatchObject(SHOWN);+ h.engine.layers[end]();+ await flushMicrotasks();+ expect(h.engine.stores.transformSession.get()).toBeNull();+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+ }+ h.dispose();+ });++ it('shows them while a float lifted from a control layer exists, until it is dropped or cancelled', async () => {+ const h = setup(stacksFrom([controlLayerForThumbnail('c'), maskLayer('m'), rasterLayer('a')]));+ const { frame, overlay } = h;+ const SHOWN = { drawn: ['a', 'c', 'm'], regionOverlays: true };+ await h.showPreview();+ h.select('c');+ await flushMicrotasks();+ frame();+ h.useTool('move');++ // Apply banks a float and Cancel abandons it, as for a transform session.+ for (const end of ['cancelTransform', 'applyTransform'] as const) {+ h.engine.selection.selectAll();+ frame();+ overlay.fire('pointerdown', pointerAt(5, 5));+ overlay.fire('pointermove', pointerAt(15, 15));+ expect(h.engine.stores.hasFloatingSelection.get()).toBe(true);+ expect(frame()).toEqual({ ...SHOWN, full: 1 });+ overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));+ // The float outlives the drag that lifted it, and so does the reveal.+ expect(frame()).toMatchObject(SHOWN);+ h.engine.layers[end]();+ expect(h.engine.stores.hasFloatingSelection.get()).toBe(false);+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+ }+ h.dispose();+ });++ it('follows the held layer to its new stack when a conversion or its undo lands during a transform session', async () => {+ const control = controlLayerForThumbnail('c');+ const h = setup(stacksFrom([control, maskLayer('m'), rasterLayer('a')]));+ const { frame } = h;+ await h.showPreview();+ h.select('c');+ await flushMicrotasks();+ frame();+ expect(h.engine.layers.beginTransform('c')).toBe('started');+ expect(frame()).toEqual({ drawn: ['a', 'c', 'm'], full: 1, regionOverlays: true });++ // The layer keeps its id and its session but becomes a raster layer, which the preview does not hide.+ const withLayer = (layer: CanvasLayerContract) =>+ h.update({+ document: {+ ...h.engine.document.getDocument()!,+ stacks: stacksFrom([layer, maskLayer('m'), rasterLayer('a')]),+ },+ });+ withLayer({ ...rasterLayer('c'), transform: control.transform });+ expect(h.engine.stores.transformSession.get()?.layerId).toBe('c');+ expect(frame()).toEqual({ drawn: ['a', 'c'], full: 1, regionOverlays: false });++ // Undoing the conversion makes it a control layer again, and the stacks show for the rest of the session.+ withLayer(control);+ expect(frame()).toEqual({ drawn: ['a', 'c', 'm'], full: 1, regionOverlays: true });+ h.engine.layers.cancelTransform();+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+ h.dispose();+ });++ it('keeps them hidden for a transform session or float on a raster layer', async () => {+ // A paint layer, so pixels can be lifted from it.+ const paint: CanvasRasterLayerContractV2 = {+ ...(rasterLayer('a') as CanvasRasterLayerContractV2),+ source: { bitmap: { height: 20, imageName: 'a.png', width: 20 }, offset: { x: 0, y: 0 }, type: 'paint' },+ };+ const h = setup(stacksFrom([controlLayerForThumbnail('c'), maskLayer('m'), paint]));+ const { frame, overlay } = h;+ await h.showPreview();+ h.select('a');+ await flushMicrotasks();+ frame();++ expect(h.engine.layers.beginTransform('a')).toBe('started');+ expect(frame().drawn ?? UNMASKED.drawn).toEqual(UNMASKED.drawn);+ h.engine.layers.cancelTransform();+ expect(frame().drawn ?? UNMASKED.drawn).toEqual(UNMASKED.drawn);++ h.useTool('move');+ h.engine.selection.selectAll();+ frame();+ overlay.fire('pointerdown', pointerAt(5, 5));+ overlay.fire('pointermove', pointerAt(15, 15));+ overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));+ expect(h.engine.stores.hasFloatingSelection.get()).toBe(true);+ expect(frame()).toMatchObject({ regionOverlays: false });+ expect(frame().drawn ?? UNMASKED.drawn).toEqual(UNMASKED.drawn);+ h.engine.layers.applyTransform();+ expect(h.engine.stores.hasFloatingSelection.get()).toBe(false);+ expect(frame().drawn ?? UNMASKED.drawn).toEqual(UNMASKED.drawn);+ h.dispose();+ });++ it('keeps them hidden while the eye hides the result to compare, until staging ends, changing no state', async () => {+ const h = setup();+ const { frame, overlay } = h;+ await h.showPreview();+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+ const document = h.engine.document.getDocument();++ // The eye shows the canvas under the result as the shown result left it: no mask, no region tint.+ h.update({ stagingArea: { ...makeCanvas(makeDoc()).stagingArea, isVisible: false, pendingImages: [candidate] } });+ h.engine.previews.setStagedPreview({ ...candidate, hidden: true });+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+ // Selecting another hidden candidate repaints nothing; showing and hiding again never brings the mask back.+ h.engine.previews.setStagedPreview({ hidden: true, imageName: 'other.png', placement: candidate.placement });+ expect(frame().drawn).toBeUndefined();+ await h.showPreview();+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });+ h.engine.previews.setStagedPreview({ ...candidate, hidden: true });+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });++ // Nothing but the screen changed: the mask's visibility and the document stand, nothing recorded or dispatched.+ expect(h.engine.document.getDocument()).toBe(document);+ expect(h.engine.history.getEntries()).toEqual({ evicted: 0, future: [], past: [] });+ expect(h.store.dispatch).not.toHaveBeenCalled();++ // A stroke on the mask shows it while it paints, as over the shown result, and hides it as it lands.+ h.select('m');+ h.useTool('brush');+ overlay.fire('pointerdown', pointerAt(5, 5));+ expect(frame()).toEqual({ ...MASKED, full: 1 });+ overlay.fire('pointerup', pointerAt(15, 15, { buttons: 0 }));+ expect(frame()).toEqual({ ...UNMASKED, full: 1 });++ // Accepting or discarding ends the preview, and the mask shows again.+ h.engine.previews.setStagedPreview(null);+ expect(frame()).toEqual({ ...MASKED, full: 1 });+ h.dispose();+ });+it('keeps the selected mask loaded while hidden, so a stroke on it starts at once', async () => {const h = setup(stacksFrom([rasterLayer('a')]));await h.showPreview();@@ -17513,10 +17693,15 @@ describe('engine selection: fill / erase', () => {engine.lifecycle.dispose();});- it('fillSelection is a no-op on an image-source layer (deferred to rasterize task)', () => {+ it('fillSelection refuses an image layer whose pixels have not loaded, asking for them', () => {const { engine } = makeEngine(imageSelectedDoc());+ const refusals: CanvasEditRefusal[] = [];+ engine.tools.onEditRefused((refusal) => refusals.push(refusal));engine.selection.selectAll();engine.selection.fillSelection();+ // Materializing now would bake an empty cache over the image; the real edit is covered in Chromium+ // (`widgets/canvas/canvasSelectionEdits.browser.test.ts`).+ expect(refusals).toEqual([{ layerId: 'img', layerName: 'img', status: 'layer-loading' }]);expect(editSteps(engine)).toEqual([]);engine.lifecycle.dispose();});@@ -18475,6 +18660,156 @@ describe('Select Object canvas engine integration', () => {h.engine.lifecycle.dispose();});+ it('places the first click as a point right after starting from another tool, with auto-update scheduling it', async () => {+ const h = await createSamHarness();+ h.engine.tools.setTool('brush');+ expect(getCanvasOperations(h.engine).startSelectObject('source')).toBe('started');+ expect(getCanvasOperations(h.engine).stores.samSession.get()?.autoProcess).toBe(true);++ h.overlay.fire('pointerdown', pointerAt(5, 5));+ h.overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));++ expect(getCanvasOperations(h.engine).stores.samSession.get()).toMatchObject({+ input: { includePoints: [{ x: 5, y: 5 }] },+ status: 'scheduled',+ });+ expect(h.engine.stores.activeTool.get()).toBe('sam');+ expect(getCanvasOperations(h.engine).controller.getSnapshot()).toMatchObject({ status: 'active' });+ h.engine.lifecycle.dispose();+ });++ it('places the first click of a session started right after cancelling one that was waiting to process', async () => {+ const h = await createSamHarness();+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ const operations = getCanvasOperations(h.engine);+ operations.startSelectObject('source');+ h.overlay.fire('pointerdown', pointerAt(5, 5));+ h.overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));+ expect(operations.stores.samSession.get()?.status).toBe('scheduled');++ operations.cancelSelectObjectSession();+ expect(operations.startSelectObject('source')).toBe('started');+ h.overlay.fire('pointerdown', pointerAt(20, 30));+ h.overlay.fire('pointerup', pointerAt(20, 30, { buttons: 0 }));++ expect(operations.stores.samSession.get()).toMatchObject({+ input: { includePoints: [{ x: 20, y: 30 }] },+ status: 'scheduled',+ });+ // The cancelled session's debounce must not land on, or reset, the new one.+ await vi.advanceTimersByTimeAsync(500);+ h.overlay.fire('pointerdown', pointerAt(40, 40));+ h.overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));+ expect(operations.stores.samSession.get()?.input.includePoints).toEqual([+ { x: 20, y: 30 },+ { x: 40, y: 40 },+ ]);+ expect(h.engine.stores.activeTool.get()).toBe('sam');+ h.engine.lifecycle.dispose();+ } finally {+ vi.useRealTimers();+ }+ });++ describe('canvas input overlapping auto-update processing', () => {+ type GraphResult = { height: number; imageName: string; origin: string; width: number };+ const click = (h: Awaited<ReturnType<typeof createSamHarness>>, x: number, y: number): void => {+ h.overlay.fire('pointerdown', pointerAt(x, y));+ h.overlay.fire('pointerup', pointerAt(x, y, { buttons: 0 }));+ };+ const startWithGraph = async (runGraph: () => Promise<GraphResult>) => {+ const graph = vi.fn(runGraph);+ const h = await createSamHarness({ runGraph: graph });+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const operations = getCanvasOperations(h.engine);+ expect(operations.startSelectObject('source')).toBe('started');+ expect(operations.stores.samSession.get()?.autoProcess).toBe(true);+ return { graph, h, operations };+ };++ afterEach(() => {+ vi.useRealTimers();+ });++ it('keeps a click whose press spans the debounce firing and the run starting', async () => {+ const pending = createDeferred<GraphResult>();+ const { graph, h, operations } = await startWithGraph(() => pending.promise);+ click(h, 20, 20);++ h.overlay.fire('pointerdown', pointerAt(40, 40));+ await vi.advanceTimersByTimeAsync(1_100);+ expect(graph).toHaveBeenCalledOnce();+ expect(operations.stores.samSession.get()?.status).toBe('processing-sam');+ h.overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));++ expect(operations.stores.samSession.get()).toMatchObject({+ input: {+ includePoints: [+ { x: 20, y: 20 },+ { x: 40, y: 40 },+ ],+ },+ status: 'scheduled',+ });+ expect(h.engine.stores.activeTool.get()).toBe('sam');+ h.engine.lifecycle.dispose();+ });++ it('adds a click made while a run is in flight, invalidates that run and schedules a new one', async () => {+ const first = createDeferred<GraphResult>();+ const { graph, h, operations } = await startWithGraph(() =>+ graph.mock.calls.length === 1+ ? first.promise+ : Promise.resolve({ height: 100, imageName: 'second.png', origin: 'test', width: 100 })+ );+ click(h, 20, 20);+ await vi.advanceTimersByTimeAsync(1_100);+ expect(operations.stores.samSession.get()?.status).toBe('processing-sam');++ click(h, 40, 40);+ expect(operations.stores.samSession.get()).toMatchObject({+ input: {+ includePoints: [+ { x: 20, y: 20 },+ { x: 40, y: 40 },+ ],+ },+ status: 'scheduled',+ });+ first.resolve({ height: 100, imageName: 'first.png', origin: 'test', width: 100 });+ await vi.advanceTimersByTimeAsync(0);+ expect(operations.stores.samSession.get()).toMatchObject({ hasPreview: false, status: 'scheduled' });++ await vi.advanceTimersByTimeAsync(1_100);+ expect(graph).toHaveBeenCalledTimes(2);+ expect(h.engine.stores.activeTool.get()).toBe('sam');+ h.engine.lifecycle.dispose();+ });++ it('adds a click made right after a run fails and clears the error', async () => {+ const { h, operations } = await startWithGraph(() => Promise.reject(new Error('backend down')));+ click(h, 20, 20);+ await vi.advanceTimersByTimeAsync(1_100);+ expect(operations.stores.samSession.get()).toMatchObject({ error: { code: 'queue' }, status: 'error' });++ click(h, 40, 40);++ expect(operations.stores.samSession.get()).toMatchObject({+ error: null,+ input: {+ includePoints: [+ { x: 20, y: 20 },+ { x: 40, y: 40 },+ ],+ },+ status: 'scheduled',+ });+ expect(h.engine.stores.activeTool.get()).toBe('sam');+ h.engine.lifecycle.dispose();+ });+ });+it('resets edited inputs and point mode immediately after launch without requiring a preview guard', async () => {const h = await createSamHarness();expect(getCanvasOperations(h.engine).startSelectObject('source')).toBe('started');@@ -18838,6 +19173,25 @@ describe('Select Object canvas engine integration', () => {h.engine.lifecycle.dispose();});+ it('cancels a pending save when Select by switches input type', async () => {+ const h = await createCommittingSamHarness();+ const leavesBefore = getDocumentLeaves(h.engine.document.getDocument()).length;+ const durable = createDeferred<void>();+ const pending = getCanvasOperations(h.engine).saveSelectObjectSession('inpaint_mask', () => durable.promise);++ getCanvasOperations(h.engine).updateSelectObjectSession({ inputType: 'prompt' });+ durable.resolve();++ await expect(pending).resolves.toEqual({ status: 'stale' });+ expect(getDocumentLeaves(h.engine.document.getDocument())).toHaveLength(leavesBefore);+ expect(getCanvasOperations(h.engine).stores.samSession.get()).toMatchObject({+ hasPreview: false,+ input: { type: 'prompt' },+ status: 'ready',+ });+ h.engine.lifecycle.dispose();+ });+it('Reset clears inputs, preview, and error while keeping the operation active', async () => {const h = await createCommittingSamHarness();getCanvasOperations(h.engine).updateSelectObjectSession({ input: { prompt: 'cat', type: 'prompt' }, invert: true });@@ -19149,7 +19503,7 @@ describe('Select Object canvas engine integration', () => {).resolves.toEqual({ message: 'promotion failed', status: 'failed' });expect(getCanvasOperations(h.engine).stores.samSession.get()).toMatchObject({- error: { code: 'unknown', detail: 'promotion failed' },+ error: { code: 'commit-failed', detail: 'promotion failed' },hasPreview: true,});expect(getCanvasOperations(h.engine).stores.samSession.get()?.input).toEqual(previewInput);@@ -19175,7 +19529,7 @@ describe('Select Object canvas engine integration', () => {).resolves.toEqual({ status: 'stale' });expect(getCanvasOperations(h.engine).stores.samSession.get()).toMatchObject({- error: { code: 'unknown', detail: 'Select Object commit is stale.' },+ error: { code: 'commit-failed', detail: 'Select Object commit is stale.' },hasPreview: true,});expect(getCanvasOperations(h.engine).stores.samSession.get()?.input).toEqual(previewInput);@@ -20189,6 +20543,7 @@ describe('layer quick-switch memory', () => {reportStructuralCommit: vi.fn(),reportPreparedCommit: vi.fn(),reportLayerOperation: vi.fn(),+ reportMergeDownRefusal: vi.fn(),reportTransformRefusal: vi.fn(),t: (key) => key,});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 84982651b0..b25f9b87be 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -213,7 +213,7 @@ import { createLayerExportGuards, isSupportedExportSource, layerUnreadable } froimport { createLayerRasterizer } from './layerRasterizer';import { createPreviewPublisher } from './previewPublisher';import { createRasterSnapshotCapture } from './rasterSnapshotCapture';-import { createCompositeFrame, isStagingHiddenStackSelected } from './render/compositeFrame';+import { createCompositeFrame, isInStagingHiddenStack } from './render/compositeFrame';import { floatingSelectionFrame } from './render/floatingSelectionFrame';import { createOverlayFrame } from './render/overlayFrame';import { createSelectObjectBridge } from './selectObjectBridge';@@ -391,6 +391,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCbboxGrid: stores.bboxGrid,bboxOptions: stores.bboxOptions,bboxOverlay: stores.bboxOverlay,+ bboxPreview: stores.bboxPreview,brushOptions: stores.brushOptions,canRedo: stores.canRedo,canUndo: stores.canUndo,@@ -417,6 +418,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCshowBbox: stores.showBbox,showGrid: stores.showGrid,snapToGrid: stores.snapToGrid,+ stagingHidesOverlays: stores.stagingHidesOverlays,textEditSession: stores.textEditSession,textOptions: stores.textOptions,transformSession: stores.transformSession,@@ -997,6 +999,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCinvalidateLayer: (layerId) => scheduler.invalidate({ layers: [layerId] }),isRasterCacheReady: (layer, document) => isLayerCacheReadyForOp(layer, document),isGestureActive: () => pipeline.isGestureActive(),+ getTransformSessionLayerId: () => stores.transformSession.get()?.layerId ?? null,layers: layerCache,markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),notifyPainted: notifyLayerPainted,@@ -1526,25 +1529,38 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC});const scheduler: RenderScheduler = renderController.scheduler;- /** Whether the pointer gesture in progress edits a mask or a region, which a shown staged preview otherwise hides. */+ /** Whether the pointer gesture in progress edits a control layer, mask or region, which a staged preview hides. */let gestureEditsStagingHiddenStack = false;+ /** Whether an open transform session or floating selection holds such a layer: it changes for as long as it lasts. */+ let sessionEditsStagingHiddenStack = false;/**- * Set once per gesture, so its pointer moves read a flag. While a preview is shown, setting and clearing it each- * repaint in full: the stacks show above the preview, then hide again.+ * The gesture flag is set once per gesture, so its pointer moves read a flag; the session flag follows the transform+ * session and floating selection stores, and document changes, since a conversion or its undo moves the held layer+ * to another stack. While a preview is shown or toggled off, the stacks showing (above the preview) or hiding again+ * repaints in full.*/- const setGestureEditsStagingHiddenStack = (edits: boolean): void => {- if (edits === gestureEditsStagingHiddenStack) {- return;- }- gestureEditsStagingHiddenStack = edits;- if (renderController.previews.getStaged()) {+ const setStagingHiddenStackEdits = (gesture: boolean, session: boolean): void => {+ const revealed = gestureEditsStagingHiddenStack || sessionEditsStagingHiddenStack;+ gestureEditsStagingHiddenStack = gesture;+ sessionEditsStagingHiddenStack = session;+ if ((gesture || session) !== revealed && renderController.previews.hidesStagingOverlays()) {scheduler.invalidate({ all: true });}};+ const setGestureEditsStagingHiddenStack = (edits: boolean): void =>+ setStagingHiddenStackEdits(edits, sessionEditsStagingHiddenStack);+ const syncSessionEditsStagingHiddenStack = (): void => {+ const layerId = stores.transformSession.get()?.layerId ?? floatingSelection.get()?.layerId ?? null;+ // With nothing held, no document is read: the mirror reports changes before construction completes.+ const document = layerId === null ? null : mirror.getDocument();+ setStagingHiddenStackEdits(gestureEditsStagingHiddenStack, !!document && isInStagingHiddenStack(document, layerId));+ };+ const unsubscribeTransformReveal = stores.transformSession.subscribe(syncSessionEditsStagingHiddenStack);+ const unsubscribeFloatReveal = stores.hasFloatingSelection.subscribe(syncSessionEditsStagingHiddenStack);/** The pointer gesture in progress edits the selected layer in place: at its press, or later (a move's drag). */const beginSelectedLayerEdit = (): void => {const document = mirror.getDocument();- if (pipeline.isGestureActive() && document && isStagingHiddenStackSelected(document)) {+ if (pipeline.isGestureActive() && document && isInStagingHiddenStack(document, document.selectedLayerId)) {setGestureEditsStagingHiddenStack(true);}};@@ -1567,7 +1583,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCgetCheckerboardTile,getMaskPatternTile,getControlView: () => controlView.get(),- isEditingStagingHiddenStack: () => gestureEditsStagingHiddenStack,+ isEditingStagingHiddenStack: () => gestureEditsStagingHiddenStack || sessionEditsStagingHiddenStack,layerCache,previews: renderController.previews,raster: rasterController,@@ -1618,6 +1634,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCinvalidateLayer: (layerId) => scheduler.invalidate({ layers: [layerId] }),isGuardCurrent: (guard) => isLayerExportGuardCurrent(guard),previews: renderController.previews,+ publishHidesStagingOverlays: (hidden) => stores.stagingHidesOverlays.set(hidden),resolveImage: imageResolver,});const {@@ -1648,6 +1665,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCconst mirror: DocumentMirror = createDocumentMirror(mutationPort, {onDocumentChanged: () => {editingController.transform.onDocumentChanged();+ syncSessionEditsStagingHiddenStack();stores.documentEpoch.set(stores.documentEpoch.get() + 1);// A tool's cursor reads the selected layer (not-allowed over a locked or hidden one), which this may change.// Skipped until the interaction controller exists, which the cursor reads.@@ -2619,6 +2637,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCfloatingSelection.commit();editingController.selectionPixels.run('erase');};+ const admitSelectionErase = (): boolean => editingController.selectionPixels.admitErase();/** Copy reuses the float's nonmutating masked-copy path so clipboard and lift select identical pixels. */const exportSelectionBlob = (): Promise<Blob | null> => {@@ -2692,6 +2711,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCcleanup.run(unsubscribeBrushOptions);cleanup.run(unsubscribeEraserOptions);cleanup.run(unsubscribeCheckerboard);+ cleanup.run(unsubscribeTransformReveal);+ cleanup.run(unsubscribeFloatReveal);cleanup.run(unsubscribeControlViewLock);cleanup.run(unsubscribeCheckerColors);cleanup.run(unsubscribeShowGrid);@@ -3008,6 +3029,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC};const selectionCapability: CanvasEngineSelectionCapability = {deselect,+ admitSelectionErase,eraseSelection,fillSelection,getSelectionBounds: () => selection.bounds(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.tsindex 5df6a54985..f8bf78d98e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts@@ -545,6 +545,8 @@ export interface EngineStores {documentEditingLayerId: ScalarStore<string | null>;/** The control layer displayed as its original (or original under map); null displays every map. */controlLayerView: ScalarStore<ControlLayerView | null>;+ /** Whether a staged or progress preview, shown or toggled off, hides the overlay stacks from the screen. */+ stagingHidesOverlays: ScalarStore<boolean>;}const brushOptionsEqual = (a: BrushOptions, b: BrushOptions): boolean =>@@ -741,6 +743,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =showBbox: createScalarStore<boolean>(true),showGrid: createScalarStore<boolean>(false),snapToGrid: createScalarStore<boolean>(true),+ stagingHidesOverlays: createScalarStore<boolean>(false),textEditSession: createScalarStore<TextEditSession | null>(null, textEditSessionEqual),textOptions: createScalarStore<TextToolOptions>({ ...DEFAULT_TEXT_OPTIONS }, textOptionsEqual),thumbnailVersion: createKeyedVersionStore(),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.test.tsindex 1fc31bd6e7..277388054b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.test.ts@@ -36,6 +36,7 @@ const build = (overrides: Partial<CreatePreviewPublisherDeps> = {}): PreviewPublinvalidateLayer,isGuardCurrent,previews,+ publishHidesStagingOverlays: () => undefined,resolveImage,...overrides,});@@ -212,6 +213,59 @@ describe('staged previews', () => {expect(previews.getStaged()).toBeNull();expect(invalidateAll).toHaveBeenCalledTimes(1);});++ it('drops a hidden candidate without decoding it, keeping the overlays hidden until staging ends', async () => {+ const published = vi.fn<(hidden: boolean) => void>();+ const publisher = build({ publishHidesStagingOverlays: published });+ publisher.setStagedPreview(staged('shown.png'));+ await vi.waitFor(() => expect(previews.getStaged()).not.toBeNull());+ invalidateAll.mockClear();++ publisher.setStagedPreview({ ...staged('shown.png'), hidden: true });+ expect(previews.getStaged()).toBeNull();+ expect(previews.hidesStagingOverlays()).toBe(true);+ expect(invalidateAll).toHaveBeenCalledOnce();+ // Selecting another candidate while hidden changes nothing on screen.+ publisher.setStagedPreview({ ...staged('other.png'), hidden: true });+ expect(invalidateAll).toHaveBeenCalledOnce();+ expect(decodeBlob).toHaveBeenCalledOnce();++ publisher.setStagedPreview(null);+ expect(previews.hidesStagingOverlays()).toBe(false);+ expect(invalidateAll).toHaveBeenCalledTimes(2);+ // Canvas chrome learns each change: shown, hidden to compare, then staging ended.+ expect(published.mock.calls).toEqual([[true], [true], [false]]);+ });++ it('never shows a result the eye hid while it was still decoding, nor masks while showing it decodes', async () => {+ const releases: Array<() => void> = [];+ decodeBlob.mockImplementation(+ () =>+ new Promise((resolve) => {+ releases.push(() => resolve({ decodedHeight: 8, decodedWidth: 8, surface: surface() }));+ })+ );+ const publisher = build();+ publisher.setStagedPreview(staged('candidate.png'));+ await vi.waitFor(() => expect(decodeBlob).toHaveBeenCalledOnce());+ publisher.setStagedPreview({ ...staged('candidate.png'), hidden: true });+ invalidateAll.mockClear();+ releases[0]!();+ // A macrotask runs only once the decode's whole promise chain has settled.+ await new Promise((resolve) => {+ setTimeout(resolve, 0);+ });+ expect(previews.getStaged()).toBeNull();+ expect(previews.hidesStagingOverlays()).toBe(true);+ expect(invalidateAll).not.toHaveBeenCalled();++ // Showing it again: no mask flashes up while the pixels decode.+ publisher.setStagedPreview(staged('candidate.png'));+ await vi.waitFor(() => expect(decodeBlob).toHaveBeenCalledTimes(2));+ expect(previews.hidesStagingOverlays()).toBe(true);+ releases[1]!();+ await vi.waitFor(() => expect(previews.getStaged()).not.toBeNull());+ });});describe('setGuardedFilterPreview', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.tsindex e6c3c97d35..e2a6a23035 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/previewPublisher.ts@@ -29,6 +29,8 @@ export interface CreatePreviewPublisherDeps {readonly resolveImage: ImageResolver;readonly decodeBlob: (blob: Blob) => Promise<{ surface: RasterSurface; decodedWidth: number; decodedHeight: number }>;readonly invalidateAll: () => void;+ /** Publishes {@link PreviewStateController.hidesStagingOverlays} after each staged change, for canvas chrome. */+ readonly publishHidesStagingOverlays: (hidden: boolean) => void;readonly invalidateLayer: (layerId: string) => void;readonly getDocument: () => CanvasDocumentContractV3 | null;readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;@@ -43,7 +45,7 @@ export interface PreviewPublisher {dispose(): void;/** Warms one full-resolution staged result without decoding it. */preloadStagedPreview(imageName: string): void;- /** Decodes and publishes a staged-generation preview; `null` clears. Never throws. */+ /** Decodes and publishes a staged-generation preview; a hidden candidate shows none, `null` clears. Never throws. */setStagedPreview(input: StagedPreviewInput | null): void;/** Drops one layer's filter preview and invalidates it. */clearFilterPreview(layerId: string): void;@@ -84,9 +86,15 @@ export const createPreviewPublisher = (deps: CreatePreviewPublisherDeps): Previeconst stagedPreviewBlobs = createStagedPreviewBlobCache(deps.resolveImage);const stagedImageDecodes = new Map<string, ReturnType<CreatePreviewPublisherDeps['decodeBlob']>>();+ /** The staged preview showed, hid or changed: repaint, and publish whether the overlay stacks are hidden. */+ const stagedChanged = (): void => {+ deps.invalidateAll();+ deps.publishHidesStagingOverlays(previews.hidesStagingOverlays());+ };+const clearStagedPreview = (): void => {if (previews.clearStaged()) {- deps.invalidateAll();+ stagedChanged();}};@@ -233,12 +241,18 @@ export const createPreviewPublisher = (deps: CreatePreviewPublisherDeps): PrevieclearStagedPreview();return;}+ if ('imageName' in input && input.hidden) {+ if (previews.hideStaged()) {+ stagedChanged();+ }+ return;+ }const token = previews.nextStagedToken();decodeStagedPreview(input, () => previews.isStagedTokenCurrent(token)).then((decoded) => {// A newer set/clear superseded this decode while it was in flight.if (previews.publishStaged(token, decoded)) {- deps.invalidateAll();+ stagedChanged();}}).catch(() => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.tsindex 768ed80c3e..59aa789d87 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts@@ -17,7 +17,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { FloatingSelectionFrame } from './floatingSelectionFrame';-import { createCompositeFrame, type CreateCompositeFrameDeps, isStagingHiddenStackSelected } from './compositeFrame';+import { createCompositeFrame, type CreateCompositeFrameDeps, isInStagingHiddenStack } from './compositeFrame';const VIEW = [1, 0, 0, 1, 0, 0] as unknown as Mat2d;@@ -338,7 +338,7 @@ describe('the surface budget', () => {});});-describe('masks while a result is staged', () => {+describe('overlay stacks while a result is staged', () => {const mask = (id: string, overrides: Record<string, unknown> = {}) =>layer(id, {mask: { bitmap: { height: 8, imageName: `${id}.png`, width: 8 }, fill: { color: '#e07575', style: 'solid' } },@@ -364,7 +364,7 @@ describe('masks while a result is staged', () => {width: 8,});- it('hides mask and region stacks and the region tint under a shown preview, rebuilding the description per flip', () => {+ it('hides control, mask and region stacks and the region tint under a shown preview, rebuilding the description per flip', () => {const frame = createCompositeFrame(harness.deps);const drawFrame = () => frame.draw(surface(), doc, VIEW, null, null);@@ -378,25 +378,72 @@ describe('masks while a result is staged', () => {drawFrame();const hidden = description();expect(hidden).not.toBe(shown);- expect(drawnIds()).toEqual(['a', 'c']);- expect(demandedIds()).toEqual(['a', 'c']);+ expect(drawnIds()).toEqual(['a']);+ expect(demandedIds()).toEqual(['a']);expect(lastCompositeOptions().regionOverlays).toBe(false);drawFrame();expect(description()).toBe(hidden);- // Toggling the preview off (or accepting/discarding) shows them again.+ // Accepting or discarding ends the preview and shows them again.+ harness.previews.clearStaged();+ drawFrame();+ expect(drawnIds()).toEqual(['a', 'c', 'm', 'r']);+ expect(demandedIds()).toEqual(['a', 'c', 'm', 'r']);+ });++ it('keeps them hidden while the staged result is toggled off to compare, until staging ends', () => {+ const frame = createCompositeFrame(harness.deps);+ const drawFrame = (document = doc) => frame.draw(surface(), document, VIEW, null, null);+ const hiddenWhileComparing = () => {+ expect(drawnIds()).toEqual(['a']);+ expect(demandedIds()).toEqual(['a']);+ expect(lastCompositeOptions().regionOverlays).toBe(false);+ };++ publishPreview();+ drawFrame();+ hiddenWhileComparing();+ expect(lastCompositeOptions().stagedPreview).not.toBeNull();++ // The eye shows the canvas under the result exactly as the shown result left it: no masks, no tint.+ harness.previews.hideStaged();+ drawFrame();+ hiddenWhileComparing();+ expect(lastCompositeOptions().stagedPreview).toBeNull();++ // A mask gesture reveals them as it would over the shown result, and the frame keeps the selected mask ready.+ harness.entries.set('m', entryFor(undefined, true));+ drawFrame({ ...doc, selectedLayerId: 'm' });+ expect(harness.rasterizeLayer).toHaveBeenCalledWith(expect.objectContaining({ id: 'm' }), expect.anything());+ expect(demandedIds()).toEqual(['a', 'm']);+ harness.editingHiddenStack = true;+ drawFrame({ ...doc, selectedLayerId: 'm' });+ expect(drawnIds()).toEqual(['a', 'c', 'm', 'r']);+ harness.editingHiddenStack = false;+ harness.entries.set('m', entryFor());++ // Showing it again and hiding it again never brings them back.+ publishPreview();+ drawFrame();+ hiddenWhileComparing();+ harness.previews.hideStaged();+ drawFrame();+ hiddenWhileComparing();++ // Accepting or discarding while it is toggled off ends the comparison.harness.previews.clearStaged();drawFrame();expect(drawnIds()).toEqual(['a', 'c', 'm', 'r']);expect(demandedIds()).toEqual(['a', 'c', 'm', 'r']);+ expect(lastCompositeOptions().regionOverlays).toBe(true);});- it('shows them over the preview only while a gesture edits a mask or region, whatever is selected', () => {+ it('shows them over the preview only while a gesture edits a control layer, mask or region, whatever is selected', () => {const frame = createCompositeFrame(harness.deps);publishPreview();// Selecting a mask alone keeps the result unmasked.frame.draw(surface(), { ...doc, selectedLayerId: 'm' }, VIEW, null, null);- expect(drawnIds()).toEqual(['a', 'c']);+ expect(drawnIds()).toEqual(['a']);harness.editingHiddenStack = true;frame.draw(surface(), { ...doc, selectedLayerId: 'm' }, VIEW, null, null);@@ -407,11 +454,11 @@ describe('masks while a result is staged', () => {harness.editingHiddenStack = false;frame.draw(surface(), { ...doc, selectedLayerId: 'm' }, VIEW, null, null);- expect(drawnIds()).toEqual(['a', 'c']);+ expect(drawnIds()).toEqual(['a']);expect(lastCompositeOptions().regionOverlays).toBe(false);});- it('keeps the selected mask or region loaded and demanded while hidden, and nothing else', () => {+ it('keeps the selected control layer, mask or region loaded and demanded while hidden, and nothing else', () => {const frame = createCompositeFrame(harness.deps);publishPreview();const drawSelected = (selectedLayerId: string, document = doc) => {@@ -421,21 +468,24 @@ describe('masks while a result is staged', () => {};// A stale cache starts loading, and the frame protects the leaf from eviction though it draws none.+ harness.entries.set('c', entryFor(undefined, true));harness.entries.set('m', entryFor(undefined, true));harness.entries.set('r', entryFor(undefined, true));expect(drawSelected('m')).toEqual(['m']);- expect(drawnIds()).toEqual(['a', 'c']);- expect(demandedIds()).toEqual(['a', 'c', 'm']);+ expect(drawnIds()).toEqual(['a']);+ expect(demandedIds()).toEqual(['a', 'm']);expect(drawSelected('r')).toEqual(['r']);- expect(demandedIds()).toEqual(['a', 'c', 'r']);+ expect(demandedIds()).toEqual(['a', 'r']);+ expect(drawSelected('c')).toEqual(['c']);+ expect(demandedIds()).toEqual(['a', 'c']);// A disabled mask draws nowhere, and a selected group's brush or shape paints a new layer instead.const disabled = documentOf([layer('a'), control('c'), { ...mask('m'), isEnabled: false }, region('r')]);expect(drawSelected('m', disabled)).toEqual([]);- expect(demandedIds()).toEqual(['a', 'c']);+ expect(demandedIds()).toEqual(['a']);const grouped = documentOf([layer('a'), control('c'), groupContract('g', [mask('m')]), region('r')]);expect(drawSelected('g', grouped)).toEqual([]);- expect(demandedIds()).toEqual(['a', 'c']);+ expect(demandedIds()).toEqual(['a']);// Off screen it is left on demand, as a drawn leaf would be.const offscreen = documentOf([@@ -445,7 +495,7 @@ describe('masks while a result is staged', () => {region('r'),]);expect(drawSelected('m', offscreen)).toEqual([]);- expect(demandedIds()).toEqual(['a', 'c']);+ expect(demandedIds()).toEqual(['a']);// Without a shown preview the stacks draw, so their leaves are demanded as usual.harness.previews.clearStaged();@@ -456,10 +506,10 @@ describe('masks while a result is staged', () => {it.each([['m', true],['r', true],- ['c', false],+ ['c', true],['a', false],[null, false],- ])('counts selecting %s as selecting a stack the staged view hides: %s', (id, hidden) => {- expect(isStagingHiddenStackSelected({ ...doc, selectedLayerId: id })).toBe(hidden);+ ])('counts %s as in a stack the staged view hides: %s', (id, hidden) => {+ expect(isInStagingHiddenStack(doc, id)).toBe(hidden);});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex 390be72b1c..d6e9ebee87 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -1,8 +1,4 @@-import type {- CanvasDocumentContractV3,- CanvasLayerContract,- CanvasLayerStackKind,-} from '@workbench/canvas-engine/contracts';+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type {PreviewStateController,SamPreviewState,@@ -10,6 +6,7 @@ import type {import type { RasterController } from '@workbench/canvas-engine/controllers/rasterController';import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';+import type { OverlayStackKind } from '@workbench/canvas-engine/document/layerStacks';import type { EngineStores } from '@workbench/canvas-engine/engineStores';import type { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';@@ -56,39 +53,42 @@ export interface CreateCompositeFrameDeps {/** Starts (or joins) the rasterization of a layer whose cache is stale. */readonly rasterizeLayer: (layer: CanvasLayerContract, doc: CanvasDocumentContractV3) => void;/**- * Whether a pointer gesture in progress edits a mask or a region. Its stacks and the regenerate tint then draw- * above a shown preview, so the user never paints a mask blind; the frame after the gesture hides them again.+ * Whether a pointer gesture, transform session or floating selection in progress edits a control layer, a mask or a+ * region. Those stacks then draw above a shown preview, so the user never edits blind, and the regenerate tint draws+ * again with its raster layer, under the preview. The frame after the edit ends hides them again.*/readonly isEditingStagingHiddenStack: () => boolean;}/**- * While a staged or progress preview shows, masks and regions stop tinting the screen, so the result reads as it- * would be accepted; control layers stay.+ * While a staged or progress preview shows, or the user toggled the staged result off to compare, the screen draws+ * raster layers only: control layers, masks and regions stop covering and tinting it, so the result reads as it would+ * be accepted and the canvas under it reads the same way. Generation still reads every stack.*/-const STAGING_OVERLAY_STACKS = { control: true, inpaint_mask: false, regional_guidance: false } as const;--const isStagingHiddenStack = (stack: CanvasLayerStackKind): boolean =>- isOverlayStack(stack) && !STAGING_OVERLAY_STACKS[stack];+const STAGING_OVERLAY_STACKS: Readonly<Record<OverlayStackKind, boolean>> = {+ control: false,+ inpaint_mask: false,+ regional_guidance: false,+};/**- * Whether the selection sits in a stack the staging view hides: a mask or a region, or a group in those stacks. A- * gesture that edits it shows those stacks again ({@link CreateCompositeFrameDeps.isEditingStagingHiddenStack}).+ * Whether `nodeId` sits in a stack the staging view hides: a control layer, a mask or a region, or a group in those+ * stacks. An edit of it shows those stacks again ({@link CreateCompositeFrameDeps.isEditingStagingHiddenStack}).*/-export const isStagingHiddenStackSelected = (doc: CanvasDocumentContractV3): boolean => {- const stack = doc.selectedLayerId ? getDocumentIndex(doc).byId.get(doc.selectedLayerId)?.stack : undefined;- return stack !== undefined && isStagingHiddenStack(stack);+export const isInStagingHiddenStack = (doc: CanvasDocumentContractV3, nodeId: string | null): boolean => {+ const stack = nodeId ? getDocumentIndex(doc).byId.get(nodeId)?.stack : undefined;+ return stack !== undefined && isOverlayStack(stack);};/**- * The selected mask or region a shown preview hides, when the screen would draw it with the stack shown. A gesture- * on it reveals the stack (and a brush refuses a mask whose pixels are not loaded yet), so the frame keeps it- * resident while hidden and on screen. A selected group needs nothing up front: brush and shapes paint a new layer,- * move drags whatever caches exist.+ * The selected control layer, mask or region a shown preview hides, when the screen would draw it with the stack+ * shown. A gesture on it reveals the stack (and a brush refuses a layer whose pixels are not loaded yet), so the frame+ * keeps it resident while hidden and on screen. A selected group needs nothing up front: brush and shapes paint a new+ * layer, move drags whatever caches exist.*/const stagingHiddenSelectedLeaf = (doc: CanvasDocumentContractV3): SemanticLeaf | null => {const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;- return leaf && isStagingHiddenStack(leaf.stack) && isLeafDrawableForScreen(leaf, false) ? leaf : null;+ return leaf && isOverlayStack(leaf.stack) && isLeafDrawableForScreen(leaf, false) ? leaf : null;};export interface CompositeFrame {@@ -234,8 +234,8 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFconst stagedPreview = previews.getStaged();const isolatedGuard = samPreview?.isolated ? samPreview.guard : null;const overrides = !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null;- // A shown preview hides masks, regions and the regenerate tint, unless a gesture is editing one of them.- const staging = stagedPreview !== null && !deps.isEditingStagingHiddenStack();+ // A shown or toggled-off preview hides every overlay stack and the regenerate tint, unless one is being edited.+ const staging = previews.hidesStagingOverlays() && !deps.isEditingStagingHiddenStack();const showOverlayStacks = staging ? STAGING_OVERLAY_STACKS : undefined;const frame = describeFrame(doc, isolatedGuard?.layerId ?? null, overrides, showOverlayStacks);// Snapshot filter previews only when active, avoiding an empty map allocation every frame.@@ -251,7 +251,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFactiveFrameLayerIds.add(layerId);}ensureLayerCaches(doc, frame, activeFrameLayerIds);- // The selected mask or region stays loaded and unevicted while hidden, ready for a gesture to reveal and edit,+ // The selected overlay leaf stays loaded and unevicted while hidden, ready for a gesture to reveal and edit,// under the same on-screen rule as the leaves the frame draws. No transform override moves a hidden leaf.const hiddenSelected = staging && !isolatedGuard ? stagingHiddenSelectedLeaf(doc) : null;const hiddenBounds = hiddenSelecteddiff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.tsindex dad776efe3..6783fbf46d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts@@ -628,7 +628,7 @@ describe('compositeDocument', () => {expect(target.callLog.some((entry) => entry.op === 'strokeRect')).toBe(false);});- it('lands the staged preview above raster and control layers and below masks and regions', () => {+ it('lands the staged preview above raster layers and below control layers, masks and regions', () => {const backend = createTestStubRasterBackend();const caches = createLayerCacheStore(backend);// Identify each blit by its source width, as the stack-order test does.@@ -660,7 +660,8 @@ describe('compositeDocument', () => {.filter((e) => e.op === 'drawImage').map((e) => widthToId[(e.args[0] as { width: number }).width]).filter((id): id is string => id !== undefined);- expect(order.indexOf('control')).toBeLessThan(order.indexOf('staged'));+ expect(order.indexOf('raster')).toBeLessThan(order.indexOf('staged'));+ expect(order.indexOf('staged')).toBeLessThan(order.indexOf('control'));expect(order.indexOf('staged')).toBeLessThan(order.indexOf('regional'));expect(order.indexOf('staged')).toBeLessThan(order.indexOf('inpaint'));});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 68dc98cc71..12f09da33e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -1,7 +1,7 @@/*** Draws cached content: clear/checkerboard across the viewport, bottom-first transformed layers with- * opacity/blend, then staged preview. Missing caches are skipped; callers own rasterization. RasterSurface- * contexts make ordering testable.+ * opacity/blend, and the staged preview between the raster stack and the overlay stacks. Missing caches are skipped;+ * callers own rasterization. RasterSurface contexts make ordering testable.*/import type {@@ -67,8 +67,8 @@ export interface CompositeOptions {/** Clips document layers to this document-space rect without clipping the background or staged preview. */clipRect?: Rect | null;/**- * A staged generation candidate to draw at its placement (document space), above the raster and control stacks and- * below masks and regions, which show over it only when the staging view leaves them on. The overlay outlines it.+ * A staged generation candidate to draw at its placement (document space), above the raster stack and below control+ * layers, masks and regions, which show over it only when the staging view leaves them on. The overlay outlines it.*/stagedPreview?: { surface: RasterSurface; rect: Rect; opacity?: number } | null;/**@@ -223,7 +223,7 @@ export const prepareComposite = (opts: Pick<CompositeOptions, 'groupSurface' | 'isolationLayerId' | 'showOverlayStacks' | 'transformOverrides'> = {}): CompositePreparation => {const isolationLayerId = opts.isolationLayerId ?? null;- // The plan lists the leaves to draw bottom first; the `stagedPreview` lands on top of every stack.+ // The plan lists the leaves to draw bottom first; the `stagedPreview` lands above the raster stack.const { leaves } = planScreenComposition(compileDocumentLeaves(doc), {isolationLayerId,showOverlayStacks: opts.showOverlayStacks ?? ALL_OVERLAY_STACKS_SHOWN,@@ -599,7 +599,7 @@ export const compositeDocument = (};applyClipRect();- // The staged preview lands once, unclipped, before the first mask or region leaf (or after every leaf).+ // The staged preview lands once, unclipped, before the first overlay-stack leaf (or after every leaf).const staged = isIsolated(opts) ? null : (opts.stagedPreview ?? null);let stagedPending = staged !== null;const drawStaged = (): void => {@@ -668,7 +668,7 @@ export const compositeDocument = (};for (let index = 0; index < leaves.length; index += 1) {- if (stagedPending && leaves[index]!.stack !== 'raster' && leaves[index]!.stack !== 'control') {+ if (stagedPending && leaves[index]!.stack !== 'raster') {drawStaged();}const scope = scopeIndex < scopes.length ? scopes[scopeIndex]! : null;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.tsindex d241a2048d..a8ec485800 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts@@ -237,7 +237,7 @@ describe('overlay stacks switched off while a result is staged', () => {backend,imageSmoothing: false,regionOverlays: !staging,- showOverlayStacks: staging ? { control: true, inpaint_mask: false, regional_guidance: false } : undefined,+ showOverlayStacks: staging ? { control: false, inpaint_mask: false, regional_guidance: false } : undefined,});draw(true);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.tsindex 3868a758f1..982381a9e3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts@@ -104,6 +104,281 @@ describe('overlay chrome across device-pixel ratios', () => {});});+describe('bbox frame over any content', () => {+ /** Large enough to hold the whole frame at every probed zoom. */+ const FRAME_CSS_SIZE = 400;+ /** An RGB colour, or an RGBA pixel whose alpha is ignored. */+ type Rgb = readonly number[];+ /** The frame's own accent: the background the frame used to vanish over. */+ const ACCENT = [59, 130, 246] as const;+ const OUTSIDE = [23, 37, 84] as const;+ const INSIDE = [255, 255, 255] as const;+ /** The accent, both extremes, and the image blues and mid tones between them that a single dark casing misses. */+ const BACKGROUNDS: readonly (readonly [string, Rgb])[] = [+ ['its accent', ACCENT],+ ['white', [255, 255, 255]],+ ['black', [0, 0, 0]],+ ['blue-600', [37, 99, 235]],+ ['blue-700', [29, 78, 216]],+ ['blue-800', [30, 64, 175]],+ ['blue-900', [30, 58, 138]],+ ['sky-700', [3, 105, 161]],+ ['mid grey', [102, 102, 102]],+ ['dark green', [47, 93, 58]],+ ];+ /** WCAG's minimum for a graphical object that identifies a UI component. */+ const MIN_CONTRAST = 3;+ const DPR_ZOOMS = [1, 1.25, 1.5, 2].flatMap((dpr) => [0.5, 1, 2.6].map((zoom) => [dpr, zoom] as const));++ const luminance = ([r = 0, g = 0, b = 0]: Rgb): number => {+ const linear = (channel: number) => {+ const c = channel / 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);+ };+ const contrast = (a: Rgb, b: Rgb): number => {+ const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);+ return (high! + 0.05) / (low! + 0.05);+ };++ /**+ * Renders the frame at `dpr` and `zoom` (a fractional pan keeps its edges off the pixel grid) and composites it over+ * an opaque `background`. Lines are read in device pixels: `overlay` alone, and `scene` as the user sees it.+ */+ const renderFrame = (dpr: number, zoom: number, background: Rgb, handles = false) => {+ const viewport = createViewport({ pan: { x: 7.3, y: 4.6 }, zoom });+ viewport.setViewportSize(FRAME_CSS_SIZE, FRAME_CSS_SIZE, dpr);+ const size = Math.round(FRAME_CSS_SIZE * dpr);+ const overlay = createDomRasterBackend().createSurface(size, size);+ renderOverlay(overlay, {+ bbox: RECT,+ bboxHandles: handles,+ dpr,+ view: viewport.viewMatrix(1),+ viewportSize: viewport.getViewportSize(),+ });+ const scene = createDomRasterBackend().createSurface(size, size);+ scene.ctx.fillStyle = `rgb(${background.join(', ')})`;+ scene.ctx.fillRect(0, 0, size, size);+ scene.ctx.drawImage(overlay.canvas, 0, 0);+ const read = (surface: typeof scene, x: number, y: number, w: number, h: number) => {+ const data = surface.ctx.getImageData(x, y, w, h).data;+ return Array.from({ length: w * h }, (_, i) => Array.from(data.subarray(i * 4, i * 4 + 4)));+ };+ return {+ /** Device pixels down the column through CSS `x`, from `y - reach` to `y + reach`, with their device rows. */+ column: (x: number, y: number, reach: number) => {+ const top = Math.floor((y - reach) * dpr);+ const height = Math.ceil(reach * 2 * dpr);+ const sx = Math.floor(x * dpr);+ return { overlay: read(overlay, sx, top, 1, height), scene: read(scene, sx, top, 1, height), start: top };+ },+ /** Device pixels along the row through CSS `y`, from `x - reach` to `x + reach`, with their device columns. */+ row: (x: number, y: number, reach: number) => {+ const left = Math.floor((x - reach) * dpr);+ const width = Math.ceil(reach * 2 * dpr);+ const sy = Math.floor(y * dpr);+ return { overlay: read(overlay, left, sy, width, 1), scene: read(scene, left, sy, width, 1), start: left };+ },+ screen: transformBounds(viewport.viewMatrix(1), RECT),+ };+ };++ /** Device rows across the top edge inside its first dash, which starts at the corner, clear of the left edge. */+ const acrossTopEdge = (dpr: number, zoom: number, background: Rgb) => {+ const { column, screen } = renderFrame(dpr, zoom, background);+ return { ...column(screen.x + 2.75, screen.y, 4), edge: screen.y * dpr };+ };++ const isOpaque = (pixel: Rgb, color: Rgb): boolean =>+ pixel[3] === 255 && color.every((channel, index) => Math.abs(pixel[index]! - channel) <= 3);++ /** Offsets (into the probe) of opaque accent pixels in the overlay: the frame's core line. */+ const coreOf = (overlay: readonly Rgb[]): number[] =>+ overlay.flatMap((pixel, index) => (isOpaque(pixel, ACCENT) ? [index] : []));++ it.each(DPR_ZOOMS)(+ 'draws a crisp accent core centred where the edge falls, one hairline wide at any zoom (%sx, zoom %s)',+ (dpr, zoom) => {+ const { edge, overlay, start } = acrossTopEdge(dpr, zoom, ACCENT);+ const core = coreOf(overlay);++ expect(core).toHaveLength(Math.max(1, Math.round(dpr)));+ expect(core.at(-1)! - core[0]!).toBe(core.length - 1);+ const center = start + (core[0]! + core.at(-1)! + 1) / 2;+ expect(Math.abs(center - edge)).toBeLessThanOrEqual(0.5);+ }+ );++ it.each(DPR_ZOOMS)('keeps the frame edge visible over blues, greys, white and black (%sx, zoom %s)', (dpr, zoom) => {+ for (const [name, background] of BACKGROUNDS) {+ const { overlay, scene } = acrossTopEdge(dpr, zoom, background);+ const core = coreOf(overlay);+ const contrastAt = (index: number) => contrast(scene[index]!, background);+ const coreContrast = Math.min(...core.map(contrastAt));+ const outside = Math.max(...scene.slice(0, core[0]).map((_, index) => contrastAt(index)));+ const inside = Math.max(...scene.slice(core.at(-1)! + 1).map((_, index) => contrastAt(core.at(-1)! + 1 + index)));++ // Some band of the line contrasts with any content; where the core matches it, both flanks still bound it.+ expect(core.length, name).toBeGreaterThan(0);+ expect(Math.max(coreContrast, outside, inside), name).toBeGreaterThanOrEqual(MIN_CONTRAST);+ if (background === ACCENT) {+ expect(Math.min(outside, inside), name).toBeGreaterThanOrEqual(MIN_CONTRAST);+ }+ }+ });++ it.each([1, 1.25, 1.5, 2])(+ 'mirrors its bands on opposite edges of a pixel-aligned frame, only the white one inside it (%sx)',+ (dpr) => {+ // At zoom 0.8 RECT spans 40..80 CSS px: whole device pixels at every probed ratio.+ const viewport = createViewport({ pan: { x: 0, y: 0 }, zoom: 0.8 });+ viewport.setViewportSize(FRAME_CSS_SIZE, FRAME_CSS_SIZE, dpr);+ const size = Math.round(FRAME_CSS_SIZE * dpr);+ const overlay = createDomRasterBackend().createSurface(size, size);+ renderOverlay(overlay, {+ bbox: RECT,+ dpr,+ view: viewport.viewMatrix(1),+ viewportSize: viewport.getViewportSize(),+ });+ const screen = transformBounds(viewport.viewMatrix(1), RECT);+ const band = (x: number, y: number) => {+ const pixel = Array.from(overlay.ctx.getImageData(x, y, 1, 1).data);+ return isOpaque(pixel, OUTSIDE)+ ? 'navy'+ : isOpaque(pixel, ACCENT)+ ? 'core'+ : isOpaque(pixel, INSIDE)+ ? 'white'+ : pixel[3] === 0+ ? 'clear'+ : `partial ${pixel.join(',')}`;+ };+ const [left, top] = [screen.x * dpr, screen.y * dpr];+ const [right, bottom] = [(screen.x + screen.width) * dpr, (screen.y + screen.height) * dpr];+ // Inside each edge's first dash, which starts at a corner.+ const row = Math.floor((screen.y + 2.75) * dpr);+ const column = Math.floor((screen.x + 2.75) * dpr);+ // Device pixels from four outside each edge to four inside it, listed outside to inside.+ const offsets = [-4, -3, -2, -1, 0, 1, 2, 3];+ const leftBands = offsets.map((o) => band(left + o, row));++ expect(Number.isInteger(left) && Number.isInteger(bottom)).toBe(true);+ expect(offsets.map((o) => band(right - 1 - o, row))).toEqual(leftBands);+ expect(offsets.map((o) => band(column, top + o))).toEqual(leftBands);+ expect(offsets.map((o) => band(column, bottom - 1 - o))).toEqual(leftBands);+ if (Math.round(dpr) === 1) {+ // A one-pixel core sits on the pixel just outside; only the white band covers the area the frame marks.+ expect(leftBands).toEqual(['clear', 'clear', 'navy', 'core', 'white', 'clear', 'clear', 'clear']);+ } else {+ // A two-pixel core straddles the edge evenly.+ expect(leftBands).toEqual(['clear', 'navy', 'navy', 'core', 'core', 'white', 'white', 'clear']);+ }+ }+ );++ it.each(DPR_ZOOMS)('joins every drawn corner whole, with no notch at the dash seam (%sx, zoom %s)', (dpr, zoom) => {+ const viewport = createViewport({ pan: { x: 7.3, y: 4.6 }, zoom });+ viewport.setViewportSize(FRAME_CSS_SIZE, FRAME_CSS_SIZE, dpr);+ const size = Math.round(FRAME_CSS_SIZE * dpr);+ const overlay = createDomRasterBackend().createSurface(size, size);+ renderOverlay(overlay, { bbox: RECT, dpr, view: viewport.viewMatrix(1), viewportSize: viewport.getViewportSize() });+ const screen = transformBounds(viewport.viewMatrix(1), RECT);+ const hairline = Math.max(1, Math.round(dpr));+ // The core occupies the hairline's device pixels nearest each edge.+ const coreStart = (css: number) =>+ hairline % 2 === 1 ? Math.floor(css * dpr) - (hairline - 1) / 2 : Math.round(css * dpr) - hairline / 2;+ const block = (x: number, y: number) => {+ const data = overlay.ctx.getImageData(x, y, hairline, hairline).data;+ return Array.from({ length: hairline * hairline }, (_, i) => Array.from(data.subarray(i * 4, i * 4 + 4)));+ };+ const corners = [+ [screen.x, screen.y, -1, -1],+ [screen.x + screen.width, screen.y, 1, -1],+ [screen.x + screen.width, screen.y + screen.height, 1, 1],+ [screen.x, screen.y + screen.height, -1, 1],+ ] as const;+ let drawn = 0;+ for (const [cx, cy, outX, outY] of corners) {+ const x = coreStart(cx);+ const y = coreStart(cy);+ const reach = hairline * 2;+ const around = overlay.ctx.getImageData(x - reach, y - reach, hairline + reach * 2, hairline + reach * 2).data;+ // Coverage is whole: a seam or clipped join would leave partly covered pixels.+ for (let i = 3; i < around.length; i += 4) {+ expect(around[i]! <= 8 || around[i]! >= 247, `corner ${cx},${cy} alpha ${around[i]}`).toBe(true);+ }+ const outer = block(x + outX * hairline, y + outY * hairline);+ if (block(x, y).every((pixel) => isOpaque(pixel, ACCENT))) {+ drawn += 1;+ expect(+ outer.every((pixel) => isOpaque(pixel, OUTSIDE)),+ `corner ${cx},${cy} outside`+ ).toBe(true);+ const inner = block(x - outX * hairline, y - outY * hairline);+ expect(+ inner.every((pixel) => isOpaque(pixel, INSIDE)),+ `corner ${cx},${cy} inside`+ ).toBe(true);+ } else {+ expect(+ outer.every((pixel) => pixel[3]! <= 8),+ `corner ${cx},${cy} stray casing`+ ).toBe(true);+ }+ }+ // Every corner is a dash by construction, and the whole frame lies on the surface.+ expect(drawn).toBe(4);+ });++ // RECT spans 50..100; at 2x its edges land 0.3 px beyond each side of a 200 px surface, leaving only the white+ // inside band on the surface's outermost row or column.+ it.each([+ ['a deep-zoomed corner, edges running far off the surface', { a: 40, b: 0, c: 0, d: 40, e: -1950.3, f: -1950.6 }],+ ['the top edge just above the surface', { a: 2, b: 0, c: 0, d: 2, e: 7, f: -100.3 }],+ ['the bottom edge just below the surface', { a: 2, b: 0, c: 0, d: 2, e: 7, f: 0.3 }],+ ['the left edge just left of the surface', { a: 2, b: 0, c: 0, d: 2, e: -100.3, f: 7 }],+ ['the right edge just right of the surface', { a: 2, b: 0, c: 0, d: 2, e: 0.3, f: 7 }],+ ])('draws %s exactly as a larger surface shows it there', (_, view) => {+ const pad = 100;+ const render = (size: number, shift: number) => {+ const target = createDomRasterBackend().createSurface(size, size);+ renderOverlay(target, {+ bbox: RECT,+ dpr: 1,+ view: { ...view, e: view.e + shift, f: view.f + shift },+ viewportSize: { height: size, width: size },+ });+ return target.ctx.getImageData(shift, shift, 200, 200).data;+ };++ expect(render(200, 0)).toEqual(render(200 + pad * 2, pad));+ });++ it.each([1, 1.25, 1.5, 2])(+ 'outlines the resize handles so they read over blues, greys, white and black (%sx)',+ (dpr) => {+ for (const [name, background] of BACKGROUNDS) {+ const { row, screen } = renderFrame(dpr, 1, background, true);+ // Through the west handle, away from the frame's dashes along its row.+ const center = { x: screen.x, y: screen.y + screen.height / 2 };+ const { scene, start } = row(center.x, center.y, 10);+ const visible = scene.flatMap((pixel, index) => (contrast(pixel, background) >= MIN_CONTRAST ? [index] : []));++ expect(visible.length, name).toBeGreaterThan(0);+ const widthCss = (visible.at(-1)! - visible[0]! + 1) / dpr;+ const centerCss = (start + (visible[0]! + visible.at(-1)! + 1) / 2) / dpr;+ // At least the white face, about 7 CSS px in whole device pixels.+ expect(widthCss, name).toBeGreaterThanOrEqual(6.5);+ expect(widthCss, name).toBeLessThanOrEqual(12);+ expect(Math.abs(centerCss - center.x), name).toBeLessThanOrEqual(1);+ }+ }+ );+});+describe('color picker loupe', () => {const RED = [239, 18, 52, 255];const GREEN = [18, 200, 52, 255];diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.tsindex d2f683e4b2..c736652a26 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts@@ -23,7 +23,7 @@ const baseState = (overrides: Partial<OverlayState> = {}): OverlayState => ({});describe('renderOverlay', () => {- it('clears then strokes ONLY the bbox (dashed) — no document outline (unbounded plane)', () => {+ it('clears then draws ONLY the bbox frame — no document outline (unbounded plane)', () => {const backend = createTestStubRasterBackend();const target = backend.createSurface(200, 200);@@ -31,11 +31,12 @@ describe('renderOverlay', () => {const ops = target.callLog.map((e) => e.op);expect(ops).toContain('clearRect');- // The document rect is retired as a visual boundary: the bbox is the only rect stroked.- expect(target.callLog.filter((e) => e.op === 'strokeRect')).toHaveLength(1);- // At least one dashed setLineDash for the bbox.- const dashArgs = target.callLog.filter((e) => e.op === 'setLineDash').map((e) => e.args[0]);- expect(dashArgs).toContainEqual([4, 4]);+ // The document rect is retired as a visual boundary: nothing is stroked, and the frame's dashed bands are the+ // only fills, many dash rects each.+ expect(ops).not.toContain('strokeRect');+ expect(ops).not.toContain('stroke');+ expect(ops.filter((op) => op === 'fill')).toHaveLength(3);+ expect(ops.filter((op) => op === 'rect').length).toBeGreaterThan(3 * 8);});it('draws no grid when showGrid is false', () => {@@ -113,14 +114,15 @@ describe('renderOverlay', () => {const strokes = target.callLog.flatMap((entry, index) =>entry.op === 'strokeRect' ? [{ args: entry.args, index }] : []);- // A halo then the dashes for each region, then the bbox frame drawn last over them.+ // A halo then the dashes for each region, then the bbox frame drawn over them.expect(strokes.map((stroke) => stroke.args)).toEqual([[0, 0, 20, 20],[0, 0, 20, 20],[120, 140, 60, 40],[120, 140, 60, 40],- [20, 20, 80, 80],]);+ const frameFills = target.callLog.flatMap((entry, index) => (entry.op === 'fill' ? [index] : []));+ expect(frameFills[0]).toBeGreaterThan(strokes.at(-1)!.index);const lastSetBefore = (prop: string, index: number) =>target.callLog.slice(0, index)@@ -136,30 +138,40 @@ describe('renderOverlay', () => {expect(selectedDash![1]).toBe(1);expect(otherDash![1] as number).toBeLessThan(1);expect(selectedHalo![2]).toBe(otherHalo![2]);- expect(lastSetBefore('strokeStyle', strokes[4]!.index)).not.toBe(selectedDash![2]);+ expect(lastSetBefore('fillStyle', frameFills.at(-1)!)).not.toBe(selectedDash![2]);});it('draws no pending-result outline without regions', () => {const backend = createTestStubRasterBackend();const target = backend.createSurface(200, 200);renderOverlay(target, baseState({ stagedRegions: [] }));- expect(target.callLog.filter((e) => e.op === 'strokeRect')).toHaveLength(1);+ expect(target.callLog.filter((e) => e.op === 'strokeRect')).toHaveLength(0);});- it('strokes the bbox in its own accent color (no document-outline color)', () => {+ it('draws the bbox in its own accent color over its casings (no document-outline color)', () => {const backend = createTestStubRasterBackend();const target = backend.createSurface(200, 200);renderOverlay(target, baseState());- const strokeStyles = findSet(target.callLog, 'strokeStyle');- // Only bbox chrome is stroked; there is no document outline.- expect(strokeStyles).toEqual(['#3b82f6']);+ const fillStyles = findSet(target.callLog, 'fillStyle');+ // Only bbox chrome is drawn, the accent core last over both casings; there is no document outline.+ expect(fillStyles).toHaveLength(3);+ expect(fillStyles.at(-1)).toBe('#3b82f6');+ expect(new Set(fillStyles).size).toBe(3);+ });++ it('traces only the frame dashes inside the surface at deep zoom', () => {+ const backend = createTestStubRasterBackend();+ const target = backend.createSurface(200, 200);+ // Edges 8000 px long would hold about a thousand dashes each; a corner and two short stretches show.+ renderOverlay(target, baseState({ view: { a: 200, b: 0, c: 0, d: 200, e: -1900, f: -1900 } }));+ expect(target.callLog.filter((e) => e.op === 'rect').length).toBeLessThan(3 * 2 * 40);});it('hides the passive bbox frame when showBbox is false', () => {const backend = createTestStubRasterBackend();const target = backend.createSurface(200, 200);renderOverlay(target, baseState({ showBbox: false }));- expect(target.callLog.filter((e) => e.op === 'strokeRect')).toHaveLength(0);+ expect(target.callLog.filter((e) => e.op === 'fill' || e.op === 'strokeRect')).toHaveLength(0);});it('draws the bbox-overlay shade (evenodd punch-out) only when bboxOverlay is on', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.tsindex 3b54db9a54..fed90d2e51 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts@@ -22,6 +22,18 @@ export const MIN_GRID_SPACING_PX = 8;const BBOX_COLOR = '#3b82f6';const BBOX_DASH: readonly number[] = [4, 4];+/**+ * The generation frame's dashes are an accent hairline cased by the accent's darkest shade outside and white inside.+ * White carries backgrounds up to about 0.30 relative luminance, navy those from about 0.16, so some band of every dash+ * keeps at least about 3.8:1 contrast with any content (least at the accent itself, where both casings do), and the+ * frame stays blue rather than the brush ring's neutral dark/light/dark. Navy outside keeps the handles, which wrap the+ * same bands around a white face, edged dark over light content. The gaps stay clear, so a pending result's outline+ * under the frame still shows through them.+ */+const BBOX_CASING_OUTSIDE = '#172554';+const BBOX_CASING_INSIDE = '#ffffff';+/** Target frame dash and gap length (CSS px); each edge fits a whole odd number of them, dashes at both corners. */+const BBOX_FRAME_DASH_PX = 4;/** Pending results' landing rects: amber, so a frame moved off them still reads as a different thing. */const STAGED_REGION_COLOR = '#f59e0b';const STAGED_REGION_DASH: readonly number[] = [6, 4];@@ -40,8 +52,8 @@ const CURSOR_DARK = '#000000';const CURSOR_LIGHT = '#ffffff';const CURSOR_OUTER_WIDTH_PX = 3;const CURSOR_INNER_WIDTH_PX = 1;-/** Side length (screen px) of a drawn bbox resize handle. */-const BBOX_HANDLE_DRAW_PX = 8;+/** Side (CSS px) of a bbox resize handle's white face, inside its accent ring and dark casing hairlines. */+const BBOX_HANDLE_FACE_PX = 7;const BBOX_HANDLE_FILL = '#ffffff';/** Solid accent used for the selected-layer bounds outline while the move tool is active. */const LAYER_OUTLINE_COLOR = '#38bdf8';@@ -638,23 +650,185 @@ const drawRuleOfThirds = (ctx: Ctx, state: OverlayState): void => {ctx.restore();};-/** Draws the eight bbox resize handles as small squares at the frame's corners/edges (screen space). */-const drawBboxHandles = (ctx: Ctx, state: OverlayState): void => {- if (!state.bboxHandles) {+/**+ * The bbox frame in device pixels: core-line centres where whole device pixels of the hairline's width land crisply, so+ * an unaligned 1px line never smears into two half-strength pixels. The frame and its handles draw in device space.+ */+interface BboxFrameGeometry {+ /** Core-line centres, device px. */+ rect: Rect;+ /** Hairline width in whole device pixels: about one CSS pixel, never thinner than one device pixel. */+ hairline: number;+ /** The backing store's device size: dashes beyond it are skipped, so a deep zoom traces only what shows. */+ width: number;+ height: number;+}++/**+ * The device coordinate within half a pixel of `device` that centres a run of device pixels with odd (or even) width.+ * Where two qualify (an odd run on a pixel boundary, an even one on a pixel centre), it takes the one toward `outward`+ * (-1 before, +1 after), so a frame on whole pixels keeps its core just outside the area it marks on every side.+ */+const snapCentre = (device: number, odd: boolean, outward: -1 | 1): number => {+ if (odd) {+ return outward < 0 ? Math.ceil(device) - 0.5 : Math.floor(device) + 0.5;+ }+ return outward < 0 ? Math.ceil(device - 0.5) : Math.floor(device + 0.5);+};++const bboxFrameGeometry = (target: RasterSurface, state: OverlayState): BboxFrameGeometry => {+ const screen = transformBounds(state.view, state.bbox);+ const { dpr } = state;+ const hairline = Math.max(1, Math.round(dpr));+ const odd = hairline % 2 === 1;+ const left = snapCentre(screen.x * dpr, odd, -1);+ const top = snapCentre(screen.y * dpr, odd, -1);+ const right = snapCentre((screen.x + screen.width) * dpr, odd, 1);+ const bottom = snapCentre((screen.y + screen.height) * dpr, odd, 1);+ return {+ height: target.height,+ hairline,+ rect: { height: bottom - top, width: right - left, x: left, y: top },+ width: target.width,+ };+};++/** Edges run clockwise from the top-left corner: 0 top, 1 right, 2 bottom, 3 left; each starts at its own corner. */+const frameEdgeLength = (rect: Rect, edge: number): number => (edge % 2 === 0 ? rect.width : rect.height);++/** Dash and gap count along `edge`: an odd number near its length over the target, so it starts and ends on a dash. */+const frameEdgeSegments = (rect: Rect, edge: number, dash: number): number =>+ Math.max(1, Math.round((frameEdgeLength(rect, edge) / dash + 1) / 2)) * 2 - 1;++/** Distance along `edge` of the boundary after its `k`th of `segments` dashes and gaps, on a whole device pixel. */+const frameBoundary = (rect: Rect, edge: number, k: number, segments: number): number => {+ const length = frameEdgeLength(rect, edge);+ if (k <= 0 || k >= segments) {+ return k <= 0 ? 0 : length;+ }+ const start = edge === 0 ? rect.x : edge === 1 ? rect.y : edge === 2 ? rect.x + rect.width : rect.y + rect.height;+ const sign = edge < 2 ? 1 : -1;+ return sign * (Math.round(start + (sign * k * length) / segments) - start);+};++/**+ * Adds one band of one dash as a device-space rect. `from`/`to` run along `edge` from its starting corner; `inner` and+ * `outer` are the band's offsets from the core line's centre, positive outward.+ */+const frameBandRect = (+ ctx: Ctx,+ rect: Rect,+ edge: number,+ from: number,+ to: number,+ inner: number,+ outer: number+): void => {+ if (to <= from) {return;}- const screenRect = transformBounds(state.view, state.bbox);- const half = BBOX_HANDLE_DRAW_PX / 2;+ const right = rect.x + rect.width;+ const bottom = rect.y + rect.height;+ if (edge === 0) {+ ctx.rect(rect.x + from, rect.y - outer, to - from, outer - inner);+ } else if (edge === 1) {+ ctx.rect(right + inner, rect.y + from, outer - inner, to - from);+ } else if (edge === 2) {+ ctx.rect(right - to, bottom + inner, to - from, outer - inner);+ } else {+ ctx.rect(rect.x - outer, bottom - to, outer - inner, to - from);+ }+};++/**+ * Traces one band of the dashed frame in device space as axis-aligned rects on whole device pixels, so every edge is+ * crisp. Each edge fits its dashes between its corners, and a dash at a corner extends past it by the band's outer+ * offset: the bands of the two edges meeting there tile one whole L, with no seam, cap or join to notch it. Dash and gap+ * lengths vary by at most a device pixel along an edge.+ */+const traceBboxFrameBand = (ctx: Ctx, frame: BboxFrameGeometry, dash: number, inner: number, outer: number): void => {+ const { rect } = frame;+ const right = rect.x + rect.width;+ const bottom = rect.y + rect.height;+ // The inside band's offsets are negative: the band reaches as far as its larger magnitude.+ const reach = Math.max(Math.abs(inner), Math.abs(outer));+ ctx.beginPath();+ for (let edge = 0; edge < 4; edge++) {+ const across = edge === 0 ? rect.y : edge === 1 ? right : edge === 2 ? bottom : rect.x;+ if (across + reach < 0 || across - reach > (edge % 2 === 0 ? frame.height : frame.width)) {+ continue;+ }+ // The stretch of the edge inside the backing store, as distances from the edge's starting corner.+ const near = edge === 0 ? -rect.x : edge === 1 ? -rect.y : edge === 2 ? right - frame.width : bottom - frame.height;+ const far = edge === 0 ? frame.width - rect.x : edge === 1 ? frame.height - rect.y : edge === 2 ? right : bottom;+ const segments = frameEdgeSegments(rect, edge, dash);+ const step = frameEdgeLength(rect, edge) / segments;+ const first = Math.max(0, Math.floor((near - reach) / step / 2) * 2 - 2);+ const last = Math.min(segments, Math.ceil((far + reach) / step) + 2);+ for (let k = first; k < last; k += 2) {+ const from = frameBoundary(rect, edge, k, segments) - (k === 0 ? outer : 0);+ const to = frameBoundary(rect, edge, k + 1, segments) + (k + 1 === segments ? outer : 0);+ frameBandRect(ctx, rect, edge, from, to, inner, outer);+ }+ }+};++/**+ * Fills the dashed frame's three bands, each one batched fill: the outside casing, the inside casing, then the accent+ * core between them, every band one hairline wide.+ */+const drawBboxFrame = (ctx: Ctx, frame: BboxFrameGeometry, dpr: number): void => {+ const { hairline } = frame;+ const dash = BBOX_FRAME_DASH_PX * dpr;+ const half = hairline / 2;ctx.save();- ctx.setLineDash([]);- ctx.fillStyle = BBOX_HANDLE_FILL;- ctx.strokeStyle = BBOX_COLOR;- ctx.lineWidth = 1;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.fillStyle = BBOX_CASING_OUTSIDE;+ traceBboxFrameBand(ctx, frame, dash, half, half * 3);+ ctx.fill();+ ctx.fillStyle = BBOX_CASING_INSIDE;+ traceBboxFrameBand(ctx, frame, dash, -half * 3, -half);+ ctx.fill();+ ctx.fillStyle = BBOX_COLOR;+ traceBboxFrameBand(ctx, frame, dash, -half, half);+ ctx.fill();+ ctx.restore();+};++/** Adds a square of half-side `half` (device px) around each bbox handle, centred on the frame's core line. */+const traceBboxHandles = (ctx: Ctx, rect: Rect, odd: boolean, half: number): void => {+ ctx.beginPath();for (const handle of BBOX_HANDLES) {- const center = bboxHandlePoint(screenRect, handle);- ctx.fillRect(center.x - half, center.y - half, BBOX_HANDLE_DRAW_PX, BBOX_HANDLE_DRAW_PX);- ctx.strokeRect(center.x - half, center.y - half, BBOX_HANDLE_DRAW_PX, BBOX_HANDLE_DRAW_PX);+ const point = bboxHandlePoint(rect, handle);+ // Corners are already centred; an edge midpoint snaps either way.+ const x = snapCentre(point.x, odd, 1);+ const y = snapCentre(point.y, odd, 1);+ ctx.rect(x - half, y - half, half * 2, half * 2);}+};++/**+ * Draws the eight bbox resize handles centred on the frame's core line as the frame's bands wrapped into a square: an+ * outside-colored hairline, an accent ring, and a white face. Each band is one batched fill, so handles a small frame+ * overlaps merge into one shape.+ */+const drawBboxHandles = (ctx: Ctx, frame: BboxFrameGeometry, dpr: number): void => {+ const { hairline, rect } = frame;+ const odd = hairline % 2 === 1;+ // Whole device pixels with the hairline's parity, so the face centres on the core line's pixels.+ const parity = odd ? 1 : 0;+ const faceHalf = Math.max(1, Math.round((BBOX_HANDLE_FACE_PX * dpr - parity) / 2) * 2 + parity) / 2;+ ctx.save();+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.fillStyle = BBOX_CASING_OUTSIDE;+ traceBboxHandles(ctx, rect, odd, faceHalf + hairline * 2);+ ctx.fill();+ ctx.fillStyle = BBOX_COLOR;+ traceBboxHandles(ctx, rect, odd, faceHalf + hairline);+ ctx.fill();+ ctx.fillStyle = BBOX_HANDLE_FILL;+ traceBboxHandles(ctx, rect, odd, faceHalf);+ ctx.fill();ctx.restore();};@@ -683,17 +857,17 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): voiddrawStagedRegions(ctx, state);// Passive bbox visibility is optional; active-tool handles remain editable even when hidden.+ const bboxFrame = bboxFrameGeometry(target, state);if (state.showBbox ?? true) {- ctx.strokeStyle = BBOX_COLOR;- ctx.setLineDash([...BBOX_DASH]);- strokeRectScreen(ctx, transformBounds(state.view, state.bbox));- ctx.setLineDash([]);+ drawBboxFrame(ctx, bboxFrame, state.dpr);}drawSamPreview(ctx, state, base);drawSamGeometry(ctx, state);drawLayerOutline(ctx, state);- drawBboxHandles(ctx, state);+ if (state.bboxHandles) {+ drawBboxHandles(ctx, bboxFrame, state.dpr);+ }drawTransformFrame(ctx, state);if (state.marchingAnts) {drawMarchingAnts(ctx, state.view, state.marchingAnts, base);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.tsindex 42bac9a4d5..c56d1489c2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOps.ts@@ -1,27 +1,46 @@/*** Masked fill/erase primitives; engine callers own guards, history and persistence. Scratch compositing confines- * edits to selection coverage. Rect coordinates are document=layer-local here; subtract target/mask origins to- * address each content-sized surface.+ * edits to selection coverage. `rect` and the target live in the layer's local space; the mask is placed through+ * `maskToLocal`, so a moved, scaled or rotated layer is edited where the selection covers it.*/import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { Rect, Vec2 } from '@workbench/canvas-engine/types';+import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';-/** Shared inputs for a masked layer edit over a document-space `rect`. */+import { identity, multiply, translate } from '@workbench/canvas-engine/math/mat2d';++/** Shared inputs for a masked layer edit over a layer-local `rect`. */export interface MaskedEditParams {backend: RasterBackend;- /** The layer cache surface (content-sized) and its document-space origin. */+ /** The layer cache surface (content-sized). */target: RasterSurface;- /** The target surface's document-space origin (its cache rect's `x`/`y`). */+ /** The target surface's layer-local origin (its cache rect's `x`/`y`). */targetOrigin: Vec2;/** The selection mask surface (alpha 255 inside). */mask: RasterSurface;- /** The mask surface's document-space origin (its selection rect's `x`/`y`). */+ /** The mask surface's origin in its own space (its selection rect's `x`/`y`). */maskOrigin: Vec2;- /** The dirty region to edit (document space), integer bounds. */+ /** Maps the mask's space into the target's; absent when both share one space. */+ maskToLocal?: Mat2d;+ /** The dirty region to edit (layer-local), integer bounds. */rect: Rect;}+/** Draws the mask into a scratch surface whose origin is `rect`'s, through `maskToLocal`. */+const drawMask = (+ ctx: RasterSurface['ctx'],+ { mask, maskOrigin, maskToLocal, rect }: Pick<MaskedEditParams, 'mask' | 'maskOrigin' | 'maskToLocal' | 'rect'>+): void => {+ if (!maskToLocal) {+ ctx.drawImage(mask.canvas, maskOrigin.x - rect.x, maskOrigin.y - rect.y);+ return;+ }+ const m = multiply(translate(identity(), { x: -rect.x, y: -rect.y }), maskToLocal);+ ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);+ ctx.drawImage(mask.canvas, maskOrigin.x, maskOrigin.y);+ ctx.setTransform(1, 0, 0, 1, 0, 0);+};+/*** Fill a region-local scratch, intersect the mask, then composite onto target. Default source-over fills coverage;* source-atop preserves transparency lock.@@ -32,6 +51,7 @@ export const fillMaskedRegion = ({composite = 'source-over',mask,maskOrigin,+ maskToLocal,rect,target,targetOrigin,@@ -47,7 +67,7 @@ export const fillMaskedRegion = ({sctx.fillStyle = color;sctx.fillRect(0, 0, rect.width, rect.height);sctx.globalCompositeOperation = 'destination-in';- sctx.drawImage(mask.canvas, maskOrigin.x - rect.x, maskOrigin.y - rect.y);+ drawMask(sctx, { mask, maskOrigin, maskToLocal, rect });const ctx = target.ctx;ctx.save();@@ -62,6 +82,7 @@ export const eraseMaskedRegion = ({backend,mask,maskOrigin,+ maskToLocal,rect,target,targetOrigin,@@ -74,7 +95,7 @@ export const eraseMaskedRegion = ({sctx.setTransform(1, 0, 0, 1, 0, 0);sctx.globalCompositeOperation = 'source-over';sctx.globalAlpha = 1;- sctx.drawImage(mask.canvas, maskOrigin.x - rect.x, maskOrigin.y - rect.y);+ drawMask(sctx, { mask, maskOrigin, maskToLocal, rect });const ctx = target.ctx;ctx.save();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.tsindex 34df0599c5..76cd093cf3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts@@ -1,10 +1,11 @@+import type { CanvasEditRefusal } from '@workbench/canvas-engine/capabilities';import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { Viewport } from '@workbench/canvas-engine/viewport';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { describe, expect, it, vi } from 'vitest';@@ -67,6 +68,7 @@ interface StructuralCommit {const createHarness = (doc: CanvasDocumentContractV3) => {const dispatched: CanvasProjectMutation[] = [];const commits: StructuralCommit[] = [];+ const refusals: CanvasEditRefusal[] = [];const stores = createEngineStores();let idCounter = 0;const ctx: ToolContext = {@@ -85,13 +87,14 @@ const createHarness = (doc: CanvasDocumentContractV3) => {invalidate: vi.fn(),layers: null as never,notifyLayerPainted: vi.fn(),+ reportEditRefusal: (refusal) => refusals.push(refusal),setLayerTransformOverride: vi.fn(),setOverlayCursor: vi.fn(),stores,updateCursor: vi.fn(),viewport: identityViewport,};- return { commits, ctx, dispatched, previewOf: () => stores.gradientPreview.get(), stores };+ return { commits, ctx, dispatched, previewOf: () => stores.gradientPreview.get(), refusals, stores };};const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDown?.(ctx, i);@@ -245,19 +248,35 @@ describe('gradient tool: edit selected gradient layer', () => {}});- it('is a no-op when the selected gradient layer is locked', () => {- const layer = gradientLayer({ isLocked: true });+ it.each([+ ['locked', { isLocked: true }, 'layer-locked'],+ ['hidden', { isEnabled: false }, 'layer-hidden'],+ ] as const)('refuses a %s selected gradient at the press, drawing no preview', (_, overrides, status) => {+ const layer = gradientLayer(overrides);const doc = makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'grad-existing' });const h = createHarness(doc);const tool = createGradientTool();+ expect(tool.cursor?.(h.ctx)).toBe('not-allowed');down(tool, h.ctx, pointer(0, 0));+ expect(h.refusals).toEqual([{ layerId: 'grad-existing', layerName: layer.name, status }]);move(tool, h.ctx, pointer(100, 0));+ expect(h.previewOf()).toBeNull();up(tool, h.ctx, pointer(100, 0));+ expect(h.refusals).toHaveLength(1);expect(h.commits).toHaveLength(0);expect(h.dispatched).toHaveLength(0);- expect(h.previewOf()).toBeNull();+ });++ it('shows the crosshair over an editable gradient or any other selection', () => {+ const tool = createGradientTool();+ expect(+ tool.cursor?.(+ createHarness(makeDoc({ stacks: stacksFrom([gradientLayer()]), selectedLayerId: 'grad-existing' })).ctx+ )+ ).toBe('crosshair');+ expect(tool.cursor?.(createHarness(makeDoc()).ctx)).toBe('crosshair');});it("reads the drag in the layer's local space when it is moved, scaled and rotated", () => {@@ -331,4 +350,36 @@ describe('gradient tool: edit selected gradient layer', () => {expect(h.commits[0]?.forward.type).toBe('addCanvasLayer');});++ it.each([+ ['an inpaint mask', 'inpaint_mask'],+ ['a regional guidance layer', 'regional_guidance'],+ ] as const)('refuses at the press with %s selected, adding no layer', (_, type) => {+ const doc = makeDoc({ stacks: stacksFrom([layerContract('mask-1', type)]), selectedLayerId: 'mask-1' });+ const h = createHarness(doc);+ const tool = createGradientTool();++ expect(tool.cursor?.(h.ctx)).toBe('not-allowed');+ down(tool, h.ctx, pointer(0, 0));+ move(tool, h.ctx, pointer(50, 50));+ up(tool, h.ctx, pointer(50, 50));++ expect(h.refusals).toEqual([{ layerId: 'mask-1', layerName: 'mask-1', status: 'gradient-unsupported' }]);+ expect(h.previewOf()).toBeNull();+ expect(h.commits).toHaveLength(0);+ expect(h.dispatched).toHaveLength(0);+ });++ it('still adds a raster gradient with a control layer selected', () => {+ const doc = makeDoc({ stacks: stacksFrom([layerContract('control-1', 'control')]), selectedLayerId: 'control-1' });+ const h = createHarness(doc);+ const tool = createGradientTool();++ down(tool, h.ctx, pointer(0, 0));+ move(tool, h.ctx, pointer(50, 50));+ up(tool, h.ctx, pointer(50, 50));++ expect(h.refusals).toEqual([]);+ expect(h.commits[0]?.forward.type).toBe('addCanvasLayer');+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.tsindex 51b6bb2ca6..8a2453c2c5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts@@ -1,10 +1,12 @@/*** Gradient drag defines linear start/end or radial center/radius. Editable selected gradients update placement in- * layer-local space while preserving kind/stops/extent; locked or hidden gradients refuse. Otherwise create a- * bbox-sized gradient from options. Preview/cancel never dispatch; one real drag makes one commit. Selection masks- * do not clip parametric gradients.+ * layer-local space while preserving kind/stops/extent; locked or hidden gradients, and a selected mask or region+ * (a gradient is a raster layer of its own), refuse at the press, with the not-allowed cursor beforehand. Otherwise+ * create a bbox-sized gradient from options. Preview/cancel never dispatch; one real drag makes one commit. Selection+ * masks do not clip parametric gradients.*/+import type { CanvasLayerEditRefusal } from '@workbench/canvas-engine/capabilities';import type {CanvasLayerBaseContract,CanvasLayerSourceContract,@@ -16,6 +18,7 @@ import type { Vec2 } from '@workbench/canvas-engine/types';import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';import { leafEditRefusal } from '@workbench/canvas-engine/document/layerEligibility';+import { isMaskLayer } from '@workbench/canvas-engine/document/sources';import { applyToPoint, invert } from '@workbench/canvas-engine/math/mat2d';import type { Tool, ToolContext } from './tool';@@ -65,6 +68,24 @@ const toLayerLocal = (return inverse ? [applyToPoint(inverse, start), applyToPoint(inverse, end)] : null;};+/**+ * Why a drag now would be refused: the selected gradient it would edit is locked or hidden, or a mask or region is+ * selected, which never takes a new raster layer in its place.+ */+const predictRefusal = (ctx: ToolContext): CanvasLayerEditRefusal | null => {+ const doc = ctx.getDocument();+ const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;+ const selected = leaf?.layer;+ if (!leaf || !selected) {+ return null;+ }+ if (isMaskLayer(selected)) {+ return { layerId: selected.id, layerName: selected.name, status: 'gradient-unsupported' };+ }+ const status = selected.type === 'raster' && selected.source.type === 'gradient' ? leafEditRefusal(leaf) : null;+ return status ? { layerId: selected.id, layerName: selected.name, status } : null;+};+/** Creates a fresh gradient tool with its own gesture state. */export const createGradientTool = (): Tool => {let state: GestureState | null = null;@@ -75,7 +96,7 @@ export const createGradientTool = (): Tool => {};return {- cursor: () => 'crosshair',+ cursor: (ctx) => (!state && predictRefusal(ctx) ? 'not-allowed' : 'crosshair'),id: 'gradient',onDeactivate: (ctx) => {state = null;@@ -101,6 +122,11 @@ export const createGradientTool = (): Tool => {if (!doc) {return;}+ const refusal = predictRefusal(ctx);+ if (refusal) {+ ctx.reportEditRefusal?.(refusal);+ return;+ }const selected = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId)?.layer : null;const kind =selected?.type === 'raster' && selected.source.type === 'gradient'@@ -144,7 +170,7 @@ export const createGradientTool = (): Tool => {const selected = leaf?.layer;if (leaf && selected && selected.type === 'raster' && selected.source.type === 'gradient') {- // Edit the selected gradient layer, unless it is locked or hidden (refused with a notice).+ // The press refused a locked or hidden gradient; this catches one that became so during the drag.const refusal = leafEditRefusal(leaf);if (refusal) {ctx.reportEditRefusal?.({ layerId: selected.id, layerName: selected.name, status: refusal });diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.browser.test.tsnew file mode 100644index 0000000000..0f18d1134a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.browser.test.ts@@ -0,0 +1,58 @@+import type { ToolContext } from '@workbench/canvas-engine/tools/tool';+import type { PointerInput } from '@workbench/canvas-engine/types';++import { createEngineStores } from '@workbench/canvas-engine/engineStores';+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { createSelectionState } from '@workbench/canvas-engine/selection/selectionState';+import { createLassoTool } from '@workbench/canvas-engine/tools/lassoTool';+import { expect, it } from 'vitest';++it.each([+ [1, 1, 1],+ [10, 10, 0.1],+ [0.5, 0.5, 10],+ [8, 0.25, 1],+])('rasterizes a %s by %s lasso at %sx zoom', (width, height, zoom) => {+ const selection = createSelectionState({+ backend: createDomRasterBackend(),+ createPath2D: (d) => new Path2D(d),+ getDocumentSize: () => ({ height: 100, width: 100 }),+ onChange: () => undefined,+ });+ const ctx = {+ commitSelection: selection.commit,+ createPath2D: (d?: string) => new Path2D(d),+ invalidate: () => {},+ stores: createEngineStores(),+ } as unknown as ToolContext;+ const pointer = (x: number, y: number): PointerInput => ({+ buttons: 1,+ documentPoint: { x, y },+ modifiers: { alt: false, ctrl: false, meta: false, shift: false },+ pointerType: 'mouse',+ pressure: 0.5,+ screenPoint: { x: x * zoom, y: y * zoom },+ timeStamp: 0,+ });+ const tool = createLassoTool();+ try {+ tool.onPointerDown?.(ctx, pointer(10, 10));+ for (const [x, y] of [+ [10 + width, 10],+ [10 + width, 10 + height],+ [10, 10 + height],+ ] as const) {+ const input = pointer(x, y);+ tool.onPointerMove?.(ctx, input, [input]);+ }+ tool.onPointerUp?.(ctx, pointer(10, 10));++ expect(selection.hasSelection()).toBe(true);+ const mask = selection.mask()!;+ const { data } = mask.surface.ctx.getImageData(0, 0, mask.surface.width, mask.surface.height);+ expect([...data].some((value, index) => index % 4 === 3 && value > 0)).toBe(true);+ expect(selection.containsPoint({ x: 10 + width / 2, y: 10 + height / 2 })).toBe(true);+ } finally {+ selection.dispose();+ }+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.tsindex 22742994f6..61cceac4ac 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts@@ -1,10 +1,11 @@import type { SelectionCommit } from '@workbench/canvas-engine/selection/selectionState';import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';-import type { PointerInput } from '@workbench/canvas-engine/types';+import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import type { WorkbenchAction } from '@workbench/workbenchState.testing';import { createEngineStores } from '@workbench/canvas-engine/engineStores';-import { createLassoTool } from '@workbench/canvas-engine/tools/lassoTool';+import { polygonBounds } from '@workbench/canvas-engine/freehand';+import { createLassoTool, FREEHAND_MIN_SPACING_PX } from '@workbench/canvas-engine/tools/lassoTool';import { describe, expect, it, vi } from 'vitest';const pointer = (@@ -117,33 +118,134 @@ describe('lassoTool: cancel + guards', () => {expect(commits).toHaveLength(0);});- it('decimates by on-screen travel, stores document points, and always keeps the release point', () => {- const at = (x: number, y: number, zoom: number): PointerInput => ({+ it.each([+ [1, 1, 1],+ [10, 10, 0.1],+ [0.5, 0.5, 10],+ [8, 0.25, 1],+ ])('keeps a %s by %s outline at %sx zoom', (width, height, zoom) => {+ const tool = createLassoTool();+ const { commits, ctx } = createHarness();+ const at = (x: number, y: number): PointerInput => ({...pointer(x, y),screenPoint: { x: x * zoom, y: y * zoom },});- // Zoomed in 10×: half-pixel document steps are 5 CSS px apart and all survive.- const zoomedIn = createLassoTool();- const near = createHarness();- down(zoomedIn, near.ctx, at(0, 0, 10));- move(zoomedIn, near.ctx, at(0.5, 0, 10));- move(zoomedIn, near.ctx, at(0.5, 0.5, 10));- expect(near.stores.lassoPreview.get()?.points).toEqual([+ down(tool, ctx, at(0, 0));+ move(tool, ctx, at(width, 0));+ move(tool, ctx, at(width, height));+ move(tool, ctx, at(0, height));+ up(tool, ctx, at(0, 0));++ expect(commits).toHaveLength(1);+ expect(commits[0]!.bounds).toEqual({ height, width, x: 0, y: 0 });+ });++ it('coalesces repeated and forward collinear samples without losing reversals or thin corners', () => {+ const tool = createLassoTool();+ const { commits, ctx, stores } = createHarness();+ down(tool, ctx, pointer(0, 0));+ for (let step = 0; step <= 1000; step++) {+ move(tool, ctx, pointer(step / 10, 0));+ }+ expect(stores.lassoPreview.get()?.points).toEqual([{ x: 0, y: 0 },- { x: 0.5, y: 0 },- { x: 0.5, y: 0.5 },+ { x: 100, y: 0 },]);+ move(tool, ctx, pointer(90, 0));+ move(tool, ctx, pointer(90, 0.25));+ up(tool, ctx, pointer(0, 0.25));++ expect(commits).toHaveLength(1);+ expect(commits[0]!.path).toEqual({ d: 'M 0 0 L 100 0 L 90 0 L 90 0.25 L 0 0.25 Z' });+ });++ it('thins a long dense drag by on-screen spacing, staying on its path and ending where it was released', () => {+ // Ten seconds of a 1000 Hz pen tracing a wobbly loop, 0.1 CSS px apart, at a zoom and pan with fractional+ // document coordinates, delivered in 60 Hz batches as coalesced events arrive.+ const zoom = 1.7;+ const pan = { x: 13.37, y: -7.21 };+ const at = (sx: number, sy: number): PointerInput => ({+ ...pointer((sx - pan.x) / zoom, (sy - pan.y) / zoom),+ screenPoint: { x: sx, y: sy },+ });+ const samples = Array.from({ length: 10_001 }, (_, index) => {+ const angle = (index / 10_000) * 2 * Math.PI;+ const radius = 150 + 20 * Math.sin(5 * angle);+ return at(400 + radius * Math.cos(angle), 300 + radius * Math.sin(angle));+ });+ const release = samples.pop()!;+ const tool = createLassoTool();+ const { commits, ctx } = createHarness();+ down(tool, ctx, samples[0]!);+ for (let start = 1; start < samples.length; start += 16) {+ const batch = samples.slice(start, start + 16);+ tool.onPointerMove?.(ctx, batch[batch.length - 1]!, batch);+ }+ up(tool, ctx, release);++ const vertices = [...(commits[0]!.path as unknown as { d: string }).d.matchAll(/[ML] (\S+) (\S+)/g)].map(+ ([, x, y]) => ({ x: Number(x), y: Number(y) })+ );+ let screenLength = 0;+ for (let index = 1; index <= samples.length; index++) {+ const a = samples[index - 1]!.screenPoint;+ const b = (samples[index] ?? release).screenPoint;+ screenLength += Math.hypot(b.x - a.x, b.y - a.y);+ }+ // A point is added only once the last point or the new sample lies the spacing from the point two back, so the+ // dense path from that point to the new sample is at least the spacing long. Later samples may replace the added+ // point, but only with ones further along, so these stretches of the dense path each end at or before a kept point+ // and overlap at most twice: added points ≤ 2 × path length / spacing, plus the first press and its next point.+ expect(vertices.length).toBeLessThanOrEqual((2 * screenLength) / FREEHAND_MIN_SPACING_PX + 2);+ expect(vertices.length).toBeLessThan(samples.length / 3);+ expect(vertices[vertices.length - 1]).toEqual(release.documentPoint);++ // Every dropped sample lies within the spacing of a kept point, so within it of the outline.+ const tolerance = FREEHAND_MIN_SPACING_PX / zoom + 1e-9;+ const distanceToSegment = (p: Vec2, a: Vec2, b: Vec2): number => {+ const dx = b.x - a.x;+ const dy = b.y - a.y;+ const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy || 1)));+ return Math.hypot(p.x - a.x - t * dx, p.y - a.y - t * dy);+ };+ let segment = 1;+ for (const { documentPoint } of samples) {+ // Samples and kept points share their order, so the nearest segment is at or after the previous one.+ while (+ segment < vertices.length - 1 &&+ distanceToSegment(documentPoint, vertices[segment - 1]!, vertices[segment]!) > tolerance+ ) {+ segment++;+ }+ expect(distanceToSegment(documentPoint, vertices[segment - 1]!, vertices[segment]!)).toBeLessThanOrEqual(+ tolerance+ );+ }+ const dense = polygonBounds([...samples.map((sample) => sample.documentPoint), release.documentPoint]);+ const kept = commits[0]!.bounds;+ for (const key of ['x', 'y', 'width', 'height'] as const) {+ expect(Math.abs(kept[key] - dense[key])).toBeLessThanOrEqual(2 * tolerance);+ }+ });++ it('commits a self-crossing outline even when its signed areas cancel', () => {+ const tool = createLassoTool();+ const { commits, ctx } = createHarness();+ down(tool, ctx, pointer(0, 0));+ move(tool, ctx, pointer(1, 1));+ move(tool, ctx, pointer(0, 1));+ move(tool, ctx, pointer(1, 0));+ up(tool, ctx, pointer(0, 0));+ expect(commits).toHaveLength(1);+ });- // Zoomed out 10×: 10-unit document steps are 1 CSS px apart and decimate away, but the release point stays.- const zoomedOut = createLassoTool();- const far = createHarness();- down(zoomedOut, far.ctx, at(0, 0, 0.1));- move(zoomedOut, far.ctx, at(10, 0, 0.1));- expect(far.stores.lassoPreview.get()?.points).toHaveLength(1);- move(zoomedOut, far.ctx, at(40, 0, 0.1));- move(zoomedOut, far.ctx, at(40, 40, 0.1));- up(zoomedOut, far.ctx, at(41, 40, 0.1));- expect(far.commits[0]?.bounds).toEqual({ height: 40, width: 41, x: 0, y: 0 });+ it('does not commit a diagonal line with three distinct vertices', () => {+ const tool = createLassoTool();+ const { commits, ctx } = createHarness();+ down(tool, ctx, pointer(0, 0));+ move(tool, ctx, pointer(2, 2));+ up(tool, ctx, pointer(4, 4));+ expect(commits).toHaveLength(0);});});@@ -203,6 +305,17 @@ describe('lassoTool: polygon mode', () => {expect(stores.lassoPreview.get()).toBeNull();});+ it('commits subpixel polygon vertices on Enter', () => {+ const tool = createLassoTool();+ const { commits, ctx } = createPolygonHarness();+ click(tool, ctx, 0, 0, 0);+ click(tool, ctx, 0.5, 0, 1000);+ click(tool, ctx, 0.5, 0.5, 2000);+ tool.onKeyCommand?.(ctx, 'apply');+ expect(commits).toHaveLength(1);+ expect(commits[0]!.bounds).toEqual({ height: 0.5, width: 0.5, x: 0, y: 0 });+ });+it('arms the close cue and pointer cursor while the cursor hovers the first vertex', () => {const tool = createLassoTool();const { ctx, stores } = createPolygonHarness();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.tsindex 09ed9595c8..6b9f056a37 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts@@ -1,40 +1,74 @@/**- * Freehand lasso gathers decimated drag points; polygon lasso spans clicks and closes on double-click, Enter or- * first-vertex proximity. Both commit through `commitSelection` with shared modifier/persistent-op resolution.+ * Freehand lasso thins its drag by sub-pixel screen spacing and straight runs, keeping corners. Polygon lasso spans+ * clicks and closes on double-click, Enter or first-vertex proximity. Both commit through `commitSelection` with shared modifier/persistent-op resolution.* Previews never dispatch. Temporary tool switches preserve polygon sessions; real switches cancel them. Selection* history is owned by the engine wrapper.*/-import type { Vec2 } from '@workbench/canvas-engine/types';+import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import { polygonBounds, polygonToSvgPath } from '@workbench/canvas-engine/freehand';import { selectionOpFor } from '@workbench/canvas-engine/selection/selectionOpMode';import type { Tool, ToolContext } from './tool';-import {- extendFreehandTrace,- finishFreehandTrace,- MIN_POLYLINE_POINTS,- movePolyline,- polylinePreview,- pressPolyline,- startFreehandTrace,- startPolyline,- type FreehandTrace,- type PolylineSession,-} from './polylineSession';+import { movePolyline, polylinePreview, pressPolyline, startPolyline, type PolylineSession } from './polylineSession';/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */const PRIMARY_BUTTON = 1;const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);-/** A freehand drag in progress. */-interface FreehandSession extends FreehandTrace {+/**+ * Least on-screen gap (CSS px) between a kept freehand point and the one before it. Below a pixel, so it never removes+ * an outline the user can see, at any zoom; it only collapses dense pointer samples (high-rate mice, pens) that would+ * otherwise each become a vertex the preview copies and strokes on every frame.+ */+export const FREEHAND_MIN_SPACING_PX = 0.5;++/** A freehand drag in progress: document points, with the screen point each was sampled at. */+interface FreehandSession {kind: 'freehand';+ points: Vec2[];+ screenPoints: Vec2[];}+/**+ * The last point gives way to a new sample while both lie within `FREEHAND_MIN_SPACING_PX` of the point before it;+ * once one leaves that radius the last point stays. Every dropped sample lies within the spacing of a kept point, so+ * thinning moves the outline by less than the spacing and keeps corners and reversals beyond it, and the outline+ * always ends at the latest sample. Redundant points on a forward straight run are dropped too.+ */+const appendFreehandPoint = (session: FreehandSession, sample: PointerInput): void => {+ const { points, screenPoints } = session;+ const point = sample.documentPoint;+ const screen = sample.screenPoint;+ const end = points.length - 1;+ const last = points[end]!;+ if (last.x === point.x && last.y === point.y) {+ return;+ }+ const previous = points[end - 1];+ const previousScreen = screenPoints[end - 1];+ if (previous && previousScreen) {+ const withinSpacing =+ distance(previousScreen, screenPoints[end]!) < FREEHAND_MIN_SPACING_PX &&+ distance(previousScreen, screen) < FREEHAND_MIN_SPACING_PX;+ const dx = last.x - previous.x;+ const dy = last.y - previous.y;+ const nextDx = point.x - last.x;+ const nextDy = point.y - last.y;+ const forwardStraight = dx * nextDy === dy * nextDx && dx * nextDx + dy * nextDy > 0;+ if (withinSpacing || forwardStraight) {+ points[end] = { x: point.x, y: point.y };+ screenPoints[end] = { x: screen.x, y: screen.y };+ return;+ }+ }+ points.push({ x: point.x, y: point.y });+ screenPoints.push({ x: screen.x, y: screen.y });+};+/** A polygon vertex-placing session spanning multiple clicks. */interface PolygonSession extends PolylineSession {kind: 'polygon';@@ -69,13 +103,20 @@ export const createLassoTool = (): Tool => {/** Commits `polygon` as a selection under the modifiers held at close time. */const commit = (ctx: ToolContext, polygon: readonly Vec2[], modifiers: { shift: boolean; alt: boolean }): void => {- const bounds = polygonBounds(polygon);- // A double-click's second press lands on the previous vertex, so count- // distinct points; and a flat polygon would select a line of nothing.- const distinct = polygon.filter((point, index) => index === 0 || distance(point, polygon[index - 1]!) >= 1);- if (distinct.length < MIN_POLYLINE_POINTS || bounds.width < 1 || bounds.height < 1 || !ctx.commitSelection) {+ const first = polygon[0];+ const second = polygon.find((point) => point.x !== first?.x || point.y !== first?.y);+ // A line has no fill, but signed area alone would also reject valid self-crossing outlines.+ if (+ !first ||+ !second ||+ !polygon.some(+ (point) => (second.x - first.x) * (point.y - first.y) !== (second.y - first.y) * (point.x - first.x)+ ) ||+ !ctx.commitSelection+ ) {return;}+ const bounds = polygonBounds(polygon);ctx.commitSelection({bounds,op: selectionOpFor(modifiers, ctx.stores.lassoOptions.get().mode),@@ -139,7 +180,7 @@ export const createLassoTool = (): Tool => {if (session) {return;}- session = { ...startFreehandTrace(input), kind: 'freehand' };+ session = { kind: 'freehand', points: [{ ...input.documentPoint }], screenPoints: [{ ...input.screenPoint }] };publishPreview(ctx);return;}@@ -169,7 +210,9 @@ export const createLassoTool = (): Tool => {ctx.updateCursor();}} else {- extendFreehandTrace(session, batch);+ for (const sample of batch) {+ appendFreehandPoint(session, sample);+ }}publishPreview(ctx);},@@ -179,7 +222,8 @@ export const createLassoTool = (): Tool => {if (!session || session.kind === 'polygon') {return;}- const polygon = finishFreehandTrace(session, input);+ appendFreehandPoint(session, input);+ const polygon = session.points;reset();clearPreview(ctx);commit(ctx, polygon, input.modifiers);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.tsindex 312822fe11..f1fb8f17f7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts@@ -678,6 +678,88 @@ describe('paint tool: target resolution', () => {const h = createHarness(makeDoc([paintLayer('paint1')], 'paint1'));expect(createBrushTool().cursor?.(h.ctx)).toBe('crosshair');});++ it.each([+ ['brush', createBrushTool],+ ['eraser', createEraserTool],+ ] as const)('%s refuses a mask hidden on the canvas only, so it never paints unseen', (_, createTool) => {+ const doc = makeDoc([{ ...inpaintMaskLayer('mask1'), isHidden: true } as CanvasLayerContract], 'mask1');+ const h = createHarness(doc);+ const tool = createTool();++ expect(tool.cursor?.(h.ctx)).toBe('not-allowed');+ expect(tool.editsSelectedLayer?.(h.ctx)).toBe(false);+ down(tool, h.ctx, pointer(20, 20));+ up(tool, h.ctx, pointer(40, 40));++ expect(h.strokeEdits).toHaveLength(0);+ expect(h.strokes).toHaveLength(0);+ expect(h.refusals).toEqual([{ layerId: 'mask1', layerName: 'mask1', status: 'layer-display-hidden' }]);+ });+});++describe('eraser targets', () => {+ const group = (id: string, children: CanvasLayerContract[]) =>+ ({ children, id, isEnabled: true, isLocked: false, name: id, type: 'group' }) as unknown as CanvasLayerContract;++ it.each([+ ['a text layer', [textLayer('sel')]],+ ['a group', [group('sel', [paintLayer('child')])]],+ ] as const)('refuses %s with a notice, creating no layer and keeping the selection', (_, layers) => {+ const doc = makeDoc([...layers], 'sel');+ const h = createHarness(doc);+ const eraser = createEraserTool();++ expect(eraser.cursor?.(h.ctx)).toBe('not-allowed');+ down(eraser, h.ctx, pointer(20, 20));+ move(eraser, h.ctx, pointer(40, 40), [pointer(40, 40)]);+ up(eraser, h.ctx, pointer(40, 40));++ expect(h.dispatched).toEqual([]);+ expect(h.strokeEdits).toHaveLength(0);+ expect(h.refusals).toEqual([{ layerId: 'sel', layerName: 'sel', status: 'erase-unsupported' }]);+ });++ it.each([+ ['brush', createBrushTool],+ ['eraser', createEraserTool],+ ] as const)('%s refuses a control layer whose empty shape has no pixels, as its cursor said', (_, createTool) => {+ const control: CanvasControlLayerContract = {+ ...controlPaintLayer('ctl'),+ source: {+ fill: '#fff',+ height: 10,+ kind: 'polygon',+ points: [],+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: 10,+ },+ };+ const h = createHarness(makeDoc([control], 'ctl'), controlTransaction('ctl'));+ const tool = createTool();++ expect(tool.cursor?.(h.ctx)).toBe('not-allowed');+ down(tool, h.ctx, pointer(20, 20));+ up(tool, h.ctx, pointer(20, 20));++ expect(h.beginPixelEdit).not.toHaveBeenCalled();+ expect(h.dispatched).toEqual([]);+ expect(h.refusals).toEqual([{ layerId: 'ctl', layerName: 'ctl', status: 'layer-unpaintable' }]);+ });++ it('refuses a press with nothing selected', () => {+ const h = createHarness(makeDoc([paintLayer('paint1')], null));+ const eraser = createEraserTool();++ expect(eraser.cursor?.(h.ctx)).toBe('not-allowed');+ down(eraser, h.ctx, pointer(20, 20));+ up(eraser, h.ctx, pointer(20, 20));++ expect(h.dispatched).toEqual([]);+ expect(h.refusals).toEqual([{ status: 'erase-no-target' }]);+ });});describe('transparency lock', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex 54266cad05..59979f11d4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -1,8 +1,9 @@/*** Shared brush/eraser gesture resolves or creates a target, drives a StrokeSession and commits/cancels. Only* gesture-start layer creation dispatches here; moves never dispatch. Fill/erase differ by blend and option- * source. A Shift press on a layer with a remembered stroke end draws a straight segment from it; the end is kept- * layer-local, so moving or transforming the layer carries it.+ * source. The eraser never creates a layer: a selection it cannot erase in place, or none, is refused. A Shift press+ * on a layer with a remembered stroke end draws a straight segment from it; the end is kept layer-local, so moving or+ * transforming the layer carries it.*/import type { CanvasLayerEditRefusal } from '@workbench/canvas-engine/capabilities';@@ -12,9 +13,10 @@ import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/documenimport type { Mat2d, PointerInput } from '@workbench/canvas-engine/types';import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';-import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';-import { isLayerTransparencyLocked, leafEditRefusal } from '@workbench/canvas-engine/document/layerEligibility';+import { getDocumentLayer, getDocumentLeaves, getDocumentNode } from '@workbench/canvas-engine/document/documentIndex';+import { isLayerTransparencyLocked } from '@workbench/canvas-engine/document/layerEligibility';import { isMaskLayer } from '@workbench/canvas-engine/document/sources';+import { editsPixelsInPlace, leafPaintRefusal } from '@workbench/canvas-engine/editing/controlPixelEdit';import { applyToPoint, fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';import type { StrokeEdit, Tool, ToolContext } from './tool';@@ -89,7 +91,7 @@ const targetMatrix = ({ transform }: PaintTarget): Mat2d | null =>/** Reports why the selected layer refused the press, naming it for the notice. */const refuse = (ctx: ToolContext,- layer: CanvasLayerContract,+ layer: Pick<CanvasLayerContract, 'id' | 'name'>,status: CanvasLayerEditRefusal['status'],extra: Pick<CanvasLayerEditRefusal, 'canPaintNewLayer'> = {}): null => {@@ -114,29 +116,17 @@ const awaitsPixels = (ctx: ToolContext, layerId: string, hasDurablePixels: boolereturn true;};-/** Whether a press paints `layer` itself; any other selection (a group, text, a gradient) gets a new paint layer. */-const paintsInPlace = (layer: CanvasLayerContract): boolean =>- layer.type === 'raster'- ? layer.source.type === 'paint' || layer.source.type === 'image'- : layer.type === 'control' || isMaskLayer(layer);-/**- * Why a press of `tool` on the selected leaf would be refused before it starts, without side effects: drives the+ * Whether a press of `tool` on the selected leaf would be refused before it starts, without side effects: drives the* not-allowed cursor. Loading pixels are not predicted; the press itself reports them.*/-const predictRefusal = (- leaf: SemanticLeaf | null,- tool: PaintToolSpec['id']-): CanvasLayerEditRefusal['status'] | null => {+const predictsRefusal = (leaf: SemanticLeaf | null, tool: PaintToolSpec['id']): boolean => {const selected = leaf?.layer;- if (!leaf || !selected || !paintsInPlace(selected)) {- return null;+ if (!leaf || !selected || !editsPixelsInPlace(selected)) {+ // A control layer with no pixels refuses both tools; elsewhere the brush paints a new layer instead.+ return tool === 'eraser' || selected?.type === 'control';}- const refusal = leafEditRefusal(leaf);- if (refusal) {- return refusal;- }- return tool === 'eraser' && isLayerTransparencyLocked(selected) ? 'layer-alpha-locked' : null;+ return leafPaintRefusal(leaf) !== null || (tool === 'eraser' && isLayerTransparencyLocked(selected));};/** Resolves (or auto-creates) the paint target for a gesture, or `null` to no-op. */@@ -150,7 +140,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetif (leaf && selected && selected.type === 'raster' && selected.source.type === 'paint') {// Locked/hidden paint targets refuse rather than silently creating another layer.- const refusal = leafEditRefusal(leaf);+ const refusal = leafPaintRefusal(leaf);if (refusal) {return refuse(ctx, selected, refusal);}@@ -172,7 +162,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget// transparency lock. A locked or hidden image refuses (the brush offers a new paint layer instead of making one// unasked), as does one whose pixels have not loaded; the eraser also refuses a transparency lock. A rasterized// image whose spatial adjustments have not landed refuses `not-ready` (or names the stack that cannot run).- const refusal = leafEditRefusal(leaf);+ const refusal = leafPaintRefusal(leaf);if (refusal) {return refuse(ctx, selected, refusal, tool === 'brush' ? { canPaintNewLayer: true } : {});}@@ -195,7 +185,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetif (leaf && selected && isMaskLayer(selected)) {// Paint mask alpha directly, adding/removing coverage. Locked/hidden masks refuse and never auto-create// paint layers.- const refusal = leafEditRefusal(leaf);+ const refusal = leafPaintRefusal(leaf);if (refusal) {return refuse(ctx, selected, refusal);}@@ -208,8 +198,8 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget: null;}- if (leaf && selected?.type === 'control') {- const refusal = leafEditRefusal(leaf);+ if (leaf && selected?.type === 'control' && editsPixelsInPlace(selected)) {+ const refusal = leafPaintRefusal(leaf);if (refusal) {return refuse(ctx, selected, refusal);}@@ -222,6 +212,19 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTargetreturn transaction ? editTarget(transaction, transaction.layerId) : null;}+ if (selected?.type === 'control') {+ // Its empty shape has no pixels to edit, and a control layer never takes a new raster layer in its place.+ return refuse(ctx, selected, 'layer-unpaintable');+ }+ if (tool === 'eraser') {+ // A new layer would have nothing to erase; a group, text, shape or gradient is not erased in place.+ const node = getDocumentNode(doc, doc.selectedLayerId);+ ctx.reportEditRefusal?.(+ node ? { layerId: node.id, layerName: node.name, status: 'erase-unsupported' } : { status: 'erase-no-target' }+ );+ return null;+ }+// Admit the stroke before the layer exists, so a refusal leaves the document untouched.const edit = ctx.beginStrokeEdit();if (!edit) {@@ -300,13 +303,13 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {cursor: (ctx) => {const doc = ctx.getDocument();const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;- return !session && predictRefusal(leaf, spec.id) ? 'not-allowed' : 'crosshair';+ return !session && predictsRefusal(leaf, spec.id) ? 'not-allowed' : 'crosshair';},// A press paints the selected leaf in place unless it is refused up front; any other selection gets a new layer.editsSelectedLayer: (ctx) => {const doc = ctx.getDocument();const leaf = doc?.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;- return !!leaf && paintsInPlace(leaf.layer) && predictRefusal(leaf, spec.id) === null;+ return !!leaf && editsPixelsInPlace(leaf.layer) && !predictsRefusal(leaf, spec.id);},id: spec.id,onDeactivate: (ctx, opts) => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.tsindex e36bd5fa6d..e1ae5286ce 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts@@ -23,6 +23,7 @@ const visualSnapshot = (overrides: Partial<SamSessionSnapshot> = {}): SamSessionlayerType: 'raster',model: 'segment-anything-2-large',pointLabel: 'include',+ retrying: false,sourceRect,status: 'ready',...overrides,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.tsindex f53ea42861..e8215f211c 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts@@ -781,6 +781,7 @@ describe('shape tool: mask placement', () => {'a mask under a locked group',[groupContract('group-1', [layerContract('mask-1', 'regional_guidance')], { isLocked: true })],],+ ['a mask hidden on the canvas', [layerContract('mask-1', 'inpaint_mask', { isHidden: true })]],])('refuses %s without spawning a layer', (label, nodes) => {const h = createHarness(makeDoc({ stacks: stacksFrom(nodes), selectedLayerId: 'mask-1' }));const tool = createShapeTool();@@ -790,7 +791,11 @@ describe('shape tool: mask placement', () => {expect(h.refusals).toEqual([expect.objectContaining({layerId: 'mask-1',- status: label.includes('disabled') ? 'layer-hidden' : 'layer-locked',+ status: label.includes('disabled')+ ? 'layer-hidden'+ : label.includes('hidden')+ ? 'layer-display-hidden'+ : 'layer-locked',}),]);expect(h.strokeEdit.record.commits).toHaveLength(0);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.tsindex 60746c3929..cd9b97ab7a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts@@ -16,7 +16,7 @@* and cancellation do not dispatch, and a nonzero shape produces one structural or stroke commit.*/-import type { CanvasLayerEditRefusal, CanvasShapeCutoutRefusal } from '@workbench/canvas-engine/capabilities';+import type { CanvasLayerEditRefusal, CanvasNoTargetRefusal } from '@workbench/canvas-engine/capabilities';import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';import type { ShapeToolOptions } from '@workbench/canvas-engine/engineStores';@@ -25,8 +25,9 @@ import type { PlacedSurface, PointerInput, PointerModifiers, Rect, Vec2 } from 'import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';-import { isLayerTransparencyLocked, leafEditRefusal } from '@workbench/canvas-engine/document/layerEligibility';+import { isLayerTransparencyLocked } from '@workbench/canvas-engine/document/layerEligibility';import { isMaskLayer } from '@workbench/canvas-engine/document/sources';+import { leafPaintRefusal } from '@workbench/canvas-engine/editing/controlPixelEdit';import { polygonBounds } from '@workbench/canvas-engine/freehand';import { identity, invert, multiply, translate } from '@workbench/canvas-engine/math/mat2d';import { intersect, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';@@ -134,7 +135,7 @@ export const polygonShapeFrom = (type ShapeTarget =| { kind: 'layer' }| { kind: 'pixels'; leaf: SemanticLeaf }- | { kind: 'refused'; refusal: CanvasLayerEditRefusal | CanvasShapeCutoutRefusal };+ | { kind: 'refused'; refusal: CanvasLayerEditRefusal | CanvasNoTargetRefusal };/** With fill off and no stroke to draw, a shape changes no pixel, so it records no step and uploads nothing. */const drawsNothing = (source: ShapeSource): boolean =>@@ -170,7 +171,7 @@ const resolveTarget = (ctx: ToolContext, mode: ShapeMode, loading: 'request' | 'return { kind: 'layer' };}const { layer } = leaf;- let status: CanvasLayerEditRefusal['status'] | null = leafEditRefusal(leaf);+ let status: CanvasLayerEditRefusal['status'] | null = leafPaintRefusal(leaf);if (!status && mode === 'cutout' && isLayerTransparencyLocked(layer)) {status = 'layer-alpha-locked';}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 23ecd9b765..04dfc3bdae 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -253,8 +253,8 @@ export interface Tool {* Whether a primary gesture starting now edits the selected layer in place, writing its pixels or its placement:* false when the press would be refused up front or would add a new layer instead. Asked once as each gesture* starts, before the press reaches the tool; absent means not known then (a tool that decides from the press's- * modifiers or later calls {@link ToolContext.beginSelectedLayerEdit}). While such a gesture targets a mask or a region, the screen shows- * their stacks above a staged preview that otherwise hides them.+ * modifiers or later calls {@link ToolContext.beginSelectedLayerEdit}). While such a gesture targets a control+ * layer, a mask or a region, the screen shows their stacks above a staged preview that otherwise hides them.*/editsSelectedLayer?(ctx: ToolContext): boolean;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.tsindex c49b08f199..88d2430d92 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts@@ -82,19 +82,14 @@ interface TransformSubject {const identityPoint = (point: Vec2): Vec2 => point;/**- * Whether a transform session may open on `layer`: an editable, non-empty leaf that is not a mask. `liveRect` also- * counts pixels the live cache holds but persistence has not acknowledged yet.+ * Whether a transform session may open on `layer`: an editable, non-empty leaf. `liveRect` also counts pixels the+ * live cache holds but persistence has not acknowledged yet.*/export const isTransformEligible = (layer: CanvasLayerContract,doc: CanvasDocumentContractV3,liveRect?: Rect-): boolean =>- // Masks lack an applyTransform bake path, so reject sessions that would preview but fail to apply.- isLeafEditable(lookupDocumentLeaf(doc, layer.id)) &&- layer.type !== 'inpaint_mask' &&- layer.type !== 'regional_guidance' &&- hittableLayerRect(layer, doc, liveRect) !== null;+): boolean => isLeafEditable(lookupDocumentLeaf(doc, layer.id)) && hittableLayerRect(layer, doc, liveRect) !== null;/** Creates a fresh transform tool with its own session/gesture state. */export const createTransformTool = (): Tool => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.test.tsindex 8c2fa0550c..55ddbcafe7 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.test.ts@@ -22,7 +22,7 @@ const layer: CanvasRasterLayerContractV2 = {};const guard: LayerExportGuard = { cacheVersion: 1, documentGeneration: 1, layer, layerId: layer.id, projectId: 'p1' };-const createCoordinator = (readAutoProcessPreference: () => boolean) => {+const createCoordinator = (readAutoUpdatePreference: () => boolean) => {const stores = createCanvasOperationStores();const deps: CanvasSelectObjectCoordinatorDeps = {captureGuard: () => guard,@@ -46,7 +46,7 @@ const createCoordinator = (readAutoProcessPreference: () => boolean) => {}),projectId: 'p1',publishPreview: vi.fn(),- readAutoProcessPreference,+ readAutoUpdatePreference,replaceSelection: vi.fn(),replaceTemporaryRestoreTool: vi.fn(),runGraph: vi.fn(),@@ -74,4 +74,25 @@ describe('createSelectObjectOperationCoordinator', () => {expect(stores.samSession.get()?.autoProcess).toBe(false);coordinator.cancel();});++ it('starts on visual input, restores each input type across switches, and Reset empties both', () => {+ const { coordinator, stores } = createCoordinator(() => false);+ const emptyVisual = { bbox: null, excludePoints: [], includePoints: [], type: 'visual' };+ coordinator.start(layer.id);+ expect(stores.samSession.get()?.input).toEqual(emptyVisual);++ coordinator.update({ input: { bbox: null, excludePoints: [], includePoints: [{ x: 1, y: 2 }], type: 'visual' } });+ coordinator.update({ inputType: 'prompt' });+ coordinator.update({ input: { prompt: 'cat', type: 'prompt' } });+ coordinator.update({ inputType: 'visual' });+ expect(stores.samSession.get()?.input).toMatchObject({ includePoints: [{ x: 1, y: 2 }], type: 'visual' });+ coordinator.update({ inputType: 'prompt' });+ expect(stores.samSession.get()?.input).toEqual({ prompt: 'cat', type: 'prompt' });++ expect(coordinator.reset()).toBe('updated');+ expect(stores.samSession.get()?.input).toEqual(emptyVisual);+ coordinator.update({ inputType: 'prompt' });+ expect(stores.samSession.get()?.input).toEqual({ prompt: '', type: 'prompt' });+ coordinator.cancel();+ });});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.tsindex 87c5fc8fe2..af1c487a7e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/SelectObjectCoordinator.ts@@ -8,6 +8,8 @@ import type {SelectObjectSessionPreview,} from '@workbench/canvas-operations/contracts';+import { DEFAULT_SELECT_OBJECT_AUTO_UPDATE } from '@workbench/settings/contracts';+import { createSelectObjectSession } from './selectObjectSession';interface CommitOwner {@@ -42,6 +44,7 @@ export const createSelectObjectOperationCoordinator = (autoProcess: state.autoProcess,error: state.error,hasPreview: state.preview !== null,+ retrying: state.retrying,layerName: startContext.layerName,layerType: startContext.layerType,input:@@ -163,7 +166,7 @@ export const createSelectObjectOperationCoordinator = (result.status === 'locked'? { code: 'locked' }: {- code: 'unknown',+ code: 'commit-failed',detail: result.status === 'failed' ? result.message : `Select Object commit is ${result.status}.`,});@@ -179,7 +182,7 @@ export const createSelectObjectOperationCoordinator = (} catch (error) {const message = error instanceof Error ? error.message : String(error);if (finishCommit(owner)) {- owner.session.reportError({ code: 'unknown', detail: message });+ owner.session.reportError({ code: 'commit-failed', detail: message });}return { message, status: 'failed' };}@@ -221,7 +224,7 @@ export const createSelectObjectOperationCoordinator = (runGraph: deps.runGraph,uploadIntermediate: deps.uploadIntermediate,},- initialAutoProcess: deps.readAutoProcessPreference?.() ?? false,+ initialAutoProcess: deps.readAutoUpdatePreference?.() ?? DEFAULT_SELECT_OBJECT_AUTO_UPDATE,operation,});const installed = session;@@ -242,7 +245,6 @@ export const createSelectObjectOperationCoordinator = (}}});- installed.update({ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' } });syncStore();deps.setSamTool();return 'started';@@ -255,6 +257,7 @@ export const createSelectObjectOperationCoordinator = (const state = session.getSnapshot();const processingChanged =('input' in sessionChanges && sessionChanges.input !== state.input) ||+ (sessionChanges.inputType !== undefined && sessionChanges.inputType !== state.input.type) ||('model' in sessionChanges && sessionChanges.model !== state.model) ||('invert' in sessionChanges && sessionChanges.invert !== state.invert) ||('applyPolygonRefinement' in sessionChanges &&@@ -300,7 +303,7 @@ export const createSelectObjectOperationCoordinator = (} catch (error) {const message = error instanceof Error ? error.message : String(error);if (finishCommit(owner)) {- owner.session.reportError({ code: 'unknown', detail: message });+ owner.session.reportError({ code: 'commit-failed', detail: message });}return { message, status: 'failed' };}@@ -361,7 +364,7 @@ export const createSelectObjectOperationCoordinator = (} catch (error) {const message = error instanceof Error ? error.message : String(error);if (finishCommit(owner)) {- owner.session.reportError({ code: 'unknown', detail: message });+ owner.session.reportError({ code: 'commit-failed', detail: message });}return { message, status: 'failed' };}@@ -392,7 +395,6 @@ export const createSelectObjectOperationCoordinator = (publishedGuard = null;pointLabel = 'include';session.reset();- session.update({ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' } });syncStore();return 'updated';},diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.tsindex eb4a6c5bbe..7c5c88ed74 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/api.ts@@ -31,11 +31,9 @@ export {getControlIntentNotice,getControlSourceSnapshot,getControlUploadNotice,- resolveControlFileDrop,sendGalleryImageAsControl,subscribeControlSourceSnapshot,uploadControlImageFile,- type ControlFileDropResolution,type ControlSourceNotice,type ControlSourceOrigin,type ControlSourceSnapshot,@@ -99,3 +97,4 @@ export {} from './filterGraphs';export { readLastUsedFilterType, recordLastUsedFilterType } from './filterPreferences';export { buildSamGraph, documentToExportLocalSamInput, isSamDocumentInputValid, isSamInputValid } from './samGraph';+export { isSamRunError } from './selectObjectSession';diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.browser.test.tsindex c4d225018b..5583afdd06 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.browser.test.ts@@ -3,7 +3,7 @@ import type { CompositeEntry } from '@workbench/canvas-operations/generationContimport { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';import { describe, expect, it } from 'vitest';-import { createCompositeDedupeCache, executeControlComposite } from './compositeForGeneration';+import { createCompositeDedupeCache, executeControlComposite, executeMaskComposite } from './compositeForGeneration';describe('executeControlComposite — real browser pixels', () => {it('uploads erased transparent pixels as opaque black', async () => {@@ -69,3 +69,53 @@ describe('executeControlComposite — real browser pixels', () => {expect(uploadedPixels).toEqual([255, 255, 255, 255, 60, 40, 20, 255, 0, 0, 0, 255]);});});++describe('executeMaskComposite — real browser pixels', () => {+ it('places a rotated, scaled mask where the canvas shows it', async () => {+ const backend = createDomRasterBackend();+ // A 2×1 local mask: covered on the left pixel only.+ const maskSurface = backend.createSurface(2, 1);+ maskSurface.ctx.fillStyle = '#ffffff';+ maskSurface.ctx.fillRect(0, 0, 1, 1);+ const entry: CompositeEntry = {+ bbox: { height: 8, width: 8, x: 0, y: 0 },+ key: 'inpaint-mask|rotated',+ kind: 'inpaint-mask',+ layers: [],+ maskLayers: [+ {+ attributeValue: 1,+ contentOffset: { x: 0, y: 0 },+ contentSize: { height: 1, width: 2 },+ id: 'mask',+ sourceRef: 'mask:mask.png',+ // A quarter turn at scale 2 about (6, 0): local (x, y) lands at document (6 - 2y, 2x).+ transform: { rotation: Math.PI / 2, scaleX: 2, scaleY: 2, x: 6, y: 0 },+ },+ ],+ };+ let uploaded: ImageData | null = null;++ const result = await executeMaskComposite(entry, {+ backend,+ dedupe: createCompositeDedupeCache(),+ getLayerSurface: () =>+ Promise.resolve({ rect: { height: 1, width: 2, x: 0, y: 0 }, release: () => undefined, surface: maskSurface }),+ hashBlob: () => Promise.resolve('mask-pixels'),+ uploadImage: async (blob) => {+ const bitmap = await backend.createImageBitmap(blob);+ const decoded = backend.createSurface(8, 8);+ decoded.ctx.drawImage(bitmap, 0, 0);+ uploaded = decoded.ctx.getImageData(0, 0, 8, 8);+ bitmap.close();+ return { height: 8, imageName: 'mask.png', width: 8 };+ },+ });++ const gray = (x: number, y: number): number => uploaded!.data[(y * 8 + x) * 4]!;+ expect(result.hasContent).toBe(true);+ // Local pixel (0, 0) covers document 4..6 × 0..2; local (1, 0), unmasked, covers 4..6 × 2..4.+ expect([gray(4, 0), gray(5, 1)]).toEqual([0, 0]);+ expect([gray(4, 2), gray(5, 3), gray(1, 0), gray(6, 0)]).toEqual([255, 255, 255, 255]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.tsindex d73f790e20..95f988e6a4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/contracts.ts@@ -51,6 +51,8 @@ export type SaveSelectObjectSessionResult =| ReplaceSelectionFromImageResult;export interface SelectObjectSessionUpdate {input?: SamInput;+ /** Switch between visual and prompt input; each type keeps its last input until Reset. */+ inputType?: SamInput['type'];pointLabel?: 'include' | 'exclude';model?: SamModel;invert?: boolean;@@ -203,8 +205,8 @@ export interface CanvasSelectObjectCoordinatorDeps {readonly stores: CanvasApplicationOperationStores;readonly controller: CanvasOperationController;readonly projectId: string;- /** Reads the account's Auto Process preference when a session starts; absent means off. */- readAutoProcessPreference?(): boolean;+ /** Reads the account's auto-update preference when a session starts; absent starts from the account default. */+ readAutoUpdatePreference?(): boolean;prepareStart(layerId: string): SelectObjectStartContext;selectLayer(layerId: string): void;clearOtherOperation(): void;@@ -295,6 +297,8 @@ export interface SelectObjectSessionState<T> {isolatedPreview: boolean;status: SelectObjectSessionStatus;error: SamSessionError | null;+ /** A run asked for after a failed run is still in flight. */+ retrying: boolean;preview: SelectObjectSessionPreview<T> | null;sourceGuard: LayerExportGuard | null;}@@ -308,7 +312,7 @@ export interface SelectObjectSession<T> {SelectObjectSessionState<T>,'applyPolygonRefinement' | 'autoProcess' | 'input' | 'invert' | 'isolatedPreview' | 'model'>- >+ > & { inputType?: SamInput['type'] }): void;process(): Promise<SelectObjectSessionProcessResult>;reportError(error: SamSessionError | string): void;@@ -388,7 +392,7 @@ export interface CreateSelectObjectSessionOptions<T> {cleanupPreview(): void;isGuardCurrent(guard: LayerExportGuard): boolean;};- initialAutoProcess?: boolean;+ initialAutoProcess: boolean;operation: CanvasOperationSession;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.test.tsindex 6b8ee751dc..c7d4a63975 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.test.ts@@ -7,7 +7,6 @@ import { createControlLayer } from '@workbench/canvas-engine/api';import {documentFrom,groupContract,- layerContract,stacksFrom,} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';@@ -20,7 +19,6 @@ import type { ControlLayerIntent, ControlLayerIntentResult } from './operationTyimport {fillControlFromBbox,getControlSourceSnapshot,- resolveControlFileDrop,sendGalleryImageAsControl,uploadControlImageFile,} from './controlSourceActions';@@ -311,60 +309,3 @@ describe('uploadControlImageFile', () => {expect(intents).toHaveLength(1);});});--/** Decides the canvas's drop effect while files hover, and whether a drop is used. */-describe('resolveControlFileDrop', () => {- const emptyControl = createControlLayer({ id: 'control-1', name: 'Depth 1' });- const IMAGE_ITEM = { type: 'image/png' };- const resolve = (- nodes: Parameters<typeof documentFrom>[0],- selectedLayerId: string,- { files = [IMAGE_ITEM] as { type: string }[], hasPixels = false, isCanvasLocked = false } = {}- ) =>- resolveControlFileDrop({- document: documentFrom(nodes, selectedLayerId),- engine: { exports: { hasExportableLayerContent: () => hasPixels } },- files,- isCanvasLocked,- });- const refusedWith = (titleKey: string) => ({ notice: { kind: 'info', titleKey }, status: 'refused' });-- it('takes one image file onto an empty, unlocked control layer', () => {- expect(resolve([emptyControl], 'control-1')).toEqual({ layerId: 'control-1', status: 'accepted' });- });-- it.each([- [- 'several files',- [emptyControl],- {- files: [IMAGE_ITEM, IMAGE_ITEM],- },- 'widgets.canvas.fileDrop.oneFile',- ],- [- 'a file that is not an image',- [emptyControl],- { files: [{ type: 'text/plain' }] },- 'widgets.canvas.fileDrop.notImage',- ],- ['a locked canvas', [emptyControl], { isCanvasLocked: true }, 'widgets.layers.actions.busy'],- ['a layer with strokes', [emptyControl], { hasPixels: true }, 'widgets.canvas.fileDrop.noTarget'],- [- 'a layer locked by its group',- [groupContract('group-1', [emptyControl], { isLocked: true })],- {},- 'widgets.layers.actions.locked',- ],- ] as const)('refuses %s', (_label, nodes, options, titleKey) => {- expect(- resolve([...nodes], 'control-1', { ...options, files: 'files' in options ? [...options.files] : undefined })- ).toEqual(refusedWith(titleKey));- });-- it('refuses a selected layer that is not a control layer', () => {- expect(resolve([layerContract('raster-1', 'raster')], 'raster-1')).toEqual(- refusedWith('widgets.canvas.fileDrop.noTarget')- );- });-});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.tsindex 395424438f..036b475ba1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/controlSourceActions.ts@@ -2,7 +2,6 @@ import type { AccountScope } from '@platform/state/accountLifecycle';import type {AdjustmentRefusal,CanvasDocumentCapability,- CanvasDocumentContractV3,CanvasExportCapability,LayerUnreadable,} from '@workbench/canvas-engine/api';@@ -102,11 +101,10 @@ export type UploadControlImageResult =/*** Uploads an image file and makes it a control layer's image at the bbox origin (`replace-image`, which detects its- * map), recording the file's name as the image's origin. The Properties Upload button and a file dropped on the- * canvas share it. One upload per layer at a time; `onUploaded` runs once the file is stored, for the caller to- * refresh the gallery it now appears in. A layer that was empty when the upload started must still be, so strokes- * drawn meanwhile are never replaced; replacing an image the layer already had is what was asked for. The upload- * stays with the account that started it.+ * map), recording the file's name as the image's origin, for the Properties Upload button. One upload per layer at a+ * time; `onUploaded` runs once the file is stored, for the caller to refresh the gallery it now appears in. A layer+ * that was empty when the upload started must still be, so strokes drawn meanwhile are never replaced; replacing an+ * image the layer already had is what was asked for. The upload stays with the account that started it.*/export const uploadControlImageFile = async (options: {engine: {@@ -210,49 +208,6 @@ export const getControlUploadNotice = (outcome: UploadControlImageResult): Contr}};-export type ControlFileDropResolution =- | { status: 'accepted'; layerId: string }- | { status: 'refused'; notice: ControlSourceNotice };--/**- * Whether files dragged onto the canvas can fill the selected control layer: exactly one image file, the canvas- * accepting edits, and the selected layer a control layer that is not locked (by itself or a group) and still empty.- * `files` are the drag's file items while it hovers (their `type` is readable then, to set the drop effect), and its- * files once dropped.- */-export const resolveControlFileDrop = (input: {- document: CanvasDocumentContractV3;- engine: { readonly exports: Pick<CanvasExportCapability, 'hasExportableLayerContent'> };- files: readonly { readonly type: string }[];- isCanvasLocked: boolean;-}): ControlFileDropResolution => {- const { document, engine, files, isCanvasLocked } = input;- const refuse = (titleKey: string): ControlFileDropResolution => ({- notice: { kind: 'info', titleKey },- status: 'refused',- });- if (files.length !== 1) {- return refuse('widgets.canvas.fileDrop.oneFile');- }- if (!files[0]!.type.startsWith('image/')) {- return refuse('widgets.canvas.fileDrop.notImage');- }- if (isCanvasLocked) {- return refuse('widgets.layers.actions.busy');- }- const layer = getDocumentLayer(document, document.selectedLayerId);- if (- layer?.type !== 'control' ||- getControlImageState(layer, engine.exports.hasExportableLayerContent(layer.id)) !== 'empty'- ) {- return refuse('widgets.canvas.fileDrop.noTarget');- }- if (lookupDocumentLeaf(document, layer.id)?.effectiveLocked !== false) {- return refuse('widgets.layers.actions.locked');- }- return { layerId: layer.id, status: 'accepted' };-};-export type FillControlFromBboxResult =| { status: 'applied'; result: ControlLayerIntentResult; imageName: string }| { status: 'empty' | 'stale' | 'not-ready' | 'over-budget' }diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.tsindex 7603bcccf7..6db12b8a11 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createCanvasEngine.ts@@ -35,8 +35,8 @@ export interface CanvasEngineOptions extends Omit<*/ensureProjectOnServer(): Promise<void>;getMainModelBase?: () => string | null;- /** The account's Select Object Auto Process preference; the widget layer injects the settings read. */- readSelectObjectAutoProcess?: () => boolean;+ /** The account's Select Object auto-update preference; the widget layer injects the settings read. */+ readSelectObjectAutoUpdate?: () => boolean;/** Where the account keeps brush, eraser, shape and text options; the engine starts from them and saves changes. */toolMemory?: CanvasToolMemoryPort;selectObjectDeps?: {@@ -83,7 +83,7 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =controlDetectionDeps,ensureProjectOnServer,filterDeps,- readSelectObjectAutoProcess,+ readSelectObjectAutoUpdate,selectObjectDeps,toolMemory,...coreOptions@@ -195,7 +195,7 @@ export const createCanvasEngine = (options: CanvasEngineOptions): CanvasEngine =isSamToolActive: host.isSamToolActive,prepareStart: host.prepareSelectObjectStart,projectId: options.projectId,- readAutoProcessPreference: readSelectObjectAutoProcess,+ readAutoUpdatePreference: readSelectObjectAutoUpdate,publishPreview: (preview) => host.publishSamPreview(preview),replaceSelection: (preview, signal) => host.replaceSelection(preview.guard, preview.image, preview.rect, signal),replaceTemporaryRestoreTool: host.replaceTemporaryRestoreTool,diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.test.tsindex 6a6919785b..39ccc3d46d 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/filterOperationSession.test.ts@@ -254,6 +254,25 @@ describe('createFilterOperationSession', () => {});});+ it('runs the same settings again on a retry after a failed run', async () => {+ const runFilter = vi+ .fn()+ .mockRejectedValueOnce(new Error('graph exploded'))+ .mockResolvedValueOnce({ height: 10, imageName: 'filtered', origin: { x: 3, y: 4 }, width: 10 });+ const deps = createDeps({ runFilter });+ const session = createFilterOperationSession({ deps, guard, initialFilter: layer.filter!, layerType: 'raster' })!;+ expect(await session.process()).toBe('error');++ expect(await session.process()).toBe('published');++ expect(runFilter).toHaveBeenCalledTimes(2);+ expect(runFilter.mock.calls[1]![0]).toMatchObject({+ filterType: runFilter.mock.calls[0]![0].filterType,+ settings: runFilter.mock.calls[0]![0].settings,+ });+ expect(session.getSnapshot()).toMatchObject({ error: null, preview: { imageName: 'filtered' }, status: 'ready' });+ });+it.each([['disabled', 'disabled'],['empty', 'empty'],diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/operationTypes.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/operationTypes.tsindex fe922a83a6..06eafa120a 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/operationTypes.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/operationTypes.ts@@ -27,6 +27,8 @@ export type SamSessionErrorCode =| 'output-dimension'| 'decode'| 'locked'+ /** Applying or saving the preview failed; its message is kept as `detail`. */+ | 'commit-failed'/** The layer's image could not be read (it is gone or does not decode). */| 'unreadable'| 'unknown';@@ -61,6 +63,8 @@ export interface SamSessionSnapshot {| 'committing'| 'error';error: SamSessionError | null;+ /** A run asked for after a failed run is still in flight, so the retry control stays for it. */+ retrying: boolean;hasPreview: boolean;}export type LayerFilterSettings = RasterFilterSettings;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.tsindex ff11f0763b..7953afbfd3 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.test.ts@@ -87,7 +87,7 @@ const createHarness = (if (!operation) {throw new Error('expected Select Object operation');}- const session = createSelectObjectSession({ deps, initialAutoProcess, operation });+ const session = createSelectObjectSession({ deps, initialAutoProcess: initialAutoProcess ?? false, operation });session.update({ input: { prompt: 'cat', type: 'prompt' } });return {controller,@@ -120,6 +120,7 @@ describe('createSelectObjectSession', () => {isolatedPreview: true,model: 'segment-anything-2-large',preview: null,+ retrying: false,sourceGuard: null,status: 'ready',});@@ -602,6 +603,60 @@ describe('createSelectObjectSession', () => {await vi.waitFor(() => expect(harness.deps.runGraph).toHaveBeenCalledOnce());});+ it('runs the same input again on a manual retry after a failed auto-run', async () => {+ vi.useFakeTimers();+ const harness = createHarness({}, { initialAutoProcess: true });+ harness.setCurrentGuard(null);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(harness.session.getSnapshot()).toMatchObject({ error: { code: 'not-ready' }, status: 'error' });++ harness.setCurrentGuard(guard);+ const retry = harness.session.process();+ expect(harness.session.getSnapshot()).toMatchObject({ error: null, retrying: true, status: 'preparing-source' });+ await expect(retry).resolves.toBe('published');+ expect(harness.deps.runGraph).toHaveBeenCalledOnce();+ expect(harness.session.getSnapshot()).toMatchObject({ retrying: false, status: 'ready' });++ vi.mocked(harness.deps.runGraph).mockRejectedValueOnce(new Error('graph failed'));+ harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });+ await vi.advanceTimersByTimeAsync(1_000);+ expect(harness.session.getSnapshot()).toMatchObject({ error: { code: 'queue' }, status: 'error' });+ await expect(harness.session.process()).resolves.toBe('published');+ expect(harness.deps.runGraph).toHaveBeenCalledTimes(3);+ expect(harness.session.getSnapshot()).toMatchObject({ error: null, retrying: false, status: 'ready' });+ });++ it('does not count a run after a failed apply as a retry', async () => {+ const harness = createHarness();+ await harness.session.process();+ harness.session.reportError({ code: 'commit-failed', detail: 'commit failed' });+ harness.setCurrentGuard(replacementGuard);+ vi.mocked(harness.deps.exportSource).mockResolvedValue({ blob, guard: replacementGuard, rect, status: 'ok' });++ const rerun = harness.session.process();++ expect(harness.session.getSnapshot()).toMatchObject({ error: null, retrying: false });+ await expect(rerun).resolves.toBe('published');+ });++ it('stops retrying once an input change supersedes the retry', async () => {+ const graph = deferred<{ height: number; imageName: string; origin: string; width: number }>();+ const harness = createHarness({+ runGraph: vi.fn().mockRejectedValueOnce(new Error('graph failed')).mockReturnValueOnce(graph.promise),+ });+ await expect(harness.session.process()).resolves.toBe('error');+ const retry = harness.session.process();+ await vi.waitFor(() => expect(harness.session.getSnapshot().status).toBe('processing-sam'));+ expect(harness.session.getSnapshot().retrying).toBe(true);++ harness.session.update({ input: { prompt: 'dog', type: 'prompt' } });++ expect(harness.session.getSnapshot().retrying).toBe(false);+ graph.resolve({ height: 12, imageName: 'result.png', origin: 'test', width: 16 });+ await expect(retry).resolves.toBe('stale');+ expect(harness.session.getSnapshot().retrying).toBe(false);+ });+it('debounces auto-processing for one second and manual processing runs immediately', async () => {vi.useFakeTimers();const harness = createHarness();@@ -844,11 +899,12 @@ describe('createSelectObjectSession', () => {applyPolygonRefinement: false,autoProcess: true,error: null,- input: { prompt: '', type: 'prompt' },+ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },invert: false,isolatedPreview: true,model: 'segment-anything-2-large',preview: null,+ retrying: false,sourceGuard: null,status: 'ready',});@@ -856,6 +912,61 @@ describe('createSelectObjectSession', () => {expect(harness.deps.runGraph).toHaveBeenCalledOnce();});+ it('keeps each input type while switching between them and Reset forgets both', () => {+ const harness = createHarness();+ const points = {+ bbox: { height: 4, width: 4, x: 1, y: 1 },+ excludePoints: [{ x: 2, y: 2 }],+ includePoints: [{ x: 3, y: 3 }],+ type: 'visual' as const,+ };++ harness.session.update({ inputType: 'visual' });+ expect(harness.session.getSnapshot().input).toEqual({+ bbox: null,+ excludePoints: [],+ includePoints: [],+ type: 'visual',+ });+ harness.session.update({ input: points });+ harness.session.update({ inputType: 'prompt' });+ expect(harness.session.getSnapshot().input).toEqual({ prompt: 'cat', type: 'prompt' });+ harness.session.update({ inputType: 'visual' });+ expect(harness.session.getSnapshot().input).toEqual(points);++ harness.session.reset();+ harness.session.update({ inputType: 'prompt' });+ expect(harness.session.getSnapshot().input).toEqual({ prompt: '', type: 'prompt' });+ });++ it('keeps the prompt when a visual input replaces it directly', () => {+ const harness = createHarness();+ const points = { bbox: null, excludePoints: [], includePoints: [{ x: 3, y: 3 }], type: 'visual' as const };++ harness.session.update({ input: points });+ harness.session.update({ inputType: 'prompt' });++ expect(harness.session.getSnapshot().input).toEqual({ prompt: 'cat', type: 'prompt' });+ harness.session.update({ inputType: 'visual' });+ expect(harness.session.getSnapshot().input).toEqual(points);+ });++ it('treats an input-type switch as an input change: clears the preview and schedules the restored input', async () => {+ vi.useFakeTimers();+ const harness = createHarness();+ await harness.session.process();+ expect(harness.session.getSnapshot().preview).not.toBeNull();+ harness.session.update({ inputType: 'visual' });+ harness.session.update({ autoProcess: true });+ expect(harness.session.getSnapshot()).toMatchObject({ preview: null, status: 'ready' });++ harness.session.update({ inputType: 'prompt' });++ expect(harness.session.getSnapshot()).toMatchObject({ input: { prompt: 'cat' }, status: 'scheduled' });+ await vi.runAllTimersAsync();+ expect(harness.session.getSnapshot().preview).not.toBeNull();+ });+it('dispose clears scheduling and preview, unsubscribes exactly once, and makes methods inert', async () => {vi.useFakeTimers();const harness = createHarness();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.tsindex e0531d676c..216b0d2abe 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/selectObjectSession.ts@@ -44,10 +44,37 @@ export interface SelectObjectSessionState<T> {isolatedPreview: boolean;status: SelectObjectSessionStatus;error: SamSessionError | null;+ /** A `process()` asked for while a run's error showed is still in flight (see `SamSessionSnapshot.retrying`). */+ retrying: boolean;preview: SelectObjectSessionPreview<T> | null;sourceGuard: LayerExportGuard | null;}+const SAM_ERROR_FROM_RUN: Record<SamSessionErrorCode, boolean> = {+ 'adjustment-error': true,+ 'adjustment-over-budget': true,+ 'adjustment-too-large': true,+ 'commit-failed': false,+ decode: true,+ empty: true,+ invalid: true,+ locked: false,+ 'no-output': true,+ 'not-ready': true,+ 'output-dimension': true,+ queue: true,+ reconcile: true,+ unknown: true,+ unreadable: true,+ upload: true,+};++/**+ * Whether a run (source preparation, upload, SAM, preview decode) reported the error, so running again is its retry;+ * applying or saving the preview reports `commit-failed` or `locked`, which Apply and Save as retry instead.+ */+export const isSamRunError = (code: SamSessionErrorCode): boolean => SAM_ERROR_FROM_RUN[code];+export interface SelectObjectSessionDeps<T> {captureGuard(): LayerExportGuard | null;controller: CanvasOperationController;@@ -62,24 +89,30 @@ export interface SelectObjectSessionDeps<T> {export interface CreateSelectObjectSessionOptions<T> {deps: SelectObjectSessionDeps<T>;- /** Auto Process is an account preference; the session starts from it and Reset keeps it. */- initialAutoProcess?: boolean;+ /** Auto-update is an account preference; the session starts from it and Reset keeps it. */+ initialAutoProcess: boolean;operation: CanvasOperationSession;}export type SelectObjectSessionProcessResult = CanvasOperationRunResult | 'deduped' | 'invalid';+export type SelectObjectSessionChanges<T> = Partial<+ Pick<+ SelectObjectSessionState<T>,+ 'applyPolygonRefinement' | 'autoProcess' | 'input' | 'invert' | 'isolatedPreview' | 'model'+ >+> & {+ /**+ * Switches between visual and prompt input: the current input is kept aside and the requested type's last input+ * (or an empty one) comes back. An explicit `input` in the same update wins; one of the other type is a switch too.+ */+ inputType?: SamInput['type'];+};+export interface SelectObjectSession<T> {getSnapshot(): SelectObjectSessionState<T>;subscribe(listener: () => void): () => void;- update(- changes: Partial<- Pick<- SelectObjectSessionState<T>,- 'applyPolygonRefinement' | 'autoProcess' | 'input' | 'invert' | 'isolatedPreview' | 'model'- >- >- ): void;+ update(changes: SelectObjectSessionChanges<T>): void;process(): Promise<SelectObjectSessionProcessResult>;reportError(error: SamSessionError | string): void;reset(): void;@@ -87,15 +120,23 @@ export interface SelectObjectSession<T> {dispose(): void;}+type StashedSamInputs = { [K in SamInput['type']]?: Extract<SamInput, { type: K }> };++const EMPTY_INPUTS: Required<StashedSamInputs> = {+ prompt: { prompt: '', type: 'prompt' },+ visual: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },+};+const defaultState = <T>(autoProcess: boolean): SelectObjectSessionState<T> => ({applyPolygonRefinement: false,autoProcess,error: null,- input: { prompt: '', type: 'prompt' },+ input: EMPTY_INPUTS.visual,invert: false,isolatedPreview: true,model: 'segment-anything-2-large',preview: null,+ retrying: false,sourceGuard: null,status: 'ready',});@@ -168,23 +209,28 @@ class SamSessionFailure extends Error {export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOptions<T>): SelectObjectSession<T> => {const { deps, operation } = options;- let state = defaultState<T>(options.initialAutoProcess ?? false);+ let state = defaultState<T>(options.initialAutoProcess);+ // The input of the type not in use, so switching back restores it; not part of the snapshot.+ let stashedInputs: StashedSamInputs = {};let source: SelectObjectPreparedSource | null = null;let requestToken = 0;let lastPublishedHash: string | null = null;let pendingHash: string | null = null;let pendingPhase: SelectObjectSessionStatus | null = null;let pendingProcess: Promise<SelectObjectSessionProcessResult> | null = null;+ /** The request a retry started; it stays `retrying` until that request settles or is superseded. */+ let retryToken: number | null = null;let timer: ReturnType<typeof setTimeout> | null = null;let disposed = false;let unsubscribeController: (() => void) | null = null;const listeners = new Set<() => void>();const publishState = (next: SelectObjectSessionState<T>): void => {+ const retrying = retryToken === requestToken && pendingHash !== null;if (next.status === 'error') {- state = next.error === null ? { ...next, status: 'ready' } : next;+ state = next.error === null ? { ...next, retrying, status: 'ready' } : { ...next, retrying };} else {- state = next.error === null ? next : { ...next, error: null };+ state = { ...next, error: null, retrying };}for (const listener of listeners) {try {@@ -418,6 +464,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOlastPublishedHash = null;publishState({ ...state, preview: null, sourceGuard: null, status: 'ready' });}+ const retry = state.error !== null && isSamRunError(state.error.code);const hash = stableInputHash(state);if (hash === pendingHash && pendingProcess) {publishState({ ...state, error: null, status: pendingPhase ?? 'preparing-source' });@@ -442,12 +489,16 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOreturn Promise.resolve('error');}pendingHash = hash;+ retryToken = retry ? token : null;const requestState = state;const promise = runRequest(token, hash, requestState, guard).finally(() => {if (token === requestToken) {pendingHash = null;pendingPhase = null;pendingProcess = null;+ if (state.retrying) {+ publishState(state);+ }}});pendingProcess = promise;@@ -523,6 +574,7 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOoperation.reset();source = null;lastPublishedHash = null;+ stashedInputs = {};publishState(defaultState<T>(state.autoProcess));},subscribe: (listener) => {@@ -532,10 +584,19 @@ export const createSelectObjectSession = <T>(options: CreateSelectObjectSessionOlisteners.add(listener);return () => listeners.delete(listener);},- update: (changes) => {+ update: ({ inputType, ...requested }) => {if (disposed) {return;}+ const changes: Omit<SelectObjectSessionChanges<T>, 'inputType'> = inputType &&+ inputType !== state.input.type &&+ !('input' in requested)+ ? { ...requested, input: stashedInputs[inputType] ?? EMPTY_INPUTS[inputType] }+ : requested;+ // Any switch of input type keeps the outgoing input, an explicit cross-type input included.+ if (changes.input && changes.input.type !== state.input.type) {+ stashedInputs = { ...stashedInputs, [state.input.type]: state.input };+ }const processingChanged =('input' in changes && changes.input !== state.input) ||('model' in changes && changes.model !== state.model) ||diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.tsindex 3175398b87..e6b68daa85 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/useCanvasEngine.ts@@ -110,7 +110,7 @@ export const useCanvasEngine = (): CanvasEngineHandle | null => {imageResolver: createImageResolver(),fonts,mutationPort: createCanvasProjectMutationPort(store, projectId),- readSelectObjectAutoProcess: () => getWorkbenchPreferences().selectObjectAutoProcess,+ readSelectObjectAutoUpdate: () => getWorkbenchPreferences().selectObjectAutoUpdate,toolMemory: {read: () => getWorkbenchPreferences().canvasToolMemory,subscribe: (listener) => subscribeWorkbenchPreferences(() => listener()),diff --git a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.tsindex 58f4bd00ae..f8e8575787 100644--- a/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasDimsSync.test.ts@@ -105,7 +105,7 @@ describe('reconcileCanvasDims (pure)', () => {prev: snapshot(1024, 1024, 1024, 1024),});- // Update the numeric ratio too; getActiveRatio prefers it over the aspect id.+ // Update the numeric ratio too; getActiveAspectRatio prefers it over the aspect id.expect(result).toMatchObject({ aspectRatioId: 'Free', aspectRatioValue: 1024 / 768, kind: 'patch-dims' });});@@ -431,7 +431,7 @@ describe('createCanvasDimsSync (wiring)', () => {const width = values.width as number;const height = values.height as number;- // Mirror GenerateDimensionFields' getActiveRatio: prefer aspectRatioValue+ // Mirror getActiveAspectRatio: prefer aspectRatioValue// when positive, else fall back to the live width/height.const activeRatio = aspectRatioValue > 0 ? aspectRatioValue : width / height;const nextWidth = 800;diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.tsindex 4fe5a7b8ac..189b5ce96b 100644--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts@@ -1,3 +1,4 @@+import type { AutoSwitchMode } from '@features/queue/contracts';import type {CanvasDocumentContractV3,CanvasGroupContract,@@ -496,11 +497,21 @@ export const placementToTransform = (y: placement.y,});-const AUTO_SWITCH_MODES: CanvasStagingAreaContractV2['autoSwitchMode'][] = ['off', 'latest', 'progress'];+type StagingAutoSwitchMode = CanvasStagingAreaContractV2['autoSwitchMode'];+type IsSameUnion<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;-const asAutoSwitchMode = (value: unknown): CanvasStagingAreaContractV2['autoSwitchMode'] =>- AUTO_SWITCH_MODES.includes(value as CanvasStagingAreaContractV2['autoSwitchMode'])- ? (value as CanvasStagingAreaContractV2['autoSwitchMode'])+/**+ * Every mode the persisted staging area stores, keyed by its own union. Its values are `true` only while that union is+ * the shared policy's (`AutoSwitchMode`): a mode added to either alone fails to compile here, so neither drifts from+ * the other and a stored value is never reset to `off` for being unknown.+ */+const STAGING_AUTO_SWITCH_MODES: Readonly<+ Record<StagingAutoSwitchMode, IsSameUnion<StagingAutoSwitchMode, AutoSwitchMode>>+> = { latest: true, off: true, progress: true };++const asAutoSwitchMode = (value: unknown): StagingAutoSwitchMode =>+ typeof value === 'string' && Object.hasOwn(STAGING_AUTO_SWITCH_MODES, value)+ ? (value as StagingAutoSwitchMode): 'off';/** Fills the known optional defaults of a staging area. */diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.tsindex 23feef262a..56cf6c492b 100644--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts@@ -1,5 +1,7 @@+import type { CanvasStagingSlot } from '@workbench/canvasStagingView';import type { Project } from '@workbench/projectContracts';+import { pickAutoSwitch } from '@features/queue/contracts';import {type CanvasDocumentContractV3,type CanvasLayerBasePatch,@@ -61,6 +63,31 @@ import {export type { CanvasLayerBasePatch, CanvasLayerConfigPatch, CanvasProjectMutation } from '@workbench/canvas-engine/api';+/** Auto-switch after the user picks this slot: the one pick rule, shared with Preview. */+export const pickStagedSlotAutoSwitch = (slot: CanvasStagingSlot) =>+ pickAutoSwitch(slot.kind === 'placeholder' ? { id: slot.id, kind: 'live' } : { kind: 'result' });++/**+ * The user picked a staged slot, by a click or right-click, an arrow key from the selected thumbnail or a step (never+ * by Tab focus): it is selected, and Auto-switch follows the pick as Preview's does (`pickStagedSlotAutoSwitch`). A+ * finished result pauses it (Off); a slot still generating turns it to In progress, and the workbench pins that slot+ * (`canvasStagingFollow`). Picking the slot already selected still counts.+ */+const pickStagedSlot = (project: Project, imageIndex: number): Project => {+ const slots = getCanvasStagingSlots(project.canvas, project.queue.items);+ const selectedImageIndex = clampStagedImageIndex(imageIndex, slots.length);+ const slot = slots[selectedImageIndex];+ const { stagingArea } = project.canvas;+ const autoSwitchMode = slot ? pickStagedSlotAutoSwitch(slot).mode : stagingArea.autoSwitchMode;++ return selectedImageIndex === stagingArea.selectedImageIndex && autoSwitchMode === stagingArea.autoSwitchMode+ ? project+ : {+ ...project,+ canvas: { ...project.canvas, stagingArea: { ...stagingArea, autoSwitchMode, selectedImageIndex } },+ };+};+/*** Restore points a canvas keeps of each kind (Clear canvas and Discard all each make one); older ones of that kind* are dropped, so a run of discards never pushes out a cleared canvas.@@ -831,34 +858,12 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasProevents: project.events.slice(1),};}- case 'setStagedImageIndex': {- const selectedImageIndex = clampStagedImageIndex(- mutation.imageIndex,- getCanvasStagingSlotCount(project.canvas, project.queue.items)- );- return selectedImageIndex === project.canvas.stagingArea.selectedImageIndex- ? project- : {- ...project,- canvas: {- ...project.canvas,- stagingArea: { ...project.canvas.stagingArea, selectedImageIndex },- },- };- }+ case 'setStagedImageIndex':+ return pickStagedSlot(project, mutation.imageIndex);case 'cycleStagedImage': {const count = getCanvasStagingSlotCount(project.canvas, project.queue.items);const current = project.canvas.stagingArea.selectedImageIndex;- const selectedImageIndex = count < 2 ? 0 : (current + mutation.direction + count) % count;- return selectedImageIndex === current- ? project- : {- ...project,- canvas: {- ...project.canvas,- stagingArea: { ...project.canvas.stagingArea, selectedImageIndex },- },- };+ return pickStagedSlot(project, count < 2 ? 0 : (current + mutation.direction + count) % count);}case 'discardSelectedStagedImage': {const selected = selectedCandidate(project);diff --git a/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts b/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.tsindex 9d85b9e898..cacab32804 100644--- a/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasStagingView.test.ts@@ -7,7 +7,6 @@ import { describe, expect, it } from 'vitest';import { createEmptyCanvasState } from './canvasMigration';import {- getCancelableCanvasStagingQueueItemId,getCanvasQueuePlaceholderSlots,getCanvasStagingCandidateFingerprint,getCanvasStagingSlotRect,@@ -226,34 +225,6 @@ describe('canvas staging view', () => {).toEqual(['candidate:q-first:1', 'placeholder:q-first:2', 'placeholder:q-second:1']);});- it('resolves a cancelable queue item only for placeholder slots', () => {- const candidate = createCandidate('ready.png', 'q-ready');-- expect(- getCancelableCanvasStagingQueueItemId({- candidate,- height: 768,- id: 'candidate:q-ready:ready.png',- imageName: 'ready.png',- kind: 'candidate',- queueItemId: 'q-ready',- width: 512,- })- ).toBeNull();- expect(- getCancelableCanvasStagingQueueItemId({- height: 320,- id: 'q-pending:0',- itemIndex: 1,- kind: 'placeholder',- queueItemId: 'q-pending',- width: 640,- x: 0,- y: 0,- })- ).toBe('q-pending');- });-it('places a candidate at its placement and a placeholder at its submitted rect, wherever the bbox is now', () => {const staged = createCandidate('ready.png', 'q-ready');// The live bbox moved after both runs were submitted.diff --git a/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts b/invokeai/frontend/webv2/src/workbench/canvasStagingView.tsindex db3504852e..ab5237d48a 100644--- a/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts+++ b/invokeai/frontend/webv2/src/workbench/canvasStagingView.ts@@ -280,11 +280,6 @@ export const hasPendingCanvasResults = ((item.status === 'pending' || item.status === 'running'));-export const getFirstCanvasPlaceholderSlotIndex = (- canvas: CanvasStateContractV3,- queueItems: readonly QueueItem[]-): number => getCanvasStagingSlots(canvas, queueItems).findIndex((slot) => slot.kind === 'placeholder');-/** Whether the queue can still cancel `item`: the backend supports it and its work is queued or running. */export const isCancellableQueueItem = (item: QueueItem): boolean =>item.cancellable && (item.status === 'pending' || item.status === 'running');@@ -295,6 +290,3 @@ export const isCancellableQueueItem = (item: QueueItem): boolean =>*/export const isUnsubmittedQueueItem = (item: QueueItem): boolean =>isCancellableQueueItem(item) && !item.backendItemIds?.length;--export const getCancelableCanvasStagingQueueItemId = (slot: CanvasStagingSlot | undefined): string | null =>- slot?.kind === 'placeholder' ? slot.queueItemId : null;diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.tsxindex 453f1c8362..998c80d270 100644--- a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx@@ -513,3 +513,32 @@ export const useFloatingWindowFocus = (return { activate, isHighlighted: isActive && showsHighlight };};++/**+ * The ref cleanup for a control that a later render can remove while it holds focus: if the node leaves the document+ * focused, focus goes to `getTarget()`, the nearest region by default, so the keys scoped there keep working, unless+ * something else has taken focus since. React also runs the cleanup when the ref callback changes on a node that stays+ * (a selection flipping on the click that focused it), so only a node really gone gives focus away; that is checked a+ * microtask on, once the commit running the cleanup has removed it.+ */+export const releaseFocusOnRemoval = (+ node: HTMLElement,+ getTarget: () => HTMLElement | null = () => node.closest<HTMLElement>('[role="region"]')+): (() => void) => {+ return () => {+ if (document.activeElement !== node) {+ return;+ }++ // Resolved while the node is still in place: a region found through it cannot be found once it is gone.+ const target = getTarget();++ queueMicrotask(() => {+ const { activeElement } = document;++ if (!node.isConnected && (activeElement === null || activeElement === document.body)) {+ target?.focus({ preventScroll: true });+ }+ });+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.browser.test.tsxindex 3af8a649c0..4eed42686c 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.browser.test.tsx@@ -627,3 +627,39 @@ describe('WorkbenchHotkeyRuntime and a focused segmented control', () => {expect(ran).toEqual(['gallery.galleryNavRight']);});});++describe('WorkbenchHotkeyRuntime and a held key', () => {+ const pressCancel = (repeat: boolean) =>+ act(async () => {+ document.body.dispatchEvent(+ new KeyboardEvent('keydown', {+ bubbles: true,+ cancelable: true,+ code: 'KeyX',+ key: 'X',+ repeat,+ shiftKey: true,+ })+ );+ await Promise.resolve();+ });++ it('runs a once-per-press command once while its key is held, and again on the next press', async () => {+ await act(() => {+ runtimeMocks.extensions.commands.register({+ handler: () => ran.push('app.cancelQueueItem'),+ id: 'app.cancelQueueItem',+ title: 'Cancel current or next queue item',+ });+ });++ await pressCancel(false);+ // The browser's auto-repeat while Shift+X stays down.+ await pressCancel(true);+ await pressCancel(true);+ expect(ran).toEqual(['app.cancelQueueItem']);++ await pressCancel(false);+ expect(ran).toEqual(['app.cancelQueueItem', 'app.cancelQueueItem']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsxindex c195014a0b..ac63d91236 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx@@ -88,6 +88,10 @@ export const WorkbenchHotkeyRuntime = () => {event.preventDefault();}+ if (event.repeat && hotkey.ignoreRepeat) {+ return;+ }+executeHotkey(hotkey, source);});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.tsindex a16ba2a31f..91bdb9c51e 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts@@ -14,6 +14,7 @@ const categoryScopes = {app: { kind: 'global' },canvas: { kind: 'widget', typeIds: ['canvas'] },gallery: { kind: 'widget', typeIds: ['gallery'] },+ queue: { kind: 'widget', typeIds: ['queue'] },viewer: { kind: 'widget', typeIds: ['preview'] },workflows: { kind: 'widget', typeIds: ['workflow'] },} as const satisfies Record<HotkeyCategory, HotkeyScope>;@@ -57,7 +58,11 @@ const hotkey = (category: HotkeyCategory,id: string,defaultKeys: string[],- { scope = categoryScopes[category], title = formatHotkeyTitle(id) }: { scope?: HotkeyScope; title?: string } = {}+ {+ ignoreRepeat,+ scope = categoryScopes[category],+ title = formatHotkeyTitle(id),+ }: { ignoreRepeat?: boolean; scope?: HotkeyScope; title?: string } = {}): HotkeyDefinition => {const commandId = `${category}.${id}`;@@ -67,6 +72,7 @@ const hotkey = (commandId,defaultKeys,id: commandId,+ ...(ignoreRepeat ? { ignoreRepeat } : {}),preventDefault: true,scope,title,@@ -93,6 +99,12 @@ export const OPEN_COMMAND_PALETTE_HOTKEY: HotkeyDefinition = {*/const PROMPT_ATTENTION_TARGET_SELECTOR = 'textarea[data-prompt-attention-target="true"]:not([readonly])';+/**+ * The Queue marks a row this way while it offers recall, so its A key works where the Gallery's does and keeps its+ * meaning everywhere else in the queue.+ */+const QUEUE_RECALL_ITEM_TARGET_SELECTOR = '[data-queue-recall-item], [data-queue-recall-item] *';+export type RegionFocusDirection = 'down' | 'left' | 'right' | 'up';/**@@ -141,8 +153,9 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [hotkey('app', 'selectEditPreset', ['alt+2']),hotkey('app', 'selectVideoPreset', ['alt+3']),hotkey('app', 'selectAutomatePreset', ['alt+4'], { title: 'Select Workflow Preset' }),- hotkey('app', 'cancelQueueItem', ['shift+x']),- hotkey('app', 'clearQueue', ['mod+shift+x'], { title: 'Cancel all queue items' }),+ // Each press stops one item; holding the key must not walk down the queue.+ hotkey('app', 'cancelQueueItem', ['shift+x'], { ignoreRepeat: true, title: 'Cancel current or next queue item' }),+ hotkey('app', 'clearQueue', ['mod+shift+x'], { ignoreRepeat: true, title: 'Cancel all queue items' }),// The ids keep "Tab" so saved bindings survive; each opens a widget, wherever the layout keeps it.hotkey('app', 'selectGenerateTab', ['1'], { title: 'Open Generate' }),hotkey('app', 'selectCanvasTab', ['2'], { title: 'Open Canvas' }),@@ -237,13 +250,15 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [hotkey('workflows', 'redo', ['mod+shift+z', 'mod+y']),hotkey('viewer', 'swapImages', ['c']),hotkey('viewer', 'nextComparisonMode', ['m']),+ // Bound only while Select for compare waits for a second image or a comparison is open, so Esc is otherwise free.+ hotkey('viewer', 'exitCompare', ['esc'], { title: 'Cancel or Exit Compare' }),hotkey('viewer', 'deleteImage', ['delete', 'backspace']),hotkey('viewer', 'loadWorkflow', ['w'], { scope: selectedImageScope }),- hotkey('viewer', 'recallAll', ['a'], { scope: selectedImageScope }),- hotkey('viewer', 'recallSeed', ['s'], { scope: selectedImageScope }),- hotkey('viewer', 'recallPrompts', ['p'], { scope: selectedImageScope }),- hotkey('viewer', 'remix', ['r']),- hotkey('viewer', 'useSize', ['d'], { scope: selectedImageScope }),+ hotkey('viewer', 'recallAll', ['a'], { ignoreRepeat: true, scope: selectedImageScope }),+ hotkey('viewer', 'recallSeed', ['s'], { ignoreRepeat: true, scope: selectedImageScope }),+ hotkey('viewer', 'recallPrompts', ['p'], { ignoreRepeat: true, scope: selectedImageScope }),+ hotkey('viewer', 'remix', ['r'], { ignoreRepeat: true }),+ hotkey('viewer', 'useSize', ['d'], { ignoreRepeat: true, scope: selectedImageScope }),hotkey('viewer', 'toggleMetadata', ['i'], { title: 'Toggle Details' }),// Preview registers these while it shows an item; the arrows step saved items outside comparison.hotkey('viewer', 'toggleFilmstrip', ['t']),@@ -276,7 +291,10 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [hotkey('gallery', 'moveFocusLeft', ['mod+left']),hotkey('gallery', 'toggleFocusedInSelection', []),hotkey('gallery', 'deleteSelection', ['delete', 'backspace']),- hotkey('gallery', 'remix', ['r']),+ hotkey('gallery', 'remix', ['r'], { ignoreRepeat: true }),hotkey('gallery', 'starImage', ['.']),+ // Preview's compare Esc, answered where its second image is picked.+ hotkey('gallery', 'exitCompare', ['esc'], { title: 'Cancel or Exit Compare' }),hotkey('gallery', 'toggleStarredOnly', []),+ { ...hotkey('queue', 'recallAll', ['a'], { ignoreRepeat: true }), targetSelector: QUEUE_RECALL_ITEM_TARGET_SELECTOR },];diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.tsindex ebc7e3708f..fdf9987022 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts@@ -374,7 +374,7 @@ export const useRegisterFirstPartyCommands = () => {commandApi.register({handler: () => requestQueueAction('cancel-current'),id: 'app.cancelQueueItem',- title: 'Cancel current queue item',+ title: 'Cancel current or next queue item',}),commandApi.register({handler: () => requestQueueAction('cancel-all'),diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/types.tsindex 681526e70f..b3fb9ef2ee 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts@@ -1,7 +1,7 @@import type { WidgetRegion } from '@workbench/layoutContracts';import type { WidgetContributionSource, WidgetInstanceId, WidgetTypeId } from '@workbench/widgetContracts';-export type HotkeyCategory = 'app' | 'canvas' | 'gallery' | 'viewer' | 'workflows';+export type HotkeyCategory = 'app' | 'canvas' | 'gallery' | 'queue' | 'viewer' | 'workflows';export type HotkeyScope =| { kind: 'global' }@@ -25,6 +25,8 @@ export interface HotkeyDefinition {preventDefault?: boolean;allowInEditable?: boolean;allowInModal?: boolean;+ /** A held key's auto-repeat does not run the command again: for commands that act once per press, such as a cancel. */+ ignoreRepeat?: boolean;/** Claim the key only while the press targets an element matching this selector; elsewhere it keeps its meaning. */targetSelector?: string;unavailableReason?: string;diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsxindex 0a9191d153..0a08c21858 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.browser.test.tsx@@ -36,6 +36,7 @@ vi.mock('@workbench/projects/library', () => ({useProjectLibrarySelector: (selector: (snapshot: { summaries: [] }) => unknown) => selector({ summaries: [] }),}));const commandsMock = vi.hoisted(() => ({+ gallery: { setCompareItem: vi.fn() },generation: { setSource: vi.fn(), submitModelOnlyUpscale: vi.fn() },notifications: { add: vi.fn() },widgets: { patchValues: vi.fn() },@@ -81,9 +82,13 @@ vi.mock('./modelOnlyUpscale', async (importOriginal) => {: original.queueModelOnlyUpscale(...args),};});+// The open project's Gallery values, which the compare entry reads its state from.+const galleryValuesMock = vi.hoisted(() => ({ current: {} as Record<string, unknown> }));vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectId: () => 'project-1',useActiveProjectName: () => 'Project',+ useWidgetValuesSelector: (_widgetId: string, selector: (values: Record<string, unknown>) => unknown) =>+ selector(galleryValuesMock.current),useWorkbenchCommands: () => commandsMock,}));// Keys stand in for copy; the one interpolated value a test reads, an upscale factor, is shown as the locale does.@@ -308,6 +313,7 @@ afterEach(async () => {host?.remove();host = null;root = null;+ galleryValuesMock.current = {};});describe('ImageContextMenu deletion delegation', () => {@@ -343,6 +349,21 @@ describe('ImageContextMenu deletion delegation', () => {});});+describe('ImageContextMenu placement', () => {+ it('opens at the right-click with no arrow, and no arrow-sized gap below the pointer', async () => {+ await renderMenu(createActions(vi.fn(() => Promise.resolve())), [image('single.png')]);+ const menu = document.querySelector<HTMLElement>('[role="menu"][data-state="open"]')!;+ const arrow = menu.parentElement!.querySelector<HTMLElement>('[data-part="arrow"]');++ // The harness right-clicks at (20, 20): a 1px anchor, then the default 8px gutter, where an arrow would add 6.+ await vi.waitFor(() => {+ expect(menu.dataset.placement).toBe('bottom-start');+ expect(arrow?.querySelector<HTMLElement>('[data-part="arrow-tip"]')?.offsetWidth ?? 0).toBe(0);+ expect(menu.getBoundingClientRect().top).toBeCloseTo(20 + 1 + 8, 0);+ });+ });+});+describe('ImageContextMenu find in gallery', () => {it('reveals a single image or video by its gallery reference', async () => {findGalleryItem.mockClear();@@ -519,6 +540,42 @@ describe('ImageContextMenu canvas destinations', () => {expect(document.body.textContent).not.toContain('widgets.gallery.itemMenu.editOnCanvasHint');});+ it('offers to cancel Select for compare on the image it waits with, and only there', async () => {+ const waiting = image('waiting.png');+ // Select for compare on the shown image: the comparison image is the selection itself.+ galleryValuesMock.current = {+ compareImage: waiting,+ selectedImage: waiting,+ selectedImageName: 'image:waiting.png',+ };+ const actions = createActions(vi.fn());+ await renderMenu(actions, [waiting]);++ expect(() => getMenuItem('widgets.preview.selectForCompare')).toThrow();+ await pickItem('widgets.preview.cancelCompare');++ expect(commandsMock.gallery.setCompareItem).toHaveBeenCalledExactlyOnceWith(null);+ expect(actions.selectForCompare).not.toHaveBeenCalled();+ });++ it('selects another image for compare while one waits, comparing the two', async () => {+ const waiting = image('waiting.png');+ galleryValuesMock.current = {+ compareImage: waiting,+ selectedImage: waiting,+ selectedImageName: 'image:waiting.png',+ };+ const actions = createActions(vi.fn());+ const other = image('other.png');+ await renderMenu(actions, [other]);++ await pickItem('widgets.preview.selectForCompare');++ expect(actions.selectForCompare).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ imageName: 'other.png' })+ );+ });+it('edits the image on the current canvas as a raster layer in one step', async () => {const actions = createActions(vi.fn());await renderMenu(actions, [image('image-0.png')]);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsxindex ff993b267e..59df409b04 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/ImageContextMenu.tsx@@ -9,7 +9,11 @@ import {legacyGeneratedImageToGalleryItem,toGalleryItemKey,} from '@features/gallery';-import { getGalleryMoveTargets } from '@features/gallery/contracts';+import {+ getGalleryCompareImage,+ getGalleryMoveTargets,+ getSelectedGalleryItemFromValues,+} from '@features/gallery/contracts';import { galleryKeys } from '@features/gallery/queries';import { canCopyImage } from '@platform/browser/clipboard';import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';@@ -19,6 +23,7 @@ import { MenuItem } from '@platform/ui/Menu';import { useQuery } from '@tanstack/react-query';import { formatHotkeyPartLabel } from '@workbench/hotkeys/keys';import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';+import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import {BoxIcon,CopyIcon,@@ -32,6 +37,7 @@ import {StarIcon,Trash2Icon,WorkflowIcon,+ XIcon,type LucideIcon,} from 'lucide-react';import { useCallback, useMemo, useRef } from 'react';@@ -124,6 +130,7 @@ export const ImageContextMenu = ({actions,boards,previewVideoActions,+ returnFocus: hostReturnFocus,target,variant = 'full',onClose,@@ -132,6 +139,11 @@ export const ImageContextMenu = ({/** The host's board listing as it shows it: folded through `useHostGalleryBoards` where boards cannot be shared. */boards: GalleryBoard[];previewVideoActions?: PreviewVideoContextActions;+ /**+ * Where focus goes when a deletion confirmation the menu opened closes, unless the target names its own. Without+ * either the dialog returns focus to what had it as it opened, which the deletion may have removed.+ */+ returnFocus?: () => HTMLElement | null;target: ImageContextMenuTarget | null;variant?: ImageContextMenuVariant;onClose: () => void;@@ -143,7 +155,7 @@ export const ImageContextMenu = ({() => (itemTarget && isCompleteImageTarget ? { images, x: itemTarget.x, y: itemTarget.y } : null),[images, isCompleteImageTarget, itemTarget]);- const returnFocus = itemTarget?.returnFocus;+ const returnFocus = itemTarget?.returnFocus ?? hostReturnFocus;const requestDeletion = useCallback((itemRefs: GalleryItemRef[]) => void actions.deleteItems(itemRefs, { returnFocus }),[actions, returnFocus]@@ -640,7 +652,6 @@ const SingleImageMenuItems = ({const handleDelete = useCallback(() => onRequestDeletion([image.imageName]), [image.imageName, onRequestDeletion]);const imageSourceBoardIds = useMemo(() => [image.boardId], [image.boardId]);const imageItemRef = useMemo<GalleryItemRef>(() => ({ kind: 'image', name: image.imageName }), [image.imageName]);- const handleSelectForCompare = useCallback(() => actions.selectForCompare(image), [actions, image]);const handleLoadWorkflow = useCallback(() => void actions.loadImageWorkflow(image), [actions, image]);const handleGeneratePbrMaps = useCallback(() => void actions.generatePbrMaps(image), [actions, image]);@@ -676,14 +687,7 @@ const SingleImageMenuItems = ({<Menu.Separator borderColor="border.subtle" /></>) : null}- <ContextMenuItem- // The grid's shortcut for the same action, otherwise found only by accident.- detail={t('widgets.gallery.itemMenu.compareShortcut', { key: formatHotkeyPartLabel('alt') })}- icon={ImagesIcon}- label={t('widgets.preview.selectForCompare')}- value="select-for-compare"- onClick={handleSelectForCompare}- />+ <SelectForCompareMenuItem actions={actions} image={image} /><ContextMenuItemicon={BoxIcon}label={t('widgets.gallery.itemActions.pbrMaps.label')}@@ -893,6 +897,48 @@ const ChangeBoardSubMenu = ({);};+/** The image Select for compare is waiting with, if any: the comparison image that is also the selection. */+const selectArmedCompareImageName = (values: Record<string, unknown>): string | null => {+ const compareImage = getGalleryCompareImage(values);+ const selectedItem = getSelectedGalleryItemFromValues(values);++ return compareImage && selectedItem?.kind === 'image' && selectedItem.name === compareImage.imageName+ ? compareImage.imageName+ : null;+};++/**+ * Select for compare, or on the image it is already waiting with, the way to call it off, as the Preview toggle does.+ * It reads the comparison itself, so the shared actions stay independent of the selection.+ */+const SelectForCompareMenuItem = ({ actions, image }: { actions: ImageActions; image: GalleryImage }) => {+ const { t } = useTranslation();+ const { gallery } = useWorkbenchCommands();+ const isArmedWithImage = useWidgetValuesSelector('gallery', selectArmedCompareImageName) === image.imageName;+ const handleClick = useCallback(+ () => (isArmedWithImage ? gallery.setCompareItem(null) : actions.selectForCompare(image)),+ [actions, gallery, image, isArmedWithImage]+ );++ return isArmedWithImage ? (+ <ContextMenuItem+ icon={XIcon}+ label={t('widgets.preview.cancelCompare')}+ value="cancel-compare"+ onClick={handleClick}+ />+ ) : (+ <ContextMenuItem+ // The grid's shortcut for the same action, otherwise found only by accident.+ detail={t('widgets.gallery.itemMenu.compareShortcut', { key: formatHotkeyPartLabel('alt') })}+ icon={ImagesIcon}+ label={t('widgets.preview.selectForCompare')}+ value="select-for-compare"+ onClick={handleClick}+ />+ );+};+const ContextMenuItem = ({detail,disabled,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.tsindex aa8818ec74..3b29865a2e 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.test.ts@@ -406,6 +406,51 @@ describe('canvas record to recall', () => {});+ it('runs one Canvas recall at a time and says so to a press made meanwhile, without holding back other recalls', async () => {+ const store = createWorkbenchStore();+ const target = targetFor(store);+ const notifications = vi.spyOn(store.commands.notifications, 'add');+ let finishLookup: (() => void) | undefined;+ api.metadata.mockResolvedValue({ canvas_v3_metadata: record(), positive_prompt: 'recalled' });+ api.resolveMany.mockImplementationOnce(+ (names: string[]) =>+ new Promise((resolve) => {+ finishLookup = () => resolve(names.map((imageName) => ({ imageName })));+ })+ );+ const recall = (kind: 'all' | 'prompts') =>+ executeImageRecall({+ commands: store.commands,+ canvasTarget: target,+ getGenerateValues: () => getProjectWidgetValues(target.getProject()!, 'generate'),+ image: { imageName: 'output.png', width: 768, height: 1024 } as GalleryImage,+ kind,+ models,+ projectId: target.projectId,+ queryClient: new QueryClient(),+ t,+ });++ const first = recall('all');+ await vi.waitFor(() => expect(finishLookup).toBeDefined());+ await expect(recall('all')).resolves.toBe(false);+ expect(notifications).toHaveBeenCalledWith(+ expect.objectContaining({ kind: 'info', message: 'widgets.gallery.itemActions.recall.recallInProgress' })+ );+ // A recall that leaves the Canvas alone runs meanwhile.+ await expect(recall('prompts')).resolves.toBe(true);++ finishLookup!();+ await expect(first).resolves.toBe(true);+ expect(notifications).not.toHaveBeenCalledWith(+ expect.objectContaining({ title: 'widgets.gallery.itemActions.recall.partiallyRecalled' })+ );+ expect(target.getProject()!.canvas.snapshots).toHaveLength(1);+ // Settled, so the next Canvas recall runs.+ await expect(recall('all')).resolves.toBe(true);+ expect(target.getProject()!.canvas.snapshots).toHaveLength(2);+ });+it.each(['all', 'remix', 'api'] as const)('preserves the whole Canvas and recalls valid Generate fields when the %s asset lookup fails',async (surface) => {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.tsindex b94fc614f0..6d9c6e612c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/canvasRecall.ts@@ -5,7 +5,7 @@ import type { Project } from '@workbench/projectContracts';import type { WorkbenchCommands } from '@workbench/workbenchStore';import type { TFunction } from 'i18next';-import { galleryDurability, galleryImages } from '@features/gallery';+import { GALLERY_REQUEST_MAX_NAMES, galleryDurability, galleryImages } from '@features/gallery';import { galleryImageUrls } from '@features/gallery/utility';import {getRegionalGuidanceSupport,@@ -26,9 +26,6 @@ import { readCanvasScaling, CANVAS_SCALING_KEYS } from '@workbench/widgets/canvaimport { resolveRecordedModel, toRecordedModelRef } from './recordedModel';-// Matches MAX_IMAGE_BATCH_SIZE in invokeai/app/api/routers/images.py.-const IMAGE_LOOKUP_BATCH_SIZE = 1000;-export interface CanvasRecallTarget {commands: Pick<WorkbenchCommands, 'canvas' | 'widgets'>;/** Null when the originating project is closed or no longer active. */@@ -195,10 +192,11 @@ export const prepareCanvasRecall = async ({}const missing = [...new Set(names)].filter((name) => !resolvedImages.has(name));assertAccountScopeCurrent(owner);- for (let offset = 0; offset < missing.length; offset += IMAGE_LOOKUP_BATCH_SIZE) {+ // One lookup per request, so a canvas change between them stops the rest.+ for (let offset = 0; offset < missing.length; offset += GALLERY_REQUEST_MAX_NAMES) {try {const images = await galleryImages.resolveMany(- missing.slice(offset, offset + IMAGE_LOOKUP_BATCH_SIZE),+ missing.slice(offset, offset + GALLERY_REQUEST_MAX_NAMES),owner.signal);assertAccountScopeCurrent(owner);diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.tsindex b1bed1848e..a0807d2b82 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.test.ts@@ -12,6 +12,7 @@ import { createInstance } from 'i18next';import { beforeEach, describe, expect, it, vi } from 'vitest';const galleryApi = vi.hoisted(() => ({+ GALLERY_REQUEST_MAX_NAMES: 1000,galleryImages: {metadata: vi.fn(),resolveMany: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.tsindex f8bca9a8c0..bffd22a218 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeImageRecall.ts@@ -10,7 +10,7 @@ import type { QueryClient } from '@tanstack/react-query';import type { WorkbenchCommands } from '@workbench/workbenchStore';import type { TFunction } from 'i18next';-import { galleryImages, galleryVideos } from '@features/gallery';+import { GALLERY_REQUEST_MAX_NAMES, galleryImages, galleryVideos } from '@features/gallery';import { fetchGalleryImageMetadata } from '@features/gallery/queries';import {getCompatibleReferenceImages,@@ -205,7 +205,7 @@ export const executeLoadMediaWorkflow = async ({const getReferenceImageName = (referenceImage: GenerateReferenceImage): string | null =>referenceImage.config.image ? getEffectiveReferenceImage(referenceImage.config.image).image_name : null;-/** Sequential, deduplicated lookups respect the Gallery API's 1,000-name request limit. */+/** Sequential, deduplicated lookups, one per request the Gallery API accepts, so a stale recall stops between them. */const resolveReferenceImages = async (names: readonly string[],signal: AbortSignal,@@ -213,11 +213,11 @@ const resolveReferenceImages = async (): Promise<Map<string, GalleryImage>> => {const assets = new Map<string, GalleryImage>();const distinctNames = [...new Set(names)];- for (let offset = 0; offset < distinctNames.length; offset += 1000) {+ for (let offset = 0; offset < distinctNames.length; offset += GALLERY_REQUEST_MAX_NAMES) {if (signal.aborted || !isCurrent()) {throw new DOMException('Recall is no longer current', 'AbortError');}- const batch = distinctNames.slice(offset, offset + 1000);+ const batch = distinctNames.slice(offset, offset + GALLERY_REQUEST_MAX_NAMES);const images = await galleryImages.resolveMany(batch, signal);if (signal.aborted || !isCurrent()) {throw new DOMException('Recall is no longer current', 'AbortError');@@ -293,19 +293,32 @@ export const getCurrentGenerateValues = ({: null;};-export const executeImageRecall = async ({- commands,- canvasTarget,- getGenerateValues,- image,- isCanvasFrame,- kind,- models,- owner: callerOwner,- projectId,- queryClient,- t,-}: {+let canvasRecallHolder: { owner: AccountScope } | null = null;++/**+ * Claims the one Canvas recall that may run at a time, or returns null while another reads or commits (a double+ * click, a second key press): a Canvas recall that started before another commits finds the document changed and+ * recalls only in part. Recalls that leave the Canvas alone need no claim: they re-read Generate values after every+ * await. A claim left over from an account that has since ended holds nothing back. Release once the recall has+ * committed, before saving its Canvas images, so a slow save holds no later recall back. Releasing again, or after+ * another claim took over, does nothing. API-driven recalls (`recall_parameters_updated`) queue among themselves+ * and do not claim.+ */+export const claimCanvasRecall = (owner: AccountScope): (() => void) | null => {+ if (canvasRecallHolder && isAccountScopeCurrent(canvasRecallHolder.owner)) {+ return null;+ }+ const claim = { owner };+ canvasRecallHolder = claim;++ return () => {+ if (canvasRecallHolder === claim) {+ canvasRecallHolder = null;+ }+ };+};++interface ImageRecallInput {commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;canvasTarget?: CanvasRecallTarget;/** Re-read after every await: the commit writes the whole Generate record, so a snapshot would revert newer edits. */@@ -321,7 +334,22 @@ export const executeImageRecall = async ({/** Holds the gallery's shared image metadata entry, which menus and Preview Details may already have read. */queryClient: QueryClient;t: TFunction;-}): Promise<boolean> => {+}++/** Recalls an image's recorded settings; a Canvas recall pressed while another runs says so (see `claimCanvasRecall`). */+export const executeImageRecall = async ({+ commands,+ canvasTarget,+ getGenerateValues,+ image,+ isCanvasFrame,+ kind,+ models,+ owner: callerOwner,+ projectId,+ queryClient,+ t,+}: ImageRecallInput): Promise<boolean> => {const owner = callerOwner ?? captureAccountScope();const originalProject = canvasTarget?.getProject();if (canvasTarget && !originalProject) {@@ -333,6 +361,7 @@ export const executeImageRecall = async ({const supportedModels = models.filter(isSupportedGenerateModel);const vaeModels = models.filter(isVaeModelConfig).map((model) => model as VaeModelConfig);+ let releaseCanvasRecall: (() => void) | null = null;try {if (!isImageRecallKindAvailable(kind)) {@@ -395,7 +424,7 @@ export const executeImageRecall = async ({if (canvasTarget && !canvasTarget.getProject()) {return false;}- const canvasRecall =+ const touchesCanvas = Boolean((kind === 'all' || kind === 'remix') &&canvasTarget &&originalProject &&@@ -407,8 +436,19 @@ export const executeImageRecall = async ({'t2iAdapters' in metadata ||'strength' in metadata ||'denoise_strength' in metadata)- ? await import('./canvasRecall')- : null;+ );+ if (touchesCanvas) {+ releaseCanvasRecall = claimCanvasRecall(owner);+ if (!releaseCanvasRecall) {+ commands.notifications.add({+ kind: 'info',+ message: t('widgets.gallery.itemActions.recall.recallInProgress'),+ title: getImageRecallTitle(kind, t),+ });+ return false;+ }+ }+ const canvasRecall = touchesCanvas ? await import('./canvasRecall') : null;const initialValues = canvasRecall ? readGenerateValues() : null;const initialResult = initialValues? buildImageRecallSettings({@@ -554,6 +594,7 @@ export const executeImageRecall = async ({title: t('widgets.gallery.itemActions.recall.partiallyRecalled'),});}+ releaseCanvasRecall?.();if (canvasApplied && canvasPlan && canvasRecall && canvasTarget) {const durable = await canvasRecall.finalizeCanvasRecallAssets(canvasPlan, canvasTarget, owner);if (!durable && isAccountScopeCurrent(owner) && canvasTarget.getProject()) {@@ -577,5 +618,7 @@ export const executeImageRecall = async ({projectId,});return false;+ } finally {+ releaseCanvasRecall?.();}};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.tsindex 16dbf36851..26d596117e 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeRecallParameters.test.ts@@ -7,6 +7,7 @@ import i18n from 'i18next';import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';const galleryApi = vi.hoisted(() => ({+ GALLERY_REQUEST_MAX_NAMES: 1000,galleryImages: {metadata: vi.fn(),resolveMany: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.tsindex 5015ca7d67..b2f70a2d0d 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/executeVideoRecall.test.ts@@ -11,6 +11,7 @@ import { createInstance } from 'i18next';import { beforeEach, describe, expect, it, vi } from 'vitest';const galleryApi = vi.hoisted(() => ({+ GALLERY_REQUEST_MAX_NAMES: 1000,galleryImages: { metadata: vi.fn(), resolveMany: vi.fn() },galleryItems: { resolve: vi.fn() },}));diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.tsindex bf8ebec639..a11925325e 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts@@ -320,6 +320,42 @@ describe('image recall', () => {expect(result?.fields).toContain('seed');});+ describe("the recorded model's default VAE", () => {+ const fluxModel: MainModelConfig = { base: 'flux', key: 'flux-model', name: 'FLUX', type: 'main' };+ const fluxVae: VaeModelConfig = { base: 'flux', key: 'flux-vae', name: 'FLUX VAE', type: 'vae' };+ const sdxlVae: VaeModelConfig = { base: 'sdxl', key: 'sdxl-vae', name: 'SDXL VAE', type: 'vae' };+ const recall = (current: GenerateWidgetValues, model: MainModelConfig, vaeModels: VaeModelConfig[]) =>+ buildImageRecallSettings({+ currentValues: current,+ image,+ kind: 'all',+ // No VAE recorded, so only the model's default could change it.+ metadata: { model: { key: model.key }, positive_prompt: 'a recalled prompt' },+ models: [model, ...vaeModels],+ supportedModels: [model],+ vaeModels,+ });++ it("keeps a family's required VAE for the 'default' sentinel", () => {+ const model = { ...fluxModel, default_settings: { vae: 'default' } };+ const result = recall(createValues({ model: fluxModel, modelKey: fluxModel.key, vae: fluxVae }), model, [+ fluxVae,+ ]);++ expect(result?.values.vae).toEqual(fluxVae);+ });++ // An image made with the bundled VAE records none; recalling it must not keep another VAE.+ it('uses the bundled VAE when the default names one that is not installed, as recall always has', () => {+ const model = { ...sdxlModel, default_settings: { vae: 'gone' } };+ const result = recall(createValues({ model: sdxlModel, modelKey: sdxlModel.key, vae: sdxlVae }), model, [+ sdxlVae,+ ]);++ expect(result?.values.vae).toBeNull();+ });+ });+it('recalls reference images from metadata, re-targeting configs to the effective model', () => {// The metadata model is not installed, so the current SDXL model stays// selected and the Qwen reference config is rebuilt for SDXL.@@ -332,6 +368,7 @@ describe('image recall', () => {{id: 'ref-1',isEnabled: true,+ name: 'Hero pose',config: {image: {height: 770,@@ -357,6 +394,8 @@ describe('image recall', () => {image: { original: { image: { height: 770, image_name: 'reference.png', width: 513 } } },type: 'ip_adapter',});+ // The user's name stays with its image through the retarget to another family.+ expect(result?.values.referenceImages[0]?.name).toBe('Hero pose');expect(result?.fields).toContain('referenceImages');});diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.tsindex d8fccac723..77670acafb 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.ts@@ -24,10 +24,8 @@ import {getGenerateModelSelectionResult,getGenerationUiPolicy,isComponentCompatibleWithModel,- getModelDefaultVae,getSettingsWithModelDefaults,hasArchitectureCapabilities,- hasModelDefaultVae,isKnownScheduler,isLoraCompatibleWithModel,isLoraModelConfig,@@ -63,6 +61,8 @@ import {MIN_ZIMAGE_SEED_VARIANCE_RANDOMIZE_PERCENT,normalizeMossImageSkipLayers,normalizeReferenceImages,+ getRecallDefaultVae,+ resolveModelDefaultVae,} from '@features/generation/settings';import { SEED_MAX } from '@platform/core/seed';@@ -1540,11 +1540,8 @@ export const buildImageRecallSettings = ({if (model) {const valuesWithModelDefaults = getSettingsWithModelDefaults(values, model);- values = {- ...valuesWithModelDefaults,- model,- ...(hasModelDefaultVae(model) ? { vae: getModelDefaultVae(model, vaeModels) } : {}),- };+ const vae = getRecallDefaultVae(resolveModelDefaultVae(model, valuesWithModelDefaults, vaeModels));+ values = { ...valuesWithModelDefaults, model, ...(vae === undefined ? {} : { vae }) };fields.push('model');}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts b/invokeai/frontend/webv2/src/workbench/image-actions/index.tsindex e3aae2fb3e..72eee0aca7 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/index.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/index.ts@@ -20,7 +20,7 @@ export {type ImageRecallKind,type ImageRecallResult,} from './imageRecall';-export { executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';+export { claimCanvasRecall, executeImageRecall, getCurrentGenerateValues } from './executeImageRecall';export { readRecordedModelRef } from './recordedModel';export {appendReferenceVideo,diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.test.tsindex d263c6df4c..2bae0cd850 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.test.ts@@ -6,7 +6,6 @@ import { ApiError } from '@platform/transport/http';import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';import {- MEDIA_USAGE_MAX_NAMES_PER_KIND,MEDIA_USAGE_MAX_PROJECT_READ_BYTES,MEDIA_USAGE_MAX_PROJECT_READS,resolveMediaUsage,@@ -21,6 +20,7 @@ const mocks = vi.hoisted(() => ({}));vi.mock('@features/gallery/mediaUsage', () => ({+ GALLERY_REQUEST_MAX_NAMES: 1000,checkGalleryMediaUsage: (request: unknown, signal: AbortSignal) => mocks.check(request, signal),}));vi.mock('@workbench/projects/api', () => ({@@ -484,19 +484,27 @@ describe('resolveMediaUsage', () => {expect(report.groups).toEqual([{ count: 1, kind: 'projectUnchecked', name: 'Big' }]);});- it('says a selection past what one check takes was too large, not that the server failed', async () => {- const names = Array.from({ length: MEDIA_USAGE_MAX_NAMES_PER_KIND + 1 }, (_, index) => `${index}.png`);+ it('asks the server about a selection larger than one request takes, as about any other', async () => {+ const names = Array.from({ length: 2500 }, (_, index) => `${index}.png`);+ mocks.check.mockResolvedValue(+ answer({ documents: [usageDocument('workflow', 'wf-1', 'Upscale pass', ['2400.png'])] })+ );const report = await resolveMediaUsage(items(...names),host([project('open', 'Open', { raster: ['7.png'] })], 'open'));- expect(mocks.check).not.toHaveBeenCalled();- expect(report.serverCheck).toBe('tooManyItems');- expect(report.groups).toEqual([- { count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] },- ]);+ expect(mocks.check).toHaveBeenCalledWith({ kind: 'items', refs: names.map(image) }, expect.any(AbortSignal));+ expect(report).toMatchObject({+ checkedCount: 2500,+ groups: [+ { count: 1, kind: 'openProject', surfaces: [{ count: 1, surface: 'canvasRaster' }] },+ { count: 1, kind: 'workflow', name: 'Upscale pass' },+ ],+ inUseCount: 2,+ serverCheck: 'complete',+ });});it('takes workflows, the legacy editor, projects kept for repair, unknown documents, queued jobs and other accounts as they are', async () => {@@ -575,6 +583,95 @@ describe('resolveMediaUsage', () => {expect(report.groups).toEqual([]);});+ it('gives a check sent in several requests that long for each of them', async () => {+ vi.useFakeTimers();+ onTestFinished(() => {+ vi.useRealTimers();+ });+ mocks.check.mockImplementation(+ (_request, signal) =>+ new Promise((resolve, reject) => {+ setTimeout(() => resolve(answer()), 25);+ signal.addEventListener('abort', () => reject(signal.reason));+ })+ );+ // 2,500 images take three requests, so 30 ms in all.+ const names = Array.from({ length: 2500 }, (_, index) => `${index}.png`);++ const pending = resolveMediaUsage(items(...names), host(), { serverTimeoutMs: 10 });+ await vi.advanceTimersByTimeAsync(25);++ await expect(pending).resolves.toMatchObject({ serverCheck: 'complete' });+ });++ it('lists a document a batched check could not name in full as unchecked, counting at least what it named', async () => {+ const xEntry = {+ ...usageDocument('project', 'p-x', 'X', ['1001.png', '1002.png', '1003.png']),+ namesIncomplete: true as const,+ };+ mocks.check.mockResolvedValue(answer({ checkedImageCount: 2000, documents: [xEntry], inUseImageCount: 503 }));+ serveProjects([project('p-x', 'X', { raster: ['1001.png'] })]);+ const names = Array.from({ length: 2000 }, (_, index) => `${index}.png`);++ const report = await resolveMediaUsage(items(...names), host());++ // Not read and narrowed to what the server happened to name: its other uses were never named.+ expect(mocks.getProject).not.toHaveBeenCalled();+ expect(report.groups).toEqual([{ count: 3, countAtLeast: true, kind: 'projectUnchecked', name: 'X' }]);+ // The server's own exact total still stands.+ expect(report.inUseCount).toBe(503);+ });++ it('reads an open project’s saved copy when a batched check could not name all its uses, keeping the server’s total', async () => {+ // As a batched check answers: the flag exists only because a batch left documents unlisted.+ const xEntry = { ...usageDocument('project', 'p-x', 'X', ['1001.png']), namesIncomplete: true as const };+ const listed = [+ xEntry,+ ...Array.from({ length: 99 }, (_, index) =>+ usageDocument('workflow', `wf-${index}`, `Flow ${index}`, ['1500.png'])+ ),+ ];+ mocks.check.mockResolvedValue(+ answer({ checkedImageCount: 2000, documents: listed, documentsTotal: 101, inUseImageCount: 503 })+ );+ // The saved copy also uses an image the first batch left unnamed; the copy here does not.+ serveProjects([project('p-x', 'X', { raster: ['1001.png', '7.png'] })]);+ const names = Array.from({ length: 2000 }, (_, index) => `${index}.png`);++ const report = await resolveMediaUsage(items(...names), host([project('p-x', 'X', { raster: ['1001.png'] })]));++ expect(mocks.getProject).toHaveBeenCalledOnce();+ expect(report.groups[0]).toEqual({+ count: 2,+ kind: 'project',+ name: 'X',+ surfaces: [{ count: 2, surface: 'canvasRaster' }],+ });+ expect(report.groups.at(-1)).toEqual({ documentCount: 1, kind: 'moreDocuments' });+ // The uses the server counted in unnamed documents count nowhere else: its total stands.+ expect(report.inUseCount).toBe(503);+ });++ it('keeps the server’s total when a scan narrows a project but other documents went unlisted', async () => {+ // The open project names a.png only as its Gallery selection; an unlisted document uses b.png.+ mocks.check.mockResolvedValue(+ answer({+ documents: [atServed(usageDocument('project', 'open', 'Open', ['a.png']))],+ documentsTotal: 2,+ inUseImageCount: 2,+ })+ );++ const report = await resolveMediaUsage(+ items('a.png', 'b.png'),+ host([project('open', 'Open', { selected: 'a.png' })], 'open', { open: SERVED })+ );++ expect(mocks.getProject).not.toHaveBeenCalled();+ expect(report.groups).toEqual([{ documentCount: 1, kind: 'moreDocuments' }]);+ expect(report.inUseCount).toBe(2);+ });+it('lists a closed project as the server counts it when reading it outlasts the deadline', async () => {vi.useFakeTimers();onTestFinished(() => {diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.ts b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.tsindex cb70c04c2c..76e31b0eb6 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/mediaUsageReport.ts@@ -28,6 +28,7 @@ import type { ProjectSyncInfo } from '@workbench/projects/syncStore';import { toGalleryItemKey } from '@features/gallery/contracts';import {checkGalleryMediaUsage,+ GALLERY_REQUEST_MAX_NAMES,type GalleryMediaUsage,type GalleryMediaUsageDocument,type GalleryMediaUsageGroup,@@ -41,8 +42,6 @@ import { deserializeProjectRecord } from '@workbench/projects/projectHydration';import { collectMediaUsage, mergeMediaUsage, type MediaUsage } from './mediaUsage';-/** The server checks at most this many names of each kind per request. */-export const MEDIA_USAGE_MAX_NAMES_PER_KIND = 1000;/*** Projects read from the server to narrow its answer, at most, a few at a time: first projects in memory whose scan* dropped a name the server found at revisions other than the ones the copy builds on, then closed projects. Each read@@ -77,7 +76,10 @@ export interface MediaUsageHost {}export interface MediaUsageOptions {- /** How long the server check may take before the report says it could not finish. */+ /**+ * How long each request of the server check may take before the report says it could not finish: a selection past+ * one request's cap is checked in several, and gets this long for each.+ */serverTimeoutMs?: number;/** How long reading projects from the server may take; any not read by then are listed as the server counts them. */projectReadsTimeoutMs?: number;@@ -109,8 +111,21 @@ const withDeadline = (signal: AbortSignal, ms: number): { clear: () => void; sig};};-const isTruncated = (entry: GalleryMediaUsageDocument): boolean =>- entry.imageCount > entry.imageNames.length || entry.videoCount > entry.videoNames.length;+/** Whether the server named only some of what the entry uses: its list was capped, or a batched check left it out. */+const isTruncated = (entry: {+ imageCount: number;+ imageNames: readonly string[];+ namesIncomplete?: true;+ videoCount: number;+ videoNames: readonly string[];+}): boolean =>+ entry.namesIncomplete === true ||+ entry.imageCount > entry.imageNames.length ||+ entry.videoCount > entry.videoNames.length;++/** A count taken from a server entry that does not name all of its uses is a lower bound. */+const countBoundOf = (entry: GalleryMediaUsageDocument): { countAtLeast?: true } =>+ entry.namesIncomplete ? { countAtLeast: true } : {};const refsOf = (entry: GalleryMediaUsageDocument): GalleryItemRef[] => [...entry.imageNames.map((name) => ({ kind: 'image' as const, name })),@@ -230,24 +245,24 @@ export const resolveMediaUsage = async (const owner = captureAccountScope();const signal = callerSignal ? AbortSignal.any([callerSignal, owner.signal]) : owner.signal;const requestedRefs = request.kind === 'items' ? dedupeRefs(request.refs) : [];- const overServerLimit =- requestedRefs.filter((ref) => ref.kind === 'image').length > MEDIA_USAGE_MAX_NAMES_PER_KIND ||- requestedRefs.filter((ref) => ref.kind === 'video').length > MEDIA_USAGE_MAX_NAMES_PER_KIND;let server: GalleryMediaUsage | null = null;-- if (!overServerLimit) {- const deadline = withDeadline(signal, serverTimeoutMs);-- try {- server = await checkGalleryMediaUsage(- request.kind === 'items' ? { kind: 'items', refs: requestedRefs } : request,- deadline.signal- );- } catch {- server = null;- } finally {- deadline.clear();- }+ const serverRequests = Math.max(+ 1,+ ...(['image', 'video'] as const).map((kind) =>+ Math.ceil(requestedRefs.filter((ref) => ref.kind === kind).length / GALLERY_REQUEST_MAX_NAMES)+ )+ );+ const deadline = withDeadline(signal, serverTimeoutMs * serverRequests);++ try {+ server = await checkGalleryMediaUsage(+ request.kind === 'items' ? { kind: 'items', refs: requestedRefs } : request,+ deadline.signal+ );+ } catch {+ server = null;+ } finally {+ deadline.clear();}signal.throwIfAborted();@@ -282,7 +297,8 @@ export const resolveMediaUsage = async (const base = host.getSyncBase(project.id);- if (entry && dropsServerNames(entry, localKeys) && !isServerCopyOf(base, entry)) {+ // A document a batched check could not name in full cannot vouch for a scan that dropped nothing it named.+ if (entry && (entry.namesIncomplete || dropsServerNames(entry, localKeys)) && !isServerCopyOf(base, entry)) {// An edit here removed the name, or another tab or device saved a use this copy lacks: the server's copy decides.outcomes.set(project.id, { entry, kind: 'unchecked', local: usage });reads.push({ entry, local: { base, usage }, refs });@@ -329,7 +345,7 @@ export const resolveMediaUsage = async (signal.throwIfAborted();assertAccountScopeCurrent(owner);- return buildReport({ documents, host, loadedProjects, outcomes, overServerLimit, request, requestedRefs, server });+ return buildReport({ documents, host, loadedProjects, outcomes, request, requestedRefs, server });};const buildReport = ({@@ -337,7 +353,6 @@ const buildReport = ({host,loadedProjects,outcomes,- overServerLimit,request,requestedRefs,server,@@ -346,7 +361,6 @@ const buildReport = ({host: MediaUsageHost;loadedProjects: ReturnType<MediaUsageHost['getLoadedProjects']>;outcomes: ReadonlyMap<string, ProjectOutcome>;- overServerLimit: boolean;request: GalleryMediaUsageRequest;requestedRefs: readonly GalleryItemRef[];server: GalleryMediaUsage | null;@@ -359,10 +373,10 @@ const buildReport = ({// A server project entry replaced by a scan that dropped one of its names: the server's own in-use total, which// counted that name, no longer holds.let narrowed = false;- const addNames = (entry: { imageCount: number; imageNames: string[]; videoCount: number; videoNames: string[] }) => {+ const addNames = (entry: Parameters<typeof isTruncated>[0]) => {entry.imageNames.forEach((name) => inUse.add(toGalleryItemKey({ kind: 'image', name })));entry.videoNames.forEach((name) => inUse.add(toGalleryItemKey({ kind: 'video', name })));- if (entry.imageCount > entry.imageNames.length || entry.videoCount > entry.videoNames.length) {+ if (isTruncated(entry)) {exact = false;lowerBound = Math.max(lowerBound, entry.imageCount + entry.videoCount);}@@ -380,7 +394,7 @@ const buildReport = ({addNames(entry);if (!local) {- return { count: entry.imageCount + entry.videoCount, kind: 'projectUnchecked', name };+ return { count: entry.imageCount + entry.videoCount, kind: 'projectUnchecked', name, ...countBoundOf(entry) };}// A project open here: what its copy uses, beside the server's names its saved version could not be checked for.@@ -393,8 +407,8 @@ const buildReport = ({localKeys.forEach((key) => inUse.add(key));return projectId === host.openProjectId- ? { count, kind: 'openProject', savedCopyUnchecked: true, surfaces }- : { count, kind: 'project', name, savedCopyUnchecked: true, surfaces };+ ? { count, kind: 'openProject', savedCopyUnchecked: true, surfaces, ...countBoundOf(entry) }+ : { count, kind: 'project', name, savedCopyUnchecked: true, surfaces, ...countBoundOf(entry) };}const used = usedKeysOf(outcome.usage);@@ -445,7 +459,7 @@ const buildReport = ({for (const entry of documents) {if (entry.kind === kind) {addNames(entry);- groups.push(toGroup(entry));+ groups.push({ ...toGroup(entry), ...countBoundOf(entry) });}}};@@ -486,7 +500,12 @@ const buildReport = ({// server's count, the items deleting it removes.const checkedCount =request.kind === 'items' || !server ? requestedRefs.length : server.checkedImageCount + server.checkedVideoCount;- const serverInUse = server && !narrowed ? server.inUseImageCount + server.inUseVideoCount : 0;+ // A narrowing scan makes the server's total too high, but documents it did not list count nowhere else: with any of+ // those, the higher total stands.+ const serverInUse =+ server && (!narrowed || server.documentsTotal > server.documents.length)+ ? server.inUseImageCount + server.inUseVideoCount+ : 0;const inUseCount = exact ? inUse.size : Math.max(inUse.size, lowerBound, serverInUse);return {@@ -498,7 +517,7 @@ const buildReport = ({? requestedRefs.every((ref) => ref.kind === 'image'): server !== null && server.checkedVideoCount === 0,scope: request.kind,- serverCheck: server ? 'complete' : overServerLimit ? 'tooManyItems' : 'unavailable',+ serverCheck: server ? 'complete' : 'unavailable',};};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.tsindex 32ad5dcd68..20c54b6145 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.test.ts@@ -154,6 +154,42 @@ describe('buildRecallParametersSettings', () => {expect(result.values.vae).toBeNull();});+ describe("the new model's default VAE", () => {+ const fluxVae = makeModel('flux-vae', 'flux', 'vae');+ const sdxlNamingMissingVae = makeModel('sdxl-missing-vae', 'sdxl', 'main', { default_settings: { vae: 'gone' } });+ // The Model Manager stores "default" when the VAE default is on with no VAE picked; FLUX bundles no VAE.+ const fluxDefaultVae = makeModel('flux-default-vae', 'flux', 'main', { default_settings: { vae: 'default' } });+ const sd3DefaultVae = makeModel('sd3-default-vae', 'sd-3', 'main', { default_settings: { vae: 'default' } });+ const sd3Vae = makeModel('sd3-vae', 'sd-3', 'vae');+ const catalog = [...models, fluxVae, sdxlNamingMissingVae, fluxDefaultVae, sd3DefaultVae, sd3Vae];+ const buildWith = (currentValues: ReturnType<typeof currentFor>, parameters: Record<string, unknown>) =>+ buildRecallParametersSettings({+ currentValues,+ models: catalog,+ parameters,+ supportedModels: catalog.filter(isSupportedGenerateModel) as GenerateModelConfig[],+ vaeModels: catalog.filter(isVaeModelConfig) as VaeModelConfig[],+ });++ it('uses the bundled VAE when the default names one that is not installed, as recall always has', () => {+ const result = buildWith(currentFor(sdxl, { vae: sdxlVae }), { model: sdxlNamingMissingVae.key });++ expect(result.values.vae).toBeNull();+ });++ it("clears an optional VAE override for the 'default' sentinel", () => {+ const result = buildWith(currentFor(sd3, { vae: sd3Vae }), { model: sd3DefaultVae.key });++ expect(result.values.vae).toBeNull();+ });++ it("keeps a family's required VAE for the 'default' sentinel", () => {+ const result = buildWith(currentFor(flux, { vae: fluxVae }), { model: fluxDefaultVae.key });++ expect(result.values.vae?.key).toBe(fluxVae.key);+ });+ });+it('reports an unknown model and a VAE from another family without changing the selection', () => {const current = currentFor(sdxl);const result = build(current, { model: 'not-installed', vae_model: sdxlVae.name });diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.tsindex 65d905c5c6..fd3cbcb354 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParameters.ts@@ -22,10 +22,8 @@ import {getGenerateModelSelectionResult,getGenerationUiPolicy,getReferenceImageLimit,- getModelDefaultVae,getSettingsWithModelDefaults,hasArchitectureCapabilities,- hasModelDefaultVae,isLoraCompatibleWithModel,isLoraModelConfig,isMainModelConfig,@@ -39,6 +37,8 @@ import {MIN_REFINER_CFG_SCALE,MIN_REFINER_START,MIN_REFINER_STEPS,+ getRecallDefaultVae,+ resolveModelDefaultVae,withAddedReferenceImages,} from '@features/generation/settings';@@ -232,12 +232,8 @@ export const buildRecallParametersSettings = ({model,models,});- values = {- ...values,- ...settings,- model,- ...(hasModelDefaultVae(model) ? { vae: getModelDefaultVae(model, vaeModels) } : {}),- };+ const vae = getRecallDefaultVae(resolveModelDefaultVae(model, settings, vaeModels));+ values = { ...values, ...settings, model, ...(vae === undefined ? {} : { vae }) };fields.add('model');}}@@ -261,7 +257,9 @@ export const buildRecallParametersSettings = ({fields.add('vae');}} else if (isReset('vae_model')) {- values = { ...values, vae: hasModelDefaultVae(values.model) ? getModelDefaultVae(values.model, vaeModels) : null };+ // A strict null asks for the default, so anything the default cannot name is the bundled VAE, as before.+ const defaultVae = resolveModelDefaultVae(values.model, values, vaeModels);+ values = { ...values, vae: defaultVae.kind === 'apply' ? defaultVae.vae : null };fields.add('vae');}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.test.tsindex 5a17df13fb..7354643965 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallParametersRuntime.test.ts@@ -9,6 +9,7 @@ import { createWorkbenchStore } from '@workbench/workbenchStore';import { beforeEach, describe, expect, it, vi } from 'vitest';const galleryApi = vi.hoisted(() => ({+ GALLERY_REQUEST_MAX_NAMES: 1000,galleryImages: {metadata: vi.fn(),resolveMany: vi.fn(),diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsxindex 7bf586fec1..7f6ba5302a 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.browser.test.tsx@@ -11,7 +11,7 @@ import { DEFAULT_PREFERENCES, getWorkbenchPreferences, patchWorkbenchPreferencesimport { act, createRef, useImperativeHandle } 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 { RequestDeletionConfirmation } from './useDeletionConfirmation';@@ -62,6 +62,7 @@ vi.mock('react-i18next', () => ({'widgets.gallery.deleteInUse.surface.workflow': `Workflow “${String(values?.name)}”`,'widgets.gallery.deleteInUse.unchecked': 'Other projects couldn’t be checked.','widgets.gallery.deleteInUse.itemCount': count === 1 ? '1 item' : `${count} items`,+ 'widgets.gallery.deleteInUse.itemCountAtLeast': count === 1 ? 'at least 1 item' : `at least ${count} items`,'widgets.gallery.deleteInUse.warning':count === 1? 'Work that uses it will point at missing media.'@@ -229,7 +230,8 @@ describe('useDeletionConfirmation', () => {{ count: 1, label: 'Upscale pass', surface: 'workflow' },],},- { count: 1, kind: 'projectUnchecked', name: 'Harbor Tower' },+ // A batched check could not name all of its uses.+ { count: 1, countAtLeast: true, kind: 'projectUnchecked', name: 'Harbor Tower' },// Open in this tab, its saved version unread: what it uses here, and a note.{ count: 1, kind: 'project', name: 'Atlas', savedCopyUnchecked: true, surfaces: [] },{ count: 1, kind: 'workflow', name: 'Portraits' },@@ -258,7 +260,7 @@ describe('useDeletionConfirmation', () => {'Canvas raster layers · 1 item','Workflow “Upscale pass” · 2 items','Workflow “Upscale pass” · 1 item',- 'Project “Harbor Tower” · 1 item',+ 'Project “Harbor Tower” · at least 1 item','Project “Atlas” · 1 item','Library workflow “Portraits” · 1 item','2 queued or running jobs · 1 item',@@ -278,6 +280,56 @@ describe('useDeletionConfirmation', () => {consoleError.mockRestore();});+ it('sits centred in the window like other confirmations, and a report taller than the window scrolls', async () => {+ let settleCheck: (report: GalleryMediaUsageReport) => void = () => {};+ const checkUsage = () =>+ new Promise<GalleryMediaUsageReport>((resolve) => {+ settleCheck = resolve;+ });+ // Once the enter animation is over, so its transform does not shift the box.+ const settledBox = async () => {+ const dialog = openDialog()!;+ await Promise.all(dialog.getAnimations().map((animation) => animation.finished));+ return dialog.getBoundingClientRect();+ };+ const verticalOffset = (box: DOMRect) => (box.top + box.bottom) / 2 - window.innerHeight / 2;++ const original = { height: window.innerHeight, width: window.innerWidth };++ try {+ await page.viewport(1000, 700);+ await act(() => {+ void confirmationRef.current!.requestDeletionConfirmation(imageRefs, async () => {}, { checkUsage });+ });++ expect(Math.abs(verticalOffset(await settledBox()))).toBeLessThanOrEqual(1);++ await page.viewport(1000, 320);+ await act(() =>+ settleCheck(+ usageReport({+ groups: Array.from({ length: 12 }, (_, index) => ({+ count: 1,+ kind: 'workflow' as const,+ name: `Workflow ${index + 1}`,+ })),+ inUseCount: 1,+ })+ )+ );+ await vi.waitFor(() => expect(openDialog()?.querySelector('[role="group"]')).not.toBeNull(), REPORT_WAIT);++ // Taller than the window: its top stays reachable, and the rest scrolls into view.+ const tallBox = await settledBox();+ const positioner = openDialog()!.parentElement!;+ expect(tallBox.height).toBeGreaterThan(window.innerHeight);+ expect(tallBox.top).toBeGreaterThanOrEqual(0);+ expect(positioner.scrollHeight).toBeGreaterThan(positioner.clientHeight);+ } finally {+ await page.viewport(original.width, original.height);+ }+ });+it('warns when the check failed, offers Retry, and still offers the deletion', async () => {let settleRetry: (report: GalleryMediaUsageReport) => void = () => {};const checkUsage = vidiff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsxindex 6a361a41a3..96bcebd543 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useDeletionConfirmation.tsx@@ -341,8 +341,6 @@ export const useDeletionConfirmation = (): {confirmLabel={t('widgets.gallery.deleteConfirmLabel')}finalFocusEl={returnFocus ?? undefined}isOpen={pendingDeletion !== null}- // The usage report arrives after the dialog opens; anchored at the top, it grows the dialog downward.- placement="top"title={t(titleKey, { count: itemCount })}onClose={settlePendingDeletion}onConfirm={handleConfirm}diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsxindex ec4e0ef167..107e8c007c 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.browser.test.tsx@@ -97,6 +97,7 @@ const mocks = vi.hoisted(() => ({const preferences = vi.hoisted(() => ({ confirmImageDeletion: false }));vi.mock('@features/gallery', () => ({+ GALLERY_REQUEST_MAX_NAMES: 1000,galleryImages: {metadata: (...args: unknown[]) => mocks.imageMetadata(...args),resolve: (...args: unknown[]) => mocks.imageResolve(...args),@@ -274,7 +275,10 @@ vi.mock('react-i18next', () => ({if (key === 'widgets.gallery.itemActions.move.success') {return `Moved to ${String(values?.board)}`;}- if (key.startsWith('widgets.gallery.itemActions.undoStale.')) {+ if (+ key.startsWith('widgets.gallery.itemActions.undoStale.') ||+ key.startsWith('widgets.gallery.itemActions.download.')+ ) {return `${key}:${JSON.stringify(values)}`;}if (key.startsWith('widgets.gallery.itemActions.loadWorkflow.loadedLabel')) {@@ -1903,7 +1907,11 @@ describe('mixed item mutation outcomes', () => {expect(mocks.patchGalleryItemCaches.mock.invocationCallOrder[0]).toBeLessThan(mocks.itemDelete.mock.invocationCallOrder[0] ?? 0);- expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(1, ['video:gone.mp4', 'image:locked.png']);+ // A next image may follow the request, so an open comparison is kept until it settles.+ expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(1, ['video:gone.mp4', 'image:locked.png'], {+ keepComparisonForSuccessor: true,+ projectId: 'project-1',+ });expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();// The rollback restored every page's total, so the re-removal lowers them across the listing again.@@ -1913,7 +1921,10 @@ describe('mixed item mutation outcomes', () => {{ kind: 'delete', result },{ totals: 'listing' });- expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(2, ['video:gone.mp4']);+ expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(2, ['video:gone.mp4'], {+ keepComparisonForSuccessor: false,+ projectId: 'project-1',+ });expect(mocks.invalidateGallery).toHaveBeenCalledOnce();expect(mocks.notificationsAdd.mock.calls.length + mocks.reportError.mock.calls.length).toBe(1);});@@ -1975,7 +1986,10 @@ describe('total transport failure rollback', () => {});// The optimistic removal happened up front, before the transport was asked.- expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(1, ['image:gone.png']);+ expect(mocks.galleryRemoveItems).toHaveBeenNthCalledWith(1, ['image:gone.png'], {+ keepComparisonForSuccessor: true,+ projectId: 'project-1',+ });// Transport failures must roll back immediately; trailing invalidation may fail too.expect(mocks.patchGalleryItemCaches.mock.results[0]?.value).toHaveBeenCalledOnce();@@ -2316,6 +2330,39 @@ describe('primary successor after confirmed deletion', () => {expect(mocks.gallerySelectItem).toHaveBeenCalledWith(after, 'project-1');});+ it.each([+ ['keeps an open comparison for the next image when one follows', ['primary.png', 'after.png'], true],+ ['ends an open comparison when no next image follows', ['primary.png'], false],+ ] as const)('%s', async (_title, names, keepsComparison) => {+ const items = names.map((name) => galleryItem('image', name));+ const refs = items.map(({ kind, name }) => ({ kind, name }));+ currentItemActionContext = {+ filterIdentity: 'filter-a',+ items,+ loadOrderedRefs: () => Promise.resolve(refs),+ selectedItemKey: 'image:primary.png',+ };+ const store = modelGallerySelectionStore('image:primary.png');+ mocks.galleryRemoveItems.mockImplementation((itemKeys: GalleryItemKey[]) => store.remove(itemKeys));+ mocks.itemDelete.mockResolvedValue({+ affectedBoardIds: ['board-1'],+ failed: [],+ succeeded: [{ kind: 'image', name: 'primary.png' }],+ });++ await act(async () => {+ await getItemActions().deleteItems([{ kind: 'image', name: 'primary.png' }]);+ });++ // The confirmed removal tells the store whether the next image is about to be selected: deleting the shown image of+ // a comparison then shows the next one against the same comparison image, and otherwise ends the comparison.+ expect(mocks.galleryRemoveItems).toHaveBeenLastCalledWith(['image:primary.png'], {+ keepComparisonForSuccessor: keepsComparison,+ projectId: 'project-1',+ });+ expect(mocks.gallerySelectItem).toHaveBeenCalledTimes(keepsComparison ? 1 : 0);+ });+it('selects the successor beside a rejected item when the host has re-rendered without the primary', async () => {const primary = galleryItem('image', 'primary.png');const rejected = galleryItem('image', 'rejected.png');@@ -2612,7 +2659,10 @@ describe('primary successor after confirmed deletion', () => {await getItemActions().deleteItems(requested);});- expect(mocks.galleryRemoveItems).toHaveBeenCalledWith(['image:shared']);+ expect(mocks.galleryRemoveItems).toHaveBeenCalledWith(['image:shared'], {+ keepComparisonForSuccessor: true,+ projectId: 'project-1',+ });expect(mocks.gallerySetItemMultiSelection).toHaveBeenCalledWith(['image:failed.png', 'video:shared', 'image:successor.png'],successor,@@ -2752,6 +2802,72 @@ describe('mixed item downloads', () => {expect(mocks.downloadBlob).toHaveBeenCalledWith(expect.any(Blob), 'images.zip');});+ it('downloads a selection larger than one archive request takes as several archives', async () => {+ const imageNames = Array.from({ length: 2500 }, (_, index) => `image-${index}.png`);+ mocks.downloadArchive.mockImplementation(({ imageNames: archiveNames }: { imageNames: string[] }) =>+ Promise.resolve({ blob: new Blob(['archive']), fileName: `${archiveNames[0]}.zip` })+ );+ vi.stubGlobal('fetch', vi.fn());++ await act(async () => {+ await getItemActions().downloadItems(imageNames.map((name) => ({ kind: 'image', name })));+ });++ expect(mocks.downloadArchive.mock.calls.map(([request]) => request.imageNames)).toEqual([+ imageNames.slice(0, 1000),+ imageNames.slice(1000, 2000),+ imageNames.slice(2000),+ ]);+ expect(mocks.downloadBlob.mock.calls.map(([, name]) => name)).toEqual([+ 'image-0.png.zip',+ 'image-1000.png.zip',+ 'image-2000.png.zip',+ ]);+ expect(mocks.notificationsAdd.mock.calls.map(([notice]) => notice)).toEqual([+ {+ kind: 'info',+ message: 'widgets.gallery.itemActions.download.preparingArchives:{"count":3}',+ title: 'widgets.gallery.preparingDownload',+ },+ { kind: 'success', title: 'widgets.gallery.itemActions.download.successArchives:{"count":3}' },+ ]);+ });++ it('says nothing is being prepared in parts for a selection one archive holds', async () => {+ const imageNames = Array.from({ length: 1000 }, (_, index) => `image-${index}.png`);+ mocks.downloadArchive.mockResolvedValue({ blob: new Blob(['archive']), fileName: 'images.zip' });+ vi.stubGlobal('fetch', vi.fn());++ await act(async () => {+ await getItemActions().downloadItems(imageNames.map((name) => ({ kind: 'image', name })));+ });++ expect(mocks.downloadArchive).toHaveBeenCalledOnce();+ expect(mocks.notificationsAdd.mock.calls.map(([notice]) => notice)).toEqual([+ { kind: 'success', title: 'widgets.gallery.itemActions.download.success:{"count":1000}' },+ ]);+ });++ it('keeps preparing the later archives when a middle one fails, and reports the partial outcome', async () => {+ const imageNames = Array.from({ length: 2500 }, (_, index) => `image-${index}.png`);+ mocks.downloadArchive+ .mockResolvedValueOnce({ blob: new Blob(['first']), fileName: 'first.zip' })+ .mockRejectedValueOnce(new Error('archive failed'))+ .mockResolvedValueOnce({ blob: new Blob(['third']), fileName: 'third.zip' });+ vi.stubGlobal('fetch', vi.fn());++ await act(async () => {+ await getItemActions().downloadItems(imageNames.map((name) => ({ kind: 'image', name })));+ });++ expect(mocks.downloadArchive).toHaveBeenCalledTimes(3);+ expect(mocks.downloadBlob.mock.calls.map(([, name]) => name)).toEqual(['first.zip', 'third.zip']);+ expect(mocks.reportError).toHaveBeenCalledOnce();+ expect(mocks.reportError.mock.calls[0]?.[0]).toMatchObject({+ message: 'widgets.gallery.itemActions.download.partial:{"count":2500,"failed":1000,"succeeded":1500}',+ });+ });+it('downloads a single video from its protected full URL with its actual name', async () => {vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('video-one')));diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.tsindex b3ac9b735a..318d49ace3 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/useImageActions.ts@@ -6,6 +6,7 @@ import type { VideoConditioningRole } from '@features/video';import type { WorkbenchSnapshot } from '@workbench/workbenchStore';import {+ GALLERY_REQUEST_MAX_NAMES,galleryItemOrganization,galleryItems,galleryTransfers,@@ -371,7 +372,8 @@ export const useImageActions = ({const applyGalleryItemRemoval = (itemKeys: GalleryItemKey[]): GalleryWidgetKeySnapshotEntry[] => {const before = captureGalleryWidgetKeyValues(queries.getSnapshot().projects);- gallery.removeItems(itemKeys);+ // The request decides whether a next image is selected; until it settles an open comparison waits for it.+ gallery.removeItems(itemKeys, { keepComparisonForSuccessor: true, projectId });return diffGalleryWidgetKeyValues(before, queries.getSnapshot().projects);};@@ -581,7 +583,12 @@ export const useImageActions = ({{ kind: 'delete', result },{ totals: cachesRolledBack ? 'listing' : 'holder' });- gallery.removeItems(result.succeeded.map(toGalleryItemKey));+ // Deleting the shown image of a comparison shows the next image against the same comparison image; with no+ // next image, a comparison left without a selection ends here.+ gallery.removeItems(result.succeeded.map(toGalleryItemKey), {+ keepComparisonForSuccessor: successor !== null,+ projectId,+ });if (successor) {const failedKeys = new Set(result.failed.map(toGalleryItemKey));const retainedFailedKeys = items@@ -1022,25 +1029,39 @@ export const useImageActions = ({const loadedByKey = new Map(loadedItems.map((item) => [toGalleryItemKey(item), item]));const imageNames = items.filter((item) => item.kind === 'image').map((item) => item.name);const videoRefs = items.filter((item) => item.kind === 'video');+ // One archive request names at most the server's cap, so a larger selection downloads as several archives.+ const archiveCount = Math.ceil(imageNames.length / GALLERY_REQUEST_MAX_NAMES);let failedCount = 0;+ let savedFileCount = 0;let succeededCount = 0;- if (imageNames.length > 0) {+ if (archiveCount > 1) {+ notifications.add({+ kind: 'info',+ message: t('widgets.gallery.itemActions.download.preparingArchives', { count: archiveCount }),+ title: t('widgets.gallery.preparingDownload'),+ });+ }++ for (let offset = 0; offset < imageNames.length; offset += GALLERY_REQUEST_MAX_NAMES) {+ const archiveNames = imageNames.slice(offset, offset + GALLERY_REQUEST_MAX_NAMES);+try {const { blob, fileName } = await galleryTransfers.downloadArchive({- imageNames,+ imageNames: archiveNames,signal: owner.signal,});assertAccountScopeCurrent(owner);downloadBlob(blob, fileName);- succeededCount += imageNames.length;+ savedFileCount += 1;+ succeededCount += archiveNames.length;} catch {if (!isAccountScopeCurrent(owner)) {return;}- failedCount += imageNames.length;+ failedCount += archiveNames.length;}}@@ -1058,6 +1079,7 @@ export const useImageActions = ({assertAccountScopeCurrent(owner);downloadBlob(blob, item.name);+ savedFileCount += 1;succeededCount += 1;} catch {if (!isAccountScopeCurrent(owner)) {@@ -1080,9 +1102,9 @@ export const useImageActions = ({);} else {recordSuccess(- t('widgets.gallery.itemActions.download.success', {- count: succeededCount,- })+ archiveCount > 1+ ? t('widgets.gallery.itemActions.download.successArchives', { count: savedFileCount })+ : t('widgets.gallery.itemActions.download.success', { count: succeededCount }));}};diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.tsindex 5bc4eebf74..a444654ba3 100644--- a/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-actions/videoRecallRuntime.test.ts@@ -10,6 +10,7 @@ import { createWorkbenchStore } from '@workbench/workbenchStore';import { beforeEach, describe, expect, it, vi } from 'vitest';const galleryApi = vi.hoisted(() => ({+ GALLERY_REQUEST_MAX_NAMES: 1000,galleryImages: { metadata: vi.fn(), resolveMany: vi.fn() },galleryItems: { resolve: vi.fn() },galleryVideos: { workflow: vi.fn() },diff --git a/invokeai/frontend/webv2/src/workbench/invocation.ts b/invokeai/frontend/webv2/src/workbench/invocation.tsindex c83df7a238..7a82f92f33 100644--- a/invokeai/frontend/webv2/src/workbench/invocation.ts+++ b/invokeai/frontend/webv2/src/workbench/invocation.ts@@ -21,15 +21,17 @@ import {expandsDynamicPrompts,getEffectivePrompts,getGenerateInvocationIssues,+ getPromptDraftFromValues,isExternalTextOnlyCanvasModel,isGenerateModelConfig,isSupportedGenerateModel,NO_GENERATE_MODEL_ISSUE,normalizeGenerateSettings,normalizeGenerateWidgetValues,+ type ProjectPromptDraft,sanitizeBatchCount,} from '@features/generation/settings';-import { getUpscaleValidationReasons, normalizeUpscaleWidgetValues } from '@features/upscale';+import { getUpscaleValidationReasons, normalizeUpscaleWidgetValues, readsUpscalePrompt } from '@features/upscale';import { getVideoWidgetValidationReasons, normalizeVideoWidgetValues } from '@features/video';import { getProjectGraphReadiness } from '@features/workflow/graph';import { getInvocationTemplatesSnapshot } from '@features/workflow/react';@@ -53,23 +55,31 @@ import { getActiveProjectGraph } from './projectWorkflows';import { getWorkbenchPreferences } from './settings/store';import { getProjectWidgetValues } from './widgetState';+/** Upscale's Refine prompt is the draft it shares with Generate; Model only reads no prompt. */+const getUpscalePromptDraft = (project: Project): ProjectPromptDraft | null =>+ readsUpscalePrompt(getProjectWidgetValues(project, 'upscale'))+ ? getPromptDraftFromValues(getProjectWidgetValues(project, 'generate'))+ : null;+/*** What the route's positive prompt expands from, with the sample seed to draw with, or null when the route sends its- * prompt as typed: Upscale and workflows never expand, and dynamic prompts may be off or the prompt plain. Canvas- * expands Generate's prompt.+ * prompt as typed: workflows and Model only upscales never expand, and dynamic prompts may be off or the prompt plain.+ * Canvas and Upscale expand Generate's prompt.*/export const getDynamicPromptsExpansionSource = (project: Project,sourceId: InvocationSourceId): (DynamicPromptsExpansionSource & { sampleSeed: number }) | null => {- if (sourceId === 'upscale' || sourceId === 'workflow') {+ if (sourceId === 'workflow') {return null;}const settings =sourceId === 'video'? normalizeVideoWidgetValues(getProjectWidgetValues(project, 'video'))- : normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));+ : sourceId === 'upscale'+ ? getUpscalePromptDraft(project)+ : normalizeGenerateSettings(getProjectWidgetValues(project, 'generate'));if (!settings) {return null;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.browser.test.tsxindex 7333e20635..f7044d6b11 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/Launchpad.browser.test.tsx@@ -1,4 +1,5 @@/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop */+import type * as SessionModule from '@features/identity/session';import type { ModelConfig } from '@features/models/core/types';import type * as ModelsApi from '@features/models/data/api';import type * as openProjects from '@workbench/projects/openProjects';@@ -37,6 +38,19 @@ vi.mock('@features/identity', async (importOriginal) => ({UsersPage: () => null,}));vi.mock('@features/identity/launchpad', () => ({ UsersPage: () => null }));+/** Single-user unless a test signs someone in. */+const auth = vi.hoisted(() => ({ session: null as SessionModule.AuthSession | null }));+vi.mock('@features/identity/session', async (importOriginal) => {+ const original = await importOriginal<typeof SessionModule>();++ return {+ ...original,+ useAuthSession: () => {+ const session = original.useAuthSession();+ return auth.session ?? session;+ },+ };+});vi.mock('@features/intermediates', () => ({ INTERMEDIATES_SETTING_ID: 'x', requestIntermediatesFocus: () => {} }));vi.mock('@features/fonts/launchpad', () => ({ FontsPage: () => null }));vi.mock('@features/nodes', () => ({ NodesPage: () => null }));@@ -129,6 +143,7 @@ const render = async () => {};const rail = () => page.getByRole('navigation', { name: 'launchpad.sectionsLabel' });+const rect = (element: Element) => element.getBoundingClientRect();const row = (key: string) => document.querySelector<HTMLElement>(`[data-list-row="${key}"] [data-list-primary]`)!;@@ -160,6 +175,7 @@ beforeEach(() => {afterEach(async () => {projects.open = ['one', 'two'];+ auth.session = null;await act(() => root.unmount());queryClient.clear();host.remove();@@ -232,6 +248,89 @@ describe('Launchpad shell', () => {await expect.element(page.getByRole('button', { name: 'launchpad.help.label' })).toHaveFocus();});+ it('puts the signed-in account at the foot of the rail and opens its menu beside it', async () => {+ const name = 'Maximiliana Bartholomew-Featherstonehaugh of the Very Long Name';+ auth.session = {+ accountEpoch: 1,+ expiredUserId: null,+ multiuserEnabled: true,+ phase: 'ready',+ sessionExpired: false,+ setupRequired: false,+ strictPasswordChecking: false,+ switchingAccount: false,+ user: {+ created_at: '2026-01-01T00:00:00Z',+ display_name: name,+ email: '[email protected]',+ is_active: true,+ is_admin: true,+ last_login_at: null,+ updated_at: '2026-01-01T00:00:00Z',+ user_id: 'max',+ },+ };+ // The row is named by its lines, the icon-only button by its label; both start from the name.+ const account = page.getByRole('button', { name: new RegExp(name) });+ const help = page.getByRole('button', { name: 'launchpad.help.label' });+ await page.viewport(1280, 900);+ await render();++ // Last in the rail, after Help, in both tab and visual order; a long name truncates rather than widening the rail.+ await expect.element(account).toBeVisible();+ expect(rail().element().contains(account.element())).toBe(true);+ expect(help.element().compareDocumentPosition(account.element()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(rect(account.element()).top).toBeGreaterThan(rect(help.element()).bottom);+ expect(rect(rail().element()).width).toBe(224);+ expect(rect(account.element()).right).toBeLessThanOrEqual(rect(rail().element()).right);+ // The name truncates inside the row, which keeps its chevron; the email shows under it.+ const [nameLine, emailLine] = account.element().querySelectorAll('p');+ expect(nameLine!.textContent).toBe(name);+ expect(nameLine!.scrollWidth).toBeGreaterThan(nameLine!.clientWidth);+ expect(emailLine!.textContent).toBe('[email protected]');+ const chevron = [...account.element().querySelectorAll('svg')].at(-1)!;+ expect(rect(chevron).right).toBeLessThanOrEqual(rect(account.element()).right);+ expect(rect(chevron).left).toBeGreaterThan(rect(nameLine!).right);+ expect(rail().element().querySelectorAll('[role="separator"]')).toHaveLength(1);+ expect(await auditAccessibility(rail().element())).toEqual([]);++ await account.click();+ const menu = page.getByRole('menu');+ await expect.element(page.getByRole('menuitem', { name: 'auth.accountSettings' })).toBeVisible();+ // Beside the trigger, as Help's menu opens, and inside the window whatever the name's length.+ expect(rect(menu.element()).left).toBeGreaterThan(rect(account.element()).right);+ expect(rect(menu.element()).bottom).toBeLessThanOrEqual(innerHeight);+ expect(await auditAccessibility(menu.element())).toEqual([]);+ await page.getByRole('menuitem', { name: 'users.manageUsers' }).click();+ await expect+ .element(page.getByRole('link', { name: 'launchpad.sections.users' }))+ .toHaveAttribute('aria-current', 'page');++ // The icon rail names the avatar with a tooltip, which leaves once the menu opens.+ await page.viewport(720, 450);+ await expect.poll(() => rect(rail().element()).width).toBeLessThan(64);+ expect(await auditAccessibility(rail().element())).toEqual([]);+ await account.hover();+ await expect.element(page.getByRole('tooltip')).toHaveTextContent(name);+ await account.click();+ await expect.element(page.getByRole('menuitem', { name: 'auth.signOut' })).toBeVisible();+ await expect+ .poll(() => [...document.querySelectorAll('[role="tooltip"]')].some((tip) => tip.checkVisibility()))+ .toBe(false);+ expect(rect(menu.element()).bottom).toBeLessThanOrEqual(innerHeight);+ await userEvent.keyboard('{Escape}');+ await expect.element(account).toHaveFocus();+ });++ it('keeps the rail free of an account row and its separator in single-user mode', async () => {+ await page.viewport(1280, 900);+ await render();++ await expect.element(page.getByRole('button', { name: 'launchpad.help.label' })).toBeVisible();+ expect(rail().element().querySelector('[data-scope="avatar"]')).toBeNull();+ expect(rail().element().querySelectorAll('[role="separator"]')).toHaveLength(0);+ });+it('squeezes the open projects list to one entry before the rail scrolls', async () => {projects.open = ['one', 'two', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8'];const viewportOf = (element: Element) => element.closest('[data-scope="scroll-area"][data-part="viewport"]')!;diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsxindex 413a32a319..8840079b4a 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadNav.tsx@@ -2,6 +2,7 @@ import type { SystemStyleObject } from '@chakra-ui/react';import type { LucideIcon } from 'lucide-react';import { Box, Icon, Separator, Stack, Text, VisuallyHidden } from '@chakra-ui/react';+import { AccountMenu, useHasAccountMenu } from '@features/identity';import { Button, IconButton } from '@platform/ui/Button';import { Scrollable } from '@platform/ui/Scrollable';import { Tooltip } from '@platform/ui/Tooltip';@@ -30,7 +31,8 @@ const TOOLTIP_PLACEMENT = 'right';/*** Sections are routes, so the rail is route links in visual order: Workspace, the open projects, Manage, then the- * footer (Preferences, then the What's New and Help actions). Tab and reading order follow what the rail shows.+ * footer (Preferences, then the What's New and Help actions, then the signed-in account in multi-user mode). Tab and+ * reading order follow what the rail shows.*/export type LaunchpadNavGroupId = 'workspace' | 'manage' | 'footer';@@ -182,6 +184,7 @@ export const LaunchpadNav = ({ activeId, items }: { activeId: string; items: Lau// Show headings only when multiple groups need distinguishing.const showGroupLabels = workspaceItems.length > 0 && manageItems.length > 0;const compact = useSyncExternalStore(subscribeCompact, getCompact);+ const hasAccount = useHasAccountMenu();return (// The landmark wraps the scroll area: Zag gives the area's root a presentation role.@@ -226,6 +229,12 @@ export const LaunchpadNav = ({ activeId, items }: { activeId: string; items: Lau))}<WhatsNewButton compact={compact} /><HelpMenu compact={compact} />+ {hasAccount ? (+ <>+ <Separator my={compact ? '1' : '1.5'} />+ <AccountMenu compact={compact} />+ </>+ ) : null}</Stack></Scrollable></Box>diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsxindex a0480e2518..e3c4db6dcf 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/LaunchpadTopBar.tsx@@ -1,7 +1,6 @@import type { BackendConnectionStatus } from '@platform/transport/types';import { Badge, Box, Flex, HStack, Text } from '@chakra-ui/react';-import { AccountMenu } from '@features/identity';import { useConnectionStatusSelector } from '@platform/transport/connectionStore';import { InvokeMark } from '@platform/ui/InvokeMark';import { PaletteButton } from '@workbench/palette/PaletteButton';@@ -48,10 +47,7 @@ export const LaunchpadTopBar = () => (</HStack><HStack gap="2"><ConnectionChip />- <HStack gap="0.5">- <PaletteButton />- <AccountMenu />- </HStack>+ <PaletteButton /></HStack></Flex>);diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCard.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCard.tsxindex f0551f0e3f..d3c315edfd 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCard.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectCard.tsx@@ -23,6 +23,8 @@ import { ProjectCover } from './ProjectCover';const CARD_HOVER = { bg: 'bg.muted', borderColor: 'border.emphasized' } as const;const REVEAL_ON_HOVER = { opacity: 1 } as const;+// The pin sits on the cover, so it carries its own scrim and edge: a tint alone vanishes on a light image.+const PIN_HOVER = { bg: 'bg' } as const;// The card clips its overlay link's own outline, so the card draws the keyboard focus ring around itself.const LINK_STYLE = { cursor: 'default', inset: 0, outline: 'none', position: 'absolute' } as const;const CARD_FOCUS_RING = {@@ -95,12 +97,16 @@ export const ProjectCard = ({<IconButtonaria-label={pinLabel}aria-pressed={isPinned}+ bg="bg/85"+ borderColor="border.subtle"color={isPinned ? 'fg' : 'fg.muted'}opacity={isPinned ? 1 : 0}+ shadow="xs"size="sm"- variant="subtle"+ variant="outline"_focusVisible={REVEAL_ON_HOVER}_groupHover={REVEAL_ON_HOVER}+ _hover={PIN_HOVER}onClick={handleTogglePin}><Icon as={PinIcon} boxSize="3" fill={isPinned ? 'currentColor' : 'none'} />diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectRow.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectRow.tsxindex 9a6975e29f..9a3c1b82b8 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectRow.tsx@@ -70,7 +70,8 @@ export const ProjectRow = ({<Box flexShrink={0} overflow="hidden" pointerEvents="none" rounded="sm" w={THUMBNAIL_WIDTH}><ProjectCover coverUrl={summary.coverUrl} /></Box>- <Flex flex="1" gap="3" minW="0" pointerEvents="none">+ {/* Centred: the smaller timestamp would otherwise sit at the top of the name's taller line. */}+ <Flex align="center" flex="1" gap="3" minW="0" pointerEvents="none"><MiddleTruncate flex="1" fontSize="md" fontWeight="600" minW="0" text={summary.name} /><ProjectCompatibilityBadge summary={summary} /><Text color="fg.muted" flexShrink={0} fontSize="xs">diff --git a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.tsx b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.tsxindex 64bfb4fe27..7f2351da0b 100644--- a/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.tsx+++ b/invokeai/frontend/webv2/src/workbench/launchpad/projects/ProjectsToolbar.tsx@@ -133,7 +133,7 @@ export const ProjectsToolbar = ({</Menu.ItemGroupLabel>{PROJECT_SORT_IDS.map((id) => (<Menu.Item key={id} value={id}>- <Icon as={CheckIcon} boxSize="3.5" opacity={id === sort ? 1 : 0} />+ <Icon as={CheckIcon} boxSize="3.5" color="fg" opacity={id === sort ? 1 : 0} /><Menu.ItemText>{t(SORT_LABEL_KEY[id])}</Menu.ItemText></Menu.Item>))}diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.tsindex 6602bd9eca..797730ac26 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts@@ -36,7 +36,7 @@ describe('built-in layout preset descriptors', () => {defaultKeys: ['alt+2'],defaultRoute: { destination: 'canvas', sourceId: 'canvas' },hotkeyId: 'selectEditPreset',- iconId: 'layers',+ iconId: 'pencil-ruler',label: 'Edit',presetId: 'edit',},diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.tsindex c600d09dd0..eba534fb0e 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts@@ -193,7 +193,7 @@ export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [defaultRoute: { destination: 'canvas', sourceId: 'canvas' },hotkeyId: 'selectEditPreset',id: 'edit',- iconId: 'layers',+ iconId: 'pencil-ruler',label: BUILT_IN_LAYOUT_PRESET_LABELS.edit,panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },widgetRegions: {diff --git a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.jsonindex 7f2b3d99ce..1eac063e72 100644--- a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json+++ b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json@@ -22,7 +22,7 @@{"s":"users-guide/image-generation/advanced-topics/hidiffusion","t":"HiDiffusion","c":1,"h":[["where-to-find-the-switches","Where to find the switches"],["what-the-switches-do","What the switches do"],["manual-ratio-constraint","Manual ratio constraint"],["tips","Tips"]]},{"s":"users-guide/image-generation/advanced-topics/pid-decode","t":"PiD Super-Resolution Decode","c":1,"h":[["supported-models","Supported models"],["what-you-need-to-install","What you need to install"],["enabling-pid","Enabling PiD"],["running-pid-on-an-existing-image","Running PiD on an existing image"],["tips--limitations","Tips & limitations"]]},{"s":"users-guide/image-generation/advanced-topics/tiny-autoencoder-previews","t":"Tiny AutoEncoder Previews","c":1,"h":[["enabling-tae-previews","Enabling TAE previews"],["cost-and-fallback","Cost and fallback"],["running-the-decoder-on-the-cpu","Running the decoder on the CPU"]]},-{"s":"users-guide/image-generation/generate-panel","t":"Generate Panel Reference","d":"Every section of the Generate panel in detail — size, render settings, negative prompts, advanced options, resetting to defaults, concepts, reference images and the prompt tools.","c":1,"h":[["setting-the-image-size","Setting the image size"],["render-settings","Render settings"],["steps","Steps"],["cfg-and-guidance","CFG and Guidance"],["scheduler","Scheduler"],["seed","Seed"],["model-specific-options","Model-specific options"],["negative-prompt","Negative prompt"],["refiner","Refiner"],["advanced-settings","Advanced settings"],["resetting-to-defaults","Resetting to defaults"],["adding-concepts","Adding concepts"],["adding-reference-images","Adding reference images"],["prompt-tools","Prompt tools"],["prompt-enhancement","Prompt enhancement"],["image-to-prompt","Image to prompt"],["prompt-history","Prompt history"],["more-prompting-features","More prompting features"]]},+{"s":"users-guide/image-generation/generate-panel","t":"Generate Panel Reference","d":"Every section of the Generate panel in detail — size, render settings, negative prompts, advanced options, resetting to defaults, concepts, reference images and the prompt tools.","c":1,"h":[["working-with-sections","Working with sections"],["setting-the-image-size","Setting the image size"],["render-settings","Render settings"],["steps","Steps"],["cfg-and-guidance","CFG and Guidance"],["scheduler","Scheduler"],["seed","Seed"],["model-specific-options","Model-specific options"],["negative-prompt","Negative prompt"],["refiner","Refiner"],["advanced-settings","Advanced settings"],["resetting-to-defaults","Resetting to defaults"],["adding-concepts","Adding concepts"],["adding-reference-images","Adding reference images"],["prompt-tools","Prompt tools"],["prompt-enhancement","Prompt enhancement"],["image-to-prompt","Image to prompt"],["prompt-history","Prompt history"],["more-prompting-features","More prompting features"]]},{"s":"users-guide/image-generation/image-generation","t":"Concepts and Terms","d":"A short glossary of the ideas and terms you meet when generating images — models, prompts, steps, CFG, schedulers, seeds, latents, LoRAs, ControlNets and more — with links to the guides that cover them.","c":1,"h":[["how-an-image-is-made","How an image is made"],["glossary","Glossary"],["learn-more","Learn more"]]},{"s":"users-guide/image-generation/intermediates","t":"Intermediates","d":"Reclaim disk space by deleting the temporary images and videos generation leaves behind, per project and per account.","c":1,"h":[["the-intermediates-section","The Intermediates section"],["clean-up","Clean up"],["what-a-normal-delete-always-keeps","What a normal delete always keeps"],["permissions","Permissions"],["limits-and-edge-cases","Limits and edge cases"]]},{"s":"users-guide/image-generation/introduction","t":"Generating and modifying still images","d":"Get started with the Generate panel — choose a model, write a prompt, generate a first image, and send results to the Gallery or the Canvas.","c":1,"h":[["selecting-a-model","Selecting a model"],["model-components","Model components"],["your-first-image","Your first image"],["routing-images-to-the-gallery-or-the-canvas","Routing images to the Gallery or the Canvas"],["going-further","Going further"]]},@@ -38,7 +38,7 @@{"s":"users-guide/video-generation/minimax-h3","t":"MiniMax H3","c":1,"h":[["the-h3-models","The H3 Models"]]},{"s":"users-guide/video-generation/video-workflows","t":"Video Workflows","d":"A plain-language guide to the ready-made Wan 2.2, MiniMax H3 and LTX-2 video workflows that ship with InvokeAI — which one to pick, and how to run it.","c":1,"h":[["before-you-start","Before you start"],["which-workflow-should-i-use","Which workflow should I use?"],["bundled-wan-22-workflows","Bundled Wan 2.2 workflows"],["text-to-video","Text to Video"],["image-to-video","Image to Video"],["interpolate-between-two-images","Interpolate Between Two Images"],["extend-video","Extend Video"],["bundled-minimax-h3-workflows","Bundled MiniMax H3 workflows"],["bundled-ltx-2-workflows","Bundled LTX-2 workflows"],["running-a-workflow","Running a workflow"],["which-one-fits-my-gpu","Which one fits my GPU?"],["going-further","Going further"]]},{"s":"users-guide/video-generation/wan-22","t":"Wan 2.2","c":1,"h":[["license","License"],["the-wan-models","The Wan Models"]]},-{"s":"users-guide/workbench/hotkeys","t":"Keyboard shortcuts","d":"Every default keyboard shortcut in Invoke, where each one works, and how to change, add, disable or reset shortcuts in Settings.","c":1,"h":[["where-shortcuts-work","Where shortcuts work"],["changing-shortcuts","Changing shortcuts"],["app","App"],["layout-and-focus","Layout and focus"],["canvas","Canvas"],["tools-and-colors","Tools and colors"],["layers-and-selection","Layers and selection"],["frame-and-view","Frame and view"],["staging-bar","Staging bar"],["workflows","Workflows"],["viewer","Viewer"],["gallery","Gallery"],["image-map","Image Map"]]},+{"s":"users-guide/workbench/hotkeys","t":"Keyboard shortcuts","d":"Every default keyboard shortcut in Invoke, where each one works, and how to change, add, disable or reset shortcuts in Settings.","c":1,"h":[["where-shortcuts-work","Where shortcuts work"],["changing-shortcuts","Changing shortcuts"],["app","App"],["layout-and-focus","Layout and focus"],["canvas","Canvas"],["tools-and-colors","Tools and colors"],["layers-and-selection","Layers and selection"],["frame-and-view","Frame and view"],["staging-bar","Staging bar"],["workflows","Workflows"],["viewer","Viewer"],["gallery","Gallery"],["queue","Queue"],["image-map","Image Map"]]},{"s":"users-guide/workbench/introduction","t":"Guided tour","d":"How the Invoke workbench is laid out, how to arrange panels in the rails and the center, and how to save favourite arrangements as layout presets.","c":1,"h":[["the-parts-of-the-workbench","The parts of the workbench"],["rails-and-side-panels","Rails and side panels"],["the-center-panel","The center panel"],["the-status-bar-and-bottom-panel","The status bar and bottom panel"],["floating-windows","Floating windows"],["when-invoke-is-blocked","When Invoke is blocked"],["arranging-panels","Arranging panels"],["available-panels","Available panels"],["adding-and-removing-panels","Adding and removing panels"],["moving-panels-between-rails","Moving panels between rails"],["layout-shortcuts","Layout shortcuts"],["layout-presets","Layout presets"],["built-in-presets","Built-in presets"],["switching-presets","Switching presets"],["changing-a-preset","Changing a preset"],["creating-your-own-preset","Creating your own preset"],["managing-presets","Managing presets"],["what-is-saved-where","What is saved where"],["tips","Tips"]]},{"s":"users-guide/workflows/comfyui-migration","t":"ComfyUI Migration","c":1,"h":[["node-equivalents","Node Equivalents"],["sampling","Sampling"],["loaders","Loaders"],["conditioning","Conditioning"],["latent","Latent"],["image","Image"],["mask","Mask"],["advanced","Advanced"]]},{"s":"users-guide/workflows/community-nodes","t":"Community Nodes","d":"Node packs written by the InvokeAI community, and how to install them with the Nodes manager or Git.","c":1,"h":[["install-a-node-pack","Install a node pack"],["browse-node-packs","Browse node packs"],["add-your-node-pack","Add your node pack"]]},diff --git a/invokeai/frontend/webv2/src/workbench/palette/entries.ts b/invokeai/frontend/webv2/src/workbench/palette/entries.tsindex e4eca2b9dd..43d7349f9c 100644--- a/invokeai/frontend/webv2/src/workbench/palette/entries.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/entries.ts@@ -206,6 +206,8 @@ const PALETTE_HIDDEN_COMMANDS = new Set(['gallery.moveFocusRight','gallery.moveFocusUp','gallery.toggleFocusedInSelection',+ // Acts on the focused queue row, which the palette has taken focus from.+ 'queue.recallAll','viewer.nextItem','viewer.previousItem',]);diff --git a/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts b/invokeai/frontend/webv2/src/workbench/palette/paletteStore.tsindex 53649c88fb..8d17cb5677 100644--- a/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts+++ b/invokeai/frontend/webv2/src/workbench/palette/paletteStore.ts@@ -23,22 +23,23 @@ registerAccountOwnedResource({name: 'command-palette',});-const captureReturnFocusElement = (): void => {- const activeElement = document.activeElement;-- returnFocusElement = activeElement instanceof HTMLElement ? activeElement : null;-};-export const getCommandPaletteReturnFocusElement = (): HTMLElement | null =>returnFocusElement?.isConnected ? returnFocusElement : null;-export const openCommandPalette = (): void => {+/**+ * Closing focuses `returnFocus`, for a control that is gone by then (a menu item), or else whatever had focus when the+ * palette opened.+ */+export const openCommandPaletteFrom = (returnFocus: HTMLElement | null): void => {if (!commandPaletteStore.getSnapshot().isOpen) {- captureReturnFocusElement();+ const target = returnFocus ?? document.activeElement;+ returnFocusElement = target instanceof HTMLElement ? target : null;}commandPaletteStore.setSnapshot({ isOpen: true });};+export const openCommandPalette = (): void => openCommandPaletteFrom(null);+export const closeCommandPalette = (): void => {commandPaletteStore.setSnapshot({ isOpen: false });};diff --git a/invokeai/frontend/webv2/src/workbench/projectContracts.ts b/invokeai/frontend/webv2/src/workbench/projectContracts.tsindex ed5234a214..1ded161842 100644--- a/invokeai/frontend/webv2/src/workbench/projectContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/projectContracts.ts@@ -93,6 +93,15 @@ export interface WorkbenchState {widgetFailures: WidgetFailure[];/** Mirror of the user's `WorkbenchPreferences.scopedDefaults`: reads resolve pins over defaults in one snapshot. */scopedDefaults: ScopedDefaults;+ /**+ * Canvas staging Auto-switch's follow state, by open project: the placeholders that have shown a frame of their own+ * (the reducer hears each first frame once) and the generating slot the user picked, which Auto-switch keeps shown+ * over newer slots (`pickAutoSwitch`). Transient, as Preview's follow state is: never persisted, synced across tabs+ * or undone; entries go with their placeholders and with closed projects.+ */+ canvasStagingFollow?: Readonly<+ Record<string, { readonly framedSlotIds: readonly string[]; readonly pinnedSlotId: string | null }>+ >;}export interface BackendConnectionState {diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.browser.test.tsxnew file mode 100644index 0000000000..852c8a0b79--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.browser.test.tsx@@ -0,0 +1,279 @@+import type * as apiModule from '@workbench/projects/api';+import type { ProjectSummaryDTO } from '@workbench/projects/api';++import { ChakraProvider } from '@chakra-ui/react';+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';+import { system } from '@theme/system';+import { MAX_SUPPORTED_CANVAS_SCHEMA_VERSION } from '@workbench/canvasSchemaVersion';+import { seedProjectLibrary } from '@workbench/projects/library';+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';++const harness = vi.hoisted(() => ({+ hydrate: vi.fn(),+ listProjects: vi.fn(),+ notifyError: vi.fn(),+ open: vi.fn(),+ openProjectIds: [] as string[],+}));++// The project library is real; only its HTTP listing (and the cover index it reads alongside) is replaced.+vi.mock('@workbench/projects/api', async (importOriginal) => ({+ ...(await importOriginal<typeof apiModule>()),+ getClientStateValue: () => Promise.resolve(null),+ listProjects: harness.listProjects,+}));+vi.mock('@workbench/WorkbenchContext', () => ({+ useWorkbenchCommands: () => ({ projects: { open: harness.open } }),+ useWorkbenchPersistenceService: () => ({ adoptProjectRecord: vi.fn(), hydrateProjectFromServer: harness.hydrate }),+ useWorkbenchSelector: <T,>(selector: (snapshot: { projects: { id: string }[] }) => T) =>+ selector({ projects: harness.openProjectIds.map((id) => ({ id })) }),+}));+vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: harness.notifyError }) }));+vi.mock('@workbench/projects/useProjectFileActions', () => ({ useImportProjectFile: () => vi.fn() }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++import { OpenProjectDialog } from './OpenProjectDialog';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const dto = (id: string, name: string, updatedAt: string, minimumCanvasSchemaVersion = 3): ProjectSummaryDTO => ({+ board_id: `board-${id}`,+ created_at: '2026-10-01T08:00:00.000Z',+ minimum_canvas_schema_version: minimumCanvasSchemaVersion,+ minimum_document_schema_version: 3,+ name,+ project_id: id,+ revision: 1,+ updated_at: updatedAt,+ workspace_updated_at: null,+});++// Listed most recently edited first.+const harbor = dto('harbor', 'Harbor Tower', '2026-10-30T08:00:00.000Z');+const mahogany = dto('mahogany', 'Mahogany House', '2026-10-29T08:00:00.000Z');+const site = dto('site', 'Site plan', '2026-10-28T08:00:00.000Z');+const future = dto('future', 'From the future', '2026-10-31T08:00:00.000Z', MAX_SUPPORTED_CANVAS_SCHEMA_VERSION + 1);++const onClose = vi.fn();+let host: HTMLDivElement;+let root: Root;++/** Opens the dialog, whose mount refreshes the library from `listProjects`, and lets that listing settle. */+const render = async () => {+ await act(async () => {+ root.render(+ <ChakraProvider value={system}>+ <OpenProjectDialog isOpen onClose={onClose} />+ </ChakraProvider>+ );+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });+ });+};++const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]')!;+const list = () => dialog().querySelector<HTMLElement>('[role="list"]');+const buttonNamed = (label: string) =>+ [...dialog().querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === label)!;+const rowNamed = (name: string) =>+ [...dialog().querySelectorAll<HTMLElement>('[role="listitem"]')].find((row) => row.textContent?.includes(name))!;+const primaryOf = (name: string) => rowNamed(name).querySelector<HTMLButtonElement>('[data-list-primary]')!;++beforeEach(() => {+ accountLifecycle.activate('open-project-dialog-browser-test');+ harness.hydrate.mockReset();+ harness.hydrate.mockImplementation((id: string) => Promise.resolve({ project: { id }, status: 'loaded' }));+ harness.listProjects.mockReset();+ harness.notifyError.mockReset();+ harness.open.mockReset();+ harness.openProjectIds = [];+ onClose.mockReset();+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root.unmount());+ accountLifecycle.invalidate();+ host.remove();+});++describe('OpenProjectDialog', () => {+ it('lists the projects not already open as list items with a divider between each pair', async () => {+ harness.openProjectIds = ['mahogany'];+ harness.listProjects.mockResolvedValue([harbor, mahogany, future, site]);+ await render();++ expect(list()?.getAttribute('aria-label')).toBe('projects.openProject');+ const rows = [...list()!.querySelectorAll('[role="listitem"]')];++ expect(rows.map((row) => row.querySelector('[data-list-primary]')?.textContent)).toEqual([+ expect.stringContaining('From the future'),+ expect.stringContaining('Harbor Tower'),+ expect.stringContaining('Site plan'),+ ]);+ expect(rows.every((row) => row.textContent?.includes('projects.editedRelative'))).toBe(true);+ expect(list()!.querySelectorAll('[data-list-divider]')).toHaveLength(rows.length - 1);+ });++ it('opens a project by click and closes once it is loaded', async () => {+ harness.listProjects.mockResolvedValue([harbor, mahogany]);+ await render();++ await userEvent.click(primaryOf('Mahogany House'));++ expect(harness.hydrate).toHaveBeenCalledWith('mahogany', 'Mahogany House');+ expect(harness.open).toHaveBeenCalledWith({ id: 'mahogany' });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('keeps one tab stop, moves between projects with the arrow keys, and opens with Enter', async () => {+ harness.listProjects.mockResolvedValue([harbor, mahogany]);+ await render();++ expect(primaryOf('Harbor Tower').tabIndex).toBe(0);+ expect(primaryOf('Mahogany House').tabIndex).toBe(-1);++ await act(() => primaryOf('Harbor Tower').focus());+ await userEvent.keyboard('{ArrowDown}');+ expect(document.activeElement).toBe(primaryOf('Mahogany House'));++ await userEvent.keyboard('{Enter}');+ expect(harness.hydrate).toHaveBeenCalledWith('mahogany', 'Mahogany House');+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it('starts keyboard users on the first openable project, keeping an incompatible one reachable but inert', async () => {+ harness.listProjects.mockResolvedValue([harbor, future]);+ await render();++ const incompatible = primaryOf('From the future');++ // The incompatible project is the most recent, so it is listed first; the tab stop skips it.+ expect(list()!.querySelector('[data-list-primary]')).toBe(incompatible);+ expect(primaryOf('Harbor Tower').tabIndex).toBe(0);+ expect(incompatible.tabIndex).toBe(-1);++ expect(incompatible.getAttribute('aria-disabled')).toBe('true');+ expect(incompatible.textContent).toContain('projects.requiresNewerInvoke');+ expect(incompatible.querySelector('svg')).toBeNull();+ expect(primaryOf('Harbor Tower').hasAttribute('aria-disabled')).toBe(false);+ expect(primaryOf('Harbor Tower').textContent).not.toContain('projects.requiresNewerInvoke');++ await act(() => primaryOf('Harbor Tower').focus());+ await userEvent.keyboard('{ArrowUp}');+ expect(document.activeElement).toBe(incompatible);++ await userEvent.keyboard('{Enter}');+ // Force past Playwright's actionability check: aria-disabled is exactly what is under test.+ await userEvent.click(incompatible, { force: true });+ expect(harness.hydrate).not.toHaveBeenCalled();+ expect(onClose).not.toHaveBeenCalled();+ });++ it('holds every row while one project opens, then reports an unavailable project without closing', async () => {+ let finish: (result: unknown) => void = () => undefined;+ harness.hydrate.mockImplementation(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ })+ );+ harness.listProjects.mockResolvedValue([harbor, mahogany]);+ await render();++ await userEvent.click(primaryOf('Harbor Tower'));++ expect(list()!.getAttribute('aria-busy')).toBe('true');+ expect(primaryOf('Harbor Tower').querySelector('.chakra-spinner')).not.toBeNull();+ expect(primaryOf('Mahogany House').querySelector('.chakra-spinner')).toBeNull();+ expect(primaryOf('Mahogany House').getAttribute('aria-disabled')).toBe('true');+ await userEvent.click(primaryOf('Mahogany House'), { force: true });+ expect(harness.hydrate).toHaveBeenCalledTimes(1);++ await act(async () => {+ finish({ status: 'unavailable' });+ await Promise.resolve();+ });++ expect(harness.notifyError).toHaveBeenCalledWith('projects.couldNotOpen', 'projects.couldNotOpenDescription');+ expect(onClose).not.toHaveBeenCalled();+ expect(list()!.hasAttribute('aria-busy')).toBe(false);+ expect(primaryOf('Harbor Tower').querySelector('.chakra-spinner')).toBeNull();+ });++ it('says why there is nothing to open: no saved projects, or all of them already open', async () => {+ harness.listProjects.mockResolvedValue([]);+ await render();++ expect(list()).toBeNull();+ expect(dialog().textContent).toContain('projects.noSavedProjects');++ harness.openProjectIds = ['harbor'];+ harness.listProjects.mockResolvedValue([harbor]);+ await act(() => root.unmount());+ root = createRoot(host);+ await render();++ expect(dialog().textContent).toContain('projects.allSavedAlreadyOpen');+ });++ it('shows loading before the first listing, then a failure whose retry lands focus on Import when nothing returns', async () => {+ let fail: (error: Error) => void = () => undefined;+ harness.listProjects.mockImplementation(+ () =>+ new Promise((_resolve, reject) => {+ fail = reject;+ })+ );+ await render();++ expect(dialog().querySelector('[role="status"]')?.getAttribute('aria-label')).toBe('common.loading');+ expect(dialog().textContent).not.toContain('projects.noSavedProjects');++ await act(async () => {+ fail(new Error('Server unavailable'));+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });+ });++ expect(dialog().textContent).toContain('projects.failedToLoad');+ expect(dialog().textContent).not.toContain('projects.noSavedProjects');++ harness.listProjects.mockResolvedValue([]);+ const retry = dialog().querySelector<HTMLButtonElement>('[role="alert"] button')!;+ await userEvent.click(retry);++ await expect.poll(() => dialog().textContent).toContain('projects.noSavedProjects');+ expect(harness.listProjects).toHaveBeenCalledTimes(2);+ await expect.poll(() => document.activeElement).toBe(buttonNamed('projects.importWithEllipsis'));+ });++ it('lands focus on the first openable project when a retry recovers', async () => {+ harness.listProjects.mockRejectedValue(new Error('Server unavailable'));+ await render();++ harness.listProjects.mockResolvedValue([future, harbor]);+ await userEvent.click(dialog().querySelector<HTMLButtonElement>('[role="alert"] button')!);++ await expect.poll(() => document.activeElement).toBe(primaryOf('Harbor Tower'));+ });++ it('keeps the projects listed earlier usable when a later refresh fails', async () => {+ seedProjectLibrary([harbor, mahogany], captureAccountScope());+ harness.listProjects.mockRejectedValue(new Error('Server unavailable'));+ await render();++ expect(harness.listProjects).toHaveBeenCalledTimes(1);+ expect(dialog().textContent).not.toContain('projects.failedToLoad');++ await userEvent.click(primaryOf('Mahogany House'));+ expect(harness.hydrate).toHaveBeenCalledWith('mahogany', 'Mahogany House');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsxindex d3dbaf1da0..6562b30cab 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/OpenProjectDialog.tsx@@ -1,6 +1,8 @@+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop -- List slots take JSX and callbacks; the React Compiler memoizes them. */+import type { ListRowProps } from '@platform/ui/list/List';import type { ProjectWithWorkspaceDTO } from '@workbench/projects/api';-import { Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';+import { Box, Icon, Portal, Spinner, Text } from '@chakra-ui/react';import { useMountEffect } from '@platform/react/useMountEffect';import {assertAccountScopeCurrent,@@ -9,12 +11,14 @@ import {} from '@platform/state/accountLifecycle';import { areArraysEqual } from '@platform/state/selectors';import { getApiErrorMessage } from '@platform/transport/http';-import { Button, CloseButton, Row, Scrollable } from '@platform/ui';+import { Button, CloseButton } from '@platform/ui/Button';import { Dialog } from '@platform/ui/Dialog';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { MIN_SUPPORTED_CANVAS_SCHEMA_VERSION } from '@workbench/canvasSchemaVersion';+import { getListContentHeight, List } from '@platform/ui/list/List';+import { ListItem } from '@platform/ui/list/ListItem';+import { listRowsFromItems } from '@platform/ui/list/listRows';import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';import { ProjectCompatibilityBadge } from '@workbench/launchpad/projects/ProjectCompatibilityBadge';+import { ProjectsLoadError } from '@workbench/launchpad/projects/ProjectsLoadError';import {isProjectSummaryCompatible,refreshProjectLibrary,@@ -30,10 +34,15 @@ import {useWorkbenchSelector,} from '@workbench/WorkbenchContext';import { ArrowRightIcon, FileUpIcon } from 'lucide-react';-import { useCallback, useMemo, useState } from 'react';+import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-const disabledRowStyles = { opacity: 0.6 } as const;+/** Title, edited time and an inline compatibility badge fit the comfortable pitch. */+const LIST_DENSITY = 'comfortable';+/** Five rows and a bit, so a longer library visibly scrolls. */+const MAX_LIST_HEIGHT_PX = 288;++const getSummaryKey = (summary: ProjectSummary) => summary.id;const ProjectLibraryRefresh = () => {useMountEffect(() => {@@ -51,6 +60,7 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClosconst notify = useNotify();const { t } = useTranslation();const summaries = useProjectLibrarySelector((snapshot) => snapshot.summaries);+ const libraryStatus = useProjectLibrarySelector((snapshot) => snapshot.status);const [busyProjectId, setBusyProjectId] = useState<string | null>(null);const openProjectIds = useMemo(() => new Set(projectIds), [projectIds]);@@ -58,24 +68,30 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos() => summaries.filter((summary) => !openProjectIds.has(summary.id)),[openProjectIds, summaries]);+ const rows = useMemo(() => listRowsFromItems(available, getSummaryKey), [available]);+ // Keyboard users start on the first project they can open; incompatible ones stay reachable with the arrows.+ const firstOpenableKey = available.find(isProjectSummaryCompatible)?.id ?? null;+ const listRef = useRef<HTMLDivElement>(null);+ const importRef = useRef<HTMLButtonElement>(null);+ // After a retry recovers: the list's tab stop, or Import when nothing came back to open.+ const getRecoveryFocus = useCallback(+ () => listRef.current?.querySelector<HTMLElement>('button[tabindex="0"]') ?? importRef.current,+ []+ );+ // A failed listing with nothing listed earlier is not an empty library; earlier rows stay usable after a failure.+ const listStatus =+ summaries.length > 0+ ? 'ready'+ : libraryStatus === 'error'+ ? 'error'+ : libraryStatus === 'ready'+ ? 'ready'+ : 'loading';const openProject = useCallback(async (summary: ProjectSummary) => {const owner = captureAccountScope();- if (!isProjectSummaryCompatible(summary)) {- notify.error(- t('projects.couldNotOpen'),- t(- summary.minimumCanvasSchemaVersion < MIN_SUPPORTED_CANVAS_SCHEMA_VERSION- ? 'projects.file.legacyCanvasProject'- : 'projects.file.updateClient'- )- );-- return;- }-setBusyProjectId(summary.id);try {@@ -144,6 +160,29 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClosconst startImport = useCallback(() => void handleImport(), [handleImport]);+ // An incompatible project stays listed, dimmed, with its badge saying why it cannot open here.+ const renderItem = (summary: ProjectSummary, rowProps: ListRowProps) => {+ const isCompatible = isProjectSummaryCompatible(summary);++ return (+ <ListItem+ {...rowProps}+ badges={isCompatible ? undefined : <ProjectCompatibilityBadge summary={summary} />}+ description={t('projects.editedRelative', { time: formatRelativeTime(summary.updatedAt) })}+ isDisabled={!isCompatible}+ title={summary.name}+ trailing={+ busyProjectId === summary.id ? (+ <Spinner color="fg.muted" />+ ) : isCompatible ? (+ <Icon as={ArrowRightIcon} boxSize="3.5" />+ ) : undefined+ }+ onPress={() => void openProject(summary)}+ />+ );+ };+return (<Dialog.Root lazyMount open={isOpen} size="sm" unmountOnExit onOpenChange={handleOpenChange}>{isOpen ? <ProjectLibraryRefresh /> : null}@@ -155,27 +194,37 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos<Dialog.Title>{t('projects.openProject')}</Dialog.Title></Dialog.Header><Dialog.Body>- <Scrollable maxH="72">- <Stack gap="1">- {available.map((summary) => (- <OpenProjectRow- key={summary.id}- isBusy={busyProjectId === summary.id}- isDisabled={busyProjectId !== null || !isProjectSummaryCompatible(summary)}- summary={summary}- onOpen={openProject}- />- ))}- {available.length === 0 ? (- <Text color="fg.muted" fontSize="md" px="2.5" py="4" textAlign="center">+ <Box+ ref={listRef}+ h={+ rows.length > 0+ ? `${Math.min(getListContentHeight(rows, LIST_DENSITY), MAX_LIST_HEIGHT_PX)}px`+ : undefined+ }+ // Row surfaces bleed into the dialog padding so their text lines up with the title.+ mx="-2"+ >+ <List+ defaultFocusKey={firstOpenableKey}+ density={LIST_DENSITY}+ dividers+ inset="none"+ emptyState={+ <Text color="fg.muted" fontSize="md" py="2" textAlign="center">{summaries.length === 0 ? t('projects.noSavedProjects') : t('projects.allSavedAlreadyOpen')}</Text>- ) : null}- </Stack>- </Scrollable>+ }+ errorState={<ProjectsLoadError getRecoveryFocus={getRecoveryFocus} layout="state" />}+ isBusy={busyProjectId !== null}+ label={t('projects.openProject')}+ renderItem={renderItem}+ rows={rows}+ status={listStatus}+ />+ </Box></Dialog.Body><Dialog.Footer justifyContent="space-between">- <Button variant="outline" onClick={startImport}>+ <Button ref={importRef} variant="outline" onClick={startImport}><FileUpIcon />{t('projects.importWithEllipsis')}</Button>@@ -192,33 +241,3 @@ export const OpenProjectDialog = ({ isOpen, onClose }: { isOpen: boolean; onClos</Dialog.Root>);};--const OpenProjectRow = ({- isBusy,- isDisabled,- onOpen,- summary,-}: {- isBusy: boolean;- isDisabled: boolean;- onOpen: (summary: ProjectSummary) => Promise<void>;- summary: ProjectSummary;-}) => {- const open = useCallback(() => void onOpen(summary), [onOpen, summary]);- const { t } = useTranslation();-- return (- <Row asChild gap="2.5" px="2.5" py="2" rounded="md" _disabled={disabledRowStyles}>- <button disabled={isDisabled} type="button" onClick={open}>- <Stack flex="1" gap="0" minW="0">- <MiddleTruncate fontSize="md" fontWeight="600" text={summary.name} />- <Text color="fg.muted" fontSize="xs">- {t('projects.editedRelative', { time: formatRelativeTime(summary.updatedAt) })}- </Text>- <ProjectCompatibilityBadge summary={summary} />- </Stack>- {isBusy ? <Spinner color="fg.muted" /> : <Icon as={ArrowRightIcon} boxSize="3.5" color="fg.muted" />}- </button>- </Row>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.pending.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.pending.browser.test.tsxindex 5cd9add1ef..6b4ccad66e 100644--- a/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.pending.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/components/ProjectFileOptionsProvider.pending.browser.test.tsx@@ -69,5 +69,5 @@ it('suspends shortcuts from the request that opens the dialog, while its module});await expect.poll(() => host.querySelector('[data-testid="options"]')).not.toBeNull();// The stand-in steps aside for the loaded dialog, which this test replaces with one that announces nothing.- expect(isModalPresent()).toBe(false);+ await expect.poll(() => isModalPresent()).toBe(false);});diff --git a/invokeai/frontend/webv2/src/workbench/projects/components/index.ts b/invokeai/frontend/webv2/src/workbench/projects/components/index.tsdeleted file mode 100644index 55ddb7bc60..0000000000--- a/invokeai/frontend/webv2/src/workbench/projects/components/index.ts+++ /dev/null@@ -1 +0,0 @@-export { OpenProjectDialog } from './OpenProjectDialog';diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.tsindex 63518537e4..4d6c02d0d6 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts@@ -1,8 +1,12 @@+import openapi from '@api/openapi.json';import { ApiError } from '@platform/transport/http';import { beforeEach, describe, expect, it, vi } from 'vitest';import { INVK_MAX_ARCHIVE_BYTES } from './archive';+// The server's cap on one body's name list; the gallery's backend tests hold every name list to the same cap.+const SERVER_CAP = openapi.components.schemas.Body_star_images_in_list.properties.image_names.maxItems;+const mocks = vi.hoisted(() => ({ apiFetch: vi.fn(), apiFetchJson: vi.fn(), apiFetchRaw: vi.fn() }));vi.mock('@platform/transport/http', async (importOriginal) => ({@@ -88,16 +92,29 @@ describe('import rollback transport', () => {});});- it('chunks video cleanup to the server request ceiling', async () => {- const names = Array.from({ length: 1_001 }, (_, index) => `video-${String(index)}.mp4`);+ it.each([+ ['image', deleteArchiveImages, 'image_names'],+ ['video', deleteArchiveVideos, 'video_names'],+ ] as const)('chunks %s cleanup to the server request ceiling', async (_, cleanUp, requestKey) => {+ const names = Array.from({ length: SERVER_CAP + 1 }, (_, index) => `media-${String(index)}`);mocks.apiFetchJson.mockResolvedValue({});- await deleteArchiveVideos(names);+ await cleanUp(names);expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);expect(- mocks.apiFetchJson.mock.calls.map(([, options]) => JSON.parse(options.body as string).video_names.length)- ).toEqual([1_000, 1]);+ mocks.apiFetchJson.mock.calls.map(([, options]) => JSON.parse(options.body as string)[requestKey].length)+ ).toEqual([SERVER_CAP, 1]);+ });++ it('still sends later image cleanup batches after one fails, then reports the failure', async () => {+ const names = Array.from({ length: 2_001 }, (_, index) => `image-${String(index)}.png`);+ const failure = new ApiError('cleanup failed', 500);++ mocks.apiFetchJson.mockResolvedValueOnce({}).mockRejectedValueOnce(failure).mockResolvedValueOnce({});++ await expect(deleteArchiveImages(names)).rejects.toBe(failure);+ expect(mocks.apiFetchJson).toHaveBeenCalledTimes(3);});});@@ -167,7 +184,7 @@ describe('board media transport', () => {'chunks project %s copies to the server request ceiling',async (_, copy, requestKey, nameKey, sourceKey) => {const extension = requestKey === 'image_names' ? 'png' : 'mp4';- const names = Array.from({ length: 1_001 }, (_, index) => `media-${String(index)}.${extension}`);+ const names = Array.from({ length: SERVER_CAP + 1 }, (_, index) => `media-${String(index)}.${extension}`);mocks.apiFetchJson.mockImplementation((_path: string, options: { body: string }) => {const requested = JSON.parse(options.body)[requestKey] as string[];@@ -182,13 +199,13 @@ describe('board media transport', () => {expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);expect(mocks.apiFetchJson.mock.calls.map(([, options]) => JSON.parse(options.body as string)[requestKey].length)- ).toEqual([1_000, 1]);+ ).toEqual([SERVER_CAP, 1]);});it('finishes an in-flight copy batch after cancellation so its identities remain available for rollback', async () => {const controller = new AbortController();- const names = Array.from({ length: 1_001 }, (_, index) => `media-${String(index)}.png`);+ const names = Array.from({ length: SERVER_CAP + 1 }, (_, index) => `media-${String(index)}.png`);mocks.apiFetchJson.mockImplementation((_path: string, options: { body: string; signal?: AbortSignal }) => {const requested = JSON.parse(options.body).image_names as string[];@@ -201,24 +218,39 @@ describe('board media transport', () => {});await expect(copyImagesToBoard(names, 'staging', controller.signal)).resolves.toMatchObject({- copied: { length: 1_000 },+ copied: { length: SERVER_CAP },failed: [names.at(-1)],});expect(mocks.apiFetchJson).toHaveBeenCalledTimes(1);expect(mocks.apiFetchJson.mock.calls[0]![1].signal).toBeUndefined();});- it('chunks video starring to the server request ceiling', async () => {- const names = Array.from({ length: 1_001 }, (_, index) => `video-${String(index)}.mp4`);+ it.each([+ ['image', starImages, 'image_names', 'starred_images'],+ ['video', starVideos, 'video_names', 'starred_videos'],+ ] as const)('chunks %s starring to the server request ceiling', async (_, star, requestKey, responseKey) => {+ const names = Array.from({ length: SERVER_CAP + 1 }, (_, index) => `media-${String(index)}`);mocks.apiFetchJson.mockImplementation((_path: string, options: { body: string }) => {- const requested = JSON.parse(options.body).video_names as string[];+ const requested = JSON.parse(options.body)[requestKey] as string[];- return Promise.resolve({ starred_videos: requested });+ return Promise.resolve({ [responseKey]: requested });});- await expect(starVideos(names)).resolves.toEqual({ failed: [] });- expect(mocks.apiFetchJson).toHaveBeenCalledTimes(2);+ await expect(star(names)).resolves.toEqual({ failed: [] });+ expect(+ mocks.apiFetchJson.mock.calls.map(([, options]) => JSON.parse(options.body as string)[requestKey].length)+ ).toEqual([SERVER_CAP, 1]);+ });++ it('reports a failed image star batch as unstarred and still stars the rest', async () => {+ const names = Array.from({ length: SERVER_CAP + 1 }, (_, index) => `image-${String(index)}.png`);++ mocks.apiFetchJson+ .mockRejectedValueOnce(new ApiError('star failed', 500))+ .mockResolvedValueOnce({ starred_images: [names[SERVER_CAP]] });++ await expect(starImages(names)).resolves.toEqual({ failed: names.slice(0, SERVER_CAP) });});it('creates a staging board by name and truncates it as the backend would', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.tsindex 49a97f37dd..e6e9cbaeb2 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.ts@@ -29,7 +29,11 @@ export const isRequestCancellation = (error: unknown): boolean =>/** Names per existence request, so one slow lookup cannot stall the whole check. */const EXISTENCE_BATCH_SIZE = 500;-/** Maximum names the backend's synchronous batch routes accept. Adapters below own the split. */+/**+ * Maximum names the backend's synchronous batch routes accept (`MAX_IMAGE_BATCH_SIZE`, `MAX_VIDEO_BATCH_SIZE` and+ * `MAX_COPY_BATCH_SIZE` in `invokeai/app/api/routers/_limits.py`); the gallery's transports split by the same limit.+ * Adapters below own the split.+ */const MEDIA_REQUEST_BATCH_SIZE = 1_000;const toBatches = <T>(items: readonly T[], size: number): T[][] => {@@ -589,38 +593,25 @@ const toBulkStarResult = (requested: readonly string[], starred: readonly stringreturn { failed: requested.filter((name) => !succeeded.has(name)) };};-/** Star restored images. Starring is never part of an upload or a copy — it is always this call. */-export const starImages = async (imageNames: readonly string[], signal?: AbortSignal): Promise<BulkStarResult> => {- if (imageNames.length === 0) {- return { failed: [] };- }-- const body = await apiFetchJson<{ starred_images?: string[] }>(`${IMAGES_BASE}/star`, {- body: JSON.stringify({ image_names: imageNames }),- method: 'POST',- signal,- });-- return toBulkStarResult(imageNames, body.starred_images ?? []);-};--/** The same, for videos. */-export const starVideos = async (videoNames: readonly string[], signal?: AbortSignal): Promise<BulkStarResult> => {- if (videoNames.length === 0) {- return { failed: [] };- }-+/** Star in batches the server accepts; a failed batch's names are reported, not thrown, and later batches still run. */+const starMedia = async (+ names: readonly string[],+ endpoint: string,+ requestKey: 'image_names' | 'video_names',+ responseKey: 'starred_images' | 'starred_videos',+ signal?: AbortSignal+): Promise<BulkStarResult> => {const failed: string[] = [];- for (const batch of toBatches(videoNames, MEDIA_REQUEST_BATCH_SIZE)) {+ for (const batch of toBatches(names, MEDIA_REQUEST_BATCH_SIZE)) {try {- const body = await apiFetchJson<{ starred_videos?: string[] }>(`${VIDEOS_BASE}/star`, {- body: JSON.stringify({ video_names: batch }),+ const body = await apiFetchJson<Partial<Record<typeof responseKey, string[]>>>(endpoint, {+ body: JSON.stringify({ [requestKey]: batch }),method: 'POST',signal,});- failed.push(...toBulkStarResult(batch, body.starred_videos ?? []).failed);+ failed.push(...toBulkStarResult(batch, body[responseKey] ?? []).failed);} catch (error) {if (isRequestCancellation(error)) {throw error;@@ -632,6 +623,14 @@ export const starVideos = async (videoNames: readonly string[], signal?: AbortSireturn { failed };};+/** Star restored images. Starring is never part of an upload or a copy — it is always this call. */+export const starImages = (imageNames: readonly string[], signal?: AbortSignal): Promise<BulkStarResult> =>+ starMedia(imageNames, `${IMAGES_BASE}/star`, 'image_names', 'starred_images', signal);++/** The same, for videos. */+export const starVideos = (videoNames: readonly string[], signal?: AbortSignal): Promise<BulkStarResult> =>+ starMedia(videoNames, `${VIDEOS_BASE}/star`, 'video_names', 'starred_videos', signal);+/** Atomically claiming the staging board is the project-create commit point. */export const createStagingBoard = async (boardName: string, signal?: AbortSignal): Promise<string> => {const query = new URLSearchParams({ board_name: clampBoardName(boardName) });@@ -677,31 +676,22 @@ export const deleteStagingBoard = async (boardId: string, signal?: AbortSignal):});};-/** Delete image identities created by a restore whose project could not be created. */-export const deleteArchiveImages = async (imageNames: string[], signal?: AbortSignal): Promise<void> => {- if (imageNames.length === 0) {- return;- }-- await apiFetchJson<unknown>(`${IMAGES_BASE}/delete`, {- body: JSON.stringify({ image_names: imageNames }),- method: 'POST',- signal,- });-};--/** Delete video identities created by a restore whose project could not be created. */-export const deleteArchiveVideos = async (videoNames: string[], signal?: AbortSignal): Promise<void> => {- if (videoNames.length === 0) {- return;- }-+/**+ * Delete in batches the server accepts. Every batch is sent even after one fails, so as much as possible is cleaned+ * up; the first failure is thrown once all have run.+ */+const deleteArchiveMedia = async (+ names: readonly string[],+ endpoint: string,+ requestKey: 'image_names' | 'video_names',+ signal?: AbortSignal+): Promise<void> => {let firstError: unknown = null;- for (const batch of toBatches(videoNames, MEDIA_REQUEST_BATCH_SIZE)) {+ for (const batch of toBatches(names, MEDIA_REQUEST_BATCH_SIZE)) {try {- await apiFetchJson<unknown>(`${VIDEOS_BASE}/delete`, {- body: JSON.stringify({ video_names: batch }),+ await apiFetchJson<unknown>(endpoint, {+ body: JSON.stringify({ [requestKey]: batch }),method: 'POST',signal,});@@ -716,10 +706,18 @@ export const deleteArchiveVideos = async (videoNames: string[], signal?: AbortSiif (firstError !== null) {throw firstError instanceof Error? firstError- : new Error('One or more video cleanup requests failed.', { cause: firstError });+ : new Error('One or more media cleanup requests failed.', { cause: firstError });}};+/** Delete image identities created by a restore whose project could not be created. */+export const deleteArchiveImages = (imageNames: string[], signal?: AbortSignal): Promise<void> =>+ deleteArchiveMedia(imageNames, `${IMAGES_BASE}/delete`, 'image_names', signal);++/** Delete video identities created by a restore whose project could not be created. */+export const deleteArchiveVideos = (videoNames: string[], signal?: AbortSignal): Promise<void> =>+ deleteArchiveMedia(videoNames, `${VIDEOS_BASE}/delete`, 'video_names', signal);+const EXTENSION_BY_MIME: Readonly<Record<string, string>> = {'image/jpeg': 'jpg','image/png': 'png',diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectTransitionDrafts.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/projects/projectTransitionDrafts.browser.test.tsxindex 72be7b458b..f79ff61b66 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectTransitionDrafts.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/projects/projectTransitionDrafts.browser.test.tsx@@ -73,7 +73,7 @@ const target = { id: '', name: '' };(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const generationUi = {- sectionPreferences: { sectionsOpen: {}, setSectionOpen: () => undefined },+ sectionPreferences: { sectionsOpen: {}, setSectionsOpen: () => undefined },} as unknown as GenerationUiAdapter;const HarnessBody = () => {diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.browser.test.tsxindex b2a38d6155..22ed258651 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.browser.test.tsx@@ -21,6 +21,11 @@ vi.mock('@features/queue/publicApi', async (importOriginal) => ({}),}));+// Recall has its own coverage (`app/QueueItemRecall.browser.test.tsx`); these cases are about the saved data.+vi.mock('./useQueueItemRecall', () => ({+ useQueueItemRecall: () => ({ capabilities: {}, isPending: true, reasons: {}, recall: () => Promise.resolve() }),+}));+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const item = { batchId: 'batch-9', id: 9, status: 'failed' } as QueueItemReadModel;diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsxindex e361a0632f..18eb683338 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueItemActions.tsx@@ -1,16 +1,22 @@import type { QueueItemReadModel } from '@features/queue/contracts';import type { QueueItemDetailReadModel } from '@features/queue/react';-import { ButtonGroup, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';+import { ButtonGroup, Icon, Menu, Portal, Spinner, Stack, Text } from '@chakra-ui/react';import { useQueueItemDetail } from '@features/queue/react';import { Button, CloseButton } from '@platform/ui/Button';import { Dialog } from '@platform/ui/Dialog';import { JsonPreview } from '@platform/ui/JsonPreview';+import { MenuContent } from '@platform/ui/Menu';import { Tabs } from '@platform/ui/Tabs';-import { FileTextIcon, TriangleAlertIcon } from 'lucide-react';-import { useCallback, useRef, useState } from 'react';+import { getImageRecallVerb } from '@workbench/image-actions';+import { ChevronDownIcon, FileTextIcon, TriangleAlertIcon } from 'lucide-react';+import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { readQueueItemRecallInput } from './queueRecall';+import { QueueRecallMenuGroup } from './QueueRecallMenuGroup';+import { useQueueItemRecall } from './useQueueItemRecall';+type DetailView = 'error' | 'graph' | 'item' | 'results' | 'workflow';const hasErrorDetail = (detail: QueueItemDetailReadModel): boolean =>@@ -149,6 +155,55 @@ const QueueItemDetailBody = ({ item, open }: { item: QueueItemReadModel; open: b);};+/** Recall for one item, read only while its row is expanded or its menu is open. */+const useItemRecall = (item: QueueItemReadModel) => {+ const { isNonGenerateRun, meta } = useMemo(() => readQueueItemRecallInput(item), [item]);++ return useQueueItemRecall(item.origin, meta, { isNonGenerateRun });+};++/** The queue row context menu's recall entries. */+export const QueueItemRecallMenuGroup = ({ item }: { item: QueueItemReadModel }) => (+ <QueueRecallMenuGroup recall={useItemRecall(item)} />+);++/** Recall all leads, as the A key does on the row; the menu holds every recall verb. */+const QueueItemRecallActions = ({ item }: { item: QueueItemReadModel }) => {+ const { t } = useTranslation();+ const recall = useItemRecall(item);+ const recallAll = getImageRecallVerb('all', t);+ const allReason = recall.reasons.all;+ const onRecallAll = useCallback(() => void recall.recall('all'), [recall]);++ return (+ <>+ <Button+ disabled={!recall.capabilities.all}+ unavailableReason={allReason ? t(allReason) : undefined}+ onClick={onRecallAll}+ >+ <Icon as={recallAll.icon} boxSize="3" />+ {recallAll.label}+ </Button>+ <Menu.Root lazyMount unmountOnExit>+ <Menu.Trigger asChild>+ <Button>+ {t('widgets.canvas.staging.recall')}+ <Icon as={ChevronDownIcon} boxSize="3" />+ </Button>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="13rem" py="1">+ <QueueRecallMenuGroup recall={recall} />+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </>+ );+};+export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {const { t } = useTranslation();const [jsonOpen, setJsonOpen] = useState(false);@@ -160,6 +215,7 @@ export const QueueItemActions = ({ item }: { item: QueueItemReadModel }) => {return (<><ButtonGroup flexWrap="wrap" minW="0" rowGap="1" size="sm" variant="subtle">+ <QueueItemRecallActions item={item} /><Button onClick={openJson}><Icon as={isFailed ? TriangleAlertIcon : FileTextIcon} boxSize="3" />{isFailed ? t('widgets.queue.viewError') : t('common.viewJson')}diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecallMenuGroup.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecallMenuGroup.tsxnew file mode 100644index 0000000000..4af5a2bbb0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/QueueRecallMenuGroup.tsx@@ -0,0 +1,44 @@+import type { ImageRecallKind } from '@workbench/image-actions';++import { Menu } from '@chakra-ui/react';+import { MenuActionItem } from '@platform/ui/Menu';+import { getImageRecallVerb, IMAGE_RECALL_KINDS } from '@workbench/image-actions';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import type { QueueItemRecall } from './useQueueItemRecall';++/**+ * A queued run's recall verbs, for every menu that offers them (staged results, queue rows, queue details). A kind it+ * cannot recall stays listed, unavailable with its reason.+ */+export const QueueRecallMenuGroup = ({ recall }: { recall: QueueItemRecall }) => {+ const { t } = useTranslation();++ return (+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('widgets.canvas.staging.recall')}</Menu.ItemGroupLabel>+ {IMAGE_RECALL_KINDS.map((kind) => (+ <RecallItem key={kind} kind={kind} recall={recall} />+ ))}+ </Menu.ItemGroup>+ );+};++const RecallItem = ({ kind, recall }: { kind: ImageRecallKind; recall: QueueItemRecall }) => {+ const { t } = useTranslation();+ const verb = getImageRecallVerb(kind, t);+ const reason = recall.reasons[kind];+ const onSelect = useCallback(() => void recall.recall(kind), [kind, recall]);++ return (+ <MenuActionItem+ disabled={!recall.capabilities[kind]}+ icon={verb.icon}+ label={verb.label}+ unavailableReason={reason ? t(reason) : undefined}+ value={kind}+ onSelect={onSelect}+ />+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/executeQueueItemRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/executeQueueItemRecall.tsnew file mode 100644index 0000000000..5cbc24a679--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/executeQueueItemRecall.ts@@ -0,0 +1,204 @@+import type { ModelConfig } from '@features/models';+import type { QueueGenerationMeta } from '@features/queue/contracts';+import type { ImageRecallKind } from '@workbench/image-actions';+import type * as CanvasRecallModule from '@workbench/image-actions/canvasRecall';+import type { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';+import type { WorkbenchCommands, WorkbenchQueries } from '@workbench/workbenchStore';+import type { TFunction } from 'i18next';++import { hasArchitectureCapabilities, isSupportedGenerateModel } from '@features/generation/settings';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { claimCanvasRecall, getCurrentGenerateValues, getImageRecallTitle } from '@workbench/image-actions';+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';++import type { LocalRecallSnapshot } from './useLocalRecallSnapshot';++import {+ getQueueRecallAvailability,+ getQueueRecallSource,+ getQueueRecallTargetState,+ planQueueRecall,+} from './queueRecall';++/** What a queue item recall writes through, and how it reports: the Workbench's commands, read side and notices. */+export interface QueueItemRecallContext {+ commands: WorkbenchCommands;+ notify: { info(title: string, description?: string): void; success(title: string, description?: string): void };+ openWidget: ReturnType<typeof useOpenWorkbenchWidget>;+ queries: WorkbenchQueries;+ t: TFunction;+}++/**+ * Recalls a local submission snapshot, or a foreign item's session prompts and seed, into the active project, then+ * reveals the destination panel. An unavailable kind writes nothing and says why. A Canvas recall pressed while+ * another runs says so (see `claimCanvasRecall`).+ */+export const executeQueueItemRecall = async ({+ context,+ isNonGenerateRun,+ kind,+ meta,+ models,+ snapshot,+}: {+ context: QueueItemRecallContext;+ /** The server names a workflow the item ran; a snapshot, when this browser kept one, names its source instead. */+ isNonGenerateRun: boolean;+ kind: ImageRecallKind;+ meta: QueueGenerationMeta;+ models: readonly ModelConfig[];+ /** Null when this browser kept no snapshot for the item. */+ snapshot: LocalRecallSnapshot | null;+}): Promise<void> => {+ const { commands, notify, openWidget, queries, t } = context;+ const { generation, widgets } = commands;+ const owner = captureAccountScope();+ const originalProject = queries.getSnapshot().activeProject;+ const supportedModels = models.filter(isSupportedGenerateModel);+ const localGenerateValues = snapshot?.generateValues ?? null;+ const videoSnapshot = snapshot?.videoValues ?? null;+ const isVideoItem = snapshot?.sourceId === 'video';+ const readCurrentValues = () => {+ const project = queries.getProject(originalProject.id);+ return project+ ? getCurrentGenerateValues({+ generateValues: getResolvedProjectWidgetValues(project, 'generate', queries.getSnapshot().scopedDefaults),+ supportedModels,+ })+ : null;+ };+ const current = readCurrentValues();+ const { reasons } = getQueueRecallAvailability({+ meta,+ snapshot: localGenerateValues,+ source: getQueueRecallSource(snapshot?.sourceId ?? null, isNonGenerateRun),+ // Callers read the catalog before recalling; one that failed to load leaves no model to select.+ target: getQueueRecallTargetState({+ hasCapabilityTable: hasArchitectureCapabilities(),+ hasCurrentValues: current !== null,+ isCatalogSettled: true,+ }),+ videoSnapshot,+ });+ const unavailableReason = reasons[kind];+ let plan = unavailableReason+ ? null+ : planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues, videoSnapshot });++ if (!plan) {+ notify.info(t('widgets.queue.nothingRecalled'), t(unavailableReason ?? 'widgets.queue.recallUnavailableForItem'));+ return;+ }++ if (plan.target === 'video') {+ widgets.patchValues('video', plan.patch);+ openWidget('video', { preferredRegions: ['left'] });+ notify.success(getImageRecallTitle(kind, t), t('widgets.queue.settingsRecalledIntoVideoDescription'));+ return;+ }++ let canvasRecall: typeof CanvasRecallModule | null = null;+ let canvasPlan: CanvasRecallModule.CanvasRecallPlan | null = null;+ let canvasProblem: string | null = null;+ let canvasApplied = false;+ const preparedModelKey = plan.values.model?.key;+ // Released once committed: saving the Canvas images afterwards holds no later recall back.+ let releaseCanvasRecall: (() => void) | null = null;+ try {+ if ((kind === 'all' || kind === 'remix') && snapshot?.canvasMetadata) {+ releaseCanvasRecall = claimCanvasRecall(owner);+ if (!releaseCanvasRecall) {+ notify.info(getImageRecallTitle(kind, t), t('widgets.gallery.itemActions.recall.recallInProgress'));+ return;+ }+ try {+ canvasRecall = await import('@workbench/image-actions/canvasRecall');+ canvasPlan = await canvasRecall.prepareCanvasRecall({+ metadata: snapshot.canvasMetadata,+ model: plan.values.model,+ models: [...models],+ owner,+ isCurrent: () =>+ queries.isActiveProject(originalProject.id) &&+ queries.getProject(originalProject.id)?.canvas.document === originalProject.canvas.document,+ });+ await canvasRecall.settleCanvasRecall(+ canvasPlan,+ {+ commands,+ projectId: originalProject.id,+ getProject: () => queries.getProject(originalProject.id) ?? null,+ },+ owner+ );+ } catch (error) {+ canvasPlan = null;+ canvasProblem = error instanceof Error ? error.message : 'unavailable';+ }+ }+ if (!isAccountScopeCurrent(owner) || !queries.isActiveProject(originalProject.id)) {+ return;+ }+ // Asset reads and paint persistence may yield; retain edits made while the canvas was loading.+ plan = planQueueRecall(kind, {+ current: readCurrentValues(),+ isVideoItem,+ meta,+ snapshot: localGenerateValues,+ videoSnapshot,+ });+ if (!plan || plan.target !== 'generate') {+ return;+ }+ if (canvasPlan && canvasRecall) {+ try {+ if (preparedModelKey !== plan.values.model?.key) {+ canvasPlan.problems.push('model-changed');+ } else {+ canvasApplied = canvasRecall.commitCanvasRecall({+ plan: canvasPlan,+ expectedDocument: originalProject.canvas.document,+ target: {+ commands,+ projectId: originalProject.id,+ getProject: () =>+ queries.isActiveProject(originalProject.id) ? (queries.getProject(originalProject.id) ?? null) : null,+ },+ restorePointName: t('widgets.gallery.itemActions.recall.beforeCanvasRecall'),+ });+ }+ if (canvasPlan.problems.length) {+ canvasProblem = canvasRecall.getCanvasRecallProblemsMessage(canvasPlan.problems, t);+ }+ } catch (error) {+ canvasProblem = error instanceof Error ? error.message : 'unavailable';+ }+ }+ if (canvasProblem) {+ notify.info(+ t('widgets.gallery.itemActions.recall.partiallyRecalled'),+ t('widgets.gallery.itemActions.recall.canvasPartial', { items: canvasProblem })+ );+ }+ generation.setSettings(plan.values, originalProject.id);+ openWidget('generate', { preferredRegions: ['left'] });+ notify.success(getImageRecallTitle(kind, t), t('widgets.queue.settingsRecalledDescription'));+ } finally {+ releaseCanvasRecall?.();+ }+ if (canvasApplied && canvasPlan && canvasRecall) {+ const durable = await canvasRecall.finalizeCanvasRecallAssets(+ canvasPlan,+ {+ commands,+ projectId: originalProject.id,+ getProject: () => queries.getProject(originalProject.id) ?? null,+ },+ owner+ );+ if (!durable && isAccountScopeCurrent(owner) && queries.isActiveProject(originalProject.id)) {+ notify.info(getImageRecallTitle(kind, t), t('widgets.gallery.itemActions.recall.canvasImagesTemporary'));+ }+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.tsindex 7c0c6bcc54..ec84464c34 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.test.ts@@ -1,14 +1,19 @@import type { GenerateWidgetValues } from '@features/generation/contracts';+import type { QueueItemReadModel } from '@features/queue/contracts';+import { buildQueueItemOrigin } from '@features/queue/contracts';import { createDefaultVideoWidgetValues } from '@features/video';import { describe, expect, it } from 'vitest';import {buildQueueRecallValues,buildVideoQueueRecallPatch,+ getQueueRecallAvailability,getQueueRecallCapabilities,+ getQueueRecallSource,getVideoQueueRecallCapabilities,planQueueRecall,+ readQueueItemRecallInput,} from './queueRecall';const makeValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues =>@@ -29,6 +34,157 @@ const makeValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidg...overrides,}) as GenerateWidgetValues;+describe('getQueueRecallAvailability', () => {+ const available = (input: Partial<Parameters<typeof getQueueRecallAvailability>[0]>) =>+ getQueueRecallAvailability({+ meta: {},+ snapshot: null,+ source: 'unknown',+ target: 'ready',+ videoSnapshot: null,+ ...input,+ });+ const SETTINGS_NOT_KEPT = 'widgets.queue.recallSettingsNotKept';++ it('offers an item without a snapshot in this browser only what the server recorded', () => {+ expect(available({ meta: { positivePrompt: 'p' } })).toEqual({+ capabilities: expect.objectContaining({ all: false, prompts: true, remix: false, seed: false }),+ reasons: {+ all: SETTINGS_NOT_KEPT,+ clipSkip: SETTINGS_NOT_KEPT,+ dimensions: SETTINGS_NOT_KEPT,+ remix: SETTINGS_NOT_KEPT,+ seed: SETTINGS_NOT_KEPT,+ },+ });+ });++ it.each([+ ['a Workflow or Upscale snapshot', getQueueRecallSource('workflow', false)],+ ['a workflow run another browser queued', getQueueRecallSource(null, true)],+ ])('offers nothing from %s, whatever its session values look like', (_, source) => {+ // Session values matched by type alone would read a workflow's text field as a prompt.+ const result = available({ meta: { positivePrompt: 'a workflow string field', seed: 3 }, source });++ expect(Object.values(result.capabilities).some(Boolean)).toBe(false);+ expect(new Set(Object.values(result.reasons))).toEqual(new Set(['widgets.queue.recallUnavailableForItem']));+ expect(Object.keys(result.reasons)).toHaveLength(6);+ });++ it('names what the Generate panel lacks beside an available full recall', () => {+ const snapshot = makeValues({ seedMode: 'fixed' });++ expect(available({ snapshot, source: 'generate', target: 'no-model' })).toEqual({+ capabilities: expect.objectContaining({ all: true, dimensions: false, prompts: false, remix: true }),+ reasons: {+ clipSkip: 'widgets.generate.selectSupportedModelFirst',+ dimensions: 'widgets.generate.selectSupportedModelFirst',+ prompts: 'widgets.generate.selectSupportedModelFirst',+ seed: 'widgets.generate.selectSupportedModelFirst',+ },+ });+ expect(available({ snapshot, source: 'generate', target: 'no-capabilities' }).reasons.prompts).toBe(+ 'widgets.generate.capabilitiesUnavailableForSetup'+ );+ });++ it('says nothing is recallable while partial kinds wait and nothing else can be recalled', () => {+ const meta = { positivePrompt: 'p' };++ expect(available({ meta, target: 'no-model' }).reasons.prompts).toBe('widgets.queue.recallUnavailable');+ expect(available({ meta, target: 'no-capabilities' }).reasons.prompts).toBe(+ 'widgets.queue.recallUnavailableCapabilities'+ );+ });++ it('gives no reason while the model catalog is still loading', () => {+ const result = available({ meta: { positivePrompt: 'p' }, target: 'loading' });++ expect(result.capabilities.prompts).toBe(false);+ expect(result.reasons.prompts).toBeUndefined();+ });++ it('says a random seed is unreported rather than unrecorded', () => {+ expect(available({ snapshot: makeValues({ seedMode: 'random' }), source: 'generate' }).reasons.seed).toBe(+ 'widgets.queue.recallRandomSeed'+ );+ });++ it('lets a video item recall into the Video panel whatever Generate holds', () => {+ const result = available({+ source: 'video',+ target: 'no-capabilities',+ videoSnapshot: { ...createDefaultVideoWidgetValues(), seedMode: 'fixed' },+ });++ expect(result.capabilities).toMatchObject({ all: true, prompts: true, seed: true });+ expect(result.reasons).toEqual({+ clipSkip: 'widgets.queue.recallNotForVideo',+ dimensions: 'widgets.queue.recallNotForVideo',+ });+ });+});++describe('readQueueItemRecallInput', () => {+ const field = (nodePath: string, value: number | string) => ({ fieldName: 'value', nodePath, value });+ const item = (overrides: Partial<QueueItemReadModel>): QueueItemReadModel => ({+ batchId: 'batch',+ createdAt: '2026-01-01T00:00:00Z',+ id: 1,+ resultImageNames: [],+ sessionId: 'session',+ status: 'completed',+ updatedAt: '2026-01-01T00:00:00Z',+ ...overrides,+ });+ const webv2Origin = buildQueueItemOrigin('run', 'project');++ it('reads a webv2 Generate-style run by its named prompt and seed only', () => {+ expect(+ readQueueItemRecallInput(+ item({+ fieldValues: [field('caption', 'not a prompt'), field('positive_prompt', 'a fox'), field('seed', 7)],+ origin: webv2Origin,+ })+ )+ ).toEqual({ isNonGenerateRun: false, meta: { positivePrompt: 'a fox', seed: 7 } });+ });++ it.each([+ ['a webv2 run without the named values', { fieldValues: [field('caption', 'a caption'), field('n', 3)] }],+ // Several workflow_return nodes submit no workflow, so the server names none.+ ['a webv2 workflow that submitted no workflow', { fieldValues: [] }],+ ])('treats %s as something other than Generate', (_, overrides) => {+ expect(readQueueItemRecallInput(item({ ...overrides, origin: webv2Origin }))).toEqual({+ isNonGenerateRun: true,+ meta: {},+ });+ });++ it('treats a workflow with an empty name as a workflow run', () => {+ expect(readQueueItemRecallInput(item({ workflowName: '' })).isNonGenerateRun).toBe(true);+ });++ it("still reads another client's unfamiliar node names by type and order", () => {+ expect(readQueueItemRecallInput(item({ fieldValues: [field('prompt_node', 'a fox'), field('noise', 3)] }))).toEqual(+ { isNonGenerateRun: false, meta: { positivePrompt: 'a fox', seed: 3 } }+ );+ });+});++describe('getQueueRecallSource', () => {+ it.each([+ ['generate', false, 'generate'],+ ['canvas', false, 'generate'],+ ['video', true, 'video'],+ ['upscale', false, 'other'],+ [null, true, 'other'],+ [null, false, 'unknown'],+ ] as const)('reads a %s snapshot (workflow run named: %s) as %s', (snapshotSourceId, isWorkflowRun, expected) => {+ expect(getQueueRecallSource(snapshotSourceId, isWorkflowRun)).toBe(expected);+ });+});+describe('getQueueRecallCapabilities', () => {it('grants everything for local snapshots', () => {expect(getQueueRecallCapabilities(makeValues({ seedMode: 'fixed' }), {})).toEqual({diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.tsindex 553c32b39e..14eb5e6c80 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRecall.ts@@ -1,8 +1,9 @@import type { GenerateWidgetValues } from '@features/generation/contracts';-import type { QueueGenerationMeta } from '@features/queue/contracts';+import type { QueueGenerationMeta, QueueItemReadModel } from '@features/queue/contracts';import type { VideoWidgetValues } from '@features/video';import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-actions';+import { extractGenerationMeta, extractNamedGenerationMeta, isWebv2QueueItemOrigin } from '@features/queue/contracts';import { cloneVideoWidgetValues } from '@features/video';/**@@ -36,6 +37,146 @@ export const getVideoQueueRecallCapabilities = (workflow: false,});+/**+ * Whether the Generate panel can take a partial recall: one merges into its current values, which exist once a+ * supported model is selected under a loaded capability table. `loading` waits for the model catalog to load or fail:+ * it can hold the model the panel will select.+ */+export type QueueRecallTargetState = 'ready' | 'loading' | 'no-model' | 'no-capabilities';++export const getQueueRecallTargetState = ({+ hasCapabilityTable,+ hasCurrentValues,+ isCatalogSettled,+}: {+ hasCapabilityTable: boolean;+ hasCurrentValues: boolean;+ isCatalogSettled: boolean;+}): QueueRecallTargetState =>+ hasCurrentValues ? 'ready' : !hasCapabilityTable ? 'no-capabilities' : isCatalogSettled ? 'no-model' : 'loading';++/**+ * What submitted an item, as far as this browser can tell. Its snapshot names the source; Workflow and Upscale+ * snapshots record no settings. Without one, `readQueueItemRecallInput` says whether the item ran something other than+ * a Generate-style graph. `unknown` is an item another browser or client queued, which may have come from Generate.+ */+export type QueueRecallSource = 'generate' | 'video' | 'other' | 'unknown';++export const getQueueRecallSource = (snapshotSourceId: string | null, isNonGenerateRun: boolean): QueueRecallSource =>+ snapshotSourceId === 'generate' || snapshotSourceId === 'canvas'+ ? 'generate'+ : snapshotSourceId === 'video'+ ? 'video'+ : snapshotSourceId !== null || isNonGenerateRun+ ? 'other'+ : 'unknown';++/**+ * What a queue item's session tells recall. The server keeps a submitted workflow, named or not. webv2's own+ * Generate, Canvas, Video and Upscale submissions name their prompts and seed, so a webv2 item without them ran+ * something else, and its other values are never read by type and order; items from other clients still are.+ */+export const readQueueItemRecallInput = (+ item: QueueItemReadModel+): { isNonGenerateRun: boolean; meta: QueueGenerationMeta } => {+ const ranWorkflow = typeof item.workflowName === 'string';++ if (!isWebv2QueueItemOrigin(item.origin)) {+ return { isNonGenerateRun: ranWorkflow, meta: extractGenerationMeta(item) };+ }++ const meta = extractNamedGenerationMeta(item);++ return { isNonGenerateRun: ranWorkflow || (meta.positivePrompt === undefined && meta.seed === undefined), meta };+};++export interface QueueRecallAvailability {+ capabilities: ImageRecallCapabilities;+ /** For each unavailable kind, the i18n key of why; none while the answer is still loading. */+ reasons: Partial<Record<ImageRecallKind, string>>;+}++const RECALL_KINDS = ['all', 'remix', 'prompts', 'seed', 'dimensions', 'clipSkip'] as const satisfies ImageRecallKind[];++const EMPTY_CAPABILITIES: ImageRecallCapabilities = {+ all: false,+ clipSkip: false,+ dimensions: false,+ prompts: false,+ remix: false,+ seed: false,+ workflow: false,+};++const getUnrecordedReason = (kind: ImageRecallKind, source: QueueRecallSource, hasSnapshot: boolean): string =>+ source === 'video' && (kind === 'dimensions' || kind === 'clipSkip')+ ? 'widgets.queue.recallNotForVideo'+ : hasSnapshot+ ? // With a snapshot only a random seed is ever missing: the server has not reported the one it chose.+ 'widgets.queue.recallRandomSeed'+ : 'widgets.queue.recallSettingsNotKept';++/**+ * What each recall kind can do for an item, and why not when it cannot; every reason holds wherever it is shown.+ * Without this browser's snapshot only the prompts and seed the server ran are known, and a Workflow or Upscale run+ * holds no Generate settings at all (its session values are not Generate's, whatever their names). A missing record+ * outranks an unready Generate panel: selecting a model would not make it recallable.+ */+export const getQueueRecallAvailability = ({+ meta,+ snapshot,+ source,+ target,+ videoSnapshot,+}: {+ meta: QueueGenerationMeta;+ snapshot: GenerateWidgetValues | null;+ source: QueueRecallSource;+ target: QueueRecallTargetState;+ videoSnapshot: VideoWidgetValues | null;+}): QueueRecallAvailability => {+ const reasons: QueueRecallAvailability['reasons'] = {};++ if (source === 'other') {+ for (const kind of RECALL_KINDS) {+ reasons[kind] = 'widgets.queue.recallUnavailableForItem';+ }+ return { capabilities: EMPTY_CAPABILITIES, reasons };+ }++ const isVideo = source === 'video';+ const hasSnapshot = isVideo ? videoSnapshot !== null : snapshot !== null;+ const recorded = isVideo+ ? getVideoQueueRecallCapabilities(videoSnapshot, meta)+ : getQueueRecallCapabilities(snapshot, meta);+ const capabilities = { ...recorded };+ // Partial kinds then wait for the Generate panel while nothing else is recallable, which the "Nothing recallable"+ // reasons say; beside an available full recall they name only what the panel lacks.+ const blockedReason =+ target === 'no-capabilities'+ ? hasSnapshot+ ? 'widgets.generate.capabilitiesUnavailableForSetup'+ : 'widgets.queue.recallUnavailableCapabilities'+ : target === 'no-model'+ ? hasSnapshot+ ? 'widgets.generate.selectSupportedModelFirst'+ : 'widgets.queue.recallUnavailable'+ : null;++ for (const kind of RECALL_KINDS) {+ if (!recorded[kind]) {+ reasons[kind] = getUnrecordedReason(kind, source, hasSnapshot);+ } else if (!isVideo && kind !== 'all' && kind !== 'remix' && target !== 'ready') {+ capabilities[kind] = false;+ if (blockedReason) {+ reasons[kind] = blockedReason;+ }+ }+ }++ return { capabilities, reasons };+};+/** The prompt tool model picks are the widget's preference, not part of what was submitted. */const withCurrentToolModelPicks = (values: GenerateWidgetValues,diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/recallQueueItem.browser.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/recallQueueItem.browser.test.tsnew file mode 100644index 0000000000..b4b4175fe0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/recallQueueItem.browser.test.ts@@ -0,0 +1,113 @@+import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';+import type * as ModelsModule from '@features/models';+import type { QueueItemReadModel } from '@features/queue/contracts';+import type { Project } from '@workbench/projectContracts';+import type { TFunction } from 'i18next';++import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';+import { getDefaultGenerateSettings } from '@features/generation/settings';+import { buildQueueItemOrigin } from '@features/queue/contracts';+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';+import { QueryClient } from '@tanstack/react-query';+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { afterEach, expect, it, vi } from 'vitest';++import { recallQueueItem } from './recallQueueItem';++const models = vi.hoisted(() => ({ release: () => {} }));++// The catalog read is where the key's recall waits; the test decides when it settles.+vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<typeof ModelsModule>()),+ ensureModelsLoaded: () =>+ new Promise<void>((resolve) => {+ models.release = resolve;+ }),+}));++seedArchitectureCapabilities();++afterEach(() => accountLifecycle.invalidate());++it.each(['its module loaded', 'it read the catalog'] as const)(+ 'drops a key recall whose project stopped being active while %s',+ async (moment) => {+ accountLifecycle.activate('queue-recall-project-switch');+ const main = { base: 'sdxl', key: 'main', name: 'SDXL', type: 'main' } as MainModelConfig;+ const state = createInitialWorkbenchState();+ const project = state.projects[0]!;+ project.queue = {+ items: [+ {+ backendItemIds: [1],+ cancellable: false,+ id: 'run-1',+ snapshot: {+ recall: {+ generateValues: { ...getDefaultGenerateSettings(main), model: main, positivePrompt: 'Recalled' },+ },+ sourceId: 'generate',+ },+ status: 'completed',+ } as unknown as Project['queue']['items'][number],+ ],+ };+ const store = createWorkbenchStore(state);+ const notify = { info: vi.fn(), success: vi.fn() };+ const openWidget = vi.fn();+ const item = {+ batchId: 'batch-1',+ createdAt: '2026-01-01T00:00:00Z',+ id: 1,+ origin: buildQueueItemOrigin('run-1', project.id),+ resultImageNames: [],+ sessionId: 'session-1',+ status: 'completed',+ updatedAt: '2026-01-01T00:00:00Z',+ } satisfies QueueItemReadModel;++ // Captured at the press, as the queue's adapter does before it loads this module.+ const owner = captureAccountScope();+ const recall = () =>+ recallQueueItem({+ context: {+ commands: store.commands,+ notify,+ openWidget,+ queries: store.queries,+ t: ((key: string) => key) as TFunction,+ },+ item,+ kind: 'all',+ owner,+ projectId: project.id,+ queryClient: new QueryClient(),+ });+ let pending: Promise<void>;+ if (moment === 'its module loaded') {+ store.commands.projects.create();+ pending = recall();+ } else {+ pending = recall();+ store.commands.projects.create();+ }+ const switchedTo = store.queries.getSnapshot().activeProject.id;+ models.release();+ await pending;++ expect(switchedTo).not.toBe(project.id);+ for (const id of [project.id, switchedTo]) {+ const values = getResolvedProjectWidgetValues(+ store.queries.getProject(id)!,+ 'generate',+ store.queries.getSnapshot().scopedDefaults+ ) as Partial<GenerateWidgetValues>;+ expect(values.positivePrompt).not.toBe('Recalled');+ }+ expect(notify.success).not.toHaveBeenCalled();+ expect(notify.info).not.toHaveBeenCalled();+ expect(openWidget).not.toHaveBeenCalled();+ }+);diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/recallQueueItem.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/recallQueueItem.tsnew file mode 100644index 0000000000..08f9bba708--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/recallQueueItem.ts@@ -0,0 +1,53 @@+import type { QueueItemReadModel } from '@features/queue/contracts';+import type { AccountScope } from '@platform/state/accountLifecycle';+import type { QueryClient } from '@tanstack/react-query';+import type { ImageRecallKind } from '@workbench/image-actions';++import { ensureModelsLoaded, getModelsSnapshot } from '@features/models';+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';++import { executeQueueItemRecall, type QueueItemRecallContext } from './executeQueueItemRecall';+import { readQueueItemRecallInput } from './queueRecall';+import { loadLocalRecallSnapshot } from './useLocalRecallSnapshot';++/**+ * Recalls from an item no menu has open, such as the focused queue row on a key press: what the open menus read as+ * they mount (the snapshot, the model catalog) is read first. The caller captures the account and project at the+ * press, before loading this module, so a switch while anything loads drops the recall.+ */+export const recallQueueItem = async ({+ context,+ item,+ kind,+ owner,+ projectId,+ queryClient,+}: {+ context: QueueItemRecallContext;+ item: QueueItemReadModel;+ kind: ImageRecallKind;+ owner: AccountScope;+ projectId: string;+ queryClient: QueryClient;+}): Promise<void> => {+ if (!isAccountScopeCurrent(owner) || !context.queries.isActiveProject(projectId)) {+ return;+ }+ const [snapshot] = await Promise.all([+ loadLocalRecallSnapshot({ origin: item.origin, projects: context.queries.getSnapshot().projects, queryClient }),+ // A catalog that fails to load leaves the recall to say what it cannot apply.+ ensureModelsLoaded().catch(() => undefined),+ ]);+ if (!isAccountScopeCurrent(owner) || !context.queries.isActiveProject(projectId)) {+ return;+ }+ const { isNonGenerateRun, meta } = readQueueItemRecallInput(item);+ await executeQueueItemRecall({+ context,+ isNonGenerateRun,+ kind,+ meta,+ models: getModelsSnapshot().models,+ snapshot,+ });+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.tsindex 0c68bc2897..6f45e0aa0c 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useLocalRecallSnapshot.ts@@ -5,8 +5,8 @@ import type { Project } from '@workbench/projectContracts';import { normalizeGenerateWidgetValues } from '@features/generation/settings';import { parseQueueItemOrigin, parseQueueItemOriginProjectId } from '@features/queue/contracts';import { normalizeVideoWidgetValues, type VideoWidgetValues } from '@features/video';-import { assertAccountScopeCurrent, captureAccountScope } from '@platform/state/accountLifecycle';-import { useQuery } from '@tanstack/react-query';+import { assertAccountScopeCurrent, captureAccountScope, type AccountScope } from '@platform/state/accountLifecycle';+import { type QueryClient, useQuery } from '@tanstack/react-query';import { isRecord } from '@workbench/canvasMigration';import { useWorkbenchSelector } from '@workbench/WorkbenchContext';@@ -42,6 +42,42 @@ export const getLocalQueueItemSource = (origin?: string | null): InvocationSourceId | null => findLocalQueueItem(projects, origin)?.snapshot.sourceId ?? null;+/** This browser's durable snapshot of a queue item another tab, or an earlier page, submitted. */+const durableRecallSnapshotOptions = (owner: AccountScope, projectId: string | null, queueItemId: string | null) => ({+ queryKey: ['queue-recall', owner.epoch, projectId, queueItemId],+ retry: false,+ staleTime: 30_000,+ async queryFn(): Promise<LocalRecallSnapshot | null> {+ if (!queueItemId) {+ return null;+ }+ const cache = await createAccountOwnedQueueRecallCache(owner);+ try {+ const result = await cache.get(queueItemId);+ assertAccountScopeCurrent(owner);+ if (result.kind !== 'found' || (projectId && result.snapshot.projectId !== projectId)) {+ return null;+ }+ const snapshot = result.snapshot;+ return {+ sourceId: snapshot.sourceId,+ ...(isRecord(snapshot.canvasMetadata) ? { canvasMetadata: snapshot.canvasMetadata } : {}),+ generateValues: snapshot.generateValues+ ? (normalizeGenerateWidgetValues(snapshot.generateValues) ?? undefined)+ : undefined,+ videoValues: snapshot.videoValues ? (normalizeVideoWidgetValues(snapshot.videoValues) ?? undefined) : undefined,+ };+ } finally {+ cache.close();+ }+ },+});++const toLocalRecallSnapshot = (item: Pick<Project, 'queue'>['queue']['items'][number]): LocalRecallSnapshot => ({+ ...item.snapshot.recall,+ sourceId: item.snapshot.sourceId,+});+/** `undefined` means the durable lookup is pending; `null` means it completed without a usable snapshot. */export const useLocalRecallSnapshot = (origin?: string | null): LocalRecallSnapshot | null | undefined => {const owner = captureAccountScope();@@ -49,42 +85,41 @@ export const useLocalRecallSnapshot = (origin?: string | null): LocalRecallSnapsconst queueItemId = parseQueueItemOrigin(origin);const projectId = parseQueueItemOriginProjectId(origin);const { data, isPending } = useQuery({+ ...durableRecallSnapshotOptions(owner, projectId, queueItemId),enabled: !localItem && queueItemId !== null,- queryKey: ['queue-recall', owner.epoch, projectId, queueItemId],- retry: false,- staleTime: 30_000,- async queryFn(): Promise<LocalRecallSnapshot | null> {- if (!queueItemId) {- return null;- }- const cache = await createAccountOwnedQueueRecallCache(owner);- try {- const result = await cache.get(queueItemId);- assertAccountScopeCurrent(owner);- if (result.kind !== 'found' || (projectId && result.snapshot.projectId !== projectId)) {- return null;- }- const snapshot = result.snapshot;- return {- sourceId: snapshot.sourceId,- ...(isRecord(snapshot.canvasMetadata) ? { canvasMetadata: snapshot.canvasMetadata } : {}),- generateValues: snapshot.generateValues- ? (normalizeGenerateWidgetValues(snapshot.generateValues) ?? undefined)- : undefined,- videoValues: snapshot.videoValues- ? (normalizeVideoWidgetValues(snapshot.videoValues) ?? undefined)- : undefined,- };- } finally {- cache.close();- }- },});if (localItem) {- return { ...localItem.snapshot.recall, sourceId: localItem.snapshot.sourceId };+ return toLocalRecallSnapshot(localItem);}if (queueItemId !== null && isPending) {return undefined;}return data ?? null;};++/** The same answer as `useLocalRecallSnapshot`, read once for a caller outside React; null when there is none. */+export const loadLocalRecallSnapshot = async ({+ origin,+ projects,+ queryClient,+}: {+ origin?: string | null;+ projects: readonly Pick<Project, 'id' | 'queue'>[];+ queryClient: QueryClient;+}): Promise<LocalRecallSnapshot | null> => {+ const localItem = findLocalQueueItem(projects, origin);+ if (localItem) {+ return toLocalRecallSnapshot(localItem);+ }+ const queueItemId = parseQueueItemOrigin(origin);+ if (queueItemId === null) {+ return null;+ }+ try {+ return await queryClient.fetchQuery(+ durableRecallSnapshotOptions(captureAccountScope(), parseQueueItemOriginProjectId(origin), queueItemId)+ );+ } catch {+ return null;+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsxindex 22c0f9a837..1ba1d8c196 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.browser.test.tsx@@ -16,9 +16,10 @@ import {} from '@features/generation/core/architectureCapabilities.testing';import { getDefaultGenerateSettings } from '@features/generation/settings';import { createDefaultVideoWidgetValues } from '@features/video';-import { accountLifecycle } from '@platform/state/accountLifecycle';+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';import { recordCanvasMetadata } from '@workbench/canvas-operations/saveCanvasToGallery';import { createEmptyCanvasDocument } from '@workbench/canvasMigration';+import { claimCanvasRecall } from '@workbench/image-actions';import { getResolvedProjectWidgetValues } from '@workbench/widgetState';import { createWorkbenchStore } from '@workbench/workbenchStore';import { act, createRef, type Ref, useImperativeHandle } from 'react';@@ -59,6 +60,13 @@ vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({generation: { setSettings: mocks.setSettings },widgets: { patchValues: mocks.patchValues },},+ // Read once per render: these probes do not re-render on Workbench changes.+ useWidgetValuesSelector: (widgetId: string, selector: (values: Record<string, unknown>) => unknown) => {+ const snapshot = mocks.store?.queries.getSnapshot();+ return selector(+ snapshot ? getResolvedProjectWidgetValues(snapshot.activeProject, widgetId, snapshot.scopedDefaults) : {}+ );+ },}));vi.mock('@features/models', async (importOriginal) => ({...(await importOriginal<typeof ModelsModule>()),@@ -146,7 +154,8 @@ describe('useQueueItemRecall', () => {it('recalls a generate submission into the Generate panel and reveals it', async () => {await render({ generateValues: generateSnapshot, sourceId: 'canvas' });- expect(handle.current!.capabilities).toMatchObject({ all: true, prompts: true, seed: true });+ // A full recall replaces the Generate values, so it needs no supported model selected.+ expect(handle.current!.capabilities).toMatchObject({ all: true, remix: true });await recall('all');@@ -166,15 +175,43 @@ describe('useQueueItemRecall', () => {expect(mocks.openWidget).toHaveBeenCalledWith('video', { preferredRegions: ['left'] });});- it('explains an unavailable recall instead of writing anything', async () => {- // A foreign item: no snapshot, only the executed prompt from the session.+ it('says why each kind is unavailable, and explains instead of writing when one is recalled anyway', async () => {+ // A foreign item: no snapshot, only the executed prompt from the session, and no supported model selected.await render(null, { positivePrompt: 'session prompt' });- expect(handle.current!.capabilities).toMatchObject({ all: false, prompts: true, seed: false });+ expect(handle.current!.capabilities).toMatchObject({ all: false, prompts: false, seed: false });+ expect(handle.current!.reasons).toMatchObject({+ all: 'widgets.queue.recallSettingsNotKept',+ prompts: 'widgets.queue.recallUnavailable',+ seed: 'widgets.queue.recallSettingsNotKept',+ });+ await recall('prompts');await recall('seed');expect(mocks.setSettings).not.toHaveBeenCalled();- expect(mocks.notifyInfo).toHaveBeenCalledWith(expect.any(String), 'widgets.queue.recallUnavailable');+ expect(mocks.notifyInfo.mock.calls).toEqual([+ [expect.any(String), 'widgets.queue.recallUnavailable'],+ [expect.any(String), 'widgets.queue.recallSettingsNotKept'],+ ]);+ });++ it('offers a foreign item its session prompt once a supported model is selected', async () => {+ const main = { base: 'sdxl', key: 'main', name: 'SDXL', type: 'main' } as MainModelConfig &+ ModelsModule.ModelConfig;+ mocks.models = [main];+ mocks.store = createWorkbenchStore();+ const projectId = mocks.store.queries.getSnapshot().activeProject.id;+ mocks.store.commands.generation.setSettings({ ...getDefaultGenerateSettings(main), model: main }, projectId);+ await render(null, { positivePrompt: 'session prompt' });+ expect(handle.current!.capabilities).toMatchObject({ all: false, prompts: true });+ expect(handle.current!.reasons.prompts).toBeUndefined();++ await recall('prompts');++ const snapshot = mocks.store.queries.getSnapshot();+ expect(+ getResolvedProjectWidgetValues(snapshot.activeProject, 'generate', snapshot.scopedDefaults).positivePrompt+ ).toBe('session prompt');});it('names the missing capability table, not a missing model, while the table is absent', async () => {@@ -182,7 +219,8 @@ describe('useQueueItemRecall', () => {await act(() => resetArchitectureCapabilities());try {- await recall('seed');+ expect(handle.current!.reasons.prompts).toBe('widgets.queue.recallUnavailableCapabilities');+ await recall('prompts');} finally {await act(() => setArchitectureCapabilities(architectureCapabilitiesFixture));}@@ -303,6 +341,53 @@ it('retains prompt tool edits made while canvas assets load and recalls the snapexpect(snapshot.activeProject.canvas.document.stacks.raster[0]).toMatchObject({ name: 'Recorded image' });});+it('drops a second recall pressed while one is under way, rather than recalling the canvas in part', async () => {+ accountLifecycle.activate('queue-canvas-repeated-recall');+ const main = { base: 'sdxl', key: 'queue-main', name: 'SDXL', type: 'main' } as MainModelConfig &+ ModelsModule.ModelConfig;+ mocks.models = [main];+ const store = (mocks.store = createWorkbenchStore());+ let resolveAssets!: (images: Awaited<ReturnType<typeof galleryImages.resolveMany>>) => void;+ const resolveMany = vi.spyOn(galleryImages, 'resolveMany').mockReturnValue(+ new Promise((resolve) => {+ resolveAssets = resolve;+ })+ );+ await render({+ sourceId: 'canvas',+ generateValues: { ...getDefaultGenerateSettings(main), model: main, modelKey: main.key },+ canvasMetadata: makeCanvasMetadata(),+ });+ let first!: Promise<void>;+ let second!: Promise<void>;+ await act(() => {+ first = Promise.resolve(handle.current!.recall('all'));+ });+ await vi.waitFor(() => expect(resolveMany).toHaveBeenCalledOnce());+ await act(() => {+ second = Promise.resolve(handle.current!.recall('all'));+ });+ await act(async () => {+ resolveAssets([{ imageName: 'recorded.png' }] as Awaited<ReturnType<typeof galleryImages.resolveMany>>);+ await Promise.all([first, second]);+ });++ expect(resolveMany).toHaveBeenCalledOnce();+ expect(mocks.notifyInfo).toHaveBeenCalledExactlyOnceWith(+ expect.any(String),+ 'widgets.gallery.itemActions.recall.recallInProgress'+ );+ expect(mocks.notifySuccess).toHaveBeenCalledOnce();+ expect(store.queries.getSnapshot().activeProject.canvas.snapshots).toHaveLength(1);++ // Once it has committed, the next press recalls again.+ resolveMany.mockResolvedValue([{ imageName: 'recorded.png' }] as Awaited<+ ReturnType<typeof galleryImages.resolveMany>+ >);+ await recall('all');+ expect(mocks.notifySuccess).toHaveBeenCalledTimes(2);+});+it('recalls Generate settings and reports a partial result when canvas assets cannot load', async () => {accountLifecycle.activate('queue-canvas-failed-recall');const main = { base: 'sdxl', key: 'queue-main', name: 'SDXL', type: 'main' } as MainModelConfig &@@ -455,6 +540,10 @@ it.each(['project', 'account', 'promotion-failure', 'project-promotion-failure']);expect(mocks.openWidget).toHaveBeenCalledOnce();expect(mocks.notifySuccess).toHaveBeenCalledOnce();+ // Committed, so saving the images holds no other recall back.+ const nextRecall = claimCanvasRecall(captureAccountScope());+ expect(nextRecall).not.toBeNull();+ nextRecall!();mocks.store!.commands.generation.setSettings({ ...getDefaultGenerateSettings(main), model: main, steps: 47 },projectIddiff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.tsindex 5ef6d841c9..c3a43f2fe0 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/useQueueItemRecall.ts@@ -1,55 +1,81 @@import type { QueueGenerationMeta } from '@features/queue/contracts';-import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-actions';-import type * as CanvasRecallModule from '@workbench/image-actions/canvasRecall';+import type { ImageRecallKind } from '@workbench/image-actions';+import { createGenerateFormValuesSelector } from '@features/generation/react';+import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';import { hasArchitectureCapabilities, isSupportedGenerateModel } from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';import { useMountEffect } from '@platform/react/useMountEffect';-import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';-import {- EMPTY_IMAGE_RECALL_CAPABILITIES,- getCurrentGenerateValues,- getImageRecallTitle,-} from '@workbench/image-actions';+import { useExternalStoreSelector } from '@platform/state/selectors';+import { EMPTY_IMAGE_RECALL_CAPABILITIES, getCurrentGenerateValues } from '@workbench/image-actions';import { useNotify } from '@workbench/useNotify';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';-import { getResolvedProjectWidgetValues } from '@workbench/widgetState';-import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';+import { useWidgetValuesSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { getQueueRecallCapabilities, getVideoQueueRecallCapabilities, planQueueRecall } from './queueRecall';+import { executeQueueItemRecall } from './executeQueueItemRecall';+import {+ getQueueRecallAvailability,+ getQueueRecallSource,+ getQueueRecallTargetState,+ type QueueRecallAvailability,+} from './queueRecall';import { useLocalRecallSnapshot } from './useLocalRecallSnapshot';+export interface QueueItemRecall extends QueueRecallAvailability {+ /** The durable snapshot lookup has not answered yet: everything is unavailable, with no reason to give. */+ isPending: boolean;+ recall: (kind: ImageRecallKind) => Promise<void>;+}++const selectGenerateValues = createGenerateFormValuesSelector();+const NO_REASONS: QueueRecallAvailability['reasons'] = {};+/**- * Recall local submission snapshots or foreign session prompts/seed into the active project, then reveal the- * destination panel.+ * What an item's recall menus offer, and the recall itself. Mount it only for the item whose menu or details are+ * open: it reads the durable snapshot and loads the model catalog.*/export const useQueueItemRecall = (origin: string | null | undefined,- meta: QueueGenerationMeta-): { capabilities: ImageRecallCapabilities; isPending: boolean; recall: (kind: ImageRecallKind) => void } => {+ meta: QueueGenerationMeta,+ /** The server names a workflow the item ran: without a snapshot, the only sign it holds no Generate settings. */+ { isNonGenerateRun = false }: { isNonGenerateRun?: boolean } = {}+): QueueItemRecall => {const { t } = useTranslation();const commands = useWorkbenchCommands();- const { generation, widgets } = commands;const queries = useWorkbenchQueries();const openWidget = useOpenWorkbenchWidget();const notify = useNotify();const snapshot = useLocalRecallSnapshot(origin);const isPending = snapshot === undefined;- const localGenerateValues = snapshot?.generateValues ?? null;- const videoSnapshot = snapshot?.videoValues ?? null;- const isVideoItem = snapshot?.sourceId === 'video';const models = useModelsSelector((state) => state.models);+ const isCatalogSettled = useModelsSelector((state) => state.status === 'loaded' || state.status === 'error');const supportedModels = useMemo(() => models.filter(isSupportedGenerateModel), [models]);- const capabilities = useMemo(+ const generateValues = useWidgetValuesSelector('generate', selectGenerateValues);+ // Read under the capability store: Generate values synthesized from architecture policy appear with its table.+ const target = useExternalStoreSelector(+ subscribeArchitectureCapabilities,+ getArchitectureCapabilitiesSnapshot,+ useCallback(+ () =>+ getQueueRecallTargetState({+ hasCapabilityTable: hasArchitectureCapabilities(),+ hasCurrentValues: getCurrentGenerateValues({ generateValues, supportedModels }) !== null,+ isCatalogSettled,+ }),+ [generateValues, isCatalogSettled, supportedModels]+ )+ );+ const source = getQueueRecallSource(snapshot?.sourceId ?? null, isNonGenerateRun);+ const generateSnapshot = snapshot?.generateValues ?? null;+ const videoSnapshot = snapshot?.videoValues ?? null;+ const availability = useMemo<QueueRecallAvailability>(() =>isPending- ? EMPTY_IMAGE_RECALL_CAPABILITIES- : isVideoItem- ? getVideoQueueRecallCapabilities(videoSnapshot, meta)- : getQueueRecallCapabilities(localGenerateValues, meta),- [isPending, isVideoItem, localGenerateValues, meta, videoSnapshot]+ ? { capabilities: EMPTY_IMAGE_RECALL_CAPABILITIES, reasons: NO_REASONS }+ : getQueueRecallAvailability({ meta, snapshot: generateSnapshot, source, target, videoSnapshot }),+ [generateSnapshot, isPending, meta, source, target, videoSnapshot]);useMountEffect(() => {@@ -57,153 +83,21 @@ export const useQueueItemRecall = (});const recall = useCallback(- async (kind: ImageRecallKind) => {- const owner = captureAccountScope();- const originalProject = queries.getSnapshot().activeProject;- if (isPending) {- return;- }- const readCurrentValues = () => {- const project = queries.getProject(originalProject.id);- return project- ? getCurrentGenerateValues({- generateValues: getResolvedProjectWidgetValues(project, 'generate', queries.getSnapshot().scopedDefaults),- supportedModels,- })- : null;- };- const current = readCurrentValues();- let plan = planQueueRecall(kind, { current, isVideoItem, meta, snapshot: localGenerateValues, videoSnapshot });-- if (!plan) {- // Use a generic unavailable reason: Video and missing capabilities are not missing Generate models.- const reason = isVideoItem- ? 'widgets.queue.recallUnavailableForItem'- : !current && !hasArchitectureCapabilities()- ? 'widgets.queue.recallUnavailableCapabilities'- : 'widgets.queue.recallUnavailable';- notify.info(getImageRecallTitle(kind, t), t(reason));- return;+ (kind: ImageRecallKind) => {+ if (snapshot === undefined) {+ return Promise.resolve();}-- if (plan.target === 'video') {- widgets.patchValues('video', plan.patch);- openWidget('video', { preferredRegions: ['left'] });- notify.success(getImageRecallTitle(kind, t), t('widgets.queue.settingsRecalledIntoVideoDescription'));- return;- }-- let canvasRecall: typeof CanvasRecallModule | null = null;- let canvasPlan: CanvasRecallModule.CanvasRecallPlan | null = null;- let canvasProblem: string | null = null;- let canvasApplied = false;- const preparedModelKey = plan.values.model?.key;- if ((kind === 'all' || kind === 'remix') && snapshot?.canvasMetadata) {- try {- canvasRecall = await import('@workbench/image-actions/canvasRecall');- canvasPlan = await canvasRecall.prepareCanvasRecall({- metadata: snapshot.canvasMetadata,- model: plan.values.model,- models,- owner,- isCurrent: () =>- queries.isActiveProject(originalProject.id) &&- queries.getProject(originalProject.id)?.canvas.document === originalProject.canvas.document,- });- await canvasRecall.settleCanvasRecall(- canvasPlan,- {- commands,- projectId: originalProject.id,- getProject: () => queries.getProject(originalProject.id) ?? null,- },- owner- );- } catch (error) {- canvasPlan = null;- canvasProblem = error instanceof Error ? error.message : 'unavailable';- }- }- if (!isAccountScopeCurrent(owner) || !queries.isActiveProject(originalProject.id)) {- return;- }- // Asset reads and paint persistence may yield; retain edits made while the canvas was loading.- plan = planQueueRecall(kind, {- current: readCurrentValues(),- isVideoItem,+ return executeQueueItemRecall({+ context: { commands, notify, openWidget, queries, t },+ isNonGenerateRun,+ kind,meta,- snapshot: localGenerateValues,- videoSnapshot,+ models,+ snapshot,});- if (!plan || plan.target !== 'generate') {- return;- }- if (canvasPlan && canvasRecall) {- try {- if (preparedModelKey !== plan.values.model?.key) {- canvasPlan.problems.push('model-changed');- } else {- canvasApplied = canvasRecall.commitCanvasRecall({- plan: canvasPlan,- expectedDocument: originalProject.canvas.document,- target: {- commands,- projectId: originalProject.id,- getProject: () =>- queries.isActiveProject(originalProject.id) ? (queries.getProject(originalProject.id) ?? null) : null,- },- restorePointName: t('widgets.gallery.itemActions.recall.beforeCanvasRecall'),- });- }- if (canvasPlan.problems.length) {- canvasProblem = canvasRecall.getCanvasRecallProblemsMessage(canvasPlan.problems, t);- }- } catch (error) {- canvasProblem = error instanceof Error ? error.message : 'unavailable';- }- }- if (canvasProblem) {- notify.info(- getImageRecallTitle(kind, t),- t('widgets.gallery.itemActions.recall.canvasPartial', { items: canvasProblem })- );- }- generation.setSettings(plan.values, originalProject.id);- openWidget('generate', { preferredRegions: ['left'] });- notify.success(getImageRecallTitle(kind, t), t('widgets.queue.settingsRecalledDescription'));- if (canvasApplied && canvasPlan && canvasRecall) {- const durable = await canvasRecall.finalizeCanvasRecallAssets(- canvasPlan,- {- commands,- projectId: originalProject.id,- getProject: () => queries.getProject(originalProject.id) ?? null,- },- owner- );- if (!durable && isAccountScopeCurrent(owner) && queries.isActiveProject(originalProject.id)) {- notify.info(getImageRecallTitle(kind, t), t('widgets.gallery.itemActions.recall.canvasImagesTemporary'));- }- }},- [- commands,- queries,- snapshot,- models,- generation,- isPending,- isVideoItem,- localGenerateValues,- meta,- notify,- openWidget,- supportedModels,- t,- videoSnapshot,- widgets,- ]+ [commands, isNonGenerateRun, meta, models, notify, openWidget, queries, snapshot, t]);- return { capabilities, isPending, recall };+ return { ...availability, isPending, recall };};diff --git a/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsxindex c723c75910..8c1589e6b3 100644--- a/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/DatabaseMaintenance.browser.test.tsx@@ -25,13 +25,11 @@ const mocks = vi.hoisted(() => ({vi.mock('@features/identity', async (importOriginal) => ({...(await importOriginal<typeof IdentityModule>()),AccountMenu: () => null,- AccountMenuSection: () => null,useCapabilities: () => ({canManageAppConfig: mocks.canManageAppConfig,canManageModels: false,canManageNodes: false,}),- useHasAccountSection: () => false,}));vi.mock('@platform/transport/http', async (importOriginal) => ({...(await importOriginal<typeof HttpModule>()),@@ -55,7 +53,10 @@ vi.mock('@tanstack/react-router', async (importOriginal) => ({}));vi.mock('@workbench/palette/PaletteButton', () => ({ PaletteButton: () => null }));vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));-vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({ useShortcutLabel: () => null }));+vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({+ useShortcutBinding: () => null,+ useShortcutLabel: () => null,+}));vi.mock('./store', async (importOriginal) => ({...(await importOriginal<typeof SettingsStoreModule>()),useWorkbenchSettingsSelector: (selector: (snapshot: never) => unknown) => selector({ scope: 'user' } as never),diff --git a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsxindex 7a03a6a5df..459a6972e9 100644--- a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx@@ -72,7 +72,10 @@ vi.mock('@tanstack/react-router', async (importOriginal) => ({}));vi.mock('@workbench/palette/PaletteButton', () => ({ PaletteButton: () => null }));vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));-vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({ useShortcutLabel: () => null }));+vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({+ useShortcutBinding: () => null,+ useShortcutLabel: () => null,+}));vi.mock('./store', async (importOriginal) => ({...(await importOriginal<typeof SettingsStoreModule>()),useWorkbenchSettingsSelector: (selector: (snapshot: never) => unknown) => selector({ scope: 'user' } as never),diff --git a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsxindex b590052938..42ae540b45 100644--- a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx@@ -33,6 +33,7 @@ const SCOPE_LABEL_KEYS: Record<HotkeyCategory, string> = {app: 'hotkeys.scopes.focusedPanel',canvas: 'hotkeys.categories.canvas',gallery: 'hotkeys.categories.gallery',+ queue: 'hotkeys.categories.queue',viewer: 'hotkeys.categories.viewer',workflows: 'hotkeys.categories.workflows',};@@ -47,11 +48,12 @@ const CATEGORY_LABEL_KEYS: Record<HotkeyCategory, string> = {app: 'hotkeys.categories.app',canvas: 'hotkeys.categories.canvas',gallery: 'hotkeys.categories.gallery',+ queue: 'hotkeys.categories.queue',viewer: 'hotkeys.categories.viewer',workflows: 'hotkeys.categories.workflows',};-const CATEGORY_ORDER: HotkeyCategory[] = ['app', 'canvas', 'workflows', 'viewer', 'gallery'];+const CATEGORY_ORDER: HotkeyCategory[] = ['app', 'canvas', 'workflows', 'viewer', 'gallery', 'queue'];const SEARCH_START_ELEMENT = <Icon as={SearchIcon} boxSize="3.5" />;const NO_MATCHES_ICON = <Icon as={SearchIcon} />;diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsxindex e4edf354db..ebc4896357 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.browser.test.tsx@@ -75,7 +75,9 @@ const quickWidgetProps: WidgetViewProps = {runtime: {} as WidgetRuntimeApi,};-const render = async (quick = false) => {+const queueWidgetProps: WidgetViewProps = { ...quickWidgetProps, manifest: queueWidgetManifest };++const render = async (widget?: WidgetViewProps) => {await act(() =>root.render(<ChakraProvider value={system}>@@ -83,7 +85,7 @@ const render = async (quick = false) => {<button type="button" onClick={() => openWorkbenchSettings('behavior')}>Open settings</button>- {quick ? <WidgetSettingsButton {...quickWidgetProps} /> : null}+ {widget ? <WidgetSettingsButton {...widget} /> : null}<SettingsDialogHost /></I18nextProvider></ChakraProvider>@@ -331,7 +333,7 @@ describe('settings dialog', () => {});it('returns focus to the widget gear when quick settings close with Escape', async () => {- await render(true);+ await render(quickWidgetProps);const gear = page.getByRole('button', {name: i18n.t('widgets.settingsLabel', { label: 'Appearance' }),exact: true,@@ -343,8 +345,27 @@ describe('settings dialog', () => {await expect.element(gear).toHaveFocus();});+ it("edits the Queue's job scope from its gear without opening the dialog", async () => {+ await render(queueWidgetProps);+ await act(() =>+ page.getByRole('button', { name: i18n.t('widgets.settingsLabel', { label: 'Queue' }), exact: true }).click()+ );+ const scope = page.getByRole('combobox', { name: 'Show jobs from', exact: true });+ await expect.element(scope).toHaveTextContent('All projects');+ await userEvent.click(scope);+ await userEvent.click(page.getByRole('option', { name: 'Active project', exact: true }));+ await expect.poll(() => getWorkbenchPreferences().queueJobsScope).toBe('active-project');+ await expect.element(scope).toHaveTextContent('Active project');+ expect(settingsDialogStore.getSnapshot().isOpen).toBe(false);+ await expect+ .element(+ page.getByRole('button', { name: i18n.t('settingsDialog.allWidgetSettings', { widget: 'Queue' }), exact: true })+ )+ .toBeVisible();+ });+it('hands quick settings to the full section and restores the widget gear', async () => {- await render(true);+ await render(quickWidgetProps);const gear = page.getByRole('button', {name: i18n.t('widgets.settingsLabel', { label: 'Appearance' }),exact: true,diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogTarget.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogTarget.browser.test.tsxindex c63b5319de..70054ed858 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogTarget.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialogTarget.browser.test.tsx@@ -11,6 +11,7 @@ import { useExternalStoreSelector } from '@platform/state/selectors';import { system } from '@theme/system';import { canvasWidgetManifest } from '@workbench/widgets/canvas/manifest';import { generateWidgetManifest } from '@workbench/widgets/generate/manifest';+import { imageMapWidgetManifest } from '@workbench/widgets/image-map/manifest';import { getResolvedProjectWidgetValues, resolveWidgetValues } from '@workbench/widgetState';import { createInitialWorkbenchState } from '@workbench/workbenchState';import { createWorkbenchStore } from '@workbench/workbenchStore';@@ -239,3 +240,39 @@ it("shows the project's generation flags behind the Generate cog, and pins and f.element(page.getByRole('checkbox', { name: i18n.t('settings.catalog.useNsfwChecker.label'), exact: true })).not.toBeChecked();});++it('pins the Image Map clustering strength and cluster click behavior from its gear', async () => {+ const store = storeRef.current!;+ const project = store.getSnapshot().activeProject;+ const imageMap = Object.values(project.widgetInstances).find((instance) => instance.typeId === 'image-map')!;+ const values = () => store.getSnapshot().activeProject.widgetInstances[imageMap.id]!.state.values;+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <WidgetSettingsButton+ {...widgetProps}+ instance={{ ...imageMap, title: 'Image Map' }}+ manifest={imageMapWidgetManifest}+ />+ </I18nextProvider>+ </ChakraProvider>+ )+ );+ await act(() => page.getByRole('button', { name: 'Image Map settings', exact: true }).click());+ // The custom clustering-strength editor renders in the popover like the shared controls around it.+ const strength = page.getByRole('spinbutton', { name: i18n.t('settingsDialog.fields.clusterStrength'), exact: true });+ await expect.element(strength).toBeVisible();+ await act(() => strength.fill('0.25'));+ await expect.poll(() => values().clusterEps, { timeout: 3000 }).toBe(0.25);++ const clickSelects = page.getByRole('checkbox', {+ name: i18n.t('settingsDialog.fields.clickSelectsCluster'),+ exact: true,+ });+ await expect.element(clickSelects).toBeVisible();+ const wasChecked = (clickSelects.element() as HTMLInputElement).checked;+ await act(() => page.getByText(i18n.t('settingsDialog.fields.clickSelectsCluster'), { exact: true }).click());+ await expect.poll(() => values().clickSelectsCluster).toBe(!wasChecked);+ expect(settingsDialogStore.getSnapshot().isOpen).toBe(false);+});diff --git a/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts b/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.tsindex ecc64f9d7c..8e79af05d2 100644--- a/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/applicationContributions.ts@@ -84,7 +84,7 @@ export const behaviorSettings = section('behavior', 'Behavior', [{ value: 'recentProject', label: text('options.recentProject', 'Most recent project') },],},- preference('autoSwitchInvocationRoute', 'Invoke follows what you edit', 'route source destination'),+ preference('autoSwitchInvocationRoute', "Auto-switch Invoke to what you're editing", 'route source destination'),preference('enableInformationalPopovers', 'Enable informational popovers', 'help tooltips'),preference('enableModelDescriptions', 'Show descriptions in model pickers', 'models dropdowns'),preference('notifyOnEnqueue', 'Notify when queued', 'notifications queue'),@@ -100,41 +100,48 @@ export const galleryPreferenceSettings = section('gallery', 'Gallery', [export const previewPreferenceSettings = section('preview', 'Preview', [preference('antialiasProgressImages', 'Antialias progress images'),]);-export const workflowSettings = section('workflow', 'Workflow', [- {- id: 'workflowEdgeStyle',- label: text('workflowEdgeStyle.label', 'Connection style'),- description: text('workflowEdgeStyle.description'),- kind: 'select',- scope: 'preference',- options: [- { value: 'curved', label: text('options.curved', 'Curved') },- { value: 'square', label: text('options.square', 'Square') },- ],- },- preference(- 'workflowEdgesBehindNodes',- 'Keep highlighted connections behind nodes',- 'workflow edges wires links z-order'- ),- preference('workflowSnapToGrid', 'Always snap to grid', 'workflow nodes'),- preference('workflowGroupNodesByCategory', 'Group node search by category', 'workflow nodes add search categories'),- preference('workflowShowMinimap', 'Show minimap'),- preference('workflowValidateConnections', 'Validate connections', 'workflow edges'),-]);-export const queueSettings = section('queue', 'Queue', [- {- id: 'queueJobsScope',- label: text('queueJobsScope.label', 'Show jobs from'),- description: text('queueJobsScope.description'),- kind: 'select',- scope: 'preference',- options: [- { value: 'active-project', label: text('options.activeProject', 'Active project') },- { value: 'all', label: text('options.all', 'All projects') },- ],- },-]);+export const workflowSettings: SettingsContribution = {+ ...section('workflow', 'Workflow', [+ {+ id: 'workflowEdgeStyle',+ label: text('workflowEdgeStyle.label', 'Connection style'),+ description: text('workflowEdgeStyle.description'),+ kind: 'select',+ scope: 'preference',+ options: [+ { value: 'curved', label: text('options.curved', 'Curved') },+ { value: 'square', label: text('options.square', 'Square') },+ ],+ },+ preference(+ 'workflowEdgesBehindNodes',+ 'Keep highlighted connections behind nodes',+ 'workflow edges wires links z-order'+ ),+ preference('workflowSnapToGrid', 'Always snap to grid', 'workflow nodes'),+ preference('workflowGroupNodesByCategory', 'Group node search by category', 'workflow nodes add search categories'),+ preference('workflowShowMinimap', 'Show minimap'),+ preference('workflowValidateConnections', 'Validate connections', 'workflow edges'),+ ]),+ // What people change while arranging a graph; the rest stay in the dialog.+ quick: ['workflowSnapToGrid', 'workflowShowMinimap', 'workflowEdgeStyle'],+};+export const queueSettings: SettingsContribution = {+ ...section('queue', 'Queue', [+ {+ id: 'queueJobsScope',+ label: text('queueJobsScope.label', 'Show jobs from'),+ description: text('queueJobsScope.description'),+ kind: 'select',+ scope: 'preference',+ options: [+ { value: 'active-project', label: text('options.activeProject', 'Active project') },+ { value: 'all', label: text('options.all', 'All projects') },+ ],+ },+ ]),+ quick: ['queueJobsScope'],+};export const imageMapVocabularySettings = section('imageMap', 'Image Map', [custom('imageMapVocabulary', 'Vocabulary', 'server'),]);diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsindex bca1f4d7a8..89604f89d0 100644--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -1,3 +1,4 @@+import type { AutoSwitchMode } from '@features/queue/contracts';import type { WorkbenchLanguage } from '@platform/i18n/languages';import type { LogLevel, LogNamespace } from '@platform/logging/contracts';import type { SettingsTarget } from '@platform/ui/settings/contracts';@@ -5,6 +6,9 @@ import type { PromptFontSize } from '@theme/scale';import type { WorkbenchThemeId } from '@theme/themes';import type { ProjectSortId, ProjectsViewId } from '@workbench/launchpad/projects/projectLibraryView';+/** Select Object starts with auto-update on until the person turns it off. */+export const DEFAULT_SELECT_OBJECT_AUTO_UPDATE = true;+export type { ProjectSortId, ProjectsViewId } from '@workbench/launchpad/projects/projectLibraryView';export type { WorkbenchLanguage } from '@platform/i18n/languages';@@ -49,11 +53,8 @@ export interface ProjectSettings {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';+/** The Preview's Auto-switch: the shared policy's modes (`AutoSwitchMode`, rules in `@features/queue/contracts`). */+export type ViewerAutoSwitchMode = AutoSwitchMode;/** {@link ProjectSettings} with every layered flag resolved: project pin, then the user's default, then built-in. */export type EffectiveProjectSettings = Required<ProjectSettings>;@@ -159,8 +160,12 @@ export interface WorkbenchPreferences {workflowLibraryThumbnailFit: WorkflowLibraryThumbnailFit;/** Raise text and border contrast on every theme (a11y). */highContrast: boolean;- /** Select Object processes each prompt edit automatically; kept across sessions, Reset, and reloads. */- selectObjectAutoProcess: boolean;+ /**+ * Select Object updates its preview after each input change; kept across sessions, Reset, and reloads. Stored under+ * a new name since auto-update became the default: the old `selectObjectAutoProcess` field was written as `false` by+ * any settings save, so it cannot tell a choice from the old default, and normalization drops it.+ */+ selectObjectAutoUpdate: boolean;/** Account-bound overrides keyed by hotkey id (`app.invoke`, `gallery.galleryNavLeft`, etc.). */customHotkeys: Record<string, string[]>;/** Generate panel section open/closed overrides keyed by section id; absent = section default. */diff --git a/invokeai/frontend/webv2/src/workbench/settings/projectSettings.ts b/invokeai/frontend/webv2/src/workbench/settings/projectSettings.tsindex 0c9adb671b..b70fcd953b 100644--- a/invokeai/frontend/webv2/src/workbench/settings/projectSettings.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/projectSettings.ts@@ -120,8 +120,20 @@ export const getLayeredKeys = (ownerId: string): Readonly<Record<string, Layeredreturn ownerId === PROJECT_SETTINGS_OWNER ? table.projectSettings : table.widgetValues[ownerId];};+/**+ * Every Auto-switch mode, keyed by the shared policy's union (`ViewerAutoSwitchMode` is `AutoSwitchMode`): a mode added+ * there fails to compile here until it is listed, so a stored value is never reset to `off` for being unknown. A record+ * rather than the policy's own list: importing it would bring the Queue contracts into the boot graph with the+ * settings store.+ */+const VIEWER_AUTO_SWITCH_MODES: Readonly<Record<ViewerAutoSwitchMode, true>> = {+ latest: true,+ off: true,+ progress: true,+};+export const isViewerAutoSwitchMode = (value: unknown): value is ViewerAutoSwitchMode =>- value === 'off' || value === 'latest' || value === 'progress';+ typeof value === 'string' && Object.hasOwn(VIEWER_AUTO_SWITCH_MODES, value);/** Keeps the project's own pins (absent follows the user's default) and drops everything else it does not own. */export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): ProjectSettings => {diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex dec3174526..573092b67e 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -445,13 +445,31 @@ describe('normalizeWorkbenchPreferences appearance', () => {});});-describe('normalizeWorkbenchPreferences canvas operations', () => {- it('keeps Select Object auto-process off unless it was stored as on', () => {- expect(store.normalizeWorkbenchPreferences({}).selectObjectAutoProcess).toBe(false);+describe('Select Object auto-update preference', () => {+ it('starts on for an account whose saves wrote the old auto-process field as false', async () => {+ seedBackendPreferences({ selectObjectAutoProcess: false, themeId: 'osakaJade' });++ expect((await store.loadWorkbenchSettings()).selectObjectAutoUpdate).toBe(true);+ await store.patchWorkbenchPreferences({ reduceMotion: true });++ expect(readBackendPreferences()).not.toHaveProperty('selectObjectAutoProcess');+ expect(readBackendPreferences().selectObjectAutoUpdate).toBe(true);+ });++ it('keeps a choice made after the change across a reload', async () => {+ await store.loadWorkbenchSettings();+ await store.patchWorkbenchPreferences({ selectObjectAutoUpdate: false });++ vi.resetModules();+ store = await import('./store');++ expect((await store.loadWorkbenchSettings()).selectObjectAutoUpdate).toBe(false);+ });++ it('ignores a stored value that is not a boolean', () => {expect(- store.normalizeWorkbenchPreferences({ selectObjectAutoProcess: 'true' as never }).selectObjectAutoProcess- ).toBe(false);- expect(store.normalizeWorkbenchPreferences({ selectObjectAutoProcess: true }).selectObjectAutoProcess).toBe(true);+ store.normalizeWorkbenchPreferences({ selectObjectAutoUpdate: 'false' as never }).selectObjectAutoUpdate+ ).toBe(true);});});diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex 2dc2c75329..10f0f11001 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -26,6 +26,7 @@ import { isPromptFontSize } from '@theme/scale';import { DEFAULT_THEME_ID, resolveWorkbenchThemeId } from '@theme/themes';import { deleteClientStateValue, getClientStateValue, setClientStateValue } from '@workbench/projects/api';import { fetchSessionBlob } from '@workbench/projects/session';+import { DEFAULT_SELECT_OBJECT_AUTO_UPDATE } from '@workbench/settings/contracts';import { getLayeredKeys } from '@workbench/settings/projectSettings';export { WORKBENCH_LANGUAGES } from '@platform/i18n/languages';@@ -72,7 +73,7 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {queueJobsScope: 'all',reduceMotion: false,scopedDefaults: {},- selectObjectAutoProcess: false,+ selectObjectAutoUpdate: DEFAULT_SELECT_OBJECT_AUTO_UPDATE,showPromptSyntaxHighlighting: true,showFocusRegionHighlight: true,startupDestination: 'launchpad',@@ -514,10 +515,10 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferencesreduceMotion:typeof preferences?.reduceMotion === 'boolean' ? preferences.reduceMotion : DEFAULT_PREFERENCES.reduceMotion,scopedDefaults: normalizeScopedDefaults(preferences?.scopedDefaults),- selectObjectAutoProcess:- typeof preferences?.selectObjectAutoProcess === 'boolean'- ? preferences.selectObjectAutoProcess- : DEFAULT_PREFERENCES.selectObjectAutoProcess,+ selectObjectAutoUpdate:+ typeof preferences?.selectObjectAutoUpdate === 'boolean'+ ? preferences.selectObjectAutoUpdate+ : DEFAULT_PREFERENCES.selectObjectAutoUpdate,showFocusRegionHighlight:typeof preferences?.showFocusRegionHighlight === 'boolean'? preferences.showFocusRegionHighlightdiff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsxindex 0da6a2d2b2..1de4705681 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx@@ -1,5 +1,5 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */-import { Box, ChakraProvider, HStack, Text } from '@chakra-ui/react';+import { Box, ChakraProvider, HStack, Menu, Portal, Text } from '@chakra-ui/react';import { system } from '@theme/system';import { createWidgetRecovery } from '@workbench/widget-frame/widgetRecoveryStore';import { createInstance } from 'i18next';@@ -449,17 +449,28 @@ describe('CenterArea with the workflow editor chrome at a narrow width', () => {const snapshot = {activeWorkflow: { document, source: linkedSource },activeWorkflowId: document.id,+ // A step to undo and one to redo, so both history buttons are live targets.+ canRedo: true,+ canUndo: true,id: 'project-1',projectGraph: document,workflows: [{ document, source: linkedSource }],};const port = <T,>(value: T) => ({ getSnapshot: () => value, subscribe: () => () => {} });const adapter = {+ CommandShortcut: () => null,+ commands: { redo: () => undefined, undo: () => undefined },+ getProjectGraph: () => document,persistence: port({ error: null, hasLocalRecovery: true, lastSavedAt: null, status: 'saved' }),project: port(snapshot),+ widgets: { open: () => undefined, patchValues: () => undefined },} as unknown as Parameters<typeof WorkflowUiProvider>[0]['adapter'];const Label = implementation.headerLabel as ComponentType<{ region: 'center' }>;- const Actions = implementation.headerActions as ComponentType<{ region: 'center' }>;+ // The frame hands both slots the same instance's runtime; the menu answers for the header beside it.+ const runtime = { instanceId: 'workflow:center', region: 'center', typeId: 'workflow' };+ const HeaderActions = implementation.headerActions as ComponentType<{ region: 'center'; runtime: typeof runtime }>;+ const MenuItems = implementation.headerMenu as ComponentType<{ region: 'center'; runtime: typeof runtime }>;+ const Actions = ({ region }: { region: 'center' }) => <HeaderActions region={region} runtime={runtime} />;centerAreaMocks.chromeSlots = { actions: Actions, label: Label };centerAreaMocks.activeItem.label = 'Workflow';@@ -468,6 +479,16 @@ describe('CenterArea with the workflow editor chrome at a narrow width', () => {<QueryClientProvider client={new QueryClient()}><WorkflowUiProvider adapter={adapter}><CenterArea />+ {/* The widget's ⋯ menu entries, held open beside the chrome the frame stand-in replaces. */}+ <Menu.Root open>+ <Portal>+ <Menu.Positioner>+ <Menu.Content>+ <MenuItems region="center" runtime={runtime} />+ </Menu.Content>+ </Menu.Positioner>+ </Portal>+ </Menu.Root></WorkflowUiProvider></QueryClientProvider>,320@@ -495,10 +516,28 @@ describe('CenterArea with the workflow editor chrome at a narrow width', () => {];expect(workflowsButton).not.toBeNull();- expect(actions.length).toBe(source ? 6 : 5);+ // The library actions keep their place; Undo and Redo give way to the ⋯ menu, so nothing overflows into a scroll.+ expect(+ actions.filter((action) => action.checkVisibility()).map((action) => action.getAttribute('aria-label'))+ ).toEqual([+ 'widgets.workflow.addNode',+ 'widgets.workflow.saveToLibraryWithEllipsis',+ ...(source ? ['widgets.workflow.updateTemplateWithEllipsis'] : []),+ 'widgets.workflow.persistenceSaved',+ 'Widget settings',+ 'Widget menu',+ ]);+ await vi.waitFor(() =>+ expect([...document.querySelectorAll('[role="menuitem"]')].slice(0, 2).map((item) => item.textContent)).toEqual([+ 'widgets.workflow.toolbar.undo',+ 'widgets.workflow.toolbar.redo',+ ])+ );expect(isHitTestable(workflowsButton!)).toBe(true);expect(- actions.filter((action) => !isHitTestable(action)).map((action) => action.getAttribute('aria-label'))+ actions+ .filter((action) => action.checkVisibility() && !isHitTestable(action))+ .map((action) => action.getAttribute('aria-label'))).toEqual([]);});});diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsxindex 93b017e704..bac3a6ec5b 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx@@ -430,7 +430,7 @@ const CenterViewMenuRow = ({{...intentPreloadProps}onClick={handleClick}>- <Icon as={CheckIcon} boxSize="3" opacity={isActive ? 1 : 0} />+ <Icon as={CheckIcon} boxSize="3" color="fg" opacity={isActive ? 1 : 0} /><WidgetIcon icon={item.icon} boxSize="3.5" /><Menu.ItemText>{item.label}</Menu.ItemText></Menu.Item>diff --git a/invokeai/frontend/webv2/src/workbench/shell/ChromeIsland.tsx b/invokeai/frontend/webv2/src/workbench/shell/ChromeIsland.tsxindex 9ea2bdb25e..3e47728a23 100644--- a/invokeai/frontend/webv2/src/workbench/shell/ChromeIsland.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/ChromeIsland.tsx@@ -1,9 +1,10 @@import type { ReactNode } from 'react';import { Flex, HStack } from '@chakra-ui/react';+import { HIDDEN_SCROLLBAR_CSS } from '@platform/ui/scrollStripEdges';import { useTranslation } from 'react-i18next';-import { CUE_WIDTH, HIDDEN_SCROLLBAR_CSS, OverflowCue, ROW_PADDING_X, useOverflowEdges } from './overflowEdges';+import { CUE_WIDTH, OverflowCue, ROW_PADDING_X, useOverflowEdges } from './overflowEdges';/*** The narrowest island that still shows `controlWidth` of its row's start clear of the end cue: border, start padding,diff --git a/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx b/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsxindex dc515f7bf3..3e38ebe00f 100644--- a/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/StatusBar.tsx@@ -5,6 +5,7 @@ import type { PlacedWidgetRegionItem, WidgetPlacementInstanceMeta } from '@workbimport { Box, Flex, Icon, Popover, Portal } from '@chakra-ui/react';import { useDndContext, useDroppable } from '@dnd-kit/core';import { horizontalListSortingStrategy } from '@dnd-kit/sortable';+import { isEventFromOwnDom } from '@platform/react/isEventFromOwnDom';import { PopoverContent, Row, Tooltip } from '@platform/ui';import { Button } from '@platform/ui/Button';import { isModalPresent, subscribeModalPresence } from '@platform/ui/modalPresence';@@ -70,6 +71,11 @@ const WIDGET_POPOVER_POSITIONING = { placement: 'top-end' } as const;const BOTTOM_MENU_TRIGGER = { kind: 'bottom' } as const;/** Use content color for active brand accents; background tint is indistinguishable on the light theme. */const COMPACT_ROW_HOVER_PROPS = { bg: 'bg.hover', color: 'fg' };+/**+ * Chips read as SegmentTabs segments: rounded fills inset from the bar's edges (the strip's vertical padding) with a+ * small gap between them. Gaps sit inside the clusters, so the remaining-space chip's capacity already excludes them.+ */+const CHIP_GAP = '0.5';/** Size drop overlays per cluster so one strip-wide curtain cannot cover the other target. */const ClusterDropRing = ({ dropState, isOver }: { dropState: WidgetRegionDropState; isOver: boolean }) => (@@ -98,6 +104,7 @@ const BottomEndCluster = ({align="center"alignSelf="stretch"flexShrink={0}+ gap={CHIP_GAP}position="relative">{children}@@ -157,6 +164,10 @@ export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) =[startItems, endItems]);const openEnableMenu = useCallback((event: MouseEvent) => {+ // Chips' popovers, tooltips and the bar's own menus are portalled; a right-click in them is theirs.+ if (!isEventFromOwnDom(event)) {+ return;+ }event.preventDefault();setEnableMenuTarget({ x: event.clientX, y: event.clientY });}, []);@@ -203,11 +214,14 @@ export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) =const handleInstanceClose = useCallback(() => setInstanceMenuTarget(null), []);// The bottom panel's outline is drawn over this border.const isBottomOutlined = useHighlightedRegion() === 'bottom';+ const bottomWidgetsLabel = t('widgets.regionWidgets.bottom');return (<CompactWidgetCapacityProvider capacity={capacity}><WidgetStripalign="center"+ // The status bar's landmark, named like the rails beside it ("Left rail", "Right rail").+ aria-label={t('shell.widgets.placement.bottom')}as="footer"bg="bg.subtle"borderTopWidth="1px"@@ -217,14 +231,22 @@ export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) =flexShrink={0}h="6"overlay="none"- px="2"+ // The same inset on every side, so the end chips sit as close to the bar's edges as to its top and bottom.+ p={CHIP_GAP}region="bottom"sortableInstanceIds={sortableInstanceIds}strategy={horizontalListSortingStrategy}w="full"onContextMenu={openEnableMenu}>- <Flex data-status-bar-cluster align="center" alignSelf="stretch" flexShrink={0} position="relative">+ <Flex+ data-status-bar-cluster+ align="center"+ alignSelf="stretch"+ flexShrink={0}+ gap={CHIP_GAP}+ position="relative"+ >{startItems.map((item) => (<CompactBottomWidgetkey={item.id}@@ -237,11 +259,11 @@ export const StatusBar = ({ dropState }: { dropState: WidgetRegionDropState }) =<WidgetEnableMenucontextTarget={enableMenuTarget}- groupLabel="Bottom Widgets"+ groupLabel={bottomWidgetsLabel}items={items}positioning={BOTTOM_MENU_POSITIONING}trigger={BOTTOM_MENU_TRIGGER}- triggerLabel="Bottom widget visibility"+ triggerLabel={bottomWidgetsLabel}onContextClose={handleContextClose}onToggle={toggleBottomWidget}/>@@ -414,8 +436,9 @@ const CompactBottomWidget = ({aria-pressed={item.isPopover || recovery.error ? undefined : isRowActive}color={isRowActive ? undefined : 'fg.muted'}cursor={isDragging ? 'grabbing' : 'default'}- px={item.widget.manifest.compactSizing === 'remaining-space' ? '1.5' : undefined}+ px={item.widget.manifest.compactSizing === 'remaining-space' ? '2' : undefined}h="full"+ rounded="control"w="auto"{...(isRowActive ? COMPACT_ROW_ACTIVE_PROPS : null)}_hover={isRowActive ? COMPACT_ROW_ACTIVE_HOVER_PROPS : COMPACT_ROW_HOVER_PROPS}diff --git a/invokeai/frontend/webv2/src/workbench/shell/StatusBarContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/StatusBarContextMenu.browser.test.tsxnew file mode 100644index 0000000000..043511f1bd--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/StatusBarContextMenu.browser.test.tsx@@ -0,0 +1,230 @@+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+import type { WidgetRegion } from '@workbench/layoutContracts';+import type { Project, WorkbenchState } from '@workbench/projectContracts';+import type { RegisteredWidget, WidgetViewProps } from '@workbench/widgetContracts';+import type * as WidgetRegistry from '@workbench/widgetRegistry';+import type * as WorkbenchContext from '@workbench/WorkbenchContext';+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';++import { ChakraProvider } from '@chakra-ui/react';+import { DndContext, useSensor, useSensors } from '@dnd-kit/core';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { useExternalStoreSelector } from '@platform/state/selectors';+import { system } from '@theme/system';+import { createExtensionRegistry } from '@workbench/extensions/extensionRegistry';+import { FocusRegionProvider } from '@workbench/focusRegions';+import { createTestFocusController } from '@workbench/focusRegions.testing';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegistryContext';+import { createInstance } from 'i18next';+import { CircleIcon } from 'lucide-react';+import { act, type ReactNode, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { PrimaryMouseSensor } from './holdToDragSensor';+import { StatusBar } from './StatusBar';++const runtime = vi.hoisted(() => ({+ store: null as unknown as WorkbenchInternalStore,+ widgets: [] as RegisteredWidget[],+}));+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const extensions = createExtensionRegistry();+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContext>()),+ useWorkbenchInternalStore: () => runtime.store,+ useWorkbenchReload: () => () => Promise.resolve(),+ useWorkbenchExtensions: () => extensions,+ useOptionalWorkbenchExtensions: () => extensions,+ useWorkbenchCommands: () => runtime.store.commands,+ useOptionalWorkbenchCommands: () => runtime.store.commands,+ useWorkbenchQueries: () => runtime.store.queries,+ useOptionalWorkbenchQueries: () => runtime.store.queries,+ useActiveProjectId: () =>+ useExternalStoreSelector(runtime.store.subscribe, runtime.store.getSnapshot, (s) => s.activeProject.id),+ useActiveProjectSelector: <T,>(select: (project: Project) => T, equal?: (a: T, b: T) => boolean) =>+ useExternalStoreSelector(runtime.store.subscribe, runtime.store.getSnapshot, (s) => select(s.activeProject), equal),+}));+vi.mock('@workbench/widgetRegistry', async (importOriginal) => ({+ ...(await importOriginal<typeof WidgetRegistry>()),+ getWidgetById: (id: string) => runtime.widgets.find((widget) => widget.manifest.id === id),+ getWidgetsForRegion: (region: WidgetRegion) =>+ runtime.widgets.filter((widget) => widget.manifest.allowedRegions.includes(region)),+}));+const { registerWidgets } = await import('@workbench/widgetRegistry');+const getWidgetById = (id: string) => runtime.widgets.find((widget) => widget.manifest.id === id);+const getWidgetsForRegion = (region: WidgetRegion) =>+ runtime.widgets.filter((widget) => widget.manifest.allowedRegions.includes(region));+const i18n = createInstance();+await i18n+ .use(initReactI18next)+ .init({ lng: 'en', resources: { en: { translation: await fetch('/locales/en.json').then((r) => r.json()) } } });++const DROP_STATE = { helperText: '', isActive: false, isAllowed: false };+const STATUS_MENU_LABEL = 'Status bar widgets';++/** A popover body with plain content and a row that owns its own context menu, as notification rows do. */+const FixtureView = ({ presentation }: WidgetViewProps) => {+ const [ownMenuOpen, setOwnMenuOpen] = useState(false);+ if (presentation === 'compact') {+ return <span>Fixture chip</span>;+ }+ return (+ <div>+ <p>Fixture body</p>+ <div+ data-own-menu=""+ onContextMenu={(event) => {+ event.preventDefault();+ setOwnMenuOpen(true);+ }}+ >+ {ownMenuOpen ? 'Row menu open' : 'Fixture row'}+ </div>+ </div>+ );+};++const makeState = (): WorkbenchState => {+ const state = createInitialWorkbenchState();+ const project = state.projects[0]!;+ project.widgetInstances = {+ fixture: {+ id: 'fixture',+ typeId: 'fixture',+ createdAt: '2026-11-14',+ state: { id: 'fixture', label: 'fixture', values: {}, version: 1 },+ },+ };+ for (const region of Object.values(project.widgetRegions)) {+ region.instanceIds = [];+ region.activeInstanceId = '';+ }+ project.widgetRegions.bottom.instanceIds = ['fixture'];+ return state;+};++/** Every open menu naming the status bar's widgets: the widgets menu, opened from the bar. */+const statusMenus = () =>+ [...document.querySelectorAll<HTMLElement>('[role="menu"]')].filter(+ (menu) => menu.textContent?.includes(STATUS_MENU_LABEL) && menu.closest('[data-state="open"]') !== null+ );++/** Menus open within a frame of their event; give a leaked one two frames to show before checking. */+const expectNoStatusMenu = async () => {+ for (let frame = 0; frame < 2; frame++) {+ await new Promise((resolve) => {+ requestAnimationFrame(resolve);+ });+ }+ expect(statusMenus()).toHaveLength(0);+};++/** Records whether the page's handlers left a right-click's default (the browser's own menu) in place. */+const lastContextMenuDefault = () => {+ const seen: { prevented: boolean | null } = { prevented: null };+ const record = (event: Event) => {+ seen.prevented = event.defaultPrevented;+ };+ window.addEventListener('contextmenu', record);+ return {+ seen,+ release: () => window.removeEventListener('contextmenu', record),+ };+};++/** The shell's mouse sensor, so a click on a chip activates it instead of starting a drag. */+const ShellDnd = ({ children }: { children: ReactNode }) => {+ const sensors = useSensors(useSensor(PrimaryMouseSensor, { activationConstraint: { distance: 6 } }));+ return <DndContext sensors={sensors}>{children}</DndContext>;+};++let host: HTMLDivElement;+let root: Root;++beforeEach(async () => {+ await page.viewport(1280, 900);+ accountLifecycle.activate('status-bar-context-menu', ':user:status-bar-context-menu');+ runtime.widgets = registerWidgets([+ {+ id: 'fixture',+ label: 'Fixture',+ version: 1,+ icon: CircleIcon,+ allowedRegions: ['bottom'],+ allowMultiple: false,+ bottomPanel: 'popover',+ load: () => Promise.resolve({ view: FixtureView }),+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },+ },+ ]);+ runtime.store = createWorkbenchStore(makeState());+ host = document.createElement('div');+ host.style.cssText = 'display:flex;flex-direction:column;justify-content:flex-end;height:600px;width:1200px';+ document.body.append(host);+ root = createRoot(host);+ const focus = createTestFocusController({+ getProjectId: () => runtime.store.getSnapshot().activeProject.id,+ isFloating: () => false,+ });+ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <FocusRegionProvider controller={focus}>+ <WorkbenchWidgetRegistryProvider getWidgetById={getWidgetById} getWidgetsForRegion={getWidgetsForRegion}>+ <ShellDnd>+ <StatusBar dropState={DROP_STATE} />+ </ShellDnd>+ </WorkbenchWidgetRegistryProvider>+ </FocusRegionProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ await expect.poll(() => host.textContent).toContain('Fixture chip');+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ accountLifecycle.invalidate();+});++describe('status bar context menus', () => {+ it('leaves a right-click inside a widget popover to the popover', async () => {+ await userEvent.click(page.getByText('Fixture chip'));+ const popup = page.getByRole('dialog');+ await expect.element(popup.getByText('Fixture body')).toBeVisible();+ const contextMenu = lastContextMenuDefault();++ try {+ await userEvent.click(popup.getByText('Fixture body'), { button: 'right' });+ // The browser's own menu applies: nothing on the page claimed the event.+ expect(contextMenu.seen.prevented).toBe(false);+ await expectNoStatusMenu();++ await userEvent.click(popup.getByText('Fixture row'), { button: 'right' });+ await expect.element(popup.getByText('Row menu open')).toBeVisible();+ await expectNoStatusMenu();+ } finally {+ contextMenu.release();+ }++ await expect.element(popup).toBeVisible();+ });++ it("opens the widgets menu for a right-click on the bar's own surface", async () => {+ const bar = host.querySelector<HTMLElement>('footer')!;+ const bounds = bar.getBoundingClientRect();++ // The middle of the bar is its spacer, between the start cluster and the end cluster.+ await userEvent.click(bar, { button: 'right', position: { x: bounds.width / 2, y: bounds.height / 2 } });++ await expect.poll(() => statusMenus()).toHaveLength(1);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/overflowEdges.tsx b/invokeai/frontend/webv2/src/workbench/shell/overflowEdges.tsxindex f29b7efdf8..0b59d91542 100644--- a/invokeai/frontend/webv2/src/workbench/shell/overflowEdges.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/overflowEdges.tsx@@ -2,6 +2,7 @@ import type { MouseEvent } from 'react';import { Flex, Icon, Text } from '@chakra-ui/react';import { Button, IconButton } from '@platform/ui/Button';+import { measureHiddenEdges, SCROLL_EDGE_TOLERANCE_PX } from '@platform/ui/scrollStripEdges';import { Tooltip } from '@platform/ui/Tooltip';import { forwardWheelToStrip, wheelScrollsHorizontally } from '@platform/ui/wheelScrollsHorizontally';import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';@@ -25,9 +26,6 @@ export interface HiddenEdges {const NO_HIDDEN_EDGES: HiddenEdges = { end: false, endCount: 0, start: false };-// A fractional zoom can leave a sub-pixel remainder at either end of a fully scrolled row; that hides nothing.-const EDGE_TOLERANCE_PX = 1;-/** Fade plus the cue's button and the island's inline padding beside it. */export const CUE_WIDTH = '2.75rem';/** The row's inline padding; the cue covers the end padding, the start padding stays in front of the first control. */@@ -45,8 +43,6 @@ const CUE_CSS: Record<Edge, object> = {const MIRRORED_IN_RTL = { _rtl: { transform: 'scaleX(-1)' } } as const;-export const HIDDEN_SCROLLBAR_CSS = { '&::-webkit-scrollbar': { display: 'none' }, scrollbarWidth: 'none' } as const;-const prefersReducedMotion = (): boolean =>document.documentElement.dataset.reduceMotion === 'true' ||globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;@@ -72,18 +68,16 @@ const createHiddenEdgesStore = ({ itemSelector, keepInViewSelector }: OverflowEdif (!scroller) {return;}- // Right-to-left rows scroll toward negative offsets; the distance from the start is the same either way.- const offset = Math.abs(scroller.scrollLeft);- const range = scroller.scrollWidth - scroller.clientWidth;- const start = offset >= EDGE_TOLERANCE_PX;- const end = range - offset >= EDGE_TOLERANCE_PX;+ const { end, start } = measureHiddenEdges(scroller);const bounds = end && itemSelector ? scroller.getBoundingClientRect() : null;const isRtl = bounds !== null && getComputedStyle(scroller).direction === 'rtl';const endCount = bounds? [...scroller.querySelectorAll(itemSelector!)].filter((item) => {const rect = item.getBoundingClientRect();- return isRtl ? rect.left < bounds.left - EDGE_TOLERANCE_PX : rect.right > bounds.right + EDGE_TOLERANCE_PX;+ return isRtl+ ? rect.left < bounds.left - SCROLL_EDGE_TOLERANCE_PX+ : rect.right > bounds.right + SCROLL_EDGE_TOLERANCE_PX;}).length: 0;@@ -108,7 +102,7 @@ const createHiddenEdgesStore = ({ itemSelector, keepInViewSelector }: OverflowEdconst bounds = scroller.getBoundingClientRect();const rect = item.getBoundingClientRect();- if (rect.left < bounds.left - EDGE_TOLERANCE_PX || rect.right > bounds.right + EDGE_TOLERANCE_PX) {+ if (rect.left < bounds.left - SCROLL_EDGE_TOLERANCE_PX || rect.right > bounds.right + SCROLL_EDGE_TOLERANCE_PX) {item.scrollIntoView({ behavior: 'instant', block: 'nearest', inline: 'nearest' });}};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.browser.test.tsxindex 4d7197ce64..b44ec57586 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.browser.test.tsx@@ -9,9 +9,10 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';+const auth = vi.hoisted(() => ({ multiuser: true }));vi.mock('@features/identity/session', async (importOriginal) => {const original = await importOriginal<typeof SessionModule>();- const session: SessionModule.AuthSession = {+ const signedIn: SessionModule.AuthSession = {accountEpoch: 1,expiredUserId: null,multiuserEnabled: true,@@ -25,14 +26,16 @@ vi.mock('@features/identity/session', async (importOriginal) => {display_name: 'Ada',email: '[email protected]',is_active: true,- is_admin: false,+ is_admin: true,last_login_at: null,updated_at: '2026-01-01T00:00:00Z',user_id: 'ada',},};- return { ...original, useAuthSession: () => session };+ const singleUser: SessionModule.AuthSession = { ...signedIn, multiuserEnabled: false, user: null };++ return { ...original, useAuthSession: () => (auth.multiuser ? signedIn : singleUser) };});vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({...(await importOriginal<typeof WorkbenchContextModule>()),@@ -45,9 +48,22 @@ vi.mock('@tanstack/react-router', async (importOriginal) => ({useNavigate: () => vi.fn(),}));vi.mock('@workbench/useOpenWorkbenchWidget', () => ({ useOpenWorkbenchWidget: () => vi.fn() }));-vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({ useShortcutLabel: () => null }));+vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({+ // Settings has a binding; the command palette is unbound, so it advertises none.+ useShortcutBinding: (commandId: string) =>+ commandId === 'app.openSettings' ? { aria: 'Control+Comma', display: 'Ctrl+,', parts: ['ctrl', ','] } : null,+}));+// The real store preloads the whole settings dialog; the call is the contract the dialog honours.+const openSettings = vi.hoisted(() => vi.fn());+vi.mock('@workbench/settings/settingsDialogStore', () => ({ openWorkbenchSettings: openSettings }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+import {+ closeCommandPalette,+ commandPaletteStore,+ getCommandPaletteReturnFocusElement,+} from '@workbench/palette/paletteStore';+import { AppMenu } from './AppMenu';(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -62,41 +78,81 @@ beforeEach(() => {});afterEach(async () => {+ closeCommandPalette();+ auth.multiuser = true;await act(() => root.unmount());host.remove();});-const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');+const menuItems = () => [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+const itemNamed = (name: string) => menuItems().find((item) => item.textContent?.startsWith(name));++const openMenu = async () => {+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={new QueryClient()}>+ <AppMenu />+ </QueryClientProvider>+ </ChakraProvider>+ )+ );+ await act(() => userEvent.click(host.querySelector<HTMLButtonElement>('[aria-label="topbar.appMenu.open"]')!));+ await vi.waitFor(() => expect(itemNamed('topbar.appMenu.launchpad')).toBeDefined());+};describe('AppMenu', () => {- it('keeps Account settings open after the menu unmounts, and returns focus to the menu button', async () => {- await act(() =>- root.render(- <ChakraProvider value={system}>- <QueryClientProvider client={new QueryClient()}>- <AppMenu />- </QueryClientProvider>- </ChakraProvider>- )- );+ it('leads with Launchpad, Settings and the command palette as full items, each opening what it names', async () => {+ await openMenu();++ expect(+ menuItems()+ .map((item) => item.dataset.value)+ .slice(0, 3)+ ).toEqual(['launchpad', 'settings', 'command-palette']);+ // Keycaps show the binding but stay out of the name; aria-keyshortcuts announces it.+ const settings = itemNamed('common.settings')!;+ expect(settings.querySelector('kbd')?.closest('[aria-hidden="true"]')).not.toBeNull();+ expect(settings.getAttribute('aria-keyshortcuts')).toBe('Control+Comma');+ // Unbound: no shortcut is advertised.+ expect(itemNamed('commandPalette.buttonLabel')?.querySelector('kbd')).toBeNull();+ expect(itemNamed('commandPalette.buttonLabel')?.hasAttribute('aria-keyshortcuts')).toBe(false);+ // The icon-only footer keeps the actions that have no item of their own.+ expect(menuItems().flatMap((item) => item.getAttribute('aria-label') ?? [])).toEqual([+ 'whatsNew.whatsNewInInvoke',+ 'topbar.appMenu.documentation',+ 'Discord',+ ]);++ // Each dialog closes back to the menu's button: the item that opened it is gone by then.const trigger = host.querySelector<HTMLButtonElement>('[aria-label="topbar.appMenu.open"]')!;+ await act(() => userEvent.click(itemNamed('common.settings')!));+ expect(openSettings).toHaveBeenCalledExactlyOnceWith(undefined, trigger);+ expect(commandPaletteStore.getSnapshot().isOpen).toBe(false);+ await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());await act(() => userEvent.click(trigger));- const item = await vi.waitFor(() => {- const found = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(- (candidate) => candidate.textContent === 'auth.accountSettings'- );- expect(found).toBeDefined();- return found!;+ const palette = await vi.waitFor(() => {+ expect(itemNamed('commandPalette.buttonLabel')).toBeDefined();+ return itemNamed('commandPalette.buttonLabel')!;});- await act(() => userEvent.click(item));+ await act(() => userEvent.click(palette));+ expect(commandPaletteStore.getSnapshot().isOpen).toBe(true);+ expect(getCommandPaletteReturnFocusElement()).toBe(trigger);+ });- // The menu content unmounts once its exit animation ends; the dialog must outlive it.- await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).toBeNull());- expect(dialog()?.textContent).toContain('auth.account');+ // The account lives in the launchpad's rail; the editor's menu ends at the app's own items and the footer.+ it.each([+ ['a signed-in admin', true],+ ['single-user mode', false],+ ])('shows no account block for %s', async (_mode, multiuser) => {+ auth.multiuser = multiuser;+ await openMenu();- await act(() => userEvent.keyboard('{Escape}'));- await vi.waitFor(() => expect(dialog()).toBeNull());- expect(document.activeElement).toBe(trigger);+ const values = menuItems().map((item) => item.dataset.value);+ expect(values.slice(values.indexOf('widgets') + 1)).toEqual(['whats-new', 'documentation', 'discord']);+ expect(values).not.toContain('sign-out');+ expect(values).not.toContain('users');+ expect(document.querySelector('[role="menu"]')?.textContent).not.toContain('[email protected]');});});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsxindex 66486d4ea5..517d39d9da 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/AppMenu.tsx@@ -1,7 +1,7 @@import type { DonationMenuItemProps } from '@workbench/shell/DonationMenuItem';import { Badge, Box, chakra, HStack, Icon, Menu, Portal } from '@chakra-ui/react';-import { AccountMenuSection, AccountProfileDialog, useCapabilities, useHasAccountSection } from '@features/identity';+import { useCapabilities } from '@features/identity';import { getQueueSummary } from '@features/queue/contracts';import { APP_VERSION, DOCS_URL } from '@platform/runtime/appMetadata';import { IconButton } from '@platform/ui/Button';@@ -12,8 +12,9 @@ import { DiscordIcon, LightbulbFilamentIcon } from '@platform/ui/VendoredIcon';import { useQueryClient } from '@tanstack/react-query';import { useNavigate } from '@tanstack/react-router';import { OPEN_COMMAND_PALETTE_HOTKEY } from '@workbench/hotkeys/catalog';-import { useShortcutLabel } from '@workbench/hotkeys/useShortcutBinding';-import { openCommandPalette } from '@workbench/palette/paletteStore';+import { ShortcutKeycaps } from '@workbench/hotkeys/keyGlyphs';+import { useShortcutBinding } from '@workbench/hotkeys/useShortcutBinding';+import { openCommandPaletteFrom } from '@workbench/palette/paletteStore';import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';import { openWhatsNew } from '@workbench/shell/whatsNewStore';import { openWidgetsDialogFrom } from '@workbench/shell/widgetsDialogStore';@@ -44,7 +45,6 @@ const loadDonationMenuItem = () => import('@workbench/shell/DonationMenuItem');export const AppMenu = () => {const { t } = useTranslation();const { canManageModels, canManageNodes } = useCapabilities();- const hasAccount = useHasAccountSection();const navigate = useNavigate();const projectId = useActiveProjectId();const openWorkbenchWidget = useOpenWorkbenchWidget();@@ -66,15 +66,12 @@ export const AppMenu = () => {void navigate({ to: '/fonts' });}, [navigate]);const openQueue = useCallback(() => openWorkbenchWidget('queue'), [openWorkbenchWidget]);- const openSettings = useCallback(() => openWorkbenchSettings(), []);const triggerRef = useRef<HTMLButtonElement>(null);// The menu item is gone once a dialog it opened closes; focus returns to the menu's own button.const getTrigger = useCallback(() => triggerRef.current, []);+ const openSettings = useCallback(() => openWorkbenchSettings(undefined, triggerRef.current ?? undefined), []);+ const openPalette = useCallback(() => openCommandPaletteFrom(triggerRef.current), []);const openWidgets = useCallback(() => openWidgetsDialogFrom(getTrigger), [getTrigger]);- // Lives outside the menu: its content unmounts once the menu closes, which would take the dialog along.- const [isProfileOpen, setIsProfileOpen] = useState(false);- const openProfile = useCallback(() => setIsProfileOpen(true), []);- const closeProfile = useCallback(() => setIsProfileOpen(false), []);const queryClient = useQueryClient();// Rendered only once loaded: a lazy() boundary would suspend on open and React delays its reveal, shifting rows.// A chunk that fails to load (e.g. after an upgrade) leaves the optional link absent.@@ -99,101 +96,102 @@ export const AppMenu = () => {);return (- <>- <Menu.Root lazyMount positioning={MENU_POSITIONING} onOpenChange={handleOpenChange}>- <Menu.Trigger asChild>- <IconButton- ref={triggerRef}- aria-label={t('topbar.appMenu.open')}- className="group"- pe="1.5"- size="lg"- variant="ghost"- onFocus={preloadDonationMenuItem}- onPointerEnter={preloadDonationMenuItem}- >- <AppMenuGlyph />- </IconButton>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <MenuContent minW="15rem">- <MenuHeadingGroup label="Invoke" trailing={`v${APP_VERSION}`}>- <Menu.Item value="launchpad" onClick={openLaunchpad}>- <Icon as={HouseIcon} boxSize="3.5" />- <Menu.ItemText>{t('topbar.appMenu.launchpad')}</Menu.ItemText>+ <Menu.Root lazyMount positioning={MENU_POSITIONING} onOpenChange={handleOpenChange}>+ <Menu.Trigger asChild>+ <IconButton+ ref={triggerRef}+ aria-label={t('topbar.appMenu.open')}+ className="group"+ pe="1.5"+ size="lg"+ variant="ghost"+ onFocus={preloadDonationMenuItem}+ onPointerEnter={preloadDonationMenuItem}+ >+ <AppMenuGlyph />+ </IconButton>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="15rem">+ <MenuHeadingGroup label="Invoke" trailing={`v${APP_VERSION}`}>+ <Menu.Item value="launchpad" onClick={openLaunchpad}>+ <Icon as={HouseIcon} boxSize="3.5" />+ <Menu.ItemText>{t('topbar.appMenu.launchpad')}</Menu.ItemText>+ </Menu.Item>+ <ShortcutMenuItem+ commandId="app.openSettings"+ icon={SettingsIcon}+ label={t('common.settings')}+ value="settings"+ onClick={openSettings}+ />+ <ShortcutMenuItem+ commandId={OPEN_COMMAND_PALETTE_HOTKEY.commandId}+ icon={SearchIcon}+ label={t('commandPalette.buttonLabel')}+ value="command-palette"+ onClick={openPalette}+ />+ </MenuHeadingGroup>+ <Menu.Separator />+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('topbar.appMenu.manage')}</Menu.ItemGroupLabel>+ <Menu.Item value="projects" onClick={openProjects}>+ <Icon as={FolderIcon} boxSize="3.5" />+ <Menu.ItemText>{t('launchpad.sections.projects')}</Menu.ItemText>+ </Menu.Item>+ {canManageModels ? (+ <Menu.Item value="models" onClick={openModels}>+ <Icon as={BoxIcon} boxSize="3.5" />+ <Menu.ItemText>{t('models.manager')}</Menu.ItemText></Menu.Item>- </MenuHeadingGroup>- <Menu.Separator />- <Menu.ItemGroup>- <Menu.ItemGroupLabel>{t('topbar.appMenu.manage')}</Menu.ItemGroupLabel>- <Menu.Item value="projects" onClick={openProjects}>- <Icon as={FolderIcon} boxSize="3.5" />- <Menu.ItemText>{t('launchpad.sections.projects')}</Menu.ItemText>- </Menu.Item>- {canManageModels ? (- <Menu.Item value="models" onClick={openModels}>- <Icon as={BoxIcon} boxSize="3.5" />- <Menu.ItemText>{t('models.manager')}</Menu.ItemText>- </Menu.Item>- ) : null}- {canManageNodes ? (- <Menu.Item value="nodes" onClick={openNodes}>- <Icon as={BlocksIcon} boxSize="3.5" />- <Menu.ItemText>{t('nodes.manager')}</Menu.ItemText>- </Menu.Item>- ) : null}- <Menu.Item value="fonts" onClick={openFonts}>- <Icon as={TypeIcon} boxSize="3.5" />- <Menu.ItemText>{t('launchpad.sections.fonts')}</Menu.ItemText>- </Menu.Item>- <Menu.Item value="queue" onClick={openQueue}>- <Icon as={ListOrderedIcon} boxSize="3.5" />- <Menu.ItemText>{t('widgets.labels.queue')}</Menu.ItemText>- {queuedCount > 0 ? (- <Badge colorPalette="accent" fontSize="xs" ms="auto" variant="surface">- {queuedCount}- </Badge>- ) : null}- </Menu.Item>- <Menu.Item value="widgets" onClick={openWidgets}>- <Icon as={LayoutGridIcon} boxSize="3.5" />- <Menu.ItemText>{t('shell.widgets.menuItem')}</Menu.ItemText>+ ) : null}+ {canManageNodes ? (+ <Menu.Item value="nodes" onClick={openNodes}>+ <Icon as={BlocksIcon} boxSize="3.5" />+ <Menu.ItemText>{t('nodes.manager')}</Menu.ItemText></Menu.Item>- </Menu.ItemGroup>- {DonationMenuItem ? <DonationMenuItem separated /> : null}- {hasAccount ? (- <>- <Menu.Separator />- <AccountMenuSection onOpenProfile={openProfile} />- </>) : null}- <Menu.Separator />- <HStack gap="0.5" px="0" py="0">- <SearchMenuAction />- <SettingsMenuAction onClick={openSettings} />- <AppMenuAction- icon={LightbulbFilamentIcon}- label={t('whatsNew.whatsNewInInvoke')}- value="whats-new"- onClick={openWhatsNew}- />- <AppMenuLink- href={DOCS_URL}- icon={BookOpenTextIcon}- label={t('topbar.appMenu.documentation')}- value="documentation"- />- <AppMenuLink href={DISCORD_URL} icon={DiscordIcon} label="Discord" value="discord" />- </HStack>- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- {hasAccount ? (- <AccountProfileDialog finalFocusEl={getTrigger} isOpen={isProfileOpen} onClose={closeProfile} />- ) : null}- </>+ <Menu.Item value="fonts" onClick={openFonts}>+ <Icon as={TypeIcon} boxSize="3.5" />+ <Menu.ItemText>{t('launchpad.sections.fonts')}</Menu.ItemText>+ </Menu.Item>+ <Menu.Item value="queue" onClick={openQueue}>+ <Icon as={ListOrderedIcon} boxSize="3.5" />+ <Menu.ItemText>{t('widgets.labels.queue')}</Menu.ItemText>+ {queuedCount > 0 ? (+ <Badge colorPalette="accent" fontSize="xs" ms="auto" variant="surface">+ {queuedCount}+ </Badge>+ ) : null}+ </Menu.Item>+ <Menu.Item value="widgets" onClick={openWidgets}>+ <Icon as={LayoutGridIcon} boxSize="3.5" />+ <Menu.ItemText>{t('shell.widgets.menuItem')}</Menu.ItemText>+ </Menu.Item>+ </Menu.ItemGroup>+ {DonationMenuItem ? <DonationMenuItem separated /> : null}+ <Menu.Separator />+ <HStack gap="0.5" px="0" py="0">+ <AppMenuAction+ icon={LightbulbFilamentIcon}+ label={t('whatsNew.whatsNewInInvoke')}+ value="whats-new"+ onClick={openWhatsNew}+ />+ <AppMenuLink+ href={DOCS_URL}+ icon={BookOpenTextIcon}+ label={t('topbar.appMenu.documentation')}+ value="documentation"+ />+ <AppMenuLink href={DISCORD_URL} icon={DiscordIcon} label="Discord" value="discord" />+ </HStack>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>);};@@ -206,22 +204,34 @@ const AppMenuGlyph = () => (</HStack>);-const SearchMenuAction = () => {- const { t } = useTranslation();- const shortcut = useShortcutLabel(OPEN_COMMAND_PALETTE_HOTKEY.commandId);- const label = shortcut ? t('commandPalette.buttonTooltip', { hotkey: shortcut }) : t('commandPalette.buttonLabel');-- return <AppMenuAction icon={SearchIcon} label={label} value="command-palette" onClick={openCommandPalette} />;-};--const SettingsMenuAction = ({ onClick }: { onClick: () => void }) => {- const { t } = useTranslation();- // Reads the effective binding, so a remapped or unbound shortcut is never- // advertised as one that still works.- const shortcut = useShortcutLabel('app.openSettings');- const label = shortcut ? t('common.settingsWithShortcut', { hotkey: shortcut }) : t('common.settings');+/** An app-level item with its effective shortcut: a remapped or unbound shortcut is never advertised as working. */+const ShortcutMenuItem = ({+ commandId,+ icon,+ label,+ onClick,+ value,+}: {+ commandId: string;+ icon: ElementType;+ label: string;+ onClick: () => void;+ value: string;+}) => {+ const shortcut = useShortcutBinding(commandId);- return <AppMenuAction icon={SettingsIcon} label={label} value="settings" onClick={onClick} />;+ return (+ // The keycaps stay out of the name ("Settings", not "Settingsctrl,"); aria-keyshortcuts announces the binding.+ <Menu.Item aria-keyshortcuts={shortcut?.aria} value={value} onClick={onClick}>+ <Icon as={icon} boxSize="3.5" />+ <Menu.ItemText>{label}</Menu.ItemText>+ {shortcut ? (+ <Menu.ItemCommand aria-hidden>+ <ShortcutKeycaps parts={shortcut.parts} />+ </Menu.ItemCommand>+ ) : null}+ </Menu.Item>+ );};const FOOTER_ITEM_PROPS = {diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsxindex e61d2af8b4..dd7c50e4e6 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx@@ -39,8 +39,8 @@ const loadPopoverBody = (): Promise<InvokePopoverBodyComponent> =>));/**- * Invoke ends its attached group and sits on top of the iterations field with full control corners; the field runs a- * tail of its frame under Invoke's leading corners so it reads as a continuing border, not a notch.+ * Invoke ends its attached group and sits on top of the iterations field with full control corners; the field's frame+ * runs on under Invoke's leading corners so it reads as a continuing border, not a notch.* Doubled specificity outranks the attached Group's `!important` corner reset.*/const INVOKE_BUTTON_CSS = { '&&': { borderRadius: 'control !important' } } as const;diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokePopoverBody.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokePopoverBody.tsxindex e04256655f..c3d658204d 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokePopoverBody.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokePopoverBody.tsx@@ -228,6 +228,26 @@ const InvokeIssueList = ({ issues, onJump }: { issues: readonly InvocationIssue[<Stack as="ul" gap="2" listStyleType="none" m="0" p="0">{issues.map((issue, index) => {const actions = getActions(issue);+ const buttons = actions.map((action) => (+ <Button+ key={action.id}+ flexShrink={0}+ size="xs"+ data-issue-action=""+ variant="outline"+ // oxlint-disable-next-line react-perf/jsx-no-new-function-as-prop -- a few buttons per shown issue.+ onClick={() => {+ action.run();+ if (!action.stays) {+ onJump();+ }+ }}+ >+ {action.label}+ </Button>+ ));+ // A lone action sits at the end of the message's row; several get a row of their own under it.+ const isInline = actions.length === 1;return (// Two issues can read the same (two nodes missing the same input), so the position keeps keys apart.@@ -242,29 +262,14 @@ const InvokeIssueList = ({ issues, onJump }: { issues: readonly InvocationIssue[flexShrink={0}mt="0.5"/>- <Text color="fg" fontSize="sm" lineHeight="1.4" textWrap="pretty">+ <Text color="fg" flex="1" fontSize="sm" lineHeight="1.4" minW="0" textWrap="pretty">{issue.message}</Text>+ {isInline ? buttons : null}</HStack>- {actions.length > 0 ? (+ {actions.length > 1 ? (<HStack gap="1" ps="4.5" wrap="wrap">- {actions.map((action) => (- <Button- key={action.id}- size="xs"- data-issue-action=""- variant="outline"- // oxlint-disable-next-line react-perf/jsx-no-new-function-as-prop -- a few buttons per shown issue.- onClick={() => {- action.run();- if (!action.stays) {- onJump();- }- }}- >- {action.label}- </Button>- ))}+ {buttons}</HStack>) : null}</Stack>diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.browser.test.tsxindex 9b1976b42d..8839b4e75e 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.browser.test.tsx@@ -1,6 +1,8 @@import type { Project } from '@workbench/projectContracts';import { ChakraProvider } from '@chakra-ui/react';+import { Button } from '@platform/ui/Button';+import { Group } from '@platform/ui/Group';import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -35,7 +37,7 @@ afterEach(async () => {root = null;});-const renderForUpscale = async (mode: 'refine' | 'model-only') => {+const renderForUpscale = async (mode: 'refine' | 'model-only', withInvoke = false) => {let state = workbenchReducer(createInitialWorkbenchState(), {type: 'patchWidgetValues',values: { batchCount: 3, mode },@@ -50,7 +52,17 @@ const renderForUpscale = async (mode: 'refine' | 'model-only') => {await act(() => {root?.render(<ChakraProvider value={system}>- <IterationsField />+ {withInvoke ? (+ // The cluster's join: Invoke follows the field in an attached group.+ <Group attached>+ <IterationsField />+ <Button size="lg" zIndex="2">+ Invoke+ </Button>+ </Group>+ ) : (+ <IterationsField />+ )}</ChakraProvider>);});@@ -94,3 +106,19 @@ describe('IterationsField for Upscale', () => {expect(harness.patchValues).not.toHaveBeenCalled();});});++describe('IterationsField beside Invoke', () => {+ it("runs its frame under Invoke's rounded corners while its steppers stay clear of Invoke", async () => {+ const input = await renderForUpscale('refine', true);+ const field = input.parentElement!;+ const invoke = host!.querySelector('button:not([data-part])')!.getBoundingClientRect();+ const steppers = field.querySelector('[data-part="control"]')!.getBoundingClientRect();+ // Invoke keeps full control corners in the cluster; the field's own leading corner shows that radius.+ const cornerRadius = Number.parseFloat(getComputedStyle(field).borderTopLeftRadius);++ expect(cornerRadius).toBeGreaterThan(0);+ // The top and bottom borders reach where Invoke's edges turn straight, so no notch opens beside its corners.+ expect(input.getBoundingClientRect().right).toBeGreaterThanOrEqual(invoke.left + cornerRadius);+ expect(steppers.right).toBeLessThanOrEqual(invoke.left);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsxindex 418ea7c3e3..c5025ebcfa 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/IterationsField.tsx@@ -9,22 +9,14 @@ import { useTranslation } from 'react-i18next';import { getBatchCount, isBatchCountFixed } from './useInvocationState';/**- * Invoke's rounded corners overlap this field, so its edge facing Invoke is hidden and a tail continues the frame- * beneath them. The input is a replaced element, so the root carries the tail; it overlaps the input by 2px so the- * opaque border rows join without a sub-pixel seam.+ * Invoke's rounded corners overlap this field. The input, the field's visible frame, runs one control radius past the+ * root beneath them and has no facing edge, so its top and bottom borders reach Invoke's straight edges in every state+ * (hover, focus, invalid) in the color the input itself draws. A zero width rather than a transparent color, because+ * state colors would repaint that edge inside an outline Invoke. The root keeps its width and the steppers stay+ * anchored to it, so layout is unchanged.*/-const TAIL_UNDER_INVOKE_AFTER_CSS = {- '& input': { borderInlineEndColor: 'transparent' },- '&::after': {- borderBlockWidth: '1px',- content: '""',- pointerEvents: 'none',- position: 'absolute',- borderColor: 'border',- insetBlock: 0,- insetInlineStart: 'calc(100% - 2px)',- width: 'calc({radii.control} + 2px)',- },+const RUN_UNDER_INVOKE_CSS = {+ '& input': { borderInlineEndWidth: '0', width: 'calc(100% + {radii.control})' },} as const;export const IterationsField = () => {@@ -71,7 +63,7 @@ export const IterationsField = () => {say why it cannot change. */}<NumberInput.RootallowMouseWheel- css={TAIL_UNDER_INVOKE_AFTER_CSS}+ css={RUN_UNDER_INVOKE_CSS}cursor={isFixed ? 'not-allowed' : undefined}flexShrink={0}opacity={isFixed ? 0.55 : undefined}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.browser.test.tsxindex 5dea3392a2..f7c3b7f973 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.browser.test.tsx@@ -2,7 +2,7 @@ import { ChakraProvider } from '@chakra-ui/react';import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';import { system } from '@theme/system';import { createWorkbenchStore, type WorkbenchInternalStore } from '@workbench/workbenchStore';-import { act, useSyncExternalStore } from 'react';+import { act, StrictMode, useSyncExternalStore } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';@@ -14,6 +14,7 @@ vi.mock('react-i18next', () => ({t: (key: string, options?: { name?: string }) =>({'common.done': 'Done',+ 'topbar.presets.edit': 'Edit layout preset','topbar.presets.deleteNamed': `Delete ${options?.name ?? ''}`,'topbar.presets.editNamed': `Edit ${options?.name ?? ''}`,'topbar.presets.manage': 'Manage presets',@@ -31,6 +32,7 @@ vi.mock('@workbench/WorkbenchContext', () => ({) => selector(useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot)),}));+import { LayoutPresetAdminDialogs } from './LayoutPresetAdminDialogs';import { LayoutPresetManagerDialog } from './LayoutPresetManagerDialog';import { LayoutPresetManagerDialogBody } from './LayoutPresetManagerDialogBody';import { closeLayoutPresetManager, openLayoutPresetManager } from './layoutPresetManagerStore';@@ -59,9 +61,7 @@ const renderManager = async () => {};const presetRowIds = () =>- Array.from(document.querySelectorAll<HTMLElement>('[data-layout-preset-id]')).map(- (element) => element.dataset.layoutPresetId- );+ Array.from(document.querySelectorAll<HTMLElement>('[data-list-row]')).map((element) => element.dataset.listRow);const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {target.dispatchEvent(@@ -72,8 +72,35 @@ const pointer = (type: string, target: EventTarget, clientX: number, clientY: nuconst dragHandle = (name: string): HTMLButtonElement | null =>document.querySelector<HTMLButtonElement>(`button[aria-label="Reorder ${name}"]`);-const presetRow = (id: string): HTMLElement | null =>- document.querySelector<HTMLElement>(`[data-layout-preset-id="${id}"]`);+const presetRow = (id: string): HTMLElement | null => document.querySelector<HTMLElement>(`[data-list-row="${id}"]`);++/** Both topbar hosts, as the app mounts them (StrictMode included), so the edit dialog stacks over the manager. */+const renderTopBarDialogs = async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <LayoutPresetManagerDialog />+ <LayoutPresetAdminDialogs />+ </ChakraProvider>+ </StrictMode>+ )+ );+};++const dialogNamed = (title: string): HTMLElement | null =>+ Array.from(document.querySelectorAll<HTMLElement>('[role="dialog"]')).find(+ (dialog) => dialog.querySelector('[data-part="title"]')?.textContent === title+ ) ?? null;++const buttonNamed = (container: Element, text: string): HTMLButtonElement =>+ Array.from(container.querySelectorAll('button')).find((button) => button.textContent === text)!;++const editButton = (name: string): HTMLButtonElement | null =>+ document.querySelector<HTMLButtonElement>(`button[aria-label="Edit ${name}"]`);beforeEach(() => {store = createWorkbenchStore();@@ -114,6 +141,31 @@ describe('LayoutPresetManagerDialogBody', () => {await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();});+ it.each([+ ['Cancel', () => userEvent.click(buttonNamed(dialogNamed('Edit layout preset')!, 'common.cancel'))],+ ['Escape', () => userEvent.keyboard('{Escape}')],+ [+ 'the close button',+ () => userEvent.click(dialogNamed('Edit layout preset')!.querySelector('[data-part="close-trigger"]')!),+ ],+ ])('closes only the edit dialog stacked over the manager on %s', async (_way, dismiss) => {+ await renderTopBarDialogs();+ await act(() => openLayoutPresetManager());+ await expect.poll(() => dialogNamed('Manage presets')?.getAttribute('data-state')).toBe('open');++ for (let attempt = 0; attempt < 2; attempt += 1) {+ await act(() => userEvent.click(editButton('Writing')!));+ await expect.poll(() => dialogNamed('Edit layout preset')?.getAttribute('data-state')).toBe('open');+ await expect.poll(() => dialogNamed('Edit layout preset')?.contains(document.activeElement)).toBe(true);++ await act(dismiss);++ await expect.poll(() => dialogNamed('Edit layout preset')).toBeNull();+ expect(dialogNamed('Manage presets')?.getAttribute('data-state')).toBe('open');+ await expect.poll(() => document.activeElement).toBe(editButton('Writing'));+ }+ });+it('renders one account-ordered list without preset descriptions', async () => {await renderManager();diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsxindex 2d175387ac..43e24bb17d 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetManagerDialogBody.tsx@@ -1,39 +1,21 @@-import type { DragEndEvent, KeyboardSensorOptions } from '@dnd-kit/core';-import type { LayoutPreset, LayoutPresetId } from '@workbench/layoutContracts';+/* oxlint-disable react-perf/jsx-no-jsx-as-prop -- ListItem slots take JSX; the React Compiler memoizes them. */+import type { LayoutPreset } from '@workbench/layoutContracts';-import { Box, HStack, Icon, Portal, Stack } from '@chakra-ui/react';-import { closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';-import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers';-import {- sortableKeyboardCoordinates,- SortableContext,- useSortable,- verticalListSortingStrategy,-} from '@dnd-kit/sortable';-import { CSS } from '@dnd-kit/utilities';+import { Box, Icon, Portal } from '@chakra-ui/react';import { Button, CloseButton, IconButton } from '@platform/ui/Button';import { Dialog } from '@platform/ui/Dialog';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { SortableListItem, SortableListStack } from '@platform/ui/list/SortableListStack';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 { PencilIcon, RotateCcwIcon, Trash2Icon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { resolveLayoutPresetIcon } from './layoutPresetIcons';import { closeLayoutPresetManager, openLayoutPresetDelete, openLayoutPresetEdit } from './layoutPresetManagerStore';-const ROW_FILL_TRANSITION =- 'background var(--chakra-durations-faster) ease, border-color var(--chakra-durations-faster) ease, color var(--chakra-durations-faster) ease';--const DND_MODIFIERS = [restrictToVerticalAxis, restrictToParentElement];-const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } } as const;-const KEYBOARD_SENSOR_OPTIONS = {- coordinateGetter: sortableKeyboardCoordinates,-} satisfies KeyboardSensorOptions;-/** The account-wide layout preset editor, rendered lazily from the top bar. */export const LayoutPresetManagerDialogBody = ({isOpen,@@ -60,26 +42,12 @@ export const LayoutPresetManagerDialogBody = ({]),[account.layoutPresetMetadataOverrides, account.layoutPresetOverrides, account.layoutPresetRouteOverrides]);- const sensors = useSensors(- useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),- useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)- );const handleOpenChange = useCallback((event: { open: boolean }) => {if (!event.open) {closeLayoutPresetManager();}}, []);- const handleDragEnd = useCallback(- (event: DragEndEvent) => {- if (!event.over || event.active.id === event.over.id) {- return;- }-- layout.reorderPresets(event.active.id as LayoutPresetId, event.over.id as LayoutPresetId);- },- [layout]- );return (<Dialog.Root lazyMount open={isOpen} unmountOnExit onExitComplete={onExitComplete} onOpenChange={handleOpenChange}>@@ -94,24 +62,22 @@ export const LayoutPresetManagerDialogBody = ({</Dialog.CloseTrigger></Dialog.Header><Dialog.Body>- <DndContext- collisionDetection={closestCenter}- modifiers={DND_MODIFIERS}- sensors={sensors}- onDragEnd={handleDragEnd}+ {/* Row surfaces bleed into the dialog padding so their content lines up with the header. */}+ <SortableListStack+ dividers+ items={presetIds}+ label={t('topbar.presets.list')}+ mx="-2"+ onReorder={layout.reorderPresets}>- <SortableContext items={presetIds} strategy={verticalListSortingStrategy}>- <Stack gap="1.5">- {presets.map((preset) => (- <PresetRow- key={preset.id}- isOverridden={preset.isBuiltIn === true && overriddenPresetIds.has(preset.id)}- preset={preset}- />- ))}- </Stack>- </SortableContext>- </DndContext>+ {presets.map((preset) => (+ <PresetRow+ key={preset.id}+ isOverridden={preset.isBuiltIn === true && overriddenPresetIds.has(preset.id)}+ preset={preset}+ />+ ))}+ </SortableListStack></Dialog.Body><Dialog.Footer><Button variant="ghost" onClick={closeLayoutPresetManager}>@@ -128,94 +94,65 @@ export const LayoutPresetManagerDialogBody = ({const PresetRow = ({ isOverridden, preset }: { isOverridden: boolean; preset: LayoutPreset }) => {const { t } = useTranslation();const { layout } = useWorkbenchCommands();- const icon = resolveLayoutPresetIcon(preset.iconId);- const { attributes, isDragging, listeners, setActivatorNodeRef, setNodeRef, transform, transition } = useSortable({- id: preset.id,- });- const dndStyle = useMemo(- () => ({- opacity: isDragging ? 0.5 : undefined,- position: 'relative' as const,- transform: CSS.Translate.toString(transform),- // Compose the hover-fill fade back in: dnd-kit's inline transform- // transition otherwise replaces the CSS transition (see LayoutPresetStrip).- transition: [transition, ROW_FILL_TRANSITION].filter(Boolean).join(', '),- zIndex: isDragging ? 1 : undefined,- }),- [isDragging, transform, transition]- );const edit = useCallback(() => openLayoutPresetEdit(preset.id), [preset.id]);const deletePreset = useCallback(() => openLayoutPresetDelete(preset.id), [preset.id]);const restoreDefault = useCallback(() => layout.restorePresetDefault(preset.id), [layout, preset.id]);return (- <HStack- ref={setNodeRef}- borderColor="border.subtle"- borderWidth="1px"- data-layout-preset-id={preset.id}- gap="2"- px="3"- py="2"- rounded="md"- style={dndStyle}- >- <IconButton- ref={setActivatorNodeRef}- {...attributes}- {...listeners}- aria-label={t('topbar.presets.reorderNamed', { name: preset.label })}- color="fg.subtle"- cursor={isDragging ? 'grabbing' : 'grab'}- size="sm"- touchAction="none"- variant="ghost"- >- <Icon as={GripVerticalIcon} boxSize="3.5" />- </IconButton>- <Icon as={icon} boxSize="4" color="fg.muted" flexShrink={0} />- <MiddleTruncate flex="1" fontSize="md" fontWeight="600" minW="0" text={preset.label} />- {isOverridden ? (- <Box- aria-label={t('topbar.presets.edited')}- bg="accent.solid"- boxSize="1.5"- flexShrink={0}- role="img"- rounded="full"- />- ) : null}- <IconButton- aria-label={t('topbar.presets.editNamed', { name: preset.label })}- size="sm"- variant="ghost"- onClick={edit}- >- <Icon as={PencilIcon} boxSize="3.5" />- </IconButton>- {isOverridden ? (- <Tooltip content={t('topbar.presets.restore')} showArrow>+ <SortableListItem+ actions={+ <><IconButton- aria-label={t('topbar.presets.restoreNamed', { name: preset.label })}+ aria-label={t('topbar.presets.editNamed', { name: preset.label })}size="sm"+ tooltip={t('topbar.presets.edit')}variant="ghost"- onClick={restoreDefault}+ onClick={edit}>- <Icon as={RotateCcwIcon} boxSize="3.5" />+ <Icon as={PencilIcon} boxSize="3.5" /></IconButton>- </Tooltip>- ) : null}- {preset.isBuiltIn ? null : (- <IconButton- aria-label={t('topbar.presets.deleteNamed', { name: preset.label })}- color="fg.error"- size="sm"- variant="ghost"- onClick={deletePreset}- >- <Icon as={Trash2Icon} boxSize="3.5" />- </IconButton>- )}- </HStack>+ {isOverridden ? (+ <Tooltip content={t('topbar.presets.restore')} showArrow>+ <IconButton+ aria-label={t('topbar.presets.restoreNamed', { name: preset.label })}+ size="sm"+ variant="ghost"+ onClick={restoreDefault}+ >+ <Icon as={RotateCcwIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ ) : null}+ {preset.isBuiltIn ? null : (+ <IconButton+ aria-label={t('topbar.presets.deleteNamed', { name: preset.label })}+ color="fg.error"+ size="sm"+ tooltip={t('topbar.presets.delete')}+ variant="ghost"+ onClick={deletePreset}+ >+ <Icon as={Trash2Icon} boxSize="3.5" />+ </IconButton>+ )}+ </>+ }+ badges={+ isOverridden ? (+ <Box+ aria-label={t('topbar.presets.edited')}+ bg="accent.solid"+ boxSize="1.5"+ flexShrink={0}+ role="img"+ rounded="full"+ />+ ) : null+ }+ handleLabel={t('topbar.presets.reorderNamed', { name: preset.label })}+ id={preset.id}+ leading={<Icon as={resolveLayoutPresetIcon(preset.iconId)} boxSize="4" color="fg.muted" flexShrink={0} />}+ title={preset.label}+ />);};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 95f1e447a5..9dfcdfc694 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@@ -20,6 +20,11 @@ vi.mock('react-i18next', () => ({'topbar.presets.moreAvailable': `More layout presets, ${options?.count} available`,// A translated default, as another language shows the Workflow preset.'topbar.presets.builtInLabels.automate': 'Arbeitsablauf',+ 'topbar.presets.builtInLabels.edit': 'Edit',+ 'topbar.presets.builtInDescriptions.automate': 'Build and run workflows',+ 'topbar.presets.builtInDescriptions.compose': 'Generate images from text',+ 'topbar.presets.builtInDescriptions.edit': 'Edit and refine images',+ 'topbar.presets.builtInDescriptions.video': 'Generate video','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.',@@ -64,7 +69,12 @@ vi.mock('@workbench/layoutPresetActivation', async (importOriginal) => {};});-vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({ useShortcutLabel: () => null }));+// Compose keeps its default key; Edit models one the user unbound, which no tip may advertise.+const COMPOSE_SHORTCUT = { aria: 'Alt+1', display: 'Alt+1', parts: ['alt', '1'] };+vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({+ useShortcutBinding: (commandId: string) => (commandId === 'app.selectComposePreset' ? COMPOSE_SHORTCUT : null),+ useShortcutLabel: () => null,+}));import { LayoutPresetAdminDialogs } from './LayoutPresetAdminDialogs';import { LayoutPresetStrip } from './LayoutPresetStrip';@@ -122,6 +132,28 @@ const settle = (ms = 200): Promise<void> =>});const POLL = { timeout: 5000 } as const;+// The tip opens on focus without a delay and on hover after 400 ms; these waits are well past both.+const QUIET_MS = 700;++const openTooltip = () =>+ [...document.querySelectorAll<HTMLElement>('[data-scope="tooltip"][data-part="content"]')].find(+ (element) => element.dataset.state === 'open'+ ) ?? null;++// Either side of the width at which the tabs hide their labels.+const WIDE_VIEWPORT = { height: 900, width: 1440 } as const;+const NARROW_VIEWPORT = { height: 900, width: 1024 } as const;++/** Runs the enclosing tests at `size`, then gives the next ones back the frame they started with. */+const runAtViewport = (size: { height: number; width: number }) => {+ let original = { height: 0, width: 0 };++ beforeEach(async () => {+ original = { height: globalThis.innerHeight, width: globalThis.innerWidth };+ await page.viewport(size.width, size.height);+ });+ afterEach(() => page.viewport(original.width, original.height));+};const openPresetMenuItem = async (presetId: string, item: string) => {const menuItem = () => document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${item}"]`);@@ -528,10 +560,6 @@ describe('LayoutPresetStrip', () => {describe('unsaved arrangements', () => {const UNSAVED = 'Unsaved layout changes';- const openTooltip = () =>- [...document.querySelectorAll<HTMLElement>('[data-scope="tooltip"][data-part="content"]')].find(- (element) => element.dataset.state === 'open'- ) ?? null;const unsavedDot = (id: string) => presetTab(id)?.querySelector('[data-unsaved-dot]') ?? null;const label = (id: string) => presetTab(id)?.getAttribute('aria-label') ?? '';const activePresetId = () => store.getSnapshot().activeProject.layout.presetId;@@ -591,24 +619,25 @@ describe('LayoutPresetStrip', () => {expect(unsavedDot('automate')).toBeNull();});- it('explains the dot on keyboard focus whichever tab focus came from, and stays quiet on a clean preset', async () => {+ it('explains the dot on keyboard focus whichever tab focus came from, and says nothing of it on a clean preset', async () => {rearrange('video', 401);rearrange('compose', 433);await renderStrip();- // A clean tab under keyboard focus: focus opens a tip at once when there is one, so none here is not vacuous.+ // A clean tab under keyboard focus shows its own tip, which must not borrow the unsaved line.presetTab('compose')!.focus();await act(() => userEvent.keyboard('{ArrowRight}'));await act(() => userEvent.keyboard('{ArrowRight}'));await waitForActivePreset('edit');expect(document.activeElement).toBe(presetTab('edit'));- expect(openTooltip()).toBeNull();+ await expect.poll(() => openTooltip()?.textContent, POLL).toContain('Edit and refine images');+ expect(openTooltip()?.textContent).not.toContain(UNSAVED);// Clean → unsaved by keyboard.await act(() => userEvent.keyboard('{ArrowRight}'));await waitForActivePreset('video');expect(document.activeElement).toBe(presetTab('video'));- await expect.poll(() => openTooltip()?.textContent, POLL).toBe(UNSAVED);+ await expect.poll(() => openTooltip()?.textContent, POLL).toContain(UNSAVED);expect(label('video')).toContain(UNSAVED);});@@ -620,70 +649,72 @@ describe('LayoutPresetStrip', () => {// Keyboard focus lands on the selected (unsaved) tab and its tip shows.await act(() => userEvent.tab());expect(document.activeElement).toBe(presetTab('video'));- await expect.poll(() => openTooltip()?.textContent, POLL).toBe(UNSAVED);+ await expect.poll(() => openTooltip()?.textContent, POLL).toContain(UNSAVED);await act(() => userEvent.keyboard('{ArrowRight}'));await waitForActivePreset('automate');expect(document.activeElement).toBe(presetTab('automate'));expect(label('automate')).toContain(UNSAVED);- await expect.poll(() => openTooltip()?.textContent, POLL).toBe(UNSAVED);+ // The tip now describes the arriving preset, not the one focus left.+ await expect.poll(() => openTooltip()?.textContent, POLL).toBe(`ArbeitsablaufBuild and run workflows${UNSAVED}`);// Still open once the switch has settled, not closed by it.await act(() => settle(400));- expect(openTooltip()?.textContent).toBe(UNSAVED);+ expect(openTooltip()?.textContent).toContain(UNSAVED);});describe('never opens the tip on a tab nobody is on', () => {- // The tip opens on focus without a delay and on hover after 400 ms; these waits are well past both.- const QUIET_MS = 700;- const unsavedTip = () => (openTooltip()?.textContent === UNSAVED ? openTooltip() : null);- const dirtyCompose = async (sizePx: number) => {+ // Labels showing, a clean custom preset has no tip: it gains one only by becoming unsaved.+ runAtViewport(WIDE_VIEWPORT);+ beforeEach(() => store.commands.layout.applyPreset('custom-1'));+ const unsavedTip = () => (openTooltip()?.textContent?.includes(UNSAVED) ? openTooltip() : null);+ const dirtyCustom = async (sizePx: number) => {await act(() => store.commands.layout.setRegionSize('right', sizePx));- await expect.poll(() => label('compose'), POLL).toContain(UNSAVED);+ await expect.poll(() => label('custom-1'), POLL).toContain(UNSAVED);};it('after keyboard focus left a clean tab that then became unsaved', async () => {await renderStrip();await act(() => userEvent.tab());- expect(document.activeElement).toBe(presetTab('compose'));+ expect(document.activeElement).toBe(presetTab('custom-1'));await act(() => (document.activeElement as HTMLElement).blur());- await dirtyCompose(401);+ await dirtyCustom(401);await act(() => settle(QUIET_MS));- expect(unsavedTip()).toBeNull();+ expect(openTooltip()).toBeNull();// The tip itself works: focus brings it.- await act(() => presetTab('compose')!.focus());+ await act(() => presetTab('custom-1')!.focus());await expect.poll(unsavedTip, POLL).not.toBeNull();});it('after a focused unsaved tab was reverted in place, left, and changed again', async () => {await renderStrip();- await dirtyCompose(401);+ await dirtyCustom(401);await act(() => userEvent.tab());await expect.poll(unsavedTip, POLL).not.toBeNull();await act(() => store.commands.layout.reset());- await expect.poll(() => label('compose'), POLL).not.toContain(UNSAVED);- await expect.poll(unsavedTip, POLL).toBeNull();+ await expect.poll(() => label('custom-1'), POLL).not.toContain(UNSAVED);+ await expect.poll(openTooltip, POLL).toBeNull();await act(() => (document.activeElement as HTMLElement).blur());- await dirtyCompose(433);+ await dirtyCustom(433);await act(() => settle(QUIET_MS));- expect(unsavedTip()).toBeNull();+ expect(openTooltip()).toBeNull();});it('after the pointer left a clean tab that then became unsaved', async () => {await renderStrip();- await act(() => userEvent.hover(presetTab('compose')!));+ await act(() => userEvent.hover(presetTab('custom-1')!));await act(() => settle(QUIET_MS));- expect(unsavedTip()).toBeNull();- await act(() => userEvent.unhover(presetTab('compose')!));+ expect(openTooltip()).toBeNull();+ await act(() => userEvent.unhover(presetTab('custom-1')!));- await dirtyCompose(401);+ await dirtyCustom(401);await act(() => settle(QUIET_MS));- expect(unsavedTip()).toBeNull();+ expect(openTooltip()).toBeNull();- await act(() => userEvent.hover(presetTab('compose')!));+ await act(() => userEvent.hover(presetTab('custom-1')!));await expect.poll(unsavedTip, POLL).not.toBeNull();});});@@ -694,7 +725,7 @@ describe('LayoutPresetStrip', () => {await renderStrip();await act(() => userEvent.hover(presetTab('compose')!));- await expect.poll(() => openTooltip()?.textContent, POLL).toBe(UNSAVED);+ await expect.poll(() => openTooltip()?.textContent, POLL).toContain(UNSAVED);await act(() => userEvent.unhover(presetTab('compose')!));await expect.poll(openTooltip, POLL).toBeNull();});@@ -740,4 +771,166 @@ describe('LayoutPresetStrip', () => {expect(label('compose')).toContain(UNSAVED);});});++ describe('preset tips', () => {+ const tipText = () => openTooltip()?.textContent ?? null;+ const tipKeycap = () => openTooltip()?.querySelector('kbd') ?? null;++ describe('with the labels hidden', () => {+ runAtViewport(NARROW_VIEWPORT);++ it('names the preset under the pointer, with what a built-in is for and its shortcut', async () => {+ await renderStrip();++ // Renamed (beforeEach calls Compose "Writing"): the shipped purpose may no longer hold, so only name and key.+ await act(() => userEvent.hover(presetTab('compose')!));+ await expect.poll(tipText, POLL).toContain('Writing');+ expect(tipText()).not.toContain('Generate images from text');+ expect(tipKeycap()?.textContent).toContain('1');+ // The tip describes the tab; the tab keeps its name.+ expect(presetTab('compose')).toHaveAttribute('aria-label', 'Writing');++ // Still the built-in, but unbound: the purpose shows, no keycap.+ await act(() => userEvent.hover(presetTab('edit')!));+ await expect.poll(tipText, POLL).toBe('EditEdit and refine images');+ expect(tipKeycap()).toBeNull();++ // A custom preset has only its name to show, which is all an icon-only tab is missing.+ await act(() => userEvent.hover(presetTab('custom-1')!));+ await expect.poll(tipText, POLL).toBe('Custom');+ });++ it('shows on keyboard focus', async () => {+ await renderStrip();++ await act(() => userEvent.tab());+ expect(document.activeElement).toBe(presetTab('compose'));+ await expect.poll(tipText, POLL).toContain('Writing');+ });++ it('keeps quiet while a preset menu is open', async () => {+ await renderStrip();+ await act(() => userEvent.tab());+ await expect.poll(openTooltip, POLL).not.toBeNull();++ await act(() => userEvent.keyboard('{ArrowDown}'));+ await expect.poll(() => document.querySelector('[role="menu"]'), POLL).not.toBeNull();+ await expect.poll(openTooltip, POLL).toBeNull();++ // Nor does pointing at another tab bring it while the menu stays open.+ await act(() => userEvent.hover(presetTab('video')!));+ await act(() => settle(QUIET_MS));+ expect(document.querySelector('[role="menu"]')).not.toBeNull();+ expect(openTooltip()).toBeNull();++ await act(() => userEvent.keyboard('{Escape}'));+ await expect.poll(() => document.querySelector('[role="menu"]'), POLL).toBeNull();+ await act(() => userEvent.unhover(presetTab('video')!));+ await act(() => userEvent.hover(presetTab('video')!));+ await expect.poll(tipText, POLL).toContain('Generate video');+ });++ it('keeps quiet while a tab is dragged', async () => {+ await renderStrip();+ await act(() => userEvent.tab());+ expect(document.activeElement).toBe(presetTab('compose'));+ await expect.poll(openTooltip, POLL).not.toBeNull();++ await act(() => userEvent.keyboard('{Space}'));+ await expect.poll(openTooltip, POLL).toBeNull();+ await act(() => userEvent.keyboard('{ArrowRight}'));+ await act(() => settle(QUIET_MS));+ expect(openTooltip()).toBeNull();++ await act(() => userEvent.keyboard('{Space}'));+ expect(store.getSnapshot().account.layoutPresetOrder).toEqual([+ 'custom-1',+ 'compose',+ 'edit',+ 'video',+ 'automate',+ ]);+ });+ });++ describe('with the labels showing', () => {+ runAtViewport(WIDE_VIEWPORT);++ it('shows only what the label does not already say', async () => {+ store.commands.layout.applyPreset('custom-1');+ await renderStrip();++ // A clean custom preset's tip would only repeat its label.+ await act(() => userEvent.hover(presetTab('custom-1')!));+ await act(() => settle(QUIET_MS));+ expect(openTooltip()).toBeNull();+ await act(() => userEvent.unhover(presetTab('custom-1')!));++ // A built-in's purpose and shortcut are not on the tab.+ await act(() => userEvent.hover(presetTab('edit')!));+ await expect.poll(tipText, POLL).toContain('Edit and refine images');+ await act(() => userEvent.unhover(presetTab('edit')!));+ await expect.poll(openTooltip, POLL).toBeNull();++ // Unsaved changes are: the tip explains the dot.+ await act(() => store.commands.layout.setRegionSize('right', 401));+ await expect.poll(() => presetTab('custom-1')?.getAttribute('aria-label'), POLL).toContain('Unsaved');+ await act(() => userEvent.hover(presetTab('custom-1')!));+ await expect.poll(tipText, POLL).toBe('CustomUnsaved layout changes');+ });++ it('never shows a clean custom preset in a tip that focus hands over', async () => {+ await renderStrip();+ await act(() => userEvent.tab());+ expect(document.activeElement).toBe(presetTab('compose'));+ await expect.poll(tipText, POLL).toContain('Writing');++ // Every frame, whatever any visible tip says, through the hand-over and the closing fade.+ const seen = new Set<string>();+ let isSampling = true;+ const sample = () => {+ for (const element of document.querySelectorAll<HTMLElement>('[data-scope="tooltip"][data-part="content"]')) {+ if (element.checkVisibility()) {+ seen.add(element.textContent ?? '');+ }+ }+ if (isSampling) {+ requestAnimationFrame(sample);+ }+ };+ sample();++ await act(() => userEvent.keyboard('{ArrowRight}'));+ expect(document.activeElement).toBe(presetTab('custom-1'));+ await act(() => settle(QUIET_MS));+ isSampling = false;++ expect([...seen].filter((text) => text.includes('Custom'))).toEqual([]);+ expect(openTooltip()).toBeNull();+ });+ });++ it('announces each preset’s bound key, and none for a preset without one', async () => {+ await renderStrip();+ const keyShortcuts = (id: string) => presetTab(id)?.getAttribute('aria-keyshortcuts') ?? null;++ // The active tab's menu key comes first; Compose's binding follows.+ expect(keyShortcuts('compose')).toBe('ArrowDown Alt+1');+ // Edit is unbound, and a custom preset has no key to bind.+ expect(keyShortcuts('edit')).toBeNull();+ expect(keyShortcuts('custom-1')).toBeNull();++ await act(() => userEvent.click(presetTab('edit')!));+ await expect.poll(() => keyShortcuts('edit'), POLL).toBe('ArrowDown');+ expect(keyShortcuts('compose')).toBe('Alt+1');+ });++ it('names the add button', async () => {+ await renderStrip();+ const addButton = document.querySelector<HTMLElement>('[aria-label="Save this layout as a new preset"]')!;++ await act(() => userEvent.hover(addButton));+ await expect.poll(tipText, POLL).toBe('Save this layout as a new preset');+ });+ });});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsxindex 4dace36a8a..2b2b161175 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStrip.tsx@@ -1,9 +1,14 @@import type { DragEndEvent } from '@dnd-kit/core';-import type { LayoutPreset, LayoutPresetId, LayoutPresetSnapshot } from '@workbench/layoutContracts';+import type {+ BuiltInLayoutPresetId,+ LayoutPreset,+ LayoutPresetId,+ LayoutPresetSnapshot,+} from '@workbench/layoutContracts';import type { Project } from '@workbench/projectContracts';import type { KeyboardEvent, MouseEvent, PointerEvent } from 'react';-import { Box, HStack, Icon, Menu, Portal, Text, VisuallyHidden } from '@chakra-ui/react';+import { Box, HStack, Icon, Kbd, Menu, Portal, Stack, Text, useTooltipContext, VisuallyHidden } from '@chakra-ui/react';import {closestCenter,DndContext,@@ -24,15 +29,20 @@ import { CSS } from '@dnd-kit/utilities';import { useExitPresence } from '@platform/react/useExitRetainedValue';import { IconButton } from '@platform/ui/Button';import { MenuContent, MenuHeadingGroup } from '@platform/ui/Menu';+import { HIDDEN_SCROLLBAR_CSS } from '@platform/ui/scrollStripEdges';import { Tabs } from '@platform/ui/Tabs';import { Tooltip, TooltipGroup } from '@platform/ui/Tooltip';import { getPlacedWidgetTypeIds, graphWidgetSources } from '@workbench/graphWidgets';-import { useShortcutLabel } from '@workbench/hotkeys/useShortcutBinding';+import { useShortcutBinding, useShortcutLabel } from '@workbench/hotkeys/useShortcutBinding';import { preloadLayoutPresetWidgets } from '@workbench/layoutPresetActivation';import { getOrderedLayoutPresets } from '@workbench/layoutPresetCollection';-import { getLayoutPresetLabel } from '@workbench/layoutPresets';+import {+ builtInLayoutPresetDescriptors,+ getLayoutPresetLabel,+ isBuiltInLayoutPresetId,+} from '@workbench/layoutPresets';import { findLayoutPresetWorkingCopy } from '@workbench/layoutPresetSnapshots';-import { CUE_WIDTH, HIDDEN_SCROLLBAR_CSS, OverflowCue, useOverflowEdges } from '@workbench/shell/overflowEdges';+import { CUE_WIDTH, OverflowCue, useOverflowEdges } from '@workbench/shell/overflowEdges';import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchSelector } from '@workbench/WorkbenchContext';import {ArrowRightIcon,@@ -44,7 +54,7 @@ import {SettingsIcon,Trash2Icon,} from 'lucide-react';-import { useCallback, useId, useMemo, useRef, useState } from 'react';+import { useCallback, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react';import { useTranslation } from 'react-i18next';import type { LayoutPresetDialogValue } from './layoutPresetDialogModel';@@ -53,6 +63,7 @@ import { LayoutPresetDialog } from './LayoutPresetDialog';import { resolveLayoutPresetIcon } from './layoutPresetIcons';import { openLayoutPresetDelete, openLayoutPresetEdit, openLayoutPresetManager } from './layoutPresetManagerStore';import { HIDE_BELOW_PRESET_LABEL_WIDTH } from './topbarBreakpoints';+import { TopbarShortcutKeys } from './TopbarShortcutKeys';import { useActiveLayoutPresetId, useLayoutDrift, useUnsavedInactiveLayoutPresetIds } from './useLayoutDrift';const PRESET_MENU_ATTRIBUTE = 'data-preset-menu';@@ -75,6 +86,30 @@ const TOUCH_SENSOR_OPTIONS = { activationConstraint: { delay: 250, tolerance: 5const createCustomPresetId = (): string =>`custom-layout-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;+/** What each built-in preset is for, as the tab's tip says under its name. */+const BUILT_IN_PRESET_DESCRIPTION_KEYS: Record<BuiltInLayoutPresetId, string> = {+ automate: 'topbar.presets.builtInDescriptions.automate',+ compose: 'topbar.presets.builtInDescriptions.compose',+ edit: 'topbar.presets.builtInDescriptions.edit',+ video: 'topbar.presets.builtInDescriptions.video',+};++const findPresetShortcutCommandId = (presetId: LayoutPresetId): string | null => {+ const descriptor = builtInLayoutPresetDescriptors.find(({ preset }) => preset.id === presetId);++ return descriptor ? `app.${descriptor.hotkeyId}` : null;+};++// The label's own hiding condition, so the tip and the label never disagree about whether the name is on screen.+const matchLabelHidden = (): MediaQueryList =>+ globalThis.matchMedia(Object.keys(HIDE_BELOW_PRESET_LABEL_WIDTH)[0]!.replace(/^@media\s+/, ''));+const subscribeLabelHidden = (onChange: () => void): (() => void) => {+ const query = matchLabelHidden();+ query.addEventListener('change', onChange);+ return () => query.removeEventListener('change', onChange);+};+const getLabelHidden = (): boolean => matchLabelHidden().matches;+const selectPresetWorkingLayouts = (project: Project) => project.presetWorkingLayouts;const selectPlacedGraphWidgetSources = (project: Project) => {@@ -109,6 +144,23 @@ export const LayoutPresetStrip = () => {(presetId: LayoutPresetId) => (presetId === activePresetId ? hasDrifted : unsavedInactiveIds.has(presetId)),[activePresetId, hasDrifted, unsavedInactiveIds]);+ const [isReordering, setIsReordering] = useState(false);+ const isLabelHidden = useSyncExternalStore(subscribeLabelHidden, getLabelHidden);+ // Like the top bar's other labelled controls, a visible label is not repeated: beside it, a preset has a tip only for+ // what the label does not say (a built-in's shortcut and purpose, unsaved changes).+ const hasTip = useCallback(+ (presetId: LayoutPresetId) => isLabelHidden || isBuiltInLayoutPresetId(presetId) || isPresetUnsaved(presetId),+ [isLabelHidden, isPresetUnsaved]+ );+ // Quiet while a preset's menu is open or a tab is being dragged, where it would cover the menu or trail the drag.+ const isTipShown = useCallback(+ (presetId: LayoutPresetId) => menuTarget === null && !isReordering && hasTip(presetId),+ [hasTip, isReordering, menuTarget]+ );+ const presetTip = useMemo(+ () => <PresetTipContent hasTip={hasTip} isUnsaved={isPresetUnsaved} presets={presets} />,+ [hasTip, isPresetUnsaved, presets]+ );const tabsIdPrefix = useId();// Named so the strip's tooltip can anchor to each tab's own id instead of replacing it.const tabIds = useMemo(() => ({ trigger: (value: string) => `${tabsIdPrefix}-preset-${value}` }), [tabsIdPrefix]);@@ -203,8 +255,12 @@ export const LayoutPresetStrip = () => {const closeMenu = useCallback(() => setMenuTarget(null), []);const requestEdit = useCallback((preset: LayoutPreset) => openLayoutPresetEdit(preset.id), []);const requestDelete = useCallback((preset: LayoutPreset) => openLayoutPresetDelete(preset.id), []);+ const handleDragStart = useCallback(() => setIsReordering(true), []);+ const handleDragCancel = useCallback(() => setIsReordering(false), []);const handleDragEnd = useCallback((event: DragEndEvent) => {+ setIsReordering(false);+if (!event.over || event.active.id === event.over.id) {return;}@@ -237,7 +293,9 @@ export const LayoutPresetStrip = () => {collisionDetection={closestCenter}modifiers={DND_MODIFIERS}sensors={sensors}+ onDragCancel={handleDragCancel}onDragEnd={handleDragEnd}+ onDragStart={handleDragStart}><Tabs.Rootids={tabIds}@@ -250,14 +308,14 @@ export const LayoutPresetStrip = () => {{/* The name belongs on the tablist, not the root — the root is a plaincontainer and carries no role for it to name. */}<SortableContext items={presetIds} strategy={horizontalListSortingStrategy}>- {/* One tip for the strip, shown on unsaved presets: it follows focus and the pointer from tab to tab.- Not closed by scrolling: an arrow-key switch re-lays out the workbench, whose panels restore their- scroll positions, and the tab itself never scrolls out from under the tip. */}+ {/* One tip for the strip: it follows focus and the pointer from tab to tab. Not closed by scrolling:+ an arrow-key switch re-lays out the workbench, whose panels restore their scroll positions, and the+ tab itself never scrolls out from under the tip. */}<TooltipGroup.RootcloseOnScroll={false}- content={t('topbar.presets.unsavedLayoutChanges')}+ content={presetTip}getTriggerId={tabIds.trigger}- isEnabled={isPresetUnsaved}+ isEnabled={isTipShown}><Tabs.List aria-label={t('topbar.presets.layoutPreset')} gap="0.5">{presets.map((preset) => (@@ -364,6 +422,9 @@ const PresetTab = ({}) => {const { t } = useTranslation();const icon = resolveLayoutPresetIcon(preset.iconId);+ // An unknown command id resolves to no binding, so a custom preset advertises no key.+ const shortcut = useShortcutBinding(findPresetShortcutCommandId(preset.id) ?? '');+ const keyShortcuts = [isActive ? 'ArrowDown' : null, shortcut?.aria].filter(Boolean).join(' ') || undefined;const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({attributes: { role: 'tab', roleDescription: 'sortable', tabIndex: isActive ? 0 : -1 },id: preset.id,@@ -454,7 +515,7 @@ const PresetTab = ({{...attributes}{...listeners}aria-label={isUnsaved ? `${preset.label}, ${unsavedLabel}` : preset.label}- aria-keyshortcuts={isActive ? 'ArrowDown' : undefined}+ aria-keyshortcuts={keyShortcuts}css={PRESET_TAB_CSS}cursor={isDragging ? 'grabbing' : 'default'}data-layout-preset-id={preset.id}@@ -515,6 +576,66 @@ const PRESET_TAB_SELECTED_PROPS = {} as const;const UNSAVED_DOT_CSS = { boxShadow: `0 0 0 1.5px var(${PRESET_TAB_SURFACE})` } as const;+/**+ * The strip's one tip, describing the tab it is on: the preset's name and shortcut, what a built-in is for while it is+ * still the built-in (not renamed), and the unsaved state its dot marks. The shared tooltip reports which tab that is.+ */+const PresetTipContent = ({+ hasTip,+ isUnsaved,+ presets,+}: {+ hasTip: (presetId: LayoutPresetId) => boolean;+ isUnsaved: (presetId: LayoutPresetId) => boolean;+ presets: readonly LayoutPreset[];+}) => {+ const { t } = useTranslation();+ const { triggerValue } = useTooltipContext();+ const preset = presets.find(({ id }) => id === triggerValue);++ // Focus moving off an open tip switches the tooltip's tab at once and closes the tip a render later: a tab with no+ // tip of its own must not show in the fading one.+ if (!preset || !hasTip(preset.id)) {+ return null;+ }++ const shortcutCommandId = findPresetShortcutCommandId(preset.id);++ return (+ <Stack gap="0.5" maxW="16rem">+ <HStack gap="1.5" justify="space-between">+ <Text as="span" fontWeight="600">+ {preset.label}+ </Text>+ {shortcutCommandId ? <PresetShortcutKeys commandId={shortcutCommandId} /> : null}+ </HStack>+ {/* A renamed built-in may have been turned to another purpose; its shipped description could contradict it. */}+ {isBuiltInLayoutPresetId(preset.id) && preset.labelKey !== undefined ? (+ <Text as="span" color="fg.muted">+ {t(BUILT_IN_PRESET_DESCRIPTION_KEYS[preset.id])}+ </Text>+ ) : null}+ {isUnsaved(preset.id) ? (+ <HStack as="span" gap="1.5">+ <Box aria-hidden="true" bg="accent.solid" boxSize="1.5" flexShrink={0} rounded="full" />+ <Text as="span">{t('topbar.presets.unsavedLayoutChanges')}</Text>+ </HStack>+ ) : null}+ </Stack>+ );+};++/** Reads the effective binding, so a remapped or unbound shortcut is never advertised. */+const PresetShortcutKeys = ({ commandId }: { commandId: string }) => {+ const binding = useShortcutBinding(commandId);++ return binding ? (+ <Kbd variant="subtle">+ <TopbarShortcutKeys parts={binding.parts} />+ </Kbd>+ ) : null;+};+/** Over the icon's upper-right corner; the tab's accessible name and tooltip carry the state, not the colour. */const UnsavedDot = () => (<Boxdiff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsxindex a2cbdd44a2..b31bf4ffc6 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/LayoutPresetStripAck.browser.test.tsx@@ -46,7 +46,10 @@ vi.mock('@workbench/layoutPresetActivation', async (importOriginal) => ({...(await importOriginal<typeof LayoutPresetActivationModule>()),preloadLayoutPresetWidgets: () => undefined,}));-vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({ useShortcutLabel: () => null }));+vi.mock('@workbench/hotkeys/useShortcutBinding', () => ({+ useShortcutBinding: () => null,+ useShortcutLabel: () => null,+}));import { LayoutPresetStrip } from './LayoutPresetStrip';diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsxindex c0685f4dc4..23b0593df5 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.browser.test.tsx@@ -59,7 +59,11 @@ vi.mock('@features/queue/react', () => ({ useQueueItemProgress: () => null }));vi.mock('@platform/ui/ConfirmDialog', () => ({ ConfirmDialog: () => null }));vi.mock('@workbench/components/QueueProgressIndicator', () => ({ QueueCircularProgress: () => null }));vi.mock('@workbench/launchpad/formatRelativeTime', () => ({ formatRelativeTime: () => '' }));-vi.mock('@workbench/projects/components', () => ({ OpenProjectDialog: () => null }));+vi.mock('@workbench/projects/components/OpenProjectDialog', () => ({+ OpenProjectDialog: ({ isOpen }: { isOpen: boolean }) => (+ <div data-open={String(isOpen)} data-testid="open-project-dialog" />+ ),+}));vi.mock('@workbench/projects/components/DeleteProjectDialog', () => ({ DeleteProjectDialog: () => null }));vi.mock('@workbench/projects/library', () => ({refreshProjectLibrary: vi.fn(() => Promise.resolve()),@@ -189,6 +193,20 @@ describe('ProjectSwitcher', () => {await vi.waitFor(() => expect(document.querySelector('[role="dialog"][data-state="open"]')).not.toBeNull());});+ it('loads the Open Project dialog only once it is asked for, and opens it', async () => {+ const dialog = () => document.querySelector('[data-testid="open-project-dialog"]');+ let openItem: HTMLElement | undefined;+ await vi.waitFor(() => {+ openItem = document.querySelector<HTMLElement>('[role="menuitem"][data-value="open-project"]') ?? undefined;+ expect(openItem).toBeDefined();+ });+ expect(dialog()).toBeNull();++ await act(() => userEvent.click(openItem!));++ await vi.waitFor(() => expect(dialog()?.getAttribute('data-open')).toBe('true'));+ });+it('brightens the trigger chevron while hovered and while the menu is open, like the app menu', async () => {const resolveColor = (token: string) => {const probe = document.createElement('span');@@ -215,9 +233,22 @@ describe('ProjectSwitcher', () => {await vi.waitFor(() => expect(chevronColor()).toBe(bright));});- it('stands a folder icon in for the project name where the topbar is too narrow for it', async () => {+ it('shows an open folder while its menu is open and a closed one otherwise', async () => {const trigger = document.querySelector<HTMLElement>('button[aria-label="topbar.projectSwitcher.trigger"]')!;- const folderIcon = trigger.querySelector<SVGElement>('svg.lucide-folder')!;++ expect(trigger.querySelector('svg.lucide-folder-open')).not.toBeNull();+ expect(trigger.querySelector('svg.lucide-folder')).toBeNull();++ await act(() => setProjectSwitcherOpen(false));++ expect(trigger.querySelector('svg.lucide-folder')).not.toBeNull();+ expect(trigger.querySelector('svg.lucide-folder-open')).toBeNull();+ });++ it('keeps its folder icon and drops the project name where the topbar is too narrow for it', async () => {+ const trigger = document.querySelector<HTMLElement>('button[aria-label="topbar.projectSwitcher.trigger"]')!;+ // The menu is open here, so the trigger shows its open-folder glyph.+ const folderIcon = trigger.querySelector<SVGElement>('svg.lucide-folder-open')!;const name = [...trigger.children].find((child) => child.textContent === 'Prompt project')!;const { innerHeight, innerWidth } = window;@@ -231,7 +262,7 @@ describe('ProjectSwitcher', () => {await page.viewport(1200, 700);await vi.waitFor(() => {expect(name.checkVisibility()).toBe(true);- expect(folderIcon.checkVisibility()).toBe(false);+ expect(folderIcon.checkVisibility()).toBe(true);});} finally {await page.viewport(innerWidth, innerHeight);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsxindex 889b8c6f5d..f805cd30e0 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/ProjectSwitcher.tsx@@ -17,7 +17,6 @@ import { RenameDialog } from '@platform/ui/RenameDialog';import { toaster } from '@platform/ui/toaster';import { QueueCircularProgress } from '@workbench/components/QueueProgressIndicator';import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';-import { OpenProjectDialog } from '@workbench/projects/components';import { refreshProjectLibrary, renameLibraryProject, useProjectLibrarySelector } from '@workbench/projects/library';import { useProjectSyncAttention } from '@workbench/projects/syncStore';import { useProjectActions } from '@workbench/projects/useProjectActions';@@ -45,7 +44,7 @@ import { lazy, Suspense, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { projectSwitcherStore, setProjectSwitcherOpen } from './projectSwitcherStore';-import { HIDE_BELOW_PROJECT_NAME_WIDTH, SHOW_BELOW_PROJECT_NAME_WIDTH } from './topbarBreakpoints';+import { HIDE_BELOW_PROJECT_NAME_WIDTH } from './topbarBreakpoints';import { TopbarMenuChevron } from './TopbarMenuChevron';// The dialog reads the gallery's board query, and this host sits in a boot graph the performance gates pin by source@@ -55,6 +54,12 @@ const LazyDeleteProjectDialog = lazy(() =>default: module.DeleteProjectDialog,})));+// The project list's virtualized rows are not boot code either; loaded the first time Open Project is asked for.+const LazyOpenProjectDialog = lazy(() =>+ import('@workbench/projects/components/OpenProjectDialog').then((module) => ({+ default: module.OpenProjectDialog,+ }))+);// Modal from the request onward: while the dialog's module is still on its way, shortcuts must already be off.const PENDING_DIALOG = <Dialog.Pending />;@@ -79,8 +84,9 @@ export const ProjectSwitcher = () => {const returnFocus = useCallback(() => triggerRef.current, []);const [renameTarget, setRenameTarget] = useState<{ id: string; name: string } | null>(null);const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);- // Once mounted the dialog stays, so its close animation and the lazy chunk are paid for once.+ // Once mounted a dialog stays, so its close animation and the lazy chunk are paid for once.const [hasRequestedDelete, setHasRequestedDelete] = useState(false);+ const [hasRequestedOpenDialog, setHasRequestedOpenDialog] = useState(false);const [isOpenDialogVisible, setIsOpenDialogVisible] = useState(false);const isMenuOpen = projectSwitcherStore.useSelector((snapshot) => snapshot.isOpen);@@ -106,7 +112,10 @@ export const ProjectSwitcher = () => {const createProject = useCallback(() => {projects.create();}, [projects]);- const showOpenDialog = useCallback(() => setIsOpenDialogVisible(true), []);+ const showOpenDialog = useCallback(() => {+ setHasRequestedOpenDialog(true);+ setIsOpenDialogVisible(true);+ }, []);const hideOpenDialog = useCallback(() => setIsOpenDialogVisible(false), []);const closeRenameDialog = useCallback(() => setRenameTarget(null), []);const closeDeleteDialog = useCallback(() => setDeleteTarget(null), []);@@ -207,11 +216,12 @@ export const ProjectSwitcher = () => {{ name: activeProjectName })}className="group"+ px="2"size="lg"variant="ghost"onContextMenu={handleTriggerContextMenu}>- <Icon as={FolderIcon} boxSize="4" css={SHOW_BELOW_PROJECT_NAME_WIDTH} flexShrink={0} />+ <Icon as={isMenuOpen ? FolderOpenIcon : FolderIcon} boxSize="4" flexShrink={0} /><MiddleTruncate css={HIDE_BELOW_PROJECT_NAME_WIDTH} fontWeight="500" minW="0" text={activeProjectName} />{hasProjectNeedingAttention ? (<Icon as={TriangleAlertIcon} boxSize="3.5" color="fg.warning" flexShrink={0} />@@ -310,11 +320,11 @@ export const ProjectSwitcher = () => {/></Suspense>) : null}- {/*- * Keep the dialog mounted by open state; its lazyMount/unmountOnExit handle closed cost and preserve exit- * animation.- */}- <OpenProjectDialog isOpen={isOpenDialogVisible} onClose={hideOpenDialog} />+ {hasRequestedOpenDialog ? (+ <Suspense fallback={isOpenDialogVisible ? PENDING_DIALOG : null}>+ <LazyOpenProjectDialog isOpen={isOpenDialogVisible} onClose={hideOpenDialog} />+ </Suspense>+ ) : null}</>);};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.browser.test.tsxindex 418ff25fb2..1036052914 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.browser.test.tsx@@ -2,10 +2,12 @@import type * as QueueDataStore from '@features/queue/ui/queueDataStore';import { ChakraProvider } from '@chakra-ui/react';+import { CANCEL_CURRENT_SETTLE_MS } from '@features/queue/ui/cancelCurrent';import { clearQueueConfirmation } from '@features/queue/ui/queueConfirmationStore';import { QueueDataRuntime } from '@features/queue/ui/QueueDataRuntime';-import { createTestQueueUiAdapter } from '@features/queue/ui/queueUiAdapter.testing';-import { QueueUiProvider } from '@features/queue/ui/QueueUiContext';+import { createTestLocalRun, createTestQueueUiAdapter } from '@features/queue/ui/queueUiAdapter.testing';+import { QueueUiProvider, type QueueLocalRun } from '@features/queue/ui/QueueUiContext';+import { accountLifecycle } from '@platform/state/accountLifecycle';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act } from 'react';@@ -13,11 +15,36 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';-const state = vi.hoisted(() => ({ isConnected: true, localItems: [] as unknown[] }));+const state = vi.hoisted(() => ({+ isConnected: true,+ /** The queue processor is paused. */+ isPaused: false,+ /** "Show jobs from" the active project; with it, how many items run anywhere in the queue. */+ projectScoped: false,+ wholeQueueInProgress: 0,+ localItems: [] as unknown[],+ /** This tab's runs the backend has not accepted, which only cancel-all reaches. */+ localRuns: [] as QueueLocalRun[],+ /** A read of the server fails, as when it stops answering. */+ readFails: false,+ /**+ * The server's items now. The seeded reading stays cached until a read asks again; null keeps the server as the test+ * seeded it.+ */+ serverItems: null as null | Array<{ id: number; status: string }>,+}));const commands = vi.hoisted(() => ({- cancelItem: vi.fn(() => Promise.resolve()),+ // Cancels an unfinished item; returns a finished one unchanged, as the server does.+ cancelItem: vi.fn((id: number) => {+ const item = state.serverItems?.find((candidate) => candidate.id === id);+ if (item && ['pending', 'in_progress'].includes(item.status)) {+ item.status = 'canceled';+ }+ return Promise.resolve({ ...item, id, status: item?.status ?? 'canceled' });+ }),cancelScopedItems: vi.fn(() => Promise.resolve()),}));+const notify = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -28,8 +55,12 @@ vi.mock('@features/models', () => ({ useModelLoads: () => [] }));vi.mock('@features/queue/publicApi', () => ({createProductionQueueRealtimeRuntime: () => ({ dispose: vi.fn(), start: vi.fn() }),getQueueItemDetailOptions: (itemId: number) => ({ queryFn: () => null, queryKey: ['queue', 'item-detail', itemId] }),- // The seeded read model stays put: nothing refetches it over the test's data.- getQueueReadModelOptions: () => ({ queryFn: () => null, queryKey: ['queue'], staleTime: Number.POSITIVE_INFINITY }),+ // The seeded read model stays put: nothing refetches it over the test's data unless an action asks afresh.+ getQueueReadModelOptions: () => ({+ queryFn: () => serverReading(),+ queryKey: ['queue', 'read-model', 'all'],+ staleTime: Number.POSITIVE_INFINITY,+ }),queueCommands: commands,}));vi.mock('@features/queue/data/generationDevicesStore', () => ({ refreshGenerationDevices: vi.fn() }));@@ -62,7 +93,7 @@ const running = {updatedAt: '2026-06-27T00:00:00Z',};-const serverItem = (id: number, status: 'in_progress' | 'pending') => ({+const serverItem = (id: number, status: 'canceled' | 'completed' | 'in_progress' | 'pending') => ({...running,id,sessionId: `session-${id}`,@@ -75,14 +106,66 @@ const render = async ({items = [running, serverItem(8, 'pending'), serverItem(9, 'pending')],}: { current?: ReturnType<typeof serverItem> | null; items?: ReturnType<typeof serverItem>[] } = {}) => {client = new QueryClient();+ client.setQueryData(['queue', 'read-model', 'all'], readModel({ current, items }));+ if (state.projectScoped) {+ // The whole queue's status read the Launchpad shares, fresh, so nothing reads it again here.+ const whole = readModel({ current: null, items: [] }).status;+ client.setQueryData(['queue', 'status', 'all'], {+ ...whole,+ queue: { ...whole.queue, inProgress: state.wholeQueueInProgress },+ });+ }+ state.serverItems ??= structuredClone(items);++ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={client}>+ <QueueUiProvider+ adapter={createTestQueueUiAdapter({+ activeProjectId: 'project-1',+ canManageItem: (item) => item.userId !== 'someone-else',+ queueJobsScope: state.projectScoped ? 'active-project' : 'all',+ isConnected: state.isConnected,+ localRuns: state.localRuns,+ notify,+ })}+ >+ <QueueCluster />+ <QueueDataRuntime />+ </QueueUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ )+ );+};++/** What a read of the server finds now. */+function serverReading() {+ if (state.readFails) {+ throw new Error('Server unavailable');+ }+ const items = (state.serverItems ?? []) as ReturnType<typeof serverItem>[];+ return readModel({ current: items.find((item) => item.status === 'in_progress') ?? null, items });+}++/** A server reading of the scope; the next item is the oldest one waiting, as the server picks it. */+const readModel = ({+ current,+ items,+}: {+ current: ReturnType<typeof serverItem> | null;+ items: ReturnType<typeof serverItem>[];+}) => {const open = items.filter((item) => item.status === 'pending' || item.status === 'in_progress');- client.setQueryData(['queue'], {++ return {current,items,- next: null,+ next: open.filter((item) => item.status === 'pending').sort((left, right) => left.id - right.id)[0] ?? null,scope: {},status: {- processor: { isProcessing: true, isStarted: true },+ processor: { isProcessing: true, isStarted: !state.isPaused },queue: {canceled: 0,completed: 0,@@ -94,24 +177,14 @@ const render = async ({waiting: 0,},},- });-- await act(() =>- root.render(- <ChakraProvider value={system}>- <QueryClientProvider client={client}>- <QueueUiProvider adapter={createTestQueueUiAdapter({ isConnected: state.isConnected })}>- <QueueCluster />- <QueueDataRuntime />- </QueueUiProvider>- </QueryClientProvider>- </ChakraProvider>- )- );+ };};+/** The ×: named for the running item, or between items for the next one, unless Shift arms cancel-all. */const cancelButton = () =>- host.querySelector<HTMLButtonElement>('button[aria-label="widgets.queue.cancelCurrentItem"]')!;+ host.querySelector<HTMLButtonElement>(+ 'button[aria-label="widgets.queue.cancelCurrentItem"], button[aria-label="widgets.queue.cancelNextItem"]'+ )!;const confirmation = () => document.querySelector('[role="alertdialog"]');const queueButton = () => host.querySelector<HTMLButtonElement>('button[aria-label^="topbar.queue.remaining"]')!;const announcement = () => host.querySelector('[aria-live="polite"]')?.textContent;@@ -134,6 +207,15 @@ const projectRun = (status: 'completed' | 'pending' | 'running', backendItemIdsbeforeEach(() => {state.isConnected = true;state.localItems = [];+ state.localRuns = [];+ state.isPaused = false;+ state.projectScoped = false;+ state.wholeQueueInProgress = 0;+ state.readFails = false;+ state.serverItems = null;+ notify.error.mockClear();+ notify.info.mockClear();+ notify.success.mockClear();commands.cancelItem.mockClear();commands.cancelScopedItems.mockClear();host = document.createElement('div');@@ -145,6 +227,10 @@ afterEach(async () => {clearQueueConfirmation();await act(() => root.unmount());host.remove();+ // A cancel that stopped an item keeps the command busy for its settle window; a new account ends it, so the next+ // test starts free.+ accountLifecycle.invalidate();+ accountLifecycle.activate('queue-cluster-test');});describe('QueueCluster', () => {@@ -155,6 +241,192 @@ describe('QueueCluster', () => {await vi.waitFor(() => expect(commands.cancelItem).toHaveBeenCalledWith(7));expect(confirmation()).toBeNull();+ await vi.waitFor(() =>+ expect(notify.success).toHaveBeenCalledExactlyOnceWith('widgets.queue.cancellationRequested', expect.any(String))+ );+ });++ it('keeps the cancel button in place, disabled, while nothing is running or waiting', async () => {+ await render({ current: null, items: [serverItem(6, 'completed')] });++ expect(cancelButton().disabled).toBe(true);+ });++ it('names and stops the next waiting item between items, while nothing runs', async () => {+ // Item 7 finished and item 8 has not started yet.+ await render({+ current: null,+ items: [serverItem(7, 'completed'), serverItem(8, 'pending'), serverItem(9, 'pending')],+ });++ expect(cancelButton().disabled).toBe(false);+ expect(cancelButton().getAttribute('aria-label')).toBe('widgets.queue.cancelNextItem');+ await act(() => userEvent.click(cancelButton()));++ await vi.waitFor(() => expect(commands.cancelItem).toHaveBeenCalledExactlyOnceWith(8));+ await vi.waitFor(() =>+ expect(notify.success).toHaveBeenCalledExactlyOnceWith('widgets.queue.cancellationRequested', expect.any(String))+ );+ });++ it('stops one item for a double click, and the next one on a later click', async () => {+ let answer!: () => void;+ commands.cancelItem.mockImplementationOnce((id: number) => {+ const item = state.serverItems!.find((candidate) => candidate.id === id)!;+ item.status = 'canceled';+ return new Promise((resolve) => {+ answer = () => resolve({ ...item, id, status: 'canceled' });+ });+ });+ await render();++ await act(() => userEvent.dblClick(cancelButton()));+ await act(() => answer());+ await vi.waitFor(() => expect(notify.success).toHaveBeenCalledOnce());+ expect(commands.cancelItem.mock.calls).toEqual([[7]]);++ // Once the reconciling read has landed and the settle window is over, a deliberate click stops the next item.+ await vi.waitFor(() => expect(cancelButton().getAttribute('aria-label')).toBe('widgets.queue.cancelNextItem'));+ await act(+ () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, CANCEL_CURRENT_SETTLE_MS + 100);+ })+ );+ await act(() => userEvent.click(cancelButton()));+ await vi.waitFor(() => expect(commands.cancelItem.mock.calls).toEqual([[7], [8]]));+ });++ it("ignores a double click's second click, though the first click's cancel has already failed", async () => {+ // Nothing keeps the command busy after a failure, so only the click's own count tells the two apart.+ commands.cancelItem.mockImplementationOnce(() => Promise.reject(new Error('Server unavailable')));+ await render();++ await act(() => userEvent.dblClick(cancelButton()));++ await vi.waitFor(() => expect(notify.error).toHaveBeenCalledOnce());+ expect(commands.cancelItem.mock.calls).toEqual([[7]]);+ });++ it('acts once for a held Enter: its repeats neither retry a failed cancel nor stop another item', async () => {+ commands.cancelItem.mockImplementationOnce(() => Promise.reject(new Error('Server unavailable')));+ await render();++ cancelButton().focus();+ await act(() => userEvent.keyboard('{Enter>4}'));+ await act(() => userEvent.keyboard('{/Enter}'));++ await vi.waitFor(() => expect(notify.error).toHaveBeenCalledOnce());+ expect(commands.cancelItem.mock.calls).toEqual([[7]]);+ // A new press is no repeat.+ await act(() => userEvent.keyboard('{Enter}'));+ await vi.waitFor(() => expect(commands.cancelItem.mock.calls).toEqual([[7], [7]]));+ });++ it('stops nothing waiting while the processor is paused: the × is disabled', async () => {+ state.isPaused = true;+ await render({ current: null, items: [serverItem(7, 'completed'), serverItem(8, 'pending')] });++ expect(cancelButton().disabled).toBe(true);+ });++ it("in a project view, stops nothing waiting while another project's item runs: the × is disabled", async () => {+ state.projectScoped = true;+ state.wholeQueueInProgress = 1;+ // The project's own reading: nothing of its own runs, and its next item waits.+ await render({ current: null, items: [serverItem(7, 'completed'), serverItem(8, 'pending')] });++ expect(cancelButton().disabled).toBe(true);+ });++ it('in a project view, offers the next item while nothing runs anywhere', async () => {+ state.projectScoped = true;+ await render({ current: null, items: [serverItem(7, 'completed'), serverItem(8, 'pending')] });++ expect(cancelButton().disabled).toBe(false);+ expect(cancelButton().getAttribute('aria-label')).toBe('widgets.queue.cancelNextItem');+ });++ it("stops nothing waiting while someone else's item runs: the × is disabled", async () => {+ const theirs = { ...serverItem(20, 'in_progress'), userId: 'someone-else' };+ await render({ current: theirs, items: [serverItem(21, 'pending'), theirs] });++ expect(cancelButton().disabled).toBe(true);+ });++ it('shows the item running again and says the cancel failed, so the next click tries it again', async () => {+ commands.cancelItem.mockImplementationOnce(() => Promise.reject(new Error('Server unavailable')));+ await render();++ await act(() => userEvent.click(cancelButton()));++ await vi.waitFor(() =>+ expect(notify.error).toHaveBeenCalledExactlyOnceWith(+ 'widgets.queue.failedToCancelCurrentItem',+ 'Server unavailable'+ )+ );+ expect(notify.success).not.toHaveBeenCalled();+ expect(cancelButton().getAttribute('aria-label')).toBe('widgets.queue.cancelCurrentItem');+ await act(() => userEvent.click(cancelButton()));+ await vi.waitFor(() => expect(commands.cancelItem.mock.calls).toEqual([[7], [7]]));+ });++ it('stops what runs now when the item it read as running had already finished', async () => {+ // The server has moved on: item 7 completed and item 8 runs.+ state.serverItems = [serverItem(7, 'completed'), serverItem(8, 'in_progress'), serverItem(9, 'pending')];+ await render();++ await act(() => userEvent.click(cancelButton()));++ await vi.waitFor(() => expect(commands.cancelItem.mock.calls).toEqual([[7], [8]]));+ await vi.waitFor(() => expect(notify.success).toHaveBeenCalledOnce());+ expect(notify.info).not.toHaveBeenCalled();+ });++ it('says there is nothing to cancel, and claims no cancel, when everything had already finished', async () => {+ state.serverItems = [serverItem(7, 'completed')];+ await render({ current: running, items: [running] });++ await act(() => userEvent.click(cancelButton()));++ await vi.waitFor(() =>+ expect(notify.info).toHaveBeenCalledExactlyOnceWith('widgets.queue.noCurrentItem', expect.any(String))+ );+ expect(commands.cancelItem.mock.calls).toEqual([[7]]);+ expect(notify.success).not.toHaveBeenCalled();+ });++ it('says the item had already finished, not that the cancel failed, when what runs now cannot be read', async () => {+ state.serverItems = [serverItem(7, 'completed')];+ await render({ current: running, items: [running] });+ state.readFails = true;++ await act(() => userEvent.click(cancelButton()));++ await vi.waitFor(() =>+ expect(notify.info).toHaveBeenCalledExactlyOnceWith('widgets.queue.itemAlreadyFinished', expect.any(String))+ );+ expect(notify.error).not.toHaveBeenCalled();+ expect(notify.success).not.toHaveBeenCalled();+ });++ it('does not arm cancel-all on the disabled button, though Shift is held over it with work waiting', async () => {+ // Offline, nothing on the server is in reach; this tab's unaccepted run still is, for cancel-all alone.+ state.isConnected = false;+ state.localItems = [projectRun('pending', [])];+ state.localRuns = [createTestLocalRun()];+ await render({ current: null, items: [] });+ const button = cancelButton();++ await act(() => userEvent.hover(button));+ await act(() => userEvent.keyboard('{Shift>}'));+ const labelWithShift = button.getAttribute('aria-label');+ const disabledWithShift = button.disabled;+ await act(() => userEvent.keyboard('{/Shift}'));++ expect(labelWithShift).toBe('widgets.queue.cancelCurrentItem');+ expect(disabledWithShift).toBe(true);});it('asks before cancelling everything on shift-click, and cancels nothing until confirmed', async () => {@@ -215,7 +487,7 @@ describe('QueueCluster', () => {await render({ items: window });// The server counts all 80 open items, not just the window it lists.await act(() =>- client.setQueryData(['queue'], (model: { status: { queue: object } }) => ({+ client.setQueryData(['queue', 'read-model', 'all'], (model: { status: { queue: object } }) => ({...model,status: { ...model.status, queue: { ...model.status.queue, inProgress: 1, pending: 79 } },}))diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsxindex 8dcfa80648..5089c473d8 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/QueueCluster.tsx@@ -19,7 +19,15 @@ import { getDestinationLabel, getSourceLabel } from '@workbench/invocation';import { useQueueChromeActivity } from '@workbench/queue-integration/useActiveQueueProgress';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { CloudOffIcon, ListOrderedIcon, ListXIcon, PauseIcon, XIcon } from 'lucide-react';-import { useCallback, useMemo, useState, type MouseEvent, type PointerEvent, type ReactNode } from 'react';+import {+ useCallback,+ useMemo,+ useState,+ type KeyboardEvent as ReactKeyboardEvent,+ type MouseEvent,+ type PointerEvent,+ type ReactNode,+} from 'react';import { useTranslation } from 'react-i18next';import { TopbarMenuChevron } from './TopbarMenuChevron';@@ -78,8 +86,9 @@ export const QueueCluster = () => {const isCancellable = !cancelCurrent?.disabled;const [lastCancellable, setLastCancellable] = useState(isCancellable);- // The "x" unmounts while hovered when the running job finishes, so its- // pointer-leave never fires; reset the gesture state with it.+ // Hover is tracked only while the "x" is enabled, so the shift gesture cannot arm a button that does nothing. It+ // turns disabled under a resting pointer when the running job finishes, and that pointer's leave goes unhandled;+ // reset the gesture state with it.if (isCancellable !== lastCancellable) {setLastCancellable(isCancellable);@@ -100,9 +109,16 @@ export const QueueCluster = () => {setIsCancelHovered(false);setIsShiftHeld(false);}, []);- // Shift-click reaches every item, so it confirms first; a plain click stops only the running one and does not.+ // Shift-click reaches every item, so it confirms first; a plain click stops one item, the running one or between+ // items the next one waiting (the button's name says which), and does not.+ // The later clicks of a double click are one gesture with the first, however long the system lets it take; the+ // command's own settle window covers double taps from the keyboard and the palette.const handleCancelClick = useCallback((event: MouseEvent<HTMLButtonElement>) => {+ if (event.detail > 1) {+ return;+ }+if (event.shiftKey && cancelAll && !cancelAll.disabled) {void cancelAll.trigger();return;@@ -112,6 +128,13 @@ export const QueueCluster = () => {},[cancelAll, cancelCurrent]);+ // A held Enter clicks on every auto-repeat, and the repeats outlast the command's settle window; one press stops one+ // item. Space clicks on release, so it never repeats. Enter alone: a held Tab moving through must not stop here.+ const handleCancelKeyDown = useCallback((event: ReactKeyboardEvent<HTMLButtonElement>) => {+ if (event.repeat && event.key === 'Enter') {+ event.preventDefault();+ }+ }, []);return (<Menu.Root>@@ -145,23 +168,28 @@ export const QueueCluster = () => {</Button></QueueButtonTooltip>- {isCancellable && cancelCurrent ? (+ {/* Always present, so the cluster keeps its width and the control its place; disabled with nothing to stop. */}+ {cancelCurrent ? (<Tooltipcontent={isCancelAllArmed && cancelAll? cancelAll.label- : `${cancelCurrent.label} · ${t('topbar.queue.shiftCancelsAll')}`+ : isCancellable+ ? `${cancelCurrent.label} · ${t('topbar.queue.shiftCancelsAll')}`+ : cancelCurrent.label}showArrow><IconButtonaria-label={isCancelAllArmed && cancelAll ? cancelAll.label : cancelCurrent.label}- color="fg.error"+ color={isCancellable ? 'fg.error' : undefined}+ disabled={!isCancellable}size="lg"variant="outline"onClick={handleCancelClick}- onPointerEnter={handleCancelPointerEnter}- onPointerLeave={handleCancelPointerLeave}+ onKeyDown={handleCancelKeyDown}+ onPointerEnter={isCancellable ? handleCancelPointerEnter : undefined}+ onPointerLeave={isCancellable ? handleCancelPointerLeave : undefined}><Icon as={isCancelAllArmed ? ListXIcon : XIcon} /></IconButton>diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.browser.test.tsxindex 7616a1ab49..13bc1b7a3c 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.browser.test.tsx@@ -265,4 +265,29 @@ describe('useInvokeIssueActions', () => {videoPrompt.remove();}});++ it("opens Upscale and its Detail guidance, and focuses Upscale's prompt, not Generate's", async () => {+ await patchWorkbenchPreferences({ generateSectionsOpen: { upscaleDetailGuidance: false } });+ const generatePrompt = document.createElement('textarea');+ const upscalePrompt = document.createElement('textarea');+ document.body.append(generatePrompt, upscalePrompt);+ registerPositivePromptElement('generate', generatePrompt, null);+ registerPositivePromptElement('upscale', upscalePrompt, null);++ try {+ await run(+ { message: 'The prompt could not be expanded.', target: { kind: 'prompt', widgetId: 'upscale' } },+ 'show'+ );+ await expect.poll(() => document.activeElement).toBe(upscalePrompt);++ expect(getWorkbenchPreferences().generateSectionsOpen.upscaleDetailGuidance).toBe(true);+ expect(isPlaced('upscale')).toBe(true);+ } finally {+ registerPositivePromptElement('generate', null, generatePrompt);+ registerPositivePromptElement('upscale', null, upscalePrompt);+ generatePrompt.remove();+ upscalePrompt.remove();+ }+ });});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.tsindex f9b6b5d303..afe88a2251 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueActions.ts@@ -1,6 +1,6 @@import type { GenerationIssue } from '@features/generation/contracts';-import { flushGenerateDrafts, focusPositivePrompt, revealGenerateIssue } from '@features/generation/react';+import { flushGenerateDrafts, revealGenerateIssue, revealPositivePrompt } from '@features/generation/react';import {describeGenerationIssueFix,getGenerationIssueFixPatch,@@ -8,6 +8,7 @@ import {} from '@features/generation/settings';import { useCapabilities } from '@features/identity';import { openModelManager } from '@features/models';+import { UPSCALE_SECTION_IDS } from '@features/upscale';import { revealWorkflowNode } from '@features/workflow/react';import { useWorkbenchFocus } from '@workbench/focusRegions';import { getWidgetTypeIdForSourceId } from '@workbench/graphWidgets';@@ -114,8 +115,17 @@ export const useInvokeIssueActions = (): ((issue: InvocationIssue) => InvokeIssucase 'prompt':return [show(() => {+ // Upscale's prompt, and the note saying why it cannot expand, sit in its Detail guidance section.+ if (target.widgetId === 'upscale') {+ void patchWorkbenchPreferences({+ generateSectionsOpen: {+ ...getWorkbenchPreferences().generateSectionsOpen,+ [UPSCALE_SECTION_IDS.detailGuidance]: true,+ },+ });+ }reveal(target.widgetId);- requestAnimationFrame(() => focusPositivePrompt(target.widgetId));+ revealPositivePrompt(target.widgetId);}),];case 'layer':diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.tsindex 5176abea5a..74f340efea 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/invokeIssueTargets.ts@@ -11,7 +11,7 @@ export type InvocationIssueTarget =/** A Generate setting: open the Generate panel at its section, or apply its one-step fix. */| { kind: 'generation'; issue: GenerationIssue }/** The positive prompt of this widget could not be expanded. */- | { kind: 'prompt'; widgetId: 'generate' | 'video' }+ | { kind: 'prompt'; widgetId: 'generate' | 'upscale' | 'video' }| { kind: 'layer'; layerId: string }| { kind: 'workflowNode'; nodeId: string }/** The source's widget is not in the layout: add it, or run another source. */diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.tsindex 0a28a57235..b138477566 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/layoutPresetIcons.ts@@ -25,6 +25,7 @@ import {LayoutPanelTopIcon,PaletteIcon,PanelsTopLeftIcon,+ PencilRulerIcon,PenToolIcon,RocketIcon,Rows2Icon,@@ -76,6 +77,7 @@ export const layoutPresetIconGroups: LayoutPresetIconGroup[] = [option('type', TypeIcon, 'Text'),option('brush', BrushIcon, 'Brush'),option('pen-tool', PenToolIcon, 'Pen'),+ option('pencil-ruler', PencilRulerIcon, 'Pencil and ruler'),option('palette', PaletteIcon, 'Palette'),option('layers', LayersIcon, 'Layers'),option('crop', CropIcon, 'Crop'),diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/topbarBreakpoints.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/topbarBreakpoints.tsindex f0d6493a8e..a13c6b8f90 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/topbarBreakpoints.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/topbarBreakpoints.ts@@ -1,14 +1,7 @@const hideBelow = (px: number) => ({ [`@media (max-width: ${px - 1}px)`]: { display: 'none' } }) as const;-const showBelow = (px: number) => ({ [`@media (min-width: ${px}px)`]: { display: 'none' } }) as const;--const PROJECT_NAME_MIN_WIDTH = 1024;-export const HIDE_BELOW_HINT_WIDTH = hideBelow(1440);export const HIDE_BELOW_PRESET_LABEL_WIDTH = hideBelow(1280);-export const HIDE_BELOW_PROJECT_NAME_WIDTH = hideBelow(PROJECT_NAME_MIN_WIDTH);--/** Stands in for the project name where `HIDE_BELOW_PROJECT_NAME_WIDTH` hides it. */-export const SHOW_BELOW_PROJECT_NAME_WIDTH = showBelow(PROJECT_NAME_MIN_WIDTH);+export const HIDE_BELOW_PROJECT_NAME_WIDTH = hideBelow(1024);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 0b0a2c5345..d9a3f74fe4 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@@ -350,3 +350,35 @@ describe('useInvocationState and Video dynamic prompts', () => {).toBe('1');});});++describe('useInvocationState and Upscale dynamic prompts', () => {+ const renderUpscale = async (upscaleValues: Record<string, unknown>) => {+ let state = workbenchReducer(createInitialWorkbenchState(), {+ sourceId: 'upscale',+ type: 'patchProjectPromptDraft',+ values: {+ positivePrompt: 'a {cat|dog|bird}',+ promptTemplate: { id: 'film', name: 'Film', negativePrompt: '', positivePrompt: '{prompt}, {grain|haze}' },+ },+ });+ state = workbenchReducer(state, { type: 'patchWidgetValues', values: upscaleValues, widgetId: 'upscale' });+ state = workbenchReducer(state, { sourceId: 'upscale', type: 'setInvocationSource' });+ harness.useDynamicPrompts.mockClear();+ await renderProbe(activeProject(state));++ return host?.querySelector('[data-testid="reasons"]')?.getAttribute('data-prompt-count');+ };++ it('counts the expansion of the prompt Refine shares with Generate, inside its template', async () => {+ expect(await renderUpscale({ mode: 'refine' })).toBe('4');+ expect(harness.useDynamicPrompts).toHaveBeenLastCalledWith(+ 'a {cat|dog|bird}, {grain|haze}',+ expect.objectContaining({ enabled: true })+ );+ });++ it('counts one prompt for Model only, which reads none', async () => {+ expect(await renderUpscale({ mode: 'model-only' })).toBe('1');+ expect(harness.useDynamicPrompts).toHaveBeenLastCalledWith(expect.any(String), null);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.tsindex a835da3abd..8acbc809cb 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts@@ -10,12 +10,13 @@ import {describeGenerationIssue,getDynamicPromptsConfig,getEffectivePrompts,+ getPromptDraftFromValues,normalizeGenerateSettings,sanitizeBatchCount,sanitizeDynamicPromptsConfig,} from '@features/generation/settings';import { ensureModelsLoaded, useModelsSelector } from '@features/models';-import { isUpscaleBatchCountFixed } from '@features/upscale';+import { isUpscaleBatchCountFixed, readsUpscalePrompt } from '@features/upscale';import { normalizeVideoWidgetValues } from '@features/video';import { getInvocationTemplatesSnapshot, subscribeInvocationTemplates } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';@@ -187,15 +188,26 @@ export const useInvocationState = ({ sourceId }: { sourceId?: InvocationSourceId? routeInput.workflowValues: routeInput.generateValues;- // Video reads its own normalized values, so the count follows what its submission expands.+ // Video reads its own normalized values, so the count follows what its submission expands. Upscale's Refine reads+ // the draft it shares with Generate, as its submission does.const videoValues = invocation.sourceId === 'video' ? normalizeVideoWidgetValues(routeInput.videoValues) : null;+ const upscalePromptDraft =+ invocation.sourceId === 'upscale' && readsUpscalePrompt(routeInput.upscaleValues)+ ? getPromptDraftFromValues(routeInput.generateValues)+ : null;const promptExpansion = useDynamicPrompts(- videoValues ? videoValues.positivePrompt : readEffectivePositivePrompt(routeInput.generateValues),+ videoValues+ ? videoValues.positivePrompt+ : upscalePromptDraft+ ? getEffectivePrompts(upscalePromptDraft).positivePrompt+ : readEffectivePositivePrompt(routeInput.generateValues),videoValues? getDynamicPromptsConfig(videoValues)- : invocation.sourceId === 'generate' || invocation.sourceId === 'canvas'- ? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues))- : null+ : upscalePromptDraft+ ? getDynamicPromptsConfig(upscalePromptDraft)+ : invocation.sourceId === 'generate' || invocation.sourceId === 'canvas'+ ? sanitizeDynamicPromptsConfig(readDynamicPromptsConfig(routeInput.generateValues))+ : null);// Block unexpandable prompts rather than submitting literal dynamic syntax; hotkey submission enforces the same// rule. The prompt field offers the way out: retry, or turn dynamic prompts off and run the prompt as typed.@@ -212,7 +224,13 @@ export const useInvocationState = ({ sourceId }: { sourceId?: InvocationSourceId: [{message: expansionReason,- target: { kind: 'prompt', widgetId: invocation.sourceId === 'video' ? 'video' : 'generate' },+ target: {+ kind: 'prompt',+ widgetId:+ invocation.sourceId === 'video' || invocation.sourceId === 'upscale'+ ? invocation.sourceId+ : 'generate',+ },} as const,]),...resolvedRoute.validationReasons.map((reason) => ({diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsxindex 056ac51e45..8319c5f4a7 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx@@ -745,10 +745,11 @@ export const FloatingWidgetWindow = ({flexShrink={0}gap="1.5"// Tighter than a docked panel's header: a window's chrome should take as little of it as it can. The- // end padding keeps the Dock button clear of the top-right resize corner, which reaches 12px inside.+ // side padding on each end equals the space above and below what sits there: the 16px title icon at the+ // start, the 24px controls at the end.h={8}- pe="3"- ps="3"+ pe="1"+ ps="2"tabIndex={isMaximized ? undefined : 0}// `preventDefault` on pointerdown does not stop touch panning: without// this the browser claims the gesture and cancels the drag.@@ -800,7 +801,8 @@ export const FloatingWidgetWindow = ({</HStack></Suspense>) : null}- <HStack flexShrink={0} gap="1" data-floating-controls="">+ {/* Above the resize handles: the top-right corner's handle reaches 12px inside, over the last button. */}+ <HStack flexShrink={0} gap="1" data-floating-controls="" position="relative" zIndex="2">{isEnabled && widget ? <Separator h="4" mx="0.5" orientation="vertical" /> : null}<Tooltip content={isShaded ? t('widgets.floating.unshade') : t('widgets.floating.shade')}><IconButtondiff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelBodySlot.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelBodySlot.browser.test.tsxindex a1d9ef566a..34caac428d 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelBodySlot.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelBodySlot.browser.test.tsx@@ -69,4 +69,42 @@ describe('PanelBodySlot', () => {// The wrap actually engaged: eight buttons cannot fit one 300px line.expect(strip.getBoundingClientRect().height).toBeGreaterThan(row.getBoundingClientRect().height * 1.5);});++ it('grows and shrinks its scroll content with a flowing view, so the scrollbar follows sections opening', async () => {+ host = document.createElement('div');+ host.style.cssText = `display:flex;flex-direction:column;height:400px;width:${PANEL_WIDTH}px;`;+ document.body.append(host);+ root = createRoot(host);+ const renderSections = (heightsPx: number[]) =>+ interact(() => {+ root?.render(+ <ChakraProvider value={system}>+ <PanelBodySlot>+ <div>+ {heightsPx.map((heightPx, index) => (+ <div key={index} style={{ height: heightPx }} />+ ))}+ </div>+ </PanelBodySlot>+ </ChakraProvider>+ );+ });+ const viewport = () => host!.querySelector<HTMLElement>('[data-scope="scroll-area"][data-part="viewport"]')!;+ const content = () => host!.querySelector<HTMLElement>('[data-scope="scroll-area"][data-part="content"]')!;+ const scrollbar = () => host!.querySelector<HTMLElement>('[data-part="scrollbar"][data-orientation="vertical"]')!;+ await renderSections([100, 100]);+ expect(content().getBoundingClientRect().height).toBeCloseTo(400, 0);+ expect(scrollbar().hasAttribute('data-overflow-y')).toBe(false);++ // A section opens past the fold: the content element itself grows, which is what the thumb is measured from.+ await renderSections([100, 100, 700]);+ expect(content().getBoundingClientRect().height).toBeCloseTo(900, 0);+ expect(viewport().scrollHeight).toBeGreaterThan(viewport().clientHeight);+ await expect.poll(() => scrollbar().hasAttribute('data-overflow-y')).toBe(true);++ // It folds again: content and scrollbar return to the viewport's height and nothing to scroll.+ await renderSections([100, 100]);+ expect(content().getBoundingClientRect().height).toBeCloseTo(400, 0);+ await expect.poll(() => scrollbar().hasAttribute('data-overflow-y')).toBe(false);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/README.md b/invokeai/frontend/webv2/src/workbench/widget-frame/README.mdindex 57f49f9afe..e80a56401e 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/README.md+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/README.md@@ -45,7 +45,7 @@ Workbench focus is transient, never persisted. `WorkbenchFocusProvider` (`workbe## Contextual shortcut guidance-Shortcuts is a bottom-only popover widget. Built-in layouts put it on right immediately before Notifications; saved and custom layouts keep their placements and can enable it through Bottom Widgets. Whole chip opens its guide; normal widget controls own reordering, alignment, visibility and dismissal. Its `compactSizing` metadata asks status-bar host for remaining capacity: host observes its strip, two clusters and spacer; guide measures only its own keycaps. Up to four whole hints fit without increasing status bar height; a keyboard icon keeps access when no hint or label fits. Status-bar chips take their accessible name from compact content, never a host `aria-label`, so speech-input users can say the status they see (WCAG 2.5.3 Label in Name). Once its view loads (until then its busy fallback reads "Loading <label>"), every chip's name starts with its widget's label: a compact view whose status text does not say it ("Queue idle", a workflow's name) passes `StatusWidgetChip` a `hiddenLabel` or renders the label visually hidden. The guide's name is only "Shortcuts": its preview hints are `aria-hidden`, so a voice command for a hint cannot land on the chip, and the popover lists them. The `workbench-status-bar-names` accessibility journey enables every bottom widget and checks each chip's name. If all relevant bindings are unassigned, popover explains that state and provides keyboard shortcut settings.+Shortcuts is a bottom-only popover widget. Built-in layouts put it on right immediately before Notifications; saved and custom layouts keep their placements and can enable it from the Status bar widgets menu. Whole chip opens its guide; normal widget controls own reordering, alignment, visibility and dismissal. Its `compactSizing` metadata asks status-bar host for remaining capacity: host observes its strip, two clusters and spacer; guide measures only its own keycaps. Up to four whole hints fit without increasing status bar height; a keyboard icon keeps access when no hint or label fits. Status-bar chips take their accessible name from compact content, never a host `aria-label`, so speech-input users can say the status they see (WCAG 2.5.3 Label in Name). Once its view loads (until then its busy fallback reads "Loading <label>"), every chip's name starts with its widget's label: a compact view whose status text does not say it ("Queue idle", a workflow's name) passes `StatusWidgetChip` a `hiddenLabel` or renders the label visually hidden. The guide's name is only "Shortcuts": its preview hints are `aria-hidden`, so a voice command for a hint cannot land on the chip, and the popover lists them. The `workbench-status-bar-names` accessibility journey enables every bottom widget and checks each chip's name. If all relevant bindings are unassigned, popover explains that state and provides keyboard shortcut settings.Workbench focus lifecycle also owns transient hint-source registry and last editing element. A keyed Canvas registration mounts one stable source for its project/instance engine lease. Generation and staged results never change Canvas hints: nothing locks the canvas. Narrow tool/session subscriptions cache scalar hint inputs; guide never acquires an engine lease or imports property forms. Sources are fenced by project and instance and released with their owner. Project/account changes clear editing origin. Widget's `preserveWorkbenchFocus` metadata keeps its compact chip and portal from replacing that origin; closing returns focus there. Healthy preserve-focus guides are suppressed under unrelated modals and do not reopen when the modal closes; their hidden sortable is disabled and their measured chip DOM is released. A failed item keeps its recovery mounted through its own confirmation, while modal presence still suspends application shortcuts. Guide activation and Escape do not reach Canvas session handlers; configured global chords keep normal runtime handling.@@ -61,6 +61,13 @@ Command hints resolve against runtime catalog and mounted extension contribution- **Title bar.** Double-click maximizes or restores, and expands a collapsed window; Restore returns to windowed geometry, which maximizing never touches. Collapse and Expand are explicit buttons; Close removes the window as a marker's Remove does (an undoable layout step), sending focus to the center when it gets its view back, else to the panel the window's rail shows, else the center. Label truncates first, down to its icon; contributed widget actions then give way in a strip that scrolls, without a scrollbar, by focus, sideways scroll, or touch, so a focused action is always in view with its ring; window's own controls never shrink.- **Shaded bodies stay mounted.** Shaded body is hidden with React `Activity`, so its local state survives and no second copy mounts. Drafts are flushed before shading, docking, and removing, because hiding or unmounting an editor stops its flusher.+## Docked bodies++A left, right or bottom panel puts its widget's body in one vertical `Scrollable` (`PanelBodySlot` in `WidgetRenderer.tsx`); the manifest's `chrome.body` says how the view meets it.++- **`flow` (default).** The scroll content grows with the view and is never shrunk below it, because the scroll area sizes its thumb from that element: a squeezed one leaves the scrollbar stale as sections open and fold. A view's `h="full"` means at least the body's height, never a bound.+- **`fill`.** For views that bound their own regions: inner lists and trees that scroll themselves, resizable panes, filters or footers that stay in view. The frame wraps the view in a size-contained column, so the view's rows never count toward the body's height and the view gets exactly the body's height. Past the view's own minimum heights the overflow still spills into the body, which then scrolls instead of crushing them. Center and floating hosts give every view exactly their height, with no outer scroll, whatever the manifest says.+## Center chromeCenter view's header floats over its body as two islands (`workbench/shell/CenterArea.tsx`): view menu and widget label at start, toolbar widgets and header actions at end.diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsxindex 35c9eb8eba..8106531263 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx@@ -5,6 +5,7 @@ import type { WidgetPlacementInstanceMeta, WidgetRegionItem } from '@workbench/wimport { Box, Flex, Icon, type SystemStyleObject } from '@chakra-ui/react';import { verticalListSortingStrategy } from '@dnd-kit/sortable';+import { isEventFromOwnDom } from '@platform/react/isEventFromOwnDom';import { Row } from '@platform/ui/Row';import { Tooltip } from '@platform/ui/Tooltip';import { useHighlightedRegion } from '@workbench/focusRegions';@@ -77,6 +78,10 @@ export const WidgetBar = ({const instanceMenuTarget = instanceMenu?.projectId === projectId ? instanceMenu : null;const openEnableMenu = useCallback((event: MouseEvent) => {+ // The rail's menus and tooltips are portalled; a right-click in them is theirs.+ if (!isEventFromOwnDom(event)) {+ return;+ }event.preventDefault();setEnableMenuTarget({ x: event.clientX, y: event.clientY });}, []);@@ -99,6 +104,7 @@ export const WidgetBar = ({);const trigger = useMemo(() => ({ kind: 'rail', region }) as const, [region]);+ const regionWidgetsLabel = t(side === 'left' ? 'widgets.regionWidgets.left' : 'widgets.regionWidgets.right');const handleContextClose = useCallback(() => setEnableMenuTarget(null), []);const handleMenuToggle = useCallback((item: WidgetEnableMenuItem) => onToggle(item as WidgetBarItem), [onToggle]);const handleInstanceClose = useCallback(() => setInstanceMenu(null), []);@@ -115,9 +121,8 @@ export const WidgetBar = ({return (<Flex- aria-label={t('widgets.visibilityLabel', {- region: side === 'left' ? t('widgets.rail.create') : t('widgets.rail.inspect'),- })}+ // Named apart from the widget panel landmark beside it, whose widget this rail switches.+ aria-label={t(side === 'left' ? 'widgets.rail.left' : 'widgets.rail.right')}as="nav"bg="bg.subtle"borderColor={isEdgeOutlined ? 'transparent' : 'border.subtle'}@@ -144,11 +149,11 @@ export const WidgetBar = ({<WidgetEnableMenucontextTarget={enableMenuTarget}- groupLabel={region === 'left' ? t('widgets.rail.createWidgets') : t('widgets.rail.inspectWidgets')}+ groupLabel={regionWidgetsLabel}items={menuItems}positioning={positioning}trigger={trigger}- triggerLabel={region === 'left' ? t('widgets.rail.createWidgets') : t('widgets.rail.inspectWidgets')}+ triggerLabel={regionWidgetsLabel}onContextClose={handleContextClose}onToggle={handleMenuToggle}/>diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBarFloatingMarker.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBarFloatingMarker.browser.test.tsxindex 4bbe7e11f5..8107c46088 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBarFloatingMarker.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBarFloatingMarker.browser.test.tsx@@ -79,7 +79,7 @@ await i18n.use(initReactI18next).init({railMarker: '{{label}}, floating window',railMarkerHint: '{{label}} is floating — click to show the window',},- rail: { inspectWidgets: 'Inspect widgets' },+ regionWidgets: { right: 'Right panel widgets' },removeWidget: 'Remove {{label}}',},},@@ -228,7 +228,7 @@ describe('WidgetBar floating marker', () => {it('removes the window from the enable menu as a toggle, not as a marker removal', async () => {await renderBar();await act(async () => {- slot('Inspect widgets').click();+ slot('Right panel widgets').click();await Promise.resolve();});@@ -260,6 +260,27 @@ describe('WidgetBar floating marker', () => {expect(handlers.onRemoveFloating).not.toHaveBeenCalled();});+ it("leaves a right-click inside a slot's menu to that menu, and opens the widgets menu from the rail itself", async () => {+ const openWidgetsMenus = () =>+ [...document.body.querySelectorAll<HTMLElement>('[role="menu"][data-state="open"]')].filter((menu) =>+ menu.textContent?.includes('Right panel widgets')+ );+ await renderBar();+ await openMenu(slot('Queue'));++ // The slot's menu is portalled out of the rail, but React still bubbles its events through the rail.+ await openMenu(menuItem('remove-widget')!);+ expect(openWidgetsMenus()).toHaveLength(0);+ expect(menuItem('remove-widget')).not.toBeNull();++ await act(async () => {+ menuItem('remove-widget')?.click();+ await Promise.resolve();+ });+ await openMenu(host!.querySelector('nav')!);+ expect(openWidgetsMenus()).toHaveLength(1);+ });+it("closes a marker's menu when the project changes, so it cannot dock or remove the new project's window", async () => {await renderBar('project-a');await openMenu(marker());diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsxindex 66500e064e..f5851db552 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetEnableMenu.tsx@@ -43,7 +43,8 @@ interface WidgetEnableMenuProps {onToggle: (item: WidgetEnableMenuItem) => void;}-const TRIGGER_HOVER_PROPS = { bg: 'bg.muted' };+/** The neighbouring rail slots' and status-bar chips' pointed fill, kept while the menu is open. */+const TRIGGER_POINTED_PROPS = { bg: 'bg.hover', color: 'fg' };const MENU_ITEM_DISABLED_PROPS = { opacity: 0.4 };const getWidgetEnableMenuTriggerButton = (label: string, trigger: WidgetEnableMenuTrigger) => {@@ -60,17 +61,18 @@ const getWidgetEnableMenuTriggerButton = (label: string, trigger: WidgetEnableMereturn (<Flexalign="center"- // Center the fixed-size trigger within full-width rail drop targets; fill the status bar inside its border.+ // Center the fixed-size trigger within full-width rail drop targets; take the status-bar chips' inset height.alignSelf={isBottom ? 'stretch' : 'center'}aria-label={label}as="button"color="fg"h={isBottom ? undefined : '9'}justify="center"- rounded={isBottom ? 'sm' : 'md'}+ rounded={isBottom ? 'control' : 'md'}transition="background var(--wb-motion-duration-fast) ease, color var(--wb-motion-duration-fast) ease"w={isBottom ? '6' : '9'}- _hover={TRIGGER_HOVER_PROPS}+ _expanded={TRIGGER_POINTED_PROPS}+ _hover={TRIGGER_POINTED_PROPS}><Icon as={MoreHorizontalIcon} boxSize={isBottom ? '4' : '5'} /></Flex>@@ -186,7 +188,7 @@ const WidgetEnableMenuRow = ({{...intentPreloadProps}onClick={handleClick}>- <Icon as={CheckIcon} boxSize="3" opacity={item.isEnabled ? 1 : 0} />+ <Icon as={CheckIcon} boxSize="3" color="fg" opacity={item.isEnabled ? 1 : 0} /><WidgetIcon icon={item.icon} boxSize="3.5" /><Menu.ItemText>{item.label}</Menu.ItemText>{meta ? (diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsxindex e086f09165..f011933d6b 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.tsx@@ -1,6 +1,7 @@import type { WidgetRegion } from '@workbench/layoutContracts';import type {RegisteredWidget,+ WidgetBodySizing,WidgetImplementation,WidgetInstanceContract,WidgetInstanceId,@@ -445,7 +446,7 @@ const WidgetShellFrame = ({/></WidgetRecoveryBoundary>)}- <PanelBodySlot>{children}</PanelBodySlot>+ <PanelBodySlot body={widget.manifest.chrome?.body}>{children}</PanelBodySlot>{footer}</WidgetPanelFrame>);@@ -548,18 +549,31 @@ const HeaderSlot = memo(function HeaderSlot({);}, areSlotPropsEqual);-// Stretch fill-height views while allowing flowing content to scroll vertically. minmax(0,1fr) prevents long-// content from widening and clipping panels.+// minmax(0,1fr) prevents long content from widening and clipping panels.+// Never shrunk: the viewport is a flex column, and `minH: full` would let it squeeze the content to its own height.+// The scroll area sizes its thumb from this element, so a squeezed one leaves a stale or missing scrollbar.const panelBodyContentProps = {display: 'grid',+ flexShrink: 0,gridTemplateColumns: 'minmax(0, 1fr)',maxW: 'full',minH: 'full',} as const;-export const PanelBodySlot = ({ children }: { children: React.ReactNode }) => (+// Size containment drops the view's own height from the grid row, which then stretches to the body's height alone:+// lists and panes inside stay bounded instead of pushing the content as tall as all their rows. Overflow past the+// view's own minimums still spills, so a very short dock scrolls rather than crushing them.+const FILL_BODY_CSS = { contain: 'size' } as const;++export const PanelBodySlot = ({ body = 'flow', children }: { body?: WidgetBodySizing; children: React.ReactNode }) => (<Scrollable contentProps={panelBodyContentProps} flex="1" minH="0" minW="0" overflowX="hidden">- {children}+ {body === 'fill' ? (+ <Flex css={FILL_BODY_CSS} direction="column">+ {children}+ </Flex>+ ) : (+ children+ )}</Scrollable>);diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/compactWidgetCapacity.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/compactWidgetCapacity.tsxindex 0aa5f6b92a..e903cee989 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/compactWidgetCapacity.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/compactWidgetCapacity.tsx@@ -31,6 +31,9 @@ export const createCompactWidgetCapacity = () => {};return {...store,+ /** The width the chip adds around `content` (padding, borders, sibling chrome); none outside a bound chip. */+ measureInset: (content: Element) =>+ chip ? chip.getBoundingClientRect().width - content.getBoundingClientRect().width : 0,bindSpacer: (element: HTMLDivElement | null) => {spacer = element;if (!element) {diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.tsindex ae283d87f6..5263cfdddc 100644--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts@@ -249,6 +249,12 @@ export interface WidgetWorkbenchApi {closeWidgetInstance: (instanceId: WidgetInstanceId) => WidgetWorkbenchApiResult;}+/**+ * How a docked widget's body is sized. `flow` (default): the body grows with the view and scrolls as a whole. `fill`:+ * the view gets exactly the body's height, for views that scroll or resize their own regions (lists, trees, panes).+ */+export type WidgetBodySizing = 'fill' | 'flow';+export interface WidgetManifest {/** Widget runtime API contract version. Defaults to 1 during registry normalization. */apiVersion?: 1;@@ -272,6 +278,7 @@ export interface WidgetManifest {requiresAdmin?: boolean;chrome?: {header?: 'hidden' | 'visible';+ body?: WidgetBodySizing;};/*** Literal dynamic loader for all render slots. The registry owns caching,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.browser.test.tsxindex 7793112cbb..64b626508f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.browser.test.tsx@@ -89,28 +89,98 @@ const refusal = (describe('CanvasEditRefusalNotices', () => {it.each([['layer-hidden', '“Sky” is hidden', 'Show the layer to edit it.'],+ ['layer-display-hidden', '“Sky” is hidden on the canvas', 'Show it on the canvas to edit it.'],+ [+ 'erase-unsupported',+ '“Sky” can’t be erased',+ 'The eraser works on paint layers, images, control layers and masks.',+ ],+ [+ 'gradient-unsupported',+ 'Can’t add a gradient to “Sky”',+ 'A gradient is a raster layer of its own. Select a raster layer, or nothing, to add one.',+ ],['layer-locked', '“Sky” is locked', 'Unlock the layer to edit it.'],['layer-alpha-locked', '“Sky” has its transparency locked', 'Unlock its transparency to remove pixels from it.'],['layer-loading', '“Sky” is still loading', 'Its pixels are on their way. Try again in a moment.'],+ [+ 'layer-unpaintable',+ '“Sky” has no pixels to edit',+ 'Its shape is empty, so there is nothing to paint on or erase.',+ ],+ [+ 'selection-erase-unsupported',+ 'Can’t remove the selection from “Sky”',+ 'Erase, Delete and Cut remove pixels from paint layers, images, control layers and masks.',+ ],+ ['transform-session', '“Sky” is being transformed', 'Apply or cancel the transform first.'],] as const)('explains a %s refusal with no offer', async (status, title, message) => {const { emit } = await mount([layerContract('sky', 'raster', { name: 'Sky' })], 'sky');await emit(refusal(status, 'sky', 'Sky'));await expect.poll(toastTexts).toEqual([{ actions: [], message, title }]);});- it('explains a shape cutout with nothing to cut from, once however often it is pressed', async () => {+ it.each([+ ['inpaint_mask', '“Sky” is left out of generation', 'Use it in generation to edit it.'],+ ['control', '“Sky” is left out of generation', 'Use it in generation to edit it.'],+ ['raster', '“Sky” is hidden', 'Show the layer to edit it.'],+ ] as const)('words a %s out of generation for the control that brings it back', async (type, title, message) => {+ const { emit } = await mount([layerContract('sky', type, { isEnabled: false, name: 'Sky' })], 'sky');+ await emit(refusal('layer-hidden', 'sky', 'Sky'));+ await expect.poll(toastTexts).toEqual([{ actions: [], message, title }]);+ });++ it.each([+ ['cutout-no-target', 'Nothing to cut the shape out of', 'Select a paint layer or mask to cut the shape out of it.'],+ ['erase-no-target', 'Nothing to erase', 'Select a paint layer, image, control layer or mask to erase from it.'],+ [+ 'selection-erase-no-target',+ 'No layer to remove the selection from',+ 'Select a paint layer, image, control layer or mask, then try again.',+ ],+ ] as const)('explains a %s refusal once however often it is pressed', async (status, title, message) => {const { emit } = await mount([], null);- await emit({ status: 'cutout-no-target' });- await emit({ status: 'cutout-no-target' });- await expect.poll(toastTexts).toEqual([- {- actions: [],- message: 'Select a paint layer or mask to cut the shape out of it.',- title: 'Nothing to cut the shape out of',- },- ]);+ await emit({ status });+ await emit({ status });+ await expect.poll(toastTexts).toEqual([{ actions: [], message, title }]);});+ it.each([+ [+ 'layer-hidden',+ '“Sky” is hidden',+ 'Show the layer to paint on it, or paint on a new layer above it.',+ ['Paint on a new layer'],+ ],+ [+ 'layer-display-hidden',+ '“Sky” is hidden on the canvas',+ 'Show it on the canvas to paint on it, or paint on a new layer above it.',+ ['Paint on a new layer'],+ ],+ [+ 'layer-locked',+ '“Sky” is locked',+ 'Unlock the layer to paint on it, or paint on a new layer above it.',+ ['Paint on a new layer'],+ ],+ // A status a new layer would not escape keeps its own words and makes no offer.+ ['layer-loading', '“Sky” is still loading', 'Its pixels are on their way. Try again in a moment.', []],+ [+ 'layer-alpha-locked',+ '“Sky” has its transparency locked',+ 'Unlock its transparency to remove pixels from it.',+ [],+ ],+ ] as const)(+ 'words a %s refusal that could offer a new layer in its own terms',+ async (status, title, message, actions) => {+ const { emit } = await mount([layerContract('sky', 'raster', { name: 'Sky' })], 'sky');+ await emit(refusal(status, 'sky', 'Sky', true));+ await expect.poll(toastTexts).toEqual([{ actions: [...actions], message, title }]);+ }+ );+it('replaces a repeated refusal without an offer, one toast per layer and reason', async () => {const { emit } = await mount([layerContract('sky', 'raster', { name: 'Sky' }), layerContract('sea', 'raster', { name: 'Sea' })],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsxindex d0d54fd81e..63279edc02 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx@@ -1,21 +1,22 @@import type {CanvasDocumentContractV3,CanvasLayerEditRefusal,+ CanvasNoTargetRefusal,CanvasNodeContract,} from '@workbench/canvas-engine/api';import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';-import type { TFunction } from 'i18next';import { createItemId } from '@platform/browser/randomUuid';import { useMountEffect } from '@platform/react/useMountEffect';import { captureAccountScope } from '@platform/state/accountLifecycle';import { ACTION_TOAST_DURATION_MS, createActionToast, toaster } from '@platform/ui/toaster';-import { getDocumentIndex, isNodeHidden } from '@workbench/canvas-engine/api';+import { getDocumentIndex, isNodeHidden, isOverlayStack } from '@workbench/canvas-engine/api';import { nextLayerName } from '@workbench/canvasProjectMutations';import { useNotify } from '@workbench/useNotify';import {commitPreparedEdit,describeAdjustmentRefusal,+ describeLayerEditRefusal,reportPreparedCommit,reportStructuralCommit,type CanvasPreparedEngine,@@ -24,36 +25,19 @@ import {import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';import { useTranslation } from 'react-i18next';-const LAYER_REFUSAL_KEYS: Record<CanvasLayerEditRefusal['status'], { message: string; title: string }> = {- 'layer-alpha-locked': {- message: 'widgets.canvas.editRefusal.alphaLockedMessage',- title: 'widgets.canvas.editRefusal.alphaLocked',+const NO_TARGET_KEYS: Record<CanvasNoTargetRefusal['status'], { message: string; title: string }> = {+ 'cutout-no-target': {+ message: 'widgets.canvas.editRefusal.noCutoutTargetMessage',+ title: 'widgets.canvas.editRefusal.noCutoutTarget',},- 'layer-hidden': { message: 'widgets.canvas.editRefusal.hiddenMessage', title: 'widgets.canvas.editRefusal.hidden' },- 'layer-loading': {- message: 'widgets.canvas.editRefusal.loadingMessage',- title: 'widgets.canvas.editRefusal.loading',+ 'erase-no-target': {+ message: 'widgets.canvas.editRefusal.noEraseTargetMessage',+ title: 'widgets.canvas.editRefusal.noEraseTarget',+ },+ 'selection-erase-no-target': {+ message: 'widgets.canvas.editRefusal.noSelectionEraseTargetMessage',+ title: 'widgets.canvas.editRefusal.noSelectionEraseTarget',},- 'layer-locked': { message: 'widgets.canvas.editRefusal.lockedMessage', title: 'widgets.canvas.editRefusal.locked' },-};--/** The notice's title and message for a layer the active tool could not edit. */-export const describeLayerEditRefusal = (- refusal: CanvasLayerEditRefusal,- t: TFunction-): { message: string; title: string } => {- const keys = LAYER_REFUSAL_KEYS[refusal.status];- const name = refusal.layerName;- return {- message: refusal.canPaintNewLayer- ? t(- refusal.status === 'layer-hidden'- ? 'widgets.canvas.editRefusal.hiddenOfferMessage'- : 'widgets.canvas.editRefusal.lockedOfferMessage'- )- : t(keys.message),- title: t(keys.title, { name }),- };};/**@@ -98,12 +82,13 @@ const paintOnNewLayer = (/*** Explains edits the engine refused without a caller to report to: a stroke too large to undo, a press on a layer- * the tool cannot edit (hidden, locked, still loading), or a shape cutout with no paint layer or mask selected. A- * brush press on a locked or hidden image offers a new paint layer above it rather than making one unasked; that- * offer holds a closure, so it is a toast only, closed with this canvas or the account. Layer refusals are toasts- * only, one per layer and reason: a repeated press (every eraser press on a transparency-locked layer, say) replaces- * its toast instead of stacking another, and taking one offer closes the other offers. A cutout with nothing to cut- * from keeps a single toast the same way. Keyed by engine.+ * the tool cannot edit (hidden, hidden on the canvas, locked, still loading, one the eraser cannot erase, or a mask+ * the gradient cannot go on), or an erase or shape cutout with no layer selected. A brush press on a locked or hidden+ * image offers a new paint layer above it rather than making one unasked; that offer holds a closure, so it is a+ * toast only, closed with this canvas or the account. Layer refusals are toasts only, one per layer and reason: a+ * repeated press (every eraser press on a transparency-locked layer, say) replaces its toast instead of stacking+ * another, and taking one offer closes the other offers. An erase or cutout with nothing to act on keeps a single+ * toast the same way. Keyed by engine.*/export const CanvasEditRefusalNotices = ({engine,@@ -132,21 +117,28 @@ export const CanvasEditRefusalNotices = ({return;}const signal = AbortSignal.any([captureAccountScope().signal, mounted.signal]);- if (refusal.status === 'cutout-no-target') {+ if (!('layerId' in refusal)) {+ const keys = NO_TARGET_KEYS[refusal.status];createActionToast({actions: [],- description: t('widgets.canvas.editRefusal.noCutoutTargetMessage'),+ description: t(keys.message),id: `${scope}:${refusal.status}`,signal,- title: t('widgets.canvas.editRefusal.noCutoutTarget'),+ title: t(keys.title),type: 'info',});return;}- const { message, title } = describeLayerEditRefusal(refusal, t);+ const document = engine.document.model()?.document;+ const stack = document ? getDocumentIndex(document).byId.get(refusal.layerId)?.stack : undefined;+ const { message, offersNewLayer, title } = describeLayerEditRefusal(+ refusal,+ t,+ stack !== undefined && isOverlayStack(stack)+ );// One toast per layer and reason: pressing again on the same layer replaces it rather than stacking another.const id = `${scope}:${refusal.status}:${refusal.layerId}`;- if (!refusal.canPaintNewLayer) {+ if (!offersNewLayer) {createActionToast({ actions: [], description: message, id, signal, title, type: 'info' });return;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFrameSizeReadout.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFrameSizeReadout.browser.test.tsxnew file mode 100644index 0000000000..6abec50a84--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFrameSizeReadout.browser.test.tsx@@ -0,0 +1,264 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { Rect } from '@workbench/canvas-engine/api';+import type { ComponentProps } from 'react';++import { Box, ChakraProvider } from '@chakra-ui/react';+import {+ resetArchitectureCapabilities,+ setArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities';+import { architectureCapabilitiesFixture } from '@features/generation/core/architectureCapabilities.testing';+import { createExternalStoreCore } from '@platform/state/externalStoreCore';+import { useExternalStoreSelector } from '@platform/state/selectors';+import { applyThemeToRoot } from '@theme/applyTheme';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++interface HarnessProject {+ canvas: { document: { bbox: Rect } };+ values: Record<string, Record<string, unknown>>;+}++// The active project as a store, so a committed frame or setting re-renders its readers as the Workbench would.+const harness = vi.hoisted(() => ({+ project: null as unknown as {+ getSnapshot: () => HarnessProject;+ setSnapshot: (next: HarnessProject) => void;+ subscribe: (listener: () => void) => () => void;+ },+}));++vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectSelector: <Selected,>(+ selector: (project: HarnessProject) => Selected,+ isEqual?: (a: Selected, b: Selected) => boolean+ ) => useExternalStoreSelector(harness.project.subscribe, harness.project.getSnapshot, selector, isEqual),+}));+vi.mock('@workbench/widgetState', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getProjectWidgetValues: (project: HarnessProject, widgetId: string) => project.values[widgetId] ?? {},+}));++import { CanvasFrameSizeReadout } from './CanvasFrameSizeReadout';++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ fallbackLng: 'en',+ initAsync: false,+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const SD1_MODEL = { base: 'sd-1', key: 'sd1', name: 'SD 1.5', type: 'main' } as const;+const WAN_TI2V_MODEL = { base: 'wan', key: 'wan-ti2v', name: 'Wan 2.2 TI2V-5B', type: 'main', variant: 'ti2v_5b' };++type ReadoutEngine = ComponentProps<typeof CanvasFrameSizeReadout>['engine'];++/** The engine's interaction store as the readout reads it: only the Frame tool's drag preview. */+const createFakeEngine = () => {+ let preview: Rect | null = null;+ const listeners = new Set<() => void>();+ const engine = {+ interaction: {+ get: (key: string) => (key === 'bboxPreview' ? preview : undefined),+ subscribe: (key: string, listener: () => void) => {+ if (key !== 'bboxPreview') {+ return () => undefined;+ }+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ };+ return {+ engine: engine as unknown as ReadoutEngine,+ setPreview: (next: Rect | null) => {+ preview = next;+ listeners.forEach((listener) => listener());+ },+ };+};++const createProject = ({+ canvas = {},+ frame,+ model = SD1_MODEL,+}: {+ canvas?: Record<string, unknown>;+ frame: { height: number; width: number };+ model?: Record<string, unknown> | null;+}): HarnessProject => ({+ canvas: { document: { bbox: { ...frame, x: 0, y: 0 } } },+ values: { canvas, generate: { ...frame, model, pidMode: 'off' } },+});++let host: HTMLDivElement | null = null;+let root: Root | null = null;+let beneathClicks = 0;++/** The readout over a canvas-sized stand-in for the surface, which counts the clicks that reach it. */+const mount = async (project: HarnessProject, { height = 480, width = 720 } = {}) => {+ harness.project = createExternalStoreCore(project);+ const fake = createFakeEngine();+ applyThemeToRoot('classic');+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ beneathClicks = 0;+ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <Box bg="bg.inset" h={`${height}px`} overflow="hidden" position="relative" w={`${width}px`}>+ <button+ aria-label="Canvas surface"+ style={{ inset: 0, position: 'absolute' }}+ type="button"+ onClick={() => {+ beneathClicks += 1;+ }}+ />+ <CanvasFrameSizeReadout engine={fake.engine} />+ </Box>+ </ChakraProvider>+ </I18nextProvider>+ );+ });+ return fake;+};++const readout = () => page.getByRole('group', { name: 'Frame and render size' });+/** Each term and its value, as assistive tech reads the list. */+const rows = () =>+ [...readout().element().querySelectorAll('dt')].map((term) => [+ term.textContent,+ term.nextElementSibling?.textContent,+ ]);++beforeEach(() => {+ setArchitectureCapabilities(architectureCapabilitiesFixture);+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ resetArchitectureCapabilities();+});++describe('CanvasFrameSizeReadout', () => {+ it('shows only the frame size when the frame renders at its own size', async () => {+ // 1024×768 is on SD 1.5's 8px grid and already past its 512×512 optimum, so Optimal for model leaves it alone.+ await mount(createProject({ frame: { height: 768, width: 1024 } }));++ await expect.element(readout()).toBeVisible();+ expect(rows()).toEqual([['Frame', '1024×768']]);+ });++ it('shows the render size each Render at mode generates at', async () => {+ // Optimal for model: a 1:2 frame grows toward SD 1.5's 512×512 area on its 8px grid. 720 tall needs 360 wide+ // (259,200 px, short of 262,144); 728 tall needs 364, which snaps to 368 (267,904 px).+ await mount(createProject({ canvas: { scaleMethod: 'auto' }, frame: { height: 512, width: 256 } }));+ expect(rows()).toEqual([+ ['Frame', '256×512'],+ ['Render', '368×728'],+ ]);++ // Custom renders at the chosen size.+ await act(() => {+ harness.project.setSnapshot(+ createProject({+ canvas: { scaleMethod: 'manual', scaledHeight: 1152, scaledWidth: 1536 },+ frame: { height: 512, width: 256 },+ })+ );+ });+ expect(rows()).toEqual([+ ['Frame', '256×512'],+ ['Render', '1536×1152'],+ ]);++ // Frame size renders at the frame itself, so nothing differs.+ await act(() => {+ harness.project.setSnapshot(+ createProject({ canvas: { scaleMethod: 'none' }, frame: { height: 512, width: 256 } })+ );+ });+ expect(rows()).toEqual([['Frame', '256×512']]);+ });++ it('shows the size a frame off the model grid renders at', async () => {+ // Wan 2.2 TI2V-5B generates on a 32px grid: 720 rounds to 736 (22.5 × 32 rounds up to 23 × 32).+ await mount(+ createProject({ canvas: { scaleMethod: 'none' }, frame: { height: 720, width: 1280 }, model: WAN_TI2V_MODEL })+ );++ expect(rows()).toEqual([+ ['Frame', '1280×720'],+ ['Render', '1280×736'],+ ]);+ });++ it('follows a committed frame change and a Frame tool drag before it commits', async () => {+ const fake = await mount(createProject({ frame: { height: 768, width: 1024 } }));++ await act(() => {+ harness.project.setSnapshot(createProject({ frame: { height: 640, width: 896 } }));+ });+ expect(rows()).toEqual([['Frame', '896×640']]);++ // A free (Alt) drag reshapes the frame off whole pixels; the drag commits it rounded, and renders it on the grid.+ await act(() => fake.setPreview({ height: 480.6, width: 640.4, x: 10, y: 10 }));+ expect(rows()).toEqual([+ ['Frame', '640×481'],+ ['Render', '640×480'],+ ]);++ // The drag ended without a commit: the committed frame shows again.+ await act(() => fake.setPreview(null));+ expect(rows()).toEqual([['Frame', '896×640']]);+ });++ it('shows the frame alone until a model is selected', async () => {+ await mount(createProject({ canvas: { scaleMethod: 'auto' }, frame: { height: 128, width: 128 }, model: null }));++ expect(rows()).toEqual([['Frame', '128×128']]);+ });++ it('lets a click at its position through to the canvas beneath', async () => {+ await mount(createProject({ canvas: { scaleMethod: 'auto' }, frame: { height: 384, width: 384 } }));+ const box = readout().element().getBoundingClientRect();+ const surface = page.getByRole('button', { name: 'Canvas surface' });+ const surfaceBox = surface.element().getBoundingClientRect();++ // A real pointer click at the readout's centre; Playwright refuses it if the readout would intercept it.+ await userEvent.click(surface, {+ position: { x: box.left + box.width / 2 - surfaceBox.left, y: box.top + box.height / 2 - surfaceBox.top },+ });+ expect(beneathClicks).toBe(1);+ });++ it('sits in the top-right corner and steps aside when the canvas is too small', async () => {+ await mount(createProject({ frame: { height: 768, width: 1024 } }));+ const box = readout().element().getBoundingClientRect();+ const canvas = host!.firstElementChild!.getBoundingClientRect();+ // 8px (spacing 2) in from the top and right edges outside the center region's chrome.+ expect(Math.round(canvas.right - box.right)).toBe(8);+ expect(Math.round(box.top - canvas.top)).toBe(8);+ await act(() => root?.unmount());+ host?.remove();++ await mount(createProject({ frame: { height: 768, width: 1024 } }), { height: 480, width: 480 });+ // Hidden, so assistive tech skips it too.+ await expect.element(readout()).not.toBeInTheDocument();+ expect(getComputedStyle(host!.querySelector('[role="group"]')!).display).toBe('none');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFrameSizeReadout.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFrameSizeReadout.tsxnew file mode 100644index 0000000000..ee3cf0f74c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasFrameSizeReadout.tsx@@ -0,0 +1,147 @@+/**+ * A glanceable readout of the generation frame's size and, when it differs, the size the frame renders at. It sits in+ * the canvas's top-right corner, under the center chrome, follows a Frame tool drag before it commits, and never takes+ * the pointer. The render size comes from the policy the canvas graph compiler applies, so the two cannot disagree.+ */++import type { CanvasScalingSettings, PidMode } from '@features/generation/contracts';+import type { Project } from '@workbench/projectContracts';++import { Box } from '@chakra-ui/react';+import { resolveCanvasProcessingSize } from '@features/generation/canvasProcessingSize';+import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';+import { isGenerateModelConfig } from '@features/generation/settings';+import { useExternalStoreSelector } from '@platform/state/selectors';+import { roundBbox, type CanvasCoreStoreCapability } from '@workbench/canvas-engine/api';+import { readCanvasScaling } from '@workbench/widgets/canvas/invoke/canvasScaling';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useCanvasBboxPreview } from './engineStoreHooks';++interface Size {+ height: number;+ width: number;+}++const sizeEqual = (a: Size | null, b: Size | null): boolean =>+ a === b || (!!a && !!b && a.width === b.width && a.height === b.height);++const selectCommittedFrame = (project: Project): Size => {+ const { height, width } = project.canvas.document.bbox;+ return { height, width };+};++/** The inputs `compileCanvasGraph` resolves its processing size from, read from the stored settings as it reads them. */+const selectRenderInputs = (project: Project) => {+ const generate = getProjectWidgetValues(project, 'generate') as { model?: unknown; pidMode?: PidMode };+ return {+ model: isGenerateModelConfig(generate.model) ? generate.model : null,+ pidMode: generate.pidMode ?? 'off',+ scaling: readCanvasScaling(getProjectWidgetValues(project, 'canvas')),+ };+};++type RenderInputs = ReturnType<typeof selectRenderInputs>;++const scalingEqual = (a: CanvasScalingSettings, b: CanvasScalingSettings): boolean =>+ a.method === b.method && a.width === b.width && a.height === b.height;++const renderInputsEqual = (a: RenderInputs, b: RenderInputs): boolean =>+ a.model === b.model && a.pidMode === b.pidMode && scalingEqual(a.scaling, b.scaling);++// Below the center view's header row, as the tool strip sits.+const READOUT_TOP = 'var(--wb-center-chrome-inset, var(--chakra-spacing-2))';++/**+ * The layer spans the canvas so the readout can query its size: on a canvas too narrow it would crowd the top-center+ * chips (the control layer view switch), and on one too short, the tool strip's row, so it steps aside. It stacks under+ * the drop zones and the tool strip (z-index 2).+ */+const LAYER_CSS = { containerType: 'size' } as const;+const READOUT_CSS = {+ '@container (width < 34rem)': { display: 'none' },+ '@container (height < 12rem)': { display: 'none' },+} as const;+// A definition list's own margins would offset the grid.+const LIST_CSS = { '& dd': { margin: 0 } } as const;++export const CanvasFrameSizeReadout = ({ engine }: { engine: CanvasCoreStoreCapability }) => {+ const { t } = useTranslation();+ const preview = useCanvasBboxPreview(engine);+ const committed = useActiveProjectSelector(selectCommittedFrame, sizeEqual);+ const inputs = useActiveProjectSelector(selectRenderInputs, renderInputsEqual);+ // A drag shows the frame it would commit, which rounds to whole pixels.+ const frame = preview ? roundBbox(preview) : committed;+ const frameWidth = frame.width;+ const frameHeight = frame.height;+ // Read policy inside the capability selector so the model's grid replaces the fallback grid when it arrives.+ const render = useExternalStoreSelector(+ subscribeArchitectureCapabilities,+ getArchitectureCapabilitiesSnapshot,+ useCallback(+ () =>+ inputs.model+ ? resolveCanvasProcessingSize(+ inputs.model,+ inputs.pidMode,+ { height: frameHeight, width: frameWidth },+ inputs.scaling+ )+ : null,+ [frameHeight, frameWidth, inputs]+ ),+ sizeEqual+ );+ const isResized = !!render && (render.width !== frameWidth || render.height !== frameHeight);++ return (+ <Box css={LAYER_CSS} inset="0" pointerEvents="none" position="absolute" zIndex="1">+ <Box+ aria-label={t('widgets.canvas.frameReadout.label')}+ bg="bg.subtle/90"+ borderColor="border.subtle"+ borderWidth="1px"+ css={READOUT_CSS}+ position="absolute"+ right="2"+ role="group"+ rounded="md"+ shadow="sm"+ top={READOUT_TOP}+ >+ <Box+ as="dl"+ columnGap="2"+ css={LIST_CSS}+ display="grid"+ fontSize="xs"+ gridTemplateColumns="auto auto"+ lineHeight="1.4"+ px="2"+ py="1"+ rowGap="0.5"+ >+ <Box as="dt" color="fg.muted">+ {t('widgets.canvas.frameReadout.frame')}+ </Box>+ <Box as="dd" fontVariantNumeric="tabular-nums" textAlign="end">+ {t('widgets.canvas.frameReadout.size', { height: frameHeight, width: frameWidth })}+ </Box>+ {isResized ? (+ <>+ <Box as="dt" color="fg.muted">+ {t('widgets.canvas.frameReadout.render')}+ </Box>+ <Box as="dd" fontVariantNumeric="tabular-nums" textAlign="end">+ {t('widgets.canvas.frameReadout.size', { height: render.height, width: render.width })}+ </Box>+ </>+ ) : null}+ </Box>+ </Box>+ </Box>+ );+};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.tsxindex 570a0ad4f6..1cc47205bf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsx@@ -749,18 +749,86 @@ describe('CanvasHeaderActions use frame as', () => {});describe('CanvasHeaderActions undo and redo', () => {+ const historyButton = (name: string) => page.getByRole('button', { exact: true, name });+ /** One undoable step: the frame fitted to a layer it does not already match. */+ const fitFrame = async () => {+ await frameTrigger().click();+ await menuItem(/^Fit frame to layers/).click();+ await expect.element(historyButton('Undo: Fit generation frame')).not.toHaveAttribute('aria-disabled');+ };+it('name the step they would undo or redo, and plain Undo and Redo without one', async () => {await renderActions({ canvasValues: { snapToGrid: false }, layers: [sizedLayer(128, 96)] });- await expect.element(page.getByRole('button', { exact: true, name: 'Undo' })).toBeDisabled();- await expect.element(page.getByRole('button', { exact: true, name: 'Redo' })).toBeDisabled();+ await expect.element(historyButton('Undo')).toHaveAttribute('aria-disabled', 'true');+ await expect.element(historyButton('Redo')).toHaveAttribute('aria-disabled', 'true');- await frameTrigger().click();- await menuItem(/^Fit frame to layers/).click();+ await fitFrame();+ await historyButton('Undo: Fit generation frame').click();+ await expect.element(historyButton('Redo: Fit generation frame')).not.toHaveAttribute('aria-disabled');+ await expect.element(historyButton('Undo')).toHaveAttribute('aria-disabled', 'true');+ });++ it('show their bound keys after the step in the tooltip', async () => {+ await renderActions();+ const keys = (step: string) =>+ [...page.getByRole('tooltip').filter({ hasText: step }).element().querySelectorAll('kbd')].map(+ (key) => key.textContent+ );++ await userEvent.hover(historyButton('Undo'));+ await expect.element(page.getByRole('tooltip').filter({ hasText: 'Undo' })).toBeVisible();+ expect(keys('Undo')).toHaveLength(2);+ expect(keys('Undo').at(-1)).toBe('z');++ await userEvent.hover(historyButton('Redo'));+ await expect.element(page.getByRole('tooltip').filter({ hasText: 'Redo' })).toBeVisible();+ expect(keys('Redo')).toHaveLength(3);+ expect(keys('Redo').at(-1)).toBe('z');+ });- const undo = page.getByRole('button', { exact: true, name: 'Undo: Fit generation frame' });- await expect.element(undo).toBeEnabled();- await undo.click();- await expect.element(page.getByRole('button', { exact: true, name: 'Redo: Fit generation frame' })).toBeEnabled();- await expect.element(page.getByRole('button', { exact: true, name: 'Undo' })).toBeDisabled();+ it('keep keyboard focus on Undo when it steps back over the last edit, and step no further', async () => {+ await renderActions({ canvasValues: { snapToGrid: false }, layers: [sizedLayer(128, 96)] });+ await fitFrame();+ const undo = historyButton('Undo: Fit generation frame').element() as HTMLButtonElement;++ undo.focus();+ await userEvent.keyboard('{Enter}');++ // The history is now empty: the button says so but keeps focus, so the keyboard user is not dropped to the page.+ await expect.element(historyButton('Undo')).toHaveAttribute('aria-disabled', 'true');+ expect(document.activeElement).toBe(undo);+ await userEvent.keyboard('{Enter}');+ await expect.element(historyButton('Redo: Fit generation frame')).toBeInTheDocument();+ expect(harness.engine!.stores.canUndo.get()).toBe(false);+ });++ it('say why an existing step cannot run while an operation holds the document, and do not run it', async () => {+ const { rerender } = await renderActions({ canvasValues: { snapToGrid: false }, layers: [sizedLayer(128, 96)] });+ await fitFrame();+ harness.editingLocked = true;+ await rerender();++ const undo = historyButton('Undo: Fit generation frame');+ await expect.element(undo).toHaveAttribute('aria-disabled', 'true');+ await expect.element(undo).toHaveAccessibleDescription('Finish or cancel the current canvas operation first.');+ // The tooltip carries the step, its keys and the reason, as valid markup: no layout inside a paragraph. Pointer+ // tooling refuses aria-disabled targets; keyboard focus opens it (a key press first makes the focus visible).+ await userEvent.keyboard('{Tab}');+ await act(() => (undo.element() as HTMLElement).focus());+ const tooltip = () => document.querySelector('[role="tooltip"]');+ await vi.waitFor(() =>+ expect(tooltip()?.textContent).toMatch(+ /^Undo: Fit generation frame.*Finish or cancel the current canvas operation/+ )+ );+ expect([...tooltip()!.querySelectorAll('kbd')].at(-1)?.textContent).toBe('z');+ expect(tooltip()!.querySelector('p div, p p')).toBeNull();++ // A click still reaches the element and must do nothing.+ await act(() => (undo.element() as HTMLButtonElement).click());+ expect(harness.engine!.stores.canUndo.get()).toBe(true);+ // Nothing to redo has nothing to explain.+ await expect.element(historyButton('Redo')).toHaveAttribute('aria-disabled', 'true');+ await expect.element(historyButton('Redo')).not.toHaveAccessibleDescription();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsxindex 7126bd3336..b88a3f1aa5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx@@ -5,11 +5,12 @@ import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { Project } from '@workbench/projectContracts';import type { WidgetViewProps } from '@workbench/widgetContracts';-import { Box, Checkbox, HStack, Menu, Portal, Spinner, Stack, Text } from '@chakra-ui/react';+import { Checkbox, HStack, Menu, Portal, Spinner, Stack, Text } from '@chakra-ui/react';import { useModifierHeld } from '@platform/react/useModifierHeld';import { Button, IconButton } from '@platform/ui/Button';import { ConfirmDialog } from '@platform/ui/ConfirmDialog';import { MenuActionItem, MenuContent, MenuHeadingGroup, type MenuActionItemProps } from '@platform/ui/Menu';+import { HeaderActionDivider, HeaderHistoryButton } from '@platform/ui/PanelHeader';import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';import { getBaseRasterContentBounds, getDocumentLeaves } from '@workbench/canvas-engine/api';import { getCanvasEngine, isBlankCanvasDocument } from '@workbench/canvas-operations/api';@@ -125,6 +126,8 @@ const CanvasHeaderActionsInner = ({? t('widgets.canvas.controls.redoStep', { label: redoLabel }): t('widgets.canvas.controls.redo');const editingLocked = useCanvasDocumentEditingLocked(engine);+ const undoShortcut = useMemo(() => <CommandKeycaps commandId="canvas.undo" />, []);+ const redoShortcut = useMemo(() => <CommandKeycaps commandId="canvas.redo" />, []);const { describeDestination, isSaving, save: saveToGallery } = useCanvasGallerySave(engine);const { createFromBbox, isCreating } = useCreateFromBbox(engine);const saveMenuIds = useTooltipTriggerIds();@@ -356,35 +359,27 @@ const CanvasHeaderActionsInner = ({</Portal></Menu.Root>- <HeaderDivider />-- <Tooltip content={undoText}>- <IconButton- aria-label={undoText}- color="fg.muted"- disabled={editingLocked || !canUndo}- size="sm"- variant="ghost"- onClick={() => engine.history.undo()}- >- <Undo2Icon />- </IconButton>- </Tooltip>-- <Tooltip content={redoText}>- <IconButton- aria-label={redoText}- color="fg.muted"- disabled={editingLocked || !canRedo}- size="sm"- variant="ghost"- onClick={() => engine.history.redo()}- >- <Redo2Icon />- </IconButton>- </Tooltip>-- <HeaderDivider />+ <HeaderActionDivider />++ {/* A lock explains itself only on a step that exists; with nothing to step over there is nothing to explain. */}+ <HeaderHistoryButton+ available={canUndo}+ icon={Undo2Icon}+ label={undoText}+ shortcut={undoShortcut}+ unavailableReason={canUndo ? lockReason : undefined}+ onStep={() => engine.history.undo()}+ />+ <HeaderHistoryButton+ available={canRedo}+ icon={Redo2Icon}+ label={redoText}+ shortcut={redoShortcut}+ unavailableReason={canRedo ? lockReason : undefined}+ onStep={() => engine.history.redo()}+ />++ <HeaderActionDivider /><Menu.Rootids={saveMenuIds}@@ -457,6 +452,12 @@ const CommandMenuItem = ({ commandId, ...item }: Omit<MenuActionItemProps, 'shorreturn <MenuActionItem {...item} shortcut={shortcut} />;};+/** A command's effective first binding, remaps included, as keycaps; nothing while it is unbound. */+const CommandKeycaps = ({ commandId }: { commandId: string }) => {+ const parts = useShortcutBinding(commandId)?.parts;+ return parts ? <ShortcutKeycaps parts={parts} /> : null;+};+/** "{w} × {h} · {board}", dropping whichever part is unknown; undefined when neither is. */const describeSave = (t: (key: string, options?: Record<string, unknown>) => string,@@ -509,9 +510,6 @@ const SaveMenuItems = ({);};-/** A thin vertical rule separating header-action groups (matching legacy's dividers). */-const HeaderDivider = () => <Box bg="border.subtle" flexShrink={0} h="4" mx="1" w="1px" />;-/** Diagnostics use an existing engine; opening settings must never acquire a canvas engine lease. */export const CanvasSettingsActions = (_props: WidgetViewProps) => {const projectId = useActiveProjectId();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsxindex 1dcab093ea..ad0d577d98 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropOverlay.tsx@@ -1,8 +1,13 @@+import type { NativeFileDrag } from '@platform/react/useNativeFileDrag';+import { Grid } from '@chakra-ui/react';import { useDndContext } from '@dnd-kit/core';import { isGalleryImageDragData } from '@features/gallery/utility';+import { DropZone } from '@platform/ui/DropZone';+import { DropZoneLabel } from '@workbench/widgets/shared/DropZoneLabel';+import { useTranslation } from 'react-i18next';-import { getCanvasImageDropData, getCanvasImageDropId } from './canvasImageDnd';+import { getCanvasImageDropData, getCanvasImageDropId, type CanvasImageDropData } from './canvasImageDnd';import { CanvasImageDropZone, type CanvasImageDropZoneProps } from './CanvasImageDropZone';export const CANVAS_IMAGE_DROP_LAYOUT = [@@ -38,17 +43,47 @@ const CANVAS_IMAGE_DROP_ZONES = CANVAS_IMAGE_DROP_LAYOUT.map((zone) => ({labelKey: LABEL_KEYS[zone.destination],})) satisfies readonly CanvasImageDropZoneProps[];-export const CanvasImageDropOverlay = ({ isDocumentEditingLocked }: { isDocumentEditingLocked: boolean }) => {+/**+ * The drop zones over the canvas while a gallery image is dragged with dnd-kit, or files from the desktop+ * (`fileDrag`); both land the same way. A canvas held by a running operation takes neither and says so instead.+ */+export const CanvasImageDropOverlay = ({+ fileDrag,+ isDocumentEditingLocked,+}: {+ fileDrag: NativeFileDrag<CanvasImageDropData['destination']> | null;+ isDocumentEditingLocked: boolean;+}) => {+ const { t } = useTranslation();const { active } = useDndContext();- if (isDocumentEditingLocked || !isGalleryImageDragData(active?.data.current)) {+ if (fileDrag === null && !isGalleryImageDragData(active?.data.current)) {return null;}+ if (isDocumentEditingLocked) {+ return (+ <DropZone+ alignItems="center"+ display="flex"+ inset="0.5"+ isDisabled+ justifyContent="center"+ p="6"+ pointerEvents="none"+ position="absolute"+ variant="overlay"+ zIndex="2"+ >+ <DropZoneLabel>{t('widgets.layers.actions.busy')}</DropZoneLabel>+ </DropZone>+ );+ }+return (<Grid {...CANVAS_IMAGE_DROP_GRID_LAYOUT} inset="0" pointerEvents="none" position="absolute" zIndex="2">{CANVAS_IMAGE_DROP_ZONES.map((zone) => (- <CanvasImageDropZone key={zone.id} {...zone} />+ <CanvasImageDropZone key={zone.id} {...zone} isFileOver={fileDrag?.zone === zone.destination} />))}</Grid>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropZone.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropZone.tsxindex ebc689f8c9..f448a52f9c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropZone.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasImageDropZone.tsx@@ -1,14 +1,17 @@-import { GridItem, Text } from '@chakra-ui/react';+import { GridItem } from '@chakra-ui/react';import { useDroppable } from '@dnd-kit/core';import { DropZone } from '@platform/ui/DropZone';+import { DropZoneLabel } from '@workbench/widgets/shared/DropZoneLabel';import { useTranslation } from 'react-i18next';-import type { CanvasImageDropData } from './canvasImageDnd';+import { CANVAS_IMAGE_DROP_DESTINATION_ATTRIBUTE, type CanvasImageDropData } from './canvasImageDnd';export interface CanvasImageDropZoneProps {colSpan: number;data: CanvasImageDropData;id: string;+ /** A file dragged in from the desktop hovers this zone; dnd-kit reports its own drags. */+ isFileOver?: boolean;labelKey:| 'widgets.canvas.import.dropControl'| 'widgets.canvas.import.dropInpaintMask'@@ -18,12 +21,27 @@ export interface CanvasImageDropZoneProps {row: number;}-export const CanvasImageDropZone = ({ colSpan, data, id, labelKey, row }: CanvasImageDropZoneProps) => {+export const CanvasImageDropZone = ({+ colSpan,+ data,+ id,+ isFileOver = false,+ labelKey,+ row,+}: CanvasImageDropZoneProps) => {const { t } = useTranslation();- const { isOver, setNodeRef } = useDroppable({ data, id });+ const { isOver: isDragOver, setNodeRef } = useDroppable({ data, id });+ const isOver = isDragOver || isFileOver;return (- <GridItem ref={setNodeRef} colSpan={colSpan} gridRow={row} position="relative">+ <GridItem+ ref={setNodeRef}+ colSpan={colSpan}+ gridRow={row}+ data-over={isOver || undefined}+ position="relative"+ {...{ [CANVAS_IMAGE_DROP_DESTINATION_ATTRIBUTE]: data.destination }}+ ><DropZonealignItems="center"display="flex"@@ -34,9 +52,7 @@ export const CanvasImageDropZone = ({ colSpan, data, id, labelKey, row }: Canvasposition="absolute"variant="overlay">- <Text color="fg" fontSize="lg" fontWeight="700" textAlign="center">- {t(labelKey)}- </Text>+ <DropZoneLabel>{t(labelKey)}</DropZoneLabel></DropZone></GridItem>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsxindex c628ffde9b..580b845170 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx@@ -1,4 +1,6 @@import type * as DndKitCore from '@dnd-kit/core';+import type { GalleryImage } from '@features/gallery';+import type * as GalleryBackend from '@features/gallery/data/backend';import type {CanvasControlLayerContract,CanvasLayerContract,@@ -7,6 +9,7 @@ import type {ControlLayerViewOutcome,} from '@workbench/canvas-engine/api';import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';+import type * as CanvasOperationsApi from '@workbench/canvas-operations/api';import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';import type { Project } from '@workbench/projectContracts';import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';@@ -14,19 +17,15 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';import { ChakraProvider } from '@chakra-ui/react';-import { galleryTransfers, type GalleryImage } from '@features/gallery';import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';+import { TINY_PNG_BASE64 } from '@platform/browser/nativeDrag.testing';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { createControlLayer } from '@workbench/canvas-engine/api';-import {- groupContract,- layerContract,- stacksFrom,-} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';-import { getCanvasOperations, getControlSourceSnapshot } from '@workbench/canvas-operations/api';+import { getCanvasOperations, uploadControlImageFile } from '@workbench/canvas-operations/api';import { createControlDetectionStatusStore } from '@workbench/canvas-operations/controlDetectionStatusStore';import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';@@ -38,7 +37,7 @@ 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, userEvent } from 'vitest/browser';+import { commands, page, userEvent } from 'vitest/browser';import type * as EngineStoreHooks from './engineStoreHooks';@@ -47,7 +46,13 @@ const harness = vi.hoisted(() => ({/** Drag data dnd-kit reports as active; null leaves the real (idle) context. */dragData: null as unknown,engine: null as CanvasEngine | null,+ /** Whether the registry still holds `engine` live for its project; a closed Canvas releases it. */+ isEngineLive: true,+ /** The operation holding the document, if any; null leaves the canvas editable. */+ operation: null as unknown,store: null as ReturnType<typeof createWorkbenchStore> | null,+ /** The server's answer to each image upload; the transport is the only double on the upload path. */+ uploadImage: vi.fn<(file: File, boardId: string) => Promise<GalleryImage>>(),}));const activeProject = () => harness.store!.getState().projects[0]!;@@ -64,6 +69,18 @@ vi.mock('@dnd-kit/core', async (importOriginal) => {useDndMonitor: () => undefined,};});+vi.mock('@features/gallery/data/backend', async (importOriginal) => ({+ ...(await importOriginal<typeof GalleryBackend>()),+ // No board listing: uploads judge their board from an empty one.+ listGalleryBoards: () => Promise.resolve([]),+ uploadGalleryImage: (file: File, boardId: string) => harness.uploadImage(file, boardId),+}));+// The engine registry's non-owning lookup, as the registry answers it for the harness engine.+vi.mock('@workbench/canvas-operations/api', async (importOriginal) => ({+ ...(await importOriginal<typeof CanvasOperationsApi>()),+ getCanvasEngine: (projectId: string) =>+ harness.isEngineLive && harness.engine?.projectId === projectId ? harness.engine : undefined,+}));vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({...(await importOriginal<typeof WorkbenchContextModule>()),useActiveProjectId: () => activeProject().id,@@ -83,7 +100,7 @@ vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({}));vi.mock('./engineStoreHooks', async (importOriginal) => ({...(await importOriginal<typeof EngineStoreHooks>()),- useCanvasOperation: () => null,+ useCanvasOperation: () => harness.operation,}));vi.mock('@workbench/canvas-operations/react', () => ({ useCanvasEngine: () => harness.engine }));vi.mock('./useCanvasGallerySave', () => ({@@ -97,7 +114,6 @@ vi.mock('./useCreateFromBbox', () => ({}));vi.mock('./CanvasCreateFromBboxSubmenu', () => ({ CanvasCreateFromBboxSubmenu: () => null }));vi.mock('./CanvasGlobalContextMenu', () => ({ CanvasGlobalContextMenu: () => null }));-vi.mock('./CanvasImageDropOverlay', () => ({ CanvasImageDropOverlay: () => null }));vi.mock('./CanvasSaveToGallerySubmenu', () => ({ CanvasSaveToGallerySubmenu: () => null }));vi.mock('./CanvasSurface', () => ({ CanvasSurface: () => null }));vi.mock('./MissingFontsDialog', () => ({ MissingFontsDialog: () => null }));@@ -120,7 +136,8 @@ afterEach(async () => {await act(() => root?.unmount());host?.remove();harness.engine?.lifecycle.dispose();- Object.assign(harness, { dragData: null, engine: null, store: null });+ Object.assign(harness, { dragData: null, engine: null, isEngineLive: true, operation: null, store: null });+ harness.uploadImage.mockReset();root = null;host = null;});@@ -147,6 +164,7 @@ const renderView = async ({beforeRender,domRaster = false,+ hostWidth = 1000,nodes,selectedLayer,staged = true,@@ -154,6 +172,8 @@ const renderView = async (beforeRender?: (engine: CanvasEngine) => void;/** Real Canvas2D pixels, for a test that attaches a surface and draws. */domRaster?: boolean;+ /** The surface's width; a drag through the browser's own input reaches only what fits in the test frame. */+ hostWidth?: number;nodes?: CanvasNodeContract[];selectedLayer?: CanvasLayerContract;staged?: boolean;@@ -207,7 +227,7 @@ const renderView = async (beforeRender?.(harness.engine);host = document.createElement('div');host.style.height = '600px';- host.style.width = '1000px';+ host.style.width = `${hostWidth}px`;document.body.append(host);root = createRoot(host);const commandHandlers = new Map<string, () => void>();@@ -455,6 +475,8 @@ describe('CanvasWidgetView clipboard shortcuts', () => {const { commandHandlers, store } = await renderView('completed', { staged: false });withoutClipboard();vi.spyOn(harness.engine!.selection, 'exportSelectionBlob').mockResolvedValue(new Blob([], { type: 'image/png' }));+ // A cut the layer allows, so it reaches the clipboard write that fails.+ vi.spyOn(harness.engine!.selection, 'admitSelectionErase').mockReturnValue(true);const erase = vi.spyOn(harness.engine!.selection, 'eraseSelection');await act(() => commandHandlers.get('canvas.copySelection')!());@@ -511,7 +533,7 @@ describe('CanvasWidgetView clipboard shortcuts', () => {describe('CanvasWidgetView control layer overlay', () => {const emptyControlLayer = createControlLayer({ id: 'control-1', name: 'Control Layer 1' });- const hint = () => page.getByRole('note').filter({ hasText: 'Drop an image here' });+ const hint = () => page.getByRole('note').filter({ hasText: 'Add an image' });afterEach(() => {vi.restoreAllMocks();@@ -521,7 +543,9 @@ describe('CanvasWidgetView control layer overlay', () => {await renderView('completed', { selectedLayer: emptyControlLayer, staged: false });await expect.element(hint()).toBeVisible();- await expect.element(hint().getByText('or pick one in Properties', { exact: true })).toBeVisible();+ await expect+ .element(hint().getByText('Drag one onto Add as control layer, or pick one in Properties', { exact: true }))+ .toBeVisible();await act(() => harness.engine!.tools.setTool('brush'));await expect.element(hint()).not.toBeInTheDocument();@@ -544,7 +568,7 @@ describe('CanvasWidgetView control layer overlay', () => {harness.dragData = { items: [{ kind: 'image', name: 'photo.png' }], kind: 'gallery-item' };await renderView('completed', { selectedLayer: emptyControlLayer, staged: false });- await expect.element(page.getByText('Drop an image here')).toBeInTheDocument();+ await expect.element(page.getByText('Add an image')).toBeInTheDocument();await expect.element(hint()).not.toBeInTheDocument();});@@ -556,7 +580,7 @@ describe('CanvasWidgetView control layer overlay', () => {await renderView('completed', { selectedLayer: filled, staged: false });expect(page.getByRole('note').elements()).toHaveLength(0);- expect(page.getByText('Drop an image here').elements()).toHaveLength(0);+ expect(page.getByText('Add an image').elements()).toHaveLength(0);});const depthLayer: CanvasControlLayerContract = {@@ -712,10 +736,15 @@ describe('CanvasWidgetView control layer overlay', () => {expect(viewSwitch().elements()).toHaveLength(0);});- it('keeps the view switch while a result is staged', async () => {+ it('hides the view switch while a staged result hides the layer, and offers it again once staging ends', async () => {await renderView('completed', { selectedLayer: readyLayer });await expect.element(page.getByRole('button', { exact: true, name: 'Accept to layer' })).toBeVisible();+ await expect.poll(() => harness.engine!.interaction.get('stagingHidesOverlays')).toBe(true);+ expect(viewSwitch().elements()).toHaveLength(0);++ // The view clears the preview as accept or discard ends staging; the harness view does not rerender on its own.+ await act(() => harness.engine!.previews.setStagedPreview(null));await expect.element(viewSwitch()).toBeVisible();});@@ -742,114 +771,391 @@ describe('CanvasWidgetView control layer overlay', () => {describe('CanvasWidgetView desktop file drops', () => {const emptyControlLayer = createControlLayer({ id: 'control-1', name: 'Control Layer 1' });- const PHOTO_FILE = new File([new Uint8Array([137, 80, 78, 71])], 'photo.png', { type: 'image/png' });- const UPLOADED = { height: 64, imageName: 'dropped.png', width: 96 } as GalleryImage;- const hint = () => page.getByRole('note');+ const imageFile = (name: string) =>+ new File([Uint8Array.from(atob(TINY_PNG_BASE64), (char) => char.charCodeAt(0))], name, { type: 'image/png' });+ const stored = (file: { name: string }): GalleryImage => ({+ boardId: 'none',+ height: 2,+ imageCategory: 'user',+ imageName: `stored-${file.name}`,+ imageUrl: `/images/stored-${file.name}`,+ queuedAt: '2026-11-10T00:00:00.000Z',+ sourceQueueItemId: 'upload',+ starred: false,+ thumbnailUrl: `/thumbnails/stored-${file.name}`,+ width: 2,+ });+ const surface = () => page.getByRole('region', { exact: true, name: 'Canvas surface' }).element();+ const zone = (name: string) => page.getByText(name, { exact: true });+ /** The zone element dnd-kit and file drags hover, around the label `name`. */+ const zoneTarget = (name: string) => zone(name).element().closest('[data-canvas-image-drop-destination]')!;+ const titles = (store: Awaited<ReturnType<typeof renderView>>['store']) =>+ store.getState().notifications.map((notification) => notification.title);+ const rasterLayersOf = (projectId: string) =>+ harness.store!.getState().projects.find((project) => project.id === projectId)!.canvas.document.stacks.raster;+ // The first drop loads the upload code; a cold transform can take longer than `waitFor`'s default second.+ const LANDED = { timeout: 5_000 };afterEach(() => {vi.restoreAllMocks();});- /** Sends a native drag carrying `transfer` over the canvas and drops it; returns whether each event was taken. */- const drag = async (transfer: DataTransfer) => {- const surface = page.getByRole('region', { exact: true, name: 'Canvas surface' }).element();- const over = new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: transfer });- const drop = new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: transfer });- await act(() => surface.dispatchEvent(over));- await act(() => surface.dispatchEvent(drop));- return { dropTaken: drop.defaultPrevented, overTaken: over.defaultPrevented };+ const centreOf = (element: Element) => {+ const rect = element.getBoundingClientRect();+ return { clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 };+ };+ /** Where the zone labelled `name` sits on the surface, before any drag shows it: the overlay's grid places it. */+ const pointOn = (destination: 'control' | 'raster') => {+ const rect = surface().getBoundingClientRect();+ return {+ x: rect.left + rect.width * (destination === 'raster' ? 0.25 : 0.75),+ y: rect.top + rect.height * 0.25,+ };};- const dragFiles = (files: File[]) => {+ /** A real drag from the operating system, through the browser's own drag input. */+ const nativeDrop = (destination: 'control' | 'raster', names: string[]) =>+ commands.nativeDrag({+ files: names.map((name) => ({ base64: TINY_PNG_BASE64, name })),+ frameWidth: window.innerWidth,+ points: [pointOn(destination)],+ });+ const send = async (type: string, transfer: DataTransfer, init: DragEventInit = {}, target: Element = surface()) => {+ const event = new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: transfer, ...init });+ await act(() => target.dispatchEvent(event));+ return event;+ };+ const transferOf = (files: File[]) => {const transfer = new DataTransfer();for (const file of files) {transfer.items.add(file);}- return drag(transfer);+ return transfer;+ };+ /** Dispatches a drag over the zone labelled `zoneName` and drops it there, from the test itself. */+ const dropOn = async (zoneName: string, files: File[]) => {+ const transfer = transferOf(files);+ await send('dragenter', transfer);+ await expect.element(zone(zoneName)).toBeVisible();+ const at = centreOf(zone(zoneName).element());+ await send('dragover', transfer, at);+ return send('drop', transfer, at);};- const lastNotice = (store: Awaited<ReturnType<typeof renderView>>['store']) => store.getState().notifications[0];- it('fills an empty control layer from a dropped image, says it is uploading, and refuses a second drop meanwhile', async () => {- let finishUpload!: (image: GalleryImage) => void;- const upload = vi.spyOn(galleryTransfers, 'upload').mockReturnValue(- new Promise((resolve) => {- finishUpload = resolve;- })+ it('uploads image files dropped from the desktop on a zone and adds them as it says, at the frame', async () => {+ harness.uploadImage.mockImplementation((file) => Promise.resolve(stored(file)));+ const { projectId, store } = await renderView('completed', { hostWidth: window.innerWidth, staged: false });+ const before = rasterLayersOf(projectId).length;++ await nativeDrop('raster', ['one.png', 'two.png']);++ await vi.waitFor(() => expect(rasterLayersOf(projectId)).toHaveLength(before + 2), LANDED);+ // Stored as pasted media is: in the project's auto-add board (Uncategorized here), then layered at the frame.+ expect(harness.uploadImage.mock.calls.map(([file, boardId]) => [file.name, boardId])).toEqual([+ ['one.png', 'none'],+ ['two.png', 'none'],+ ]);+ const { bbox } = activeProject().canvas.document;+ expect(+ rasterLayersOf(projectId)+ .slice(-2)+ .map((layer) =>+ layer.type === 'raster' ? { source: layer.source, x: layer.transform.x, y: layer.transform.y } : null+ )+ ).toEqual([+ { source: { image: { height: 2, imageName: 'stored-one.png', width: 2 }, type: 'image' }, x: bbox.x, y: bbox.y },+ { source: { image: { height: 2, imageName: 'stored-two.png', width: 2 }, type: 'image' }, x: bbox.x, y: bbox.y },+ ]);+ await vi.waitFor(() =>+ expect(titles(store)).toEqual(['Added 2 images as canvas layers', expect.stringMatching(/^Uploaded 2 /)]));+ // The zones went with the drag.+ expect(zone('Add as raster layer').elements()).toHaveLength(0);+ });++ it('fills the selected empty control layer from one image dropped on the control zone, as a gallery drop does', async () => {+ harness.uploadImage.mockImplementation((file) => Promise.resolve(stored(file)));const { store } = await renderView('completed', {beforeRender: (engine) => {vi.spyOn(getCanvasOperations(engine), 'applyControlLayerIntent').mockReturnValue('updated');},+ hostWidth: window.innerWidth,selectedLayer: emptyControlLayer,staged: false,});const apply = vi.mocked(getCanvasOperations(harness.engine!).applyControlLayerIntent);- expect(await dragFiles([PHOTO_FILE])).toEqual({ dropTaken: true, overTaken: true });- await expect.element(hint()).toHaveTextContent('Uploading…');- await expect.element(hint()).toHaveAttribute('aria-busy', 'true');-- // A second drop while the first is on its way would race it: refused, with the reason.- await dragFiles([PHOTO_FILE]);- expect(upload).toHaveBeenCalledTimes(1);- await vi.waitFor(() =>- expect(lastNotice(store)).toMatchObject({ title: 'An image is still uploading to this layer.' })- );+ await nativeDrop('control', ['depth.png']);- await act(() => finishUpload(UPLOADED));- await vi.waitFor(() => expect(apply).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(apply).toHaveBeenCalledTimes(1), LANDED);const { bbox } = activeProject().canvas.document;- expect(upload).toHaveBeenCalledWith(PHOTO_FILE, 'none', expect.anything());expect(apply).toHaveBeenCalledWith('control-1', {- image: { height: 64, imageName: 'dropped.png', width: 96 },+ image: { height: 2, imageName: 'stored-depth.png', width: 2 },kind: 'replace-image',transform: { rotation: 0, scaleX: 1, scaleY: 1, x: bbox.x, y: bbox.y },});- // Properties names the image after the file, as for its own Upload.- expect(getControlSourceSnapshot(harness.engine!).origins['dropped.png']).toEqual({- kind: 'file',- name: 'photo.png',+ await vi.waitFor(() => expect(titles(store)[0]).toBe('Filled Control Layer 1'));+ });++ it('highlights the zone under the files as they move between zones', async () => {+ await renderView('completed', { hostWidth: window.innerWidth, staged: false });+ const transfer = transferOf([imageFile('one.png')]);++ await send('dragenter', transfer);+ await send('dragover', transfer, centreOf(zoneTarget('Add as inpaint mask')));+ expect(zoneTarget('Add as inpaint mask')).toHaveAttribute('data-over');+ expect(zoneTarget('Add as raster layer')).not.toHaveAttribute('data-over');++ await send('dragover', transfer, centreOf(zoneTarget('Add as raster layer')));+ expect(zoneTarget('Add as raster layer')).toHaveAttribute('data-over');+ expect(zoneTarget('Add as inpaint mask')).not.toHaveAttribute('data-over');+ });++ it('says why files that are not images are not added, and uploads only the images among them', async () => {+ harness.uploadImage.mockImplementation((file) => Promise.resolve(stored(file)));+ const { store } = await renderView('completed', { hostWidth: window.innerWidth, staged: false });+ const notes = new File(['notes'], 'notes.txt', { type: 'text/plain' });+ const clip = new File(['clip'], 'clip.mp4', { type: 'video/mp4' });++ await dropOn('Add as raster layer', [notes, clip]);+ expect(store.getState().notifications[0]).toMatchObject({+ kind: 'error',+ title: 'Only image files can be dropped on the canvas.',+ });+ expect(harness.uploadImage).not.toHaveBeenCalled();++ await dropOn('Add as raster layer', [notes, imageFile('one.png')]);+ expect(store.getState().notifications[0]).toMatchObject({+ kind: 'info',+ title: 'Only image files can be dropped on the canvas.',});- // The upload has landed: the card no longer says it is uploading.- await vi.waitFor(() => expect(hint().element().getAttribute('aria-busy')).toBe('false'));- expect(hint().element().textContent).toContain('Drop an image here');+ await vi.waitFor(() => expect(harness.uploadImage).toHaveBeenCalledTimes(1), LANDED);+ expect(harness.uploadImage.mock.calls[0]![0].name).toBe('one.png');});- it('refuses a drop on a control layer locked by its group before uploading anything', async () => {- const upload = vi.spyOn(galleryTransfers, 'upload');- const { store } = await renderView('completed', {- nodes: [groupContract('group-1', [emptyControlLayer], { isLocked: true })],- selectedLayer: emptyControlLayer,- staged: false,+ it('refuses a second drop while the first is still uploading, rather than adding everything twice', async () => {+ let finishUpload!: () => void;+ harness.uploadImage.mockImplementation(+ (file) =>+ new Promise((resolve) => {+ finishUpload = () => resolve(stored(file));+ })+ );+ const { projectId, store } = await renderView('completed', { hostWidth: window.innerWidth, staged: false });+ const before = rasterLayersOf(projectId).length;++ await dropOn('Add as raster layer', [imageFile('one.png')]);+ await vi.waitFor(() => expect(harness.uploadImage).toHaveBeenCalledTimes(1), LANDED);+ await dropOn('Add as raster layer', [imageFile('again.png')]);++ expect(store.getState().notifications[0]).toMatchObject({+ kind: 'info',+ title: 'The files you dropped are still uploading. Try again when they are done.',});+ await act(() => finishUpload());+ await vi.waitFor(() => expect(rasterLayersOf(projectId)).toHaveLength(before + 1));+ expect(harness.uploadImage).toHaveBeenCalledTimes(1);+ });- expect(await dragFiles([PHOTO_FILE])).toEqual({ dropTaken: true, overTaken: true });+ it('lands an upload that finishes after a project switch on the project it was dropped on, keeping its edits', async () => {+ let finishUpload!: () => void;+ harness.uploadImage.mockImplementation(+ (file) =>+ new Promise((resolve) => {+ finishUpload = () => resolve(stored(file));+ })+ );+ const { projectId, store } = await renderView('completed', { hostWidth: window.innerWidth, staged: false });- expect(lastNotice(store)).toMatchObject({ title: 'Unlock the layer before using this action.' });- expect(upload).not.toHaveBeenCalled();+ await dropOn('Add as raster layer', [imageFile('late.png')]);+ await vi.waitFor(() => expect(harness.uploadImage).toHaveBeenCalledTimes(1), LANDED);+ // An edit made while the file uploads, then a switch to another project.+ await act(() =>+ store.commands.canvas.apply(projectId, {+ document: {+ ...activeProject().canvas.document,+ stacks: stacksFrom([...rasterLayersOf(projectId), layerContract('kept', 'raster')]),+ },+ type: 'replaceCanvasDocument',+ })+ );+ const switchedTo = await act(() => store.commands.projects.create());+ await act(() => finishUpload());++ await vi.waitFor(() =>+ expect(rasterLayersOf(projectId).map((layer) => layer.type === 'raster' && layer.source)).toContainEqual({+ image: { height: 2, imageName: 'stored-late.png', width: 2 },+ type: 'image',+ })+ );+ expect(rasterLayersOf(projectId).map((layer) => layer.id)).toContain('kept');+ expect(store.getState().activeProjectId).toBe(switchedTo.id);+ expect(rasterLayersOf(switchedTo.id)).toHaveLength(0);});- it('says what a drop needs when no empty control layer is selected, or the files do not fit', async () => {- const upload = vi.spyOn(galleryTransfers, 'upload');- const { store } = await renderView('completed', {- selectedLayer: layerContract('raster-1', 'raster'),- staged: false,+ it('adds through the project when its Canvas was closed while the files uploaded', async () => {+ let finishUpload!: () => void;+ harness.uploadImage.mockImplementation(+ (file) =>+ new Promise((resolve) => {+ finishUpload = () => resolve(stored(file));+ })+ );+ const { projectId } = await renderView('completed', { hostWidth: window.innerWidth, staged: false });+ const commit = vi.spyOn(harness.engine!.layers, 'commitStructural');++ await dropOn('Add as raster layer', [imageFile('late.png')]);+ await vi.waitFor(() => expect(harness.uploadImage).toHaveBeenCalledTimes(1), LANDED);+ // The registry let the released engine go; the one the drop saw must not be used.+ harness.isEngineLive = false;+ await act(() => finishUpload());++ await vi.waitFor(() =>+ expect(rasterLayersOf(projectId).map((layer) => layer.type === 'raster' && layer.source)).toContainEqual({+ image: { height: 2, imageName: 'stored-late.png', width: 2 },+ type: 'image',+ })+ );+ expect(commit).not.toHaveBeenCalled();+ });++ it('ends the drag when it leaves the canvas, leaves the window, is cancelled or is dropped elsewhere', async () => {+ await renderView('completed', { hostWidth: window.innerWidth, staged: false });+ const transfer = transferOf([imageFile('one.png')]);+ const zonesShown = () => zone('Add as inpaint mask').elements().length > 0;++ // Onto the rest of the page.+ await send('dragenter', transfer);+ expect(zonesShown()).toBe(true);+ await send('dragleave', transfer, { relatedTarget: document.body });+ expect(zonesShown()).toBe(false);++ // Out of the window, after crossing onto an element the drag itself took down: no leave reports that one.+ const doomed = document.createElement('div');+ surface().append(doomed);+ await send('dragenter', transfer);+ await send('dragenter', transfer, { relatedTarget: surface() }, doomed);+ doomed.remove();+ await send('dragleave', transfer, { relatedTarget: null });+ await vi.waitFor(() => expect(zonesShown()).toBe(false));++ // A drag that finished elsewhere: dropped outside the canvas, or ended at its source.+ await send('dragenter', transfer);+ await act(() => document.body.dispatchEvent(new DragEvent('drop', { bubbles: true, dataTransfer: transfer })));+ expect(zonesShown()).toBe(false);+ await send('dragenter', transfer);+ await act(() => window.dispatchEvent(new DragEvent('dragend')));+ expect(zonesShown()).toBe(false);+ });++ it('keeps the zones while the window loses focus mid-drag, as a focus-follows-mouse window manager does', async () => {+ await renderView('completed', { hostWidth: window.innerWidth, staged: false });+ const transfer = transferOf([imageFile('one.png')]);++ await send('dragenter', transfer);+ await act(() => window.dispatchEvent(new Event('blur')));++ await expect.element(zone('Add as raster layer')).toBeVisible();+ });++ it('takes no drop while an operation holds the canvas, and says why while files or gallery images hover', async () => {+ harness.operation = { identity: { kind: 'filter' }, status: 'active' };+ await renderView('completed', { hostWidth: window.innerWidth, staged: false });+ const busy = () => page.getByText('The canvas is busy. Try again when the current action finishes.');++ await send('dragenter', transferOf([imageFile('one.png')]));+ await expect.element(busy()).toBeVisible();+ expect(zone('Add as raster layer').elements()).toHaveLength(0);+ await send('dragleave', transferOf([imageFile('one.png')]), { relatedTarget: document.body });++ await nativeDrop('raster', ['one.png']);+ await expect.element(busy()).not.toBeInTheDocument();+ // Long enough for a taken drop to have loaded the upload and sent the file.+ await new Promise((resolve) => {+ setTimeout(resolve, 500);});+ expect(harness.uploadImage).not.toHaveBeenCalled();+ });- await dragFiles([PHOTO_FILE]);- expect(lastNotice(store)).toMatchObject({ title: 'Select an empty control layer to drop an image on it.' });- await dragFiles([new File(['notes'], 'notes.txt', { type: 'text/plain' })]);- expect(lastNotice(store)).toMatchObject({ title: 'Only image files can be dropped on the canvas.' });- await dragFiles([PHOTO_FILE, PHOTO_FILE]);- expect(lastNotice(store)).toMatchObject({ title: 'Drop one image at a time.' });+ it('says the canvas is busy to a gallery image dragged over it while an operation holds it', async () => {+ harness.operation = { identity: { kind: 'filter' }, status: 'active' };+ harness.dragData = { items: [{ kind: 'image', name: 'photo.png' }], kind: 'gallery-item' };+ await renderView('completed', { hostWidth: window.innerWidth, staged: false });- expect(upload).not.toHaveBeenCalled();+ await expect+ .element(page.getByText('The canvas is busy. Try again when the current action finishes.'))+ .toBeVisible();+ expect(zone('Add as raster layer').elements()).toHaveLength(0);});- it('leaves a drag that carries no files alone', async () => {+ it('says Uploading on the control hint while Properties uploads an image into the empty layer', async () => {+ let finishUpload!: () => void;await renderView('completed', { selectedLayer: emptyControlLayer, staged: false });+ const hint = () => page.getByRole('note');+ await expect.element(hint()).toHaveAttribute('aria-busy', 'false');++ const upload = uploadControlImageFile({+ engine: harness.engine!,+ file: imageFile('depth.png'),+ layerId: 'control-1',+ uploadImage: (file) =>+ new Promise((resolve) => {+ finishUpload = () => resolve(stored(file));+ }),+ });++ await expect.element(hint()).toHaveAttribute('aria-busy', 'true');+ await expect.element(hint()).toHaveTextContent('Uploading…');+ await act(() => finishUpload());+ await act(() => upload);+ // The layer has its image: the hint and its spinner are gone.+ await expect.element(page.getByText('Uploading…')).not.toBeInTheDocument();+ });++ it('leaves a drag that carries no files alone', async () => {+ await renderView('completed', { hostWidth: window.innerWidth, staged: false });const transfer = new DataTransfer();transfer.setData('text/plain', 'not a file');- expect(await drag(transfer)).toEqual({ dropTaken: false, overTaken: false });+ expect((await send('dragover', transfer)).defaultPrevented).toBe(false);+ expect((await send('drop', transfer)).defaultPrevented).toBe(false);+ expect(zone('Add as raster layer').elements()).toHaveLength(0);+ });+});++describe('CanvasWidgetView frame size readout', () => {+ it('follows a Frame tool resize through the engine, then shows the committed frame', async () => {+ await renderView('completed', { domRaster: true, staged: false });+ const engine = harness.engine!;+ const screen = document.createElement('canvas');+ const overlay = document.createElement('canvas');+ for (const canvas of [screen, overlay]) {+ Object.assign(canvas.style, { height: '300px', left: '0', position: 'fixed', top: '0', width: '300px' });+ host!.append(canvas);+ }+ await act(() => engine.surface.attach(screen, overlay));+ await act(() => engine.tools.setTool('bbox'));+ const readout = page.getByRole('group', { name: 'Frame and render size' });+ const frameValue = () => readout.element().querySelector('dd')?.textContent;+ const { bbox } = activeProject().canvas.document;+ await expect.element(readout).toHaveTextContent(`Frame${bbox.width}×${bbox.height}`);++ // Drag the bottom-right handle inward by 64 document pixels; Alt turns grid snapping off, so the size is exact.+ const viewport = engine.viewport.getViewport();+ const corner = viewport.documentToScreen({ x: bbox.x + bbox.width, y: bbox.y + bbox.height });+ const target = viewport.documentToScreen({ x: bbox.x + bbox.width - 64, y: bbox.y + bbox.height - 64 });+ const pointer = (type: string, { x, y }: { x: number; y: number }, buttons: number) =>+ new PointerEvent(type, { altKey: true, bubbles: true, buttons, clientX: x, clientY: y, pointerId: 1 });+ await act(() => {+ overlay.dispatchEvent(pointer('pointerdown', corner, 1));+ overlay.dispatchEvent(pointer('pointermove', target, 1));+ });+ // Mid-drag, before anything commits, the readout shows the frame being drawn.+ expect(frameValue()).toBe(`${bbox.width - 64}×${bbox.height - 64}`);+ expect(activeProject().canvas.document.bbox).toEqual(bbox);++ await act(() => overlay.dispatchEvent(pointer('pointerup', target, 0)));+ expect(activeProject().canvas.document.bbox).toMatchObject({ height: bbox.height - 64, width: bbox.width - 64 });+ expect(frameValue()).toBe(`${bbox.width - 64}×${bbox.height - 64}`);+ engine.surface.detach();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsxindex 05537a3000..36d06bf7f5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx@@ -52,6 +52,7 @@ vi.mock('./useCreateFromBbox', () => ({useCreateFromBbox: () => ({ createFromBbox: () => undefined, isCreating: false }),}));vi.mock('./CanvasCreateFromBboxSubmenu', () => ({ CanvasCreateFromBboxSubmenu: () => null }));+vi.mock('./CanvasFrameSizeReadout', () => ({ CanvasFrameSizeReadout: () => null }));vi.mock('./CanvasGlobalContextMenu', () => ({ CanvasGlobalContextMenu: () => null }));vi.mock('./CanvasImageDropOverlay', () => ({ CanvasImageDropOverlay: () => null }));vi.mock('./CanvasSaveToGallerySubmenu', () => ({ CanvasSaveToGallerySubmenu: () => null }));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex bf266bfe86..d28010df5c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -1,20 +1,16 @@import type { WidgetViewProps } from '@workbench/widgetContracts';-import type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent } from 'react';+import type { MouseEvent as ReactMouseEvent } from 'react';import { Box } from '@chakra-ui/react';import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';-import { invalidateGallery } from '@features/gallery/queries';+import { classifyGalleryUpload } from '@features/gallery/contracts';import { useQueueItemProgressImage } from '@features/queue/react';import { ClipboardUnavailableError, copyImage } from '@platform/browser/clipboard';import { useMountEffect } from '@platform/react/useMountEffect';+import { useNativeFileDrag } from '@platform/react/useNativeFileDrag';import { useQueryClient } from '@tanstack/react-query';import { preloadCanvasInvocation } from '@workbench/activeInvocationSubmission';-import {- getControlUploadNotice,- resolveControlFileDrop,- uploadControlImageFile,- type ControlSourceNotice,-} from '@workbench/canvas-operations/api';+import { getDocumentNode } from '@workbench/canvas-engine/api';import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/canvas-operations/react';import { getCanvasStagingSlotRect, getCanvasStagingSlots } from '@workbench/canvasStagingView';import { useRegisterShortcutHintSource } from '@workbench/hotkeys/hintSources';@@ -24,6 +20,7 @@ import { useWorkbenchPreferenceSelector, useWorkbenchSettingsSelector } from '@wimport { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { useNotify } from '@workbench/useNotify';import { CanvasLayerContextMenu } from '@workbench/widgets/layers/LayerContextMenu';+import { useDroppedFileUpload } from '@workbench/widgets/shared/useDroppedFileUpload';import { getProjectWidgetValues } from '@workbench/widgetState';import {useActiveProjectId,@@ -37,7 +34,7 @@ import { useTranslation } from 'react-i18next';import { useModelGridSize } from './bboxGrid';import { CanvasBottomOverlay } from './CanvasBottomOverlay';-import { decodeImageBlob, readClipboardImage } from './canvasClipboard';+import { copyCanvasSelection, decodeImageBlob, readClipboardImage } from './canvasClipboard';import {cropAllLayersToFrame,resolveCanvasContextMenu,@@ -48,9 +45,10 @@ import { CanvasCreateFromBboxSubmenu } from './CanvasCreateFromBboxSubmenu';import { CanvasCropAllLayersMenuItem } from './CanvasCropAllLayersMenuItem';import { CanvasEditRefusalNotices } from './CanvasEditRefusalNotices';import { CanvasFrameLockFeed } from './CanvasFrameLockFeed';+import { CanvasFrameSizeReadout } from './CanvasFrameSizeReadout';import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';import { CANVAS_ONLY_HOTKEYS, executeCanvasHotkeyCommand } from './canvasHotkeyCommands';-import { resolveCanvasImageDrop } from './canvasImageDnd';+import { findCanvasImageDropDestination, resolveCanvasImageDrop, type CanvasImageDropData } from './canvasImageDnd';import { CanvasImageDropOverlay } from './CanvasImageDropOverlay';import { CanvasSaveToGallerySubmenu } from './CanvasSaveToGallerySubmenu';import {@@ -62,7 +60,12 @@ import {import { CanvasStagedRegionsFeed } from './CanvasStagedRegionsFeed';import { CanvasSurface } from './CanvasSurface';import { CanvasSurfaceContextLayout } from './CanvasSurfaceContextLayout';-import { CANVAS_COMPANION_HOTKEYS, reportTransformRefusal } from './canvasToolCommands';+import {+ CANVAS_COMPANION_HOTKEYS,+ reportMergeDownRefusal,+ reportTransformRefusal,+ showCanvasRefusalNotice,+} from './canvasToolCommands';import { resolveCheckerColors } from './checkerColors';import { CanvasColorFeed } from './color-system/CanvasColorFeed';import { useActiveColorCommands } from './color-system/useActiveColors';@@ -81,8 +84,6 @@ import { useCreateFromBbox } from './useCreateFromBbox';import { useStagedResultGallerySave } from './useStagedResultGallerySave';import { reportLayerOperation, reportPreparedCommit, reportStructuralCommit } from './useStructuralCommit';-const isFileDrag = (dataTransfer: DataTransfer): boolean => dataTransfer.types.includes('Files');-const MissingFontsDialog = lazy(() =>import('./MissingFontsDialog').then((module) => ({ default: module.MissingFontsDialog })));@@ -195,72 +196,49 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {const isDocumentEditingLocked = operationKind !== null;const canAcceptStagedImage = engine !== null && selectedCandidate !== undefined && !isDocumentEditingLocked;- // A desktop file dropped on the canvas fills the selected control layer while it is empty, as the hint over it- // says. Every file drag is taken here, since the browser's default would navigate away from the app. While it- // hovers, the drop effect shows whether the canvas would take it; a drop that still arrives and cannot be used- // says why instead of doing nothing.+ // Files dragged in from the desktop show the gallery drag's zones and land the same way once uploaded. The upload+ // and import load on the first drop, keeping them out of Canvas startup. A canvas held by a running operation shows+ // no zones, so it takes no drop; the overlay says why.const queryClient = useQueryClient();- const showNotice = useCallback(- (notice: ControlSourceNotice | null) => {- if (notice) {+ const startDroppedFileUpload = useDroppedFileUpload({+ pendingKey: 'widgets.canvas.fileDrop.pending',+ surface: 'canvas',+ uploadingKey: 'widgets.canvas.fileDrop.uploading',+ });+ const importDroppedFiles = useCallback(+ (files: File[], destination: CanvasImageDropData['destination']) => {+ const images = files.filter((file) => classifyGalleryUpload(file)?.kind === 'image');+ if (images.length < files.length) {notifications.add({- kind: notice.kind,- message: notice.messageKey ? t(notice.messageKey) : notice.message,- title: t(notice.titleKey),+ kind: images.length === 0 ? 'error' : 'info',+ title: t('widgets.canvas.fileDrop.notImage'),});}- },- [notifications, t]- );- const handleFileDragOver = useCallback(- (event: ReactDragEvent<HTMLDivElement>) => {- const { dataTransfer } = event;- if (!isFileDrag(dataTransfer)) {- return;- }- event.preventDefault();- const accepted =- engine !== null &&- resolveControlFileDrop({- document,- engine,- // File contents stay hidden until the drop, but each item's type is readable while it hovers.- files: [...dataTransfer.items].filter((item) => item.kind === 'file'),- isCanvasLocked: isDocumentEditingLocked,- }).status === 'accepted';- dataTransfer.dropEffect = accepted ? 'copy' : 'none';- },- [document, engine, isDocumentEditingLocked]- );- const handleFileDrop = useCallback(- (event: ReactDragEvent<HTMLDivElement>) => {- if (!isFileDrag(event.dataTransfer)) {- return;- }- event.preventDefault();- if (!engine) {+ if (images.length === 0) {return;}- const files = [...event.dataTransfer.files];- const resolution = resolveControlFileDrop({- document,- engine,- files,- isCanvasLocked: isDocumentEditingLocked,+ startDroppedFileUpload(images, {+ load: () => import('./importCanvasFileDrop'),+ run: ({ importCanvasFileDrop }, context) =>+ importCanvasFileDrop({+ ...context,+ canvas: canvasCommands,+ destination,+ files: images,+ notifications,+ queries,+ queryClient,+ t,+ }),+ runFailedMessage: t('widgets.canvas.import.failed'),});- if (resolution.status === 'refused') {- showNotice(resolution.notice);- return;- }- void uploadControlImageFile({- engine,- file: files[0]!,- layerId: resolution.layerId,- onUploaded: (owner) => void invalidateGallery(queryClient, owner),- }).then((outcome) => showNotice(getControlUploadNotice(outcome)));},- [document, engine, isDocumentEditingLocked, queryClient, showNotice]+ [canvasCommands, notifications, queries, queryClient, startDroppedFileUpload, t]);+ const { drag: fileDrag, handlers: fileDragHandlers } = useNativeFileDrag({+ findZone: findCanvasImageDropDestination,+ onDrop: importDroppedFiles,+ });const handleSurfaceContextMenu = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {// Preserve native menus in inline editors. Canvas context actions target the selected layer without changing@@ -326,15 +304,7 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {}void (async () => {try {- const blob = await mountedEngine.selection.exportSelectionBlob();- if (!blob) {- return;- }- await copyImage(blob);- if (cut) {- // Only after the write succeeds — a failed copy must not destroy pixels.- mountedEngine.selection.eraseSelection();- }+ await copyCanvasSelection(mountedEngine.selection, cut, copyImage);} catch (error) {notifications.add({kind: 'error',@@ -441,7 +411,6 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {/* eslint-enable react/preserve-manual-memoization */const acceptStagedImage = useCallback(() => commitSelectedStagedImage(false), [commitSelectedStagedImage]);const saveStagedImageAndContinue = useCallback(() => commitSelectedStagedImage(true), [commitSelectedStagedImage]);- const cancelQueueItem = useCallback((queueItemId: string) => queue.cancel(undefined, queueItemId), [queue]);const cycleStagedImage = useCallback((direction: -1 | 1) => canvasDispatch({ direction, type: 'cycleStagedImage' }),[canvasDispatch]@@ -516,7 +485,14 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {notifications.add({ kind: 'error', title: t('widgets.layers.actions.copyFailed') }),pasteFromClipboard,reportLayerOperation: (refusal) => reportLayerOperation(refusal, notify.error, t),- reportTransformRefusal: (refusal) => reportTransformRefusal(refusal, notify.error, t),+ reportMergeDownRefusal: (refusal) => reportMergeDownRefusal(document, refusal, showCanvasRefusalNotice, t),+ reportTransformRefusal: (refusal, layerId) =>+ reportTransformRefusal(+ refusal,+ { id: layerId, name: getDocumentNode(document, layerId)?.name ?? '' },+ { error: notify.error, notice: showCanvasRefusalNotice },+ t+ ),reportPreparedCommit: (outcome) => reportPreparedCommit(outcome, notify.error, t),reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),resetActiveColors: colorCommands.resetPair,@@ -585,8 +561,7 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {position="relative"role="region"w="full"- onDragOver={handleFileDragOver}- onDrop={handleFileDrop}+ {...fileDragHandlers}>{engine ? (<CanvasShortcutHintRegistration@@ -597,20 +572,23 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {/>) : null}<CanvasColorFeed engine={engine} />- {engine ? <CanvasFrameLockFeed key={projectId} engine={engine} projectId={projectId} /> : null}- {engine ? <CanvasEditRefusalNotices key={projectId} engine={engine} /> : null}- {engine ? <CanvasStagedRegionsFeed key={projectId} engine={engine} projectId={projectId} /> : null}+ {engine ? <CanvasFrameLockFeed key={`${projectId}:frame-lock`} engine={engine} projectId={projectId} /> : null}+ {engine ? <CanvasEditRefusalNotices key={`${projectId}:edit-refusals`} engine={engine} /> : null}+ {engine ? (+ <CanvasStagedRegionsFeed key={`${projectId}:staged-regions`} engine={engine} projectId={projectId} />+ ) : null}{engine && fontReferences.length > 0 ? (<Suspense fallback={null}><MissingFontsDialog key={projectId} engine={engine} groups={fontReferences} /></Suspense>) : null}<CanvasSurfaceContextLayout surface={canvasSurface} onContextMenu={handleSurfaceContextMenu}>- <CanvasImageDropOverlay isDocumentEditingLocked={isDocumentEditingLocked} />+ <CanvasImageDropOverlay fileDrag={fileDrag} isDocumentEditingLocked={isDocumentEditingLocked} />{engine ? (<><ToolStrip engine={engine} />- <ControlLayerCanvasOverlay engine={engine} />+ <CanvasFrameSizeReadout engine={engine} />+ <ControlLayerCanvasOverlay engine={engine} isFileDragActive={fileDrag !== null} /><CanvasLayerContextMenubeforeDangerItems={compositeSubmenus}engine={engine}@@ -644,7 +622,6 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {selectedSlot={selectedSlot}slots={stagingSlots}onAccept={acceptStagedImage}- onCancelQueueItem={cancelQueueItem}onCycle={cycleStagedImage}onDiscardAll={discardAllStagedImages}onDiscardSelected={discardSelectedStagedImage}@@ -653,6 +630,7 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {onSaveToGallery={saveStagedResult}onSaveToLayerAndContinue={saveStagedImageAndContinue}onSetAutoSwitch={setStagingAutoSwitch}+ onStopGenerating={stagingRecovery.stopGenerating}onToggleThumbnails={toggleStagingThumbnails}onToggleVisibility={toggleStagingVisibility}/>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ControlLayerCanvasOverlay.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ControlLayerCanvasOverlay.tsxindex 50c56894ca..f7a32168f2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ControlLayerCanvasOverlay.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ControlLayerCanvasOverlay.tsx@@ -27,6 +27,7 @@ import {useCanvasActiveTool,useCanvasDocumentEditingLocked,useCanvasEngineRead,+ useCanvasStagingHidesOverlays,useControlDetectionStatus,useControlLayerView,} from './engineStoreHooks';@@ -56,16 +57,27 @@ const TOP_SLOT_TOP = 'var(--wb-center-chrome-inset, var(--chakra-spacing-2))';* top-center chip while its map is detected in the background, and in its place once the map is current, an* Original / Map / Overlay switch comparing the map with the picture it was detected from.*/-export const ControlLayerCanvasOverlay = ({ engine }: { engine: OverlayEngine }) => {+export const ControlLayerCanvasOverlay = ({+ engine,+ isFileDragActive,+}: {+ engine: OverlayEngine;+ /** Files from the desktop are dragged over the canvas, showing the drop zones as a gallery drag does. */+ isFileDragActive: boolean;+}) => {const layer = useActiveProjectSelector(selectSelectedControlLayer);- return layer ? <SelectedControlLayerOverlay engine={engine} layer={layer} /> : null;+ return layer ? (+ <SelectedControlLayerOverlay engine={engine} isFileDragActive={isFileDragActive} layer={layer} />+ ) : null;};const SelectedControlLayerOverlay = ({engine,+ isFileDragActive,layer,}: {engine: OverlayEngine;+ isFileDragActive: boolean;layer: CanvasControlLayerContract;}) => {const { t } = useTranslation();@@ -85,6 +97,7 @@ const SelectedControlLayerOverlay = ({const { notifications } = useWorkbenchCommands();const isDocumentEditingLocked = useCanvasDocumentEditingLocked(engine);const isDisplayed = useActiveProjectSelector(selectSelectedLayerDisplayed);+ const isStagingHidingLayer = useCanvasStagingHidesOverlays(engine);const controlView = useControlLayerView(engine);// The requested view shows at once; the engine's view takes over when the request settles.const [pendingView, setPendingView] = useState<{ layerId: string; mode: ControlLayerViewMode } | null>(null);@@ -124,21 +137,23 @@ const SelectedControlLayerOverlay = ({? getControlImageState(layer, engine.exports.hasExportableLayerContent(layer.id)): persistedState);- const isGalleryDrag = isGalleryImageDragData(active?.data.current);- // Draw hides the hint: the user is about to give the layer its pixels by hand. A gallery drag shows the drop zones- // in its place. An upload on its way (from Properties or a dropped file) keeps the card up, saying so.+ const isImageDrag = isFileDragActive || isGalleryImageDragData(active?.data.current);+ // Draw hides the hint: the user is about to give the layer its pixels by hand. An image dragged from the gallery or+ // the desktop shows the drop zones in its place. An upload from Properties keeps the card up, saying so.const isHintVisible =- imageState === 'empty' && (isUploading || (!isGalleryDrag && activeTool !== 'brush' && activeTool !== 'eraser'));+ imageState === 'empty' && (isUploading || (!isImageDrag && activeTool !== 'brush' && activeTool !== 'eraser'));// Idle status keeps the switch and the detection chip apart: one or the other occupies the slot. The engine refuses- // a view while an operation holds the document, and a layer that does not draw has nothing to compare.+ // a view while an operation holds the document, and a layer that does not draw has nothing to compare: hidden,+ // disabled, or off the screen while a staged result shows only raster layers.const isViewSwitchVisible =layer.original !== undefined &&!!layer.detection &&isControlMapCurrent(layer) &&isDisplayed &&+ !isStagingHidingLayer &&status.status === 'idle' &&!isDocumentEditingLocked &&- !isGalleryDrag;+ !isImageDrag;const detector =status.status === 'processing'? status.detectordiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/DenoisingStrengthWave.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/DenoisingStrengthWave.tsxindex e3ca5bb646..a35b88f63d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/DenoisingStrengthWave.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/DenoisingStrengthWave.tsx@@ -27,7 +27,7 @@ export const getDenoisingStrengthWavePath = (const WAVE_WIDTH = 100;const WAVE_HEIGHT = 14;const WAVE_SEGMENTS = 5;-/** Drawn at the badge text's line height so it sits inside a header badge. */+/** Drawn at the summary text's line height so it sits in a section title row. */const WAVE_DISPLAY_HEIGHT = 10;/** A value-reactive wave whose amplitude shows the denoising strength. */diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.browser.test.tsxnew file mode 100644index 0000000000..9d2d83ae9d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.browser.test.tsx@@ -0,0 +1,103 @@+import type { GenerationUiAdapter } from '@features/generation/react';++import { ChakraProvider } from '@chakra-ui/react';+import { GenerationUiProvider } from '@features/generation/react';+import { createExternalStoreCore } from '@platform/state/externalStoreCore';+import { system } from '@theme/system';+import { DEFAULT_CANVAS_COMPOSITING } from '@workbench/widgets/canvas/invoke/canvasCompositing';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++/** The canvas widget's values, as the workbench holds them. */+const canvas = vi.hoisted(() => ({+ values: null as unknown as ReturnType<typeof createExternalStoreCore<Record<string, unknown>>>,+}));++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@workbench/WorkbenchContext', async () => {+ const { useSyncExternalStore } = await import('react');+ return {+ useActiveProjectId: () => 'project-1',+ useWidgetValuesSelector: <Selected,>(_typeId: string, selector: (values: Record<string, unknown>) => Selected) =>+ useSyncExternalStore(canvas.values.subscribe, () => selector(canvas.values.getSnapshot())),+ useWorkbenchCommands: () => ({+ widgets: {+ patchValues: (_typeId: string, patch: Record<string, unknown>) => canvas.values.patchSnapshot(patch),+ },+ }),+ };+});++import { GenerateCanvasCompositingSection } from './GenerateCanvasCompositingSection';++const generationUi = {+ sectionPreferences: { sectionsOpen: {}, setSectionsOpen: () => undefined },+} as unknown as GenerationUiAdapter;++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const render = async (values: Record<string, unknown>) => {+ canvas.values = createExternalStoreCore<Record<string, unknown>>(values);+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <GenerationUiProvider adapter={generationUi}>+ <GenerateCanvasCompositingSection />+ </GenerationUiProvider>+ </ChakraProvider>+ )+ );+};++const title = () => host!.querySelector<HTMLElement>('.generate-section > [data-part="trigger"]')!;+const openMenu = () =>+ act(() => {+ title().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }));+ });+const resetItem = () => page.getByRole('menuitem', { name: 'widgets.generate.sectionMenu.reset' });++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('GenerateCanvasCompositingSection', () => {+ it('marks its title while a field is off its default, and resets the section from its menu', async () => {+ await render({ coherenceMode: 'Staged', infillMethod: 'color', infillColorValue: { a: 1, b: 255, g: 0, r: 0 } });++ expect(title().querySelector('[data-section-changed]')).not.toBeNull();++ await openMenu();+ await act(() => userEvent.click(resetItem()));++ expect(canvas.values.getSnapshot()).toMatchObject({+ coherenceEdgeSize: DEFAULT_CANVAS_COMPOSITING.coherenceEdgeSize,+ coherenceMinDenoise: DEFAULT_CANVAS_COMPOSITING.coherenceMinDenoise,+ coherenceMode: DEFAULT_CANVAS_COMPOSITING.coherenceMode,+ infillColorValue: DEFAULT_CANVAS_COMPOSITING.infillColorValue,+ infillMethod: DEFAULT_CANVAS_COMPOSITING.infillMethod,+ maskBlur: DEFAULT_CANVAS_COMPOSITING.maskBlur,+ });+ expect(title().querySelector('[data-section-changed]')).toBeNull();+ });++ it('ignores a stored infill color that the chosen infill does not use', async () => {+ await render({+ infillMethod: DEFAULT_CANVAS_COMPOSITING.infillMethod,+ infillColorValue: { a: 1, b: 255, g: 0, r: 0 },+ });++ expect(title().querySelector('[data-section-changed]')).toBeNull();+ await openMenu();+ await expect.element(resetItem()).toHaveAttribute('data-disabled');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsxindex 949fe0104a..41ba191597 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx@@ -6,7 +6,7 @@import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';import type { CanvasCoherenceMode, CanvasInfillMethod } from '@workbench/widgets/canvas/invoke/canvasCompositing';-import { Badge, createListCollection, NumberInput, Stack } from '@chakra-ui/react';+import { createListCollection, NumberInput, Stack } from '@chakra-ui/react';import { GenerationSettingsSection } from '@features/generation/components';import { ColorPicker, Field, formatHexColor, parseHexColor, Select } from '@platform/ui';import { getCanvasEngine } from '@workbench/canvas-operations/api';@@ -14,6 +14,7 @@ import {CANVAS_COHERENCE_EDGE_SIZE_MAX,CANVAS_COMPOSITING_KEYS,CANVAS_MASK_BLUR_MAX,+ DEFAULT_CANVAS_COMPOSITING,readCanvasCompositingSettings,} from '@workbench/widgets/canvas/invoke/canvasCompositing';import { useActiveProjectId, useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';@@ -23,6 +24,16 @@ import { useTranslation } from 'react-i18next';const INFILL_METHODS: readonly CanvasInfillMethod[] = ['patchmatch', 'lama', 'cv2', 'color', 'tile'];const COHERENCE_MODES: readonly CanvasCoherenceMode[] = ['Gaussian Blur', 'Box Blur', 'Staged'];+/** The section's fields besides the infill color, for its changed dot and its reset. */+const SHOWN_VALUE_KEYS = [+ 'infillMethod',+ 'coherenceMode',+ 'coherenceEdgeSize',+ 'coherenceMinDenoise',+ 'maskBlur',+] as const satisfies readonly (keyof typeof CANVAS_COMPOSITING_KEYS)[];+const INFILL_COLOR_CHANNELS = ['r', 'g', 'b', 'a'] as const;+// Match full-width menus to the trigger width and start edge.const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;@@ -130,22 +141,40 @@ export const GenerateCanvasCompositingSection = () => {const opt = (key: string) => t(`widgets.generate.compositingOptions.${key}`);- const badges = (- <>- <Badge>{t(`widgets.generate.compositingOptions.infillMethods.${settings.infillMethod}`)}</Badge>- <Badge>{settings.maskBlur}px</Badge>- </>+ const summary = useMemo(+ () => [t(`widgets.generate.compositingOptions.infillMethods.${settings.infillMethod}`), `${settings.maskBlur}px`],+ [settings.infillMethod, settings.maskBlur, t]+ );+ const defaults = DEFAULT_CANVAS_COMPOSITING;+ // The infill color counts only while color infill uses it.+ const isChanged =+ (settings.infillMethod === 'color' &&+ INFILL_COLOR_CHANNELS.some(+ (channel) => settings.infillColorValue[channel] !== defaults.infillColorValue[channel]+ )) ||+ SHOWN_VALUE_KEYS.some((key) => settings[key] !== defaults[key]);+ const resetToDefaults = useCallback(+ () =>+ patch({+ ...Object.fromEntries(+ SHOWN_VALUE_KEYS.map((key) => [CANVAS_COMPOSITING_KEYS[key], DEFAULT_CANVAS_COMPOSITING[key]])+ ),+ [CANVAS_COMPOSITING_KEYS.infillColorValue]: { ...DEFAULT_CANVAS_COMPOSITING.infillColorValue },+ }),+ [patch]);return (<GenerationSettingsSection- badges={badges}defaultOpen={false}+ isChanged={isChanged}label={t('widgets.generate.compositing')}sectionId="canvas-fill"+ summary={summary}+ onReset={resetToDefaults}>- <Stack gap="2" p="2">- <Field label={opt('infillMethod')}>+ <Stack gap="2.5">+ <Field label={opt('infillMethod')} labelPlacement="inside"><Selectaria-label={opt('infillMethod')}collection={infillCollection}@@ -166,7 +195,7 @@ export const GenerateCanvasCompositingSection = () => {/></Field>) : null}- <Field label={opt('coherenceMode')}>+ <Field label={opt('coherenceMode')} labelPlacement="inside"><Selectaria-label={opt('coherenceMode')}collection={coherenceCollection}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsxindex fa41eba3fc..3f1d065e85 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.browser.test.tsx@@ -71,8 +71,10 @@ vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) =>update: () => undefined,},CanvasRenderSize: harness.slot,+ // The Size section names a base's defaults by its label, as the App adapter's `getModelBaseLabel` does.+ models: { getBaseLabel: (base: string) => base },project: { invocationSourceId: harness.invocationSourceId },- sectionPreferences: { sectionsOpen: { dimensions: true }, setSectionOpen: () => undefined },+ sectionPreferences: { sectionsOpen: { dimensions: true }, setSectionsOpen: () => undefined },}),}));@@ -269,7 +271,9 @@ describe('Size section in canvas mode', () => {// SD 1.5 is optimal at 512x512, so Auto grows this frame.await renderSizeSection(createProject({ frame: { height: 384, width: 384 }, model: SD1_MODEL }));- await expect.element(renderAt()).toHaveTextContent('Optimal for model');+ await expect+ .element(renderAt().element().querySelector<HTMLElement>('[data-part="value-text"]'))+ .toHaveTextContent('Optimal for model');// People who knew the setting by its legacy name find it in the select's description, tooltip open or not.await expect.element(renderAt()).toHaveAccessibleDescription(/^Scale before processing/);expect(badgeText()).toBe('384×384 → 512×512');@@ -277,12 +281,13 @@ describe('Size section in canvas mode', () => {// The stage fits the larger render size: 88px of preview spans 512px.expect(ghostSize()).toEqual([88, 88]);- // The visible label is a pointer target for the select.- await userEvent.click(page.elementLocator(host?.querySelector('label[aria-hidden]') as HTMLElement));- await expect.element(renderAt()).toHaveFocus();- await expect.element(renderAt()).toHaveAttribute('aria-expanded', 'false');-- await chooseRenderAt('Frame size');+ // The label sits inside the select's box, so a click on it opens the select like the rest of the box.+ const label = document.getElementById(renderAt().element().getAttribute('aria-labelledby')!)!;+ expect(renderAt().element().contains(label)).toBe(true);+ expect(label.textContent).toBe('Render at');+ await userEvent.click(page.elementLocator(label));+ await expect.element(renderAt()).toHaveAttribute('aria-expanded', 'true');+ await userEvent.click(page.getByRole('option', { name: 'Frame size' }));expect(canvasValues().scaleMethod).toBe('none');expect(badgeText()).toBe('384×384');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.tsxindex 38b92e174a..66cd75b81b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasRenderSize.tsx@@ -9,12 +9,12 @@ import type { CanvasScaleMethod, CanvasScalingSettings, PidMode } from '@featureimport type { CanvasRenderSizeProps } from '@features/generation/react';import type { Project } from '@workbench/projectContracts';-import { Box, chakra, createListCollection, Grid, HStack, NumberInput, Text } from '@chakra-ui/react';+import { Box, createListCollection, HStack, NumberInput, Stack, Text } from '@chakra-ui/react';import { resolveCanvasProcessingSize } from '@features/generation/canvasProcessingSize';import { getArchitectureCapabilitiesSnapshot, subscribeArchitectureCapabilities } from '@features/generation/runtime';import { clampDimension, getGenerationDimensions, isGenerateModelConfig } from '@features/generation/settings';import { useExternalStoreSelector } from '@platform/state/selectors';-import { FieldLabel, Select, Tooltip } from '@platform/ui';+import { Field, Select, Tooltip } from '@platform/ui';import {CANVAS_SCALE_METHODS,CANVAS_SCALING_KEYS,@@ -23,12 +23,11 @@ import {} from '@workbench/widgets/canvas/invoke/canvasScaling';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';-import { type MouseEvent, useCallback, useId, useMemo } from 'react';+import { useCallback, useId, useMemo } from 'react';import { useTranslation } from 'react-i18next';const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;const SIDE_INPUT_CSS = { flex: '1', minW: '0' } as const;-const VALUE_TEXT_PROPS = { truncate: true } as const;const selectScaling = (project: Project): CanvasScalingSettings =>readCanvasScaling(getProjectWidgetValues(project, 'canvas'));@@ -181,46 +180,30 @@ export const GenerateCanvasRenderSize = ({ children, frame }: CanvasRenderSizePrconst label = t('widgets.generate.renderSize.label');// The tooltip's trigger is the wrapper, so the select points at an always-present copy of the tip itself.const descriptionId = useId();- const triggerId = useId();- const selectIds = useMemo(() => ({ trigger: triggerId }), [triggerId]);const triggerProps = useMemo(() => ({ 'aria-describedby': descriptionId }), [descriptionId]);const description = t('widgets.generate.renderSize.description');- // Like a native select's label, a click focuses the select rather than activating (opening) it.- const focusSelect = useCallback(- (event: MouseEvent<HTMLLabelElement>) => {- event.preventDefault();- document.getElementById(triggerId)?.focus();- },- [triggerId]- );- // Custom's sides sit under the select they belong to, so the grid keeps the label in its own column.const controls = (- <Grid alignItems="center" columnGap="2" rowGap="1.5" templateColumns="fit-content(40%) minmax(0, 1fr)">- {/* The select carries the same name for assistive technology; this copy is what sighted people read and click. */}- <chakra.label aria-hidden cursor="default" htmlFor={triggerId} onClick={focusSelect}>- <FieldLabel>{label}</FieldLabel>- </chakra.label>+ <Stack gap="1.5" minW="0">{/* The legacy name for this setting lives in the tooltip, so people who knew it can still find it. */}<Tooltip content={description} placement="top"><Box minW="0"><Text id={descriptionId} srOnly>{description}</Text>- <Select- aria-label={label}- collection={methodCollection}- ids={selectIds}- positioning={SELECT_POSITIONING}- triggerProps={triggerProps}- value={methodValue}- valueText={methodLabel(scaling.method)}- valueTextProps={VALUE_TEXT_PROPS}- onValueChange={handleMethodChange}- />+ <Field label={label} labelPlacement="inside">+ <Select+ collection={methodCollection}+ positioning={SELECT_POSITIONING}+ triggerProps={triggerProps}+ value={methodValue}+ valueText={methodLabel(scaling.method)}+ onValueChange={handleMethodChange}+ />+ </Field></Box></Tooltip>{scaling.method === 'manual' ? (- <HStack gap="1" gridColumn="2" minW="0">+ <HStack gap="1" minW="0">{sideInput(t('widgets.generate.renderSize.width'), scaling.width ?? context.bbox.width, widthHandlers)}<Text aria-hidden color="fg.muted" flexShrink="0" fontSize="xs">×@@ -228,7 +211,7 @@ export const GenerateCanvasRenderSize = ({ children, frame }: CanvasRenderSizePr{sideInput(t('widgets.generate.renderSize.height'), scaling.height ?? context.bbox.height, heightHandlers)}</HStack>) : null}- </Grid>+ </Stack>);return children({ controls, size: processingSize });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.browser.test.tsxindex cf5095ca5d..a34b62e8ba 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.browser.test.tsx@@ -28,7 +28,7 @@ vi.mock('@workbench/WorkbenchContext', async () => {import { GenerateDenoisingStrength } from './GenerateDenoisingStrength';const generationUi = {- sectionPreferences: { sectionsOpen: {}, setSectionOpen: () => undefined },+ sectionPreferences: { sectionsOpen: {}, setSectionsOpen: () => undefined },} as unknown as GenerationUiAdapter;let host: HTMLDivElement | null = null;@@ -41,7 +41,7 @@ const Section = ({ slots }: { slots: CanvasDenoisingStrength }) => {sectionRendered();return (<div>- <div data-testid="header">{slots.badges}</div>+ <div data-testid="header">{slots.summary}</div>{slots.field}</div>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.tsxindex c67465e023..455e233a4f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateDenoisingStrength.tsx@@ -1,7 +1,7 @@import type { CanvasDenoisingStrength, CanvasDenoisingStrengthProps } from '@features/generation/react';import type { ReactNode } from 'react';-import { Badge } from '@chakra-ui/react';+import { HStack } from '@chakra-ui/react';import { useDebouncedDraftValue, useRegisterGenerateDraftFlusher } from '@features/generation/react';import { ScrubberField } from '@platform/ui/ScrubberField';import {@@ -44,7 +44,7 @@ const useStrengthDraft = (): StrengthDraft => {/*** Owns the strength draft: persists it in canvas widget values after a debounce and flushes it with the Generate* form before invocation. Its `children` keep their element identity across draft changes, so a scrub re-renders- * only the badge and field that read the draft, not the section laid out around them.+ * only the summary and field that read the draft, not the section laid out around them.*/const StrengthDraftProvider = ({ children }: { children: ReactNode }) => {const { widgets } = useWorkbenchCommands();@@ -75,13 +75,13 @@ const StrengthDraftProvider = ({ children }: { children: ReactNode }) => {return <StrengthDraftContext value={draft}>{children}</StrengthDraftContext>;};-const StrengthBadge = () => {+const StrengthSummary = () => {const { value } = useStrengthDraft();return (- <Badge gap="1.5">+ <HStack as="span" display="inline-flex" gap="1.5" verticalAlign="middle">{formatStrengthPercent(value)}<DenoisingStrengthWave value={value} />- </Badge>+ </HStack>);};@@ -103,9 +103,9 @@ const StrengthField = () => {);};-const STRENGTH_SLOTS: CanvasDenoisingStrength = { badges: <StrengthBadge />, field: <StrengthField /> };+const STRENGTH_SLOTS: CanvasDenoisingStrength = { field: <StrengthField />, summary: <StrengthSummary /> };-/** Lays out the Render section with canvas denoising strength: its badge in the header, its control under guidance. */+/** Lays out the Render section with canvas denoising strength: its summary in the title, its control under guidance. */export const GenerateDenoisingStrength = ({ children }: CanvasDenoisingStrengthProps) => (<StrengthDraftProvider>{children(STRENGTH_SLOTS)}</StrengthDraftProvider>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsxindex 9517bb6dfa..c3b7802a6d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.browser.test.tsx@@ -1,10 +1,15 @@import '@fontsource/inter/index.css';/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import type { QueueItemProgress } from '@features/queue/contracts';+import type { CanvasProjectMutation } from '@workbench/canvas-engine/api';import type { CanvasStagingSlot } from '@workbench/canvasStagingView';+import type { WorkbenchState } from '@workbench/projectContracts';+import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';import { Box, ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';+import { getCanvasStagingSlots } from '@workbench/canvasStagingView';+import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { createInstance } from 'i18next';import { act, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -16,6 +21,7 @@ import { CanvasBottomOverlay } from './CanvasBottomOverlay';import { StagingBar } from './StagingBar';const contextMenu = vi.hoisted(() => ({+ loadRecall: vi.fn(),targets: [] as { slotId: string; x: number; y: number }[],}));const queueProgress = vi.hoisted(() => ({ current: null as QueueItemProgress | null }));@@ -24,6 +30,7 @@ vi.mock('@features/queue/react', async (importOriginal) => ({useQueueItemProgress: () => queueProgress.current,}));vi.mock('./StagingItemContextMenu', () => ({+ loadStagingItemRecall: contextMenu.loadRecall,StagingItemContextMenu: ({onClose,target,@@ -105,6 +112,7 @@ const renderStagingBar = async (isGenerating = false,isSavingToGallery = false,onAccept = noop,+ onStopGenerating = noop,onCycle = noop,onDiscardSelected = noop,onSaveToGallery = () => Promise.resolve(),@@ -113,6 +121,7 @@ const renderStagingBar = async (isGenerating?: boolean;isSavingToGallery?: boolean;onAccept?: () => void;+ onStopGenerating?: () => void;onCycle?: (direction: -1 | 1) => void;onDiscardSelected?: () => void;onSaveToGallery?: (imageName: string) => Promise<void>;@@ -148,7 +157,6 @@ const renderStagingBar = async (selectedSlot={selectedSlot}slots={slots}onAccept={onAccept}- onCancelQueueItem={noop}onCycle={onCycle}onDiscardAll={noop}onDiscardSelected={onDiscardSelected}@@ -157,6 +165,7 @@ const renderStagingBar = async (onSaveToGallery={onSaveToGallery}onSaveToLayerAndContinue={onSaveToLayerAndContinue}onSetAutoSwitch={noop}+ onStopGenerating={onStopGenerating}onToggleThumbnails={noop}onToggleVisibility={noop}/>@@ -272,6 +281,19 @@ describe('StagingBar thumbnail strip', () => {expect(document.querySelector('[data-testid="staging-context-menu"]')).not.toBeNull();});+ it("warms a staged result's recall verbs when it is pointed at or focused", async () => {+ const { thumbnails } = await renderStagingBar(3, 0);++ for (const event of [+ new PointerEvent('pointerover', { bubbles: true }),+ new FocusEvent('focusin', { bubbles: true }),+ ]) {+ contextMenu.loadRecall.mockClear();+ await interact(() => thumbnails[1]!.dispatchEvent(event));+ expect(contextMenu.loadRecall).toHaveBeenCalled();+ }+ });+it('shows the spinner on the executing placeholder until its progress is known', async () => {const indicators = () => [...host!.querySelectorAll('[role="progressbar"]')];const remount = async () => {@@ -452,11 +474,18 @@ describe('StagingBar thumbnail strip', () => {await expect.element(page.getByRole('button', { exact: true, name: 'Save to gallery' })).toBeDisabled();});+ const visibleStopButtons = (overlay: HTMLElement) =>+ [...overlay.querySelectorAll<HTMLButtonElement>('button')].filter(+ (button) =>+ (button.getAttribute('aria-label') ?? button.textContent?.trim()) ===+ i18n.t('widgets.canvas.staging.stopGenerating') && button.getBoundingClientRect().width > 0+ );+it.each([- { canvasWidth: 800, iconOnly: false },+ { canvasWidth: 1000, iconOnly: false },{ canvasWidth: 360, iconOnly: true },])(- 'shows one Cancel for a running slot at $canvasWidth px, labelled only when there is room',+ 'shows one Stop generating at $canvasWidth px, labelled only when there is room',async ({ canvasWidth, iconOnly }) => {const { overlay } = await renderStagingBar(2,@@ -467,20 +496,69 @@ describe('StagingBar thumbnail strip', () => {(index) => (index === 0 ? makeSlot(index) : makePlaceholder(index)),{ canvasWidth, isGenerating: true });- const visibleCancels = [...overlay.querySelectorAll<HTMLButtonElement>('button')].filter(- (button) =>- (button.getAttribute('aria-label') ?? button.textContent?.trim()) === 'Cancel' &&- button.getBoundingClientRect().width > 0- );+ const stops = visibleStopButtons(overlay);- expect(visibleCancels).toHaveLength(1);- // The icon-only one carries its name (and so its tooltip); the labelled one shows the word itself.- expect(visibleCancels[0]!.hasAttribute('aria-label')).toBe(iconOnly);- expect(visibleCancels[0]!.getBoundingClientRect().right).toBeLessThanOrEqual(- overlay.getBoundingClientRect().right- );+ expect(stops).toHaveLength(1);+ // The icon-only one carries its name (and so its tooltip); the labelled one shows the words themselves.+ expect(stops[0]!.hasAttribute('aria-label')).toBe(iconOnly);+ expect(stops[0]!.getBoundingClientRect().right).toBeLessThanOrEqual(overlay.getBoundingClientRect().right);});++ it('keeps a long Stop generating label and every result action inside a wide canvas', async () => {+ i18n.addResource(+ 'en',+ 'translation',+ 'widgets.canvas.staging.stopGenerating',+ 'Stop generating the remaining images'+ );+ try {+ const { overlay } = await renderStagingBar(+ 3,+ 0,+ noop,+ noop,+ noop,+ (index) => (index === 0 ? makeSlot(index) : makePlaceholder(index)),+ { canvasWidth: 1000, isGenerating: true }+ );+ const bounds = overlay.getBoundingClientRect();++ expect(visibleStopButtons(overlay)[0]?.textContent?.trim()).toBe('Stop generating the remaining images');+ for (const control of overlay.querySelectorAll<HTMLElement>('button')) {+ const rect = control.getBoundingClientRect();+ if (rect.width > 1 && !control.closest('[data-scope="scroll-area"]')) {+ expect(rect.left).toBeGreaterThanOrEqual(bounds.left);+ expect(rect.right).toBeLessThanOrEqual(bounds.right);+ }+ }+ } finally {+ i18n.addResource('en', 'translation', 'widgets.canvas.staging.stopGenerating', 'Stop generating');+ }+ });++ it('stops generating while a finished result is selected and the next image of its run starts', async () => {+ const onStopGenerating = vi.fn();+ await renderStagingBar(+ 2,+ 0,+ noop,+ noop,+ noop,+ (index) => (index === 0 ? makeSlot(index) : makePlaceholder(index)),+ { isGenerating: true, onStopGenerating }+ );++ await page.getByRole('button', { exact: true, name: 'Stop generating' }).click();++ expect(onStopGenerating).toHaveBeenCalledOnce();+ });++ it('offers no Stop generating once every image has finished', async () => {+ const { overlay } = await renderStagingBar(2, 0);++ expect(visibleStopButtons(overlay)).toEqual([]);+ });});describe('StagingBar focus', () => {@@ -518,7 +596,6 @@ describe('StagingBar focus', () => {selectedSlot={selected}slots={remaining}onAccept={noop}- onCancelQueueItem={noop}onCycle={noop}onDiscardAll={() => setRemaining([])}onDiscardSelected={discardSelected}@@ -527,6 +604,7 @@ describe('StagingBar focus', () => {onSaveToGallery={() => Promise.resolve()}onSaveToLayerAndContinue={noop}onSetAutoSwitch={noop}+ onStopGenerating={() => setRemaining((current) => current.filter((slot) => slot.kind === 'candidate'))}onToggleThumbnails={noop}onToggleVisibility={noop}/>@@ -537,7 +615,7 @@ describe('StagingBar focus', () => {);};- const renderCanvas = async (slotCount: number) => {+ const renderCanvas = async (slotCount: number, slotAt: (index: number) => CanvasStagingSlot = makeSlot) => {host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -545,7 +623,7 @@ describe('StagingBar focus', () => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <CanvasWithStaging slots={Array.from({ length: slotCount }, (_, index) => makeSlot(index))} />+ <CanvasWithStaging slots={Array.from({ length: slotCount }, (_, index) => slotAt(index))} /></ChakraProvider></I18nextProvider>)@@ -575,6 +653,16 @@ describe('StagingBar focus', () => {expect(document.activeElement).toBe(surface);});+ it('keeps focus with the results when Stop generating goes with the last image still to come', async () => {+ const { thumbnails } = await renderCanvas(2, (index) => (index === 0 ? makeSlot(index) : makePlaceholder(index)));++ await userEvent.click(page.getByRole('button', { exact: true, name: 'Stop generating' }));+ await nextFrame();++ expect(page.getByRole('button', { exact: true, name: 'Stop generating' }).elements()).toEqual([]);+ expect(document.activeElement).toBe(thumbnails()[0]);+ });+it('returns focus to the thumbnail a dismissed menu opened from', async () => {const { thumbnails } = await renderCanvas(3);@@ -600,17 +688,19 @@ describe('StagingBar keys', () => {return { reached, stop: () => window.removeEventListener('keydown', listener) };};- it('selects the thumbnail the keyboard is on and steps focus between thumbnails, keeping keys from the canvas', async () => {+ it('picks with the arrows, moving focus with the pick, and keeps keys from the canvas', async () => {const onCycle = vi.fn();const onSelectImage = vi.fn();const { thumbnails } = await renderStagingBar(3, 0, noop, noop, onSelectImage, makeSlot, { onCycle });const window = watchWindow();try {- await act(() => thumbnails[1]!.focus());- expect(onSelectImage).toHaveBeenLastCalledWith(1);+ // Focus alone picks nothing.+ await act(() => thumbnails[0]!.focus());+ expect(onSelectImage).not.toHaveBeenCalled();+ await act(() => userEvent.keyboard('{ArrowRight}'));+ expect(document.activeElement).toBe(thumbnails[1]);await act(() => userEvent.keyboard('{ArrowRight}'));expect(document.activeElement).toBe(thumbnails[2]);- expect(onSelectImage).toHaveBeenLastCalledWith(2);// Wrapping, as the step buttons do.await act(() => userEvent.keyboard('{ArrowRight}'));expect(document.activeElement).toBe(thumbnails[0]);@@ -620,10 +710,17 @@ describe('StagingBar keys', () => {window.stop();}+ expect(onSelectImage.mock.calls).toEqual([[1], [2], [0], [2]]);expect(onCycle).not.toHaveBeenCalled();expect(window.reached).toEqual([]);});+ it('takes one Tab stop for the strip: the selected thumbnail', async () => {+ const { thumbnails } = await renderStagingBar(3, 1);++ expect(thumbnails.map((thumbnail) => thumbnail.tabIndex)).toEqual([-1, 0, -1]);+ });+it('steps the selection from the bar buttons, and Delete discards the selected result', async () => {const onCycle = vi.fn();const onDiscardSelected = vi.fn();@@ -678,3 +775,211 @@ describe('StagingBar keys', () => {expect(window.reached).toEqual(['Alt', 'ArrowRight', 'b']);});});++describe('StagingBar picks and Auto-switch', () => {+ type Mode = 'latest' | 'off' | 'progress';++ /** A run of three images on the canvas: two results staged, the third still generating. */+ const createStagedState = (mode: Mode): WorkbenchState => {+ const state = createInitialWorkbenchState();+ const project = state.projects[0]!;+ const result = (backendItemId: number) => ({+ height: 512,+ imageName: `result-${backendItemId}`,+ imageUrl: TRANSPARENT_PIXEL,+ placement: { height: 512, opacity: 1, width: 512, x: 0, y: 0 },+ queuedAt: '2026-01-01T00:00:00.000Z',+ sourceBackendItemId: backendItemId,+ sourceQueueItemId: 'run-1',+ thumbnailUrl: TRANSPARENT_PIXEL,+ width: 512,+ });+ const run = {+ backendItemIds: [11, 12, 13],+ cancellable: true,+ completedBackendItemIds: [11, 12],+ id: 'run-1',+ snapshot: {+ canvas: {+ document: { bbox: { height: 512, width: 512, x: 0, y: 0 }, height: 1024, width: 1024 },+ documentRevision: project.canvas.documentRevision,+ },+ destination: 'canvas',+ graph: { id: 'graph', label: 'Generate' },+ presentation: { batchCount: 3, height: 512, width: 512 },+ sourceId: 'generate',+ submittedAt: '2026-01-01T00:00:00.000Z',+ },+ status: 'running',+ } as unknown as WorkbenchQueueItem;+ const pendingImages = [result(11), result(12)];++ return {+ ...state,+ projects: [+ {+ ...project,+ canvas: {+ ...project.canvas,+ stagingArea: {+ ...project.canvas.stagingArea,+ autoSwitchMode: mode,+ isVisible: true,+ pendingImageIds: pendingImages.map((image) => image.imageName),+ pendingImages,+ selectedImageIndex: 1,+ },+ },+ queue: { items: [run] },+ },+ ],+ };+ };++ /** The bar wired to the workbench reducer, as the canvas widget wires it. */+ const WiredStagingBar = ({ initial }: { initial: WorkbenchState }) => {+ const [state, setState] = useState(initial);+ const project = state.projects[0]!;+ const { stagingArea } = project.canvas;+ const slots = getCanvasStagingSlots(project.canvas, project.queue.items);+ const selectedSlot = slots[stagingArea.selectedImageIndex];+ const mutate = (mutation: CanvasProjectMutation) =>+ setState((current) =>+ workbenchReducer(current, { mutation, projectId: project.id, type: 'applyCanvasProjectMutation' })+ );++ return (+ <Box h="400px" position="relative" w={`${CANVAS_WIDTH}px`}>+ {/* Where Tab starts from: the canvas, before the bar. */}+ <button data-testid="before-bar" type="button">+ Canvas+ </button>+ <CanvasBottomOverlay.Root>+ <CanvasBottomOverlay.Staging>+ <StagingBar+ antialiasProgressImages={false}+ areThumbnailsVisible+ autoSwitchMode={stagingArea.autoSwitchMode}+ canAccept+ hasMultipleSlots={slots.length > 1}+ isGenerating+ isSavingToGallery={false}+ isVisible+ selectedCandidate={selectedSlot?.kind === 'candidate' ? selectedSlot.candidate : undefined}+ selectedImageIndex={stagingArea.selectedImageIndex}+ selectedSlot={selectedSlot}+ slots={slots}+ onAccept={noop}+ onCycle={(direction) => mutate({ direction, type: 'cycleStagedImage' })}+ onDiscardAll={noop}+ onDiscardSelected={noop}+ onPreloadCandidate={noop}+ onSelectImage={(imageIndex) => mutate({ imageIndex, type: 'setStagedImageIndex' })}+ onSaveToGallery={() => Promise.resolve()}+ onSaveToLayerAndContinue={noop}+ onSetAutoSwitch={(mode) => mutate({ mode, type: 'setCanvasStagingAutoSwitch' })}+ onStopGenerating={noop}+ onToggleThumbnails={noop}+ onToggleVisibility={noop}+ />+ </CanvasBottomOverlay.Staging>+ </CanvasBottomOverlay.Root>+ </Box>+ );+ };++ const renderWired = async (mode: Mode) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await interact(() =>+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <WiredStagingBar initial={createStagedState(mode)} />+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ };+ const autoSwitch = () => page.getByRole('button', { name: /^Auto-switch:/ });+ const thumbnail = (number: number) =>+ page.getByRole('button', { exact: true, name: `Select staged candidate ${number}` });++ it.each(['latest', 'progress'] as const)(+ 'clicking off the newest result under %s turns Auto-switch Off',+ async (mode) => {+ await renderWired(mode);++ await thumbnail(1).click();++ await expect.element(autoSwitch()).toHaveAccessibleName('Auto-switch: Off');+ await expect.element(thumbnail(1)).toHaveAttribute('aria-current', 'true');+ }+ );++ it('passes the strip with Tab in one stop, picking nothing and leaving Auto-switch as it was', async () => {+ await renderWired('latest');+ const visited: Element[] = [];++ await act(() => host!.querySelector<HTMLElement>('[data-testid="before-bar"]')!.focus());+ for (let step = 0; step < 12; step += 1) {+ await userEvent.keyboard('{Tab}');+ if (document.activeElement) {+ visited.push(document.activeElement);+ }+ }++ const thumbnailsVisited = visited.filter((element) => element.hasAttribute('data-staging-thumbnail'));+ expect(new Set(thumbnailsVisited).size).toBe(1);+ expect(thumbnailsVisited[0]?.getAttribute('aria-label')).toBe('Select staged candidate 2');+ expect(visited.some((element) => element.getAttribute('aria-label') === 'Accept to layer')).toBe(true);+ await expect.element(autoSwitch()).toHaveAccessibleName('Auto-switch: Newest');+ await expect.element(thumbnail(2)).toHaveAttribute('aria-current', 'true');+ });++ it('an arrow from the selected thumbnail is a pick: off the newest, Auto-switch turns Off', async () => {+ await renderWired('latest');++ await act(() => (thumbnail(2).element() as HTMLElement).focus());+ await userEvent.keyboard('{ArrowLeft}');++ await expect.element(autoSwitch()).toHaveAccessibleName('Auto-switch: Off');+ await expect.element(thumbnail(1)).toHaveAttribute('aria-current', 'true');+ expect(document.activeElement).toBe(thumbnail(1).element());+ });++ it("right-clicking an older result's thumbnail is a pick too", async () => {+ await renderWired('progress');++ await act(() => {+ thumbnail(1)+ .element()+ .dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 }));+ });++ await expect.element(autoSwitch()).toHaveAccessibleName('Auto-switch: Off');+ await expect.element(thumbnail(1)).toHaveAttribute('aria-current', 'true');+ });++ it('stepping off the newest result with the bar arrows turns Auto-switch Off', async () => {+ await renderWired('latest');++ await page.getByRole('button', { exact: true, name: 'Previous staged candidate' }).click();++ await expect.element(autoSwitch()).toHaveAccessibleName('Auto-switch: Off');+ await expect.element(thumbnail(1)).toHaveAttribute('aria-current', 'true');+ });++ it.each(['off', 'latest', 'progress'] as const)(+ 'clicking the image still generating under %s follows it: Auto-switch In progress',+ async (mode) => {+ await renderWired(mode);++ await thumbnail(3).click();++ await expect.element(autoSwitch()).toHaveAccessibleName('Auto-switch: In progress');+ await expect.element(thumbnail(3)).toHaveAttribute('aria-current', 'true');+ }+ );+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsxindex f3335a6dd2..605f41d942 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingBar.tsx@@ -11,7 +11,6 @@ import { ProgressBadge } from '@platform/ui/ProgressBadge';import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';import { 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 {@@ -37,7 +36,11 @@ import {import { useTranslation } from 'react-i18next';import { CanvasFloatingBarDivider } from './CanvasFloatingBar';-import { StagingItemContextMenu, type StagingItemContextMenuTarget } from './StagingItemContextMenu';+import {+ loadStagingItemRecall,+ StagingItemContextMenu,+ type StagingItemContextMenuTarget,+} from './StagingItemContextMenu';import { CANVAS_SURFACE_ATTR } from './surfaceFocus';type AutoSwitchMode = CanvasStagingAreaContractV2['autoSwitchMode'];@@ -71,9 +74,10 @@ const COMPACT_SR_ONLY_CSS = { [COMPACT]: SR_ONLY } as const;const NARROW_SR_ONLY_CSS = { [NARROW]: SR_ONLY } as const;/** Gone while narrow: group rules (the icons' spacing still separates the groups) and labelled buttons. */const NARROW_HIDDEN_CSS = { [NARROW]: { display: 'none' } } as const;-const NARROW_ONLY_CSS = { display: 'none', [NARROW]: { display: 'inline-flex' } } as const;/** Buttons whose text goes while narrow keep a square icon footprint. */const NARROW_ICON_BUTTON_CSS = { [NARROW]: { minW: '8', px: '0' } } as const;+/** Closer controls once narrow: a finished result's actions and Stop generating fit side by side. */+const NARROW_BAR_CSS = { [NARROW]: { gap: '0.5' } } as const;/** Marks a thumbnail with its slot index, for roving focus and focus restore. */const THUMBNAIL_ATTR = 'data-staging-thumbnail';/** Marks the previous/next buttons, a focus target once no thumbnail shows. */@@ -97,7 +101,8 @@ interface StagingBarProps {selectedSlot: CanvasStagingSlot | undefined;slots: CanvasStagingSlot[];onAccept: () => void;- onCancelQueueItem: (queueItemId: string) => void;+ /** Stops every run still generating results for this canvas. */+ onStopGenerating: () => void;onCycle: (direction: -1 | 1) => void;onDiscardAll: () => void;onDiscardSelected: () => void;@@ -129,7 +134,6 @@ export const StagingBar = ({selectedSlot,slots,onAccept,- onCancelQueueItem,onCycle,onDiscardAll,onDiscardSelected,@@ -138,6 +142,7 @@ export const StagingBar = ({onSaveToGallery,onSaveToLayerAndContinue,onSetAutoSwitch,+ onStopGenerating,onToggleThumbnails,onToggleVisibility,}: StagingBarProps) => {@@ -151,7 +156,9 @@ export const StagingBar = ({setContextMenuTarget(null);}const hasSlots = slots.length > 0;- const cancelableQueueItemId = getCancelableCanvasStagingQueueItemId(selectedSlot);+ // Whatever is selected: a finished result stays selected while the next image of its run starts.+ const canStopGenerating = slots.some((slot) => slot.kind === 'placeholder');+ const stopGeneratingLabel = t('widgets.canvas.staging.stopGenerating');const acceptLabel = t('widgets.canvas.acceptToLayer');const acceptMenuIds = useTooltipTriggerIds();const thumbnailsLabel = areThumbnailsVisible@@ -200,6 +207,11 @@ export const StagingBar = ({onDiscardAll();keepFocusWithResults();};+ // The button goes with the last placeholder; focus stays with the results.+ const stopGenerating = () => {+ onStopGenerating();+ keepFocusWithResults();+ };// A menu with no trigger restores focus nowhere; send it back to the thumbnail it opened from.const closeContextMenu = () => {const slotId = contextMenuTarget?.slot.id;@@ -210,9 +222,9 @@ export const StagingBar = ({});};- // With focus in the bar, the arrows step through results and Delete discards the focused one, which is the- // selected one (focusing a thumbnail selects it); the canvas's own keys (nudge, delete the layer or selected- // pixels) never act on the document from here.+ // With focus in the bar, the arrows step through results and Delete discards the selected one (the thumbnail Tab or+ // an arrow puts focus on); the canvas's own keys (nudge, delete the layer or selected pixels) never act on the+ // document from here.const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {if (event.altKey ||@@ -236,10 +248,11 @@ export const StagingBar = ({const direction = event.key === 'ArrowLeft' ? -1 : 1;const index = thumbnail ? Number(thumbnail.getAttribute(THUMBNAIL_ATTR)) : Number.NaN;if (Number.isInteger(index)) {- // Roving focus: the next thumbnail takes focus, which selects it.- event.currentTarget- .querySelector<HTMLElement>(`[${THUMBNAIL_ATTR}="${(index + direction + slots.length) % slots.length}"]`)- ?.focus();+ // Roving focus: an arrow is the pick (it steers Auto-switch), and focus goes with it. Tab only ever reaches+ // the selected thumbnail, so passing through the strip picks nothing.+ const next = (index + direction + slots.length) % slots.length;+ onSelectImage(next);+ event.currentTarget.querySelector<HTMLElement>(`[${THUMBNAIL_ATTR}="${next}"]`)?.focus();} else {onCycle(direction);}@@ -307,6 +320,7 @@ export const StagingBar = ({antialiasProgressImages={antialiasProgressImages}index={index}isSelected={index === selectedImageIndex}+ isTabStop={areThumbnailsVisible}slot={slot}onContextMenu={(event) => {if (slot.kind !== 'candidate') {@@ -337,14 +351,40 @@ export const StagingBar = ({</ScrollArea.Root>) : null}- <CanvasOptionsBar>+ <CanvasOptionsBar css={NARROW_BAR_CSS}>+ {/* First, beside the status it acts on and away from the result's own actions: it stops every run still+ generating for this canvas, not the result shown. Labelled while there is room, an icon once compact. */}+ {canStopGenerating ? (+ <>+ {/* The one label that gives way to a long translation: it shortens, and the tooltip says it in full. */}+ <Tooltip content={stopGeneratingLabel}>+ <Button css={WIDE_ONLY_CSS} flexShrink="1" minW="0" variant="ghost" onClick={stopGenerating}>+ <CircleStopIcon />+ <Box as="span" minW="0" truncate>+ {stopGeneratingLabel}+ </Box>+ </Button>+ </Tooltip>+ <Tooltip content={stopGeneratingLabel}>+ <IconButton+ aria-label={stopGeneratingLabel}+ css={COMPACT_ONLY_CSS}+ variant="ghost"+ onClick={stopGenerating}+ >+ <CircleStopIcon />+ </IconButton>+ </Tooltip>+ </>+ ) : null}+{/* Results keep coming in and waiting here while the canvas stays editable; the status says how many. */}<Tooltip content={statusLabel}><HStackcolor="fg.muted"// Once compact a running batch keeps its spinner; otherwise the status goes, since the counter shows the- // count, and it still reads the sentence.- css={isGenerating ? undefined : COMPACT_SR_ONLY_CSS}+ // count, and it still reads the sentence. Once narrow, the stop button's icon says a run is going in its place.+ css={isGenerating ? (canStopGenerating ? NARROW_SR_ONLY_CSS : undefined) : COMPACT_SR_ONLY_CSS}flexShrink="0"gap="1.5"position="relative"@@ -417,31 +457,6 @@ export const StagingBar = ({onChange={onSetAutoSwitch}/>- {cancelableQueueItemId ? (- <>- {/* Labelled while there is room; an icon with the tooltip once narrow, as Discard all does. */}- <Button- css={NARROW_HIDDEN_CSS}- flexShrink="0"- variant="ghost"- onClick={() => onCancelQueueItem(cancelableQueueItemId)}- >- <CircleStopIcon />- {t('common.cancel')}- </Button>- <Tooltip content={t('common.cancel')}>- <IconButton- aria-label={t('common.cancel')}- css={NARROW_ONLY_CSS}- variant="ghost"- onClick={() => onCancelQueueItem(cancelableQueueItemId)}- >- <CircleStopIcon />- </IconButton>- </Tooltip>- </>- ) : null}-{selectedCandidate ? (<><Tooltip@@ -550,6 +565,7 @@ const StagingThumbnail = ({antialiasProgressImages,index,isSelected,+ isTabStop,slot,onContextMenu,onPreloadCandidate,@@ -558,6 +574,8 @@ const StagingThumbnail = ({antialiasProgressImages: boolean;index: number;isSelected: boolean;+ /** Whether the strip takes a Tab stop at all: not while its thumbnails are hidden. */+ isTabStop: boolean;slot: CanvasStagingSlot;onContextMenu: (event: ReactMouseEvent<HTMLElement>) => void;onPreloadCandidate: (imageName: string) => void;@@ -599,10 +617,13 @@ const StagingThumbnail = ({rounded="md"shadow={isSelected ? '0 0 0 1px {colors.accent.solid}' : 'md'}style={{ aspectRatio: '1 / 1' }}+ // One stop for the strip: the selected thumbnail; the arrows move between them.+ tabIndex={isSelected && isTabStop ? 0 : -1}onClick={onSelect}onContextMenu={onContextMenu}- // Focus follows selection: the bar's keys act on the thumbnail the keyboard is on.- onFocus={isSelected ? undefined : onSelect}+ // A staged result's menu offers recall; warm it on intent.+ onFocus={slot.kind === 'candidate' ? loadStagingItemRecall : undefined}+ onPointerEnter={slot.kind === 'candidate' ? loadStagingItemRecall : undefined}>{slot.kind === 'candidate' ? (<imgdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsxindex 8034a27a0c..dbb1bac31c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.browser.test.tsx@@ -1,3 +1,4 @@+import type * as MenuModule from '@platform/ui/Menu';import type { CanvasCandidateSlot } from '@workbench/canvasStagingView';import type { ImageRecallCapabilities, ImageRecallKind } from '@workbench/image-actions';import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';@@ -7,10 +8,35 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { page } from 'vitest/browser';-import { StagingItemContextMenu } from './StagingItemContextMenu';+import { loadStagingItemRecall, StagingItemContextMenu } from './StagingItemContextMenu';++// Each test starts with the verbs unloaded, as a page does: the loader the module creates is swapped for a fresh one.+const menuParts = vi.hoisted(() => ({+ loaders: [] as { getSnapshot: () => { status: string }; reset: () => void }[],+}));+vi.mock('@platform/ui/Menu', async (importOriginal) => {+ const original = await importOriginal<typeof MenuModule>();++ return {+ ...original,+ createMenuPartLoader: <Part,>(importPart: () => Promise<Part>) => {+ let current = original.createMenuPartLoader(importPart);+ const loader = {+ getSnapshot: () => current.getSnapshot(),+ load: () => current.load(),+ reset: () => {+ current = original.createMenuPartLoader(importPart);+ },+ subscribe: (listener: () => void) => current.subscribe(listener),+ };+ menuParts.loaders.push(loader);+ return loader;+ },+ };+});const mocks = vi.hoisted(() => ({capabilities: {@@ -52,7 +78,7 @@ vi.mock('@workbench/queue-integration/useQueueItemRecall', () => ({useQueueItemRecall: (origin: string, meta: unknown) => {mocks.origin = origin;mocks.meta = meta;- return { capabilities: mocks.capabilities, isPending: false, recall: mocks.recall };+ return { capabilities: mocks.capabilities, isPending: false, reasons: {}, recall: mocks.recall };},}));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));@@ -136,6 +162,20 @@ const render = async (handlers: Partial<Parameters<typeof StagingItemContextMenu);};+// The verbs' first load transforms their module graph, which can outlast `vi.waitFor`'s default second.+const COLD_LOAD = { timeout: 10_000 };++/** Warms the verbs as the staging bar does when a result is pointed at, and waits for them to load. */+const loadRecall = async () => {+ await act(() => loadStagingItemRecall());+ await vi.waitFor(+ () => expect(menuParts.loaders.map((loader) => loader.getSnapshot().status)).toEqual(['loaded']),+ COLD_LOAD+ );+};++beforeEach(() => menuParts.loaders.forEach((loader) => loader.reset()));+afterEach(async () => {await act(() => root?.unmount());host?.remove();@@ -146,9 +186,10 @@ afterEach(async () => {describe('StagingItemContextMenu', () => {it('recalls from the staged result’s own queue item and disables verbs its snapshot cannot back', async () => {+ // Nothing warmed the verbs first: the menu loads them as it opens.await render();- expect(mocks.origin).toBe('webv2:p:project-1:q:local-queue-item');+ await vi.waitFor(() => expect(mocks.origin).toBe('webv2:p:project-1:q:local-queue-item'), COLD_LOAD);// The executed prompt and seed come from the backend item that produced the result.await vi.waitFor(() => expect(mocks.meta).toEqual({ positivePrompt: 'a staged cat', seed: 4242 }));expect(menuItem('widgets.gallery.itemActions.recall.verbs.seed').getAttribute('aria-disabled')).toBe('true');@@ -163,6 +204,23 @@ describe('StagingItemContextMenu', () => {expect(mocks.recall).not.toHaveBeenCalledWith('seed');});+ it('opens on its recall verbs’ first frame once they have loaded', async () => {+ await loadRecall();+ // Records whether the placeholder ever mounts while the menu opens.+ const placeholders: Node[] = [];+ const observer = new MutationObserver(() =>+ placeholders.push(...document.querySelectorAll('[data-value="menu-part-placeholder"]'))+ );+ observer.observe(document.body, { childList: true, subtree: true });++ await render();+ observer.disconnect();++ expect(placeholders).toEqual([]);+ expect(menuItem('widgets.gallery.itemActions.recall.verbs.prompts')).toBeDefined();+ expect(document.querySelector('[role="menu"]')?.getAttribute('aria-busy')).toBe('false');+ });+it('keeps Accept inert while accepting is not allowed', async () => {const handlers = { canAccept: false, onAccept: vi.fn() };await render(handlers);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.loadFailure.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.loadFailure.browser.test.tsxnew file mode 100644index 0000000000..00745613d3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.loadFailure.browser.test.tsx@@ -0,0 +1,106 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type * as MenuModule from '@platform/ui/Menu';+import type { CanvasCandidateSlot } from '@workbench/canvasStagingView';+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';++import { ChakraProvider } from '@chakra-ui/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import { page } from 'vitest/browser';++// The verbs' import fails as a dropped connection would until `fail` clears. Its own file: a page keeps loaded verbs.+const load = vi.hoisted(() => ({ fail: true }));+vi.mock('@platform/ui/Menu', async (importOriginal) => {+ const original = await importOriginal<typeof MenuModule>();++ return {+ ...original,+ createMenuPartLoader: <Part,>(importPart: () => Promise<Part>) =>+ original.createMenuPartLoader(() =>+ load.fail ? Promise.reject(new TypeError('Failed to fetch dynamically imported module')) : importPart()+ ),+ };+});+vi.mock('@features/queue/queries', () => ({+ getQueueReadModelOptions: () => ({ queryFn: () => Promise.resolve({ items: [] }), queryKey: ['queue-read-model'] }),+}));+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useActiveProjectId: () => 'project-1',+}));+vi.mock('@workbench/queue-integration/useQueueItemRecall', () => ({+ useQueueItemRecall: () => ({+ capabilities: { all: true, clipSkip: true, dimensions: true, prompts: true, remix: true, seed: true },+ isPending: false,+ reasons: {},+ recall: vi.fn(),+ }),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++import { StagingItemContextMenu } from './StagingItemContextMenu';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const slot = {+ candidate: { imageName: 'staged.png', sourceBackendItemId: 77, sourceQueueItemId: 'local-queue-item' },+ id: 'slot-1',+ kind: 'candidate',+ queueItemId: 'local-queue-item',+} as CanvasCandidateSlot;++const host = document.createElement('div');+const root = createRoot(host);+const unhandled = vi.fn();++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ window.removeEventListener('unhandledrejection', unhandled);+});++/** Opens the menu, which loads its verbs as it mounts. */+const open = async (onSaveToGallery = vi.fn()) => {+ await act(() =>+ root.render(+ <QueryClientProvider client={new QueryClient()}>+ <ChakraProvider value={system}>+ <StagingItemContextMenu+ canAccept+ target={{ slot, x: 40, y: 40 }}+ onAccept={vi.fn()}+ onClose={vi.fn()}+ onDiscard={vi.fn()}+ onSaveToGallery={onSaveToGallery}+ />+ </ChakraProvider>+ </QueryClientProvider>+ )+ );+};++it('says the verbs could not load, keeps the rest of the menu working, and loads them on a later open', async () => {+ window.addEventListener('unhandledrejection', unhandled);+ document.body.append(host);+ const onSaveToGallery = vi.fn();+ await open(onSaveToGallery);++ const failed = page.getByRole('menuitem', { name: 'common.menuPartLoadFailed' });+ await expect.element(failed).toHaveAttribute('aria-disabled', 'true');+ expect(page.getByRole('menu').element().getAttribute('aria-busy')).toBe('false');+ await page.getByRole('menuitem', { name: 'widgets.canvas.staging.saveToGallery' }).click();+ expect(onSaveToGallery).toHaveBeenCalledOnce();++ await act(() => root.render(null));+ load.fail = false;+ await open();++ await expect+ .element(page.getByRole('menuitem', { name: 'widgets.gallery.itemActions.recall.verbs.all' }))+ .toBeVisible();+ expect(failed.query()).toBeNull();+ expect(unhandled).not.toHaveBeenCalled();+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsxindex eb350b2350..6617c98b61 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemContextMenu.tsx@@ -1,19 +1,8 @@-import type { QueueGenerationMeta, QueueReadModel } from '@features/queue/contracts';import type { CanvasCandidateSlot } from '@workbench/canvasStagingView';-import type { ImageRecallKind } from '@workbench/image-actions';import { Menu, Portal } from '@chakra-ui/react';-import {- buildProjectQueueItemOriginPrefix,- buildQueueItemOrigin,- extractGenerationMeta,-} from '@features/queue/contracts';-import { getQueueReadModelOptions } from '@features/queue/queries';-import { MenuActionItem, MenuContent } from '@platform/ui/Menu';-import { useQuery } from '@tanstack/react-query';-import { getImageRecallVerb, IMAGE_RECALL_KINDS } from '@workbench/image-actions';-import { useQueueItemRecall } from '@workbench/queue-integration/useQueueItemRecall';-import { useActiveProjectId } from '@workbench/WorkbenchContext';+import { useMountEffect } from '@platform/react/useMountEffect';+import { createMenuPartLoader, MenuActionItem, MenuContent, MenuPartPlaceholder, useMenuPart } from '@platform/ui/Menu';import { CheckIcon, SaveIcon, XIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -24,21 +13,12 @@ export interface StagingItemContextMenuTarget {y: number;}-/** A staged result carries no executed field values; the local submission snapshot is the source. */-const NO_META: QueueGenerationMeta = {};--/** Read executed prompts and seed from queue metadata; randomized seeds are unavailable from authored settings. */-const useStagedCandidateMeta = (projectId: string, backendItemId: number | undefined): QueueGenerationMeta => {- const scope = useMemo(() => ({ originPrefix: buildProjectQueueItemOriginPrefix(projectId) }), [projectId]);- const select = useCallback(- (model: QueueReadModel): QueueGenerationMeta => {- const item = model.items.find((candidate) => candidate.id === backendItemId);- return item ? extractGenerationMeta(item) : NO_META;- },- [backendItemId]- );- return useQuery({ ...getQueueReadModelOptions(scope), enabled: backendItemId !== undefined, select }).data ?? NO_META;-};+// The recall verbs and the queue item read behind them load on demand, off the Canvas's startup (the queue rows' and+// details' menus load them too). Pointing at or focusing a staged result warms them; the menu loads them as it opens.+const stagingItemRecall = createMenuPartLoader(() =>+ import('./StagingItemRecallGroup').then((module) => module.StagingItemRecallGroup)+);+export const loadStagingItemRecall = stagingItemRecall.load;export const StagingItemContextMenu = ({canAccept,@@ -56,9 +36,9 @@ export const StagingItemContextMenu = ({target: StagingItemContextMenuTarget;}) => {const { t } = useTranslation();- const projectId = useActiveProjectId();- const meta = useStagedCandidateMeta(projectId, target.slot.candidate.sourceBackendItemId);- const { capabilities, recall } = useQueueItemRecall(buildQueueItemOrigin(target.slot.queueItemId, projectId), meta);+ const recall = useMenuPart(stagingItemRecall);+ // Mounted only while open, so mounting is the open: whoever opens the menu, its verbs load.+ useMountEffect(stagingItemRecall.load);const positioning = useMemo(() => ({getAnchorRect: () => ({ height: 1, width: 1, x: target.x, y: target.y }),@@ -79,13 +59,13 @@ export const StagingItemContextMenu = ({<Menu.Root lazyMount open positioning={positioning} unmountOnExit onOpenChange={onOpenChange}><Portal><Menu.Positioner>- <MenuContent minW="13rem" py="1">- <Menu.ItemGroup>- <Menu.ItemGroupLabel>{t('widgets.canvas.staging.recall')}</Menu.ItemGroupLabel>- {IMAGE_RECALL_KINDS.map((kind) => (- <RecallItem key={kind} disabled={!capabilities[kind]} kind={kind} onRecall={recall} />- ))}- </Menu.ItemGroup>+ <MenuContent aria-busy={recall.status === 'loading'} minW="13rem" py="1">+ {/* The menu opens at once, so its other items, Escape and an outside press work while the verbs load. */}+ {recall.status === 'loaded' ? (+ <recall.part slot={target.slot} />+ ) : (+ <MenuPartPlaceholder status={recall.status} />+ )}<Menu.Separator borderColor="border.subtle" /><MenuActionItemicon={SaveIcon}@@ -107,18 +87,3 @@ export const StagingItemContextMenu = ({</Menu.Root>);};--const RecallItem = ({- disabled,- kind,- onRecall,-}: {- disabled: boolean;- kind: ImageRecallKind;- onRecall: (kind: ImageRecallKind) => void;-}) => {- const { t } = useTranslation();- const verb = getImageRecallVerb(kind, t);- const onSelect = useCallback(() => onRecall(kind), [kind, onRecall]);- return <MenuActionItem disabled={disabled} icon={verb.icon} label={verb.label} value={kind} onSelect={onSelect} />;-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemRecallGroup.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemRecallGroup.tsxnew file mode 100644index 0000000000..5bdd4e6c72--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/StagingItemRecallGroup.tsx@@ -0,0 +1,39 @@+import type { QueueGenerationMeta, QueueReadModel } from '@features/queue/contracts';+import type { CanvasCandidateSlot } from '@workbench/canvasStagingView';++import {+ buildProjectQueueItemOriginPrefix,+ buildQueueItemOrigin,+ extractGenerationMeta,+} from '@features/queue/contracts';+import { getQueueReadModelOptions } from '@features/queue/queries';+import { useQuery } from '@tanstack/react-query';+import { QueueRecallMenuGroup } from '@workbench/queue-integration/QueueRecallMenuGroup';+import { useQueueItemRecall } from '@workbench/queue-integration/useQueueItemRecall';+import { useActiveProjectId } from '@workbench/WorkbenchContext';+import { useCallback, useMemo } from 'react';++/** A staged result carries no executed field values; the local submission snapshot is the source. */+const NO_META: QueueGenerationMeta = {};++/** Read executed prompts and seed from queue metadata; randomized seeds are unavailable from authored settings. */+const useStagedCandidateMeta = (projectId: string, backendItemId: number | undefined): QueueGenerationMeta => {+ const scope = useMemo(() => ({ originPrefix: buildProjectQueueItemOriginPrefix(projectId) }), [projectId]);+ const select = useCallback(+ (model: QueueReadModel): QueueGenerationMeta => {+ const item = model.items.find((candidate) => candidate.id === backendItemId);+ return item ? extractGenerationMeta(item) : NO_META;+ },+ [backendItemId]+ );+ return useQuery({ ...getQueueReadModelOptions(scope), enabled: backendItemId !== undefined, select }).data ?? NO_META;+};++/** The staged result's recall verbs, read from the queue item that produced it. */+export const StagingItemRecallGroup = ({ slot }: { slot: CanvasCandidateSlot }) => {+ const projectId = useActiveProjectId();+ const meta = useStagedCandidateMeta(projectId, slot.candidate.sourceBackendItemId);+ const recall = useQueueItemRecall(buildQueueItemOrigin(slot.queueItemId, projectId), meta);++ return <QueueRecallMenuGroup recall={recall} />;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.tsindex 29647f695f..97324bf204 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasClipboard.ts@@ -3,6 +3,8 @@* clipboard/canvas access.*/+import type { CanvasSelectionCapability } from '@workbench/canvas-engine/api';+import { type ClipboardAccess, ClipboardUnavailableError, readClipboardItems } from '@platform/browser/clipboard';/** MIME types accepted from the clipboard, best first. */@@ -75,3 +77,27 @@ export const decodeImageBlob = async (blob: Blob, deps: DecodeImageBlobDeps = {}bitmap.close?.();}};++/**+ * Copies the selected pixels with `write`, and for a cut then removes them from the layer. A cut asks first whether+ * the removal could run, so one the engine refuses (it says why) writes nothing to the clipboard rather than turning+ * into a copy. Resolves without writing when there is nothing selected to copy; a failed write rejects before+ * anything is removed.+ */+export const copyCanvasSelection = async (+ selection: Pick<CanvasSelectionCapability, 'admitSelectionErase' | 'eraseSelection' | 'exportSelectionBlob'>,+ cut: boolean,+ write: (blob: Blob) => Promise<void>+): Promise<void> => {+ if (cut && !selection.admitSelectionErase()) {+ return;+ }+ const blob = await selection.exportSelectionBlob();+ if (!blob) {+ return;+ }+ await write(blob);+ if (cut) {+ selection.eraseSelection();+ }+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex 38175b74ee..b13f1791ea 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@ -19,7 +19,12 @@ import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';import { CANVAS_HEADER_HOTKEYS } from './canvasHeaderCommands';import { CANVAS_ONLY_HOTKEYS, executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';-import { CANVAS_COMPANION_HOTKEYS, executeCanvasToolCommand, reportTransformRefusal } from './canvasToolCommands';+import {+ CANVAS_COMPANION_HOTKEYS,+ executeCanvasToolCommand,+ reportMergeDownRefusal,+ reportTransformRefusal,+} from './canvasToolCommands';const rasterLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>({@@ -107,6 +112,7 @@ const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyCocropAllLayers: vi.fn(),dispatch,reportLayerOperation: vi.fn(),+ reportMergeDownRefusal: vi.fn(),reportTransformRefusal: vi.fn(),reportPreparedCommit: () => undefined,reportStructuralCommit: () => undefined,@@ -156,16 +162,39 @@ describe('while results are staged', () => {});it.each([- ['canvas.nudgeLeft', -1, 0],- ['canvas.nudgeRight', 1, 0],- ['canvas.nudgeUp', 0, -1],- ['canvas.nudgeDown', 0, 1],- ] as const)('%s nudges the selected layer, never steps through results', (commandId, dx, dy) => {- const engine = run(commandId, { hasMultipleStagingSlots: true });+ ['canvas.nudgeLeft', 'brush', -1],+ ['canvas.nudgeRight', 'brush', 1],+ ['canvas.nudgeLeft', 'view', -1],+ ['canvas.nudgeRight', 'lasso', 1],+ ] as const)(+ '%s with the %s tool steps through the results instead of nudging',+ (commandId, activeTool, direction) => {+ const engine = run(commandId, { engine: createEngine({ activeTool }), hasMultipleStagingSlots: true });+ expect(dispatch).toHaveBeenCalledExactlyOnceWith({+ direction,+ type: 'cycleStagedImage',+ } satisfies CanvasProjectMutation);+ expect(engine.layers.nudgeSelectedLayer).not.toHaveBeenCalled();+ }+ );++ it.each([+ ['canvas.nudgeLeft', 'move', -1, 0],+ ['canvas.nudgeRight', 'transform', 1, 0],+ ['canvas.nudgeUp', 'brush', 0, -1],+ ['canvas.nudgeDown', 'brush', 0, 1],+ ] as const)('%s with the %s tool nudges the selected layer', (commandId, activeTool, dx, dy) => {+ const engine = run(commandId, { engine: createEngine({ activeTool }), hasMultipleStagingSlots: true });expect(engine.layers.nudgeSelectedLayer).toHaveBeenCalledExactlyOnceWith(dx, dy);expect(dispatch).not.toHaveBeenCalled();});+ it('left and right nudge when only one result is staged or generating', () => {+ const engine = run('canvas.nudgeRight', { hasMultipleStagingSlots: false });+ expect(engine.layers.nudgeSelectedLayer).toHaveBeenCalledExactlyOnceWith(1, 0);+ expect(dispatch).not.toHaveBeenCalled();+ });+it('Delete erases the pixel selection, or deletes the layer, instead of discarding a result', () => {const erasing = run('canvas.deleteSelected', {engine: createEngine({ hasSelection: true }),@@ -503,21 +532,33 @@ describe('tool selection', () => {expect(engine.tools.setTool).not.toHaveBeenCalled();return reportTransformRefusal.mock.calls;};- expect(report('locked')).toEqual([['locked']]);- expect(report('ineligible')).toEqual([['ineligible']]);+ expect(report('locked')).toEqual([['locked', 'a']]);+ expect(report('ineligible')).toEqual([['ineligible', 'a']]);expect(report('busy')).toEqual([]);});- it("gives an ineligible layer Transform's own reason and other refusals the shared layer notice", () => {+ it("explains an ineligible layer as a notice naming it, with Transform's own reason; other refusals as failures", () => {const explain = (refusal: Exclude<BeginTransformResult, 'started'>) => {- const reportError = vi.fn();- reportTransformRefusal(refusal, reportError, ((key: string) => key) as unknown as TFunction);- return reportError.mock.calls;+ const report = { error: vi.fn(), notice: vi.fn() };+ const t = ((key: string, options?: { name?: string }) =>+ options?.name === undefined ? key : `${key}:${options.name}`) as unknown as TFunction;+ reportTransformRefusal(refusal, { id: 'a', name: 'Sky' }, report, t);+ return { error: report.error.mock.calls, notice: report.notice.mock.calls };};- expect(explain('ineligible')).toEqual([- ['widgets.layers.actions.actionFailed', 'widgets.layers.actions.transformIneligible'],- ]);- expect(explain('locked')).toEqual([['widgets.layers.actions.actionFailed', 'widgets.layers.actions.locked']]);+ expect(explain('ineligible')).toEqual({+ error: [],+ notice: [+ [+ 'transform:ineligible:a',+ 'widgets.layers.actions.transformUnavailable:Sky',+ 'widgets.layers.actions.transformIneligible',+ ],+ ],+ });+ expect(explain('locked')).toEqual({+ error: [['widgets.layers.actions.actionFailed', 'widgets.layers.actions.locked']],+ notice: [],+ });});it('lasso selects the tool when not already active', () => {@@ -628,14 +669,80 @@ describe('mergeDown', () => {expect(engine.layers.mergeLayerDown).toHaveBeenCalledWith('a');});- it('refuses when the selected layer is bottom-most', () => {- const engine = run('canvas.mergeDown', { document: documentOf([rasterLayer('a'), rasterLayer('b')], 'b') });+ /** What a refused merge down says, as `[key, title, message]`, through the same report the Canvas wires. */+ const explainMergeDown = (document: CanvasDocumentContractV3): unknown[][] => {+ const info = vi.fn();+ const t = ((key: string, options?: { name?: string }) =>+ options?.name === undefined ? key : `${key}:${options.name}`) as unknown as TFunction;+ const engine = run('canvas.mergeDown', {+ document,+ reportMergeDownRefusal: (refusal) => reportMergeDownRefusal(document, refusal, info, t),+ });expect(engine.layers.mergeLayerDown).not.toHaveBeenCalled();+ return info.mock.calls;+ };+ const title = 'widgets.layers.actions.mergeDownRefused:b';+ const shape = (id: string, overrides: Partial<CanvasLayerContract> = {}) =>+ rasterLayer(id, {+ source: { fill: '#fff', height: 4, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 4 },+ ...overrides,+ } as Partial<CanvasLayerContract>);++ it.each<[string, CanvasNodeContract[], string, string]>([+ ['the bottom-most layer', [rasterLayer('a'), rasterLayer('b')], 'no-layer-below', 'mergeDownNoLayerBelow:b'],+ [+ 'the bottom layer of a group',+ [groupContract('G', [rasterLayer('a'), rasterLayer('b')])],+ 'bottom-of-group',+ 'mergeDownBottomOfGroup:b',+ ],+ [+ 'a layer above a group',+ [rasterLayer('b'), groupContract('Below', [rasterLayer('a')])],+ 'group-below',+ 'mergeDownGroupBelow:Below',+ ],+ ['a layer above a shape layer', [rasterLayer('b'), shape('a')], 'not-mergeable', 'mergeDownNotMergeable:a'],+ [+ 'paint above a disabled shape layer, for its kind',+ [rasterLayer('b'), shape('a', { isEnabled: false })],+ 'not-mergeable',+ 'mergeDownNotMergeable:a',+ ],+ [+ 'a layer above a hidden one',+ [rasterLayer('b'), rasterLayer('a', { isEnabled: false })],+ 'disabled',+ 'mergeDownHidden:a',+ ],+ [+ 'a layer in a hidden group, naming the group',+ [groupContract('Hidden', [rasterLayer('b'), rasterLayer('a')], { isEnabled: false })],+ 'disabled',+ 'mergeDownHidden:Hidden',+ ],+ [+ 'a layer above a locked one',+ [rasterLayer('b'), rasterLayer('a', { isLocked: true })],+ 'locked',+ 'mergeDownLocked:a',+ ],+ [+ 'a mask, pointing to Merge masks',+ [rasterLayer('b', { type: 'inpaint_mask' } as Partial<CanvasLayerContract>)],+ 'wrong-type',+ 'mergeDownMaskSelected',+ ],+ ['a group', [groupContract('b', [rasterLayer('a')]), rasterLayer('c')], 'wrong-type', 'mergeDownGroupSelected'],+ ])('explains why %s cannot merge down, once per layer and reason', (_, nodes, reason, message) => {+ const document = { ...documentOf([], 'b'), stacks: stacksFrom(nodes) };+ expect(explainMergeDown(document)).toEqual([+ [`merge-down:b:${reason}`, title, `widgets.layers.actions.${message}`],+ ]);});- it('refuses with no selected layer', () => {- const engine = run('canvas.mergeDown', { document: documentOf([rasterLayer('a')], null) });- expect(engine.layers.mergeLayerDown).not.toHaveBeenCalled();+ it('stays silent with no selected layer', () => {+ expect(explainMergeDown(documentOf([rasterLayer('a')], null))).toEqual([]);});it('reports a merge the engine refused', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex 27ce98b236..ac6780cd8d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@ -3,8 +3,10 @@ import type {LayerUnreadable,CanvasDocumentContractV3,CanvasEngine,+ DocumentRefusal,LayerStackMoveKind,StructuralCommitResult,+ ToolId,} from '@workbench/canvas-engine/api';import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';@@ -43,7 +45,8 @@ import {export const CANVAS_ONLY_HOTKEYS = [...CANVAS_HISTORY_HOTKEYS,// With several results staged or generating `alt+[` / `alt+]` step through them; otherwise they walk the layers.- // Bare arrows always nudge, and Delete always acts on the document: the staging bar handles its own keys.+ // Left and right step through them too unless the Move or Transform tool is active (see STAGING_NUDGE_TOOLS); the+ // other arrows always nudge, and Delete always acts on the document: the staging bar handles its own keys.['canvas.prevEntity', 'widgets.canvas.commands.previousEntity', ['alt+[']],['canvas.nextEntity', 'widgets.canvas.commands.nextEntity', ['alt+]']],['canvas.quickSwitch', 'widgets.canvas.commands.quickSwitch', ['q']],@@ -91,6 +94,12 @@ const NUDGE_DELTAS: Record<string, { dx: number; dy: number }> = {'canvas.nudgeUpLarge': { dx: 0, dy: -10 },};+/**+ * Tools that keep left/right as nudges while results are staged. With any other tool active a horizontal nudge is+ * almost always a reach for the next result after panning or clicking the canvas, and a 1px move is easy to miss.+ */+const STAGING_NUDGE_TOOLS: ReadonlySet<ToolId> = new Set(['move', 'transform']);+/** Command id → z-reorder direction (index 0 = top-most; "forward" moves toward 0). */const REORDER_KINDS: Record<string, LayerStackMoveKind> = {'canvas.layerBackward': 'backward',@@ -143,7 +152,8 @@ export interface CanvasHotkeyContext extends Omit<CanvasToolCommandContext, 'engreadonly engine: CanvasEngine | null;/*** More than one staging slot exists, so alt+[ / alt+] step through results (a placeholder shows its progress) instead- * of layers. With a single slot there is nothing to step to, and they walk the layers.+ * of layers, and left / right do too outside the Move and Transform tools. With a single slot there is nothing to step+ * to: they walk the layers and nudge as usual.*/readonly hasMultipleStagingSlots: boolean;readonly selectedLayerIds: readonly string[];@@ -156,13 +166,15 @@ export interface CanvasHotkeyContext extends Omit<CanvasToolCommandContext, 'engreadonly reportStructuralCommit: (result: StructuralCommitResult) => void;readonly reportPreparedCommit: (outcome: PreparedCommitOutcome) => void;readonly reportLayerOperation: (refusal: LayerOperationRefusal | AdjustmentRefusal | LayerUnreadable) => void;+ /** Explains why the selected layer cannot merge down. */+ readonly reportMergeDownRefusal: (refusal: DocumentRefusal) => void;readonly t: (key: string) => string;}/**- * Routes one canvas command id to its effect. Staged results never lock the canvas: only alt+[ / alt+] change- * meaning while several results are staged or generating (they step through them); every other key edits the- * document as usual.+ * Routes one canvas command id to its effect. Staged results never lock the canvas: only alt+[ / alt+], and left /+ * right outside the Move and Transform tools, change meaning while several results are staged or generating (they step+ * through them); every other key edits the document as usual.*/export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyContext): void => {const { dispatch, document, engine, t } = ctx;@@ -172,8 +184,14 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCconst selectedLayer = selected && !isGroupNode(selected.node) ? selected.node : undefined;const selectedFrozen = !!selected && (selected.ancestorsLocked || selected.node.isLocked);- if ((commandId === 'canvas.prevEntity' || commandId === 'canvas.nextEntity') && ctx.hasMultipleStagingSlots) {- dispatch({ direction: commandId === 'canvas.nextEntity' ? 1 : -1, type: 'cycleStagedImage' });+ const stepsResults =+ commandId === 'canvas.prevEntity' ||+ commandId === 'canvas.nextEntity' ||+ ((commandId === 'canvas.nudgeLeft' || commandId === 'canvas.nudgeRight') &&+ !STAGING_NUDGE_TOOLS.has(engine?.interaction.get('activeTool') ?? 'move'));+ if (stepsResults && ctx.hasMultipleStagingSlots) {+ const isNext = commandId === 'canvas.nextEntity' || commandId === 'canvas.nudgeRight';+ dispatch({ direction: isNext ? 1 : -1, type: 'cycleStagedImage' });return;}@@ -324,6 +342,6 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC);}} else if (commandId === 'canvas.mergeDown') {- mergeSelectedLayerDown(engine, document, ctx.reportLayerOperation);+ mergeSelectedLayerDown(engine, document, ctx.reportLayerOperation, ctx.reportMergeDownRefusal);}};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.tsindex 956df596ab..36e87477ba 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasImageDnd.ts@@ -2,6 +2,7 @@ import type { GalleryImage } from '@features/gallery';import type { GalleryCanvasImportDestination } from '@workbench/canvas-operations/api';import { isGalleryImageDragData } from '@features/gallery/utility';+import { findDropZoneAt } from '@platform/browser/dropZones';export interface CanvasImageDropData {kind: 'canvas-image-target';@@ -19,6 +20,20 @@ export const getCanvasImageDropData = (destination: CanvasImageDropData['destinaexport const getCanvasImageDropId = (destination: CanvasImageDropData['destination']): string =>`canvas-image-target:${destination}`;+/**+ * Marks each zone's element. A file dragged in from the desktop is an HTML5 drag dnd-kit never sees; it finds its zone+ * the way dnd-kit's collision does, by the zone's rect under the pointer, whatever is painted above it.+ */+export const CANVAS_IMAGE_DROP_DESTINATION_ATTRIBUTE = 'data-canvas-image-drop-destination';++export const findCanvasImageDropDestination = (+ root: Element,+ point: { clientX: number; clientY: number }+): CanvasImageDropData['destination'] | null => {+ const destination = findDropZoneAt(root, CANVAS_IMAGE_DROP_DESTINATION_ATTRIBUTE, point);+ return isCanvasImageDropDestination(destination) ? destination : null;+};+export interface CanvasImageDropResolution {destination: CanvasImageDropData['destination'];imageNames: string[];diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.tsnew file mode 100644index 0000000000..360c3bfd07--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts@@ -0,0 +1,274 @@+/**+ * Selection Fill, Erase, Delete and Cut, and mask transforms, on a real engine in Chromium: the commands the Canvas+ * runs, through the engine's own pixel editor and history.+ */++import type { CanvasEditRefusal, CanvasLayerContract } from '@workbench/canvas-engine/api';++import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { copyCanvasSelection } from './canvasClipboard';+import { executeCanvasHotkeyCommand } from './canvasHotkeyCommands';++const cleanups: (() => void | Promise<void>)[] = [];+afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) {+ await cleanup();+ }+});++/** A 64×64 PNG: opaque blue on its left half, transparent on its right. */+const halfBluePng = (): Promise<Blob> => {+ const canvas = new OffscreenCanvas(64, 64);+ const ctx = canvas.getContext('2d')!;+ ctx.fillStyle = '#0000ff';+ ctx.fillRect(0, 0, 32, 64);+ return canvas.convertToBlob({ type: 'image/png' });+};++const MASK_BITMAP = { height: 64, imageName: 'mask.png', width: 64 };++/** A real engine over `layers` with `selected` selected, attached to on-page canvases. */+const setup = async (layers: readonly Parameters<typeof stacksFrom>[0][number][], selected: string) => {+ const store = createWorkbenchStore();+ const projectId = store.getState().activeProjectId;+ store.commands.canvas.apply(projectId, {+ document: { ...createEmptyCanvasDocument(256, 256), selectedLayerId: selected, stacks: stacksFrom(layers) },+ type: 'replaceCanvasDocument',+ });+ const png = await halfBluePng();+ const engine = createCanvasEngine({+ ensureProjectOnServer: () => Promise.resolve(),+ imageResolver: () => Promise.resolve(png),+ mutationPort: createCanvasProjectMutationPort(store, projectId),+ projectId,+ reportError: () => undefined,+ });+ cleanups.push(() => engine.lifecycle.dispose());+ const [screen, overlay] = [document.createElement('canvas'), document.createElement('canvas')];+ for (const canvas of [screen, overlay]) {+ canvas.width = 256;+ canvas.height = 256;+ canvas.style.cssText = 'position:fixed;left:0;top:0;width:256px;height:256px';+ document.body.append(canvas);+ cleanups.push(() => canvas.remove());+ }+ engine.surface.attach(screen, overlay);+ engine.interaction.set('clipToBbox', false);+ const refusals: CanvasEditRefusal[] = [];+ engine.tools.onEditRefused((refusal) => refusals.push(refusal));++ const doc = () => store.getState().projects.find((project) => project.id === projectId)!.canvas.document;+ const layer = (id: string) => engine.document.model()!.getLayer(id) as CanvasLayerContract;+ const sourceType = (id: string) => {+ const current = layer(id);+ return current.type === 'raster' ? current.source.type : null;+ };+ const maskBitmap = (id: string) => {+ const current = layer(id);+ return current.type === 'inpaint_mask' ? current.mask.bitmap : null;+ };++ /** Marquee-selects the document rect from (x0, y0) to (x1, y1), replacing the selection. */+ const select = (x0: number, y0: number, x1: number, y1: number) => {+ engine.tools.setTool('marquee');+ const view = engine.viewport.getViewport();+ const box = overlay.getBoundingClientRect();+ const fire = (type: string, x: number, y: number, buttons: number) => {+ const point = view.documentToScreen({ x, y });+ overlay.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ buttons,+ clientX: box.left + point.x,+ clientY: box.top + point.y,+ isPrimary: true,+ pointerId: 1,+ })+ );+ };+ fire('pointerdown', x0, y0, 1);+ fire('pointermove', (x0 + x1) / 2, (y0 + y1) / 2, 1);+ fire('pointermove', x1, y1, 1);+ fire('pointerup', x1, y1, 0);+ };++ /** RGBA of `id`'s pixels at document (x, y), read through its export (layer-local, so placed by its transform). */+ const pixelAt = async (id: string, x: number, y: number): Promise<number[]> => {+ const exported = await engine.exports.exportLayerPixels(id, { includeDisabled: true });+ if (exported.status !== 'ok') {+ return [0, 0, 0, 0];+ }+ try {+ const { transform } = layer(id);+ const lx = Math.floor((x - transform.x) / transform.scaleX) - exported.rect.x;+ const ly = Math.floor((y - transform.y) / transform.scaleY) - exported.rect.y;+ if (lx < 0 || ly < 0 || lx >= exported.rect.width || ly >= exported.rect.height) {+ return [0, 0, 0, 0];+ }+ return [...exported.surface.ctx.getImageData(lx, ly, 1, 1).data];+ } finally {+ exported.release();+ }+ };++ /** Waits until `id`'s pixels have loaded, as an edit needs. */+ const loaded = async (id: string) => {+ await vi.waitFor(async () => {+ expect((await engine.exports.exportLayerPixels(id, { includeDisabled: true })).status).toBe('ok');+ });+ };++ const runCommand = (commandId: string) =>+ executeCanvasHotkeyCommand(commandId, {+ copySelection: vi.fn(),+ cropAllLayers: vi.fn(),+ dispatch: () => true,+ document: doc(),+ engine,+ hasMultipleStagingSlots: false,+ notifyLayerDuplicateFailed: vi.fn(),+ pasteFromClipboard: vi.fn(),+ reportLayerOperation: vi.fn(),+ reportMergeDownRefusal: vi.fn(),+ reportPreparedCommit: vi.fn(),+ reportStructuralCommit: vi.fn(),+ reportTransformRefusal: vi.fn(),+ resetActiveColors: vi.fn(),+ selectedLayerIds: [selected],+ swapActiveColors: vi.fn(),+ t: (key) => key,+ });++ return { doc, engine, layer, loaded, maskBitmap, pixelAt, refusals, runCommand, select, sourceType };+};++const mask = () =>+ layerContract('mask', 'inpaint_mask', {+ mask: { bitmap: MASK_BITMAP, fill: { color: '#e07575', style: 'diagonal' }, offset: { x: 0, y: 0 } },+ name: 'Mask',+ } as Partial<CanvasLayerContract>);++const photo = (overrides: Partial<CanvasLayerContract> = {}) =>+ layerContract('photo', 'raster', {+ name: 'Photo',+ source: { image: { height: 64, imageName: 'photo.png', width: 64 }, type: 'image' },+ ...overrides,+ } as Partial<CanvasLayerContract>);++describe('selection edits on a real engine', () => {+ it('Delete and Cut remove a mask’s selected coverage, one undoable step each', async () => {+ const h = await setup([mask()], 'mask');+ await h.loaded('mask');+ // The mask's image covers its left half (x < 32).+ expect((await h.pixelAt('mask', 10, 10))[3]).toBe(255);++ h.select(0, 0, 16, 64);+ h.runCommand('canvas.deleteSelected');+ expect((await h.pixelAt('mask', 10, 10))[3]).toBe(0);+ expect((await h.pixelAt('mask', 20, 10))[3]).toBe(255);+ expect(h.engine.history.getEntries().past).toContain('Erase selection');++ await h.engine.history.undo();+ expect((await h.pixelAt('mask', 10, 10))[3]).toBe(255);+ await h.engine.history.redo();+ expect((await h.pixelAt('mask', 10, 10))[3]).toBe(0);++ const written: Blob[] = [];+ h.select(16, 0, 24, 64);+ await copyCanvasSelection(h.engine.selection, true, (blob) => {+ written.push(blob);+ return Promise.resolve();+ });+ expect(written).toHaveLength(1);+ expect((await h.pixelAt('mask', 20, 10))[3]).toBe(0);+ expect((await h.pixelAt('mask', 28, 10))[3]).toBe(255);+ expect(h.refusals).toEqual([]);+ });++ it('a Cut the target refuses writes nothing and says why; Delete says the same', async () => {+ const h = await setup([groupContract('group', [layerContract('inner', 'raster', { name: 'Inner' })])], 'group');+ h.select(0, 0, 32, 32);+ const write = vi.fn(() => Promise.resolve());++ await copyCanvasSelection(h.engine.selection, true, write);+ h.runCommand('canvas.deleteSelected');++ expect(write).not.toHaveBeenCalled();+ const refusal = { layerId: 'group', layerName: 'group', status: 'selection-erase-unsupported' };+ expect(h.refusals).toEqual([refusal, refusal]);+ // Only the marquee's own step: nothing was erased.+ expect(h.engine.history.getEntries().past).toEqual(['Select']);+ });++ it('fills an image in place as one step that undo and redo replay', async () => {+ const h = await setup([photo()], 'photo');+ await h.loaded('photo');+ h.engine.interaction.set('brushOptions', { ...h.engine.interaction.get('brushOptions'), color: '#ff0000' });++ h.select(40, 0, 56, 16);+ h.engine.selection.fillSelection();+ expect(h.sourceType('photo')).toBe('paint');+ expect(await h.pixelAt('photo', 48, 8)).toEqual([255, 0, 0, 255]);+ expect(await h.pixelAt('photo', 8, 8)).toEqual([0, 0, 255, 255]);++ await h.engine.history.undo();+ expect(h.sourceType('photo')).toBe('image');+ await h.loaded('photo');+ expect((await h.pixelAt('photo', 48, 8))[3]).toBe(0);+ await h.engine.history.redo();+ expect(await h.pixelAt('photo', 48, 8)).toEqual([255, 0, 0, 255]);+ });++ it('fills only the existing pixels of a transparency-locked image', async () => {+ const h = await setup([photo({ isTransparencyLocked: true } as Partial<CanvasLayerContract>)], 'photo');+ await h.loaded('photo');+ h.engine.interaction.set('brushOptions', { ...h.engine.interaction.get('brushOptions'), color: '#ff0000' });++ h.select(16, 0, 48, 16);+ h.engine.selection.fillSelection();++ expect(await h.pixelAt('photo', 24, 8)).toEqual([255, 0, 0, 255]);+ expect((await h.pixelAt('photo', 40, 8))[3]).toBe(0);+ });++ it('applies a mask transform as one step that undo and redo replay', async () => {+ const h = await setup([mask()], 'mask');+ await h.loaded('mask');++ expect(h.engine.layers.beginTransform('mask')).toBe('started');+ h.engine.layers.updateTransformSession({ rotation: 0, scaleX: 2, scaleY: 1, x: 30, y: 0 });+ h.engine.layers.applyTransform();+ const moved = { rotation: 0, scaleX: 2, scaleY: 1, x: 30, y: 0 };+ expect(h.layer('mask').transform).toEqual(moved);+ // Not baked: the mask keeps its own image.+ expect(h.maskBitmap('mask')).toEqual(MASK_BITMAP);++ await h.engine.history.undo();+ expect(h.layer('mask').transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });+ await h.engine.history.redo();+ expect(h.layer('mask').transform).toEqual(moved);+ });++ it('refuses Delete while a transform session previews another placement', async () => {+ const h = await setup([mask()], 'mask');+ await h.loaded('mask');+ h.select(0, 0, 16, 64);+ expect(h.engine.layers.beginTransform('mask')).toBe('started');+ h.engine.layers.updateTransformSession({ rotation: 0, scaleX: 1, scaleY: 1, x: 100, y: 0 });++ h.runCommand('canvas.deleteSelected');++ expect(h.refusals).toEqual([{ layerId: 'mask', layerName: 'Mask', status: 'transform-session' }]);+ expect((await h.pixelAt('mask', 10, 10))[3]).toBe(255);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.browser.test.tsxnew file mode 100644index 0000000000..34bfbf197c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.browser.test.tsx@@ -0,0 +1,56 @@+import { ChakraProvider } from '@chakra-ui/react';+import { AppToaster, toaster } from '@platform/ui/toaster';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it } from 'vitest';++import { showCanvasRefusalNotice } from './canvasToolCommands';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ await act(() => {+ toaster.remove();+ root?.unmount();+ });+ host?.remove();+ host = null;+ root = null;+});++const openTitles = (): (string | null | undefined)[] =>+ [...document.querySelectorAll<HTMLElement>('[data-part="root"][data-scope="toast"]')]+ .filter((toast) => toast.getAttribute('data-state') === 'open')+ .map((toast) => toast.querySelector('[data-part="title"]')?.textContent);++describe('showCanvasRefusalNotice', () => {+ it('keeps one toast per key however often the key is pressed', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <AppToaster />+ </ChakraProvider>+ )+ );++ await act(() => {+ for (let press = 0; press < 4; press += 1) {+ showCanvasRefusalNotice('merge-down:a:no-layer-below', 'Can’t merge “A” down', 'There is no layer below it.');+ }+ showCanvasRefusalNotice(+ 'transform:ineligible:b',+ 'Can’t transform “B”',+ 'Transform works on layers with content.'+ );+ });++ await expect.poll(openTitles).toEqual(['Can’t transform “B”', 'Can’t merge “A” down']);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.tsindex d5f22d7af4..447824de98 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts@@ -3,29 +3,62 @@ import type {BeginTransformResult,CanvasDocumentContractV3,CanvasEngine,+ DocumentRefusal,LayerUnreadable,ShapeToolKind,} from '@workbench/canvas-engine/api';import type { TFunction } from 'i18next';import type { ElementType } from 'react';-import { mergeDownEligibility } from '@workbench/canvas-engine/api';+import { captureAccountScope } from '@platform/state/accountLifecycle';+import { createActionToast } from '@platform/ui/toaster';+import { getDocumentNode, mergeDownEligibility } from '@workbench/canvas-engine/api';import { reportLayerOperation, type LayerOperationRefusal } from '@workbench/widgets/canvas/useStructuralCommit';import { CircleIcon, PenLineIcon, PentagonIcon, SquareIcon, StarIcon, TriangleIcon } from 'lucide-react';+/**+ * A command refusal the user can fix, shown the way the Canvas shows its edit refusals: an info toast only, never+ * recorded in Notifications, and one per `key`, so pressing the key again (or holding it) replaces the toast rather+ * than stacking another. It lives here, beside the commands that raise it, because the Canvas and its companion+ * widgets already load this module; a module of its own would cost Canvas activation a request.+ */+export const showCanvasRefusalNotice = (key: string, title: string, message: string): void => {+ createActionToast({+ actions: [],+ description: message,+ id: `canvas-refusal:${key}`,+ signal: captureAccountScope().signal,+ title,+ type: 'info',+ });+};++/** Shows a refusal notice under `key`; see {@link showCanvasRefusalNotice}. */+export type CanvasRefusalNotice = typeof showCanvasRefusalNotice;+/** One hotkey row: its command id, title key and default keys. */export type HotkeyTableEntry = readonly [id: string, titleKey: string, defaultKeys: readonly string[]];/** The same layer operation is available from the Canvas and the Layers widget. */export const CANVAS_MERGE_DOWN_HOTKEY = ['canvas.mergeDown', 'widgets.canvas.commands.mergeDown', ['mod+e']] as const;+/**+ * Merges the selected layer into the one below it. A layer that cannot merge is explained through `reportIneligible`+ * (nothing selected stays silent); a merge the engine refuses or that fails goes to `report`.+ */export const mergeSelectedLayerDown = (engine: Pick<CanvasEngine, 'layers'> | null,document: CanvasDocumentContractV3,- report: (refusal: LayerOperationRefusal | AdjustmentRefusal | LayerUnreadable) => void+ report: (refusal: LayerOperationRefusal | AdjustmentRefusal | LayerUnreadable) => void,+ reportIneligible: (refusal: DocumentRefusal) => void): void => {const id = document.selectedLayerId;- if (!engine || !id || mergeDownEligibility(document, id).status !== 'eligible') {+ if (!engine || !id) {+ return;+ }+ const eligibility = mergeDownEligibility(document, id);+ if (eligibility.status !== 'eligible') {+ reportIneligible(eligibility);return;}void engine.layers.mergeLayerDown(id).then(@@ -38,6 +71,64 @@ export const mergeSelectedLayerDown = ();};+/** Merge down's own invalid-target reasons (`mergeDownEligibility`); the name is the layer or group they concern. */+const MERGE_DOWN_TARGET_KEYS: Partial<+ Record<Extract<DocumentRefusal, { status: 'invalid-target' }>['reason'], string>+> = {+ 'bottom-of-group': 'widgets.layers.actions.mergeDownBottomOfGroup',+ disabled: 'widgets.layers.actions.mergeDownHidden',+ 'group-below': 'widgets.layers.actions.mergeDownGroupBelow',+ 'no-layer-below': 'widgets.layers.actions.mergeDownNoLayerBelow',+ 'not-mergeable': 'widgets.layers.actions.mergeDownNotMergeable',+};++/**+ * Says why the selected layer cannot merge down, naming the layer or group in the way, as one notice per layer and+ * reason. The engine decides the reason; this only words it.+ */+export const reportMergeDownRefusal = (+ document: CanvasDocumentContractV3,+ refusal: DocumentRefusal,+ notice: CanvasRefusalNotice,+ t: TFunction+): void => {+ const selectedId = document.selectedLayerId;+ if (!selectedId) {+ return;+ }+ const nameOf = (id: string | undefined): string => getDocumentNode(document, id)?.name ?? '';+ const message = ((): string | null => {+ switch (refusal.status) {+ case 'locked':+ return t('widgets.layers.actions.mergeDownLocked', { name: nameOf(refusal.ids[0]) });+ case 'wrong-type':+ return t(+ refusal.actual === 'group'+ ? 'widgets.layers.actions.mergeDownGroupSelected'+ : refusal.actual === 'inpaint_mask'+ ? 'widgets.layers.actions.mergeDownMaskSelected'+ : 'widgets.layers.actions.mergeDownWrongType'+ );+ case 'invalid-target': {+ const key = MERGE_DOWN_TARGET_KEYS[refusal.reason];+ return key ? t(key, { name: nameOf(refusal.targetId) }) : null;+ }+ case 'missing':+ case 'unsupported':+ // The selection is gone, or the command does not exist here: nothing the user can act on.+ return null;+ }+ })();+ if (message !== null) {+ const reason = refusal.status === 'invalid-target' ? refusal.reason : refusal.status;+ notice(+ `merge-down:${selectedId}:${reason}`,+ t('widgets.layers.actions.mergeDownRefused', { name: nameOf(selectedId) }),+ message+ );+ }+};+/*** Canvas keys that also act while a companion widget (Layers, with its Color pane) holds focus: tools, the* transform session, brush size and the color pair. The Canvas and the companion both register from this table;@@ -103,16 +194,24 @@ export const isCanvasToolCommand = (commandId: string): commandId is CanvasToolCexport type TransformRefusal = Exclude<BeginTransformResult, 'started'>;-/** Explains a refused `beginTransform`; a layer Transform cannot act on gets Transform's own reason. */+/**+ * Explains a refused `beginTransform` on `layer`. A layer Transform cannot act on is a refusal notice (one per layer,+ * not recorded), not a failure; the other refusals keep the shared layer-operation error.+ */export const reportTransformRefusal = (refusal: TransformRefusal,- reportError: (title: string, message: string) => void,+ layer: { id: string; name: string },+ report: { error: (title: string, message: string) => void; notice: CanvasRefusalNotice },t: TFunction): void => {if (refusal === 'ineligible') {- reportError(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.transformIneligible'));+ report.notice(+ `transform:ineligible:${layer.id}`,+ t('widgets.layers.actions.transformUnavailable', { name: layer.name }),+ t('widgets.layers.actions.transformIneligible')+ );} else {- reportLayerOperation(refusal, reportError, t);+ reportLayerOperation(refusal, report.error, t);}};@@ -125,7 +224,8 @@ export interface CanvasToolCommandContext {readonly swapActiveColors: () => void;/** Resets the pair to the black-on-white default. */readonly resetActiveColors: () => void;- readonly reportTransformRefusal: (refusal: TransformRefusal) => void;+ /** Explains a refused Transform of the selected layer `layerId`. */+ readonly reportTransformRefusal: (refusal: TransformRefusal, layerId: string) => void;}/** Runs one companion key. The color pair is a preference, not a document edit: X/D need no engine. */@@ -159,7 +259,7 @@ export const executeCanvasToolCommand = (commandId: CanvasToolCommandId, ctx: Caconst result = engine.layers.beginTransform(ctx.selectedLayerId);// A key pressed mid-gesture is dropped quietly; the gesture already says why.if (result !== 'started' && result !== 'busy') {- ctx.reportTransformRefusal(result);+ ctx.reportTransformRefusal(result, ctx.selectedLayerId);}return;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.tsindex 4c694a8c85..f616652665 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts@@ -114,6 +114,14 @@ export const useCanvasViewportReady = (engine: CanvasCoreStoreCapability): booleexport const useControlLayerView = (engine: CanvasCoreStoreCapability): CanvasInteractionState['controlLayerView'] =>useCanvasInteractionState(engine, 'controlLayerView');+/** Whether a staged or progress preview, shown or toggled off, hides control layers, masks and regions. */+export const useCanvasStagingHidesOverlays = (engine: CanvasCoreStoreCapability): boolean =>+ useCanvasInteractionState(engine, 'stagingHidesOverlays');++/** The generation frame while a Frame tool drag reshapes it; null when the committed frame is current. */+export const useCanvasBboxPreview = (engine: CanvasCoreStoreCapability): CanvasInteractionState['bboxPreview'] =>+ useCanvasInteractionState(engine, 'bboxPreview');+/** The active tool id for `engine`. */export const useCanvasActiveTool = (engine: CanvasCoreStoreCapability): ToolId =>useCanvasInteractionState(engine, 'activeTool');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.tsindex a75df9da0f..8cfffc2ff9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts@@ -2,7 +2,7 @@ import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';import type { Project } from '@workbench/projectContracts';import type { WorkbenchCanvasCommands, WorkbenchQueries } from '@workbench/workbenchStore';-import { galleryImages } from '@features/gallery';+import { galleryImages, type GalleryImage } from '@features/gallery';import {getCanvasImportNotice,getSendAsControlNotice,@@ -18,28 +18,39 @@ type CanvasImageDropEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | '/** Imports the dropped gallery images and says how it went, as the gallery menu's matching action does. */export const executeCanvasImageDropImport = async ({- destination,- canvas,- engine,getGalleryImages = galleryImages.resolveMany,- queries,imageNames,- importGalleryImages = importGalleryImagesToCanvas,- project,- sendAsControl = sendGalleryImageAsControl,-}: {+ ...options+}: Omit<CanvasDropImportOptions, 'images'> & {+ getGalleryImages?: typeof galleryImages.resolveMany;+ imageNames: readonly string[];+}): Promise<CanvasImportNotice> => {+ const fetchedImages = await getGalleryImages([...imageNames]);+ return importCanvasDropImages({ ...options, images: orderCanvasImageDropImages(imageNames, fetchedImages) });+};++interface CanvasDropImportOptions {destination: GalleryCanvasImportDestination;canvas: WorkbenchCanvasCommands;engine: CanvasImageDropEngine | null;- getGalleryImages?: typeof galleryImages.resolveMany;queries: Pick<WorkbenchQueries, 'getProject' | 'isActiveProject'>;- imageNames: readonly string[];+ images: readonly GalleryImage[];importGalleryImages?: typeof importGalleryImagesToCanvas;project: Project;sendAsControl?: typeof sendGalleryImageAsControl;-}): Promise<CanvasImportNotice> => {- const fetchedImages = await getGalleryImages([...imageNames]);- const images = orderCanvasImageDropImages(imageNames, fetchedImages);+}++/** Lands images dropped on a canvas zone, gallery images or files just uploaded, and says how it went. */+export const importCanvasDropImages = async ({+ destination,+ canvas,+ engine,+ queries,+ images,+ importGalleryImages = importGalleryImagesToCanvas,+ project,+ sendAsControl = sendGalleryImageAsControl,+}: CanvasDropImportOptions): Promise<CanvasImportNotice> => {const shared = {applyCanvasMutation: canvas.apply,engine,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/importCanvasFileDrop.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/importCanvasFileDrop.tsnew file mode 100644index 0000000000..76dadb51e7--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/importCanvasFileDrop.ts@@ -0,0 +1,80 @@+import type { AccountScope } from '@platform/state/accountLifecycle';+import type { QueryClient } from '@tanstack/react-query';+import type {+ WorkbenchCanvasCommands,+ WorkbenchNotificationCommands,+ WorkbenchQueries,+} from '@workbench/workbenchStore';+import type { TFunction } from 'i18next';++import { galleryImageItemToGalleryImage, isGalleryImageItem } from '@features/gallery/contracts';+import { uploadGalleryFiles } from '@features/gallery/picker';+import { resolveGalleryUploadBoardId } from '@features/gallery/queries';+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { getCanvasEngine, getCanvasImportNotice } from '@workbench/canvas-operations/api';++import type { CanvasImageDropData } from './canvasImageDnd';++import { importCanvasDropImages } from './executeCanvasImageDropImport';++/**+ * Lands image files dropped on a canvas zone as that zone lands gallery images. They are uploaded first, as pasted+ * media is: to the project's auto-add board, reporting the upload's outcome and failures. The images then go to the+ * project the drop was made on, read again once they are stored so edits made meanwhile are kept, through the canvas+ * engine live for it then; a project switched away from, or one whose Canvas was closed meanwhile, takes them through+ * its ingestion, never the canvas now showing. An account change on the way leaves nothing behind.+ */+export const importCanvasFileDrop = async ({+ canvas,+ destination,+ files,+ galleryValues,+ notifications,+ owner,+ projectId,+ queries,+ queryClient,+ t,+}: {+ canvas: WorkbenchCanvasCommands;+ destination: CanvasImageDropData['destination'];+ files: File[];+ /** The project's gallery values when the files were dropped, which name its auto-add board. */+ galleryValues: Record<string, unknown>;+ notifications: WorkbenchNotificationCommands;+ /** The account the files were dropped in. */+ owner: AccountScope;+ projectId: string;+ queries: Pick<WorkbenchQueries, 'getProject' | 'isActiveProject'>;+ queryClient: QueryClient;+ t: TFunction;+}): Promise<void> => {+ const boardId = await resolveGalleryUploadBoardId(galleryValues, queryClient);+ if (!isAccountScopeCurrent(owner)) {+ return;+ }+ const uploaded = await uploadGalleryFiles(files, {+ boards: [],+ notifications,+ queryClient,+ selectedBoardId: boardId,+ t,+ });+ // Nothing stored: the upload said why, or the account it belonged to is gone.+ const images = uploaded.filter(isGalleryImageItem).map(galleryImageItemToGalleryImage);+ if (images.length === 0) {+ return;+ }+ const project = queries.getProject(projectId);+ const notice = project+ ? await importCanvasDropImages({+ canvas,+ destination,+ engine: getCanvasEngine(projectId) ?? null,+ images,+ project,+ queries,+ })+ : getCanvasImportNotice({ status: 'stale-project' });+ notifications.add({ kind: notice.kind, title: t(notice.titleKey, notice.options ?? {}) });+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.test.tsindex 3d6b2e9d65..655fa3aa63 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.test.ts@@ -24,10 +24,10 @@ describe('selectStagedPreviewSource', () => {});});- it('returns null for a selected candidate when the preview is hidden', () => {+ it('keeps a selected candidate the eye hid as a hidden preview, so the comparison stays unmasked', () => {expect(selectStagedPreviewSource({ ...base, isVisible: false, selectedCandidate: { imageName: 'img-1', placement } })- ).toBeNull();+ ).toEqual({ hidden: true, imageName: 'img-1', placement });});it('pins the selected placeholder progress frame to its submitted rect, scaled to fill it', () => {@@ -59,6 +59,10 @@ describe('stagedPreviewKey', () => {expect(stagedPreviewKey({ imageName: 'a', placement })).not.toBe(stagedPreviewKey({ imageName: 'b', placement }));// A new progress frame (different data URL) yields a new key so the effect re-fires.expect(stagedPreviewKey({ dataUrl: 'AA', placement })).not.toBe(stagedPreviewKey({ dataUrl: 'BB', placement }));+ // Toggling the eye republishes the candidate.+ expect(stagedPreviewKey({ hidden: true, imageName: 'a', placement })).not.toBe(+ stagedPreviewKey({ imageName: 'a', placement })+ );});it('includes every placement field', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.tsindex 8c4fc5e6d3..f21de5a4c2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/stagingPreview.ts@@ -1,6 +1,8 @@/**- * Prefer the visible finished candidate, then the selected placeholder's live progress frame, otherwise no- * preview. Both land at the rect pinned at submission, so moving the bbox mid-run never moves them.+ * Prefer the selected finished candidate, then the selected placeholder's live progress frame, otherwise no+ * preview. Both land at the rect pinned at submission, so moving the bbox mid-run never moves them. A candidate the+ * eye toggled off stays selected as a hidden preview: the canvas under it compares without the masks the shown+ * candidate hides.*/import type { CanvasPlacementContract, Rect, StagedPreviewInput } from '@workbench/canvas-engine/api';@@ -23,8 +25,9 @@ export const selectStagedPreviewSource = ({progressRect,selectedCandidate,}: StagedPreviewSelection): StagedPreviewInput | null => {- if (isVisible && selectedCandidate) {- return { imageName: selectedCandidate.imageName, placement: selectedCandidate.placement };+ if (selectedCandidate) {+ const { imageName, placement } = selectedCandidate;+ return isVisible ? { imageName, placement } : { hidden: true, imageName, placement };}if (progressRect && progressImage && progressRect.width > 0 && progressRect.height > 0) {// Progress frames are low-res latents of the submitted region; scale to fill it.@@ -40,5 +43,8 @@ export const stagedPreviewKey = (source: StagedPreviewInput | null): string => {}const { placement } = source;const rect = `${placement.x}:${placement.y}:${placement.width}:${placement.height}:${placement.opacity}`;- return 'imageName' in source ? `image:${source.imageName}:${rect}` : `data:${rect}:${source.dataUrl}`;+ if ('imageName' in source) {+ return `${source.hidden ? 'hidden' : 'image'}:${source.imageName}:${rect}`;+ }+ return `data:${rect}:${source.dataUrl}`;};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.browser.test.tsxindex e240029b8a..6a634789d8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.browser.test.tsx@@ -110,11 +110,11 @@ describe('paint size control', () => {});};- /** Where the thumb sits along the track, 0–1 (the track is inset 10px from the frame). */+ /** Where the thumb sits along the track, 0–1 (the track is inset 6px from the frame). */const thumbFraction = () => {const frame = container!.querySelector<HTMLElement>('[data-scope="scrubber"]')!.getBoundingClientRect();const thumb = container!.querySelector<HTMLElement>('[data-part="thumb"]')!.getBoundingClientRect();- return (thumb.left + thumb.width / 2 - frame.left - 10) / (frame.width - 20);+ return (thumb.left + thumb.width / 2 - frame.left - 6) / (frame.width - 12);};it('announces the actual size, including sub-pixel sizes', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOptionsBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOptionsBar.tsxindex 1217636c18..aa6fb10dc1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOptionsBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/CanvasOptionsBar.tsx@@ -1,11 +1,12 @@+import type { SystemStyleObject } from '@chakra-ui/react';import type { ReactNode } from 'react';import { HStack } from '@chakra-ui/react';import { CanvasFloatingBar } from '@workbench/widgets/canvas/CanvasFloatingBar';-export const CanvasOptionsBar = ({ children }: { children?: ReactNode }) => (+export const CanvasOptionsBar = ({ children, css }: { children?: ReactNode; css?: SystemStyleObject }) => (<CanvasFloatingBar maxW="full">- <HStack align="center" gap="1" minW="0">+ <HStack align="center" css={css} gap="1" minW="0">{children}</HStack></CanvasFloatingBar>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.browser.test.tsxindex 1747413c88..bb3fda3423 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.browser.test.tsx@@ -3,15 +3,18 @@ import type { FilterOperationSessionState } from '@workbench/canvas-operations/aimport { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { attachCanvasOperations } from '@workbench/canvas-operations/operationAccess';+import { createOperationSection } from '@workbench/widgets/layers/panes/OperationSection';import { createInstance } from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { page, userEvent } from 'vitest/browser';import { filterOperationForm } from './FilterOptions';+const FilterSection = createOperationSection(filterOperationForm);+const enCatalog: Record<string, unknown> = await fetch('/locales/en.json').then((response) => response.json());(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -35,6 +38,7 @@ const sessionStore = (initial: FilterOperationSessionState) => {const listeners = new Set<() => void>();return {getFilterSessionState: () => state,+ processFilterOperation: vi.fn(() => Promise.resolve<'completed' | 'stale'>('completed')),set: (next: Partial<FilterOperationSessionState>) => {state = { ...state, ...next };listeners.forEach((listener) => listener());@@ -64,7 +68,7 @@ const SESSION: FilterOperationSessionState = {status: 'ready',};-describe('filter footer errors', () => {+describe('filter operation errors', () => {let root: Root | null = null;let container: HTMLDivElement | null = null;@@ -75,19 +79,18 @@ describe('filter footer errors', () => {container = null;});- const renderFooter = async (initial: Partial<FilterOperationSessionState>) => {+ const renderSection = async (initial: Partial<FilterOperationSessionState>) => {const i18n = await createI18n();const store = sessionStore({ ...SESSION, ...initial });const engine = engineWith(store);container = document.createElement('div');document.body.append(container);root = createRoot(container);- const Footer = filterOperationForm.footer;act(() =>root!.render(<ChakraProvider value={system}><I18nextProvider i18n={i18n}>- <Footer engine={engine as never} />+ <FilterSection engine={engine as never} /></I18nextProvider></ChakraProvider>)@@ -96,7 +99,7 @@ describe('filter footer errors', () => {};it('translates a refusal and updates an already visible error when the language changes', async () => {- const { i18n } = await renderFooter({ error: { code: 'over-budget' }, status: 'error' });+ const { i18n } = await renderSection({ error: { code: 'over-budget' }, status: 'error' });await expect.element(page.getByRole('alert')).toHaveTextContent('The filtered layer is too large to undo, so it was not applied.');@@ -107,7 +110,7 @@ describe('filter footer errors', () => {});it('falls back to English for a refusal the language does not translate', async () => {- const { i18n } = await renderFooter({ error: { code: 'stale' }, status: 'error' });+ const { i18n } = await renderSection({ error: { code: 'stale' }, status: 'error' });await act(() => i18n.changeLanguage('de'));await expect@@ -116,7 +119,7 @@ describe('filter footer errors', () => {});it('summarizes an unexpected failure and keeps its message as technical detail', async () => {- await renderFooter({ error: { code: 'apply-failed', detail: 'cache failed' }, status: 'error' });+ await renderSection({ error: { code: 'apply-failed', detail: 'cache failed' }, status: 'error' });await expect.element(page.getByRole('alert')).toHaveTextContent('The filter could not be applied.');const details = page.getByRole('button', { name: 'Technical details' });@@ -124,8 +127,118 @@ describe('filter footer errors', () => {await expect.element(page.getByText('cache failed')).toBeVisible();});+ it('offers Process to retry a failed run with auto-update on, until that retry has finished', async () => {+ const { store } = await renderSection({});+ const process = page.getByRole('button', { exact: true, name: 'Process' });+ expect(process.query()).toBeNull();++ act(() => store.set({ error: { code: 'process-failed', detail: 'graph exploded' }, status: 'error' }));+ await expect.element(process).toBeEnabled();+ let finish!: () => void;+ store.processFilterOperation.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = () => resolve('completed');+ })+ );+ await userEvent.click(process);+ expect(store.processFilterOperation).toHaveBeenCalledOnce();++ // The retry clears the error as it starts; the button stays, busy, for the run it started.+ act(() => store.set({ error: null, status: 'processing' }));+ await expect.element(process).toBeDisabled();+ act(() => store.set({ status: 'ready' }));+ await act(() => finish());+ expect(process.query()).toBeNull();+ });++ const PREVIEW: FilterOperationSessionState['preview'] = {+ guard: {} as never,+ height: 10,+ imageName: 'filtered',+ origin: { x: 0, y: 0 },+ rect: { height: 10, width: 10, x: 0, y: 0 },+ width: 10,+ };++ /** Fails a run with auto-update on, then starts the retry from the keyboard on Process; resolves the run on demand. */+ const startKeyboardRetry = async () => {+ const { store } = await renderSection({ error: { code: 'process-failed' }, status: 'error' });+ const process = page.getByRole('button', { exact: true, name: 'Process' });+ let finish!: (result: 'completed' | 'stale') => void;+ store.processFilterOperation.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ })+ );+ process.element().focus();+ await userEvent.keyboard('{Enter}');+ expect(store.processFilterOperation).toHaveBeenCalledOnce();+ act(() => store.set({ error: null, status: 'processing' }));+ const succeed = async () => {+ act(() => store.set({ preview: PREVIEW, status: 'ready' }));+ await act(() => finish('completed'));+ expect(process.query()).toBeNull();+ };+ const fail = async () => {+ act(() => store.set({ error: { code: 'process-failed' }, status: 'error' }));+ await act(() => finish('stale'));+ await expect.element(process).toBeEnabled();+ };+ return { fail, store, succeed };+ };++ it('moves focus to Apply when a keyboard retry succeeds and its Process button leaves', async () => {+ const { succeed } = await startKeyboardRetry();++ await succeed();++ await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toHaveFocus();+ });++ it('leaves focus where the user moved it during the retry', async () => {+ const { succeed } = await startKeyboardRetry();+ const cancel = page.getByRole('button', { exact: true, name: 'Cancel' });+ cancel.element().focus();++ await succeed();++ await expect.element(cancel).toHaveFocus();+ });++ it('does not move focus when Process leaves later, after the keyboard retry failed', async () => {+ const { fail, store } = await startKeyboardRetry();+ await fail();+ (document.activeElement as HTMLElement | null)?.blur();++ // A later run (an auto run after a setting change) succeeds, so the button leaves.+ act(() => store.set({ error: null, preview: PREVIEW, status: 'ready' }));+ expect(page.getByRole('button', { exact: true, name: 'Process' }).query()).toBeNull();+ await act(+ () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve);+ })+ );++ expect(document.activeElement).toBe(document.body);+ });++ it('leaves a failed apply to Apply: no Process with auto-update on', async () => {+ await renderSection({+ error: { code: 'apply-failed', detail: 'cache failed' },+ preview: PREVIEW,+ status: 'error',+ });++ await expect.element(page.getByRole('alert')).toHaveTextContent('The filter could not be applied.');+ expect(page.getByRole('button', { exact: true, name: 'Process' }).query()).toBeNull();+ await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toBeEnabled();+ });+it('clears the error once a retry starts', async () => {- const { store } = await renderFooter({ error: { code: 'busy' }, status: 'error' });+ const { store } = await renderSection({ error: { code: 'busy' }, status: 'error' });await expect.element(page.getByRole('alert')).toBeVisible();act(() => store.set({ error: null, status: 'committing' }));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsxindex 1c7e9d8ce4..3018ebf2ae 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx@@ -15,9 +15,9 @@ import { describe, expect, it, vi } from 'vitest';import {filterOperationForm,getFilterActionEligibility,+ getFilterBusyTranslationKey,getFilterErrorTranslationKey,getFilterSaveTargetEligibility,- getFilterStatusTranslationKey,} from './FilterOptions';const englishCatalogModules = import.meta.glob('../../../../../public/locales/en.json', {@@ -122,12 +122,12 @@ describe('getFilterActionEligibility', () => {});});-describe('getFilterStatusTranslationKey', () => {- it('maps each session status to its message key', () => {- expect(getFilterStatusTranslationKey('processing')).toBe('widgets.layers.rasterFilter.running');- expect(getFilterStatusTranslationKey('committing')).toBe('widgets.layers.rasterFilter.statusCommitting');- expect(getFilterStatusTranslationKey('error')).toBe('widgets.layers.rasterFilter.statusError');- expect(getFilterStatusTranslationKey('ready')).toBe('widgets.layers.selectObject.statusReady');+describe('getFilterBusyTranslationKey', () => {+ it('names the working phases and nothing at rest', () => {+ expect(testI18n.t(getFilterBusyTranslationKey('processing')!)).toBe('Running filter…');+ expect(testI18n.t(getFilterBusyTranslationKey('committing')!)).toBe('Applying filter…');+ expect(getFilterBusyTranslationKey('error')).toBeNull();+ expect(getFilterBusyTranslationKey('ready')).toBeNull();});});@@ -190,42 +190,43 @@ const renderRegions = (session: FilterOperationSessionState) => {const [choose, params] = filterOperationForm.groups;return {choose: render(createElement(choose!.body, { engine: engine as never })),- footer: render(createElement(filterOperationForm.footer, { engine: engine as never })),+ actions: render(createElement(filterOperationForm.actions, { engine: engine as never })),operations,params: render(createElement(params!.body, { engine: engine as never })),};};describe('filter operation form', () => {- it('puts the choice and auto switch in one group, parameters in the next, and every verb in the footer', () => {- const { choose, footer, params } = renderRegions(+ it('puts the choice and auto switch in one group, parameters in the next, and every verb in the actions row', () => {+ const { actions, choose, params } = renderRegions(state({ draft: { settings: { high_threshold: 200, low_threshold: 100 }, type: 'canny_edge_detection' } }));// The select names itself through a real (visually hidden) label part.expect(choose).toContain('>Filter</label>');- expect(choose).toContain('>Process automatically<');+ expect(choose).toContain('>Auto-update preview<');expect(choose).not.toContain('>Process<');expect(params).not.toContain('>Filter</label>');expect(params).toContain('Low threshold');- expect(footer).toContain('Portrait · Raster layer');- expect(footer).toContain('role="status"');- // Auto-process on: no Process verb; Reset settings then Apply then Cancel.- expect(footer).not.toContain('>Process<');- expect(footer).not.toContain('>Reset<');- expect(footer.indexOf('>Reset settings<')).toBeGreaterThan(-1);- expect(footer.indexOf('>Reset settings<')).toBeLessThan(footer.indexOf('>Apply<'));- expect(footer.indexOf('>Apply<')).toBeLessThan(footer.indexOf('>Cancel<'));+ // Auto-update on: no Process verb; Reset, then Cancel, then Apply. Status lives in the section, not in the row.+ expect(actions).not.toContain('Portrait');+ expect(actions).not.toContain('role="status"');+ expect(actions).not.toContain('>Process<');+ expect(actions.indexOf('>Reset<')).toBeGreaterThan(-1);+ expect(actions.indexOf('>Reset<')).toBeLessThan(actions.indexOf('>Cancel<'));+ expect(actions.indexOf('>Cancel<')).toBeLessThan(actions.indexOf('>Apply<'));});- it('shows Process only with auto-process off, disabled while processing, and keeps Cancel live', () => {- const manual = renderRegions(state({ autoProcess: false })).footer;- expect(manual).toContain('>Process<');+ it('shows Process only with auto-update off, labelled and disabled while processing, and keeps Cancel live', () => {+ const manual = renderRegions(state({ autoProcess: false })).actions;+ expect(manual.indexOf('>Cancel<')).toBeLessThan(manual.indexOf('>Process<'));+ expect(manual.indexOf('>Process<')).toBeLessThan(manual.indexOf('>Apply<'));- const busy = renderRegions(state({ autoProcess: false, status: 'processing' })).footer;+ const busy = renderRegions(state({ autoProcess: false, status: 'processing' })).actions;const processIdx = busy.indexOf('>Process<');+ expect(processIdx).toBeGreaterThan(-1);const processButtonTag = busy.slice(busy.lastIndexOf('<button', processIdx), processIdx);expect(processButtonTag).toContain('disabled=""');expect(processButtonTag).toContain('data-loading=""');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsxindex 46121ce7c9..c6948260b3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx@@ -1,13 +1,12 @@import type {OperationPropertyForm,+ OperationStatus,ToolFormProps,} from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';-/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import { Box, createListCollection, Flex, Icon, Menu, Portal } from '@chakra-ui/react';+/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop */+import { createListCollection } from '@chakra-ui/react';import { galleryDurability } from '@features/gallery';-import { Button } from '@platform/ui/Button';-import { MenuActionItem, MenuContent } from '@platform/ui/Menu';import { Select } from '@platform/ui/Select';import {buildFilterDefaults,@@ -23,11 +22,10 @@ import {import { useFilterSession } from '@workbench/widgets/canvas/engineStoreHooks';import { PropertySwitchRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';import { LayerFilterControls } from '@workbench/widgets/layers/LayerFilterControls';-import { ChevronDownIcon } from 'lucide-react';-import { useCallback, useMemo } from 'react';+import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { OperationStatusChip } from './OperationStatusSlot';+import { OperationActions } from './OperationActions';export interface FilterActionEligibility {canApply: boolean;@@ -59,14 +57,13 @@ export const getFilterActionEligibility = (session: FilterOperationSessionState)};};-export const getFilterStatusTranslationKey = (status: FilterOperationSessionState['status']): string =>+/** The phase shown while the filter works; null at rest. */+export const getFilterBusyTranslationKey = (status: FilterOperationSessionState['status']): string | null =>status === 'processing'? 'widgets.layers.rasterFilter.running': status === 'committing'? 'widgets.layers.rasterFilter.statusCommitting'- : status === 'error'- ? 'widgets.layers.rasterFilter.statusError'- : 'widgets.layers.selectObject.statusReady';+ : null;const FILTER_ERROR_TRANSLATION_KEYS: Record<FilterSessionErrorCode, string> = {aborted: 'widgets.layers.rasterFilter.aborted',@@ -91,6 +88,33 @@ const FILTER_ERROR_TRANSLATION_KEYS: Record<FilterSessionErrorCode, string> = {export const getFilterErrorTranslationKey = (code: FilterSessionErrorCode): string =>FILTER_ERROR_TRANSLATION_KEYS[code];+const FILTER_ERROR_FROM_RUN: Record<FilterSessionErrorCode, boolean> = {+ aborted: false,+ 'apply-failed': false,+ busy: false,+ disabled: true,+ empty: true,+ locked: false,+ missing: true,+ 'not-ready': true,+ 'over-budget': false,+ 'process-failed': true,+ 'source-adjustment-error': true,+ 'source-adjustment-over-budget': true,+ 'source-adjustment-too-large': true,+ 'source-over-budget': true,+ 'source-unreadable': true,+ stale: true,+ unsupported: true,+};++/**+ * Whether running the filter again is the error's retry: a run reported it (reading the source or filtering it).+ * Apply's own refusals and failures are retried by Apply. Codes both report count as run errors: a stale preview must+ * be filtered again, and the rest fail while reading the source, before any backend work.+ */+export const isFilterRunError = (code: FilterSessionErrorCode): boolean => FILTER_ERROR_FROM_RUN[code];+const useFilterDraft = (engine: ToolFormProps['engine']) => {const operations = getCanvasOperations(engine);const setType = useCallback(@@ -120,7 +144,7 @@ const useFilterDraft = (engine: ToolFormProps['engine']) => {return { operations, reset, setSettings, setType };};-/** Filter choice (grouped by category) and auto-process: the iteration dials. */+/** Filter choice (grouped by category) and auto-update: the iteration dials. */const FilterChooseSettings = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const session = useFilterSession(engine);@@ -205,10 +229,31 @@ const FilterParamsSettings = ({ engine }: ToolFormProps) => {);};-const FilterFooter = ({ engine }: ToolFormProps) => {+const useFilterStatus = (engine: ToolFormProps['engine']): OperationStatus | null => {+ const { t } = useTranslation();+ const session = useFilterSession(engine);+ if (!session) {+ return null;+ }+ const busyKey = getFilterBusyTranslationKey(session.status);+ return {+ busyText: busyKey ? t(busyKey) : null,+ error: session.error+ ? { detail: session.error.detail ?? null, text: t(getFilterErrorTranslationKey(session.error.code)) }+ : null,+ source: `${session.layerName} · ${t(`widgets.layers.selectObject.saveAs_${session.layerType}`)}`,+ };+};++/**+ * Process is the manual run while auto-update is off. With auto-update on it is the retry after a failed run, the only+ * way to run the same settings again, and stays for the run it started so the click shows its progress.+ */+const FilterActions = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const session = useFilterSession(engine);const { operations, reset } = useFilterDraft(engine);+ const [running, setRunning] = useState(false);const onApply = useCallback(() => void operations.commitFilterOperation('apply', galleryDurability.makeCanvasAsset),[operations]@@ -217,99 +262,57 @@ const FilterFooter = ({ engine }: ToolFormProps) => {if (!session) {return null;}+ const run = () => {+ setRunning(true);+ void operations.processFilterOperation().finally(() => setRunning(false));+ };const eligibility = getFilterActionEligibility(session);const saveTargets = getFilterSaveTargetEligibility(eligibility);- const sourceLabel = `${session.layerName} · ${t(`widgets.layers.selectObject.saveAs_${session.layerType}`)}`;- const isBusy = !session.error && (session.status === 'processing' || session.status === 'committing');return (- <Flex align="center" gap="1" minW="0" w="full">- <Box flex="1" minW="0" overflow="hidden" whiteSpace="nowrap">- <OperationStatusChip- errorDetail={session.error?.detail ?? null}- errorText={session.error ? t(getFilterErrorTranslationKey(session.error.code)) : null}- isBusy={isBusy}- sourceLabel={sourceLabel}- statusText={t(getFilterStatusTranslationKey(session.status))}- technicalDetailsLabel={t('widgets.layers.selectObject.technicalDetails')}- title={t('widgets.layers.rasterFilter.title')}- />- </Box>- <Button disabled={!eligibility.canReset} flexShrink={0} variant="ghost" onClick={reset}>- {t('widgets.layers.rasterFilter.resetSettings')}- </Button>- {session.autoProcess ? null : (- <Button- disabled={!eligibility.canProcess}- flexShrink={0}- loading={session.status === 'processing'}- onClick={() => void operations.processFilterOperation()}- >- {t('widgets.layers.selectObject.process')}- </Button>- )}- <Flex flexShrink={0}>- <Button- data-pane-action="apply"- disabled={!eligibility.canApply}- loading={session.status === 'committing'}- roundedRight="none"- variant="solid"- onClick={onApply}- >- {t('common.apply')}- </Button>- <Menu.Root positioning={APPLY_MENU_POSITIONING}>- <Menu.Trigger asChild>- <Button- aria-label={t('widgets.layers.rasterFilter.applyAs')}- disabled={!eligibility.canSave}- px="1"- roundedLeft="none"- variant="solid"- >- <Icon as={ChevronDownIcon} boxSize="3.5" />- </Button>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <MenuContent minW="12rem" py="1">- <MenuActionItem- disabled={!saveTargets.raster}- label={t('widgets.layers.selectObject.saveAs_raster')}- value="save-raster"- onSelect={() => void operations.commitFilterOperation('raster', galleryDurability.makeCanvasAsset)}- />- <MenuActionItem- disabled={!saveTargets.control}- label={t('widgets.layers.selectObject.saveAs_control')}- value="save-control"- onSelect={() => void operations.commitFilterOperation('control', galleryDurability.makeCanvasAsset)}- />- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- </Flex>- <Button- data-pane-action="cancel"- disabled={!eligibility.canCancel}- flexShrink={0}- variant="ghost"- onClick={onCancel}- >- {t('common.cancel')}- </Button>- </Flex>+ <OperationActions+ applying={session.status === 'committing'}+ canApply={eligibility.canApply}+ canCancel={eligibility.canCancel}+ canReset={eligibility.canReset}+ canSave={eligibility.canSave}+ run={+ session.autoProcess && !running && !(session.error && isFilterRunError(session.error.code))+ ? null+ : {+ disabled: !eligibility.canProcess,+ label: t('widgets.layers.rasterFilter.process'),+ loading: running || session.status === 'processing',+ onRun: run,+ }+ }+ saveAsLabel={t('widgets.layers.rasterFilter.applyAs')}+ saveTargets={[+ {+ disabled: !saveTargets.raster,+ label: t('widgets.layers.selectObject.saveAs_raster'),+ value: 'save-raster',+ onSelect: () => void operations.commitFilterOperation('raster', galleryDurability.makeCanvasAsset),+ },+ {+ disabled: !saveTargets.control,+ label: t('widgets.layers.selectObject.saveAs_control'),+ value: 'save-control',+ onSelect: () => void operations.commitFilterOperation('control', galleryDurability.makeCanvasAsset),+ },+ ]}+ onApply={onApply}+ onCancel={onCancel}+ onReset={reset}+ />);};-const APPLY_MENU_POSITIONING = { placement: 'top-end' } as const;-export const filterOperationForm: OperationPropertyForm = {- footer: FilterFooter,+ actions: FilterActions,groups: [{ body: FilterChooseSettings, id: 'filter-choose', labelKey: 'widgets.layers.control.filter' },{ body: FilterParamsSettings, id: 'filter-params', labelKey: 'widgets.properties.groups.settings' },],kind: 'filter',+ useStatus: useFilterStatus,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationActions.tsxnew file mode 100644index 0000000000..f55426c88b--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationActions.tsx@@ -0,0 +1,190 @@+/* oxlint-disable react-perf/jsx-no-jsx-as-prop */+import { Flex, Icon, Menu, Portal, Text } from '@chakra-ui/react';+import { Button, IconButton } from '@platform/ui/Button';+import { MenuActionItem, MenuContent } from '@platform/ui/Menu';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { ChevronDownIcon } from 'lucide-react';+import { useCallback, useRef } from 'react';+import { useTranslation } from 'react-i18next';++const APPLY_MENU_POSITIONING = { placement: 'bottom-end' } as const;++export interface OperationSaveTarget {+ disabled: boolean;+ label: string;+ value: string;+ onSelect(): void;+}++export interface OperationRunAction {+ disabled: boolean;+ label: string;+ /** Work is in flight: the button stays its own width and label beside a spinner. */+ loading: boolean;+ onRun(): void;+}++/**+ * The verbs of a running canvas operation, one row after its form's groups: Reset at the start; Cancel, the manual run+ * and Apply (with its save-as menu) at the end. Status and errors live in the Operation section, not here.+ *+ * A retry's run button leaves the row once its run succeeds. When the button leaves while it has focus, or leaves after+ * a run that began while it had focus and nothing took focus since it went disabled, focus moves to Apply, or to Cancel+ * while Apply is disabled, so a keyboard user is not left on the page body.+ */+export const OperationActions = ({+ applying,+ canApply,+ canCancel,+ canReset,+ canSave,+ run,+ saveAsLabel,+ saveTargets,+ onApply,+ onCancel,+ onReset,+}: {+ /** The result is being applied: Apply keeps its label beside a spinner. */+ applying: boolean;+ canApply: boolean;+ canCancel: boolean;+ canReset: boolean;+ canSave: boolean;+ /** The manual run, offered while the preview does not update by itself or to retry a run that failed. */+ run: OperationRunAction | null;+ /** Names the save-as menu trigger. */+ saveAsLabel: string;+ saveTargets: readonly OperationSaveTarget[];+ onApply(): void;+ onCancel(): void;+ onReset(): void;+}) => {+ const { t } = useTranslation();+ const saveAsIds = useTooltipTriggerIds();+ const applyRef = useRef<HTMLButtonElement>(null);+ const cancelRef = useRef<HTMLButtonElement>(null);+ const runStartedFocused = useRef(false);+ const runLoading = run?.loading ?? false;+ // Re-attached when loading changes. Cleanup runs before the commit removes or disables the button, so it reads+ // whether the button still has focus: an idle attachment's cleanup records it for the run now starting (focus falls+ // to the body once the busy button is disabled) or, finding the button gone, judges a run that settled before it+ // rendered as busy. A run that never shows as busy, refused or settled in one render, leaves nothing recorded. The+ // hand-off waits a microtask, after the same commit may have enabled Apply.+ const runButtonRef = useCallback(+ (node: HTMLButtonElement | null) => {+ if (!node) {+ return undefined;+ }+ if (!runLoading) {+ runStartedFocused.current = false;+ }+ return () => {+ const focused = node.ownerDocument.activeElement === node;+ if (!runLoading) {+ runStartedFocused.current = focused;+ }+ queueMicrotask(() => {+ if (node.isConnected) {+ return;+ }+ const handOff = runLoading ? runStartedFocused.current : focused;+ runStartedFocused.current = false;+ const { activeElement, body } = node.ownerDocument;+ if (!handOff || (activeElement !== null && activeElement !== body)) {+ return;+ }+ const target = applyRef.current && !applyRef.current.disabled ? applyRef.current : cancelRef.current;+ if (target?.isConnected && !target.disabled) {+ target.focus();+ }+ });+ };+ },+ [runLoading]+ );+ return (+ <Flex align="center" gap="1" minW="0" w="full">+ {/*+ Tighter padding keeps the row on one line down to a 280 px floating pane; past that, only the run button+ gives way, truncating its label, so every verb stays visible.+ */}+ <Button disabled={!canReset} flexShrink={0} px="2" variant="ghost" onClick={onReset}>+ {t('common.reset')}+ </Button>+ <Button+ ref={cancelRef}+ data-pane-action="cancel"+ disabled={!canCancel}+ flexShrink={0}+ ms="auto"+ px="2"+ variant="ghost"+ onClick={onCancel}+ >+ {t('common.cancel')}+ </Button>+ {run ? (+ <Button+ ref={runButtonRef}+ disabled={run.disabled}+ flexShrink={1}+ loading={run.loading}+ loadingText={+ <Text as="span" truncate>+ {run.label}+ </Text>+ }+ minW="0"+ px="2"+ spinnerPlacement="start"+ onClick={run.onRun}+ >+ <Text as="span" truncate>+ {run.label}+ </Text>+ </Button>+ ) : null}+ <Flex flexShrink={0}>+ <Button+ ref={applyRef}+ data-pane-action="apply"+ disabled={!canApply}+ loading={applying}+ loadingText={t('common.apply')}+ px="2"+ roundedRight="none"+ spinnerPlacement="start"+ variant="solid"+ onClick={onApply}+ >+ {t('common.apply')}+ </Button>+ <Menu.Root ids={saveAsIds} positioning={APPLY_MENU_POSITIONING}>+ <Tooltip content={saveAsLabel} ids={saveAsIds}>+ <Menu.Trigger asChild>+ <IconButton aria-label={saveAsLabel} disabled={!canSave} minW="6" roundedLeft="none" variant="solid">+ <Icon as={ChevronDownIcon} boxSize="3.5" />+ </IconButton>+ </Menu.Trigger>+ </Tooltip>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="12rem" py="1">+ {saveTargets.map((target) => (+ <MenuActionItem+ key={target.value}+ disabled={target.disabled}+ label={target.label}+ value={target.value}+ onSelect={target.onSelect}+ />+ ))}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </Flex>+ </Flex>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsxdeleted file mode 100644index d5f42447de..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx+++ /dev/null@@ -1,110 +0,0 @@-import type { CSSProperties } from 'react';--import { Flex, HStack, IconButton, Spinner, Text, VisuallyHidden } from '@chakra-ui/react';-import { Tooltip } from '@platform/ui/Tooltip';-import { InfoIcon } from 'lucide-react';--const ERROR_CLAMP_STYLE: CSSProperties = {- display: '-webkit-box',- overflow: 'hidden',- WebkitBoxOrient: 'vertical',- WebkitLineClamp: 2,-};--/**- * The always-mounted status slot shared by the canvas operation bars: reserves- * its width so status/error text appearing never shifts the surrounding- * controls, and keeps the polite live region in the tree before content- * arrives so announcements are reliable.- */-export const OperationStatusSlot = ({- errorDetail,- errorText,- isBusy,- minW = '8rem',- statusText,- technicalDetailsLabel,-}: {- errorDetail: string | null;- errorText: string | null;- isBusy: boolean;- minW?: string;- statusText: string;- technicalDetailsLabel: string;-}) => {- const detail = errorDetail?.trim();- return (- <Flex- align="center"- color={errorText ? 'fg.error' : 'fg.muted'}- flex="0 1 auto"- fontSize="md"- gap="1"- maxW="16rem"- minW={minW}- >- {errorText ? (- <>- <span aria-live="assertive" role="alert" style={ERROR_CLAMP_STYLE}>- {errorText}- </span>- {detail && detail !== errorText ? (- <Tooltip content={detail}>- <IconButton aria-label={technicalDetailsLabel} flexShrink="0" tabIndex={0} variant="ghost">- <InfoIcon />- </IconButton>- </Tooltip>- ) : null}- </>- ) : (- <Flex align="center" aria-live="polite" gap="2" minW="0" role="status">- {isBusy ? (- <>- <Spinner flexShrink="0" />- <span>{statusText}</span>- </>- ) : null}- </Flex>- )}- </Flex>- );-};--interface OperationStatusChipProps {- errorDetail: string | null;- errorText: string | null;- isBusy: boolean;- /** The source layer, named for assistive tech and the tooltip. */- sourceLabel: string;- statusText: string;- technicalDetailsLabel: string;- title: string;-}--/** The status of a running operation: its title, then the live status slot. */-export const OperationStatusChip = ({- errorDetail,- errorText,- isBusy,- sourceLabel,- statusText,- technicalDetailsLabel,- title,-}: OperationStatusChipProps) => (- <HStack gap="1" minW="0">- <Tooltip content={sourceLabel}>- <Text flexShrink={0} fontSize="md" fontWeight="semibold" minW="0" truncate>- {title}- <VisuallyHidden>{sourceLabel}</VisuallyHidden>- </Text>- </Tooltip>- <OperationStatusSlot- errorDetail={errorDetail}- errorText={errorText}- isBusy={isBusy}- minW="0"- statusText={statusText}- technicalDetailsLabel={technicalDetailsLabel}- />- </HStack>-);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.browser.test.tsxnew file mode 100644index 0000000000..3805285fbb--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.browser.test.tsx@@ -0,0 +1,215 @@+import type { CanvasOperationCapability, SamSessionSnapshot } from '@workbench/canvas-operations/api';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { attachCanvasOperations } from '@workbench/canvas-operations/operationAccess';+import { createOperationSection } from '@workbench/widgets/layers/panes/OperationSection';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { selectObjectOperationForm } from './SamOptions';++const SamSection = createOperationSection(selectObjectOperationForm);++const enCatalog: Record<string, unknown> = await fetch('/locales/en.json').then((response) => response.json());++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const SESSION: SamSessionSnapshot = {+ applyPolygonRefinement: false,+ autoProcess: true,+ error: { code: 'queue', detail: 'AttributeError' },+ hasPreview: false,+ input: { prompt: 'cat', type: 'prompt' },+ invert: false,+ isolatedPreview: true,+ layerName: 'Portrait',+ layerType: 'raster',+ model: 'segment-anything-2-large',+ pointLabel: 'include',+ retrying: false,+ sourceRect: { height: 768, width: 1024, x: 0, y: 0 },+ status: 'error',+};++const engineWith = (operations: object): object => {+ const engine = {};+ attachCanvasOperations(engine, operations as never);+ return engine;+};++describe('Select Object retry focus', () => {+ let root: Root | null = null;+ let container: HTMLDivElement | null = null;++ afterEach(() => {+ act(() => root?.unmount());+ container?.remove();+ root = null;+ container = null;+ });++ type SetSession = (next: Partial<SamSessionSnapshot>) => void;+ type ProcessResult = Awaited<ReturnType<CanvasOperationCapability['processSelectObjectSession']>>;++ /** The session clears the error as the retry starts and keeps `retrying` until it settles. */+ const startRetry = (set: SetSession): ProcessResult => {+ set({ error: null, retrying: true, status: 'processing-sam' });+ return 'published';+ };++ /**+ * A Select Object section whose first auto run failed; `succeed` plays the retry through to a ready preview.+ * `process` is what Find object does to the session, the run's progress by default.+ */+ const renderFailedSession = async (process: (set: SetSession) => ProcessResult = startRetry) => {+ const i18n = createInstance();+ await i18n.use(initReactI18next).init({ lng: 'en', resources: { en: { translation: enCatalog } } });+ let state = SESSION;+ const listeners = new Set<() => void>();+ const set: SetSession = (next) => {+ state = { ...state, ...next };+ listeners.forEach((listener) => listener());+ };+ const operations = {+ getSamSessionState: () => state,+ processSelectObjectSession: vi.fn(() => Promise.resolve(process(set))),+ subscribeSamSession: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ updateSelectObjectSession: vi.fn(() => 'updated' as const),+ };+ const engine = engineWith(operations);+ container = document.createElement('div');+ container.style.width = '450px';+ document.body.append(container);+ root = createRoot(container);+ act(() =>+ root!.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <SamSection engine={engine as never} />+ </I18nextProvider>+ </ChakraProvider>+ )+ );+ const findObject = page.getByRole('button', { name: 'Find object' });+ await expect.element(findObject).toBeEnabled();+ return {+ fail: () => act(() => set({ error: { code: 'queue' }, retrying: false, status: 'error' })),+ findObject,+ operations,+ set,+ succeed: async () => {+ await expect.element(findObject).toBeDisabled();+ act(() => set({ hasPreview: true, retrying: false, status: 'ready' }));+ expect(findObject.query()).toBeNull();+ },+ };+ };++ it('moves focus to Apply when a keyboard retry succeeds and Find object leaves', async () => {+ const { findObject, operations, succeed } = await renderFailedSession();+ findObject.element().focus();+ await userEvent.keyboard('{Enter}');+ expect(operations.processSelectObjectSession).toHaveBeenCalledOnce();++ await succeed();++ await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toHaveFocus();+ });++ it('does not move focus when Find object leaves later, after the keyboard retry failed', async () => {+ const { fail, findObject, set } = await renderFailedSession();+ findObject.element().focus();+ await userEvent.keyboard('{Enter}');+ await expect.element(findObject).toBeDisabled();+ fail();+ await expect.element(findObject).toBeEnabled();+ (document.activeElement as HTMLElement | null)?.blur();++ // A later auto run succeeds after an input change, so the button leaves.+ act(() => set({ error: null, hasPreview: true, status: 'ready' }));+ expect(findObject.query()).toBeNull();+ await act(+ () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve);+ })+ );++ expect(document.activeElement).toBe(document.body);+ });++ it('moves focus to Apply when a keyboard retry succeeds before it renders as running', async () => {+ const { findObject } = await renderFailedSession((set) => {+ set({ error: null, hasPreview: true, status: 'ready' });+ return 'published';+ });+ findObject.element().focus();+ await userEvent.keyboard('{Enter}');+ expect(findObject.query()).toBeNull();++ await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toHaveFocus();+ });++ it.each([+ { name: 'is refused', process: (): ProcessResult => 'deduped' },+ {+ name: 'fails before it renders as running',+ process: (set: SetSession): ProcessResult => {+ startRetry(set);+ set({ error: { code: 'queue' }, retrying: false, status: 'error' });+ return 'error';+ },+ },+ ])('does not move focus when Find object leaves later, after a keyboard retry that $name', async ({ process }) => {+ const { findObject, operations, set } = await renderFailedSession(process);+ findObject.element().focus();+ await userEvent.keyboard('{Enter}');+ expect(operations.processSelectObjectSession).toHaveBeenCalledOnce();+ await expect.element(findObject).toBeEnabled();+ (document.activeElement as HTMLElement | null)?.blur();++ // A later auto run succeeds after an input change, so the button leaves.+ act(() => set({ error: null, hasPreview: true, status: 'ready' }));+ expect(findObject.query()).toBeNull();+ await act(+ () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve);+ })+ );++ expect(document.activeElement).toBe(document.body);+ });++ it('leaves focus where the user moved it during the retry', async () => {+ const { findObject, succeed } = await renderFailedSession();+ findObject.element().focus();+ await userEvent.keyboard('{Enter}');+ const prompt = page.getByRole('textbox', { name: 'Prompt' });+ prompt.element().focus();++ await succeed();++ await expect.element(prompt).toHaveFocus();+ });++ it('keeps focus in the prompt for a retry started by Enter there', async () => {+ const { operations, succeed } = await renderFailedSession();+ const prompt = page.getByRole('textbox', { name: 'Prompt' });+ await userEvent.click(prompt);+ await userEvent.keyboard('{Enter}');+ expect(operations.processSelectObjectSession).toHaveBeenCalledOnce();++ await succeed();++ await expect.element(prompt).toHaveFocus();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.tsindex 56080b8055..2e92440598 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts@@ -1,27 +1,13 @@import type { SamSessionSnapshot } from '@workbench/canvas-operations/operationTypes';-import type { ComponentProps } from 'react';-import { ChakraProvider } from '@chakra-ui/react';-import { system } from '@theme/system';-import { attachCanvasOperations } from '@workbench/canvas-operations/operationAccess';-import { createInstance } from 'i18next';-import { createElement } from 'react';-import { renderToStaticMarkup } from 'react-dom/server';-import { I18nextProvider } from 'react-i18next';import { describe, expect, it, vi } from 'vitest';import {- getSamPanelViewModel,getSamActionEligibility,getSamActionHandlers,+ getSamBusyTranslationKey,getSamErrorTranslationKey,- getSamStatusTranslationKey,keepSamImageIntermediate,- selectObjectOperationForm,- SamPromptBody,- SamModeToggle,- SamStatusSlot,- SamVisualInput,toggleSamSetting,} from './SamOptions';@@ -35,17 +21,9 @@ const englishCatalogModules = import.meta.glob('../../../../../public/locales/eneager: true,import: 'default',});-const enCatalog = Object.values(englishCatalogModules)[0] as {- common: Record<string, string>;+const en = Object.values(englishCatalogModules)[0] as {widgets: { layers: { selectObject: Record<string, string> } };};-const en = enCatalog;-const testI18n = createInstance();-await testI18n.init({- initAsync: false,- lng: 'en',- resources: { en: { translation: enCatalog } },-});const snapshot = (overrides: Partial<SamSessionSnapshot> = {}): SamSessionSnapshot => ({applyPolygonRefinement: false,@@ -59,6 +37,7 @@ const snapshot = (overrides: Partial<SamSessionSnapshot> = {}): SamSessionSnapshlayerType: 'raster',model: 'segment-anything-2-large',pointLabel: 'include',+ retrying: false,sourceRect: { height: 20, width: 20, x: 0, y: 0 },status: 'ready',...overrides,@@ -90,7 +69,7 @@ describe('getSamActionEligibility', () => {});expect(getSamActionEligibility(- snapshot({ error: { code: 'unknown', detail: 'commit failed' }, hasPreview: true, status: 'error' })+ snapshot({ error: { code: 'commit-failed', detail: 'commit failed' }, hasPreview: true, status: 'error' }))).toMatchObject({canApply: true,@@ -123,88 +102,19 @@ describe('getSamActionEligibility', () => {});});-describe('getSamPanelViewModel', () => {- it('derives visual counts, bbox state, and a localized layer source label', () => {- expect(- getSamPanelViewModel(- snapshot({- input: {- bbox: { height: 8, width: 12, x: 1, y: 2 },- excludePoints: [{ x: 3, y: 4 }],- includePoints: [- { x: 1, y: 2 },- { x: 2, y: 3 },- ],- type: 'visual',- },- layerName: 'Subject',- sourceRect: { height: 768, width: 1024, x: 64, y: 32 },- }),- (layerName, width, height) => `${layerName} at ${width} by ${height}`- )- ).toEqual({- bboxActive: true,- excludeCount: 1,- includeCount: 2,- sourceLabel: 'Subject at 1024 by 768',- });- });+describe('Select Object status copy', () => {+ it.each(['scheduled', 'preparing-source', 'uploading', 'processing-sam', 'rendering-preview', 'committing'] as const)(+ 'names the %s phase in localized copy without exposing the identifier',+ (status) => {+ const key = getSamBusyTranslationKey(status)?.split('.').at(-1);+ const copy = key ? en.widgets.layers.selectObject[key] : undefined;+ expect(copy).toBeTypeOf('string');+ expect(copy).not.toContain(status);+ }+ );- it('returns zero visual counts for prompt mode', () => {- expect(- getSamPanelViewModel(- snapshot({ input: { prompt: 'cat', type: 'prompt' } }),- (layerName, w, h) => `${layerName} ${w} × ${h}`- )- ).toEqual({- bboxActive: false,- excludeCount: 0,- includeCount: 0,- sourceLabel: 'Layer 1 20 × 20',- });- });-});--describe('SamModeToggle', () => {- it('uses ordinary pressed buttons without incomplete tab relationships', () => {- const markup = renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(SamModeToggle, {- disabled: false,- mode: 'visual',- onPrompt: () => undefined,- onVisual: () => undefined,- promptLabel: 'Prompt',- visualLabel: 'Visual',- })- )- );-- expect(markup).toContain('aria-label="Selection mode"');- expect(markup).toContain('aria-pressed="true"');- expect(markup).toContain('aria-pressed="false"');- expect(markup).not.toContain('role="tab"');- expect(markup).not.toContain('aria-controls');- });-});--describe('SamStatusSlot', () => {- it.each([- 'ready',- 'scheduled',- 'preparing-source',- 'uploading',- 'processing-sam',- 'rendering-preview',- 'committing',- 'error',- ] as const)('maps %s to localized user-facing copy without exposing the identifier', (status) => {- const key = getSamStatusTranslationKey(status).split('.').at(-1);- const copy = key ? en.widgets.layers.selectObject[key] : undefined;- expect(copy).toBeTypeOf('string');- expect(copy).not.toContain(status);+ it.each(['ready', 'error'] as const)('shows no phase while %s', (status) => {+ expect(getSamBusyTranslationKey(status)).toBeNull();});it.each([@@ -218,6 +128,7 @@ describe('SamStatusSlot', () => {'output-dimension','decode','locked',+ 'commit-failed','unknown',] as const)('maps %s errors to localized primary copy', (code) => {const key = getSamErrorTranslationKey(code).split('.').at(-1);@@ -225,187 +136,6 @@ describe('SamStatusSlot', () => {expect(copy).toBeTypeOf('string');expect(copy).not.toBe(code);});-- it('server-renders a localized phase with polite status semantics', () => {- const markup = renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(SamStatusSlot, {- error: null,- errorText: null,- isBusy: true,- statusText: 'Rendering object preview…',- technicalDetailsLabel: 'Technical details',- })- )- );-- expect(markup).toContain('role="status"');- expect(markup).toContain('aria-live="polite"');- expect(markup).toContain('Rendering object preview…');- expect(markup).not.toContain('role="alert"');- });-- it('reserves an empty polite live region when ready without an error', () => {- const markup = renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(SamStatusSlot, {- error: null,- errorText: null,- isBusy: false,- statusText: 'Ready',- technicalDetailsLabel: 'Technical details',- })- )- );-- expect(markup).toContain('role="status"');- expect(markup).toContain('aria-live="polite"');- expect(markup).not.toContain('Ready');- expect(markup).not.toContain('role="alert"');- });-- it('server-renders a known localized error as the assertive primary message', () => {- const markup = renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(SamStatusSlot, {- error: { code: 'decode' },- errorText: 'The object preview could not be decoded.',- isBusy: false,- statusText: 'Select Object needs attention.',- technicalDetailsLabel: 'Technical details',- })- )- );-- expect(markup).toContain('role="alert"');- expect(markup).toContain('aria-live="assertive"');- expect(markup).toContain('The object preview could not be decoded.');- });-- it('server-renders unknown diagnostics only after a localized primary message', () => {- const markup = renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(SamStatusSlot, {- error: { code: 'unknown', detail: 'GPU worker disconnected' },- errorText: 'Select Object could not finish.',- isBusy: false,- statusText: 'Select Object needs attention.',- technicalDetailsLabel: 'Technical details',- })- )- );-- expect(markup).not.toContain('title=');- expect(markup).toContain('aria-label="Technical details"');- expect(markup).toContain('tabindex="0"');- expect(markup).toContain('data-scope="tooltip"');- expect(markup).not.toContain('>GPU worker disconnected<');- expect(markup).toContain('role="alert"');- });-- it('server-renders a localized queue error before its backend exception type', () => {- const errorText = en.widgets.layers.selectObject.errorQueue;- const markup = renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(SamStatusSlot, {- error: { code: 'queue', detail: 'AttributeError' },- errorText,- isBusy: false,- statusText: 'Select Object needs attention.',- technicalDetailsLabel: 'Technical details',- })- )- );-- expect(markup).not.toContain('title=');- expect(markup).toContain('aria-label="Technical details"');- expect(markup).toContain('data-scope="tooltip"');- expect(markup).not.toContain('>AttributeError<');- expect(markup).toContain('role="alert"');- });-});--describe('single-row SAM inputs', () => {- it('uses bar-scale copy including the settings popover and bbox indicator labels', () => {- expect(en.widgets.layers.selectObject.model).toBe('Model');- expect(en.widgets.layers.selectObject.refine).toBe('Refine');- expect(en.widgets.layers.selectObject.autoProcess).toBe('Auto Process');- expect(en.widgets.layers.selectObject.isolatedPreview).toBe('Isolated Preview');- expect(en.widgets.layers.selectObject.settings).toBe('Select Object settings');- expect(en.widgets.layers.selectObject.bbox).toBe('Box');- expect(en.widgets.layers.selectObject.technicalDetails).toBe('Technical details');- expect(en.widgets.layers.selectObject.sourceLayerLabel).toContain('{{name}}');- expect(en.widgets.layers.selectObject.sourceLayerLabel).toContain('{{width}}');- expect(en.widgets.layers.selectObject.saveAs_selection).toBe('Selection');- expect(en.widgets.layers.selectObject.includeCount).toBe('Include {{count}}');- expect(en.widgets.layers.selectObject.excludeCount).toBe('Exclude {{count}}');- expect(en.widgets.layers.selectObject).not.toHaveProperty('autoProcessCompact');- expect(en.widgets.layers.selectObject).not.toHaveProperty('isolatedPreviewCompact');- });-- it('server-renders Prompt as a one-line accessible input', () => {- const markup = renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(SamPromptBody, { disabled: false, prompt: 'cat', onChange: () => undefined })- )- );-- expect(markup).toContain('<input');- expect(markup).toContain('aria-label=');- expect(markup).toContain('aria-describedby="sam-prompt-guidance"');- expect(markup).toContain('id="sam-prompt-guidance"');- expect(markup).toContain('placeholder=');- expect(markup).not.toContain('<textarea');- });-- it('server-renders the visual controls as one labeled group without permanent guidance', () => {- const session = snapshot({- input: {- bbox: { height: 8, width: 12, x: 1, y: 2 },- excludePoints: [{ x: 3, y: 4 }],- includePoints: [{ x: 1, y: 2 }],- type: 'visual',- },- });- const markup = renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(- I18nextProvider,- { i18n: testI18n },- createElement(SamVisualInput, {- disabled: false,- onExclude: () => undefined,- onInclude: () => undefined,- pointLabel: session.pointLabel,- viewModel: getSamPanelViewModel(session, (layerName, width, height) => `${layerName} ${width} × ${height}`),- })- )- )- );-- expect(markup).toContain('role="group"');- expect(markup).toContain('aria-pressed="true"');- expect(markup).not.toContain('title=');- expect(markup).toContain('aria-describedby="sam-visual-guidance"');- expect(markup).toContain('id="sam-visual-guidance"');- expect(markup).toContain('aria-label="Include 1"');- expect(markup).toContain('aria-label="Exclude 1"');- expect(markup).not.toContain('>widgets.layers.selectObject.pointType<');- });});describe('getSamActionHandlers', () => {@@ -453,7 +183,7 @@ describe('getSamActionHandlers', () => {});describe('toggleSamSetting', () => {- it('saves an applied Auto Process change as the account preference, and nothing else', () => {+ it('saves an applied auto-update change as the account preference, and nothing else', () => {const updateSelectObjectSession = vi.fn(() => 'updated' as const);toggleSamSetting({ updateSelectObjectSession }, 'autoProcess', true);@@ -461,7 +191,7 @@ describe('toggleSamSetting', () => {expect(updateSelectObjectSession).toHaveBeenNthCalledWith(1, { autoProcess: true });expect(updateSelectObjectSession).toHaveBeenNthCalledWith(2, { isolatedPreview: false });- expect(patchWorkbenchPreferences).toHaveBeenCalledExactlyOnceWith({ selectObjectAutoProcess: true });+ expect(patchWorkbenchPreferences).toHaveBeenCalledExactlyOnceWith({ selectObjectAutoUpdate: true });});it('keeps the preference when the session refuses the change', () => {@@ -472,55 +202,3 @@ describe('toggleSamSetting', () => {expect(patchWorkbenchPreferences).not.toHaveBeenCalled();});});--describe('select object regions', () => {- it('splits mode, points and invert into the bar, settings and secondary commands into More, and keeps Apply / Cancel in status', () => {- const session = snapshot({- hasPreview: true,- input: { bbox: null, excludePoints: [], includePoints: [{ x: 4, y: 5 }], type: 'visual' },- sourceRect: { height: 768, width: 1024, x: 0, y: 0 },- });- const operations = {- applySelectObjectSession: vi.fn(),- cancelSelectObjectSession: vi.fn(),- getSamSessionState: () => session,- processSelectObjectSession: vi.fn(),- resetSelectObjectSession: vi.fn(),- saveSelectObjectSession: vi.fn(),- subscribeSamSession: () => () => undefined,- updateSelectObjectSession: vi.fn(),- };- const engine = {};- attachCanvasOperations(engine, operations as never);- const render = (element: React.ReactElement) =>- renderToStaticMarkup(- createElement(- ChakraProvider,- { value: system } as ComponentProps<typeof ChakraProvider>,- createElement(I18nextProvider, { i18n: testI18n }, element)- )- );- const [inputGroup, settingsGroup] = selectObjectOperationForm.groups;- const input = render(createElement(inputGroup!.body, { engine: engine as never }));- const settings = render(createElement(settingsGroup!.body, { engine: engine as never }));- const footer = render(createElement(selectObjectOperationForm.footer, { engine: engine as never }));-- // Input group: mode, points, bbox indicator, invert switch — no verbs.- expect(input.indexOf('>Visual<')).toBeLessThan(input.indexOf('aria-label="Include 1"'));- expect(input.indexOf('aria-label="Include 1"')).toBeLessThan(input.indexOf('No box prompt'));- expect(input).toContain('>Invert<');- expect(input).not.toContain('>Process<');-- // Settings group: the set-once session dials.- expect(settings).toContain('aria-label="Select Object settings"');- expect(settings).not.toContain('>Process<');-- // Footer: chip, then Reset, Process, Apply (with the save-as menu trigger), Cancel.- expect(footer).toContain('Layer 1 · Raster layer · 1024 × 768');- expect(footer.indexOf('>Select Object<')).toBeLessThan(footer.indexOf('>Reset<'));- expect(footer.indexOf('>Reset<')).toBeLessThan(footer.indexOf('>Process<'));- expect(footer.indexOf('>Process<')).toBeLessThan(footer.indexOf('>Apply<'));- expect(footer.indexOf('>Apply<')).toBeLessThan(footer.indexOf('>Cancel<'));- expect(footer).toContain('aria-label="Save As"');- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsxindex 483be46274..4a7419597c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx@@ -1,46 +1,35 @@import type {OperationPropertyForm,+ OperationStatus,ToolFormProps,} from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';-/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { ChangeEvent } from 'react';+/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop */+import type { KeyboardEvent } from 'react';-import {- Box,- createListCollection,- Flex,- Icon,- Input,- Menu,- Portal,- Stack,- Switch,- Text,- VisuallyHidden,-} from '@chakra-ui/react';+import { createListCollection, Input, Text, VisuallyHidden } from '@chakra-ui/react';+import { isImeComposing } from '@platform/browser/imeComposition';import { Button } from '@platform/ui/Button';-import { Group } from '@platform/ui/Group';-import { MenuActionItem, MenuContent } from '@platform/ui/Menu';import { Select } from '@platform/ui/Select';-import { Tooltip } from '@platform/ui/Tooltip';import {getCanvasOperations,isSamDocumentInputValid,+ isSamRunError,type CanvasOperationCapability,- type SamSessionError,type SamSessionErrorCode,type SamSessionSnapshot,- type SamModel,type SelectObjectSaveTarget,} from '@workbench/canvas-operations/api';import { patchWorkbenchPreferences } from '@workbench/settings/store';import { useSamSession } from '@workbench/widgets/canvas/engineStoreHooks';-import { PropertySwitchRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';-import { ChevronDownIcon, SquareMinusIcon, SquarePlusIcon } from 'lucide-react';-import { useMemo } from 'react';+import {+ PropertyControlRow,+ PropertySegmentedRow,+ PropertySwitchRow,+} from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';+import { useId, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { OperationStatusChip, OperationStatusSlot } from './OperationStatusSlot';+import { OperationActions } from './OperationActions';export interface SamActionEligibility {canApply: boolean;@@ -51,22 +40,13 @@ export interface SamActionEligibility {canSave: boolean;}-export interface SamPanelViewModel {- bboxActive: boolean;- excludeCount: number;- includeCount: number;- sourceLabel: string;-}--const SAM_PROMPT_GUIDANCE_ID = 'sam-prompt-guidance';-const SAM_VISUAL_GUIDANCE_ID = 'sam-visual-guidance';+type SamStatus = SamSessionSnapshot['status'];-const SAM_STATUS_TRANSLATION_KEYS: Record<SamSessionSnapshot['status'], string> = {+/** The phases shown while work is in flight; Ready and the error state show none. */+const SAM_BUSY_TRANSLATION_KEYS: Partial<Record<SamStatus, string>> = {committing: 'widgets.layers.selectObject.statusCommitting',- error: 'widgets.layers.selectObject.statusError','preparing-source': 'widgets.layers.selectObject.statusPreparingSource','processing-sam': 'widgets.layers.selectObject.statusProcessingSam',- ready: 'widgets.layers.selectObject.statusReady','rendering-preview': 'widgets.layers.selectObject.statusRenderingPreview',scheduled: 'widgets.layers.selectObject.statusScheduled',uploading: 'widgets.layers.selectObject.statusUploading',@@ -76,6 +56,7 @@ const SAM_ERROR_TRANSLATION_KEYS: Record<SamSessionErrorCode, string> = {'adjustment-error': 'widgets.layers.selectObject.errorAdjustment','adjustment-over-budget': 'widgets.layers.selectObject.errorAdjustmentOverBudget','adjustment-too-large': 'widgets.layers.selectObject.errorAdjustmentTooLarge',+ 'commit-failed': 'widgets.layers.selectObject.errorCommitFailed',decode: 'widgets.layers.selectObject.errorDecode',empty: 'widgets.layers.selectObject.errorEmpty',invalid: 'widgets.layers.selectObject.errorInvalid',@@ -98,51 +79,16 @@ const SAVE_TARGETS: readonly SelectObjectSaveTarget[] = ['regional_guidance',];-const isSamProcessingStatus = (status: SamSessionSnapshot['status']): boolean =>+const isSamProcessingStatus = (status: SamStatus): boolean =>status === 'preparing-source' ||status === 'uploading' ||status === 'processing-sam' ||status === 'rendering-preview';-export const getSamStatusTranslationKey = (status: SamSessionSnapshot['status']): string =>- SAM_STATUS_TRANSLATION_KEYS[status];+export const getSamBusyTranslationKey = (status: SamStatus): string | null => SAM_BUSY_TRANSLATION_KEYS[status] ?? null;export const getSamErrorTranslationKey = (code: SamSessionErrorCode): string => SAM_ERROR_TRANSLATION_KEYS[code];-export const getSamPanelViewModel = (- session: SamSessionSnapshot,- formatSourceLabel: (layerName: string, width: number, height: number) => string-): SamPanelViewModel => ({- bboxActive: session.input.type === 'visual' && session.input.bbox !== null,- excludeCount: session.input.type === 'visual' ? session.input.excludePoints.length : 0,- includeCount: session.input.type === 'visual' ? session.input.includePoints.length : 0,- sourceLabel: formatSourceLabel(session.layerName, session.sourceRect.width, session.sourceRect.height),-});--/** Reserve OperationStatusSlot width so SAM status/error text cannot shift controls. */-export const SamStatusSlot = ({- error,- errorText,- isBusy,- statusText,- technicalDetailsLabel,-}: {- error: SamSessionError | null;- errorText: string | null;- isBusy: boolean;- statusText: string;- technicalDetailsLabel: string;-}) => (- <OperationStatusSlot- errorDetail={error?.detail ?? null}- errorText={error && errorText ? errorText : null}- isBusy={isBusy}- minW="0"- statusText={statusText}- technicalDetailsLabel={technicalDetailsLabel}- />-);-/** Legacy parity: canvas adoption keeps the SAM result intermediate and out of the gallery. */export const keepSamImageIntermediate = (_imageName: string): Promise<void> => Promise.resolve();@@ -154,7 +100,7 @@ export const getSamActionHandlers = (operations: CanvasOperationCapability) => (save: (target: SelectObjectSaveTarget) => void operations.saveSelectObjectSession(target, keepSamImageIntermediate),});-/** Auto Process is also the account's preference, so the next session starts from the person's last choice. */+/** Auto-update is also the account's preference, so the next session starts from the person's last choice. */export const toggleSamSetting = (operations: Pick<CanvasOperationCapability, 'updateSelectObjectSession'>,key: 'applyPolygonRefinement' | 'autoProcess' | 'isolatedPreview',@@ -162,7 +108,7 @@ export const toggleSamSetting = (): void => {const result = operations.updateSelectObjectSession({ [key]: value });if (key === 'autoProcess' && result === 'updated') {- void patchWorkbenchPreferences({ selectObjectAutoProcess: value });+ void patchWorkbenchPreferences({ selectObjectAutoUpdate: value });}};@@ -180,185 +126,119 @@ export const getSamActionEligibility = (session: SamSessionSnapshot): SamActionE};};-export const SamModeToggle = ({- disabled,- groupLabel = 'Selection mode',- mode,- onPrompt,- onVisual,- promptLabel,- visualLabel,-}: {- disabled: boolean;- groupLabel?: string;- mode: SamSessionSnapshot['input']['type'];- onPrompt(): void;- onVisual(): void;- promptLabel: string;- visualLabel: string;-}) => (- <Group aria-label={groupLabel} attached flexShrink="0" role="group">- <Button- aria-pressed={mode === 'visual'}- disabled={disabled}- variant={mode === 'visual' ? 'solid' : 'ghost'}- onClick={onVisual}- >- {visualLabel}- </Button>- <Button- aria-pressed={mode === 'prompt'}- disabled={disabled}- variant={mode === 'prompt' ? 'solid' : 'ghost'}- onClick={onPrompt}- >- {promptLabel}- </Button>- </Group>+const PointCount = ({ children }: { children: string }) => (+ <Text as="span" fontVariantNumeric="tabular-nums">+ {children}+ </Text>);-export const SamVisualInput = ({- disabled,- pointLabel,- viewModel,- onExclude,- onInclude,-}: {- disabled: boolean;- pointLabel: SamSessionSnapshot['pointLabel'];- viewModel: SamPanelViewModel;- onExclude(): void;- onInclude(): void;-}) => {- const { t } = useTranslation();- const includeLabel = t('widgets.layers.selectObject.includeCount', { count: viewModel.includeCount });- const excludeLabel = t('widgets.layers.selectObject.excludeCount', { count: viewModel.excludeCount });- return (- <Group- aria-describedby={SAM_VISUAL_GUIDANCE_ID}- aria-label={t('widgets.layers.selectObject.pointType')}- attached- flexShrink="0"- role="group"- >- <VisuallyHidden id={SAM_VISUAL_GUIDANCE_ID}>{t('widgets.layers.selectObject.visualGuidance')}</VisuallyHidden>- <Tooltip content={includeLabel}>- <Button- aria-label={includeLabel}- aria-pressed={pointLabel === 'include'}- disabled={disabled}- px="1.5"- variant={pointLabel === 'include' ? 'solid' : 'outline'}- onClick={onInclude}- >- <SquarePlusIcon />- <Text as="span" fontVariantNumeric="tabular-nums">- {viewModel.includeCount}- </Text>- </Button>- </Tooltip>- <Tooltip content={excludeLabel}>- <Button- aria-label={excludeLabel}- aria-pressed={pointLabel === 'exclude'}- disabled={disabled}- px="1.5"- variant={pointLabel === 'exclude' ? 'solid' : 'outline'}- onClick={onExclude}- >- <SquareMinusIcon />- <Text as="span" fontVariantNumeric="tabular-nums">- {viewModel.excludeCount}- </Text>- </Button>- </Tooltip>- </Group>- );-};--/** Whether a visual box is placed; lives in the More menu beside the settings. */-export const SamBboxIndicator = ({ viewModel }: { viewModel: SamPanelViewModel }) => {- const { t } = useTranslation();- const bboxText = viewModel.bboxActive- ? t('widgets.layers.selectObject.bboxActive')- : t('widgets.layers.selectObject.bboxInactive');- return (- <Text color={viewModel.bboxActive ? 'fg' : 'fg.subtle'} fontSize="md" fontWeight="medium">- {bboxText}- </Text>- );-};--export const SamPromptBody = ({- disabled,- prompt,- onChange,-}: {- disabled: boolean;- prompt: string;- onChange(event: ChangeEvent<HTMLInputElement>): void;-}) => {+/** What to select: points and a box drawn on the canvas, or a prompt; plus invert. */+const SamInputSettings = ({ engine }: ToolFormProps) => {const { t } = useTranslation();+ const session = useSamSession(engine);+ const operations = getCanvasOperations(engine);+ const promptLabelId = useId();+ const gestureGuidanceId = useId();+ if (!session) {+ return null;+ }+ const eligibility = getSamActionEligibility(session);+ const disabled = !eligibility.canEditInputs;+ const { input } = session;+ const runOnEnter = (event: KeyboardEvent<HTMLInputElement>) => {+ if (event.key === 'Enter' && !isImeComposing(event.nativeEvent) && eligibility.canProcess) {+ event.preventDefault();+ getSamActionHandlers(operations).process();+ }+ };return (<>- <Input- aria-describedby={SAM_PROMPT_GUIDANCE_ID}- aria-label={t('widgets.layers.selectObject.prompt')}- autoComplete="off"+ <PropertySegmentedRowdisabled={disabled}- flexShrink={0}- placeholder={t('widgets.layers.selectObject.promptGuidance')}- value={prompt}- w="7.5rem"- onChange={onChange}+ label={t('widgets.layers.selectObject.mode')}+ options={[+ { label: t('widgets.layers.selectObject.visual'), value: 'visual' },+ { label: t('widgets.layers.selectObject.promptMode'), value: 'prompt' },+ ]}+ value={input.type}+ onValueChange={(inputType) => operations.updateSelectObjectSession({ inputType })}+ />+ {input.type === 'prompt' ? (+ <PropertyControlRow label={t('widgets.layers.selectObject.prompt')} labelId={promptLabelId}>+ <Input+ aria-labelledby={promptLabelId}+ autoComplete="off"+ disabled={disabled}+ gridColumn="2 / -1"+ placeholder={t('widgets.layers.selectObject.promptGuidance')}+ value={input.prompt}+ onChange={(event) =>+ operations.updateSelectObjectSession({ input: { prompt: event.currentTarget.value, type: 'prompt' } })+ }+ onKeyDown={runOnEnter}+ />+ </PropertyControlRow>+ ) : (+ <>+ {/* The canvas shows these gestures as hints; this keeps them with the control for assistive tech. */}+ <VisuallyHidden id={gestureGuidanceId}>{t('widgets.layers.selectObject.visualGuidance')}</VisuallyHidden>+ <PropertySegmentedRow+ describedBy={gestureGuidanceId}+ disabled={disabled}+ label={t('widgets.layers.selectObject.pointType')}+ options={[+ {+ label: (+ <PointCount>+ {t('widgets.layers.selectObject.includeCount', { count: input.includePoints.length })}+ </PointCount>+ ),+ value: 'include',+ },+ {+ label: (+ <PointCount>+ {t('widgets.layers.selectObject.excludeCount', { count: input.excludePoints.length })}+ </PointCount>+ ),+ value: 'exclude',+ },+ ]}+ value={session.pointLabel}+ onValueChange={(pointLabel) => operations.updateSelectObjectSession({ pointLabel })}+ />+ <PropertyControlRow label={t('widgets.layers.selectObject.bbox')}>+ <Text color={input.bbox ? undefined : 'fg.muted'} minW="0" truncate>+ {input.bbox ? t('widgets.layers.selectObject.bboxActive') : t('widgets.layers.selectObject.bboxInactive')}+ </Text>+ {/* Stays mounted, disabled without a box, so setting or clearing a box never reflows the row. */}+ <Button+ aria-label={t('widgets.layers.selectObject.clearBox')}+ disabled={disabled || !input.bbox}+ variant="ghost"+ onClick={() => operations.updateSelectObjectSession({ input: { ...input, bbox: null } })}+ >+ {t('common.clear')}+ </Button>+ </PropertyControlRow>+ </>+ )}+ <PropertySwitchRow+ checked={session.invert}+ disabled={disabled}+ label={t('widgets.layers.selectObject.invert')}+ onCheckedChange={(invert) => operations.updateSelectObjectSession({ invert })}/>- <VisuallyHidden id={SAM_PROMPT_GUIDANCE_ID}>{t('widgets.layers.selectObject.promptGuidance')}</VisuallyHidden></>);};-const SamSettingsSwitch = ({- checked,- disabled,- label,- onChange,-}: {- checked: boolean;- disabled?: boolean;- label: string;- onChange(checked: boolean): void;-}) => (- <Switch.Root- checked={checked}- disabled={disabled}- justifyContent="space-between"- w="full"- onCheckedChange={({ checked: next }) => onChange(next)}- >- <Switch.Label fontSize="md">{label}</Switch.Label>- <Switch.HiddenInput />- <Switch.Control>- <Switch.Thumb />- </Switch.Control>- </Switch.Root>-);--/** Set-once session settings (model, refinement, preview behavior), shown in the More menu. */-export const SamSettings = ({- eligibility,- isProcessing,- session,- onModelChange,- onToggle,-}: {- eligibility: SamActionEligibility;- isProcessing: boolean;- session: SamSessionSnapshot;- onModelChange(model: SamModel): void;- onToggle(key: 'applyPolygonRefinement' | 'autoProcess' | 'isolatedPreview', value: boolean): void;-}) => {+/** Set-once session settings: model, refinement, preview behavior. */+const SamSettingsGroup = ({ engine }: ToolFormProps) => {const { t } = useTranslation();- const modelValue = useMemo(() => [session.model], [session.model]);+ const session = useSamSession(engine);+ const operations = getCanvasOperations(engine);+ const modelLabelId = useId();const modelCollection = useMemo(() =>createListCollection({@@ -369,134 +249,78 @@ export const SamSettings = ({}),[t]);+ if (!session) {+ return null;+ }+ const eligibility = getSamActionEligibility(session);+ const settingsLocked = !eligibility.canEditInputs;+ const processingLocked = settingsLocked || isSamProcessingStatus(session.status);return (- <Stack aria-label={t('widgets.layers.selectObject.settings')} gap="2" role="group" w="full">- <Stack gap="1">- <Text asChild fontSize="md" fontWeight="semibold">- <label htmlFor="sam-model">{t('widgets.layers.selectObject.model')}</label>- </Text>+ <>+ <PropertyControlRow label={t('widgets.layers.selectObject.model')} labelId={modelLabelId}><Selectcollection={modelCollection}- disabled={isProcessing || !eligibility.canEditInputs}- ids={{ trigger: 'sam-model' }}- value={modelValue}+ disabled={processingLocked}+ gridColumn="2 / -1"+ ids={{ label: modelLabelId }}+ value={[session.model]}onValueChange={({ value }) => {const model = value[0];if (model === 'segment-anything-2-large' || model === 'segment-anything-huge') {- onModelChange(model);+ operations.updateSelectObjectSession({ model });}}}/>- </Stack>- <SamSettingsSwitch+ </PropertyControlRow>+ <PropertySwitchRowchecked={session.applyPolygonRefinement}- disabled={isProcessing || !eligibility.canEditInputs}+ disabled={processingLocked}label={t('widgets.layers.selectObject.refine')}- onChange={(value) => onToggle('applyPolygonRefinement', value)}+ onCheckedChange={(value) => toggleSamSetting(operations, 'applyPolygonRefinement', value)}/>- <SamSettingsSwitch+ <PropertySwitchRowchecked={session.autoProcess}- disabled={!eligibility.canEditInputs}+ disabled={settingsLocked}label={t('widgets.layers.selectObject.autoProcess')}- onChange={(value) => onToggle('autoProcess', value)}+ onCheckedChange={(value) => toggleSamSetting(operations, 'autoProcess', value)}/>- <SamSettingsSwitch+ <PropertySwitchRowchecked={session.isolatedPreview}- disabled={!eligibility.canEditInputs}+ disabled={settingsLocked}label={t('widgets.layers.selectObject.isolatedPreview')}- onChange={(value) => onToggle('isolatedPreview', value)}+ onCheckedChange={(value) => toggleSamSetting(operations, 'isolatedPreview', value)}/>- </Stack>+ </>);};-/** Input mode, the visual point labels or the prompt, and invert: what changes between previews. */--/** The session's inputs: visual points or a prompt, plus the invert switch. */-const SamInputSettings = ({ engine }: ToolFormProps) => {+const useSamStatus = (engine: ToolFormProps['engine']): OperationStatus | null => {const { t } = useTranslation();const session = useSamSession(engine);- const operations = getCanvasOperations(engine);if (!session) {return null;}- const eligibility = getSamActionEligibility(session);- const viewModel = getSamPanelViewModel(session, (layerName, width, height) =>- t('widgets.layers.selectObject.sourceLayerLabel', {- height,- name: layerName,+ const busyKey = getSamBusyTranslationKey(session.status);+ return {+ busyText: busyKey ? t(busyKey) : null,+ error: session.error+ ? { detail: session.error.detail ?? null, text: t(getSamErrorTranslationKey(session.error.code)) }+ : null,+ source: t('widgets.layers.selectObject.sourceLayerLabel', {+ height: session.sourceRect.height,+ name: session.layerName,type: t(`widgets.layers.selectObject.saveAs_${session.layerType}`),- width,- })- );- return (- <>- <SamModeToggle- disabled={!eligibility.canEditInputs}- groupLabel={t('widgets.layers.selectObject.mode')}- mode={session.input.type}- promptLabel={t('widgets.layers.selectObject.promptMode')}- visualLabel={t('widgets.layers.selectObject.visual')}- onPrompt={() => operations.updateSelectObjectSession({ input: { prompt: '', type: 'prompt' } })}- onVisual={() =>- operations.updateSelectObjectSession({- input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },- })- }- />- {session.input.type === 'visual' ? (- <>- <SamVisualInput- disabled={!eligibility.canEditInputs}- pointLabel={session.pointLabel}- viewModel={viewModel}- onExclude={() => operations.updateSelectObjectSession({ pointLabel: 'exclude' })}- onInclude={() => operations.updateSelectObjectSession({ pointLabel: 'include' })}- />- <SamBboxIndicator viewModel={viewModel} />- </>- ) : (- <SamPromptBody- disabled={!eligibility.canEditInputs}- prompt={session.input.prompt}- onChange={(event) =>- operations.updateSelectObjectSession({ input: { prompt: event.currentTarget.value, type: 'prompt' } })- }- />- )}- <PropertySwitchRow- checked={session.invert}- disabled={!eligibility.canEditInputs}- label={t('widgets.layers.selectObject.invert')}- onCheckedChange={(invert) => operations.updateSelectObjectSession({ invert })}- />- </>- );-};--/** Set-once session settings: model, refinement, preview behavior. */-const SamSettingsGroup = ({ engine }: ToolFormProps) => {- const session = useSamSession(engine);- const operations = getCanvasOperations(engine);- if (!session) {- return null;- }- const eligibility = getSamActionEligibility(session);- return (- <SamSettings- eligibility={eligibility}- isProcessing={isSamProcessingStatus(session.status)}- session={session}- onModelChange={(model) => operations.updateSelectObjectSession({ model })}- onToggle={(key, value) => toggleSamSetting(operations, key, value)}- />- );+ width: session.sourceRect.width,+ }),+ };};-const APPLY_MENU_POSITIONING = { placement: 'top-end' } as const;--/** The sticky footer: status chip, Reset, Process, Apply with its save-as menu, Cancel. */-const SamFooter = ({ engine }: ToolFormProps) => {+/**+ * Find object is the manual run while auto-update is off. With auto-update on it is the retry after a failed run, the+ * only way to run the same input again, and stays while that retry runs (`retrying`), whether the button or Enter in+ * the prompt started it, so it shows the retry's progress.+ */+const SamActions = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const session = useSamSession(engine);const actions = useMemo(() => getSamActionHandlers(getCanvasOperations(engine)), [engine]);@@ -504,89 +328,39 @@ const SamFooter = ({ engine }: ToolFormProps) => {return null;}const eligibility = getSamActionEligibility(session);- const isProcessing = isSamProcessingStatus(session.status);- const isBusy = !session.error && (isProcessing || session.status === 'scheduled' || session.status === 'committing');- const sourceLabel = t('widgets.layers.selectObject.sourceLayerLabel', {- height: session.sourceRect.height,- name: session.layerName,- type: t(`widgets.layers.selectObject.saveAs_${session.layerType}`),- width: session.sourceRect.width,- });return (- <Flex align="center" gap="1" minW="0" w="full">- {/* No nowrap: the chip's own two-line clamp must keep the details button visible. */}- <Box flex="1" minW="0" overflow="hidden">- <OperationStatusChip- errorDetail={session.error?.detail ?? null}- errorText={session.error ? t(getSamErrorTranslationKey(session.error.code)) : null}- isBusy={isBusy}- sourceLabel={sourceLabel}- statusText={t(getSamStatusTranslationKey(session.status))}- technicalDetailsLabel={t('widgets.layers.selectObject.technicalDetails')}- title={t('widgets.layers.selectObject.title')}- />- </Box>- <Button disabled={!eligibility.canReset} flexShrink={0} variant="ghost" onClick={actions.reset}>- {t('widgets.layers.selectObject.reset')}- </Button>- <Button disabled={!eligibility.canProcess} flexShrink={0} loading={isProcessing} onClick={actions.process}>- {t('widgets.layers.selectObject.process')}- </Button>- <Flex flexShrink={0}>- <Button- data-pane-action="apply"- disabled={!eligibility.canApply}- loading={session.status === 'committing'}- roundedRight="none"- variant="solid"- onClick={actions.apply}- >- {t('common.apply')}- </Button>- <Menu.Root positioning={APPLY_MENU_POSITIONING}>- <Menu.Trigger asChild>- <Button- aria-label={t('widgets.layers.selectObject.saveAs')}- disabled={!eligibility.canSave}- px="1"- roundedLeft="none"- variant="solid"- >- <Icon as={ChevronDownIcon} boxSize="3.5" />- </Button>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <MenuContent minW="12rem" py="1">- {SAVE_TARGETS.map((target) => (- <MenuActionItem- key={target}- disabled={!eligibility.canSave}- label={t(`widgets.layers.selectObject.saveAs_${target}`)}- value={`save-${target}`}- onSelect={() => actions.save(target)}- />- ))}- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- </Flex>- <Button- data-pane-action="cancel"- disabled={!eligibility.canCancel}- flexShrink={0}- variant="ghost"- onClick={actions.cancel}- >- {t('common.cancel')}- </Button>- </Flex>+ <OperationActions+ applying={session.status === 'committing'}+ canApply={eligibility.canApply}+ canCancel={eligibility.canCancel}+ canReset={eligibility.canReset}+ canSave={eligibility.canSave}+ run={+ session.autoProcess && !session.retrying && !(session.error && isSamRunError(session.error.code))+ ? null+ : {+ disabled: !eligibility.canProcess,+ label: t('widgets.layers.selectObject.findObject'),+ loading: isSamProcessingStatus(session.status),+ onRun: actions.process,+ }+ }+ saveAsLabel={t('widgets.layers.selectObject.saveAs')}+ saveTargets={SAVE_TARGETS.map((target) => ({+ disabled: !eligibility.canSave,+ label: t(`widgets.layers.selectObject.saveAs_${target}`),+ value: `save-${target}`,+ onSelect: () => actions.save(target),+ }))}+ onApply={actions.apply}+ onCancel={actions.cancel}+ onReset={actions.reset}+ />);};export const selectObjectOperationForm: OperationPropertyForm = {- footer: SamFooter,+ actions: SamActions,groups: [{ body: SamInputSettings, id: 'sam-input', labelKey: 'widgets.properties.groups.input' },{@@ -597,4 +371,5 @@ export const selectObjectOperationForm: OperationPropertyForm = {},],kind: 'select-object',+ useStatus: useSamStatus,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsxindex 2d44be42f4..b4a53aac91 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx@@ -6,7 +6,7 @@ import type { ReactNode } from 'react';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { createControlLayer } from '@workbench/canvas-engine/api';-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';import { createDraftProject } from '@workbench/workbenchState';import { renderToStaticMarkup } from 'react-dom/server';@@ -20,10 +20,20 @@ interface CapturedButton {'aria-disabled'?: boolean;}-const { activeProject, buttons, hasSelection } = vi.hoisted(() => ({+const { activeProject, buttons, hasSelection, reasons, transformSession } = vi.hoisted(() => ({activeProject: { current: null as Project | null },+ transformSession: { current: null as { layerId: string } | null },buttons: new Map<string, CapturedButton>(),hasSelection: { current: true },+ /** Each action's disabled-reason tooltip, by its label. */+ reasons: new Map<string, ReactNode>(),+}));++vi.mock('@platform/ui/Tooltip', () => ({+ Tooltip: ({ children, content }: { children: { props: { children?: ReactNode } }; content: ReactNode }) => {+ reasons.set(String(children.props.children), content);+ return children;+ },}));vi.mock('@platform/ui/Button', () => ({@@ -34,13 +44,21 @@ vi.mock('@platform/ui/Button', () => ({}));vi.mock('@workbench/widgets/canvas/engineStoreHooks', () => ({useCanvasHasSelection: () => hasSelection.current,+ useTransformSession: () => transformSession.current,}));vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(activeProject.current!),}));vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }) }));vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),+ useTranslation: () => ({+ t: (key: string, options?: { message?: string; name?: string; title?: string }) =>+ options?.title !== undefined+ ? `${options.title} / ${options.message}`+ : options?.name+ ? `${key}:${options.name}`+ : key,+ }),}));const engine = {@@ -76,6 +94,8 @@ const renderRow = (layer: CanvasLayerContract): Map<string, CapturedButton> => {beforeEach(() => {buttons.clear();+ reasons.clear();+ transformSession.current = null;hasSelection.current = true;});@@ -95,18 +115,74 @@ describe('SelectionActions pixel target eligibility', () => {source: { image: { height: 10, imageName: 'raster-image', width: 10 }, type: 'image' },};+ const mask = layerContract('mask', 'inpaint_mask', { name: 'Mask' });+ const shape: CanvasLayerContract = {+ ...rasterPaint,+ source: { fill: '#fff', height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 },+ };+it.each([{ disabled: false, layer: rasterPaint, scenario: 'raster paint' },{ disabled: false, layer: controlPaint, scenario: 'control paint' },+ { disabled: false, layer: rasterImage, scenario: 'raster image' },+ { disabled: false, layer: mask, scenario: 'inpaint mask' },+ { disabled: false, layer: layerContract('region', 'regional_guidance'), scenario: 'regional guidance' },{ disabled: true, layer: { ...controlPaint, isLocked: true }, scenario: 'locked control' },{ disabled: true, layer: { ...controlPaint, isEnabled: false }, scenario: 'disabled control' },- { disabled: true, layer: rasterImage, scenario: 'raster image' },+ { disabled: true, layer: shape, scenario: 'shape layer' },])('sets Fill and Erase disabled=$disabled for $scenario', ({ disabled, layer }) => {const rendered = renderRow(layer);expect(rendered.get('widgets.canvas.toolOptions.fillSelection')?.['aria-disabled']).toBe(disabled);expect(rendered.get('widgets.canvas.toolOptions.eraseSelection')?.['aria-disabled']).toBe(disabled);});+ it('names the reason the brush and eraser would give', () => {+ renderRow({ ...mask, isHidden: true } as CanvasLayerContract);+ expect(reasons.get('widgets.canvas.toolOptions.fillSelection')).toBe(+ 'widgets.canvas.editRefusal.displayHidden:Mask / widgets.canvas.editRefusal.displayHiddenMessage'+ );+ renderRow(shape);+ expect(reasons.get('widgets.canvas.toolOptions.eraseSelection')).toBe(+ 'widgets.canvas.toolOptions.selectionNeedsPixelLayer'+ );+ });++ it('words a layer out of generation by the control that brings it back: the dot on overlays, the eye on raster', () => {+ renderRow({ ...mask, isEnabled: false });+ expect(reasons.get('widgets.canvas.toolOptions.fillSelection')).toBe(+ 'widgets.canvas.editRefusal.excluded:Mask / widgets.canvas.editRefusal.excludedMessage'+ );+ renderRow({ ...rasterPaint, isEnabled: false });+ expect(reasons.get('widgets.canvas.toolOptions.fillSelection')).toBe(+ 'widgets.canvas.editRefusal.hidden:Raster / widgets.canvas.editRefusal.hiddenMessage'+ );+ });++ it('fills a transparency-locked layer but refuses to erase it', () => {+ const rendered = renderRow({ ...rasterPaint, isTransparencyLocked: true } as CanvasLayerContract);+ expect(rendered.get('widgets.canvas.toolOptions.fillSelection')?.['aria-disabled']).toBe(false);+ expect(rendered.get('widgets.canvas.toolOptions.eraseSelection')?.['aria-disabled']).toBe(true);+ expect(reasons.get('widgets.canvas.toolOptions.eraseSelection')).toBe(+ 'widgets.canvas.editRefusal.alphaLocked:Raster / widgets.canvas.editRefusal.alphaLockedMessage'+ );+ });++ it('waits for an open transform session, naming its layer, as the engine does', () => {+ transformSession.current = { layerId: 'mask' };+ const rendered = renderRow(mask);+ for (const key of ['fillSelection', 'eraseSelection']) {+ expect(rendered.get(`widgets.canvas.toolOptions.${key}`)?.['aria-disabled']).toBe(true);+ expect(reasons.get(`widgets.canvas.toolOptions.${key}`)).toBe(+ 'widgets.canvas.editRefusal.transformSession:Mask / widgets.canvas.editRefusal.transformSessionMessage'+ );+ }+ });++ it('keeps Lift to the layers it can lift from', () => {+ const rendered = renderRow(mask);+ expect(rendered.get('widgets.canvas.toolOptions.liftSelectionToLayer')?.['aria-disabled']).toBe(true);+ });+it('disables every action with no live selection, even on an eligible layer', () => {hasSelection.current = false;const rendered = renderRow(rasterPaint);@@ -116,7 +192,7 @@ describe('SelectionActions pixel target eligibility', () => {});it('leaves invert and deselect enabled on an ineligible layer (they need only a selection)', () => {- const rendered = renderRow(rasterImage);+ const rendered = renderRow(shape);expect(rendered.get('widgets.canvas.toolOptions.invertSelection')?.['aria-disabled']).toBe(false);expect(rendered.get('widgets.canvas.toolOptions.deselect')?.['aria-disabled']).toBe(false);});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsxindex c4782e7283..8adf8dcd84 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx@@ -1,13 +1,21 @@-import type { SelectionOp } from '@workbench/canvas-engine/api';+import type { CanvasDocumentContractV3, SelectionOp, SelectionPixelEditRefusal } from '@workbench/canvas-engine/api';import type { ToolFormProps } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';+import type { TFunction } from 'i18next';import { HStack } from '@chakra-ui/react';import { Button, IconButton } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';-import { isLeafPixelEditEligible, lookupDocumentLeaf } from '@workbench/canvas-engine/api';+import {+ getDocumentNode,+ isLeafPixelEditEligible,+ isOverlayStack,+ lookupDocumentLeaf,+ lookupDocumentNodeState,+ selectionPixelEditRefusal,+} from '@workbench/canvas-engine/api';import { useNotify } from '@workbench/useNotify';-import { useCanvasHasSelection } from '@workbench/widgets/canvas/engineStoreHooks';-import { reportLayerOperation } from '@workbench/widgets/canvas/useStructuralCommit';+import { useCanvasHasSelection, useTransformSession } from '@workbench/widgets/canvas/engineStoreHooks';+import { describeLayerEditRefusal, reportLayerOperation } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { SquareIcon, SquareMinusIcon, SquarePlusIcon, SquaresIntersectIcon } from 'lucide-react';import { useCallback } from 'react';@@ -102,19 +110,61 @@ const SelectionAction = ({);};+/** The selected leaf, `'group'` for a selected group, or null: what `selectionPixelEditRefusal` judges. */+const selectedLeafOrGroup = (document: CanvasDocumentContractV3) => {+ const node = getDocumentNode(document, document.selectedLayerId);+ return node ? (lookupDocumentLeaf(document, node.id) ?? 'group') : null;+};++/**+ * Why Fill or Erase is unavailable, in the words of the notice the engine would give: what is wrong and what to do.+ * `layer` names the layer that refuses and whether it sits in an overlay stack.+ */+const describePixelRefusal = (+ status: Exclude<SelectionPixelEditRefusal, 'no-target' | 'unsupported'> | 'transform-session',+ layer: { id: string; name: string; overlay: boolean },+ t: TFunction+): string => {+ const { message, title } = describeLayerEditRefusal(+ { layerId: layer.id, layerName: layer.name, status },+ t,+ layer.overlay+ );+ return t('widgets.canvas.toolOptions.refusalReason', { message, title });+};+/**- * Commands over the live selection. Select all always works; fill, erase and- * lift need an eligible (unlocked, visible) paint layer — the same rule the- * engine enforces; invert and deselect need only a selection.+ * Commands over the live selection. Select all always works; fill and erase+ * need a layer the brush and eraser would edit in place, refused the way they+ * are (the engine's own rule); lift needs an eligible paint or control layer;+ * invert and deselect need only a selection.*/export const SelectionActions = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const notify = useNotify();const hasSelection = useCanvasHasSelection(engine);- const canPaintTarget = useActiveProjectSelector((project) => {+ const canLiftTarget = useActiveProjectSelector((project) => {const { document } = project.canvas;return isLeafPixelEditEligible(lookupDocumentLeaf(document, document.selectedLayerId ?? ''));});+ const fillRefusal = useActiveProjectSelector((project) =>+ selectionPixelEditRefusal(selectedLeafOrGroup(project.canvas.document), 'fill')+ );+ const eraseRefusal = useActiveProjectSelector((project) =>+ selectionPixelEditRefusal(selectedLeafOrGroup(project.canvas.document), 'erase')+ );+ const selectedName = useActiveProjectSelector(+ (project) => getDocumentNode(project.canvas.document, project.canvas.document.selectedLayerId)?.name ?? ''+ );+ const selectedOverlay = useActiveProjectSelector((project) => {+ const { document } = project.canvas;+ const stack = lookupDocumentNodeState(document, document.selectedLayerId ?? '')?.stack;+ return stack !== undefined && isOverlayStack(stack);+ });+ const sessionLayerId = useTransformSession(engine)?.layerId ?? null;+ const sessionName = useActiveProjectSelector((project) =>+ sessionLayerId === null ? '' : (getDocumentNode(project.canvas.document, sessionLayerId)?.name ?? '')+ );const onSelectAll = useCallback(() => engine.selection.selectAll(), [engine]);const onFill = useCallback(() => engine.selection.fillSelection(), [engine]);const onErase = useCallback(() => engine.selection.eraseSelection(), [engine]);@@ -127,23 +177,35 @@ export const SelectionActions = ({ engine }: ToolFormProps) => {}}, [engine, notify, t]);const needsSelection = hasSelection ? null : t('widgets.canvas.toolOptions.selectionNeedsSelection');- const needsPaintTarget =- needsSelection ?? (canPaintTarget ? null : t('widgets.canvas.toolOptions.selectionNeedsPaintLayer'));+ // The engine's order: what the target refuses, then an open transform session.+ const pixelReason = (refusal: SelectionPixelEditRefusal | null): string | null =>+ needsSelection ??+ (refusal === 'no-target' || refusal === 'unsupported'+ ? t('widgets.canvas.toolOptions.selectionNeedsPixelLayer')+ : refusal+ ? describePixelRefusal(refusal, { id: '', name: selectedName, overlay: selectedOverlay }, t)+ : sessionLayerId !== null+ ? describePixelRefusal('transform-session', { id: sessionLayerId, name: sessionName, overlay: false }, t)+ : null);+ const fillReason = pixelReason(fillRefusal);+ const eraseReason = pixelReason(eraseRefusal);+ const liftReason =+ needsSelection ?? (canLiftTarget ? null : t('widgets.canvas.toolOptions.selectionNeedsPaintLayer'));return (<HStack flexWrap="wrap" gap="1"><SelectionAction disabledReason={null} label={t('widgets.canvas.toolOptions.selectAll')} onClick={onSelectAll} /><SelectionAction- disabledReason={needsPaintTarget}+ disabledReason={fillReason}label={t('widgets.canvas.toolOptions.fillSelection')}onClick={onFill}/><SelectionAction- disabledReason={needsPaintTarget}+ disabledReason={eraseReason}label={t('widgets.canvas.toolOptions.eraseSelection')}onClick={onErase}/><SelectionAction- disabledReason={needsPaintTarget}+ disabledReason={liftReason}label={t('widgets.canvas.toolOptions.liftSelectionToLayer')}onClick={onLiftToLayer}/>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsxindex d45cea4b2d..5f844916d9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx@@ -55,7 +55,7 @@ afterEach(async () => {host = null;});-/** The engine's interaction store as the footer reads it: a value per key and a listener set per key. */+/** The engine's interaction store as the actions row reads it: a value per key and a listener set per key. */const createEngine = () => {const state: Partial<CanvasInteractionState> = {hasFloatingSelection: false,@@ -83,9 +83,9 @@ const createEngine = () => {return { engine: engine as unknown as ToolFormProps['engine'], setPending };};-/** Renders the footer `width` px wide. */-const renderFooter = async (engine: ToolFormProps['engine'], width = 320) => {- const Footer = transformForm.footer!;+/** Renders the actions row `width` px wide. */+const renderActions = async (engine: ToolFormProps['engine'], width = 320) => {+ const Actions = transformForm.actions!;host = document.createElement('div');host.style.width = `${width}px`;document.body.append(host);@@ -94,17 +94,17 @@ const renderFooter = async (engine: ToolFormProps['engine'], width = 320) => {root!.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <Footer engine={engine} />+ <Actions engine={engine} /></ChakraProvider></I18nextProvider>));};-describe('Transform footer', () => {+describe('Transform actions', () => {it('says while a transform waits for its stroke to save, in a polite live region, and clears after', async () => {const { engine, setPending } = createEngine();- await renderFooter(engine);+ await renderActions(engine);const status = page.getByRole('status');await expect.element(status).toBeInTheDocument();await expect.element(status).toHaveTextContent('');@@ -119,7 +119,7 @@ describe('Transform footer', () => {it('shows the whole status in a tooltip where a narrow pane truncates it', async () => {const { engine, setPending } = createEngine();- await renderFooter(engine, 180);+ await renderActions(engine, 180);await setPending('layer-1');const status = page.getByRole('status');const line = status.element() as HTMLElement;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsxindex 888ade008c..92e89923ed 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx@@ -289,7 +289,7 @@ const FrameSizeSettings = ({ engine }: ToolFormProps) => {* pixels instead of opening a layer session; the numerics meanwhile edit the* settled selected layer, matching the Transform pane.*/-const TransformFooter = ({ engine }: ToolFormProps) => {+const TransformActions = ({ engine }: ToolFormProps) => {const { t } = useTranslation();const session = useTransformSession(engine);const hasFloat = useCanvasHasFloatingSelection(engine);@@ -331,7 +331,7 @@ export const bboxForm: ToolPropertyForm = {};export const transformForm: ToolPropertyForm = {- footer: TransformFooter,+ actions: TransformActions,groups: [POSITION_GROUP,{ body: TransformScaleSettings, id: 'transform-scale', labelKey: 'widgets.transform.scale' },diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsxindex 335c7aa315..5b99dea752 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/PropertyPrimitives.tsx@@ -161,7 +161,7 @@ export const PropertySegmentedRow = <Value extends string>({disabled?: boolean;label: string;onValueChange: (value: Value) => void;- options: readonly { value: Value; label: string; icon?: ElementType; disabled?: boolean }[];+ options: readonly { value: Value; label: ReactNode; icon?: ElementType; disabled?: boolean }[];value: Value;}) => {const handleChange = useCallback(diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.tsindex 4175568bde..71f407e996 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts@@ -2,7 +2,7 @@ import type { ToolId } from '@workbench/canvas-engine/api';import { describe, expect, it } from 'vitest';-import { OPERATION_PRESENTATION_ADAPTERS, TOOL_PRESENTATION_ADAPTERS } from './toolAdapters';+import { TOOL_PRESENTATION_ADAPTERS } from './toolAdapters';const TOOL_IDS = Object.keys({bbox: true,@@ -69,12 +69,4 @@ describe('tool presentation adapters', () => {expect(en.widgets.properties.sections.tool).toEqual(expect.any(String));expect(en.widgets.properties.sections.operation).toEqual(expect.any(String));});-- it('gives every guarded operation groups and a footer so Apply and Cancel stay in place', () => {- expect(Object.keys(OPERATION_PRESENTATION_ADAPTERS).sort()).toEqual(['filter', 'select-object']);- for (const adapter of Object.values(OPERATION_PRESENTATION_ADAPTERS)) {- expect(adapter.footer).toBeDefined();- expect(adapter.groups.length).toBeGreaterThan(0);- }- });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.tsindex a8c0f24ad7..4e22f081fa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolFormContracts.ts@@ -40,14 +40,26 @@ export interface ToolPropertyForm {paintsLeaf?: boolean;preview?: ComponentType<ToolFormProps>;groups: readonly ToolPropertyGroup[];- /** Sticks to the pane's bottom edge while the form scrolls: session status, Apply, Cancel. */- footer?: ComponentType<ToolFormProps>;+ /** The form's last row, inside the Tool section: session status, Apply, Cancel. */+ actions?: ComponentType<ToolFormProps>;}-/** A guarded operation's pane form: named groups plus the sticky footer that owns its verbs. */+/** What a running operation reports to its section, in the person's language. */+export interface OperationStatus {+ /** The layer it runs on (name, type, size): the section subtitle's tooltip. */+ source: string;+ /** The phase while work is in flight, beside the section title; null at rest. */+ busyText: string | null;+ /** The failure, shown after the groups; `detail` is the technical cause when it adds to `text`. */+ error: { text: string; detail: string | null } | null;+}++/** A guarded operation's pane form: named groups, its status, and the actions row that owns its verbs. */export interface OperationPropertyForm {kind: CanvasOperationKind;groups: readonly ToolPropertyGroup[];- /** Status chip, Process/Reset, Apply and Cancel; pinned to the pane's bottom edge. */- footer: ComponentType<ToolFormProps>;+ /** A hook the Operation section calls on every render; null while the operation has no session yet. */+ useStatus(engine: CanvasToolOptionsEngine): OperationStatus | null;+ /** Reset, Cancel, the manual run, and Apply with its save-as menu; the section's last row before any error. */+ actions: ComponentType<ToolFormProps>;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasRecovery.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasRecovery.browser.test.tsxnew file mode 100644index 0000000000..7673d2e43d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasRecovery.browser.test.tsx@@ -0,0 +1,104 @@+import type { Project } from '@workbench/projectContracts';+import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';++import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { describe, expect, it, vi } from 'vitest';++/** The hook reads and writes a real store; only the context that would hand it over is stood in for. */+const harness = vi.hoisted(() => ({+ stopGenerating: null as null | (() => void),+ store: null as ReturnType<typeof createWorkbenchStore> | null,+}));++vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useActiveProjectId: () => harness.store!.getState().activeProjectId,+ useOptionalWorkbenchCommands: () => harness.store!.commands,+ useWorkbenchCommands: () => harness.store!.commands,+ useWorkbenchQueries: () => harness.store!.queries,+}));++const { useStagingRecovery } = await import('./useCanvasRecovery');++const i18n = createInstance();+await i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: {} });++/** A run still generating, bound for `project`'s canvas as it is now, or for the Gallery. */+const run = (id: string, project: Project, destination: 'canvas' | 'gallery' = 'canvas'): QueueItem =>+ ({+ backendItemIds: [1, 2],+ cancellable: true,+ id,+ snapshot: {+ canvas: { document: project.canvas.document, documentRevision: project.canvas.documentRevision },+ destination,+ presentation: { batchCount: 2, height: 64, width: 64 },+ sourceId: 'canvas',+ submittedAt: '2026-07-16T00:00:00.000Z',+ },+ status: 'running',+ }) as unknown as QueueItem;++const keepStopGenerating = (stopGenerating: () => void) => {+ harness.stopGenerating = stopGenerating;+};++const Probe = ({ onReady }: { onReady: (stopGenerating: () => void) => void }) => {+ onReady(useStagingRecovery().stopGenerating);+ return null;+};++describe('Stop generating', () => {+ it('stops every run still generating for this canvas, and nothing else, with one notice for all', async () => {+ const shown = createInitialWorkbenchState().projects[0]!;+ const other = { ...createInitialWorkbenchState().projects[0]!, id: 'other-project' };+ const initial = createInitialWorkbenchState();+ harness.store = createWorkbenchStore({+ ...initial,+ activeProjectId: shown.id,+ projects: [+ {+ ...shown,+ queue: { items: [run('canvas-1', shown), run('canvas-2', shown), run('to-gallery', shown, 'gallery')] },+ },+ { ...other, queue: { items: [run('other-canvas', other)] } },+ ],+ });+ const host = document.createElement('div');+ document.body.append(host);+ const root = createRoot(host);+ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <Probe onReady={keepStopGenerating} />+ </I18nextProvider>+ )+ );++ await act(() => harness.stopGenerating!());++ const statuses = Object.fromEntries(+ harness.store+ .getState()+ .projects.flatMap((project) => project.queue.items.map((item) => [item.id, item.status] as const))+ );+ expect(statuses).toEqual({+ 'canvas-1': 'cancelled',+ 'canvas-2': 'cancelled',+ 'other-canvas': 'running',+ 'to-gallery': 'running',+ });+ expect(harness.store.getState().notifications.map((notice) => notice.title)).toEqual([+ 'widgets.canvas.staging.stoppedGenerating',+ ]);++ await act(() => root.unmount());+ host.remove();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasRecovery.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasRecovery.tsindex a51bda0cf0..76925f504f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasRecovery.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useCanvasRecovery.ts@@ -135,7 +135,10 @@ const undoWithPoint = async (}};-/** Discard, Discard all and accept, each reporting what left staging with a way to bring it back. */+/**+ * Discard, Discard all and accept, each reporting what left staging with a way to bring it back, and Stop generating,+ * which stops every run still generating for the canvas and keeps its results.+ */export const useStagingRecovery = () => {const { t } = useTranslation();const notify = useNotify();@@ -275,9 +278,24 @@ export const useStagingRecovery = () => {[offerRestore, projectId, t]);+ const stopGenerating = useCallback(() => {+ const project = queries.getProject(projectId);+ if (!project) {+ return;+ }+ const inFlight = getInFlightCanvasItems(project.canvas, project.queue.items);+ // One notice says how many stopped, not a cancel notice each.+ for (const item of inFlight) {+ queue.cancel(projectId, item.id, null);+ }+ if (inFlight.length > 0) {+ notify.info(t('widgets.canvas.staging.stoppedGenerating', { count: inFlight.length }));+ }+ }, [notify, projectId, queries, queue, t]);+return useMemo(- () => ({ discardAll, discardSelected, reportAccepted }),- [discardAll, discardSelected, reportAccepted]+ () => ({ discardAll, discardSelected, reportAccepted, stopGenerating }),+ [discardAll, discardSelected, reportAccepted, stopGenerating]);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.tsindex 8e3f6b421a..f99a090b66 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts@@ -2,6 +2,7 @@ import type {AdjustmentRefusal,AdjustmentRefusalReason,CanvasDocumentCapability,+ CanvasLayerEditRefusal,CanvasLayerBasePatch,CanvasLayerCapability,CanvasLayerConfigPatch,@@ -54,6 +55,95 @@ const ADJUSTMENT_REFUSAL_KEYS: Record<AdjustmentRefusalReason, string> = {export const describeAdjustmentRefusal = (refusal: AdjustmentRefusal, t: TFunction): string =>t(ADJUSTMENT_REFUSAL_KEYS[refusal.reason], { name: refusal.ownerName });+/**+ * Each status's title and message for a layer the Canvas refused to edit, and the message that goes with an offer to paint on a new layer instead: only a+ * hidden or locked layer makes that offer, since a new layer above it escapes the cause.+ */+const LAYER_REFUSAL_KEYS: Record<+ CanvasLayerEditRefusal['status'],+ { message: string; offerMessage: string | null; title: string }+> = {+ 'erase-unsupported': {+ message: 'widgets.canvas.editRefusal.eraseUnsupportedMessage',+ offerMessage: null,+ title: 'widgets.canvas.editRefusal.eraseUnsupported',+ },+ 'gradient-unsupported': {+ message: 'widgets.canvas.editRefusal.gradientUnsupportedMessage',+ offerMessage: null,+ title: 'widgets.canvas.editRefusal.gradientUnsupported',+ },+ 'layer-alpha-locked': {+ message: 'widgets.canvas.editRefusal.alphaLockedMessage',+ offerMessage: null,+ title: 'widgets.canvas.editRefusal.alphaLocked',+ },+ 'layer-display-hidden': {+ message: 'widgets.canvas.editRefusal.displayHiddenMessage',+ offerMessage: 'widgets.canvas.editRefusal.displayHiddenOfferMessage',+ title: 'widgets.canvas.editRefusal.displayHidden',+ },+ 'layer-hidden': {+ message: 'widgets.canvas.editRefusal.hiddenMessage',+ offerMessage: 'widgets.canvas.editRefusal.hiddenOfferMessage',+ title: 'widgets.canvas.editRefusal.hidden',+ },+ 'layer-loading': {+ message: 'widgets.canvas.editRefusal.loadingMessage',+ offerMessage: null,+ title: 'widgets.canvas.editRefusal.loading',+ },+ 'layer-unpaintable': {+ message: 'widgets.canvas.editRefusal.unpaintableMessage',+ offerMessage: null,+ title: 'widgets.canvas.editRefusal.unpaintable',+ },+ 'layer-locked': {+ message: 'widgets.canvas.editRefusal.lockedMessage',+ offerMessage: 'widgets.canvas.editRefusal.lockedOfferMessage',+ title: 'widgets.canvas.editRefusal.locked',+ },+ 'selection-erase-unsupported': {+ message: 'widgets.canvas.editRefusal.selectionEraseUnsupportedMessage',+ offerMessage: null,+ title: 'widgets.canvas.editRefusal.selectionEraseUnsupported',+ },+ 'transform-session': {+ message: 'widgets.canvas.editRefusal.transformSessionMessage',+ offerMessage: null,+ title: 'widgets.canvas.editRefusal.transformSession',+ },+};++/**+ * An overlay (mask, regional guidance or control layer) out of generation is turned back on with its row's dot, not its+ * eye, which only hides it on the canvas; its notice says so. Only raster images offer a new layer, so it has no offer.+ */+const OVERLAY_EXCLUDED_KEYS = {+ message: 'widgets.canvas.editRefusal.excludedMessage',+ offerMessage: null,+ title: 'widgets.canvas.editRefusal.excluded',+} as const;++/**+ * The notice for a layer the active tool could not edit: its title, its message, and whether it offers a new paint+ * layer instead (only for a status that has offer wording). `overlay` says the layer sits in an overlay stack.+ */+export const describeLayerEditRefusal = (+ refusal: CanvasLayerEditRefusal,+ t: TFunction,+ overlay: boolean+): { message: string; offersNewLayer: boolean; title: string } => {+ const keys =+ overlay && refusal.status === 'layer-hidden' ? OVERLAY_EXCLUDED_KEYS : LAYER_REFUSAL_KEYS[refusal.status];+ const offerMessage = refusal.canPaintNewLayer ? keys.offerMessage : null;+ return {+ message: t(offerMessage ?? keys.message),+ offersNewLayer: offerMessage !== null,+ title: t(keys.title, { name: refusal.layerName }),+ };+};+/** Words a refusal that names its layer: an image that could not be read, or adjustments that could not run. */export const describeNamedRefusal = (refusal: AdjustmentRefusal | LayerUnreadable, t: TFunction): string =>refusal.status === 'unreadable'diff --git a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/manifest.tsindex 7da591ed26..5124b99b66 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/diagnostics/manifest.ts@@ -5,6 +5,7 @@ import { BugIcon } from 'lucide-react';export const diagnosticsWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['right'],+ chrome: { body: 'fill' },failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },icon: BugIcon,id: 'diagnostics',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.tsindex 3c15c8b827..94a3b277e3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/manifest.ts@@ -7,6 +7,7 @@ export const galleryWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['left', 'right', 'center', 'bottom'],bottomPanel: 'expandable',+ chrome: { body: 'fill' },failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },icon: ImageIcon,id: 'gallery',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/manifest.tsindex b839f422a4..3f6c4e3dae 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/manifest.ts@@ -1,13 +1,13 @@import type { WidgetManifest } from '@workbench/widgetContracts';-import { SlidersHorizontalIcon } from 'lucide-react';+import { Settings2Icon } from 'lucide-react';export const generateWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['left'],failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },graphBearing: { defaultGraphId: 'generate-graph', sourceId: 'generate', surfaces: ['left'] },- icon: SlidersHorizontalIcon,+ icon: Settings2Icon,id: 'generate',label: (t) => t('widgets.labels.generate'),// The project's generation flags: they apply to every generation the project runs (Canvas and Upscale included),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.tsindex 8037a62645..66f69d09dc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/manifest.ts@@ -8,6 +8,7 @@ export const imageMapWidgetManifest: WidgetManifest = {allowFloating: true,allowMultiple: false,allowedRegions: ['left', 'right', 'center'],+ chrome: { body: 'fill' },failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },icon: MapIcon,id: 'image-map',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.tsindex 630b84ad3e..abe2b989bf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/settingsContribution.ts@@ -27,5 +27,7 @@ export const imageMapSettingsContribution: SettingsContribution = {keywords: 'click gallery selection',},],+ // The vocabulary joins this section from the application contributions; it stays in the dialog.+ quick: ['showClusterLabels', 'clusterEps', 'clickSelectsCluster'],load: () => import('./settingsBindings'),};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsxindex 303512b71b..f17b1624b7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx@@ -197,8 +197,8 @@ const scrub = async (frame: HTMLElement, offsets: number[]): Promise<void> => {const rect = frame.getBoundingClientRect();const startX = rect.left + rect.width / 2;const y = rect.top + rect.height / 2;- // The track is inset 10px from each edge of the frame.- const xAt = (offset: number): number => startX + offset * (rect.width - 20);+ // The track is inset 6px from each edge of the frame.+ const xAt = (offset: number): number => startX + offset * (rect.width - 12);await settle(() => pointer(frame, 'pointerdown', startX, y));for (const offset of offsets) {await settle(() => pointer(window, 'pointermove', xAt(offset), y));@@ -232,7 +232,7 @@ describe('scalar and levels editors', () => {const rect = hue.getBoundingClientRect();const startX = rect.left + rect.width / 2;const y = rect.top + rect.height / 2;- const trackWidth = rect.width - 20;+ const trackWidth = rect.width - 12;await settle(() => pointer(hue, 'pointerdown', startX, y));await settle(() => pointer(window, 'pointermove', startX + trackWidth * 0.1, y));@@ -273,7 +273,7 @@ describe('scalar and levels editors', () => {const rect = hue.getBoundingClientRect();const startX = rect.left + rect.width / 2;const y = rect.top + rect.height / 2;- const trackWidth = rect.width - 20;+ const trackWidth = rect.width - 12;await settle(() => pointer(hue, 'pointerdown', startX, y));await settle(() => pointer(window, 'pointermove', startX + trackWidth * 0.1, y));@@ -322,7 +322,7 @@ describe('scalar and levels editors', () => {const y = rect.top + rect.height / 2;await settle(() => pointer(hue, 'pointerdown', startX, y));- await settle(() => pointer(window, 'pointermove', startX + (rect.width - 20) * 0.1, y));+ await settle(() => pointer(window, 'pointermove', startX + (rect.width - 12) * 0.1, y));expect(latestAdjustments()[2]).toMatchObject({ id: 'hue1', rotation: 36 });await act(() => stub.engine.history.undo());diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlAdapterRows.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlAdapterRows.tsxindex c5bd03ca13..09142aa4b5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlAdapterRows.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlAdapterRows.tsx@@ -6,13 +6,9 @@ import { getControlAdapterMinWeight } from '@features/generation/graph';import { SegmentedControl } from '@platform/ui/SegmentedControl';import { Slider } from '@platform/ui/Slider';import { Tooltip } from '@platform/ui/Tooltip';-import {- FormNumberField,- useNumberCommit,- useSliderGesture,-} from '@workbench/widgets/canvas/tool-presentation/FormControls';+import { FormNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/FormControls';import { PropertyControlRow } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';-import { useCallback, useId, useMemo, useState } from 'react';+import { useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { formatPanelText, type ControlPanelModel, type ControlPriority } from './controlPanelModel';@@ -32,9 +28,8 @@ type AdapterPatch = Partial<Pick<CanvasControlAdapterContract, 'weight' | 'beginexport interface ControlAdapterEditing {/** Shows a gesture's value live; the commit that ends it records one undo step. */preview(patch: AdapterPatch): void;+ /** Records the patch from the value its gesture's preview replaced; one that changes nothing drops the preview. */commit(patch: AdapterPatch, label: string): void;- /** Ends a gesture that came back to where it began, restoring what it previewed. */- cancel(): void;}/** Weight, Steps and Priority: the adapter's own values, edited the same way whatever drives the layer. */@@ -55,28 +50,64 @@ export const ControlAdapterRows = ({const priorityLabel = t('widgets.layers.control.rows.priority');const priorityReasonId = useId();+ // Previews reach the document, so `adapter` already carries a dragged value: every gesture end commits, and the+ // commit compares with the value the preview replaced, dropping a gesture that changed nothing. Drafts keep the+ // thumbs on the pointer between previews, which land at most once per frame.+ // The held gesture's last preview, committed as its release would if the rows unmount mid-gesture.+ const pendingRef = useRef<{ label: string; patch: AdapterPatch } | null>(null);+ const previewGesture = useCallback(+ (patch: AdapterPatch, label: string) => {+ pendingRef.current = { label, patch };+ editing.preview(patch);+ },+ [editing]+ );+ const commitGesture = useCallback(+ (patch: AdapterPatch, label: string) => {+ pendingRef.current = null;+ editing.commit(patch, label);+ },+ [editing]+ );+ const flushGestureOnUnmount = useCallback(+ (node: HTMLDivElement | null) =>+ node+ ? () => {+ const pending = pendingRef.current;+ if (pending) {+ commitGesture(pending.patch, pending.label);+ }+ }+ : undefined,+ [commitGesture]+ );+// Weight: the slider covers 0–2; typed values reach the kind's lower bound.const commitWeight = useCallback((weight: number) => editing.commit({ weight }, weightLabel), [editing, weightLabel]);- const previewWeight = useCallback((weight: number) => editing.preview({ weight }), [editing]);- const weightGesture = useSliderGesture(adapter.weight, commitWeight, previewWeight);+ const [weightDraft, setWeightDraft] = useState<number | null>(null);+ const weight = weightDraft ?? adapter.weight;const weightValue = useMemo(- () => [clamp(weightGesture.value, CONTROL_WEIGHT_BOUNDS.sliderMin, CONTROL_WEIGHT_BOUNDS.sliderMax)],- [weightGesture.value]+ () => [clamp(weight, CONTROL_WEIGHT_BOUNDS.sliderMin, CONTROL_WEIGHT_BOUNDS.sliderMax)],+ [weight]);const weightAria = useMemo(() => [weightLabel], [weightLabel]);const handleWeightChange = useCallback(- ({ value }: SliderValueChangeDetails) => weightGesture.onChange(value[0]!),- [weightGesture]+ ({ value: [next] }: SliderValueChangeDetails) => {+ if (next !== undefined) {+ setWeightDraft(next);+ previewGesture({ weight: next }, weightLabel);+ }+ },+ [previewGesture, weightLabel]);const handleWeightChangeEnd = useCallback(- ({ value }: SliderValueChangeDetails) => {- const next = value[0]!;- weightGesture.onChangeEnd(next);- if (next === adapter.weight) {- editing.cancel();+ ({ value: [next] }: SliderValueChangeDetails) => {+ setWeightDraft(null);+ if (next !== undefined) {+ commitGesture({ weight: next }, weightLabel);}},- [adapter.weight, editing, weightGesture]+ [commitGesture, weightLabel]);const minWeight = getControlAdapterMinWeight(model.kind);const handleWeightTyped = useNumberCommit(@@ -96,25 +127,19 @@ export const ControlAdapterRows = ({if (value.length === 2) {const next: [number, number] = [value[0]!, value[1]!];setRangeDraft(next);- editing.preview({ beginEndStepPct: next });+ previewGesture({ beginEndStepPct: next }, stepsLabel);}},- [editing]+ [previewGesture, stepsLabel]);const handleRangeChangeEnd = useCallback(({ value }: SliderValueChangeDetails) => {setRangeDraft(null);- if (value.length !== 2) {- return;- }- const [begin, end] = adapter.beginEndStepPct;- if (value[0] === begin && value[1] === end) {- editing.cancel();- return;+ if (value.length === 2) {+ commitGesture({ beginEndStepPct: [value[0]!, value[1]!] }, stepsLabel);}- editing.commit({ beginEndStepPct: [value[0]!, value[1]!] }, stepsLabel);},- [adapter.beginEndStepPct, editing, stepsLabel]+ [commitGesture, stepsLabel]);const stepsReadout = rangeDraft? t('widgets.layers.control.stepsReadout', {@@ -152,7 +177,8 @@ export const ControlAdapterRows = ({: null;return (- <>+ // `contents` keeps the rows in the panel's own layout; the box only marks when they unmount.+ <Box ref={flushGestureOnUnmount} display="contents"><PropertyControlRow label={weightLabel}><Slideraria-label={weightAria}@@ -172,7 +198,7 @@ export const ControlAdapterRows = ({max={CONTROL_WEIGHT_BOUNDS.inputMax}min={minWeight}step={CONTROL_WEIGHT_BOUNDS.step}- value={formatWeight(weightGesture.value)}+ value={formatWeight(weight)}onValueCommit={handleWeightTyped}/></PropertyControlRow>@@ -216,6 +242,6 @@ export const ControlAdapterRows = ({) : null}</Box></PropertyControlRow>- </>+ </Box>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsxindex 0983917e16..c866e83b60 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.browser.test.tsx@@ -4,6 +4,7 @@ import type {CanvasLayerContract,CanvasLayerPreviewMutation,} from '@workbench/canvas-engine/api';+import type { StructuralEngineStub } from '@workbench/canvas-engine/controllers/structuralEngine.testStub';import type { ControlLayerIntent, ControlLayerIntentResult } from '@workbench/canvas-operations/api';import { ChakraProvider } from '@chakra-ui/react';@@ -15,7 +16,8 @@ import { toaster } from '@platform/ui/toaster';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { applyThemeToRoot } from '@theme/applyTheme';import { DEFAULT_THEME_ID, system } from '@theme/system';-import { createControlLayer, createDocumentModel } from '@workbench/canvas-engine/api';+import { createControlLayer, createDocumentModel, getDocumentLayer } from '@workbench/canvas-engine/api';+import { createStructuralEngineStub } from '@workbench/canvas-engine/controllers/structuralEngine.testStub';import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { previewInverse } from '@workbench/canvas-engine/document-model/documentModel';import { createControlDetectionStatusStore } from '@workbench/canvas-operations/controlDetectionStatusStore';@@ -24,7 +26,7 @@ import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { normalizeControlAdapter } from '@workbench/controlAdapters';import { resetPropertyGroupCollapse } from '@workbench/widgets/canvas/tool-presentation/propertyGroupStore';import { createInstance } from 'i18next';-import { act } from 'react';+import { act, useSyncExternalStore } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider } from 'react-i18next';import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';@@ -201,6 +203,11 @@ const engineWith = (layers: CanvasLayerContract[], { hasContent = true } = {}):projectId: 'test-project',tools: { setTool: vi.fn() },} as unknown as Engine;+ attachOperations(engine);+ return engine;+};++const attachOperations = (engine: Engine): void => {attachCanvasOperations(engine, {applyControlLayerIntent: (_layerId: string, intent: ControlLayerIntent) => {intents.push(intent);@@ -213,7 +220,6 @@ const engineWith = (layers: CanvasLayerContract[], { hasContent = true } = {}):},subscribeControlDetectionStatus: statuses.subscribe,} as never);- return engine;};const render = async (@@ -843,6 +849,236 @@ describe('ControlLayerSettings adapter rows', () => {});});+describe('ControlLayerSettings adapter gestures on the live document', () => {+ let stub: StructuralEngineStub;+ let liveEngine: Engine;+ const live = () => getDocumentLayer(stub.document(), 'control-1') as CanvasControlLayerContract;++ /** The panel as the Properties pane shows it: re-rendered from the document each preview reaches. */+ const LiveSettings = () => {+ const layer = useSyncExternalStore(stub.subscribe, live);+ return <ControlLayerSettings engine={liveEngine} layer={layer} />;+ };++ const renderLive = async (adapter: Partial<CanvasControlLayerContract['adapter']>) => {+ stub = createStructuralEngineStub({+ layers: [+ detectedLayer('depth', 'depth_anything_depth_estimation', {+ adapter: { ...controlLayer().adapter, ...adapter },+ }),+ ],+ // Previews reach the document at once, as a settled frame would deliver them before the release.+ schedulePreview: (flush) => {+ flush();+ return () => undefined;+ },+ });+ liveEngine = {+ ...stub.engine,+ document: { ...stub.engine.document, getDocument: () => stub.document() },+ exports: { exportRasterComposite: () => ({ status: 'empty' }), hasExportableLayerContent: () => true },+ interaction: { get: () => false, subscribe: () => () => undefined },+ lifecycle: { flushPendingUploads: () => Promise.resolve() },+ tools: { setTool: vi.fn() },+ } as unknown as Engine;+ attachOperations(liveEngine);+ applyThemeToRoot(DEFAULT_THEME_ID);+ host = document.createElement('div');+ host.style.width = '320px';+ document.body.append(host);+ root = createRoot(host);+ await settle(() =>+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <LiveSettings />+ </QueryClientProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ };++ /** Drives the slider whose thumb is `thumbName` through `fractions` of its track, pressing at the first. */+ const dragSlider = async (+ thumbName: string,+ fractions: number[],+ onMove: () => void = () => undefined,+ { release = true } = {}+ ) => {+ const control = page+ .getByRole('slider', { name: thumbName })+ .element()+ .closest<HTMLElement>('[data-part="root"]')!+ .querySelector<HTMLElement>('[data-part="control"]')!;+ const rect = control.getBoundingClientRect();+ const pointer = (target: EventTarget, type: string, fraction: number) =>+ settle(() =>+ target.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ button: 0,+ clientX: rect.left + rect.width * fraction,+ clientY: rect.top + rect.height / 2,+ pointerId: 1,+ })+ )+ );+ const [first, ...rest] = fractions;+ await pointer(control, 'pointerdown', first!);+ for (const fraction of rest) {+ await pointer(document, 'pointermove', fraction);+ onMove();+ }+ if (release) {+ await pointer(document, 'pointerup', fractions.at(-1)!);+ }+ };+ const thumbValue = (name: string) =>+ Number(page.getByRole('slider', { name }).element().getAttribute('aria-valuenow'));++ it('follows a weight drag step by step and keeps the released weight as one undoable step', async () => {+ await renderLive({ weight: 1 });+ const seen: number[] = [];+ await dragSlider('Weight', [0.5, 0.6, 0.7, 0.8], () => {+ seen.push(thumbValue('Weight'));+ expect(live().adapter.weight).toBe(thumbValue('Weight'));+ });++ // Each move carries the thumb, and its preview, further than the one before.+ expect(seen).toHaveLength(3);+ expect(seen[0]).toBeGreaterThan(1);+ expect(seen[1]).toBeGreaterThan(seen[0]!);+ expect(seen[2]).toBeGreaterThan(seen[1]!);+ const released = seen.at(-1)!;+ expect(live().adapter.weight).toBe(released);+ expect(thumbValue('Weight')).toBe(released);+ await expect.element(page.getByRole('spinbutton', { name: 'Weight' })).toHaveValue(released.toFixed(2));+ expect(stub.history.entries().past).toEqual(['Weight']);+ expect(stub.commits).toHaveLength(1);+ expect(stub.commits[0]!.inverse).toMatchObject({ config: { adapter: { weight: 1 } } });++ await settle(() => stub.engine.history.undo());+ expect(live().adapter.weight).toBe(1);+ expect(thumbValue('Weight')).toBe(1);+ await settle(() => stub.engine.history.redo());+ expect(live().adapter.weight).toBe(released);+ });++ it('records nothing for a weight drag that comes back to where it began', async () => {+ await renderLive({ weight: 1 });+ await dragSlider('Weight', [0.5, 0.7, 0.5]);++ expect(live().adapter.weight).toBe(1);+ expect(stub.history.entries().past).toEqual([]);+ });++ it('drags each step thumb on its own, recording one undoable step per drag', async () => {+ await renderLive({ beginEndStepPct: [0.1, 0.9] });++ const begins: number[] = [];+ await dragSlider('Begin step', [0.1, 0.2, 0.3], () => begins.push(thumbValue('Begin step')));+ expect(begins).toEqual([0.2, 0.3]);+ expect(live().adapter.beginEndStepPct).toEqual([0.3, 0.9]);+ expect(host!.textContent).toContain('30–90%');++ const ends: number[] = [];+ await dragSlider('End step', [0.9, 0.8, 0.6], () => ends.push(thumbValue('End step')));+ expect(ends).toEqual([0.8, 0.6]);+ expect(live().adapter.beginEndStepPct).toEqual([0.3, 0.6]);+ expect(thumbValue('Begin step')).toBe(0.3);+ expect(stub.history.entries().past).toEqual(['Steps', 'Steps']);++ await settle(() => stub.engine.history.undo());+ expect(live().adapter.beginEndStepPct).toEqual([0.3, 0.9]);+ expect(thumbValue('End step')).toBe(0.9);+ await settle(() => stub.engine.history.undo());+ expect(live().adapter.beginEndStepPct).toEqual([0.1, 0.9]);+ });++ it('pushes the end step along with a begin thumb dragged past it, as one undoable step', async () => {+ await renderLive({ beginEndStepPct: [0.2, 0.5] });+ const seen: number[][] = [];+ await dragSlider('Begin step', [0.2, 0.4, 0.7, 0.9], () =>+ seen.push([thumbValue('Begin step'), thumbValue('End step')])+ );++ // The platform slider never crosses its thumbs: past the end step, the begin thumb carries it along.+ expect(seen).toEqual([+ [0.4, 0.5],+ [0.7, 0.7],+ [0.9, 0.9],+ ]);+ expect(live().adapter.beginEndStepPct).toEqual([0.9, 0.9]);+ expect(stub.history.entries().past).toEqual(['Steps']);+ await settle(() => stub.engine.history.undo());+ expect(live().adapter.beginEndStepPct).toEqual([0.2, 0.5]);+ expect([thumbValue('Begin step'), thumbValue('End step')]).toEqual([0.2, 0.5]);+ });++ it.each([+ ['Weight', (layer: CanvasControlLayerContract) => layer.adapter.weight],+ ['Begin step', (layer: CanvasControlLayerContract) => layer.adapter.beginEndStepPct[0]],+ ['End step', (layer: CanvasControlLayerContract) => layer.adapter.beginEndStepPct[1]],+ ] as const)('records a %s drag the panel unmounts mid-gesture as one step', async (thumb, valueOf) => {+ await renderLive({ beginEndStepPct: [0.2, 0.8], weight: 1 });+ const before = valueOf(live());+ const seen: number[] = [];+ await dragSlider(thumb, [before / (thumb === 'Weight' ? 2 : 1), 0.45, 0.6], () => seen.push(valueOf(live())), {+ release: false,+ });+ expect(seen.at(-1)).not.toBe(before);+ await unmount();++ expect(stub.history.entries().past).toEqual([thumb === 'Weight' ? 'Weight' : 'Steps']);+ expect(valueOf(live())).toBe(seen.at(-1));+ // The gesture's preview session is closed: what ends an open one (any later edit) restores nothing.+ stub.controller.endPreview();+ expect(valueOf(live())).toBe(seen.at(-1));+ await settle(() => stub.engine.history.undo());+ expect(valueOf(live())).toBe(before);+ });++ it('records one step per key press on the weight and step thumbs', async () => {+ await renderLive({ beginEndStepPct: [0.1, 0.9], weight: 1 });+ await act(() => page.getByRole('slider', { name: 'Weight' }).element().focus());+ await act(() => userEvent.keyboard('{ArrowRight}{ArrowRight}'));+ expect(live().adapter.weight).toBeCloseTo(1.1);+ await act(() => userEvent.keyboard('{Home}'));+ expect(live().adapter.weight).toBe(0);+ expect(thumbValue('Weight')).toBe(0);++ await act(() => page.getByRole('slider', { name: 'End step' }).element().focus());+ await act(() => userEvent.keyboard('{ArrowLeft}'));+ expect(live().adapter.beginEndStepPct).toEqual([0.1, 0.85]);+ expect(stub.history.entries().past).toEqual(['Weight', 'Weight', 'Weight', 'Steps']);++ await settle(() => stub.engine.history.undo());+ await settle(() => stub.engine.history.undo());+ expect(live().adapter.weight).toBeCloseTo(1.1);+ expect(live().adapter.beginEndStepPct).toEqual([0.1, 0.9]);+ });++ it('records a typed weight once, and undo restores the dragged one', async () => {+ await renderLive({ weight: 1 });+ await dragSlider('Weight', [0.5, 0.75]);+ const dragged = live().adapter.weight;+ expect(dragged).toBeGreaterThan(1);+ const input = page.getByRole('spinbutton', { name: 'Weight' });+ await act(async () => {+ await userEvent.clear(input);+ await userEvent.type(input, '0.4{Enter}');+ });++ expect(live().adapter.weight).toBe(0.4);+ expect(stub.history.entries().past).toEqual(['Weight', 'Weight']);+ await settle(() => stub.engine.history.undo());+ expect(live().adapter.weight).toBe(dragged);+ await expect.element(input).toHaveValue(dragged.toFixed(2));+ });+});+describe('ControlLayerSettings and the capability table', () => {const retryButton = () => [...host!.querySelectorAll('button')].find((button) => button.textContent === 'Retry');@@ -858,6 +1094,25 @@ describe('ControlLayerSettings and the capability table', () => {).toContain('This layer is checked once model capabilities have loaded.');});+ it('checks the layer as soon as the table arrives, with nothing else changing', async () => {+ accountLifecycle.invalidate();+ const layer = detectedLayer('depth', 'depth_anything_depth_estimation');+ // Without exportable content the panel judges the layer on its own, not in Invoke's sequence.+ await render(layer, { engine: engineWith([layer], { hasContent: false }) });+ const statusTexts = () =>+ page+ .getByRole('status')+ .elements()+ .map((element) => element.textContent);++ expect(statusTexts()).toContain('This layer is checked once model capabilities have loaded.');++ await loadCapabilities();++ expect(statusTexts()).not.toContain('This layer is checked once model capabilities have loaded.');+ expect(host!.textContent).toContain(DEPTH_A.name);+ });+it('keeps the retry and its focus through a retry that fails again, then hands focus to the panel', async () => {accountLifecycle.invalidate();getArchitectureCapabilities.mockRejectedValueOnce(new Error('Fixture capability outage.'));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex 8c0c4dea81..fd35f3bc13 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -63,6 +63,15 @@ const selectStarterModels = (snapshot: {response: { starter_models: { source: string }[] } | null;}) => (snapshot.status === 'loaded' ? (snapshot.response?.starter_models ?? null) : null);+/**+ * The checks' context for one revision of the capability table, which the checks read when they run. The revision is+ * an argument, not only a dependency: the React Compiler infers a memo's dependencies from what its callback reads,+ * and prunes a side-effect-free `void revision`, so a context made from `base` and `remembered` alone would outlive+ * the table's arrival, and every check memoized on it with it.+ */+const getCheckContext = (base: string | null, remembered: Record<string, string>, _capabilitiesRevision: number) =>+ createControlLayerCheckContext(base, remembered);+/** Read from the engine in place of a reason when the layer does not contribute: its ambient warning applies. */const AMBIENT = 'ambient';@@ -87,7 +96,7 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsPropconst navigate = useNavigate();const projectId = useActiveProjectId();const { canManageModels } = useCapabilities();- const { cancel: cancelPreview, commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);+ const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const editingLocked = useCanvasDocumentEditingLocked(engine);const models = useModelsSelector((snapshot) => snapshot.models);const mainModel = useSelectedMainModel();@@ -111,10 +120,10 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsPropgetArchitectureCapabilitiesSnapshot,selectCapabilitiesRevision);- const checkContext = useMemo(() => {- void capabilitiesRevision;- return createControlLayerCheckContext(baseId, remembered);- }, [baseId, capabilitiesRevision, remembered]);+ const checkContext = useMemo(+ () => getCheckContext(baseId, remembered, capabilitiesRevision),+ [baseId, capabilitiesRevision, remembered]+ );const described = useMemo(() => describeControlLayer(layer, { ...checkContext, mainModel, models }),[checkContext, layer, mainModel, models]@@ -252,7 +261,6 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp);const adapterEditing = useMemo<ControlAdapterEditing>(() => ({- cancel: cancelPreview,commit: commitAdapter,preview: (patch) => {previewStructural({@@ -262,7 +270,7 @@ export const ControlLayerSettings = ({ engine, layer }: ControlLayerSettingsProp});},}),- [cancelPreview, commitAdapter, layer.id, previewStructural]+ [commitAdapter, layer.id, previewStructural]);const memoryKey = baseId && layer.controlType ? controlModelMemoryKey(baseId, layer.controlType) : null;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.browser.test.tsxnew file mode 100644index 0000000000..cc0b68ccd5--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.browser.test.tsx@@ -0,0 +1,108 @@+import type { RowProps } from '@platform/ui/Row';++import { Box, ChakraProvider } from '@chakra-ui/react';+import { Row } from '@platform/ui/Row';+import { applyThemeToRoot } from '@theme/applyTheme';+import { compositeColors, getContrastRatio } from '@theme/contrastRatio.testing';+import { system } from '@theme/system';+import { THEMES } from '@theme/themes';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { LayerActiveDot } from './LayerActiveDot';++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++beforeEach(() => {+ // Read settled colours: reduced motion shortens the transitions to a millisecond.+ document.documentElement.dataset.reduceMotion = 'true';+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ delete document.documentElement.dataset.reduceMotion;+ applyThemeToRoot('classic');+ host = null;+ root = null;+});++const noop = (): void => undefined;++/** Every fill a layer row can rest on: at rest, pointed, selected, primary, and the muted ancestor tone. */+const FILLS: readonly { id: string; active?: RowProps['active']; pointed?: boolean }[] = [+ { id: 'rest' },+ { id: 'hover', pointed: true },+ { id: 'selected', active: 'selected' },+ { id: 'primary', active: 'emphasized' },+ { id: 'muted', active: 'muted' },+];++const renderDots = async (checked: boolean, gatedReason: string | null = null) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <Box bg="bg.panel" data-testid="panel" p="2">+ {FILLS.map(({ active, id, pointed }) => (+ <Row key={id} active={active} data-hover={pointed || undefined} data-testid={id} h="10" px="2">+ <LayerActiveDot+ checked={checked}+ disabled={false}+ gatedReason={gatedReason}+ label="Use in generation"+ tooltip="Use in generation"+ onCheckedChange={noop}+ />+ </Row>+ ))}+ </Box>+ </ChakraProvider>+ );+ });+ const panel = getComputedStyle(host.querySelector('[data-testid="panel"]')!).backgroundColor;+ return (id: string) => {+ const row = host!.querySelector<HTMLElement>(`[data-testid="${id}"]`)!;+ const fill = compositeColors(getComputedStyle(row).backgroundColor, panel);+ const ring = getComputedStyle(row.querySelector('button')!, '::before');+ return { fill, ring };+ };+};++describe('LayerActiveDot', () => {+ // A dot that is off is the faintest state of an on/off control: its ring stays a visible boundary (WCAG 1.4.11) on+ // every fill a row can take, in every theme, while staying a solid ring unlike the gated dashed one.+ it.each(THEMES.map((theme) => [theme.id, theme.colorScheme] as const))(+ 'draws the off ring at 3:1 or more against every row fill in the %s (%s) theme',+ async (themeId) => {+ applyThemeToRoot(themeId);+ const measure = await renderDots(false);+ for (const { id } of FILLS) {+ const { fill, ring } = measure(id);+ expect(ring.borderTopStyle, id).toBe('solid');+ expect(ring.backgroundColor, id).toBe('rgba(0, 0, 0, 0)');+ expect(getContrastRatio(ring.borderTopColor, fill, 1), `${themeId} ${id}`).toBeGreaterThanOrEqual(3);+ }+ }+ );++ it('keeps the off ring apart from a dot that is on and from the dashed gated ring', async () => {+ const off = (await renderDots(false))('rest').ring;+ const offRing = { color: off.borderTopColor, style: off.borderTopStyle };+ await act(() => root?.unmount());+ host?.remove();+ const on = (await renderDots(true))('rest').ring;+ expect(on.backgroundColor).not.toBe('rgba(0, 0, 0, 0)');+ expect(on.borderTopColor).not.toBe(offRing.color);+ await act(() => root?.unmount());+ host?.remove();+ const gated = (await renderDots(true, 'Left out of generation by a group'))('rest').ring;+ expect(gated.borderTopStyle).toBe('dashed');+ expect(offRing.style).toBe('solid');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsxnew file mode 100644index 0000000000..d7995457d8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerActiveDot.tsx@@ -0,0 +1,102 @@+import { VisuallyHidden } from '@chakra-ui/react';+import { ToggleDot } from '@platform/ui/ToggleDot';+import { useId } from 'react';++/** The same 24px hit target as the row's small ghost icon buttons, so the trailing columns share one rhythm. */+export const LAYER_ACTIVE_DOT_SIZE = '6';++const DOT_TRANSITION = 'background var(--wb-motion-duration-fast), border-color var(--wb-motion-duration-fast)';+const DOT_BASE = {+ borderRadius: 'full',+ borderWidth: '1px',+ content: '""',+ h: '3',+ insetInlineStart: '50%',+ position: 'absolute',+ top: '50%',+ transform: 'translate(-50%, -50%)',+ transition: DOT_TRANSITION,+ w: '3',+};+const DOT_CHECKED = { ...DOT_BASE, bg: 'accent.solid', borderColor: 'accent.solid' };+/**+ * On by itself, but an ancestor keeps the node out: a dashed accent ring, so the state reads by shape as well as color+ * against the solid grey ring of a dot that is off.+ */+const DOT_GATED = {+ ...DOT_BASE,+ bg: 'transparent',+ borderColor: 'accent.solid',+ borderStyle: 'dashed',+ borderWidth: '1.5px',+};+// Off is the faintest state of an on/off control, so its ring keeps at least 3:1 against every row fill in every theme+// (LayerActiveDot.browser.test.tsx measures it); grey and hollow, it still reads apart from the filled accent of on.+const DOT_UNCHECKED = { ...DOT_BASE, bg: 'transparent', borderColor: 'fg.muted' };+// The button fills like the ghost icon buttons beside it. A dot that is on keeps its accent under the pointer: the+// darker hover accent of a plain ToggleDot sinks into that fill and reads as the dot switching off.+const HOVER_FILL = 'gray.hoverTint/10';+const HOVER_CHECKED = { bg: HOVER_FILL };+const HOVER_GATED = { bg: HOVER_FILL };+const HOVER_UNCHECKED = { _before: { borderColor: 'fg' }, bg: HOVER_FILL };+// Read-only while editing is locked: the dot dims as disabled icon buttons do and takes no hover fill.+const HOVER_NONE = {};+const dimmed = (style: typeof DOT_BASE) => ({ ...style, opacity: 0.5 });++const dotStyle = (checked: boolean, gated: boolean) => (checked ? (gated ? DOT_GATED : DOT_CHECKED) : DOT_UNCHECKED);+const hoverStyle = (checked: boolean, gated: boolean) =>+ checked ? (gated ? HOVER_GATED : HOVER_CHECKED) : HOVER_UNCHECKED;++const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();++/**+ * A layer row's "takes part in generation" toggle, reading on, gated by an ancestor, and off distinctly. Pointer-only+ * like every row control (the row's menu carries the same action), and it never starts a row drag.+ */+export const LayerActiveDot = ({+ checked,+ disabled,+ gatedReason,+ label,+ onCheckedChange,+ tooltip,+}: {+ checked: boolean;+ disabled: boolean;+ /**+ * Set when the dot is checked but an ancestor keeps the node out: why, shown as the tooltip and given to assistive+ * tech as the dot's description, since `aria-pressed` alone would report the node as taking part.+ */+ gatedReason: string | null;+ label: string;+ onCheckedChange: (checked: boolean) => void;+ /** The action a click takes, while nothing above gates the dot. */+ tooltip: string;+}) => {+ const descriptionId = useId();+ const gated = checked && gatedReason !== null;+ return (+ <>+ <ToggleDot+ _before={disabled ? dimmed(dotStyle(checked, gated)) : dotStyle(checked, gated)}+ _hover={disabled ? HOVER_NONE : hoverStyle(checked, gated)}+ bg="transparent"+ borderWidth="0"+ aria-describedby={gated ? descriptionId : undefined}+ checked={checked}+ disabled={disabled}+ h={LAYER_ACTIVE_DOT_SIZE}+ label={label}+ position="relative"+ rounded="control"+ tabIndex={-1}+ tooltip={gated ? gatedReason : tooltip}+ transition={DOT_TRANSITION}+ w={LAYER_ACTIVE_DOT_SIZE}+ onCheckedChange={onCheckedChange}+ onPointerDown={stopPropagation}+ />+ {gated ? <VisuallyHidden id={descriptionId}>{gatedReason}</VisuallyHidden> : null}+ </>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.browser.test.tsxindex 923ce06e75..7a3728bc0c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.browser.test.tsx@@ -79,19 +79,19 @@ const commitBlendMode = (id: string, blendMode: CanvasBlendMode): void => {let host: HTMLDivElement | null = null;let root: Root | null = null;-/** The row's engine surface: the stub's structural half plus an unlocked interaction store. */-const rowEngine = () => ({+/** The row's engine surface: the stub's structural half plus an interaction store, unlocked unless `locked`. */+const rowEngine = (locked: boolean) => ({...stub.engine,exports: {},- interaction: { get: () => false, subscribe: () => () => undefined },+ interaction: { get: () => locked, subscribe: () => () => undefined },});-const mount = async (width = 280): Promise<void> => {+const mount = async (width = 280, locked = false): Promise<void> => {host = document.createElement('div');host.style.width = `${width}px`;document.body.append(host);root = createRoot(host);- const engine = rowEngine();+ const engine = rowEngine(locked);await act(() =>root!.render(<I18nextProvider i18n={i18n}>@@ -108,6 +108,13 @@ const unmount = async (): Promise<void> => {root = null;};+const afterFrames = async (count: number): Promise<void> => {+ for (let frame = 0; frame < count; frame += 1) {+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => resolve());+ });+ }+};const layer = (id = 'r1'): CanvasLayerContract => getDocumentLayer(stub.document(), id)!;const trigger = () => page.getByRole('combobox', { name: 'Blend mode' });const option = (name: string) => page.getByRole('option', { exact: true, name });@@ -122,8 +129,6 @@ afterEach(async () => {host?.remove();host = null;vi.clearAllMocks();- // Prototype spies (pointer lock) must not leak into later tests or files sharing the browser.- vi.restoreAllMocks();});describe('blend mode preview', () => {@@ -300,6 +305,28 @@ describe('blend mode preview', () => {describe('opacity input', () => {const opacityInput = () => page.getByRole('spinbutton', { exact: true, name: 'Opacity' });+ const sliderTrigger = () => page.getByRole('button', { exact: true, name: 'Opacity slider' });+ const slider = () => page.getByRole('slider', { exact: true, name: 'Opacity' });++ /** Opens the dropdown slider; `pointer` builds a mouse event at a fraction of the track. */+ const openSlider = async () => {+ await userEvent.click(sliderTrigger());+ await expect.element(slider()).toBeVisible();+ const control = document.querySelector<HTMLElement>('[data-scope="slider"][data-part="control"]')!;+ const { height, left, top, width } = control.getBoundingClientRect();+ const pointer = (type: string, fraction: number) =>+ new PointerEvent(type, {+ bubbles: true,+ button: 0,+ buttons: type === 'pointerup' ? 0 : 1,+ clientX: left + width * fraction,+ clientY: top + height / 2,+ isPrimary: true,+ pointerId: 1,+ pointerType: 'mouse',+ });+ return { control, pointer };+ };it('records a held arrow key as one step from where it started', async () => {await mount();@@ -314,33 +341,6 @@ describe('opacity input', () => {expect(commits()[0]!.inverse).toMatchObject({ id: 'r1', patch: { opacity: 1 } });});- it('scrubs from its drag handle and records the result once when the mouse button lifts', async () => {- await mount();- // The scrubber locks the pointer once a real click has activated the page; the harness lock steals focus.- vi.spyOn(Element.prototype, 'requestPointerLock').mockImplementation(() => Promise.resolve());- const scrubber = host!.querySelector<HTMLElement>('[data-scope="number-input"][data-part="scrubber"]')!;- await act(() =>- scrubber.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 100, clientY: 100 }))- );- for (let step = 1; step <= 5; step += 1) {- await act(() =>- document.dispatchEvent(- new MouseEvent('mousemove', { bubbles: true, clientX: 100 - step * 4, clientY: 100, movementX: -4 })- )- );- }-- // Each step previews on the layer; nothing is recorded until the release.- expect(layer().opacity).toBeCloseTo(0.95, 5);- expect(commits()).toHaveLength(0);- await act(() =>- document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 80, clientY: 100 }))- );- expect(commits()).toHaveLength(1);- expect(commits()[0]!.forward).toMatchObject({ id: 'r1', patch: { opacity: 0.95 } });- expect(commits()[0]!.inverse).toMatchObject({ id: 'r1', patch: { opacity: 1 } });- });-it('previews a typed value and records it once on Enter', async () => {await mount();await userEvent.tripleClick(opacityInput());@@ -356,6 +356,34 @@ describe('opacity input', () => {expect(commits()[0]!.inverse).toMatchObject({ patch: { opacity: 1 } });});+ it('keeps a typed value pending while the caret moves, and records only the final value', async () => {+ await mount();+ const input = opacityInput().element() as HTMLInputElement;+ // Zag restores the caret one frame after each value change, so a caret move made sooner is undone. Let each+ // keystroke settle before moving the caret, as a person typing would.+ const typeSettled = async (text: string) => {+ await userEvent.keyboard(text);+ await act(() => afterFrames(2));+ };+ await userEvent.tripleClick(opacityInput());+ await typeSettled('5');+ await typeSettled('{ArrowLeft}');+ expect(input.selectionStart).toBe(0);+ await typeSettled('2');+ await expect.element(opacityInput()).toHaveValue('25');+ await typeSettled('{ArrowRight}');+ expect(input.selectionStart).toBe(2);++ expect(layer().opacity).toBeCloseTo(0.25, 5);+ expect(commits()).toHaveLength(0);++ await userEvent.keyboard('{Enter}');++ expect(commits()).toHaveLength(1);+ expect(commits()[0]!.forward).toMatchObject({ id: 'r1', patch: { opacity: 0.25 } });+ expect(commits()[0]!.inverse).toMatchObject({ id: 'r1', patch: { opacity: 1 } });+ });+it('records a still-pending edit when the row unmounts', async () => {await mount();await userEvent.tripleClick(opacityInput());@@ -368,11 +396,89 @@ describe('opacity input', () => {expect(commits()[0]!.forward).toMatchObject({ id: 'r1', patch: { opacity: 0.3 } });});- it('disables both controls without an editable selection', async () => {+ it('previews each step of a slider drag and records the result once when the pointer lifts', async () => {+ await mount();+ const { control, pointer } = await openSlider();++ await act(() => control.dispatchEvent(pointer('pointerdown', 0.8)));+ const seen = [layer().opacity];+ for (const fraction of [0.7, 0.6, 0.5]) {+ await act(() => document.dispatchEvent(pointer('pointermove', fraction)));+ seen.push(layer().opacity);+ }++ // Every step reaches the layer while nothing is recorded until the release.+ expect(new Set(seen.map((value) => value.toFixed(2))).size).toBe(4);+ expect(layer().opacity).toBeCloseTo(0.5, 1);+ await expect.element(opacityInput()).toHaveValue(String(Math.round(layer().opacity * 100)));+ expect(commits()).toHaveLength(0);++ await act(() => document.dispatchEvent(pointer('pointerup', 0.5)));++ expect(commits()).toHaveLength(1);+ expect(commits()[0]!.forward).toMatchObject({ id: 'r1', patch: { opacity: layer().opacity } });+ expect(commits()[0]!.inverse).toMatchObject({ id: 'r1', patch: { opacity: 1 } });+ expect(stub.history.entries().past).toEqual(['Opacity']);+ });++ it('records a drag once when Escape closes the slider mid-drag, ignoring the moves that follow', async () => {+ await mount();+ const { control, pointer } = await openSlider();++ await act(() => control.dispatchEvent(pointer('pointerdown', 0.8)));+ await act(() => document.dispatchEvent(pointer('pointermove', 0.6)));+ const atClose = layer().opacity;+ expect(atClose).toBeCloseTo(0.6, 1);++ await userEvent.keyboard('{Escape}');+ await act(() => document.dispatchEvent(pointer('pointermove', 0.3)));+ await act(() => document.dispatchEvent(pointer('pointerup', 0.3)));+ await expect.poll(() => slider().query()).toBeNull();++ expect(layer().opacity).toBe(atClose);+ expect(commits()).toHaveLength(1);+ expect(commits()[0]!.forward).toMatchObject({ id: 'r1', patch: { opacity: atClose } });+ // Nothing is left pending for a later flush to record.+ await unmount();+ expect(commits()).toHaveLength(1);+ expect(stub.history.entries().past).toEqual(['Opacity']);+ });++ it('opens the slider from the keyboard, records a held key once, and returns focus on Escape', async () => {+ await mount();+ await act(async () => {+ (sliderTrigger().element() as HTMLElement).focus();+ await userEvent.keyboard('{Enter}');+ });+ await expect.element(slider()).toHaveFocus();++ await userEvent.keyboard('{ArrowLeft>3/}');++ expect(layer().opacity).toBeCloseTo(0.97, 5);+ expect(commits()).toHaveLength(1);+ expect(commits()[0]!.forward).toMatchObject({ id: 'r1', patch: { opacity: 0.97 } });+ await expect.element(slider()).toHaveAttribute('aria-valuetext', '97%');++ await userEvent.keyboard('{Escape}');++ await expect.poll(() => slider().query()).toBeNull();+ await expect.element(sliderTrigger()).toHaveFocus();+ expect(commits()).toHaveLength(1);+ });++ it('disables every control without an editable selection', async () => {createStub(null);await mount();await expect.element(trigger()).toBeDisabled();await expect.element(opacityInput()).toBeDisabled();+ await expect.element(sliderTrigger()).toBeDisabled();+ });++ it('disables the field and the slider trigger while canvas editing is locked', async () => {+ await mount(280, true);++ await expect.element(opacityInput()).toBeDisabled();+ await expect.element(sliderTrigger()).toBeDisabled();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsxindex 1f44e77dc0..f341762ac5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx@@ -11,15 +11,30 @@ import type {CanvasNodeContract,} from '@workbench/canvas-engine/api';import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';+import type { KeyboardEvent } from 'react';-import { createListCollection, Flex, HStack, Icon, InputGroup, NumberInput } from '@chakra-ui/react';+import {+ chakra,+ createListCollection,+ Flex,+ HStack,+ Icon,+ InputGroup,+ NumberInput,+ Popover,+ Portal,+} from '@chakra-ui/react';import { Select } from '@platform/ui';+import { IconButton } from '@platform/ui/Button';+import { PopoverContent } from '@platform/ui/Popover';+import { Slider } from '@platform/ui/Slider';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';import { getDocumentIndex, isGroupNode } from '@workbench/canvas-engine/api';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';import { baselinePatch, useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';import { CANVAS_BLEND_MODES } from '@workbench/widgets/layers/layerOps';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-import { MoveHorizontalIcon } from 'lucide-react';+import { BlendIcon, ChevronDownIcon, OpacityIcon } from 'lucide-react';import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -28,8 +43,33 @@ type LayerBlendRowEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'inconst SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;const BLEND_TRIGGER_PROPS = { fontSize: 'md', h: 'control.md', minH: 'control.md' } as const;const OPACITY_INPUT_PROPS = { fontSize: 'md', h: 'control.md' } as const;-// The drag handle sits inside the field, as on the Transform pane's number fields.-const SCRUB_HANDLE_PROPS = { color: 'fg.muted', pointerEvents: 'auto', ps: '1.5' } as const;+const OPACITY_ICON_SLOT_PROPS = { color: 'fg.muted', ps: '2' } as const;+const SLIDER_TRIGGER_SLOT_PROPS = { pe: '0.5', pointerEvents: 'auto' } as const;+const SLIDER_POPOVER_POSITIONING = { placement: 'bottom-end' } as const;+// Lucide has no dedicated opacity glyph; two overlapping translucent circles read as opacity, and the Workflow+// editor's node-opacity control uses the same one.+const OPACITY_ICON = <Icon aria-hidden as={OpacityIcon} boxSize="3.5" />;+// Keys that step the slider; their release ends the gesture.+const SLIDER_STEP_KEYS = new Set([+ 'ArrowDown',+ 'ArrowLeft',+ 'ArrowRight',+ 'ArrowUp',+ 'End',+ 'Home',+ 'PageDown',+ 'PageUp',+]);+// Keys Zag's number input steps or commits on (Home/End only without Ctrl/Alt/Meta). Any other key, a caret move+// included, leaves a typed value pending.+const FIELD_COMMIT_KEYS = new Set(['ArrowDown', 'ArrowUp', 'Enter']);+const FIELD_BOUND_KEYS = new Set(['End', 'Home']);++const isFieldCommitKey = (event: { altKey: boolean; ctrlKey: boolean; key: string; metaKey: boolean }): boolean =>+ FIELD_COMMIT_KEYS.has(event.key) ||+ (FIELD_BOUND_KEYS.has(event.key) && !event.ctrlKey && !event.altKey && !event.metaKey);++const getPercentValueText = ({ value }: { value: number }): string => `${value}%`;const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));@@ -123,6 +163,17 @@ const BlendModeControl = ({[t]);const blendValue = useMemo(() => [shownMode], [shownMode]);+ const blendValueText = useMemo(+ () => (+ <HStack as="span" display="inline-flex" gap="1.5" maxW="full" minW="0" verticalAlign="middle">+ <Icon aria-hidden as={BlendIcon} boxSize="3.5" color="fg.muted" flexShrink={0} />+ <chakra.span minW="0" truncate>+ {t(`widgets.layers.blendModes.${shownMode}`)}+ </chakra.span>+ </HStack>+ ),+ [shownMode, t]+ );const endPreview = useCallback(() => {previewRef.current = null;@@ -194,7 +245,7 @@ const BlendModeControl = ({positioning={SELECT_POSITIONING}triggerProps={BLEND_TRIGGER_PROPS}value={blendValue}- valueText={t(`widgets.layers.blendModes.${shownMode}`)}+ valueText={blendValueText}onHighlightChange={handleHighlightChange}onOpenChange={handleOpenChange}onValueChange={handleBlendChange}@@ -203,6 +254,12 @@ const BlendModeControl = ({);};+/**+ * Typed entry, arrow keys, and a slider in a popover at the field's end. Every change previews on the layer; each+ * completed gesture records one history entry: a typed value on Enter or blur, a held key on its release, a slider+ * drag when the pointer lifts. The field shows the slider's live value, so the thumb carries no tooltip to cover the+ * trigger.+ */const OpacityRow = ({editingLocked,engine,@@ -214,10 +271,19 @@ const OpacityRow = ({}) => {const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const { t } = useTranslation();+ const sliderTriggerIds = useTooltipTriggerIds();// Track latest writes outside render closures so same-event commits record current values.const pendingRef = useRef<{ id: string; latest: number } | null>(null);+ // A slider key settles on its release, as in the field, so a held key records once.+ const sliderKeyHeldRef = useRef(false);+ // The closing popover's slider can keep tracking a drag through its exit; closing already recorded the gesture, so+ // nothing the slider reports after it may preview or become pending.+ const sliderOpenRef = useRef(false);const disabled = isLayerEditingDisabled(layer, editingLocked);- const opacityPercent = useMemo(() => String(Math.round((layer?.opacity ?? 1) * 100)), [layer?.opacity]);+ const percent = Math.round((layer?.opacity ?? 1) * 100);+ const opacityPercent = String(percent);+ const sliderValue = useMemo(() => [percent], [percent]);+ const sliderLabel = useMemo(() => [t('widgets.layers.actions.opacity')], [t]);// Record one history entry per completed opacity gesture.const commitPending = useCallback(() => {@@ -232,9 +298,9 @@ const OpacityRow = ({);}, [commitPrepared, t]);- const handleOpacityChange = useCallback(- ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {- if (!layer || !Number.isFinite(valueAsNumber)) {+ const previewOpacity = useCallback(+ (nextPercent: number) => {+ if (!layer || !Number.isFinite(nextPercent)) {return;}// If a pending edit belongs to a previously selected layer, flush it first@@ -242,14 +308,8 @@ const OpacityRow = ({if (pendingRef.current && pendingRef.current.id !== layer.id) {commitPending();}- const next = clamp01(valueAsNumber / 100);- if (- !previewStructural({- id: layer.id,- patch: { opacity: next },- type: 'updateCanvasLayer',- })- ) {+ const next = clamp01(nextPercent / 100);+ if (!previewStructural({ id: layer.id, patch: { opacity: next }, type: 'updateCanvasLayer' })) {return;}pendingRef.current = { id: layer.id, latest: next };@@ -257,58 +317,133 @@ const OpacityRow = ({[commitPending, previewStructural, layer]);- // Commit on spinner release, arrow/page-key release, Enter, or typed-value blur.+ const handleInputChange = useCallback(+ ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => previewOpacity(valueAsNumber),+ [previewOpacity]+ );++ // Commit on a step key's release, Enter, or typed-value blur.const handleInputKeyUp = useCallback(- (event: { key: string }) => {- if (['ArrowDown', 'ArrowUp', 'End', 'Enter', 'Home', 'PageDown', 'PageUp'].includes(event.key)) {+ (event: KeyboardEvent<HTMLInputElement>) => {+ if (isFieldCommitKey(event)) {commitPending();}},[commitPending]);- // A scrub ends with the mouse button rather than a key or blur, so the release records it.- const scrubRef = useRef<AbortController | null>(null);- const handleScrubStart = useCallback(() => {- scrubRef.current?.abort();- const scrub = new AbortController();- scrubRef.current = scrub;- window.addEventListener(- 'mouseup',- () => {- scrub.abort();- scrubRef.current = null;- commitPending();- },- { signal: scrub.signal }- );+ const handleSliderChange = useCallback(+ ({ value: [next] }: { value: number[] }) => {+ if (next !== undefined && sliderOpenRef.current) {+ previewOpacity(next);+ }+ },+ [previewOpacity]+ );++ // Zag ends a value change on every key press, from the thumb's own keydown; the capture-phase key flag lets a held+ // key settle on its release instead. A drag ends once, when the pointer lifts.+ const handleSliderChangeEnd = useCallback(() => {+ if (!sliderKeyHeldRef.current) {+ commitPending();+ }}, [commitPending]);- const scrubHandle = useMemo(- () => (- <NumberInput.Scrubber aria-hidden onMouseDownCapture={handleScrubStart}>- <Icon as={MoveHorizontalIcon} boxSize="3" />- </NumberInput.Scrubber>- ),- [handleScrubStart]+ const handleSliderKeyDown = useCallback((event: { key: string }) => {+ if (SLIDER_STEP_KEYS.has(event.key)) {+ sliderKeyHeldRef.current = true;+ }+ }, []);++ const handleSliderKeyUp = useCallback(+ (event: { key: string }) => {+ if (SLIDER_STEP_KEYS.has(event.key)) {+ sliderKeyHeldRef.current = false;+ commitPending();+ }+ },+ [commitPending]+ );++ const handlePopoverOpenChange = useCallback(+ ({ open }: { open: boolean }) => {+ sliderOpenRef.current = open;+ sliderKeyHeldRef.current = false;+ commitPending();+ },+ [commitPending]);// Flush a still-pending edit if the row unmounts mid-gesture (e.g. the panel- // closes right after a spinner click or mid-scrub) so the edit is never lost to history.+ // closes mid-drag or right after an arrow key) so the edit is never lost to history.const flushOnUnmountRef = useCallback(- (node: HTMLDivElement | null) => {- if (node) {- return () => {- scrubRef.current?.abort();- scrubRef.current = null;- commitPending();- };- }- return undefined;- },+ (node: HTMLDivElement | null) => (node ? commitPending : undefined),[commitPending]);+ const sliderTrigger = useMemo(+ () => (+ <Popover.Root+ ids={sliderTriggerIds}+ lazyMount+ positioning={SLIDER_POPOVER_POSITIONING}+ unmountOnExit+ onOpenChange={handlePopoverOpenChange}+ >+ <Tooltip content={t('widgets.layers.actions.opacitySlider')} ids={sliderTriggerIds}>+ <Popover.Trigger asChild>+ <IconButton+ aria-label={t('widgets.layers.actions.opacitySlider')}+ color="fg.muted"+ disabled={disabled}+ minW="5"+ size="sm"+ variant="ghost"+ w="5"+ >+ <Icon as={ChevronDownIcon} boxSize="3" />+ </IconButton>+ </Popover.Trigger>+ </Tooltip>+ <Portal>+ <Popover.Positioner>+ <PopoverContent aria-label={t('widgets.layers.actions.opacity')} w="auto">+ <Popover.Body px="3" py="2.5">+ <Slider+ aria-label={sliderLabel}+ disabled={disabled}+ getAriaValueText={getPercentValueText}+ max={100}+ min={0}+ step={1}+ value={sliderValue}+ w="36"+ withThumbTooltip={false}+ onKeyDownCapture={handleSliderKeyDown}+ onKeyUp={handleSliderKeyUp}+ onValueChange={handleSliderChange}+ onValueChangeEnd={handleSliderChangeEnd}+ />+ </Popover.Body>+ </PopoverContent>+ </Popover.Positioner>+ </Portal>+ </Popover.Root>+ ),+ [+ disabled,+ handlePopoverOpenChange,+ handleSliderChange,+ handleSliderChangeEnd,+ handleSliderKeyDown,+ handleSliderKeyUp,+ sliderLabel,+ sliderTriggerIds,+ sliderValue,+ t,+ ]+ );+return (<HStack ref={flushOnUnmountRef} flexShrink={0} gap="2"><NumberInput.Root@@ -318,14 +453,19 @@ const OpacityRow = ({size="lg"step={1}value={opacityPercent}- w="20"- onValueChange={handleOpacityChange}+ w="24"+ onValueChange={handleInputChange}>- <NumberInput.Control onClick={commitPending} />- <InputGroup startElement={scrubHandle} startElementProps={SCRUB_HANDLE_PROPS}>+ <InputGroup+ endElement={sliderTrigger}+ endElementProps={SLIDER_TRIGGER_SLOT_PROPS}+ startElement={OPACITY_ICON}+ startElementProps={OPACITY_ICON_SLOT_PROPS}+ ><NumberInput.Inputaria-label={t('widgets.layers.actions.opacity')}css={OPACITY_INPUT_PROPS}+ fontVariantNumeric="tabular-nums"onBlur={commitPending}onKeyUp={handleInputKeyUp}/>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsxindex 95a672d179..76eefb09f2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx@@ -4,6 +4,7 @@ import { Box, HStack, Icon, Input, Text } from '@chakra-ui/react';import { useDraggable, useDroppable } from '@dnd-kit/core';import { IconButton } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';+import { isOverlayStack } from '@workbench/canvas-engine/api';import {ApertureIcon,WandSparklesIcon,@@ -317,7 +318,9 @@ const LayerChildRowComponent = ({content={child.parentContributing? t('widgets.layers.modifiers.toggleActive')- : t('widgets.layers.modifiers.parentDisabled')+ : isOverlayStack(child.stack)+ ? t('widgets.layers.modifiers.parentExcluded')+ : t('widgets.layers.modifiers.parentDisabled')}><IconButtondiff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsxindex f427b99924..29f4d577f6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx@@ -1,5 +1,5 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */-import type { CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/api';+import type { CanvasGroupContract, CanvasLayerContract, CanvasNodeContract } from '@workbench/canvas-engine/api';import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';import type { Project } from '@workbench/projectContracts';import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';@@ -7,7 +7,12 @@ import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';import { ChakraProvider } from '@chakra-ui/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';-import { CanvasImageMissingError, getDocumentIndex, getDocumentLeaves } from '@workbench/canvas-engine/api';+import {+ CanvasImageMissingError,+ getDocumentIndex,+ getDocumentLeaves,+ isNodeHidden,+} from '@workbench/canvas-engine/api';import {groupContract,layerContract,@@ -41,6 +46,7 @@ vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({}));import { CanvasLayerContextMenu } from './LayerContextMenu';+import { LayerGroupContextMenu } from './LayerGroupContextMenu';const i18n = createInstance();let root: Root | null = null;@@ -219,15 +225,20 @@ describe('Layers context menu over a real engine', () => {});- it('describes Add regenerate region under its label', async () => {+ it('describes Add regenerate region under its label without widening the menu', async () => {const { openMenu } = await renderMenu([imageLayer('art')]);await openMenu('art');- const regenerate = document.querySelector('[role="menuitem"][data-value="add-regenerate-region"]');- expect(regenerate?.textContent).toBe(- 'Add regenerate regionRegenerate where this layer has content, as a live inpaint mask.'- );+ const regenerate = document.querySelector<HTMLElement>('[role="menuitem"][data-value="add-regenerate-region"]')!;+ expect(regenerate.textContent).toBe('Add regenerate regionInpaint where this layer has content.');+ const menu = regenerate.closest<HTMLElement>('[role="menu"]')!;+ const description = document.getElementById(regenerate.getAttribute('aria-describedby')!)!;+ const width = menu.getBoundingClientRect().width;+ description.textContent = '';+ // The description is about as wide as the widest label; which of the two is wider depends on the font, so allow+ // it a few pixels rather than none.+ expect(width - menu.getBoundingClientRect().width).toBeLessThan(8);});it('keeps an unavailable Merge masks reachable by keyboard and says why', async () => {@@ -251,3 +262,105 @@ describe('Layers context menu over a real engine', () => {expect(getDocumentLeaves(engine.document.getDocument()!).map((layer) => layer.id)).toEqual(['m1', 'm2']);});});++describe('generation and canvas visibility in the layer menus', () => {+ const nodeOf = (document: () => ReturnType<CanvasEngine['document']['getDocument']>, id: string) =>+ getDocumentIndex(document()!).byId.get(id)!.node;+ const labels = () =>+ [...window.document.querySelectorAll<HTMLElement>('[role="menuitem"]')].map((entry) => entry.textContent);++ it('names an overlay’s two axes as its row does, and each item changes only its own', async () => {+ const { engine, openMenu } = await renderMenu([maskLayer('mask')]);+ const document_ = () => engine.document.getDocument();++ await openMenu('mask');+ expect(labels()).toEqual(expect.arrayContaining(['Exclude from generation', 'Hide on canvas']));+ expect(labels()).not.toContain('Hide layer');+ await act(() => item('Hide on canvas').click());+ await vi.waitFor(() => expect(nodeOf(document_, 'mask')).toMatchObject({ isEnabled: true, isHidden: true }));++ await openMenu('mask');+ expect(labels()).toContain('Show on canvas');+ // From the keyboard, as the row's controls are reached.+ const exclude = window.document.querySelector<HTMLElement>('[role="menuitem"][data-value="toggle-visibility"]')!;+ expect(exclude.textContent).toBe('Exclude from generation');+ for (let step = 0; step < 30 && !exclude.hasAttribute('data-highlighted'); step += 1) {+ await userEvent.keyboard('{ArrowDown}');+ }+ await userEvent.keyboard('{Enter}');+ await vi.waitFor(() => expect(nodeOf(document_, 'mask')).toMatchObject({ isEnabled: false, isHidden: true }));+ expect(engine.history.getEntries().past).toEqual(['Hide on canvas', 'Exclude from generation']);++ await openMenu('mask');+ expect(labels()).toEqual(expect.arrayContaining(['Use in generation', 'Show on canvas']));+ });++ it('keeps one show-or-hide item on a raster layer', async () => {+ const { engine, openMenu } = await renderMenu([imageLayer('art')]);+ await openMenu('art');+ expect(labels()).toContain('Hide layer');+ expect(labels().some((label) => /generation|on canvas/.test(label ?? ''))).toBe(false);+ await act(() => item('Hide layer').click());+ await vi.waitFor(() => expect(engine.history.getEntries().past).toEqual(['Hide layer']));+ });++ it('turns a selection of overlays and raster layers off and on, in words true of both', async () => {+ const { engine, openMenu } = await renderMenu([maskLayer('mask'), imageLayer('art')], ['mask', 'art']);+ const document_ = () => engine.document.getDocument();+ const enabled = () => ['mask', 'art'].map((id) => nodeOf(document_, id).isEnabled);++ await openMenu('mask');+ expect(labels()).not.toContain('Hide selected');+ await act(() => item('Turn off selected').click());+ await vi.waitFor(() => expect(enabled()).toEqual([false, false]));+ await openMenu('art');+ await act(() => item('Turn on selected').click());+ await vi.waitFor(() => expect(enabled()).toEqual([true, true]));+ expect(engine.history.getEntries().past).toEqual(['Turn off selected', 'Turn on selected']);+ });++ it('applies the overlay items to a selection of overlays', async () => {+ const { engine, openMenu } = await renderMenu([maskLayer('m1'), maskLayer('m2')], ['m1', 'm2']);+ const document_ = () => engine.document.getDocument();++ await openMenu('m1');+ await act(() => item('Exclude selected from generation').click());+ await vi.waitFor(() => expect(['m1', 'm2'].map((id) => nodeOf(document_, id).isEnabled)).toEqual([false, false]));+ await openMenu('m1');+ await act(() => item('Hide selected on canvas').click());+ await vi.waitFor(() => expect(['m1', 'm2'].map((id) => isNodeHidden(nodeOf(document_, id)))).toEqual([true, true]));+ expect(engine.history.getEntries().past).toEqual(['Exclude selected from generation', 'Hide selected on canvas']);+ });++ it.each([+ ['inpaint_mask', ['Exclude group from generation', 'Hide group on canvas'], 'Hide group'],+ ['raster', ['Hide group'], 'Exclude group from generation'],+ ] as const)('words a group in the %s stack for its axes', async (stack, expected, absent) => {+ const member = stack === 'raster' ? imageLayer('member') : maskLayer('member');+ const { engine } = await renderMenu([groupContract('G', [member])]);+ const document_ = () => engine.document.getDocument();+ await act(() =>+ root!.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <LayerGroupContextMenu+ anchor={{ height: 1, width: 1, x: 40, y: 40 }}+ editingLocked={false}+ engine={engine}+ group={nodeOf(document_, 'G') as CanvasGroupContract}+ stack={stack}+ onClose={() => undefined}+ />+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ await expect.element(page.getByRole('menu')).toBeVisible();+ expect(labels()).toEqual(expect.arrayContaining([...expected]));+ expect(labels()).not.toContain(absent);++ await act(() => item(expected[0]).click());+ await vi.waitFor(() => expect(nodeOf(document_, 'G').isEnabled).toBe(false));+ expect(engine.history.getEntries().past).toEqual([expected[0]]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 5f6d8f9af3..e88a657fd7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -41,7 +41,7 @@ import { ShortcutKeycaps } from '@workbench/hotkeys/keyGlyphs';import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';import { useNotify } from '@workbench/useNotify';-import { reportTransformRefusal } from '@workbench/widgets/canvas/canvasToolCommands';+import { reportTransformRefusal, showCanvasRefusalNotice } from '@workbench/widgets/canvas/canvasToolCommands';import {useCanvasDocumentEditingLocked,useCanvasEngineRead,@@ -81,6 +81,7 @@ import type { LayerMenuDialogKind, LayerMenuDialogState } from './layerMenuStateimport {actionTargets,+ enabledToggleLabel,getLayerContextActions,type LayerConfigPatchKind,type LayerContextAction,@@ -536,17 +537,12 @@ const LayerMenu = ({const handleToggleVisibility = useCallback(() => {const targets = actionTargets({ layer, selectedIds });- if (targets.length > 1) {- const index = getDocumentIndex(document);- const isEnabled = !targets.every((id) => index.byId.get(id)?.node.isEnabled ?? true);- commitPrepared(- t(isEnabled ? 'widgets.layers.actions.showSelected' : 'widgets.layers.actions.hideSelected'),- (model) => model.prepare({ type: 'set-enabled', updates: targets.map((id) => ({ id, isEnabled })) })- );- return;- }- patchBase(t('widgets.layers.actions.toggleActive'), { isEnabled: !layer.isEnabled });- }, [commitPrepared, document, layer, patchBase, selectedIds, t]);+ const index = getDocumentIndex(document);+ const isEnabled = !targets.every((id) => index.byId.get(id)?.node.isEnabled ?? true);+ commitPrepared(t(enabledToggleLabel(document, targets, !isEnabled).key), (model) =>+ model.prepare({ type: 'set-enabled', updates: targets.map((id) => ({ id, isEnabled })) })+ );+ }, [commitPrepared, document, layer, selectedIds, t]);const handleToggleHidden = useCallback(() => {const targets = actionTargets({ layer, selectedIds });@@ -649,9 +645,14 @@ const LayerMenu = ({}const result = engine.layers.beginTransform(layer.id);if (result !== 'started') {- reportTransformRefusal(result, notify.error, t);+ reportTransformRefusal(+ result,+ { id: layer.id, name: layer.name },+ { error: notify.error, notice: showCanvasRefusalNotice },+ t+ );}- }, [engine, layer.id, makeStatusError, notify, t]);+ }, [engine, layer.id, layer.name, makeStatusError, notify, t]);const handleFitToBbox = useCallback(() => {const transform = fitLayerTransformToBbox(layer, bbox, documentRect);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.browser.test.tsxindex 85a1cf83ac..3c5c459e5a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterControls.browser.test.tsx@@ -78,7 +78,7 @@ const drag = async (offsets: number[], beforeRelease: () => void = () => undefinconst frame = lowThreshold().element().closest<HTMLElement>('[data-scope="scrubber"]')!;const rect = frame.getBoundingClientRect();const startX = rect.left + rect.width / 2;- const xAt = (offset: number) => startX + offset * (rect.width - 20);+ const xAt = (offset: number) => startX + offset * (rect.width - 12);const pointer = (target: EventTarget, type: string, x: number) =>settle(() => target.dispatchEvent(new PointerEvent(type, { bubbles: true, button: 0, clientX: x, pointerId: 1 })));await pointer(frame, 'pointerdown', startX);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsxindex 9b5fc8f547..51e2099a14 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx@@ -25,7 +25,6 @@ import {CircleIcon,CircleOffIcon,CopyIcon,- EyeClosedIcon,EyeIcon,EyeOffIcon,FolderPlusIcon,@@ -41,7 +40,7 @@ import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { COLOR_LABEL_ITEMS } from './colorLabels';-import { ADJUSTMENT_ADD_ITEMS, adjustmentAddActionId } from './layerContextActions';+import { ADJUSTMENT_ADD_ITEMS, adjustmentAddActionId, enabledToggleLabel } from './layerContextActions';import { canGroupSelection, groupLayers, ungroupLayers } from './layerGroupCommands';import { createAdjustmentEntry } from './layerOps';@@ -148,9 +147,11 @@ export const LayerGroupContextMenu = ({onClose();}}, [menuOpen, onClose]);+ const hideable = isOverlayStack(stack);+ const enabledLabel = enabledToggleLabel(document, [group.id], group.isEnabled);const handleToggleEnabled = useCallback(- () => patch(t('widgets.layers.actions.toggleActive'), { isEnabled: !group.isEnabled }),- [group.isEnabled, patch, t]+ () => patch(t(enabledLabel.key), { isEnabled: !group.isEnabled }),+ [enabledLabel.key, group.isEnabled, patch, t]);const handleToggleLock = useCallback(() => patch(t('widgets.layers.actions.toggleLock'), { isLocked: !group.isLocked }),@@ -208,7 +209,6 @@ export const LayerGroupContextMenu = ({);const locked = editingLocked;- const hideable = isOverlayStack(stack);const adjustable = stack === 'raster';const handleAddAdjustment = useCallback(@@ -317,15 +317,15 @@ export const LayerGroupContextMenu = ({<Menu.Separator borderColor="border.subtle" /><MenuActionItemdisabled={locked}- icon={group.isEnabled ? EyeOffIcon : EyeIcon}- label={t(group.isEnabled ? 'widgets.layers.actions.hideGroup' : 'widgets.layers.actions.showGroup')}+ icon={enabledLabel.icon}+ label={t(enabledLabel.key)}value="enabled"onSelect={handleToggleEnabled}/>{hideable ? (<MenuActionItemdisabled={locked}- icon={group.isHidden ? EyeIcon : EyeClosedIcon}+ icon={group.isHidden ? EyeIcon : EyeOffIcon}label={t(group.isHidden ? 'widgets.layers.actions.showGroupOnCanvas' : 'widgets.layers.actions.hideGroupOnCanvas')}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsxindex ac71e7c359..e564b5c75c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx@@ -5,10 +5,9 @@ import { Badge, Box, chakra, HStack, Icon, Input, Text } from '@chakra-ui/react'import { useDraggable, useDroppable } from '@dnd-kit/core';import { IconButton, Tooltip } from '@platform/ui';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { isGroupNode, isHideableLayer, isNodeHidden, isOverlayStack } from '@workbench/canvas-engine/api';+import { isGroupNode, isNodeHidden, isOverlayStack } from '@workbench/canvas-engine/api';import {ChevronRightIcon,- EyeClosedIcon,EyeIcon,EyeOffIcon,FolderIcon,@@ -26,6 +25,7 @@ import type { LayerTreeRow } from './layerTreeRows';import { AdjustmentStatusIcon, useAdjustmentStatus } from './AdjustmentStatusIcon';import { colorLabelHex } from './colorLabels';import { ControlLayerStatusIcon } from './ControlLayerStatusIcon';+import { LAYER_ACTIVE_DOT_SIZE, LayerActiveDot } from './LayerActiveDot';import { recordLayerRowCommit } from './layerPanelDiagnostics';import { anchorFromPoint } from './layerRowCommands';import { layerRowSummary } from './layerRowSummary';@@ -171,6 +171,10 @@ const LayerRowComponent = ({},[commands, node.isEnabled, row.id]);+ const handleSetEnabled = useCallback(+ (isEnabled: boolean) => commands.setEnabled(row.id, isEnabled),+ [commands, row.id]+ );const handleToggleHidden = useCallback((event: { stopPropagation: () => void }) => {event.stopPropagation();@@ -271,9 +275,9 @@ const LayerRowComponent = ({return rest;}, [dragDisabled, listeners]);- const hideable = group ? isOverlayStack(vm.stack) : isHideableLayer(layer!);- const ownHidden = isNodeHidden(node);- const hiddenByAncestor = vm.documentHidden && !ownHidden;+ // Overlay rows (control, inpaint and regional layers, and groups in those stacks) can hide on the canvas alone.+ const overlay = isOverlayStack(vm.stack);+ const hiddenByAncestor = vm.documentHidden && !isNodeHidden(node);const lockedByAncestor = vm.effectiveLocked && !node.isLocked;const disabledByAncestor = !vm.contributionEnabled && node.isEnabled;const tone = primary@@ -438,54 +442,78 @@ const LayerRowComponent = ({{/* Trailing cluster on the stack header's rhythm: the eye sits left of the lock as an overlay header's eye sitsleft of its New button, so eyes and locks each form one column at every depth. */}<HStack flexShrink="0" gap={LAYER_PANEL_CONTROL_GAP} onClick={stopPropagation} onMouseDown={keepRowFocus}>- {hideable && vm.documentHidden && vm.contributionEnabled ? (- // Hidden on the canvas only (an overlay put out of the way): it still shapes generation. The row menu- // sets it; this says so and brings it back. Rendered only when it applies, left of the eye column.- <Tooltip- content={- hiddenByAncestor- ? t('widgets.layers.actions.groupHidden')- : t('widgets.layers.actions.canvasHiddenTooltip')- }- >- <IconButton- aria-label={t('widgets.layers.actions.showOnCanvas')}- color="fg.muted"- disabled={editingLocked || hiddenByAncestor}- size="sm"- tabIndex={-1}- variant="ghost"- onClick={handleToggleHidden}- onPointerDown={stopPropagation}+ {overlay ? (+ // Overlays keep two axes: the dot says whether the layer takes part in generation (off, it is neither+ // drawn nor generated) and the eye only whether it is drawn, so a mask can be out of view yet still used.+ <>+ <LayerActiveDot+ checked={node.isEnabled}+ disabled={editingLocked}+ gatedReason={disabledByAncestor ? t('widgets.layers.actions.groupExcluded') : null}+ label={t('widgets.layers.actions.useInGeneration')}+ tooltip={+ node.isEnabled+ ? t('widgets.layers.actions.excludeFromGeneration')+ : t('widgets.layers.actions.useInGeneration')+ }+ onCheckedChange={handleSetEnabled}+ />+ <Tooltip+ content={+ hiddenByAncestor+ ? t('widgets.layers.actions.groupHidden')+ : vm.documentHidden+ ? t('widgets.layers.actions.showOnCanvas')+ : t('widgets.layers.actions.hideOnCanvas')+ }>- <EyeClosedIcon />- </IconButton>- </Tooltip>- ) : null}- {/* One visibility control: a hidden layer is off the canvas and out of generation alike. */}- <Tooltip- content={- disabledByAncestor- ? t('widgets.layers.actions.groupDisabled')- : node.isEnabled- ? t('widgets.layers.actions.hideLayerTooltip')- : t('widgets.layers.actions.showLayerTooltip')- }- >- <IconButton- aria-label={t('widgets.layers.actions.toggleActive')}- aria-pressed={node.isEnabled}- color={vm.contributionEnabled ? 'fg.muted' : 'fg.subtle'}- disabled={editingLocked}- size="sm"- tabIndex={-1}- variant="ghost"- onClick={handleToggleVisible}- onPointerDown={stopPropagation}- >- {node.isEnabled ? <EyeIcon /> : <EyeOffIcon />}- </IconButton>- </Tooltip>+ <IconButton+ aria-label={t('widgets.layers.actions.showOnCanvas')}+ aria-pressed={!vm.documentHidden}+ // Out of generation the layer is not drawn either; the eye keeps its own state, dimmed, for when+ // the dot comes back on.+ color={vm.contributionEnabled && !vm.documentHidden ? 'fg.muted' : 'fg.subtle'}+ disabled={editingLocked || hiddenByAncestor}+ size="sm"+ tabIndex={-1}+ variant="ghost"+ onClick={handleToggleHidden}+ onPointerDown={stopPropagation}+ >+ {vm.documentHidden ? <EyeOffIcon /> : <EyeIcon />}+ </IconButton>+ </Tooltip>+ </>+ ) : (+ // Raster layers have one axis: the eye takes a layer off the canvas and out of generation alike. The empty+ // dot slot keeps the eye and lock columns aligned with the overlay stacks.+ <>+ <Box aria-hidden flexShrink="0" w={LAYER_ACTIVE_DOT_SIZE} />+ <Tooltip+ content={+ disabledByAncestor+ ? t('widgets.layers.actions.groupDisabled')+ : node.isEnabled+ ? t('widgets.layers.actions.hideLayerTooltip')+ : t('widgets.layers.actions.showLayerTooltip')+ }+ >+ <IconButton+ aria-label={t('widgets.layers.actions.toggleActive')}+ aria-pressed={node.isEnabled}+ color={vm.contributionEnabled ? 'fg.muted' : 'fg.subtle'}+ disabled={editingLocked}+ size="sm"+ tabIndex={-1}+ variant="ghost"+ onClick={handleToggleVisible}+ onPointerDown={stopPropagation}+ >+ {node.isEnabled ? <EyeIcon /> : <EyeOffIcon />}+ </IconButton>+ </Tooltip>+ </>+ )}<Tooltipcontent={lockedByAncestor ? t('widgets.layers.actions.groupLocked') : t('widgets.layers.actions.toggleLock')diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsxindex 1e3b8115ec..62ed80a9d1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRowSurface.tsx@@ -2,11 +2,11 @@ import type { RowProps } from '@platform/ui';import type { ReactNode } from 'react';import { Row } from '@platform/ui';+import { rowFocusRing } from '@theme/recipes';import { useMemo } from 'react';import { LAYER_TREE_INDENT_PX } from './layerPanelRows';-const LAYER_ROW_BACKGROUND_TRANSITION = 'background min(40ms, var(--wb-motion-duration-fast)) ease-out';/*** Rows and stack headers end with this inset and space their trailing buttons by this gap, so the header eye and New* buttons share columns with the rows' eyes and locks. Nesting indents the start edge only.@@ -16,13 +16,14 @@ export const LAYER_PANEL_CONTROL_GAP = '0.5';/*** Tree rows keep a gap below their surface (`pb="0.5"`) and indent it past the tree guides; the ring frames the* surface, not the gap or the guides, so it matches the selection fill and the row's content stays centred inside it.+ * It is the platform rows' own ring, moved from the focused tree item onto its surface.*/export const TREE_ROW_FOCUS = {- '& > [data-layer-row-surface]': { boxShadow: 'inset 0 0 0 2px {colors.accent.solid}' },+ '& > [data-layer-row-surface]': rowFocusRing,outline: 'none',};// The leading inset mirrors the end inset.-export const LAYER_ROW_INSET_PX = 6;+export const LAYER_ROW_INSET_PX = 3;/** Layer and group rows lead with a box this wide: thumbnail, group pile or degraded placeholder. */export const LAYER_LEADING_BOX_PX = 32;@@ -51,7 +52,6 @@ export const LayerRowSurface = ({pe={LAYER_PANEL_END_INSET}ps={`${LAYER_ROW_INSET_PX}px`}style={indentStyle}- transition={LAYER_ROW_BACKGROUND_TRANSITION}>{children}</Row>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsxindex 225085cd17..ac01db61dd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackHeader.tsx@@ -5,6 +5,7 @@ import type { KeyboardEvent, MouseEvent } from 'react';import { Box, HStack, Icon, Text, VisuallyHidden } from '@chakra-ui/react';import { IconButton, Tooltip } from '@platform/ui';import { FeatureHint, FeatureHintExclusion } from '@platform/ui/hints/FeatureHint';+import { rowFocusRing } from '@theme/recipes';import { ChevronDownIcon } from 'lucide-react';import { memo, useCallback, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -15,8 +16,6 @@ import { anchorFromPoint } from './layerRowCommands';import { LAYER_PANEL_CONTROL_GAP, LAYER_PANEL_END_INSET } from './LayerRowSurface';import { useLayerStackActions, type LayerStackActionsEngine } from './useLayerStackActions';-const HEADER_FOCUS = { outline: '2px solid', outlineColor: 'accent.solid', outlineOffset: '-2px' };-const STACK_HINTS: Record<LayerStackKind, FeatureHintId> = {control: 'layerStackControl',inpaint_mask: 'layerStackInpaintMask',@@ -115,7 +114,7 @@ const LayerStackHeaderComponent = ({role={pinned ? undefined : 'treeitem'}rounded="sm"tabIndex={pinned ? undefined : focused ? 0 : -1}- _focusVisible={HEADER_FOCUS}+ _focusVisible={rowFocusRing}onClick={handleClick}onContextMenu={handleContextMenu}onFocus={pinned ? undefined : handleFocus}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsxindex 4baa910ab7..8c2de0a7f1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackMenu.tsx@@ -43,7 +43,7 @@ export const LayerStackMenu = ({ anchor, document, editingLocked, engine, stack,{actions.map((action) => (<Menu.Item key={action.id} disabled={action.disabled} value={action.id} onSelect={action.run}><HStack gap="2" minW="0" w="full">- <Icon as={action.icon} boxSize="3.5" color="fg.muted" flexShrink={0} />+ <Icon as={action.icon} boxSize="3.5" color="fg.subtle" flexShrink={0} /><Text flex="1" fontSize="md">{action.status ?? action.label}</Text>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsxindex 55dcb1e4d3..f71cd09701 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx@@ -7,10 +7,12 @@ import type { Project } from '@workbench/projectContracts';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import {+ compileDocumentLeaves,createDocumentModel,getDocumentIndex,getDocumentLayer,getDocumentLeaves,+ isNodeHidden,} from '@workbench/canvas-engine/api';import {groupContract,@@ -123,12 +125,21 @@ vi.mock('./LayerSurfaceHost', () => ({surface,}: {commands: LayerRowCommands;- surface: { kind: string; id?: string; child?: { key: string } } | null;+ surface: {+ kind: string;+ id?: string;+ child?: { key: string };+ anchor: { height: number; width: number; x: number; y: number };+ } | null;}) => {surfaceCommands.current = commands;return (// Hidden like the harness outputs so the tree's scroll geometry doesn't depend on this stand-in's line height.- <output data-testid="surface" style={{ display: 'none' }}>+ <output+ data-anchor={surface ? JSON.stringify(surface.anchor) : undefined}+ data-testid="surface"+ style={{ display: 'none' }}+ >{surface ? `${surface.kind}:${surface.child?.key ?? surface.id}` : 'none'}</output>);@@ -147,8 +158,15 @@ void i18n.use(initReactI18next).init({layers: {actions: {collapseGroup: 'Collapse group',+ excludeFromGeneration: 'Exclude from generation',+ excludeGroupFromGeneration: 'Exclude group from generation',expandGroup: 'Expand group',+ groupExcluded: 'Left out of generation by a group',+ groupHidden: 'Hidden on the canvas by a group',groupLocked: 'Locked by a group',+ hideGroup: 'Hide group',+ hideLayer: 'Hide layer',+ hideOnCanvas: 'Hide on canvas',hideModifiers: 'Hide modifiers',indent: 'Move into the group above',outdent: 'Move out of the group',@@ -160,6 +178,7 @@ void i18n.use(initReactI18next).init({toggleLock: 'Toggle lock',toggleActive: 'Toggle layer active',toggleVisibility: 'Toggle visibility',+ useInGeneration: 'Use in generation',},adjustments: { curves: 'Curves', saturation: 'Saturation' },modifiers: {@@ -172,6 +191,8 @@ void i18n.use(initReactI18next).init({removeAdjustment: 'Remove adjustment',removeDenoise: 'Remove denoise limit',removeNoise: 'Remove noise',+ parentDisabled: 'The layer is hidden',+ parentExcluded: 'The layer is left out of generation',reorderAdjustment: 'Reorder adjustment',toggleActive: 'Toggle active',},@@ -600,6 +621,14 @@ describe('LayersTree keyboard and accessibility', () => {expect(document.activeElement).toBe(treeitem('Top'));await act(() => userEvent.keyboard('{Shift>}{F10}{/Shift}'));expect(output('surface')).toBe('menu:top');+ // Opened where a right-click would be, at a point under the row, so it shows no arrow as a context menu.+ const row = treeitem('Top').closest('[data-layer-row-id]')!.getBoundingClientRect();+ expect(JSON.parse(host!.querySelector<HTMLElement>('[data-testid="surface"]')!.dataset.anchor!)).toEqual({+ height: 1,+ width: 1,+ x: row.left,+ y: row.bottom,+ });});it('frames the keyboard-focused row surface with its ring, not the gap below it or the guides beside it', async () => {@@ -610,16 +639,17 @@ describe('LayersTree keyboard and accessibility', () => {const row = treeitem('Inner');expect(document.activeElement).toBe(row);- // The ring is the surface's own inset shadow, so it shares the selection fill's box: clear of the gap below the- // row and of the indent where the tree guides run.+ // The ring is the platform rows' own inset ring, drawn on the surface so it shares the selection fill's box: clear+ // of the gap below the row and of the indent where the tree guides run.const surface = row.querySelector<HTMLElement>('[data-layer-row-surface]')!;- expect(getComputedStyle(surface).boxShadow).toContain('inset');+ const ring = getComputedStyle(surface);+ expect([ring.outlineStyle, ring.outlineWidth, ring.outlineOffset]).toEqual(['solid', '2px', '-2px']);expect(getComputedStyle(row).outlineStyle).toBe('none');const rowRect = row.getBoundingClientRect();const surfaceRect = surface.getBoundingClientRect();expect(surfaceRect.bottom).toBeLessThan(rowRect.bottom);expect(surfaceRect.left - rowRect.left).toBe(LAYER_TREE_INDENT_PX);- expect(getComputedStyle(treeitem('Top').querySelector('[data-layer-row-surface]')!).boxShadow).toBe('none');+ expect(getComputedStyle(treeitem('Top').querySelector('[data-layer-row-surface]')!).outlineStyle).toBe('none');});it('keeps the focused row mounted and focused while scrolled far away', async () => {@@ -694,38 +724,55 @@ describe('LayersTree selection, surfaces and structure', () => {expect(output('selected-layer')).toBe('none');});- it('ends every row with the eye then the lock, each in one column at any depth', async () => {+ it('ends overlay rows with the dot, eye and lock and raster rows with the eye and lock, in shared columns', async () => {await renderTree([paint('top', 'Top'),groupContract('g', [paint('inner', 'Inner'), groupContract('h', [paint('deep', 'Deep')], { name: 'H' })], {name: 'G',}),layerContract('masked', 'inpaint_mask', { isHidden: true, name: 'Masked' }),+ groupContract('mg', [layerContract('nested', 'inpaint_mask', { name: 'Nested' })], { name: 'Mask group' }),]);- await act(() => userEvent.click(treeitem('G').querySelector('button[aria-label="Expand group"]')!));- await act(() => userEvent.click(treeitem('H').querySelector('button[aria-label="Expand group"]')!));- const ids = ['top', 'g', 'inner', 'h', 'deep', 'masked'];+ for (const name of ['G', 'H', 'Mask group']) {+ await act(() => userEvent.click(treeitem(name).querySelector('button[aria-label="Expand group"]')!));+ }+ const raster = ['top', 'g', 'inner', 'h', 'deep'];+ const overlays = ['masked', 'mg', 'nested'];const rowButtons = (id: string) =>[...host!.querySelectorAll<HTMLButtonElement>(`[data-layer-row-id="${id}"] button`)].map((button) => ({label: button.getAttribute('aria-label'),rect: button.getBoundingClientRect(),}));- for (const id of ids) {+ for (const id of raster) {const labels = rowButtons(id).map((button) => button.label);expect(labels.slice(-2)).toEqual(['Toggle layer active', 'Toggle lock']);+ expect(labels).not.toContain('Use in generation');+ expect(labels).not.toContain('Show on canvas');+ }+ // Layers and groups alike; the canvas-hidden mask carries that state on its eye, not on an extra marker.+ for (const id of overlays) {+ expect(rowButtons(id).map((button) => button.label)).toEqual([+ ...(id === 'mg' ? ['Collapse group'] : []),+ 'Use in generation',+ 'Show on canvas',+ 'Toggle lock',+ ]);}- // The canvas-only marker appears only where it applies, ahead of the eye column rather than in it.- expect(- rowButtons('masked')- .map((button) => button.label)- .slice(-3)- ).toEqual(['Show on canvas', 'Toggle layer active', 'Toggle lock']);-- const columnLefts = (label: string) =>- new Set(ids.map((id) => rowButtons(id).find((button) => button.label === label)!.rect.left));- expect(columnLefts('Toggle layer active').size).toBe(1);- expect(columnLefts('Toggle lock').size).toBe(1);++ const leftOf = (id: string, label: string) => rowButtons(id).find((button) => button.label === label)!.rect.left;+ const eyes = new Set([+ ...raster.map((id) => leftOf(id, 'Toggle layer active')),+ ...overlays.map((id) => leftOf(id, 'Show on canvas')),+ ]);+ expect(eyes.size).toBe(1);+ expect(new Set([...raster, ...overlays].map((id) => leftOf(id, 'Toggle lock'))).size).toBe(1);+ expect(new Set(overlays.map((id) => leftOf(id, 'Use in generation'))).size).toBe(1);+ // The dot is as wide as the eye beside it.+ const dot = rowButtons('masked').find((button) => button.label === 'Use in generation')!.rect;+ const eye = rowButtons('masked').find((button) => button.label === 'Show on canvas')!.rect;+ expect(dot.width).toBe(eye.width);+ expect(dot.right).toBeLessThan(eye.left);// Nesting indents the leading edge only.const thumbnailLeft = (id: string) =>host!.querySelector(`[data-layer-row-id="${id}"] [data-testid="thumbnail"]`)!.getBoundingClientRect().left;@@ -733,6 +780,39 @@ describe('LayersTree selection, surfaces and structure', () => {expect(thumbnailLeft('inner') - thumbnailLeft('top')).toBe(LAYER_TREE_INDENT_PX);});+ it('keeps a long name truncated beside the overlay controls at a narrow panel width', async () => {+ const name = 'A regional guidance layer with a very long descriptive name';+ await renderTree([layerContract('long', 'regional_guidance', { name })]);+ const panel = host!.querySelector<HTMLElement>('div[style*="width: 480px"]')!;+ panel.style.width = '220px';+ await settle();+ const row = treeitem(name);+ const lock = row.querySelector('button[aria-label="Toggle lock"]')!.getBoundingClientRect();+ const dot = row.querySelector('button[aria-label="Use in generation"]')!.getBoundingClientRect();+ expect(lock.right).toBeLessThanOrEqual(row.getBoundingClientRect().right);+ // The name gives way to the controls: it ends before the dot and its text is cut short.+ const label = row.querySelector<HTMLElement>(`[title="${name}"]`)!;+ const text = label.firstElementChild as HTMLElement;+ expect(label.getBoundingClientRect().right).toBeLessThanOrEqual(dot.left);+ expect(text.scrollWidth).toBeGreaterThan(text.clientWidth);+ });++ it('keeps a long raster name truncated before its eye, the empty dot slot included', async () => {+ const name = 'A raster layer with a very long descriptive name that cannot fit';+ await renderTree([paint('long', name)]);+ const panel = host!.querySelector<HTMLElement>('div[style*="width: 480px"]')!;+ panel.style.width = '220px';+ await settle();+ const row = treeitem(name);+ const eye = row.querySelector('button[aria-label="Toggle layer active"]')!.getBoundingClientRect();+ const lock = row.querySelector('button[aria-label="Toggle lock"]')!.getBoundingClientRect();+ expect(lock.right).toBeLessThanOrEqual(row.getBoundingClientRect().right);+ const label = row.querySelector<HTMLElement>(`[title="${name}"]`)!;+ const text = label.firstElementChild as HTMLElement;+ expect(label.getBoundingClientRect().right).toBeLessThanOrEqual(eye.left);+ expect(text.scrollWidth).toBeGreaterThan(text.clientWidth);+ });+it('fills a group’s leading box with its preview pile, whatever the number of cards', async () => {await renderTree([paint('plain', 'Plain'),@@ -917,13 +997,12 @@ describe('LayersTree selection, surfaces and structure', () => {[...host!.querySelectorAll<HTMLElement>(`[role="tree"] ${selector}`)].map((element) => element.getBoundingClientRect().left);- const rowLefts = (label: string) =>- ['top', 'mask', 'mg', 'nested'].flatMap((id) =>- lefts(`[data-layer-row-id="${id}"] button[aria-label="${label}"]`)- );+ const rowLefts = (ids: readonly string[], label: string) =>+ ids.flatMap((id) => lefts(`[data-layer-row-id="${id}"] button[aria-label="${label}"]`));- const eyes = rowLefts('Toggle layer active');- const locks = rowLefts('Toggle lock');+ // The raster eye shows and generates; an overlay's eye only shows. Either way it is the row's eye column.+ const eyes = [...rowLefts(['top'], 'Toggle layer active'), ...rowLefts(['mask', 'mg', 'nested'], 'Show on canvas')];+ const locks = rowLefts(['top', 'mask', 'mg', 'nested'], 'Toggle lock');expect(eyes).toHaveLength(4);expect(locks).toHaveLength(4);// The inpaint header's eye, and both headers' New buttons (raster has no eye).@@ -939,22 +1018,188 @@ describe('LayersTree selection, surfaces and structure', () => {}});- it('marks an overlay hidden on the canvas only, and brings it back from the row', async () => {- await renderTree([- layerContract('shown', 'inpaint_mask', { name: 'Shown' }),- layerContract('masked', 'inpaint_mask', { isHidden: true, name: 'Masked' }),- ]);- const showOnCanvas = (id: string) =>- host!.querySelector<HTMLButtonElement>(`[data-layer-row-id="${id}"] button[aria-label="Show on canvas"]`);- expect(showOnCanvas('shown')).toBeNull();- // Still used by generation, so its own eye stays open.- expect(- host!.querySelector('[data-layer-row-id="masked"] button[aria-label="Toggle layer active"]')- ).toHaveAttribute('aria-pressed', 'true');- await act(() => userEvent.click(showOnCanvas('masked')!));- expect(committedEdits.at(-1)!.forward).toEqual({- type: 'setCanvasLayersHidden',- updates: [{ id: 'masked', isHidden: false }],+ describe('overlay rows keep generation and canvas visibility apart', () => {+ const leaf = (id: string) => compileDocumentLeaves(harnessDocument).find((entry) => entry.id === id)!;+ const control = (id: string, label: string) =>+ host!.querySelector<HTMLButtonElement>(`[data-layer-row-id="${id}"] button[aria-label="${label}"]`)!;+ const dotOf = (id: string) => control(id, 'Use in generation');+ const eyeOf = (id: string) => control(id, 'Show on canvas');+ const state = (id: string) => {+ const { contributionEnabled, documentHidden, layer } = leaf(id);+ return { contributionEnabled, documentHidden, isEnabled: layer.isEnabled, isHidden: isNodeHidden(layer) };+ };++ it.each([+ ['inpaint_mask', 'Mask'],+ ['regional_guidance', 'Region'],+ ['control', 'Control'],+ ] as const)(+ 'hides a %s on the canvas yet keeps it in generation, and the dot takes it out of both',+ async (type, name) => {+ await renderTree([layerContract('overlay', type, { name })]);+ expect(dotOf('overlay')).toHaveAttribute('aria-pressed', 'true');+ expect(eyeOf('overlay')).toHaveAttribute('aria-pressed', 'true');++ await act(() => userEvent.click(eyeOf('overlay')));+ expect(state('overlay')).toEqual({+ contributionEnabled: true,+ documentHidden: true,+ isEnabled: true,+ isHidden: true,+ });+ expect(eyeOf('overlay')).toHaveAttribute('aria-pressed', 'false');+ expect(eyeOf('overlay').querySelector('svg.lucide-eye-off')).not.toBeNull();+ expect(dotOf('overlay')).toHaveAttribute('aria-pressed', 'true');+ expect(output('selected-layer')).toBe('none');++ await act(() => userEvent.click(dotOf('overlay')));+ expect(state('overlay')).toEqual({+ contributionEnabled: false,+ documentHidden: true,+ isEnabled: false,+ isHidden: true,+ });+ expect(dotOf('overlay')).toHaveAttribute('aria-pressed', 'false');++ // Out of generation the eye stays operable, keeping its own state for when the dot comes back on.+ expect(eyeOf('overlay').disabled).toBe(false);+ await act(() => userEvent.click(eyeOf('overlay')));+ expect(state('overlay')).toEqual({+ contributionEnabled: false,+ documentHidden: false,+ isEnabled: false,+ isHidden: false,+ });+ // Shown, but dimmed like the muted name: an excluded layer is not drawn either.+ const eyeColor = () => getComputedStyle(eyeOf('overlay')).color;+ const lockColor = getComputedStyle(control('overlay', 'Toggle lock')).color;+ await expect.poll(eyeColor).not.toBe(lockColor);+ await act(() => userEvent.click(dotOf('overlay')));+ expect(state('overlay')).toEqual({+ contributionEnabled: true,+ documentHidden: false,+ isEnabled: true,+ isHidden: false,+ });+ await expect.poll(eyeColor).toBe(lockColor);+ }+ );++ it('drives an overlay group from its own dot and eye, and shows its members gated by it', async () => {+ await renderTree([+ groupContract('rg', [layerContract('member', 'regional_guidance', { name: 'Member' })], { name: 'Regions' }),+ layerContract('loose', 'regional_guidance', { isEnabled: false, name: 'Loose' }),+ ]);+ await act(() => userEvent.click(treeitem('Regions').querySelector('button[aria-label="Expand group"]')!));+ const dotFill = (id: string) => getComputedStyle(dotOf(id), '::before').backgroundColor;+ const dotRing = (id: string) => getComputedStyle(dotOf(id), '::before').borderColor;+ const ringStyle = (id: string) => getComputedStyle(dotOf(id), '::before').borderTopStyle;+ const description = (id: string) => {+ const describedBy = dotOf(id).getAttribute('aria-describedby');+ return describedBy ? document.getElementById(describedBy)?.textContent : null;+ };+ expect(description('member')).toBeNull();+ const accent = dotFill('member');+ expect(accent).not.toBe('rgba(0, 0, 0, 0)');++ await act(() => userEvent.click(dotOf('rg')));+ expect(getDocumentIndex(harnessDocument).byId.get('rg')!.node.isEnabled).toBe(false);+ // The member is on by itself but left out by the group: a hollow, dashed accent ring, unlike the solid ring of a+ // dot that is off, and it says why to assistive tech rather than only reporting itself pressed.+ expect(state('member')).toMatchObject({ contributionEnabled: false, isEnabled: true });+ expect(dotOf('member')).toHaveAttribute('aria-pressed', 'true');+ expect(description('member')).toBe('Left out of generation by a group');+ await expect.poll(() => dotFill('member')).toBe('rgba(0, 0, 0, 0)');+ expect(dotRing('member')).toBe(accent);+ expect(ringStyle('member')).toBe('dashed');+ expect(dotFill('loose')).toBe('rgba(0, 0, 0, 0)');+ expect(ringStyle('loose')).toBe('solid');+ expect(description('loose')).toBeNull();+ await act(() => userEvent.click(dotOf('rg')));+ expect(ringStyle('member')).toBe('solid');+ expect(description('member')).toBeNull();++ await act(() => userEvent.click(eyeOf('rg')));+ expect(isNodeHidden(getDocumentIndex(harnessDocument).byId.get('rg')!.node)).toBe(true);+ // Hidden by the group, still generated; the member's eye reports it and yields to the group's.+ expect(state('member')).toEqual({+ contributionEnabled: true,+ documentHidden: true,+ isEnabled: true,+ isHidden: false,+ });+ expect(eyeOf('member')).toHaveAttribute('aria-pressed', 'false');+ expect(eyeOf('member').disabled).toBe(true);+ expect(dotOf('member').disabled).toBe(false);+ });++ it('labels the undo step by the axis each control changed, naming groups as their menus do', async () => {+ await renderTree([+ layerContract('mask', 'inpaint_mask', { name: 'Mask' }),+ groupContract('mg', [layerContract('inner', 'inpaint_mask', { name: 'Inner' })], { name: 'Masks' }),+ paint('art', 'Art'),+ groupContract('rg', [paint('deep', 'Deep')], { name: 'Paints' }),+ ]);+ const labels: string[] = [];+ const commit = vi.spyOn(engine.layers, 'commitPrepared').mockImplementation((label, edit) => {+ labels.push(label);+ committedEdits.push(edit);+ dispatchExternal(edit.forward);+ return { status: 'committed' };+ });+ try {+ await act(() => userEvent.click(dotOf('mask')));+ await act(() => userEvent.click(dotOf('mask')));+ await act(() => userEvent.click(eyeOf('mask')));+ await act(() => userEvent.click(control('art', 'Toggle layer active')));+ await act(() => userEvent.click(dotOf('mg')));+ await act(() => userEvent.click(control('rg', 'Toggle layer active')));+ } finally {+ commit.mockRestore();+ }+ expect(labels).toEqual([+ 'Exclude from generation',+ 'Use in generation',+ 'Hide on canvas',+ 'Hide layer',+ 'Exclude group from generation',+ 'Hide group',+ ]);+ });++ it('says why an overlay child row has no effect in the overlay’s words, and a raster one in its own', async () => {+ await renderTree([+ layerContract('mask', 'inpaint_mask', {+ isEnabled: false,+ name: 'Mask',+ noise: { isEnabled: true, level: 0.2 },+ }),+ layerContract('art', 'raster', {+ adjustments: [{ id: 'a1', isEnabled: true, saturation: 0.1, type: 'hsl' }],+ isEnabled: false,+ name: 'Art',+ }),+ ]);+ // Polled: the previous row's tooltip can still be fading out when the next one is hovered.+ const expectTooltip = async (row: string, text: string) => {+ const toggle = treeitem(row).querySelector('button[aria-label="Toggle active"]')!;+ await act(() => userEvent.hover(toggle));+ await expect+ .poll(() => [...document.querySelectorAll('[role="tooltip"]')].map((tooltip) => tooltip.textContent))+ .toContain(text);+ await act(() => userEvent.unhover(toggle));+ await expect.poll(() => document.querySelectorAll('[role="tooltip"]').length).toBe(0);+ };+ await expectTooltip('Noise', 'The layer is left out of generation');+ await expectTooltip('Saturation', 'The layer is hidden');+ });++ it('keeps one tab stop with both overlay controls on the row', async () => {+ await renderTree([layerContract('mask', 'inpaint_mask', { name: 'Mask' })]);+ expect(tabStops()).toHaveLength(1);+ expect(tabStops()[0]!.getAttribute('role')).toBe('treeitem');+ await act(() => userEvent.click(dotOf('mask')));+ expect(document.activeElement).toBe(treeitem('Mask'));});});@@ -1003,6 +1248,7 @@ describe('LayersTree selection, surfaces and structure', () => {reportStructuralCommit: vi.fn(),reportPreparedCommit: vi.fn(),reportLayerOperation: vi.fn(),+ reportMergeDownRefusal: vi.fn(),reportTransformRefusal: vi.fn(),t: (key) => key,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsxindex 1ae3fdea24..18f97c3fb9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx@@ -46,6 +46,7 @@ import {type ProjectedChildRow,} from './layerChildRows';import { clearLayerChildSelection, selectLayerChild, useLayerChildSelection } from './layerChildSelection';+import { enabledToggleLabel } from './layerContextActions';import { copyLayerToClipboard } from './layerExportActions';import { createAdjustmentId, createNoiseSeed } from './layerOps';import {@@ -62,7 +63,7 @@ import {} from './layerPanelRows';import { clearLayerPropertiesRequest, useCurrentLayerPropertiesRequest } from './layerPropertiesRequestStore';import { LayerDragGhost, LayerRow, type LayerRowDragState } from './LayerRow';-import { anchorFromRect } from './layerRowCommands';+import { anchorFromPoint } from './layerRowCommands';import { LayerStackHeader } from './LayerStackHeader';import { LayerSurfaceHost, type LayerSurfaceEngine, type LayerSurfaceRequest } from './LayerSurfaceHost';import { createLayerTreeAutoScroller, type LayerTreeAutoScroller } from './layerTreeAutoScroll';@@ -145,10 +146,13 @@ const reparentCommandForTarget = (target: LayerDropTarget): ReparentCommand => (const isMenuKey = (event: KeyboardEvent<HTMLElement>): boolean =>event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey);-/** The viewport box of a rendered item, the anchor a keyboard-opened menu uses. */+/**+ * A keyboard-opened menu anchors where a right-click would: a point, at the rendered item's bottom-left corner. A point+ * keeps it a context menu, without the arrow a menu anchored to a box gets.+ */const anchorOfItem = (host: HTMLElement | null, key: string): LayerSurfaceAnchor | null => {- const element = host?.querySelector<HTMLElement>(`[data-layer-row-id="${CSS.escape(key)}"]`);- return element ? anchorFromRect(element.getBoundingClientRect()) : null;+ const rect = host?.querySelector<HTMLElement>(`[data-layer-row-id="${CSS.escape(key)}"]`)?.getBoundingClientRect();+ return rect ? anchorFromPoint(rect.left, rect.bottom) : null;};/** One absolutely positioned slot of the virtual list; the style object is built once per offset. */@@ -669,7 +673,7 @@ export const LayersTree = ({setChildEnabled: (child, isEnabled) =>runChildStructural(t('widgets.layers.modifiers.toggleActive'), child, { isEnabled, type: 'set-enabled' }),setEnabled: (id, isEnabled) =>- runStructural(t('widgets.layers.actions.toggleActive'), {+ runStructural(t(enabledToggleLabel(latest.current.document, [id], !isEnabled).key), {type: 'set-enabled',updates: [{ id, isEnabled }],}),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.browser.test.tsxnew file mode 100644index 0000000000..a8c090b3d6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.browser.test.tsx@@ -0,0 +1,298 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { CanvasNodeContract } from '@workbench/canvas-engine/contracts';+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 { shallowEqual, useExternalStoreSelector } from '@platform/state/selectors';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';+import { resolveWidgetValues } from '@workbench/widgetState';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { createInstance } from 'i18next';+import { act, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++type Store = ReturnType<typeof createWorkbenchStore>;+type Snapshot = ReturnType<Store['getSnapshot']>;++const harness = vi.hoisted(() => ({+ engine: null as CanvasEngine | null,+ store: null as ReturnType<typeof createWorkbenchStore> | null,+}));+const store = () => harness.store!;+const useSnapshot = <Selected,>(+ select: (snapshot: Snapshot) => Selected,+ isEqual: (a: Selected, b: Selected) => boolean = shallowEqual+) => useExternalStoreSelector(store().subscribe, store().getSnapshot, select, isEqual);++// A real store and engine without account persistence or the canvas registry; the panel reads and acts through them.+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useActiveProjectId: () => useSnapshot((snapshot) => snapshot.activeProject.id),+ useActiveProjectName: () => useSnapshot((snapshot) => snapshot.activeProject.name),+ useActiveProjectSelector: <T,>(select: (project: Project) => T, isEqual?: (a: T, b: T) => boolean) =>+ useSnapshot((snapshot) => select(snapshot.activeProject), isEqual),+ useOptionalWorkbenchCommands: () => store().commands,+ useOptionalWorkbenchQueries: () => store().queries,+ useWidgetInstanceValuesSelector: <T,>(+ instanceId: string,+ select: (values: Record<string, unknown>) => T,+ isEqual?: (a: T, b: T) => boolean+ ) =>+ useSnapshot(+ (snapshot) =>+ select(resolveWidgetValues(snapshot.activeProject.widgetInstances[instanceId], snapshot.scopedDefaults)),+ isEqual+ ),+ useWorkbenchCommands: () => store().commands,+ useWorkbenchQueries: () => store().queries,+ useWorkbenchSelector: <T,>(select: (snapshot: Snapshot) => T, isEqual?: (a: T, b: T) => boolean) =>+ useSnapshot(select, isEqual),+}));+vi.mock('@workbench/canvas-operations/react', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useCanvasEngine: () => harness.engine,+}));++const { LayersWidgetView } = await import('./LayersWidgetView');+const { PanelBodySlot } = await import('@workbench/widget-frame/WidgetRenderer');+const { layersWidgetManifest } = await import('./manifest');++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ initAsync: false,+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const noop = () => undefined;+const runtime = {+ commands: { register: () => noop },+ hotkeys: { register: () => noop },+ instanceId: 'layers-instance',+ state: { patch: noop },+} as unknown as WidgetViewProps['runtime'];+const manifest = { id: 'layers', label: 'Layers' } as unknown as WidgetViewProps['manifest'];+const instance = { id: 'layers-instance', typeId: 'layers' } as unknown as WidgetViewProps['instance'];++/** The Add-layer menu the panel opens for a right-click on its empty area. */+const addLayerMenus = () =>+ [...document.querySelectorAll<HTMLElement>('[role="menu"][data-state="open"]')].filter(+ (menu) => menu.querySelector('[role="menuitem"][data-value="inpaint_mask"]') !== null+ );++let host: HTMLDivElement;+let root: Root;++/** Mounts the panel over a real store and engine; `wrap` places it in a host such as the widget frame's body. */+const mountPanel = async ({+ hostStyle = 'display:flex;flex-direction:column;height:700px;width:360px',+ layers = [layerContract('art', 'raster', { name: 'Art' })],+ wrap = (view) => view,+}: {+ hostStyle?: string;+ layers?: CanvasNodeContract[];+ wrap?: (view: ReactNode) => ReactNode;+} = {}) => {+ const initial = createInitialWorkbenchState();+ const base = initial.projects[0]!;+ const document = { ...base.canvas.document, stacks: stacksFrom(layers) };+ harness.store = createWorkbenchStore({ ...initial, projects: [{ ...base, canvas: { ...base.canvas, document } }] });+ const projectId = store().getState().activeProjectId;+ harness.engine = createCanvasEngine({+ ensureProjectOnServer: () => Promise.resolve(),+ imageResolver: () => Promise.reject(new Error('no images in this harness')),+ mutationPort: createCanvasProjectMutationPort(store(), projectId),+ projectId,+ reportError: noop,+ });+ host = window.document.createElement('div');+ host.style.cssText = hostStyle;+ window.document.body.append(host);+ root = createRoot(host);+ await act(() =>+ root.render(+ <QueryClientProvider client={new QueryClient()}>+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ {wrap(<LayersWidgetView instance={instance} manifest={manifest} region="right" runtime={runtime} />)}+ </ChakraProvider>+ </I18nextProvider>+ </QueryClientProvider>+ )+ );+ await expect.element(page.getByRole('treeitem', { name: /Art/ })).toBeVisible();+};++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ harness.engine?.lifecycle.dispose();+ harness.engine = null;+ harness.store = null;+});++/** Menus open within a frame of their event; give a leaked one two frames to show before checking. */+const expectNoAddLayerMenu = async () => {+ for (let frame = 0; frame < 2; frame++) {+ await new Promise((resolve) => {+ requestAnimationFrame(resolve);+ });+ }+ expect(addLayerMenus()).toHaveLength(0);+};++describe('layers panel context menus', () => {+ beforeEach(() => mountPanel());++ it("leaves a right-click in a layer menu's rename dialog to the browser", async () => {+ await userEvent.click(page.getByRole('treeitem', { name: /Art/ }), { button: 'right' });+ await page.getByRole('menuitem', { name: 'Rename layer', exact: true }).click();+ const dialog = page.getByRole('dialog', { name: 'Rename layer' });+ await expect.element(dialog).toBeVisible();++ const seen: { prevented: boolean | null } = { prevented: null };+ const record = (event: Event) => {+ seen.prevented = event.defaultPrevented;+ };+ window.addEventListener('contextmenu', record);+ try {+ await userEvent.click(dialog.getByRole('textbox'), { button: 'right' });+ } finally {+ window.removeEventListener('contextmenu', record);+ }++ // The input's native menu (paste, spelling) applies: nothing on the page claimed the event.+ expect(seen.prevented).toBe(false);+ await expectNoAddLayerMenu();+ await expect.element(dialog).toBeVisible();+ });++ it("keeps a right-click on an open layer menu's item inside that menu", async () => {+ await userEvent.click(page.getByRole('treeitem', { name: /Art/ }), { button: 'right' });+ const rename = page.getByRole('menuitem', { name: 'Rename layer', exact: true });+ await expect.element(rename).toBeVisible();++ await userEvent.click(rename, { button: 'right' });++ await expectNoAddLayerMenu();+ });++ it('opens the Add-layer menu for a right-click on the empty area below the layers', async () => {+ const tree = page.getByRole('tree').element();+ // The tree's scroll area keeps a minimum height, so space below the last row stays part of the panel.+ const area = tree.parentElement!.parentElement!;+ const bounds = area.getBoundingClientRect();+ const lastRow = [...tree.querySelectorAll('[role="treeitem"]')].at(-1)!.getBoundingClientRect();+ expect(bounds.bottom - lastRow.bottom).toBeGreaterThan(20);++ await userEvent.click(area, {+ button: 'right',+ position: { x: bounds.width / 2, y: (lastRow.bottom + bounds.bottom) / 2 - bounds.top },+ });++ await expect.poll(() => addLayerMenus()).toHaveLength(1);+ });+});++describe('layers panel in a docked widget body', () => {+ // Enough rows that the tree's own height is several times the panel's.+ const manyLayers = Array.from({ length: 65 }, (_, index) =>+ layerContract(`layer-${index}`, 'raster', { name: index === 0 ? 'Art' : `Layer ${index}` })+ );+ const mountInPanelBody = (heightPx: number) =>+ mountPanel({+ hostStyle: `display:flex;flex-direction:column;height:${heightPx}px;width:360px`,+ layers: manyLayers,+ wrap: (view) => <PanelBodySlot body={layersWidgetManifest.chrome?.body}>{view}</PanelBodySlot>,+ });+ const bodyViewport = () => host.querySelector<HTMLElement>('[data-scope="scroll-area"][data-part="viewport"]')!;+ const treeViewport = () => page.getByRole('tree').element().closest<HTMLElement>('[data-part="viewport"]')!;+ const editorPane = () => host.querySelector<HTMLElement>('[data-layer-pane-block="layer-editor-pane"]')!;++ it('fits the panel to the body, so the editor pane stays in view and the tree scrolls itself', async () => {+ await mountInPanelBody(700);+ const viewport = bodyViewport();+ const bounds = viewport.getBoundingClientRect();+ const panelRoot = editorPane().parentElement!;++ expect(panelRoot.getBoundingClientRect().height).toBeCloseTo(bounds.height, 0);+ // The Properties / Transform / Overview block sits wholly inside the body, its panel open.+ const pane = editorPane().getBoundingClientRect();+ expect(pane.top).toBeGreaterThanOrEqual(bounds.top);+ expect(pane.bottom).toBeLessThanOrEqual(bounds.bottom + 0.5);+ expect(editorPane().querySelector('[role="tabpanel"]')!.getBoundingClientRect().height).toBeGreaterThan(40);+ // The rows scroll inside the tree, and the body has nothing of its own to scroll.+ expect(treeViewport().scrollHeight).toBeGreaterThan(treeViewport().clientHeight);+ expect(viewport.scrollHeight).toBeLessThanOrEqual(viewport.clientHeight);+ });++ it("scrolls a dock shorter than the panel's minimums instead of crushing the tree", async () => {+ await mountInPanelBody(260);+ const viewport = bodyViewport();+ const treePanel = page.getByRole('tree').element().closest<HTMLElement>('[role="tabpanel"]')!;++ // The tree keeps its 13rem floor; the body scrolls to reach the panes below it.+ expect(treePanel.getBoundingClientRect().height).toBeGreaterThanOrEqual(208);+ expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight);+ viewport.scrollTop = viewport.scrollHeight;+ expect(editorPane().getBoundingClientRect().bottom).toBeLessThanOrEqual(+ viewport.getBoundingClientRect().bottom + 0.5+ );+ });++ it('never squeezes the open colour pane below its whole wheel, however short the dock', async () => {+ await mountInPanelBody(260);+ const colorPane = host.querySelector<HTMLElement>('[data-layer-pane-block="layer-color-pane"]')!;+ const colorPanel = colorPane.querySelector<HTMLElement>('[role="tabpanel"]')!.getBoundingClientRect();+ // The hue ring spans the wheel's full box.+ const wheel = colorPane.querySelector<HTMLElement>('[role="slider"]')!.getBoundingClientRect();++ expect(wheel.height).toBe(168);+ expect(wheel.top).toBeGreaterThanOrEqual(colorPanel.top);+ expect(wheel.bottom).toBeLessThanOrEqual(colorPanel.bottom);+ });++ it('folds the colour pane to its tabs while a drag is past the collapse point, before the button lifts', async () => {+ await mountInPanelBody(700);+ const colorPane = host.querySelector<HTMLElement>('[data-layer-pane-block="layer-color-pane"]')!;+ // The colour pane docks at the top, so its divider is the panel's first.+ const separator = host.querySelector<HTMLElement>('[role="separator"]')!;+ const pointer = (type: string, clientY: number, buttons = 1) =>+ new PointerEvent(type, { bubbles: true, buttons, clientY, pointerId: 1 });+ const frame = () =>+ new Promise((resolve) => {+ requestAnimationFrame(resolve);+ });++ const expandedHeight = colorPane.getBoundingClientRect().height;+ await act(() => separator.dispatchEvent(pointer('pointerdown', 300)));++ // Short of the collapse point the pane holds its floor, the wheel whole.+ await act(() => window.dispatchEvent(pointer('pointermove', 280)));+ await frame();+ expect(colorPane.getBoundingClientRect().height).toBeGreaterThanOrEqual(224);++ // Past it, the pane shows only its tab strip while the button is still down.+ await act(() => window.dispatchEvent(pointer('pointermove', 150)));+ await frame();+ expect(expandedHeight).toBeGreaterThanOrEqual(224);+ expect(colorPane.getBoundingClientRect().height).toBe(40);+ expect(colorPane.hasAttribute('data-pane-collapsed')).toBe(false);++ // Releasing commits the collapse through the divider (ResizeHandle's own tests); here it only ends the drag.+ await act(() => window.dispatchEvent(pointer('pointerup', 150, 0)));+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsxindex 067977f9c8..a59830cfe1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx@@ -1,6 +1,7 @@import type { WidgetViewProps } from '@workbench/widgetContracts';import { Flex, Icon, Stack, Text } from '@chakra-ui/react';+import { isEventFromOwnDom } from '@platform/react/isEventFromOwnDom';import { SegmentTabs, segmentTabsPanelId, segmentTabsTabId } from '@platform/ui/SegmentTabs';import { getDocumentIndex } from '@workbench/canvas-engine/api';import { useCanvasEngine } from '@workbench/canvas-operations/react';@@ -108,7 +109,12 @@ export const LayersWidgetView = ({ runtime }: WidgetViewProps) => {);const [addMenuAnchor, setAddMenuAnchor] = useState<LayerSurfaceAnchor | null>(null);const handleEmptyAreaContextMenu = useCallback((event: MouseEvent<HTMLElement>) => {- if (event.defaultPrevented || (event.target as HTMLElement).closest('[role="treeitem"]')) {+ // Layer menus and their dialogs are portalled; a right-click in them is theirs.+ if (+ event.defaultPrevented ||+ !isEventFromOwnDom(event) ||+ (event.target as HTMLElement).closest('[role="treeitem"]')+ ) {return;}event.preventDefault();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.browser.test.tsxindex bbf6a43fd0..cd2f7bb73d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/MaskModifierSettings.browser.test.tsx@@ -103,7 +103,7 @@ const startDrag = async () => {const frame = noiseSlider().element().closest<HTMLElement>('[data-scope="scrubber"]')!;const rect = frame.getBoundingClientRect();const startX = rect.left + rect.width / 2;- const xAt = (offset: number) => startX + offset * (rect.width - 20);+ const xAt = (offset: number) => startX + offset * (rect.width - 12);const pointer = (target: EventTarget, type: string, x: number) =>settle(() => target.dispatchEvent(new PointerEvent(type, { bubbles: true, button: 0, clientX: x, pointerId: 1 })));await pointer(frame, 'pointerdown', startX);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.browser.test.tsxindex c43bab91ca..6c4ece6a4b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ReferenceImageSettings.browser.test.tsx@@ -143,7 +143,7 @@ const startDrag = async () => {const frame = weightSlider().element().closest<HTMLElement>('[data-scope="scrubber"]')!;const rect = frame.getBoundingClientRect();const startX = rect.left + rect.width / 2;- const xAt = (offset: number) => startX + offset * (rect.width - 20);+ const xAt = (offset: number) => startX + offset * (rect.width - 12);const pointer = (target: EventTarget, type: string, x: number) =>settle(() => target.dispatchEvent(new PointerEvent(type, { bubbles: true, button: 0, clientX: x, pointerId: 1 })));await pointer(frame, 'pointerdown', startX);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsxindex 7f6c8d2879..56ae6c9b23 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx@@ -93,11 +93,47 @@ afterEach(async () => {resetArchitectureCapabilities();});+let stub: StructuralEngineStub;+const liveLayer = () => getDocumentLayer(stub.document(), 'rg-1') as CanvasRegionalGuidanceLayerContract;++const LiveSettings = () => {+ const layer = useSyncExternalStore(stub.subscribe, liveLayer);+ return <RegionalGuidanceSettings engine={stub.engine as never} layer={layer} />;+};++/** Renders the panel over the real reducer and history, so commits land and undo replays them. */+const renderLive = async (base: string, overrides: Partial<CanvasRegionalGuidanceLayerContract> = {}) => {+ stub = createStructuralEngineStub({+ layers: [layerContract('rg-1', 'regional_guidance', { positivePrompt: 'a shop front', ...overrides })],+ });+ selectedBase = base;+ applyThemeToRoot('classic');+ host = document.createElement('div');+ host.style.width = '260px';+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <LiveSettings />+ </ChakraProvider>+ </I18nextProvider>+ );+ });+};+const alerts = () => [...host!.querySelectorAll('[role="alert"]')].map((el) => el.textContent);const hasNegativeField = () =>host!.querySelector('[aria-label="widgets.layers.regionalGuidance.negativePrompt"]') !== null;const hasAutoNegativeSwitch = () =>Boolean(host!.textContent?.includes('widgets.layers.regionalGuidance.autoNegative'));+const negativeInput = () => page.getByRole('textbox', { name: 'widgets.layers.regionalGuidance.negativePrompt' });+const addNegativeButton = () => page.getByRole('button', { name: 'widgets.layers.regionalGuidance.addNegativePrompt' });+const removeNegativeButton = () =>+ page.getByRole('button', { name: 'widgets.layers.regionalGuidance.removeNegativePrompt' });+/** The negative prompt itself, or the button that adds it. */+const hasNegativeControls = () => hasNegativeField() || addNegativeButton().query() !== null;describe('RegionalGuidanceSettings per model base', () => {beforeEach(() => {@@ -115,11 +151,17 @@ describe('RegionalGuidanceSettings per model base', () => {expect(prompt.matches('[data-prompt-attention-target="true"]')).toBe(readsAttention);});- it('offers both prompt polarities on an SD base', async () => {+ it('offers both prompt polarities on an SD base, the negative behind its add button until it has one', async () => {await render('sd-1', createLayer());expect(alerts()).toEqual([]);- expect(hasNegativeField()).toBe(true);+ expect(hasNegativeField()).toBe(false);+ // Without an engine there is no document to add it to.+ await expect.element(addNegativeButton()).toBeDisabled();expect(hasAutoNegativeSwitch()).toBe(true);++ await render('sd-1', createLayer({ negativePrompt: 'blurry' }));+ await expect.element(negativeInput()).toHaveValue('blurry');+ expect(addNegativeButton().query()).toBeNull();});it.each(['krea-2', 'z-image', 'anima'])(@@ -127,7 +169,6 @@ describe('RegionalGuidanceSettings per model base', () => {async (base) => {const layer = createLayer({ autoNegative: true, negativePrompt: 'blurry' });await render(base, layer);- const negativeInput = () => page.getByRole('textbox', { name: 'widgets.layers.regionalGuidance.negativePrompt' });const autoNegative = () => page.getByRole('checkbox', { name: 'widgets.layers.regionalGuidance.autoNegative' });expect(alerts()).toEqual([]);@@ -135,7 +176,7 @@ describe('RegionalGuidanceSettings per model base', () => {await expect.element(autoNegative()).toBeChecked();await render('flux2', layer);- expect(hasNegativeField()).toBe(false);+ expect(hasNegativeControls()).toBe(false);expect(hasAutoNegativeSwitch()).toBe(false);await render(base, layer);@@ -170,6 +211,15 @@ describe('RegionalGuidanceSettings per model base', () => {});+ it('keeps the CFG Scale hint for a region without a negative prompt, describing its add button', async () => {+ const hint = 'Negative prompts and Auto-Negative take effect only when CFG Scale is above 1.';+ selectedCfgScale = 1;+ await render('krea-2', createLayer({ autoNegative: true }), english);++ await expect.element(page.getByRole('button', { name: 'Add negative prompt' })).toHaveAccessibleDescription(hint);+ await expect.element(page.getByRole('checkbox', { name: 'Auto-Negative' })).toHaveAccessibleDescription(hint);+ });+it('gives no CFG hint on an SD base, whose graph reads regional negatives at any CFG Scale', async () => {selectedCfgScale = 1;await render('sd-1', createLayer({ negativePrompt: 'blurry' }), english);@@ -180,20 +230,20 @@ describe('RegionalGuidanceSettings per model base', () => {it('hides the negative controls on a positive-only base even when the layer still holds a negative', async () => {await render('flux2', createLayer({ autoNegative: true, negativePrompt: 'blurry' }));expect(alerts()).toEqual([]);- expect(hasNegativeField()).toBe(false);+ expect(hasNegativeControls()).toBe(false);expect(hasAutoNegativeSwitch()).toBe(false);});it('warns that a base with no regional path skips the layer', async () => {await render('sd-3', createLayer());expect(alerts()).toEqual(['widgets.layers.regionalGuidance.unsupportedModel']);- expect(hasNegativeField()).toBe(true);+ expect(hasNegativeControls()).toBe(true);});it('offers everything while no model is selected', async () => {await render(null, createLayer());expect(alerts()).toEqual([]);- expect(hasNegativeField()).toBe(true);+ expect(hasNegativeControls()).toBe(true);});});@@ -204,7 +254,7 @@ describe('RegionalGuidanceSettings before the capability table arrives', () => {await render('sd-1', createLayer());expect(alerts()).toEqual([]);- expect(hasNegativeField()).toBe(true);+ expect(hasNegativeControls()).toBe(true);expect(hasAutoNegativeSwitch()).toBe(true);});@@ -227,47 +277,16 @@ describe('RegionalGuidanceSettings before the capability table arrives', () => {setArchitectureCapabilities(architectureCapabilitiesFixture);});- expect(hasNegativeField()).toBe(false);+ expect(hasNegativeControls()).toBe(false);expect(hasAutoNegativeSwitch()).toBe(false);});});describe('RegionalGuidanceSettings on a layout base', () => {- let stub: StructuralEngineStub;- const liveLayer = () => getDocumentLayer(stub.document(), 'rg-1') as CanvasRegionalGuidanceLayerContract;-- const LiveSettings = () => {- const layer = useSyncExternalStore(stub.subscribe, liveLayer);- return <RegionalGuidanceSettings engine={stub.engine as never} layer={layer} />;- };-- /** Renders the panel over the real reducer and history, so commits land and undo replays them. */- const renderLive = async (base: string, overrides: Partial<CanvasRegionalGuidanceLayerContract> = {}) => {- stub = createStructuralEngineStub({- layers: [layerContract('rg-1', 'regional_guidance', { positivePrompt: 'a shop front', ...overrides })],- });- selectedBase = base;- applyThemeToRoot('classic');- host = document.createElement('div');- host.style.width = '260px';- document.body.append(host);- root = createRoot(host);- await act(() => {- root?.render(- <I18nextProvider i18n={i18n}>- <ChakraProvider value={system}>- <LiveSettings />- </ChakraProvider>- </I18nextProvider>- );- });- };-const kindGroup = () => page.getByRole('radiogroup', { name: 'widgets.layers.regionalGuidance.layoutKind' });const pickKind = (kind: 'object' | 'character' | 'text') =>act(() => userEvent.click(page.getByText(`widgets.layers.regionalGuidance.layoutKinds.${kind}`, { exact: true })));const promptInput = () => page.getByRole('textbox', { name: 'widgets.layers.regionalGuidance.positivePrompt' });- const negativeInput = () => page.getByRole('textbox', { name: 'widgets.layers.regionalGuidance.negativePrompt' });const visibleTextInput = () => page.getByRole('textbox', { name: 'widgets.layers.regionalGuidance.visibleText' });/** What the always-present status region announces. */const announced = () => host!.querySelector('[role="status"]')?.textContent ?? null;@@ -284,7 +303,7 @@ describe('RegionalGuidanceSettings on a layout base', () => {it('offers the region type instead of the negative controls, and no type on a mask base', async () => {await render('moss-image', createLayer({ autoNegative: true, negativePrompt: 'blurry' }));await expect.element(kindGroup()).toBeInTheDocument();- expect(hasNegativeField()).toBe(false);+ expect(hasNegativeControls()).toBe(false);expect(hasAutoNegativeSwitch()).toBe(false);expect(alerts()).toEqual([]);await render('sd-1', createLayer());@@ -436,7 +455,7 @@ describe('RegionalGuidanceSettings on a layout base', () => {});it('leaves an undone negative prompt undone when drafts flush later', async () => {- await renderLive('sd-1');+ await renderLive('sd-1', { negativePrompt: '' });await act(() => negativeInput().fill('blurry'));await act(() => userEvent.tab());@@ -446,12 +465,12 @@ describe('RegionalGuidanceSettings on a layout base', () => {await act(() => flushWorkbenchDrafts());expect(stub.commits).toHaveLength(1);- expect(liveLayer().negativePrompt).toBeNull();+ expect(liveLayer().negativePrompt).toBe('');expect(stub.engine.history.canRedo()).toBe(true);});it('commits an unsaved negative prompt on a mask base when drafts are flushed', async () => {- await renderLive('sd-1');+ await renderLive('sd-1', { negativePrompt: '' });await act(() => negativeInput().fill('blurry'));await act(() => flushWorkbenchDrafts());@@ -460,3 +479,77 @@ describe('RegionalGuidanceSettings on a layout base', () => {expect(liveLayer().negativePrompt).toBe('blurry');});});++describe('RegionalGuidanceSettings negative prompt', () => {+ beforeEach(() => {+ setArchitectureCapabilities(architectureCapabilitiesFixture);+ });++ it('adds an empty negative prompt as one undo step, focuses it, and records what is typed', async () => {+ await renderLive('sd-1');+ expect(hasNegativeField()).toBe(false);++ await act(() => userEvent.click(addNegativeButton()));++ expect(liveLayer().negativePrompt).toBe('');+ expect(stub.history.entries().past).toEqual(['widgets.layers.regionalGuidance.addNegativePrompt']);+ await expect.element(negativeInput()).toHaveFocus();+ expect(addNegativeButton().query()).toBeNull();++ await act(() => userEvent.keyboard('blurry'));+ await act(() => userEvent.tab());+ expect(liveLayer().negativePrompt).toBe('blurry');++ // Clearing the text keeps the prompt, empty; only its remove control takes it out.+ await act(() => negativeInput().fill(''));+ await act(() => userEvent.tab());+ expect(liveLayer().negativePrompt).toBe('');+ await expect.element(negativeInput()).toBeInTheDocument();+ });++ it('removes the negative prompt from the layer, hands focus to the add button, and undoes back', async () => {+ await renderLive('sd-1', { negativePrompt: 'blurry' });+ await expect.element(negativeInput()).toHaveValue('blurry');++ await act(() => userEvent.click(removeNegativeButton()));++ expect(liveLayer().negativePrompt).toBeNull();+ expect(stub.history.entries().past).toEqual(['widgets.layers.regionalGuidance.removeNegativePrompt']);+ expect(hasNegativeField()).toBe(false);+ await expect.element(addNegativeButton()).toHaveFocus();++ await act(() => stub.engine.history.undo());+ await expect.element(negativeInput()).toHaveValue('blurry');+ expect(liveLayer().negativePrompt).toBe('blurry');+ });++ it('adds an empty negative prompt after one with unsaved text was undone away', async () => {+ await renderLive('sd-1');++ await act(() => userEvent.click(addNegativeButton()));+ await act(() => userEvent.keyboard('blurry'));+ // Undo from outside the field (the History pane) takes the prompt out before its text is saved.+ await act(() => stub.engine.history.undo());+ expect(liveLayer().negativePrompt).toBeNull();++ await act(() => userEvent.click(addNegativeButton()));+ await expect.element(negativeInput()).toHaveValue('');+ await act(() => userEvent.tab());+ expect(liveLayer().negativePrompt).toBe('');+ });++ it('keeps text typed right before removing it as its own undo step', async () => {+ await renderLive('sd-1', { negativePrompt: '' });++ await act(() => negativeInput().fill('blurry'));+ await act(() => userEvent.click(removeNegativeButton()));++ expect(liveLayer().negativePrompt).toBeNull();+ expect(stub.history.entries().past).toEqual([+ 'widgets.layers.regionalGuidance.negativePrompt',+ 'widgets.layers.regionalGuidance.removeNegativePrompt',+ ]);+ await act(() => stub.engine.history.undo());+ await expect.element(negativeInput()).toHaveValue('blurry');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex fb959c3082..2922fe74ff 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -19,7 +19,7 @@ import {Textarea,VisuallyHidden,} from '@chakra-ui/react';-import { PromptTextarea } from '@features/generation/components';+import { AddNegativePromptButton, PromptTextarea, RemoveNegativePromptButton } from '@features/generation/components';import {areRegionalNegativesActive,getEffectiveLayoutKind,@@ -45,7 +45,7 @@ import {useStructuralPreview,} from '@workbench/widgets/canvas/useStructuralCommit';import { PaletteIcon } from 'lucide-react';-import { useCallback, useId, useMemo, useState } from 'react';+import { useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useSelectedCfgScale, useSelectedModelBase } from './useSelectedModelBase';@@ -95,6 +95,9 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst [positiveDraft, setPositiveDraft] = useState<string | null>(null);const [negativeDraft, setNegativeDraft] = useState<string | null>(null);const positivePrompt = positiveDraft ?? layer.positivePrompt ?? '';+ // A region has a negative prompt once one is added, even while it is empty; null means none, and generation reads+ // an empty one as none too.+ const hasNegativePrompt = layer.negativePrompt !== null;const negativePrompt = negativeDraft ?? layer.negativePrompt ?? '';const attentionSyntax = supportsPromptAttentionSyntax(base) ? 'edit' : 'none';@@ -139,7 +142,9 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettreturn;}const positive = positiveDraft === null ? layer.positivePrompt : positiveDraft || null;- const negative = negativeDraft === null ? layer.negativePrompt : negativeDraft || null;+ // Clearing the text keeps the negative prompt; only its remove control takes it out. A draft left behind after+ // the prompt was removed elsewhere (undo) does not bring it back.+ const negative = negativeDraft === null || layer.negativePrompt === null ? layer.negativePrompt : negativeDraft;const patch: RegionalConfigPatch = {...(positive === layer.positivePrompt ? {} : { positivePrompt: positive }),...(negative === layer.negativePrompt ? {} : { negativePrompt: negative }),@@ -168,6 +173,62 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett[]);+ // Adding or removing the prompt swaps the field and its add button; focus follows to whichever one mounts. Only the+ // render that commit causes may take it: a later mount (an undo, a model switch back) must not steal focus, so the+ // request lapses after a frame. Another layer's settings remount (keyed by layer id) with no request.+ const pendingNegativeFocus = useRef<'add' | 'field' | null>(null);+ const requestNegativeFocus = useCallback((target: 'add' | 'field') => {+ pendingNegativeFocus.current = target;+ requestAnimationFrame(() => {+ if (pendingNegativeFocus.current === target) {+ pendingNegativeFocus.current = null;+ }+ });+ }, []);+ const focusWhenPending = useCallback(+ (target: 'add' | 'field') => (element: HTMLElement | null) => {+ if (element && pendingNegativeFocus.current === target) {+ pendingNegativeFocus.current = null;+ element.focus();+ }+ },+ []+ );+ const negativeFieldRef = useMemo(() => focusWhenPending('field'), [focusWhenPending]);+ const addNegativeRef = useMemo(() => focusWhenPending('add'), [focusWhenPending]);++ const handleAddNegative = useCallback(() => {+ requestNegativeFocus('field');+ const outcome = commitConfig(t('widgets.layers.regionalGuidance.addNegativePrompt'), { negativePrompt: '' });+ if (outcome.status === 'committed') {+ // Text left unsaved in a prompt that was undone away belongs to that prompt, not this new empty one.+ setNegativeDraft(null);+ } else {+ pendingNegativeFocus.current = null;+ }+ }, [commitConfig, requestNegativeFocus, t]);++ const handleRemoveNegative = useCallback(() => {+ requestNegativeFocus('add');+ const outcome = commitConfig(t('widgets.layers.regionalGuidance.removeNegativePrompt'), { negativePrompt: null });+ if (outcome.status === 'committed') {+ setNegativeDraft(null);+ } else {+ pendingNegativeFocus.current = null;+ }+ }, [commitConfig, requestNegativeFocus, t]);++ const negativeLabelEnd = useMemo(+ () => (+ <RemoveNegativePromptButton+ disabled={!engine}+ label={t('widgets.layers.regionalGuidance.removeNegativePrompt')}+ onClick={handleRemoveNegative}+ />+ ),+ [engine, handleRemoveNegative, t]+ );+const handleAutoNegative = useCallback((details: { checked: boolean }) => {commitConfig(t('widgets.layers.regionalGuidance.autoNegative'), { autoNegative: details.checked });@@ -380,11 +441,12 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett</Text>) : null}{isLayout ? <VisuallyHidden role="status">{layoutIssueMessage}</VisuallyHidden> : null}- {showNegativeControls && (+ {showNegativeControls && hasNegativePrompt ? (<FieldhelpText={negativesIgnoredAtCfg ? t('widgets.layers.regionalGuidance.negativesNeedCfg') : undefined}id={negativeFieldId}label={t('widgets.layers.regionalGuidance.negativePrompt')}+ labelEnd={negativeLabelEnd}><PromptTextareaaria-describedby={negativeHelpId}@@ -396,12 +458,31 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettresizeHandleAriaLabel={t('widgets.layers.regionalGuidance.negativePrompt')}showSyntaxHighlighting={showSyntaxHighlighting}size="lg"+ textareaRef={negativeFieldRef}value={negativePrompt}onBlur={commitPrompts}onChange={handleNegativeChange}/></Field>- )}+ ) : null}+ {showNegativeControls && !hasNegativePrompt ? (+ <Stack gap="1.5">+ <AddNegativePromptButton+ ref={addNegativeRef}+ aria-describedby={negativeHelpId}+ aria-label={t('widgets.layers.regionalGuidance.addNegativePrompt')}+ disabled={!engine}+ label={t('widgets.layers.regionalGuidance.negativePromptAdd')}+ onClick={handleAddNegative}+ />+ {/* The field's help line while there is no field, so Auto-Negative keeps its description. */}+ {negativesIgnoredAtCfg ? (+ <Text color="fg.muted" fontSize="xs" id={negativeHelpId}>+ {t('widgets.layers.regionalGuidance.negativesNeedCfg')}+ </Text>+ ) : null}+ </Stack>+ ) : null}{showNegativeControls && (<Switch.Root checked={layer.autoNegative} onCheckedChange={handleAutoNegative}><Switch.HiddenInput aria-describedby={negativeHelpId} />diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex f71025849c..e718f9a39c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -8,6 +8,7 @@ import type {import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';import { createControlLayer } from '@workbench/canvas-engine/api';import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { CircleDotIcon, CircleIcon } from 'lucide-react';import { describe, expect, it, vi } from 'vitest';import {@@ -228,9 +229,7 @@ describe('layer context action registry', () => {'widgets.layers.selectObject.modelHuge','widgets.layers.selectObject.modelSam2Large','widgets.layers.selectObject.prompt',- 'widgets.layers.selectObject.process','widgets.layers.selectObject.refine',- 'widgets.layers.selectObject.reset','widgets.layers.selectObject.saveAs','widgets.layers.selectObject.saveAs_control','widgets.layers.selectObject.saveAs_inpaint_mask',@@ -360,14 +359,20 @@ describe('getLayerContextActions', () => {expect(Boolean(action)).toBe(expected);});+ it.each(['raster', 'control', 'inpaint_mask', 'regional_guidance'] as const)(+ 'exposes transform for %s layers',+ (type) => {+ const action = getLayerContextActions(makeState(makeLayer(type))).find((item) => item.id === 'transform');+ expect(action).toBeDefined();+ }+ );+it.each([- ['raster', true],- ['control', true],- ['inpaint_mask', false],- ['regional_guidance', false],- ] as const)('exposes transform only for engine-supported %s layers', (type, expected) => {- const action = getLayerContextActions(makeState(makeLayer(type))).find((item) => item.id === 'transform');- expect(Boolean(action)).toBe(expected);+ ['an empty mask', makeLayer('inpaint_mask'), { hasSupportedContent: false }],+ ['a disabled mask', { ...makeLayer('inpaint_mask'), isEnabled: false }, {}],+ ] as const)('disables transform for %s, which has nothing to transform', (_, layer, state) => {+ const action = getLayerContextActions(makeState(layer, state)).find((item) => item.id === 'transform');+ expect(action?.isDisabled).toBe(true);});it.each([@@ -942,12 +947,44 @@ describe('getLayerContextActions', () => {});describe('toggle-visibility', () => {- it('hides and shows the layer itself, the one visibility that generation also follows', () => {- const shown = getLayerContextActions(makeState(rasterLayer));- expect(byId(shown, 'toggle-visibility').labelKey).toBe('widgets.layers.actions.hideLayer');- expect(getEnglishTranslation('widgets.layers.actions.hideLayer')).toBe('Hide layer');- const off = getLayerContextActions(makeState({ ...rasterLayer, isEnabled: false }));- expect(byId(off, 'toggle-visibility').labelKey).toBe('widgets.layers.actions.showLayer');+ const labelOf = (layer: CanvasLayerContract, overrides: Partial<LayerContextActionState> = {}) =>+ getEnglishTranslation(byId(getLayerContextActions(makeState(layer, overrides)), 'toggle-visibility').labelKey);++ it('hides and shows a raster layer, the one visibility that generation also follows', () => {+ expect(labelOf(rasterLayer)).toBe('Hide layer');+ expect(labelOf({ ...rasterLayer, isEnabled: false })).toBe('Show layer');+ });++ it.each(['control', 'inpaint_mask', 'regional_guidance'] as const)(+ 'names the flag for generation on a %s layer, whose canvas visibility is its own action',+ (type) => {+ const layer = makeLayer(type);+ expect(labelOf(layer)).toBe('Exclude from generation');+ expect(labelOf({ ...layer, isEnabled: false })).toBe('Use in generation');+ // The row dot's shapes: a plain ring for off, a dot for on; the dashed ring belongs to a group leaving it out.+ const iconOf = (target: CanvasLayerContract) =>+ byId(getLayerContextActions(makeState(target)), 'toggle-visibility').icon;+ expect(iconOf(layer)).toBe(CircleIcon);+ expect(iconOf({ ...layer, isEnabled: false })).toBe(CircleDotIcon);+ }+ );++ it('words a selection by the kinds it holds: overlays, raster layers, or both', () => {+ const mask = createInpaintMaskLayer('Mask', 'mask');+ const region = { ...createRegionalGuidanceLayer('Region', 0, 'region'), isEnabled: false };+ const overlays = { document: makeDocument([mask, region]), selectedIds: ['mask', 'region'] };+ expect(labelOf(mask, overlays)).toBe('Use selected in generation');+ expect(labelOf(mask, { ...overlays, document: makeDocument([mask, { ...region, isEnabled: true }]) })).toBe(+ 'Exclude selected from generation'+ );+ const mixed = { document: makeDocument([mask, rasterLayer]), selectedIds: ['mask', 'raster'] };+ // Both kinds: the flag hides the raster layer and leaves the overlay out, so it is turned off.+ expect(labelOf(mask, mixed)).toBe('Turn off selected');+ expect(+ labelOf(rasterLayer, { ...mixed, document: makeDocument([{ ...mask, isEnabled: false }, rasterLayer]) })+ ).toBe('Turn on selected');+ const rasters = { document: makeDocument([rasterLayer, paintLayer('second')]), selectedIds: ['raster', 'second'] };+ expect(labelOf(rasterLayer, rasters)).toBe('Hide selected');});});@@ -956,10 +993,25 @@ describe('toggle-hidden', () => {expect(idsFor(rasterLayer)).not.toContain('toggle-hidden');const control = getLayerContextActions(makeState(nonEmptyControlLayer));expect(byId(control, 'toggle-hidden').isDisabled).toBe(false);- expect(byId(control, 'toggle-hidden').labelKey).toBe('widgets.layers.actions.hideOnCanvas');- expect(getEnglishTranslation('widgets.layers.actions.hideOnCanvas')).toBe('Hide on canvas only');+ expect(getEnglishTranslation(byId(control, 'toggle-hidden').labelKey)).toBe('Hide on canvas');const hidden = getLayerContextActions(makeState({ ...nonEmptyControlLayer, isHidden: true }));- expect(byId(hidden, 'toggle-hidden').labelKey).toBe('widgets.layers.actions.showOnCanvas');+ expect(getEnglishTranslation(byId(hidden, 'toggle-hidden').labelKey)).toBe('Show on canvas');+ const mask = createInpaintMaskLayer('Mask', 'mask');+ const selection = (masks: CanvasLayerContract[]) =>+ getLayerContextActions(+ makeState(masks[0]!, {+ document: makeDocument([...masks, rasterLayer]),+ selectedIds: ['mask', 'other', 'raster'],+ })+ );+ const other = { ...createInpaintMaskLayer('Other', 'other'), isHidden: true };+ expect(getEnglishTranslation(byId(selection([mask, other]), 'toggle-hidden').labelKey)).toBe(+ 'Hide selected on canvas'+ );+ // The raster target has no canvas-only state, so it does not keep the selection from reading as hidden.+ expect(getEnglishTranslation(byId(selection([{ ...mask, isHidden: true }, other]), 'toggle-hidden').labelKey)).toBe(+ 'Show selected on canvas'+ );const gated = getLayerContextActions(makeState(nonEmptyControlLayer, { hiddenByAncestor: true }));expect(byId(gated, 'toggle-hidden').isDisabled).toBe(true);const runtime = makeRuntimeContext(nonEmptyControlLayer);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex 2f3258109f..aab1759b6f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -12,9 +12,11 @@ import type { LucideIcon } from 'lucide-react';import {getDocumentIndex,getSourceContentRect,+ isGroupNode,isEmptyPolygonShape,isHideableLayer,isNodeHidden,+ isOverlayStack,isPixelBackedLayer,lookupLayerBelow,} from '@workbench/canvas-engine/api';@@ -27,12 +29,12 @@ import {ArrowUpToLineIcon,BookmarkIcon,BookmarkMinusIcon,+ CircleDotIcon,CircleIcon,CircleOffIcon,CopyIcon,CropIcon,DropletIcon,- EyeClosedIcon,EyeIcon,FilmIcon,FingerprintPatternIcon,@@ -323,6 +325,94 @@ const targetNodes = (context: LayerContextActionState) => {};const allTargetsEnabled = (context: LayerContextActionState): boolean =>targetNodes(context).every((node) => node.isEnabled);+interface EnabledToggleLabel {+ readonly defaultLabel: string;+ readonly icon: LucideIcon;+ readonly key: string;+}+interface EnabledToggleLabels {+ readonly off: EnabledToggleLabel;+ readonly on: EnabledToggleLabel;+}+const toggleLabel = (key: string, defaultLabel: string, icon: LucideIcon): EnabledToggleLabel => ({+ defaultLabel,+ icon,+ key: `widgets.layers.actions.${key}`,+});+// Overlays name the enabled flag for what it decides there, taking part in generation, since their canvas visibility+// is its own action; raster layers show and hide; a selection holding both is turned off or on, which is true of each.+// The overlay icons are the row dot's shapes: a plain ring for off, a dot for on (the dashed ring means a group above+// leaves the layer out, which no action sets).+const OVERLAY_LAYER: EnabledToggleLabels = {+ off: toggleLabel('excludeFromGeneration', 'Exclude from generation', CircleIcon),+ on: toggleLabel('useInGeneration', 'Use in generation', CircleDotIcon),+};+const OVERLAY_GROUP: EnabledToggleLabels = {+ off: toggleLabel('excludeGroupFromGeneration', 'Exclude group from generation', CircleIcon),+ on: toggleLabel('useGroupInGeneration', 'Use group in generation', CircleDotIcon),+};+const OVERLAY_SELECTION: EnabledToggleLabels = {+ off: toggleLabel('excludeSelectedFromGeneration', 'Exclude selected from generation', CircleIcon),+ on: toggleLabel('useSelectedInGeneration', 'Use selected in generation', CircleDotIcon),+};+const RASTER_LAYER: EnabledToggleLabels = {+ off: toggleLabel('hideLayer', 'Hide layer', EyeOffIcon),+ on: toggleLabel('showLayer', 'Show layer', EyeIcon),+};+const RASTER_GROUP: EnabledToggleLabels = {+ off: toggleLabel('hideGroup', 'Hide group', EyeOffIcon),+ on: toggleLabel('showGroup', 'Show group', EyeIcon),+};+const RASTER_SELECTION: EnabledToggleLabels = {+ off: toggleLabel('hideSelected', 'Hide selected', EyeOffIcon),+ on: toggleLabel('showSelected', 'Show selected', EyeIcon),+};+const MIXED_SELECTION: EnabledToggleLabels = {+ off: toggleLabel('turnOffSelected', 'Turn off selected', EyeOffIcon),+ on: toggleLabel('turnOnSelected', 'Turn on selected', EyeIcon),+};++/**+ * How turning the enabled flag of `targets` off (`turnOff`) or on is named, wherever it is offered: the row's dot or+ * eye, the layer and group menus, and the undo step each records.+ */+export const enabledToggleLabel = (+ document: Pick<CanvasDocumentContractV3, 'stacks'>,+ targets: readonly string[],+ turnOff: boolean+): EnabledToggleLabel => {+ const index = getDocumentIndex(document);+ const entries = targets.flatMap((id) => index.byId.get(id) ?? []);+ const overlays = entries.filter((entry) => isOverlayStack(entry.stack)).length;+ const labels =+ entries.length > 1+ ? overlays === entries.length+ ? OVERLAY_SELECTION+ : overlays === 0+ ? RASTER_SELECTION+ : MIXED_SELECTION+ : overlays === 1+ ? isGroupNode(entries[0]!.node)+ ? OVERLAY_GROUP+ : OVERLAY_LAYER+ : entries[0] && isGroupNode(entries[0].node)+ ? RASTER_GROUP+ : RASTER_LAYER;+ return turnOff ? labels.off : labels.on;+};+const enabledActionLabel = (context: LayerContextActionState): EnabledToggleLabel =>+ enabledToggleLabel(context.document, actionTargets(context), allTargetsEnabled(context));+/** The overlay targets, which are the ones Hide on canvas changes, are all hidden already: the item shows them. */+const allOverlayTargetsHidden = (context: LayerContextActionState): boolean => {+ if (!isMultiTarget(context)) {+ return isNodeHidden(context.layer);+ }+ const index = getDocumentIndex(context.document);+ return actionTargets(context).every((id) => {+ const entry = index.byId.get(id);+ return !entry || !isOverlayStack(entry.stack) || isNodeHidden(entry.node);+ });+};const allTargetsLocked = (context: LayerContextActionState): boolean =>targetNodes(context).every((node) => node.isLocked);const allTargetsInpaintMasks = (context: LayerContextActionState): boolean =>@@ -528,7 +618,7 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinilabelKey: 'widgets.layers.actions.transform',order: 10,section: 'primary',- supportedLayerTypes: ['raster', 'control'],+ supportedLayerTypes: ['raster', 'control', 'inpaint_mask', 'regional_guidance'],},{defaultLabel: 'Rename',@@ -962,26 +1052,13 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinisection: 'output',supportedLayerTypes: ALL_LAYER_TYPES,},- // One visibility model: hiding a layer takes it off the canvas and out of generation alike.+ // Raster layers have one axis: hiding takes a layer off the canvas and out of generation alike. Overlays name the+ // same flag for generation (see enabledToggleLabel).{defaultLabel: 'Show or hide layer',- getDefaultLabel: (context) =>- isMultiTarget(context)- ? allTargetsEnabled(context)- ? 'Hide selected'- : 'Show selected'- : context.layer.isEnabled- ? 'Hide layer'- : 'Show layer',- getIcon: (context) => (allTargetsEnabled(context) ? EyeOffIcon : EyeIcon),- getLabelKey: (context) =>- isMultiTarget(context)- ? allTargetsEnabled(context)- ? 'widgets.layers.actions.hideSelected'- : 'widgets.layers.actions.showSelected'- : context.layer.isEnabled- ? 'widgets.layers.actions.hideLayer'- : 'widgets.layers.actions.showLayer',+ getDefaultLabel: (context) => enabledActionLabel(context).defaultLabel,+ getIcon: (context) => enabledActionLabel(context).icon,+ getLabelKey: (context) => enabledActionLabel(context).key,handler: ({ effects }) => effects.toggleVisibility(),icon: EyeOffIcon,id: 'toggle-visibility',@@ -994,13 +1071,26 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini},// Overlays only: off the canvas to see the image under them, still used by generation.{- defaultLabel: 'Hide on canvas only',- getDefaultLabel: (context) => (isNodeHidden(context.layer) ? 'Show on canvas' : 'Hide on canvas only'),- getIcon: (context) => (isNodeHidden(context.layer) ? EyeIcon : EyeClosedIcon),+ defaultLabel: 'Hide on canvas',+ getDefaultLabel: (context) =>+ isMultiTarget(context)+ ? allOverlayTargetsHidden(context)+ ? 'Show selected on canvas'+ : 'Hide selected on canvas'+ : allOverlayTargetsHidden(context)+ ? 'Show on canvas'+ : 'Hide on canvas',+ getIcon: (context) => (allOverlayTargetsHidden(context) ? EyeIcon : EyeOffIcon),getLabelKey: (context) =>- isNodeHidden(context.layer) ? 'widgets.layers.actions.showOnCanvas' : 'widgets.layers.actions.hideOnCanvas',+ isMultiTarget(context)+ ? allOverlayTargetsHidden(context)+ ? 'widgets.layers.actions.showSelectedOnCanvas'+ : 'widgets.layers.actions.hideSelectedOnCanvas'+ : allOverlayTargetsHidden(context)+ ? 'widgets.layers.actions.showOnCanvas'+ : 'widgets.layers.actions.hideOnCanvas',handler: ({ effects }) => effects.toggleHidden(),- icon: EyeClosedIcon,+ icon: EyeOffIcon,id: 'toggle-hidden',isEnabled: (context) => isOperationFree(context) && !context.hiddenByAncestor,isVisible: (context) => isHideableLayer(context.layer),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex 19d9ffb26f..4b84cdf525 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -126,12 +126,12 @@ describe('getLayerContextMenuLayout', () => {expect(summarize(inpaint)[1]).toEqual({id: 'primary',- items: ['rename', 'fit-to-bbox', 'add-noise', 'add-denoise-limit', 'extract-masked-area'],+ items: ['transform', 'rename', 'fit-to-bbox', 'add-noise', 'add-denoise-limit', 'extract-masked-area'],presentation: 'list',});expect(summarize(regional)[1]).toEqual({id: 'primary',- items: ['rename', 'fit-to-bbox', 'regional-auto-negative', 'add-reference-image'],+ items: ['transform', 'rename', 'fit-to-bbox', 'regional-auto-negative', 'add-reference-image'],presentation: 'list',});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.tsindex 6b81b16af7..1ca5d6ff86 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerRowCommands.ts@@ -55,11 +55,4 @@ export interface LayerRowCommands {keyDown(id: string, event: KeyboardEvent<HTMLElement>): void;}-export const anchorFromRect = (rect: DOMRect): LayerSurfaceAnchor => ({- height: rect.height,- width: rect.width,- x: rect.left,- y: rect.top,-});-export const anchorFromPoint = (x: number, y: number): LayerSurfaceAnchor => ({ height: 1, width: 1, x, y });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/manifest.tsindex e7f58d7967..dedfbd547c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/manifest.ts@@ -8,7 +8,7 @@ export const layersWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['right'],// The rail context menu still offers close/move; the panel body is the chrome.- chrome: { header: 'hidden' },+ chrome: { body: 'fill', header: 'hidden' },failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },icon: LayersIcon,id: 'layers',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsxindex a7b8e3a78c..9b23480015 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx@@ -6,7 +6,7 @@ import type {PreparedDocumentEdit,} from '@workbench/canvas-engine/api';import type * as CanvasOperationsApi from '@workbench/canvas-operations/api';-import type { CanvasOperationState } from '@workbench/canvas-operations/api';+import type { CanvasOperationState, SamSessionSnapshot } from '@workbench/canvas-operations/api';import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';import type { FilterOperationSessionState } from '@workbench/canvas-operations/filterOperationSession';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';@@ -180,6 +180,24 @@ const filterSession = (): FilterOperationSessionState => ({status: 'ready',});+const samSession = (patch: Partial<SamSessionSnapshot> = {}): SamSessionSnapshot => ({+ applyPolygonRefinement: false,+ autoProcess: true,+ error: null,+ hasPreview: false,+ input: { bbox: null, excludePoints: [], includePoints: [], type: 'visual' },+ invert: false,+ isolatedPreview: true,+ layerName: 'Portrait',+ layerType: 'raster',+ model: 'segment-anything-2-large',+ pointLabel: 'include',+ retrying: false,+ sourceRect: { height: 768, width: 1024, x: 0, y: 0 },+ status: 'ready',+ ...patch,+});+const createFakeOperations = () => {const listeners = new Set<() => void>();const subscribe = (listener: () => void) => {@@ -187,16 +205,38 @@ const createFakeOperations = () => {return () => listeners.delete(listener);};let filter: FilterOperationSessionState | null = null;+ let sam: SamSessionSnapshot | null = null;let state: CanvasOperationState = { status: 'idle' };return {+ applySelectObjectSession: vi.fn(),cancelFilterOperation: vi.fn(),+ cancelSelectObjectSession: vi.fn(),commitFilterOperation: vi.fn(),getFilterSessionState: () => filter,getOperationState: () => state,- getSamSessionState: () => null,+ getSamSessionState: () => sam,processFilterOperation: vi.fn(),+ processSelectObjectSession: vi.fn(() => Promise.resolve('completed' as const)),resetFilterOperation: vi.fn(),+ resetSelectObjectSession: vi.fn(() => 'updated' as const),+ saveSelectObjectSession: vi.fn(),setFilterOperationAutoProcess: vi.fn(),+ /** Starts Select Object on a fake session the test then moves through its states. */+ startSam: (patch: Partial<SamSessionSnapshot> = {}) => {+ sam = samSession(patch);+ state = {+ error: null,+ identity: { kind: 'select-object', layerId: 'layer-1', projectId: 'p' },+ phase: 'ready',+ status: 'active',+ };+ listeners.forEach((listener) => listener());+ },+ setSam: (patch: Partial<SamSessionSnapshot>) => {+ sam = { ...sam!, ...patch };+ listeners.forEach((listener) => listener());+ },+ updateSelectObjectSession: vi.fn(() => 'updated' as const),start: (running: boolean) => {filter = running ? filterSession() : null;state = running@@ -531,7 +571,7 @@ describe('Properties pane', () => {// The log track spends its middle on the sizes text is set at.const frame = slider.element().closest<HTMLElement>('[data-scope="scrubber"]')!.getBoundingClientRect();const thumb = slider.element().parentElement!.querySelector('[data-part="thumb"]')!.getBoundingClientRect();- const thumbFraction = (thumb.left + thumb.width / 2 - frame.left - 10) / (frame.width - 20);+ const thumbFraction = (thumb.left + thumb.width / 2 - frame.left - 6) / (frame.width - 12);expect(thumbFraction).toBeGreaterThan(0.4);expect(thumbFraction).toBeLessThan(0.6);await act(() => (slider.element() as HTMLElement).focus());@@ -596,7 +636,7 @@ describe('Properties pane', () => {await expect.element(page.getByRole('button', { exact: true, name: `Gradient stop at ${moved}%` })).toBeVisible();});- it('keeps the Position row identity across move, frame and transform, with the transform footer live', async () => {+ it('keeps the Position row identity across move, frame and transform, with the transform actions live', async () => {await mount(PropertiesPane, 'layer');await act(() => engine!.tools.setTool('move'));await settle();@@ -609,7 +649,7 @@ describe('Properties pane', () => {await act(() => engine!.tools.setTool('transform'));await settle();expect(page.getByRole('spinbutton', { exact: true, name: 'X' }).element()).toBe(xField);- // No session and no float: Apply/Cancel are pinned but disabled.+ // No session and no float: Apply/Cancel close the Tool section, disabled.await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toBeDisabled();await expect.element(page.getByRole('button', { exact: true, name: 'Cancel' })).toBeDisabled();});@@ -692,7 +732,15 @@ describe('Properties pane', () => {await mount(PropertiesPane);await act(() => engine!.tools.setTool('brush'));await settle();- await act(() => page.getByRole('slider', { exact: true, name: 'Brush size' }).element().focus());+ const slider = page.getByRole('slider', { exact: true, name: 'Brush size' }).element();+ await act(() => slider.focus());+ // Scrolled down to the tool: the operation's Cancel, inline in its section above, must come into view.+ const viewport = [...host!.querySelectorAll<HTMLElement>('*')].find(+ (element) => element.scrollHeight > element.clientHeight && getComputedStyle(element).overflowY !== 'visible'+ );+ if (viewport) {+ viewport.scrollTop = viewport.scrollHeight;+ }await act(() => operations!.start(true));await settle();const operationSection = host!.querySelector('[role="group"][aria-label="Operation"]')!;@@ -702,6 +750,10 @@ describe('Properties pane', () => {await expect.element(cancel).toBeEnabled();await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toBeDisabled();expect(document.activeElement).toBe(cancel.element());+ const hostRect = host!.getBoundingClientRect();+ const cancelRect = cancel.element().getBoundingClientRect();+ expect(cancelRect.top).toBeGreaterThanOrEqual(hostRect.top);+ expect(cancelRect.bottom).toBeLessThanOrEqual(hostRect.bottom);expect(host!.querySelector('[role="group"][inert]')?.getAttribute('aria-label')).toBe('Tool');await act(() => operations!.start(false));await settle();@@ -709,6 +761,196 @@ describe('Properties pane', () => {});});+describe('Select Object properties', () => {+ beforeEach(() => resetPropertyGroupCollapse());++ const operationSection = () => host!.querySelector<HTMLElement>('[role="group"][aria-label="Operation"]')!;+ const startSam = async (patch: Partial<SamSessionSnapshot> = {}, width?: number) => {+ await mount(PropertiesPane, 'none', width ? { width } : undefined);+ await act(() => operations!.startSam(patch));+ await settle();+ };++ it('lays points, box and settings on pane rows and switches input type by intent', async () => {+ await startSam();++ await expect.element(page.getByRole('radiogroup', { name: 'Select by' })).toBeVisible();+ await expect.element(page.getByRole('radio', { name: 'Include 0' })).toBeChecked();+ await expect.element(page.getByText('Drag on the canvas')).toBeVisible();+ expect(page.getByRole('radiogroup', { name: 'Points' }).element().getAttribute('aria-describedby')).toBeTruthy();+ await userEvent.click(page.getByText('Settings'));+ await expect.element(page.getByRole('combobox', { name: 'Model' })).toBeVisible();+ for (const name of ['Refine edges', 'Auto-update preview', 'Show only the object']) {+ await expect.element(page.getByRole('checkbox', { name })).toBeVisible();+ }++ await userEvent.click(page.getByText('Prompt', { exact: true }));+ expect(operations!.updateSelectObjectSession).toHaveBeenCalledExactlyOnceWith({ inputType: 'prompt' });+ });++ it('labels new points from the Points row', async () => {+ await startSam();++ await userEvent.click(page.getByText('Exclude 0'));++ expect(operations!.updateSelectObjectSession).toHaveBeenCalledExactlyOnceWith({ pointLabel: 'exclude' });+ });++ it('clears only the box from its row', async () => {+ const input = {+ bbox: { height: 8, width: 12, x: 1, y: 2 },+ excludePoints: [{ x: 3, y: 4 }],+ includePoints: [{ x: 1, y: 2 }],+ type: 'visual' as const,+ };+ await startSam({ input });++ await expect.element(page.getByText('Set', { exact: true })).toBeVisible();+ const clear = page.getByRole('button', { name: 'Clear box' });+ await userEvent.click(clear);++ expect(operations!.updateSelectObjectSession).toHaveBeenCalledExactlyOnceWith({ input: { ...input, bbox: null } });++ // Without a box the same button stays in the row, disabled rather than gone.+ const clearElement = clear.element();+ const clearRect = clearElement.getBoundingClientRect();+ await act(() => operations!.setSam({ input: { ...input, bbox: null } }));+ expect(clear.element()).toBe(clearElement);+ expect(clearElement.getBoundingClientRect()).toEqual(clearRect);+ await expect.element(clear).toBeDisabled();+ });++ it('finds the prompted object on Enter whatever auto-update says, and offers Find object while manual', async () => {+ await startSam({ input: { prompt: 'cat', type: 'prompt' } });+ const prompt = page.getByRole('textbox', { name: 'Prompt' });+ expect(page.getByRole('button', { name: 'Find object' }).query()).toBeNull();++ await userEvent.click(prompt);+ await userEvent.keyboard('{Enter}');+ expect(operations!.processSelectObjectSession).toHaveBeenCalledOnce();++ await act(() => operations!.setSam({ autoProcess: false }));+ await userEvent.click(page.getByRole('button', { name: 'Find object' }));+ expect(operations!.processSelectObjectSession).toHaveBeenCalledTimes(2);+ });++ it('offers Find object to retry a failed run with auto-update on, until that retry has finished', async () => {+ const input = { bbox: null, excludePoints: [], includePoints: [{ x: 4, y: 5 }], type: 'visual' as const };+ await startSam({ input });+ const findObject = page.getByRole('button', { name: 'Find object' });+ expect(findObject.query()).toBeNull();++ await act(() => operations!.setSam({ error: { code: 'not-ready' }, status: 'error' }));+ await expect.element(findObject).toBeEnabled();+ await userEvent.click(findObject);+ expect(operations!.processSelectObjectSession).toHaveBeenCalledOnce();++ // The retry clears the error as it starts; the button stays, busy, while the session says it retries.+ await act(() => operations!.setSam({ error: null, retrying: true, status: 'processing-sam' }));+ await expect.element(findObject).toBeDisabled();+ await act(() => operations!.setSam({ hasPreview: true, retrying: false, status: 'ready' }));+ expect(findObject.query()).toBeNull();+ });++ it('keeps Find object for a retry started by Enter in the prompt', async () => {+ await startSam({+ error: { code: 'queue', detail: 'AttributeError' },+ input: { prompt: 'cat', type: 'prompt' },+ status: 'error',+ });+ const findObject = page.getByRole('button', { name: 'Find object' });+ await expect.element(findObject).toBeEnabled();++ await userEvent.click(page.getByRole('textbox', { name: 'Prompt' }));+ await userEvent.keyboard('{Enter}');+ expect(operations!.processSelectObjectSession).toHaveBeenCalledOnce();+ await act(() => operations!.setSam({ error: null, retrying: true, status: 'uploading' }));++ await expect.element(findObject).toBeDisabled();+ });++ it('leaves a failed apply to Apply: no Find object with auto-update on', async () => {+ await startSam({ error: { code: 'commit-failed', detail: 'commit failed' }, hasPreview: true, status: 'error' });++ await expect+ .element(page.getByRole('alert'))+ .toHaveTextContent('Select Object could not apply or save the result.');+ expect(page.getByRole('button', { name: 'Find object' }).query()).toBeNull();+ await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toBeEnabled();+ });++ it('leaves Enter to an IME that is composing, and does nothing on an empty prompt', async () => {+ await startSam({ input: { prompt: 'cat', type: 'prompt' } });+ const prompt = page.getByRole('textbox', { name: 'Prompt' }).element();+ const pressEnter = (init: KeyboardEventInit) =>+ act(() => {+ prompt.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: 'Enter', ...init }));+ });++ await pressEnter({ isComposing: true });+ // Safari confirms a candidate after compositionend; keyCode 229 is the only sign.+ await pressEnter({ keyCode: 229 } as KeyboardEventInit);+ expect(operations!.processSelectObjectSession).not.toHaveBeenCalled();++ await act(() => operations!.setSam({ input: { prompt: ' ', type: 'prompt' } }));+ await pressEnter({});+ expect(operations!.processSelectObjectSession).not.toHaveBeenCalled();+ });++ it('keeps the Find object label while it runs and reports the phase beside the section title', async () => {+ await startSam({ autoProcess: false, input: { prompt: 'cat', type: 'prompt' } });+ const status = operationSection().querySelector('[role="status"]')!;+ expect(status.textContent).toBe('');+ const promptTop = page.getByRole('textbox', { name: 'Prompt' }).element().getBoundingClientRect().top;++ await act(() => operations!.setSam({ status: 'processing-sam' }));++ expect(operationSection().querySelector('[role="status"]')).toBe(status);+ expect(status.textContent).toBe('Finding object…');+ await expect.element(page.getByRole('button', { name: 'Find object' })).toBeDisabled();+ expect(page.getByRole('textbox', { name: 'Prompt' }).element().getBoundingClientRect().top).toBe(promptTop);+ });++ it('puts an error after the groups and actions with its technical detail, leaving both in place', async () => {+ await startSam({ input: { prompt: 'cat', type: 'prompt' } });+ const promptTop = page.getByRole('textbox', { name: 'Prompt' }).element().getBoundingClientRect().top;+ const cancel = page.getByRole('button', { exact: true, name: 'Cancel' }).element();+ const cancelTop = cancel.getBoundingClientRect().top;++ await act(() => operations!.setSam({ error: { code: 'queue', detail: 'AttributeError' }, status: 'error' }));++ const alert = page.getByRole('alert');+ await expect.element(alert).toHaveTextContent('Select Object processing failed on the backend.');+ const groups = operationSection().querySelectorAll('[role="group"]');+ const lastGroup = groups[groups.length - 1]!;+ expect(lastGroup.compareDocumentPosition(alert.element()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(cancel.compareDocumentPosition(alert.element()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(page.getByRole('textbox', { name: 'Prompt' }).element().getBoundingClientRect().top).toBe(promptTop);+ expect(cancel.getBoundingClientRect().top).toBe(cancelTop);+ await userEvent.hover(page.getByRole('button', { name: 'Technical details' }));+ await expect.element(page.getByText('AttributeError')).toBeVisible();+ expect(operations!.cancelSelectObjectSession).not.toHaveBeenCalled();+ });++ it('names the source layer with the section subtitle', async () => {+ await startSam();+ expect(operationSection().textContent).toContain('Select ObjectPortrait · Raster layer · 1024 × 768');+ });++ it('fits the actions row in a 280 px pane with every verb showing', async () => {+ await startSam({ autoProcess: false, hasPreview: true, status: 'processing-sam' }, 280);+ const actions = host!.querySelector<HTMLElement>('[data-pane-action="cancel"]')!.parentElement!;+ const hostRect = host!.getBoundingClientRect();+ for (const name of ['Reset', 'Cancel', 'Find object', 'Apply', 'Save as']) {+ const rect = page.getByRole('button', { exact: true, name }).element().getBoundingClientRect();+ expect(rect.width, name).toBeGreaterThan(0);+ expect(rect.right, name).toBeLessThanOrEqual(hostRect.right);+ }+ expect(actions.scrollWidth).toBeLessThanOrEqual(actions.clientWidth);+ expect(host!.scrollWidth).toBeLessThanOrEqual(280);+ });+});+describe('Control layer properties', () => {it('fits a 320 px pane without horizontal overflow or clipped text', async () => {await mount(PropertiesPane, 'control', { width: 320 });@@ -1355,6 +1597,55 @@ describe('Overview pane', () => {.toBeCloseTo(offset.y, 0);});+ it('paints the viewport outline as dark, light and dark bands just inside its box', async () => {+ const outpaint = layerContract('outpaint', 'raster', {+ source: { bitmap: { height: 512, imageName: 'outpaint', width: 1024 }, type: 'paint' },+ transform: { ...IDENTITY, x: -1024 },+ });+ await mount(OverviewHarness, 'none', { extraNodes: [outpaint] });+ const pan = page.getByRole('button', { exact: true, name: 'Pan the canvas view' });+ await expect.element(pan).toBeVisible();+ const canvas = pan.element().querySelector('canvas')!;+ engine!.surface.resize(400, 300, 1);+ await act(async () => {+ await userEvent.click(canvas);+ });+ const outline = pan.element().querySelector('div')!;+ // The throttled glide can move any edge between measuring it and capturing the pixels.+ await vi.waitFor(async () => {+ const button = pan.element().getBoundingClientRect();+ const box = outline.getBoundingClientRect();+ const png = await page.screenshot({ element: pan.element(), save: false });+ const bitmap = await createImageBitmap(await (await fetch(`data:image/png;base64,${png}`)).blob());+ const scale = bitmap.width / button.width;+ const context = new OffscreenCanvas(bitmap.width, bitmap.height).getContext('2d')!;+ context.drawImage(bitmap, 0, 0);+ bitmap.close();+ // Scan the outline's left edge at its vertical middle, from a pixel outside the box to a pixel past the bands.+ const row = Math.round((box.top + box.height / 2 - button.top) * scale);+ const edge = (box.left - button.left) * scale;+ const start = Math.floor(edge - scale);+ const pixels = context.getImageData(start, row, Math.ceil(5 * scale) + 1, 1).data;+ // Runs of near-black and near-white pixels, in scan order; mid tones (the checkerboard) start no run.+ const runs: { start: number; tone: 'dark' | 'light' }[] = [];+ for (let i = 0; i < pixels.length / 4; i++) {+ const luma = 0.2126 * pixels[i * 4]! + 0.7152 * pixels[i * 4 + 1]! + 0.0722 * pixels[i * 4 + 2]!;+ const tone = luma < 48 ? 'dark' : luma > 208 ? 'light' : null;+ if (tone && tone !== runs.at(-1)?.tone) {+ runs.push({ start: start + i, tone });+ }+ }+ const lightBand = runs.findIndex(+ (run, i) => run.tone === 'light' && runs[i - 1]?.tone === 'dark' && runs[i + 1]?.tone === 'dark'+ );+ expect(lightBand).toBeGreaterThan(0);+ // The light band sits one dark band inside the box edge: the outline stays within the viewport's rect.+ const lightStart = runs[lightBand]!.start;+ expect(lightStart).toBeGreaterThanOrEqual(edge);+ expect(lightStart).toBeLessThanOrEqual(edge + 2 * scale);+ });+ });+it('zooms the view around the document point under the wheel', async () => {const outpaint = layerContract('outpaint', 'raster', {source: { bitmap: { height: 512, imageName: 'outpaint', width: 1024 }, type: 'paint' },diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsxindex b9b5f66a4e..b328edbce7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx@@ -33,6 +33,8 @@ import { TransformPane } from './TransformPane';/** Parity with the shell panels: releasing at the floor stops there; collapse asks for a real push past it. */const COLLAPSE_OVERSHOOT_PX = 80;+// While a drag is past the collapse point the block previews its strip, so its expanded floor must let go.+const ARMED_BLOCK_CSS = { '&[data-collapse-armed]': { minHeight: `${SEGMENT_TABS_HEIGHT_PX}px` } };interface PaneBlockLabels {collapse: string;@@ -162,10 +164,12 @@ const LayerPaneBlock = ({ref={blockRef}borderColor="border.subtle"data-layer-pane-block={blockId}+ css={ARMED_BLOCK_CSS}data-pane-collapsed={isCollapsed ? '' : undefined}direction="column"flex={isCollapsed ? '0 0 auto' : `0 1 ${sizePx}px`}- minH={`${SEGMENT_TABS_HEIGHT_PX}px`}+ // Expanded, a block never squeezes below its minimum: a short panel scrolls instead of hiding its content.+ minH={`${isCollapsed ? SEGMENT_TABS_HEIGHT_PX : minSizePx}px`}overflow="hidden"{...(isCollapsed ? (edge === 'top' ? { borderBottomWidth: '1px' } : { borderTopWidth: '1px' }) : {})}>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OperationSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OperationSection.tsxnew file mode 100644index 0000000000..acfdb1be35--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OperationSection.tsx@@ -0,0 +1,86 @@+import type {+ CanvasToolOptionsEngine,+ OperationPropertyForm,+} from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';+/* oxlint-disable react-perf/jsx-no-jsx-as-prop */++import { Box, Flex, Icon, Spinner, Text } from '@chakra-ui/react';+import { IconButton } from '@platform/ui/Button';+import { Tooltip } from '@platform/ui/Tooltip';+import { PropertyGroup } from '@workbench/widgets/canvas/tool-presentation/PropertyPrimitives';+import { InfoIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { PropertiesSection } from './PropertiesSection';++const OPERATION_TITLE_KEYS = {+ filter: 'widgets.layers.rasterFilter.title',+ 'select-object': 'widgets.layers.selectObject.title',+} as const;++/**+ * The running operation's section: its groups and actions, the busy phase beside the title, and any error last, where it+ * can grow without moving a control. One component per form, so each calls one status hook for its lifetime.+ */+export const createOperationSection = (form: OperationPropertyForm) => {+ const useStatus = form.useStatus;+ const Actions = form.actions;+ const OperationSection = ({ engine }: { engine: CanvasToolOptionsEngine }) => {+ const { t } = useTranslation();+ const status = useStatus(engine);+ const error = status?.error ?? null;+ const detail = error?.detail?.trim();+ const busyText = error ? null : (status?.busyText ?? null);+ return (+ <PropertiesSection+ subtitle={t(OPERATION_TITLE_KEYS[form.kind])}+ subtitleDetail={status?.source}+ title={t('widgets.properties.sections.operation')}+ trailing={+ // Mounted for as long as the operation runs, so the phase it reports is announced.+ <Text aria-live="polite" color="fg.muted" flex="1 1 0" minW="0" role="status" textAlign="end" truncate>+ {busyText ? (+ // The tooltip shows the whole phase where a narrow pane truncates it.+ <Tooltip content={busyText}>+ <span>+ {/* Inline in the text line, so the header keeps its height and baseline while busy. */}+ <Spinner me="1.5" size="inherit" verticalAlign="-0.125em" />+ {busyText}+ </span>+ </Tooltip>+ ) : null}+ </Text>+ }+ >+ {form.groups.map((group) => (+ <PropertyGroup key={group.id} collapsible={group.collapsible} id={group.id} label={t(group.labelKey)}>+ <group.body engine={engine} />+ </PropertyGroup>+ ))}+ <Box pt="1">+ <Actions engine={engine} />+ </Box>+ {error ? (+ <Flex align="flex-start" color="fg.error" gap="1">+ <Text aria-live="assertive" flex="1" minW="0" py="1" role="alert">+ {error.text}+ </Text>+ {detail && detail !== error.text ? (+ <IconButton+ aria-label={t('widgets.layers.selectObject.technicalDetails')}+ color="fg.muted"+ flexShrink={0}+ size="xs"+ tooltip={detail}+ variant="ghost"+ >+ <Icon as={InfoIcon} boxSize="3.5" />+ </IconButton>+ ) : null}+ </Flex>+ ) : null}+ </PropertiesSection>+ );+ };+ return OperationSection;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsxindex 5007e5ca47..93c54d3003 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/OverviewPane.tsx@@ -18,6 +18,25 @@ const CHECKERBOARD_CSS = {backgroundSize: '12px 12px',};+/**+ * The viewport outline is three 1px bands inside the box, dark/light/dark, matching the canvas brush ring so it reads+ * over any pixels. Fixed black/white rather than theme tokens: contrast must not depend on the content or the theme.+ * Borders, unlike box-shadow spreads, snap to whole device pixels, so each band stays crisp at any device pixel ratio.+ */+const VIEW_RECT_DARK = '#000000';+const VIEW_RECT_LIGHT = '#ffffff';+/** Smallest drawn outline: the three bands on each side plus a 2px hollow, so a tiny viewport still reads as a box. */+const VIEW_RECT_MIN_PX = 8;+const VIEW_RECT_INNER_CSS = {+ _before: {+ borderColor: VIEW_RECT_DARK,+ borderWidth: '1px',+ content: '""',+ inset: '0',+ position: 'absolute',+ },+};+const VIEW_RECT_TRANSITION = `left ${VIEW_RECT_INTERVAL_MS}ms linear, top ${VIEW_RECT_INTERVAL_MS}ms linear, width ${VIEW_RECT_INTERVAL_MS}ms linear, height ${VIEW_RECT_INTERVAL_MS}ms linear`;/**@@ -94,11 +113,16 @@ const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {const top = (topLeft.y - current.y) * current.scale;const width = (bottomRight.x - topLeft.x) * current.scale;const height = (bottomRight.y - topLeft.y) * current.scale;+ const drawnWidth = Math.max(VIEW_RECT_MIN_PX, Math.min(width, widthPx * 2));+ const drawnHeight = Math.max(VIEW_RECT_MIN_PX, Math.min(height, heightPx * 2));+ // A box grown to the minimum stays centred on the viewport.+ const drawnLeft = left - Math.max(0, drawnWidth - width) / 2;+ const drawnTop = top - Math.max(0, drawnHeight - height) / 2;outline.style.visibility = 'visible';- outline.style.left = `${Math.max(-widthPx, Math.min(left, widthPx))}px`;- outline.style.top = `${Math.max(-heightPx, Math.min(top, heightPx))}px`;- outline.style.width = `${Math.max(4, Math.min(width, widthPx * 2))}px`;- outline.style.height = `${Math.max(4, Math.min(height, heightPx * 2))}px`;+ outline.style.left = `${Math.max(-widthPx, Math.min(drawnLeft, widthPx))}px`;+ outline.style.top = `${Math.max(-heightPx, Math.min(drawnTop, heightPx))}px`;+ outline.style.width = `${drawnWidth}px`;+ outline.style.height = `${drawnHeight}px`;};// Throttle DOM outline updates and let CSS interpolate between them.const outlineThrottle = { last: 0, timer: null as ReturnType<typeof setTimeout> | null };@@ -287,14 +311,21 @@ const ConnectedOverview = ({ engine }: { engine: CanvasEngineHandle }) => {<chakra.canvas ref={canvasRef} display="block" touchAction="none" /><Boxref={viewRectRef}- borderColor="accent.solid"- borderWidth="1.5px"+ borderColor={VIEW_RECT_DARK}+ borderWidth="1px"pointerEvents="none"position="absolute"- rounded="xs"transition={VIEW_RECT_TRANSITION}visibility="hidden"- />+ >+ <Box+ borderColor={VIEW_RECT_LIGHT}+ borderWidth="1px"+ css={VIEW_RECT_INNER_CSS}+ inset="0"+ position="absolute"+ />+ </Box></chakra.button></Flex>);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsxindex 1e119888c7..46511c8a97 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesPane.tsx@@ -1,4 +1,4 @@-import { Flex, Stack } from '@chakra-ui/react';+import { Box, Flex, Stack } from '@chakra-ui/react';import { Scrollable } from '@platform/ui/Scrollable';import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/canvas-operations/react';import { useCanvasActiveTool, useCanvasOperation } from '@workbench/widgets/canvas/engineStoreHooks';@@ -12,11 +12,12 @@ import { useTranslation } from 'react-i18next';import { GroupSelectedNotice } from './GroupSelectedNotice';import { LayerSection } from './LayerSection';+import { createOperationSection } from './OperationSection';import { PropertiesSection } from './PropertiesSection';-const OPERATION_TITLE_KEYS = {- filter: 'widgets.layers.rasterFilter.title',- 'select-object': 'widgets.layers.selectObject.title',+const OPERATION_SECTIONS = {+ filter: createOperationSection(OPERATION_PRESENTATION_ADAPTERS.filter),+ 'select-object': createOperationSection(OPERATION_PRESENTATION_ADAPTERS['select-object']),} as const;/** Show active operation before tool forms; use existing engine stores/transactions without mirrored state. */@@ -44,15 +45,15 @@ const ConnectedProperties = ({ engine }: { engine: CanvasEngineHandle }) => {const activeTool = useCanvasActiveTool(engine);const operation = useCanvasOperation(engine);const running = operation.status === 'active' ? OPERATION_PRESENTATION_ADAPTERS[operation.identity.kind] : null;+ const RunningSection = operation.status === 'active' ? OPERATION_SECTIONS[operation.identity.kind] : null;const tool = TOOL_PRESENTATION_ADAPTERS[activeTool];const toolName = t(`widgets.canvas.tools.${tool.id}`);const Preview = tool.preview;const regionProps = { engine };- // The pane has ONE sticky footer: a running operation's, else the tool- // form's; the operation always wins because the tool section is inert then.- const Footer = running ? running.footer : tool.footer;+ const ToolActions = tool.actions;- // `inert` will blur a focused tool control once an operation starts; hand focus to the operation's Cancel first.+ // `inert` will blur a focused tool control once an operation starts; hand focus to the operation's Cancel first. The+ // Operation section comes first, so its Cancel is the first match; focusing it scrolls it into view.const root = useRef<HTMLDivElement>(null);const toolSection = useRef<HTMLDivElement>(null);useLayoutEffect(() => {@@ -63,19 +64,8 @@ const ConnectedProperties = ({ engine }: { engine: CanvasEngineHandle }) => {return (<Stack ref={root} gap="0">- {running ? (- <PropertiesSection- subtitle={t(OPERATION_TITLE_KEYS[running.kind])}- title={t('widgets.properties.sections.operation')}- >- {running.groups.map((group) => (- <PropertyGroup key={group.id} collapsible={group.collapsible} id={group.id} label={t(group.labelKey)}>- <group.body {...regionProps} />- </PropertyGroup>- ))}- </PropertiesSection>- ) : null}- {tool.groups.length > 0 || Preview ? (+ {RunningSection ? <RunningSection engine={engine} /> : null}+ {tool.groups.length > 0 || Preview || ToolActions ? (<PropertiesSectionref={toolSection}disabled={running !== null}@@ -91,22 +81,14 @@ const ConnectedProperties = ({ engine }: { engine: CanvasEngineHandle }) => {<group.body {...regionProps} /></PropertyGroup>))}+ {ToolActions ? (+ <Box pt="1">+ <ToolActions engine={engine} />+ </Box>+ ) : null}</PropertiesSection>) : null}<LayerSection disabled={running !== null} />- {Footer ? (- <Flex- bg="bg.panel"- borderColor="border.subtle"- borderTopWidth="1px"- bottom="0"- position="sticky"- px="3"- py="1.5"- >- <Footer engine={engine} />- </Flex>- ) : null}</Stack>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesSection.tsxindex cebcb4f0d1..b7984869fe 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/PropertiesSection.tsx@@ -1,7 +1,8 @@import type { ReactNode, Ref } from 'react';-import { Flex, Stack, Text } from '@chakra-ui/react';+import { Flex, Stack, Text, VisuallyHidden } from '@chakra-ui/react';import { FieldLabel } from '@platform/ui/Field';+import { Tooltip } from '@platform/ui/Tooltip';/** A headed group of rows in an editor pane: Operation, Tool, Layer. */export const PropertiesSection = ({@@ -9,15 +10,27 @@ export const PropertiesSection = ({disabled = false,ref,subtitle,+ subtitleDetail,title,+ trailing,}: {children: ReactNode;/** The surface is busy elsewhere (staging, generation, an operation): the rows stay in place but cannot act. */disabled?: boolean;ref?: Ref<HTMLDivElement>;subtitle?: string;+ /** More about the subtitle: its tooltip, and read with it by assistive tech. */+ subtitleDetail?: string;title: string;+ /** Right-aligned beside the title, in the header's one line: it truncates rather than growing the header. */+ trailing?: ReactNode;}) => {+ const subtitleText = subtitle ? (+ <Text color="fg.muted" flexShrink={1} minW="0" truncate>+ {subtitle}+ {subtitleDetail ? <VisuallyHidden>{subtitleDetail}</VisuallyHidden> : null}+ </Text>+ ) : null;return (<Stackref={ref}@@ -33,11 +46,8 @@ export const PropertiesSection = ({><Flex align="baseline" gap="2" minW="0"><FieldLabel>{title}</FieldLabel>- {subtitle ? (- <Text color="fg.muted" minW="0" truncate>- {subtitle}- </Text>- ) : null}+ {subtitleText && subtitleDetail ? <Tooltip content={subtitleDetail}>{subtitleText}</Tooltip> : subtitleText}+ {trailing}</Flex>{children}</Stack>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.tsindex 84be8c4a1d..e540ecc609 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts@@ -50,7 +50,8 @@ export interface LayerColorPaneLayout extends PaneBlockLayout {activePane: LayerColorPaneId;}-export const COLOR_PANE_MIN_SIZE_PX = 160;+/** The tab strip (40) plus the picker tray's padding (16) and the 168px colour wheel: the wheel always shows whole. */+export const COLOR_PANE_MIN_SIZE_PX = 224;export const COLOR_PANE_MAX_SIZE_PX = 560;export const COLOR_PANE_DEFAULTS: LayerColorPaneLayout = {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.tsindex b5bd68a959..943b7633e8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts@@ -8,7 +8,9 @@ import {CANVAS_MERGE_DOWN_HOTKEY,executeCanvasToolCommand,mergeSelectedLayerDown,+ reportMergeDownRefusal,reportTransformRefusal,+ showCanvasRefusalNotice,type CanvasToolCommandId,} from '@workbench/widgets/canvas/canvasToolCommands';import { useActiveColorCommands } from '@workbench/widgets/canvas/color-system/useActiveColors';@@ -46,14 +48,25 @@ export const useCanvasCompanionHotkeys = (const model = engine?.document.model() ?? null;if (commandId === 'canvas.mergeDown') {if (model) {- mergeSelectedLayerDown(engine, model.document, (refusal) => reportLayerOperation(refusal, notify.error, t));+ mergeSelectedLayerDown(+ engine,+ model.document,+ (refusal) => reportLayerOperation(refusal, notify.error, t),+ (refusal) => reportMergeDownRefusal(model.document, refusal, showCanvasRefusalNotice, t)+ );}return;}const selectedId = model?.document.selectedLayerId ?? null;executeCanvasToolCommand(commandId, {engine,- reportTransformRefusal: (refusal) => reportTransformRefusal(refusal, notify.error, t),+ reportTransformRefusal: (refusal, layerId) =>+ reportTransformRefusal(+ refusal,+ { id: layerId, name: model?.getLayer(layerId)?.name ?? '' },+ { error: notify.error, notice: showCanvasRefusalNotice },+ t+ ),resetActiveColors: colorCommands.resetPair,selectedLayerId: selectedId === null ? null : (model?.getLayer(selectedId)?.id ?? null),swapActiveColors: colorCommands.swapPair,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsxindex 5710f93e35..780dcc1472 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsHeaderActions.tsx@@ -34,11 +34,11 @@ export const NotificationsHeaderActions = () => {}, [notifications, notify, queries, t]);return (- <HStack gap="2">- <Button disabled={!hasUnread} size="sm" variant="outline" onClick={markRead}>+ <HStack gap="1">+ <Button disabled={!hasUnread} size="xs" variant="ghost" onClick={markRead}>{t('notifications.markRead')}</Button>- <Button disabled={!hasAny} size="sm" variant="outline" onClick={clear}>+ <Button disabled={!hasAny} size="xs" variant="ghost" onClick={clear}>{t('common.clear')}</Button></HStack>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsList.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsList.tsxnew file mode 100644index 0000000000..cef9743d4a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsList.tsx@@ -0,0 +1,463 @@+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */+import type { ListRowProps } from '@platform/ui/list/List';+import type { ListContextMenuAnchor } from '@platform/ui/list/ListItem';+import type { ToastAction } from '@platform/ui/toaster';+import type { WorkbenchNotification, WorkbenchNotificationKind } from '@workbench/projectContracts';++import { Badge, Box, chakra, HStack, Icon, Menu, Portal, VisuallyHidden } from '@chakra-ui/react';+import { queueCommands } from '@features/queue';+import { useExitRetainedValue } from '@platform/react/useExitRetainedValue';+import { Button, IconButton } from '@platform/ui/Button';+import { EmptyState } from '@platform/ui/EmptyState';+import { List } from '@platform/ui/list/List';+import { ListItem } from '@platform/ui/list/ListItem';+import { listRowsFromItems } from '@platform/ui/list/listRows';+import { MenuActionItem, MenuContent } from '@platform/ui/Menu';+import { useWorkbenchFocus } from '@workbench/focusRegions';+import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';+import { createEditorNotificationActionContext } from '@workbench/shell/notifications/editorNotificationActions';+import {+ resolveNotificationActions,+ type NotificationActionContext,+} from '@workbench/shell/notifications/notificationActions';+import { resolveNotificationText } from '@workbench/shell/notifications/notificationToasts';+import { hasNotificationUndo, subscribeNotificationUndos } from '@workbench/shell/notifications/undoRegistry';+import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';+import { BellIcon, CircleCheckIcon, CircleXIcon, InfoIcon, XIcon, type LucideIcon } from 'lucide-react';+import { memo, useCallback, useMemo, useRef, useState, useSyncExternalStore } from 'react';+import { useTranslation } from 'react-i18next';++const kindMeta = {+ error: { color: 'fg.error', icon: CircleXIcon },+ info: { color: 'accent.fg', icon: InfoIcon },+ success: { color: 'fg.success', icon: CircleCheckIcon },+} satisfies Record<WorkbenchNotificationKind, { color: string; icon: LucideIcon }>;++/** How long a new notice must be on screen before it counts as read. */+const SEEN_AFTER_MS = 1_500;++/** Share of a row that must show for it to count as seen. */+const SEEN_THRESHOLD = 0.5;++/** A title, a wrapped line of message and the age line; rows are measured, so this only steadies the first scroll. */+const ESTIMATED_ROW_HEIGHT_PX = 64;++const getNotificationKey = (notification: WorkbenchNotification) => notification.id;++interface NotificationMenuTarget extends ListContextMenuAnchor {+ notificationId: string;+}++/**+ * The buttons a notice offers, as its toast offered them. Undo closures live outside workbench state, so the notice's+ * still-offered undos are a snapshot of their own (they go when run elsewhere or withdrawn). The actions are filtered by+ * that snapshot rather than by the registry alone, so memoization sees the change.+ */+const useNotificationActions = (+ notification: WorkbenchNotification,+ actionContext: NotificationActionContext+): ToastAction[] => {+ const getOfferedUndoIds = useCallback(+ () =>+ (notification.actions ?? [])+ .flatMap((action) => (action.kind === 'undo' && hasNotificationUndo(action.undoId) ? [action.undoId] : []))+ .join('\n'),+ [notification.actions]+ );+ const offeredUndoIds = useSyncExternalStore(subscribeNotificationUndos, getOfferedUndoIds, getOfferedUndoIds);+ const offered = (notification.actions ?? []).filter(+ (action) => action.kind !== 'undo' || offeredUndoIds.split('\n').includes(action.undoId)+ );++ return resolveNotificationActions(offered, actionContext);+};++/**+ * The expanded notifications list, loaded with the popover rather than with the status-bar chip. Rows are measured:+ * messages wrap in full, so nothing needs a details view to be read.+ */+export const NotificationsList = () => {+ const { i18n, t } = useTranslation();+ const notifications = useWorkbenchSelector((snapshot) => snapshot.notifications);+ const commands = useWorkbenchCommands();+ const queries = useWorkbenchQueries();+ const focus = useWorkbenchFocus();+ const { getWidgetById, getWidgetsForRegion } = useWorkbenchWidgetRegistry();+ const panelRef = useRef<HTMLDivElement>(null);+ const rows = useMemo(() => listRowsFromItems(notifications, getNotificationKey), [notifications]);+ // The same buttons the toasts offer, resolved against this editor at render time.+ const actionContext = useMemo(+ () =>+ createEditorNotificationActionContext({+ focus,+ getWidgetById,+ getWidgetsForRegion,+ notifications: commands.notifications,+ queries,+ retryQueueItems: queueCommands.retryItems,+ t: i18n.t,+ widgets: commands.widgets,+ }),+ [commands, focus, getWidgetById, getWidgetsForRegion, i18n, queries]+ );+ const [menuTarget, setMenuTarget] = useState<NotificationMenuTarget | null>(null);+ /**+ * Focus moves to the next notice's dismiss, else the previous one's. The List keeps the focused row and its overscan+ * mounted, so a neighbour's dismiss is always in the DOM. With none left the header's buttons are disabled, so focus+ * holds on the panel until the empty state that replaces the list can take it.+ */+ const dismiss = useCallback(+ (notificationId: string) => {+ const panel = panelRef.current;+ const buttons = [...(panel?.querySelectorAll<HTMLButtonElement>('[data-notification-dismiss]') ?? [])];+ const index = buttons.findIndex((button) => button.dataset.notificationDismiss === notificationId);+ const neighbourId = (buttons[index + 1] ?? buttons[index - 1])?.dataset.notificationDismiss;+ const target = () =>+ panel?.querySelector<HTMLElement>(+ neighbourId ? `[data-notification-dismiss="${CSS.escape(neighbourId)}"]` : '[data-notifications-empty]'+ ) ?? null;++ (target() ?? panel)?.focus();+ commands.notifications.dismiss(notificationId);+ // Settle once the list has: the empty state appears only after the commit, and a dismiss chosen from the row's+ // menu (an update outside React's event handling) can remount the neighbour's row, dropping focus to the page.+ requestAnimationFrame(() => {+ const active = document.activeElement;++ if (active === null || active === document.body || active === panel) {+ target()?.focus();+ }+ });+ },+ [commands]+ );+ const openMenu = useCallback(+ (notificationId: string, anchor: ListContextMenuAnchor) => setMenuTarget({ ...anchor, notificationId }),+ []+ );+ const closeMenu = useCallback(() => setMenuTarget(null), []);+ const markSeen = useCallback(+ (notificationId: string) => commands.notifications.markRead([notificationId]),+ [commands]+ );+ const renderItem = useCallback(+ (notification: WorkbenchNotification, rowProps: ListRowProps) => (+ // Spread so the memoized row compares the List's primitives, not a fresh object per render.+ <NotificationRow+ {...rowProps}+ actionContext={actionContext}+ isMenuOpen={menuTarget?.notificationId === notification.id}+ notification={notification}+ onDismiss={dismiss}+ onOpenMenu={openMenu}+ onSeen={markSeen}+ />+ ),+ [actionContext, dismiss, markSeen, menuTarget, openMenu]+ );++ return (+ <Box+ ref={panelRef}+ // A grid area is a definite height for the List to fill, even when the popover sizes to its content up to a cap;+ // a flex column would let the List grow past the cap and clip instead of scroll.+ display="grid"+ flex="1"+ focusVisibleRing="inside"+ gridTemplateRows="minmax(0, 1fr)"+ minH="0"+ px="1.5"+ py="1.5"+ // Holds focus for the moment between dismissing the last notice and the empty state appearing.+ tabIndex={-1}+ >+ <List+ dividers+ emptyState={+ // Named so that focus landing here after the last dismiss says what happened.+ <EmptyState+ aria-label={t('notifications.emptyTitle')}+ data-notifications-empty=""+ description={t('notifications.empty')}+ focusVisibleRing="inside"+ icon={<BellIcon />}+ role="group"+ tabIndex={-1}+ title={t('notifications.emptyTitle')}+ />+ }+ estimatedRowHeight={ESTIMATED_ROW_HEIGHT_PX}+ // The panel pads the rows; the header above lines up with them.+ inset="none"+ label={t('widgets.labels.notifications')}+ renderItem={renderItem}+ rowHeight="measured"+ rows={rows}+ />+ <NotificationMenu+ actionContext={actionContext}+ notifications={notifications}+ target={menuTarget}+ onClose={closeMenu}+ onDismiss={dismiss}+ />+ </Box>+ );+};++/**+ * One menu for the list, opened from a row's button or by right-click: the row's actions and its dismiss. An item that+ * moved focus on (a dismiss to the next notice, Show in queue to the queue) keeps it; otherwise focus returns to the+ * row.+ */+const NotificationMenu = ({+ actionContext,+ notifications,+ onClose,+ onDismiss,+ target,+}: {+ actionContext: NotificationActionContext;+ notifications: readonly WorkbenchNotification[];+ onClose: () => void;+ onDismiss: (notificationId: string) => void;+ target: NotificationMenuTarget | null;+}) => {+ // Kept through the exit animation; keyed by notice so another row's menu still opens at its own anchor.+ const { release, value: shown } = useExitRetainedValue(target);+ const notification = shown+ ? (notifications.find((candidate) => candidate.id === shown.notificationId) ?? null)+ : null;++ return (+ <Menu.Root+ key={shown ? shown.notificationId : 'none'}+ lazyMount+ open={target !== null}+ positioning={{+ getAnchorRect: () => (shown ? { height: 1, width: 1, x: shown.x, y: shown.y } : null),+ placement: 'bottom-start',+ }}+ unmountOnExit+ onExitComplete={release}+ onOpenChange={(event) => {+ if (event.open) {+ return;+ }++ const active = document.activeElement;++ if (!active || active === document.body || active.closest('[data-scope="menu"]')) {+ target?.restoreFocus();+ }+ onClose();+ }}+ >+ <Portal>+ <Menu.Positioner>+ {notification ? (+ <NotificationMenuItems actionContext={actionContext} notification={notification} onDismiss={onDismiss} />+ ) : null}+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++const NotificationMenuItems = ({+ actionContext,+ notification,+ onDismiss,+}: {+ actionContext: NotificationActionContext;+ notification: WorkbenchNotification;+ onDismiss: (notificationId: string) => void;+}) => {+ const { t } = useTranslation();+ const actions = useNotificationActions(notification, actionContext);++ return (+ <MenuContent minW="12rem">+ {actions.map((action) => (+ <MenuActionItem key={action.label} label={action.label} value={action.label} onSelect={action.onClick} />+ ))}+ {actions.length > 0 ? <Menu.Separator /> : null}+ <MenuActionItem+ icon={XIcon}+ label={t('common.dismissNotification')}+ value="dismiss"+ onSelect={() => onDismiss(notification.id)}+ />+ </MenuContent>+ );+};++const NotificationRow = memo(+ ({+ actionContext,+ density,+ isMenuOpen,+ itemKey,+ notification,+ onDismiss,+ onOpenMenu,+ onSeen,+ positionInSet,+ setSize,+ tabIndex,+ }: Pick<ListRowProps, 'density' | 'itemKey' | 'positionInSet' | 'setSize' | 'tabIndex'> & {+ actionContext: NotificationActionContext;+ isMenuOpen: boolean;+ notification: WorkbenchNotification;+ onDismiss: (notificationId: string) => void;+ onOpenMenu: (notificationId: string, anchor: ListContextMenuAnchor) => void;+ onSeen: (notificationId: string) => void;+ }) => {+ const { t } = useTranslation();+ /**+ * Seeing a notice is reading it: an unread row that stays at least half on screen for a moment becomes read. One+ * scrolled out of view, or a glance shorter than that (a StrictMode remount included), leaves it new.+ */+ const watchSeen = useCallback(+ (node: HTMLElement | null) => {+ if (!node || notification.isRead) {+ return;+ }++ let timer: ReturnType<typeof setTimeout> | undefined;+ const observer = new IntersectionObserver(+ ([entry]) => {+ if (entry && entry.isIntersecting && entry.intersectionRatio >= SEEN_THRESHOLD) {+ timer ??= setTimeout(() => onSeen(notification.id), SEEN_AFTER_MS);+ } else {+ clearTimeout(timer);+ timer = undefined;+ }+ },+ // Crossing either mark reports; a row sliding under half visible stops its clock.+ { threshold: [0, SEEN_THRESHOLD] }+ );++ observer.observe(node);++ return () => {+ observer.disconnect();+ clearTimeout(timer);+ };+ },+ [notification.id, notification.isRead, onSeen]+ );+ const actions = useNotificationActions(notification, actionContext);+ const { message, title } = resolveNotificationText(notification, actionContext.t);+ const repeats = notification.occurrenceCount ?? 1;+ const kind = kindMeta[notification.kind];+ const dismiss = useCallback(() => onDismiss(notification.id), [notification.id, onDismiss]);+ // The row's button opens its menu (keyboard, assistive tech, touch); a mouse right-clicks.+ const openMenu = useCallback(+ (anchor: ListContextMenuAnchor) => onOpenMenu(notification.id, anchor),+ [notification.id, onOpenMenu]+ );++ // The wrapper is the list item so the seen observer can watch the whole row; the List places and measures it.+ return (+ <Box ref={watchSeen} aria-posinset={positionInSet} aria-setsize={setSize} role="listitem">+ <ListItem+ actions={+ // Level with the title rather than centred on a message that wraps over several lines.+ <Box alignSelf="flex-start" pt="1">+ <IconButton+ aria-label={t('common.dismissNotification')}+ color="fg.muted"+ data-notification-dismiss={notification.id}+ size="xs"+ tooltip={t('common.dismissNotification')}+ variant="ghost"+ onClick={dismiss}+ >+ <Icon as={XIcon} boxSize="3.5" />+ </IconButton>+ </Box>+ }+ badges={+ repeats > 1 ? (+ <Badge fontSize="xs" fontVariantNumeric="tabular-nums" variant="surface">+ {t('notifications.repeatCount', { count: repeats })}+ </Badge>+ ) : undefined+ }+ density={density}+ description={+ // Phrasing content only: the text sits inside the row's button.+ <chakra.span display="flex" flexDirection="column" gap="0.5">+ {message ? <chakra.span overflowWrap="anywhere">{message}</chakra.span> : null}+ <chakra.time color="fg.subtle" dateTime={notification.createdAt}>+ {formatRelativeTime(notification.createdAt)}+ </chakra.time>+ </chakra.span>+ }+ detail={+ actions.length > 0 ? (+ // Inset past the kind tile, under the text the actions belong to.+ <HStack flexWrap="wrap" gap="1" ps="10">+ {actions.map((action) => (+ <Button key={action.label} size="xs" variant="outline" onClick={action.onClick}>+ {action.label}+ </Button>+ ))}+ </HStack>+ ) : undefined+ }+ isMenuOpen={isMenuOpen}+ itemKey={itemKey}+ leading={+ <>+ <KindTile color={kind.color} icon={kind.icon} isUnread={!notification.isRead} />+ {/* Kind and unread state lead the row's name; the tile's icon shape and dot are their visual cues. */}+ <VisuallyHidden>+ {notification.isRead ? null : `${t('notifications.unread')}, `}+ {`${t(`notifications.kind.${notification.kind}`)}: `}+ </VisuallyHidden>+ </>+ }+ role="presentation"+ tabIndex={tabIndex}+ title={title}+ titleTruncate="end"+ onContextMenu={openMenu}+ />+ </Box>+ );+ }+);++/** The kind's icon on a tile, as the queue's rows show their state; an unread notice adds a dot to its corner. */+const KindTile = ({ color, icon, isUnread }: { color: string; icon: LucideIcon; isUnread: boolean }) => (+ <chakra.span+ alignItems="center"+ alignSelf="flex-start"+ aria-hidden+ bg="bg.subtle"+ boxSize="8"+ color={color}+ display="flex"+ flexShrink={0}+ justifyContent="center"+ position="relative"+ rounded="md"+ >+ <Icon as={icon} boxSize="4" />+ {isUnread ? (+ <chakra.span+ bg="accent.solid"+ borderColor="bg.panel"+ borderWidth="2px"+ boxSize="2.5"+ insetEnd="-0.5"+ position="absolute"+ rounded="full"+ top="-0.5"+ />+ ) : null}+ </chakra.span>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.browser.test.tsxindex 899d4411ae..72baf62daf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.browser.test.tsx@@ -13,7 +13,7 @@ import { registerNotificationUndo } from '@workbench/shell/notifications/undoRegimport { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';import { createWorkbenchStore } from '@workbench/workbenchStore';import i18next from 'i18next';-import { act, StrictMode } from 'react';+import { act, StrictMode, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -58,21 +58,32 @@ let root: Root | null = null;let stopToasts: (() => void) | null = null;const popoverProps = { presentation: 'expanded', region: 'popover' } as WidgetViewProps;+/** The list loads with the popover, not with the chip; wait for it rather than for its loading fallback. */+const listLoaded = () =>+ vi.waitFor(() =>+ expect(+ host?.querySelector('[role="list"][aria-label="Notifications"], [role="group"][aria-label="No notifications"]')+ ).not.toBeNull()+ );++const renderView = async (view: ReactNode) => {+ await act(() => root?.render(<ChakraProvider value={system}>{view}</ChakraProvider>));+ await listLoaded();+};+const renderPopover = () =>- act(() =>- root?.render(- <ChakraProvider value={system}>- <AppToaster />- <NotificationsWidgetView {...popoverProps} />- </ChakraProvider>- )+ renderView(+ <>+ <AppToaster />+ <NotificationsWidgetView {...popoverProps} />+ </>);const button = (name: string) =>[...document.querySelectorAll<HTMLButtonElement>('button')].find((candidate) => candidate.textContent === name || candidate.getAttribute('aria-label') === name);-const cards = () => [...(host?.querySelectorAll<HTMLElement>('li') ?? [])];+const cards = () => [...(host?.querySelectorAll<HTMLElement>('[role="listitem"]') ?? [])];const cardNamed = (title: string) => cards().find((card) => card.textContent?.includes(title));const buttonsOf = (element: HTMLElement | undefined) =>[...(element?.querySelectorAll<HTMLButtonElement>('button') ?? [])].map((candidate) => candidate.textContent);@@ -200,7 +211,7 @@ describe('notifications widget', () => {await renderPopover();const dismissOf = (index: number) =>cards()[index]!.querySelector<HTMLButtonElement>('button[aria-label="Dismiss notification"]')!;- const focusedCard = () => document.activeElement?.closest('li')?.textContent ?? '';+ const focusedCard = () => document.activeElement?.closest('[role="listitem"]')?.textContent ?? '';const titles = () =>store().getSnapshot()@@ -219,8 +230,8 @@ describe('notifications widget', () => {await act(() => userEvent.keyboard('{Enter}'));expect(titles()).toEqual([]);- // With no notice left, focus rests on the list, visibly, not on the page.- expect(document.activeElement?.getAttribute('aria-label')).toBe('Notifications');+ // With no notice left, focus rests on the empty state that says so, visibly, not on the page.+ await vi.waitFor(() => expect(document.activeElement?.getAttribute('aria-label')).toBe('No notifications'));expect(document.activeElement?.matches(':focus-visible')).toBe(true);});@@ -235,6 +246,7 @@ describe('notifications widget', () => {</StrictMode>));+ await listLoaded();// StrictMode's extra detach must not count as seen.expect(store().getSnapshot().notifications[0]?.isRead).toBe(false);@@ -245,14 +257,10 @@ describe('notifications widget', () => {for (let index = 0; index < 20; index += 1) {store().commands.notifications.add({ kind: 'info', message: `Notice ${index}`, title: `Notice ${index}` });}- await act(() =>- root?.render(- <ChakraProvider value={system}>- <Box display="flex" flexDirection="column" h="160px">- <NotificationsWidgetView {...popoverProps} />- </Box>- </ChakraProvider>- )+ await renderView(+ <Box display="flex" flexDirection="column" h="160px">+ <NotificationsWidgetView {...popoverProps} />+ </Box>);const isRead = (title: string) =>store()@@ -302,6 +310,8 @@ describe('notifications widget', () => {await renderPopover();await act(() => recordUndoable('Deleted curve', onUndo));await vi.waitFor(() => expect(buttonsOf(toastNamed('Deleted curve'))).toContain('Undo'));+ // The first row of an empty list mounts once the list has measured its viewport.+ await vi.waitFor(() => expect(buttonsOf(cardNamed('Deleted curve'))).toContain('Undo'));await act(() => userEvent.click(buttonIn(cardNamed('Deleted curve')!, 'Undo')));@@ -341,7 +351,151 @@ describe('notifications widget', () => {await act(() => Promise.resolve());expect(toastNamed('Deleted preset')).toBeUndefined();expect(toastNamed('Kept')).toBeUndefined();+ await vi.waitFor(() => expect(buttonsOf(cardNamed('Deleted preset'))).toContain('Undo'));await act(() => userEvent.click(buttonIn(cardNamed('Deleted preset')!, 'Undo')));expect(onUndo).toHaveBeenCalledOnce();});++ it('names each row by its kind and unread state, which Mark read clears', async () => {+ store().commands.notifications.add({ kind: 'success', title: 'Saved' });+ store().commands.notifications.add({ kind: 'error', title: 'Upload failed' });+ // Checked before the rows have been on screen long enough to count as seen.+ await renderPopover();+ const rowName = (title: string) => cardNamed(title)?.querySelector('[data-list-primary]')?.textContent ?? '';++ // Kind is said in words and drawn as a distinct icon, never by colour alone.+ expect(rowName('Upload failed')).toMatch(/^Unread, Error: Upload failed/);+ expect(rowName('Saved')).toMatch(/^Unread, Success: Saved/);+ const iconOf = (title: string) => cardNamed(title)?.querySelector('svg')?.outerHTML;+ expect(iconOf('Upload failed')).not.toBe(iconOf('Saved'));++ await act(() => userEvent.click(button('Mark read')!));++ expect(+ store()+ .getSnapshot()+ .notifications.every((notification) => notification.isRead)+ ).toBe(true);+ expect(rowName('Upload failed')).toMatch(/^Error: Upload failed/);+ expect(button('Mark read')?.disabled).toBe(true);+ });++ it('shows the empty state once nothing is left, with the header actions disabled', async () => {+ await renderPopover();++ expect(host?.textContent).toContain('No notifications');+ expect(host?.textContent).toContain('Successful operations, errors, and system messages appear here.');+ expect(host?.querySelector('[role="list"]')).toBeNull();+ expect(button('Mark read')?.disabled).toBe(true);+ expect(button('Clear')?.disabled).toBe(true);+ });++ it('wraps a long message in full instead of clipping it', async () => {+ const message = `CUDA out of memory. ${'Tried to allocate 2.00 GiB on a card that is already nearly full. '.repeat(6)}`;+ store().commands.notifications.add({ kind: 'error', message, title: 'Run failed' });+ await renderView(+ <Box display="flex" flexDirection="column" maxH="28rem" w="26rem">+ <NotificationsWidgetView {...popoverProps} />+ </Box>+ );+ const card = cardNamed('Run failed')!;+ const text = [...card.querySelectorAll('span')].find((span) => span.textContent === message)!;++ expect(text).toBeDefined();+ // Several lines tall, inside its row, and no wider than the row.+ expect(text.getBoundingClientRect().height).toBeGreaterThan(40);+ expect(text.getBoundingClientRect().bottom).toBeLessThanOrEqual(card.getBoundingClientRect().bottom);+ expect(text.scrollWidth).toBeLessThanOrEqual(text.clientWidth);+ });++ it('scrolls a long list inside a height-capped popover, mounting only the rows near view', async () => {+ for (let index = 0; index < 60; index += 1) {+ store().commands.notifications.add({ kind: 'info', title: `Notice ${index}` });+ }+ await renderView(+ <Box display="flex" flexDirection="column" maxH="240px" w="26rem">+ <NotificationsWidgetView {...popoverProps} />+ </Box>+ );+ const viewport = host!.querySelector<HTMLElement>('[data-list-viewport]')!;++ expect(viewport.clientHeight).toBeLessThan(240);+ expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight);+ expect(cards().length).toBeLessThan(60);+ });++ it('moves between rows with the arrow keys and reaches a row’s actions with Tab', async () => {+ store().commands.notifications.add({+ actions: [{ itemIds: [7], kind: 'retry-queue-item' }],+ kind: 'error',+ title: 'First',+ });+ store().commands.notifications.add({ kind: 'info', title: 'Second' });+ store().commands.notifications.add({ kind: 'info', title: 'Third' });+ await renderPopover();+ const primaryOf = (title: string) => cardNamed(title)!.querySelector<HTMLElement>('[data-list-primary]')!;+ const focusedRow = () => document.activeElement?.closest('[role="listitem"]')?.textContent ?? '';++ // One tab stop for the rows: the newest.+ expect(+ [...host!.querySelectorAll<HTMLElement>('[data-list-primary]')].filter((primary) => primary.tabIndex === 0)+ ).toEqual([primaryOf('Third')]);++ primaryOf('Third').focus();+ await act(() => userEvent.keyboard('{ArrowDown}'));+ expect(document.activeElement).toBe(primaryOf('Second'));+ await act(() => userEvent.keyboard('{End}'));+ expect(document.activeElement).toBe(primaryOf('First'));++ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement?.getAttribute('aria-label')).toBe('Dismiss notification');+ expect(focusedRow()).toContain('First');+ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement?.textContent).toBe('Retry');++ // Arrows from a row's action move on to the neighbouring row.+ await act(() => userEvent.keyboard('{ArrowUp}'));+ expect(document.activeElement).toBe(primaryOf('Second'));+ await act(() => userEvent.keyboard('{Home}'));+ expect(document.activeElement).toBe(primaryOf('Third'));+ });++ it('opens a row’s menu from its button, offering the notice’s actions and Dismiss', async () => {+ store().commands.notifications.add({ kind: 'info', title: 'Older' });+ store().commands.notifications.add({+ actions: [+ { itemId: 41, kind: 'reveal-queue-item' },+ { itemIds: [41], kind: 'retry-queue-item' },+ ],+ kind: 'error',+ title: 'Run failed',+ });+ await renderPopover();+ const primary = cardNamed('Run failed')!.querySelector<HTMLElement>('[data-list-primary]')!;+ const menuItems = () =>+ [...document.querySelectorAll<HTMLElement>('[data-scope="menu"][data-part="item"]')].map(+ (item) => item.textContent+ );++ // The row's button says it opens a menu, and pressing it does.+ expect(primary.getAttribute('aria-haspopup')).toBe('menu');+ primary.focus();+ await act(() => userEvent.keyboard('{Enter}'));+ await vi.waitFor(() => expect(menuItems()).toEqual(['Show in queue', 'Retry', 'Dismiss notification']));+ expect(primary.getAttribute('aria-expanded')).toBe('true');++ const dismiss = [...document.querySelectorAll<HTMLElement>('[data-scope="menu"][data-part="item"]')].find(+ (item) => item.textContent === 'Dismiss notification'+ )!;+ await act(() => userEvent.click(dismiss));++ expect(+ store()+ .getSnapshot()+ .notifications.map((notification) => notification.title)+ ).toEqual(['Older']);+ // As with the inline Dismiss, focus moves on to the next notice's dismiss.+ await vi.waitFor(() => expect(document.activeElement?.getAttribute('aria-label')).toBe('Dismiss notification'));+ expect(document.activeElement?.closest('[role="listitem"]')?.textContent).toContain('Older');+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsxindex 67fd646681..64250e3ea5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/notifications/NotificationsWidgetView.tsx@@ -1,47 +1,19 @@-import type { WorkbenchNotification, WorkbenchNotificationKind } from '@workbench/projectContracts';import type { WidgetViewProps } from '@workbench/widgetContracts';-import { Badge, HStack, Icon, Stack, Text, VisuallyHidden } from '@chakra-ui/react';-import { queueCommands } from '@features/queue';-import { Button, IconButton } from '@platform/ui/Button';-import { Scrollable } from '@platform/ui/Scrollable';-import { useWorkbenchFocus } from '@workbench/focusRegions';-import { formatRelativeTime } from '@workbench/launchpad/formatRelativeTime';-import { createEditorNotificationActionContext } from '@workbench/shell/notifications/editorNotificationActions';-import {- resolveNotificationActions,- type NotificationActionContext,-} from '@workbench/shell/notifications/notificationActions';-import { resolveNotificationText } from '@workbench/shell/notifications/notificationToasts';-import { hasNotificationUndo, subscribeNotificationUndos } from '@workbench/shell/notifications/undoRegistry';+import { Box, Flex, HStack, Spinner } from '@chakra-ui/react';+import { ListSectionHeader } from '@platform/ui/list/ListSectionHeader';import { StatusWidgetChip } from '@workbench/widget-frame';-import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSelector } from '@workbench/WorkbenchContext';-import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';-import {- BellIcon,- CircleCheckIcon,- CircleXIcon,- InfoIcon,- TriangleAlertIcon,- XIcon,- type LucideIcon,-} from 'lucide-react';-import { memo, useCallback, useMemo, useRef, useSyncExternalStore } from 'react';+import { useWorkbenchSelector } from '@workbench/WorkbenchContext';+import { BellIcon, TriangleAlertIcon } from 'lucide-react';+import { lazy, Suspense } from 'react';import { useTranslation } from 'react-i18next';import { NotificationsHeaderActions } from './NotificationsHeaderActions';-const kindColorPalette: Record<WorkbenchNotificationKind, string> = {- error: 'red',- info: 'blue',- success: 'green',-};--const kindIcon = {- error: CircleXIcon,- info: InfoIcon,- success: CircleCheckIcon,-} satisfies Record<WorkbenchNotificationKind, LucideIcon>;+/** The list loads when it is first shown: the editor boots with the status-bar chip alone. */+const NotificationsList = lazy(() =>+ import('./NotificationsList').then((module) => ({ default: module.NotificationsList }))+);export const NotificationsWidgetView = ({ presentation, region }: WidgetViewProps) => {const { t } = useTranslation();@@ -60,234 +32,44 @@ export const NotificationsWidgetView = ({ presentation, region }: WidgetViewPropreturn <StatusWidgetChip icon={icon}>{t('notifications.labelWithCount', { label })}</StatusWidgetChip>;}- // The popover renders the view bare (no widget-frame header), so the header- // actions that frame would have mounted live here instead.+ const list = (+ <Suspense fallback={LIST_PENDING}>+ <NotificationsList />+ </Suspense>+ );++ // The popover renders the view bare (no widget-frame header), so the header actions that frame would have mounted+ // live here instead, styled as the list's section header and lined up with its rows.if (region === 'popover') {return (- <Stack flex="1" gap="0" minH="0">- <HStack borderBottomWidth="1px" borderColor="border.subtle" justify="space-between" px="2" py="1.5">- <Text color="fg.subtle" fontSize="xs" fontWeight="700" textTransform="uppercase">- {t('widgets.labels.notifications')}- </Text>+ <Box display="flex" flex="1" flexDirection="column" minH="0">+ <HStack+ borderBottomWidth="1px"+ borderColor="border.subtle"+ flexShrink={0}+ justify="space-between"+ pe="2.5"+ ps="1.5"+ >+ <ListSectionHeader count={totalCount} label={t('widgets.labels.notifications')} placement="bar" /><NotificationsHeaderActions /></HStack>- <Scrollable minH="0">- <NotificationsPanel />- </Scrollable>- </Stack>+ {list}+ </Box>);}- return <NotificationsPanel />;+ return list;};-/** How long a new notice must be on screen before it counts as read. */-const SEEN_AFTER_MS = 1_500;--/** Share of a card that must show for it to count as seen. */-const SEEN_THRESHOLD = 0.5;--const NotificationsPanel = () => {- const { i18n, t } = useTranslation();- const notifications = useWorkbenchSelector((snapshot) => snapshot.notifications);- const commands = useWorkbenchCommands();- const queries = useWorkbenchQueries();- const focus = useWorkbenchFocus();- const { getWidgetById, getWidgetsForRegion } = useWorkbenchWidgetRegistry();- const panelRef = useRef<HTMLDivElement>(null);- // The same buttons the toasts offer, resolved against this editor at render time.- const actionContext = useMemo(- () =>- createEditorNotificationActionContext({- focus,- getWidgetById,- getWidgetsForRegion,- notifications: commands.notifications,- queries,- retryQueueItems: queueCommands.retryItems,- t: i18n.t,- widgets: commands.widgets,- }),- [commands, focus, getWidgetById, getWidgetsForRegion, i18n, queries]- );- /**- * Focus moves to the next notice's dismiss, else the previous one's. With none left the header's buttons are- * disabled, so it lands on the list itself, which then shows the empty state and draws a focus ring.- */- const dismiss = useCallback(- (notificationId: string) => {- const buttons = [...(panelRef.current?.querySelectorAll<HTMLButtonElement>('[data-notification-dismiss]') ?? [])];- const index = buttons.findIndex((button) => button.dataset.notificationDismiss === notificationId);-- (buttons[index + 1] ?? buttons[index - 1] ?? panelRef.current)?.focus();- commands.notifications.dismiss(notificationId);- },- [commands]- );- const markSeen = useCallback(- (notificationId: string) => commands.notifications.markRead([notificationId]),- [commands]- );+const NotificationsListPending = () => {+ const { t } = useTranslation();return (- <Stack- ref={panelRef}- aria-label={t('widgets.labels.notifications')}- flex="1"- focusVisibleRing="inside"- gap="3"- minH="0"- p="2"- tabIndex={-1}- >- {notifications.length === 0 ? (- <Text color="fg.subtle" fontSize="xs">- {t('notifications.empty')}- </Text>- ) : (- <Stack aria-label={t('widgets.labels.notifications')} as="ul" gap="2" listStyle="none">- {notifications.map((notification) => (- <NotificationCard- key={notification.id}- actionContext={actionContext}- notification={notification}- onDismiss={dismiss}- onSeen={markSeen}- />- ))}- </Stack>- )}- </Stack>+ <Flex align="center" aria-label={t('common.loading')} flex="1" justify="center" py="6" role="status">+ <Spinner color="fg.subtle" size="md" />+ </Flex>);};-const NotificationCard = memo(- ({- actionContext,- notification,- onDismiss,- onSeen,- }: {- actionContext: NotificationActionContext;- notification: WorkbenchNotification;- onDismiss: (notificationId: string) => void;- onSeen: (notificationId: string) => void;- }) => {- const { t } = useTranslation();- /**- * Seeing a notice is reading it: an unread card that stays at least half on screen for a moment becomes read. One- * scrolled out of view, or a glance shorter than that (a StrictMode remount included), leaves it new.- */- const watchSeen = useCallback(- (node: HTMLElement | null) => {- if (!node || notification.isRead) {- return;- }-- let timer: ReturnType<typeof setTimeout> | undefined;- const observer = new IntersectionObserver(- ([entry]) => {- if (entry && entry.isIntersecting && entry.intersectionRatio >= SEEN_THRESHOLD) {- timer ??= setTimeout(() => onSeen(notification.id), SEEN_AFTER_MS);- } else {- clearTimeout(timer);- timer = undefined;- }- },- // Crossing either mark reports; a card sliding under half visible stops its clock.- { threshold: [0, SEEN_THRESHOLD] }- );-- observer.observe(node);-- return () => {- observer.disconnect();- clearTimeout(timer);- };- },- [notification.id, notification.isRead, onSeen]- );- // Undo closures live outside workbench state: re-render when this notice's go (run elsewhere, withdrawn).- const getOfferedUndoCount = useCallback(- () =>- notification.actions?.filter((action) => action.kind === 'undo' && hasNotificationUndo(action.undoId)).length ??- 0,- [notification.actions]- );- useSyncExternalStore(subscribeNotificationUndos, getOfferedUndoCount, getOfferedUndoCount);- const { message, title } = resolveNotificationText(notification, actionContext.t);- const actions = resolveNotificationActions(notification.actions ?? [], actionContext);- const repeats = notification.occurrenceCount ?? 1;- const IconComponent = kindIcon[notification.kind];- const dismiss = useCallback(() => onDismiss(notification.id), [notification.id, onDismiss]);-- return (- <Stack- ref={watchSeen}- as="li"- bg={notification.isRead ? 'bg.subtle' : 'bg.muted'}- borderWidth="1px"- borderColor={notification.isRead ? 'border.subtle' : 'border.emphasized'}- gap="1"- p="2"- rounded="md"- >- <HStack align="start" gap="2" justify="space-between">- <HStack align="start" gap="2" minW="0">- <Icon- as={IconComponent}- boxSize="3.5"- color={`${kindColorPalette[notification.kind]}.300`}- flexShrink={0}- mt="0.5"- />- <Text fontSize="xs" fontWeight="700" overflowWrap="anywhere">- <VisuallyHidden>{`${t(`notifications.kind.${notification.kind}`)}: `}</VisuallyHidden>- {title}- </Text>- {repeats > 1 ? (- <Badge- colorPalette={kindColorPalette[notification.kind]}- flexShrink={0}- fontVariantNumeric="tabular-nums"- >- {t('notifications.repeatCount', { count: repeats })}- </Badge>- ) : null}- </HStack>- <IconButton- aria-label={t('common.dismissNotification')}- color="fg.muted"- data-notification-dismiss={notification.id}- flexShrink={0}- size="xs"- tooltip={t('common.dismissNotification')}- variant="ghost"- onClick={dismiss}- >- <Icon as={XIcon} boxSize="3" />- </IconButton>- </HStack>- {message ? (- <Text color="fg.subtle" fontSize="xs" overflowWrap="anywhere">- {message}- </Text>- ) : null}- <HStack flexWrap="wrap" gap="2" justify="space-between">- <Text asChild color="fg.subtle" fontSize="xs">- <time dateTime={notification.createdAt}>{formatRelativeTime(notification.createdAt)}</time>- </Text>- {actions.length > 0 ? (- <HStack flexWrap="wrap" gap="1">- {actions.map((action) => (- <Button key={action.label} size="xs" variant="outline" onClick={action.onClick}>- {action.label}- </Button>- ))}- </HStack>- ) : null}- </HStack>- </Stack>- );- }-);+const LIST_PENDING = <NotificationsListPending />;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsxindex deb8b55bf3..875c607684 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewActionStrip.tsx@@ -4,9 +4,10 @@ import type { ImageActions, ImageContextMenuVariant } from '@workbench/image-actimport { Icon, HStack, Menu, Portal } from '@chakra-ui/react';import { galleryImageItemToGalleryImage, isGalleryImageItem, toGalleryItemRef } from '@features/gallery/contracts';import { canCopyImage } from '@platform/browser/clipboard';-import { Button, IconButton } from '@platform/ui/Button';+import { Button, IconButton, ToggleIconButton } from '@platform/ui/Button';import { MenuContent } from '@platform/ui/Menu';import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { releaseFocusOnRemoval } from '@workbench/focusRegions';import {ImageContinueGroup,ImageUseGroups,@@ -23,7 +24,7 @@ import {StarIcon,type LucideIcon,} from 'lucide-react';-import { useCallback, useMemo, useState, type ComponentProps, type MouseEvent } from 'react';+import { useCallback, useMemo, useState, type ComponentProps, type MouseEvent, type Ref } from 'react';import { useTranslation } from 'react-i18next';import type { PreviewDensity } from './previewDensity';@@ -42,15 +43,21 @@ const STAR_LABEL_KEYS = {export const PreviewActionStrip = ({actions,density,+ getRegion,isVideoFrameCopyAvailable = false,item,+ onCancelCompare,onCopyCurrentFrame,onOpenMenu,}: {actions: ImageActions;density: PreviewDensity;+ /** Preview's focusable region, which takes focus from the ⋮ when a later render removes it. */+ getRegion?: () => HTMLElement | null;isVideoFrameCopyAvailable?: boolean;item: GalleryItem;+ /** Set only while Select for compare waits for a second image, which shows it pressed; switches it off. */+ onCancelCompare?: () => void;onCopyCurrentFrame?: () => void;/** Opens the view's image context menu at viewport coordinates, leaving out what the strip already offers. */onOpenMenu: ((x: number, y: number, variant: ImageContextMenuVariant) => void) | null;@@ -61,7 +68,17 @@ export const PreviewActionStrip = ({() => void actions.setItemsStarred([toGalleryItemRef(item)], !item.starred),[actions, item]);- const selectForCompare = useCallback(() => image && actions.selectForCompare(image), [actions, image]);+ const isCompareArmed = onCancelCompare !== undefined;+ const toggleCompare = useCallback(+ (checked: boolean) => {+ if (!checked) {+ onCancelCompare?.();+ } else if (image) {+ actions.selectForCompare(image);+ }+ },+ [actions, image, onCancelCompare]+ );const copyCurrentFrame = useCallback(() => onCopyCurrentFrame?.(), [onCopyCurrentFrame]);const hasItemMenus = density !== 'minimal';const openMenu = useCallback(@@ -80,8 +97,18 @@ export const PreviewActionStrip = ({</IconButton></Tooltip>);+ // Focus comes back to the ⋮ when its menu closes, and the strip goes with the selection.+ const menuButtonRef = useCallback(+ (node: HTMLButtonElement | null) => (node && getRegion ? releaseFocusOnRemoval(node, getRegion) : undefined),+ [getRegion]+ );const menuButton = onOpenMenu ? (- <StripIconButton icon={EllipsisVerticalIcon} label={t('widgets.preview.imageActions')} onClick={openMenu} />+ <StripIconButton+ ref={menuButtonRef}+ icon={EllipsisVerticalIcon}+ label={t('widgets.preview.imageActions')}+ onClick={openMenu}+ />) : null;if (density === 'compact') {@@ -110,7 +137,17 @@ export const PreviewActionStrip = ({{image ? <EditMenu actions={actions} image={image} /> : null}<UseMenu actions={actions} item={item} />{image ? (- <StripIconButton icon={ImagesIcon} label={t('widgets.preview.selectForCompare')} onClick={selectForCompare} />+ // A fixed name with the state in aria-pressed, as the routing lock is: pressed, it waits for a second image.+ <ToggleIconButton+ bg={isCompareArmed ? 'accent.subtle' : undefined}+ checked={isCompareArmed}+ color={isCompareArmed ? 'accent.fg' : 'fg.muted'}+ icon={ImagesIcon}+ label={t('widgets.preview.selectForCompare')}+ tooltip={isCompareArmed ? t('widgets.preview.compareArmedTooltip') : undefined}+ variant="ghost"+ onCheckedChange={toggleCompare}+ />) : null}{starButton}{item.kind === 'video' && onCopyCurrentFrame ? (@@ -270,16 +307,19 @@ const StripIconButton = ({disabled,icon,label,+ ref,unavailableReason,onClick,}: {disabled?: boolean;icon: LucideIcon;label: string;+ ref?: Ref<HTMLButtonElement>;unavailableReason?: string;onClick: (event: MouseEvent<HTMLButtonElement>) => void;}) => (<IconButton+ ref={ref}aria-label={label}color="fg.muted"disabled={disabled}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsxindex b035e77fed..ac2f3cb9cb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.browser.test.tsx@@ -8,6 +8,7 @@ import type { WidgetRuntimeApi } from '@workbench/widgetContracts';import { ChakraProvider } from '@chakra-ui/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';+import { WHEEL_ZOOM_STEP } from '@workbench/panZoom';import { createInstance } from 'i18next';import { act, useCallback, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -164,10 +165,12 @@ const clearMouseHover = (element: HTMLElement): Promise<void> =>const renderComparison = async ({baseImage = createImage('base', 1200, 800),+ compareImage = createImage('compare', 800, 1200),initialMode = 'hover',withDetails = false,}: {baseImage?: GeneratedImageContract;+ compareImage?: GeneratedImageContract;initialMode?: PreviewComparisonMode;withDetails?: boolean;} = {}) => {@@ -175,8 +178,13 @@ const renderComparison = async ({const onExit = vi.fn();const onModeChange = vi.fn();const onSwap = vi.fn();- const compareImage = createImage('compare', 800, 1200);- const Harness = () => {+ const Harness = ({+ baseImage,+ compareImage,+ }: {+ baseImage: GeneratedImageContract;+ compareImage: GeneratedImageContract;+ }) => {const [mode, setMode] = useState(initialMode);const handleModeChange = useCallback((nextMode: PreviewComparisonMode) => {setMode(nextMode);@@ -196,25 +204,30 @@ const renderComparison = async ({);};+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ /** Renders the pair into the same tree, so a new pair reaches the mounted comparison as a selection change does. */+ const showPair = (pair: { base: GeneratedImageContract; compare: GeneratedImageContract }) =>+ interact(() => {+ root?.render(+ <QueryClientProvider client={queryClient}>+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ {withDetails ? <OpenDetails /> : null}+ <Harness baseImage={pair.base} compareImage={pair.compare} />+ </ChakraProvider>+ </I18nextProvider>+ </QueryClientProvider>+ );+ });+host = document.createElement('div');host.style.height = '500px';host.style.width = '800px';document.body.append(host);root = createRoot(host);- await interact(() => {- root?.render(- <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>- <I18nextProvider i18n={i18n}>- <ChakraProvider value={system}>- {withDetails ? <OpenDetails /> : null}- <Harness />- </ChakraProvider>- </I18nextProvider>- </QueryClientProvider>- );- });+ await showPair({ base: baseImage, compare: compareImage });- return { commandHandlers, onExit, onModeChange, onSwap };+ return { commandHandlers, onExit, onModeChange, onSwap, showPair };};afterEach(async () => {@@ -272,6 +285,175 @@ describe('PreviewCompare', () => {expect(onExit).toHaveBeenCalledOnce();});+ describe('zoom with differently sized images', () => {+ /** Parses `translate(Xpx, Ypx) scale(S)` into fractions of the image's frame, so differently sized panes compare. */+ const readFractionTransform = (image: HTMLImageElement) => {+ const frame = image.parentElement!;+ const match = /translate\((-?[\d.]+)px, (-?[\d.]+)px\) scale\(([\d.]+)\)/.exec(image.style.transform);++ if (!match) {+ return null;+ }++ return {+ fx: Number(match[1]) / frame.clientWidth,+ fy: Number(match[2]) / frame.clientHeight,+ scale: Number(match[3]),+ };+ };+ /** Both panes show the same region of their own picture: equal scale and equal frame-relative pan. */+ const expectLinked = (first: HTMLImageElement, second: HTMLImageElement) => {+ const a = readFractionTransform(first);+ const b = readFractionTransform(second);++ expect(a).not.toBeNull();+ expect(b?.scale).toBeCloseTo(a!.scale, 3);+ expect(b?.fx).toBeCloseTo(a!.fx, 3);+ expect(b?.fy).toBeCloseTo(a!.fy, 3);+ };+ const getImages = () => ({+ base: host!.querySelector<HTMLImageElement>('img[alt="base"]')!,+ compare: host!.querySelector<HTMLImageElement>('img[alt="compare"]')!,+ });+ const wheelAt = (frame: HTMLElement, fractionX: number, fractionY: number, deltaY: number) => {+ const rect = frame.getBoundingClientRect();++ frame.dispatchEvent(+ new WheelEvent('wheel', {+ bubbles: true,+ cancelable: true,+ clientX: rect.left + rect.width * fractionX,+ clientY: rect.top + rect.height * fractionY,+ deltaY,+ })+ );+ };+ const mouse = (target: HTMLElement, type: string, clientX: number, clientY: number) =>+ target.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ button: type === 'pointermove' ? -1 : 0,+ cancelable: true,+ clientX,+ clientY,+ isPrimary: true,+ pointerId: 1,+ pointerType: 'mouse',+ })+ );++ it('links wheel zoom, pan, and reset across side-by-side panes of different sizes and aspect ratios', async () => {+ // 1200×800 landscape beside 800×1200 portrait.+ await renderComparison({ initialMode: 'side-by-side' });+ const { base, compare } = getImages();+ const baseFrame = base.parentElement!;+ const compareFrame = compare.parentElement!;++ expect(baseFrame.clientWidth).not.toBe(compareFrame.clientWidth);++ // Zoom ×2 around a point three quarters across, one quarter down the landscape pane.+ await interact(() => wheelAt(baseFrame, 0.75, 0.25, -Math.log(2) / WHEEL_ZOOM_STEP));+ const zoomed = readFractionTransform(base);++ expect(zoomed?.scale).toBeCloseTo(2, 3);+ // The point under the cursor stays put: f + scale * 0.75 = 0.75.+ expect(zoomed?.fx).toBeCloseTo(-0.75, 3);+ expect(zoomed?.fy).toBeCloseTo(-0.25, 3);+ expectLinked(base, compare);++ // Drag the portrait pane by a tenth of its own width: both pictures follow by the same share of their frames.+ const rect = compareFrame.getBoundingClientRect();+ const startX = rect.left + rect.width / 2;+ const startY = rect.top + rect.height / 2;++ await interact(() => mouse(compareFrame, 'pointerdown', startX, startY));+ const tenth = compareFrame.clientWidth / 10;++ await interact(() => mouse(compareFrame, 'pointermove', startX + tenth, startY));+ await interact(() => mouse(compareFrame, 'pointerup', startX + tenth, startY));+ const panned = readFractionTransform(compare);++ expect(panned?.scale).toBeCloseTo(2, 3);+ expect(panned?.fx).toBeCloseTo(-0.65, 3);+ expect(panned?.fy).toBeCloseTo(-0.25, 3);+ expectLinked(compare, base);++ // Double-click resets both panes to fit.+ await interact(() =>+ baseFrame.dispatchEvent(new MouseEvent('dblclick', { bubbles: true, clientX: startX, clientY: startY }))+ );+ expect(base.style.transform).toBe('');+ expect(compare.style.transform).toBe('');+ });++ it('caps zoom where the sharper image reaches eight times its own pixels', async () => {+ // A 300×200 image beside the 800×1200 one: the larger image sets the limit.+ await renderComparison({ baseImage: createImage('base', 300, 200), initialMode: 'side-by-side' });+ const { base, compare } = getImages();+ const compareFrame = compare.parentElement!;++ await interact(() => wheelAt(compareFrame, 0.5, 0.5, -Math.log(1000) / WHEEL_ZOOM_STEP));++ expect(readFractionTransform(compare)?.scale).toBeCloseTo((8 * 800) / compareFrame.clientWidth, 3);+ expectLinked(compare, base);+ // Past 2× of its own pixels, each pane renders crisp pixels by its own resolution.+ expect(base.style.imageRendering).toBe('pixelated');+ });++ it('keeps the zoom on a new selection against the same comparison image, within the new pair’s limit', async () => {+ const compareImage = createImage('compare', 512, 512);+ const { showPair } = await renderComparison({+ baseImage: createImage('large', 4096, 4096),+ compareImage,+ initialMode: 'side-by-side',+ });+ const compareFrame = getImages().compare.parentElement!;++ // Zoom to the 4096px image's cap, a quarter of the way across.+ await interact(() => wheelAt(compareFrame, 0.25, 0.5, -Math.log(1000) / WHEEL_ZOOM_STEP));+ expect(readFractionTransform(getImages().compare)?.scale).toBeCloseTo((8 * 4096) / compareFrame.clientWidth, 3);++ await showPair({ base: createImage('base', 512, 512), compare: compareImage });+ const { base, compare } = getImages();+ const limit = (8 * 512) / compareFrame.clientWidth;+ const kept = readFractionTransform(compare);++ expect(kept?.scale).toBeCloseTo(limit, 3);+ // Clamping zooms out around the view's centre, so the region in view stays where it was.+ expect((0.5 - kept!.fx) / kept!.scale).toBeCloseTo(0.25, 2);+ expectLinked(compare, base);+ expect(getComputedStyle(base.parentElement!).cursor).toBe('grab');+ });++ it('opens a wholly new pair at fit', async () => {+ const { showPair } = await renderComparison({ initialMode: 'side-by-side' });+ const baseFrame = getImages().base.parentElement!;++ await interact(() => wheelAt(baseFrame, 0.5, 0.5, -Math.log(2) / WHEEL_ZOOM_STEP));+ expect(readFractionTransform(getImages().base)?.scale).toBeCloseTo(2, 3);++ await showPair({ base: createImage('next-base', 1200, 800), compare: createImage('next-compare', 800, 1200) });++ expect(host!.querySelector<HTMLImageElement>('img[alt="next-base"]')!.style.transform).toBe('');+ expect(host!.querySelector<HTMLImageElement>('img[alt="next-compare"]')!.style.transform).toBe('');+ expect(getComputedStyle(host!.querySelector('img[alt="next-base"]')!.parentElement!).cursor).not.toBe('grab');+ });++ it('keeps the zoom when the pair swaps sides', async () => {+ const baseImage = createImage('base', 1200, 800);+ const compareImage = createImage('compare', 800, 1200);+ const { showPair } = await renderComparison({ baseImage, compareImage, initialMode: 'side-by-side' });++ await interact(() => wheelAt(getImages().base.parentElement!, 0.75, 0.25, -Math.log(2) / WHEEL_ZOOM_STEP));+ await showPair({ base: compareImage, compare: baseImage });+ const { base, compare } = getImages();++ expect(readFractionTransform(base)?.scale).toBeCloseTo(2, 3);+ expect(readFractionTransform(base)?.fx).toBeCloseTo(-0.75, 3);+ expectLinked(base, compare);+ });+ });+it.each([['portrait', 400, 1600],['panorama', 1600, 400],diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsxindex ceb2ac2b10..7c4a8bc6a8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx@@ -2,7 +2,7 @@ import type { GeneratedImageContract } from '@features/gallery';import type { WidgetRuntimeApi } from '@workbench/widgetContracts';import { Badge, Box, Flex, HStack, SegmentGroup, Stack } from '@chakra-ui/react';-import { Button } from '@platform/ui';+import { Button, IconButton } from '@platform/ui/Button';import { ArrowLeftRightIcon, XIcon } from 'lucide-react';import {useCallback,@@ -18,8 +18,9 @@ import { useTranslation } from 'react-i18next';import type { PreviewComparisonMode } from './previewSettings';-import { previewStageStore } from './previewHeaderStore';-import { getFittedFrameCss, PreviewStage } from './PreviewStage';+import { getPreviewDockBarHeight, PREVIEW_DOCK_BAR_PROPS } from './previewDockBar';+import { previewStageStore, usePreviewStageDensity } from './previewHeaderStore';+import { getFittedFrameCss, getPreviewStagePadding, PreviewStage } from './PreviewStage';import { useCompareLoupe, type CompareLoupePane } from './useCompareLoupe';const { setStageElement } = previewStageStore;@@ -74,15 +75,19 @@ export const PreviewCompare = ({runtime: WidgetRuntimeApi;}) => {const { t } = useTranslation();+ // Full until the view has measured, as the view itself first guesses.+ const density = usePreviewStageDensity() ?? 'full';const [dividerPercent, setDividerPercent] = useState(50);const containerRef = useRef<HTMLDivElement | null>(null);const isDraggingRef = useRef(false);- // Zoom-synced side-by-side: one shared transform drives both panes. Gated to- // matching-dimension pairs, where fraction-space sync is exact.- const dimensionsMatch = baseImage.width === compareImage.width && baseImage.height === compareImage.height;+ // Zoom-synced side-by-side: one shared pane-fraction transform drives both panes, so it links any pair of sizes.const compareLoupe = useCompareLoupe({- enabled: mode === 'side-by-side' && dimensionsMatch,- naturalWidth: baseImage.width,+ enabled: mode === 'side-by-side',+ // Pane order: the comparison image left, the selection right.+ images: [+ { id: compareImage.imageName, naturalWidth: compareImage.width },+ { id: baseImage.imageName, naturalWidth: baseImage.width },+ ],});const nextMode = useEffectEvent(() => onModeChange(getNextPreviewComparisonMode(mode)));const nextComparisonModeLabel = t('widgets.preview.commands.nextComparisonMode');@@ -155,9 +160,9 @@ export const PreviewCompare = ({const clipStyle = useMemo(() => ({ clipPath: `inset(0 ${100 - dividerPercent}% 0 0)` }), [dividerPercent]);return (- <Stack gap="3" h="full" minH="0" w="full">+ <Stack gap="0" h="full" minH="0" w="full">{/* Details pins to this stage, above the mode controls, as it pins to the single item's. */}- <PreviewStage ref={setStageElement} fill="flex" padding="6">+ <PreviewStage ref={setStageElement} fill="flex" padding={getPreviewStagePadding(density)}>{mode === 'slider' ? (// Use a plain frame for capture/drag behavior without introducing FittedFrame's shadow.<Box@@ -224,7 +229,19 @@ export const PreviewCompare = ({</HStack>)}</PreviewStage>- <HStack flexShrink={0} gap="1" justify="center">+ {/* Docked where the filmstrip docks, on the same surface. Narrow widths turn swap and exit into icons, then wrap;+ `safe` keeps a row wider than the bar scrollable from its start. */}+ <Flex+ {...PREVIEW_DOCK_BAR_PROPS}+ align="center"+ columnGap="1"+ flexWrap="wrap"+ justify="safe center"+ minH={getPreviewDockBarHeight(density)}+ overflowX="auto"+ py="1"+ rowGap="1"+ ><SegmentGroup.Root value={mode} onValueChange={handleModeChange}><SegmentGroup.Indicator />{COMPARISON_MODES.map((item) => (@@ -234,15 +251,42 @@ export const PreviewCompare = ({</SegmentGroup.Item>))}</SegmentGroup.Root>- <Button size="sm" variant="outline" onClick={onSwap}>- <ArrowLeftRightIcon />- {t('common.swap')}- </Button>- <Button size="sm" variant="outline" onClick={onExit}>- <XIcon />- {t('widgets.preview.exitCompare')}- </Button>- </HStack>+ {density === 'full' ? (+ <>+ <Button size="sm" variant="outline" onClick={onSwap}>+ <ArrowLeftRightIcon />+ {t('common.swap')}+ </Button>+ <Button size="sm" variant="outline" onClick={onExit}>+ <XIcon />+ {t('widgets.preview.exitCompare')}+ </Button>+ </>+ ) : (+ <>+ <IconButton+ aria-label={t('common.swap')}+ size="sm"+ tooltip={t('common.swap')}+ tooltipPlacement="top"+ variant="outline"+ onClick={onSwap}+ >+ <ArrowLeftRightIcon />+ </IconButton>+ <IconButton+ aria-label={t('widgets.preview.exitCompare')}+ size="sm"+ tooltip={t('widgets.preview.exitCompare')}+ tooltipPlacement="top"+ variant="outline"+ onClick={onExit}+ >+ <XIcon />+ </IconButton>+ </>+ )}+ </Flex></Stack>);};@@ -401,12 +445,12 @@ const CompareSidePane = ({cursor={isZoomed ? 'grab' : undefined}overflow="hidden"position="relative"- // Suppress native pan/pinch only when the shared loupe can replace them; mismatched dimensions retain- // browser gestures.+ // Suppress native pan/pinch only when the shared loupe replaces them.touchAction={pane ? 'none' : undefined}{...pane?.frameProps}><img+ key={image.imageName}ref={pane?.imageRefCallback}alt={image.imageName}draggable={false}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsxindex 416a69e535..ba10cb0039 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompareDropZone.tsx@@ -1,7 +1,7 @@-import { Badge } from '@chakra-ui/react';import { useDndContext, useDroppable } from '@dnd-kit/core';import { isGalleryImageDragData } from '@features/gallery/utility';import { DropZone } from '@platform/ui/DropZone';+import { DropZoneLabel } from '@workbench/widgets/shared/DropZoneLabel';import { useTranslation } from 'react-i18next';import { PREVIEW_COMPARE_DROP_DATA, PREVIEW_COMPARE_DROP_ID } from './previewCompareDnd';@@ -40,7 +40,7 @@ export const PreviewCompareDropZone = ({ currentImageName }: { currentImageName:variant="overlay"zIndex="2">- <Badge variant="subtle">{t('widgets.preview.dropToCompare')}</Badge>+ <DropZoneLabel>{t('widgets.preview.dropToCompare')}</DropZoneLabel></DropZone>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPanel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPanel.tsxindex 56ca078d81..89317ea604 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPanel.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDetailsPanel.tsx@@ -5,6 +5,7 @@ import { Box, chakra, HStack, Text, VisuallyHidden } from '@chakra-ui/react';import { formatGalleryVideoDuration, toGalleryItemKey, toGalleryItemRef } from '@features/gallery/contracts';import { imageIndexAvailabilityOptions } from '@features/gallery/queries';import { useAuthSession } from '@features/identity';+import { isEventFromOwnDom } from '@platform/react/isEventFromOwnDom';import { ToggleIconButton } from '@platform/ui/Button';import { useQuery } from '@tanstack/react-query';import { useWorkbenchFocus } from '@workbench/focusRegions';@@ -114,11 +115,13 @@ export const PreviewDetailsPanel = ({event.key !== 'Escape' ||event.defaultPrevented ||event.nativeEvent.isComposing ||- !(event.target instanceof Node && event.currentTarget.contains(event.target))+ !isEventFromOwnDom(event)) {return;}event.preventDefault();+ // The press is the panel's alone: Preview's own Esc (cancelling or closing a comparison) must not also take it.+ event.stopPropagation();onOpenChange(false);},[onOpenChange]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDropSurface.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDropSurface.browser.test.tsxnew file mode 100644index 0000000000..c2f708ba9d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDropSurface.browser.test.tsx@@ -0,0 +1,446 @@+import type { GalleryBoard } from '@features/gallery';+import type * as GalleryBackend from '@features/gallery/data/backend';+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';+import type { ReactNode } from 'react';++import { ChakraProvider } from '@chakra-ui/react';+import {+ getGalleryCompareImage,+ getSelectedGalleryItemFromValues,+ type GalleryImage,+ type GalleryItemKind,+ type GalleryVideoItem,+} from '@features/gallery/contracts';+import { TINY_PNG_BASE64 } from '@platform/browser/nativeDrag.testing';+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { getProjectWidgetValues } from '@workbench/widgetState';+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 { commands, page } from 'vitest/browser';++/** The surface drives the real workbench store; the gallery transport is the only double. */+const harness = vi.hoisted(() => ({+ boards: [] as GalleryBoard[],+ store: null as ReturnType<typeof createWorkbenchStore> | null,+ uploadImage: vi.fn<(file: File, boardId: string) => Promise<GalleryImage>>(),+ uploadVideo: vi.fn<(file: File, boardId: string) => Promise<GalleryVideoItem>>(),+}));++vi.mock('@features/gallery/data/backend', async (importOriginal) => ({+ ...(await importOriginal<typeof GalleryBackend>()),+ listGalleryBoards: () => Promise.resolve(harness.boards),+ uploadGalleryImage: (file: File, boardId: string) => harness.uploadImage(file, boardId),+ uploadGalleryVideo: (file: File, boardId: string) => harness.uploadVideo(file, boardId),+}));+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useWorkbenchCommands: () => harness.store!.commands,+ useWorkbenchQueries: () => harness.store!.queries,+}));++import { PreviewDropSurface } from './PreviewDropSurface';++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();+ Object.assign(harness, { boards: [], store: null });+ harness.uploadImage.mockReset();+ harness.uploadVideo.mockReset();+ root = null;+ host = null;+});++const imageFile = (name: string) =>+ new File([Uint8Array.from(atob(TINY_PNG_BASE64), (char) => char.charCodeAt(0))], name, { type: 'image/png' });+const videoFile = (name: string) => new File(['clip'], name, { type: 'video/mp4' });+const storedImage = (file: { name: string }, createdAt: string, boardId = 'none'): GalleryImage => ({+ boardId,+ createdAt,+ height: 2,+ imageCategory: 'user',+ imageName: `stored-${file.name}`,+ imageUrl: `/images/stored-${file.name}`,+ queuedAt: createdAt,+ sourceQueueItemId: 'upload',+ starred: false,+ thumbnailUrl: `/thumbnails/stored-${file.name}`,+ width: 2,+});+const storedVideo = (file: { name: string }, createdAt: string): GalleryVideoItem => ({+ boardId: 'none',+ category: 'user',+ createdAt,+ durationSeconds: 1,+ fullUrl: `/videos/stored-${file.name}`,+ height: 64,+ isIntermediate: false,+ kind: 'video',+ name: `stored-${file.name}`,+ starred: false,+ thumbnailUrl: `/thumbnails/stored-${file.name}`,+ width: 64,+});+// The first drop loads the upload code; a cold transform can take longer than `waitFor`'s default second.+const LANDED = { timeout: 5_000 };++const render = async ({+ children,+ fillsFrame = false,+ galleryValues,+ isComparing = false,+ isFollowingLive = false,+ shownKind = null,+}: {+ /** Rendered inside the surface after its content, such as a dialog it opened. */+ children?: ReactNode;+ /** Covers the whole test frame, so a centred dialog lies over the surface. */+ fillsFrame?: boolean;+ galleryValues?: Record<string, unknown>;+ isComparing?: boolean;+ isFollowingLive?: boolean;+ shownKind?: GalleryItemKind | null;+} = {}) => {+ const store = createWorkbenchStore(createInitialWorkbenchState());+ const projectId = store.getState().activeProjectId;+ if (galleryValues) {+ store.commands.widgets.patchValues('gallery', galleryValues);+ }+ harness.store = store;+ host = document.createElement('div');+ Object.assign(+ host.style,+ fillsFrame ? { inset: '0', position: 'fixed' } : { height: '400px', width: `${Math.min(600, window.innerWidth)}px` }+ );+ document.body.append(host);+ root = createRoot(host);+ const queryClient = new QueryClient();+ const renderWith = (extra: ReactNode) =>+ act(() =>+ root!.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <PreviewDropSurface isComparing={isComparing} isFollowingLive={isFollowingLive} shownKind={shownKind}>+ <div data-testid="preview-content" style={{ height: '100%' }} />+ {extra}+ </PreviewDropSurface>+ </QueryClientProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );+ await renderWith(children);+ return { projectId, rerender: renderWith, store };+};++const galleryValuesOf = (store: ReturnType<typeof createWorkbenchStore>, projectId: string) =>+ getProjectWidgetValues(+ store.getState().projects.find((project) => project.id === projectId)!,+ 'gallery'+ );+const selectedName = (store: ReturnType<typeof createWorkbenchStore>, projectId: string) =>+ getSelectedGalleryItemFromValues(galleryValuesOf(store, projectId))?.name ?? null;+const content = () => page.getByTestId('preview-content').element();+const zone = (name: string) => page.getByText(name, { exact: true });+const zoneTarget = (name: string) => zone(name).element().closest('[data-preview-drop-zone]')!;+const transferOf = (files: File[]) => {+ const transfer = new DataTransfer();+ for (const file of files) {+ transfer.items.add(file);+ }+ return transfer;+};+const send = async (type: string, transfer: DataTransfer, init: DragEventInit = {}, target: Element = content()) => {+ const event = new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer: transfer, ...init });+ await act(() => target.dispatchEvent(event));+ return event;+};+const centreOf = (element: Element) => {+ const rect = element.getBoundingClientRect();+ return { clientX: rect.left + rect.width / 2, clientY: rect.top + rect.height / 2 };+};+/** Dispatches a drag over the zone labelled `zoneName` and drops it there, from the test itself. */+const dropOn = async (zoneName: string, files: File[]) => {+ const transfer = transferOf(files);+ await send('dragenter', transfer);+ await expect.element(zone(zoneName)).toBeVisible();+ const at = centreOf(zoneTarget(zoneName));+ await send('dragover', transfer, at);+ return send('drop', transfer, at);+};+/** A confirmation Preview opened, as its delete confirmation is: a React child of the surface, portalled to the body. */+const openConfirmation = () => (+ <ConfirmDialog+ body="This cannot be undone."+ confirmLabel="Delete"+ isOpen+ title="Delete image?"+ onClose={vi.fn()}+ onConfirm={vi.fn()}+ />+);+const confirmation = () => page.getByRole('alertdialog');+/**+ * A real drag from the operating system, through the browser's own drag input, dropped on one half of the surface: the+ * left half shows, the right half compares when comparison is offered.+ */+const nativeDrop = (half: 'left' | 'right', files: { base64: string; name: string }[]) => {+ const rect = content().getBoundingClientRect();+ return commands.nativeDrag({+ files,+ frameWidth: window.innerWidth,+ points: [{ x: rect.left + rect.width * (half === 'left' ? 0.25 : 0.75), y: rect.top + rect.height / 2 }],+ });+};++describe('PreviewDropSurface', () => {+ it('uploads files dropped from the desktop and shows the newest, as an upload in the Gallery does', async () => {+ // Listed after the video, yet the newer of the two: the newest is shown, not the last.+ harness.uploadImage.mockImplementation((file) => Promise.resolve(storedImage(file, '2026-11-10T00:00:02.000Z')));+ harness.uploadVideo.mockImplementation((file) => Promise.resolve(storedVideo(file, '2026-11-10T00:00:01.000Z')));+ const { projectId, store } = await render();++ await nativeDrop('left', [+ { base64: TINY_PNG_BASE64, name: 'still.png' },+ { base64: btoa('clip'), name: 'clip.mp4' },+ ]);++ await vi.waitFor(() => expect(selectedName(store, projectId)).toBe('stored-still.png'), LANDED);+ // To the project's auto-add board (Uncategorized here), each kind by its own route.+ expect(harness.uploadImage.mock.calls.map(([file, boardId]) => [file.name, boardId])).toEqual([+ ['still.png', 'none'],+ ]);+ expect(harness.uploadVideo.mock.calls.map(([file, boardId]) => [file.name, boardId])).toEqual([+ ['clip.mp4', 'none'],+ ]);+ // Selected within its own board, as a pick from Preview's mini gallery is.+ expect(galleryValuesOf(store, projectId).selectedImageQuery).toMatchObject({ boardId: 'none', itemBoard: true });+ expect(store.getState().notifications[0]?.title).toMatch(/^Uploaded 2 /);+ expect(zone('Drop to show').elements()).toHaveLength(0);+ });++ it('compares with a dropped image beside an image shown, as a gallery drag offers', async () => {+ harness.uploadImage.mockImplementation((file) => Promise.resolve(storedImage(file, '2026-11-10T00:00:01.000Z')));+ const { projectId, store } = await render({ shownKind: 'image' });++ await nativeDrop('right', [{ base64: TINY_PNG_BASE64, name: 'other.png' }]);++ await vi.waitFor(+ () => expect(getGalleryCompareImage(galleryValuesOf(store, projectId))?.imageName).toBe('stored-other.png'),+ LANDED+ );+ expect(selectedName(store, projectId)).toBeNull();+ });++ it.each([+ ['live progress is followed', { isFollowingLive: true, shownKind: 'image' as const }],+ ['two images are compared already', { isComparing: true, shownKind: 'image' as const }],+ ['a video is shown', { shownKind: 'video' as const }],+ ['nothing is shown', {}],+ ])('offers no comparison while %s', async (_case, state) => {+ await render(state);++ await send('dragenter', transferOf([imageFile('other.png')]));++ await expect.element(zone('Drop to show')).toBeVisible();+ expect(zone('Drop to compare').elements()).toHaveLength(0);+ });++ it('offers comparison only to a drag that carries an image, reading each new drag afresh', async () => {+ await render({ shownKind: 'image' });++ const videos = transferOf([videoFile('clip.mp4')]);+ await send('dragenter', videos);+ await expect.element(zone('Drop to show')).toBeVisible();+ expect(zone('Drop to compare').elements()).toHaveLength(0);+ await send('dragleave', videos, { relatedTarget: document.body });++ await send('dragenter', transferOf([imageFile('other.png')]));+ await expect.element(zone('Drop to compare')).toBeVisible();+ });++ it('highlights the zone under the files', async () => {+ await render({ shownKind: 'image' });+ const transfer = transferOf([imageFile('other.png')]);++ await send('dragenter', transfer);+ await expect.element(zone('Drop to compare')).toBeVisible();+ await send('dragover', transfer, centreOf(zoneTarget('Drop to compare')));+ expect(zoneTarget('Drop to compare')).toHaveAttribute('data-over');+ expect(zoneTarget('Drop to show')).not.toHaveAttribute('data-over');++ await send('dragover', transfer, centreOf(zoneTarget('Drop to show')));+ expect(zoneTarget('Drop to show')).toHaveAttribute('data-over');+ expect(zoneTarget('Drop to compare')).not.toHaveAttribute('data-over');+ });++ it('uploads to the auto-add board judged from a listing it reads first, not the board the gallery shows', async () => {+ harness.boards = [+ {+ access: { actions: ['add_media'], adminOverride: false, generalAccess: 'restricted', role: 'owner' },+ archived: false,+ assetCount: 0,+ assetVideoCount: 0,+ id: 'board-auto',+ imageCount: 0,+ isInbox: false,+ kind: 'board',+ name: 'Auto',+ projectId: null,+ videoCount: 0,+ },+ ];+ harness.uploadImage.mockImplementation((file, boardId) =>+ Promise.resolve(storedImage(file, '2026-11-10T00:00:01.000Z', boardId))+ );+ const { projectId, store } = await render({+ galleryValues: { autoAddBoardId: 'board-auto', selectedBoardId: 'board-shown' },+ });++ await dropOn('Drop to show', [imageFile('one.png')]);++ await vi.waitFor(() => expect(selectedName(store, projectId)).toBe('stored-one.png'), LANDED);+ expect(harness.uploadImage.mock.calls.map(([, boardId]) => boardId)).toEqual(['board-auto']);+ });++ it('refuses files Preview cannot show with the upload notice, uploading nothing', async () => {+ const { projectId, store } = await render();++ await dropOn('Drop to show', [new File(['notes'], 'notes.txt', { type: 'text/plain' })]);++ await vi.waitFor(+ () =>+ expect(store.getState().notifications[0]).toMatchObject({+ kind: 'error',+ message: 'No supported media files to upload (PNG, JPEG, or WebP images; video files; or audio files).',+ }),+ LANDED+ );+ expect(harness.uploadImage).not.toHaveBeenCalled();+ expect(harness.uploadVideo).not.toHaveBeenCalled();+ expect(selectedName(store, projectId)).toBeNull();+ });++ it('leaves the project switched to alone when an upload lands after the switch', async () => {+ let finishUpload!: () => void;+ harness.uploadImage.mockImplementation(+ (file) =>+ new Promise((resolve) => {+ finishUpload = () => resolve(storedImage(file, '2026-11-10T00:00:01.000Z'));+ })+ );+ const { projectId, store } = await render();++ await dropOn('Drop to show', [imageFile('late.png')]);+ await vi.waitFor(() => expect(harness.uploadImage).toHaveBeenCalledTimes(1), LANDED);+ const switchedTo = await act(() => store.commands.projects.create());+ await act(() => finishUpload());++ await vi.waitFor(() => expect(selectedName(store, projectId)).toBe('stored-late.png'));+ expect(store.getState().activeProjectId).toBe(switchedTo.id);+ expect(selectedName(store, switchedTo.id)).toBeNull();+ });++ it('takes no drop on a confirmation it opened, though React bubbles the drag to it, and drops once it closes', async () => {+ harness.uploadImage.mockImplementation((file) => Promise.resolve(storedImage(file, '2026-11-10T00:00:01.000Z')));+ const { projectId, rerender, store } = await render({ children: openConfirmation(), fillsFrame: true });+ await expect.element(confirmation()).toBeVisible();+ const dialog = confirmation().element().getBoundingClientRect();++ // Over the dialog, which lies over the surface's show zone: a drop there would upload behind the confirmation.+ await commands.nativeDrag({+ files: [{ base64: TINY_PNG_BASE64, name: 'behind.png' }],+ frameWidth: window.innerWidth,+ points: [{ x: dialog.left + dialog.width / 2, y: dialog.top + dialog.height / 2 }],+ });+ expect(zone('Drop to show').elements()).toHaveLength(0);++ await rerender(null);+ expect(document.querySelector('[data-scope="dialog"]')).toBeNull();+ await nativeDrop('left', [{ base64: TINY_PNG_BASE64, name: 'shown.png' }]);++ await vi.waitFor(() => expect(selectedName(store, projectId)).toBe('stored-shown.png'), LANDED);+ // Uploads run in drop order: had the first drop been taken, its file would lead.+ expect(harness.uploadImage.mock.calls.map(([file]) => file.name)).toEqual(['shown.png']);+ });++ it('shows no zones over a confirmation it opened and keeps no drag after passing through it', async () => {+ await render({ children: openConfirmation(), fillsFrame: true });+ await expect.element(confirmation()).toBeVisible();+ const dialog = confirmation().element();+ const dialogTitle = page.getByText('Delete image?').element();+ const transfer = transferOf([imageFile('one.png')]);+ const zonesShown = () => zone('Drop to show').elements().length > 0;+ const over = centreOf(content());++ await send('dragenter', transfer, over);+ expect(zonesShown()).toBe(true);+ // Onto the dialog, then between its own elements: each step reaches the surface through React, none is its own.+ await send('dragleave', transfer, { ...over, relatedTarget: dialog });+ expect(zonesShown()).toBe(false);+ await send('dragenter', transfer, { ...over, relatedTarget: content() }, dialog);+ expect((await send('dragover', transfer, over, dialog)).defaultPrevented).toBe(false);+ await send('dragleave', transfer, { ...over, relatedTarget: dialogTitle }, dialog);+ await send('dragenter', transfer, { ...over, relatedTarget: dialog }, dialogTitle);+ expect(zonesShown()).toBe(false);+ expect((await send('drop', transfer, over, dialogTitle)).defaultPrevented).toBe(false);++ // Back onto the surface: a new drag, which ends as it leaves.+ await send('dragleave', transfer, { ...over, relatedTarget: content() }, dialogTitle);+ await send('dragenter', transfer, { ...over, relatedTarget: dialogTitle });+ expect(zonesShown()).toBe(true);+ await send('dragleave', transfer, { ...over, relatedTarget: document.body });+ expect(zonesShown()).toBe(false);+ expect(harness.uploadImage).not.toHaveBeenCalled();+ });++ it('ends the drag when it leaves Preview or the window, or finishes elsewhere, and ignores drags without files', async () => {+ await render();+ const transfer = transferOf([imageFile('one.png')]);+ const zonesShown = () => zone('Drop to show').elements().length > 0;++ await send('dragenter', transfer);+ expect(zonesShown()).toBe(true);+ await send('dragleave', transfer, { relatedTarget: document.body });+ expect(zonesShown()).toBe(false);++ // Out of the window (or cancelled), after crossing onto an element taken down mid-drag: no leave reports it.+ const doomed = document.createElement('div');+ content().append(doomed);+ await send('dragenter', transfer);+ await send('dragenter', transfer, { relatedTarget: content() }, doomed);+ doomed.remove();+ await send('dragleave', transfer, { relatedTarget: null });+ await vi.waitFor(() => expect(zonesShown()).toBe(false));++ await send('dragenter', transfer);+ await act(() => document.body.dispatchEvent(new DragEvent('drop', { bubbles: true, dataTransfer: transfer })));+ expect(zonesShown()).toBe(false);+ await send('dragenter', transfer);+ await act(() => window.dispatchEvent(new DragEvent('dragend')));+ expect(zonesShown()).toBe(false);++ const text = new DataTransfer();+ text.setData('text/plain', 'words');+ expect((await send('dragenter', text)).defaultPrevented).toBe(false);+ expect((await send('drop', text)).defaultPrevented).toBe(false);+ expect(zonesShown()).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDropSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDropSurface.tsxnew file mode 100644index 0000000000..a77cb236a2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewDropSurface.tsx@@ -0,0 +1,109 @@+import type { GalleryItemKind } from '@features/gallery/contracts';+import type { ReactNode, Ref } from 'react';++import { Box, Flex } from '@chakra-ui/react';+import { classifyGalleryUpload } from '@features/gallery/contracts';+import { findDropZoneAt } from '@platform/browser/dropZones';+import { useNativeFileDrag } from '@platform/react/useNativeFileDrag';+import { DropZone } from '@platform/ui/DropZone';+import { useQueryClient } from '@tanstack/react-query';+import { DropZoneLabel } from '@workbench/widgets/shared/DropZoneLabel';+import { useDroppedFileUpload } from '@workbench/widgets/shared/useDroppedFileUpload';+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++export type PreviewDropZone = 'show' | 'compare';++const PREVIEW_DROP_ZONE_ATTRIBUTE = 'data-preview-drop-zone';++const findPreviewDropZone = (root: Element, point: { clientX: number; clientY: number }): PreviewDropZone | null => {+ const zone = findDropZoneAt(root, PREVIEW_DROP_ZONE_ATTRIBUTE, point);+ return zone === 'show' || zone === 'compare' ? zone : null;+};++// Only an image can be compared; a file the OS gave no type might be one.+const mayBeImage = (type: string): boolean =>+ type === '' || classifyGalleryUpload({ name: '', type })?.kind === 'image';++const PreviewDropZoneTarget = ({ isOver, label, zone }: { isOver: boolean; label: string; zone: PreviewDropZone }) => (+ <DropZone+ alignItems="center"+ data-over={isOver || undefined}+ display="flex"+ flex="1"+ isOver={isOver}+ justifyContent="center"+ minW="0"+ opacity={isOver ? 1 : 0.85}+ rounded="lg"+ variant="overlay"+ {...{ [PREVIEW_DROP_ZONE_ATTRIBUTE]: zone }}+ >+ <DropZoneLabel>{label}</DropZoneLabel>+ </DropZone>+);++/**+ * Preview's root, taking media files dragged in from the operating system. While they hover it shows where they go:+ * shown in Preview, and beside it, while Preview shows an image outside live progress and comparison, the compare zone+ * a gallery drag offers there. A drop uploads them as the Gallery does, then shows them (see `importPreviewFileDrop`,+ * loaded on the first drop to keep uploads out of Preview's startup).+ */+export const PreviewDropSurface = ({+ children,+ isComparing,+ isFollowingLive,+ ref,+ shownKind,+}: {+ children: ReactNode;+ isComparing: boolean;+ isFollowingLive: boolean;+ ref?: Ref<HTMLDivElement>;+ /** The kind of gallery item Preview shows, if any. */+ shownKind: GalleryItemKind | null;+}) => {+ const { t } = useTranslation();+ const { gallery, notifications } = useWorkbenchCommands();+ const queries = useWorkbenchQueries();+ const queryClient = useQueryClient();+ const startDroppedFileUpload = useDroppedFileUpload({+ pendingKey: 'widgets.preview.dropPending',+ surface: 'preview',+ uploadingKey: 'widgets.preview.dropUploading',+ });+ const importDroppedFiles = useCallback(+ (files: File[], zone: PreviewDropZone) =>+ startDroppedFileUpload(files, {+ load: () => import('./importPreviewFileDrop'),+ run: ({ importPreviewFileDrop }, context) =>+ importPreviewFileDrop({ ...context, files, gallery, notifications, queries, queryClient, t, zone }),+ runFailedMessage: t('widgets.gallery.uploadFailed', { failed: files.length }),+ }),+ [gallery, notifications, queries, queryClient, startDroppedFileUpload, t]+ );+ const { drag, handlers } = useNativeFileDrag({ findZone: findPreviewDropZone, onDrop: importDroppedFiles });+ const showsCompare =+ !isFollowingLive && !isComparing && shownKind === 'image' && drag !== null && drag.fileTypes.some(mayBeImage);++ return (+ // Let the dot grid fill the widget; containerType bounds Details cqh sizing to this surface.+ <Box ref={ref} containerType="size" h="full" position="relative" w="full" {...handlers}>+ {children}+ {drag ? (+ // Nearly opaque: what Preview shows stays only as a trace, so it never reads through the zones' labels.+ <Flex bg="bg.inset/95" gap="1" inset="0" p="1" pointerEvents="none" position="absolute" zIndex="2">+ <PreviewDropZoneTarget isOver={drag.zone === 'show'} label={t('widgets.preview.dropToShow')} zone="show" />+ {showsCompare ? (+ <PreviewDropZoneTarget+ isOver={drag.zone === 'compare'}+ label={t('widgets.preview.dropToCompare')}+ zone="compare"+ />+ ) : null}+ </Flex>+ ) : null}+ </Box>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsxindex 0f6549dc34..99b92d511c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFilmstrip.tsx@@ -12,12 +12,15 @@ import { ProgressBadge } from '@platform/ui/ProgressBadge';import { Scrollable } from '@platform/ui/Scrollable';import { StreamingImageFrame } from '@platform/ui/streaming-image/StreamingImageFrame';import { progressImageToStreamingSource } from '@platform/ui/streaming-image/streamingImageSource';+import { releaseFocusOnRemoval } from '@workbench/focusRegions';import { PinIcon } from 'lucide-react';import { memo, useCallback, useMemo, type MouseEvent } from 'react';import { useTranslation } from 'react-i18next';import type { PreviewDensity } from './previewDensity';+import { getPreviewDockBarHeight, PREVIEW_DOCK_BAR_PROPS } from './previewDockBar';+/*** Render board thumbnails below the stage in the gallery's order: the starred strip, the live GPU slots, then the* listing, where each slot's result lands beside it. Reserve height outside media; item drag payloads work with@@ -86,18 +89,13 @@ export const PreviewFilmstrip = ({// Set explicit ScrollArea height and inline-size containment so the strip neither consumes widget height nor// expands its width.<Scrollable- bg="bg.subtle"- borderColor="border.subtle"- borderTopWidth="1px"+ {...PREVIEW_DOCK_BAR_PROPS}contentProps={FILMSTRIP_CONTENT_PROPS}css={FILMSTRIP_CONTAIN_CSS}data-preview-filmstrip- flexShrink={0}- h={density === 'full' ? '3.75rem' : '2.75rem'}+ h={getPreviewDockBarHeight(density)}minW="0"orientation="horizontal"- px="2"- w="full"><HStack align="center" gap="1" h="full">{items.slice(0, leadingItemCount).map(renderItem)}@@ -186,20 +184,8 @@ const FilmstripLiveThumb = ({if (isFollowed) {node.scrollIntoView({ block: 'nearest', inline: 'nearest' });}- const region = node.closest<HTMLElement>('[role="region"]');- // React re-runs this cleanup when `isFollowed` flips while the node is- // still mounted — exactly the click that focused it — so only a node- // that really left the document gives focus away.- return () => {- if (document.activeElement === node) {- queueMicrotask(() => {- if (!node.isConnected) {- region?.focus({ preventScroll: true });- }- });- }- };+ return releaseFocusOnRemoval(node);},[isFollowed]);@@ -285,20 +271,31 @@ const FilmstripThumb = memo(function FilmstripThumb({},[item, onContextMenu]);- const scrollIntoView = useCallback(+ // A deletion can take the thumb away while it holds focus, in whatever later render its listing drops it.+ const thumbRef = useCallback((node: HTMLElement | null) => {setNodeRef(node);- if (node && isSelected) {+ if (!node) {+ return;+ }+ if (isSelected) {node.scrollIntoView({ block: 'nearest', inline: 'nearest' });}++ const releaseFocus = releaseFocusOnRemoval(node);++ return () => {+ setNodeRef(null);+ releaseFocus();+ };},[isSelected, setNodeRef]);return (<Box- ref={scrollIntoView}+ ref={thumbRef}{...listeners}as="button"aria-current={isSelected || undefined}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex 9f63916724..2ee360c7cc 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -10,6 +10,7 @@ import { getAuthSession, refreshProtectedMediaCookie } from '@features/identity'import { canCopyImage, copyImage } from '@platform/browser/clipboard';import { useMountEffect } from '@platform/react/useMountEffect';import { Button } from '@platform/ui/Button';+import { releaseFocusOnRemoval } from '@workbench/focusRegions';import { GripHorizontalIcon } from 'lucide-react';import {lazy,@@ -155,7 +156,7 @@ const PreviewImageFrame = ({});const { contentRefCallback, stageRefCallback } = loupe;const dragData = useMemo(() => (dragItem ? getGalleryItemDragData([dragItem]) : undefined), [dragItem]);- const isDragDisabled = !dragItem || isLive || loupe.isZoomed;+ const isDragDisabled = !dragItem || isLive || loupe.isPannable;const disabledDragId = useId();const dragId = dragItem? getGalleryItemDragId(dragItem, 'preview-frame')@@ -175,7 +176,7 @@ const PreviewImageFrame = ({displayedSourceToken,dragId,enabled: isSwipeEnabled,- isZoomed: loupe.isZoomed,+ isZoomed: loupe.isPannable,navigation: swipeNavigation ?? null,});const { contentTrackRef, onPointerDown: handleSwipePointerDown, stageRefCallback: swipeStageRefCallback } = swipe;@@ -357,7 +358,7 @@ const PreviewImageFrame = ({return (<PreviewStageref={setStageRef}- cursor={loupe.isZoomed ? 'grab' : undefined}+ cursor={loupe.isPannable ? 'grab' : undefined}fill="flex"padding={padding}paddingBottom={paddingBottom}@@ -493,14 +494,26 @@ const PreviewVideo = ({const publishCopyAvailability = useCallback(() => {onCopyAvailabilityChange?.(source.itemKey, isVideoFrameCopyAvailable(videoRef.current));}, [onCopyAvailabilityChange, source.itemKey]);+ // The video can hold focus (its native controls, and the context menu key opens Preview's menu from it), so it hands+ // focus on when a later render removes it.const setVideoRef = useCallback((video: HTMLVideoElement | null) => {- videoRef.current = video;- if (video) {- video.muted = previewVideoAudio.muted;- video.volume = previewVideoAudio.volume;+ if (!video) {+ return;}++ videoRef.current = video;+ video.muted = previewVideoAudio.muted;+ video.volume = previewVideoAudio.volume;onCopyAvailabilityChange?.(source.itemKey, isVideoFrameCopyAvailable(video));++ const releaseFocus = releaseFocusOnRemoval(video);++ return () => {+ videoRef.current = null;+ onCopyAvailabilityChange?.(source.itemKey, false);+ releaseFocus();+ };},[onCopyAvailabilityChange, source.itemKey]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsxindex 95d799d6ee..4f5407bcf0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx@@ -189,6 +189,31 @@ describe('PreviewFrame image drag', () => {});});+ it('still drags out once wheel zoom-out shows an enlarged image below fit, at 100%', async () => {+ const onDrop = await renderHarness();+ const image = host!.querySelector<HTMLImageElement>('img[alt="preview.png"]')!;+ const frame = image.parentElement!;++ // The 128px image fits larger than its own size, so zooming far out rests at 100%, under fit.+ await interact(() =>+ image.dispatchEvent(+ new WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 140, clientY: 140, deltaY: 2000 })+ )+ );+ expect(frame.style.transform).toMatch(/scale\(0\.\d+\)/);++ const rect = image.getBoundingClientRect();+ const x = rect.left + rect.width / 2;+ const y = rect.top + rect.height / 2;++ await interact(() => pointer('pointerdown', image, x, y));+ await interact(() => pointer('pointermove', image.ownerDocument, x + 30, y));+ await interact(() => pointer('pointermove', image.ownerDocument, 400, 120));+ await interact(() => pointer('pointerup', image.ownerDocument, 400, 120));++ expect(onDrop.mock.calls[0]?.[0]?.overId).toBe('test-image-drop');+ });+it('gives a second finger the pinch and abandons the drag it interrupted', async () => {// A second touch must cancel image dragging before taking over pinch, avoiding an unintended drop on release.const onDrop = await renderHarness();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameLazyPlayer.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameLazyPlayer.browser.test.tsxindex 81bee6d321..585462ebaf 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameLazyPlayer.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameLazyPlayer.browser.test.tsx@@ -25,7 +25,8 @@ vi.mock('@platform/ui/video-player/VideoPlayer', async (importOriginal) => {return importOriginal();});-vi.mock('@features/identity', () => ({+vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<object>()),getAuthSession: () => ({ accountEpoch: 1 }),refreshProtectedMediaCookie: () => Promise.resolve(false),}));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsxindex f17f619e4f..548485a8d1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameVideo.browser.test.tsx@@ -31,7 +31,8 @@ const identityMocks = vi.hoisted(() => ({refreshProtectedMediaCookie: vi.fn<() => Promise<boolean>>(),}));-vi.mock('@features/identity', () => ({+vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<object>()),getAuthSession: () => ({ accountEpoch: identityMocks.accountEpoch }),refreshProtectedMediaCookie: identityMocks.refreshProtectedMediaCookie,}));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 04b5c51747..d0533545ce 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@@ -72,6 +72,7 @@ void i18n.use(initReactI18next).init({},},preview: {+ compareArmedTooltip: 'Pick another image to compare · click to cancel',details: 'Details',editOnCanvas: 'Edit on Canvas',editThisImage: 'Edit this image',@@ -95,6 +96,8 @@ void i18n.use(initReactI18next).init({const state = vi.hoisted(() => ({actionItem: null as null | Record<string, unknown>,+ /** Set while Select for compare waits for a second image, as Preview publishes it. */+ cancelCompare: null as null | (() => void),density: 'full' as 'compact' | 'full' | 'minimal' | null,viewerAutoSwitch: 'progress' as 'latest' | 'off' | 'progress',zoom: null as null | {@@ -151,6 +154,7 @@ vi.mock('./previewHeaderStore', async (importOriginal) => ({usePreviewHeaderContext: () => ({actionItem: state.actionItem,actions: state.actionItem ? itemActions : null,+ cancelCompare: state.cancelCompare,copyCurrentVideoFrame: null,isVideoFrameCopyAvailable: false,openItemMenu,@@ -240,7 +244,9 @@ const button = (label: string): HTMLButtonElement =>beforeEach(() => {state.actionItem = null;+ state.cancelCompare = null;state.density = 'full';+ itemActions.selectForCompare.mockClear();openItemMenu.mockClear();itemActions.canUseAsReferenceImage = false;queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });@@ -564,6 +570,35 @@ describe('preview header Edit and Use', () => {);});+ it('shows Select for compare pressed while it waits for a second image, and switches it off again', async () => {+ state.actionItem = STILL_IMAGE;+ await render();+ const compare = button('Select for Compare');++ expect(compare).toHaveAttribute('aria-pressed', 'false');+ await settle(() => compare.click());+ expect(itemActions.selectForCompare).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ imageName: 'still.png' })+ );++ const cancelCompare = vi.fn();+ state.cancelCompare = cancelCompare;+ await settle(() => root?.unmount());+ await render();+ // The name stays put, so it never reads as "Cancel, pressed"; the state is the pressed one, and the tooltip says how+ // to call it off.+ const pressed = button('Select for Compare');++ expect(pressed).toHaveAttribute('aria-pressed', 'true');+ await settle(() => pressed.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse' })));+ await expect+ .element(page.getByRole('tooltip'))+ .toHaveTextContent('Pick another image to compare · click to cancel');+ await settle(() => pressed.click());+ expect(cancelCompare).toHaveBeenCalledOnce();+ expect(itemActions.selectForCompare).toHaveBeenCalledOnce();+ });+it('keeps Edit and Use down to compact, icon-only there, and leaves minimal to star and the full ⋮', async () => {const strip = () =>[...host!.querySelectorAll<HTMLButtonElement>('button')]diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsxindex e29dd24d2e..3108ba6ea4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewHeaderActions.tsx@@ -26,8 +26,17 @@ const AUTO_SWITCH_POSITIONING = { placement: 'bottom-end' } as const;export const PreviewHeaderActions = (_props: WidgetViewProps) => {const livePreview = useLivePreviewFollow();const autoSwitch = useActiveProjectSelector((project) => project.settings.viewerAutoSwitch);- const { actionItem, actions, copyCurrentVideoFrame, isVideoFrameCopyAvailable, openItemMenu, position, zoom } =- usePreviewHeaderContext();+ const {+ actionItem,+ actions,+ cancelCompare,+ copyCurrentVideoFrame,+ getRegion,+ isVideoFrameCopyAvailable,+ openItemMenu,+ position,+ zoom,+ } = usePreviewHeaderContext();const { density, stageElement, zoom: zoomReadout } = usePreviewStageContext();const zoomControls = useMemo<PreviewZoomControls | null>(() => (zoom && zoomReadout ? { ...zoom, ...zoomReadout } : null),@@ -61,8 +70,10 @@ export const PreviewHeaderActions = (_props: WidgetViewProps) => {actions={actions}// The strip has a band of its own below compact; until the view measures, it is compact.density={density ?? 'compact'}+ getRegion={getRegion ?? undefined}isVideoFrameCopyAvailable={isVideoFrameCopyAvailable}item={actionItem}+ onCancelCompare={cancelCompare ?? undefined}onCopyCurrentFrame={copyCurrentVideoFrame ?? undefined}onOpenMenu={openItemMenu}/>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsxindex cd7a273300..3ac6c3ebd0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewMediaChrome.browser.test.tsx@@ -55,12 +55,13 @@ const mocks = vi.hoisted(() => ({vi.mock('@features/queue/react', () => ({consumeQueueItemSwapProgressImage: () => undefined,useItemProgress: () => mocks.itemProgress,- useQueueItemBridgeProgressImage: () => null,useQueueItemProgressImage: () => mocks.progressImage,useQueueItemSwapProgressImage: () => null,useActiveProgressTargets: () => [],useActiveProgressTarget: () => null,useFollowedProgressTargets: () => [],+ useFramedProgressTargets: () => [],+ useQueueItemProgress: () => null,useActiveProgressItemIds: () => [],useProgressImage: () => null,}));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.browser.test.tsxindex 2e4ddb696e..62f8a4a224 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewNavButtons.browser.test.tsx@@ -15,7 +15,8 @@ import type { PreviewSwipeNavigation } from './usePreviewSwipe';import { PreviewFrame } from './PreviewFrame';import { PREVIEW_NAV_STAGE_CSS, PreviewNavButtons } from './PreviewNavButtons';-vi.mock('@features/identity', () => ({+vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<object>()),getAuthSession: () => ({ accountEpoch: 1 }),refreshProtectedMediaCookie: () => Promise.resolve(false),}));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 1099c17305..a9ef6fb80d 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@@ -2,6 +2,8 @@import type { GalleryImage, GalleryImageItem, GalleryItemsPage, GalleryVideoItem } from '@features/gallery';import type { InvocationProgressEvent, QueueItem, QueueItemStatusChangedEvent } from '@features/queue/contracts';import type { ExtensionRegistry } from '@workbench/extensions/extensionRegistry';+import type { ImageActions } from '@workbench/image-actions';+import type * as ImageContextMenuModule from '@workbench/image-actions/ImageContextMenu';import type * as DeletionConfirmationModule from '@workbench/image-actions/useDeletionConfirmation';import type * as projectsApi from '@workbench/projects/api';import type { WidgetContributionSource, WidgetViewProps } from '@workbench/widgetContracts';@@ -17,17 +19,19 @@ import { system } from '@theme/system';import { createExtensionRegistry } from '@workbench/extensions/extensionRegistry';import { useFocusRegionProps } from '@workbench/focusRegions';import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';+import { EMPTY_IMAGE_RECALL_CAPABILITIES } from '@workbench/image-actions/imageRecall';import { DEFAULT_PREFERENCES, patchWorkbenchPreferences } from '@workbench/settings/store';import { HoldToDragSensor, PrimaryMouseSensor } from '@workbench/shell/holdToDragSensor';import { WorkbenchFocusProvider } from '@workbench/WorkbenchRuntime';import i18next from 'i18next';-import { act, useCallback } from 'react';+import { act, useCallback, useSyncExternalStore } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { commands, page, userEvent } from 'vitest/browser';import { LivePreviewFollowProvider, useLivePreviewFollow } from './livePreviewFollow';+import { PreviewActionStrip } from './PreviewActionStrip';import { usePreviewHeaderContext, type PreviewItemPosition } from './previewHeaderStore';import { PREVIEW_NAV_ATTRIBUTE } from './PreviewNavButtons';import { PreviewWidgetLabel } from './PreviewWidgetChrome';@@ -169,6 +173,11 @@ const mocks = vi.hoisted(() => {galleryItemNames: [] as Array<{ kind: 'image' | 'video'; name: string }>,galleryItemNamesGate: null as Promise<void> | null,galleryItemNamesOptionCalls: 0,+ // Widget values as an external store: `publishGalleryValues` re-renders its subscribers, as the workbench does.+ widgetValues: { listeners: new Set<() => void>(), version: 0 },+ // Set by a test that drives the real item menu: the actions the view hands it, in place of the empty stand-in.+ imageActions: null as ImageActions | null,+ realImageContextMenu: null as typeof ImageContextMenuModule.ImageContextMenu | null,imageActionOptions: null as null | {getItemActionContext?: () => {getItemSelectionPage?: (item: GalleryImageItem | GalleryVideoItem) => number;@@ -180,7 +189,8 @@ const mocks = vi.hoisted(() => {requestDeletionConfirmation?: DeletionConfirmationModule.RequestDeletionConfirmation;},recentImages,- bridgeProgressImage: null as unknown,+ /** Slots that have shown a frame of their own; every followed slot unless a test says otherwise. */+ framedProgressTargets: undefined as { queueItemId: string; itemIndex: number }[] | undefined,runningProgressTargets: undefined as { queueItemId: string; itemIndex: number }[] | undefined,slotProgressImage: undefined as unknown,useActiveProgressTarget: vi.fn(() => null as unknown),@@ -197,13 +207,22 @@ vi.mock('@workbench/useOpenWorkbenchWidget', () => ({useOpenWorkbenchWidget: () => mocks.openWidget,}));+const subscribeWidgetValues = (listener: () => void) => {+ mocks.widgetValues.listeners.add(listener);+ return () => mocks.widgetValues.listeners.delete(listener);+};+const getWidgetValuesVersion = () => mocks.widgetValues.version;+vi.mock('@workbench/WorkbenchContext', () => ({useActiveProjectId: () => 'project-1',+ useActiveProjectName: () => 'Project 1',useActiveProjectSelector: (selector: (project: typeof mocks.project) => unknown) => selector(mocks.project),useOptionalWorkbenchCommands: () => mocks.commands,useOptionalWorkbenchExtensions: () => mocks.extensions,- useWidgetValuesSelector: (widgetId: string, selector: (values: Record<string, unknown>) => unknown) =>- selector(+ useWidgetValuesSelector: (widgetId: string, selector: (values: Record<string, unknown>) => unknown) => {+ useSyncExternalStore(subscribeWidgetValues, getWidgetValuesVersion);++ return selector(widgetId === 'gallery' || widgetId === 'preview'? ((Object.values(mocks.project.widgetInstances).find((instance) => instance.typeId === widgetId) as@@ -211,7 +230,8 @@ vi.mock('@workbench/WorkbenchContext', () => ({| undefined)?.state?.values ?? {}): {}- ),+ );+ },useWorkbenchCommands: () => mocks.commands,useWorkbenchExtensions: () => mocks.extensions,// Imported beside the focus provider; only the workbench runtime component, not rendered here, reads it.@@ -230,18 +250,20 @@ const mockProgressTargets = () => {return target ? [target] : [];};+const mockFollowedProgressTargets = () =>+ [...(mocks.runningProgressTargets ?? []), ...mockProgressTargets()].filter(+ (target, index, all) =>+ all.findIndex((other) => other.queueItemId === target.queueItemId && other.itemIndex === target.itemIndex) ===+ index+ );+vi.mock('@features/queue/react', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),useActiveProgressTarget: () => mocks.useActiveProgressTarget(),useActiveProgressTargets: () => mocks.runningProgressTargets ?? mockProgressTargets(),- useFollowedProgressTargets: () =>- [...(mocks.runningProgressTargets ?? []), ...mockProgressTargets()].filter(- (target, index, all) =>- all.findIndex((other) => other.queueItemId === target.queueItemId && other.itemIndex === target.itemIndex) ===- index- ),+ useFollowedProgressTargets: () => mockFollowedProgressTargets(),+ useFramedProgressTargets: () => mocks.framedProgressTargets ?? mockFollowedProgressTargets(),useProgressImage: () => mocks.useProgressImage(),- useQueueItemBridgeProgressImage: () => mocks.bridgeProgressImage,// The slot's own frame: derived from the "latest" mock by target unless a test overrides it.useQueueItemProgressImage: (queueItemId: string, itemIndex: number) => {if (mocks.slotProgressImage !== undefined) {@@ -263,6 +285,21 @@ vi.mock('@workbench/projects/api', async (importOriginal) => ({vi.mock('@workbench/hotkeys/firstPartyCommands', () => ({ useRegisterFirstPartyCommands: () => {} }));vi.mock('@features/gallery/queries', () => ({+ // The item menu's reads: recorded metadata, which these images have none of, and whether one embeds a workflow.+ galleryImageMetadataOptions: (_owner: unknown, imageName: string) => ({+ queryFn: () => null,+ queryKey: ['test-image-metadata', imageName],+ staleTime: Infinity,+ }),+ galleryKeys: {+ imageHasWorkflow: (_owner: unknown, imageName: string) => ['test-image-has-workflow', imageName],+ videoHasWorkflow: (_owner: unknown, videoName: string) => ['test-video-has-workflow', videoName],+ },+ galleryVideoMetadataOptions: (_owner: unknown, videoName: string) => ({+ queryFn: () => null,+ queryKey: ['test-video-metadata', videoName],+ staleTime: Infinity,+ }),GALLERY_MAX_ROWS: 600,GALLERY_PAGE_SIZE: 60,isDateBoardId: (boardId: string) => boardId.startsWith('by_date:'),@@ -439,12 +476,17 @@ vi.mock('@features/gallery/contracts', async (importOriginal) => ({vi.mock('@workbench/image-actions', async () => ({EMPTY_IMAGE_RECALL_CAPABILITIES: {},- ImageContextMenu: (props: { target: unknown; variant?: string }) => {+ ImageContextMenu: (props: Parameters<typeof ImageContextMenuModule.ImageContextMenu>[0]) => {+ const { realImageContextMenu: RealImageContextMenu } = mocks;+contextMenuProps.current = props;- return null;+ return mocks.imageActions && RealImageContextMenu ? (+ <RealImageContextMenu {...props} actions={mocks.imageActions} />+ ) : null;},ImageContinueGroup: () => null,ImageUseGroups: () => null,+ VideoUseGroups: () => null,RecallActionButtons: () => null,buildImageRecallSettings: () => ({}),executeImageRecall: () => {},@@ -460,8 +502,9 @@ vi.mock('@workbench/image-actions', async () => ({).useDeletionConfirmation,useImageActions: (options: typeof mocks.imageActionOptions) => {mocks.imageActionOptions = options;- return {};+ return mocks.imageActions ?? {};},+ useImageRecallCapabilities: () => ({ capabilities: {}, isLoading: false }),}));vi.mock('@features/generation/react', () => ({@@ -477,6 +520,11 @@ vi.mock('@features/generation/react', () => ({import { PreviewWidgetView } from './PreviewWidgetView';+// Loaded after the mocks, so the real menu reads the same mocked workbench as the view.+mocks.realImageContextMenu = (+ await vi.importActual<typeof ImageContextMenuModule>('@workbench/image-actions/ImageContextMenu')+).ImageContextMenu;+const i18n = i18next.createInstance();await i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -485,6 +533,7 @@ await i18n.use(initReactI18next).init({en: {translation: {common: {+ cancel: 'Cancel',countOfTotal: '{{count}} of {{total}}',generating: 'Generating',videoPlayer: {@@ -501,7 +550,14 @@ await i18n.use(initReactI18next).init({widgets: {gallery: { commands: { clearSelection: 'Clear gallery selection' } },preview: {- commands: { nextItem: 'Show next item', previousItem: 'Show previous item' },+ cancelCompare: 'Cancel compare',+ commands: {+ exitCompare: 'Cancel or exit compare',+ nextItem: 'Show next item',+ previousItem: 'Show previous item',+ },+ compareArmedHint: 'Pick another image to compare with this one',+ imageActions: 'Item actions',noGallerySelection: 'No gallery selection',showGallery: 'Show Gallery',framesPerSecond: '{{count}} fps',@@ -590,6 +646,22 @@ const HeaderPositionProbe = () => {return <span ref={ref} />;};+// Off unless a test renders it: the header's ⋮ as the chrome shows it, only while Preview publishes an item to act on.+let showsHeaderMenuButton = false;+const HeaderMenuButton = () => {+ const { actionItem, actions, getRegion, openItemMenu } = usePreviewHeaderContext();++ return actionItem && actions ? (+ <PreviewActionStrip+ actions={actions}+ density="minimal"+ getRegion={getRegion ?? undefined}+ item={actionItem}+ onOpenMenu={openItemMenu}+ />+ ) : null;+};+// The shell's sensors, so touch on the preview arbitrates between swipe and drag as it does in the app.const ShellDndContext = ({ children }: Pick<DndContextProps, 'children'>) => {const sensors = useSensors(@@ -636,6 +708,7 @@ const renderTree = async (client: QueryClient) => {<LivePreviewFollowProvider><FollowProbe /><HeaderPositionProbe />+ {showsHeaderMenuButton ? <HeaderMenuButton /> : null}<CenterRegion><PreviewWidgetView instance={instance} manifest={manifest} region="center" runtime={runtime} /></CenterRegion>@@ -681,6 +754,14 @@ const setGalleryValues = (patch: Record<string, unknown>) => {state.values = { ...state.values, ...patch };};+// Gallery values republished as the workbench store publishes them: subscribers re-render at once, within the event+// that changed them.+const publishGalleryValues = (patch: Record<string, unknown>) => {+ setGalleryValues(patch);+ mocks.widgetValues.version += 1;+ mocks.widgetValues.listeners.forEach((listener) => listener());+};+// Apply mocked selection results back to Gallery values so subsequent navigation starts from the newly selected// item.const commitLastSelection = async () => {@@ -829,6 +910,7 @@ beforeEach(() => {mocks.commands.gallery.selectItem.mockClear();mocks.commands.gallery.clearSelection.mockReset();showsHeaderLabel = false;+ showsHeaderMenuButton = false;vi.mocked(requestGalleryItemReveal).mockClear();mocks.project.queue.items = [];mocks.project.settings.viewerAutoSwitch = 'off';@@ -859,6 +941,7 @@ beforeEach(() => {mocks.galleryItemNamesGate = null;mocks.galleryItemNamesOptionCalls = 0;mocks.imageActionOptions = null;+ mocks.imageActions = null;mocks.galleryItemPages = [{items: mocks.recentImages.map((image) => ({@@ -880,7 +963,7 @@ beforeEach(() => {];mocks.useActiveProgressTarget.mockReturnValue(null);mocks.useProgressImage.mockReturnValue(null);- mocks.bridgeProgressImage = null;+ mocks.framedProgressTargets = undefined;mocks.runningProgressTargets = undefined;mocks.slotProgressImage = undefined;});@@ -3153,25 +3236,62 @@ describe('preview keyboard navigation boundary', () => {expect(mocks.galleryItemFilters.every((filter) => filter.boardId !== 'board-live')).toBe(true);});- it('keeps following a completed slot while its result is still routing', async () => {- // Keep settling results in the single live frame after backend completion and before gallery arrival; do not- // tile them.- mocks.project.queue.items = [queueItem];+ it("holds the finished slot's last frame while its result routes, then shows the result until the next first frame", async () => {+ // Slot 1 completed and its result is still on its way; slot 2 runs but is loading its model.+ const slotOne = { itemIndex: 1, queueItemId: 'queue-item-live' };+ const slotTwo = { itemIndex: 2, queueItemId: 'queue-item-live' };+ const resultOfSlotOne = { ...mocks.recentImages[0]!, sourceQueueItemId: 'queue-item-live' };+ const stageSources = () =>+ [...host!.querySelectorAll<HTMLImageElement>('img:not([data-preview-filmstrip] img)')].map((image) =>+ image.getAttribute('src')+ );+ const statusLines = () => [...host!.querySelectorAll('[role="status"]')].map((line) => line.textContent);+ mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2], completedBackendItemIds: [1] }];mocks.project.settings.viewerAutoSwitch = 'progress';- mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 1, queueItemId: 'queue-item-live' });- mocks.runningProgressTargets = [];+ mocks.useActiveProgressTarget.mockReturnValue(slotOne);+ mocks.runningProgressTargets = [slotTwo];+ mocks.framedProgressTargets = [slotOne];mocks.useProgressImage.mockReturnValue({- dataUrl: 'data:image/png;base64,',+ dataUrl: 'data:image/png;base64,slot-one-last',height: 64,- target: { itemIndex: 1, queueItemId: 'queue-item-live' },+ target: slotOne,width: 64,});+ setGalleryValues({ selectedImage: legacyImage('oldest', '2026-07-20T00:00:00.000Z'), selectedImageName: 'oldest' });await render();+ expect(stageSources().filter((src) => src?.startsWith('data:image/png'))).toEqual([+ 'data:image/png;base64,slot-one-last',+ ]);- expect(- host?.querySelectorAll<HTMLImageElement>('img[src^="data:image/png"]:not([data-preview-filmstrip] img)')- ).toHaveLength(1);+ // Routing lands: the settling slot is released and its result selected; slot 2 still has no frame.+ mocks.useActiveProgressTarget.mockReturnValue(null);+ mocks.framedProgressTargets = [];+ mocks.useProgressImage.mockReturnValue(null);+ publishGalleryValues({+ recentImages: [resultOfSlotOne, ...mocks.recentImages.slice(1)],+ selectedImage: legacyImage('newest', resultOfSlotOne.queuedAt),+ selectedImageName: 'newest',+ });+ await rerender();++ expect(stageSources()).toContain(resultOfSlotOne.imageUrl);+ expect(stageSources().some((src) => src?.startsWith('data:image/png'))).toBe(false);+ expect(host!.querySelector('[data-preview-starting-cue]')?.textContent).toBe('widgets.preview.starting');+ expect(statusLines()).toContain('widgets.preview.startingAnnouncement');+ });++ it('shows a session starting before its first frame when nothing is selected, saying so', async () => {+ mocks.project.queue.items = [queueItem];+ mocks.project.settings.viewerAutoSwitch = 'progress';+ mocks.runningProgressTargets = [{ itemIndex: 1, queueItemId: 'queue-item-live' }];+ mocks.framedProgressTargets = [];+ setGalleryValues({ selectedImage: null, selectedImageName: null, selectedImageNames: [] });++ await render();++ expect(host!.textContent).not.toContain('widgets.preview.noGallerySelection');+ expect(host!.querySelector('[data-preview-starting-cue]')?.textContent).toBe('widgets.preview.starting');});it('keeps the same-root preview through child gaps and browser focus changes until the next denoising step', async () => {@@ -3211,6 +3331,11 @@ describe('preview keyboard navigation boundary', () => {mocks.runningProgressTargets = [];}},+ markFramed: (target) => {+ activeTarget = target;+ mocks.useActiveProgressTarget.mockReturnValue(target);+ mocks.runningProgressTargets = [target];+ },set: (target) => {activeTarget = target;mocks.useActiveProgressTarget.mockReturnValue(target);@@ -3436,7 +3561,7 @@ describe('preview keyboard navigation boundary', () => {);});- it('follows a running slot over a settling one so a concurrent session is never hidden', async () => {+ it('follows a running slot with a frame of its own over a settling one so a concurrent session is never hidden', async () => {// 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] }];@@ -3449,31 +3574,42 @@ describe('preview keyboard navigation boundary', () => {target: { itemIndex: 2, queueItemId: 'queue-item-live' },width: 64,});- mocks.bridgeProgressImage = { dataUrl: 'data:image/png;base64,slot-one', height: 64, width: 64 };await render();- expect(host?.querySelector<HTMLImageElement>('img[src="data:image/png;base64,slot-two"]')).not.toBeNull();- expect(host?.querySelector<HTMLImageElement>('img[src="data:image/png;base64,slot-one"]')).toBeNull();+ expect(+ [...host!.querySelectorAll<HTMLImageElement>('img[src^="data:image/png"]:not([data-preview-filmstrip] img)')].map(+ (image) => image.getAttribute('src')+ )+ ).toEqual(['data:image/png;base64,slot-two']);});- 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.+ it("shows a finished batch image, not the next slot, until that slot's first frame, saying what it waits for", async () => {+ // Slot 1's result has landed and is selected; slot 2 runs but is still loading its model.+ const finished = mocks.recentImages[0]!;mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2], completedBackendItemIds: [1] }];mocks.project.settings.viewerAutoSwitch = 'progress';- mocks.useActiveProgressTarget.mockReturnValue({ itemIndex: 2, queueItemId: 'queue-item-live' });- mocks.useProgressImage.mockReturnValue({- dataUrl: 'data:image/png;base64,slot-one',- height: 64,- target: { itemIndex: 1, queueItemId: 'queue-item-live' },- width: 64,- });- mocks.bridgeProgressImage = { dataUrl: 'data:image/png;base64,bridge', height: 64, width: 64 };+ mocks.runningProgressTargets = [{ itemIndex: 2, queueItemId: 'queue-item-live' }];+ mocks.framedProgressTargets = [];+ mocks.slotProgressImage = null;await render();- expect(host?.querySelector<HTMLImageElement>('img[src="data:image/png;base64,bridge"]')).not.toBeNull();- expect(host?.querySelector<HTMLImageElement>('img[src="data:image/png;base64,slot-one"]')).toBeNull();+ const stageSources = () =>+ [...host!.querySelectorAll<HTMLImageElement>('img:not([data-preview-filmstrip] img)')].map((image) =>+ image.getAttribute('src')+ );+ expect(stageSources()).toContain(finished.imageUrl);+ expect(stageSources().some((src) => src?.startsWith('data:image/png'))).toBe(false);+ expect(host?.querySelector('[data-preview-starting-cue]')?.textContent).toBe('widgets.preview.starting');++ // The first frame of its own: the Preview follows the slot from here.+ mocks.framedProgressTargets = [{ itemIndex: 2, queueItemId: 'queue-item-live' }];+ mocks.slotProgressImage = { dataUrl: 'data:image/png;base64,slot-two-first', height: 64, width: 64 };+ await rerender();++ expect(stageSources()).toEqual(['data:image/png;base64,slot-two-first']);+ expect(host?.querySelector('[data-preview-starting-cue]')).toBeNull();});it('keeps every concurrent session in the filmstrip, follows the newest session, and pins on request', async () => {@@ -3524,6 +3660,39 @@ describe('preview keyboard navigation boundary', () => {expect(followedThumb()).toBe('queue-item-live:1');});+ it('shows a picked session before its first frame, over the selected result, until it stops running', async () => {+ mocks.project.queue.items = [{ ...queueItem, backendItemIds: [1, 2] }];+ mocks.project.settings.viewerAutoSwitch = 'progress';+ mocks.runningProgressTargets = [+ { queueItemId: queueItem.id, itemIndex: 1 },+ { queueItemId: queueItem.id, itemIndex: 2 },+ ];+ // Slot 1 streams; slot 2 has started but shows nothing of its own yet.+ mocks.framedProgressTargets = [{ queueItemId: queueItem.id, itemIndex: 1 }];+ mocks.useProgressImage.mockReturnValue({+ dataUrl: 'data:image/png;base64,slot-one',+ height: 64,+ target: { itemIndex: 1, queueItemId: queueItem.id },+ width: 64,+ });+ const followedThumb = () =>+ host!.querySelector<HTMLElement>('[data-preview-live-thumb][aria-current="true"]')?.dataset.previewLiveThumb;+ await render();+ expect(followedThumb()).toBe('queue-item-live:1');++ await act(() => followControls.follow('queue-item-live:2'));+ expect(mocks.commands.account.updateProjectPreferences).toHaveBeenCalledWith({ viewerAutoSwitch: 'progress' });+ await rerender();+ expect(followedThumb()).toBe('queue-item-live:2');+ expect(host!.querySelector('[data-preview-starting-cue]')).not.toBeNull();++ // It finishes: the pin goes, and the newest running session with a frame is followed again.+ mocks.runningProgressTargets = [{ queueItemId: queueItem.id, itemIndex: 1 }];+ await rerender();+ expect(followControls.pinnedSessionId).toBeNull();+ expect(followedThumb()).toBe('queue-item-live:1');+ });+it('keeps live previews available during similarity search and temporary comparison override', async () => {mocks.project.queue.items = [queueItem];mocks.project.settings.viewerAutoSwitch = 'progress';@@ -3561,16 +3730,21 @@ describe('preview keyboard navigation boundary', () => {const values = mocks.project.widgetInstances.gallery.state.values as Record<string, unknown>;values.compareImage = mocks.recentImages[1];mocks.project.settings.viewerAutoSwitch = 'progress';+ // Narrow Preview shows exit as an icon, so look for the control by its accessible name.+ const isComparing = () =>+ Array.from(host!.querySelectorAll('button')).some(+ (button) => (button.getAttribute('aria-label') ?? button.textContent) === 'widgets.preview.exitCompare'+ );await render();- expect(host!.textContent).toContain('widgets.preview.exitCompare');+ expect(isComparing()).toBe(true);mocks.project.queue.items = [queueItem];mocks.runningProgressTargets = [{ queueItemId: queueItem.id, itemIndex: 1 }];await rerender();- expect(host!.textContent).not.toContain('widgets.preview.exitCompare');+ expect(isComparing()).toBe(false);mocks.runningProgressTargets = [];mocks.project.queue.items = [];await rerender();- expect(host!.textContent).toContain('widgets.preview.exitCompare');+ expect(isComparing()).toBe(true);});it('keeps pinned live controls and footer inside the widget without saved-image arrows or zero count', async () => {mocks.project.queue.items = [queueItem];@@ -3937,6 +4111,262 @@ describe('preview deletion confirmation', () => {});});+/** The shared item actions as stand-ins, for tests that open the real item menu. */+const createItemMenuActions = (overrides: Partial<ImageActions>): ImageActions => ({+ canUseAsConditioningClip: { audio: false, video: false },+ canUseAsReferenceImage: false,+ canUseAsReferenceVideo: false,+ copyImage: vi.fn(() => Promise.resolve()),+ createCanvasFromImages: vi.fn(() => Promise.resolve()),+ deleteItems: vi.fn(() => Promise.resolve()),+ deleteImages: vi.fn(() => Promise.resolve()),+ deriveImageRecallCapabilities: vi.fn(() => EMPTY_IMAGE_RECALL_CAPABILITIES),+ downloadItem: vi.fn(() => Promise.resolve()),+ downloadItems: vi.fn(() => Promise.resolve()),+ downloadImage: vi.fn(() => Promise.resolve()),+ downloadImages: vi.fn(() => Promise.resolve()),+ generatePbrMaps: vi.fn(() => Promise.resolve()),+ loadImageWorkflow: vi.fn(() => Promise.resolve()),+ moveItemsToBoard: vi.fn(() => Promise.resolve()),+ moveImagesToBoard: vi.fn(() => Promise.resolve()),+ openItemInNewTab: vi.fn(),+ openItemInPreview: vi.fn(),+ openImageInPreview: vi.fn(),+ recallImageData: vi.fn(() => Promise.resolve()),+ loadVideoWorkflow: vi.fn(() => Promise.resolve()),+ recallVideoData: vi.fn(() => Promise.resolve()),+ selectForCompare: vi.fn(),+ sendToCanvas: vi.fn(() => Promise.resolve()),+ sendImageAsControl: vi.fn(() => Promise.resolve()),+ setItemsStarred: vi.fn(() => Promise.resolve()),+ setImagesStarred: vi.fn(() => Promise.resolve()),+ savePromptAsTemplate: vi.fn(),+ sendToInitialVideo: vi.fn(),+ useAsReferenceImage: vi.fn(),+ useAsConditioningClip: vi.fn(),+ useAsReferenceVideo: vi.fn(),+ ...overrides,+});++describe('preview item menu focus', () => {+ const successor = { ...mocks.recentImages[1], boardId: 'none' };+ let confirmDeletion: (() => void) | null = null;+ // Deleting the shown item as the shared actions do: it leaves the selection at once (the optimistic removal), and+ // the item after it is selected once the server confirms.+ const deleteShownItem = () => {+ publishGalleryValues({ selectedImage: null, selectedImageName: null });++ return new Promise<void>((resolve) => {+ confirmDeletion = () => {+ publishGalleryValues({ selectedImage: successor, selectedImageName: successor.imageName });+ resolve();+ };+ });+ };+ /** Renders Preview with the real item menu, whose Delete asks first unless the user chose not to be asked. */+ const renderWithItemMenu = async ({ asks = true, ...overrides }: Partial<ImageActions> & { asks?: boolean } = {}) => {+ const deleteItems = vi.fn<ImageActions['deleteItems']>((items, options) =>+ asks+ ? mocks.imageActionOptions!.requestDeletionConfirmation!(items, deleteShownItem, {+ canSkipFutureConfirmations: true,+ returnFocus: options?.returnFocus,+ })+ : deleteShownItem()+ );++ confirmDeletion = null;+ mocks.imageActions = createItemMenuActions({ deleteItems, ...overrides });+ await render();+ return deleteItems;+ };+ const findByText = (selector: string, text: string) =>+ vi.waitFor(() => {+ const element = [...document.querySelectorAll<HTMLElement>(selector)].find((candidate) =>+ candidate.textContent?.includes(text)+ );++ expect(element).toBeDefined();+ return element!;+ });+ /** The context menu event on `target`: a right-click, or the menu key on whatever holds focus. */+ const openMenuOn = (target: Element) =>+ act(async () => {+ target.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 40, clientY: 40 })+ );+ await Promise.resolve();+ });+ const chooseMenuItem = async (label: string) => {+ const item = await findByText('[role="menuitem"]', label);++ await act(() => userEvent.click(item));+ };+ /** Deletes through the open menu, confirming when asked, until the next item is shown and every overlay is gone. */+ const deleteThroughMenu = async (asks: boolean) => {+ await chooseMenuItem('widgets.gallery.itemMenu.deleteImage');++ if (asks) {+ const confirm = await findByText('[role="alertdialog"] button', 'widgets.gallery.deleteConfirmLabel');+ // The closing menu hands focus back without taking it from the confirmation.+ await expect.poll(() => document.activeElement?.closest('[role="alertdialog"]')).not.toBeNull();+ await act(() => userEvent.click(confirm));+ }++ await vi.waitFor(() => expect(confirmDeletion).not.toBeNull());+ await act(async () => {+ confirmDeletion!();+ await Promise.resolve();+ });+ expect(host?.querySelector(`img[alt="${successor.imageName}"]`)).not.toBeNull();+ await expect.poll(() => document.querySelector('[role="alertdialog"]')).toBeNull();+ await expect.poll(() => document.querySelector('[role="menu"]')).toBeNull();+ };+ const stageImage = () => host!.querySelector(`[${PREVIEW_NAV_ATTRIBUTE}]`)!.parentElement!.querySelector('img')!;+ const shownThumb = () => host!.querySelector<HTMLButtonElement>('button[aria-current]')!;++ it.each([+ { asks: true, preference: 'deletions confirmed' },+ { asks: false, preference: "don't ask again chosen" },+ ])('closes for good after Delete on the stage, and leaves focus with Preview ($preference)', async ({ asks }) => {+ const deleteItems = await renderWithItemMenu({ asks });++ await openMenuOn(stageImage());+ await deleteThroughMenu(asks);++ // The menu opened on the deleted item does not come back with the next one.+ expect(document.querySelector('[role="menu"]')).toBeNull();+ expect(deleteItems).toHaveBeenCalledExactlyOnceWith([{ kind: 'image', name: 'newest' }], expect.anything());+ // Nothing had focus before the menu, which has no trigger: Preview takes it, so its keys still work.+ expect(document.activeElement).toBe(getBoundary());+ });++ // Without a confirmation the removal lands in the same click that closes the menu.+ it.each([+ { asks: true, preference: 'deletions confirmed' },+ { asks: false, preference: "don't ask again chosen" },+ ])(+ 'gives focus to Preview after Delete takes away the filmstrip thumb the menu opened from ($preference)',+ async ({ asks }) => {+ await renderWithItemMenu({ asks });+ const thumb = shownThumb();++ thumb.focus();+ await openMenuOn(thumb);+ await deleteThroughMenu(asks);++ expect(thumb.isConnected).toBe(false);+ expect(document.activeElement).toBe(getBoundary());+ }+ );++ it.each([+ { asks: true, preference: 'deletions confirmed' },+ { asks: false, preference: "don't ask again chosen" },+ ])(+ "gives focus to Preview after Delete from the header's ⋮, which remounts with the next item ($preference)",+ async ({ asks }) => {+ showsHeaderMenuButton = true;+ await renderWithItemMenu({ asks });+ const menuButton = host!.querySelector<HTMLButtonElement>('button[aria-label="Item actions"]')!;++ await act(() => userEvent.click(menuButton));+ await deleteThroughMenu(asks);++ expect(menuButton.isConnected).toBe(false);+ expect(host!.querySelector('button[aria-label="Item actions"]')).not.toBeNull();+ expect(document.activeElement).toBe(getBoundary());+ }+ );++ it('gives focus to Preview after Delete without a confirmation takes away a neighbouring thumb', async () => {+ const [firstPage] = mocks.galleryItemPages;+ const listed = { ...firstPage!.items[1]!, name: 'listed', thumbnailUrl: '/images/listed/thumbnail' };++ mocks.galleryItemPages = [{ ...firstPage!, items: [...firstPage!.items, listed], total: 3 }];+ // As the shared actions remove an item only the listing holds: through the query cache, whose observers hear of+ // it only after the menu has closed.+ const deleteItems = vi.fn<ImageActions['deleteItems']>(() => {+ queryClient!.setQueriesData<GalleryItemsPage>({ queryKey: ['test-items-page'] }, (page) =>+ page ? { ...page, items: page.items.filter((item) => item.name !== listed.name), total: page.total - 1 } : page+ );+ return Promise.resolve();+ });++ mocks.imageActions = createItemMenuActions({ deleteItems });+ await render();+ const thumb = await vi.waitFor(() => {+ const element = host!.querySelector<HTMLButtonElement>(`button[aria-label="${listed.name}"]`);++ expect(element).not.toBeNull();+ return element!;+ });++ thumb.focus();+ await openMenuOn(thumb);+ await chooseMenuItem('widgets.gallery.itemMenu.deleteImage');+ await expect.poll(() => thumb.isConnected).toBe(false);++ expect(deleteItems).toHaveBeenCalledExactlyOnceWith([{ kind: 'image', name: listed.name }], expect.anything());+ await expect.poll(() => document.activeElement).toBe(getBoundary());+ });++ it("gives focus to Preview when the header's ⋮ that focus went back to goes in a later render", async () => {+ showsHeaderMenuButton = true;+ await renderWithItemMenu();+ const menuButton = host!.querySelector<HTMLButtonElement>('button[aria-label="Item actions"]')!;++ await act(() => userEvent.click(menuButton));+ await findByText('[role="menuitem"]', 'widgets.gallery.itemMenu.deleteImage');+ await expect.poll(() => document.activeElement?.closest('[role="menu"]')).not.toBeNull();+ await act(() => userEvent.keyboard('{Escape}'));+ await expect.poll(() => document.querySelector('[role="menu"]')).toBeNull();+ expect(document.activeElement).toBe(menuButton);++ // The selection goes from elsewhere, as when the Gallery deletes the shown item, and the ⋮ goes with it.+ await act(async () => {+ publishGalleryValues({ selectedImage: null, selectedImageName: null });+ await Promise.resolve();+ });++ expect(menuButton.isConnected).toBe(false);+ await expect.poll(() => document.activeElement).toBe(getBoundary());+ });++ it('gives focus back to the thumb the menu opened from when closing leaves it in place', async () => {+ await renderWithItemMenu();+ const thumb = shownThumb();++ thumb.focus();+ await openMenuOn(thumb);+ await findByText('[role="menuitem"]', 'widgets.gallery.itemMenu.deleteImage');+ // The menu takes focus, so closing it has focus to give back.+ await expect.poll(() => document.activeElement?.closest('[role="menu"]')).not.toBeNull();+ await act(() => userEvent.keyboard('{Escape}'));+ await expect.poll(() => document.querySelector('[role="menu"]')).toBeNull();++ expect(document.activeElement).toBe(thumb);+ });++ it('leaves focus where the chosen action moved it', async () => {+ const elsewhere = document.createElement('input');+ document.body.append(elsewhere);++ try {+ await renderWithItemMenu({ selectForCompare: vi.fn(() => elsewhere.focus()) });+ const thumb = shownThumb();++ thumb.focus();+ await openMenuOn(thumb);+ await chooseMenuItem('widgets.preview.selectForCompare');+ await expect.poll(() => document.querySelector('[role="menu"]')).toBeNull();++ expect(document.activeElement).toBe(elsewhere);+ } finally {+ elsewhere.remove();+ }+ });+});+describe('preview image recovery', () => {const imageRouteCommands = commands as typeof commands & {endThumbnailRouteFailures: () => Promise<void>;@@ -4078,3 +4508,88 @@ describe('preview label clear selection', () => {expect(mocks.openWidget).not.toHaveBeenCalled();});});++describe('preview select for compare', () => {+ const shown = { ...mocks.recentImages[0], boardId: 'none' };+ const other = { ...mocks.recentImages[1], boardId: 'none' };+ const status = () => host!.querySelector('[role="status"][aria-live="polite"]')?.textContent ?? '';+ const hint = () => host!.querySelector<HTMLElement>('[data-preview-compare-hint]');+ const cancelButton = () => hint()?.querySelector<HTMLButtonElement>('button[aria-label="Cancel compare"]') ?? null;+ const isComparing = () =>+ Array.from(host!.querySelectorAll('button')).some(+ (button) => (button.getAttribute('aria-label') ?? button.textContent) === 'widgets.preview.exitCompare'+ );++ beforeEach(() => {+ mocks.commands.gallery.setCompareItem.mockClear();+ // Waiting for a second image: the comparison image is the shown image itself.+ setGalleryValues({ compareImage: shown });+ });++ it('says it is waiting, from the persisted state alone, and calls it off from the hint', async () => {+ await render();++ expect(status()).toBe('Pick another image to compare with this one');+ expect(hint()).not.toBeNull();+ expect(isComparing()).toBe(false);++ await act(() => userEvent.click(cancelButton()!));+ expect(mocks.commands.gallery.setCompareItem).toHaveBeenCalledExactlyOnceWith(null);+ });++ it('compares once another image is picked, the hint giving way to the comparison', async () => {+ await render();+ await act(async () => {+ publishGalleryValues({ selectedImage: other, selectedImageName: other.imageName });+ await Promise.resolve();+ });++ expect(isComparing()).toBe(true);+ expect(hint()).toBeNull();+ expect(status()).toBe('');+ });++ it('shows nothing while no image waits', async () => {+ setGalleryValues({ compareImage: null });+ await render();++ expect(hint()).toBeNull();+ expect(status()).toBe('');+ });++ it('calls it off on Esc, after an open menu takes the first press', async () => {+ mocks.imageActions = createItemMenuActions({});+ await render();+ getBoundary().focus();+ await act(async () => {+ headerOpenItemMenu?.(10, 10, 'full');+ await Promise.resolve();+ });+ await expect.poll(() => document.activeElement?.closest('[role="menu"]')).not.toBeNull();++ await act(() => userEvent.keyboard('{Escape}'));+ await expect.poll(() => document.querySelector('[role="menu"]')).toBeNull();+ expect(mocks.commands.gallery.setCompareItem).not.toHaveBeenCalled();++ await pressKeyOn(getBoundary(), 'Escape');+ expect(mocks.commands.gallery.setCompareItem).toHaveBeenCalledExactlyOnceWith(null);+ });++ it('closes an open comparison on Esc, and leaves Esc alone once nothing is compared', async () => {+ setGalleryValues({ compareImage: other });+ await render();+ expect(isComparing()).toBe(true);++ await pressKeyOn(getBoundary(), 'Escape');+ expect(mocks.commands.gallery.setCompareItem).toHaveBeenCalledExactlyOnceWith(null);++ await act(async () => {+ publishGalleryValues({ compareImage: null });+ await Promise.resolve();+ });+ const press = await pressKeyOn(getBoundary(), 'Escape');++ expect(mocks.commands.gallery.setCompareItem).toHaveBeenCalledOnce();+ expect(press.defaultPrevented).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsxindex 55b61133b6..7d5031be51 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewStage.tsx@@ -2,6 +2,8 @@ import type { Ref } from 'react';import { Box, Flex, type BoxProps, type FlexProps, type SystemStyleObject } from '@chakra-ui/react';+import type { PreviewDensity } from './previewDensity';+/*** Share PreviewStage's fitted dot-grid surface and chrome clearance across media/live/empty states; FittedFrame* supplies bordered, shadowed media geometry.@@ -26,10 +28,14 @@ const CENTER_CHROME_INSET = 'var(--wb-center-chrome-inset, 0px)';/*** Reserve chrome clearance on the stage content box so fitting shrinks media while the dot grid continues behind- * chrome.+ * chrome. The inset already ends a gap below the islands, so the stage's own padding is not added on top of it: the+ * larger of the two is the top padding.*/const getStagePaddingTop = (padding: string | undefined): string =>- padding === undefined ? CENTER_CHROME_INSET : `calc(var(--chakra-spacing-${padding}) + ${CENTER_CHROME_INSET})`;+ padding === undefined ? CENTER_CHROME_INSET : `max(var(--chakra-spacing-${padding}), ${CENTER_CHROME_INSET})`;++/** Stage padding by density, shared by the single item's stage and the comparison stage so their geometry matches. */+export const getPreviewStagePadding = (density: PreviewDensity): string => (density === 'full' ? '6' : '3');/*** Use parent fill for inset widget bodies and flex fill for framed stages. Both establish positioning for absolutediff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 5d1101df84..ae476eb13f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -2,7 +2,7 @@ import type { SystemStyleObject } from '@chakra-ui/react';import type { QueueActiveSession, QueueItem } from '@features/queue/contracts';import type { WidgetViewProps } from '@workbench/widgetContracts';-import { Box, Flex, Stack, Text } from '@chakra-ui/react';+import { Box, Flex, HStack, Icon, Spinner, Stack, Text } from '@chakra-ui/react';import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';import {galleryImages,@@ -35,12 +35,13 @@ import { useGalleryImageRecovery, useHostGalleryBoards } from '@features/galleryimport { createGenerateFormValuesSelector } from '@features/generation/react';import {consumeQueueItemSwapProgressImage,- useQueueItemBridgeProgressImage,+ useQueueItemProgress,useQueueItemProgressImage,useQueueItemSwapProgressImage,} from '@features/queue/react';+import { useMountEffect } from '@platform/react/useMountEffect';import { captureAccountScope } from '@platform/state/accountLifecycle';-import { Button } from '@platform/ui/Button';+import { Button, IconButton } from '@platform/ui/Button';import {imageUrlToStreamingSource,progressImageToStreamingSource,@@ -48,7 +49,7 @@ import {} from '@platform/ui/streaming-image/streamingImageSource';import { useStreamingImageSource } from '@platform/ui/streaming-image/useStreamingImageSource';import { useQuery } from '@tanstack/react-query';-import { useWorkbenchFocus } from '@workbench/focusRegions';+import { releaseFocusOnRemoval, useWorkbenchFocus } from '@workbench/focusRegions';import {ImageContextMenu,useDeletionConfirmation,@@ -68,6 +69,7 @@ import {useWorkbenchCommands,useWorkbenchQueries,} from '@workbench/WorkbenchContext';+import { ImagesIcon, XIcon } from 'lucide-react';import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';import { useTranslation } from 'react-i18next';@@ -78,6 +80,7 @@ import { useLivePreviewFollow } from './livePreviewFollow';import { PreviewCompare } from './PreviewCompare';import { resolvePreviewCompareDrop } from './previewCompareDnd';import { usePreviewDensity, type PreviewDensity } from './previewDensity';+import { PreviewDropSurface } from './PreviewDropSurface';import { PreviewFilmstrip } from './PreviewFilmstrip';import {PreviewFrame,@@ -94,6 +97,7 @@ import {getPreviewVideoLoop,type PreviewComparisonMode,} from './previewSettings';+import { getPreviewStagePadding } from './PreviewStage';import { usePreviewNavigation } from './usePreviewNavigation';/** For the live footer's Details slot, which renders disabled and never fires. */@@ -173,6 +177,12 @@ const FLOATING_RAIL_SX: SystemStyleObject = {zIndex: 3,};+const getFocusedElement = (): HTMLElement | null => {+ const { activeElement } = document;++ return activeElement instanceof HTMLElement && activeElement !== document.body ? activeElement : null;+};+export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const galleryValues = useWidgetValuesSelector('gallery', (values) => values);const queueItems = useActiveProjectSelector((project) => project.queue.items);@@ -197,15 +207,25 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {[galleryValues.semanticImageQuery]);const selectedItemKey = selectedItem ? toGalleryItemKey(selectedItem) : null;+ // With nothing selected to keep showing, a session that has not produced a frame yet is still the thing to show.const activeGalleryPlaceholder =- livePreview.sessions.find((session) => session.id === livePreview.followedSessionId) ?? null;+ livePreview.sessions.find((session) => session.id === livePreview.followedSessionId) ??+ (selectedItem === null ? livePreview.startingSession : null);const shouldFollowLive = activeGalleryPlaceholder !== null;+ const compareImageKey = compareImage ? toGalleryItemKey({ kind: 'image', name: compareImage.imageName }) : null;const isComparing =- !shouldFollowLive &&- selectedItem?.kind === 'image' &&- compareImage !== null &&- toGalleryItemKey({ kind: 'image', name: compareImage.imageName }) !== selectedItemKey;- const { t } = useTranslation();+ !shouldFollowLive && selectedItem?.kind === 'image' && compareImage !== null && compareImageKey !== selectedItemKey;+ // Select for compare on the shown image: the comparison image is the selection itself until a second one is picked.+ const isCompareArmed = !shouldFollowLive && selectedItem?.kind === 'image' && compareImageKey === selectedItemKey;+ // The session the stage says is starting: one shown before its first frame, or one the shown result waits on.+ const startingCueSession = activeGalleryPlaceholder+ ? activeGalleryPlaceholder.hasOwnFrame+ ? null+ : activeGalleryPlaceholder+ : selectedItem && !isComparing && !isCompareArmed+ ? livePreview.startingSession+ : null;+ const { i18n, t } = useTranslation();const navigationBoundaryRef = useRef<HTMLDivElement | null>(null);const loupeControlsRef = useRef<PreviewLoupeControls | null>(null);// The header's zoom commands close over the controls ref, so they are stable@@ -448,10 +468,28 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {[boardItems, gallery, notifications, selectedItem]);useDndMonitor({ onDragEnd: handleCompareDrop });- const openFilmstripItemContextMenu = useCallback((item: GalleryItem, x: number, y: number) => {- setContextMenuVariant('full');- setContextMenuTarget({ itemRefs: [toGalleryItemRef(item)], items: [item], x, y });+ // The menu opens at a point, with no trigger to hand focus back to: Preview remembers what had focus instead.+ const contextMenuOpenerRef = useRef<HTMLElement | null>(null);+ const showContextMenu = useCallback((target: ImageContextMenuTarget, variant: ImageContextMenuVariant) => {+ contextMenuOpenerRef.current = getFocusedElement();+ setContextMenuVariant(variant);+ setContextMenuTarget(target);}, []);+ const getNavigationBoundary = useCallback(() => navigationBoundaryRef.current, []);+ // Resolved when focus returns, from the menu or from a deletion confirmation it opened: the opener while it is still+ // there, else Preview itself, so its keys keep working; a point opening had no opener. An opener a deletion takes away+ // only after focus is back on it (the item's filmstrip thumb, the video, the header's ⋮) hands focus to Preview+ // itself as it goes, so the target never has to wait for that render.+ const getContextMenuReturnFocus = useCallback((): HTMLElement | null => {+ const opener = contextMenuOpenerRef.current;++ return opener?.isConnected ? opener : getNavigationBoundary();+ }, [getNavigationBoundary]);+ const openFilmstripItemContextMenu = useCallback(+ (item: GalleryItem, x: number, y: number) =>+ showContextMenu({ itemRefs: [toGalleryItemRef(item)], items: [item], x, y }, 'full'),+ [showContextMenu]+ );const { selectForCompare } = imageActions;const compareFilmstripItem = useCallback((item: GalleryItem) => {@@ -464,18 +502,20 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const openItemContextMenu = useCallback((x: number, y: number, variant: ImageContextMenuVariant = 'full') => {if (contextMenuItem) {- setContextMenuVariant(variant);- setContextMenuTarget({- itemRefs: [toGalleryItemRef(contextMenuItem)],- items: [contextMenuItem],- x,- y,- });+ showContextMenu({ itemRefs: [toGalleryItemRef(contextMenuItem)], items: [contextMenuItem], x, y }, variant);}},- [contextMenuItem]+ [contextMenuItem, showContextMenu]);- const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);+ const closeContextMenu = useCallback(() => {+ // Only while the closing menu still holds focus: an action that moved it on (into a dialog it opened, say) keeps+ // it there.+ if (document.activeElement?.closest('[role="menu"]')) {+ getContextMenuReturnFocus()?.focus({ preventScroll: true });+ }++ setContextMenuTarget(null);+ }, [getContextMenuReturnFocus]);const headerItemName = shouldFollowLive ? null : (selectedItem?.name ?? null);// Publish selection/actions to hoisted chrome through an external store; clear on unmount to prevent stale@@ -519,7 +559,9 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {actionItem: shouldFollowLive ? null : contextMenuItem,actions: shouldFollowLive ? null : imageActions,boardName: headerItemName === null ? null : boardName,+ cancelCompare: isCompareArmed ? exitCompare : null,copyCurrentVideoFrame: !shouldFollowLive && contextMenuItem?.kind === 'video' ? copyCurrentVideoFrame : null,+ getRegion: getNavigationBoundary,isVideoFrameCopyAvailable: !shouldFollowLive && isVideoFrameCopyAvailable,itemName: headerItemName,openItemMenu: shouldFollowLive ? null : openItemContextMenu,@@ -534,9 +576,12 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {boardName,contextMenuItem,copyCurrentVideoFrame,+ exitCompare,+ getNavigationBoundary,hasHeaderItem,headerItemName,imageActions,+ isCompareArmed,isComparing,isLoadingBoard,isVideoFrameCopyAvailable,@@ -622,8 +667,12 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {}, [isComparing, runtime.commands, runtime.hotkeys, selectedItem?.kind, t]);return (- // Let the dot grid fill the widget; containerType bounds Details cqh sizing to this surface.- <Box ref={rootRef} containerType="size" h="full" position="relative" w="full">+ <PreviewDropSurface+ ref={rootRef}+ isComparing={isComparing}+ isFollowingLive={shouldFollowLive}+ shownKind={selectedItem?.kind ?? null}+ >{/** Show progress beneath floating Preview's title bar when the main topbar may be out of view; overlay it* without reflow.@@ -643,6 +692,18 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {tabIndex={0}w="full">+ {/* Mounted throughout, so arming, or a gap before the next image's first frame, is announced once as its text+ arrives, whatever the progress messages the hint shows meanwhile; the hints repeat it visually. */}+ <Text aria-live="polite" role="status" srOnly>+ {isCompareArmed+ ? t('widgets.preview.compareArmedHint')+ : startingCueSession+ ? t('widgets.preview.startingAnnouncement')+ : ''}+ </Text>+ {isComparing || isCompareArmed ? (+ <PreviewExitCompareHotkey key={`${projectId}:${i18n.language}`} runtime={runtime} onExit={exitCompare} />+ ) : null}{shouldFollowLive && activeGalleryPlaceholder ? (<LivePreviewdensity={density}@@ -651,59 +712,64 @@ export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {shouldAntialiasProgressImage={antialiasProgressImages}/>) : selectedItem ? (- <>- {isComparing && compareImage && selectedItem.kind === 'image' ? (- <PreviewCompare- baseImage={galleryImageItemToGalleryImage(selectedItem)}- compareImage={compareImage}- mode={comparisonMode}- runtime={runtime}- onExit={exitCompare}- onModeChange={setComparisonMode}- onSwap={swapCompareImages}- />- ) : selectedItem.kind === 'image' ? (- <SelectedImagePreview- density={density}- filmstrip={filmstrip}- isItemCurrent={isItemCurrent}- item={selectedItem}- loupeControlsRef={loupeControlsRef}- shouldAntialiasProgressImage={antialiasProgressImages}- swipe={swipeNavigation}- onContextMenu={openItemContextMenu}- />- ) : (- <SelectedVideoPreview- density={density}- filmstrip={filmstrip}- isItemCurrent={isItemCurrent}- item={selectedItem}- swipe={swipeNavigation}- videoControllerRef={videoControllerRef}- videoLoop={isVideoLooping}- onContextMenu={openItemContextMenu}- onCopyAvailabilityChange={handleVideoCopyAvailabilityChange}- onVideoLoopChange={setVideoLoop}- />- )}- <ImageContextMenu- actions={imageActions}- boards={boards}- previewVideoActions={previewVideoContextActions}- target={contextMenuTarget}- variant={contextMenuVariant}- onClose={closeContextMenu}+ isComparing && compareImage && selectedItem.kind === 'image' ? (+ <PreviewCompare+ baseImage={galleryImageItemToGalleryImage(selectedItem)}+ compareImage={compareImage}+ mode={comparisonMode}+ runtime={runtime}+ onExit={exitCompare}+ onModeChange={setComparisonMode}+ onSwap={swapCompareImages}/>- </>+ ) : selectedItem.kind === 'image' ? (+ <SelectedImagePreview+ density={density}+ filmstrip={filmstrip}+ isItemCurrent={isItemCurrent}+ item={selectedItem}+ loupeControlsRef={loupeControlsRef}+ shouldAntialiasProgressImage={antialiasProgressImages}+ startingSession={startingCueSession}+ swipe={swipeNavigation}+ onCancelCompare={isCompareArmed ? exitCompare : undefined}+ onContextMenu={openItemContextMenu}+ />+ ) : (+ <SelectedVideoPreview+ density={density}+ filmstrip={filmstrip}+ isItemCurrent={isItemCurrent}+ item={selectedItem}+ startingSession={startingCueSession}+ swipe={swipeNavigation}+ videoControllerRef={videoControllerRef}+ videoLoop={isVideoLooping}+ onContextMenu={openItemContextMenu}+ onCopyAvailabilityChange={handleVideoCopyAvailabilityChange}+ onVideoLoopChange={setVideoLoop}+ />+ )) : (<EmptyPreview />)}+ {/* Outside the branches: the menu's open state is the target, which only the menu's own close clears. A+ branch swap would unmount the menu without that close (deleting the shown item clears the selection+ before the menu hears the click), and the leftover target would reopen it on the next item. */}+ <ImageContextMenu+ actions={imageActions}+ boards={boards}+ previewVideoActions={previewVideoContextActions}+ returnFocus={getContextMenuReturnFocus}+ target={contextMenuTarget}+ variant={contextMenuVariant}+ onClose={closeContextMenu}+ />{/* Outside the branches: deleting the shown item or a live session taking over must not unmount a pendingconfirmation, nor cut its exit animation short. */}{deletionConfirmationDialog}</Stack>- </Box>+ </PreviewDropSurface>);};@@ -795,8 +861,12 @@ interface SelectedMediaPreviewProps {isItemCurrent: (itemKey: GalleryItemKey) => boolean;item: GalleryItem;loupeControlsRef?: Ref<PreviewLoupeControls>;+ /** Set only while Select for compare waits for a second image: the stage shows the hint that cancels it. */+ onCancelCompare?: () => void;onCopyAvailabilityChange?: (itemKey: GalleryItemKey, isAvailable: boolean) => void;onContextMenu: (x: number, y: number) => void;+ /** A session starting without a frame yet, which the stage says it waits for while the selection stays shown. */+ startingSession?: QueueActiveSession | null;swipe?: PreviewSwipeNavigation;videoControllerRef?: Ref<PreviewVideoFrameController>;videoLoop?: boolean;@@ -813,7 +883,6 @@ const PreviewMediaScaffold = ({ children }: { children: ReactNode }) => (</Flex>);-const getMediaStagePadding = (density: PreviewDensity): string => (density === 'full' ? '6' : '3');const { setStageElement, setZoom: setZoomReadout } = previewStageStore;const SelectedMediaPreview = ({@@ -826,12 +895,14 @@ const SelectedMediaPreview = ({isItemCurrent,item,loupeControlsRef,+ onCancelCompare,onCopyAvailabilityChange,onSourceError,onSourceLoaded,placeholderSrc,shouldAntialiasHoldImage,source,+ startingSession,swipe,onContextMenu,videoControllerRef,@@ -864,7 +935,7 @@ const SelectedMediaPreview = ({onSourceLoaded={onSourceLoaded}onVideoCopyAvailabilityChange={onCopyAvailabilityChange}onZoomChange={setZoomReadout}- padding={getMediaStagePadding(density)}+ padding={getPreviewStagePadding(density)}placeholderSrc={placeholderSrc}shouldAntialiasLiveImage={shouldAntialiasHoldImage ?? true}source={source}@@ -876,11 +947,120 @@ const SelectedMediaPreview = ({onVideoLoopChange={onVideoLoopChange}/>{swipe ? <PreviewNavButtons isVideo={item.kind === 'video'} navigation={swipe} /> : null}+ {onCancelCompare ? (+ <PreviewCompareArmedHint density={density} onCancel={onCancelCompare} />+ ) : startingSession ? (+ <PreviewStartingCue density={density} session={startingSession} />+ ) : null}</Flex>{filmstrip ? <PreviewFilmstrip {...filmstrip} density={density} selectedItemKey={toGalleryItemKey(item)} /> : null}</PreviewMediaScaffold>);+// Clear of the centre region's floating chrome, at the top of the stage: the Details panel pins to its right end.+const COMPARE_HINT_TOP = 'calc(var(--wb-center-chrome-inset, 0px) + var(--chakra-spacing-2))';+const COMPARE_HINT_MOTION_REDUCE = { animation: 'none' } as const;++/**+ * Says Select for compare is waiting for a second image, where the shown image is, with the way to call it off. Over+ * the top of the stage, under the drop zones that cover it during a drag; the filmstrip below stays free to pick from.+ * Narrower Preview keeps the text, then only its icon: the status line beside the stage says it in full.+ */+const PreviewCompareArmedHint = ({ density, onCancel }: { density: PreviewDensity; onCancel: () => void }) => {+ const { t } = useTranslation();+ const cancelLabel = t('widgets.preview.cancelCompare');+ // Cancel removes the hint and itself with it; Preview keeps the keys.+ const cancelRef = useCallback(+ (node: HTMLButtonElement | null) => (node ? releaseFocusOnRemoval(node) : undefined),+ []+ );++ return (+ <Box+ data-preview-compare-hint=""+ display="flex"+ insetInline="2"+ justifyContent="center"+ pointerEvents="none"+ position="absolute"+ top={COMPARE_HINT_TOP}+ zIndex="1"+ >+ <HStack+ animationDuration="fast"+ animationName="fade-in"+ bg="bg.panel"+ borderColor="border.emphasized"+ borderWidth="1px"+ boxShadow="md"+ gap="1.5"+ maxW="full"+ minW="0"+ pointerEvents="auto"+ ps={density === 'minimal' ? '1' : '2.5'}+ pe="1"+ py="0.5"+ rounded="full"+ _motionReduce={COMPARE_HINT_MOTION_REDUCE}+ >+ <Icon as={ImagesIcon} aria-hidden="true" boxSize="3.5" color="accent.fg" flexShrink={0} />+ {density === 'minimal' ? null : (+ // The status line announces it; read here too, it would be said twice.+ <Text aria-hidden="true" color="fg" fontSize="md" minW="0" truncate>+ {t('widgets.preview.compareArmedHint')}+ </Text>+ )}+ {density === 'full' ? (+ <Button ref={cancelRef} aria-label={cancelLabel} flexShrink={0} size="xs" variant="ghost" onClick={onCancel}>+ {t('common.cancel')}+ </Button>+ ) : (+ <IconButton+ ref={cancelRef}+ aria-label={cancelLabel}+ flexShrink={0}+ size="xs"+ tooltip={cancelLabel}+ variant="ghost"+ onClick={onCancel}+ >+ <XIcon />+ </IconButton>+ )}+ </HStack>+ </Box>+ );+};++const PREVIEW_EXIT_COMPARE_COMMAND = 'viewer.exitCompare';++/**+ * Esc calls off Select for compare while it waits, and closes an open comparison. Mounted only meanwhile, so Esc keeps+ * its other meanings the rest of the time; Preview keys it by project and language, which its registration's source+ * and title follow. An open menu or dialog takes Esc first (`resolveHotkey`).+ */+const PreviewExitCompareHotkey = ({ onExit, runtime }: { onExit: () => void; runtime: WidgetViewProps['runtime'] }) => {+ const { t } = useTranslation();++ // `onExit` clears the active project's comparison through the store's commands, the same for the mount's lifetime.+ useMountEffect(() => {+ const title = t('widgets.preview.commands.exitCompare');+ const disposers = [+ runtime.commands.register({ handler: onExit, id: PREVIEW_EXIT_COMPARE_COMMAND, title }),+ runtime.hotkeys.register({+ commandId: PREVIEW_EXIT_COMPARE_COMMAND,+ defaultKeys: ['esc'],+ id: PREVIEW_EXIT_COMPARE_COMMAND,+ title,+ }),+ ];++ return () => disposers.forEach((dispose) => dispose());+ });++ return null;+};+/** Match finished-frame geometry for live previews; saved-image navigation stays in the filmstrip. */const LivePreview = ({density,@@ -895,14 +1075,7 @@ const LivePreview = ({}) => {// Use the followed slot's own frame so another slot's progress or release cannot replace it.const progressImage = useQueueItemProgressImage(placeholder.queueItemId, placeholder.itemIndex);- // The previous slot's last frame stands in until this slot produces one of- // its own (model load, text encoding) — otherwise a sequential batch drops- // to an empty card between items.- const bridgeProgressImage = useQueueItemBridgeProgressImage(placeholder.queueItemId);- const previewImage = useStreamingImageSource({- heldLiveImage: progressImageToStreamingSource(bridgeProgressImage),- liveImage: progressImageToStreamingSource(progressImage),- });+ const previewImage = useStreamingImageSource({ liveImage: progressImageToStreamingSource(progressImage) });const source = useMemo<PreviewMediaSource | null>(() =>previewImage@@ -921,16 +1094,64 @@ const LivePreview = ({frameHeight={previewImage?.height ?? placeholder.height}frameWidth={previewImage?.width ?? placeholder.width}isLive- padding={getMediaStagePadding(density)}+ padding={getPreviewStagePadding(density)}shouldAntialiasLiveImage={shouldAntialiasProgressImage}source={source}variant="framed"/>+ {/* Followed before its first frame only when pinned, or with nothing else to show. */}+ {placeholder.hasOwnFrame ? null : <PreviewStartingCue density={density} session={placeholder} />}{filmstrip ? <PreviewFilmstrip {...filmstrip} density={density} selectedItemKey={null} /> : null}</PreviewMediaScaffold>);};+/**+ * Says what a session that has no frame of its own yet is doing, in its run's own progress message, in place of a+ * frame the Preview does not switch to until there is one. In the stage's top hint slot, without a control. Model+ * loads are not named: the server reports them without the session they are for. The Preview's status line announces+ * the gap once; the message here changes as the session prepares.+ */+const PreviewStartingCue = ({ density, session }: { density: PreviewDensity; session: QueueActiveSession }) => {+ const { t } = useTranslation();+ const label = useQueueItemProgress(session.queueItemId)?.message.trim() || t('widgets.preview.starting');++ return (+ <Box+ data-preview-starting-cue=""+ display="flex"+ insetInline="2"+ justifyContent="center"+ pointerEvents="none"+ position="absolute"+ top={COMPARE_HINT_TOP}+ zIndex="1"+ >+ <HStack+ animationDuration="fast"+ animationName="fade-in"+ bg="bg.panel"+ borderColor="border.subtle"+ borderWidth="1px"+ boxShadow="sm"+ gap="1.5"+ maxW="full"+ minW="0"+ px="2.5"+ py="1"+ rounded="full"+ _motionReduce={COMPARE_HINT_MOTION_REDUCE}+ >+ <Spinner color="fg.muted" flexShrink={0} />+ {/* A minimal Preview shows the spinner alone; the words stay for assistive technology. */}+ <Text color="fg.muted" fontSize="md" minW="0" srOnly={density === 'minimal'} truncate>+ {label}+ </Text>+ </HStack>+ </Box>+ );+};+const EmptyPreview = () => {const { t } = useTranslation();const openWidget = useOpenWorkbenchWidget();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/importPreviewFileDrop.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/importPreviewFileDrop.tsnew file mode 100644index 0000000000..bdb2d634e9--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/importPreviewFileDrop.ts@@ -0,0 +1,76 @@+import type { GalleryItem } from '@features/gallery/contracts';+import type { AccountScope } from '@platform/state/accountLifecycle';+import type { QueryClient } from '@tanstack/react-query';+import type {+ WorkbenchGalleryCommands,+ WorkbenchNotificationCommands,+ WorkbenchQueries,+} from '@workbench/workbenchStore';+import type { TFunction } from 'i18next';++import { compareGalleryItems, isGalleryImageItem } from '@features/gallery/contracts';+import { uploadGalleryFiles } from '@features/gallery/picker';+import { resolveGalleryUploadBoardId } from '@features/gallery/queries';+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';++import type { PreviewDropZone } from './PreviewDropSurface';++/**+ * Uploads media files dropped on Preview as the Gallery uploads them (the project's auto-add board, the upload's own+ * notices, unsupported files refused there) and then shows them: the newest upload is selected within its own board,+ * as a pick from Preview's mini gallery is, or on the compare zone the first image becomes the comparison. Both go to+ * the project the files were dropped on, so a switch made meanwhile leaves the open project's Preview alone; an+ * account change on the way leaves nothing behind.+ */+export const importPreviewFileDrop = async ({+ files,+ gallery,+ galleryValues,+ notifications,+ owner,+ projectId,+ queries,+ queryClient,+ t,+ zone,+}: {+ files: File[];+ gallery: Pick<WorkbenchGalleryCommands, 'selectItemInItsBoard' | 'setCompareItem'>;+ /** The project's gallery values when the files were dropped, which name its auto-add board. */+ galleryValues: Record<string, unknown>;+ notifications: WorkbenchNotificationCommands;+ /** The account the files were dropped in. */+ owner: AccountScope;+ projectId: string;+ queries: Pick<WorkbenchQueries, 'getProject'>;+ queryClient: QueryClient;+ t: TFunction;+ zone: PreviewDropZone;+}): Promise<void> => {+ const boardId = await resolveGalleryUploadBoardId(galleryValues, queryClient);+ if (!isAccountScopeCurrent(owner)) {+ return;+ }+ const uploaded = await uploadGalleryFiles(files, {+ boards: [],+ notifications,+ queryClient,+ selectedBoardId: boardId,+ t,+ });+ // Nothing stored (the upload said why, or its account is gone), or the project was closed meanwhile.+ if (uploaded.length === 0 || !queries.getProject(projectId)) {+ return;+ }+ const comparison = zone === 'compare' ? uploaded.find(isGalleryImageItem) : undefined;+ if (comparison) {+ gallery.setCompareItem(comparison, projectId);+ return;+ }+ // The newest upload, as the Gallery selects after an upload of its own.+ const newest = uploaded.reduce<GalleryItem>(+ (current, item) => (compareGalleryItems(item, current, { orderDir: 'DESC' }) < 0 ? item : current),+ uploaded[0]!+ );+ gallery.selectItemInItsBoard(newest, projectId);+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsxindex 52967ee2a5..b85922493b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/livePreviewFollow.tsx@@ -2,12 +2,14 @@ import type { QueueActiveSession, QueueProgressSession } from '@features/queue/cimport type { ReactNode } from 'react';import {- getFollowedProgressSession,+ getAutoSwitchFollowedLive,getQueueActiveSessions,getQueueProgressSessions,+ isAutoSwitchPinHeld,isGalleryProgressItem,+ pickAutoSwitch,} from '@features/queue/contracts';-import { useActiveProgressTargets, useFollowedProgressTargets } from '@features/queue/react';+import { useActiveProgressTargets, useFollowedProgressTargets, useFramedProgressTargets } from '@features/queue/react';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { createContext, use, useMemo, useState } from 'react';@@ -15,11 +17,13 @@ interface LivePreviewFollow {sessions: QueueActiveSession[];gallerySessions: QueueProgressSession[];pinnedSessionId: string | null;+ /** The session Auto-switch shows (`getAutoSwitchFollowedLive`); else null, and the Preview keeps the selected result. */+ followedSessionId: string | null;/**- * Shared live target: pinned, then newest-started running session, then first settling session in gallery order,- * else null.+ * The newest running session still without a frame of its own (loading its model, encoding its prompt) while no+ * running session is followed: what the Preview says it waits for.*/- followedSessionId: string | null;+ startingSession: QueueActiveSession | null;/** 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;@@ -30,17 +34,19 @@ const LivePreviewFollowContext = createContext<LivePreviewFollow | null>(null);/** Owned by the mounted Workbench, never persisted with project documents. */export const LivePreviewFollowProvider = ({ children }: { children: ReactNode }) => {- const { projectId, items, enabled } = useActiveProjectSelector((project) => ({+ const { projectId, items, mode } = useActiveProjectSelector((project) => ({projectId: project.id,items: project.queue.items,- // Live frames show only on In progress; Newest switches to finished results alone.- enabled: project.settings.viewerAutoSwitch === 'progress',+ mode: project.settings.viewerAutoSwitch,}));+ // Live frames show only on In progress; Newest switches to finished results alone.+ const enabled = mode === 'progress';const running = useActiveProgressTargets();const followed = useFollowedProgressTargets();+ const framed = useFramedProgressTargets();const sessions = useMemo(- () => getQueueActiveSessions(items.filter(isGalleryProgressItem), running, followed),- [items, running, followed]+ () => getQueueActiveSessions(items.filter(isGalleryProgressItem), running, followed, framed),+ [items, running, followed, framed]);const gallerySessions = useMemo(() => getQueueProgressSessions(items.filter(isGalleryProgressItem), sessions),@@ -53,18 +59,18 @@ export const LivePreviewFollowProvider = ({ children }: { children: ReactNode })const isStale =selection.projectId !== projectId ||!enabled ||- (selection.sessionId !== null &&- !sessions.some((session) => session.id === selection.sessionId && session.state === 'running'));+ (selection.sessionId !== null && !isAutoSwitchPinHeld(sessions, selection.sessionId));if (isStale && (selection.sessionId !== null || selection.projectId !== projectId)) {setSelection({ projectId, sessionId: null });}const pinnedSessionId = isStale ? null : selection.sessionId;- // Follow the highest-id running session (FIFO start order), not the latest progress frame; pins take precedence.- const newestRunningSessionId = sessions.filter((session) => session.state === 'running').at(-1)?.id ?? null;- const preferredSessionId = pinnedSessionId ?? newestRunningSessionId;- const followedSessionId = enabled- ? (getFollowedProgressSession(gallerySessions, preferredSessionId)?.id ?? null)- : null;+ // Sessions are in backend start order, so the newest running one is followed, not the one whose frame came last.+ const followedSession = getAutoSwitchFollowedLive(mode, sessions, pinnedSessionId);+ const followedSessionId = followedSession?.id ?? null;+ const startingSession =+ enabled && followedSession?.state !== 'running'+ ? (sessions.filter((session) => session.state === 'running' && !session.hasOwnFrame).at(-1) ?? null)+ : null;const { account } = useWorkbenchCommands();const value = useMemo<LivePreviewFollow>(() => ({@@ -72,14 +78,16 @@ export const LivePreviewFollowProvider = ({ children }: { children: ReactNode })gallerySessions,pinnedSessionId,followedSessionId,+ startingSession,follow: (sessionId) => {- account.updateProjectPreferences({ viewerAutoSwitch: 'progress' });- setSelection({ projectId, sessionId });+ const { mode: nextMode, pinnedId } = pickAutoSwitch({ id: sessionId, kind: 'live' });+ account.updateProjectPreferences({ viewerAutoSwitch: nextMode });+ setSelection({ projectId, sessionId: pinnedId });},pin: (sessionId) => setSelection({ projectId, sessionId }),showAll: () => setSelection({ projectId, sessionId: null }),}),- [account, sessions, gallerySessions, followedSessionId, pinnedSessionId, projectId]+ [account, sessions, gallerySessions, followedSessionId, pinnedSessionId, projectId, startingSession]);return <LivePreviewFollowContext value={value}>{children}</LivePreviewFollowContext>;};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/manifest.tsindex c754f63172..2e8061b6e9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/manifest.ts@@ -8,6 +8,7 @@ export const previewWidgetManifest: WidgetManifest = {allowFloating: true,allowMultiple: false,allowedRegions: ['center', 'right'],+ chrome: { body: 'fill' },failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },icon: EyeIcon,id: 'preview',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDockBar.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDockBar.tsnew file mode 100644index 0000000000..85c6c6fc34--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewDockBar.ts@@ -0,0 +1,18 @@+import type { PreviewDensity } from './previewDensity';++/**+ * The bar docked under Preview's stage: the filmstrip, or the compare toolbar in its place. A full-width subtle+ * surface split from the dot-grid stage by a hairline, shared so the two read as one surface family.+ */+export const PREVIEW_DOCK_BAR_PROPS = {+ bg: 'bg.subtle',+ borderColor: 'border.subtle',+ borderTopWidth: '1px',+ flexShrink: 0,+ px: '2',+ w: 'full',+} as const;++/** The bar's height at a density; minimal Preview shows no filmstrip, so it shares compact's. */+export const getPreviewDockBarHeight = (density: PreviewDensity): string =>+ density === 'full' ? '3.75rem' : '2.75rem';diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.tsindex fd2eb7dcfe..fc5f45e070 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewHeaderStore.ts@@ -55,7 +55,11 @@ export interface PreviewHeaderContext {/** The view's `useImageActions` instance (carries delete-neighbor handling). */actions: ImageActions | null;boardName: string | null;+ /** Set only while Select for compare waits for a second image: switches it off again. */+ cancelCompare: (() => void) | null;copyCurrentVideoFrame: (() => void) | null;+ /** Preview's focusable region, where a header control removed while it holds focus hands it on. */+ getRegion: (() => HTMLElement | null) | null;isVideoFrameCopyAvailable: boolean;itemName: string | null;/**@@ -72,7 +76,9 @@ const emptyContext: PreviewHeaderContext = {actionItem: null,actions: null,boardName: null,+ cancelCompare: null,copyCurrentVideoFrame: null,+ getRegion: null,isVideoFrameCopyAvailable: false,itemName: null,openItemMenu: null,@@ -131,3 +137,7 @@ registerAccountOwnedResource({});export const usePreviewStageContext = (): PreviewStageContext => stageStore.useSelector((snapshot) => snapshot);++/** Only the measured density, for readers that must not re-render on every zoom readout. */+export const usePreviewStageDensity = (): PreviewDensity | null =>+ stageStore.useSelector((snapshot) => snapshot.density);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.test.tsindex aa742b4117..a69ff97e03 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.test.ts@@ -169,6 +169,12 @@ it('shows useful controls, authored layers, adapters and family settings with raideogram4_color_palette: ['green', 'gold'],ref_images: [{ config: { type: 'ip_adapter', model: { name: 'Style' }, image: { image_name: 'style.png' }, weight: 0.6 } },+ {+ config: { type: 'flux2_reference_image', image: { image_name: 'pose.png' } },+ // Shown as Generate stores it: trimmed and capped.+ name: ` Hero pose${' '.repeat(3)}`,+ },+ { config: { type: 'flux2_reference_image', image: { image_name: 'long.png' } }, name: 'x'.repeat(200) },],control_layers: [{ model: { name: 'Edges' }, image: { image_name: 'edges.png' }, type: 'controlnet', weight: 0.75 },@@ -190,6 +196,9 @@ it('shows useful controls, authored layers, adapters and family settings with raideogram4_color_palette: 'green, gold','control_layers-0': 'Edges · controlnet · edges.png · Weight 0.75','ref_images-0': 'Style · ip_adapter · style.png · Weight 0.6',+ // A named reference leads with the name it was given.+ 'ref_images-1': 'Hero pose · flux2_reference_image · pose.png',+ 'ref_images-2': `${'x'.repeat(80)} · flux2_reference_image · long.png`,canvasLayerCount: '1 layer',});expect(entries.some((entry) => entry.value.includes('My edges') && entry.value.includes('Edges'))).toBe(true);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.tsindex e22e01e0f8..18d0621d5a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/previewMetadata.ts@@ -1,5 +1,6 @@import type { TFunction } from 'i18next';+import { normalizeReferenceImageName } from '@features/generation/settings';import { readRecordedModelRef } from '@workbench/image-actions';import { getLegacyCanvasReferenceEntries } from '@workbench/image-actions/imageRecall';@@ -260,6 +261,8 @@ export const parsePreviewMetadata = (const original =asset && isRecord(asset.original) && isRecord(asset.original.image) ? asset.original.image : asset;const parts = [+ // A Generate reference the user named leads with its name.+ key === 'ref_images' && !showLegacyReferences ? (normalizeReferenceImageName(entry.name) ?? null) : null,model,getString(config, 'type'),getString(config, 'imageName') ??diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsxindex 59fbbbdf42..385f089548 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx@@ -18,7 +18,13 @@ const interact = (action: () => void): Promise<void> =>});const Harness = () => {- const loupe = useCompareLoupe({ enabled: true, naturalWidth: 200 });+ const loupe = useCompareLoupe({+ enabled: true,+ images: [+ { id: 'pane-0', naturalWidth: 200 },+ { id: 'pane-1', naturalWidth: 200 },+ ],+ });return ([0, 1] as const).map((index) => {const pane = loupe.getPane(index)!;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.tsindex 4483d2d185..b874ffbaa8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts@@ -12,8 +12,9 @@ import { useCallback, useRef, useState, type MouseEvent, type PointerEvent as Reimport { capturePointer, releasePointer, trackPointerDown } from './loupeGestures';/**- * Apply one imperative fraction-space transform to matching-size comparison panes. Pinch zooms/pans together; one- * finger pans an already-zoomed pair.+ * Apply one imperative transform to both comparison panes in pane-fraction space: each image stays fitted to its own+ * pane, and the shared zoom and pan (fractions of each pane) keep the same region of both pictures in view, whatever+ * their pixel sizes or aspect ratios. Pinch zooms/pans together; one finger pans an already-zoomed pair.*/const MAX_ACTUAL_ZOOM = 8;@@ -54,12 +55,19 @@ export interface CompareLoupePane {const clampFraction = (f: number, scale: number): number =>scale <= 1 ? (1 - scale) / 2 : Math.min(0, Math.max(1 - scale, f));+/** The image a pane shows: its identity, and its width in its own pixels. */+export interface CompareLoupeImage {+ id: string;+ naturalWidth: number;+}+export const useCompareLoupe = ({enabled,- naturalWidth,+ images,}: {enabled: boolean;- naturalWidth: number;+ /** Each pane's image, by pane index. */+ images: readonly [CompareLoupeImage, CompareLoupeImage];}): { getPane: (index: 0 | 1) => CompareLoupePane | null; isZoomed: boolean } => {const transformRef = useRef<FractionTransform>({ fx: 0, fy: 0, scale: 1 });const panesRef = useRef<[PaneElements, PaneElements]>([@@ -71,11 +79,37 @@ export const useCompareLoupe = ({/** Every pointer currently down on either pane, in client space, in arrival order. */const pointersRef = useRef(new Map<number, PanZoomPoint>());const pinchRef = useRef<PinchGesture | null>(null);- const naturalWidthRef = useRef(naturalWidth);+ const imagesRef = useRef(images);// eslint-disable-next-line react/refs- naturalWidthRef.current = naturalWidth;+ imagesRef.current = images;+ /** The image ids the current transform was set on, by pane. */+ const pairRef = useRef<readonly [string, string] | null>(null);const [isZoomed, setIsZoomed] = useState(false);+ const writeStyles = useCallback(() => {+ const { fx, fy, scale } = transformRef.current;+ const isFit = scale === 1;++ for (const [index, pane] of panesRef.current.entries()) {+ const { frame, image } = pane;++ if (!frame || !image) {+ continue;+ }++ image.style.transform = isFit+ ? ''+ : `translate(${fx * frame.clientWidth}px, ${fy * frame.clientHeight}px) scale(${scale})`;+ image.style.transformOrigin = '0 0';++ const actualZoom = (scale * frame.clientWidth) / Math.max(1, imagesRef.current[index]?.naturalWidth ?? 1);++ image.style.imageRendering = !isFit && actualZoom >= PIXELATED_ACTUAL_ZOOM ? 'pixelated' : '';+ }++ setIsZoomed(!isFit);+ }, []);+const apply = useCallback(() => {if (rafRef.current !== null) {return;@@ -83,29 +117,19 @@ export const useCompareLoupe = ({rafRef.current = requestAnimationFrame(() => {rafRef.current = null;- const { fx, fy, scale } = transformRef.current;- const isFit = scale === 1;-- for (const pane of panesRef.current) {- const { frame, image } = pane;-- if (!frame || !image) {- continue;- }-- image.style.transform = isFit- ? ''- : `translate(${fx * frame.clientWidth}px, ${fy * frame.clientHeight}px) scale(${scale})`;- image.style.transformOrigin = '0 0';-- const actualZoom = (scale * frame.clientWidth) / Math.max(1, naturalWidthRef.current);+ writeStyles();+ });+ }, [writeStyles]);- image.style.imageRendering = !isFit && actualZoom >= PIXELATED_ACTUAL_ZOOM ? 'pixelated' : '';- }+ /** Writes the transform now, before paint, superseding a pending frame. */+ const flush = useCallback(() => {+ if (rafRef.current !== null) {+ cancelAnimationFrame(rafRef.current);+ rafRef.current = null;+ }- setIsZoomed(!isFit);- });- }, []);+ writeStyles();+ }, [writeStyles]);const setTransform = useCallback((next: FractionTransform) => {@@ -120,14 +144,22 @@ export const useCompareLoupe = ({[apply]);- /** Never below fit, never past `MAX_ACTUAL_ZOOM` of the images' own pixels. */+ /**+ * Never below fit, never past `MAX_ACTUAL_ZOOM` of the sharper image's own pixels, so a pair of different+ * resolutions can still be inspected down to the larger one's detail; the other pane goes pixelated first.+ */const constrainScale = useCallback((scale: number): number => {- const firstFrame = panesRef.current.find((pane) => pane.frame)?.frame ?? null;- const maxScale = firstFrame- ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidthRef.current) / Math.max(1, firstFrame.clientWidth))- : MAX_ACTUAL_ZOOM;+ let maxScale = 0;++ for (const [index, { frame }] of panesRef.current.entries()) {+ if (frame) {+ const naturalWidth = imagesRef.current[index]?.naturalWidth ?? 1;++ maxScale = Math.max(maxScale, (MAX_ACTUAL_ZOOM * naturalWidth) / Math.max(1, frame.clientWidth));+ }+ }- return Math.max(1, Math.min(scale, maxScale));+ return Math.max(1, Math.min(scale, maxScale === 0 ? MAX_ACTUAL_ZOOM : maxScale));}, []);const zoomAroundFraction = useCallback(@@ -204,7 +236,8 @@ export const useCompareLoupe = ({zoomAroundFraction((event.clientX - rect.left) / rect.width,(event.clientY - rect.top) / rect.height,- Math.max(1, naturalWidthRef.current / frame.clientWidth)+ // One image pixel per screen pixel for the image double-clicked.+ Math.max(1, imagesRef.current[index].naturalWidth / frame.clientWidth));},onPointerDown: (event) => {@@ -297,14 +330,36 @@ export const useCompareLoupe = ({ownerDocument.removeEventListener('pointercancel', handleDocumentPointerEnd);};},+ // Panes key their image by id, so this runs, before paint, whenever a pane's image changes.imageRefCallback: (node) => {panesRef.current[index].image = node;if (node) {- apply();+ reconcilePair();+ flush();}},});+ /**+ * Carry the zoom to a pair that keeps an image (a new selection against the same comparison image, or a swap),+ * zooming out around the view's centre where the new pair's limit is lower; a wholly new pair opens at fit.+ */+ const reconcilePair = (): void => {+ const [first, second] = imagesRef.current;+ const previous = pairRef.current;++ pairRef.current = [first.id, second.id];++ if (!previous || (previous[0] === first.id && previous[1] === second.id)) {+ return;+ }++ if (previous.includes(first.id) || previous.includes(second.id)) {+ zoomAroundFraction(0.5, 0.5, transformRef.current.scale);+ } else {+ setTransform({ fx: 0, fy: 0, scale: 1 });+ }+ };/** Starts a pan from the given pointer's position, at the current transform. */const beginPan = (pointerId: number, from: PanZoomPoint): void => {panRef.current = {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.tsindex fd727b6f2f..fed731b14c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts@@ -25,8 +25,8 @@ 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 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.+ * the image grows past fit or returns to it. Zoom never goes below the smaller of fit and 100%, so an image the fit+ * enlarges can still be seen at its own size.*//** Switch to pixelated rendering at/above this actual-pixel zoom. */@@ -100,7 +100,8 @@ export const usePreviewLoupe = ({const lastSourceTokenRef = useRef<string | null | undefined>(undefined);/** 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);+ // Not `isZoomed`: below fit (an enlarged image at 100%) is zoomed but fits, so a drag still moves the image out.+ const [isPannable, setIsPannable] = 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.@@ -139,7 +140,6 @@ export const usePreviewLoupe = ({}publishedRef.current = next;- setIsZoomed(next.isZoomed);onZoomChangeRef.current?.(next);},[measureFitRatio]@@ -179,6 +179,7 @@ export const usePreviewLoupe = ({// reaches the img (whose own style leaves it unset while the loupe is// enabled).content.style.imageRendering = !isFit && actualZoom >= PIXELATED_ACTUAL_ZOOM ? 'pixelated' : '';+ setIsPannable(transform.scale > 1);publish(transform.scale);});}, [getActualZoom, publish]);@@ -608,7 +609,7 @@ export const usePreviewLoupe = ({if (!enabled) {return {contentRefCallback: null,- isZoomed: false,+ isPannable: false,reset,stageProps: null,stageRefCallback: null,@@ -618,7 +619,7 @@ export const usePreviewLoupe = ({return {contentRefCallback,- isZoomed,+ isPannable,reset,stageProps: {onDoubleClick: handleDoubleClick,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.browser.test.tsxnew file mode 100644index 0000000000..6c5211a100--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.browser.test.tsx@@ -0,0 +1,95 @@+import type { ModelLoadInfo } from '@features/models';+import type { QueueActivity } from '@features/queue/contracts';+import type { WidgetViewProps } from '@workbench/widgetContracts';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const harness = vi.hoisted(() => ({+ activity: 'idle' as QueueActivity,+ modelLoads: [] as ModelLoadInfo[],+ remaining: 0,+}));++// The frame barrel reaches the whole workbench context; the chip itself is the platform control.+vi.mock('@workbench/widget-frame', async () => ({+ StatusWidgetChip: (await import('@platform/ui/StatusWidgetChip')).StatusWidgetChip,+}));+vi.mock('@workbench/queue-integration/useActiveQueueProgress', () => ({+ useQueueChromeActivity: () => ({+ activity: harness.activity,+ elsewhere: 0,+ modelLoads: harness.modelLoads,+ progress: undefined,+ remaining: harness.remaining,+ summary: { total: harness.remaining },+ }),+}));++import { QueueStatusWidgetView } from './QueueStatusWidgetView';++const i18n = createInstance();+await i18n.use(initReactI18next).init({+ fallbackNS: 'translation',+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+});+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let host: HTMLDivElement | null = null;+let root: Root | null = null;++const renderChip = async (): Promise<string> => {+ await act(() =>+ root?.render(+ <ChakraProvider value={system}>+ <I18nextProvider i18n={i18n}>+ <QueueStatusWidgetView {...({ presentation: 'compact', region: 'bottom' } as WidgetViewProps)} />+ </I18nextProvider>+ </ChakraProvider>+ )+ );+ return host!.textContent ?? '';+};++beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+ harness.activity = 'idle';+ harness.modelLoads = [];+ harness.remaining = 0;+});++describe('QueueStatusWidgetView', () => {+ it('names the loading model alongside the queued count', async () => {+ harness.activity = 'loading-model';+ harness.modelLoads = [{ label: 'FLUX.2 Klein 4B' }];+ harness.remaining = 2;++ expect(await renderChip()).toContain('Loading FLUX.2 Klein 4B · 2 queued');+ });++ it('says a model is loading without a blank name when none is reported yet', async () => {+ harness.activity = 'loading-model';+ harness.remaining = 1;++ const text = await renderChip();++ expect(text).toContain('Loading model · 1 queued');+ expect(text).not.toContain('widgets.queueStatus');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.tsxindex 24ed52ec98..2ca608e745 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue-status/QueueStatusWidgetView.tsx@@ -1,4 +1,5 @@import type { WidgetViewProps } from '@workbench/widgetContracts';+import type { TFunction } from 'i18next';import { Stack, Text } from '@chakra-ui/react';import { getDeterminateProgressPercent } from '@features/queue/contracts';@@ -7,17 +8,32 @@ import { StatusWidgetChip } from '@workbench/widget-frame';import { CloudOffIcon, ListOrderedIcon, PauseIcon } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { getQueueStatusChip, getQueueStatusProgress } from './queueStatusModel';+import { getQueueStatusChip, getQueueStatusProgress, type QueueStatusChip } from './queueStatusModel';++// One literal key per state, visible to search and key scans; a model-less load gets its own string.+const getChipLabel = (t: TFunction, { count, labelKey }: QueueStatusChip, model: string | undefined): string => {+ switch (labelKey) {+ case 'idle':+ return t('widgets.queueStatus.idle');+ case 'loadingModel':+ return model+ ? t('widgets.queueStatus.loadingModel', { count, model })+ : t('widgets.queueStatus.loadingModelUnnamed', { count });+ case 'offline':+ return t('widgets.queueStatus.offline', { count });+ case 'paused':+ return t('widgets.queueStatus.paused', { count });+ case 'queued':+ return t('widgets.queueStatus.queued', { count });+ }+};export const QueueStatusWidgetView = ({ presentation }: WidgetViewProps) => {const { t } = useTranslation();const { activity, elsewhere, modelLoads, progress, remaining, summary } = useQueueChromeActivity();const chip = getQueueStatusChip({ remaining }, activity);const percent = getDeterminateProgressPercent(progress?.percentage);- const label =- chip.labelKey === 'idle'- ? t('widgets.queueStatus.idle')- : t(`widgets.queueStatus.${chip.labelKey}`, { count: chip.count, model: modelLoads[0]?.label });+ const label = getChipLabel(t, chip, modelLoads[0]?.label);const showPercent = chip.labelKey === 'queued' && percent !== null;const detail = chip.labelKey === 'queued' ? progress?.message.trim() : undefined;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/queue/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/queue/manifest.tsindex 53388bf666..143477bcc6 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/queue/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/queue/manifest.ts@@ -7,6 +7,7 @@ import { ListOrderedIcon } from 'lucide-react';export const queueWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['right'],+ chrome: { body: 'fill' },failurePolicy: {isolateRenderFailure: true,onRegistrationFailure: 'disable',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/shared/AutoSwitchMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/shared/AutoSwitchMenu.tsxindex e6fc3a3363..06cbc4e3fa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/shared/AutoSwitchMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/shared/AutoSwitchMenu.tsx@@ -9,10 +9,15 @@ import { ActivityIcon, CheckIcon, GalleryHorizontalEndIcon, LocateOffIcon, typeimport { useCallback } from 'react';import { useTranslation } from 'react-i18next';-/** The Preview's modes, which the Canvas staging bar shares. */-type AutoSwitchMode = ViewerAutoSwitchMode;+/** The menu's items in display order. */+const AUTO_SWITCH_MODES = ['off', 'progress', 'latest'] as const satisfies readonly ViewerAutoSwitchMode[];-const AUTO_SWITCH_MODES: readonly AutoSwitchMode[] = ['off', 'progress', 'latest'];+/**+ * The Preview's modes, which the Canvas staging bar shares. `never` while the menu leaves one out, so a mode added to+ * the policy fails to compile until it is listed above.+ */+type AutoSwitchMode =+ Exclude<ViewerAutoSwitchMode, (typeof AUTO_SWITCH_MODES)[number]> extends never ? ViewerAutoSwitchMode : never;/** Both widgets name the modes with the staging bar's keys, so existing translations carry over. */const MODE_LABEL_KEYS: Record<AutoSwitchMode, string> = {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/shared/DropZoneLabel.tsx b/invokeai/frontend/webv2/src/workbench/widgets/shared/DropZoneLabel.tsxnew file mode 100644index 0000000000..75ff5f52cf--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/shared/DropZoneLabel.tsx@@ -0,0 +1,24 @@+import type { ReactNode } from 'react';++import { Text } from '@chakra-ui/react';++/**+ * What a drop zone over Canvas or Preview does, for gallery and desktop drags alike. It sits on its own opaque backing,+ * so it stays legible over the zone's tint and whatever light or busy image shows beneath.+ */+export const DropZoneLabel = ({ children }: { children: ReactNode }) => (+ <Text+ bg="bg.panel"+ color="fg"+ fontSize="lg"+ fontWeight="700"+ maxW="full"+ px="3"+ py="1.5"+ rounded="md"+ shadow="sm"+ textAlign="center"+ >+ {children}+ </Text>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.browser.test.tsxnew file mode 100644index 0000000000..bef1707b65--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.browser.test.tsx@@ -0,0 +1,204 @@+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';++import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { createInstance } from 'i18next';+import { act, createRef, useImperativeHandle, type Ref } 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';++const harness = vi.hoisted(() => ({ store: null as ReturnType<typeof createWorkbenchStore> | null }));++vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkbenchContextModule>()),+ useWorkbenchCommands: () => harness.store!.commands,+ useWorkbenchQueries: () => harness.store!.queries,+}));++import { useDroppedFileUpload } from './useDroppedFileUpload';++const i18n = createInstance();+let root: Root | 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());+ root = null;+ harness.store = null;+});++const renderStart = async () => {+ harness.store = createWorkbenchStore(createInitialWorkbenchState());+ const startRef = createRef<ReturnType<typeof useDroppedFileUpload>>();+ const Probe = ({ ref }: { ref: Ref<ReturnType<typeof useDroppedFileUpload>> }) => {+ const start = useDroppedFileUpload({+ pendingKey: 'widgets.preview.dropPending',+ surface: 'preview',+ uploadingKey: 'widgets.preview.dropUploading',+ });+ useImperativeHandle(ref, () => start, [start]);+ return null;+ };+ root = createRoot(document.createElement('div'));+ // A new key mounts a new hook instance, as a surface's host does when it is rebuilt for another project.+ const render = (key: number) =>+ act(() =>+ root!.render(+ <I18nextProvider i18n={i18n}>+ <Probe key={key} ref={startRef} />+ </I18nextProvider>+ )+ );+ let mounts = 0;+ await render(mounts);+ return {+ remount: () => render(++mounts),+ start: () => startRef.current!,+ store: harness.store,+ };+};++describe('useDroppedFileUpload', () => {+ it('says the upload did not start when its code cannot load, in its own words', async () => {+ const { start, store } = await renderStart();+ const run = vi.fn();++ await act(() => {+ start()([new File(['x'], 'one.png', { type: 'image/png' })], {+ // What a lost connection or a replaced deploy gives a lazy import.+ load: () => Promise.reject(new TypeError('Failed to fetch dynamically imported module: /assets/upload.js')),+ run,+ runFailedMessage: 'unused',+ });+ });++ await vi.waitFor(() =>+ expect(store.getState().notifications[0]).toMatchObject({ kind: 'error', title: 'No files uploaded. 1 failed.' })+ );+ // The browser's own wording stays out of the notice.+ expect(JSON.stringify(store.getState().notifications[0])).not.toContain('dynamically imported module');+ expect(run).not.toHaveBeenCalled();+ });++ it('reports code that fails to load at once like any other, and takes a new drop after it', async () => {+ const { start, store } = await renderStart();+ const drop = (load: () => Promise<object>) =>+ act(() => {+ start()([new File(['x'], 'one.png', { type: 'image/png' })], { load, run, runFailedMessage: 'unused' });+ });+ const run = vi.fn(() => Promise.resolve());++ await drop(() => {+ throw new Error('import refused');+ });+ await vi.waitFor(() =>+ expect(store.getState().notifications[0]).toMatchObject({ kind: 'error', title: 'No files uploaded. 1 failed.' })+ );++ await drop(() => Promise.resolve({}));+ await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1));+ });++ it('names a failure of the work itself with the caller’s message, and takes a new drop once it ended', async () => {+ const { start, store } = await renderStart();+ const drop = (run: () => Promise<void>) =>+ act(() => {+ start()([new File(['x'], 'one.png', { type: 'image/png' })], {+ load: () => Promise.resolve({}),+ run,+ runFailedMessage: "Couldn't add images to canvas",+ });+ });++ await drop(() => Promise.reject(new Error('commit refused')));+ await vi.waitFor(() =>+ expect(store.getState().notifications[0]).toMatchObject({+ kind: 'error',+ title: "Couldn't add images to canvas",+ })+ );++ const run = vi.fn(() => Promise.resolve());+ await drop(run);+ await vi.waitFor(() => expect(run).toHaveBeenCalledTimes(1));+ });++ it('holds each project to one upload at a time, however the user moves between projects', async () => {+ const { remount, start, store } = await renderStart();+ const started: { finish: () => void; projectId: string }[] = [];+ const settle = () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });+ const pendingNotices = () =>+ store+ .getState()+ .notifications.filter(+ (notice) => notice.title === 'The files you dropped are still uploading. Try again when they are done.'+ ).length;+ const drop = () =>+ act(async () => {+ start()([new File(['x'], 'one.png', { type: 'image/png' })], {+ load: () => Promise.resolve({}),+ run: (_module, { projectId }) =>+ new Promise<void>((resolve) => {+ started.push({ finish: resolve, projectId });+ }),+ runFailedMessage: 'unused',+ });+ // Past the lazy load, so an accepted drop has reached its run.+ await settle();+ });+ const finish = (index: number) =>+ act(async () => {+ started[index]!.finish();+ await settle();+ });+ const projectA = store.getState().activeProjectId;++ await drop();+ let projectB = '';+ await act(() => {+ projectB = store.commands.projects.create().id;+ });+ // A's surface host goes with the project switch; the one B gets must still know A's upload.+ await remount();+ await drop();+ await act(() => {+ store.commands.projects.switchTo(projectA);+ });+ await drop();++ expect(started.map(({ projectId }) => projectId)).toEqual([projectA, projectB]);+ expect(pendingNotices()).toBe(1);++ // A's first upload ending frees A only.+ await finish(0);+ await drop();+ await act(() => {+ store.commands.projects.switchTo(projectB);+ });+ await drop();+ expect(started.map(({ projectId }) => projectId)).toEqual([projectA, projectB, projectA]);+ expect(pendingNotices()).toBe(2);++ // B's ending frees B, and A's second upload still holds A.+ await finish(1);+ await drop();+ await act(() => {+ store.commands.projects.switchTo(projectA);+ });+ await drop();+ expect(started.map(({ projectId }) => projectId)).toEqual([projectA, projectB, projectA, projectB]);+ expect(pendingNotices()).toBe(3);++ await finish(2);+ await finish(3);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.ts b/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.tsnew file mode 100644index 0000000000..673aadc1a2--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/shared/useDroppedFileUpload.ts@@ -0,0 +1,117 @@+import type { AccountScope } from '@platform/state/accountLifecycle';+import type { WidgetTypeId } from '@workbench/widgetContracts';++import { createItemId } from '@platform/browser/randomUuid';+import { createLogger } from '@platform/logging/logger';+import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { toaster } from '@platform/ui/toaster';+import { getResolvedProjectWidgetValues } from '@workbench/widgetState';+import { useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++/** What a dropped upload is fenced to, captured at the drop. */+export interface DroppedFileUploadContext {+ /** The project's resolved gallery values at the drop, which name its auto-add board. */+ galleryValues: Record<string, unknown>;+ owner: AccountScope;+ projectId: string;+}++/** A quick upload finishes unnoticed; a slower one shows a progress notice until it does, as deletion checks do. */+const UPLOADING_NOTICE_DELAY_MS = 400;++const uploadLogger = createLogger({ area: 'file-drop-upload', namespace: 'gallery' });++// Uploads under way, by account lifetime, surface and project. Module-held: a surface's host is rebuilt when the+// project changes (a floating window is keyed by project), and the new instance must still see the upload. The account+// epoch keeps a stale lifetime's upload from holding the new one, and each key admits one upload, so the upload that+// added it is the only one that removes it.+const pendingUploads = new Set<string>();++/**+ * Runs the upload of files dropped on a surface (Canvas, Preview), loading its code on demand. Each surface, named by+ * its widget (`surface`; neither allows a second instance per project), runs one upload per project at a time: while one+ * is under way for the open project, a further drop on that surface is refused with `pendingKey`'s notice, even after+ * the surface remounts, so a slow upload is never doubled; other projects and surfaces go ahead. Past a moment a+ * progress notice (`uploadingKey`, with the file count) shows until the upload ends.+ * The drop's account, project and gallery values are captured at the drop, so nothing that changes while the code+ * loads or the files upload can retarget it. Code that cannot load (offline, or replaced by a newer deploy) is+ * reported as an upload that did not start; `runFailedMessage` names a failure of the work itself.+ */+export const useDroppedFileUpload = ({+ pendingKey,+ surface,+ uploadingKey,+}: {+ pendingKey: string;+ surface: WidgetTypeId;+ uploadingKey: string;+}) => {+ const { t } = useTranslation();+ const { notifications } = useWorkbenchCommands();+ const queries = useWorkbenchQueries();++ return useCallback(+ <Module>(+ files: File[],+ {+ load,+ run,+ runFailedMessage,+ }: {+ load: () => Promise<Module>;+ run: (module: Module, context: DroppedFileUploadContext) => Promise<void>;+ runFailedMessage: string;+ }+ ) => {+ const { activeProject, scopedDefaults } = queries.getSnapshot();+ const projectId = activeProject.id;+ const owner = captureAccountScope();+ const uploadKey = JSON.stringify([owner.epoch, surface, projectId]);+ if (pendingUploads.has(uploadKey)) {+ notifications.add({ kind: 'info', title: t(pendingKey) });+ return;+ }+ const context: DroppedFileUploadContext = {+ galleryValues: getResolvedProjectWidgetValues(activeProject, 'gallery', scopedDefaults),+ owner,+ projectId,+ };+ // The notice says what happened in the user's words; the cause goes to the log, not into the notice.+ const report = (message: string, error: unknown) => {+ if (isAccountScopeCurrent(context.owner)) {+ uploadLogger.error({ context: { files: files.length, projectId }, error, message });+ notifications.add({ kind: 'error', title: message });+ }+ };+ pendingUploads.add(uploadKey);+ const toastId = createItemId('file-drop-upload');+ const timer = setTimeout(() => {+ // Infinite: the notice goes when the upload ends, however it ends.+ toaster.create({+ duration: Number.POSITIVE_INFINITY,+ id: toastId,+ title: t(uploadingKey, { count: files.length }),+ type: 'loading',+ });+ }, UPLOADING_NOTICE_DELAY_MS);+ // From a settled promise, so a load that throws at once still ends the upload below.+ void Promise.resolve()+ .then(load)+ .then(+ (module) =>+ isAccountScopeCurrent(context.owner)+ ? run(module, context).catch((error: unknown) => report(runFailedMessage, error))+ : undefined,+ (error: unknown) => report(t('widgets.gallery.uploadFailed', { failed: files.length }), error)+ )+ .finally(() => {+ clearTimeout(timer);+ toaster.dismiss(toastId);+ pendingUploads.delete(uploadKey);+ });+ },+ [notifications, pendingKey, queries, surface, t, uploadingKey]+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/shortcuts/ShortcutGuide.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/shortcuts/ShortcutGuide.browser.test.tsxindex 7bcda095b3..da4c12ad44 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/shortcuts/ShortcutGuide.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/shortcuts/ShortcutGuide.browser.test.tsx@@ -297,7 +297,7 @@ describe('contextual status-bar guide', () => {expect(guide.element().getBoundingClientRect().width).toBeLessThan(80);await act(() => widgetWidths.setSnapshot({ ...widgetWidths.getSnapshot(), 'server-status': 250 }));await render(700);- await expect.poll(() => guide.element().getBoundingClientRect().width).toBeLessThanOrEqual(24);+ await expect.poll(() => guide.element().getBoundingClientRect().width).toBeLessThanOrEqual(28);// Icon only: the visible label is gone, and its hidden copy keeps the chip's name.expect(guide.element().querySelector('[data-shortcut-guide]')?.lastElementChild?.querySelector('p')).toBeNull();await expect.element(guide).toHaveAccessibleName('Shortcuts');@@ -312,6 +312,49 @@ describe('contextual status-bar guide', () => {await expect.poll(() => footer.scrollWidth).toBeLessThanOrEqual(footer.clientWidth);expect(notification.getBoundingClientRect().right).toBeLessThanOrEqual(700);});+ it('keeps the chip, padding included, within its space at every width as its content steps down', async () => {+ await leaveCanvas();+ await page.viewport(700, 600);+ await render(700);+ const footer = host!.querySelector('footer')!;+ // The strip's own padding is no room for widgets: the trailing chip must end where its content box does.+ const stripEnd = footer.getBoundingClientRect().right - parseFloat(getComputedStyle(footer).paddingRight);+ const notification = host!.querySelector('[data-status-bar-widget="notifications"]')!;+ const content = () => host!.querySelector<HTMLElement>('[data-shortcut-guide]')!;+ const visibleRow = () => content().lastElementChild!;+ // Text runs past its box when the chip is too narrow for it, so measure the glyphs, not the elements. The+ // visually hidden name is clipped to nothing and stays out.+ const visibleContentRight = () =>+ Math.max(+ ...[...visibleRow().children]+ .filter((child) => getComputedStyle(child).position !== 'absolute')+ .map((child) => {+ const range = document.createRange();+ range.selectNodeContents(child);+ return range.getBoundingClientRect().right;+ })+ );+ const misfits: number[] = [];+ // One pixel at a time from a hint through the label to icon only, so every fit boundary is crossed.+ for (let other = 400; visibleRow().querySelector('p'); other++) {+ expect(other).toBeLessThan(700);+ await act(() => widgetWidths.setSnapshot({ 'server-status': other }));+ // The strip and the guide measure from ResizeObserver callbacks; two frames let both settle.+ await act(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ })+ );+ if (+ notification.getBoundingClientRect().right > stripEnd + 0.5 ||+ visibleContentRight() > content().getBoundingClientRect().right + 0.5+ ) {+ misfits.push(other);+ }+ }+ expect(misfits).toEqual([]);+ });it('shrinks whole hints, preserves source in its popover, consumes Escape and restores the editing origin', async () => {const canvas = host!.querySelector<HTMLElement>('[data-testid="canvas"]')!;await act(() => canvas.focus());diff --git a/invokeai/frontend/webv2/src/workbench/widgets/shortcuts/ShortcutGuide.tsx b/invokeai/frontend/webv2/src/workbench/widgets/shortcuts/ShortcutGuide.tsxindex 372d2198b7..3cfa1b17f4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/shortcuts/ShortcutGuide.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/shortcuts/ShortcutGuide.tsx@@ -5,6 +5,7 @@ import type { WidgetViewProps } from '@workbench/widgetContracts';import { Box, Flex, Icon, Popover, Stack, Text, usePopoverContext, VisuallyHidden } from '@chakra-ui/react';import { Button } from '@platform/ui';+import { chipLabelStyles } from '@theme/recipes';import { useCurrentWorkbenchFocusTarget } from '@workbench/focusRegions';import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';import { useExtensionHotkeyDefinitions } from '@workbench/hotkeys/extensionHotkeys';@@ -20,7 +21,10 @@ import {import { getHotkeyTargetWidget, resolveHotkeyTarget } from '@workbench/hotkeys/targetWidget';import { openWorkbenchSettings } from '@workbench/settings/settingsDialogStore';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';-import { useCompactWidgetCapacity } from '@workbench/widget-frame/compactWidgetCapacity';+import {+ useCompactWidgetCapacity,+ useCompactWidgetCapacityResource,+} from '@workbench/widget-frame/compactWidgetCapacity';import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { KeyboardIcon } from 'lucide-react';@@ -143,11 +147,11 @@ const Hint = ({ hint, compact = false }: { hint: ResolvedShortcutHint; compact?:>{hint.parts.length > 0 ? <ShortcutKeycaps parts={hint.parts} /> : null}{hint.pointerKey ? (- <Text as="span" fontSize="xs">+ <Text as="span" css={compact ? chipLabelStyles : undefined} fontSize="xs">{t(hint.pointerKey)}</Text>) : null}- <Text as="span" fontSize="xs">+ <Text as="span" css={compact ? chipLabelStyles : undefined} fontSize="xs">{hint.labelKey ? t(hint.labelKey) : hint.title}</Text></Flex>@@ -175,6 +179,7 @@ export const ShortcutGuideContent = ({// The bottom-only manifest guarantees both presentations are hosted by the same Popover.Root.const popover = usePopoverContext();const capacity = useCompactWidgetCapacity();+ const capacityResource = useCompactWidgetCapacityResource();const title = onCanvas ? t('workbench.shortcuts.onCanvas', { tool: t(titleKey) }) : t(titleKey);const measurementRoot = useRef<HTMLDivElement>(null);// Keycap/text changes need a pre-paint measurement; only this widget's own root is observed.@@ -190,18 +195,20 @@ export const ShortcutGuideContent = ({if (!heading || !probe) {return;}+ // Capacity is the chip's outer width, so its padding comes out of what the content may use.+ const inset = capacityResource?.measureInset(root) ?? 0;const available = Math.max(24, Math.min(capacity, probe.getBoundingClientRect().width));const widths = items.map((item) => item.getBoundingClientRect().width + 8);- setCapacityWidth(available - 12);- setVisibleCount(getVisibleShortcutHintCount(available, heading.getBoundingClientRect().width + 12, widths));+ setCapacityWidth(available - inset);+ setVisibleCount(getVisibleShortcutHintCount(available, heading.getBoundingClientRect().width + inset, widths));const fallback = root.querySelector('[data-hint-fallback]');- setShowFallbackLabel((fallback?.getBoundingClientRect().width ?? 0) + 12 <= available);+ setShowFallbackLabel((fallback?.getBoundingClientRect().width ?? 0) + inset <= available);};const observer = new ResizeObserver(measure);observer.observe(root);measure();return () => observer.disconnect();- }, [capacity, hints, title]);+ }, [capacity, capacityResource, hints, title]);const stopKeyPropagation = useCallback((event: KeyboardEvent) => {if (isShortcutGuideSessionKey(event)) {event.stopPropagation();@@ -260,13 +267,15 @@ export const ShortcutGuideContent = ({aria-hidden="true"data-hint-fallbackalign="center"- gap="1"+ gap="2"position="absolute"visibility="hidden"w="max-content"><Icon as={KeyboardIcon} boxSize="3" />- <Text fontSize="xs">{t('workbench.shortcuts.title')}</Text>+ <Text css={chipLabelStyles} fontSize="xs" fontWeight="500">+ {t('workbench.shortcuts.title')}+ </Text></Flex><Flexaria-hidden="true"@@ -277,7 +286,9 @@ export const ShortcutGuideContent = ({visibility="hidden"w="max-content">- <Text fontSize="xs">{title}</Text>+ <Text css={chipLabelStyles} fontSize="xs">+ {title}+ </Text>{hints.map((hint) => (<Hint key={hint.id} compact hint={hint} />))}@@ -289,13 +300,17 @@ export const ShortcutGuideContent = ({<VisuallyHidden>{t('workbench.shortcuts.title')}</VisuallyHidden>) : null}{visibleCount > 0 ? (- <Text aria-hidden color="fg.muted" flexShrink={0} fontSize="xs">+ <Text aria-hidden color="fg.muted" css={chipLabelStyles} flexShrink={0} fontSize="xs">{title}</Text>) : (- <Flex align="center" gap="1">+ <Flex align="center" gap="2"><Icon as={KeyboardIcon} boxSize="3" />- {showFallbackLabel ? <Text fontSize="xs">{t('workbench.shortcuts.title')}</Text> : null}+ {showFallbackLabel ? (+ <Text css={chipLabelStyles} fontSize="xs" fontWeight="500">+ {t('workbench.shortcuts.title')}+ </Text>+ ) : null}</Flex>)}{hints.slice(0, visibleCount).map((hint) => (diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/workflow/manifest.tsindex dd05f4c70a..bf874446b0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/manifest.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/manifest.ts@@ -8,6 +8,7 @@ export const workflowWidgetManifest: WidgetManifest = {allowMultiple: false,allowedRegions: ['center', 'left', 'bottom'],bottomPanel: 'expandable',+ chrome: { body: 'fill' },failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },graphBearing: {defaultGraphId: 'workflow-graph',diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 007b6aa907..63c530b685 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -3446,6 +3446,10 @@ describe('workbenchReducer Phase 5 generation flow', () => {queueItemId: queueItem.id,type: 'routeQueueItemResults',});+ // The newest result of the batch is selected; stepping wraps around the slots.+ expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(1);+ state = workbenchReducer(state, { direction: 1, type: 'cycleStagedImage' });+ expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(0);state = workbenchReducer(state, { direction: -1, type: 'cycleStagedImage' });expect(getActiveProject(state).canvas.stagingArea.selectedImageIndex).toBe(1);@@ -6518,7 +6522,7 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(createDraftProject([]).settings.viewerAutoSwitch).toBe('progress');});- it('clears the Gallery selection while keeping the compare image and navigation stamp', () => {+ it('clears the Gallery selection and its comparison, keeping the navigation stamp', () => {let state = createInitialWorkbenchState();state = workbenchReducer(state, { item: createGalleryImageItem('selected.png'), type: 'selectGalleryItem' });@@ -6533,10 +6537,369 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(values.selectedImage).toBeNull();expect(values.selectedImageName).toBeNull();expect(values.selectedImageNames).toEqual([]);- expect(values.compareImage).toMatchObject({ name: 'compare.png' });+ // A comparison left behind would open again on whatever image is selected next.+ expect(values.compareImage).toBeNull();expect(values.selectedImageQuery).toBeDefined();});+ describe('a comparison waiting for its second image', () => {+ const galleryValues = (state: WorkbenchState) => getProjectWidgetValues(getActiveProject(state), 'gallery');+ // Select for compare on the shown image: the comparison image is the selection itself until another is picked.+ const arm = (name = 'base.png') => {+ const base = createGalleryImageItem(name);+ let state = workbenchReducer(createInitialWorkbenchState(), { item: base, type: 'selectGalleryItem' });++ state = workbenchReducer(state, { image: base, type: 'setGalleryCompareImage' });+ return state;+ };++ it('compares the next image picked against it', () => {+ const state = workbenchReducer(arm(), { item: createGalleryImageItem('other.png'), type: 'selectGalleryItem' });++ expect(galleryValues(state)).toMatchObject({+ compareImage: { name: 'base.png' },+ selectedImageName: 'image:other.png',+ });+ });++ it('is cancelled by a multi-selection, whether toggled or ranged', () => {+ const toggled = workbenchReducer(arm(), {+ item: createGalleryImageItem('other.png'),+ nextPrimaryItem: null,+ type: 'toggleGalleryItemInSelection',+ });+ const ranged = workbenchReducer(arm(), {+ itemKeys: ['image:base.png', 'image:other.png'],+ primaryItem: createGalleryImageItem('other.png'),+ type: 'setGalleryMultiSelection',+ });++ expect(galleryValues(toggled).compareImage).toBeNull();+ expect(galleryValues(toggled).selectedImageNames).toEqual(['image:base.png', 'image:other.png']);+ expect(galleryValues(ranged).compareImage).toBeNull();+ });++ it('keeps an open comparison through a multi-selection, as before', () => {+ let state = workbenchReducer(arm(), { item: createGalleryImageItem('other.png'), type: 'selectGalleryItem' });++ state = workbenchReducer(state, {+ item: createGalleryImageItem('third.png'),+ nextPrimaryItem: null,+ type: 'toggleGalleryItemInSelection',+ });++ expect(galleryValues(state).compareImage).toMatchObject({ name: 'base.png' });+ });++ it('is cancelled, not consumed, by a result Auto-switch selects', () => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);+ const queueItem = getActiveProject(state).queue.items[0]!;+ const base = createGalleryImageItem('base.png');++ state = workbenchReducer(state, { item: base, type: 'selectGalleryItem' });+ state = workbenchReducer(state, { image: base, type: 'setGalleryCompareImage' });+ // Arming turned Auto-switch Off; the user turns it back on before the run finishes.+ state = workbenchReducer(state, { settings: { viewerAutoSwitch: 'latest' }, type: 'setActiveProjectSettings' });+ state = workbenchReducer(state, {+ images: [createImage('result.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });++ expect(galleryValues(state)).toMatchObject({ compareImage: null, selectedImageName: 'image:result.png' });+ });++ it.each(['progress', 'latest'] as const)(+ 'is ended by turning Auto-switch back on (%s), so live frames never hide it',+ (mode) => {+ let state = primeGenerate();+ state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });+ state = submitGenerate(state);+ const queueItem = getActiveProject(state).queue.items[0]!;+ const base = createGalleryImageItem('base.png');++ state = workbenchReducer(state, { item: base, type: 'selectGalleryItem' });+ state = workbenchReducer(state, { image: base, type: 'setGalleryCompareImage' });+ expect(getActiveProject(state).settings.viewerAutoSwitch).toBe('off');+ // Following the run's live frames again (the Auto-switch menu, or a progress tile) ends the wait at once.+ state = workbenchReducer(state, { settings: { viewerAutoSwitch: mode }, type: 'setActiveProjectSettings' });+ expect(galleryValues(state).compareImage).toBeNull();++ // Picking another image mid-run, then the result arriving, opens no comparison.+ state = workbenchReducer(state, { item: createGalleryImageItem('other.png'), type: 'selectGalleryItem' });+ state = workbenchReducer(state, {+ images: [createImage('result.png', queueItem.id)],+ projectId: getActiveProject(state).id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemResults',+ });+ expect(galleryValues(state).compareImage).toBeNull();+ }+ );++ it('is cancelled by deleting the image it waits with', () => {+ const state = workbenchReducer(arm(), { itemKeys: ['image:base.png'], type: 'removeGalleryItems' });++ expect(galleryValues(state).compareImage).toBeNull();+ });+ });++ describe('deleting the shown image of an open comparison', () => {+ const galleryValues = (state: WorkbenchState) => getProjectWidgetValues(getActiveProject(state), 'gallery');+ const compareWithReference = () => {+ const state = workbenchReducer(createInitialWorkbenchState(), {+ item: createGalleryImageItem('candidate-1.png'),+ type: 'selectGalleryItem',+ });++ return workbenchReducer(state, {+ image: createGalleryImageItem('reference.png'),+ type: 'setGalleryCompareImage',+ });+ };++ it('keeps the comparison for the next candidate the deletion selects', () => {+ // Culling: each rejected candidate is deleted, and the next one shows against the same reference.+ let state = workbenchReducer(compareWithReference(), {+ itemKeys: ['image:candidate-1.png'],+ keepComparisonForSuccessor: true,+ type: 'removeGalleryItems',+ });++ expect(galleryValues(state).compareImage).toMatchObject({ name: 'reference.png' });+ state = workbenchReducer(state, { item: createGalleryImageItem('candidate-2.png'), type: 'selectGalleryItem' });+ expect(galleryValues(state)).toMatchObject({+ compareImage: { name: 'reference.png' },+ selectedImageName: 'image:candidate-2.png',+ });+ });++ it('ends the comparison when no next image follows, so a later selection opens none', () => {+ let state = workbenchReducer(compareWithReference(), {+ itemKeys: ['image:candidate-1.png'],+ type: 'removeGalleryItems',+ });++ expect(galleryValues(state)).toMatchObject({ compareImage: null, selectedImage: null });+ state = workbenchReducer(state, { item: createGalleryImageItem('later.png'), type: 'selectGalleryItem' });+ expect(galleryValues(state).compareImage).toBeNull();+ });++ it('keeps the comparison when the selection survives the deletion', () => {+ const state = workbenchReducer(compareWithReference(), {+ itemKeys: ['image:unrelated.png'],+ type: 'removeGalleryItems',+ });++ expect(galleryValues(state).compareImage).toMatchObject({ name: 'reference.png' });+ });++ it.each<[string, `image:${string}`[]]>([+ ['selected alone', ['image:reference.png']],+ ['selected beside an item that failed to delete', ['image:candidate-2.png', 'image:reference.png']],+ ])('ends the comparison when the next image is the comparison image, %s', (_case, itemKeys) => {+ let state = workbenchReducer(compareWithReference(), {+ itemKeys: ['image:candidate-1.png'],+ keepComparisonForSuccessor: true,+ type: 'removeGalleryItems',+ });++ state = workbenchReducer(state, {+ itemKeys,+ primaryItem: createGalleryImageItem('reference.png'),+ type: 'setGalleryMultiSelection',+ });++ expect(galleryValues(state)).toMatchObject({+ compareImage: null,+ selectedImageName: 'image:reference.png',+ selectedImageNames: itemKeys,+ });+ });++ it('ends the comparison when a plain selection of the comparison image follows', () => {+ let state = workbenchReducer(compareWithReference(), {+ itemKeys: ['image:candidate-1.png'],+ keepComparisonForSuccessor: true,+ type: 'removeGalleryItems',+ });++ state = workbenchReducer(state, { item: createGalleryImageItem('reference.png'), type: 'selectGalleryItem' });++ expect(galleryValues(state)).toMatchObject({ compareImage: null, selectedImageName: 'image:reference.png' });+ });+ });++ describe('a multi-selection landing on the comparison image of an open comparison', () => {+ const galleryValues = (state: WorkbenchState) => getProjectWidgetValues(getActiveProject(state), 'gallery');+ // Compare base.png (the comparison image) against other.png (the selection).+ const compare = () => {+ const base = createGalleryImageItem('base.png');+ let state = workbenchReducer(createInitialWorkbenchState(), { item: base, type: 'selectGalleryItem' });++ state = workbenchReducer(state, { image: base, type: 'setGalleryCompareImage' });+ return workbenchReducer(state, { item: createGalleryImageItem('other.png'), type: 'selectGalleryItem' });+ };++ it('ends the comparison on a Ctrl/Cmd-click of the comparison image, keeping the selection made', () => {+ const state = workbenchReducer(compare(), {+ item: createGalleryImageItem('base.png'),+ nextPrimaryItem: null,+ type: 'toggleGalleryItemInSelection',+ });++ // Not a comparison waiting for another image: the next plain click opens none.+ expect(galleryValues(state)).toMatchObject({+ compareImage: null,+ selectedImageName: 'image:base.png',+ selectedImageNames: ['image:other.png', 'image:base.png'],+ });+ expect(+ galleryValues(workbenchReducer(state, { item: createGalleryImageItem('third.png'), type: 'selectGalleryItem' }))+ .compareImage+ ).toBeNull();+ });++ it('ends the comparison on a range ending on the comparison image', () => {+ const state = workbenchReducer(compare(), {+ itemKeys: ['image:other.png', 'image:between.png', 'image:base.png'],+ primaryItem: createGalleryImageItem('base.png'),+ type: 'setGalleryMultiSelection',+ });++ expect(galleryValues(state)).toMatchObject({+ compareImage: null,+ selectedImageName: 'image:base.png',+ selectedImageNames: ['image:other.png', 'image:between.png', 'image:base.png'],+ });+ });++ it('keeps the comparison for a range that holds the comparison image but ends elsewhere', () => {+ const state = workbenchReducer(compare(), {+ itemKeys: ['image:base.png', 'image:between.png', 'image:third.png'],+ primaryItem: createGalleryImageItem('third.png'),+ type: 'setGalleryMultiSelection',+ });++ expect(galleryValues(state)).toMatchObject({+ compareImage: { name: 'base.png' },+ selectedImageName: 'image:third.png',+ });+ });++ it('keeps a waiting comparison restored together with its selection', () => {+ const base = createGalleryImageItem('base.png');+ // A rollback writes the selection and the comparison image back in one patch: the wait it restores stays.+ const state = workbenchReducer(createInitialWorkbenchState(), {+ type: 'patchWidgetValues',+ values: {+ compareImage: base,+ selectedImage: base,+ selectedImageName: 'image:base.png',+ selectedImageNames: ['image:base.png'],+ },+ widgetId: 'gallery',+ });++ expect(galleryValues(state).compareImage).toMatchObject({ name: 'base.png' });+ });+ });++ describe('deleting an image shown in another project', () => {+ const galleryValues = (state: WorkbenchState, projectId: string) =>+ getProjectWidgetValues(getProject(state, projectId), 'gallery');+ // The deleting project compares x.png against reference.png; the other compares x.png against y.png.+ const twoComparisons = () => {+ let state = createInitialWorkbenchState();+ const deletingProjectId = state.activeProjectId;++ state = workbenchReducer(state, { item: createGalleryImageItem('x.png'), type: 'selectGalleryItem' });+ state = workbenchReducer(state, {+ image: createGalleryImageItem('reference.png'),+ type: 'setGalleryCompareImage',+ });+ state = workbenchReducer(state, { type: 'createProject' });+ const otherProjectId = state.activeProjectId;++ state = workbenchReducer(state, { item: createGalleryImageItem('x.png'), type: 'selectGalleryItem' });+ state = workbenchReducer(state, { image: createGalleryImageItem('y.png'), type: 'setGalleryCompareImage' });+ state = workbenchReducer(state, { projectId: deletingProjectId, type: 'switchProject' });++ return { deletingProjectId, otherProjectId, state };+ };++ it('keeps the comparison for the successor only in the deleting project', () => {+ const { deletingProjectId, otherProjectId, state: compared } = twoComparisons();+ let state = workbenchReducer(compared, {+ itemKeys: ['image:x.png'],+ keepComparisonForSuccessor: true,+ type: 'removeGalleryItems',+ });++ expect(galleryValues(state, deletingProjectId).compareImage).toMatchObject({ name: 'reference.png' });+ // No successor is selected there, so no comparison is left to open on its next selection.+ expect(galleryValues(state, otherProjectId)).toMatchObject({+ compareImage: null,+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ });++ state = workbenchReducer(state, {+ item: createGalleryImageItem('later.png'),+ projectId: otherProjectId,+ type: 'selectGalleryItem',+ });+ expect(galleryValues(state, otherProjectId).compareImage).toBeNull();+ });++ it('scopes the kept comparison to the project named, whichever is active', () => {+ const { deletingProjectId, otherProjectId, state: compared } = twoComparisons();+ const state = workbenchReducer(workbenchReducer(compared, { projectId: otherProjectId, type: 'switchProject' }), {+ itemKeys: ['image:x.png'],+ keepComparisonForSuccessor: true,+ projectId: deletingProjectId,+ type: 'removeGalleryItems',+ });++ expect(galleryValues(state, deletingProjectId).compareImage).toMatchObject({ name: 'reference.png' });+ expect(galleryValues(state, otherProjectId).compareImage).toBeNull();+ });++ it("ends another project's comparison when its comparison image is deleted", () => {+ const { deletingProjectId, otherProjectId, state: compared } = twoComparisons();+ const state = workbenchReducer(compared, {+ itemKeys: ['image:y.png'],+ keepComparisonForSuccessor: true,+ type: 'removeGalleryItems',+ });++ expect(galleryValues(state, otherProjectId)).toMatchObject({+ compareImage: null,+ selectedImageName: 'image:x.png',+ });+ expect(galleryValues(state, deletingProjectId).compareImage).toMatchObject({ name: 'reference.png' });+ });+ });++ it('swaps an open comparison when its comparison image is picked', () => {+ const base = createGalleryImageItem('base.png');+ const viewing = createGalleryImageItem('viewing.png');+ let state = workbenchReducer(createInitialWorkbenchState(), { item: viewing, type: 'selectGalleryItem' });++ state = workbenchReducer(state, { image: base, type: 'setGalleryCompareImage' });+ state = workbenchReducer(state, { item: base, type: 'selectGalleryItem' });++ // The pair stays open with its sides exchanged, rather than collapsing into a comparison waiting for an image.+ expect(getProjectWidgetValues(getActiveProject(state), 'gallery')).toMatchObject({+ compareImage: { name: 'viewing.png' },+ selectedImageName: 'image:base.png',+ });+ });+it('preserves a manually selected image when later Gallery results arrive', () => {let state = primeGenerate();state = workbenchReducer(state, { destination: 'gallery', type: 'setInvocationDestination' });@@ -9795,7 +10158,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =expect(selectedSlot).toMatchObject({ itemIndex: 1, kind: 'candidate' });});- it("'off' keeps a later placeholder selected when an earlier partial result arrives", () => {+ it('follows a picked generating slot (In progress) when an earlier partial result arrives', () => {let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));const project = getActiveProject(state);const queueItem = project.queue.items[0];@@ -9821,9 +10184,10 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =];expect(selectedSlot).toMatchObject({ itemIndex: 2, kind: 'placeholder' });+ expect(updatedProject.canvas.stagingArea.autoSwitchMode).toBe('progress');});- it("'off' keeps a later placeholder selected when an earlier partial has no visible images", () => {+ it('follows a picked generating slot (In progress) when an earlier partial has no visible images', () => {let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));const project = getActiveProject(state);const queueItem = project.queue.items[0];@@ -9849,6 +10213,7 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =];expect(selectedSlot).toMatchObject({ itemIndex: 2, kind: 'placeholder' });+ expect(updatedProject.canvas.stagingArea.autoSwitchMode).toBe('progress');});it("'off' keeps a candidate selected when an earlier final result has no visible images", () => {@@ -9927,10 +10292,23 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =expect(selectedSlot).toMatchObject({ candidate: { imageName: 'candidate-1.png' }, kind: 'candidate' });});- it("'progress' selects the active in-progress placeholder", () => {+ const selectedStagingSlot = (state: WorkbenchState) => {+ const project = getActiveProject(state);++ return getCanvasStagingSlots(project.canvas, project.queue.items)[project.canvas.stagingArea.selectedImageIndex];+ };++ it("'progress' keeps each finished result on screen until the next image's first frame", () => {let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));const project = getActiveProject(state);const queueItem = project.queue.items[0];+ const firstFrame = (itemIndex: number) =>+ workbenchReducer(state, {+ itemIndex,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'noteQueueItemFirstProgressFrame',+ });state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });state = workbenchReducer(state, {@@ -9939,15 +10317,108 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =queueItemId: queueItem.id,type: 'markQueueItemBackendSubmitted',});+ state = firstFrame(1);+ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 1, kind: 'placeholder' });- expect(getCanvas(state).stagingArea.autoSwitchMode).toBe('progress');- expect(getCanvas(state).stagingArea.selectedImageIndex).toBe(0);+ state = workbenchReducer(state, {+ backendItemId: 11,+ images: [createImage('candidate-1.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });+ // The second image is loading its model: the first one's result stays shown and selected.+ expect(selectedStagingSlot(state)).toMatchObject({+ candidate: { imageName: 'candidate-1.png' },+ kind: 'candidate',+ });++ state = firstFrame(2);+ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 2, kind: 'placeholder' });+ // Later frames of the slot already shown change nothing.+ expect(firstFrame(2)).toBe(state);});- it("'progress' advances selection to the next in-progress placeholder as partials land", () => {+ it("'progress' leaves the shown result for a new run only once that run's first frame arrives", () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 1 }));+ const firstQueueItem = getActiveProject(state).queue.items[0];++ state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });+ state = workbenchReducer(state, {+ images: [createImage('first-result.png', firstQueueItem.id)],+ projectId: state.activeProjectId,+ queueItemId: firstQueueItem.id,+ type: 'routeQueueItemResults',+ });+ state = submitGenerate(primeGenerate(state, { batchCount: 2, positivePrompt: 'second prompt' }));+ const secondQueueItem = getActiveProject(state).queue.items[0];+ state = workbenchReducer(state, {+ backendItemIds: [21, 22],+ projectId: state.activeProjectId,+ queueItemId: secondQueueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });++ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'first-result.png' } });++ state = workbenchReducer(state, {+ itemIndex: 1,+ projectId: state.activeProjectId,+ queueItemId: secondQueueItem.id,+ type: 'noteQueueItemFirstProgressFrame',+ });++ expect(selectedStagingSlot(state)).toMatchObject({+ itemIndex: 1,+ kind: 'placeholder',+ queueItemId: secondQueueItem.id,+ });+ });++ it("'progress' keeps a slot that is still generating on screen when another slot's result lands", () => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 2 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });+ state = workbenchReducer(state, {+ backendItemIds: [11, 12],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ // Two GPUs: the second image streams while the first one finishes.+ state = workbenchReducer(state, {+ itemIndex: 2,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'noteQueueItemFirstProgressFrame',+ });+ state = workbenchReducer(state, {+ backendItemId: 11,+ images: [createImage('candidate-1.png', queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });++ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 2, kind: 'placeholder' });+ });++ it.each([+ ['canceled', { backendItemId: 12, type: 'markQueueItemBackendCancelled' as const }],+ ['finished without an image', { backendItemId: 12, images: [], type: 'routeQueueItemPartialResults' as const }],+ ])("'progress' falls back to the newest result when the followed slot is %s", (_label, ending) => {let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));const project = getActiveProject(state);const queueItem = project.queue.items[0];+ const firstFrame = (itemIndex: number) =>+ workbenchReducer(state, {+ itemIndex,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'noteQueueItemFirstProgressFrame',+ });state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });state = workbenchReducer(state, {@@ -9963,11 +10434,254 @@ describe('workbenchReducer canvas staging auto-switch + canvas submission', () =queueItemId: queueItem.id,type: 'routeQueueItemPartialResults',});+ state = firstFrame(2);+ state = workbenchReducer(state, { ...ending, projectId: project.id, queueItemId: queueItem.id });- expect(- getCanvasStagingSlots(getCanvas(state), getActiveProject(state).queue.items).map((slot) => slot.kind)- ).toEqual(['candidate', 'placeholder', 'placeholder']);- expect(getCanvas(state).stagingArea.selectedImageIndex).toBe(1);+ // Not the third image's placeholder, which slid into the index and has no frame yet.+ expect(selectedStagingSlot(state)).toMatchObject({+ candidate: { imageName: 'candidate-1.png' },+ kind: 'candidate',+ });+ });++ describe('picking a slot steers Auto-switch as Preview does', () => {+ const startBatch = (mode: 'latest' | 'off' | 'progress') => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 3 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0]!;+ state = workbenchReducer(state, { mode, type: 'setCanvasStagingAutoSwitch' });+ state = workbenchReducer(state, {+ backendItemIds: [11, 12, 13],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ const land = (current: WorkbenchState, backendItemId: number, imageName: string) =>+ workbenchReducer(current, {+ backendItemId,+ images: [createImage(imageName, queueItem.id)],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'routeQueueItemPartialResults',+ });+ const firstFrame = (current: WorkbenchState, itemIndex: number) =>+ workbenchReducer(current, {+ itemIndex,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'noteQueueItemFirstProgressFrame',+ });+ return { firstFrame, land, state };+ };++ it.each(['latest', 'progress'] as const)(+ "picking a finished result under '%s' pauses Auto-switch: later results and frames leave it shown",+ (mode) => {+ const { firstFrame, land, state: started } = startBatch(mode);+ let state = land(land(started, 11, 'first.png'), 12, 'second.png');+ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'second.png' } });++ // Click off the newest onto the older result.+ state = workbenchReducer(state, { imageIndex: 0, type: 'setStagedImageIndex' });+ expect(getCanvas(state).stagingArea.autoSwitchMode).toBe('off');+ state = land(firstFrame(state, 3), 13, 'third.png');++ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'first.png' } });+ }+ );++ it('stepping onto a finished result pauses Auto-switch as clicking it does', () => {+ const { land, state: started } = startBatch('latest');+ let state = land(land(started, 11, 'first.png'), 12, 'second.png');++ state = workbenchReducer(state, { direction: -1, type: 'cycleStagedImage' });++ expect(getCanvas(state).stagingArea.autoSwitchMode).toBe('off');+ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'first.png' } });+ });++ it("the canvas stepping keys' step onto the image still generating follows it", () => {+ const { land, state: started } = startBatch('latest');+ let state = land(land(started, 11, 'first.png'), 12, 'second.png');++ // What ← / → and Alt+[ / Alt+] on the canvas dispatch (`canvasHotkeyCommands`).+ state = workbenchReducer(state, { direction: 1, type: 'cycleStagedImage' });++ expect(getCanvas(state).stagingArea.autoSwitchMode).toBe('progress');+ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 3, kind: 'placeholder' });+ });++ it.each(['off', 'latest', 'progress'] as const)(+ "picking a generating slot under '%s' turns Auto-switch to In progress and pins it over newer slots",+ (mode) => {+ const { firstFrame, land, state: started } = startBatch(mode);+ let state = workbenchReducer(started, { imageIndex: 1, type: 'setStagedImageIndex' });+ expect(getCanvas(state).stagingArea.autoSwitchMode).toBe('progress');++ // Another slot (a second GPU) shows its first frame, and a result lands: the picked slot stays.+ state = land(firstFrame(state, 3), 11, 'first.png');+ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 2, kind: 'placeholder' });++ // Its own result releases the pin: the slot already streaming beside it is followed at once.+ state = land(state, 12, 'second.png');+ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 3, kind: 'placeholder' });+ }+ );++ it('follows the image already streaming when In progress is chosen from the menu', () => {+ const { firstFrame, land, state: started } = startBatch('latest');+ let state = land(started, 11, 'first.png');+ state = workbenchReducer(state, { imageIndex: 0, type: 'setStagedImageIndex' });+ state = firstFrame(state, 2);+ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'first.png' } });++ state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });++ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 2, kind: 'placeholder' });+ });++ it('follows another slot already streaming when the followed slot ends (two GPUs)', () => {+ const { firstFrame, land, state: started } = startBatch('progress');+ let state = firstFrame(firstFrame(started, 1), 2);+ // The newest slot showing frames is followed.+ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 2, kind: 'placeholder' });++ state = land(state, 12, 'second.png');++ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 1, kind: 'placeholder' });+ });++ it('lets no placeholder without a frame keep the selection under In progress when a result lands', () => {+ const { land, state: started } = startBatch('off');+ // Selected only because nothing else was staged.+ expect(selectedStagingSlot(started)).toMatchObject({ itemIndex: 1, kind: 'placeholder' });+ let state = workbenchReducer(started, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });++ state = land(state, 12, 'second.png');++ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'second.png' } });+ });++ it.each(['latest', 'progress'] as const)(+ "under '%s', a discard that would leave a placeholder without a frame selected shows the newest result",+ (mode) => {+ const { land, state: started } = startBatch(mode);+ let state = land(land(started, 11, 'first.png'), 12, 'second.png');+ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'second.png' } });++ // The third image, next in the slots, has not shown a frame.+ state = workbenchReducer(state, { type: 'discardSelectedStagedImage' });++ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'first.png' } });+ }+ );++ it("under 'off', a landed result takes the selection only while no result is selected", () => {+ const { land, state: started } = startBatch('off');+ // A placeholder the reducer selected, not the user: no result is selected.+ let state = {+ ...started,+ projects: started.projects.map((project) =>+ project.id === started.activeProjectId+ ? {+ ...project,+ canvas: { ...project.canvas, stagingArea: { ...project.canvas.stagingArea, selectedImageIndex: 1 } },+ }+ : project+ ),+ };++ state = land(state, 11, 'first.png');+ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'first.png' } });+ state = land(state, 12, 'second.png');+ expect(selectedStagingSlot(state)).toMatchObject({ candidate: { imageName: 'first.png' } });+ });++ it('releases the pin when the mode is set from the menu, and keeps it out of the project', () => {+ const { firstFrame, state: started } = startBatch('progress');+ let state = workbenchReducer(started, { imageIndex: 1, type: 'setStagedImageIndex' });+ expect(state.canvasStagingFollow?.[state.activeProjectId]?.pinnedSlotId).toBeTruthy();+ expect(JSON.stringify(getActiveProject(state))).not.toContain('pinnedSlotId');++ state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });+ expect(state.canvasStagingFollow?.[state.activeProjectId]?.pinnedSlotId ?? null).toBeNull();+ state = firstFrame(state, 3);++ expect(selectedStagingSlot(state)).toMatchObject({ itemIndex: 3, kind: 'placeholder' });+ });+ });++ it('keeps each open project its own follow state, and drops it with the project', () => {+ const startRun = (current: WorkbenchState) => {+ let state = submitGenerate(primeGenerate(withInvocationDestination(current, 'canvas'), { batchCount: 2 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0]!;+ state = workbenchReducer(state, { mode: 'progress', type: 'setCanvasStagingAutoSwitch' });+ state = workbenchReducer(state, {+ backendItemIds: [11, 12],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });+ return { projectId: project.id, queueItemId: queueItem.id, state };+ };+ const selectedIn = (state: WorkbenchState, projectId: string) => {+ const project = state.projects.find((candidate) => candidate.id === projectId)!;+ return getCanvasStagingSlots(project.canvas, project.queue.items)[project.canvas.stagingArea.selectedImageIndex];+ };+ const a = startRun(createInitialWorkbenchState());+ // Pin the second image of A, then open B and start a run there.+ let state = workbenchReducer(a.state, { imageIndex: 1, type: 'setStagedImageIndex' });+ state = workbenchReducer(state, { type: 'createProject' });+ const b = startRun(state);+ state = b.state;++ // A first frame in A, now in the background, is recorded and followed there; B is left alone.+ state = workbenchReducer(state, {+ itemIndex: 1,+ projectId: a.projectId,+ queueItemId: a.queueItemId,+ type: 'noteQueueItemFirstProgressFrame',+ });+ expect(state.canvasStagingFollow?.[a.projectId]?.framedSlotIds).toEqual([`${a.queueItemId}:0`]);+ // A's pin holds over its first image's frame.+ expect(selectedIn(state, a.projectId)).toMatchObject({ itemIndex: 2, kind: 'placeholder' });+ expect(state.canvasStagingFollow?.[b.projectId]).toBeUndefined();++ // A pick in B pins B's slot and leaves A's pin as it was.+ state = workbenchReducer(state, { imageIndex: 0, type: 'setStagedImageIndex' });+ expect(state.canvasStagingFollow?.[b.projectId]?.pinnedSlotId).toBe(`${b.queueItemId}:0`);+ expect(state.canvasStagingFollow?.[a.projectId]?.pinnedSlotId).toBe(`${a.queueItemId}:1`);++ // Closing A takes its follow state with it.+ state = workbenchReducer(state, { projectId: a.projectId, type: 'closeProject' });+ expect(state.canvasStagingFollow?.[a.projectId]).toBeUndefined();+ expect(state.canvasStagingFollow?.[b.projectId]?.pinnedSlotId).toBe(`${b.queueItemId}:0`);+ });++ it.each(['off', 'latest'] as const)("'%s' keeps its selection when a slot shows its first frame", (mode) => {+ let state = submitGenerate(primeGenerate(undefined, { batchCount: 2 }));+ const project = getActiveProject(state);+ const queueItem = project.queue.items[0];++ state = workbenchReducer(state, { mode, type: 'setCanvasStagingAutoSwitch' });+ state = workbenchReducer(state, {+ backendItemIds: [11, 12],+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'markQueueItemBackendSubmitted',+ });++ const next = workbenchReducer(state, {+ itemIndex: 2,+ projectId: project.id,+ queueItemId: queueItem.id,+ type: 'noteQueueItemFirstProgressFrame',+ });++ // The frame is remembered for In progress, outside the project; the project and its selection stay as they were.+ expect(getActiveProject(next)).toBe(getActiveProject(state));+ expect(next.canvasStagingFollow?.[project.id]?.framedSlotIds).toEqual([`${queueItem.id}:1`]);});const createCanvasGenerateSnapshot = () => ({diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex c1ac699df1..8c2d1f91ad 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -118,7 +118,11 @@ import {type WorkbenchActionOrigin,} from './autoRoutePolicy';import { createNewCanvasState, loadCanvasState } from './canvasMigration';-import { applyCanvasProjectMutation, type CanvasProjectMutation } from './canvasProjectMutations';+import {+ applyCanvasProjectMutation,+ pickStagedSlotAutoSwitch,+ type CanvasProjectMutation,+} from './canvasProjectMutations';import { gateProjectCanvases } from './projectCanvasGate';import {addProjectWorkflow,@@ -166,7 +170,12 @@ import {syncGenerateWidgetValuesWithModels,} from '@features/generation/settings';import { getQueueSourceResultSelection, MAX_QUEUE_BATCH_ITEMS } from '@features/queue';-import { getQueueItemSnapshotLabel } from '@features/queue/contracts';+import {+ getAutoSwitchFollowedLive,+ getQueueItemSnapshotLabel,+ pickAutoSwitch,+ selectsLandedResult,+} from '@features/queue/contracts';import {clearDeletedUpscaleInput,cloneUpscaleWidgetValues,@@ -175,6 +184,7 @@ import {createDefaultUpscaleWidgetValues,getSpandrelNativeScale,getUpscaleOutputDimensions,+ getUpscaleSubmissionSource,getUpscaleValidationReasons,isUpscaleSourceMetadataCurrent,normalizeUpscaleWidgetValues,@@ -207,7 +217,6 @@ import {import {getCanvasStagingSlotCount,getCanvasStagingSlots,- getFirstCanvasPlaceholderSlotIndex,type CanvasStagingSlot,isCancellableQueueItem,isUnsubmittedQueueItem,@@ -495,6 +504,8 @@ type WorkbenchReducerAction =videos?: GeneratedVideoContract[];}| { type: 'markQueueItemBackendCancelled'; projectId: string; queueItemId: string; backendItemId: number }+ /** A slot of the run showed its first progress frame of its own: Canvas staging on 'progress' follows it. */+ | { type: 'noteQueueItemFirstProgressFrame'; projectId: string; queueItemId: string; itemIndex: number }| { type: 'setQueueItemCancellationPending'; projectId: string; queueItemId: string; pending: boolean }| {type: 'setQueueItemLocalRecoveryState';@@ -576,7 +587,18 @@ type WorkbenchReducerAction =changes: Partial<Pick<GalleryItem, 'boardId' | 'starred'>>;itemKeys: GalleryItemKey[];}- | { type: 'removeGalleryItems'; itemKeys: GalleryItemKey[] }+ | {+ type: 'removeGalleryItems';+ itemKeys: GalleryItemKey[];+ /**+ * The caller selects a next image in `projectId` right after, as deleting the shown item does: that project's open+ * comparison stays for it. Otherwise, and in every other project, a removal that leaves nothing selected ends the+ * comparison.+ */+ keepComparisonForSuccessor?: boolean;+ /** The project deleting; the active one when omitted. */+ projectId?: string;+ }| {type: 'reconcileDeletedGalleryBoard';outcome: GalleryBoardDeletionResult;@@ -1233,43 +1255,24 @@ const resolveStagingSelectionIndexForSlots = ({project: Project;slotCount: number;}): number => {- if (project.canvas.stagingArea.autoSwitchMode === 'progress') {- const placeholderIndex = getFirstCanvasPlaceholderSlotIndex(- getCanvasWithPendingImages(project.canvas, pendingImages),- project.queue.items- );-- if (placeholderIndex !== -1) {- return placeholderIndex;- }-- const firstIncomingSlotIndex = getCanvasStagingCandidateSlotIndex(project, pendingImages, incomingImages[0]);-- return firstIncomingSlotIndex !== -1- ? firstIncomingSlotIndex- : clampStagedImageIndex(project.canvas.stagingArea.selectedImageIndex, slotCount);- }+ // A landed result takes the selection by Auto-switch's rule; `followCanvasStaging` then shows a followed live slot.+ const slots = getCanvasStagingSlots(getCanvasWithPendingImages(project.canvas, pendingImages), project.queue.items);+ const selectedSlot = previousSelectedSlot ?? getSelectedCanvasStagingSlot(project);+ const preservedSlotIndex = findPreservedCanvasStagingSlotIndex(slots, selectedSlot);+ const { autoSwitchMode } = project.canvas.stagingArea;+ const newestIncoming = incomingImages.at(-1);- if (project.canvas.stagingArea.autoSwitchMode === 'off' || incomingImages.length === 0) {- const selectedSlot = previousSelectedSlot ?? getSelectedCanvasStagingSlot(project);- const preservedSlotIndex = findPreservedCanvasStagingSlotIndex(- getCanvasStagingSlots(getCanvasWithPendingImages(project.canvas, pendingImages), project.queue.items),- selectedSlot- );+ if (newestIncoming && selectsLandedResult(autoSwitchMode, selectedSlot?.kind === 'candidate')) {+ const newestSlotIndex = getCanvasStagingCandidateSlotIndex(project, pendingImages, newestIncoming);- if (preservedSlotIndex !== -1) {- return preservedSlotIndex;+ if (newestSlotIndex !== -1) {+ return newestSlotIndex;}-- return clampStagedImageIndex(project.canvas.stagingArea.selectedImageIndex, slotCount);}- const selectedImage = pendingImages[pendingImages.length - 1] ?? incomingImages[incomingImages.length - 1];- const selectedSlotIndex = getCanvasStagingCandidateSlotIndex(project, pendingImages, selectedImage);-- return selectedSlotIndex === -1- ? clampStagedImageIndex(project.canvas.stagingArea.selectedImageIndex, slotCount)- : selectedSlotIndex;+ return preservedSlotIndex !== -1+ ? preservedSlotIndex+ : clampStagedImageIndex(project.canvas.stagingArea.selectedImageIndex, slotCount);};const stageCanvasResultImages = (@@ -1394,19 +1397,202 @@ const appendCanvasStagingCandidate = (project: Project, candidate: CanvasStaging};};+type CanvasStagingFollow = NonNullable<WorkbenchState['canvasStagingFollow']>[string];++const NO_STAGING_FOLLOW: CanvasStagingFollow = { framedSlotIds: [], pinnedSlotId: null };++const updateCanvasStagingFollow = (+ state: WorkbenchState,+ projectId: string,+ update: (follow: CanvasStagingFollow) => CanvasStagingFollow+): WorkbenchState => {+ const previous = state.canvasStagingFollow?.[projectId] ?? NO_STAGING_FOLLOW;+ const next = update(previous);++ return next === previous+ ? state+ : { ...state, canvasStagingFollow: { ...state.canvasStagingFollow, [projectId]: next } };+};++/** A placeholder showed its first frame of its own: Auto-switch may follow it from now on (`followCanvasStaging`). */+const recordCanvasStagingFrame = (+ state: WorkbenchState,+ projectId: string,+ queueItemId: string,+ itemIndex: number+): WorkbenchState => {+ const project = state.projects.find((candidate) => candidate.id === projectId);+ const slot = project+ ? getCanvasStagingSlots(project.canvas, project.queue.items).find(+ (candidate) =>+ candidate.kind === 'placeholder' && candidate.queueItemId === queueItemId && candidate.itemIndex === itemIndex+ )+ : undefined;++ return slot+ ? updateCanvasStagingFollow(state, projectId, (follow) =>+ follow.framedSlotIds.includes(slot.id)+ ? follow+ : { ...follow, framedSlotIds: [...follow.framedSlotIds, slot.id] }+ )+ : state;+};++/**+ * Keeps the pin with the user's picks (`pickStagedSlotAutoSwitch`, the one pick rule): a generating slot picked pins+ * it, a finished result picked or a mode set from the menu releases it, as Preview's pin does.+ */+const updateCanvasStagingPin = (+ state: WorkbenchState,+ projectId: string,+ mutation: CanvasProjectMutation+): WorkbenchState => {+ const project = state.projects.find((candidate) => candidate.id === projectId);+ const isPick = mutation.type === 'setStagedImageIndex' || mutation.type === 'cycleStagedImage';++ if (!project || (!isPick && mutation.type !== 'setCanvasStagingAutoSwitch')) {+ return state;+ }++ const slot = isPick ? getSelectedCanvasStagingSlot(project) : undefined;+ const pinnedSlotId = slot ? pickStagedSlotAutoSwitch(slot).pinnedId : null;++ return updateCanvasStagingFollow(state, projectId, (follow) =>+ follow.pinnedSlotId === pinnedSlotId ? follow : { ...follow, pinnedSlotId }+ );+};++/**+ * Shows what Auto-switch follows among the staging slots, with the rules Preview follows: under In progress the pinned+ * placeholder while it remains, else the newest one with a frame of its own; otherwise, under In progress and Newest,+ * never a placeholder with nothing to show when a result is staged (the newest one takes the selection). Off leaves the+ * selection alone. The reducer cannot tell a placeholder waiting to start from one running, so every placeholder counts+ * as running: a pin holds until its placeholder is gone.+ */+const followCanvasStaging = (+ project: Project,+ slots: readonly CanvasStagingSlot[],+ follow: CanvasStagingFollow+): Project => {+ const { autoSwitchMode, selectedImageIndex } = project.canvas.stagingArea;++ if (autoSwitchMode === 'off') {+ return project;+ }++ const lives = slots.flatMap((slot) =>+ slot.kind === 'placeholder'+ ? [{ hasOwnFrame: follow.framedSlotIds.includes(slot.id), id: slot.id, state: 'running' as const }]+ : []+ );+ const followed = getAutoSwitchFollowedLive(autoSwitchMode, lives, follow.pinnedSlotId);+ const nextIndex = followed+ ? slots.findIndex((slot) => slot.id === followed.id)+ : slots[selectedImageIndex]?.kind === 'placeholder'+ ? getLatestCandidateSlotIndex(project, slots)+ : -1;++ return nextIndex === -1 || nextIndex === selectedImageIndex+ ? project+ : {+ ...project,+ canvas: { ...project.canvas, stagingArea: { ...project.canvas.stagingArea, selectedImageIndex: nextIndex } },+ };+};++/** Forgets frames and pins of placeholders that have gone, so a slot id a retry brings back starts fresh. */+const pruneCanvasStagingFollow = (+ follow: CanvasStagingFollow,+ slots: readonly CanvasStagingSlot[]+): CanvasStagingFollow => {+ const placeholderIds = new Set(slots.flatMap((slot) => (slot.kind === 'placeholder' ? [slot.id] : [])));+ const framedSlotIds = follow.framedSlotIds.filter((id) => placeholderIds.has(id));+ const pinnedSlotId =+ follow.pinnedSlotId !== null && placeholderIds.has(follow.pinnedSlotId) ? follow.pinnedSlotId : null;++ return framedSlotIds.length === follow.framedSlotIds.length && pinnedSlotId === follow.pinnedSlotId+ ? follow+ : { framedSlotIds, pinnedSlotId };+};++/**+ * After every action: each project whose staging, queue or follow state changed shows what Auto-switch follows, and+ * the follow state keeps only placeholders that remain and projects that are open.+ */+const reconcileCanvasStagingFollow = (previous: WorkbenchState, next: WorkbenchState): WorkbenchState => {+ if (next.projects === previous.projects && next.canvasStagingFollow === previous.canvasStagingFollow) {+ return next;+ }++ const previousById = new Map(previous.projects.map((project) => [project.id, project]));+ const follows: Record<string, CanvasStagingFollow> = {};+ let didChangeProjects = false;+ const projects = next.projects.map((project) => {+ const before = previousById.get(project.id);+ const follow = next.canvasStagingFollow?.[project.id];+ const isUnchanged =+ before !== undefined &&+ before.canvas.stagingArea === project.canvas.stagingArea &&+ before.canvas.documentRevision === project.canvas.documentRevision &&+ before.queue === project.queue &&+ follow === previous.canvasStagingFollow?.[project.id];++ if (isUnchanged) {+ if (follow) {+ follows[project.id] = follow;+ }+ return project;+ }++ const slots = getCanvasStagingSlots(project.canvas, project.queue.items);+ const pruned = pruneCanvasStagingFollow(follow ?? NO_STAGING_FOLLOW, slots);+ const followed = followCanvasStaging(project, slots, pruned);++ if (pruned.framedSlotIds.length > 0 || pruned.pinnedSlotId !== null) {+ follows[project.id] = pruned;+ }+ didChangeProjects ||= followed !== project;+ return followed;+ });++ // Closed projects, and projects with nothing left to follow, drop their entry.+ const previousFollows = next.canvasStagingFollow ?? {};+ const followIds = Object.keys(follows);+ const didChangeFollows =+ followIds.length !== Object.keys(previousFollows).length ||+ followIds.some((projectId) => follows[projectId] !== previousFollows[projectId]);++ return didChangeFollows || didChangeProjects+ ? {+ ...next,+ ...(didChangeProjects ? { projects } : {}),+ ...(didChangeFollows ? { canvasStagingFollow: follows } : {}),+ }+ : next;+};++/** The slot of the result staged last, or -1 when nothing is staged. */+const getLatestCandidateSlotIndex = (project: Project, slots: readonly CanvasStagingSlot[]): number => {+ const latest = project.canvas.stagingArea.pendingImages.at(-1);++ return latest ? slots.findIndex((slot) => slot.kind === 'candidate' && slot.candidate === latest) : -1;+};+const clampCanvasStagingSelection = (project: Project, previousSelectedSlot?: CanvasStagingSlot): Project => {const slots = getCanvasStagingSlots(project.canvas, project.queue.items);const slotCount = slots.length;- const placeholderIndex =- project.canvas.stagingArea.autoSwitchMode === 'progress'- ? getFirstCanvasPlaceholderSlotIndex(project.canvas, project.queue.items)- : -1;const preservedSlotIndex = findPreservedCanvasStagingSlotIndex(slots, previousSelectedSlot);+ // On 'progress', a followed slot that ends without a result (canceled, or finished with no image) hands the canvas+ // to the newest result rather than to whatever placeholder takes its index, which has no frame yet.+ const fallbackIndex =+ project.canvas.stagingArea.autoSwitchMode === 'progress' && previousSelectedSlot?.kind === 'placeholder'+ ? getLatestCandidateSlotIndex(project, slots)+ : -1;const selectedImageIndex =- placeholderIndex !== -1- ? placeholderIndex- : preservedSlotIndex !== -1- ? preservedSlotIndex+ preservedSlotIndex !== -1+ ? preservedSlotIndex+ : fallbackIndex !== -1+ ? fallbackIndex: clampStagedImageIndex(project.canvas.stagingArea.selectedImageIndex, slotCount);const isVisible = slotCount > 0 ? project.canvas.stagingArea.isVisible : false;@@ -1442,6 +1628,55 @@ const getGalleryItemFromPersistedValue = (values: Record<string, unknown>, valueselectedImageName: null,});+const getPersistedPrimaryGalleryItemKey = (values: Record<string, unknown>): GalleryItemKey | null => {+ if (typeof values.selectedImageName === 'string') {+ return canonicalizeGalleryItemKey(values.selectedImageName);+ }++ const selectedItem = getSelectedGalleryItemFromValues(values);++ return selectedItem ? toGalleryItemKey(selectedItem) : null;+};++/**+ * Preview compares the stored comparison image with a different selected image. While both are the same image, Select+ * for compare is waiting for the second one (`armed`).+ */+const getGalleryCompareState = (values: Record<string, unknown>): 'armed' | 'comparing' | null => {+ const compareItem = getGalleryItemFromPersistedValue(values, values.compareImage);+ const primaryKey = getPersistedPrimaryGalleryItemKey(values);++ if (!compareItem || primaryKey === null || parseGalleryItemKey(primaryKey).kind !== 'image') {+ return null;+ }++ return primaryKey === toGalleryItemKey(compareItem) ? 'armed' : 'comparing';+};++/**+ * What selecting `item` does to the comparison. A video cannot be compared. Picking the comparison image of an open pair+ * swaps the pair, as Swap does; any other selection landing on the comparison image ends it (`settleGalleryValues`).+ */+const getSelectionComparePatch = (values: Record<string, unknown>, item: GalleryItem): Record<string, unknown> => {+ if (item.kind === 'video') {+ return { compareImage: null };+ }++ const compareItem = getGalleryItemFromPersistedValue(values, values.compareImage);++ if (+ !compareItem ||+ toGalleryItemKey(compareItem) !== toGalleryItemKey(item) ||+ getGalleryCompareState(values) !== 'comparing'+ ) {+ return {};+ }++ const previousItem = getSelectedGalleryItemFromValues(values);++ return { compareImage: previousItem?.kind === 'image' ? previousItem : null };+};+/*** Deep-clones an already-v2 canvas state and normalizes staging candidate placements. Not a* migration boundary: callers with genuinely unknown/legacy input must run@@ -3444,7 +3679,9 @@ const getLocallyKnownGalleryItemsOnBoard = (const removeGalleryItemsFromAllProjects = (state: WorkbenchState,- removedItemKeys: ReadonlySet<GalleryItemKey>+ removedItemKeys: ReadonlySet<GalleryItemKey>,+ /** The deleting project, when it selects a next image right after; only its comparison waits for that image. */+ successorProjectId: string | null = null): WorkbenchState => {if (removedItemKeys.size === 0) {return state;@@ -3466,6 +3703,7 @@ const removeGalleryItemsFromAllProjects = ();let didChange = false;const projects = state.projects.map((project) => {+ const keepComparisonForSuccessor = project.id === successorProjectId;const withoutGalleryItems = updateProjectWidgetValues(project, 'gallery', (values) => {const selectedImage = values.selectedImage;const compareImage = values.compareImage;@@ -3482,8 +3720,14 @@ const removeGalleryItemsFromAllProjects = ();const nextSelectedItemKeys = selectedItemKeys.filter((key) => !removedItemKeys.has(key));const nextSelectedImage = selectedImageKey && removedItemKeys.has(selectedImageKey) ? null : selectedImage;- const nextCompareImage = compareImageKey && removedItemKeys.has(compareImageKey) ? null : compareImage;const nextSelectedImageName = selectedNameKey && removedItemKeys.has(selectedNameKey) ? null : selectedImageName;+ // As clearing the selection does: a comparison left without a selection would open on whatever image is selected+ // next, unless the caller is about to select the next image itself.+ const nextCompareImage =+ (compareImageKey && removedItemKeys.has(compareImageKey)) ||+ (!keepComparisonForSuccessor && !nextSelectedImage && !nextSelectedImageName)+ ? null+ : compareImage;if (nextRecentImages.length === recentImages.length &&@@ -3617,15 +3861,17 @@ const updateGalleryValuesAndStopAutoSwitch = (getValues: (values: Record<string, unknown>) => Record<string, unknown>,projectId = state.activeProjectId): WorkbenchState =>- updateProjectById(state, projectId, (project) =>- updateProjectWidgetValues(- project.settings.viewerAutoSwitch === 'off'+ updateProjectById(state, projectId, (project) => {+ const { mode } = pickAutoSwitch({ kind: 'result' });++ return updateProjectWidgetValues(+ project.settings.viewerAutoSwitch === mode? project- : { ...project, settings: { ...project.settings, viewerAutoSwitch: 'off' } },+ : { ...project, settings: { ...project.settings, viewerAutoSwitch: mode } },'gallery',getValues- )- );+ );+ });const updateQueueItem = (project: Project, queueItemId: string, getItem: (item: QueueItem) => QueueItem): Project => {let didChange = false;@@ -3747,7 +3993,7 @@ 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>): boolean =>- typeof galleryValues.selectedImageName !== 'string' || project.settings.viewerAutoSwitch !== 'off';+ selectsLandedResult(project.settings.viewerAutoSwitch, typeof galleryValues.selectedImageName === 'string');const getGalleryResultSelectionValues = (galleryValues: Record<string, unknown>,@@ -3760,7 +4006,8 @@ const getGalleryResultSelectionValues = (const mediaKind = toGalleryMediaKind(gallerySettings.mediaFilter);return {- ...(item.kind === 'video' ? { compareImage: null } : {}),+ // A comparison waiting for its second image is the user's to complete; a result arriving does not complete it.+ ...(item.kind === 'video' || getGalleryCompareState(galleryValues) === 'armed' ? { compareImage: null } : {}),selectedImage: item,selectedImageName: itemKey,selectedImageNames: [itemKey],@@ -4014,13 +4261,18 @@ const enqueueCompiledSnapshot = (const videoSettings = route.sourceId === 'video' ? normalizeVideoWidgetValues(widgetStates.video.values) : null;const backendGraph = graph.backendGraph;const canvasGenerateSettings = route.sourceId === 'canvas' ? normalizeGenerateSettings(generate?.values) : null;- // Upscale has no dynamic prompts switch: its prompt always runs as typed.+ // Upscale runs the prompt it shares with Generate, template and dynamic prompts included, from the same snapshot its+ // prompt text was resolved from.+ const upscalePromptDraft = upscaleSettings ? getPromptDraftFromValues(widgetStates.generate?.values ?? {}) : null;const sourceGenerateSettings =route.sourceId === 'canvas'? canvasGenerateSettings: route.sourceId === 'generate'? generateSettings- : (videoSettings ?? (upscaleSettings ? { ...upscaleSettings, dynamicPromptsEnabled: false } : null));+ : (videoSettings ??+ (upscaleSettings && upscalePromptDraft+ ? getUpscaleSubmissionSource(upscaleSettings, upscalePromptDraft)+ : null));// Resolve template-merged prompts and seeds here, where Generate, Canvas, Upscale and Video submissions converge; the// planner decides whether the expansion counts.const submissionPlan = sourceGenerateSettings@@ -4172,7 +4424,7 @@ const enqueueCompiledSnapshot = (? advanceWorkflowSeeds(project, compiled.projectWorkflowId, compiled.workflow.seedAdvances): project;// The queued item carries the previewed draw; rotating afterward makes the preview show the next one.- const dynamicPromptsSettings = canvasGenerateSettings ?? generateSettings ?? videoSettings;+ const dynamicPromptsSettings = canvasGenerateSettings ?? generateSettings ?? videoSettings ?? upscalePromptDraft;// Fencing on the expansion's seed keeps a submission that drew an already-rotated sample from rotating again.const resampledProject =expansionSampleSeed !== null &&@@ -4181,7 +4433,8 @@ const enqueueCompiledSnapshot = (dynamicPromptsSettings.dynamicPromptsResample? updateProjectWidgetValues(advancedProject,- route.sourceId === 'canvas' ? 'generate' : route.sourceId,+ // Canvas and Upscale draw from Generate's dynamic prompts settings.+ route.sourceId === 'canvas' || route.sourceId === 'upscale' ? 'generate' : route.sourceId,(values) =>// Sanitized as the expansion read it: a record saved without the field drew sample seed 0.sanitizeSampleSeed(values.dynamicPromptsSampleSeed) === expansionSampleSeed &&@@ -4453,7 +4706,7 @@ export const __workbenchReducerInternal = (action: WorkbenchReducerAction,context: WorkbenchReducerContext): WorkbenchState => {- const next = reduceWorkbenchAction(state, action, context);+ const next = reconcileCanvasStagingFollow(state, reduceWorkbenchAction(state, action, context));const describeStep = RECORDED_LAYOUT_ACTIONS[action.type];if (!describeStep || next === state || next.projects === state.projects) {@@ -5715,6 +5968,9 @@ const reduceWorkbenchAction = ());}+ case 'noteQueueItemFirstProgressFrame': {+ return recordCanvasStagingFrame(state, action.projectId, action.queueItemId, action.itemIndex);+ }case 'markQueueItemBackendCancelled': {const project = state.projects.find((project) => project.id === action.projectId);const queueItem = project?.queue.items.find((item) => item.id === action.queueItemId);@@ -5893,7 +6149,7 @@ const reduceWorkbenchAction = (return {...values,- ...(action.item.kind === 'video' ? { compareImage: null } : {}),+ ...getSelectionComparePatch(values, action.item),selectedImage: action.item,selectedImageName: itemKey,selectedImageNames: [itemKey],@@ -5910,13 +6166,15 @@ const reduceWorkbenchAction = ((values) => {const itemKey = toGalleryItemKey(action.item);const selectedItemKeys = getPersistedSelectedGalleryItemKeys(values);+ // Building a selection is not picking the second image: a comparison waiting for one ends.+ const isCompareArmed = getGalleryCompareState(values) === 'armed';if (!selectedItemKeys.includes(itemKey)) {const selectedImagePage = getGallerySelectionPage(values, action.selectionPage);return {...values,- ...(action.item.kind === 'video' ? { compareImage: null } : {}),+ ...(action.item.kind === 'video' || isCompareArmed ? { compareImage: null } : {}),selectedImage: action.item,selectedImageName: itemKey,selectedImageNames: [...selectedItemKeys, itemKey],@@ -5938,6 +6196,7 @@ const reduceWorkbenchAction = (if (!wasPrimary) {return {...values,+ ...(isCompareArmed ? { compareImage: null } : {}),selectedImageNames: remainingItemKeys,};}@@ -5958,7 +6217,7 @@ const reduceWorkbenchAction = (return {...values,- ...(nextPrimaryItem?.kind === 'image' ? {} : { compareImage: null }),+ ...(nextPrimaryItem?.kind === 'image' && !isCompareArmed ? {} : { compareImage: null }),selectedImage: nextPrimaryItem,selectedImageName: nextPrimaryKey,selectedImageNames: expectedNextPrimaryKey && !nextPrimaryItem ? [] : remainingItemKeys,@@ -5986,7 +6245,10 @@ const reduceWorkbenchAction = (return {...values,- ...(action.primaryItem.kind === 'video' ? { compareImage: null } : {}),+ // Building a selection is not picking the second image: a comparison waiting for one ends.+ ...(action.primaryItem.kind === 'video' || getGalleryCompareState(values) === 'armed'+ ? { compareImage: null }+ : {}),selectedImage: action.primaryItem,selectedImageName: toGalleryItemKey(action.primaryItem),selectedImageNames: action.itemKeys,@@ -6033,7 +6295,14 @@ const reduceWorkbenchAction = (case 'clearGallerySelection': {return updateGalleryValues(state,- (values) => ({ ...values, selectedImage: null, selectedImageName: null, selectedImageNames: [] }),+ // A comparison has no pair without a selection; one left behind would open on the next image selected.+ (values) => ({+ ...values,+ compareImage: null,+ selectedImage: null,+ selectedImageName: null,+ selectedImageNames: [],+ }),action.projectId);}@@ -6193,7 +6462,11 @@ const reduceWorkbenchAction = (return patchGalleryItemsAcrossProjects(state, new Set(action.itemKeys), action.changes);}case 'removeGalleryItems': {- return removeGalleryItemsFromAllProjects(state, new Set(action.itemKeys));+ return removeGalleryItemsFromAllProjects(+ state,+ new Set(action.itemKeys),+ action.keepComparisonForSuccessor ? (action.projectId ?? state.activeProjectId) : null+ );}case 'reconcileDeletedGalleryBoard': {const { outcome } = action;@@ -6216,13 +6489,15 @@ const reduceWorkbenchAction = (return updateGalleryValues(state, (values) => ({ ...values, projectBoardId: action.boardId }), action.projectId);}case 'applyCanvasProjectMutation': {- return updateProjectById(state, action.projectId, (project) => {+ const nextState = updateProjectById(state, action.projectId, (project) => {const updated = applyCanvasProjectMutation(project, action.mutation);return updated !== project && action.origin !== 'system' && isHighConfidenceCanvasEdit(action.mutation)? applyAutoRouteForEdit(updated, 'canvas', context): updated;});++ return updateCanvasStagingPin(nextState, action.projectId, action.mutation);}case 'commitCanvasEdit': {if (!isHighConfidenceCanvasEditIntent(action.intent)) {@@ -6625,9 +6900,21 @@ const reduceWorkbenchAction = (keyof ProjectSettings>;- return [...keys].every((key) => areProjectSettingValuesEqual(project.settings[key], settings[key]))- ? project- : { ...project, settings };+ if ([...keys].every((key) => areProjectSettingValuesEqual(project.settings[key], settings[key]))) {+ return project;+ }++ // Select for compare turns Auto-switch Off; turning it back on ends the wait, so live frames can never hide a+ // comparison that a later selection would open.+ const endsCompareWait =+ project.settings.viewerAutoSwitch === 'off' &&+ settings.viewerAutoSwitch !== 'off' &&+ getGalleryCompareState(getWidgetValues(project, 'gallery')) === 'armed';+ const nextProject = { ...project, settings };++ return endsCompareWait+ ? updateProjectWidgetValues(nextProject, 'gallery', (values) => ({ ...values, compareImage: null }))+ : nextProject;});}case 'setScopedDefaults': {diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.tsindex d354991454..b6695d2f8d 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts@@ -77,7 +77,9 @@ describe('createWorkbenchStore', () => {runningState.projects[0] = {...source,queue: {- items: [{ backendItemIds: [11], id: 'run-1', status: 'running' } as (typeof source.queue.items)[number]],+ items: [+ { backendItemIds: [11], id: 'run-1', snapshot: {}, status: 'running' } as (typeof source.queue.items)[number],+ ],},};const runningStore = createWorkbenchStore(runningState);@@ -106,6 +108,7 @@ describe('createWorkbenchStore', () => {{backendItemIds: [11],id: 'run-1',+ snapshot: {},status,} as (typeof source.queue.items)[number],],@@ -119,7 +122,9 @@ describe('createWorkbenchStore', () => {const pendingState = createInitialWorkbenchState();pendingState.projects[0] = {...pendingState.projects[0]!,- queue: { items: [{ id: 'pending-1', status: 'pending' } as (typeof source.queue.items)[number]] },+ queue: {+ items: [{ id: 'pending-1', snapshot: {}, status: 'pending' } as (typeof source.queue.items)[number]],+ },};const pendingStore = createWorkbenchStore(pendingState);const pendingSource = pendingState.projects[0]!;@@ -144,6 +149,7 @@ describe('createWorkbenchStore', () => {backendItemIds: [11],cancellationPending: true,id: 'run-1',+ snapshot: {},status: 'cancelled',} as (typeof source.queue.items)[number],],diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex d157899930..f7727188fe 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -134,9 +134,13 @@ const createCommands = (itemKeys,})),- removeItems: command('removeGalleryItems', (itemKeys: ActionPayload<'removeGalleryItems'>['itemKeys']) => ({- itemKeys,- })),+ removeItems: command(+ 'removeGalleryItems',+ (+ itemKeys: ActionPayload<'removeGalleryItems'>['itemKeys'],+ options?: Pick<ActionPayload<'removeGalleryItems'>, 'keepComparisonForSuccessor' | 'projectId'>+ ) => ({ itemKeys, ...options })+ ),reconcileDeletedBoardOutcome: command('reconcileDeletedGalleryBoard',(outcome: ActionPayload<'reconcileDeletedGalleryBoard'>['outcome']) => ({ outcome })@@ -505,6 +509,7 @@ const createCommands = (clearCompleted: command('clearCompletedQueueItems'),markBackendCancelled: command('markQueueItemBackendCancelled'),markBackendSubmitted: command('markQueueItemBackendSubmitted'),+ noteFirstProgressFrame: command('noteQueueItemFirstProgressFrame'),recordSubmissionRetry: command('recordQueueItemSubmissionRetry'),setCancellationPending: command('setQueueItemCancellationPending'),setLocalRecoveryState: command('setQueueItemLocalRecoveryState'),diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 4d6b527663..8596689e9d 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -181,6 +181,9 @@ const EDITOR_BOOT_SHARED_MODULES = [// The topbar (editor boot) and the image menus' keycaps read effective bindings; alone it cost a boot request.'/workbench/hotkeys/useShortcutBinding.ts','/workbench/widget-frame/compactWidgetCapacity.tsx',+ // The status bar and rails (editor boot) and the lazy Layers, Gallery and drop surfaces share this portal guard;+ // alone it costs a boot request.+ '/platform/react/isEventFromOwnDom.ts','/features/gallery/ui/GalleryItemSearch.tsx',// The image menu (editor boot) and the lazy layer menu share the board destination list; alone it costs a request.'/workbench/image-actions/GalleryBoardDestinationGroups.tsx',@@ -204,6 +207,9 @@ const EDITOR_BOOT_SHARED_MODULES = ['/features/generation/ui/promptFields/promptAttentionHotkeys.ts','/platform/ui/ResizeHandle.tsx','/platform/ui/SeedInput.tsx',+ // The Generate form (editor boot) and the lazy quick-settings popovers share the scrubber; alone it costs a boot+ // request.+ '/platform/ui/ScrubberField.tsx','/workbench/shell/topbar/LayoutPresetAdminDialogs.tsx','/workbench/shell/topbar/LayoutPresetStrip.tsx','/workbench/shell/topbar/ProjectSwitcher.tsx',@@ -236,9 +242,17 @@ const EDITOR_BOOT_SHARED_MODULES = ['/workbench/shell/notifications/toastPolicy.ts',// The boot UI adapters and the lazy palette, image menu and canvas saves find gallery items through it.'/workbench/image-actions/useFindGalleryItem.ts',+ // The queue runtime (editor boot) and the lazy recall menus share the recall cache; alone it costs a boot request.+ '/workbench/queue-integration/queueRecallCache.ts',// Invoke (editor boot), the lazy workflow editor and canvas header actions share the modifier-key hook; alone it// costs a boot request.'/platform/react/useModifierHeld.ts',+ // The Preview (open at boot) and the lazy Canvas share their drop zones' label and the desktop file drop: its drag+ // tracking, zone lookup and the upload start that loads the rest on the first drop. Alone they cost a boot request.+ '/platform/browser/dropZones.ts',+ '/platform/react/useNativeFileDrag.ts',+ '/workbench/widgets/shared/DropZoneLabel.tsx',+ '/workbench/widgets/shared/useDroppedFileUpload.ts',] as const;// Editor runtime the workbench store reaches: the editor boots it, and the settings field bindings (lazy on both@@ -344,6 +358,8 @@ const GALLERY_PICKER_MODULES = ['/features/gallery/core/mediaCounts.ts','/features/gallery/data/queries.ts','/features/gallery/data/queryCache.ts',+ // Where uploads from Canvas and Preview drops land; published by the queries entry beside the cache it reads.+ '/features/gallery/data/uploadDestination.ts','/features/gallery/ui/GallerySearchHelp.tsx','/platform/state/compareAndSwapRollback.ts','/features/gallery/picker.ts',@@ -416,6 +432,28 @@ const WIDGET_HOST_MODULES = ['/workbench/widgets/image-map/ImageMapDataRuntime.tsx',] as const;+// The image menus and actions the Gallery and Preview boot with, which the lazy queue recall chunks (the queue row and+// details actions, the staging menu's recall verbs, the queue's Recall all) import as well. The lazy Canvas reaches only+// their import notices and reference append, so without the group Rolldown splits those out, costing every editor boot+// a request.+const IMAGE_ACTIONS_MODULES = [+ '/workbench/canvas-operations/canvasImportNotice.ts',+ '/workbench/image-actions/ContextSubMenu.tsx',+ '/workbench/image-actions/ImageContextMenu.tsx',+ '/workbench/image-actions/ImageItemMenuGroups.tsx',+ '/workbench/image-actions/RecallActionButtons.tsx',+ '/workbench/image-actions/appendReferenceImage.ts',+ '/workbench/image-actions/canvasImportError.ts',+ '/workbench/image-actions/executeVideoRecall.ts',+ '/workbench/image-actions/galleryOptimisticRollback.ts',+ '/workbench/image-actions/index.ts',+ '/workbench/image-actions/pbrMapsGraph.ts',+ '/workbench/image-actions/useDeletionConfirmation.tsx',+ '/workbench/image-actions/useImageActions.ts',+ '/workbench/image-actions/useImageRecallCapabilities.ts',+ '/workbench/image-actions/videoRecall.ts',+] as const;+// Keep the Image Map data modules in one chunk. Its API is also reached through the Gallery's lazily loaded label// cache, and without this group Rolldown splits the API out, costing every editor boot a request.const IMAGE_MAP_DATA_MODULES = [@@ -462,6 +500,15 @@ const CANVAS_LAYER_SHARED_MODULES = ['/workbench/widgets/layers/useSelectedModelBase.ts',];+/**+ * The Canvas widget's frame readout, the lazy Size section and the canvas compiler share the render-size policy. Its+ * public entry only re-exports the policy, so it rides in the policy's chunk; alone it costs the Canvas a boot request.+ */+const CANVAS_PROCESSING_SIZE_MODULES = [+ '/features/generation/canvasProcessingSize.ts',+ '/features/generation/core/canvas/canvasProcessingSize.ts',+];+const matchesAnySuffix = (id: string, suffixes: readonly string[]) => suffixes.some((suffix) => id.endsWith(suffix));const getLegacyChunkName = (id: string): string | null => {@@ -555,6 +602,12 @@ export default defineConfig({priority: 30,test: (id) => matchesAnySuffix(id, CANVAS_LAYER_SHARED_MODULES),},+ {+ includeDependenciesRecursively: false,+ name: 'canvasProcessingSize',+ priority: 30,+ test: (id) => matchesAnySuffix(id, CANVAS_PROCESSING_SIZE_MODULES),+ },{includeDependenciesRecursively: false,name: 'gallery-picker',@@ -616,6 +669,12 @@ export default defineConfig({priority: 30,test: (id) => matchesAnySuffix(id, WIDGET_HOST_MODULES),},+ {+ includeDependenciesRecursively: false,+ name: 'image-actions',+ priority: 30,+ test: (id) => matchesAnySuffix(id, IMAGE_ACTIONS_MODULES),+ },{includeDependenciesRecursively: false,name: 'imageMapStore',diff --git a/invokeai/frontend/webv2/vitest.browser.config.mts b/invokeai/frontend/webv2/vitest.browser.config.mtsindex e10a025465..bf8961e91c 100644--- a/invokeai/frontend/webv2/vitest.browser.config.mts+++ b/invokeai/frontend/webv2/vitest.browser.config.mts@@ -1,12 +1,18 @@-import type { BrowserContext, Route } from 'playwright';+import type { BrowserContext, CDPSession, Route } from 'playwright';import type { BrowserCommand } from 'vitest/node';import { playwright } from '@vitest/browser-playwright';+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { mergeConfig } from 'vite';import { defineConfig } from 'vitest/config';import viteConfig from './vite.config.mts';+// Keep the initial Playwright page and Vitest iframe the same size before either can receive focus.+const TEST_VIEWPORT = { width: 414, height: 896 };+/** A previous test's pointer must not hover controls mounted by the next test. */const resetBrowserPointer: BrowserCommand<[]> = async ({ page }) => {await page.mouse.move(-1, -1);@@ -66,6 +72,150 @@ const mouseDragPath: BrowserCommand<[points: readonly { x: number; y: number }[]}};+/** A file for `nativeDrag`, written to disk so Chromium attaches it as the operating system would. */+type NativeDragFile = { base64: string; name: string };++/**+ * Drags files, a link (`uriList`) or plain text (`text`), alone or together, in from outside the page through+ * Chromium's own drag input: enters at the first point (the test frame's viewport coordinates), hovers each point and+ * drops at the last one. The browser dispatches each drag event in its own task, with a microtask checkpoint between+ * listeners, which events a test dispatches itself never have. It always drops, even when a step fails: a drag left+ * open swallows the next one's enter, and CDP's `dragCancel` reaches the page as no event at all, so it cannot stand+ * in for a cancel. The files are deleted once the command returns: read a dropped file's contents in a drop handler,+ * not after the drag.+ */+const nativeDrag: BrowserCommand<+ [+ options: {+ files?: readonly NativeDragFile[];+ frameWidth: number;+ points: readonly { x: number; y: number }[];+ text?: string;+ uriList?: string;+ },+ ]+> = async ({ context, frame, page }, { files = [], frameWidth, points, text, uriList }) => {+ const box = await (await (await frame()).frameElement()).boundingBox();+ if (!box || points.length === 0) {+ throw new Error('nativeDrag needs a visible test frame and at least one point');+ }+ const scale = box.width / frameWidth;+ const viewportPoints = points.map((point) => ({+ x: Math.round(box.x + point.x * scale),+ y: Math.round(box.y + point.y * scale),+ }));+ const directory = await mkdtemp(join(tmpdir(), 'native-drag-'));+ const session = await context.newCDPSession(page);+ // The page's next frame, so what a drag event rendered is on screen before the next one hit-tests it.+ const nextFrame = () =>+ page.evaluate(+ () =>+ new Promise((resolve) => {+ requestAnimationFrame(resolve);+ })+ );++ try {+ const paths = await Promise.all(+ files.map(async (file) => {+ const path = join(directory, file.name);+ await writeFile(path, Buffer.from(file.base64, 'base64'));+ return path;+ })+ );+ const data = {+ dragOperationsMask: 1,+ files: paths,+ items: [+ ...(uriList === undefined ? [] : [{ data: uriList, mimeType: 'text/uri-list' }]),+ ...(text === undefined ? [] : [{ data: text, mimeType: 'text/plain' }]),+ ],+ };+ const drop = { data, type: 'drop', ...viewportPoints.at(-1)! } as const;+ let isOpen = false;+ try {+ await session.send('Input.dispatchDragEvent', { data, type: 'dragEnter', ...viewportPoints[0]! });+ isOpen = true;+ for (const point of viewportPoints) {+ // Twice per point: the first hover may render the zones the second one finds.+ for (let hover = 0; hover < 2; hover++) {+ await nextFrame();+ await session.send('Input.dispatchDragEvent', { data, type: 'dragOver', ...point });+ }+ }+ await nextFrame();+ isOpen = false;+ await session.send('Input.dispatchDragEvent', drop);+ } finally {+ // A step that failed must not leave the drag open for the next test.+ if (isOpen) {+ await session.send('Input.dispatchDragEvent', drop).catch(() => undefined);+ }+ }+ } finally {+ await session.detach();+ await rm(directory, { force: true, recursive: true });+ }+};++const devicePixelRatioSessions = new Map<string, CDPSession>();++/**+ * Emulates a display's device pixel ratio, such as a desktop scaled to 125%, at the same CSS viewport size; `null`+ * restores the real one. Chromium drops the override with the CDP session that set it, so the session stays open until+ * then.+ */+const emulateDevicePixelRatio: BrowserCommand<[ratio: number | null]> = async ({ context, page, sessionId }, ratio) => {+ const previous = devicePixelRatioSessions.get(sessionId);+ devicePixelRatioSessions.delete(sessionId);+ await previous?.detach();+ if (ratio === null) {+ return;+ }+ const session = await context.newCDPSession(page);+ devicePixelRatioSessions.set(sessionId, session);+ await session.send('Emulation.setDeviceMetricsOverride', {+ deviceScaleFactor: ratio,+ height: 0,+ mobile: false,+ width: 0,+ });+};++/**+ * Captures `rect` (the test frame's CSS pixels) at the display's device pixels, under any emulated device pixel ratio.+ * Playwright's own screenshots restore its viewport emulation, which ends `emulateDevicePixelRatio`'s.+ */+const captureDevicePixels: BrowserCommand<+ [rect: { height: number; width: number; x: number; y: number }, frameWidth: number]+> = async ({ context, frame, page, sessionId }, rect, frameWidth) => {+ const box = await (await (await frame()).frameElement()).boundingBox();+ if (!box) {+ throw new Error('captureDevicePixels needs a visible test frame');+ }+ const scale = box.width / frameWidth;+ // Detaching any other session ends the emulation too, so capture through the one that set it.+ const emulating = devicePixelRatioSessions.get(sessionId);+ const session = emulating ?? (await context.newCDPSession(page));+ try {+ const { data } = await session.send('Page.captureScreenshot', {+ clip: {+ height: rect.height * scale,+ scale: 1 / scale,+ width: rect.width * scale,+ x: box.x + rect.x * scale,+ y: box.y + rect.y * scale,+ },+ format: 'png',+ });+ return data;+ } finally {+ if (!emulating) {+ await session.detach();+ }+ }+};+type ThumbnailRouteState = {/** Requests still to be answered with `failureStatus`. */failuresLeft: number;@@ -177,10 +327,13 @@ export default mergeConfig(test: {browser: {commands: {+ captureDevicePixels,+ emulateDevicePixelRatio,endThumbnailRouteFailures,getThumbnailRequests,imeCompose,mouseDragPath,+ nativeDrag,resetBrowserPointer,startThumbnailRoute,stopThumbnailRoute: stopThumbnailRouteCommand,@@ -188,7 +341,15 @@ export default mergeConfig(enabled: true,headless: true,instances: [{ browser: 'chromium' }],- provider: playwright(),+ // Focus must not scroll the runner while its iframe and outer viewport resize independently.+ orchestratorScripts: [+ {+ content: "document.head.insertAdjacentHTML('beforeend', '<style>body { overflow: clip }</style>')",+ type: 'text/javascript',+ },+ ],+ provider: playwright({ contextOptions: { viewport: TEST_VIEWPORT } }),+ viewport: TEST_VIEWPORT,},include: ['src/**/*.browser.test.{ts,tsx}'],setupFiles: ['./scripts/browser-test-console.ts', './scripts/browser-test-pointer.ts'],