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(workflows): redesign the workflow library, previews and editor nodes (#10222)
Josh Corbettd7b3179a9f7c
diff --git a/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx b/docs/src/content/docs/Users Guide/02.Projects/introduction.mdxindex ab266bf197..2bf08aba14 100644--- a/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx+++ b/docs/src/content/docs/Users Guide/02.Projects/introduction.mdx@@ -154,7 +154,7 @@ Export is also the simplest way to back up a project you care about, or to handA project can hold several workflows. Each is saved as part of the project and changes automatically along with it; your [workflow library](/users-guide/workflows/editor-reference/#your-workflows) changes only when you save a workflow to it on purpose.-In the Workflow Library dialog, **This project** lists the project's own workflows, while **Browse** and **Yours** list bundled templates and your saved library. Opening a library workflow adds a copy to the current project. **Fork into new project** copies a workflow into a brand-new project of its own.+In the Workflow Library dialog, **In this project** lists the project's own workflows, while **Templates** and **My library** list bundled templates and your saved library. Opening a library workflow adds a copy to the current project. **Fork into new project** copies a workflow into a brand-new project of its own.## Making the most of projectsdiff --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 d4da4c39c2..fd0c8fe7c2 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@@ -51,6 +51,8 @@ Hover over **Invoke** to see what will be queued, for example *1 prompt × 4 iteThe **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.+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.+## Routing images to the Gallery or the CanvasEvery press of **Invoke** has a *route*: a **source**, the panel whose settings are used, and a **destination**, where the results go. Images can go to one of two destinations: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 1e9d220479..24d7ade5ac 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@@ -55,8 +55,8 @@ Hover over a numbered circle, or tap it on a touchscreen, for a short descriptio| 1 | **Workflow panel** | The workflow's **form**: its most important settings as simple controls, like a Generate panel for this workflow. || 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 open the **Workflows** library. |-| 5 | **Workflow actions** | **Add node** (**+**), **Save to library…**, the save status, settings, and the **⋯** menu with **Workflow details…**, **Rename workflow…**, **Import workflow JSON…**, **Export workflow JSON**, **New workflow** and more. |+| 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**). || 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. |@@ -68,7 +68,7 @@ Hover over a numbered circle, or tap it on a touchscreen, for a short descriptio* **Add a node** by pressing **Shift+A** or **Space** in the editor, or with the **+** button in its header, then search for it by name.* **Connect nodes** by dragging from an output on the right of one node to an input on the left of another.* **Choose which images are kept.** Only nodes with **Save to Gallery** checked, at the bottom of image nodes, send their images to the Gallery.-* **Manage workflows** from the **Workflows** library: click the workflow's name in the editor's header.+* **Switch workflows** from the workflow's name in the editor's header: its menu lists the project's workflows. **New workflow** at the bottom of that menu adds a blank one, and **Workflow library…** opens the **Workflows** library to manage them.The [Workflow Editor Reference](/users-guide/workflows/editor-reference/) covers all of this in detail, along with connectors, the library, common node patterns, community nodes and keyboard shortcuts.@@ -84,7 +84,7 @@ You need an SDXL model and an SDXL VAE, such as the *sdxl-vae-fp16-fix* starter1. Press **Alt+4** for the Workflow layout.-2. Click the workflow's name at the top of the editor to open the **Workflows** library, go to **Browse**, and open **Text to Image - SDXL**. A copy is added to your project and becomes the active workflow.+2. Click the workflow's name at the top of the editor and choose **Workflow library…** to open the **Workflows** library, go to **Templates**, and open **Text to Image - SDXL**. A copy is added to your project and becomes the active workflow.3. In the **Main Model - SDXL** node, choose your SDXL model in **Model**, and in the **VAE Model** node choose an SDXL VAE.@@ -133,13 +133,13 @@ In summary, the **Image Compositor**'s settings are:A workflow with a dozen nodes is not the most convenient thing to use day to day. The **form** in the Workflow panel on the left gathers the settings you actually change into one simple panel, like the Generate panel.-To add a setting to the form, click the **pin** icon at the right end of its row in the node (**Add to form**). Only settings with their own control can be pinned; connected inputs cannot.+To add a setting to the form, point at its row in the node (or move keyboard focus into it) and click the **+** button at the right end of the row (**Add to form**). Only settings with their own control can go in the form; connected inputs cannot.<Steps>1. The SDXL workflow already puts its **Positive Prompt**, **Negative Prompt**, **Model**, VAE and board settings in the form.-2. In **Image Compositor**, pin **Image Background**, **Threshold**, **X Offset** and **Y Offset**. The pins turn blue, and the settings appear at the end of the form.+2. In **Image Compositor**, add **Image Background**, **Threshold**, **X Offset** and **Y Offset** to the form. Their names turn blue with a link mark, and the settings appear at the end of the form.3. In the Workflow panel, click **Edit**, then **Form**. Each setting is a card:* Drag a card's title bar to reorder it.@@ -151,7 +151,7 @@ To add a setting to the form, click the **pin** icon at the right end of its row</Steps>-<Image src={formEdit} alt="The Workflow panel in Edit mode, with the Form tab listing the pinned settings as cards and the Node Inspector below." width={380} />+<Image src={formEdit} alt="The Workflow panel in Edit mode, with the Form tab listing the settings added to the form as cards and the Node Inspector below." width={380} />In **View**, the form works like any generation panel: change the prompt or the background and press **Invoke**. The form is part of the workflow, so it is saved with it, exported with it, and shown to anyone who opens your workflow.@@ -159,7 +159,7 @@ In **View**, the form works like any generation panel: change the prompt or the### 5. Save and share it-Use **Details** in the Workflow panel's Edit mode to give the workflow a name and description, then click **Save to library…** in the editor's header to keep it in your library for other projects. To share it, choose **Export workflow JSON** from the **⋯** menu.+Use **Details** in the Workflow panel's Edit mode to give the workflow a name and description, then click **Save to library…** in the editor's header to keep it in your library for other projects. To share it, choose **Export** → **Export JSON** from the **⋯** menu.## Learn morediff --git a/docs/src/content/docs/Users Guide/08.Workflows/assets/workflow-editor-tour.svg b/docs/src/content/docs/Users Guide/08.Workflows/assets/workflow-editor-tour.svgindex d9897b1d3a..981a9e7076 100644--- a/docs/src/content/docs/Users Guide/08.Workflows/assets/workflow-editor-tour.svg+++ b/docs/src/content/docs/Users Guide/08.Workflows/assets/workflow-editor-tour.svg@@ -33,8 +33,8 @@<g id="wfe-t1" class="wfe-tip" aria-hidden="true"><rect x="54" y="76" width="420" height="122" rx="10"/><text class="wfe-tip-title" x="70" y="106">Workflow panel</text><text x="70" y="134">The linear form: the workflow's key</text><text x="70" y="160">settings as simple controls. View uses</text><text x="70" y="186">the form; Edit builds it.</text></g><g id="wfe-t2" class="wfe-tip" aria-hidden="true"><rect x="10" y="108" width="420" height="148" rx="10"/><text class="wfe-tip-title" x="26" y="138">View and Edit</text><text x="26" y="166">Switch between using the form (View)</text><text x="26" y="192">and designing it (Edit), with the</text><text x="26" y="218">workflow's details and a Node</text><text x="26" y="244">Inspector.</text></g><g id="wfe-t3" class="wfe-tip" aria-hidden="true"><rect x="228" y="116" width="420" height="148" rx="10"/><text class="wfe-tip-title" x="244" y="146">Editor toolbar</text><text x="244" y="174">Pan, box select, lasso select and</text><text x="244" y="200">erase tools; zoom and Fit view;</text><text x="244" y="226">download the graph as a PNG; node</text><text x="244" y="252">opacity.</text></g>- <g id="wfe-t4" class="wfe-tip" aria-hidden="true"><rect x="490" y="79" width="420" height="96" rx="10"/><text class="wfe-tip-title" x="506" y="109">Workflow name</text><text x="506" y="137">The active workflow. Click it to open</text><text x="506" y="163">the Workflows library at This project.</text></g>- <g id="wfe-t5" class="wfe-tip" aria-hidden="true"><rect x="888" y="79" width="420" height="148" rx="10"/><text class="wfe-tip-title" x="904" y="109">Workflow actions</text><text x="904" y="137">Add node (+), Save to library, save</text><text x="904" y="163">status, settings, and the ⋯ menu:</text><text x="904" y="189">details, rename, import/export JSON,</text><text x="904" y="215">new workflow.</text></g>+ <g id="wfe-t4" class="wfe-tip" aria-hidden="true"><rect x="490" y="79" width="420" height="96" rx="10"/><text class="wfe-tip-title" x="506" y="109">Workflow name</text><text x="506" y="137">The active workflow. Click it to switch,</text><text x="506" y="163">add a workflow, or open the library.</text></g>+ <g id="wfe-t5" class="wfe-tip" aria-hidden="true"><rect x="888" y="79" width="420" height="148" rx="10"/><text class="wfe-tip-title" x="904" y="109">Workflow actions</text><text x="904" y="137">Add node (+), Save to library, save</text><text x="904" y="163">status, settings, and the ⋯ menu:</text><text x="904" y="189">rename, details, import JSON, and</text><text x="904" y="215">export as JSON or PNG.</text></g><g id="wfe-t6" class="wfe-tip" aria-hidden="true"><rect x="534" y="290" width="420" height="148" rx="10"/><text class="wfe-tip-title" x="550" y="320">The graph</text><text x="550" y="348">Nodes and the connections between</text><text x="550" y="374">them. Drag from an output on the right</text><text x="550" y="400">of a node to an input on the left of</text><text x="550" y="426">another.</text></g><g id="wfe-t7" class="wfe-tip" aria-hidden="true"><rect x="902" y="666" width="420" height="96" rx="10"/><text class="wfe-tip-title" x="918" y="696">Minimap</text><text x="918" y="724">An overview of the whole graph. Drag</text><text x="918" y="750">in it to move around large workflows.</text></g><g id="wfe-t8" class="wfe-tip" aria-hidden="true"><rect x="1170" y="76" width="420" height="122" rx="10"/><text class="wfe-tip-title" x="1170" y="106">Gallery, Queue and more</text><text x="1170" y="134">The right panel shows the Gallery,</text><text x="1170" y="160">where results appear, with the Queue,</text><text x="1170" y="186">Preview and Image Map on its rail.</text></g>diff --git a/docs/src/content/docs/Users Guide/08.Workflows/editor-reference.mdx b/docs/src/content/docs/Users Guide/08.Workflows/editor-reference.mdxindex 8c484ae888..470af02cca 100644--- a/docs/src/content/docs/Users Guide/08.Workflows/editor-reference.mdx+++ b/docs/src/content/docs/Users Guide/08.Workflows/editor-reference.mdx@@ -23,7 +23,7 @@ A quicker way to add a node that is already connected: drag from a connection poTo connect two nodes, drag from an output on the right of one node to an input on the left of another. Only compatible connection points accept the connection. An input takes one connection, but an output can feed as many inputs as you like. To reconnect, drag the end of a connection to another point; to disconnect, drag it away and release it over empty space, or select the connection and press **Delete**.-Right-click a node to **Copy**, **Paste**, **Duplicate**, **Collapse** or **Delete** it, and double-click its title to rename it. The chevron in a node's title bar collapses it to keep a large graph tidy. Pasted nodes land at the pointer when the editor has focus and the pointer is over it, at the click point when you right-click empty space and choose **Paste**, and otherwise in the center of the visible view.+Right-click a node to **Copy**, **Paste**, **Duplicate**, **Collapse** or **Delete** it, and double-click its title to rename it. The chevron in a node's title bar collapses it to keep a large graph tidy: a collapsed node shows one port on each side, and its connections run from those ports. Connections between two collapsed nodes draw as one line with a count; selecting or deleting it acts on all of them. To make a new connection to or from a collapsed node, expand it first. Pasted nodes land at the pointer when the editor has focus and the pointer is over it, at the click point when you right-click empty space and choose **Paste**, and otherwise in the center of the visible view.Right-click an unselected node and choose **Fit selection** to frame that node. To frame several nodes, select them, then right-click a selected node or the selection outline and choose **Fit selection**. Use **Fit view** in the editor toolbar to frame the whole workflow.@@ -37,7 +37,13 @@ The picker's **Utility** group has three special nodes:Connectors tidy up the wiring of a large graph. They pass a value straight through and are removed before the workflow runs, so they cannot change what it does. To add one, right-click empty space in the editor and choose **Add connector**, then connect to and from it. You can wire a connector's output first and its input later; it only accepts a source whose type matches what it feeds. Deleting a connector joins its incoming connection directly to everything it fed.-A node's border shows its state: red when a required input is missing or the node failed, highlighted with a progress strip while it runs, and green when it has finished. After a run, **Latest output** on an image node shows its result. A node whose type this installation does not have, usually from a node pack that is not installed, says so; select it for **Open Nodes Manager**, where you can install the pack (administrators only on a multi-user installation; others are asked to contact one).+A node shows its state in its title bar. A red outline and title bar mean the node cannot run as it is, because a value is missing or invalid, or because its last run failed; the field at fault has a red name and a red border on its control. An amber outline and title bar mean the node's version does not match this installation's: a newer version of the node is available, the node is newer than this installation supports, or its version cannot be updated in place (the status button says which, and what to do). Beside the title, the status button shows a progress ring while the node runs (and the node glows), a check once it has finished, or a warning mark; point at it or move keyboard focus to it to see what it means, such as *Model is required. Pick a model.* or the error from a failed run. The info button beside it shows the node's type, node pack, version, description and notes. Nodes that are not yet stable carry an icon before the title (beta, prototype, internal or special) that explains itself on hover.++Each field row shows its actions when you point at it or move keyboard focus into it: edit the field's description, reset it to its default and add it to or remove it from the form. A field in the form has a blue name with a link mark, and an asterisk marks a required field. Each connection point grabs a little beyond its dot, so it is easy to start a connection.++Selecting a node highlights its own connections and dims the others; with nothing selected, every connection looks the same. With the minimap on, nodes that cannot run or that failed show red on it and the running node shows in the accent colour.++After a run, **Latest output** on an image node shows its result. A node whose type this installation does not have, usually from a node pack that is not installed, says so; select it for **Open Nodes Manager**, where you can install the pack (administrators only on a multi-user installation; others are asked to contact one).When the workflow cannot run, hovering or clicking **Invoke** lists why. Problems with a node, such as a missing required input, name the node and input, and choosing one selects that node and zooms the editor to it.@@ -51,25 +57,41 @@ Beside it, **Use cache** lets InvokeAI reuse a node's previous result when its i### Your workflows-Each project keeps its own workflows, and one of them is **active**: the one shown in the editor and run by Invoke. Changes are saved with the project automatically. Click the workflow's name to open the **Workflows** library:+Each project keeps its own workflows, and one of them is **active**: the one shown in the editor and run by Invoke. Changes are saved with the project automatically. Click the workflow's name to switch: its menu lists the project's workflows in project order, the active one checked, and choosing another makes it active. Below the list, **New workflow** adds a blank workflow and makes it active, and **Workflow library…** opens the **Workflows** library on **In this project**. Its left rail lists the places to look:++* **In this project** — the project's workflows. Open one to make it active, or start a **New workflow** from the toolbar.+* **Recent** — your saved workflows you have opened, most recently opened first. Bundled template opens are not recorded. On multi-user servers, templates previously opened by an administrator may still appear for everyone; templates opened by a non-administrator do not enter Recent.+* **My library** — workflows you have saved with **Save to library…**, for use in other projects.+* **Templates** — the workflows that ship with InvokeAI, such as *Text to Image - SDXL*, *Flux Text to Image* and the video workflows. Opening one adds a copy to your project.+* **Shared with me** — public workflows on a multi-user server, your own included.++Under the places, **Tags** lists the tags used in the current place, each with how many workflows carry it. Check several to see workflows with any of them; **Clear** unchecks them all.++The toolbar above the cards is the same everywhere. Search matches names, descriptions and tags on every place. The **Sort** menu names the current order and sets both the key and its direction, such as **Newest first** or **A to Z**: **My library** and **Shared with me** sort by **Last opened**, **Last updated**, **Last run**, **Date created** or **Name**; **In this project** sorts by **Project order**, **Name**, **Last updated** or **Last run**; **Templates** always lists by name; **Recent** always lists the most recently opened first. Sorted by **Last run** or **Last opened**, workflows never run or never opened come last in either direction. **Last run** for a library template follows runs of its linked copies in your projects. The view menu beside it, its glyph showing the current layout, shows the workflows as a **Grid** of cards or as a **List**; for the grid it also switches between small and large cards and chooses whether thumbnails **Fill** their cards, cropped at the edges, or **Fit** whole. A list row shows the thumbnail, name, base model, readiness and the date of the current order (when it was last opened, run, created or updated), and a **…** menu at its end. **Open** and **Preview** appear beside it when you point at the row; the **…** menu always offers **Open**, and the detail rail **Preview**. Right-click a card or row, or use its **…** menu, for that workflow's actions without changing which workflow the detail rail shows. On **In this project**, **New workflow** sits at the end of the toolbar. The line under the toolbar counts the matching workflows and names the checked tags.++A dot beside each card's or row's facts says whether the workflow can run here: green when it is ready, amber when it needs models you have not installed, and red when it uses node types this installation does not have. The detail rail on the right lists the requirements and offers the installs, and names the missing node packs.++The detail rail describes the selected workflow before you open it: where it comes from (a template, your library, a shared workflow or this project), its author and version, how many nodes and inputs it has, **You set** (the inputs its form exposes, grouped under the form's headings) and the author's notes, cut to three lines until **Read all notes**.++Pressing <kbd>Space</kbd> or <kbd>Enter</kbd> on a card or row selects it. **Preview**, a card's or row's **Preview** action, or a press on the rail's thumbnail shows the workflow in place of the places and the cards; the detail rail, with **Open**, the installs and its **…** menu, stays beside it. Three tabs at the start of the bar above it switch what it shows. **Nodes** draws the workflow as saved, with each node named as in the editor, even when it would not run here. It opens simplified: small value nodes such as a prompt or the steps fold into labels on the node they feed, and collect and metadata nodes are hidden; **Show all** draws every node where its author placed it. Markers show the nodes whose values you set, the ones that need a model you have not installed, and the result. Select a node, or press <kbd>Enter</kbd> on it, for a card with its note, its values and the nodes it connects to; **Find a node**, at the end of the bar while **Nodes** shows, highlights nodes by name, and <kbd>Enter</kbd> moves between the matches. A workflow too large to read at full size opens at a readable size from its start, with a minimap. **Inputs** shows the workflow's form as its author arranged it, with the saved values and the models still to install; each input links to the node it sets. **Graph** shows the graph the workflow compiles to, the JSON the server is sent when it runs, or says why it would not compile. The **…** menu at the end of the bar copies or downloads the workflow's own JSON, the file the editor imports. While previewing, the top of the detail rail counts the workflow's place in the current results, with arrows to the previous and next one (<kbd>↑</kbd> and <kbd>↓</kbd> on them step too). The back button or <kbd>Esc</kbd> returns to the cards as you left them; the next <kbd>Esc</kbd> closes the library.++When a project workflow came from a library template, its detail rail shows the linked template and its revision, and says when the template is newer than the copy. **Update from template** replaces the copy with the template's current version (Undo restores your edits), and **Update library template** writes the copy over the template.-* **This project** — the project's workflows. Open one to make it active, or start a **New workflow**.-* **Browse** — the workflows that ship with InvokeAI, such as *Text to Image - SDXL*, *Flux Text to Image* and the video workflows. Opening one adds a copy to your project.-* **Yours** — workflows you have saved to your library with **Save to library…**, for use in other projects.+In a narrow window the places become a menu at the start of the toolbar with a **Tags** button beside it that counts the checked tags, and the selected workflow's details open from a bar under the cards. A preview fills the window above that bar, without **Find a node**, and the arrows sit beside the workflow's name in the bar.-On **Yours**, **Sort by** orders the list by **Last updated**, **Last opened**, **Date created** or **Name**; **Browse** always lists by name. **Fill** shows each thumbnail filling its card, cropped at the edges, and **Fit** shows the whole image. The library remembers both choices the next time you open it.+The library remembers the place and the **In this project** order until you leave the app, and **Nodes**, **Inputs** or **Graph** until you close it, and the other places' order, the layout, the card size and the thumbnail choice for your account. Closing it clears the search and the checked tags.Opening a library workflow adds an independent copy to the project; the library's version is untouched. If the project already has a copy, opening the template asks what to do: **Open copy** switches to the existing copy, **Add new copy** makes another one, and **Replace copy** replaces the copy's graph with the library version while keeping its name. A replace can be undone in one step.Changes to a project's workflows never change the library by themselves. **Save to library…**, in the editor's header, saves the workflow as a new library template with the name you give it, including its form and its current settings as defaults. Owners can update their own linked saved workflow templates, and multi-user administrators can update any user's saved non-bundled template; bundled templates remain read-only. If the template has changed since you opened it, you can save as a new template instead, or review the current one and replace it deliberately. Replacing a template also affects workflows that use it through the **Call Saved Workflow** node.-Add comma-separated tags, such as `portrait, SDXL, upscaling`, in the workflow's **Details**; they become filters in the library. Each workflow also keeps its own undo history while the project is open.+Add comma-separated tags, such as `portrait, SDXL, upscaling`, in the workflow's **Details**; they appear under **Tags** in the library. Each workflow also keeps its own undo history while the project is open.:::note[Changed from v6]In InvokeAI 6, editing a workflow opened from the library saved every change straight back to the library. Workflows now belong to their project and autosave there; the library changes only when you choose **Save to library…** or **Update library template**.:::-To share a workflow, use **Export workflow JSON** from the **⋯** menu; others can load it with **Import workflow JSON…**. If parts of a file cannot be loaded, such as nodes of an unknown kind, one notice lists everything that was skipped. An image made by a workflow also carries the workflow in its metadata: right-click the image and choose **Load Workflow**. **Download workflow as PNG** in the editor toolbar saves a picture of the whole graph, at up to twice screen resolution, for documentation or sharing. A large graph is saved at a lower resolution, with a notice when that falls below screen resolution; one too large to stay legible as a picture is not exported, so share its JSON instead. Closing the workflow editor while the picture is being prepared cancels the export.+To share a workflow, use **Export** → **Export JSON** from the **⋯** menu, or **Copy JSON** beside it; others can load it with **Import from JSON…**. If parts of a file cannot be loaded, such as nodes of an unknown kind, one notice lists everything that was skipped. An image made by a workflow also carries the workflow in its metadata: right-click the image and choose **Load Workflow**. **Download workflow as PNG** in the editor toolbar, or **Export** → **Download as PNG** in the **⋯** menu, saves a picture of the whole graph, at up to twice screen resolution, for documentation or sharing. A large graph is saved at a lower resolution, with a notice when that falls below screen resolution; one too large to stay legible as a picture is not exported, so share its JSON instead. Closing the workflow editor while the picture is being prepared cancels the export.## Common node patternsdiff --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 5799f350e6..eed291af77 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@@ -71,7 +71,7 @@ Switching modes changes no data. Every record keeps its owner, and the mode deci| --- | --- | --- || Boards, images, videos | Owned by `system`: only administrators can open them | All visible: the single-user mode user is an administrator || Projects | Owned by `system`: no account can open them. They come back when you return to single-user mode | Only projects created in single-user mode are listed. Each account's projects come back when you return to multi-user mode |-| Library workflows | Public, owned by `system`: every user can open, duplicate or download them from **Shared** | All visible |+| Library workflows | Public, owned by `system`: every user can open, duplicate or download them from **Shared with me** | All visible || Accounts | Kept. Created in multi-user mode only | Kept, unused until you switch back |Content that accounts create in multi-user mode stays theirs across any number of switches. There is no tool yet to move `system`-owned content to another account.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 b1bdc6b42f..18bfd21172 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@@ -84,10 +84,10 @@ Library workflows have a visibility:| Visibility | Who can see it | Who can change it || --- | --- | --- || **Private** (default for new workflows) | You and administrators | You |-| **Public** | Every signed-in user of this server, under **Shared**. It is not published to the internet | You; others can open, duplicate or download it |-| Saved in single-user mode, or before workflows had owners | Every signed-in user, under **Shared** | No one is offered rename, delete or visibility controls; anyone can open, duplicate or download it |+| **Public** | Every signed-in user of this server, under **Shared with me**. It is not published to the internet | You; others can open, duplicate or download it |+| Saved in single-user mode, or before workflows had owners | Every signed-in user, under **Shared with me** | No one is offered rename, delete or visibility controls; anyone can open, duplicate or download it |-- To change visibility, select the workflow under **Yours** and use **Visibility** in its detail panel.+- To change visibility, select the workflow under **My library** and use **Visibility** in its detail panel.- **Save to library…** has a **Public workflow** option for the new Library copy. It does not make the project's own workflow public.- Changing visibility does not publish unsaved project edits. **Update library template** writes them to the Library copy and keeps its visibility. Only the template's owner or an administrator can update it; anyone else can use **Save as new** to create their own.- Public workflows that can be called from other workflows also appear in the **Call Saved Workflow** node's picker.diff --git a/invokeai/app/services/shared/database/queries/workflows.py b/invokeai/app/services/shared/database/queries/workflows.pyindex 61b02c6005..488ae1ed45 100644--- a/invokeai/app/services/shared/database/queries/workflows.py+++ b/invokeai/app/services/shared/database/queries/workflows.py@@ -132,9 +132,16 @@ _ORDER_COLUMNS: dict[WorkflowRecordOrderBy, ColumnElement[Any]] = {WorkflowRecordOrderBy.CreatedAt: _W.created_at,WorkflowRecordOrderBy.UpdatedAt: _W.updated_at,WorkflowRecordOrderBy.OpenedAt: _W.opened_at,+ WorkflowRecordOrderBy.LastRunAt: _W.last_run_at,WorkflowRecordOrderBy.Name: CaseInsensitiveOrder(_W.name),WorkflowRecordOrderBy.IsPublic: _W.is_public,}+# Workflows never opened or run sort after the others in both directions. Both dialects sort NULL lowest, and MySQL+# has no NULLS LAST, so a leading ascending `IS NULL` term places them.+_NULLABLE_ORDER_COLUMNS: dict[WorkflowRecordOrderBy, ColumnElement[Any]] = {+ WorkflowRecordOrderBy.OpenedAt: _W.opened_at,+ WorkflowRecordOrderBy.LastRunAt: _W.last_run_at,+}_THE_WORKFLOW = _W.workflow_id == bindparam("workflow_id")_GET = select(*_SUMMARY_COLUMNS, _W.workflow).where(_THE_WORKFLOW)@@ -190,10 +197,14 @@ def _list(shape: _Shape, order_by: WorkflowRecordOrderBy, direction: SQLiteDirec# The enums are also strings, which share their cache entries: compare by value, never by identity. The workflow# id breaks ties, so that equal keys keep one order from page to page.ordering = (_ORDER_COLUMNS[order_by], _W.workflow_id)+ nullable = _NULLABLE_ORDER_COLUMNS.get(order_by)statement = (select(*_LIST_COLUMNS).where(*_conditions(shape))- .order_by(*(column.desc() if direction == SQLiteDirection.Descending else column.asc() for column in ordering))+ .order_by(+ *(() if nullable is None else (nullable.is_(None).asc(),)),+ *(column.desc() if direction == SQLiteDirection.Descending else column.asc() for column in ordering),+ ))if paged:statement = statement.limit(bindparam("limit")).offset(bindparam("offset"))diff --git a/invokeai/app/services/workflow_records/workflow_records_common.py b/invokeai/app/services/workflow_records/workflow_records_common.pyindex b9db4e5a5f..b946e0f314 100644--- a/invokeai/app/services/workflow_records/workflow_records_common.py+++ b/invokeai/app/services/workflow_records/workflow_records_common.py@@ -65,6 +65,7 @@ class WorkflowRecordOrderBy(str, Enum, metaclass=MetaEnum):CreatedAt = "created_at"UpdatedAt = "updated_at"OpenedAt = "opened_at"+ LastRunAt = "last_run_at"Name = "name"IsPublic = "is_public"diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 8689552589..e339645c55 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -128908,7 +128908,7 @@},"WorkflowRecordOrderBy": {"type": "string",- "enum": ["created_at", "updated_at", "opened_at", "name", "is_public"],+ "enum": ["created_at", "updated_at", "opened_at", "last_run_at", "name", "is_public"],"title": "WorkflowRecordOrderBy","description": "The order by options for workflow records"},diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex b7300782d4..dac5f08cc5 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -58367,7 +58367,7 @@ export type components = {* @description The order by options for workflow records* @enum {string}*/- WorkflowRecordOrderBy: "created_at" | "updated_at" | "opened_at" | "name" | "is_public";+ WorkflowRecordOrderBy: "created_at" | "updated_at" | "opened_at" | "last_run_at" | "name" | "is_public";/** WorkflowRecordWithThumbnailDTO */WorkflowRecordWithThumbnailDTO: {/**diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex d94c0b8835..d0efccc54f 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": 816492,+ "brotliBytes": 816542,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 816093,+ "gzipBytes": 815312,"imageRawBytes": 44398,- "initialRawBytes": 2106927,- "largestAssetRawBytes": 751079,+ "initialRawBytes": 2108233,+ "largestAssetRawBytes": 751084,"otherAssetRawBytes": 0,- "ownedRawBytes": 115509,+ "ownedRawBytes": 115499,"requestCount": 34,"scriptRequestCount": 18,"sourceOwners": [@@ -361,15 +361,15 @@},"editor": {"baseline": {- "brotliBytes": 1272615,+ "brotliBytes": 1273806,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 1265631,+ "gzipBytes": 1266186,"imageRawBytes": 44398,- "initialRawBytes": 3516969,- "largestAssetRawBytes": 751079,+ "initialRawBytes": 3520316,+ "largestAssetRawBytes": 751084,"otherAssetRawBytes": 0,- "ownedRawBytes": 176678,+ "ownedRawBytes": 178002,"requestCount": 70,"scriptRequestCount": 54,"sourceOwners": [@@ -917,7 +917,6 @@"source:src/workbench/extensions/extensionRegistry.ts","source:src/workbench/floatingWindows.ts","source:src/workbench/focusRegions.tsx",- "source:src/workbench/graphPreviewInvocation.ts","source:src/workbench/graphSurfaces.ts","source:src/workbench/graphWidgets.ts","source:src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx",@@ -1071,6 +1070,7 @@"source:src/workbench/shell/notifications/undoRegistry.ts","source:src/workbench/shell/overflowEdges.tsx","source:src/workbench/shell/topbar/AppMenu.tsx",+ "source:src/workbench/shell/topbar/GraphPreviewInvokeScope.tsx","source:src/workbench/shell/topbar/InvocationCluster.tsx","source:src/workbench/shell/topbar/InvokeButton.tsx","source:src/workbench/shell/topbar/IterationsField.tsx",@@ -1117,6 +1117,7 @@"source:src/workbench/widget-frame/WidgetStrip.tsx","source:src/workbench/widget-frame/compactWidgetCapacity.tsx","source:src/workbench/widget-frame/createWidgetRuntime.ts",+ "source:src/workbench/widget-frame/graphPreviewInvoke.ts","source:src/workbench/widget-frame/index.ts","source:src/workbench/widget-frame/useWidgetIntentPreload.ts","source:src/workbench/widget-frame/useWidgetSortable.ts",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex dff52e984d..af7d5b7138 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1,5 +1,5 @@{- "browserExecutable": "/home/lstein/.cache/ms-playwright/chromium-1248/chrome-linux64/chrome",+ "browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1248/chrome-linux64/chrome","capturedAt": "2026-11-09","routes": [{@@ -14,13 +14,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 93.5,+ "domContentLoadedMedianMs": 117.5,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 93.59999990463257,- "longestTaskMaxMs": 66,+ "loadMedianMs": 117.59999999776483,+ "longestTaskMaxMs": 74,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -29,14 +29,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 0,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 28,- "scriptRawBytes": 1931272,+ "scriptRawBytes": 1932580,"scriptRequestCount": 24,- "totalRawBytes": 2272325+ "totalRawBytes": 2276142},- "routeReadyMedianMs": 198.40000009536743,+ "routeReadyMedianMs": 241.90000000223517,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "empty"},@@ -52,13 +52,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 91.89999961853027,+ "domContentLoadedMedianMs": 118.30000000074506,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 92.09999990463257,- "longestTaskMaxMs": 67,+ "loadMedianMs": 118.5,+ "longestTaskMaxMs": 79,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -67,14 +67,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 0,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 28,- "scriptRawBytes": 1931272,+ "scriptRawBytes": 1932580,"scriptRequestCount": 24,- "totalRawBytes": 2272325+ "totalRawBytes": 2276142},- "routeReadyMedianMs": 216.09999990463257,+ "routeReadyMedianMs": 261.30000000074506,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "representative"},@@ -90,29 +90,29 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 94.7999997138977,+ "domContentLoadedMedianMs": 118.39999999850988,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 95,- "longestTaskMaxMs": 157,+ "loadMedianMs": 118.39999999850988,+ "longestTaskMaxMs": 182,"owner": "workbench",- "projectSwitchMedianMs": 41.80000019073486,+ "projectSwitchMedianMs": 37.70000000298023,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 84,- "scriptRawBytes": 4648020,+ "scriptRawBytes": 4575582,"scriptRequestCount": 79,- "totalRawBytes": 5033471+ "totalRawBytes": 4963542},- "routeReadyMedianMs": 335.90000009536743,+ "routeReadyMedianMs": 421.19999999925494,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -128,29 +128,29 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 94.2000002861023,+ "domContentLoadedMedianMs": 115.69999999925494,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 94.40000009536743,- "longestTaskMaxMs": 155,+ "loadMedianMs": 115.80000000074506,+ "longestTaskMaxMs": 181,"owner": "workbench",- "projectSwitchMedianMs": 51.40000009536743,+ "projectSwitchMedianMs": 46.899999998509884,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 84,- "scriptRawBytes": 4648020,+ "scriptRawBytes": 4575582,"scriptRequestCount": 79,- "totalRawBytes": 5033471+ "totalRawBytes": 4963542},- "routeReadyMedianMs": 339.59999990463257,+ "routeReadyMedianMs": 423.19999999925494,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"},@@ -159,20 +159,20 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 342603,+ "largestAssetRawBytes": 342634,"otherRawBytes": 0,"requestCount": 8,- "scriptRawBytes": 598449,+ "scriptRawBytes": 598467,"scriptRequestCount": 8,- "totalRawBytes": 598449+ "totalRawBytes": 598467},- "domContentLoadedMedianMs": 91.89999961853027,+ "domContentLoadedMedianMs": 117.5,"id": "editor-canvas",- "layoutAckMedianMs": 3.6000003814697266,- "layoutReturnSwitchMedianMs": 60.200000286102295,- "layoutSwitchMedianMs": 78.80000019073486,- "loadMedianMs": 92.09999990463257,- "longestTaskMaxMs": 152,+ "layoutAckMedianMs": 3.5,+ "layoutReturnSwitchMedianMs": 65.19999999925494,+ "layoutSwitchMedianMs": 88.59999999776483,+ "loadMedianMs": 117.59999999776483,+ "longestTaskMaxMs": 181,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -181,14 +181,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 92,- "scriptRawBytes": 5246469,+ "scriptRawBytes": 5174049,"scriptRequestCount": 87,- "totalRawBytes": 5631920+ "totalRawBytes": 5562009},- "routeReadyMedianMs": 1051.5999999046326,+ "routeReadyMedianMs": 1158.2999999970198,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "empty"},@@ -197,20 +197,20 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 342603,+ "largestAssetRawBytes": 342634,"otherRawBytes": 0,"requestCount": 8,- "scriptRawBytes": 598449,+ "scriptRawBytes": 598467,"scriptRequestCount": 8,- "totalRawBytes": 598449+ "totalRawBytes": 598467},- "domContentLoadedMedianMs": 90.5,+ "domContentLoadedMedianMs": 117.60000000149012,"id": "editor-canvas",- "layoutAckMedianMs": 3.9000000953674316,- "layoutReturnSwitchMedianMs": 55.200000286102295,- "layoutSwitchMedianMs": 79.80000019073486,- "loadMedianMs": 90.59999990463257,- "longestTaskMaxMs": 186,+ "layoutAckMedianMs": 4.099999997764826,+ "layoutReturnSwitchMedianMs": 60.30000000074506,+ "layoutSwitchMedianMs": 90.30000000074506,+ "loadMedianMs": 117.79999999701977,+ "longestTaskMaxMs": 209,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -219,14 +219,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 92,- "scriptRawBytes": 5246469,+ "scriptRawBytes": 5174049,"scriptRequestCount": 87,- "totalRawBytes": 5631920+ "totalRawBytes": 5562009},- "routeReadyMedianMs": 1049.4000000953674,+ "routeReadyMedianMs": 1150.699999999255,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "representative"},@@ -235,20 +235,20 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 210757,+ "largestAssetRawBytes": 220580,"otherRawBytes": 0,"requestCount": 6,- "scriptRawBytes": 459316,+ "scriptRawBytes": 459562,"scriptRequestCount": 5,- "totalRawBytes": 474729+ "totalRawBytes": 474975},- "domContentLoadedMedianMs": 87.90000009536743,+ "domContentLoadedMedianMs": 117.90000000223517,"id": "editor-workflow",- "layoutAckMedianMs": 3.799999713897705,- "layoutReturnSwitchMedianMs": 36.200000286102295,- "layoutSwitchMedianMs": 70.30000019073486,- "loadMedianMs": 88,- "longestTaskMaxMs": 151,+ "layoutAckMedianMs": 3.699999999254942,+ "layoutReturnSwitchMedianMs": 39.30000000074506,+ "layoutSwitchMedianMs": 77.30000000074506,+ "loadMedianMs": 118,+ "longestTaskMaxMs": 177,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -257,14 +257,14 @@"cssRawBytes": 17572,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 90,- "scriptRawBytes": 5107336,+ "scriptRawBytes": 5035144,"scriptRequestCount": 84,- "totalRawBytes": 5508200+ "totalRawBytes": 5438517},- "routeReadyMedianMs": 1043.1999998092651,+ "routeReadyMedianMs": 1151.300000000745,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "empty"},@@ -273,20 +273,20 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 210757,+ "largestAssetRawBytes": 220580,"otherRawBytes": 0,"requestCount": 6,- "scriptRawBytes": 459316,+ "scriptRawBytes": 459562,"scriptRequestCount": 5,- "totalRawBytes": 474729+ "totalRawBytes": 474975},- "domContentLoadedMedianMs": 92.19999980926514,+ "domContentLoadedMedianMs": 116.19999999925494,"id": "editor-workflow",- "layoutAckMedianMs": 3.9000000953674316,- "layoutReturnSwitchMedianMs": 47,- "layoutSwitchMedianMs": 132.5,- "loadMedianMs": 92.39999961853027,- "longestTaskMaxMs": 233,+ "layoutAckMedianMs": 3.900000002235174,+ "layoutReturnSwitchMedianMs": 49.099999997764826,+ "layoutSwitchMedianMs": 144.89999999850988,+ "loadMedianMs": 116.30000000074506,+ "longestTaskMaxMs": 281,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -295,14 +295,14 @@"cssRawBytes": 17572,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 90,- "scriptRawBytes": 5107336,+ "scriptRawBytes": 5035144,"scriptRequestCount": 84,- "totalRawBytes": 5508200+ "totalRawBytes": 5438517},- "routeReadyMedianMs": 1105.4000000953674,+ "routeReadyMedianMs": 1185.5,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "representative"},@@ -318,13 +318,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 89.80000019073486,+ "domContentLoadedMedianMs": 117.19999999925494,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 45.39999961853027,- "loadMedianMs": 89.90000009536743,- "longestTaskMaxMs": 158,+ "layoutSwitchMedianMs": 48.600000001490116,+ "loadMedianMs": 117.40000000223517,+ "longestTaskMaxMs": 176,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -333,14 +333,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 84,- "scriptRawBytes": 4648020,+ "scriptRawBytes": 4575582,"scriptRequestCount": 79,- "totalRawBytes": 5033471+ "totalRawBytes": 4963542},- "routeReadyMedianMs": 1284.4000000953674,+ "routeReadyMedianMs": 1400.199999999255,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -356,13 +356,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 89,+ "domContentLoadedMedianMs": 117.39999999850988,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 53.19999980926514,- "loadMedianMs": 89.09999990463257,- "longestTaskMaxMs": 152,+ "layoutSwitchMedianMs": 58.399999998509884,+ "loadMedianMs": 117.39999999850988,+ "longestTaskMaxMs": 186,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -371,14 +371,14 @@"cssRawBytes": 2159,"fontRawBytes": 23664,"imageRawBytes": 44398,- "largestAssetRawBytes": 751079,- "otherRawBytes": 315230,+ "largestAssetRawBytes": 751084,+ "otherRawBytes": 317739,"requestCount": 84,- "scriptRawBytes": 4648020,+ "scriptRawBytes": 4575582,"scriptRequestCount": 79,- "totalRawBytes": 5033471+ "totalRawBytes": 4963542},- "routeReadyMedianMs": 1283.0999999046326,+ "routeReadyMedianMs": 1382.699999999255,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"}@@ -1260,14 +1260,12 @@"source:src/features/workflow/core/validation.ts","source:src/features/workflow/core/workflowJson.ts","source:src/features/workflow/data/api.ts",- "source:src/features/workflow/data/libraryBrowseStore.ts","source:src/features/workflow/data/libraryCache.ts","source:src/features/workflow/data/publication.ts","source:src/features/workflow/data/savedWorkflowQueries.ts","source:src/features/workflow/data/templates.ts","source:src/features/workflow/queries.ts","source:src/features/workflow/react.ts",- "source:src/features/workflow/ui/MenuActionItem.tsx","source:src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx","source:src/features/workflow/ui/WorkflowUiContext.tsx","source:src/features/workflow/ui/WorkflowWidgetChrome.tsx",@@ -1275,23 +1273,15 @@"source:src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx","source:src/features/workflow/ui/editor/flowInstanceStore.ts","source:src/features/workflow/ui/editor/selectionStore.ts",+ "source:src/features/workflow/ui/editor/workflowPngExport.ts","source:src/features/workflow/ui/editor/workflowViewportStore.ts","source:src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsx",- "source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx","source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx",- "source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx","source:src/features/workflow/ui/library/libraryPreviewSource.ts","source:src/features/workflow/ui/library/projectWorkflowEntries.ts","source:src/features/workflow/ui/library/relativeTime.ts","source:src/features/workflow/ui/library/useOpenLibraryWorkflow.ts","source:src/features/workflow/ui/library/useWorkflowPublication.ts",- "source:src/features/workflow/ui/library/workflowThumbnail.tsx","source:src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts","source:src/features/workflow/ui/useProjectGraphCommands.ts","source:src/features/workflow/ui/workflowTransfer.ts",@@ -1319,6 +1309,7 @@"source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts","source:src/platform/react/composeProviders.tsx",+ "source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts","source:src/platform/react/useDebouncedValue.ts",@@ -1632,7 +1623,6 @@"source:src/workbench/extensions/extensionRegistry.ts","source:src/workbench/floatingWindows.ts","source:src/workbench/focusRegions.tsx",- "source:src/workbench/graphPreviewInvocation.ts","source:src/workbench/graphSurfaces.ts","source:src/workbench/graphWidgets.ts","source:src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx",@@ -1807,6 +1797,7 @@"source:src/workbench/shell/notifications/undoRegistry.ts","source:src/workbench/shell/overflowEdges.tsx","source:src/workbench/shell/topbar/AppMenu.tsx",+ "source:src/workbench/shell/topbar/GraphPreviewInvokeScope.tsx","source:src/workbench/shell/topbar/InvocationCluster.tsx","source:src/workbench/shell/topbar/InvokeButton.tsx","source:src/workbench/shell/topbar/IterationsField.tsx",@@ -1853,6 +1844,7 @@"source:src/workbench/widget-frame/WidgetStrip.tsx","source:src/workbench/widget-frame/compactWidgetCapacity.tsx","source:src/workbench/widget-frame/createWidgetRuntime.ts",+ "source:src/workbench/widget-frame/graphPreviewInvoke.ts","source:src/workbench/widget-frame/index.ts","source:src/workbench/widget-frame/useWidgetIntentPreload.ts","source:src/workbench/widget-frame/useWidgetSortable.ts",@@ -2437,14 +2429,12 @@"source:src/features/workflow/core/validation.ts","source:src/features/workflow/core/workflowJson.ts","source:src/features/workflow/data/api.ts",- "source:src/features/workflow/data/libraryBrowseStore.ts","source:src/features/workflow/data/libraryCache.ts","source:src/features/workflow/data/publication.ts","source:src/features/workflow/data/savedWorkflowQueries.ts","source:src/features/workflow/data/templates.ts","source:src/features/workflow/queries.ts","source:src/features/workflow/react.ts",- "source:src/features/workflow/ui/MenuActionItem.tsx","source:src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx","source:src/features/workflow/ui/WorkflowUiContext.tsx","source:src/features/workflow/ui/WorkflowWidgetChrome.tsx",@@ -2452,23 +2442,15 @@"source:src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx","source:src/features/workflow/ui/editor/flowInstanceStore.ts","source:src/features/workflow/ui/editor/selectionStore.ts",+ "source:src/features/workflow/ui/editor/workflowPngExport.ts","source:src/features/workflow/ui/editor/workflowViewportStore.ts","source:src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsx",- "source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx","source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx",- "source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx","source:src/features/workflow/ui/library/libraryPreviewSource.ts","source:src/features/workflow/ui/library/projectWorkflowEntries.ts","source:src/features/workflow/ui/library/relativeTime.ts","source:src/features/workflow/ui/library/useOpenLibraryWorkflow.ts","source:src/features/workflow/ui/library/useWorkflowPublication.ts",- "source:src/features/workflow/ui/library/workflowThumbnail.tsx","source:src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts","source:src/features/workflow/ui/useProjectGraphCommands.ts","source:src/features/workflow/ui/workflowTransfer.ts",@@ -2496,6 +2478,7 @@"source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts","source:src/platform/react/composeProviders.tsx",+ "source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts","source:src/platform/react/useDebouncedValue.ts",@@ -2816,7 +2799,6 @@"source:src/workbench/extensions/extensionRegistry.ts","source:src/workbench/floatingWindows.ts","source:src/workbench/focusRegions.tsx",- "source:src/workbench/graphPreviewInvocation.ts","source:src/workbench/graphSurfaces.ts","source:src/workbench/graphWidgets.ts","source:src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx",@@ -2994,6 +2976,7 @@"source:src/workbench/shell/notifications/undoRegistry.ts","source:src/workbench/shell/overflowEdges.tsx","source:src/workbench/shell/topbar/AppMenu.tsx",+ "source:src/workbench/shell/topbar/GraphPreviewInvokeScope.tsx","source:src/workbench/shell/topbar/InvocationCluster.tsx","source:src/workbench/shell/topbar/InvokeButton.tsx","source:src/workbench/shell/topbar/IterationsField.tsx",@@ -3041,6 +3024,7 @@"source:src/workbench/widget-frame/WidgetStrip.tsx","source:src/workbench/widget-frame/compactWidgetCapacity.tsx","source:src/workbench/widget-frame/createWidgetRuntime.ts",+ "source:src/workbench/widget-frame/graphPreviewInvoke.ts","source:src/workbench/widget-frame/index.ts","source:src/workbench/widget-frame/useWidgetIntentPreload.ts","source:src/workbench/widget-frame/useWidgetSortable.ts",@@ -3798,7 +3782,6 @@"source:src/features/workflow/core/formFieldSettings.ts","source:src/features/workflow/core/graphIndex.ts","source:src/features/workflow/core/graphLayout.ts",- "source:src/features/workflow/core/graphToDocument.ts","source:src/features/workflow/core/libraryTags.ts","source:src/features/workflow/core/modelRequirements.ts","source:src/features/workflow/core/outputFields.ts",@@ -3807,7 +3790,6 @@"source:src/features/workflow/core/validation.ts","source:src/features/workflow/core/workflowJson.ts","source:src/features/workflow/data/api.ts",- "source:src/features/workflow/data/libraryBrowseStore.ts","source:src/features/workflow/data/libraryCache.ts","source:src/features/workflow/data/publication.ts","source:src/features/workflow/data/savedWorkflowFieldUtils.ts",@@ -3815,7 +3797,6 @@"source:src/features/workflow/data/templates.ts","source:src/features/workflow/queries.ts","source:src/features/workflow/react.ts",- "source:src/features/workflow/ui/MenuActionItem.tsx","source:src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx","source:src/features/workflow/ui/WorkflowUiContext.tsx","source:src/features/workflow/ui/WorkflowWidgetChrome.tsx",@@ -3830,6 +3811,7 @@"source:src/features/workflow/ui/editor/NodeContextMenu.tsx","source:src/features/workflow/ui/editor/NotesFlowNode.tsx","source:src/features/workflow/ui/editor/WorkflowEdge.tsx",+ "source:src/features/workflow/ui/editor/WorkflowEditorMiniMap.tsx","source:src/features/workflow/ui/editor/WorkflowEditorView.tsx","source:src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx","source:src/features/workflow/ui/editor/clipboard.ts",@@ -3837,42 +3819,28 @@"source:src/features/workflow/ui/editor/flowAdapters.ts","source:src/features/workflow/ui/editor/flowInstanceStore.ts","source:src/features/workflow/ui/editor/handleTooltip.ts",+ "source:src/features/workflow/ui/editor/nodeStatusText.ts","source:src/features/workflow/ui/editor/performanceConstants.ts","source:src/features/workflow/ui/editor/selectionStore.ts","source:src/features/workflow/ui/editor/useEraser.tsx","source:src/features/workflow/ui/editor/useLasso.tsx","source:src/features/workflow/ui/editor/workflowHotkeys.ts",+ "source:src/features/workflow/ui/editor/workflowPngExport.ts","source:src/features/workflow/ui/editor/workflowViewportStore.ts","source:src/features/workflow/ui/fields/FieldDescriptionPopover.tsx","source:src/features/workflow/ui/fields/NumericInput.tsx","source:src/features/workflow/ui/fields/WorkflowFieldInput.tsx","source:src/features/workflow/ui/fields/mediaFieldDnd.ts","source:src/features/workflow/ui/graph-preview/FlowMiniMap.tsx",- "source:src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx",- "source:src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx",- "source:src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx",- "source:src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx",- "source:src/features/workflow/ui/graph-preview/GraphPreviewSnapshot.tsx","source:src/features/workflow/ui/graph-preview/flowTheme.ts",- "source:src/features/workflow/ui/graph-preview/index.ts",- "source:src/features/workflow/ui/graph-preview/nodeSummaries.ts","source:src/features/workflow/ui/implementation.ts","source:src/features/workflow/ui/library/LibraryCopyChoiceDialog.tsx",- "source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",- "source:src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx","source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx",- "source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx","source:src/features/workflow/ui/library/libraryPreviewSource.ts","source:src/features/workflow/ui/library/projectWorkflowEntries.ts","source:src/features/workflow/ui/library/relativeTime.ts","source:src/features/workflow/ui/library/useOpenLibraryWorkflow.ts","source:src/features/workflow/ui/library/useWorkflowPublication.ts",- "source:src/features/workflow/ui/library/workflowThumbnail.tsx","source:src/features/workflow/ui/linear/FormBuilderTab.tsx","source:src/features/workflow/ui/linear/LinearFormView.tsx","source:src/features/workflow/ui/linear/LinkifiedText.tsx",@@ -3914,6 +3882,7 @@"source:src/platform/pwa/registerServiceWorker.ts","source:src/platform/query/client.ts","source:src/platform/react/composeProviders.tsx",+ "source:src/platform/react/deferredModule.tsx","source:src/platform/react/draftRegistry.ts","source:src/platform/react/focusIfUnclaimed.ts","source:src/platform/react/useDebouncedValue.ts",@@ -4227,7 +4196,6 @@"source:src/workbench/extensions/extensionRegistry.ts","source:src/workbench/floatingWindows.ts","source:src/workbench/focusRegions.tsx",- "source:src/workbench/graphPreviewInvocation.ts","source:src/workbench/graphSurfaces.ts","source:src/workbench/graphWidgets.ts","source:src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx",@@ -4402,6 +4370,7 @@"source:src/workbench/shell/notifications/undoRegistry.ts","source:src/workbench/shell/overflowEdges.tsx","source:src/workbench/shell/topbar/AppMenu.tsx",+ "source:src/workbench/shell/topbar/GraphPreviewInvokeScope.tsx","source:src/workbench/shell/topbar/InvocationCluster.tsx","source:src/workbench/shell/topbar/InvokeButton.tsx","source:src/workbench/shell/topbar/IterationsField.tsx",@@ -4448,6 +4417,7 @@"source:src/workbench/widget-frame/WidgetStrip.tsx","source:src/workbench/widget-frame/compactWidgetCapacity.tsx","source:src/workbench/widget-frame/createWidgetRuntime.ts",+ "source:src/workbench/widget-frame/graphPreviewInvoke.ts","source:src/workbench/widget-frame/index.ts","source:src/workbench/widget-frame/useWidgetIntentPreload.ts","source:src/workbench/widget-frame/useWidgetSortable.ts",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 09093d0023..9201199006 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -870,45 +870,26 @@"instancesTitle": "Named instances"},"graphPreview": {- "back": "Back","cfgScale": "CFG scale",- "compiledFrom": "Compiled from {{source}}.",- "copied": "Copied","copyFailed": "Failed to copy JSON",- "copyJson": "Copy JSON",- "destination": "Destination",- "downloadJson": "Download JSON",- "downloadJsonHint": "For bug reports and sharing",- "edges": "Edges",- "edgesInNone": "in · none",- "edgesIn_one": "in · {{count}} input from {{sources}}",- "edgesIn_other": "in · {{count}} inputs from {{sources}}",- "edgesOut": "out · {{field}} → {{target}}","editInEditor": "Edit in workflow editor","editInEditorFailed": "No editable nodes in this graph.",- "editInEditorHint": "Replaces the current workflow","forkIntoProject": "Fork into new project","forkIntoProjectFailed": "No nodes to fork into a project.",- "forkIntoProjectHint": "Copies this graph into a fresh project",- "graph": "Graph",- "graphJsonLabel": "{{title}} graph JSON","inputCount_one": "{{count}} input","inputCount_other": "{{count}} inputs","invalidTitle": "This graph can't compile yet.",- "invokeRoute": "Invoke {{route}}",- "list": "List","liveHint": "Updates as you change settings.","loras": "LoRAs","model": "Model","noCompiledGraph": "No compiled graph is available for \"{{graphId}}\" yet.","nodeSummary": {- "denoise": "{{steps}} steps · cfg {{cfg}}",+ "denoise_one": "{{count, number}} step · cfg {{cfg, number}}",+ "denoise_other": "{{count, number}} steps · cfg {{cfg, number}}","noise": "{{width}} × {{height}}"},- "nodes": "Nodes","nodesSkipped_one": "Skipped {{count}} node type without a template: {{types}}","nodesSkipped_other": "Skipped {{count}} node types without templates: {{types}}",- "openAs": "Open as","openedFromPreview": "Opened from graph preview","provenance": {"cfgScale": "Generate → CFG scale",@@ -923,23 +904,25 @@"size": "Generate → Size","steps": "Generate → Steps"},- "resolvedInputs": "Resolved inputs","saveToLibrary": "Save to workflow library","saveToLibraryFailed": "No saveable nodes in this graph.",- "saveToLibraryHint": "Reusable, leaves this project alone",- "savedToLibrary": "Saved to workflow library","scheduler": "Scheduler","seed": "Seed","seedRandomValue": "random","seedRandomized": "Seed is randomized. This graph runs differently each time.","seedRegenerated": "regenerated each run",- "selectNode": "Select a node for details.",- "setBy": "Set by",- "showNode": "show node",+ "showNode": "Show node","size": "Size","steps": "Steps",- "thisGraph": "This graph",- "title": "Graph preview"+ "aboutThisGraph": "About this graph",+ "more": "More",+ "copyGraphJson": "Copy graph JSON",+ "downloadGraphJson": "Download graph JSON",+ "graphJsonCopied": "Graph JSON copied",+ "readyToInvoke": "Ready to invoke",+ "cannotInvoke": "Can't invoke yet",+ "editAsWorkflow": "Edit as workflow",+ "destination": "Destination"},"hotkeys": {"addHotkey": "Add hotkey",@@ -1996,11 +1979,9 @@"direct": "Direct value only","any": "Direct value or connection"},- "pinnedToForm": "Pinned to the form.",+ "inForm": "In the form","renameFieldHint": "Double-click the name to rename it.",- "addToForm": "Add to form","addFieldToForm": "Add {{label}} to the form",- "removeFromForm": "Remove from form","removeFieldFromForm": "Remove {{label}} from the form","resetToDefault": "Reset to default value","resetFieldToDefault": "Reset {{label}} to default value",@@ -2062,7 +2043,6 @@"nodePacks": "Node Packs","nodeType": "Type: {{type}}","nodeVersion": "Version: {{version}}",- "nodeClassification": "Classification: {{classification}}","seedModeTooltip": "Applies between queued runs of the workflow; a loop inside one run reuses that run's seed.","framePreview": "Frame preview","framePreviewPlaybackError": "Frame preview unavailable — the video could not be played.",@@ -2141,6 +2121,25 @@},"executionCompleted": "Completed","executionFailed": "Failed",+ "collapsedConnections_one": "{{count}} connection between collapsed nodes",+ "collapsedConnections_other": "{{count}} connections between collapsed nodes",+ "status": {+ "label": "Status: {{status}}",+ "running": "Running",+ "runningProgress": "Running ({{percent, number}}%)",+ "issueCount_one": "{{count}} field needs attention",+ "issueCount_other": "{{count}} fields need attention",+ "fieldRequired": "{{field}} is required.",+ "pickModel": "{{field}} is required. Pick a model.",+ "needsConnection": "{{field}} needs a connection.",+ "fieldInvalid": "{{field}}: {{reason}}"+ },+ "classificationDescriptions": {+ "beta": "This node is in beta. Until it is stable, app updates may change it in breaking ways.",+ "internal": "This node is used internally by Invoke. App updates may change it in breaking ways or remove it.",+ "prototype": "This node is a prototype. App updates may change it in breaking ways or remove it.",+ "special": "This node gets special handling in the app. For example, batch nodes queue several graphs from one workflow."+ },"childWorkflowError": "Child workflow error: {{error}}","forLoopBodyBoundary": "For loop body","imageCollectionCount_one": "{{count}} image",@@ -2172,7 +2171,7 @@"updateDroppedFormFields_one": "Removed {{count}} form field for an input its updated node no longer has.","updateDroppedFormFields_other": "Removed {{count}} form fields for inputs their updated nodes no longer have.","contextPaste": "Paste",- "contextPasteWithConnections": "Paste with connections",+ "contextPasteWithConnections": "Smart paste","contextCollapse": "Collapse","contextExpand": "Expand","contextFitSelection": "Fit selection",@@ -4749,7 +4748,7 @@},"connectorNode": "Connector node","contact": "Contact",- "copyJson": "Copy workflow JSON",+ "copyJson": "Copy JSON","copyJsonFailed": "Failed to copy workflow JSON","copyJsonSuccess": "Workflow JSON copied","copiedNodes_one": "Copied {{count}} node",@@ -4759,9 +4758,13 @@"declaredOutputs": "Declared outputs","description": "Description","details": "Details",- "detailsWithEllipsis": "Workflow details…",- "renameWithEllipsis": "Rename workflow…",- "exportJson": "Export workflow JSON",+ "detailsWithEllipsis": "Details…",+ "downloadPng": "Download as PNG",+ "downloadPngUnavailable": "Open the workflow editor to download it as an image",+ "downloadPngRunning": "Already downloading the workflow as an image",+ "export": "Export",+ "renameWithEllipsis": "Rename…",+ "exportJson": "Export JSON","exportAsPng": "Download workflow as PNG","exportImageBusy": "A previous workflow image export is still finishing. Try again shortly.","exportImageFailed": "Could not export workflow image.",@@ -4830,9 +4833,10 @@"generating": "Generating…","importFailed": "Failed to import workflow","importInvalid": "The file is not a valid workflow JSON.",- "importJsonWithEllipsis": "Import workflow JSON…",+ "importJsonWithEllipsis": "Import from JSON…","importWarning": "Workflow import warning","importedLabel": "Imported \"{{name}}\"",+ "inThisProject": "In this project","inspectorTabs": {"data": "Data","details": "Details",@@ -4849,6 +4853,8 @@"loadingGraphEdges_other": "{{count, number}} edges","loadingGraphNodes_one": "{{count, number}} node","loadingGraphNodes_other": "{{count, number}} nodes",+ "menuImportExport": "Import and export",+ "menuThisWorkflow": "This workflow","newWorkflow": "New workflow","noRunRecorded": "This node has not run in this session.","noTemplateKnown": "No template is known for \"{{type}}\" on this backend.",@@ -4862,7 +4868,6 @@"noteTitle": "Note title","notes": "Notes","notesNode": "Notes node",- "openProjectWorkflows": "Open this project's workflows. Current workflow: {{name}}","outputImage": "Output image","pack": "Pack","panelContent": "Workflow panel content",@@ -4874,13 +4879,13 @@"persistenceSaved": "Project saved to the server","persistenceSaving": "Saving project…","preparingGraph": "Preparing workflow graph",- "projectWorkflows": "This project's workflows","resizeNodeInspector": "Resize node inspector","runStatus": {"completed": "Completed","failed": "Failed","running": "Running…"},+ "saveAsNewTemplateWithEllipsis": "Save as new template…","saveToLibrary": "Save to library","saveToLibraryWithEllipsis": "Save to library…","selectNodeToInspect": "Select a node in the workflow editor to inspect it.",@@ -4888,6 +4893,8 @@"status": "Status","submitRemovedBody": "The workflow was removed from the project before it could be queued.","submitRemovedTitle": "Workflow not queued",+ "switchWorkflow": "Switch workflow",+ "switchWorkflowTrigger": "Switch workflow. Current workflow: {{name}}","tags": "Tags","title": "Title","toolbar": {@@ -6730,10 +6737,16 @@}},"workflowLibrary": {+ "dialogLoadFailed": "Could not load the workflow library.","activeWorkflow": "Active",- "allTag": "All","applying": "Applying workflow…",- "browse": "Browse",+ "cardSize": "Card size",+ "cardSizeLarge": "Large cards",+ "cardSizeSmall": "Small cards",+ "clearTags": "Clear",+ "layoutGrid": "Grid",+ "layoutGroup": "View",+ "layoutList": "List","conflictStaleBody": "The library template behind \"{{name}}\" has changed since this copy was loaded or last saved.","conflictTitle": "Template has changed","conflictUnknownBody": "It is not known whether the library template behind \"{{name}}\" still matches this copy.",@@ -6741,20 +6754,18 @@"deleteConfirmBody": "Delete \"{{name}}\" from the workflow library? This cannot be undone.","deleteConfirmTitle": "Delete workflow","deleteFailed": "Failed to delete workflow",- "deleteHint": "Removes it from your library","downloadJson": "Download JSON",- "downloadJsonHint": "For bug reports and sharing","duplicate": "Duplicate","duplicateFailed": "Failed to duplicate workflow",- "duplicateHint": "Saves a copy under Yours, original untouched","duplicateName": "{{name}} copy",- "duplicateProjectWorkflowHint": "A copy beside it in this project",- "duplicated": "Saved a copy under Yours",+ "duplicated": "Saved a copy in My library","empty": "No workflows match these filters.",+ "emptyRecent": "Nothing opened yet. Workflows you open from My library or Templates appear here.",+ "emptyShared": "Nothing shared yet. Public workflows on this server appear here.",+ "emptyUser": "No saved workflows yet. Use Save to library… in the editor to keep one here.","fetching": "Fetching workflow…","findModel": "Find {{name}} in the model manager","forkIntoProject": "Fork into new project",- "forkIntoProjectHint": "Copies it into a new project","installModels_one": "Install 1 model","installModels_other": "Install {{count}} models","installQueued": "Model installs queued",@@ -6763,6 +6774,105 @@"loadFailedBody": "Could not load \"{{name}}\".","loadWarning": "Workflow load warning","loadedLabel": "Loaded \"{{name}}\" from library",+ "placeDefault": "Templates",+ "placeProject": "In this project",+ "placeRecent": "Recent",+ "places": "Places",+ "placeShared": "Shared with me",+ "placeUser": "My library",+ "preview": {+ "loadFailed": "Could not load the workflow preview.",+ "action": "Preview",+ "actionHint": "Preview",+ "atFirst": "This is the first workflow here",+ "atLast": "This is the last workflow here",+ "authorNotes": "Author's notes",+ "backTo": "Back to {{place}}",+ "byAuthor": "by {{author}}",+ "copyJson": "Copy workflow JSON",+ "downloadJson": "Download workflow JSON",+ "edgeLabel": "{{source}} to {{target}}",+ "empty": "This workflow has no nodes yet.",+ "emptyValue": "Empty",+ "exportMenu": "Export",+ "find": "Find a node",+ "findMatches_one": "{{count}} match",+ "findMatches_other": "{{count}} matches",+ "findNone": "No matches",+ "fit": "Fit",+ "from": "From",+ "graph": "Graph",+ "helpersFolded_one": "{{count}} helper folded",+ "helpersFolded_other": "{{count}} helpers folded",+ "inputCount_one": "{{count}} input",+ "inputCount_other": "{{count}} inputs",+ "inputs": "Inputs",+ "inputsIntro": "What you fill in after opening, as the author arranged it. The values shown are the saved defaults; nothing here is editable.",+ "kindLibrary": "My library",+ "kindProject": "In this project",+ "kindShared": "Shared",+ "kindTemplate": "Template",+ "legend": "Markers",+ "loading": "Loading workflow…",+ "minimap": "Minimap",+ "modelNotInstalled": "Model not installed",+ "modelToPick": "Model to pick",+ "more": "+{{count}}",+ "needsModel": "Needs a model",+ "needsModelInline": "needs a model",+ "needsModelNote": "Needs a model that isn't installed",+ "next": "Next workflow",+ "noInputs": "This workflow exposes no inputs. Its values are set on its nodes.",+ "nodeHint": "Press Enter to show this node's details.",+ "nodePackMissing": "Node pack missing",+ "nothingSelected": "No workflow is selected.",+ "pickAfterOpening": "Pick one after opening",+ "position": "{{position, number}} of {{total, number}}",+ "positionUnknown": "Its place in these results isn't loaded",+ "previewNamed": "Preview {{name}}",+ "previous": "Previous workflow",+ "readAllNotes": "Read all notes",+ "region": "Preview of {{name}}",+ "result": "Result",+ "resultInline": "result",+ "seeAllInputs_one": "See the input",+ "seeAllInputs_other": "See all {{count}} inputs",+ "showAll": "Show all {{count, number}}",+ "showLessNotes": "Show less",+ "showNode": "{{node}}: show in Nodes",+ "showingAll_one": "Showing {{count, number}} node, as drawn",+ "showingAll_other": "Showing all {{count, number}} nodes, as drawn",+ "showingNodes_one": "Showing {{shown, number}} of {{count, number}} node",+ "showingNodes_other": "Showing {{shown, number}} of {{count, number}} nodes",+ "simplify": "Simplify",+ "stepper": "Step through workflows",+ "summaryFrames_one": "{{count, number}} frame",+ "summaryFrames_other": "{{count, number}} frames",+ "summaryFramesSteps": "{{frames}} · {{steps}}",+ "summarySteps_one": "{{count, number}} step",+ "summarySteps_other": "{{count, number}} steps",+ "to": "To",+ "unknownNode": "Unknown node type: its node pack isn't installed on this server.",+ "unknownNodeMarker": "unknown node type",+ "unreadable": "This workflow can't be previewed: {{message}}",+ "valueItems_one": "{{count}} item",+ "valueItems_other": "{{count}} items",+ "valueNumber": "{{value, number}}",+ "valueOff": "Off",+ "valueOn": "On",+ "version": "v{{version}}",+ "view": "Preview view",+ "withHelpers": "with {{helpers}}",+ "youSet": "You set",+ "youSetThis": "You set this",+ "youSetThisInline": "you set this",+ "zoomControls": "Zoom",+ "zoomIn": "Zoom in",+ "zoomOut": "Zoom out",+ "zoomPercent": "{{percent}}%",+ "nodes": "Nodes",+ "graphJson": "Graph JSON"+ },"replacedLabel": "Replaced with \"{{name}}\" from library","loading": "Loading workflows…","loadingMore": "Loading more…",@@ -6770,8 +6880,8 @@"multipleWorkflowReturnNodes": "The workflow must contain exactly one workflow return node before it can be saved.","multipleWorkflowReturnNodesForTransfer": "The workflow must contain exactly one workflow return node before it can be exported or copied.","newWorkflow": "New workflow",- "nodeCount_one": "{{count}} node",- "nodeCount_other": "{{count}} nodes",+ "nodeCount_one": "{{count, number}} node",+ "nodeCount_other": "{{count, number}} nodes","notRunYet": "Not run yet","copyChoice": {"addCopy": "Add new copy",@@ -6785,28 +6895,20 @@"title": "“{{name}}” is already in this project"},"open": "Open",- "openExistingCopiesHint": "This project already has a copy; choose to open it, add another, or replace it",- "openHint": "Adds a copy to this project","openWithEllipsis": "Open…","openProjectChanged": "The project changed while \"{{name}}\" was loading; nothing was added.",- "openProjectWorkflowHint": "Makes it the active workflow","previewGraph": "Preview graph","private": "Private","public": "Public","publicVisibilityHelp": "Visible to users of this Invoke instance.","publicVisibilityPartial": "The template was saved, but its public visibility could not be confirmed ({{message}}). Retry to make it public.","publicWorkflow": "Public workflow",- "projectWorkflowCount_one": "{{count}} workflow in this project",- "projectWorkflowCount_other": "{{count}} workflows in this project","remove": "Remove","removeConfirmBody": "Remove \"{{name}}\" from this project? Its library template, if any, is not affected.","removeConfirmTitle": "Remove workflow",- "removeHint": "Removes it from this project only","removeWithEllipsis": "Remove…","rename": "Rename","renameFailed": "Rename failed",- "renameProjectWorkflowHint": "Changes its name in this project; a linked template keeps its own",- "renameTemplateHint": "Changes the template's name in the library","renameTemplateTitle": "Rename template","renameTitle": "Rename workflow","renamed": "Template renamed",@@ -6817,6 +6919,10 @@"requirementInstalling": "Installing…","requirementMissing": "Not available to install","requires": "Requires",+ "resultCount_one": "{{count, number}} workflow",+ "resultCount_other": "{{count, number}} workflows",+ "resultCountWithTags_one": "{{count, number}} workflow · {{tags}}",+ "resultCountWithTags_other": "{{count, number}} workflows · {{tags}}","retry": "Retry","retryBody": "Saving \"{{name}}\" did not get an answer from the library ({{message}}). Retry the same save, or discard it. If the library did receive it, that template already exists.","retryDiscard": "Discard",@@ -6835,21 +6941,28 @@"saveToLibraryExplanation": "Creates a new library template from this workflow; its current input values become the template's defaults. This workflow then links to the new template and takes its name.","saveToLibraryRelink": "Update library template will then write to the new template instead of \"{{template}}\".","saveToLibraryRelinkUnnamed": "Update library template will then write to the new template instead of the one this workflow is linked to now.",- "saveToLibraryHint": "Creates a new template from this workflow","saveToLibraryTitle": "Save to library","saveToLibraryWithEllipsis": "Save to library…","saved": "Workflow saved","savedCreatedBody": "Saved \"{{name}}\" to the library.","savedUpdatedBody": "Updated \"{{name}}\" in the library.","searchPlaceholder": "Search names, tags, or descriptions",- "shared": "Shared",+ "sortAToZ": "A to Z",+ "sortControl": "Sort: {{sort}}, {{direction}}",+ "sortFirstToLast": "First to last",+ "sortLastRun": "Last run",+ "sortLastToFirst": "Last to first",+ "sortNewestFirst": "Newest first",+ "sortOldestFirst": "Oldest first",+ "sortProjectOrder": "Project order",+ "sortZToA": "Z to A","sourceBundled": "From a bundled template (read-only)","sourceNone": "Not linked to a library template","sourceRevision": "Linked to library template at revision {{revision}}","sourceUnknownRevision": "Linked to a library template (revision unknown)",- "tagsLabel": "Filter by tag",+ "tags": "Tags",+ "tagsAnyHint": "Showing workflows with any checked tag","templateName": "Template name",- "thisProject": "This project","thisProjectHint": "Workflows saved with this project. Edits autosave here; the library changes only when you save to it.","thumbnail": "Thumbnail","thumbnailChoose": "Choose thumbnail",@@ -6860,6 +6973,7 @@"thumbnailUpdateFailed": "Failed to update thumbnail","thumbnailUpdated": "Thumbnail updated","thumbnailUpdating": "Updating thumbnail…",+ "viewOptions": "View options","visibility": "Visibility","visibilityUpdateFailed": "Failed to update workflow visibility","visibilityUnknown": "Visibility unknown",@@ -6875,13 +6989,11 @@"updateConfirmIrreversible": "This cannot be undone: the template's current version is replaced.","updateConfirmNamedBody": "Replace the library template \"{{template}}\" with this workflow's current graph, form, and input values?","updateTemplate": "Update library template",- "updateTemplateHint": "Writes this workflow over its library template","updateTitle": "Update library template","workflowGone": "The workflow is no longer in this project.","workflowMetadataOmitted": "Workflow metadata omitted","workflowMetadataOmittedBody": "Workflow metadata was omitted because the workflow contains multiple workflow_return nodes.","workflowName": "Workflow name",- "yours": "Yours","sortLabel": "Sort by","sortUpdated": "Last updated","sortOpened": "Last opened",@@ -6889,7 +7001,43 @@"sortName": "Name","thumbnailFit": "Thumbnail display","thumbnailFitCover": "Fill",- "thumbnailFitContain": "Fit"+ "thumbnailFitContain": "Fit",+ "activeRanWhen": "Active workflow · ran {{when}}",+ "activeWorkflowLine": "Active workflow",+ "callable": "Callable",+ "factCreated": "Created",+ "factEdited": "Edited",+ "factInProject": "In this project",+ "factLastRun": "Last run",+ "factUpdated": "Updated",+ "inProject": "In project",+ "linkedTemplate": "Linked template",+ "modelsToInstall_one": "{{count, number}} model to install",+ "modelsToInstall_other": "{{count, number}} models to install",+ "nodePacksMissing_one": "{{count, number}} node pack missing",+ "nodePacksMissing_other": "{{count, number}} node packs missing",+ "openedWhen": "Opened {{when}}",+ "projectCopies_one": "{{count, number}} copy",+ "projectCopies_other": "{{count, number}} copies",+ "projectCopiesNone": "None",+ "projectCopyRevision_one": "{{count, number}} copy · revision {{revision, number}}",+ "projectCopyRevision_other": "{{count, number}} copies · revision {{revision, number}}",+ "ranWhen": "Ran {{when}}",+ "readyToRun": "Ready to run",+ "templateNewer": "Template is newer",+ "templateRevision": "Library template is at revision {{revision}}",+ "updateFromTemplate": "Update from template",+ "updateFromTemplateBody": "Replace \"{{name}}\" with the library template's current version? Your edits to this copy are replaced; Undo restores them.",+ "updateFromTemplateConfirm": "Update",+ "updatedFromTemplate": "Updated from template",+ "whenAtRevision": "{{when}} · revision {{revision}}",+ "detailsAndRequirements": "Details and requirements",+ "hideDetails": "Hide details",+ "sortAndViewOptions": "Sort and view options",+ "sortDirectionGroup": "Direction",+ "missingNodePackNames_one": "Missing node pack: {{packs}}",+ "missingNodePackNames_other": "Missing node packs: {{packs}}",+ "sourceNamedRevision": "Linked to {{name}}, revision {{revision}}"},"settingsDialog": {"search": "Search settings…",diff --git a/invokeai/frontend/webv2/public/locales/fr.json b/invokeai/frontend/webv2/public/locales/fr.jsonindex 3e72d3e254..d834a621f3 100644--- a/invokeai/frontend/webv2/public/locales/fr.json+++ b/invokeai/frontend/webv2/public/locales/fr.json@@ -19,7 +19,6 @@"nodeType": "Type : {{type}}","nodePackLabel": "Pack de nœuds : {{name}}","nodeVersion": "Version : {{version}}",- "nodeClassification": "Classification : {{classification}}","nodeCategory": "Catégorie : {{category}}","nodeUpdateAvailable": "Version {{from}} → {{to}} : mise à jour disponible","nodeNewerThanBackend": "La version {{from}} est plus récente que celle prise en charge par cette installation d’Invoke ({{to}}) ; mettez Invoke à jour",diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex 0dcc3c5b02..c1f18c9035 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -1182,14 +1182,57 @@ test('the workflow list orders as the server does: names ignoring case, dates wiassert.deepEqual(await names('ASC'), ['alpha', 'Bravo', 'charlie', 'Delta']);assert.deepEqual(await names('DESC'), ['Delta', 'charlie', 'Bravo', 'alpha']);- const opened = (- await getJson(backend, '/api/v1/workflows/?categories=user&order_by=opened_at&direction=DESC&per_page=100')- ).items.map((item) => item.opened_at);- const firstNever = opened.indexOf(null);-- assert.ok(firstNever > 0);- assert.ok(opened.slice(firstNever).every((value) => value === null));- assert.deepEqual(opened.slice(0, firstNever), opened.slice(0, firstNever).sort().reverse());+ for (const direction of ['ASC', 'DESC']) {+ const opened = (+ await getJson(+ backend,+ `/api/v1/workflows/?categories=user&order_by=opened_at&direction=${direction}&per_page=100`+ )+ ).items.map((item) => item.opened_at);+ const firstNever = opened.indexOf(null);+ const ascending = opened.slice(0, firstNever).sort();++ assert.ok(firstNever > 0);+ assert.ok(opened.slice(firstNever).every((value) => value === null));+ assert.deepEqual(opened.slice(0, firstNever), direction === 'ASC' ? ascending : ascending.reverse());+ }+ });+});++test('workflow runs order the list by last run, and has_been_opened narrows lists and tag counts', async () => {+ await withRepresentativeBackend(async (backend) => {+ // Run against id order, so only the run times can put them in the expected order.+ const ranFirst = 'fixture-workflow-003';+ const ranLast = 'fixture-workflow-002';+ for (const ran of [ranFirst, ranLast]) {+ await getJson(backend, `/api/v1/workflows/i/${ran}/last_run_at`, { method: 'PUT' });+ }+ const ids = async (direction) =>+ (+ await getJson(+ backend,+ `/api/v1/workflows/?categories=user&order_by=last_run_at&direction=${direction}&per_page=100`+ )+ ).items.map((item) => item.workflow_id);++ // Workflows never run come after the runs either way.+ assert.deepEqual((await ids('DESC')).slice(0, 2), [ranLast, ranFirst]);+ assert.deepEqual((await ids('ASC')).slice(0, 2), [ranFirst, ranLast]);++ const listed = async (opened) =>+ (await getJson(backend, `/api/v1/workflows/?categories=user&has_been_opened=${opened}&per_page=100`)).items;+ const openedItems = await listed(true);+ const neverOpened = await listed(false);++ assert.ok(openedItems.length > 0 && neverOpened.length > 0);+ assert.ok(openedItems.every((item) => item.opened_at !== null));+ assert.ok(neverOpened.every((item) => !item.opened_at));++ const counts = await getJson(+ backend,+ '/api/v1/workflows/counts_by_tag?categories=user&tags=fixture&has_been_opened=true'+ );+ assert.deepEqual(counts, { fixture: openedItems.length });});});diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex cef60939c2..66f4e88064 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -3418,6 +3418,9 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt};};const workflowListItem = ({ workflow: _workflow, ...item }) => workflowRecord(item);+ const hasBeenOpened = url.searchParams.get('has_been_opened');+ const matchesOpened = (workflow) =>+ hasBeenOpened === null || (hasBeenOpened === 'true') === Boolean(workflow.opened_at);const workflowTags = (workflow) =>String(workflow.tags ?? '').split(',')@@ -3457,6 +3460,7 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'emptcounts[tag] = [...state.workflows.values()].filter((workflow) =>(categories.length === 0 || categories.includes(workflow.category)) &&+ matchesOpened(workflow) &&workflowTags(workflow).includes(tag)).length;}@@ -3495,7 +3499,7 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'emptreturn json(200, workflowRecord(workflow));}- const workflowMatch = /^\/api\/v1\/workflows\/i\/([^/]+)(\/opened_at|\/thumbnail)?$/.exec(path);+ const workflowMatch = /^\/api\/v1\/workflows\/i\/([^/]+)(\/opened_at|\/last_run_at|\/thumbnail)?$/.exec(path);if (workflowMatch) {const workflowId = decodeURIComponent(workflowMatch[1]);const suffix = workflowMatch[2] ?? '';@@ -3505,8 +3509,8 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'emptreturn json(404, { detail: 'Workflow not found' });}- if (suffix === '/opened_at' && method === 'PUT') {- workflow.opened_at = timestamp(state);+ if ((suffix === '/opened_at' || suffix === '/last_run_at') && method === 'PUT') {+ workflow[suffix.slice(1)] = timestamp(state);return json(200, null);}@@ -3630,6 +3634,7 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'emptdescription: content.description ?? '',is_public: !isMultiuserCaller(faults),name: content.name ?? '',+ last_run_at: null,opened_at: null,revision: 1,tags: content.tags ?? '',@@ -3660,24 +3665,27 @@ export const startMockBackend = async (port, { clock = Date.now, profile = 'empt}const orderBy = url.searchParams.get('order_by') ?? 'updated_at';const sign = url.searchParams.get('direction') === 'ASC' ? 1 : -1;- // As the server orders: names ignoring ASCII case (SQLite's NOCASE), NULLs lowest, the id breaking ties.+ // As the server orders: names ignoring ASCII case (SQLite's NOCASE), NULLs last in both directions, the id+ // breaking ties.const sortKey = (workflow) =>orderBy === 'name'? workflow.name.replace(/[A-Z]/g, (letter) => letter.toLowerCase()): (workflow[orderBy] ?? null);- const compare = (left, right) =>- left === right ? 0 : left === null ? -1 : right === null ? 1 : left < right ? -1 : 1;+ const compare = (left, right) => (left === right ? 0 : left < right ? -1 : 1);+ const compareKeys = (left, right) =>+ left === right ? 0 : left === null ? 1 : right === null ? -1 : sign * compare(left, right);const items = [...state.workflows.values()].filter((workflow) =>(categories.length === 0 || categories.includes(workflow.category)) &&(!query || `${workflow.name} ${workflow.description}`.toLocaleLowerCase().includes(query)) &&(tags.length === 0 || tags.some((tag) => workflowTags(workflow).includes(tag))) &&- (isPublic === null || String(workflow.is_public) === isPublic)+ (isPublic === null || String(workflow.is_public) === isPublic) &&+ matchesOpened(workflow)).sort((left, right) =>- sign * (compare(sortKey(left), sortKey(right)) || compare(left.workflow_id, right.workflow_id))+ compareKeys(sortKey(left), sortKey(right)) || sign * compare(left.workflow_id, right.workflow_id));const pages = Math.max(1, Math.ceil(items.length / perPage));const pageItems = items.slice(page * perPage, (page + 1) * perPage).map(workflowListItem);diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjsindex 96940da55c..f37103e095 100644--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs@@ -245,13 +245,24 @@ const waitForSavedWorkflows = async (projectId, predicate, label) => {throw new Error(`The project record never reached the expected state: ${label}.`);};+/** The editor header's workflow name: a menu that switches workflows and opens the library. */+const WORKFLOW_SWITCHER_PREFIX = 'Switch workflow. Current workflow: ';+const workflowSwitcher = (page) => page.getByRole('button', { name: /^Switch workflow\. Current workflow: / });+const currentWorkflowNameOf = async (page) =>+ (await workflowSwitcher(page).getAttribute('aria-label')).replace(WORKFLOW_SWITCHER_PREFIX, '');+/** Opens the Workflows library on In this project from the workflow name's menu. */+const openWorkflowLibraryFromName = async (page) => {+ await workflowSwitcher(page).click();+ await page.getByRole('menuitem', { exact: true, name: 'Workflow library…' }).click();+ await page.getByRole('dialog', { exact: true, name: 'Workflows' }).locator('[data-library-tab="project"]').waitFor();+};+/** Rename the active workflow through the Workflows dialog. */const renameActiveWorkflow = async (page, name) => {const dialog = page.getByRole('dialog', { exact: true, name: 'Workflows' });const renameDialog = page.getByRole('dialog', { exact: true, name: 'Rename workflow' });- await page.getByRole('button', { name: /^Open this project's workflows\. Current workflow: / }).click();- await dialog.locator('[data-library-tab="project"]').waitFor();+ await openWorkflowLibraryFromName(page);await dialog.locator('[data-project-workflow-detail]').getByRole('button', { exact: true, name: 'More actions' })@@ -579,7 +590,7 @@ const runDuplication = async ({ browser, contexts, errors, imported, importedBoa/*** The primary workflow journey: open a template into the project, edit it, switch away and back, save it to the* library under a new name, restart, and find both workflows intact. Project edits and runs issue no library writes;- * the This-project view fetches no templates.+ * the In this project view reads no library pages or records (the rail's one-row place totals and tag counts aside).*/const runWorkflowCollection = async ({ browser, contexts, errors, imported }) => {const projectId = imported.project_id;@@ -614,34 +625,47 @@ const runWorkflowCollection = async ({ browser, contexts, errors, imported }) =>const page = await context.newPage();await observeBrowserErrors(page, 'workflow-collection', errors);+ // The browser's own library reads, with their queries: the mock's request log keeps paths only.+ const libraryReads = [];+ page.on('request', (request) => {+ const url = new URL(request.url());++ if (request.method() === 'GET' && url.pathname.startsWith('/api/v1/workflows')) {+ libraryReads.push(url);+ }+ });await page.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();await page.goto(`${origin}/#/app?project=${encodeURIComponent(projectId)}`, { waitUntil: 'domcontentloaded' });await page.getByRole('main', { exact: true, name: imported.name }).waitFor();await selectLayoutPreset(page, 'Workflow', 'Workflow');- const workflowName = () => page.getByRole('button', { name: /^Open this project's workflows\. Current workflow: / });const dialog = page.getByRole('dialog', { exact: true, name: 'Workflows' });const cards = dialog.locator('[data-workflow-card]');- const openProjectWorkflows = async () => {- await workflowName().click();- await dialog.waitFor();- await dialog.locator('[data-library-tab="project"]').waitFor();- };- const currentWorkflowName = async () =>- (await workflowName().getAttribute('aria-label')).replace("Open this project's workflows. Current workflow: ", '');+ const openProjectWorkflows = () => openWorkflowLibraryFromName(page);+ const currentWorkflowName = () => currentWorkflowNameOf(page);- // The migrated project owns exactly its old graph, marked active; opening the local view fetched nothing.+ // The migrated project owns exactly its old graph, marked active. Opening on In this project reads no library page+ // (a listing of more than one row) and no workflow record; the rail's one-row place totals and tag counts may run.await openProjectWorkflows();assert.equal(await cards.count(), 1);await cards.first().locator('[data-active-workflow]').waitFor();- assert.equal(- (await workflowRequests()).slice(requestsBefore).some((entry) => entry.method === 'GET'),- false+ const libraryPageOrRecordReads = libraryReads.filter(+ (url) =>+ /^\/api\/v1\/workflows\/i\/[^/]+$/.test(url.pathname) ||+ (url.pathname === '/api/v1/workflows/' && Number(url.searchParams.get('per_page') ?? 'Infinity') > 1)+ );+ assert.deepEqual(+ libraryPageOrRecordReads.map((url) => `${url.pathname}${url.search}`),+ [],+ 'opening In this project must read no library pages or records');- // A template opened from the library tabs becomes an independent copy in this project.- await dialog.getByText('Yours', { exact: true }).click();+ // A template opened from My library becomes an independent copy in this project.+ await dialog+ .getByRole('navigation', { name: 'Places' })+ .getByRole('button', { name: /^My library/ })+ .click();await dialog.locator('[data-library-tab="user"]').waitFor();await dialog.locator(`[data-workflow-card="${template.workflow_id}"]`).click();await dialog@@ -669,11 +693,10 @@ const runWorkflowCollection = async ({ browser, contexts, errors, imported }) =>await dialog.waitFor({ state: 'hidden' });assert.equal(await currentWorkflowName(), 'Journey Template edited');- // Switching to the other workflow and back keeps both documents.- await openProjectWorkflows();- await cards.filter({ hasText: 'Empty Workflow' }).dblclick();- await dialog.waitFor({ state: 'hidden' });- assert.equal(await currentWorkflowName(), 'Empty Workflow');+ // Switching to the other workflow, from the name's menu, and back from the library keeps both documents.+ await workflowSwitcher(page).click();+ await page.getByRole('menuitemradio', { exact: true, name: 'Empty Workflow' }).click();+ await page.getByRole('button', { exact: true, name: `${WORKFLOW_SWITCHER_PREFIX}Empty Workflow` }).waitFor();await openProjectWorkflows();await cards.filter({ hasText: 'Journey Template edited' }).dblclick();await dialog.waitFor({ state: 'hidden' });@@ -792,11 +815,9 @@ const runUnloadRecovery = async ({ browser, contexts, errors, imported }) => {const page = await context.newPage();await observeBrowserErrors(page, 'unload recovery', errors);const main = page.getByRole('main', { exact: true, name: imported.name });- const workflowName = page.getByRole('button', { name: /^Open this project's workflows\. Current workflow: / });const dialog = page.getByRole('dialog', { exact: true, name: 'Workflows' });const renameDialog = page.getByRole('dialog', { exact: true, name: 'Rename workflow' });- const currentWorkflowName = async () =>- (await workflowName.getAttribute('aria-label')).replace("Open this project's workflows. Current workflow: ", '');+ const currentWorkflowName = () => currentWorkflowNameOf(page);const openEditor = async () => {await page.goto(`${origin}/#/app?project=${encodeURIComponent(imported.project_id)}`, {waitUntil: 'domcontentloaded',diff --git a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsxindex c7a5fc1922..003f413189 100644--- a/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/QueueRuntimeAdapter.tsx@@ -19,7 +19,7 @@ import {} from '@workbench/queue-integration/queueRecallCache';import { createAccountOwnedQueueRunJournal, type QueueRunJournal } from '@workbench/queue-integration/queueRunJournal';import { createQueueRunLockPort } from '@workbench/queue-integration/queueRunLocks';-import { withQueueRecallCache } from '@workbench/queue-integration/queueRunPersistence';+import { withLibraryWorkflowRunTouch, withQueueRecallCache } from '@workbench/queue-integration/queueRunPersistence';import { useWorkbenchCommands, useWorkbenchQueries, useWorkbenchSubscription } from '@workbench/WorkbenchContext';/** App-owned production composition of Queue, Workbench, Gallery, Workflow, Nodes, and Models adapters. */@@ -33,6 +33,7 @@ export const QueueRuntimeAdapter = () => {const owner = captureAccountScope();// Changing users remounts the workbench route, so the session read here stays the runtime's viewer.const session = getAuthSession();+ const viewerUserId = session.multiuserEnabled ? (session.user?.user_id ?? null) : null;let isDisposed = false;let journal: QueueRunJournal | undefined;let recallCache: QueueRecallCache | undefined;@@ -124,6 +125,12 @@ export const QueueRuntimeAdapter = () => {recordError: notifications.reportError,refreshBackendData: () => void invalidateGallery(queryClient),refreshBoardDestinations: () => void invalidateGalleryBoardDestinations(queryClient),+ routeResults: withLibraryWorkflowRunTouch(queue.routeResults, {+ getProject: (projectId) => queries.getSnapshot().projects.find((project) => project.id === projectId),+ isDisposed: () => isDisposed,+ owner,+ viewerUserId,+ }),},listStagedResults: () => getQueueStagedResults(queries.getSnapshot().projects),getSnapshot: () => {@@ -155,7 +162,7 @@ export const QueueRuntimeAdapter = () => {locks: createQueueRunLockPort(owner.storageSuffix),modelLoads: modelLoadActivitySink,nodeExecution: nodeExecutionStore,- viewerUserId: session.multiuserEnabled ? (session.user?.user_id ?? null) : null,+ viewerUserId,});runtime.start();};diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxindex 8f8024d947..fba7099ed4 100644--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -4,32 +4,16 @@ import type { WorkbenchPreferences } from '@workbench/settings/contracts';import type { WorkbenchSnapshot } from '@workbench/workbenchStore';import type { ReactNode } from 'react';-import { flushGenerateDrafts } from '@features/generation/react';import { getAuthSession, getCapabilities, subscribeAuthSession } from '@features/identity';-import { ensureModelsLoaded, openModelManager, useModelsSelector } from '@features/models';+import { ensureModelsLoaded, openModelManager } from '@features/models';import { nodeExecutionStore } from '@features/nodes';import { hasPendingWorkflowQueueItem } from '@features/queue';import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';-import {- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';import { createProjectedExternalStore } from '@platform/state/projectedExternalStore';import { shallowEqual } from '@platform/state/selectors';-import { describeControlLayerIssue } from '@workbench/controlLayerChecks';import { useWorkbenchFocus } from '@workbench/focusRegions';-import { resolveAndSubmitGraphPreviewInvocation } from '@workbench/graphPreviewInvocation';import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';-import {- createInvocationRouteInputSelector,- formatRoute,- isInvocationRouteValid,- localizeInvocationValidationReason,- resolveInvocationRouteInput,-} from '@workbench/invocation';-import { useIsInvocationPreparing } from '@workbench/invocationPreparation';import { markWorkbenchPerf, measureWorkbenchPerf, timeWorkbenchPerf } from '@workbench/performanceMarks';import { getProjectSyncSnapshot, subscribeProjectSync } from '@workbench/projects/syncStore';import { getActiveProjectWorkflow, getProjectWorkflowHistory } from '@workbench/projectWorkflows';@@ -41,26 +25,21 @@ import {import { useNotify } from '@workbench/useNotify';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { getProjectWidgetValues, getResolvedProjectWidgetValues } from '@workbench/widgetState';-import {- useActiveProjectSelector,- useWorkbenchCommands,- useWorkbenchInternalStore,- useWorkbenchQueries,-} from '@workbench/WorkbenchContext';+import { useWorkbenchCommands, useWorkbenchInternalStore, useWorkbenchQueries } from '@workbench/WorkbenchContext';import { useMemo } from 'react';-import { useTranslation } from 'react-i18next';import { WorkflowCommandShortcut } from './WorkflowCommandShortcut';-const selectInvocationRouteInput = createInvocationRouteInputSelector();-const selectWorkflowPreferences = (preferences: WorkbenchPreferences) => ({reduceMotion: preferences.reduceMotion,themeId: preferences.themeId,workflowEdgeStyle: preferences.workflowEdgeStyle,workflowEdgesBehindNodes: preferences.workflowEdgesBehindNodes,workflowGroupNodesByCategory: preferences.workflowGroupNodesByCategory,+ workflowLibraryCardSize: preferences.workflowLibraryCardSize,+ workflowLibraryLayout: preferences.workflowLibraryLayout,workflowLibrarySort: preferences.workflowLibrarySort,+ workflowLibrarySortDirection: preferences.workflowLibrarySortDirection,workflowLibraryThumbnailFit: preferences.workflowLibraryThumbnailFit,workflowShowMinimap: preferences.workflowShowMinimap,workflowSnapToGrid: preferences.workflowSnapToGrid,@@ -125,16 +104,8 @@ const createPairedSource = <A, B>(};const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNode }) => {- const routeInput = useActiveProjectSelector(selectInvocationRouteInput);- const models = useModelsSelector((snapshot) => snapshot.models);- const modelsStatus = useModelsSelector((snapshot) => snapshot.status);- const availabilityModels = modelsStatus === 'loaded' ? models : undefined;const commands = useWorkbenchCommands();- const queries = useWorkbenchQueries();const openWidget = useOpenWorkbenchWidget();- const { t } = useTranslation();- // The preview submits under the topbar's lease, so it is unavailable while that is held.- const isPreparing = useIsInvocationPreparing(routeInput.projectId);const adapter = useMemo<WorkflowGraphPreviewPort>(() => ({@@ -143,57 +114,6 @@ const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNodeopenWidget(sourceId);}},- getRoute: (sourceId) => {- if (!sourceId) {- return null;- }-- const route = resolveInvocationRouteInput(- routeInput,- 'dialog',- { ...routeInput.invocation, sourceId, sourceLocked: true },- availabilityModels- );-- const message = route.validationMessage;-- return {- canInvoke: isInvocationRouteValid(route) && !isPreparing,- label: formatRoute(route),- validationMessage: isPreparing- ? t('topbar.invoke.preparing')- : message === undefined- ? undefined- : localizeInvocationValidationReason(message, t),- };- },- invoke: async (sourceId) => {- const owner = captureAccountScope();- flushGenerateDrafts();- try {- const { prepareCanvasInvocation } = await import('@workbench/widgets/canvas/invoke/prepareCanvasInvocation');-- assertAccountScopeCurrent(owner);- const snapshot = queries.getSnapshot();- return resolveAndSubmitGraphPreviewInvocation({- commands,- formatControlLayerError: (rejection) => describeControlLayerIssue(t, rejection),- formatUpscaleMetadataFailure: (name) => t('widgets.gallery.itemActions.upscale.metadataFailed', { name }),- models: availabilityModels,- owner,- prepareCanvasInvocation,- project: snapshot.activeProject,- scopedDefaults: snapshot.scopedDefaults,- sourceId,- });- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return false;- }-- throw error;- }- },openDocumentInNewProject: (document, label, source) => {// Create first: the new project's blank placeholder is what the document takes over.commands.projects.create();@@ -204,7 +124,7 @@ const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNodeopenWidget('workflow');},}),- [availabilityModels, commands, isPreparing, openWidget, queries, routeInput, t]+ [commands, openWidget]);return <WorkflowGraphPreviewProvider adapter={adapter}>{children}</WorkflowGraphPreviewProvider>;diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.jsonindex 738d4ee234..46c6dc0755 100644--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json@@ -105,7 +105,6 @@"focusRegions.tsx": "workbench","generationSettingsOrchestration.ts": "workbench","graphContracts.ts": "workbench",- "graphPreviewInvocation.ts": "workbench","graphSurfaces.ts": "workbench","graphWidgets.ts": "workbench","iconResolver.tsx": "workbench",diff --git a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.tsindex 1879f10c52..8ff4e36b57 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts+++ b/invokeai/frontend/webv2/src/features/gallery/ui/galleryDnd.ts@@ -30,7 +30,7 @@ export interface GalleryBoardDropResolution {items: GalleryItemRef[];}-export type GalleryItemDragSource = 'gallery-grid' | 'preview-filmstrip' | 'preview-frame';+export type GalleryItemDragSource = 'gallery-grid' | 'preview-filmstrip' | 'preview-frame' | 'workflow-current-image';export type GalleryItemDragId = `${GalleryItemDragSource}${string}:${GalleryItemKey}`;/**diff --git a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsxindex 40ba8af673..3dd7023980 100644--- a/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/generation/ui/promptFields/ResizableTextareaIntegration.browser.test.tsx@@ -1,4 +1,4 @@-import { ChakraProvider } from '@chakra-ui/react';+import { Box, ChakraProvider } from '@chakra-ui/react';import { adjustFocusedPromptAttention } from '@features/generation/ui/promptFields/promptAttentionHotkeys';import { PromptTextarea } from '@features/generation/ui/promptFields/PromptTextarea';import { ResizableTextarea } from '@platform/ui/ResizableTextarea';@@ -12,34 +12,50 @@ 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 renderTextarea = async (maxHeightPx?: number) => {+const WELL_HOST_CSS = { '--wb-control-well': '{colors.bg}', '& textarea': { bg: 'var(--wb-control-well)' } };++const renderTextarea = async (maxHeightPx?: number, well?: { zoom: number }) => {host = document.createElement('div');document.body.append(host);root = createRoot(host);const onResizeEnd = vi.fn();+ const textarea = (+ <ResizableTextarea+ aria-label="Prompt"+ defaultHeightPx={100}+ maxHeightPx={maxHeightPx}+ minHeightPx={60}+ resizeHandleAriaLabel="Resize prompt"+ onResizeEnd={onResizeEnd}+ />+ );await act(() => {root?.render(<ChakraProvider value={system}>- <ResizableTextarea- aria-label="Prompt"- defaultHeightPx={100}- maxHeightPx={maxHeightPx}- minHeightPx={60}- resizeHandleAriaLabel="Resize prompt"- onResizeEnd={onResizeEnd}- />+ {well ? (+ // A scaled well host, as the node editor is: it paints its controls on the well, and its zoom puts the inner+ // bottom edge inside a device pixel.+ <Box css={WELL_HOST_CSS} data-control-well="" transform={`scale(${well.zoom})`}>+ {textarea}+ </Box>+ ) : (+ textarea+ )}</ChakraProvider>);});return {+ fade: host.querySelector<HTMLElement>('[data-resizable-textarea-fade]')!,handle: host.querySelector<HTMLElement>('[role="separator"]')!,onResizeEnd,textarea: host.querySelector<HTMLTextAreaElement>('textarea')!,};};+const lastColor = (gradient: string) => [...gradient.matchAll(/(?:rgba?|oklch)\([^)]*\)/g)].at(-1)?.[0];+afterEach(async () => {await act(() => root?.unmount());host?.remove();@@ -54,27 +70,20 @@ describe('ResizableTextarea', () => {await act(async () => {await userEvent.hover(textarea);await userEvent.tab();- await new Promise((resolve) => {- globalThis.setTimeout(resolve, 200);- });});expect(document.activeElement).toBe(textarea);- const hoveredFocusBorderColor = getComputedStyle(textarea).borderTopColor;const accentProbe = document.createElement('div');accentProbe.style.border = '1px solid var(--chakra-colors-accent-solid)';document.body.append(accentProbe);const accentBorderColor = getComputedStyle(accentProbe).borderTopColor;accentProbe.remove();expect(getComputedStyle(textarea).outlineStyle).toBe('none');- expect(hoveredFocusBorderColor).toBe(accentBorderColor);+ await expect.poll(() => getComputedStyle(textarea).borderTopColor).toBe(accentBorderColor);await act(async () => {await userEvent.unhover(textarea);- await new Promise((resolve) => {- globalThis.setTimeout(resolve, 200);- });});- expect(getComputedStyle(textarea).borderTopColor).toBe(accentBorderColor);+ await expect.poll(() => getComputedStyle(textarea).borderTopColor).toBe(accentBorderColor);});it('allows unbounded pointer and keyboard growth while keeping Home at the minimum', async () => {@@ -118,6 +127,84 @@ describe('ResizableTextarea', () => {await expect.poll(() => host!.querySelector<HTMLElement>('[data-part="thumb"]')!.clientHeight).toBeGreaterThan(0);});+ it('fades to whatever lies behind it outside a well host', async () => {+ const { fade, textarea } = await renderTextarea();++ expect(getComputedStyle(textarea.parentElement!.parentElement!).maskImage).not.toBe('none');+ expect(getComputedStyle(fade).display).toBe('none');+ });++ it('covers a scaled well host’s bottom edge with an opaque well fade and repaints the border over it', async () => {+ const zoom = 1.37;+ const { fade, textarea } = await renderTextarea(undefined, { zoom });+ const style = getComputedStyle(textarea);+ const lineHeight = Number.parseFloat(style.lineHeight);+ await act(() => {+ textarea.value = Array.from({ length: 20 }, (_, index) => `line ${index}`).join('\n');+ textarea.dispatchEvent(new Event('input', { bubbles: true }));+ });+ // Half a line past a line boundary, so a line straddles the inner bottom edge.+ textarea.scrollTop =+ Math.ceil(textarea.clientHeight / lineHeight) * lineHeight - textarea.clientHeight + lineHeight / 2;+ expect(textarea.scrollTop).toBeGreaterThan(0);++ const box = textarea.getBoundingClientRect();+ const fill = fade.getBoundingClientRect();+ const border = getComputedStyle(fade, '::after');+ const innerBottom = box.bottom - Number.parseFloat(style.borderBottomWidth) * zoom;+ expect(getComputedStyle(textarea.parentElement!.parentElement!).maskImage).toBe('none');+ // The fill is the text area's own bottom, so it covers the inner bottom edge and the row the border shares with it;+ // the repainted border's inner edge is the text area's.+ expect(Math.abs(fill.bottom - box.bottom)).toBeLessThanOrEqual(0.5);+ expect(Math.abs(fill.left - box.left)).toBeLessThanOrEqual(0.5);+ expect(Math.abs(fill.right - box.right)).toBeLessThanOrEqual(0.5);+ expect(+ Math.abs(fill.bottom - Number.parseFloat(border.borderBottomWidth) * zoom - innerBottom)+ ).toBeLessThanOrEqual(0.5);+ expect(lastColor(getComputedStyle(fade).backgroundImage)).toBe(style.backgroundColor);+ expect(style.backgroundColor).not.toMatch(/rgba|\//);+ expect(border.borderBottomLeftRadius).toBe(style.borderBottomLeftRadius);+ expect(border.borderBottomColor).toBe(style.borderBottomColor);+ });++ it('repaints the well fade’s border in the text area’s hover, focus and error colours', async () => {+ const { fade, textarea } = await renderTextarea(undefined, { zoom: 1 });+ const settled = () =>+ act(async () => {+ // Flush style so the transitions exist before waiting for their actual completion.+ textarea.getBoundingClientRect();+ await Promise.all(+ textarea.parentElement!.parentElement!.getAnimations({ subtree: true }).map((animation) => animation.finished)+ );+ });+ const colors = () => [+ getComputedStyle(fade, '::after').borderBottomColor,+ getComputedStyle(textarea).borderBottomColor,+ ];+ const rest = colors()[1];++ await act(() => userEvent.hover(textarea));+ await settled();+ const [hoverRing, hoverBorder] = colors();+ expect(hoverBorder).not.toBe(rest);+ expect(hoverRing).toBe(hoverBorder);++ await act(async () => {+ await userEvent.unhover(textarea);+ await userEvent.tab();+ });+ await settled();+ const [focusRing, focusBorder] = colors();+ expect(focusBorder).not.toBe(rest);+ expect(focusRing).toBe(focusBorder);++ await act(() => textarea.setAttribute('aria-invalid', 'true'));+ await settled();+ const [errorRing, errorBorder] = colors();+ expect(errorBorder).not.toBe(focusBorder);+ expect(errorRing).toBe(errorBorder);+ });+it('retains bounded End behavior when a maximum is supplied', async () => {const { handle, textarea } = await renderTextarea(140);diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.browser.test.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.browser.test.tsxnew file mode 100644index 0000000000..5853a939bb--- /dev/null+++ b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.browser.test.tsx@@ -0,0 +1,143 @@+import '@fontsource/inter/index.css';+import type { FieldInputTemplate, InvocationTemplate } from '@features/workflow/contracts';++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 { NodePreviewCard } from './NodePreviewCard';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const input: FieldInputTemplate = {+ default: undefined,+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ fieldKind: 'input',+ input: 'connection',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name: 'image',+ options: null,+ required: true,+ title: 'Image',+ type: { batch: false, cardinality: 'SINGLE', name: 'ImageField' },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelFormat: null,+ uiModelType: null,+ uiOrder: null,+};+const template: InvocationTemplate = {+ category: 'image',+ classification: 'stable',+ description: '',+ inputs: { image: input },+ nodePack: 'invokeai',+ outputType: 'image_output',+ outputs: {+ width: {+ description: '',+ name: 'width',+ title: 'Width',+ type: { batch: false, cardinality: 'SINGLE', name: 'IntegerField' },+ },+ },+ tags: [],+ title: 'Resize Image',+ type: 'img_resize',+ useCache: true,+ version: '1.0.0',+};++// A title and an output title split next to a space: the head keeps its trailing space.+const splitTemplate: InvocationTemplate = {+ ...template,+ outputs: { width: { ...template.outputs.width!, title: 'Image to Latents' } },+ title: 'Latents to Image',+};++/** The middle of a label's lowercase letters: a 1ex inline box standing on its baseline spans its x-height. */+const letterBodyCentre = (text: HTMLElement) => {+ const probe = document.createElement('span');+ probe.style.cssText = 'display: inline-block; height: 1ex; vertical-align: baseline; width: 0';+ text.append(probe);+ const box = probe.getBoundingClientRect();+ probe.remove();+ return box.top + box.height / 2;+};++describe('NodePreviewCard', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.width = '320px';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('keeps the space where its title or an output title is split, as an untrimmed label draws it', async () => {+ await document.fonts.load('600 12px Inter');+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <NodePreviewCard template={splitTemplate} />+ </ChakraProvider>+ )+ );++ for (const text of ['Latents to Image', 'Image to Latents']) {+ const label = host.querySelector<HTMLElement>(`[data-full-text="${text}"]`)!;+ const [head, tail] = [...label.children] as HTMLElement[];+ expect(getComputedStyle(head!).whiteSpace).toBe('pre');+ // The same label untrimmed, beside it in the same font: its spans hold their own white-space.+ const reference = label.cloneNode(true) as HTMLElement;+ reference.style.cssText = 'position: absolute; visibility: hidden; overflow: visible';+ for (const span of reference.children as HTMLCollectionOf<HTMLElement>) {+ span.style.cssText = 'text-box: normal; white-space: pre; flex-shrink: 0';+ }+ label.parentElement!.append(reference);+ const width = [...reference.children].reduce((sum, span) => sum + span.getBoundingClientRect().width, 0);+ reference.remove();+ expect(head!.getBoundingClientRect().width + tail!.getBoundingClientRect().width).toBeCloseTo(width, 0);+ }+ });++ it('centres each port dot on its label’s letters, as a node’s field rows do', async () => {+ await document.fonts.load('400 10px Inter');+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <NodePreviewCard template={template} />+ </ChakraProvider>+ )+ );++ for (const [side, title] of [+ ['left', 'Image'],+ ['right', 'Width'],+ ] as const) {+ const dot = host.querySelector<HTMLElement>(`[data-node-port-dot="${side}"]`)!;+ const label = [...dot.parentElement!.querySelectorAll<HTMLElement>('p, span')].find((element) =>+ [...element.childNodes].some((child) => child.nodeType === Node.TEXT_NODE && child.textContent === title)+ )!;+ const box = dot.getBoundingClientRect();+ expect(Math.abs(box.top + box.height / 2 - letterBodyCentre(label))).toBeLessThanOrEqual(0.5);+ }+ });+});diff --git a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsx b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsxindex c1ed3ce8e0..c89cb330a8 100644--- a/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsx+++ b/invokeai/frontend/webv2/src/features/nodes/ui/detail/NodePreviewCard.tsx@@ -12,8 +12,10 @@ import {getWorkflowNodeHeaderProps,getWorkflowNodeShellProps,WORKFLOW_NODE_DENSITY,+ WORKFLOW_NODE_LABEL_TEXT_CSS,+ WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS,WorkflowNodeHandleDot,- WorkflowNodeInfoIcon,+ WorkflowNodeInfoButton,} from '@features/workflow/preview';import { getFieldTypeLabel } from '@features/workflow/utility';import { Tooltip } from '@platform/ui';@@ -56,12 +58,13 @@ const OutputRow = ({ template }: { template: FieldOutputTemplate }) => (content={<FieldTooltip description={template.description} direction="output" template={template} />}positioning={{ placement: 'top-end' }}>- <Flex justify="flex-end">+ <Flex align="center" h={WORKFLOW_NODE_DENSITY.labelLine} justify="flex-end"><MiddleTruncatecolor="fg.muted"+ {...WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS}fontSize="xs"justifyContent="flex-end"- lineHeight="shorter"+ lineHeight={WORKFLOW_NODE_DENSITY.labelLine}maxW="full"text={template.title}/>@@ -77,14 +80,22 @@ const InputRow = ({ template }: { template: FieldInputTemplate }) => (content={<FieldTooltip description={template.description} direction="input" template={template} />}positioning={{ placement: 'top-start' }}>- <Text color="fg" fontSize="xs" lineHeight="shorter" minW="0" truncate>- {template.title}- {template.required ? (- <Text as="span" color="fg.error">- {' *'}- </Text>- ) : null}- </Text>+ <Flex align="center" h={WORKFLOW_NODE_DENSITY.labelLine}>+ <Text+ color="fg"+ css={WORKFLOW_NODE_LABEL_TEXT_CSS}+ fontSize="xs"+ lineHeight={WORKFLOW_NODE_DENSITY.labelLine}+ minW="0"+ >+ {template.title}+ {template.required ? (+ <Text as="span" color="fg.error">+ {' *'}+ </Text>+ ) : null}+ </Text>+ </Flex></Tooltip>{template.input !== 'direct' ? <WorkflowNodeHandleDot side="left" type={template.type} /> : null}</Box>@@ -112,10 +123,10 @@ export const NodePreviewCard = ({ template }: { template: InvocationTemplate })return (<Box w="full" {...getWorkflowNodeShellProps({ selected: false })}>- <Flex {...getWorkflowNodeHeaderProps()}>- <MiddleTruncate fontWeight="700" minW="0" text={template.title} />+ <Flex {...getWorkflowNodeHeaderProps({ endsWithButton: true })}>+ <MiddleTruncate {...WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS} fontWeight="600" minW="0" text={template.title} /><Box flex="1" />- <WorkflowNodeInfoIcon+ <WorkflowNodeInfoButtoncontent={<NodeInfoTooltip template={template} />}label={t('nodes.nodeDetailsAria', { title: template.title })}/>diff --git a/invokeai/frontend/webv2/src/features/queue/core/types.ts b/invokeai/frontend/webv2/src/features/queue/core/types.tsindex ea87c31813..3c32bb8c7d 100644--- a/invokeai/frontend/webv2/src/features/queue/core/types.ts+++ b/invokeai/frontend/webv2/src/features/queue/core/types.ts@@ -85,6 +85,8 @@ export type QueueCompiledSubmission =* on records queued before projects owned several workflows; those results keep their destination only.*/projectWorkflowId?: string;+ /** Library binding captured at enqueue, independent of later relinking or removing the project copy. */+ libraryWorkflowSource?: { libraryWorkflowId: string; ownerUserId?: string };}| {batchCount: number;diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts b/invokeai/frontend/webv2/src/features/queue/runtime.test.tsindex 3ecd62372f..eefd69402e 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.test.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.test.ts@@ -365,6 +365,7 @@ describe('queue runtime', () => {graph: { edges: [], id: 'backend-graph', nodes: {} },kind: 'workflow',libraryWorkflowId: 'lib-1',+ libraryWorkflowSource: { libraryWorkflowId: 'lib-2', ownerUserId: 'user-a' },projectWorkflowId: 'wf-1',} as never;queueItem.snapshot.sourceId = 'workflow';@@ -375,6 +376,7 @@ describe('queue runtime', () => {expect(submission).toHaveProperty('request');expect((submission as { request: object }).request).not.toHaveProperty('projectWorkflowId');expect((submission as { request: object }).request).not.toHaveProperty('libraryWorkflowId');+ expect((submission as { request: object }).request).not.toHaveProperty('libraryWorkflowSource');});it('replays persisted batch groups and rejects ones the graph or the backend would refuse', () => {diff --git a/invokeai/frontend/webv2/src/features/queue/runtime.ts b/invokeai/frontend/webv2/src/features/queue/runtime.tsindex cdf9b32dad..9479d1e0d1 100644--- a/invokeai/frontend/webv2/src/features/queue/runtime.ts+++ b/invokeai/frontend/webv2/src/features/queue/runtime.ts@@ -359,6 +359,7 @@ export const createQueueItemBackendSubmission = (const {kind: _,projectWorkflowId: _projectWorkflowId,+ libraryWorkflowSource: _libraryWorkflowSource,...compiled} = submission as typeof submission & {libraryWorkflowId?: string;diff --git a/invokeai/frontend/webv2/src/features/workflow/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/contracts.tsindex fc4a13ee1f..d183fe64df 100644--- a/invokeai/frontend/webv2/src/features/workflow/contracts.ts+++ b/invokeai/frontend/webv2/src/features/workflow/contracts.ts@@ -3,6 +3,7 @@ export type * from './core/types';export type { WorkflowIssueReason, WorkflowReadinessIssue, WorkflowReadinessReason } from './core/readinessIssues';export { isConnectorNode, isCurrentImageNode, isInvocationNode, isNotesNode } from './core/types';export type {+ GraphPreviewInvoke,GraphPreviewNotice,GraphPreviewProvenance,GraphPreviewSourceState,diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.tsindex af180e5b75..e853c80389 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.test.ts@@ -7,6 +7,7 @@ import {getEffectiveWorkflowFieldDescription,getFieldRecordId,getWorkflowFieldInvalidReason,+ getWorkflowFieldIssue,isDirectInputField,isLoraFieldCollectionEntry,isLoraFieldWeightValid,@@ -94,6 +95,22 @@ describe('workflow field validation', () => {).toBe('Required connection.');});+ it('names what a blocking field lacks, so callers can say what to do about it', () => {+ const integer = input({ minimum: 1, type: single('IntegerField') });++ expect(getWorkflowFieldIssue({ isConnected: false, template: integer, value: undefined })?.kind).toBe(+ 'missingValue'+ );+ expect(getWorkflowFieldIssue({ isConnected: false, template: integer, value: 0 })).toEqual({+ kind: 'invalidValue',+ reason: 'Invalid value.',+ });+ expect(+ getWorkflowFieldIssue({ isConnected: false, template: input({ input: 'connection' }), value: undefined })?.kind+ ).toBe('missingConnection');+ expect(getWorkflowFieldIssue({ isConnected: false, template: integer, value: 3 })).toBeNull();+ });+it('accepts persisted values for unsupported direct controls', () => {const template = input({ type: single('AnyField') });diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts b/invokeai/frontend/webv2/src/features/workflow/core/fields.tsindex d4ebd54c9a..f10691b2a3 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/fields.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/fields.ts@@ -465,7 +465,22 @@ export const isWorkflowFieldValueValid = (template: FieldInputTemplate, value: uconst isEmptyOptionalValue = (value: unknown): boolean => value === undefined || value === null || value === '';-export const getWorkflowFieldInvalidReason = ({+/** What a field that blocks a run lacks: a value, a connection, or a value it accepts. */+export type WorkflowFieldIssueKind = 'invalidValue' | 'missingConnection' | 'missingValue';++export interface WorkflowFieldIssue {+ kind: WorkflowFieldIssueKind;+ /** The field's own wording of the problem. */+ reason: string;+}++const MISSING_CONNECTION: WorkflowFieldIssue = { kind: 'missingConnection', reason: 'Required connection.' };+const MISSING_VALUE: WorkflowFieldIssue = { kind: 'missingValue', reason: 'Required value.' };++const toInvalidValueIssue = (reason: string | null): WorkflowFieldIssue | null =>+ reason === null ? null : { kind: 'invalidValue', reason };++export const getWorkflowFieldIssue = ({isConnected,template,value,@@ -473,7 +488,7 @@ export const getWorkflowFieldInvalidReason = ({isConnected: boolean;template: FieldInputTemplate;value: unknown;-}): string | null => {+}): WorkflowFieldIssue | null => {if (isConnected) {return null;}@@ -484,11 +499,11 @@ export const getWorkflowFieldInvalidReason = ({// An editable list reports which count or entry rule it breaks; the generic reasons cannot say.if (template.type.cardinality === 'COLLECTION' && Array.isArray(value) && isDirectInputField(template)) {- return getCollectionInvalidReason(template, value);+ return toInvalidValueIssue(getCollectionInvalidReason(template, value));}if (template.type.name === 'LoRAField' && isDirectInputField(template) && !isEmptyOptionalValue(value)) {- return getLoraCollectionInvalidReason(toLoraFieldCollectionList(value));+ return toInvalidValueIssue(getLoraCollectionInvalidReason(toLoraFieldCollectionList(value)));}if (@@ -498,15 +513,17 @@ export const getWorkflowFieldInvalidReason = ({) {const generator = parseWorkflowGeneratorValue(template.type.name, value);- return generator === null ? 'Invalid value.' : getWorkflowGeneratorInvalidReason(generator);+ return toInvalidValueIssue(generator === null ? 'Invalid value.' : getWorkflowGeneratorInvalidReason(generator));}if (!template.required) {- return isDirectInputField(template) && !isWorkflowFieldValueValid(template, value) ? 'Invalid value.' : null;+ return isDirectInputField(template) && !isWorkflowFieldValueValid(template, value)+ ? toInvalidValueIssue('Invalid value.')+ : null;}if (template.input === 'connection') {- return 'Required connection.';+ return MISSING_CONNECTION;}if (isWorkflowFieldValueValid(template, value)) {@@ -514,12 +531,15 @@ export const getWorkflowFieldInvalidReason = ({}if (!isDirectInputField(template)) {- return 'Required connection.';+ return MISSING_CONNECTION;}- return isEmptyOptionalValue(value) ? 'Required value.' : 'Invalid value.';+ return isEmptyOptionalValue(value) ? MISSING_VALUE : toInvalidValueIssue('Invalid value.');};+export const getWorkflowFieldInvalidReason = (field: Parameters<typeof getWorkflowFieldIssue>[0]): string | null =>+ getWorkflowFieldIssue(field)?.reason ?? null;+// Raw hex (not Chakra tokens) because xyflow handles are styled inline.const FIELD_TYPE_COLORS: Record<string, string> = {AnyField: '#9ca3af',diff --git a/invokeai/frontend/webv2/src/features/workflow/core/fixtures/extend-video-ltx2.json b/invokeai/frontend/webv2/src/features/workflow/core/fixtures/extend-video-ltx2.jsonnew file mode 100644index 0000000000..cb85caa3fd--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/fixtures/extend-video-ltx2.json@@ -0,0 +1,3577 @@+{+ "templates": {+ "string": {+ "type": "string",+ "title": "String Primitive",+ "category": "primitives",+ "classification": "stable",+ "version": "1.0.1",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "string_output",+ "tags": ["primitives", "string"],+ "description": "",+ "inputs": {+ "value": {+ "name": "value",+ "title": "Value",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": "textarea",+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ }+ },+ "outputs": {}+ },+ "integer": {+ "type": "integer",+ "title": "Integer Primitive",+ "category": "primitives",+ "classification": "stable",+ "version": "1.0.1",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "integer_output",+ "tags": ["primitives", "integer"],+ "description": "",+ "inputs": {+ "value": {+ "name": "value",+ "title": "Value",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ }+ },+ "outputs": {}+ },+ "ltx2_model_loader": {+ "type": "ltx2_model_loader",+ "title": "Main Model - LTX-2",+ "category": "model",+ "classification": "prototype",+ "version": "1.2.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "ltx2_model_loader_output",+ "tags": ["model", "ltx", "ltx2", "video"],+ "description": "",+ "inputs": {+ "model": {+ "name": "model",+ "title": "Model",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "direct",+ "required": true,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": ["ltx-2"],+ "uiModelType": ["main"],+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "component_source": {+ "name": "component_source",+ "title": "Components",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "direct",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": ["ltx-2"],+ "uiModelType": ["main"],+ "uiModelFormat": ["diffusers"],+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "text_encoder_model": {+ "name": "text_encoder_model",+ "title": "Text Encoder",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "direct",+ "required": true,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": ["ltx-2"],+ "uiModelType": ["gemma4_encoder"],+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ }+ },+ "outputs": {}+ },+ "ltx2_text_encoder": {+ "type": "ltx2_text_encoder",+ "title": "Prompt - LTX-2",+ "category": "conditioning",+ "classification": "prototype",+ "version": "1.0.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "ltx2_text_encoder_output",+ "tags": ["prompt", "conditioning", "ltx", "ltx2", "video"],+ "description": "",+ "inputs": {+ "prompt": {+ "name": "prompt",+ "title": "Prompt",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": true,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": "textarea",+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "negative_prompt": {+ "name": "negative_prompt",+ "title": "Negative Prompt",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": "textarea",+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": "has_subtitles, has_blurbox, transition from black, transition to black, speech_ending_short, blurry, out of focus, overexposed, underexposed, low contrast, washed out colors, excessive noise, grainy texture, poor lighting, flickering, motion blur, distorted proportions, unnatural skin tones, deformed facial features, asymmetrical face, missing facial features, extra limbs, disfigured hands, wrong hand count, artifacts around text, inconsistent perspective, camera shake, incorrect depth of field, background too sharp, background clutter, distracting reflections, harsh shadows, inconsistent lighting direction, color banding, cartoonish rendering, 3D CGI look, unrealistic materials, uncanny valley effect, incorrect ethnicity, wrong gender, exaggerated expressions, wrong gaze direction, mismatched lip sync, silent or muted audio, distorted voice, robotic voice, echo, background noise, off-sync audio, incorrect dialogue, added dialogue, repetitive speech, jittery movement, awkward pauses, incorrect timing, unnatural transitions, inconsistent framing, tilted camera, flat lighting, inconsistent tone, cinematic oversaturation, stylized filters, or AI artifacts."+ },+ "encode_negative": {+ "name": "encode_negative",+ "title": "Encode Negative",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "BooleanField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": true+ },+ "max_sequence_length": {+ "name": "max_sequence_length",+ "title": "Max Sequence Length",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": 1024,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 1024+ }+ },+ "outputs": {}+ },+ "ltx2_denoise": {+ "type": "ltx2_denoise",+ "title": "Denoise - LTX-2",+ "category": "latents",+ "classification": "prototype",+ "version": "1.5.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "ltx2_denoise_output",+ "tags": ["ltx", "ltx2", "video", "audio", "denoise"],+ "description": "",+ "inputs": {+ "width": {+ "name": "width",+ "title": "Width",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": 32,+ "description": "",+ "default": 1248+ },+ "height": {+ "name": "height",+ "title": "Height",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": 32,+ "description": "",+ "default": 704+ },+ "num_frames": {+ "name": "num_frames",+ "title": "Num Frames",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 121+ },+ "fps": {+ "name": "fps",+ "title": "Fps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 1,+ "maximum": 120,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 24+ },+ "steps": {+ "name": "steps",+ "title": "Steps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 30+ },+ "cfg_scale": {+ "name": "cfg_scale",+ "title": "Cfg Scale",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 1,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 3+ },+ "audio_cfg_scale": {+ "name": "audio_cfg_scale",+ "title": "Audio CFG Scale",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 1,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 7+ },+ "stg_scale": {+ "name": "stg_scale",+ "title": "STG Scale",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 0,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 1+ },+ "modality_scale": {+ "name": "modality_scale",+ "title": "Modality Scale",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 1,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 3+ },+ "guidance_rescale": {+ "name": "guidance_rescale",+ "title": "Guidance Rescale",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 0,+ "maximum": 1,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0.7+ },+ "schedule": {+ "name": "schedule",+ "title": "Schedule",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "EnumField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": {+ "auto": "Auto (from the model's variant)",+ "dev": "Dev (shifted, guided)",+ "distilled": "Distilled (8 fixed steps, no guidance)"+ },+ "options": ["auto", "dev", "distilled"],+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": "auto"+ },+ "seed": {+ "name": "seed",+ "title": "Seed",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 0,+ "maximum": 4294967295,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "noise_scale": {+ "name": "noise_scale",+ "title": "Noise Scale",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": 1,+ "multipleOf": null,+ "description": "",+ "default": 0.909375+ }+ },+ "outputs": {}+ },+ "ltx2_latents_to_video": {+ "type": "ltx2_latents_to_video",+ "title": "Latents to Video - LTX-2",+ "category": "latents",+ "classification": "prototype",+ "version": "1.2.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "video_output",+ "tags": ["latents", "video", "audio", "vae", "l2v", "ltx", "ltx2"],+ "description": "",+ "inputs": {+ "fps": {+ "name": "fps",+ "title": "Fps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 1,+ "maximum": 120,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 24+ },+ "tile_size": {+ "name": "tile_size",+ "title": "Tile Size",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 64,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 512+ },+ "temporal_tile": {+ "name": "temporal_tile",+ "title": "Temporal Tile",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 8,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 16+ }+ },+ "outputs": {}+ },+ "extract_video_range": {+ "type": "extract_video_range",+ "title": "Frame Range from Video",+ "category": "video",+ "classification": "prototype",+ "version": "1.3.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "extract_video_range_output",+ "tags": ["video", "trim", "range", "frames"],+ "description": "",+ "inputs": {+ "video": {+ "name": "video",+ "title": "Video",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "VideoField" },+ "fieldKind": "input",+ "input": "any",+ "required": true,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "start_frame": {+ "name": "start_frame",+ "title": "Start Frame",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": "video-frame-index",+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "end_frame": {+ "name": "end_frame",+ "title": "End Frame",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": "video-frame-index",+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": -1+ },+ "fps": {+ "name": "fps",+ "title": "Fps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 0,+ "maximum": 120,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ }+ },+ "outputs": {}+ },+ "collect": {+ "type": "collect",+ "title": "Collect",+ "category": "other",+ "classification": "stable",+ "version": "1.1.0",+ "useCache": false,+ "nodePack": "invokeai",+ "outputType": "collect_output",+ "tags": [],+ "description": "",+ "inputs": {},+ "outputs": {}+ },+ "video_concat": {+ "type": "video_concat",+ "title": "Concatenate Videos",+ "category": "video",+ "classification": "prototype",+ "version": "1.3.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "video_output",+ "tags": ["video", "concat", "transition"],+ "description": "",+ "inputs": {+ "videos": {+ "name": "videos",+ "title": "Videos",+ "type": { "batch": false, "cardinality": "COLLECTION", "name": "VideoField" },+ "fieldKind": "input",+ "input": "any",+ "required": true,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "transition": {+ "name": "transition",+ "title": "Transition",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "EnumField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": ["cut", "crossfade", "fade_through_black"],+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": "cut"+ },+ "transition_frames": {+ "name": "transition_frames",+ "title": "Transition Frames",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 0,+ "maximum": 240,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 8+ },+ "fps": {+ "name": "fps",+ "title": "Fps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "size_mismatch": {+ "name": "size_mismatch",+ "title": "Size Mismatch",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "EnumField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": ["error", "match_first"],+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": "error"+ },+ "smart_render": {+ "name": "smart_render",+ "title": "Smart Render",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "BooleanField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": true+ }+ },+ "outputs": {}+ },+ "ltx2_extend_conditioning": {+ "type": "ltx2_extend_conditioning",+ "title": "Extend Conditioning - LTX-2",+ "category": "conditioning",+ "classification": "prototype",+ "version": "1.1.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "ltx2_extend_conditioning_output",+ "tags": ["ltx", "ltx2", "video", "extend", "conditioning"],+ "description": "",+ "inputs": {+ "video": {+ "name": "video",+ "title": "Video",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "VideoField" },+ "fieldKind": "input",+ "input": "any",+ "required": true,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "fps": {+ "name": "fps",+ "title": "Fps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 1,+ "maximum": 120,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 24+ },+ "width": {+ "name": "width",+ "title": "Width",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": 32,+ "description": "",+ "default": 1248+ },+ "height": {+ "name": "height",+ "title": "Height",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": 32,+ "description": "",+ "default": 704+ },+ "context_frames": {+ "name": "context_frames",+ "title": "Context Frames",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 1,+ "maximum": 481,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 17+ },+ "tile_size": {+ "name": "tile_size",+ "title": "Tile Size",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 64,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 512+ },+ "temporal_tile": {+ "name": "temporal_tile",+ "title": "Temporal Tile",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": 8,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 16+ }+ },+ "outputs": {}+ },+ "core_metadata": {+ "type": "core_metadata",+ "title": "Core Metadata",+ "category": "metadata",+ "classification": "internal",+ "version": "2.9.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "metadata_output",+ "tags": ["metadata"],+ "description": "",+ "inputs": {+ "generation_mode": {+ "name": "generation_mode",+ "title": "Generation Mode",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "EnumField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": [+ "txt2img",+ "img2img",+ "inpaint",+ "outpaint",+ "sdxl_txt2img",+ "sdxl_img2img",+ "sdxl_inpaint",+ "sdxl_outpaint",+ "flux_txt2img",+ "flux_img2img",+ "flux_inpaint",+ "flux_outpaint",+ "flux2_txt2img",+ "flux2_img2img",+ "flux2_inpaint",+ "flux2_outpaint",+ "sd3_txt2img",+ "sd3_img2img",+ "sd3_inpaint",+ "sd3_outpaint",+ "cogview4_txt2img",+ "cogview4_img2img",+ "cogview4_inpaint",+ "cogview4_outpaint",+ "z_image_txt2img",+ "z_image_img2img",+ "z_image_inpaint",+ "z_image_outpaint",+ "ernie_image_txt2img",+ "ideogram4_txt2img",+ "qwen_image_txt2img",+ "qwen_image_img2img",+ "qwen_image_inpaint",+ "qwen_image_outpaint",+ "anima_txt2img",+ "anima_img2img",+ "anima_inpaint",+ "anima_outpaint",+ "krea2_txt2img",+ "krea2_img2img",+ "krea2_inpaint",+ "krea2_outpaint",+ "qwen_image_2_1_txt2img",+ "qwen_image_2_1_img2img",+ "qwen_image_2_1_inpaint",+ "qwen_image_2_1_outpaint",+ "flux3_txt2img",+ "flux3_img2img",+ "flux3_inpaint",+ "flux3_outpaint",+ "moss_image_txt2img",+ "moss_image_img2img",+ "moss_image_inpaint",+ "moss_image_outpaint",+ "wan_txt2img",+ "wan_img2img",+ "wan_inpaint",+ "wan_outpaint",+ "wan_t2v",+ "wan_i2v",+ "wan_interpolate",+ "wan_extend_video",+ "minimax_h3_t2v",+ "minimax_h3_i2v",+ "ltx2_t2v",+ "ltx2_i2v",+ "ltx2_a2v",+ "ltx2_v2a",+ "ltx2_lf2v",+ "ltx2_flf2v",+ "ltx2_extend_video",+ "minimax_h3_lf2v",+ "minimax_h3_flf2v",+ "minimax_h3_extend_video",+ "minimax_h3_ref2v",+ "minimax_h3_txt2img"+ ],+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "positive_prompt": {+ "name": "positive_prompt",+ "title": "Positive Prompt",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "negative_prompt": {+ "name": "negative_prompt",+ "title": "Negative Prompt",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "width": {+ "name": "width",+ "title": "Width",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "height": {+ "name": "height",+ "title": "Height",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "seed": {+ "name": "seed",+ "title": "Seed",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "rand_device": {+ "name": "rand_device",+ "title": "Rand Device",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "cfg_scale": {+ "name": "cfg_scale",+ "title": "Cfg Scale",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "cfg_rescale_multiplier": {+ "name": "cfg_rescale_multiplier",+ "title": "Cfg Rescale Multiplier",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "steps": {+ "name": "steps",+ "title": "Steps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "scheduler": {+ "name": "scheduler",+ "title": "Scheduler",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "seamless_x": {+ "name": "seamless_x",+ "title": "Seamless X",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "BooleanField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": false+ },+ "seamless_y": {+ "name": "seamless_y",+ "title": "Seamless Y",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "BooleanField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": false+ },+ "clip_skip": {+ "name": "clip_skip",+ "title": "Clip Skip",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "model": {+ "name": "model",+ "title": "Model",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "controlnets": {+ "name": "controlnets",+ "title": "Controlnets",+ "type": { "batch": false, "cardinality": "COLLECTION", "name": "ControlNetMetadataField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "ipAdapters": {+ "name": "ipAdapters",+ "title": "Ipadapters",+ "type": { "batch": false, "cardinality": "COLLECTION", "name": "IPAdapterMetadataField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "t2iAdapters": {+ "name": "t2iAdapters",+ "title": "T2Iadapters",+ "type": { "batch": false, "cardinality": "COLLECTION", "name": "T2IAdapterMetadataField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "loras": {+ "name": "loras",+ "title": "Loras",+ "type": { "batch": false, "cardinality": "COLLECTION", "name": "LoRAMetadataField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "strength": {+ "name": "strength",+ "title": "Strength",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "init_image": {+ "name": "init_image",+ "title": "Init Image",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "vae": {+ "name": "vae",+ "title": "Vae",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "qwen3_encoder": {+ "name": "qwen3_encoder",+ "title": "Qwen3 Encoder",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "mistral_encoder": {+ "name": "mistral_encoder",+ "title": "Mistral Encoder",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "ideogram4_caption": {+ "name": "ideogram4_caption",+ "title": "Ideogram4 Caption",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "num_frames": {+ "name": "num_frames",+ "title": "Num Frames",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "first_frame_image": {+ "name": "first_frame_image",+ "title": "First Frame Image",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ImageField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "last_frame_image": {+ "name": "last_frame_image",+ "title": "Last Frame Image",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ImageField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "source_video": {+ "name": "source_video",+ "title": "Source Video",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "VideoField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "source_video_start_frame": {+ "name": "source_video_start_frame",+ "title": "Source Video Start Frame",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "source_video_end_frame": {+ "name": "source_video_end_frame",+ "title": "Source Video End Frame",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "fps": {+ "name": "fps",+ "title": "Fps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "wan_guidance_scale_low_noise": {+ "name": "wan_guidance_scale_low_noise",+ "title": "Wan Guidance Scale Low Noise",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "wan_t5_encoder_model": {+ "name": "wan_t5_encoder_model",+ "title": "Wan T5 Encoder Model",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "wan_transformer_low_noise": {+ "name": "wan_transformer_low_noise",+ "title": "Wan Transformer Low Noise",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "wan_component_source": {+ "name": "wan_component_source",+ "title": "Wan Component Source",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "minimax_h3_transformer_model": {+ "name": "minimax_h3_transformer_model",+ "title": "Minimax H3 Transformer Model",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "minimax_h3_text_encoder_model": {+ "name": "minimax_h3_text_encoder_model",+ "title": "Minimax H3 Text Encoder Model",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "minimax_h3_component_source": {+ "name": "minimax_h3_component_source",+ "title": "Minimax H3 Component Source",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "minimax_h3_hybrid_base_model": {+ "name": "minimax_h3_hybrid_base_model",+ "title": "Minimax H3 Hybrid Base Model",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "minimax_h3_hybrid_start_block": {+ "name": "minimax_h3_hybrid_start_block",+ "title": "Minimax H3 Hybrid Start Block",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "minimax_h3_references": {+ "name": "minimax_h3_references",+ "title": "Minimax H3 References",+ "type": { "batch": false, "cardinality": "COLLECTION", "name": "MiniMaxH3ReferenceMetadataField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "hrf_enabled": {+ "name": "hrf_enabled",+ "title": "Hrf Enabled",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "BooleanField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": false+ },+ "hrf_method": {+ "name": "hrf_method",+ "title": "Hrf Method",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "hrf_strength": {+ "name": "hrf_strength",+ "title": "Hrf Strength",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "positive_style_prompt": {+ "name": "positive_style_prompt",+ "title": "Positive Style Prompt",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "negative_style_prompt": {+ "name": "negative_style_prompt",+ "title": "Negative Style Prompt",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "refiner_model": {+ "name": "refiner_model",+ "title": "Refiner Model",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "ModelIdentifierField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": null+ },+ "refiner_cfg_scale": {+ "name": "refiner_cfg_scale",+ "title": "Refiner Cfg Scale",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "refiner_steps": {+ "name": "refiner_steps",+ "title": "Refiner Steps",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "refiner_scheduler": {+ "name": "refiner_scheduler",+ "title": "Refiner Scheduler",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "StringField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": ""+ },+ "refiner_positive_aesthetic_score": {+ "name": "refiner_positive_aesthetic_score",+ "title": "Refiner Positive Aesthetic Score",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "refiner_negative_aesthetic_score": {+ "name": "refiner_negative_aesthetic_score",+ "title": "Refiner Negative Aesthetic Score",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ },+ "refiner_start": {+ "name": "refiner_start",+ "title": "Refiner Start",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "FloatField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 0+ }+ },+ "outputs": {}+ },+ "ltx2_ideal_dimensions": {+ "type": "ltx2_ideal_dimensions",+ "title": "LTX-2 Ideal Dimensions",+ "category": "video",+ "classification": "prototype",+ "version": "1.1.0",+ "useCache": true,+ "nodePack": "invokeai",+ "outputType": "ltx2_ideal_dimensions_output",+ "tags": ["ltx", "ltx2", "video", "dimensions", "math"],+ "description": "",+ "inputs": {+ "width": {+ "name": "width",+ "title": "Width",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 1024+ },+ "height": {+ "name": "height",+ "title": "Height",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "IntegerField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": null,+ "options": null,+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": 0,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": 1024+ },+ "target_resolution": {+ "name": "target_resolution",+ "title": "Target Resolution",+ "type": { "batch": false, "cardinality": "SINGLE", "name": "EnumField" },+ "fieldKind": "input",+ "input": "any",+ "required": false,+ "uiHidden": false,+ "uiOrder": null,+ "uiChoiceLabels": {+ "1024p": "1024p (short edge 1024, two-stage)",+ "1536p": "1536p (short edge 1536, two-stage - very slow)",+ "512p": "512p (short edge 512 - fastest)",+ "704p": "704p (short edge 704)",+ "768p": "768p (short edge 768 - sharpest, slowest)"+ },+ "options": ["512p", "704p", "768p", "1024p", "1536p"],+ "uiModelBase": null,+ "uiModelType": null,+ "uiModelFormat": null,+ "uiComponent": null,+ "minimum": null,+ "maximum": null,+ "exclusiveMinimum": null,+ "exclusiveMaximum": null,+ "multipleOf": null,+ "description": "",+ "default": "704p"+ }+ },+ "outputs": {}+ }+ },+ "workflow": {+ "name": "Extend Video - LTX-2",+ "author": "Invoke",+ "description": "Continues an existing clip with LTX-2, holding the source's last frames and its closing sound so the join is seamless. Exposes context_frames for tuning how much of the source carries into the continuation.",+ "version": "1.0.0",+ "contact": "",+ "tags": "ltx, ltx2, video, extend, audio",+ "notes": "Target Resolution: use 512p, 704p or 768p. The two-stage presets (1024p, 1536p) generate at half their named size and finish in a refine pass this single-pass template does not have, so they render SMALLER than 768p rather than larger.\n\nContext Frames decides how much of the source the model sees. The default 17 (about 0.7s at 24 fps) carries motion but only ~1 syllable of sound -- enough for tone, not for cadence. Raise it (25/33/41/49...) when continuing rhythmic material such as singing, and raise Number of Frames with it so the extension is not mostly replay.\n\nEach InvokeAI install assigns its own internal model IDs, so the model fields ship blank -- pick these in the form after loading (all from the LTX-2.5 starter bundle):\n\n- Model: LTX-2.5 Dev Transformer (int8) or LTX-2.5 Distilled Transformer (int8). The Denoise node's 'auto' schedule follows the checkpoint: Dev runs the guided 30-step recipe, Distilled a fixed 8 steps with no guidance (its Steps and guidance values are ignored, and the log says so).\n- Components: LTX-2.5 Components (VAEs, vocoder, text connectors, latent upscaler).\n- Text Encoder: LTX-2.5 Text Encoder (Gemma-4 12B, int8). Required: no LTX-2 model carries one.\n\nThe negative prompt is pre-filled with the release's own default list and is used only on Dev with a CFG or Audio CFG above 1. On Distilled, turning off 'Encode Negative' on the Prompt node skips its encode.",+ "exposedFields": [+ { "nodeId": "source_video", "fieldName": "video" },+ { "nodeId": "source_video", "fieldName": "start_frame" },+ { "nodeId": "source_video", "fieldName": "end_frame" },+ { "nodeId": "extend_conditioning", "fieldName": "context_frames" },+ { "nodeId": "denoise_latents", "fieldName": "num_frames" },+ { "nodeId": "positive_prompt", "fieldName": "value" },+ { "nodeId": "negative_prompt", "fieldName": "value" },+ { "nodeId": "ideal_dimensions", "fieldName": "target_resolution" },+ { "nodeId": "steps", "fieldName": "value" },+ { "nodeId": "seed", "fieldName": "value" },+ { "nodeId": "model_loader", "fieldName": "model" },+ { "nodeId": "model_loader", "fieldName": "component_source" },+ { "nodeId": "model_loader", "fieldName": "text_encoder_model" }+ ],+ "meta": { "version": "4.0.0", "category": "default" },+ "nodes": [+ {+ "id": "negative_prompt",+ "type": "invocation",+ "data": {+ "id": "negative_prompt",+ "version": "1.0.1",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "type": "string",+ "inputs": {+ "value": {+ "name": "value",+ "label": "Negative Prompt",+ "description": "What to steer the generation away from.",+ "value": "has_subtitles, has_blurbox, transition from black, transition to black, speech_ending_short, blurry, out of focus, overexposed, underexposed, low contrast, washed out colors, excessive noise, grainy texture, poor lighting, flickering, motion blur, distorted proportions, unnatural skin tones, deformed facial features, asymmetrical face, missing facial features, extra limbs, disfigured hands, wrong hand count, artifacts around text, inconsistent perspective, camera shake, incorrect depth of field, background too sharp, background clutter, distracting reflections, harsh shadows, inconsistent lighting direction, color banding, cartoonish rendering, 3D CGI look, unrealistic materials, uncanny valley effect, incorrect ethnicity, wrong gender, exaggerated expressions, wrong gaze direction, mismatched lip sync, silent or muted audio, distorted voice, robotic voice, echo, background noise, off-sync audio, incorrect dialogue, added dialogue, repetitive speech, jittery movement, awkward pauses, incorrect timing, unnatural transitions, inconsistent framing, tilted camera, flat lighting, inconsistent tone, cinematic oversaturation, stylized filters, or AI artifacts."+ }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 0, "y": 260 }+ },+ {+ "id": "positive_prompt",+ "type": "invocation",+ "data": {+ "id": "positive_prompt",+ "version": "1.0.1",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "type": "string",+ "inputs": {+ "value": { "name": "value", "label": "Prompt", "description": "Describe what to generate.", "value": "" }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 0, "y": 0 }+ },+ {+ "id": "seed",+ "type": "invocation",+ "data": {+ "id": "seed",+ "version": "1.0.1",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "type": "integer",+ "inputs": {+ "value": { "name": "value", "label": "Seed", "description": "Reuse a seed to repeat a result.", "value": 0 }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 0, "y": 520 }+ },+ {+ "id": "model_loader",+ "type": "invocation",+ "data": {+ "id": "model_loader",+ "version": "1.2.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "type": "ltx2_model_loader",+ "inputs": {+ "model": { "name": "model", "label": "Model", "description": "", "value": null },+ "component_source": { "name": "component_source", "label": "Components", "description": "", "value": null },+ "text_encoder_model": {+ "name": "text_encoder_model",+ "label": "Text Encoder",+ "description": "",+ "value": null+ }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 0, "y": 700 }+ },+ {+ "id": "pos_cond",+ "type": "invocation",+ "data": {+ "id": "pos_cond",+ "version": "1.0.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "type": "ltx2_text_encoder",+ "inputs": {+ "prompt": { "name": "prompt", "label": "", "description": "", "value": null },+ "negative_prompt": {+ "name": "negative_prompt",+ "label": "",+ "description": "",+ "value": "has_subtitles, has_blurbox, transition from black, transition to black, speech_ending_short, blurry, out of focus, overexposed, underexposed, low contrast, washed out colors, excessive noise, grainy texture, poor lighting, flickering, motion blur, distorted proportions, unnatural skin tones, deformed facial features, asymmetrical face, missing facial features, extra limbs, disfigured hands, wrong hand count, artifacts around text, inconsistent perspective, camera shake, incorrect depth of field, background too sharp, background clutter, distracting reflections, harsh shadows, inconsistent lighting direction, color banding, cartoonish rendering, 3D CGI look, unrealistic materials, uncanny valley effect, incorrect ethnicity, wrong gender, exaggerated expressions, wrong gaze direction, mismatched lip sync, silent or muted audio, distorted voice, robotic voice, echo, background noise, off-sync audio, incorrect dialogue, added dialogue, repetitive speech, jittery movement, awkward pauses, incorrect timing, unnatural transitions, inconsistent framing, tilted camera, flat lighting, inconsistent tone, cinematic oversaturation, stylized filters, or AI artifacts."+ },+ "encode_negative": { "name": "encode_negative", "label": "", "description": "", "value": true },+ "max_sequence_length": { "name": "max_sequence_length", "label": "", "description": "", "value": 1024 }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 460, "y": 0 }+ },+ {+ "id": "denoise_latents",+ "type": "invocation",+ "data": {+ "id": "denoise_latents",+ "version": "1.5.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "num_frames is the GENERATED clip's length and must exceed context_frames -- at or below it the output would be all replay. width/height must match the Extend Conditioning node's.",+ "type": "ltx2_denoise",+ "inputs": {+ "width": { "name": "width", "label": "", "description": "", "value": 1248 },+ "height": { "name": "height", "label": "", "description": "", "value": 704 },+ "num_frames": { "name": "num_frames", "label": "Number of Frames", "description": "", "value": 121 },+ "fps": { "name": "fps", "label": "", "description": "", "value": 24 },+ "steps": { "name": "steps", "label": "", "description": "", "value": 30 },+ "cfg_scale": { "name": "cfg_scale", "label": "", "description": "", "value": 3 },+ "audio_cfg_scale": { "name": "audio_cfg_scale", "label": "", "description": "", "value": 7 },+ "stg_scale": { "name": "stg_scale", "label": "", "description": "", "value": 1 },+ "modality_scale": { "name": "modality_scale", "label": "", "description": "", "value": 3 },+ "guidance_rescale": { "name": "guidance_rescale", "label": "", "description": "", "value": 0.7 },+ "schedule": { "name": "schedule", "label": "", "description": "", "value": "auto" },+ "seed": { "name": "seed", "label": "", "description": "", "value": 0 },+ "noise_scale": { "name": "noise_scale", "label": "", "description": "", "value": 0.909375 }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 900, "y": 0 }+ },+ {+ "id": "extension_clip",+ "type": "invocation",+ "data": {+ "id": "extension_clip",+ "version": "1.2.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "Decodes the generated half. The join below is the finished result.",+ "type": "ltx2_latents_to_video",+ "inputs": {+ "fps": { "name": "fps", "label": "", "description": "", "value": 24 },+ "tile_size": { "name": "tile_size", "label": "", "description": "", "value": 512 },+ "temporal_tile": { "name": "temporal_tile", "label": "", "description": "", "value": 16 }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": false+ },+ "position": { "x": 1380, "y": 0 }+ },+ {+ "id": "source_video",+ "type": "invocation",+ "data": {+ "id": "source_video",+ "version": "1.3.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "Trims the source. The extension continues from wherever this trim ENDS.",+ "type": "extract_video_range",+ "inputs": {+ "video": { "name": "video", "label": "Source Video", "description": "", "value": null },+ "start_frame": { "name": "start_frame", "label": "Start Frame", "description": "", "value": 0 },+ "end_frame": { "name": "end_frame", "label": "End Frame", "description": "", "value": -1 },+ "fps": { "name": "fps", "label": "", "description": "", "value": 0 }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": false+ },+ "position": { "x": 420, "y": 1000 }+ },+ {+ "id": "source_clip_collect",+ "type": "invocation",+ "data": {+ "id": "source_clip_collect",+ "version": "1.1.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "type": "collect",+ "inputs": {},+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 1380, "y": 900 }+ },+ {+ "id": "clips_to_join",+ "type": "invocation",+ "data": {+ "id": "clips_to_join",+ "version": "1.1.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "",+ "type": "collect",+ "inputs": {},+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 1700, "y": 900 }+ },+ {+ "id": "video_output",+ "type": "invocation",+ "data": {+ "id": "video_output",+ "version": "1.3.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "Joins source + extension. `transition_frames` arrives over an edge from context_frames -- the crossfade must consume exactly the held frames or they play twice.",+ "type": "video_concat",+ "inputs": {+ "videos": { "name": "videos", "label": "", "description": "", "value": null },+ "transition": { "name": "transition", "label": "", "description": "", "value": "crossfade" },+ "transition_frames": { "name": "transition_frames", "label": "", "description": "", "value": 17 },+ "fps": { "name": "fps", "label": "", "description": "", "value": null },+ "size_mismatch": { "name": "size_mismatch", "label": "", "description": "", "value": "match_first" },+ "smart_render": { "name": "smart_render", "label": "", "description": "", "value": true }+ },+ "isOpen": true,+ "isIntermediate": false,+ "useCache": false+ },+ "position": { "x": 2020, "y": 640 }+ },+ {+ "id": "extend_conditioning",+ "type": "invocation",+ "data": {+ "id": "extend_conditioning",+ "version": "1.1.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "Reads the TAIL of the trimmed clip. `context_frames` is the knob this template exists for: the number of source frames carried into the continuation, snapped DOWN to the VAE's 8n+1 grid (17, 25, 33, 41, 49...). It drives three things at once -- the held picture, the held soundtrack, and the crossfade length, which is why it is wired to the join rather than set there. Larger = smoother motion and more rhythmic context, but more of the generation spent replaying footage you already have.",+ "type": "ltx2_extend_conditioning",+ "inputs": {+ "video": { "name": "video", "label": "", "description": "", "value": null },+ "fps": { "name": "fps", "label": "", "description": "", "value": 24 },+ "width": { "name": "width", "label": "", "description": "", "value": 1248 },+ "height": { "name": "height", "label": "", "description": "", "value": 704 },+ "context_frames": {+ "name": "context_frames",+ "label": "Context Frames",+ "description": "How many frames from the initial video to carry into the extension. More frames improves continuity, but reduces the overall length of the clip.",+ "value": 17,+ "descriptionOverride": true+ },+ "tile_size": { "name": "tile_size", "label": "", "description": "", "value": 512 },+ "temporal_tile": { "name": "temporal_tile", "label": "", "description": "", "value": 16 }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 900, "y": 760 }+ },+ {+ "id": "core_metadata",+ "type": "invocation",+ "data": {+ "id": "core_metadata",+ "version": "2.9.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "Recorded on the output. The prompt, seed, model, canvas, frame count and steps arrive over edges from the nodes that set them. The frame rate is recorded as 24 and CFG as 3 whatever the source and the Denoise node say: the join delivers the source's own frame rate, and edit this node if you change CFG.",+ "type": "core_metadata",+ "inputs": {+ "generation_mode": {+ "name": "generation_mode",+ "label": "",+ "description": "",+ "value": "ltx2_extend_video"+ },+ "positive_prompt": { "name": "positive_prompt", "label": "", "description": "", "value": null },+ "negative_prompt": { "name": "negative_prompt", "label": "", "description": "", "value": null },+ "width": { "name": "width", "label": "", "description": "", "value": null },+ "height": { "name": "height", "label": "", "description": "", "value": null },+ "seed": { "name": "seed", "label": "", "description": "", "value": null },+ "rand_device": { "name": "rand_device", "label": "", "description": "", "value": null },+ "cfg_scale": { "name": "cfg_scale", "label": "", "description": "", "value": 3 },+ "cfg_rescale_multiplier": {+ "name": "cfg_rescale_multiplier",+ "label": "",+ "description": "",+ "value": null+ },+ "steps": { "name": "steps", "label": "", "description": "", "value": 30 },+ "scheduler": { "name": "scheduler", "label": "", "description": "", "value": null },+ "seamless_x": { "name": "seamless_x", "label": "", "description": "", "value": null },+ "seamless_y": { "name": "seamless_y", "label": "", "description": "", "value": null },+ "clip_skip": { "name": "clip_skip", "label": "", "description": "", "value": null },+ "model": { "name": "model", "label": "", "description": "", "value": null },+ "controlnets": { "name": "controlnets", "label": "", "description": "", "value": null },+ "ipAdapters": { "name": "ipAdapters", "label": "", "description": "", "value": null },+ "t2iAdapters": { "name": "t2iAdapters", "label": "", "description": "", "value": null },+ "loras": { "name": "loras", "label": "", "description": "", "value": null },+ "strength": { "name": "strength", "label": "", "description": "", "value": null },+ "init_image": { "name": "init_image", "label": "", "description": "", "value": null },+ "vae": { "name": "vae", "label": "", "description": "", "value": null },+ "qwen3_encoder": { "name": "qwen3_encoder", "label": "", "description": "", "value": null },+ "mistral_encoder": { "name": "mistral_encoder", "label": "", "description": "", "value": null },+ "ideogram4_caption": { "name": "ideogram4_caption", "label": "", "description": "", "value": null },+ "num_frames": { "name": "num_frames", "label": "", "description": "", "value": 121 },+ "first_frame_image": { "name": "first_frame_image", "label": "", "description": "", "value": null },+ "last_frame_image": { "name": "last_frame_image", "label": "", "description": "", "value": null },+ "source_video": { "name": "source_video", "label": "", "description": "", "value": null },+ "source_video_start_frame": {+ "name": "source_video_start_frame",+ "label": "",+ "description": "",+ "value": null+ },+ "source_video_end_frame": {+ "name": "source_video_end_frame",+ "label": "",+ "description": "",+ "value": null+ },+ "fps": { "name": "fps", "label": "", "description": "", "value": 24 },+ "wan_guidance_scale_low_noise": {+ "name": "wan_guidance_scale_low_noise",+ "label": "",+ "description": "",+ "value": null+ },+ "wan_t5_encoder_model": { "name": "wan_t5_encoder_model", "label": "", "description": "", "value": null },+ "wan_transformer_low_noise": {+ "name": "wan_transformer_low_noise",+ "label": "",+ "description": "",+ "value": null+ },+ "wan_component_source": { "name": "wan_component_source", "label": "", "description": "", "value": null },+ "minimax_h3_transformer_model": {+ "name": "minimax_h3_transformer_model",+ "label": "",+ "description": "",+ "value": null+ },+ "minimax_h3_text_encoder_model": {+ "name": "minimax_h3_text_encoder_model",+ "label": "",+ "description": "",+ "value": null+ },+ "minimax_h3_component_source": {+ "name": "minimax_h3_component_source",+ "label": "",+ "description": "",+ "value": null+ },+ "minimax_h3_hybrid_base_model": {+ "name": "minimax_h3_hybrid_base_model",+ "label": "",+ "description": "",+ "value": null+ },+ "minimax_h3_hybrid_start_block": {+ "name": "minimax_h3_hybrid_start_block",+ "label": "",+ "description": "",+ "value": null+ },+ "minimax_h3_references": { "name": "minimax_h3_references", "label": "", "description": "", "value": null },+ "hrf_enabled": { "name": "hrf_enabled", "label": "", "description": "", "value": null },+ "hrf_method": { "name": "hrf_method", "label": "", "description": "", "value": null },+ "hrf_strength": { "name": "hrf_strength", "label": "", "description": "", "value": null },+ "positive_style_prompt": { "name": "positive_style_prompt", "label": "", "description": "", "value": null },+ "negative_style_prompt": { "name": "negative_style_prompt", "label": "", "description": "", "value": null },+ "refiner_model": { "name": "refiner_model", "label": "", "description": "", "value": null },+ "refiner_cfg_scale": { "name": "refiner_cfg_scale", "label": "", "description": "", "value": null },+ "refiner_steps": { "name": "refiner_steps", "label": "", "description": "", "value": null },+ "refiner_scheduler": { "name": "refiner_scheduler", "label": "", "description": "", "value": null },+ "refiner_positive_aesthetic_score": {+ "name": "refiner_positive_aesthetic_score",+ "label": "",+ "description": "",+ "value": null+ },+ "refiner_negative_aesthetic_score": {+ "name": "refiner_negative_aesthetic_score",+ "label": "",+ "description": "",+ "value": null+ },+ "refiner_start": { "name": "refiner_start", "label": "", "description": "", "value": null }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 460, "y": 420 }+ },+ {+ "id": "ideal_dimensions",+ "type": "invocation",+ "data": {+ "id": "ideal_dimensions",+ "version": "1.1.0",+ "nodePack": "invokeai",+ "label": "",+ "notes": "Derives the canvas from the SOURCE clip so the denoise and the conditioning cannot disagree. Only the source's aspect ratio is used; target_resolution pins the short edge to a trained preset and each axis is rounded to 32 (the VAE's spatial compression), which is why a clip's own pixel size cannot be wired straight through. base_width/base_height are wired out rather than width/height: identical on 512p/704p/768p, and on 1024p/1536p they are the canvas a single pass is actually trained for. THIS TEMPLATE IS A SINGLE PASS, so use 512p, 704p or 768p: the two-stage presets (1024p, 1536p) generate at HALF their named size and rely on a refine pass this graph does not have, so picking 1024p here renders at a 512 short edge, not 1024.",+ "type": "ltx2_ideal_dimensions",+ "inputs": {+ "width": { "name": "width", "label": "", "description": "", "value": 1024 },+ "height": { "name": "height", "label": "", "description": "", "value": 1024 },+ "target_resolution": {+ "name": "target_resolution",+ "label": "Target Resolution",+ "description": "",+ "value": "704p"+ }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 420, "y": 1300 }+ },+ {+ "id": "steps",+ "type": "invocation",+ "data": {+ "id": "steps",+ "version": "1.0.1",+ "nodePack": "invokeai",+ "label": "",+ "notes": "Dev's released recipe is 30. The Distilled checkpoint always runs 8.",+ "type": "integer",+ "inputs": {+ "value": { "name": "value", "label": "Steps", "description": "Number of denoising steps.", "value": 30 }+ },+ "isOpen": true,+ "isIntermediate": true,+ "useCache": true+ },+ "position": { "x": 0, "y": 380 }+ }+ ],+ "edges": [+ {+ "id": "edge-model_loader-text_encoder-pos_cond-text_encoder",+ "source": "model_loader",+ "sourceHandle": "text_encoder",+ "target": "pos_cond",+ "targetHandle": "text_encoder",+ "type": "default"+ },+ {+ "id": "edge-positive_prompt-value-pos_cond-prompt",+ "source": "positive_prompt",+ "sourceHandle": "value",+ "target": "pos_cond",+ "targetHandle": "prompt",+ "type": "default"+ },+ {+ "id": "edge-negative_prompt-value-pos_cond-negative_prompt",+ "source": "negative_prompt",+ "sourceHandle": "value",+ "target": "pos_cond",+ "targetHandle": "negative_prompt",+ "type": "default"+ },+ {+ "id": "edge-model_loader-transformer-denoise_latents-transformer",+ "source": "model_loader",+ "sourceHandle": "transformer",+ "target": "denoise_latents",+ "targetHandle": "transformer",+ "type": "default"+ },+ {+ "id": "edge-pos_cond-conditioning-denoise_latents-positive_conditioning",+ "source": "pos_cond",+ "sourceHandle": "conditioning",+ "target": "denoise_latents",+ "targetHandle": "positive_conditioning",+ "type": "default"+ },+ {+ "id": "edge-pos_cond-negative_conditioning-denoise_latents-negative_conditioning",+ "source": "pos_cond",+ "sourceHandle": "negative_conditioning",+ "target": "denoise_latents",+ "targetHandle": "negative_conditioning",+ "type": "default"+ },+ {+ "id": "edge-seed-value-denoise_latents-seed",+ "source": "seed",+ "sourceHandle": "value",+ "target": "denoise_latents",+ "targetHandle": "seed",+ "type": "default"+ },+ {+ "id": "edge-denoise_latents-video_latents-extension_clip-video_latents",+ "source": "denoise_latents",+ "sourceHandle": "video_latents",+ "target": "extension_clip",+ "targetHandle": "video_latents",+ "type": "default"+ },+ {+ "id": "edge-denoise_latents-audio_latents-extension_clip-audio_latents",+ "source": "denoise_latents",+ "sourceHandle": "audio_latents",+ "target": "extension_clip",+ "targetHandle": "audio_latents",+ "type": "default"+ },+ {+ "id": "edge-model_loader-vae-extension_clip-vae",+ "source": "model_loader",+ "sourceHandle": "vae",+ "target": "extension_clip",+ "targetHandle": "vae",+ "type": "default"+ },+ {+ "id": "edge-model_loader-audio_vae-extension_clip-audio_vae",+ "source": "model_loader",+ "sourceHandle": "audio_vae",+ "target": "extension_clip",+ "targetHandle": "audio_vae",+ "type": "default"+ },+ {+ "id": "edge-model_loader-vocoder-extension_clip-vocoder",+ "source": "model_loader",+ "sourceHandle": "vocoder",+ "target": "extension_clip",+ "targetHandle": "vocoder",+ "type": "default"+ },+ {+ "id": "edge-source_video-video-source_clip_collect-item",+ "source": "source_video",+ "sourceHandle": "video",+ "target": "source_clip_collect",+ "targetHandle": "item",+ "type": "default"+ },+ {+ "id": "edge-source_clip_collect-collection-clips_to_join-collection",+ "source": "source_clip_collect",+ "sourceHandle": "collection",+ "target": "clips_to_join",+ "targetHandle": "collection",+ "type": "default"+ },+ {+ "id": "edge-extension_clip-video-clips_to_join-item",+ "source": "extension_clip",+ "sourceHandle": "video",+ "target": "clips_to_join",+ "targetHandle": "item",+ "type": "default"+ },+ {+ "id": "edge-clips_to_join-collection-video_output-videos",+ "source": "clips_to_join",+ "sourceHandle": "collection",+ "target": "video_output",+ "targetHandle": "videos",+ "type": "default"+ },+ {+ "id": "edge-source_video-video-extend_conditioning-video",+ "source": "source_video",+ "sourceHandle": "video",+ "target": "extend_conditioning",+ "targetHandle": "video",+ "type": "default"+ },+ {+ "id": "edge-model_loader-vae-extend_conditioning-vae",+ "source": "model_loader",+ "sourceHandle": "vae",+ "target": "extend_conditioning",+ "targetHandle": "vae",+ "type": "default"+ },+ {+ "id": "edge-extend_conditioning-video_conditioning-denoise_latents-video_conditioning",+ "source": "extend_conditioning",+ "sourceHandle": "video_conditioning",+ "target": "denoise_latents",+ "targetHandle": "video_conditioning",+ "type": "default"+ },+ {+ "id": "edge-model_loader-audio_vae-extend_conditioning-audio_vae",+ "source": "model_loader",+ "sourceHandle": "audio_vae",+ "target": "extend_conditioning",+ "targetHandle": "audio_vae",+ "type": "default"+ },+ {+ "id": "edge-model_loader-vocoder-extend_conditioning-vocoder",+ "source": "model_loader",+ "sourceHandle": "vocoder",+ "target": "extend_conditioning",+ "targetHandle": "vocoder",+ "type": "default"+ },+ {+ "id": "edge-source_video-fps-extend_conditioning-fps",+ "source": "source_video",+ "sourceHandle": "fps",+ "target": "extend_conditioning",+ "targetHandle": "fps",+ "type": "default"+ },+ {+ "id": "edge-extend_conditioning-audio_conditioning-denoise_latents-audio_prefix_conditioning",+ "source": "extend_conditioning",+ "sourceHandle": "audio_conditioning",+ "target": "denoise_latents",+ "targetHandle": "audio_prefix_conditioning",+ "type": "default"+ },+ {+ "id": "edge-extend_conditioning-context_frames-video_output-transition_frames",+ "source": "extend_conditioning",+ "sourceHandle": "context_frames",+ "target": "video_output",+ "targetHandle": "transition_frames",+ "type": "default"+ },+ {+ "id": "edge-source_video-fps-denoise_latents-fps",+ "source": "source_video",+ "sourceHandle": "fps",+ "target": "denoise_latents",+ "targetHandle": "fps",+ "type": "default"+ },+ {+ "id": "edge-source_video-fps-extension_clip-fps",+ "source": "source_video",+ "sourceHandle": "fps",+ "target": "extension_clip",+ "targetHandle": "fps",+ "type": "default"+ },+ {+ "id": "edge-seed-value-core_metadata-seed",+ "source": "seed",+ "sourceHandle": "value",+ "target": "core_metadata",+ "targetHandle": "seed",+ "type": "default"+ },+ {+ "id": "edge-positive_prompt-value-core_metadata-positive_prompt",+ "source": "positive_prompt",+ "sourceHandle": "value",+ "target": "core_metadata",+ "targetHandle": "positive_prompt",+ "type": "default"+ },+ {+ "id": "edge-negative_prompt-value-core_metadata-negative_prompt",+ "source": "negative_prompt",+ "sourceHandle": "value",+ "target": "core_metadata",+ "targetHandle": "negative_prompt",+ "type": "default"+ },+ {+ "id": "edge-core_metadata-metadata-extension_clip-metadata",+ "source": "core_metadata",+ "sourceHandle": "metadata",+ "target": "extension_clip",+ "targetHandle": "metadata",+ "type": "default"+ },+ {+ "id": "edge-core_metadata-metadata-video_output-metadata",+ "source": "core_metadata",+ "sourceHandle": "metadata",+ "target": "video_output",+ "targetHandle": "metadata",+ "type": "default"+ },+ {+ "id": "edge-source_video-width-ideal_dimensions-width",+ "source": "source_video",+ "sourceHandle": "width",+ "target": "ideal_dimensions",+ "targetHandle": "width",+ "type": "default"+ },+ {+ "id": "edge-ideal_dimensions-base_width-denoise_latents-width",+ "source": "ideal_dimensions",+ "sourceHandle": "base_width",+ "target": "denoise_latents",+ "targetHandle": "width",+ "type": "default"+ },+ {+ "id": "edge-ideal_dimensions-base_width-extend_conditioning-width",+ "source": "ideal_dimensions",+ "sourceHandle": "base_width",+ "target": "extend_conditioning",+ "targetHandle": "width",+ "type": "default"+ },+ {+ "id": "edge-ideal_dimensions-base_width-core_metadata-width",+ "source": "ideal_dimensions",+ "sourceHandle": "base_width",+ "target": "core_metadata",+ "targetHandle": "width",+ "type": "default"+ },+ {+ "id": "edge-source_video-height-ideal_dimensions-height",+ "source": "source_video",+ "sourceHandle": "height",+ "target": "ideal_dimensions",+ "targetHandle": "height",+ "type": "default"+ },+ {+ "id": "edge-ideal_dimensions-base_height-denoise_latents-height",+ "source": "ideal_dimensions",+ "sourceHandle": "base_height",+ "target": "denoise_latents",+ "targetHandle": "height",+ "type": "default"+ },+ {+ "id": "edge-ideal_dimensions-base_height-extend_conditioning-height",+ "source": "ideal_dimensions",+ "sourceHandle": "base_height",+ "target": "extend_conditioning",+ "targetHandle": "height",+ "type": "default"+ },+ {+ "id": "edge-ideal_dimensions-base_height-core_metadata-height",+ "source": "ideal_dimensions",+ "sourceHandle": "base_height",+ "target": "core_metadata",+ "targetHandle": "height",+ "type": "default"+ },+ {+ "id": "edge-steps-value-denoise_latents-steps",+ "source": "steps",+ "sourceHandle": "value",+ "target": "denoise_latents",+ "targetHandle": "steps",+ "type": "default"+ },+ {+ "id": "edge-steps-value-core_metadata-steps",+ "source": "steps",+ "sourceHandle": "value",+ "target": "core_metadata",+ "targetHandle": "steps",+ "type": "default"+ },+ {+ "id": "edge-denoise_latents-num_frames-core_metadata-num_frames",+ "source": "denoise_latents",+ "sourceHandle": "num_frames",+ "target": "core_metadata",+ "targetHandle": "num_frames",+ "type": "default"+ },+ {+ "id": "edge-model_loader-model-core_metadata-model",+ "source": "model_loader",+ "sourceHandle": "model",+ "target": "core_metadata",+ "targetHandle": "model",+ "type": "default"+ }+ ],+ "form": {+ "elements": {+ "heading-initial-video": {+ "id": "heading-initial-video",+ "type": "heading",+ "parentId": "root",+ "data": { "content": "Initial Video" }+ },+ "field-source_video-video": {+ "id": "field-source_video-video",+ "type": "node-field",+ "parentId": "root",+ "data": {+ "fieldIdentifier": { "nodeId": "source_video", "fieldName": "video" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "field-source_video-start_frame": {+ "id": "field-source_video-start_frame",+ "type": "node-field",+ "parentId": "container-trim",+ "data": {+ "fieldIdentifier": { "nodeId": "source_video", "fieldName": "start_frame" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "field-source_video-end_frame": {+ "id": "field-source_video-end_frame",+ "type": "node-field",+ "parentId": "container-trim",+ "data": {+ "fieldIdentifier": { "nodeId": "source_video", "fieldName": "end_frame" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "container-trim": {+ "id": "container-trim",+ "type": "container",+ "parentId": "root",+ "data": { "layout": "row", "children": ["field-source_video-start_frame", "field-source_video-end_frame"] }+ },+ "field-extend_conditioning-context_frames": {+ "id": "field-extend_conditioning-context_frames",+ "type": "node-field",+ "parentId": "root",+ "data": {+ "fieldIdentifier": { "nodeId": "extend_conditioning", "fieldName": "context_frames" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "heading-extension": {+ "id": "heading-extension",+ "type": "heading",+ "parentId": "root",+ "data": { "content": "Extension" }+ },+ "field-positive_prompt-value": {+ "id": "field-positive_prompt-value",+ "type": "node-field",+ "parentId": "root",+ "data": {+ "fieldIdentifier": { "nodeId": "positive_prompt", "fieldName": "value" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "field-negative_prompt-value": {+ "id": "field-negative_prompt-value",+ "type": "node-field",+ "parentId": "root",+ "data": {+ "fieldIdentifier": { "nodeId": "negative_prompt", "fieldName": "value" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "field-ideal_dimensions-target_resolution": {+ "id": "field-ideal_dimensions-target_resolution",+ "type": "node-field",+ "parentId": "container-continuation",+ "data": {+ "fieldIdentifier": { "nodeId": "ideal_dimensions", "fieldName": "target_resolution" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "field-denoise_latents-num_frames": {+ "id": "field-denoise_latents-num_frames",+ "type": "node-field",+ "parentId": "container-continuation",+ "data": {+ "fieldIdentifier": { "nodeId": "denoise_latents", "fieldName": "num_frames" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "container-continuation": {+ "id": "container-continuation",+ "type": "container",+ "parentId": "root",+ "data": {+ "layout": "row",+ "children": ["field-ideal_dimensions-target_resolution", "field-denoise_latents-num_frames"]+ }+ },+ "field-steps-value": {+ "id": "field-steps-value",+ "type": "node-field",+ "parentId": "container-sampling",+ "data": {+ "fieldIdentifier": { "nodeId": "steps", "fieldName": "value" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "field-seed-value": {+ "id": "field-seed-value",+ "type": "node-field",+ "parentId": "container-sampling",+ "data": {+ "fieldIdentifier": { "nodeId": "seed", "fieldName": "value" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "container-sampling": {+ "id": "container-sampling",+ "type": "container",+ "parentId": "root",+ "data": { "layout": "row", "children": ["field-steps-value", "field-seed-value"] }+ },+ "heading-model": {+ "id": "heading-model",+ "type": "heading",+ "parentId": "root",+ "data": { "content": "Model" }+ },+ "field-model_loader-model": {+ "id": "field-model_loader-model",+ "type": "node-field",+ "parentId": "root",+ "data": {+ "fieldIdentifier": { "nodeId": "model_loader", "fieldName": "model" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "field-model_loader-component_source": {+ "id": "field-model_loader-component_source",+ "type": "node-field",+ "parentId": "root",+ "data": {+ "fieldIdentifier": { "nodeId": "model_loader", "fieldName": "component_source" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "field-model_loader-text_encoder_model": {+ "id": "field-model_loader-text_encoder_model",+ "type": "node-field",+ "parentId": "root",+ "data": {+ "fieldIdentifier": { "nodeId": "model_loader", "fieldName": "text_encoder_model" },+ "showDescription": true,+ "showShuffle": false+ }+ },+ "root": {+ "id": "root",+ "type": "container",+ "data": {+ "layout": "column",+ "children": [+ "heading-initial-video",+ "field-source_video-video",+ "container-trim",+ "field-extend_conditioning-context_frames",+ "heading-extension",+ "field-positive_prompt-value",+ "field-negative_prompt-value",+ "container-continuation",+ "container-sampling",+ "heading-model",+ "field-model_loader-model",+ "field-model_loader-component_source",+ "field-model_loader-text_encoder_model"+ ]+ }+ }+ },+ "rootElementId": "root"+ },+ "id": "default_ltx2_extend"+ }+}diff --git a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.tsindex d2fd572579..10f779c10b 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts@@ -1,4 +1,10 @@-import type { FieldInputTemplate, InvocationTemplates, ProjectGraphState } from './types';+import type {+ FieldInputTemplate,+ InvocationTemplate,+ InvocationTemplates,+ ProjectGraphState,+ WorkflowInvocationNode,+} from './types';import { isLoraFieldCollectionEntry, isModelFieldType, toLoraFieldCollectionList } from './fields';import { isInvocationNode } from './types';@@ -188,114 +194,173 @@ const computePrimaryBase = (requirements: readonly WorkflowModelRequirement[]):};/**- * Classify concrete model identifiers as exact requirements and empty required inputs as slots; skip- * connection-fed inputs owned upstream.+ * Visits the model each of a node's model fields names, and each required model field left empty; connection-fed+ * inputs are owned upstream and skipped.*/-export const extractWorkflowModelRequirements = (- document: ProjectGraphState,- templates: InvocationTemplates-): WorkflowModelRequirementSet => {- const connectionTargets = new Set(document.edges.map((edge) => `${edge.target}::${edge.targetHandle}`));-- const requirements: WorkflowModelRequirement[] = [];- const exactKeyHashes = new Map<string, string | undefined>();- const seenExactDedupeKeys = new Set<string>();- const seenSlotSignatures = new Set<string>();-- for (const node of document.nodes) {- if (!isInvocationNode(node)) {+const visitNodeModelNeeds = (+ node: WorkflowInvocationNode,+ template: InvocationTemplate,+ connectionTargets: ReadonlySet<string>,+ visitExact: (value: DuckTypedModelValue, fieldName: string) => void,+ visitSlot: (requirement: Extract<WorkflowModelRequirement, { kind: 'slot' }>, fieldName: string) => void+): void => {+ for (const fieldTemplate of Object.values({ ...template.inputs, ...node.data.dynamicInputTemplates })) {+ const isLoraCollection = fieldTemplate.type.name === 'LoRAField';++ if (!isModelFieldType(fieldTemplate.type) && !isLoraCollection) {continue;}- const template = templates[node.data.type];-- if (!template) {+ if (connectionTargets.has(`${node.id}::${fieldTemplate.name}`)) {continue;}- const addExactRequirement = (value: unknown): void => {- if (!isDuckTypedModelValue(value)) {- return;- }-- const identifier = buildIdentifier(value);-- let dedupeKey = identifier.key;+ const value = node.data.inputs[fieldTemplate.name]?.value;- if (exactKeyHashes.has(identifier.key)) {- const existingHash = exactKeyHashes.get(identifier.key);+ // Inspect nested identifiers in LoRA collections so their requirements match equivalent selector-node+ // graphs.+ if (isLoraCollection) {+ const entries = toLoraFieldCollectionList(value);- if (identifier.hash !== undefined && existingHash !== undefined && existingHash !== identifier.hash) {- dedupeKey = `${identifier.key}::${identifier.hash}`;+ for (const entry of entries) {+ if (isLoraFieldCollectionEntry(entry) && isDuckTypedModelValue(entry.lora)) {+ visitExact(entry.lora, fieldTemplate.name);}- } else {- exactKeyHashes.set(identifier.key, identifier.hash);}- if (seenExactDedupeKeys.has(dedupeKey)) {- return;+ // An empty collection still falls through to the slot path below, so a required-but-blank+ // field keeps describing what it needs the way every other blank model field does.+ if (entries.length > 0) {+ continue;}+ }- seenExactDedupeKeys.add(dedupeKey);- requirements.push({ identifier, kind: 'exact', label: identifier.name ?? identifier.key });- };+ if (isDuckTypedModelValue(value)) {+ visitExact(value, fieldTemplate.name);+ continue;+ }- for (const fieldTemplate of Object.values({ ...template.inputs, ...node.data.dynamicInputTemplates })) {- const isLoraCollection = fieldTemplate.type.name === 'LoRAField';+ if (!fieldTemplate.required) {+ continue;+ }- if (!isModelFieldType(fieldTemplate.type) && !isLoraCollection) {- continue;- }+ const base = fieldTemplate.uiModelBase?.[0] ?? null;+ const modelType = fieldTemplate.uiModelType?.[0] ?? null;- if (connectionTargets.has(`${node.id}::${fieldTemplate.name}`)) {- continue;- }+ visitSlot(+ { base, kind: 'slot', label: buildSlotLabel(fieldTemplate, base, modelType), modelType },+ fieldTemplate.name+ );+ }+};- const value = node.data.inputs[fieldTemplate.name]?.value;+const getConnectionTargets = (document: ProjectGraphState): Set<string> =>+ new Set(document.edges.map((edge) => `${edge.target}::${edge.targetHandle}`));- // Inspect nested identifiers in LoRA collections so their requirements match equivalent selector-node- // graphs.- if (isLoraCollection) {- const entries = toLoraFieldCollectionList(value);+/** Classify concrete model identifiers as exact requirements and empty required inputs as slots. */+export const extractWorkflowModelRequirements = (+ document: ProjectGraphState,+ templates: InvocationTemplates+): WorkflowModelRequirementSet => {+ const connectionTargets = getConnectionTargets(document);- for (const entry of entries) {- if (isLoraFieldCollectionEntry(entry)) {- addExactRequirement(entry.lora);- }- }+ const requirements: WorkflowModelRequirement[] = [];+ const exactKeyHashes = new Map<string, string | undefined>();+ const seenExactDedupeKeys = new Set<string>();+ const seenSlotSignatures = new Set<string>();- // An empty collection still falls through to the slot path below, so a required-but-blank- // field keeps describing what it needs the way every other blank model field does.- if (entries.length > 0) {- continue;- }- }+ const addExactRequirement = (value: DuckTypedModelValue): void => {+ const identifier = buildIdentifier(value);- if (isDuckTypedModelValue(value)) {- addExactRequirement(value);- continue;- }+ let dedupeKey = identifier.key;- if (!fieldTemplate.required) {- continue;+ if (exactKeyHashes.has(identifier.key)) {+ const existingHash = exactKeyHashes.get(identifier.key);++ if (identifier.hash !== undefined && existingHash !== undefined && existingHash !== identifier.hash) {+ dedupeKey = `${identifier.key}::${identifier.hash}`;}+ } else {+ exactKeyHashes.set(identifier.key, identifier.hash);+ }- const base = fieldTemplate.uiModelBase?.[0] ?? null;- const modelType = fieldTemplate.uiModelType?.[0] ?? null;- const signature = `${base ?? ''}::${modelType ?? ''}`;+ if (seenExactDedupeKeys.has(dedupeKey)) {+ return;+ }- if (seenSlotSignatures.has(signature)) {- continue;- }+ seenExactDedupeKeys.add(dedupeKey);+ requirements.push({ identifier, kind: 'exact', label: identifier.name ?? identifier.key });+ };+ const addSlotRequirement = (requirement: Extract<WorkflowModelRequirement, { kind: 'slot' }>): void => {+ const signature = `${requirement.base ?? ''}::${requirement.modelType ?? ''}`;+ if (!seenSlotSignatures.has(signature)) {seenSlotSignatures.add(signature);- requirements.push({ base, kind: 'slot', label: buildSlotLabel(fieldTemplate, base, modelType), modelType });+ requirements.push(requirement);+ }+ };++ for (const node of document.nodes) {+ const template =+ isInvocationNode(node) && Object.hasOwn(templates, node.data.type) ? templates[node.data.type] : undefined;++ if (isInvocationNode(node) && template) {+ visitNodeModelNeeds(node, template, connectionTargets, addExactRequirement, addSlotRequirement);}}return { primaryBase: computePrimaryBase(requirements), requirements };};+/** One model field's requirement: the model it names, or the kind it needs while empty. */+export interface WorkflowFieldModelRequirement {+ fieldName: string;+ requirement: WorkflowModelRequirement;+}++/**+ * The same requirements per invocation node and field, so a view can mark the node or the input that needs a model.+ * A node lists each model it names and each empty required model field; nodes with neither are absent.+ */+export const extractNodeModelRequirements = (+ document: ProjectGraphState,+ templates: InvocationTemplates+): ReadonlyMap<string, readonly WorkflowFieldModelRequirement[]> => {+ const connectionTargets = getConnectionTargets(document);+ const byNode = new Map<string, WorkflowFieldModelRequirement[]>();++ for (const node of document.nodes) {+ const template =+ isInvocationNode(node) && Object.hasOwn(templates, node.data.type) ? templates[node.data.type] : undefined;++ if (!isInvocationNode(node) || !template) {+ continue;+ }++ const requirements: WorkflowFieldModelRequirement[] = [];++ visitNodeModelNeeds(+ node,+ template,+ connectionTargets,+ (value, fieldName) => {+ const identifier = buildIdentifier(value);+ requirements.push({+ fieldName,+ requirement: { identifier, kind: 'exact', label: identifier.name ?? identifier.key },+ });+ },+ (requirement, fieldName) => requirements.push({ fieldName, requirement })+ );++ if (requirements.length > 0) {+ byNode.set(node.id, requirements);+ }+ }++ return byNode;+};+export interface InstalledModelSummary {key: string;hash: string;diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowPreview.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowPreview.test.tsnew file mode 100644index 0000000000..a152e82f8e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowPreview.test.ts@@ -0,0 +1,823 @@+import { describe, expect, it } from 'vitest';++import type {+ FieldInputTemplate,+ FieldType,+ InvocationTemplate,+ InvocationTemplates,+ ProjectGraphState,+ WorkflowEdge,+ WorkflowFormElement,+ WorkflowInvocationNode,+} from './types';++import extendVideo from './fixtures/extend-video-ltx2.json';+import { parseWorkflowJson } from './workflowJson';+import {+ buildWorkflowPreviewModel,+ chooseWorkflowPreviewChipWidth,+ compiledGraphToPreviewDocument,+ getWorkflowPreviewMetrics,+ findWorkflowPreviewNodes,+ WORKFLOW_PREVIEW_METRICS,+ type WorkflowPreviewMetrics,+ type WorkflowPreviewModel,+} from './workflowPreview';++const METRICS: WorkflowPreviewMetrics = {+ authorScale: 0.5,+ layerGap: 40,+ nodeHeight: 50,+ nodeWidth: 100,+ pillHeight: 20,+ rowGap: 10,+};++const type = (name: string, cardinality: FieldType['cardinality'] = 'SINGLE'): FieldType => ({+ batch: false,+ cardinality,+ name,+});++const input = (+ name: string,+ fieldType: FieldType,+ overrides: Partial<FieldInputTemplate> = {}+): FieldInputTemplate => ({+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ fieldKind: 'input',+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name,+ options: null,+ required: false,+ title: name.replace(/^./, (letter) => letter.toUpperCase()),+ type: fieldType,+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelFormat: null,+ uiModelType: null,+ uiOrder: null,+ ...overrides,+});++const template = (name: string, title: string, inputs: FieldInputTemplate[]): InvocationTemplate => ({+ category: 'test',+ classification: 'stable',+ description: '',+ inputs: Object.fromEntries(inputs.map((field) => [field.name, field])),+ nodePack: 'invokeai',+ outputs: {},+ outputType: `${name}_output`,+ tags: [],+ title,+ type: name,+ useCache: true,+ version: '1.0.0',+});++const TEMPLATES: InvocationTemplates = {+ collect: template('collect', 'Collect', [input('item', type('AnyField'))]),+ core_metadata: template('core_metadata', 'Metadata', [input('seed', type('IntegerField'))]),+ denoise: template('denoise', 'Denoise Latents', [+ input('steps', type('IntegerField')),+ input('cfg_scale', type('FloatField')),+ input('noise', type('LatentsField')),+ input('positive', type('ConditioningField')),+ input('seed', type('IntegerField')),+ ]),+ image_batch: template('image_batch', 'Image Batch', [input('images', type('ImageField', 'COLLECTION'))]),+ integer: template('integer', 'Integer Primitive', [input('value', type('IntegerField'))]),+ l2i: template('l2i', 'Latents to Image', [+ input('latents', type('LatentsField')),+ input('metadata', type('MetadataField')),+ ]),+ model_loader: template('model_loader', 'Main Model', [+ input('model', type('ModelIdentifierField'), { required: true, uiModelBase: ['sdxl'], uiModelType: ['main'] }),+ ]),+ prompt: template('prompt', 'Prompt', [input('prompt', type('StringField'))]),+ string: template('string', 'String Primitive', [input('value', type('StringField'))]),+};++const node = (+ id: string,+ nodeType: string,+ values: Record<string, unknown> = {},+ extras: { label?: string; notes?: string; fieldLabels?: Record<string, string> } = {}+): WorkflowInvocationNode => ({+ data: {+ inputs: Object.fromEntries(+ Object.entries(values).map(([name, value]) => [name, { label: extras.fieldLabels?.[name] ?? '', name, value }])+ ),+ isIntermediate: true,+ isOpen: true,+ label: extras.label ?? '',+ nodePack: 'invokeai',+ notes: extras.notes ?? '',+ type: nodeType,+ useCache: true,+ version: '1.0.0',+ },+ id,+ position: { x: id.length * 10, y: 0 },+ type: 'invocation',+});++const edge = (source: string, target: string, targetHandle: string, sourceHandle = 'value'): WorkflowEdge => ({+ id: `${source}-${target}-${targetHandle}`,+ source,+ sourceHandle,+ target,+ targetHandle,+ type: 'default',+});++const exposed = (...fields: [nodeId: string, fieldName: string][]): ProjectGraphState['form'] => {+ const elements: Record<string, WorkflowFormElement> = {+ root: {+ data: { children: fields.map((_, index) => `field-${index}`), layout: 'column' },+ id: 'root',+ type: 'container',+ },+ };++ fields.forEach(([nodeId, fieldName], index) => {+ elements[`field-${index}`] = {+ data: { fieldIdentifier: { fieldName, nodeId }, showDescription: false, showShuffle: false },+ id: `field-${index}`,+ parentId: 'root',+ type: 'node-field',+ };+ });++ return { elements, rootElementId: 'root' };+};++const graph = (+ nodes: WorkflowInvocationNode[],+ edges: WorkflowEdge[],+ form: ProjectGraphState['form'] = exposed()+): ProjectGraphState => ({+ author: '',+ contact: '',+ description: '',+ edges,+ form,+ id: 'preview-test',+ name: 'Preview test',+ nodes,+ notes: '',+ tags: '',+ updatedAt: '2026-01-01T00:00:00.000Z',+ version: 2,+ workflowVersion: '1.0.0',+});++/**+ * A text-to-image graph: prompt and seed primitives, a model loader, a collect feeding the denoiser, and metadata+ * recording the seed on the decoder.+ */+const TEXT_TO_IMAGE = graph(+ [+ node('positive', 'string', { value: 'a lighthouse at dusk, long exposure, film grain and soft haze' }),+ node('seed', 'integer', { value: 7 }),+ node('model', 'model_loader', { model: undefined }),+ node('prompt', 'prompt', { prompt: '' }, { label: 'Prompt - SDXL', notes: 'Encodes the positive prompt.' }),+ node('collect', 'collect'),+ node('denoise', 'denoise', { cfg_scale: 4.5, seed: 0, steps: 30 }, { fieldLabels: { steps: 'Sampling steps' } }),+ node('metadata', 'core_metadata'),+ node('decode', 'l2i'),+ ],+ [+ edge('positive', 'prompt', 'prompt'),+ edge('model', 'prompt', 'clip', 'clip'),+ edge('prompt', 'collect', 'item', 'conditioning'),+ edge('collect', 'denoise', 'positive', 'collection'),+ edge('seed', 'denoise', 'seed'),+ edge('seed', 'metadata', 'seed'),+ edge('model', 'metadata', 'model', 'unet'),+ edge('denoise', 'decode', 'latents', 'latents'),+ edge('metadata', 'decode', 'metadata', 'metadata'),+ ],+ exposed(['positive', 'value'], ['denoise', 'steps'])+);++const build = (document: ProjectGraphState) => buildWorkflowPreviewModel(document, TEMPLATES, METRICS);+const titles = (model: WorkflowPreviewModel, ids: readonly string[]) => ids.map((id) => model.nodes.get(id)!.title);++describe('buildWorkflowPreviewModel', () => {+ it.each(['toString', 'constructor', '__proto__'])('previews a parsed unknown node type named %s', (name) => {+ const parsed = parseWorkflowJson(graph([node('unknown', name, { value: 'saved' })], []));+ const model = build(parsed.document);++ expect(model.nodes.get('unknown')).toMatchObject({ isUnknown: true, title: name });+ expect(model.nodes.get('unknown')!.fields).toEqual([+ { isExposed: false, label: 'value', name: 'value', value: { kind: 'text', text: 'saved' } },+ ]);+ });++ it.each(['toString', 'constructor', '__proto__'])(+ 'previews a parsed form field named %s without an inherited template',+ (name) => {+ const parsed = parseWorkflowJson(graph([node('primitive', 'string')], [], exposed(['primitive', name])));+ const model = build(parsed.document);++ expect(model.inputs).toMatchObject([{ fieldName: name, isModelField: false, label: name, value: null }]);+ }+ );++ it.each(['string_split_neg', 'custom_prompt'])(+ 'keeps single-input computation %s visible in the simplified view',+ (name) => {+ const document = graph(+ [+ node('seed', 'integer', { value: 1 }),+ node('compute', name, { value: 'cat [dog]' }),+ node('positive', 'prompt'),+ node('negative', 'prompt'),+ ],+ [+ edge('seed', 'positive', 'seed'),+ edge('compute', 'positive', 'prompt', 'positive'),+ edge('compute', 'negative', 'prompt', 'negative'),+ ]+ );+ const model = buildWorkflowPreviewModel(+ document,+ {+ ...TEMPLATES,+ [name]: template(name, 'Compute prompt', [input('value', type('StringField'))]),+ },+ METRICS+ );++ expect(model.simplified!.nodeIds).toContain('compute');+ expect(model.simplified!.pills.negative).toBeUndefined();+ expect(model.simplified!.edges).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ source: 'compute', target: 'positive' }),+ expect.objectContaining({ source: 'compute', target: 'negative' }),+ ])+ );+ }+ );++ it('names nodes by their own label, then their template, then their type id, and marks an unknown type', () => {+ const model = build(+ graph(+ [node('prompt', 'prompt', {}, { label: 'Prompt - SDXL' }), node('seed', 'integer'), node('x', 'face_mask')],+ []+ )+ );++ expect(model.nodes.get('prompt')!.title).toBe('Prompt - SDXL');+ expect(model.nodes.get('seed')!.title).toBe('Integer Primitive');+ expect(model.nodes.get('x')).toMatchObject({ isUnknown: true, title: 'face_mask' });+ expect(model.nodes.get('seed')!.isUnknown).toBe(false);+ });++ it('lists a node’s own values with field labels, leaving out connected and empty inputs', () => {+ const model = build(TEXT_TO_IMAGE);++ // `seed` is fed by the seed primitive, so its stale 0 is not the node's own value.+ expect(model.nodes.get('denoise')!.fields).toEqual([+ { isExposed: true, label: 'Sampling steps', name: 'steps', value: { kind: 'number', value: 30 } },+ { isExposed: false, label: 'Cfg_scale', name: 'cfg_scale', value: { kind: 'number', value: 4.5 } },+ ]);+ expect(model.nodes.get('prompt')!.fields).toEqual([]);+ expect(model.nodes.get('prompt')!.notes).toBe('Encodes the positive prompt.');+ });++ it('marks exposed nodes, results and the model fields a node still needs', () => {+ const model = build(TEXT_TO_IMAGE);+ const marked = (key: 'isExposed' | 'isResult') =>+ [...model.nodes.values()].filter((candidate) => candidate[key]).map((candidate) => candidate.id);++ expect(marked('isExposed')).toEqual(['positive', 'denoise']);+ // The decoder feeds nothing; metadata and the primitives are helpers, never results.+ expect(marked('isResult')).toEqual(['decode']);+ expect(model.nodes.get('model')!.modelRequirements).toEqual([+ { base: 'sdxl', kind: 'slot', label: 'SDXL checkpoint', modelType: 'main' },+ ]);+ expect(model.nodes.get('denoise')!.modelRequirements).toEqual([]);+ });++ it('orders nodes and their neighbours topologically', () => {+ const model = build(TEXT_TO_IMAGE);++ expect(model.all.nodeIds).toEqual([+ 'positive',+ 'seed',+ 'model',+ 'prompt',+ 'metadata',+ 'collect',+ 'denoise',+ 'decode',+ ]);+ expect(model.all.neighbours.denoise).toEqual({ sources: ['seed', 'collect'], targets: ['decode'] });+ expect(model.simplified!.neighbours.denoise).toEqual({ sources: ['prompt'], targets: ['decode'] });+ });++ it('draws every node in the author’s arrangement in the full view, scaled to the chips, one edge per pair', () => {+ const a = { ...node('a', 'integer', { value: 1 }), position: { x: -400, y: 300 } };+ const b = { ...node('b', 'denoise'), position: { x: 200, y: 100 } };+ const model = build(graph([a, b], [edge('a', 'b', 'steps'), edge('a', 'b', 'seed')]));++ // Moved to the origin and halved: editor nodes are about twice a chip's size.+ expect(model.all.positions).toEqual({ a: { x: 0, y: 100 }, b: { x: 300, y: 0 } });+ expect(model.all.edges).toHaveLength(1);+ expect(model.all.pills).toEqual({});+ });++ it('folds value-only primitives into pills on their consumers and hides plumbing, rerouting through a collect', () => {+ const { nodes, simplified } = build(TEXT_TO_IMAGE);++ expect(simplified).not.toBeNull();+ expect(titles({ nodes } as WorkflowPreviewModel, simplified!.nodeIds)).toEqual([+ 'Main Model',+ 'Prompt - SDXL',+ 'Denoise Latents',+ 'Latents to Image',+ ]);+ // The exposed prompt is labelled as the form labels it, its long value left off; the seed shows its value.+ expect(simplified!.pills).toEqual({+ denoise: [{ label: 'Integer Primitive', nodeId: 'seed', value: { kind: 'number', value: 7 } }],+ prompt: [{ label: 'Value', nodeId: 'positive', value: null }],+ });+ // The collect is rerouted; metadata only records what reaches it, so the seed and model get no line to the decoder.+ expect(simplified!.pills.decode).toBeUndefined();+ expect(+ simplified!.edges.map(+ ({ isRerouted, source, target }) => `${source}->${target}${isRerouted ? ' (rerouted)' : ''}`+ )+ ).toEqual(['model->prompt', 'denoise->decode', 'prompt->denoise (rerouted)']);+ });++ it('lays the simplified view out in layers, leaving room above a node for its pills', () => {+ const { simplified } = build(TEXT_TO_IMAGE);+ const { positions } = simplified!;++ expect(positions.model!.x).toBeLessThan(positions.prompt!.x);+ expect(positions.prompt!.x).toBeLessThan(positions.denoise!.x);+ expect(positions.denoise!.x).toBeLessThan(positions.decode!.x);+ // Layer pitch is the node width plus the gap.+ expect(positions.prompt!.x - positions.model!.x).toBe(METRICS.nodeWidth + METRICS.layerGap);++ // In one layer, a node with a pill keeps the row gap between the chip above and its pill, not its chip.+ const stacked = build(+ graph(+ [+ node('model', 'model_loader'),+ node('seed', 'integer', { value: 1 }),+ node('a', 'denoise'),+ node('b', 'denoise'),+ ],+ [edge('model', 'a', 'noise', 'unet'), edge('model', 'b', 'noise', 'unet'), edge('seed', 'b', 'seed')]+ )+ ).simplified!;++ expect(stacked.pills.b).toHaveLength(1);+ expect(stacked.positions.b!.y - stacked.positions.a!.y).toBe(+ METRICS.nodeHeight + METRICS.rowGap + METRICS.pillHeight+ );+ });++ it('levels a chain’s chips whatever pills they carry, starting the topmost pill at 0', () => {+ // model -> prompt (two pills) -> denoise (none) -> decode (one pill).+ const { simplified } = build(+ graph(+ [+ node('model', 'model_loader'),+ node('positive', 'string', { value: 'a lighthouse' }),+ node('negative', 'string', { value: 'blurry' }),+ node('prompt', 'prompt'),+ node('denoise', 'denoise'),+ node('strength', 'integer', { value: 2 }),+ node('decode', 'l2i'),+ ],+ [+ edge('model', 'prompt', 'clip', 'clip'),+ edge('positive', 'prompt', 'prompt'),+ edge('negative', 'prompt', 'prompt'),+ edge('prompt', 'denoise', 'positive', 'conditioning'),+ edge('denoise', 'decode', 'latents', 'latents'),+ edge('strength', 'decode', 'metadata'),+ ]+ )+ );+ const { pills, positions } = simplified!;++ expect([pills.model?.length, pills.prompt?.length, pills.denoise?.length, pills.decode?.length]).toEqual([+ undefined,+ 2,+ undefined,+ 1,+ ]);+ // Every chip on one row, so every edge runs level, and the tallest pill stack fits above it from 0.+ expect(new Set(['model', 'prompt', 'denoise', 'decode'].map((id) => positions[id]!.y))).toEqual(+ new Set([2 * METRICS.pillHeight])+ );+ });++ it('keeps a primitive that feeds nothing, a collection primitive and a primitive fed by another node', () => {+ const model = build(+ graph(+ [+ node('lonely', 'integer', { value: 3 }),+ node('images', 'image_batch', { images: [{ image_name: 'a.png' }] }),+ node('source', 'integer', { value: 1 }),+ node('fed', 'integer'),+ node('denoise', 'denoise'),+ ],+ [edge('images', 'denoise', 'noise', 'images'), edge('source', 'fed', 'value'), edge('fed', 'denoise', 'steps')]+ )+ );++ expect(model.simplified!.nodeIds).toEqual(['lonely', 'images', 'fed', 'denoise']);+ expect(model.simplified!.pills).toEqual({+ fed: [{ label: 'Integer Primitive', nodeId: 'source', value: { kind: 'number', value: 1 } }],+ });+ expect(model.nodes.get('images')!.fields[0]!.value).toEqual({ count: 1, kind: 'list' });+ });++ it('has no simplified view when nothing folds or hides', () => {+ const model = build(+ graph([node('denoise', 'denoise'), node('decode', 'l2i')], [edge('denoise', 'decode', 'latents')])+ );++ expect(model.simplified).toBeNull();+ });++ it('previews a workflow that would not compile: a connection to a node type the server lacks', () => {+ const model = build(graph([node('mask', 'face_mask'), node('decode', 'l2i')], [edge('mask', 'decode', 'latents')]));++ expect(model.all.edges).toHaveLength(1);+ expect(model.all.neighbours.mask!.targets).toEqual(['decode']);+ });++ it('reads a choice by its template’s label', () => {+ const sampler: InvocationTemplates = {+ sampler: template('sampler', 'Sampler', [+ input('scheduler', type('EnumField'), { uiChoiceLabels: { dpmpp_2m_sde_k: 'DPM++ 2M SDE Karras' } }),+ input('mode', type('EnumField')),+ ]),+ };+ const model = buildWorkflowPreviewModel(+ graph([node('s', 'sampler', { mode: 'fast', scheduler: 'dpmpp_2m_sde_k' })], []),+ sampler,+ METRICS+ );++ expect(model.nodes.get('s')!.fields.map((field) => field.value)).toEqual([+ { kind: 'text', text: 'DPM++ 2M SDE Karras' },+ { kind: 'text', text: 'fast' },+ ]);+ });++ it('reads the form as authored, with each input’s saved value and the model it still needs', () => {+ const document = graph(+ [+ node('positive', 'string', { value: '' }, { fieldLabels: { value: 'Prompt' } }),+ node('model', 'model_loader'),+ node('denoise', 'denoise', { steps: 30 }),+ ],+ [],+ {+ elements: {+ heading: { data: { content: 'Prompt' }, id: 'heading', parentId: 'root', type: 'heading' },+ intro: { data: { content: 'Describe the scene.' }, id: 'intro', parentId: 'root', type: 'text' },+ 'field-positive': {+ data: {+ fieldIdentifier: { fieldName: 'value', nodeId: 'positive' },+ showDescription: false,+ showShuffle: false,+ },+ id: 'field-positive',+ parentId: 'row',+ type: 'node-field',+ },+ 'field-steps': {+ data: {+ fieldIdentifier: { fieldName: 'steps', nodeId: 'denoise' },+ showDescription: false,+ showShuffle: false,+ },+ id: 'field-steps',+ parentId: 'row',+ type: 'node-field',+ },+ 'field-gone': {+ data: {+ fieldIdentifier: { fieldName: 'value', nodeId: 'deleted' },+ showDescription: false,+ showShuffle: false,+ },+ id: 'field-gone',+ parentId: 'row',+ type: 'node-field',+ },+ row: {+ data: { children: ['field-positive', 'field-steps', 'field-gone'], layout: 'row' },+ id: 'row',+ type: 'container',+ },+ rule: { id: 'rule', parentId: 'root', type: 'divider' },+ 'heading-model': { data: { content: 'Model' }, id: 'heading-model', parentId: 'root', type: 'heading' },+ 'field-model': {+ data: {+ fieldIdentifier: { fieldName: 'model', nodeId: 'model' },+ showDescription: false,+ showShuffle: false,+ },+ id: 'field-model',+ parentId: 'root',+ type: 'node-field',+ },+ root: {+ data: { children: ['heading', 'intro', 'row', 'rule', 'heading-model', 'field-model'], layout: 'column' },+ id: 'root',+ type: 'container',+ },+ },+ rootElementId: 'root',+ }+ );+ const model = build(document);++ expect(model.form.map((item) => item.kind)).toEqual([+ 'heading',+ 'text',+ 'container',+ 'divider',+ 'heading',+ 'input',+ ]);+ expect(model.inputs).toEqual([+ {+ fieldName: 'value',+ id: 'field-positive',+ isModelField: false,+ label: 'Prompt',+ modelRequirements: [],+ nodeId: 'positive',+ nodeTitle: 'String Primitive',+ value: null,+ },+ {+ fieldName: 'steps',+ id: 'field-steps',+ isModelField: false,+ label: 'Steps',+ modelRequirements: [],+ nodeId: 'denoise',+ nodeTitle: 'Denoise Latents',+ value: { kind: 'number', value: 30 },+ },+ {+ fieldName: 'model',+ id: 'field-model',+ isModelField: true,+ label: 'Model',+ modelRequirements: [{ base: 'sdxl', kind: 'slot', label: 'SDXL checkpoint', modelType: 'main' }],+ nodeId: 'model',+ nodeTitle: 'Main Model',+ value: null,+ },+ ]);+ expect(model.inputGroups).toEqual([+ { heading: 'Prompt', labels: ['Prompt', 'Steps'] },+ { heading: 'Model', labels: ['Model'] },+ ]);+ });++ it('builds once per document, templates and metrics', () => {+ expect(build(TEXT_TO_IMAGE)).toBe(build(TEXT_TO_IMAGE));+ expect(buildWorkflowPreviewModel(TEXT_TO_IMAGE, { ...TEMPLATES }, METRICS)).not.toBe(build(TEXT_TO_IMAGE));+ });+});++describe('the Extend Video - LTX-2 template', () => {+ const document = parseWorkflowJson(extendVideo.workflow).document;+ const model = buildWorkflowPreviewModel(document, extendVideo.templates as unknown as InvocationTemplates);+ const { positions } = model.simplified!;++ it('labels a folded primitive by the form even while its value is empty', () => {+ expect(model.simplified!.pills.pos_cond!.map((pill) => pill.label)).toEqual(['Negative Prompt', 'Prompt']);+ });++ it('lays its eight drawn nodes out six columns wide, over rows kept well apart', () => {+ const { layerGap, nodeHeight, nodeWidth, pillHeight, rowGap } = WORKFLOW_PREVIEW_METRICS;+ const right = Math.max(...Object.values(positions).map((position) => position.x)) + nodeWidth;+ const pillsTop = (id: string) => positions[id]!.y - (model.simplified!.pills[id]?.length ?? 0) * pillHeight;++ expect(model.simplified!.nodeIds).toHaveLength(8);+ expect(right).toBe(6 * nodeWidth + 5 * layerGap);+ expect(new Set(Object.values(positions).map((position) => position.y)).size).toBeGreaterThan(4);++ // Within a column, each node's pills start below the chip above them by at least the row gap, and the topmost+ // pill, not the topmost chip, starts at 0.+ const columns = new Map<number, string[]>();+ for (const id of model.simplified!.nodeIds) {+ columns.set(positions[id]!.x, [...(columns.get(positions[id]!.x) ?? []), id]);+ }+ for (const ids of columns.values()) {+ const sorted = [...ids].sort((a, b) => positions[a]!.y - positions[b]!.y);+ for (const [index, id] of sorted.slice(1).entries()) {+ const above = sorted[index]!;+ expect(pillsTop(id) - (positions[above]!.y + nodeHeight), id).toBeGreaterThanOrEqual(rowGap);+ }+ }+ expect(Math.min(...model.simplified!.nodeIds.map(pillsTop))).toBe(0);+ // The denoiser's chip sits level with the middle of the chips feeding it, its two pills above it.+ const feeding = ['model_loader', 'pos_cond', 'extend_conditioning', 'source_video', 'ideal_dimensions'];+ expect(model.simplified!.pills.denoise_latents).toHaveLength(2);+ expect(positions.denoise_latents!.y).toBeCloseTo(+ feeding.reduce((sum, id) => sum + positions[id]!.y, 0) / feeding.length+ );+ });++ it('sums up a node by its first exposed input with a short value', () => {+ const summary = (id: string) => {+ const field = model.nodes.get(id)!.exposedSummary;+ return field ? [field.label, field.value] : null;+ };++ expect(summary('extend_conditioning')).toEqual(['Context Frames', { kind: 'number', value: 17 }]);+ expect(summary('ideal_dimensions')).toEqual(['Target Resolution', { kind: 'text', text: '704p (short edge 704)' }]);+ expect(summary('denoise_latents')).toEqual(['Number of Frames', { kind: 'number', value: 121 }]);+ expect(summary('pos_cond')).toBeNull();+ });++ it('groups the form’s inputs under its headings', () => {+ expect(model.inputs).toHaveLength(13);+ expect(model.inputGroups.map((group) => [group.heading, group.labels.length])).toEqual([+ ['Initial Video', 4],+ ['Extension', 6],+ ['Model', 3],+ ]);+ });+});++describe('findWorkflowPreviewNodes', () => {+ it('matches drawn nodes by title or type id, ignoring case, in keyboard order', () => {+ const model = build(TEXT_TO_IMAGE);++ expect(findWorkflowPreviewNodes(model, model.all, 'PRIM')).toEqual(['positive', 'seed']);+ expect(findWorkflowPreviewNodes(model, model.simplified!, 'l2i')).toEqual(['decode']);+ expect(findWorkflowPreviewNodes(model, model.all, ' ')).toEqual([]);+ });+});++describe('compiled graphs', () => {+ const COMPILED: Parameters<typeof compiledGraphToPreviewDocument>[0] = {+ edges: [+ { id: 'e1', sourceField: 'value', sourceNodeId: 'seed', targetField: 'seed', targetNodeId: 'denoise' },+ { id: 'e2', sourceField: 'latents', sourceNodeId: 'denoise', targetField: 'latents', targetNodeId: 'upscale' },+ ],+ id: 'generate-preview',+ label: 'Generate',+ nodes: [+ { id: 'seed', inputs: { id: 'seed', is_intermediate: true, type: 'integer', value: 42 }, type: 'integer' },+ { id: 'denoise', inputs: { cfg_scale: 4.5, steps: 30, use_cache: true }, type: 'denoise' },+ { id: 'upscale', inputs: { factor: 2 }, type: 'pack_upscale' },+ ],+ };++ it('draws every node, unknown types included, marking what was set and showing what runs', () => {+ const document = compiledGraphToPreviewDocument(COMPILED, {+ getSetLabel: (nodeId, fieldName) =>+ `${nodeId}.${fieldName}` === 'denoise.steps' ? 'Steps' : nodeId === 'seed' ? 'Seed' : null,+ metrics: METRICS,+ overrides: { seed: { value: 'regenerated each run' } },+ });+ const model = build(document);++ expect(model.all.nodeIds).toEqual(['seed', 'denoise', 'upscale']);+ expect(model.nodes.get('upscale')).toMatchObject({ isResult: true, isUnknown: true, title: 'pack_upscale' });+ expect(model.nodes.get('upscale')!.fields).toEqual([+ { isExposed: false, label: 'factor', name: 'factor', value: { kind: 'number', value: 2 } },+ ]);+ // The backend's bookkeeping is not a value; the steps were set, the scale was not.+ expect(model.nodes.get('denoise')!.fields.map((field) => [field.name, field.isExposed])).toEqual([+ ['steps', true],+ ['cfg_scale', false],+ ]);+ expect(model.nodes.get('denoise')!.isExposed).toBe(true);+ // The seed shows what runs rather than the placeholder it was compiled with, folded onto the denoiser.+ expect(model.simplified!.pills.denoise).toEqual([+ { label: 'Seed', nodeId: 'seed', value: { kind: 'text', text: 'regenerated each run' } },+ ]);+ // A layered arrangement in editor units, which the full view scales like an author's.+ const step = (METRICS.nodeWidth + METRICS.layerGap) / METRICS.authorScale;++ expect(document.nodes.map((node) => node.position)).toEqual([+ { x: 0, y: 0 },+ { x: step, y: 0 },+ { x: step * 2, y: 0 },+ ]);+ expect(model.all.positions.upscale).toEqual({ x: (METRICS.nodeWidth + METRICS.layerGap) * 2, y: 0 });+ });++ it('places nodes where the source hints', () => {+ const document = compiledGraphToPreviewDocument(COMPILED, { positionHints: { denoise: { x: 5, y: 6 } } });++ expect(document.nodes.find((node) => node.id === 'denoise')!.position).toEqual({ x: 5, y: 6 });+ });++ it('keys the structure on node ids, types and connections, in any order, not on values', () => {+ const key = (graph: Parameters<typeof compiledGraphToPreviewDocument>[0]) =>+ build(compiledGraphToPreviewDocument(graph)).structureKey;+ const recompiled = {+ ...COMPILED,+ nodes: COMPILED.nodes.map((node) => (node.id === 'denoise' ? { ...node, inputs: { steps: 12 } } : node)),+ };+ const reordered = { ...COMPILED, edges: [...COMPILED.edges].reverse(), nodes: [...COMPILED.nodes].reverse() };+ const retyped = {+ ...COMPILED,+ nodes: COMPILED.nodes.map((node) => (node.id === 'upscale' ? { ...node, type: 'l2i' } : node)),+ };+ const rewired = {+ ...COMPILED,+ edges: [+ ...COMPILED.edges,+ { id: 'e3', sourceField: 'value', sourceNodeId: 'seed', targetField: 'seed', targetNodeId: 'upscale' },+ ],+ };++ expect(key(recompiled)).toBe(key(COMPILED));+ expect(key(reordered)).toBe(key(COMPILED));+ expect(key(retyped)).not.toBe(key(COMPILED));+ expect(key(rewired)).not.toBe(key(COMPILED));+ });++ it('keeps what a recompile did not change, so a view redraws only what did', () => {+ const compile = (steps: number, seed: string) =>+ compiledGraphToPreviewDocument(+ {+ ...COMPILED,+ nodes: COMPILED.nodes.map((node) =>+ node.id === 'denoise' ? { ...node, inputs: { ...node.inputs, steps } } : node+ ),+ },+ { metrics: METRICS, overrides: { seed: { value: seed } } }+ );+ const first = build(compile(30, 'random'));+ const stepsChanged = buildWorkflowPreviewModel(compile(12, 'random'), TEMPLATES, METRICS, first);++ expect(stepsChanged.nodes.get('denoise')).not.toBe(first.nodes.get('denoise'));+ expect(stepsChanged.nodes.get('denoise')!.values.steps).toBe(12);+ expect(stepsChanged.nodes.get('seed')).toBe(first.nodes.get('seed'));+ expect(stepsChanged.nodes.get('upscale')).toBe(first.nodes.get('upscale'));+ expect(stepsChanged.all).toBe(first.all);+ expect(stepsChanged.simplified).toBe(first.simplified);++ // A pill's value changes only its row; the layout stays.+ const seedChanged = buildWorkflowPreviewModel(compile(12, 'fixed'), TEMPLATES, METRICS, stepsChanged);++ expect(seedChanged.simplified).not.toBe(stepsChanged.simplified);+ expect(seedChanged.simplified!.positions).toBe(stepsChanged.simplified!.positions);+ expect(seedChanged.simplified!.pills.denoise![0]!.value).toEqual({ kind: 'text', text: 'fixed' });+ });+});++describe('chip width', () => {+ it('is wide enough for the longest title, within 136 to 200 px, as wide as still fits', () => {+ const tried: number[] = [];+ const fitsUpTo = (limit: number) => (width: number) => {+ tried.push(width);+ return width <= limit;+ };++ expect(chooseWorkflowPreviewChipWidth(170.2, fitsUpTo(400))).toBe(171);+ expect(chooseWorkflowPreviewChipWidth(260, fitsUpTo(400))).toBe(200);+ expect(chooseWorkflowPreviewChipWidth(90, fitsUpTo(400))).toBe(136);+ // Where the widest does not fit, narrower steps are tried, down to the minimum.+ tried.length = 0;+ expect(chooseWorkflowPreviewChipWidth(200, fitsUpTo(170))).toBe(168);+ expect(tried).toEqual([200, 184, 168]);+ expect(chooseWorkflowPreviewChipWidth(200, () => false)).toBe(136);+ });++ it('lays a drawing out at its chip width, columns and the author’s arrangement widening with it', () => {+ const narrow = buildWorkflowPreviewModel(TEXT_TO_IMAGE, TEMPLATES, getWorkflowPreviewMetrics(136));+ const wide = buildWorkflowPreviewModel(TEXT_TO_IMAGE, TEMPLATES, getWorkflowPreviewMetrics(200));+ const { layerGap } = WORKFLOW_PREVIEW_METRICS;++ expect(getWorkflowPreviewMetrics(200)).toBe(getWorkflowPreviewMetrics(200));+ expect([narrow.all.nodeWidth, wide.all.nodeWidth, wide.simplified!.nodeWidth]).toEqual([136, 200, 200]);+ // Layered columns are a chip and a gap apart.+ const columns = (model: WorkflowPreviewModel) =>+ [...new Set(model.simplified!.nodeIds.map((id) => model.simplified!.positions[id]!.x))].sort((a, b) => a - b);+ expect(columns(wide).slice(0, 2)).toEqual([0, 200 + layerGap]);+ expect(columns(narrow).slice(0, 2)).toEqual([0, 136 + layerGap]);+ // The author's positions scale with the chips.+ expect(wide.all.positions.denoise!.x / narrow.all.positions.denoise!.x).toBeCloseTo(200 / 136);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/core/workflowPreview.ts b/invokeai/frontend/webv2/src/features/workflow/core/workflowPreview.tsnew file mode 100644index 0000000000..a9bec21706--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/core/workflowPreview.ts@@ -0,0 +1,965 @@+import type { PreviewGraphLike } from './graphToDocument';+import type { WorkflowModelRequirement } from './modelRequirements';+import type {+ FieldInputTemplate,+ InvocationTemplate,+ InvocationTemplates,+ ProjectGraphState,+ WorkflowFormElement,+ WorkflowInvocationNode,+ XYPosition,+} from './types';++import { isModelFieldType } from './fields';+import { getCanonicalWorkflowEdges } from './forLoops';+import { getNodeDepths, getTopologicalOrder } from './graphLayout';+import { extractNodeModelRequirements } from './modelRequirements';+import { isInvocationNode } from './types';++/**+ * The library's read-only preview of a saved workflow document: its nodes as the editor names them, the markers a+ * reader decides by, a simplified view that folds value-only helpers into the nodes they feed and hides plumbing, and+ * the form's inputs as authored. Drawn from the document, not the compiled graph, so a workflow that does not compile+ * still previews.+ */++/** A value as the preview shows it; the view words and formats each kind. */+export type WorkflowPreviewValue =+ | { kind: 'text'; text: string }+ | { kind: 'number'; value: number }+ | { kind: 'boolean'; value: boolean }+ | { kind: 'model'; name: string }+ | { kind: 'image'; name: string }+ | { kind: 'list'; count: number };++export interface WorkflowPreviewField {+ name: string;+ /** The author's label, else the template's title, else the field name. */+ label: string;+ value: WorkflowPreviewValue;+ /** The workflow's form exposes it. */+ isExposed: boolean;+}++export interface WorkflowPreviewNode {+ id: string;+ type: string;+ /** The node's own label, else its template's title, else its type id. */+ title: string;+ /** No template on this server: its node pack is missing. */+ isUnknown: boolean;+ /** The author's note on the node. */+ notes: string;+ /** Inputs with a value of their own (not fed by a connection), in template order. */+ fields: readonly WorkflowPreviewField[];+ /** The same inputs' raw values by field name, for type-specific summaries. */+ values: Readonly<Record<string, unknown>>;+ /** Its first exposed field with a value short enough for a one-line summary. */+ exposedSummary: WorkflowPreviewField | null;+ /** At least one of its fields is in the form. */+ isExposed: boolean;+ /** Nothing consumes it and it is not a helper: what the workflow makes. */+ isResult: boolean;+ /** Models it names and empty model fields it requires; the view resolves them against the catalog. */+ modelRequirements: readonly WorkflowModelRequirement[];+}++export interface WorkflowPreviewEdge {+ id: string;+ source: string;+ target: string;+ /** Drawn through hidden plumbing in the simplified view. */+ isRerouted: boolean;+ isLoopLinkage: boolean;+}++/** A folded value-only helper, drawn on the node it feeds. */+export interface WorkflowPreviewPill {+ nodeId: string;+ /** The form's label for its value when exposed, else the helper's title. */+ label: string;+ /** Shown beside the label when short. */+ value: WorkflowPreviewValue | null;+}++export interface WorkflowPreviewLayout {+ /** Every chip's width in this layout: one per drawing, so columns stay aligned. */+ nodeWidth: number;+ /** Drawn nodes in topological order, which is also their keyboard order. */+ nodeIds: readonly string[];+ edges: readonly WorkflowPreviewEdge[];+ /** Each chip's top-left corner; a chip's pills stack above it, `pillHeight` each. */+ positions: Readonly<Record<string, XYPosition>>;+ /** Folded helpers per consumer; empty in the full view. */+ pills: Readonly<Record<string, readonly WorkflowPreviewPill[]>>;+ /** Each drawn node's drawn neighbours, each once, in keyboard order. */+ neighbours: Readonly<Record<string, { sources: readonly string[]; targets: readonly string[] }>>;+}++/** One input the form exposes, read-only. */+export interface WorkflowPreviewInput {+ /** The form element's id. */+ id: string;+ nodeId: string;+ fieldName: string;+ /** The author's label, else the template's title, else the field name. */+ label: string;+ nodeTitle: string;+ /** The saved value; null when empty. */+ value: WorkflowPreviewValue | null;+ isModelField: boolean;+ /** What the field needs from the model catalog: the model it names, or the kind it asks for while empty. */+ modelRequirements: readonly WorkflowModelRequirement[];+}++/** The form as authored: its layout elements and inputs, in order. */+export type WorkflowPreviewFormItem =+ | { kind: 'heading'; id: string; text: string }+ | { kind: 'text'; id: string; text: string }+ | { kind: 'divider'; id: string }+ | { kind: 'container'; id: string; layout: 'row' | 'column'; children: readonly WorkflowPreviewFormItem[] }+ | { kind: 'input'; id: string; input: WorkflowPreviewInput };++/** The form's inputs under one heading (null before the first heading), as the rail summarises them. */+export interface WorkflowPreviewInputGroup {+ heading: string | null;+ labels: readonly string[];+}++export interface WorkflowPreviewModel {+ nodes: ReadonlyMap<string, WorkflowPreviewNode>;+ /**+ * The drawn structure (node ids and connections), equal across documents that differ only in values: a live source+ * recompiled after a setting change keeps its drawing, and a different graph starts a new one.+ */+ structureKey: string;+ /** Every node at the author's positions, scaled to the chips. */+ all: WorkflowPreviewLayout;+ /** Helpers folded and plumbing hidden, in a layered layout; null when nothing folds or hides. */+ simplified: WorkflowPreviewLayout | null;+ /** The form's root children. */+ form: readonly WorkflowPreviewFormItem[];+ /** Every input the form shows, in its order. */+ inputs: readonly WorkflowPreviewInput[];+ inputGroups: readonly WorkflowPreviewInputGroup[];+}++/** The chip sizes the layouts space; each pill adds a row of its height above its chip. */+export interface WorkflowPreviewMetrics {+ nodeWidth: number;+ nodeHeight: number;+ pillHeight: number;+ layerGap: number;+ rowGap: number;+ /** The author's positions are laid out for editor-sized nodes; the full view scales them by this. */+ authorScale: number;+}++/**+ * The preview's node chips: 136px by 48px, a 26px row per pill above. Layers stay close, so a workflow six layers+ * deep fits a ~870px stage at a readable zoom; rows sit well apart, since a layered graph is wide and short and the+ * stage has the height to spare.+ */+export const WORKFLOW_PREVIEW_METRICS: WorkflowPreviewMetrics = {+ authorScale: 0.5,+ layerGap: 28,+ nodeHeight: 48,+ nodeWidth: 136,+ pillHeight: 26,+ rowGap: 56,+};++/** The chip widths a drawing chooses between: wide enough for its titles, where the stage has the room. */+export const WORKFLOW_PREVIEW_MIN_CHIP_WIDTH = WORKFLOW_PREVIEW_METRICS.nodeWidth;+export const WORKFLOW_PREVIEW_MAX_CHIP_WIDTH = 200;+const CHIP_WIDTH_STEP = 16;++const metricsByWidth = new Map<number, WorkflowPreviewMetrics>([+ [WORKFLOW_PREVIEW_METRICS.nodeWidth, WORKFLOW_PREVIEW_METRICS],+]);++/**+ * The metrics for chips `width` wide, one object per width (models cache by metrics). The author's arrangement scales+ * with the chips, so wider chips keep the gaps the author left between nodes.+ */+export const getWorkflowPreviewMetrics = (width: number): WorkflowPreviewMetrics => {+ let metrics = metricsByWidth.get(width);++ if (!metrics) {+ metrics = {+ ...WORKFLOW_PREVIEW_METRICS,+ authorScale: (WORKFLOW_PREVIEW_METRICS.authorScale * width) / WORKFLOW_PREVIEW_METRICS.nodeWidth,+ nodeWidth: width,+ };+ metricsByWidth.set(width, metrics);+ }++ return metrics;+};++/**+ * A drawing's chip width: wide enough for its longest title (`wanted`), within the minimum and maximum, and no wider+ * than the drawing still `fits` its stage at (laid out at that width, read at a legible zoom); else the minimum.+ * Tried in steps from the widest wanted down.+ */+export const chooseWorkflowPreviewChipWidth = (wanted: number, fits: (width: number) => boolean): number => {+ const widest = Math.min(+ WORKFLOW_PREVIEW_MAX_CHIP_WIDTH,+ Math.max(WORKFLOW_PREVIEW_MIN_CHIP_WIDTH, Math.ceil(wanted))+ );++ for (let width = widest; width > WORKFLOW_PREVIEW_MIN_CHIP_WIDTH; width -= CHIP_WIDTH_STEP) {+ if (fits(width)) {+ return width;+ }+ }++ return WORKFLOW_PREVIEW_MIN_CHIP_WIDTH;+};++/** Plumbing the simplified view hides. */+const PLUMBING_TYPES = new Set(['collect', 'core_metadata']);+/**+ * Plumbing that only records the values it receives on an output (metadata): almost every parameter reaches the+ * decoder through it, which is no data flow worth drawing, so nothing is rerouted through it. A collect is rerouted:+ * what feeds it, feeds what it feeds.+ */+const RECORDING_TYPES = new Set(['core_metadata']);+const VALUE_PRIMITIVE_TYPES = new Set(['string', 'integer', 'float', 'boolean']);+const SCALAR_FIELD_TYPES = new Set(['StringField', 'IntegerField', 'FloatField', 'BooleanField']);+const SHORT_TEXT_LENGTH = 24;++const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;++/** Equal plain data (the model's own nodes, values and layouts), so a rebuild can keep what did not change. */+const isSameData = (a: unknown, b: unknown): boolean => {+ if (Object.is(a, b)) {+ return true;+ }++ if (Array.isArray(a)) {+ return Array.isArray(b) && a.length === b.length && a.every((item, index) => isSameData(item, b[index]));+ }++ if (!isRecord(a) || !isRecord(b) || Array.isArray(b)) {+ return false;+ }++ const keys = Object.keys(a);++ return (+ keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && isSameData(a[key], b[key]))+ );+};++/** `next`, or `previous` where they hold the same data: unchanged parts keep their identity across rebuilds. */+const keepSame = <T>(previous: T | undefined, next: T): T =>+ previous !== undefined && isSameData(previous, next) ? previous : next;++/** The kinds of value the preview can say something about; a choice reads as its template's label. */+const describeValue = (value: unknown, template: FieldInputTemplate | undefined): WorkflowPreviewValue | null => {+ if (typeof value === 'string') {+ return value.trim() === '' ? null : { kind: 'text', text: template?.uiChoiceLabels?.[value] ?? value };+ }++ if (typeof value === 'number') {+ return Number.isFinite(value) ? { kind: 'number', value } : null;+ }++ if (typeof value === 'boolean') {+ return { kind: 'boolean', value };+ }++ if (Array.isArray(value)) {+ return value.length === 0 ? null : { kind: 'list', count: value.length };+ }++ if (isRecord(value)) {+ if (typeof value.image_name === 'string') {+ return { kind: 'image', name: value.image_name };+ }++ if (typeof value.key === 'string' && value.key.trim() !== '') {+ return { kind: 'model', name: typeof value.name === 'string' && value.name ? value.name : value.key };+ }+ }++ return null;+};++const isShortValue = (value: WorkflowPreviewValue): boolean =>+ value.kind === 'number' ||+ value.kind === 'boolean' ||+ (value.kind === 'text' && value.text.length <= SHORT_TEXT_LENGTH);++/** The inputs a person sets on the node: internal and hidden ones are the backend's. */+const getAuthoredInputs = (template: InvocationTemplate): FieldInputTemplate[] =>+ Object.values(template.inputs).filter((input) => input.fieldKind === 'input' && !input.uiHidden);++const getFieldTemplate = (node: WorkflowInvocationNode, template: InvocationTemplate | undefined, name: string) =>+ (template && Object.hasOwn(template.inputs, name) ? template.inputs[name] : undefined) ??+ (node.data.dynamicInputTemplates && Object.hasOwn(node.data.dynamicInputTemplates, name)+ ? node.data.dynamicInputTemplates[name]+ : undefined);++const getTemplate = (templates: InvocationTemplates, type: string) =>+ Object.hasOwn(templates, type) ? templates[type] : undefined;++const getFieldLabel = (node: WorkflowInvocationNode, template: InvocationTemplate | undefined, name: string) =>+ node.data.inputs[name]?.label || getFieldTemplate(node, template, name)?.title || name;++/** Template order (`uiOrder`, then declaration), then any instance the template no longer lists. */+const getOrderedFieldNames = (node: WorkflowInvocationNode, template: InvocationTemplate | undefined): string[] => {+ const declared = Object.values({ ...template?.inputs, ...node.data.dynamicInputTemplates })+ .map((input, index) => ({ index, input }))+ .sort((a, b) => (a.input.uiOrder ?? Infinity) - (b.input.uiOrder ?? Infinity) || a.index - b.index)+ .map(({ input }) => input.name);+ const known = new Set(declared);++ return [...declared, ...Object.keys(node.data.inputs).filter((name) => !known.has(name))];+};++const fieldKey = (nodeId: string, fieldName: string) => `${nodeId}\u0000${fieldName}`;++const pushUnique = (lists: Map<string, string[]>, key: string, value: string) => {+ const list = lists.get(key);++ if (!list) {+ lists.set(key, [value]);+ } else if (!list.includes(value)) {+ list.push(value);+ }+};++const getNeighbours = (+ nodeIds: readonly string[],+ edges: readonly WorkflowPreviewEdge[]+): WorkflowPreviewLayout['neighbours'] => {+ const rank = new Map(nodeIds.map((id, index) => [id, index]));+ const sources = new Map<string, string[]>();+ const targets = new Map<string, string[]>();++ for (const edge of edges) {+ pushUnique(sources, edge.target, edge.source);+ pushUnique(targets, edge.source, edge.target);+ }++ const ordered = (list: string[] | undefined) =>+ [...(list ?? [])].sort((a, b) => (rank.get(a) ?? 0) - (rank.get(b) ?? 0));++ return Object.fromEntries(+ nodeIds.map((id) => [id, { sources: ordered(sources.get(id)), targets: ordered(targets.get(id)) }])+ );+};++/**+ * Layered layout: one column per depth, as narrow as the chips. Each chip sits level with the middle of the chips+ * feeding it, and a column's nodes are then pushed apart to keep the row gap between a chip and the pills stacked+ * above the next one, so edges (which meet chips, not pills) run level where they can and the graph spreads over rows+ * rather than stacking every column from the top. Unconnected first-column nodes stack. Positions are the chips'; the+ * topmost pill stack starts at 0.+ */+const getPreviewLayeredPositions = (+ nodes: readonly { id: string; pillsHeight: number }[],+ edges: readonly { sourceNodeId: string; targetNodeId: string }[],+ metrics: WorkflowPreviewMetrics+): Record<string, XYPosition> => {+ const depths = getNodeDepths([...nodes], [...edges]);+ const pillsHeights = new Map(nodes.map((node) => [node.id, node.pillsHeight]));+ const parents = new Map<string, string[]>();++ for (const edge of edges) {+ pushUnique(parents, edge.targetNodeId, edge.sourceNodeId);+ }++ const layers = new Map<number, string[]>();++ for (const node of nodes) {+ const depth = depths.get(node.id) ?? 0;++ layers.set(depth, [...(layers.get(depth) ?? []), node.id]);+ }++ const positions: Record<string, XYPosition> = {};++ for (const depth of [...layers.keys()].sort((a, b) => a - b)) {+ const x = depth * (metrics.nodeWidth + metrics.layerGap);+ // Every chip is as tall as the others, so the mean of the parents' chip tops levels the chip with their middle.+ const wanted = layers.get(depth)!.map((id, index) => {+ const placed = (parents.get(id) ?? []).filter((parent) => positions[parent] !== undefined);+ const y =+ placed.length === 0 ? null : placed.reduce((sum, parent) => sum + positions[parent]!.y, 0) / placed.length;++ return { id, index, y };+ });+ let bottom = -Infinity;++ // Parentless nodes keep node order at the top; the rest go where their parents are, in that order.+ for (const { id, y } of wanted.sort((a, b) => (a.y ?? -Infinity) - (b.y ?? -Infinity) || a.index - b.index)) {+ const top = Math.max(y ?? 0, bottom + metrics.rowGap + pillsHeights.get(id)!);++ positions[id] = { x, y: top };+ bottom = top + metrics.nodeHeight;+ }+ }++ const minY = Math.min(...Object.entries(positions).map(([id, position]) => position.y - pillsHeights.get(id)!));++ for (const position of Object.values(positions)) {+ position.y -= minY;+ }++ return positions;+};++/**+ * The form's tree from its root, as the preview reads it. Elements naming a missing node or element are skipped, and+ * a container is entered once, so a malformed form cannot loop.+ */+const readForm = (+ document: ProjectGraphState,+ toInput: (id: string, nodeId: string, fieldName: string) => WorkflowPreviewInput | null+): WorkflowPreviewFormItem[] => {+ const { elements, rootElementId } = document.form;+ const entered = new Set<string>();+ const read = (element: WorkflowFormElement | undefined): WorkflowPreviewFormItem | null => {+ switch (element?.type) {+ case 'container': {+ if (entered.has(element.id)) {+ return null;+ }++ entered.add(element.id);++ return {+ children: element.data.children.map((id) => read(elements[id])).filter((item) => item !== null),+ id: element.id,+ kind: 'container',+ layout: element.data.layout,+ };+ }+ case 'node-field': {+ const input = toInput(element.id, element.data.fieldIdentifier.nodeId, element.data.fieldIdentifier.fieldName);++ return input ? { id: element.id, input, kind: 'input' } : null;+ }+ case 'heading':+ return { id: element.id, kind: 'heading', text: element.data.content };+ case 'text':+ return { id: element.id, kind: 'text', text: element.data.content };+ case 'divider':+ return { id: element.id, kind: 'divider' };+ default:+ return null;+ }+ };+ const root = read(elements[rootElementId]);++ return root?.kind === 'container' ? [...root.children] : [];+};++const collectInputs = (items: readonly WorkflowPreviewFormItem[], into: WorkflowPreviewInput[] = []) => {+ for (const item of items) {+ if (item.kind === 'input') {+ into.push(item.input);+ } else if (item.kind === 'container') {+ collectInputs(item.children, into);+ }+ }++ return into;+};++/** The form's inputs grouped under the heading before them, in order; groups without inputs drop out. */+const groupInputs = (items: readonly WorkflowPreviewFormItem[]): WorkflowPreviewInputGroup[] => {+ const groups: { heading: string | null; labels: string[] }[] = [{ heading: null, labels: [] }];+ const walk = (list: readonly WorkflowPreviewFormItem[]) => {+ for (const item of list) {+ if (item.kind === 'heading') {+ groups.push({ heading: item.text, labels: [] });+ } else if (item.kind === 'input') {+ groups.at(-1)!.labels.push(item.input.label);+ } else if (item.kind === 'container') {+ walk(item.children);+ }+ }+ };++ walk(items);++ return groups.filter((group) => group.labels.length > 0);+};++const buildModel = (+ document: ProjectGraphState,+ templates: InvocationTemplates,+ metrics: WorkflowPreviewMetrics,+ previous: WorkflowPreviewModel | null+): WorkflowPreviewModel => {+ const invocationNodes = document.nodes.filter(isInvocationNode);+ const nodeIds = new Set(invocationNodes.map((node) => node.id));+ const canonicalEdges = getCanonicalWorkflowEdges(document).filter(+ (edge) => nodeIds.has(edge.source.node_id) && nodeIds.has(edge.destination.node_id)+ );+ const connectedInputs = new Set(+ canonicalEdges.map((edge) => fieldKey(edge.destination.node_id, edge.destination.field))+ );+ const exposedFields = new Set<string>();++ for (const element of Object.values(document.form.elements)) {+ if (element.type === 'node-field' && nodeIds.has(element.data.fieldIdentifier.nodeId)) {+ exposedFields.add(fieldKey(element.data.fieldIdentifier.nodeId, element.data.fieldIdentifier.fieldName));+ }+ }++ const exposedNodes = new Set([...exposedFields].map((key) => key.slice(0, key.indexOf('\u0000'))));+ const requirements = extractNodeModelRequirements(document, templates);+ const incoming = new Map<string, string[]>();+ const outgoing = new Map<string, string[]>();++ for (const edge of canonicalEdges) {+ pushUnique(outgoing, edge.source.node_id, edge.destination.node_id);+ pushUnique(incoming, edge.destination.node_id, edge.source.node_id);+ }++ const layoutEdges = canonicalEdges+ .filter((edge) => edge.type !== 'loop_linkage')+ .map((edge) => ({ sourceNodeId: edge.source.node_id, targetNodeId: edge.destination.node_id }));+ const order = getTopologicalOrder(invocationNodes, layoutEdges);+ const rank = new Map(order.map((id, index) => [id, index]));+ const byRank = (a: string, b: string) => (rank.get(a) ?? 0) - (rank.get(b) ?? 0);+ const documentNodes = new Map(invocationNodes.map((node) => [node.id, node]));++ const isPlumbing = (id: string) => PLUMBING_TYPES.has(documentNodes.get(id)!.data.type);+ /** A value-only primitive's one input: a scalar it holds itself, with nothing feeding the node and something fed. */+ const getFoldableInput = (id: string): FieldInputTemplate | null => {+ const template = getTemplate(templates, documentNodes.get(id)!.data.type);+ const inputs = template ? getAuthoredInputs(template) : [];+ const input = inputs[0];++ return VALUE_PRIMITIVE_TYPES.has(documentNodes.get(id)!.data.type) &&+ inputs.length === 1 &&+ input!.type.cardinality === 'SINGLE' &&+ SCALAR_FIELD_TYPES.has(input!.type.name) &&+ !incoming.has(id) &&+ outgoing.has(id)+ ? input!+ : null;+ };++ const nodes = new Map<string, WorkflowPreviewNode>();++ for (const id of order) {+ const node = documentNodes.get(id)!;+ const template = getTemplate(templates, node.data.type);+ const values: Record<string, unknown> = {};+ const fields: WorkflowPreviewField[] = [];++ for (const name of getOrderedFieldNames(node, template)) {+ const instance = node.data.inputs[name];+ const fieldTemplate = getFieldTemplate(node, template, name);++ if (!instance || connectedInputs.has(fieldKey(id, name)) || fieldTemplate?.uiHidden) {+ continue;+ }++ const value = describeValue(instance.value, fieldTemplate);++ if (value) {+ values[name] = instance.value;+ fields.push({+ isExposed: exposedFields.has(fieldKey(id, name)),+ label: getFieldLabel(node, template, name),+ name,+ value,+ });+ }+ }++ nodes.set(+ id,+ keepSame(previous?.nodes.get(id), {+ exposedSummary: fields.find((field) => field.isExposed && isShortValue(field.value)) ?? null,+ fields,+ id,+ isExposed: exposedNodes.has(id),+ isResult: !outgoing.has(id) && !isPlumbing(id) && getFoldableInput(id) === null,+ isUnknown: template === undefined,+ modelRequirements: (requirements.get(id) ?? []).map(({ requirement }) => requirement),+ notes: node.data.notes,+ title: node.data.label || template?.title || node.data.type,+ type: node.data.type,+ values,+ })+ );+ }++ const form = readForm(document, (id, nodeId, fieldName) => {+ const node = documentNodes.get(nodeId);++ if (!node) {+ return null;+ }++ const template = getTemplate(templates, node.data.type);+ const fieldTemplate = getFieldTemplate(node, template, fieldName);++ return {+ fieldName,+ id,+ isModelField: fieldTemplate+ ? isModelFieldType(fieldTemplate.type) || fieldTemplate.type.name === 'LoRAField'+ : false,+ label: getFieldLabel(node, template, fieldName),+ modelRequirements: (requirements.get(nodeId) ?? [])+ .filter((entry) => entry.fieldName === fieldName)+ .map(({ requirement }) => requirement),+ nodeId,+ nodeTitle: nodes.get(nodeId)!.title,+ value: describeValue(node.data.inputs[fieldName]?.value, fieldTemplate),+ };+ });++ // One drawn edge per connected pair and kind: several fields between two nodes read as one connection.+ const allEdges: WorkflowPreviewEdge[] = [];+ const seenPairs = new Set<string>();++ for (const edge of canonicalEdges) {+ const isLoopLinkage = edge.type === 'loop_linkage';+ const pair = `${edge.source.node_id}\u0000${edge.destination.node_id}\u0000${isLoopLinkage}`;++ if (!seenPairs.has(pair)) {+ seenPairs.add(pair);+ allEdges.push({+ id: edge.id,+ isLoopLinkage,+ isRerouted: false,+ source: edge.source.node_id,+ target: edge.destination.node_id,+ });+ }+ }++ // Node ids and types and the drawn connections, in no particular order: what the layouts depend on besides values.+ const structureKey = JSON.stringify([+ order.map((id) => `${id}\u0000${documentNodes.get(id)!.data.type}`).sort(),+ allEdges.map((edge) => `${edge.source}\u0000${edge.target}\u0000${edge.isLoopLinkage}`).sort(),+ ]);+ // A rebuild of the same structure (a live source recompiled with new values) keeps the previous layouts.+ const same = previous?.structureKey === structureKey ? previous : null;++ // The author's arrangement, scaled from editor-sized nodes to the chips and moved to the origin.+ const authorX = Math.min(...order.map((id) => documentNodes.get(id)!.position.x));+ const authorY = Math.min(...order.map((id) => documentNodes.get(id)!.position.y));+ const authorPositions = Object.fromEntries(+ order.map((id) => {+ const { x, y } = documentNodes.get(id)!.position;++ return [id, { x: (x - authorX) * metrics.authorScale, y: (y - authorY) * metrics.authorScale }];+ })+ );+ const all: WorkflowPreviewLayout =+ same && isSameData(same.all.positions, authorPositions)+ ? same.all+ : {+ edges: same?.all.edges ?? allEdges,+ neighbours: same?.all.neighbours ?? getNeighbours(order, allEdges),+ nodeIds: same?.all.nodeIds ?? order,+ nodeWidth: metrics.nodeWidth,+ pills: {},+ positions: authorPositions,+ };+ const inputs = collectInputs(form);+ const shared = { form, inputGroups: groupInputs(form), inputs, nodes, structureKey };++ const folded = new Map(+ order.flatMap((id) => {+ const input = getFoldableInput(id);++ return input ? [[id, input] as const] : [];+ })+ );+ const hidden = new Set(order.filter(isPlumbing));++ if (folded.size === 0 && hidden.size === 0) {+ return { ...shared, all, simplified: null };+ }++ const visible = order.filter((id) => !folded.has(id) && !hidden.has(id));+ const visibleIds = new Set(visible);++ /** The visible nodes `id` feeds, directly or through hidden plumbing other than a recorder. */+ const reach = (id: string) => {+ const direct = new Set<string>();+ const rerouted = new Set<string>();+ const pending = [id];+ const seen = new Set<string>();++ while (pending.length > 0) {+ const current = pending.pop()!;++ for (const target of outgoing.get(current) ?? []) {+ if (visibleIds.has(target)) {+ (current === id ? direct : rerouted).add(target);+ } else if (+ hidden.has(target) &&+ !RECORDING_TYPES.has(documentNodes.get(target)!.data.type) &&+ !seen.has(target)+ ) {+ seen.add(target);+ pending.push(target);+ }+ }+ }++ return { direct, rerouted };+ };++ const edges: WorkflowPreviewEdge[] = allEdges.filter(+ (edge) => visibleIds.has(edge.source) && visibleIds.has(edge.target)+ );+ const pills: Record<string, WorkflowPreviewPill[]> = {};++ for (const id of order) {+ if (hidden.has(id)) {+ continue;+ }++ const { direct, rerouted } = reach(id);+ const foldedInput = folded.get(id);++ if (foldedInput) {+ // Labelled by the form even while its value is empty: the form names what the value is for.+ const node = documentNodes.get(id)!;+ const template = getTemplate(templates, node.data.type);+ const value = describeValue(node.data.inputs[foldedInput.name]?.value, foldedInput);+ const pill: WorkflowPreviewPill = {+ label: exposedFields.has(fieldKey(id, foldedInput.name))+ ? getFieldLabel(node, template, foldedInput.name)+ : nodes.get(id)!.title,+ nodeId: id,+ value: value && isShortValue(value) ? value : null,+ };++ for (const consumer of [...new Set([...direct, ...rerouted])].sort(byRank)) {+ (pills[consumer] ??= []).push(pill);+ }++ continue;+ }++ for (const target of [...rerouted].sort(byRank)) {+ if (!direct.has(target)) {+ edges.push({ id: `rerouted:${id}:${target}`, isLoopLinkage: false, isRerouted: true, source: id, target });+ }+ }+ }++ if (same?.simplified) {+ // Pills carry values; the rest of the layout is structure. Unchanged pill rows keep their identity.+ const kept = Object.fromEntries(+ Object.entries(pills).map(([consumer, row]) => [consumer, keepSame(same.simplified!.pills[consumer], row)])+ );+ const simplified = isSameData(same.simplified.pills, kept) ? same.simplified : { ...same.simplified, pills: kept };++ return { ...shared, all, simplified };+ }++ const positions = getPreviewLayeredPositions(+ visible.map((id) => ({ id, pillsHeight: (pills[id]?.length ?? 0) * metrics.pillHeight })),+ edges+ .filter((edge) => !edge.isLoopLinkage)+ .map((edge) => ({ sourceNodeId: edge.source, targetNodeId: edge.target })),+ metrics+ );++ return {+ ...shared,+ all,+ simplified: {+ edges,+ neighbours: getNeighbours(visible, edges),+ nodeIds: visible,+ nodeWidth: metrics.nodeWidth,+ pills,+ positions,+ },+ };+};++interface ModelInputs {+ metrics: WorkflowPreviewMetrics;+ templates: InvocationTemplates;+}++/** Per document, the models built for it: one per templates and metrics in use (a drawing's chip width among them). */+const modelCache = new WeakMap<ProjectGraphState, (ModelInputs & { model: WorkflowPreviewModel })[]>();+const MODEL_CACHE_SIZE = 4;+const modelInputs = new WeakMap<WorkflowPreviewModel, ModelInputs>();++/**+ * Builds the preview of a document, once per document, templates and metrics. Given the `previous` model of the same+ * source (a live source recompiled), the new one keeps every node, pill row and layout that did not change, so a view+ * redraws only what did; a structure unchanged keeps its layouts without laying them out again.+ */+export const buildWorkflowPreviewModel = (+ document: ProjectGraphState,+ templates: InvocationTemplates,+ metrics: WorkflowPreviewMetrics = WORKFLOW_PREVIEW_METRICS,+ previous: WorkflowPreviewModel | null = null+): WorkflowPreviewModel => {+ const built = modelCache.get(document) ?? [];+ const cached = built.find((entry) => entry.templates === templates && entry.metrics === metrics);++ if (cached) {+ return cached.model;+ }++ const previousInputs = previous ? modelInputs.get(previous) : undefined;+ const model = buildModel(+ document,+ templates,+ metrics,+ previousInputs?.templates === templates && previousInputs.metrics === metrics ? previous : null+ );++ modelCache.set(document, [{ metrics, model, templates }, ...built].slice(0, MODEL_CACHE_SIZE));+ modelInputs.set(model, { metrics, templates });++ return model;+};++/** The drawn nodes whose title or type id contains the query, in keyboard order; none for a blank query. */+export const findWorkflowPreviewNodes = (+ model: WorkflowPreviewModel,+ layout: WorkflowPreviewLayout,+ query: string+): string[] => {+ const needle = query.trim().toLocaleLowerCase();++ if (!needle) {+ return [];+ }++ return layout.nodeIds.filter((id) => {+ const node = model.nodes.get(id)!;++ return node.title.toLocaleLowerCase().includes(needle) || node.type.toLocaleLowerCase().includes(needle);+ });+};++/** Compiled inputs that are the backend's bookkeeping, not values a node is set to. */+const COMPILED_META_INPUTS = new Set(['id', 'type', 'is_intermediate', 'use_cache']);++/**+ * A compiled graph (Generate's, a widget's) as a document the preview draws, so it takes the one model path: every+ * node, its type known here or not, with the compiled values, or the text `overrides` gives where the compiled value+ * is not what runs (a seed drawn afresh each run). The fields `getSetLabel` names (a setting the person made) become the+ * document's form, labelled as that setting ("Seed" rather than the field's generic "Value"), which is how the preview+ * marks and names what was set. Nodes take `positionHints` where given, else a layered arrangement in editor units, so+ * the full view scales them like a document's.+ */+export const compiledGraphToPreviewDocument = (+ graph: PreviewGraphLike & { id: string },+ {+ getSetLabel,+ metrics = WORKFLOW_PREVIEW_METRICS,+ overrides,+ positionHints,+ }: {+ /** The setting a field was set by, as a field label; null when nothing set it. */+ getSetLabel?: (nodeId: string, fieldName: string) => string | null;+ metrics?: WorkflowPreviewMetrics;+ overrides?: Readonly<Record<string, Readonly<Record<string, string>>>>;+ positionHints?: Readonly<Record<string, XYPosition>>;+ } = {}+): ProjectGraphState => {+ const depths = getNodeDepths(+ graph.nodes.map((node) => ({ id: node.id })),+ graph.edges+ .filter((edge) => edge.type !== 'loop_linkage')+ .map((edge) => ({ sourceNodeId: edge.sourceNodeId, targetNodeId: edge.targetNodeId }))+ );+ const rows = new Map<number, number>();+ const nextPosition = (id: string): XYPosition => {+ const depth = depths.get(id) ?? 0;+ const row = rows.get(depth) ?? 0;++ rows.set(depth, row + 1);++ return {+ x: (depth * (metrics.nodeWidth + metrics.layerGap)) / metrics.authorScale,+ y: (row * (metrics.nodeHeight + metrics.rowGap)) / metrics.authorScale,+ };+ };+ const elements: Record<string, WorkflowFormElement> = {};+ const children: string[] = [];++ const nodes = graph.nodes.map((node): WorkflowInvocationNode => {+ const inputs: WorkflowInvocationNode['data']['inputs'] = {};++ for (const [name, value] of Object.entries(node.inputs)) {+ if (COMPILED_META_INPUTS.has(name)) {+ continue;+ }++ const setLabel = getSetLabel?.(node.id, name) ?? null;++ inputs[name] = { label: setLabel ?? '', name, value: overrides?.[node.id]?.[name] ?? value };++ if (setLabel !== null) {+ const id = `set:${node.id}:${name}`;++ children.push(id);+ elements[id] = {+ data: { fieldIdentifier: { fieldName: name, nodeId: node.id }, showDescription: false, showShuffle: false },+ id,+ parentId: 'root',+ type: 'node-field',+ };+ }+ }++ return {+ data: {+ inputs,+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: '',+ notes: '',+ type: node.type,+ useCache: true,+ version: '',+ },+ id: node.id,+ position: positionHints?.[node.id] ?? nextPosition(node.id),+ type: 'invocation',+ };+ });++ elements.root = { data: { children, layout: 'column' }, id: 'root', type: 'container' };++ return {+ author: '',+ contact: '',+ description: '',+ edges: graph.edges.map((edge) => ({+ id: edge.id,+ source: edge.sourceNodeId,+ sourceHandle: edge.sourceField,+ target: edge.targetNodeId,+ targetHandle: edge.targetField,+ type: edge.type ?? 'default',+ })),+ form: { elements, rootElementId: 'root' },+ id: graph.id,+ name: graph.label ?? '',+ nodes,+ notes: '',+ tags: '',+ updatedAt: '',+ version: 2,+ workflowVersion: '',+ };+};diff --git a/invokeai/frontend/webv2/src/features/workflow/data/README.md b/invokeai/frontend/webv2/src/features/workflow/data/README.mdindex 4104d13fae..7dc8a9aa96 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/README.md+++ b/invokeai/frontend/webv2/src/features/workflow/data/README.md@@ -2,12 +2,14 @@Paths are relative to the webv2 package.-`src/features/workflow/data/libraryBrowseStore.ts` owns account-scoped server listings, navigation positions, and demand-driven enrichment. Search, category/visibility, tags, order, totals and tag counts are server-authoritative. A result position is a server offset, not an index in a locally filtered subset.+`src/features/workflow/data/libraryBrowseStore.ts` owns account-scoped server listings, navigation positions, and demand-driven enrichment. Search, place (category, visibility and, for Recent, opened state), checked tags (any of, kept sorted so one selection is one view), order, totals, per-place totals and tag counts are server-authoritative. Per-place totals come from one-row probes once per library opening, skipping the place whose first page that opening loads, and from each unfiltered listing or cached view of the current place. Library mutations keep previous totals visible and refresh known or pending place probes while the listing is held; a probe started before a mutation cannot publish afterward. A recorded open or run drops cached views ordered by last opened or last run and refreshes the current one in that order. A result position is a server offset, not an index in a locally filtered subset.-The active view retains at most 60 consecutive metadata entries. Requests usually align to three server pages of 20; a tall viewport spanning four pages retains partial edge pages within the same 60-entry bound. Its `startIndex` locates that window in the full server result. `loadWorkflowLibraryRange` fetches missing pages, reusing only complete resident page positions from the current list generation while the window is no more than 30 seconds old. Partial reads preserve that conservative window age; only a read of every retained position renews it, including rereads after a changed total. Stale cached views remain ineligible for position reuse until a fresh list read completes, including when revalidation queues behind another filter. Partial edge pages must be read again before extension. Forced Retry and list revalidation read resident positions again. Known mutations immediately disable reuse and fence existing first-page, range and refresh publications before notifying subscribers, even when revalidation queues behind another filter. A changed total detected by a missing-page read also rereads reused offsets. The server supplies no list snapshot version, so concurrent external reorderings still converge through revalidation; newer range requests abort and fence older requests. List revalidation reads the pages intersecting the resident window and retains only its bounded positions; selected metadata is revalidated independently. `selectWorkflowLibraryEntry` selects the freshest matching resident or selected revision from a supplied snapshot, preferring selected state (including errors) at equal revisions. Both enrichment scheduling and the dialog use this policy so detail and preview cannot fall behind selected validation. Invalidation drops enrichment while preserving the selected identity, and only a confirmed removal or access loss clears that pin. Transient failures retain its metadata with a retryable detail error. If deletions move that window beyond the end, it reads the last remaining page. The eight least-recently-used view records retain metadata, totals and one logical scroll anchor per view, with no parsed documents: at most 540 metadata entries across current and cached views, plus one selected entry. Returning to an evicted view starts a fresh server listing.+The active view retains at most 60 consecutive metadata entries. Requests usually align to three server pages of 20; a tall viewport spanning four pages retains partial edge pages within the same 60-entry bound. Its `startIndex` locates that window in the full server result. `loadWorkflowLibraryRange` fetches missing pages, reusing only complete resident page positions from the current list generation while the window is no more than 30 seconds old. Partial reads preserve that conservative window age; only a read of every retained position renews it, including rereads after a changed total. Stale cached views remain ineligible for position reuse until a fresh list read completes, including when revalidation queues behind another filter. Partial edge pages must be read again before extension. Forced Retry and list revalidation read resident positions again. Known mutations immediately disable reuse and fence existing first-page, range and refresh publications before notifying subscribers, even when revalidation queues behind another filter. A changed total detected by a missing-page read also rereads reused offsets. The server supplies no list snapshot version, so concurrent external reorderings still converge through revalidation; newer range requests abort and fence older requests. List revalidation reads the pages intersecting the resident window and retains only its bounded positions; selected metadata is revalidated independently. `selectWorkflowLibraryEntry` selects the freshest matching resident or selected revision from a supplied snapshot, preferring selected state (including errors) at equal revisions. Both enrichment scheduling and the dialog use this policy so detail and preview cannot fall behind selected validation. Because scheduling then skips a pending list copy of the selected workflow, every list publication gives that copy the selected enrichment at an equal revision, so its card, missing-model count and preview match the rail without another read. Invalidation drops enrichment while preserving the selected identity, and only a confirmed removal or access loss clears that pin. Transient failures retain its metadata with a retryable detail error. If deletions move that window beyond the end, it reads the last remaining page. The eight least-recently-used view records retain metadata, totals and one logical scroll anchor per view, with no parsed documents: at most 540 metadata entries across current and cached views, plus one selected entry. Returning to an evicted view starts a fresh server listing.-The grid supplies visible workflow identities before overscan so the 48-identity enrichment bound reaches every visible card even in tall viewports. During restoration, its target rows take that priority until the measured viewport reaches them. Selected detail supplies a separate identity and has priority over visible work. Four workers perform revision-aware raw reads, parsing and requirement extraction. There is no accumulated enrichment queue. Leaving demand aborts work and drops parsed documents immediately; an aborted, obsolete-generation, old-revision or old-account completion cannot publish. Selected detail can retain one document outside the metadata window. Preview owns at most one additional document through its explicit preview request, released after exit or library close. Operations consume documents through their existing operation lifetimes. The raw record cache in `libraryCache.ts` separately retains at most 50 records, validated against list revision and cleared on invalidation/account change.+The grid and the list supply visible workflow identities before overscan so the 48-identity enrichment bound reaches every visible card even in tall viewports. During restoration, its target rows take that priority until the measured viewport reaches them. Selected detail supplies a separate identity and has priority over visible work. Four workers perform revision-aware raw reads, parsing and requirement extraction. There is no accumulated enrichment queue. Leaving demand aborts work and drops parsed documents immediately; an aborted, obsolete-generation, old-revision or old-account completion cannot publish. Selected detail can retain one document outside the metadata window. The in-place preview draws the selected workflow's document, so it adds none; while it shows, the hidden grid or list keeps the demand it had, and stepping past the resident window reads that position as scrolling would. Operations consume documents through their existing operation lifetimes. The raw record cache in `libraryCache.ts` separately retains at most 50 records, validated against list revision and cleared on invalidation/account change.-`src/features/workflow/ui/library/WorkflowLibraryGrid.tsx` virtualizes rows with one to three columns (at least 180 px per card where space permits) against the actual `Scrollable` viewport, measures mounted rows and observes viewport width. The account's view records retain only a server item position and the fraction of its row above the viewport, not row measurement caches. The dialog does not subscribe to anchor changes: each keyed grid reads its filter-owned anchor once at mount, so fractional scrolling does not render the shell or detail rail. A returning grid waits for its actual width before demanding the anchor's range, navigates to that row through the virtualizer, and translates the saved fraction using the resident row's measured geometry. Preliminary top/incorrect-column ranges cannot evict that window. Restoration moves only the grid viewport, never focus; keyboard, pointer or wheel intent cancels it, and filter/account changes or unmount discard it. Narrow dialogs stack the detail rail below the grid, preserving both scroll areas at increased zoom. The viewport is capped at 15 estimated rows even on unusually tall displays, keeping visible rows plus two overscan rows on either side within the metadata bound; one focused/menu row may also remain mounted. Focus pinning retains metadata only; a confirmed local deletion clears the matching pin without discarding a valid off-window focused or menu card. Tab navigation scrolls and refetches the next position before focusing its card/menu control. Matching range requests share transport while their metadata reuse remains fresh; an expired partial flight is replaced by a full read. Each caller checks its own requested positions after settlement; superseded, failed or removed targets do not claim readiness. Focus intent waits for resident metadata and mounted controls, and ends on another keyboard/pointer/focus intent, filter/account change, or unmount. A sticky viewport notice exposes range failures, and explicit Retry revalidates even resident positions. A pinned card's action refetches its metadata position before acting. The project view uses the same virtual rows over its project-owned collection without making library reads. Library selection survives metadata eviction; filters and accounts reset its demand through keyed mount leases. An explicit selection remains preferred when present in the returned view. Otherwise detail selects the first resident entry near the restored viewport, avoiding a page-zero read that would evict its anchor window; per-view selections are not cached.+`src/features/workflow/ui/library/WorkflowLibraryGrid.tsx` virtualizes rows with one to six columns, as many as fit at the account's card size (at least 150 px per small card, 220 px per large card), against the actual `Scrollable` viewport, measures mounted rows and observes viewport width. The account's view records retain only a server item position and the fraction of its row above the viewport, not row measurement caches. The dialog does not subscribe to anchor changes: each keyed grid reads its filter-owned anchor once at mount, so fractional scrolling does not render the shell or detail rail. A returning grid waits for its actual width before demanding the anchor's range, navigates to that row through the virtualizer, and translates the saved fraction using the resident row's measured geometry. Preliminary top/incorrect-column ranges cannot evict that window. Restoration moves only the grid viewport, never focus; keyboard, pointer or wheel intent cancels it, and filter/account changes or unmount discard it. In narrow dialogs the detail rail becomes a bottom sheet: a one-row summary under the grid whose expanded details lie over the grid, which stays laid out (invisible and out of the tab order) and keeps its scroll position. The viewport height is capped in estimated rows by column count (`workflowLibraryGridLayout.ts`): 15 up to three columns, 10 at four, 8 at five and 7 at six, with two overscan rows on either side up to four columns and one at five and six. The row estimate is a lower bound, so the rows a capped viewport spans stay within the 48-identity enrichment bound, and with overscan within the 60-position metadata bound, even on unusually tall displays; one focused/menu row may also remain mounted. Focus pinning retains metadata only; a confirmed local deletion clears the matching pin without discarding a valid off-window focused or menu card. Tab navigation scrolls and refetches the next position before focusing its card/menu control. Matching range requests share transport while their metadata reuse remains fresh; an expired partial flight is replaced by a full read. Each caller checks its own requested positions after settlement; superseded, failed or removed targets do not claim readiness. Focus intent waits for resident metadata and mounted controls, and ends on another keyboard/pointer/focus intent, filter/account change, or unmount. A sticky viewport notice exposes range failures, and explicit Retry revalidates even resident positions. A pinned card's action refetches its metadata position before acting. A card's or row's actions menu acts on that workflow without selecting it: it resolves its target from the resident window or the selected pin, and closes once the target leaves both. The project view uses the same virtual rows over its project-owned collection without making library reads. Library selection survives metadata eviction; filters and accounts reset its demand through keyed mount leases. An explicit selection remains preferred when present in the returned view. Otherwise detail selects the first resident entry near the restored viewport, avoiding a page-zero read that would evict its anchor window; per-view selections are not cached.++The account can show either view as a list instead (`src/features/workflow/ui/library/WorkflowLibraryList.tsx`), built on the platform List with fixed 54 px rows. Both layouts derive the demanded identities and hold the range and visible demand through the shared demand module (`workflowLibraryCollection.tsx`): one mount lease per range, visible rows first, released when the viewport leaves. The list has one row per server position, keyed by that position: a position outside the resident window renders as a busy placeholder row with the same button and controls, so when its page arrives the row, and focus on it, stay put. The List's visible range plus eight rows on either side is the range it loads, so a viewport of up to 44 rows (about 2,400 px) stays within the 48-identity and 60-position bounds; on a taller one the rows past the 60-position window stay placeholders. The rows last focused or given a menu and the selected row are kept with their positions while their pages are evicted, metadata only, so they keep their names. A selection made while its row is outside the window (a duplicate's copy, a switch from the grid) is marked as the List's active row once its page is resident; until then the List's tab stop falls back to the row focused last, else to its first row, placeholder or not. The list shares the grid's per-view anchor: it records the first visible position and its fraction whenever its visible range moves and on unmount, and a returning list opens at that offset. It needs no restoration loop, since its fixed rows map a position to an offset exactly.The owner tests exercise 1,000 workflows with 40 nodes each, repeated view changes, return positions, selected pins and obsolete completions. `getWorkflowLibraryBrowseRetention` exposes deterministic resource counts for that fixture. It does not measure browser heap or production latency.diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.test.tsindex 637aa45471..0a4bbd37b8 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/api.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.test.ts@@ -10,6 +10,8 @@ import {getWorkflowTagCounts,listLibraryWorkflows,setLibraryWorkflowPublic,+ touchLibraryWorkflowOpenedAt,+ onLibraryWorkflowOpened,} from './api';describe('workflow library api', () => {@@ -18,6 +20,24 @@ describe('workflow library api', () => {mocks.apiFetchJson.mockReset().mockResolvedValue({});});+ it('records user workflow opens but leaves bundled templates untouched', async () => {+ const opened = vi.fn();+ const unsubscribe = onLibraryWorkflowOpened(opened);+ try {+ await touchLibraryWorkflowOpenedAt('default_text_to_image');+ expect(mocks.apiFetch).not.toHaveBeenCalled();+ expect(opened).not.toHaveBeenCalled();+ await touchLibraryWorkflowOpenedAt('my-workflow');+ expect(mocks.apiFetch).toHaveBeenCalledWith('/api/v1/workflows/i/my-workflow/opened_at', {+ method: 'PUT',+ signal: undefined,+ });+ expect(opened).toHaveBeenCalledTimes(1);+ } finally {+ unsubscribe();+ }+ });+it('forwards repeated tags query params when listing workflows', async () => {mocks.apiFetchJson.mockResolvedValue({ items: [], page: 1, pages: 1, total: 0 });diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.tsindex ad25831043..091d18aa94 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/api.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.ts@@ -44,7 +44,9 @@ export interface ListWorkflowsParams {tags?: string[];isPublic?: boolean;callable?: boolean;- orderBy?: 'created_at' | 'name' | 'opened_at' | 'updated_at';+ /** True lists only workflows this account has opened (`opened_at` set), false only those it never opened. */+ hasBeenOpened?: boolean;+ orderBy?: 'created_at' | 'last_run_at' | 'name' | 'opened_at' | 'updated_at';direction?: 'ASC' | 'DESC';signal?: AbortSignal;}@@ -54,6 +56,7 @@ export const listLibraryWorkflows = ({categories,callable,direction = 'DESC',+ hasBeenOpened,page,perPage = 20,query,@@ -81,6 +84,10 @@ export const listLibraryWorkflows = ({params.set('callable', String(callable));}+ if (hasBeenOpened !== undefined) {+ params.set('has_been_opened', String(hasBeenOpened));+ }+if (query?.trim()) {params.set('query', query.trim());}@@ -107,6 +114,10 @@ export interface WorkflowRecordDTO {workflow: Record<string, unknown>;}+/** Bundled template ids are a server invariant (`default_` prefix); they are read-only whoever asks. */+export const isBundledLibraryWorkflowId = (libraryWorkflowId: string): boolean =>+ libraryWorkflowId.startsWith('default_');+export const getWorkflowRecordCategory = (record: WorkflowRecordDTO): WorkflowLibraryCategory | undefined => {const meta = record.workflow.meta;@@ -297,6 +308,11 @@ export const onLibraryWorkflowOpened = (listener: () => void): (() => void) => {};export const touchLibraryWorkflowOpenedAt = async (workflowId: string, signal?: AbortSignal): Promise<void> => {+ // Bundled opens are global rows: non-admin writes fail and admin writes leak into everyone's Recent.+ if (isBundledLibraryWorkflowId(workflowId)) {+ return;+ }+await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/opened_at`, { method: 'PUT', signal });for (const listener of openedListeners) {@@ -304,6 +320,23 @@ export const touchLibraryWorkflowOpenedAt = async (workflowId: string, signal?:}};+const runListeners = new Set<() => void>();++/** Registers a listener fired once the server has recorded a run: lists ordered by last run have moved. */+export const onLibraryWorkflowRun = (listener: () => void): (() => void) => {+ runListeners.add(listener);+ return () => runListeners.delete(listener);+};++/** Marks the template as run now, for lists ordered by last run. The server refuses bundled and foreign templates. */+export const touchLibraryWorkflowLastRunAt = async (workflowId: string, signal?: AbortSignal): Promise<void> => {+ await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/last_run_at`, { method: 'PUT', signal });++ for (const listener of runListeners) {+ listener();+ }+};+export interface GetWorkflowTagCountsParams {categories?: WorkflowLibraryCategory[];hasBeenOpened?: boolean;diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.tsindex 52942c7821..b3791f8753 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts@@ -8,19 +8,29 @@ import type * as libraryBrowseStoreModule from './libraryBrowseStore';const api = vi.hoisted(() => {const openedListeners = new Set<() => void>();+ const runListeners = new Set<() => void>();return {getAllWorkflowTags: vi.fn(),getWorkflowTagCounts: vi.fn(),listLibraryWorkflows: vi.fn(),/** Each test imports a fresh store; listeners of earlier tests' stores must not hear its opens. */- clearOpenedListeners: () => openedListeners.clear(),+ clearOpenedListeners: () => {+ openedListeners.clear();+ runListeners.clear();+ },/** What `touchLibraryWorkflowOpenedAt` does once the server recorded an open. */notifyOpened: () => openedListeners.forEach((listener) => listener()),onLibraryWorkflowOpened: (listener: () => void) => {openedListeners.add(listener);return () => openedListeners.delete(listener);},+ /** What `touchLibraryWorkflowLastRunAt` does once the server recorded a run. */+ notifyRun: () => runListeners.forEach((listener) => listener()),+ onLibraryWorkflowRun: (listener: () => void) => {+ runListeners.add(listener);+ return () => runListeners.delete(listener);+ },};});@@ -142,6 +152,8 @@ const flushAsyncWork = (): Promise<void> =>let account: typeof accountLifecycleModule;let browse: typeof libraryBrowseStoreModule;let invalidate: () => void;+/** Releases the hold every test starts with, standing in for the open dialog's browse session. */+let releaseBrowseHold: () => void;const demandEntries = () =>browse.setWorkflowLibraryVisibleDemand(browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item.workflow_id)@@ -169,11 +181,12 @@ beforeEach(async () => {account = await import('@platform/state/accountLifecycle');browse = await import('./libraryBrowseStore');account.accountLifecycle.activate('user-a');+ releaseBrowseHold = browse.holdWorkflowLibraryBrowse();});describe('workflow library page fetching', () => {- it('sends the active category, tag, and search filter to the list endpoint', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ it('sends the active place, tags, and search filter to the list endpoint', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();expect(api.listLibraryWorkflows).toHaveBeenCalledWith(@@ -181,7 +194,7 @@ describe('workflow library page fetching', () => {);api.listLibraryWorkflows.mockClear();- browse.setWorkflowLibraryBrowseFilter({ category: 'default', search: 'upscale', tag: 'lora' });+ browse.setWorkflowLibraryBrowseFilter({ place: 'default', search: 'upscale', tags: ['lora'] });await vi.waitFor(() => {demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');@@ -192,6 +205,49 @@ describe('workflow library page fetching', () => {);});+ it('asks for any of the checked tags in one listing, whatever order they were checked in', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });+ api.listLibraryWorkflows.mockClear();++ browse.setWorkflowLibraryBrowseFilter({ tags: ['upscale', 'lora', 'upscale'] });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));++ expect(api.listLibraryWorkflows).toHaveBeenCalledTimes(1);+ expect(api.listLibraryWorkflows).toHaveBeenCalledWith(expect.objectContaining({ tags: ['lora', 'upscale'] }));+ expect(browse.getWorkflowLibraryBrowseSnapshot().filter.tags).toEqual(['lora', 'upscale']);++ // The same selection checked in another order is the same view.+ api.listLibraryWorkflows.mockClear();+ browse.setWorkflowLibraryBrowseFilter({ tags: ['lora', 'upscale'] });+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();++ browse.setWorkflowLibraryBrowseFilter({ tags: [] });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();+ });++ it('lists Recent as the owned and bundled workflows opened before, most recent first', async () => {+ api.getAllWorkflowTags.mockResolvedValue(['lora', 'sdxl']);+ api.getWorkflowTagCounts.mockResolvedValue({ lora: 1, sdxl: 0 });+ await browse.ensureWorkflowLibraryBrowseLoaded({ place: 'recent', sort: 'name', direction: 'asc' });++ const [params] = api.listLibraryWorkflows.mock.calls.at(-1)!;+ expect(params).toMatchObject({+ categories: ['user', 'default'],+ direction: 'DESC',+ hasBeenOpened: true,+ orderBy: 'opened_at',+ page: 0,+ });+ expect(params).not.toHaveProperty('category');+ expect(params).not.toHaveProperty('isPublic');+ expect(api.getAllWorkflowTags).toHaveBeenCalledWith(expect.objectContaining({ categories: ['user', 'default'] }));+ expect(api.getWorkflowTagCounts).toHaveBeenCalledWith(+ expect.objectContaining({ categories: ['user', 'default'], hasBeenOpened: true, tags: ['lora', 'sdxl'] })+ );+ expect(browse.getWorkflowLibraryBrowseSnapshot().tagCounts).toEqual([{ count: 1, tag: 'lora' }]);+ });+it('queries shared workflows and their tags as public user workflows', async () => {api.getAllWorkflowTags.mockResolvedValue(['shared-tag']);api.getWorkflowTagCounts.mockResolvedValue({ 'shared-tag': 2 });@@ -203,7 +259,7 @@ describe('workflow library page fetching', () => {)));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();expect(api.listLibraryWorkflows.mock.calls[0]?.[0]).toMatchObject({ category: 'user', page: 0, perPage: 20 });@@ -212,7 +268,7 @@ describe('workflow library page fetching', () => {api.listLibraryWorkflows.mockClear();api.getAllWorkflowTags.mockClear();api.getWorkflowTagCounts.mockClear();- browse.setWorkflowLibraryBrowseFilter({ category: 'user', isPublic: true, tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'shared', tags: [] });await vi.waitFor(() => {demandEntries();@@ -256,11 +312,11 @@ describe('workflow library page fetching', () => {});it('ignores a repeated filter patch that changes nothing', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();api.listLibraryWorkflows.mockClear();- browse.setWorkflowLibraryBrowseFilter({ category: 'user', search: '' });+ browse.setWorkflowLibraryBrowseFilter({ place: 'user', search: '', tags: [] });expect(api.listLibraryWorkflows).not.toHaveBeenCalled();});@@ -268,9 +324,9 @@ describe('workflow library page fetching', () => {it('clears the accumulated pages as soon as the filter changes', async () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a'), buildItem('b')], { pages: 3, total: 6 }));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();- browse.setWorkflowLibraryBrowseFilter({ tag: 'lora' });+ browse.setWorkflowLibraryBrowseFilter({ tags: ['lora'] });const snapshot = browse.getWorkflowLibraryBrowseSnapshot();expect(snapshot.entries).toEqual([]);@@ -278,7 +334,7 @@ describe('workflow library page fetching', () => {});it('drops a stale in-flight page when the filter changes mid-flight', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();const stale = createDeferred<WorkflowLibraryPage>();@@ -304,7 +360,7 @@ describe('workflow library page fetching', () => {it('records the error message when a page request fails', async () => {api.listLibraryWorkflows.mockRejectedValue(new Error('backend down'));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();const snapshot = browse.getWorkflowLibraryBrowseSnapshot();@@ -315,7 +371,7 @@ describe('workflow library page fetching', () => {it('parses each item tag string once into the entry', async () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a', { tags: ' lora , , sdxl ' })]));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.tags).toEqual(['lora', 'sdxl']);@@ -326,7 +382,7 @@ describe('workflow library sort', () => {const listCalls = () => api.listLibraryWorkflows.mock.calls.map(([params]) => params).filter((p) => p.perPage !== 1);it('loads the first page in the stored sort with one request', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('opened');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'opened' });expect(listCalls()).toEqual([expect.objectContaining({ category: 'user', direction: 'DESC', orderBy: 'opened_at', page: 0 }),@@ -334,16 +390,16 @@ describe('workflow library sort', () => {});it('refetches page 0 in a new sort, and returns to an earlier sort from the cache', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();api.listLibraryWorkflows.mockClear();- browse.setWorkflowLibraryBrowseFilter({ sort: 'name' });+ browse.setWorkflowLibraryBrowseFilter({ direction: 'asc', sort: 'name' });await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));expect(listCalls()).toEqual([expect.objectContaining({ direction: 'ASC', orderBy: 'name', page: 0 })]);api.listLibraryWorkflows.mockClear();- browse.setWorkflowLibraryBrowseFilter({ sort: 'updated' });+ browse.setWorkflowLibraryBrowseFilter({ direction: 'desc', sort: 'updated' });expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');await flushAsyncWork();@@ -354,14 +410,14 @@ describe('workflow library sort', () => {api.listLibraryWorkflows.mockImplementation(({ perPage }: { perPage: number }) =>Promise.resolve(buildPage(perPage === 1 ? [] : [buildItem('a'), buildItem('x')])));- await browse.ensureWorkflowLibraryBrowseLoaded('opened');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'opened' });api.listLibraryWorkflows.mockClear();api.listLibraryWorkflows.mockImplementation(({ perPage }: { perPage: number }) =>Promise.resolve(buildPage(perPage === 1 ? [] : [buildItem('x'), buildItem('a')])));// Opening `x` closed the dialog; its slow opened-at request is still in flight when the dialog opens again.- await browse.ensureWorkflowLibraryBrowseLoaded('opened');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'opened' });await flushAsyncWork();expect(listCalls()).toEqual([]);@@ -380,7 +436,7 @@ describe('workflow library sort', () => {});it('drops hidden views by last opened on an open without reading them until revisited', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('opened');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'opened' });browse.setWorkflowLibraryBrowseFilter({ sort: 'updated' });await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));api.listLibraryWorkflows.mockClear();@@ -393,22 +449,163 @@ describe('workflow library sort', () => {expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loading');});+ it('rereads the current view by last run, and drops hidden ones, when a run is recorded', async () => {+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a'), buildItem('b')]));+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'lastRun' });+ browse.setWorkflowLibraryBrowseFilter({ sort: 'updated' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ api.listLibraryWorkflows.mockClear();++ // A hidden view by last run is dropped without a read; the current view in another order stays.+ api.notifyRun();+ await flushAsyncWork();+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();+ browse.setWorkflowLibraryBrowseFilter({ sort: 'lastRun' });+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loading');+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));++ // The current view by last run rereads once, however many runs land together.+ api.listLibraryWorkflows.mockClear();+ api.notifyRun();+ api.notifyRun();+ await vi.waitFor(() => expect(listCalls()).toHaveLength(1));+ await flushAsyncWork();+ expect(listCalls()).toEqual([expect.objectContaining({ orderBy: 'last_run_at', page: 0 })]);+ });++ it.each([+ ['run', 'lastRun', 'last_run_at'],+ ['open', 'opened', 'opened_at'],+ ] as const)(+ 'only marks the view outdated on a recorded %s while the library is closed, and revalidates as it reopens',+ async (touch, sort, orderBy) => {+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a'), buildItem('b')]));+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort });+ // The dialog closed: its browse session released the listing. A second release changes nothing.+ releaseBrowseHold();+ releaseBrowseHold();+ api.listLibraryWorkflows.mockClear();++ if (touch === 'run') {+ api.notifyRun();+ } else {+ api.notifyOpened();+ }+ await flushAsyncWork();+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();+ expect(api.getAllWorkflowTags).toHaveBeenCalledTimes(1);++ // The next opening, on the same view, rereads it once.+ const release = browse.holdWorkflowLibraryBrowse();+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort });+ await vi.waitFor(() => expect(listCalls()).toHaveLength(1));+ await flushAsyncWork();+ expect(listCalls()).toEqual([expect.objectContaining({ orderBy, page: 0 })]);++ // Held again, a touch refreshes at once; an opening on a fresh view reads nothing.+ api.listLibraryWorkflows.mockClear();+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort });+ await flushAsyncWork();+ expect(listCalls()).toEqual([]);+ if (touch === 'run') {+ api.notifyRun();+ } else {+ api.notifyOpened();+ }+ await vi.waitFor(() => expect(listCalls()).toHaveLength(1));+ release();+ }+ );++ it('shares the stale-view revalidation requested by both opening sessions', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'lastRun' });+ releaseBrowseHold();+ api.notifyRun();+ const response = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockClear().mockReturnValue(response.promise);++ const first = browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'lastRun' });+ const second = browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'lastRun' });+ response.resolve(buildPage([buildItem('latest')]));+ await Promise.all([first, second]);+ await flushAsyncWork();++ expect(listCalls()).toHaveLength(1);+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.workflow_id).toBe('latest');+ });++ it('revalidates on reopening instead of joining a refresh fenced by a closed-session run', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'lastRun' });+ const response = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockReturnValueOnce(response.promise);+ const staleRefresh = browse.refreshWorkflowLibraryBrowse();+ releaseBrowseHold();+ api.notifyRun();+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('latest')]));+ const opening = browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'lastRun' });+ response.resolve(buildPage([buildItem('stale')]));+ await Promise.all([staleRefresh, opening]);+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.workflow_id).toBe('latest')+ );+ });++ it('fences a closed-session filter reset when a run completes before its first page returns', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ search: 'cat', sort: 'lastRun' });+ releaseBrowseHold();+ const response = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockReturnValueOnce(response.promise);+ browse.setWorkflowLibraryBrowseFilter({ search: '' });+ api.notifyRun();+ response.resolve(buildPage([buildItem('stale')]));+ await flushAsyncWork();++ expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toEqual([]);+ api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('latest')]));+ await browse.ensureWorkflowLibraryBrowseLoaded({ search: '', sort: 'lastRun' });+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.workflow_id).toBe('latest');+ });+it('keeps views in other orders when a workflow is opened', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();api.listLibraryWorkflows.mockClear();api.notifyOpened();- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await flushAsyncWork();expect(api.listLibraryWorkflows).not.toHaveBeenCalled();});+ it('reverses the order and lists by last run on request', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });+ api.listLibraryWorkflows.mockClear();++ browse.setWorkflowLibraryBrowseFilter({ direction: 'asc' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ browse.setWorkflowLibraryBrowseFilter({ direction: 'desc', sort: 'lastRun' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));++ expect(listCalls()).toEqual([+ expect.objectContaining({ direction: 'ASC', orderBy: 'updated_at', page: 0 }),+ expect.objectContaining({ direction: 'DESC', orderBy: 'last_run_at', page: 0 }),+ ]);+ });++ it('reverses bundled templates only while the key is name', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ direction: 'desc', place: 'default', sort: 'name' });+ expect(listCalls().at(-1)).toEqual(expect.objectContaining({ direction: 'DESC', orderBy: 'name' }));++ browse.setWorkflowLibraryBrowseFilter({ sort: 'updated' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ expect(listCalls().at(-1)).toEqual(expect.objectContaining({ direction: 'ASC', orderBy: 'name' }));+ });+it('lists bundled templates by name whatever the sort, sharing one cached view', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('created');- browse.setWorkflowLibraryBrowseFilter({ category: 'default', tag: null });+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'created' });+ browse.setWorkflowLibraryBrowseFilter({ place: 'default', tags: [] });await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));expect(listCalls().at(-1)).toEqual(@@ -423,11 +620,11 @@ describe('workflow library sort', () => {});describe('workflow library tag counts', () => {- it('stores sorted, non-zero counts for the active category', async () => {+ it('stores sorted, non-zero counts for the active place', async () => {api.getAllWorkflowTags.mockResolvedValue(['lora', 'sdxl', 'unused']);api.getWorkflowTagCounts.mockResolvedValue({ lora: 2, sdxl: 5, unused: 0 });- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();expect(api.getAllWorkflowTags).toHaveBeenCalledWith(expect.objectContaining({ categories: ['user'] }));@@ -440,8 +637,8 @@ describe('workflow library tag counts', () => {]);});- it('refetches counts for the new category and not for a search-only change', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ it('refetches counts for the new place and not for a search-only change', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();api.getAllWorkflowTags.mockClear();@@ -452,7 +649,7 @@ describe('workflow library tag counts', () => {});expect(api.getAllWorkflowTags).not.toHaveBeenCalled();- browse.setWorkflowLibraryBrowseFilter({ category: 'default' });+ browse.setWorkflowLibraryBrowseFilter({ place: 'default' });await vi.waitFor(() => {demandEntries();expect(api.getAllWorkflowTags).toHaveBeenCalledWith(expect.objectContaining({ categories: ['default'] }));@@ -465,7 +662,7 @@ describe('workflow library entry enrichment', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(2));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => {demandEntries();@@ -485,7 +682,7 @@ describe('workflow library entry enrichment', () => {workflowId === 'bad' ? Promise.reject(new Error('payload gone')) : Promise.resolve(buildRawWorkflow(1)));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => {demandEntries();@@ -501,7 +698,7 @@ describe('workflow library entry enrichment', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));libraryCache.getLibraryWorkflowCached.mockResolvedValue('not a workflow');- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => {demandEntries();@@ -522,7 +719,7 @@ describe('workflow library entry enrichment', () => {return deferred.promise;});- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => {demandEntries();@@ -554,7 +751,7 @@ describe('workflow library entry enrichment', () => {buildPage(Array.from({ length: 6 }, (_unused, index) => buildItem(`item-${index}`))));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => {demandEntries();@@ -576,7 +773,7 @@ describe('workflow library entry enrichment', () => {});api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => {demandEntries();@@ -601,7 +798,7 @@ describe('workflow library entry enrichment', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('gone')]));libraryCache.getLibraryWorkflowCached.mockReturnValueOnce(stalled.promise);- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(1));@@ -629,7 +826,7 @@ describe('workflow library entry enrichment', () => {workflowId === 'slow' ? slow.promise : Promise.resolve(buildRawWorkflow(1)));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => {demandEntries();@@ -652,7 +849,7 @@ describe('workflow library browse refresh', () => {it('coalesces a burst of cache invalidations into one refresh', async () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();api.listLibraryWorkflows.mockClear();@@ -674,9 +871,9 @@ describe('workflow library browse refresh', () => {Promise.resolve(buildPage(isPublic ? [sharedWorkflow] : [])));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();- browse.setWorkflowLibraryBrowseFilter({ category: 'user', isPublic: true, tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'shared', tags: [] });await vi.waitFor(() => {demandEntries();const snapshot = browse.getWorkflowLibraryBrowseSnapshot();@@ -691,7 +888,7 @@ describe('workflow library browse refresh', () => {demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot()).toMatchObject({entries: [],- filter: { category: 'user', isPublic: true },+ filter: { place: 'shared' },status: 'loaded',});});@@ -715,7 +912,7 @@ describe('workflow library browse refresh', () => {{ page: index, pages: 10, total: 200 });api.listLibraryWorkflows.mockImplementation(({ page: index }: { page: number }) => Promise.resolve(page(index)));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });const held: { index: number; response: Deferred<WorkflowLibraryPage> }[] = [];api.listLibraryWorkflows.mockImplementation(({ page: index }: { page: number }) => {const response = createDeferred<WorkflowLibraryPage>();@@ -747,7 +944,7 @@ describe('workflow library browse refresh', () => {)));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });await browse.loadWorkflowLibraryRange(20, 25);const before = browse.getWorkflowLibraryBrowseSnapshot().entries;api.listLibraryWorkflows.mockClear();@@ -762,7 +959,7 @@ describe('workflow library browse refresh', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(1));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => {demandEntries();@@ -784,9 +981,10 @@ describe('workflow library browse account ownership', () => {it('resets to the initial snapshot when the account switches', async () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')], { total: 3 }));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();- browse.setWorkflowLibraryBrowseFilter({ category: 'default', search: 'cat', tag: 'lora' });+ browse.setWorkflowLibraryBrowseFilter({ place: 'default', search: 'cat', tags: ['lora'] });+ await browse.loadWorkflowLibraryPlaceTotals(['user']);await vi.waitFor(() => {demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(1);@@ -797,23 +995,23 @@ describe('workflow library browse account ownership', () => {expect(browse.getWorkflowLibraryBrowseSnapshot()).toEqual({entries: [],error: null,- filter: { category: 'user', search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'user', search: '', sort: 'opened', tags: [] },page: 0,pages: 0,+ placeTotals: {},status: 'idle',tagCounts: [],total: 0,- userTotal: null,});});it('drops an in-flight shared page when the account switches', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();const stale = createDeferred<WorkflowLibraryPage>();api.listLibraryWorkflows.mockReturnValueOnce(stale.promise);- browse.setWorkflowLibraryBrowseFilter({ isPublic: true });+ browse.setWorkflowLibraryBrowseFilter({ place: 'shared' });account.accountLifecycle.activate('user-b');stale.resolve(buildPage([buildItem('other-account-shared')]));@@ -821,34 +1019,120 @@ describe('workflow library browse account ownership', () => {expect(browse.getWorkflowLibraryBrowseSnapshot()).toMatchObject({entries: [],- filter: { category: 'user', search: '', tag: null },+ filter: { place: 'user', search: '', tags: [] },status: 'idle',});});});-describe('workflow library user total probe', () => {- it('probes the user category with a one-row request', async () => {+describe('workflow library place totals', () => {+ it('probes each place with a one-row request in its own scope', async () => {+ api.listLibraryWorkflows.mockImplementation(+ ({ category, hasBeenOpened, isPublic }: { category?: string; hasBeenOpened?: boolean; isPublic?: boolean }) =>+ Promise.resolve(buildPage([], { total: hasBeenOpened ? 3 : isPublic ? 5 : category === 'default' ? 12 : 7 }))+ );++ await browse.loadWorkflowLibraryPlaceTotals(['recent', 'user', 'default', 'shared']);++ const probes = api.listLibraryWorkflows.mock.calls.map(([params]) => params);+ expect(probes).toEqual([+ expect.objectContaining({ categories: ['user', 'default'], hasBeenOpened: true, page: 0, perPage: 1 }),+ expect.objectContaining({ category: 'user', page: 0, perPage: 1 }),+ expect.objectContaining({ category: 'default', page: 0, perPage: 1 }),+ expect.objectContaining({ category: 'user', isPublic: true, page: 0, perPage: 1 }),+ ]);+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({+ default: 12,+ recent: 3,+ shared: 5,+ user: 7,+ });+ });++ it('does not launch place probes when cache invalidation is part of account cleanup', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });+ await browse.loadWorkflowLibraryPlaceTotals(['recent']);+ api.listLibraryWorkflows.mockClear();++ // The account lifecycle clears the record cache first, then the browse store.+ invalidate();+ account.accountLifecycle.invalidate();+ await flushAsyncWork();++ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({});+ });++ it('refreshes other place totals on mutations and ignores probes from before the mutation', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });+ const stale = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockReturnValueOnce(stale.promise);+ const priorProbe = browse.loadWorkflowLibraryPlaceTotals(['recent']);api.listLibraryWorkflows.mockImplementation(({ perPage }: { perPage: number }) =>- Promise.resolve(perPage === 1 ? buildPage([buildItem('a')], { total: 7 }) : buildPage([]))+ Promise.resolve(buildPage([], { total: perPage === 1 ? 2 : 4 })));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');- demandEntries();+ invalidate();+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({ recent: 2, user: 4 })+ );+ stale.resolve(buildPage([], { total: 3 }));+ await priorProbe;+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({ recent: 2, user: 4 });+ });- expect(api.listLibraryWorkflows).toHaveBeenCalledWith(- expect.objectContaining({ category: 'user', page: 0, perPage: 1 })+ it('retains place totals while mutation refreshes are pending, then replaces them', async () => {+ api.listLibraryWorkflows.mockResolvedValue(buildPage([], { total: 3 }));+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });+ await browse.loadWorkflowLibraryPlaceTotals(['recent']);++ const listing = createDeferred<WorkflowLibraryPage>();+ const probe = createDeferred<WorkflowLibraryPage>();+ api.listLibraryWorkflows.mockImplementation(({ perPage }: { perPage: number }) =>+ perPage === 1 ? probe.promise : listing.promise+ );+ api.listLibraryWorkflows.mockClear();++ invalidate();+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({ recent: 3, user: 3 });+ await flushAsyncWork();+ expect(api.listLibraryWorkflows).toHaveBeenCalledWith(expect.objectContaining({ hasBeenOpened: true, perPage: 1 }));+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({ recent: 3, user: 3 });++ probe.resolve(buildPage([], { total: 2 }));+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({ recent: 2, user: 3 })+ );+ listing.resolve(buildPage([], { total: 4 }));+ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({ recent: 2, user: 4 }));- expect(browse.getWorkflowLibraryBrowseSnapshot().userTotal).toBe(7);});- it('probes only once across repeated ensure calls', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded('updated');- demandEntries();- await browse.ensureWorkflowLibraryBrowseLoaded('updated');- demandEntries();+ it('shares a probe in flight and follows the current place’s unfiltered listings', async () => {+ api.listLibraryWorkflows.mockImplementation(({ perPage }: { perPage: number }) =>+ Promise.resolve(buildPage([buildItem('a')], { total: perPage === 1 ? 7 : 9 }))+ );- expect(api.listLibraryWorkflows.mock.calls.filter(([params]) => params.perPage === 1)).toHaveLength(1);+ await Promise.all([+ browse.loadWorkflowLibraryPlaceTotals(['user']),+ // Joins the user probe in flight and still probes Shared.+ browse.loadWorkflowLibraryPlaceTotals(['user', 'shared']),+ ]);+ expect(api.listLibraryWorkflows.mock.calls.map(([params]) => params)).toEqual([+ expect.objectContaining({ category: 'user', perPage: 1 }),+ expect.objectContaining({ category: 'user', isPublic: true, perPage: 1 }),+ ]);+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals).toEqual({ shared: 7, user: 7 });++ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals.user).toBe(9);++ // A filtered total is not the place's total.+ api.listLibraryWorkflows.mockResolvedValue(buildPage([], { total: 1 }));+ browse.setWorkflowLibraryBrowseFilter({ search: 'cat' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ expect(browse.getWorkflowLibraryBrowseSnapshot().placeTotals.user).toBe(9);});});@@ -865,12 +1149,12 @@ describe('workflow library view cache', () => {const browseYoursThenBrowse = async () => {listByCategory({ default: [buildItem('x', { category: 'default' })], user: userItems });- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() => expect(allEnriched()).toBe(true));const yours = browse.getWorkflowLibraryBrowseSnapshot().entries;- browse.setWorkflowLibraryBrowseFilter({ category: 'default', tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'default', tags: [] });await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));api.listLibraryWorkflows.mockClear();libraryCache.getLibraryWorkflowCached.mockClear();@@ -881,7 +1165,7 @@ describe('workflow library view cache', () => {it('returns to a view browsed moments ago at once, without refetching or re-reading its rows', async () => {const yours = await browseYoursThenBrowse();- browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'user', tags: [] });const snapshot = browse.getWorkflowLibraryBrowseSnapshot();expect(snapshot.status).toBe('loaded');@@ -902,14 +1186,14 @@ describe('workflow library view cache', () => {Promise.resolve({ [tags[0] ?? '']: isPublic ? 2 : 1 }));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });demandEntries();await vi.waitFor(() =>expect(browse.getWorkflowLibraryBrowseSnapshot().tagCounts).toEqual([{ count: 1, tag: 'yours-tag' }]));const yours = browse.getWorkflowLibraryBrowseSnapshot().entries;- browse.setWorkflowLibraryBrowseFilter({ isPublic: true });+ browse.setWorkflowLibraryBrowseFilter({ place: 'shared' });await vi.waitFor(() => {demandEntries();expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.workflow_id).toBe('shared');@@ -918,13 +1202,13 @@ describe('workflow library view cache', () => {const shared = browse.getWorkflowLibraryBrowseSnapshot().entries;api.listLibraryWorkflows.mockClear();- browse.setWorkflowLibraryBrowseFilter({ isPublic: undefined });+ browse.setWorkflowLibraryBrowseFilter({ place: 'user' });expect(browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item)).toEqual(yours.map((entry) => entry.item));expect(browse.getWorkflowLibraryBrowseSnapshot().tagCounts).toEqual([{ count: 1, tag: 'yours-tag' }]);- browse.setWorkflowLibraryBrowseFilter({ isPublic: true });+ browse.setWorkflowLibraryBrowseFilter({ place: 'shared' });expect(browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item)).toEqual(shared.map((entry) => entry.item));@@ -940,7 +1224,7 @@ describe('workflow library view cache', () => {const refreshed = createDeferred<WorkflowLibraryPage>();api.listLibraryWorkflows.mockReturnValueOnce(refreshed.promise);- browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'user', tags: [] });// The cached rows stay up while the refresh is in flight.expect(browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item)).toEqual(@@ -968,7 +1252,7 @@ describe('workflow library view cache', () => {await flushAsyncWork();api.listLibraryWorkflows.mockClear();- browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'user', tags: [] });expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loading');await vi.waitFor(() => expect(api.listLibraryWorkflows).toHaveBeenCalled());@@ -976,15 +1260,15 @@ describe('workflow library view cache', () => {it('does not keep a view that a library change outdated when it is left before its refresh lands', async () => {await browseYoursThenBrowse();- browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'user', tags: [] });// The change's refresh is scheduled but has not run when the user moves on.invalidate();- browse.setWorkflowLibraryBrowseFilter({ category: 'default', tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'default', tags: [] });await flushAsyncWork();api.listLibraryWorkflows.mockClear();- browse.setWorkflowLibraryBrowseFilter({ category: 'user', tag: null });+ browse.setWorkflowLibraryBrowseFilter({ place: 'user', tags: [] });expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loading');await vi.waitFor(() =>@@ -1017,14 +1301,17 @@ describe('stale cached view revalidation', () => {({ query = '', page: index, perPage }: { query?: string; page: number; perPage: number }) =>Promise.resolve(page(query, index, perPage, false)));- await browse.ensureWorkflowLibraryBrowseLoaded(sort);+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort });await browse.loadWorkflowLibraryRange(0, 59);browse.setWorkflowLibraryBrowseFilter({ search: 'other' });await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));const held: HeldPage[] = [];api.listLibraryWorkflows.mockClear()- .mockImplementation(({ query = '', page: index }: { query?: string; page: number }) => {+ .mockImplementation(({ query = '', page: index, perPage }: { query?: string; page: number; perPage: number }) => {+ if (perPage === 1) {+ return Promise.resolve(page(query, index, perPage, true));+ }const read = { query, page: index, response: createDeferred<WorkflowLibraryPage>() };held.push(read);return read.response.promise;@@ -1276,9 +1563,35 @@ describe('large library retention fixture', () => {libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(40));};+ it('gives the selected workflow’s returning list copy the selected enrichment, without reading it again', async () => {+ seedLargeLibrary();+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });+ browse.setWorkflowLibrarySelectedDemand('large-0');+ browse.setWorkflowLibraryVisibleDemand(['large-0']);+ const listCopy = () =>+ browse.getWorkflowLibraryBrowseSnapshot().entries.find((entry) => entry.item.workflow_id === 'large-0');+ await vi.waitFor(() => expect(listCopy()?.enrichment.status).toBe('ready'));+ expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(1);++ // The window moves past the selected page, so its list copy leaves; the selected copy stays enriched.+ browse.setWorkflowLibraryVisibleDemand([]);+ await browse.loadWorkflowLibraryRange(200, 205);+ expect(listCopy()).toBeUndefined();+ expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment.status).toBe('ready');++ // Back again: the list copy arrives pending and takes the selected enrichment at once, with no second read.+ await browse.loadWorkflowLibraryRange(0, 5);+ expect(listCopy()?.enrichment).toBe(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment);+ expect(listCopy()?.enrichment.status).toBe('ready');+ browse.setWorkflowLibraryVisibleDemand(['large-0', 'large-1']);+ await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(2));+ await flushAsyncWork();+ expect(libraryCache.getLibraryWorkflowCached.mock.calls.filter(([id]) => id === 'large-0')).toHaveLength(1);+ });+it('bounds retention and reads only demanded workflows across 1,000 results', async () => {seedLargeLibrary();- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });expect(libraryCache.getLibraryWorkflowCached).not.toHaveBeenCalled();browse.setWorkflowLibrarySelectedDemand('large-0');for (let page = 0; page < 50; page += 1) {@@ -1300,7 +1613,7 @@ describe('large library retention fixture', () => {).toBeLessThanOrEqual(7);}expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(300);- expect(api.listLibraryWorkflows).toHaveBeenCalledTimes(51);+ expect(api.listLibraryWorkflows).toHaveBeenCalledTimes(50);expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.item.workflow_id).toBe('large-0');await browse.loadWorkflowLibraryRange(0, 5);expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.workflow_id).toBe('large-0');@@ -1314,7 +1627,7 @@ describe('large library retention fixture', () => {it('reaches a stable bound across repeated cached views and restores return-scroll', async () => {seedLargeLibrary();- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });for (let view = 0; view < 20; view += 1) {browse.setWorkflowLibraryBrowseFilter({ search: `view-${view}` });await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));@@ -1343,7 +1656,7 @@ describe('large library retention fixture', () => {it('rejects scroll measurements from a leaving view', async () => {seedLargeLibrary();- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });const leavingFilter = browse.getWorkflowLibraryBrowseSnapshot().filter;browse.rememberWorkflowLibraryScroll(leavingFilter, { index: 400, fraction: 0.75 });browse.setWorkflowLibraryBrowseFilter({ search: 'another view' });@@ -1356,7 +1669,7 @@ describe('large library retention fixture', () => {it('gives selected detail priority over waiting visible work', async () => {seedLargeLibrary();- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibrarySelectedDemand('large-19');browse.setWorkflowLibraryVisibleDemand(['large-0', 'large-1', 'large-2', 'large-3', 'large-4']);await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalled());@@ -1369,7 +1682,7 @@ describe('large library retention fixture', () => {seedLargeLibrary();const slow = createDeferred<Record<string, unknown>>();libraryCache.getLibraryWorkflowCached.mockReturnValue(slow.promise);- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibraryVisibleDemand(['large-0']);await vi.waitFor(() => expect(libraryCache.getLibraryWorkflowCached).toHaveBeenCalledTimes(1));const signal = libraryCache.getLibraryWorkflowCached.mock.calls[0]?.[1].signal as AbortSignal;@@ -1391,7 +1704,7 @@ describe('review regressions', () => {)));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibrarySelectedDemand('wf-0');await browse.loadWorkflowLibraryRange(400, 410);};@@ -1413,7 +1726,7 @@ describe('review regressions', () => {});it('keeps fresh resident metadata and its document when an older selected read finishes last', async () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0')]));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibrarySelectedDemand('wf-0');await vi.waitFor(() =>expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment.status).toBe('ready')@@ -1457,7 +1770,7 @@ describe('review regressions', () => {it('keeps fresh resident metadata when the concurrent selected read fails transiently', async () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0')]));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibrarySelectedDemand('wf-0');const selectedRead = createDeferred<never>();libraryCache.getLibraryWorkflowRecordCached.mockReturnValueOnce(selectedRead.promise);@@ -1474,7 +1787,7 @@ describe('review regressions', () => {it('retains a newer selected revision when an older resident listing arrives later', async () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0')]));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibrarySelectedDemand('wf-0');await vi.waitFor(() =>expect(browse.getWorkflowLibraryBrowseSnapshot().selectedEntry?.enrichment.status).toBe('ready')@@ -1509,7 +1822,7 @@ describe('review regressions', () => {it('discards old selected enrichment when resident metadata advances during the read', async () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('wf-0')]));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });const oldDocument = createDeferred<Record<string, unknown>>();libraryCache.getLibraryWorkflowCached.mockReturnValueOnce(oldDocument.promise).mockResolvedValue({...buildRawWorkflow(2),@@ -1634,7 +1947,7 @@ describe('overlapping metadata windows', () => {)));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });api.listLibraryWorkflows.mockClear();};const requests = () => api.listLibraryWorkflows.mock.calls.map(([params]) => params.page);diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.tsindex 253d35f7da..225c3a8adf 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts@@ -17,9 +17,15 @@ import { shallowEqual } from '@platform/state/selectorCore';import { createTrailingSingleFlight } from '@platform/state/singleFlight';import { ApiError, getApiErrorMessage } from '@platform/transport/http';-import type { WorkflowLibraryCategory, WorkflowLibraryListItem, WorkflowLibraryPage } from './api';+import type { ListWorkflowsParams, WorkflowLibraryCategory, WorkflowLibraryListItem, WorkflowLibraryPage } from './api';-import { getAllWorkflowTags, getWorkflowTagCounts, listLibraryWorkflows, onLibraryWorkflowOpened } from './api';+import {+ getAllWorkflowTags,+ getWorkflowTagCounts,+ listLibraryWorkflows,+ onLibraryWorkflowOpened,+ onLibraryWorkflowRun,+} from './api';import {getLibraryWorkflowCached,getLibraryWorkflowRecordCached,@@ -37,19 +43,54 @@ const libraryLogger = createLogger({ area: 'library', namespace: 'workflows' });export type { WorkflowTagCount } from '@features/workflow/core/libraryTags';-/** What the library's own templates are ordered by; bundled templates always list by name. */-export type WorkflowLibrarySort = 'updated' | 'opened' | 'created' | 'name';+/**+ * Where the library browses: the account's own templates, bundled templates, public templates (multi-user), or the+ * owned and bundled templates the account has opened.+ */+export type WorkflowLibraryPlace = 'user' | 'default' | 'shared' | 'recent';++/** What My library and Shared are ordered by; the other places have fixed keys, see `getWorkflowLibraryOrder`. */+export type WorkflowLibrarySort = 'updated' | 'opened' | 'created' | 'name' | 'lastRun';++export type WorkflowLibrarySortDirection = 'asc' | 'desc';export interface WorkflowLibraryBrowseFilter {- category: WorkflowLibraryCategory;- /** Public user workflows form a distinct view; absent keeps user listings owner scoped. */- isPublic?: boolean;- tag: string | null;+ place: WorkflowLibraryPlace;+ /** Any-of: a workflow carrying one of these tags matches. Kept sorted and unique, so equal selections share a view. */+ tags: readonly string[];search: string;- /** Applies to the user category only; see `getListOrder`. */sort: WorkflowLibrarySort;+ direction: WorkflowLibrarySortDirection;}+/** A key's natural direction: dates newest first, names A to Z. */+export const getWorkflowLibrarySortDefaultDirection = (sort: WorkflowLibrarySort): WorkflowLibrarySortDirection =>+ sort === 'name' ? 'asc' : 'desc';++/**+ * The order a place actually lists in. Recent is always most recently opened first. Bundled templates always list by+ * name, because the server rewrites their timestamps at every start; they take the filter's direction only while the+ * filter's key is name, so a date order's descending direction never turns them Z to A.+ */+export const getWorkflowLibraryOrder = ({+ direction,+ place,+ sort,+}: Pick<WorkflowLibraryBrowseFilter, 'direction' | 'place' | 'sort'>): {+ direction: WorkflowLibrarySortDirection;+ sort: WorkflowLibrarySort;+} => {+ if (place === 'recent') {+ return { direction: 'desc', sort: 'opened' };+ }++ if (place === 'default') {+ return { direction: sort === 'name' ? direction : 'asc', sort: 'name' };+ }++ return { direction, sort };+};+export type WorkflowLibraryEntryEnrichment =| { status: 'pending' }| { status: 'error'; message: string }@@ -80,41 +121,80 @@ export interface WorkflowLibraryBrowseSnapshot {page: number;pages: number;total: number;- /** Chip counts for the current category and visibility filter. */+ /** Tag counts for the current place, independent of the search and the checked tags. */tagCounts: readonly WorkflowTagCount[];- /** Total user-category workflows, for the one-time Browse/Yours auto-switch. */- userTotal: number | null;+ /** Unfiltered totals per place, for the rail and the empty-account switch to Templates; absent until known. */+ placeTotals: Readonly<Partial<Record<WorkflowLibraryPlace, number>>>;error: string | null;}const PER_PAGE = 20;-const MAX_RESIDENT_ENTRIES = PER_PAGE * 3;-const MAX_DEMAND = 48;+/** The most consecutive metadata positions the current view keeps resident (see README). */+export const WORKFLOW_LIBRARY_METADATA_WINDOW = PER_PAGE * 3;+/** The most demanded identities enrichment serves at once, visible cards first. */+export const WORKFLOW_LIBRARY_ENRICHMENT_DEMAND = 48;const ENRICHMENT_CONCURRENCY = 4;const PENDING_ENRICHMENT: WorkflowLibraryEntryEnrichment = { status: 'pending' };const EMPTY_ENTRIES: readonly WorkflowLibraryEntry[] = [];const EMPTY_TAG_COUNTS: readonly WorkflowTagCount[] = [];-const INITIAL_FILTER: WorkflowLibraryBrowseFilter = { category: 'user', search: '', sort: 'updated', tag: null };+const EMPTY_TAGS: readonly string[] = [];+const EMPTY_PLACE_TOTALS: WorkflowLibraryBrowseSnapshot['placeTotals'] = {};+const INITIAL_FILTER: WorkflowLibraryBrowseFilter = {+ direction: 'desc',+ place: 'user',+ search: '',+ sort: 'opened',+ tags: EMPTY_TAGS,+};++type ListOrderBy = NonNullable<ListWorkflowsParams['orderBy']>;-const ORDER_BY: Record<WorkflowLibrarySort, 'created_at' | 'name' | 'opened_at' | 'updated_at'> = {+const ORDER_BY: Record<WorkflowLibrarySort, ListOrderBy> = {created: 'created_at',+ lastRun: 'last_run_at',name: 'name',opened: 'opened_at',updated: 'updated_at',};+/** The list order a filter asks the server for. */+const getListOrder = (filter: WorkflowLibraryBrowseFilter): { direction: 'ASC' | 'DESC'; orderBy: ListOrderBy } => {+ const { direction, sort } = getWorkflowLibraryOrder(filter);++ return { direction: direction === 'asc' ? 'ASC' : 'DESC', orderBy: ORDER_BY[sort] };+};+/**- * The list order a filter asks the server for. Bundled templates always list by name: the server rewrites their- * timestamps at every start, so their dates order nothing. Dates list newest first; names A to Z.+ * What each place reads. Shared is every account's public templates; My library and Recent stay owner scoped (the+ * server keeps bundled templates in an owner-scoped listing).*/-const getListOrder = ({- category,- sort,-}: WorkflowLibraryBrowseFilter): { direction: 'ASC' | 'DESC'; orderBy: (typeof ORDER_BY)[WorkflowLibrarySort] } => {- const effective = category === 'default' ? 'name' : sort;+const PLACE_SCOPES: Record<+ WorkflowLibraryPlace,+ { categories: readonly WorkflowLibraryCategory[]; hasBeenOpened?: true; isPublic?: true }+> = {+ default: { categories: ['default'] },+ recent: { categories: ['user', 'default'], hasBeenOpened: true },+ shared: { categories: ['user'], isPublic: true },+ user: { categories: ['user'] },+};- return { direction: effective === 'name' ? 'ASC' : 'DESC', orderBy: ORDER_BY[effective] };+/** List parameters for a place: a single category as `category`, mixed ones as `categories`. */+const getListScope = (place: WorkflowLibraryPlace) => {+ const { categories, ...flags } = PLACE_SCOPES[place];++ return categories.length === 1 ? { category: categories[0]!, ...flags } : { categories: [...categories], ...flags };+};++/** Sorted and unique; the previous array when the selection is unchanged, so an equal patch is a no-op. */+const normalizeTags = (tags: readonly string[], previous: readonly string[]): readonly string[] => {+ const next = [...new Set(tags)].sort();++ if (next.length === 0) {+ return EMPTY_TAGS;+ }++ return next.length === previous.length && next.every((tag, index) => tag === previous[index]) ? previous : next;};const INITIAL_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {@@ -124,17 +204,23 @@ const INITIAL_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {page: 0,pages: 0,status: 'idle',+ placeTotals: EMPTY_PLACE_TOTALS,tagCounts: EMPTY_TAG_COUNTS,total: 0,- userTotal: null,};const store = createExternalStore<WorkflowLibraryBrowseSnapshot>(INITIAL_SNAPSHOT);+/** The place's unfiltered total, learned from any unfiltered listing of it. */+const withPlaceTotal = (filter: WorkflowLibraryBrowseFilter, total: number) =>+ filter.search === '' && filter.tags.length === 0 && store.getSnapshot().placeTotals[filter.place] !== total+ ? { placeTotals: { ...store.getSnapshot().placeTotals, [filter.place]: total } }+ : {};+// #region View cache/**- * Views already browsed (Browse, Yours, Shared, a tag or search), kept so switching back shows their metadata at once instead of refetching every row. A view older than `VIEW_FRESH_MS` is revalidated in the+ * Views already browsed (a place, a tag selection or a search), kept so switching back shows their metadata at once instead of refetching every row. A view older than `VIEW_FRESH_MS` is revalidated in the* background and merged in place; library mutations drop the other views.*/interface CachedBrowseView {@@ -157,10 +243,9 @@ let currentViewFetchedAt = 0;const getFilterKey = (filter: WorkflowLibraryBrowseFilter): string =>JSON.stringify([- filter.category,- filter.isPublic,+ filter.place,filter.search,- filter.tag,+ filter.tags,getListOrder(filter).orderBy,getListOrder(filter).direction,]);@@ -205,6 +290,8 @@ const rememberCurrentView = (): void => {const initialLoadFlight = createTrailingSingleFlight();const refreshFlight = createTrailingSingleFlight();+let initialLoadGeneration = -1;+let refreshGeneration = -1;/*** Fences page responses by generation, not request order. A filter change, an account change, or a revalidation of@@ -258,6 +345,7 @@ const publishPage = (result: WorkflowLibraryPage): void => {pages: result.pages,status: 'loaded',total: result.total,+ ...withPlaceTotal(store.getSnapshot().filter, result.total),});pumpEnrichment();};@@ -324,17 +412,34 @@ const findEntry = (workflowId: string): WorkflowLibraryEntry | undefined =>selectWorkflowLibraryEntry(store.getSnapshot(), workflowId);const demandedIds = (): Set<string> =>- new Set([...(selectedDemand ? [selectedDemand] : []), ...visibleDemand.slice(0, MAX_DEMAND)]);+ new Set([...(selectedDemand ? [selectedDemand] : []), ...visibleDemand.slice(0, WORKFLOW_LIBRARY_ENRICHMENT_DEMAND)]);+/**+ * Drops documents nobody demands, and gives a pending list copy of the selected workflow the selected copy's+ * enrichment at the same revision. Every list publication (first page, range, revalidation, cached view) runs this+ * through `pumpEnrichment`, so a card, its missing-model count and its preview never stay pending beside a rail that+ * already shows the same revision (the enrichment loop skips the id: `findEntry` answers with the selected copy).+ */const trimDocuments = (): void => {const demand = demandedIds();const snapshot = store.getSnapshot();const selectedEntry = selectedDemand ? (findEntry(selectedDemand) ?? null) : null;- const entries = snapshot.entries.map((entry) =>- !demand.has(entry.item.workflow_id) && entry.enrichment.status !== 'pending'+ const inherited = selectedEntry?.enrichment.status === 'pending' ? null : selectedEntry;+ const entries = snapshot.entries.map((entry) => {+ if (+ inherited &&+ entry !== inherited &&+ entry.enrichment.status === 'pending' &&+ entry.item.workflow_id === inherited.item.workflow_id &&+ entry.item.revision === inherited.item.revision+ ) {+ return { ...entry, enrichment: inherited.enrichment };+ }++ return !demand.has(entry.item.workflow_id) && entry.enrichment.status !== 'pending'? { ...entry, enrichment: PENDING_ENRICHMENT }- : entry- );+ : entry;+ });if (selectedEntry !== snapshot.selectedEntry || entries.some((entry, index) => entry !== snapshot.entries[index])) {store.patchSnapshot({ entries, selectedEntry });}@@ -421,7 +526,7 @@ const pumpEnrichment = (): void => {};export const setWorkflowLibraryVisibleDemand = (ids: readonly string[]): void => {- visibleDemand = ids.slice(0, MAX_DEMAND);+ visibleDemand = ids.slice(0, WORKFLOW_LIBRARY_ENRICHMENT_DEMAND);pumpEnrichment();};@@ -507,8 +612,8 @@ const loadWorkflowLibraryWindow = (start: number, end: number, force: boolean):}// Most viewports fit aligned pages. A tall viewport can cross four pages while still needing only 60 positions.const alignedStart = Math.max(0, Math.min(Math.floor(start / PER_PAGE), snapshot.pages - 3)) * PER_PAGE;- const windowStart = end < alignedStart + MAX_RESIDENT_ENTRIES ? alignedStart : Math.max(0, start);- const windowEnd = Math.min(snapshot.total, windowStart + MAX_RESIDENT_ENTRIES);+ const windowStart = end < alignedStart + WORKFLOW_LIBRARY_METADATA_WINDOW ? alignedStart : Math.max(0, start);+ const windowEnd = Math.min(snapshot.total, windowStart + WORKFLOW_LIBRARY_METADATA_WINDOW);const first = Math.floor(windowStart / PER_PAGE);const last = Math.max(first, Math.ceil(windowEnd / PER_PAGE) - 1);const key = `${listGeneration}:${windowStart}:${windowEnd}:${force}`;@@ -579,7 +684,7 @@ const loadWorkflowLibraryWindow = (start: number, end: number, force: boolean):store.patchSnapshot({entries: mergeEntries(store.getSnapshot().entries,- items.slice(0, Math.min(MAX_RESIDENT_ENTRIES, Math.max(0, result.total - publishedStart)))+ items.slice(0, Math.min(WORKFLOW_LIBRARY_METADATA_WINDOW, Math.max(0, result.total - publishedStart)))),startIndex: publishedStart,page: Math.min(last, Math.max(0, result.pages - 1)),@@ -625,13 +730,12 @@ const fetchPage = (): Promise<WorkflowLibraryPage> =>listLibraryWorkflows({...getListOrder(filter),- category: filter.category,- ...(filter.isPublic === undefined ? {} : { isPublic: filter.isPublic }),+ ...getListScope(filter.place),page,perPage: PER_PAGE,query: filter.search || undefined,signal: signal ? AbortSignal.any([signal, owner.signal]) : owner.signal,- tags: filter.tag ? [filter.tag] : undefined,+ tags: filter.tags.length > 0 ? [...filter.tags] : undefined,});const loadFirstPage = async (filter: WorkflowLibraryBrowseFilter, owner: AccountScope): Promise<void> => {@@ -656,23 +760,27 @@ const loadFirstPage = async (filter: WorkflowLibraryBrowseFilter, owner: Account}};-/** Tag chips are best-effort: a failed count leaves the previous chips in place. */-const loadTagCounts = async (- category: WorkflowLibraryCategory,- isPublic: boolean | undefined,- owner: AccountScope-): Promise<void> => {+/** Tag counts are best-effort: a failed count leaves the previous tags in place. */+const loadTagCounts = async (place: WorkflowLibraryPlace, owner: AccountScope): Promise<void> => {try {+ const { categories: placeCategories, hasBeenOpened, isPublic } = PLACE_SCOPES[place];+ const categories = [...placeCategories];const publicFilter = isPublic === undefined ? {} : { isPublic };- const tags = await getAllWorkflowTags({ categories: [category], ...publicFilter, signal: owner.signal });+ const tags = await getAllWorkflowTags({ categories, ...publicFilter, signal: owner.signal });+ // The tag list has no recency filter; Recent's counts drop the tags none of its workflows carry.const counts =tags.length > 0- ? await getWorkflowTagCounts({ categories: [category], ...publicFilter, signal: owner.signal, tags })+ ? await getWorkflowTagCounts({+ categories,+ ...publicFilter,+ ...(hasBeenOpened ? { hasBeenOpened } : {}),+ signal: owner.signal,+ tags,+ }): {};- // A category or visibility switch mid-flight owns the chips now.- const filter = store.getSnapshot().filter;- if (!isAccountScopeCurrent(owner) || filter.category !== category || filter.isPublic !== isPublic) {+ // A place switch mid-flight owns the tags now.+ if (!isAccountScopeCurrent(owner) || store.getSnapshot().filter.place !== place) {return;}@@ -680,42 +788,74 @@ const loadTagCounts = async (store.patchSnapshot({ tagCounts: tagCounts.length > 0 ? tagCounts : EMPTY_TAG_COUNTS });} catch {- // Chips are decoration around the grid; the list request owns the error state.+ // Tag counts are decoration around the grid; the list request owns the error state.}};-/** Probe one user workflow to decide whether fresh accounts should open bundled defaults. */-const probeUserTotal = async (owner: AccountScope): Promise<void> => {- if (store.getSnapshot().userTotal !== null) {- return;- }+let placeTotalsGeneration = 0;+const placeTotalFlights = new Map<WorkflowLibraryPlace, Promise<void>>();- try {- const result = await listLibraryWorkflows({ category: 'user', page: 0, perPage: 1, signal: owner.signal });+/** One place's one-row probe; a caller during a probe of the same place shares it. */+const probePlaceTotal = (place: WorkflowLibraryPlace): Promise<void> => {+ const inflight = placeTotalFlights.get(place);- if (isAccountScopeCurrent(owner)) {- store.patchSnapshot({ userTotal: result.total });- }- } catch {- // Leaves `userTotal` null: the dialog simply keeps the category it opened on.+ if (inflight) {+ return inflight;}++ const owner = captureAccountScope();+ const generation = placeTotalsGeneration;+ const flight: Promise<void> = listLibraryWorkflows({+ ...getListScope(place),+ page: 0,+ perPage: 1,+ signal: owner.signal,+ })+ .then(+ (result) => {+ if (isAccountScopeCurrent(owner) && generation === placeTotalsGeneration) {+ store.patchSnapshot({ placeTotals: { ...store.getSnapshot().placeTotals, [place]: result.total } });+ }+ },+ () => {+ // A failed probe leaves the previous total in place, or unknown until the first successful probe.+ }+ )+ .finally(() => {+ if (placeTotalFlights.get(place) === flight) {+ placeTotalFlights.delete(place);+ }+ });++ placeTotalFlights.set(place, flight);+ return flight;};+/**+ * One-row probes for the rail's place totals; the dialog asks once per opening. The current place's total also follows+ * its unfiltered listings, so the dialog leaves out the place whose first page it is loading anyway.+ */+export const loadWorkflowLibraryPlaceTotals = (places: readonly WorkflowLibraryPlace[]): Promise<void> =>+ Promise.all(places.map(probePlaceTotal)).then(() => undefined);+/*** Applies a filter patch. A view browsed before comes back from the cache at once (revalidated in the background once* stale); a new one starts from page 0.*/export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrowseFilter>): void => {const snapshot = store.getSnapshot();- const filter = { ...snapshot.filter, ...patch };+ const filter = {+ ...snapshot.filter,+ ...patch,+ tags: patch.tags ? normalizeTags(patch.tags, snapshot.filter.tags) : snapshot.filter.tags,+ };if (shallowEqual(filter, snapshot.filter)) {return;}const owner = captureAccountScope();- const isCategoryChanged = filter.category !== snapshot.filter.category;- const isTagScopeChanged = isCategoryChanged || filter.isPublic !== snapshot.filter.isPublic;+ const isTagScopeChanged = filter.place !== snapshot.filter.place;rememberCurrentView();rangeController?.abort();@@ -753,6 +893,7 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrostatus: 'loaded',tagCounts: cached.tagCounts,total: cached.total,+ ...withPlaceTotal(filter, cached.total),});pumpEnrichment();@@ -779,37 +920,48 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrovoid loadFirstPage(filter, owner);if (isTagScopeChanged) {- void loadTagCounts(filter.category, filter.isPublic, owner);+ void loadTagCounts(filter.place, owner);}};/**- * First open: page 0, the category's tag counts, and the user-total probe, in the account's stored sort so the first- * request already comes back in order. A later open with another sort switches to it as a filter change.+ * Every open of a template place applies the opening filter, a patch over the current one; the dialog passes its+ * place, the account's stored order, and the session's search and tags. The first open loads page 0 and the place's+ * tag counts in that filter, so the first request already comes back in order; a later open applies it as a filter+ * change.*/-export const ensureWorkflowLibraryBrowseLoaded = (sort: WorkflowLibrarySort): Promise<void> => {- const { status } = store.getSnapshot();+export const ensureWorkflowLibraryBrowseLoaded = (opening: Partial<WorkflowLibraryBrowseFilter>): Promise<void> => {+ const snapshot = store.getSnapshot();- if (status !== 'idle' && status !== 'error') {- setWorkflowLibraryBrowseFilter({ sort });+ if (snapshot.status !== 'idle' && snapshot.status !== 'error') {+ setWorkflowLibraryBrowseFilter(opening);++ // A view outdated while nobody looked (see `onOrderTouched`) revalidates as the library opens on it again.+ if (store.getSnapshot().filter === snapshot.filter && currentViewFetchedAt === 0) {+ return (+ (initialLoadGeneration === listGeneration ? initialLoadFlight.inflight() : null) ??+ (refreshGeneration === listGeneration ? refreshFlight.inflight() : null) ??+ refreshWorkflowLibraryBrowse()+ );+ }return initialLoadFlight.inflight() ?? Promise.resolve();}return initialLoadFlight.run(async () => {+ initialLoadGeneration = listGeneration;const owner = captureAccountScope();- const filter = { ...store.getSnapshot().filter, sort };-- store.patchSnapshot({ filter });+ const current = store.getSnapshot().filter;+ const filter = {+ ...current,+ ...opening,+ tags: opening.tags ? normalizeTags(opening.tags, current.tags) : current.tags,+ };hasTemplateLoadFailed = false;- store.patchSnapshot({ error: null, status: 'loading' });+ store.patchSnapshot({ error: null, filter, status: 'loading' });- await Promise.all([- loadFirstPage(filter, owner),- loadTagCounts(filter.category, filter.isPublic, owner),- probeUserTotal(owner),- ]);+ await Promise.all([loadFirstPage(filter, owner), loadTagCounts(filter.place, owner)]);});};@@ -895,6 +1047,7 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>const request = ++windowRequest;const generation = listGeneration;+ refreshGeneration = generation;const firstPage = Math.floor((store.getSnapshot().startIndex ?? 0) / PER_PAGE);const residentStart = store.getSnapshot().startIndex ?? 0;const residentEnd = residentStart + store.getSnapshot().entries.length;@@ -929,7 +1082,7 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>publishedStart - (results[0]?.page ?? 0) * PER_PAGE,publishedStart -(results[0]?.page ?? 0) * PER_PAGE +- Math.min(MAX_RESIDENT_ENTRIES, Math.max(0, last.total - publishedStart))+ Math.min(WORKFLOW_LIBRARY_METADATA_WINDOW, Math.max(0, last.total - publishedStart)))),error: null,@@ -938,6 +1091,7 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>pages: last.pages,status: 'loaded',total: last.total,+ ...withPlaceTotal(filter, last.total),});await selectedRead;pumpEnrichment();@@ -955,7 +1109,7 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>await selectedRead;pumpEnrichment();- await loadTagCounts(filter.category, filter.isPublic, owner);+ await loadTagCounts(filter.place, owner);});export const getWorkflowLibraryBrowseSnapshot = (): WorkflowLibraryBrowseSnapshot => store.getSnapshot();@@ -1012,6 +1166,12 @@ const scheduleCurrentViewRefresh = (): void => {};onWorkflowLibraryCacheInvalidated(() => {+ const { filter, placeTotals } = store.getSnapshot();+ const places = [+ ...new Set([...(Object.keys(placeTotals) as WorkflowLibraryPlace[]), ...placeTotalFlights.keys()]),+ ].filter((place) => place !== filter.place || filter.search !== '' || filter.tags.length > 0);+ placeTotalsGeneration += 1;+ placeTotalFlights.clear();metadataGeneration = -1;currentViewFetchedAt = 0;// A mutation can change any view; the current one refreshes, the others fetch afresh when revisited.@@ -1029,21 +1189,62 @@ onWorkflowLibraryCacheInvalidated(() => {? { ...store.getSnapshot().selectedEntry!, enrichment: PENDING_ENRICHMENT }: null,});+ const generation = placeTotalsGeneration;+ queueMicrotask(() => {+ // Account cleanup invalidates the record cache before clearing this store.+ if (browseHolds > 0 && placeTotalsGeneration === generation) {+ void loadWorkflowLibraryPlaceTotals(places);+ }+ });});-// Opening a workflow moves it to the top of every view ordered by last opened. The server may record the open after-// the dialog is open again, so the current view refreshes now; hidden ones are dropped and fetched when revisited.-onLibraryWorkflowOpened(() => {+/** Holders of the listing: the library dialog while it shows a template place. */+let browseHolds = 0;++/**+ * Marks the listing as in use until the returned release runs (once). A count rather than a flag, so a remount's+ * release and re-hold leave it held.+ */+export const holdWorkflowLibraryBrowse = (): (() => void) => {+ let isReleased = false;+ browseHolds += 1;++ return () => {+ if (!isReleased) {+ isReleased = true;+ browseHolds -= 1;+ }+ };+};++/**+ * Opening or running a workflow moves it to the top of every view ordered by last opened or last run; hidden views in+ * that order are dropped and fetched when revisited. While the library is in use, the current view in that order+ * refreshes now (the server may record the change after the dialog is open again). Otherwise it is only marked+ * outdated, and the next opening revalidates it: runs complete all session long with nobody looking.+ */+const onOrderTouched = (orderBy: ListOrderBy) => (): void => {for (const [key, view] of viewCache) {- if (view.orderBy === 'opened_at') {+ if (view.orderBy === orderBy) {viewCache.delete(key);}}- if (getListOrder(store.getSnapshot().filter).orderBy === 'opened_at') {+ if (getListOrder(store.getSnapshot().filter).orderBy !== orderBy) {+ return;+ }++ if (browseHolds > 0) {scheduleCurrentViewRefresh();+ } else {+ listGeneration += 1;+ currentViewFetchedAt = 0;+ metadataGeneration = -1;}-});+};++onLibraryWorkflowOpened(onOrderTouched('opened_at'));+onLibraryWorkflowRun(onOrderTouched('last_run_at'));registerAccountOwnedResource({clear: () => {@@ -1062,6 +1263,8 @@ registerAccountOwnedResource({rangeController = null;windowRequest += 1;templatesFlight = null;+ placeTotalsGeneration += 1;+ placeTotalFlights.clear();hasTemplateLoadFailed = false;isRefreshScheduled = false;viewCache.clear();diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.tsindex 84a9a57c05..460c4834a8 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts@@ -13,6 +13,7 @@ const api = vi.hoisted(() => ({getWorkflowTagCounts: vi.fn(),listLibraryWorkflows: vi.fn(),onLibraryWorkflowOpened: () => () => {},+ onLibraryWorkflowRun: () => () => {},}));const templates = vi.hoisted(() => ({@@ -112,7 +113,7 @@ describe('workflow library record freshness', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a', 1)]));api.getLibraryWorkflowRecord.mockResolvedValue(buildRecord('a', 1));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibraryVisibleDemand(['a']);await vi.waitFor(() => expect(enrichedNodeCount()).toBe(1));@@ -151,7 +152,7 @@ describe('workflow library record freshness', () => {.mockResolvedValue(buildPage([buildItem('a', 2)]));api.getLibraryWorkflowRecord.mockResolvedValue(buildRecord('a', 2));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibraryVisibleDemand(['a']);await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.revision).toBe(2));await vi.waitFor(() => expect(enrichedNodeCount()).toBe(2));@@ -292,7 +293,7 @@ describe('workflow library invalidation fencing', () => {.mockReturnValueOnce(retry.promise).mockResolvedValue(buildRecord('a', 1));- await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded({ sort: 'updated' });browse.setWorkflowLibraryVisibleDemand(['a']);await vi.waitFor(() => expect(api.getLibraryWorkflowRecord).toHaveBeenCalledTimes(1));// The refreshes these invalidations start never land, so nothing but the row's own read can enrich it.diff --git a/invokeai/frontend/webv2/src/features/workflow/preview.ts b/invokeai/frontend/webv2/src/features/workflow/preview.tsindex f8197754e4..93ac54d905 100644--- a/invokeai/frontend/webv2/src/features/workflow/preview.ts+++ b/invokeai/frontend/webv2/src/features/workflow/preview.ts@@ -1,11 +1,13 @@export { storedGraphToDocument } from './core/graphToDocument';-export { documentToPreviewGraph, GraphPreviewDialog, GraphPreviewFlow } from './ui/graph-preview';+export { GraphPreviewDialog } from './ui/graph-preview/GraphPreviewDialog';export {getWorkflowNodeBodyProps,getWorkflowNodeChromeProps,getWorkflowNodeHeaderProps,getWorkflowNodeShellProps,WORKFLOW_NODE_DENSITY,+ WORKFLOW_NODE_LABEL_TEXT_CSS,+ WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS,WorkflowNodeHandleDot,- WorkflowNodeInfoIcon,+ WorkflowNodeInfoButton,} from './ui/nodeChrome';diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/MenuActionItem.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/MenuActionItem.tsxdeleted file mode 100644index 9917d00bb9..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/MenuActionItem.tsx+++ /dev/null@@ -1,48 +0,0 @@-import type { ElementType } from 'react';--import { Icon, Menu, Stack, Text } from '@chakra-ui/react';--/** Share workflow menu row geometry; optional hint lines top-align the icon with the primary label. */--const DISABLED_ITEM = { opacity: 0.4 } as const;-const SINGLE_LINE_LAYOUT = { alignItems: 'center', gap: '2.5', py: '1' } as const;-const TWO_LINE_LAYOUT = { alignItems: 'flex-start', gap: '2.5', py: '1.5' } as const;-const SINGLE_LINE_ICON = { boxSize: '3.5', flexShrink: 0 } as const;-const TWO_LINE_ICON = { boxSize: '3.5', flexShrink: 0, mt: '0.5' } as const;--export interface MenuActionItemProps {- /** Second line under the label, for choices whose consequences are not obvious. */- hint?: string;- icon: ElementType;- isDisabled?: boolean;- label: string;- /** `'danger'` is reserved for destructive choices (delete). */- tone?: 'danger';- /** Ark's item value, also mirrored to `data-menu-item` so tests can address the row. */- value: string;- onSelect: () => void;-}--export const MenuActionItem = ({ hint, icon, isDisabled, label, tone, value, onSelect }: MenuActionItemProps) => (- <Menu.Item- {...(hint ? TWO_LINE_LAYOUT : SINGLE_LINE_LAYOUT)}- _disabled={DISABLED_ITEM}- data-danger={tone === 'danger' ? '' : undefined}- data-menu-item={value}- disabled={isDisabled}- value={value}- onClick={onSelect}- >- <Icon as={icon} {...(hint ? TWO_LINE_ICON : SINGLE_LINE_ICON)} />- {hint ? (- <Stack gap="0" minW="0">- <Menu.ItemText>{label}</Menu.ItemText>- <Text color="fg.subtle" fontSize="xs">- {hint}- </Text>- </Stack>- ) : (- <Menu.ItemText>{label}</Menu.ItemText>- )}- </Menu.Item>-);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDeferredLoadFailure.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDeferredLoadFailure.browser.test.tsxnew file mode 100644index 0000000000..332ed20429--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDeferredLoadFailure.browser.test.tsx@@ -0,0 +1,136 @@+/* eslint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop -- explicit per-case test props */+import type * as DeferredModuleModule from '@platform/react/deferredModule';++import { ChakraProvider } from '@chakra-ui/react';+import { createProjectGraph } from '@features/workflow/utility';+import { system } from '@theme/system';+import { act, type ComponentProps, StrictMode } from 'react';+import { createRoot } from 'react-dom/client';+import { expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import type { WorkflowUiAdapter } from './WorkflowUiContext';++import { WorkflowPreviewJson } from './graph-preview/WorkflowPreviewStage';+import { DeferredGraphPreviewSnapshot, DeferredWorkflowDocumentGraph } from './library/libraryPreviewSource';+import { WorkflowUiProvider } from './WorkflowUiContext';+import { requestWorkflowRename, setWorkflowLibraryOpen, workflowUiStore } from './workflowUiStore';+import { WorkflowDialogHost } from './WorkflowWidgetChrome';++const chunk = vi.hoisted(() => ({ fails: true, rejections: 0 }));+// Fail the actual deferred import seam, rather than a Vitest module response (which would never settle its request).+vi.mock('@platform/react/deferredModule', async (importOriginal) => {+ const actual = await importOriginal<typeof DeferredModuleModule>();+ return {+ ...actual,+ createDeferredModule: <Module,>(load: () => Promise<Module>) =>+ actual.createDeferredModule(() => {+ if (chunk.fails) {+ chunk.rejections += 1;+ return Promise.reject(new TypeError('Failed to fetch dynamically imported module'));+ }+ return load();+ }),+ };+});+vi.mock('./editor/AddNodeDialog', () => ({ AddNodeDialog: () => null }));+vi.mock('./editor/CallSavedWorkflowSyncRuntime', () => ({ CallSavedWorkflowSyncRuntime: () => null }));+vi.mock('./library/WorkflowPublicationHost', () => ({ WorkflowPublicationHost: () => null }));+vi.mock('./PendingLibraryWorkflowLoader', () => ({ PendingWorkflowLoader: () => null }));+vi.mock('./library/WorkflowLibraryDialog', () => ({+ WorkflowLibraryDialog: ({ isOpen }: { isOpen: boolean }) => (isOpen ? <p>loaded library</p> : null),+}));+vi.mock('./graph-preview/WorkflowPreviewJson', () => ({ default: () => <p>loaded JSON</p> }));+vi.mock('./graph-preview/GraphPreviewDialog', () => ({ WorkflowDocumentGraph: () => <p>loaded graph</p> }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++it('keeps failed library and preview imports local and recovers them without reloading the page', async () => {+ const host = document.createElement('div');+ document.body.append(host);+ const root = createRoot(host);+ const workflow = { document: createProjectGraph('workflow') };+ const project = {+ activeWorkflow: workflow,+ activeWorkflowId: 'workflow',+ galleryValues: {},+ id: 'project',+ isWorkflowRunning: false,+ projectGraph: workflow.document,+ workflows: [workflow],+ workflowValues: {},+ };+ const adapter = {+ commands: { renameWorkflow: vi.fn() },+ project: { getSnapshot: () => project, subscribe: () => () => {} },+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ } as unknown as WorkflowUiAdapter;+ const render = (children: React.ReactNode) =>+ act(() =>+ root.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>{children}</WorkflowUiProvider>+ </ChakraProvider>+ </StrictMode>+ )+ );+ const retry = () => act(() => userEvent.click(page.getByRole('button', { name: 'common.retry' })));++ try {+ setWorkflowLibraryOpen(true);+ await render(<WorkflowDialogHost />);+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')?.textContent).toContain('workflowLibrary.dialogLoadFailed')+ );+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(workflowUiStore.getSnapshot().isLibraryOpen).toBe(false));+ // The import failure must leave the rest of this host usable, rather than trip the widget's boundary.+ await act(() => requestWorkflowRename('workflow'));+ await expect.element(page.getByRole('textbox')).toBeVisible();+ await act(() => userEvent.keyboard('{Escape}'));+ await act(() => setWorkflowLibraryOpen(true));+ chunk.fails = false;+ await retry();+ await vi.waitFor(() => expect(host.textContent).toContain('loaded library'));+ await act(() => setWorkflowLibraryOpen(false));++ chunk.fails = true;+ await render(+ <WorkflowPreviewJson copyFailedLabel="failed" copyLabel="copy" getText={() => '{}'} label="Graph JSON" />+ );+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')?.textContent).toContain('workflowLibrary.preview.loadFailed')+ );+ chunk.fails = false;+ await retry();+ await vi.waitFor(() => expect(host.textContent).toContain('loaded JSON'));++ chunk.fails = true;+ const onError = vi.fn();+ await render(+ <DeferredGraphPreviewSnapshot+ graph={{ edges: [], id: 'graph', nodes: [], version: 1 }}+ onCapture={vi.fn()}+ onError={onError}+ />+ );+ await vi.waitFor(() => expect(onError).toHaveBeenCalled());+ expect(onError.mock.calls[0]![0]).toBeInstanceOf(TypeError);+ await render(null);+ const props = {} as ComponentProps<typeof DeferredWorkflowDocumentGraph>;+ await render(<DeferredWorkflowDocumentGraph {...props} />);+ await vi.waitFor(() =>+ expect(document.querySelector('[role="alert"]')?.textContent).toContain('workflowLibrary.preview.loadFailed')+ );+ chunk.fails = false;+ await retry();+ await vi.waitFor(() => expect(host.textContent).toContain('loaded graph'));+ } finally {+ await act(() => root.unmount());+ host.remove();+ setWorkflowLibraryOpen(false);+ workflowUiStore.patchSnapshot({ renameRequest: null });+ }+});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 3980ce21df..5df928b6f4 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@@ -13,11 +13,17 @@ 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, userEvent } from 'vitest/browser';+import { registerWorkflowFlowInstance, releaseWorkflowFlowInstance } from './editor/flowInstanceStore';+import { registerWorkflowPngExportHost } from './editor/workflowPngExport';import { WorkflowUiProvider } from './WorkflowUiContext';-import { clearWorkflowPublicationIntent, workflowUiStore } from './workflowUiStore';+import { clearWorkflowPublicationIntent, setWorkflowLibraryOpen, workflowUiStore } from './workflowUiStore';import { WorkflowHeaderActions, WorkflowMenuItems, WorkflowWidgetLabel } from './WorkflowWidgetChrome';+// The export's run loads on first use; loading it here keeps that first load out of each test's waits.+await import('./editor/workflowPngExportRun');+const { copyWorkflowJsonMock, downloadWorkflowJsonMock, getLibraryWorkflowRecordMock } = vi.hoisted(() => ({copyWorkflowJsonMock: vi.fn(),downloadWorkflowJsonMock: vi.fn(),@@ -47,16 +53,39 @@ vi.mock('./workflowTransfer', () => ({downloadWorkflowJson: downloadWorkflowJsonMock,}));+const imageExport = vi.hoisted(() => ({+ exportWorkflowAsPng: vi.fn(),+ preflightWorkflowImageExport: vi.fn(),+}));++vi.mock('./editor/workflowImageExport', () => imageExport);++const clipboard = vi.hoisted(() => ({ canCopyText: vi.fn(() => true) }));++vi.mock('@platform/browser/clipboard', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ canCopyText: clipboard.canCopyText,+}));+const TRANSLATIONS: Record<string, string> = {'projects.exportFailed': 'Export failed','widgets.labels.workflow': 'Workflow','widgets.workflow.addNode': 'Add node',- 'widgets.workflow.copyJson': 'Copy workflow JSON',+ 'common.copyUnavailable': 'Copying needs HTTPS or localhost',+ 'widgets.workflow.copyJson': 'Copy JSON','widgets.workflow.copyJsonFailed': 'Failed to copy workflow JSON',- 'widgets.workflow.detailsWithEllipsis': 'Workflow details…',- 'widgets.workflow.renameWithEllipsis': 'Rename workflow…',- 'widgets.workflow.exportJson': 'Export workflow JSON',- 'widgets.workflow.importJsonWithEllipsis': 'Import workflow JSON…',+ 'widgets.workflow.detailsWithEllipsis': 'Details…',+ 'widgets.workflow.downloadPng': 'Download as PNG',+ 'widgets.workflow.downloadPngUnavailable': 'Open the workflow editor to download it as an image',+ 'widgets.workflow.downloadPngRunning': 'Already downloading the workflow as an image',+ 'widgets.workflow.export': 'Export',+ 'widgets.workflow.exportJson': 'Export JSON',+ 'widgets.workflow.importJsonWithEllipsis': 'Import from JSON…',+ 'widgets.workflow.menuImportExport': 'Import and export',+ 'widgets.workflow.menuThisWorkflow': 'This workflow',+ 'widgets.workflow.renameWithEllipsis': 'Rename…',+ 'widgets.workflow.saveAsNewTemplateWithEllipsis': 'Save as new template…',+ 'widgets.workflow.inThisProject': 'In this project','widgets.workflow.library': 'Workflow library','widgets.workflow.libraryWithEllipsis': 'Workflow library…','widgets.workflow.newWorkflow': 'New workflow',@@ -67,6 +96,7 @@ const TRANSLATIONS: Record<string, string> = {'widgets.workflow.persistenceSaved': 'Project saved to the server','widgets.workflow.persistenceSaving': 'Saving project…','widgets.workflow.saveToLibraryWithEllipsis': 'Save to library…',+ 'widgets.workflow.switchWorkflow': 'Switch workflow','widgets.workflow.linkedTemplateUnnamed': 'Linked to a library template','widgets.workflow.untitled': 'Untitled Workflow','widgets.workflow.updateTemplateWithEllipsis': 'Update library template…',@@ -85,7 +115,9 @@ vi.mock('react-i18next', () => ({? `Linked to library template "${String(options?.name)}"`: key === 'workflowLibrary.sourceRevision'? `Linked to library template at revision ${String(options?.revision)}`- : (TRANSLATIONS[key] ?? key),+ : key === 'widgets.workflow.switchWorkflowTrigger'+ ? `Switch workflow. Current workflow: ${String(options?.name)}`+ : (TRANSLATIONS[key] ?? key),}),}));@@ -159,6 +191,7 @@ describe('WorkflowMenuItems', () => {let root: Root;let notifications: WorkflowUiAdapter['notifications'];let commands: ReturnType<typeof createCommands>;+ const releases: (() => void)[] = [];beforeEach(() => {host = document.createElement('div');@@ -166,6 +199,9 @@ describe('WorkflowMenuItems', () => {root = createRoot(host);copyWorkflowJsonMock.mockReset();downloadWorkflowJsonMock.mockReset();+ imageExport.exportWorkflowAsPng.mockReset().mockResolvedValue({ status: 'exported', reduced: false });+ imageExport.preflightWorkflowImageExport.mockReset().mockReturnValue(null);+ clipboard.canCopyText.mockReturnValue(true);identity.session = { multiuserEnabled: false, phase: 'ready', user: null };clearWorkflowPublicationIntent();notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };@@ -173,6 +209,9 @@ describe('WorkflowMenuItems', () => {});afterEach(async () => {+ for (const release of releases.splice(0)) {+ release();+ }await act(() => root.unmount());host.remove();clearWorkflowPublicationIntent();@@ -205,15 +244,155 @@ describe('WorkflowMenuItems', () => {);});};+ /** A mounted editor, as far as the PNG export needs one: its offscreen view and its flow instance. */+ const mountEditor = () => {+ const flowElement = document.createElement('div');+ const flow = {+ getNodes: () => [{ id: 'node-1' }],+ getNodesBounds: () => ({ height: 10, width: 10, x: 0, y: 0 }),+ } as unknown as Parameters<typeof registerWorkflowFlowInstance>[0];+ const prepare = vi.fn(() => Promise.resolve(flowElement));+ const complete = vi.fn();++ registerWorkflowFlowInstance(flow);+ releases.push(registerWorkflowPngExportHost({ complete, prepare }), () => releaseWorkflowFlowInstance(flow));++ return { complete, flowElement, prepare };+ };++ const menuItem = (name: string) => page.getByRole('menuitem', { exact: true, name });+ const groupItems = (name: string) =>+ Array.from(+ page.getByRole('group', { name }).element().querySelectorAll('[role="menuitem"]'),+ (item) => item.textContent+ );+ const openExport = async () => {+ await act(() => userEvent.click(menuItem('Export')));+ await expect.element(menuItem('Export JSON')).toBeVisible();+ };++ it('groups this workflow’s actions apart from import and export, with no library or new workflow', async () => {+ await renderMenu(createProjectGraph('workflow-1'));++ expect(+ Array.from(host.querySelectorAll('[role="group"]'), (group) => group.getAttribute('aria-labelledby'))+ ).toHaveLength(2);+ expect(groupItems('This workflow')).toEqual(['Rename…', 'Details…', 'Save to library…']);+ expect(groupItems('Import and export')).toEqual(['Import from JSON…', 'Export']);+ expect(menuItem('Export').element().getAttribute('aria-haspopup')).toBe('menu');+ // The breadcrumb's switcher carries both now.+ expect(host.textContent).not.toContain('Workflow library…');+ expect(host.textContent).not.toContain('New workflow');+ // Every row leads with its icon.+ for (const item of host.querySelectorAll('[role="menuitem"]')) {+ expect(item.querySelector('svg')).not.toBeNull();+ }+ });++ it('exports, copies and draws the workflow from the Export submenu through the existing commands', async () => {+ const graph = { ...createProjectGraph('workflow-1'), name: 'Portraits' };+ const editor = mountEditor();+ copyWorkflowJsonMock.mockResolvedValue(undefined);+ await renderMenu(graph);++ await openExport();+ expect(+ Array.from(+ document.querySelectorAll('[role="menu"]')[1]!.querySelectorAll('[role="menuitem"]'),+ (item) => item.textContent+ )+ ).toEqual(['Export JSON', 'Copy JSON', 'Download as PNG']);+ await act(() => userEvent.click(menuItem('Export JSON')));+ expect(downloadWorkflowJsonMock).toHaveBeenCalledExactlyOnceWith(graph);++ await openExport();+ await act(() => userEvent.click(menuItem('Copy JSON')));+ expect(copyWorkflowJsonMock).toHaveBeenCalledExactlyOnceWith(graph);+ await vi.waitFor(() => expect(notifications.success).toHaveBeenCalledOnce());++ await openExport();+ await act(() => userEvent.click(menuItem('Download as PNG')));+ await vi.waitFor(() => expect(editor.complete).toHaveBeenCalledOnce());+ expect(imageExport.exportWorkflowAsPng).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ flowElement: editor.flowElement, workflowName: 'Portraits' })+ );+ expect(notifications.error).not.toHaveBeenCalled();+ });++ it('opens Export from the keyboard and closes it back to its row', async () => {+ await renderMenu(createProjectGraph('workflow-1'));+ const highlighted = () =>+ Array.from(document.querySelectorAll('[role="menu"] [data-highlighted]'), (item) => item.textContent);++ await act(() => (host.querySelector('[role="menu"]') as HTMLElement).focus());+ for (let step = 0; step < 5; step += 1) {+ await act(() => userEvent.keyboard('{ArrowDown}'));+ await act(() => new Promise(requestAnimationFrame));+ }+ expect(highlighted()).toEqual(['Export']);- const menuItems = () => Array.from(host.querySelectorAll<HTMLElement>('[role="menuitem"]'));- const menuItem = (text: string) => menuItems().find((item) => item.textContent === text);+ await act(() => userEvent.keyboard('{ArrowRight}'));+ await vi.waitFor(() => expect(highlighted()).toEqual(['Export', 'Export JSON']));+ await act(() => userEvent.keyboard('{ArrowLeft}'));+ await vi.waitFor(() => expect(document.querySelectorAll('[role="menu"]')).toHaveLength(1));+ expect(highlighted()).toEqual(['Export']);+ });++ it('explains why the image or the copy is unavailable instead of acting', async () => {+ clipboard.canCopyText.mockReturnValue(false);+ await renderMenu(createProjectGraph('workflow-1'));+ await openExport();++ // No editor is mounted, as when the panel shows only the form.+ await expect.element(menuItem('Download as PNG')).toHaveAttribute('aria-disabled', 'true');+ await expect+ .element(menuItem('Download as PNG'))+ .toHaveAccessibleDescription('Open the workflow editor to download it as an image');+ await expect.element(menuItem('Copy JSON')).toHaveAttribute('aria-disabled', 'true');+ await act(() => (menuItem('Download as PNG').element() as HTMLElement).click());+ await act(() => (menuItem('Copy JSON').element() as HTMLElement).click());++ expect(imageExport.exportWorkflowAsPng).not.toHaveBeenCalled();+ expect(copyWorkflowJsonMock).not.toHaveBeenCalled();+ });++ it('says an image download is already running until it finishes', async () => {+ const editor = mountEditor();+ let finishPreparing: (element: HTMLDivElement) => void = () => undefined;+ editor.prepare.mockReturnValueOnce(+ new Promise((resolve) => {+ finishPreparing = resolve;+ })+ );+ await renderMenu(createProjectGraph('workflow-1'));++ await openExport();+ await act(() => userEvent.click(menuItem('Download as PNG')));+ await vi.waitFor(() => expect(editor.prepare).toHaveBeenCalledOnce());+ await openExport();++ await expect.element(menuItem('Download as PNG')).toHaveAttribute('aria-disabled', 'true');+ await expect+ .element(menuItem('Download as PNG'))+ .toHaveAccessibleDescription('Already downloading the workflow as an image');+ await act(() => (menuItem('Download as PNG').element() as HTMLElement).click());++ await act(async () => {+ finishPreparing(editor.flowElement);+ await vi.waitFor(() => expect(editor.complete).toHaveBeenCalledOnce());+ });+ await expect.element(menuItem('Download as PNG')).not.toHaveAttribute('aria-disabled');+ expect(editor.prepare).toHaveBeenCalledOnce();+ expect(imageExport.exportWorkflowAsPng).toHaveBeenCalledOnce();+ });it('blocks export and copy with action-specific translated feedback', async () => {await renderMenu(duplicateReturnGraph());- await act(() => menuItem('Export workflow JSON')?.click());- await act(() => menuItem('Copy workflow JSON')?.click());+ await openExport();+ await act(() => userEvent.click(menuItem('Export JSON')));+ await openExport();+ await act(() => userEvent.click(menuItem('Copy JSON')));expect(downloadWorkflowJsonMock).not.toHaveBeenCalled();expect(copyWorkflowJsonMock).not.toHaveBeenCalled();@@ -229,23 +408,19 @@ describe('WorkflowMenuItems', () => {);});- it('starts a new workflow beside the others without asking for confirmation', async () => {+ it('asks the dialog host to import a workflow file', async () => {await renderMenu(createProjectGraph('workflow-1'));+ const before = workflowUiStore.getSnapshot().importRequestCount;- const item = menuItem('New workflow');- expect(item).not.toBeUndefined();-- await act(() => item?.click());+ await act(() => userEvent.click(menuItem('Import from JSON…')));- expect(commands.createWorkflow).toHaveBeenCalledTimes(1);- // Nothing is replaced, so nothing stands between the click and the new workflow.- expect(document.querySelector('[role="alertdialog"]')).toBeNull();+ expect(workflowUiStore.getSnapshot().importRequestCount).toBe(before + 1);});it('asks the publication host to save the active workflow as a new template', async () => {await renderMenu(createProjectGraph('workflow-1'));- await act(() => menuItem('Save to library…')?.click());+ await act(() => userEvent.click(menuItem('Save to library…')));expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({ kind: 'save-as-new', workflowId: 'workflow-1' });});@@ -253,29 +428,31 @@ describe('WorkflowMenuItems', () => {it('asks the dialog host to rename the active workflow, naming it', async () => {await renderMenu(createProjectGraph('workflow-1'));- await act(() => menuItem('Rename workflow…')?.click());+ await act(() => userEvent.click(menuItem('Rename…')));expect(workflowUiStore.getSnapshot().renameRequest).toMatchObject({ workflowId: 'workflow-1' });});- it('offers a template update only for a workflow whose source can be written', async () => {+ it('offers a template update only for a workflow whose source can be written, and then names the save for what it makes', async () => {+ const thisWorkflow = () => groupItems('This workflow');+await renderMenu(createProjectGraph('workflow-1'));- expect(menuItem('Update library template…')).toBeUndefined();+ expect(thisWorkflow()).toEqual(['Rename…', 'Details…', 'Save to library…']);await renderMenu(createProjectGraph('workflow-1'), { libraryWorkflowId: 'default_text', revision: 1 });- expect(menuItem('Update library template…')).toBeUndefined();+ expect(thisWorkflow()).toEqual(['Rename…', 'Details…', 'Save to library…']);await renderMenu(createProjectGraph('workflow-1'), { libraryWorkflowId: 'lib-1', revision: 4 });+ expect(thisWorkflow()).toEqual(['Rename…', 'Details…', 'Save as new template…', 'Update library template…']);- const item = menuItem('Update library template…');- expect(item).not.toBeUndefined();-- await act(() => item?.click());-+ await act(() => userEvent.click(menuItem('Update library template…')));expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({kind: 'update-source',workflowId: 'workflow-1',});+ // Saving a linked workflow still makes a new template; only its label changes.+ await act(() => userEvent.click(menuItem('Save as new template…')));+ expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({ kind: 'save-as-new', workflowId: 'workflow-1' });identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } };await renderMenu(createProjectGraph('workflow-1'), {@@ -283,32 +460,23 @@ describe('WorkflowMenuItems', () => {ownerUserId: 'another-user',revision: 4,});- expect(menuItem('Update library template…')).toBeUndefined();- const saveAsNew = menuItem('Save to library…');- expect(saveAsNew).not.toBeUndefined();-- await act(() => saveAsNew?.click());-- expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({- kind: 'save-as-new',- workflowId: 'workflow-1',- });+ expect(thisWorkflow()).toEqual(['Rename…', 'Details…', 'Save to library…']);});it('matches persisted source ownership against the current account and fails closed without an owner', async () => {const source = { libraryWorkflowId: 'lib-1', ownerUserId: 'user-a', revision: 4 };+ const canUpdate = () => groupItems('This workflow').includes('Update library template…');identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } };await renderMenu(createProjectGraph('workflow-1'), source);- expect(menuItem('Update library template…')).not.toBeUndefined();+ expect(canUpdate()).toBe(true);identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-b' } };await renderMenu(createProjectGraph('workflow-1'), source);- expect(menuItem('Update library template…')).toBeUndefined();- expect(menuItem('Save to library…')).not.toBeUndefined();+ expect(canUpdate()).toBe(false);identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } };await renderMenu(createProjectGraph('workflow-1'), { libraryWorkflowId: 'lib-1', revision: 4 });- expect(menuItem('Update library template…')).toBeUndefined();+ expect(canUpdate()).toBe(false);});});@@ -415,6 +583,8 @@ describe('WorkflowHeaderActions', () => {describe('WorkflowWidgetLabel', () => {let host: HTMLDivElement;let root: Root;+ let commands: ReturnType<typeof createCommands>;+ let project: ReturnType<typeof createMutablePort<ReturnType<typeof projectWithWorkflows>>>;beforeEach(() => {host = document.createElement('div');@@ -422,18 +592,38 @@ describe('WorkflowWidgetLabel', () => {root = createRoot(host);identity.session = { multiuserEnabled: false, phase: 'ready', user: null };getLibraryWorkflowRecordMock.mockReset().mockResolvedValue({ name: 'Portrait template' });+ commands = createCommands();});afterEach(async () => {await act(() => root.unmount());host.remove();+ setWorkflowLibraryOpen(false);});- const renderLabel = async (source?: ProjectWorkflowSource) => {- const graph = { ...createProjectGraph('workflow-1'), name: 'Portraits' };- const project = createMutablePort(projectSnapshot(graph, source));+ const workflow = (id: string, name: string, source?: ProjectWorkflowSource) => ({+ document: { ...createProjectGraph(id), name },+ source,+ });+ const projectWithWorkflows = (workflows: ReturnType<typeof workflow>[], activeWorkflowId: string) => {+ const activeWorkflow = workflows.find((entry) => entry.document.id === activeWorkflowId)!;++ return {+ activeWorkflow,+ activeWorkflowId,+ galleryValues: {},+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph: activeWorkflow.document,+ workflowValues: {},+ workflows,+ };+ };++ const renderProject = async (snapshot: ReturnType<typeof projectWithWorkflows>) => {+ project = createMutablePort(snapshot);// eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapter- const adapter = { project: project.port } as unknown as WorkflowUiAdapter;+ const adapter = { commands, project: project.port } as unknown as WorkflowUiAdapter;await act(() => {root.render(@@ -447,9 +637,30 @@ describe('WorkflowWidgetLabel', () => {);});};+ const renderLabel = (source?: ProjectWorkflowSource) =>+ renderProject(projectWithWorkflows([workflow('workflow-1', 'Portraits', source)], 'workflow-1'));+ const PROJECT_WORKFLOWS = [+ workflow('workflow-1', 'Text 2 Image'),+ workflow('workflow-2', 'Upscale'),+ workflow('workflow-3', ''),+ workflow('workflow-4', 'Background swap'),+ ];+const workflowsButton = () => host.querySelector<HTMLElement>('[data-template-link]')!.closest('button')!;const linkDescription = () =>document.getElementById(workflowsButton().getAttribute('aria-describedby') ?? '')?.textContent ?? null;+ const menu = () => document.querySelector<HTMLElement>('[role="menu"]');+ const choices = () =>+ Array.from(document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')).map((item) => ({+ checked: item.getAttribute('aria-checked'),+ name: item.textContent,+ }));+ const libraryItem = () => page.getByRole('menuitem', { name: 'Workflow library…' });+ const openMenu = async () => {+ await act(() => userEvent.click(workflowsButton()));+ await vi.waitFor(() => expect(menu()).toBeVisible());+ };+ const expectClosed = () => vi.waitFor(() => expect(menu()).toBeNull());it('describes the link state on the workflow name: unlinked, bundled, or linked', async () => {await renderLabel();@@ -479,4 +690,206 @@ describe('WorkflowWidgetLabel', () => {await vi.waitFor(() => expect(linkDescription()).toBe('Linked to library template "Portrait template"'));expect(getLibraryWorkflowRecordMock).toHaveBeenCalledWith('library-1', expect.anything());});++ it('names the current workflow on a menu trigger whose list mounts only while open', async () => {+ await renderProject(projectWithWorkflows(PROJECT_WORKFLOWS, 'workflow-2'));++ await expect+ .element(page.getByRole('button', { name: 'Switch workflow. Current workflow: Upscale' }))+ .toHaveAttribute('aria-haspopup', 'menu');+ expect(workflowsButton()).toHaveAccessibleDescription('Not linked to a library template');+ expect(document.querySelectorAll('[role="menuitemradio"]')).toHaveLength(0);+ });++ it('lists the project’s workflows in project order with the active one checked', async () => {+ await renderProject(projectWithWorkflows(PROJECT_WORKFLOWS, 'workflow-2'));+ await openMenu();++ expect(choices()).toEqual([+ { checked: 'false', name: 'Text 2 Image' },+ { checked: 'true', name: 'Upscale' },+ { checked: 'false', name: 'Untitled Workflow' },+ { checked: 'false', name: 'Background swap' },+ ]);+ await expect.element(page.getByRole('group', { name: 'In this project' })).toBeVisible();+ // New workflow and the library follow, past a separator.+ const items = menu()!.querySelectorAll('[role="menuitemradio"], [role="menuitem"], [role="separator"]');+ expect(Array.from(items, (item) => item.textContent || item.getAttribute('role')).slice(-3)).toEqual([+ 'separator',+ 'New workflow',+ 'Workflow library…',+ ]);+ });++ it('opens another workflow through the project’s select command and closes', async () => {+ await renderProject(projectWithWorkflows(PROJECT_WORKFLOWS, 'workflow-2'));+ await openMenu();++ await act(() => userEvent.click(page.getByRole('menuitemradio', { name: 'Background swap' })));++ expect(commands.selectWorkflow).toHaveBeenCalledExactlyOnceWith('workflow-4');+ await expectClosed();+ expect(workflowUiStore.getSnapshot().isLibraryOpen).toBe(false);+ });++ it('only closes when the active workflow is chosen', async () => {+ await renderProject(projectWithWorkflows(PROJECT_WORKFLOWS, 'workflow-2'));+ await openMenu();++ await act(() => userEvent.click(page.getByRole('menuitemradio', { name: 'Upscale' })));++ await expectClosed();+ expect(commands.selectWorkflow).not.toHaveBeenCalled();+ });++ it('opens the library on the project’s workflows with the active one selected', async () => {+ await renderProject(projectWithWorkflows(PROJECT_WORKFLOWS, 'workflow-2'));+ await openMenu();++ await act(() => userEvent.click(libraryItem()));++ await expectClosed();+ expect(workflowUiStore.getSnapshot()).toMatchObject({+ isLibraryOpen: true,+ librarySelection: { projectId: 'project-1', workflowId: 'workflow-2' },+ libraryTab: 'project',+ });+ expect(commands.selectWorkflow).not.toHaveBeenCalled();+ });++ it('opens with every row, so a click on the library straight away reaches it, on a project of several workflows', async () => {+ await renderProject(projectWithWorkflows(PROJECT_WORKFLOWS, 'workflow-2'));+ await act(() => userEvent.click(workflowsButton()));+ const library = () => document.querySelector<HTMLElement>('[data-value="workflow-library"]')!;+ await vi.waitFor(() => expect(library()).not.toBeNull());+ // Every row is there in the commit that opens the menu; nothing arrives later to push the actions down under the+ // pointer, so a click straight away reaches the library.+ expect(choices()).toHaveLength(PROJECT_WORKFLOWS.length);+ await act(() => userEvent.click(library()));+ expect(workflowUiStore.getSnapshot()).toMatchObject({+ isLibraryOpen: true,+ librarySelection: { projectId: 'project-1', workflowId: 'workflow-2' },+ libraryTab: 'project',+ });+ expect(commands.createWorkflow).not.toHaveBeenCalled();+ });++ it('adds a new workflow that becomes the active one, returning focus to the renamed trigger', async () => {+ const snapshot = projectWithWorkflows(PROJECT_WORKFLOWS, 'workflow-2');+ commands.createWorkflow.mockImplementation(() => {+ const created = workflow('workflow-new', 'Fresh workflow');+ project.setSnapshot(projectWithWorkflows([...snapshot.workflows, created], created.document.id));+ return created.document.id;+ });+ await renderProject(snapshot);+ await openMenu();++ const newWorkflow = page.getByRole('menuitem', { name: 'New workflow' });+ // A pointer arriving over an item refocuses the menu a frame later; a click in that same frame would lose the+ // restored focus to it, which a person's pointer never does.+ await act(() => userEvent.hover(newWorkflow));+ await act(() => new Promise(requestAnimationFrame));+ await act(() => userEvent.click(newWorkflow));++ expect(commands.createWorkflow).toHaveBeenCalledOnce();+ expect(commands.selectWorkflow).not.toHaveBeenCalled();+ await expectClosed();+ await vi.waitFor(() =>+ expect(document.activeElement?.getAttribute('aria-label')).toBe(+ 'Switch workflow. Current workflow: Fresh workflow'+ )+ );+ expect(document.activeElement).toBe(workflowsButton());+ await openMenu();+ expect(choices().at(-1)).toEqual({ checked: 'true', name: 'Fresh workflow' });+ });++ it('opens from the keyboard, moves by arrows and typeahead, and returns focus on Escape', async () => {+ await renderProject(projectWithWorkflows(PROJECT_WORKFLOWS, 'workflow-2'));+ const highlighted = () => document.querySelector('[role="menu"] [data-highlighted]')?.textContent;++ for (const key of ['{Enter}', ' ', '{ArrowDown}']) {+ await act(() => workflowsButton().focus());+ await act(() => userEvent.keyboard(key));+ await vi.waitFor(() => expect(menu()).toBeVisible());+ expect(workflowsButton().getAttribute('aria-expanded')).toBe('true');++ await act(() => userEvent.keyboard('{Escape}'));+ await expectClosed();+ expect(document.activeElement).toBe(workflowsButton());+ }++ await act(() => userEvent.keyboard('{ArrowDown}'));+ // Zag moves focus into the open menu a frame later; keys sent before then reach the trigger.+ await vi.waitFor(() => expect(document.activeElement).toBe(menu()));+ expect(highlighted()).toBe('Text 2 Image');+ await act(() => userEvent.keyboard('b'));+ await vi.waitFor(() => expect(highlighted()).toBe('Background swap'));+ await act(() => userEvent.keyboard('{ArrowDown}'));+ await vi.waitFor(() => expect(highlighted()).toBe('New workflow'));+ await act(() => userEvent.keyboard('{ArrowDown}'));+ await vi.waitFor(() => expect(highlighted()).toBe('Workflow library…'));+ await act(() => userEvent.keyboard('{ArrowUp}{ArrowUp}{ArrowUp}{ArrowUp}'));+ await vi.waitFor(() => expect(highlighted()).toBe('Upscale'));+ await act(() => userEvent.keyboard('{ArrowUp}'));+ await vi.waitFor(() => expect(highlighted()).toBe('Text 2 Image'));+ // An arrow refocuses the menu a frame later; Enter in that same frame would lose the restored focus to it.+ await act(() => new Promise(requestAnimationFrame));+ await act(() => userEvent.keyboard('{Enter}'));++ expect(commands.selectWorkflow).toHaveBeenCalledExactlyOnceWith('workflow-1');+ await expectClosed();+ expect(document.activeElement).toBe(workflowsButton());+ });++ it('follows workflows added, renamed, reordered and removed while open', async () => {+ const [first, second] = PROJECT_WORKFLOWS;+ await renderProject(projectWithWorkflows([first!, second!], 'workflow-1'));+ await openMenu();+ const names = () => choices().map((choice) => choice.name);++ await act(() =>+ project.setSnapshot(+ projectWithWorkflows(+ [workflow('workflow-2', 'Upscale 4×'), first!, workflow('workflow-5', 'Inpaint')],+ 'workflow-1'+ )+ )+ );+ expect(names()).toEqual(['Upscale 4×', 'Text 2 Image', 'Inpaint']);++ await act(() => project.setSnapshot(projectWithWorkflows([workflow('workflow-5', 'Inpaint')], 'workflow-5')));+ expect(choices()).toEqual([{ checked: 'true', name: 'Inpaint' }]);+ });++ it('scrolls a long list, opened on the active workflow, under a library item that stays in view', async () => {+ const workflows = Array.from({ length: 60 }, (_, index) => workflow(`workflow-${index}`, `Workflow ${index}`));+ await renderProject(projectWithWorkflows(workflows, 'workflow-45'));+ await openMenu();++ const content = menu()!.getBoundingClientRect();+ const footer = Array.from(menu()!.querySelectorAll<HTMLElement>('[role="menuitem"]'), (item) =>+ item.getBoundingClientRect()+ );+ const viewport = menu()!.querySelector<HTMLElement>('[data-scope="scroll-area"][data-part="viewport"]')!;+ const isInViewport = (name: string) => {+ const item = page.getByRole('menuitemradio', { name }).element().getBoundingClientRect();+ const bounds = viewport.getBoundingClientRect();++ return item.top >= bounds.top - 1 && item.bottom <= bounds.bottom + 1;+ };++ expect(content.bottom).toBeLessThanOrEqual(window.innerHeight);+ expect(viewport.scrollHeight).toBeGreaterThan(viewport.clientHeight);+ expect(footer).toHaveLength(2);+ for (const item of footer) {+ expect(item.top).toBeGreaterThanOrEqual(content.top);+ expect(item.bottom).toBeLessThanOrEqual(content.bottom);+ }+ await vi.waitFor(() => expect(isInViewport('Workflow 45')).toBe(true));++ // The keyboard reaches the end of the list by scrolling it.+ await act(() => userEvent.keyboard('{End}{ArrowUp}{ArrowUp}'));+ await vi.waitFor(() => expect(isInViewport('Workflow 59')).toBe(true));+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowSwitcherLoadFailure.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowSwitcherLoadFailure.browser.test.tsxnew file mode 100644index 0000000000..24d8ab2ebf--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowSwitcherLoadFailure.browser.test.tsx@@ -0,0 +1,155 @@+import type { ProjectWorkflowSource } from '@features/workflow/core/types';+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';+import type * as DeferredModuleModule from '@platform/react/deferredModule';++import { ChakraProvider } from '@chakra-ui/react';+import { createProjectGraph } from '@features/workflow/utility';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { WorkflowUiProvider } from './WorkflowUiContext';+import { setWorkflowLibraryOpen, workflowUiStore } from './workflowUiStore';+import { WorkflowWidgetLabel } from './WorkflowWidgetChrome';++// The later open's real import resolves from the module cache rather than an on-demand transform under suite load.+await import('@platform/ui/ScrollableMenuContent');++// The switcher's scrolling list loads on first use. Here its chunk fails to load at first, as a stale or dropped chunk+// does: the import rejects. Its own file, because a page keeps a module that has loaded, and the rejection comes from+// the deferred module's import seam: a `vi.mock` factory that rejects is not an import failure in browser mode, since+// Vitest's module interception reports it as an unhandled error and never answers the request.+const scrollableChunk = vi.hoisted(() => ({ fails: false, rejected: 0 }));+vi.mock('@platform/react/deferredModule', async (importOriginal) => {+ const actual = await importOriginal<typeof DeferredModuleModule>();++ return {+ ...actual,+ // The scrolling list is the only deferred module the switcher renders.+ createDeferredModule: <Module,>(importModule: () => Promise<Module>) =>+ actual.createDeferredModule(() => {+ if (!scrollableChunk.fails) {+ return importModule();+ }+ scrollableChunk.rejected += 1;+ return Promise.reject(new TypeError('Failed to fetch dynamically imported module'));+ }),+ };+});+vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useAuthSession: () => ({ multiuserEnabled: false, phase: 'ready', user: null }),+}));++const TRANSLATIONS: Record<string, string> = {+ 'widgets.workflow.inThisProject': 'In this project',+ 'widgets.workflow.libraryWithEllipsis': 'Workflow library…',+ 'widgets.workflow.newWorkflow': 'New workflow',+};+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) =>+ key === 'widgets.workflow.switchWorkflowTrigger' ? `Switch ${String(options?.name)}` : (TRANSLATIONS[key] ?? key),+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const workflow = (id: string, name: string, source?: ProjectWorkflowSource) => ({+ document: { ...createProjectGraph(id), name },+ source,+});+const WORKFLOWS = [workflow('workflow-1', 'Text 2 Image'), workflow('workflow-2', 'Upscale')];+const SNAPSHOT = {+ activeWorkflow: WORKFLOWS[1]!,+ activeWorkflowId: 'workflow-2',+ galleryValues: {},+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph: WORKFLOWS[1]!.document,+ workflowValues: {},+ workflows: WORKFLOWS,+};++describe('the workflow switcher when its scrolling list fails to load', () => {+ let host: HTMLDivElement;+ let root: Root;+ const commands = { createWorkflow: vi.fn(() => 'workflow-3'), selectWorkflow: vi.fn() };++ beforeEach(async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ commands.createWorkflow.mockClear();+ setWorkflowLibraryOpen(false);+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapter+ const adapter = {+ commands,+ project: { getSnapshot: () => SNAPSHOT, subscribe: () => () => {} },+ } as unknown as WorkflowUiAdapter;+ await act(() =>+ root.render(+ <QueryClientProvider client={new QueryClient()}>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <WorkflowWidgetLabel region="center" />+ </WorkflowUiProvider>+ </ChakraProvider>+ </QueryClientProvider>+ )+ );+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ setWorkflowLibraryOpen(false);+ });++ const trigger = () => page.getByRole('button', { name: 'Switch Upscale' });+ const menu = () => document.querySelector<HTMLElement>('[role="menu"]');+ const choices = () => [...document.querySelectorAll('[role="menuitemradio"]')].map((item) => item.textContent);+ const themedList = () => menu()?.querySelector('[data-scope="scroll-area"]') ?? null;+ const library = () => document.querySelector<HTMLElement>('[data-value="workflow-library"]')!;+ const openMenu = async () => {+ await act(() => userEvent.click(trigger()));+ await vi.waitFor(() => expect(menu()).toBeVisible());+ // Measured once the menu's open animation has settled.+ await act(() =>+ Promise.all(+ menu()!+ .getAnimations({ subtree: true })+ .map((animation) => animation.finished)+ )+ );+ };+ const expectLibraryOnThisProject = () =>+ expect(workflowUiStore.getSnapshot()).toMatchObject({+ isLibraryOpen: true,+ librarySelection: { projectId: 'project-1', workflowId: 'workflow-2' },+ libraryTab: 'project',+ });++ it('keeps every row and both actions when the list fails, and uses it on a later open', async () => {+ scrollableChunk.fails = true;+ await openMenu();+ await vi.waitFor(() => expect(scrollableChunk.rejected).toBeGreaterThan(0));+ expect(themedList()).toBeNull();+ expect(choices()).toEqual(['Text 2 Image', 'Upscale']);+ await act(() => userEvent.click(page.getByRole('menuitem', { name: 'New workflow' })));+ expect(commands.createWorkflow).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(menu()).toBeNull());++ await openMenu();+ await act(() => userEvent.click(library()));+ expectLibraryOnThisProject();+ await vi.waitFor(() => expect(menu()).toBeNull());++ scrollableChunk.fails = false;+ await openMenu();+ await vi.waitFor(() => expect(themedList()).not.toBeNull());+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowSwitcherLoading.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowSwitcherLoading.browser.test.tsxnew file mode 100644index 0000000000..afe5bc8b06--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowSwitcherLoading.browser.test.tsx@@ -0,0 +1,150 @@+import type { ProjectWorkflowSource } from '@features/workflow/core/types';+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';++import { ChakraProvider } from '@chakra-ui/react';+import { createProjectGraph } from '@features/workflow/utility';+import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { system } from '@theme/system';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { WorkflowUiProvider } from './WorkflowUiContext';+import { setWorkflowLibraryOpen, workflowUiStore } from './workflowUiStore';+import { WorkflowWidgetLabel } from './WorkflowWidgetChrome';++// The switcher's scrolling list loads on first use. Here it is held back until a test releases it; the menu must open+// whole and work before and as it arrives. A list that fails to load: WorkflowSwitcherLoadFailure.browser.test.tsx.+const scrollableChunk = vi.hoisted(() => {+ let release = () => {};+ const loaded = new Promise<void>((resolve) => {+ release = resolve;+ });+ return { loaded, release: () => release() };+});+vi.mock('@platform/ui/ScrollableMenuContent', async (importOriginal) => {+ await scrollableChunk.loaded;+ return importOriginal();+});+vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useAuthSession: () => ({ multiuserEnabled: false, phase: 'ready', user: null }),+}));++const TRANSLATIONS: Record<string, string> = {+ 'widgets.workflow.inThisProject': 'In this project',+ 'widgets.workflow.libraryWithEllipsis': 'Workflow library…',+ 'widgets.workflow.newWorkflow': 'New workflow',+};+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) =>+ key === 'widgets.workflow.switchWorkflowTrigger' ? `Switch ${String(options?.name)}` : (TRANSLATIONS[key] ?? key),+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const workflow = (id: string, name: string, source?: ProjectWorkflowSource) => ({+ document: { ...createProjectGraph(id), name },+ source,+});+const WORKFLOWS = [workflow('workflow-1', 'Text 2 Image'), workflow('workflow-2', 'Upscale')];+const SNAPSHOT = {+ activeWorkflow: WORKFLOWS[1]!,+ activeWorkflowId: 'workflow-2',+ galleryValues: {},+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph: WORKFLOWS[1]!.document,+ workflowValues: {},+ workflows: WORKFLOWS,+};++describe('the workflow switcher while its scrolling list loads', () => {+ let host: HTMLDivElement;+ let root: Root;+ const commands = { createWorkflow: vi.fn(() => 'workflow-3'), selectWorkflow: vi.fn() };++ beforeEach(async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ commands.createWorkflow.mockClear();+ setWorkflowLibraryOpen(false);+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapter+ const adapter = {+ commands,+ project: { getSnapshot: () => SNAPSHOT, subscribe: () => () => {} },+ } as unknown as WorkflowUiAdapter;+ await act(() =>+ root.render(+ <QueryClientProvider client={new QueryClient()}>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <WorkflowWidgetLabel region="center" />+ </WorkflowUiProvider>+ </ChakraProvider>+ </QueryClientProvider>+ )+ );+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ setWorkflowLibraryOpen(false);+ });++ const trigger = () => page.getByRole('button', { name: 'Switch Upscale' });+ const menu = () => document.querySelector<HTMLElement>('[role="menu"]');+ const choices = () => [...document.querySelectorAll('[role="menuitemradio"]')].map((item) => item.textContent);+ const themedList = () => menu()?.querySelector('[data-scope="scroll-area"]') ?? null;+ const library = () => document.querySelector<HTMLElement>('[data-value="workflow-library"]')!;+ const openMenu = async () => {+ await act(() => userEvent.click(trigger()));+ await vi.waitFor(() => expect(menu()).toBeVisible());+ // Measured once the menu's open animation has settled.+ await act(() =>+ Promise.all(+ menu()!+ .getAnimations({ subtree: true })+ .map((animation) => animation.finished)+ )+ );+ };+ const expectLibraryOnThisProject = () =>+ expect(workflowUiStore.getSnapshot()).toMatchObject({+ isLibraryOpen: true,+ librarySelection: { projectId: 'project-1', workflowId: 'workflow-2' },+ libraryTab: 'project',+ });++ it('opens whole before its list loads, keeps its actions in place as the list arrives, and works throughout', async () => {+ const wasDark = document.documentElement.classList.contains('dark');+ document.documentElement.classList.add('dark');+ onTestFinished(() => {+ document.documentElement.classList.toggle('dark', wasDark);+ });+ await openMenu();+ expect(themedList()).toBeNull();+ expect(choices()).toEqual(['Text 2 Image', 'Upscale']);+ expect(await auditAccessibility(menu()!)).toEqual([]);+ await act(() => userEvent.click(library()));+ expectLibraryOnThisProject();+ await vi.waitFor(() => expect(menu()).toBeNull());++ setWorkflowLibraryOpen(false);+ await openMenu();+ const before = library().getBoundingClientRect().top;+ await act(() => scrollableChunk.release());+ await vi.waitFor(() => expect(themedList()).not.toBeNull(), { timeout: 8000 });+ expect(library().getBoundingClientRect().top).toBe(before);+ expect(await auditAccessibility(menu()!)).toEqual([]);+ expect(menu()!.contains(document.activeElement)).toBe(true);+ await act(() => userEvent.click(library()));+ expectLibraryOnThisProject();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsxindex 62b562f271..417db51b7a 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx@@ -114,8 +114,6 @@ describe('Workflow UI read-port isolation', () => {let setGraphPreview: ((adapter: WorkflowGraphPreviewPort) => void) | null = null;const initialGraphPreview: WorkflowGraphPreviewPort = {focusSource: () => {},- getRoute: () => null,- invoke: () => Promise.resolve(false),openDocumentInNewProject: () => {},openWorkflowEditor: () => {},};@@ -186,8 +184,6 @@ describe('Workflow UI read-port isolation', () => {await act(() =>setGraphPreview?.({focusSource: () => {},- getRoute: () => null,- invoke: () => Promise.resolve(true),openDocumentInNewProject: () => {},openWorkflowEditor: () => {},})@@ -195,8 +191,6 @@ describe('Workflow UI read-port isolation', () => {await act(() =>setGraphPreview?.({focusSource: () => {},- getRoute: () => null,- invoke: () => Promise.resolve(false),openDocumentInNewProject: () => {},openWorkflowEditor: () => {},})diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsxindex 68b7a4e0d2..0e1d88e060 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx@@ -1,7 +1,7 @@import type { GalleryItemRef } from '@features/gallery/contracts';-import type { ForLoopValidationReason } from '@features/workflow/core/forLoops';import type { ProjectGraphState, ProjectWorkflowEntry, ProjectWorkflowSource } from '@features/workflow/core/types';-import type { WorkflowLibrarySort } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibrarySort, WorkflowLibrarySortDirection } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibraryCardSize } from '@features/workflow/ui/library/workflowThumbnail';import type { WorkbenchThemeId } from '@theme/themes';import type { ComponentType, ReactNode } from 'react';@@ -19,13 +19,19 @@ import type {/** How workflow thumbnails sit in their 3:2 box: cropped to fill it, or letterboxed whole. */export type WorkflowThumbnailFit = 'cover' | 'contain';+/** Whether the library and This project show workflows as a card grid or as list rows. */+export type WorkflowLibraryLayout = 'grid' | 'list';+export interface WorkflowPreferences {reduceMotion: boolean;themeId: WorkbenchThemeId;workflowEdgeStyle: 'curved' | 'square';workflowEdgesBehindNodes: boolean;workflowGroupNodesByCategory: boolean;+ workflowLibraryCardSize: WorkflowLibraryCardSize;+ workflowLibraryLayout: WorkflowLibraryLayout;workflowLibrarySort: WorkflowLibrarySort;+ workflowLibrarySortDirection: WorkflowLibrarySortDirection;workflowLibraryThumbnailFit: WorkflowThumbnailFit;workflowShowMinimap: boolean;workflowSnapToGrid: boolean;@@ -70,10 +76,6 @@ export interface WorkflowReadPort<Snapshot> {}export interface WorkflowGraphPreviewPort {- getRoute(- sourceId?: WorkflowInvocationSourceId- ): { canInvoke: boolean; label: string; validationMessage?: string | ForLoopValidationReason } | null;- invoke(sourceId?: WorkflowInvocationSourceId): Promise<boolean>;focusSource(sourceId?: WorkflowInvocationSourceId): void; // reveal the source's widget (provenance links)openWorkflowEditor(): void; // reveal the workflow editor widget/** Forks a document into a fresh project; a library source travels with it so the copy can update its template. */@@ -93,7 +95,16 @@ export interface WorkflowUiAdapter {getProjectGraph(): ProjectGraphState;/** Saves the library's account-bound display choices. */setLibraryPreferences(- patch: Partial<Pick<WorkflowPreferences, 'workflowLibrarySort' | 'workflowLibraryThumbnailFit'>>+ patch: Partial<+ Pick<+ WorkflowPreferences,+ | 'workflowLibraryCardSize'+ | 'workflowLibraryLayout'+ | 'workflowLibrarySort'+ | 'workflowLibrarySortDirection'+ | 'workflowLibraryThumbnailFit'+ >+ >): void;notifications: {error(title: string, message?: string): void;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex a640f51a9a..1bc6f0afee 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -1,9 +1,11 @@import type { InvocationTemplate, ProjectWorkflowSource, XYPosition } from '@features/workflow/contracts';+import type * as ScrollableMenuModule from '@platform/ui/ScrollableMenuContent';-import { Box, HStack, Icon, Menu, Stack, Text, VisuallyHidden } from '@chakra-ui/react';+import { Box, Center, HStack, Icon, Menu, Portal, Spinner, Stack, Text, VisuallyHidden } from '@chakra-ui/react';import { useAuthSession } from '@features/identity';import { savedWorkflowDetailQueryOptions } from '@features/workflow/data/savedWorkflowQueries';import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';+import { isBundledLibraryWorkflowId } from '@features/workflow/queries';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {buildConnectorNode,@@ -23,38 +25,54 @@ import {summarizeWorkflowLoadWarnings,} from '@features/workflow/utility';import { canCopyText } from '@platform/browser/clipboard';+import { createDeferredModule } from '@platform/react/deferredModule';import { useMountEffect } from '@platform/react/useMountEffect';import { Button, IconButton, RenameDialog, Tooltip } from '@platform/ui';-import { MenuItem } from '@platform/ui/Menu';+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 { useTooltipTriggerIds } from '@platform/ui/Tooltip';import { useQuery } from '@tanstack/react-query';import {BookmarkIcon,BookUpIcon,+ CameraIcon,+ CheckIcon,+ ChevronDownIcon,+ ChevronRightIcon,CloudAlertIcon,CloudCheckIcon,CloudIcon,+ CopyIcon,+ DownloadIcon,+ FileDownIcon,+ InfoIcon,LibraryIcon,Link2Icon,Link2OffIcon,LockIcon,+ PencilIcon,PlusIcon,RefreshCwIcon,TriangleAlertIcon,+ UploadIcon,} from 'lucide-react';import { useCallback, useEffect, useId, useMemo, useRef, useState, type ChangeEvent, type ElementType } from 'react';import { useTranslation } from 'react-i18next';import type { WorkflowWidgetLabelProps, WorkflowWidgetViewProps } from './contracts';-import type { WorkflowProjectPersistence } from './WorkflowUiContext';+import type * as WorkflowLibraryDialogModule from './library/WorkflowLibraryDialog';+import type { WorkflowProjectPersistence, WorkflowProjectSnapshot } from './WorkflowUiContext';import { AddNodeDialog } from './editor/AddNodeDialog';import { CallSavedWorkflowSyncRuntime } from './editor/CallSavedWorkflowSyncRuntime';import { getWorkflowViewCenter } from './editor/flowInstanceStore';+import { exportWorkflowPng, useWorkflowPngExportState } from './editor/workflowPngExport';import { releaseWorkflowViewportsExcept } from './editor/workflowViewportStore';import { LibraryCopyChoiceHost } from './library/LibraryCopyChoiceDialog';-import { isBundledLibraryWorkflowId, isUpdatableSource } from './library/projectWorkflowEntries';-import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';+import { isUpdatableSource } from './library/projectWorkflowEntries';import { WorkflowPublicationHost } from './library/WorkflowPublicationHost';import { PendingWorkflowLoader } from './PendingLibraryWorkflowLoader';import { copyWorkflowJson, downloadWorkflowJson } from './workflowTransfer';@@ -80,6 +98,191 @@ import {* actions, and shared menu actions.*/+/**+ * The library dialog's chunk (cards, rails, toolbar, detail sheet) stays out of the editor's startup bundle until the+ * library first opens; its entry points preload it on hover or focus so that opening feels immediate. A failed load+ * (an offline moment, a redeploy) retries on the next attempt.+ */+const workflowLibraryDialog = createDeferredModule(() => import('./library/WorkflowLibraryDialog'));+const preloadWorkflowLibraryDialog = workflowLibraryDialog.preload;++const handleLibraryPlaceholderOpenChange = ({ open }: { open: boolean }) => setWorkflowLibraryOpen(open);++const WorkflowLibraryDialogLoader = ({ isOpen }: { isOpen: boolean }) => {+ const { t } = useTranslation();+ const [attempt, setAttempt] = useState(0);+ const retry = useCallback(() => setAttempt((value) => value + 1), []);+ const renderDialog = useCallback(+ (module: typeof WorkflowLibraryDialogModule) => (+ <module.WorkflowLibraryDialog isOpen={isOpen} onOpenChange={setWorkflowLibraryOpen} />+ ),+ [isOpen]+ );+ const renderPlaceholder = useCallback(+ (failed: boolean) => (+ <Dialog.Root open={isOpen} onOpenChange={handleLibraryPlaceholderOpenChange}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content>+ <Dialog.Header>+ <Dialog.Title>{t('workflowLibrary.title')}</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ {failed ? (+ <LoadError+ isRetrying={false}+ layout="state"+ message={t('workflowLibrary.dialogLoadFailed')}+ onRetry={retry}+ />+ ) : (+ <Center gap="2" p="6" role="status">+ <Spinner />+ <Text>{t('workflowLibrary.loading')}</Text>+ </Center>+ )}+ </Dialog.Body>+ <Dialog.CloseTrigger asChild>+ <CloseButton />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ ),+ [isOpen, retry, t]+ );+ const renderError = useCallback(() => renderPlaceholder(true), [renderPlaceholder]);++ return (+ <workflowLibraryDialog.Deferred+ key={attempt}+ fallback={renderPlaceholder(false)}+ render={renderDialog}+ renderError={renderError}+ />+ );+};++interface WorkflowChoice {+ id: string;+ name: string;+}++const selectWorkflowChoices = (project: WorkflowProjectSnapshot): WorkflowChoice[] =>+ project.workflows.map((entry) => ({ id: entry.document.id, name: entry.document.name }));+const areWorkflowChoicesEqual = (left: readonly WorkflowChoice[], right: readonly WorkflowChoice[]) =>+ left.length === right.length &&+ left.every((choice, index) => choice.id === right[index]?.id && choice.name === right[index].name);++/**+ * A long list opens with the active workflow in view. A frame later, once the positioner has capped the menu to the room+ * beside its trigger; the list's own viewport is the nearest scroller, so only the list moves.+ */+const revealActiveChoice = (item: HTMLElement | null) => {+ if (item) {+ requestAnimationFrame(() => item.scrollIntoView({ block: 'nearest' }));+ }+};++/**+ * The list's scroller is the shared scrolling menu list, which lives with the editor's boot code: imported here, it would+ * make this chunk, which a Launchpad manager reaches, reach the editor. It loads on first use instead, already loaded+ * wherever the editor has booted; until then, or if it fails to load, the same rows scroll natively. The rows and the+ * actions are this component's either way, so the menu opens whole and nothing moves under a click when it arrives.+ */+const scrollableMenu = createDeferredModule(() => import('@platform/ui/ScrollableMenuContent'));+const NATIVE_SCROLL_LIST_PROPS = { minH: '0', overflowY: 'auto' } as const;++/**+ * The project's workflows in collection order (the library's "Project order"), the active one checked, then a new+ * workflow and the way on to the library. Choosing one opens it as the library's Open does; the list scrolls, the two+ * actions under it stay.+ */+const WorkflowSwitcherContent = ({+ activeWorkflowId,+ onOpenLibrary,+}: {+ activeWorkflowId: string;+ onOpenLibrary: () => void;+}) => {+ const { t } = useTranslation();+ const choices = useWorkflowProjectSelector(selectWorkflowChoices, areWorkflowChoicesEqual);+ const { createWorkflow, selectWorkflow } = useProjectGraphCommands();+ // Nothing is replaced: a new workflow is added beside the others and becomes the active one, so nothing asks first.+ const newWorkflow = useCallback(() => createWorkflow(), [createWorkflow]);+ const chooseWorkflow = useCallback(+ (event: { value: string }) => {+ if (event.value !== activeWorkflowId) {+ selectWorkflow(event.value);+ }+ },+ [activeWorkflowId, selectWorkflow]+ );+ const footer = useMemo(+ () => (+ <>+ <Menu.Separator />+ <MenuActionItem+ icon={PlusIcon}+ label={t('widgets.workflow.newWorkflow')}+ value="new-workflow"+ onSelect={newWorkflow}+ />+ <MenuActionItem+ icon={LibraryIcon}+ label={t('widgets.workflow.libraryWithEllipsis')}+ value="workflow-library"+ onSelect={onOpenLibrary}+ />+ </>+ ),+ [newWorkflow, onOpenLibrary, t]+ );++ const rows = useMemo(+ () => (+ <Menu.RadioItemGroup value={activeWorkflowId} onValueChange={chooseWorkflow}>+ <Menu.ItemGroupLabel color="fg.muted">{t('widgets.workflow.inThisProject')}</Menu.ItemGroupLabel>+ {choices.map((choice) => {+ const name = choice.name || t('widgets.workflow.untitled');++ return (+ // Typeahead matches an option's value text, which is its value (an id) unless named.+ <Menu.RadioItem+ key={choice.id}+ ref={choice.id === activeWorkflowId ? revealActiveChoice : undefined}+ value={choice.id}+ valueText={name}+ >+ <Menu.ItemIndicator color="accent.fg">+ <Icon as={CheckIcon} boxSize="3.5" />+ </Menu.ItemIndicator>+ <Menu.ItemText color={choice.name ? undefined : 'fg.subtle'} flex="1" minW="0">+ <MiddleTruncate as="span" text={name} />+ </Menu.ItemText>+ </Menu.RadioItem>+ );+ })}+ </Menu.RadioItemGroup>+ ),+ [activeWorkflowId, choices, chooseWorkflow, t]+ );+ const nativeList = useMemo(() => <Box {...NATIVE_SCROLL_LIST_PROPS}>{rows}</Box>, [rows]);+ const renderList = useCallback(+ (module: typeof ScrollableMenuModule) => <module.ScrollableMenuList>{rows}</module.ScrollableMenuList>,+ [rows]+ );++ return (+ <MenuContent {...SCROLLABLE_MENU_CONTENT_PROPS} maxW="20rem" minW="14rem">+ <scrollableMenu.Deferred fallback={nativeList} render={renderList} />+ {footer}+ </MenuContent>+ );+};+/** How the project's own persistence is shown beside the library actions. */const PERSISTENCE_VIEW: Record<WorkflowProjectPersistence['status'],@@ -124,9 +327,10 @@ const useTemplateLinkDescription = (};/**- * The center chrome's label: the workflow's name, with its library link inside the same button, so the name pill- * shrinks as one piece. The label clips rather than overflows its island: at narrow center widths the actions island- * beside it would otherwise paint over the name and take its clicks.+ * The center chrome's label: the workflow's name, with its library link inside the same trigger, so the name pill+ * shrinks as one piece. It opens a menu that switches between the project's workflows or opens the library. The label+ * clips rather than overflows its island: at narrow center widths the actions island beside it would otherwise paint+ * over the name and take its clicks.*/export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {const { t } = useTranslation();@@ -135,6 +339,8 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);const source = useWorkflowProjectSelector((project) => project.activeWorkflow.source);const session = useAuthSession();+ const triggerIds = useTooltipTriggerIds();+ const [isMenuOpen, setIsMenuOpen] = useState(false);const [wantsTemplateName, setWantsTemplateName] = useState(false);const linkDescription = useTemplateLinkDescription(source, wantsTemplateName, session);const linkDescriptionId = useId();@@ -142,6 +348,7 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {() => openWorkflowLibraryAtProjectWorkflow(projectId, activeWorkflowId),[activeWorkflowId, projectId]);+ const onMenuOpenChange = useCallback((event: { open: boolean }) => setIsMenuOpen(event.open), []);const onTooltipOpenChange = useCallback((event: { open: boolean }) => {if (event.open) {setWantsTemplateName(true);@@ -151,7 +358,7 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {const tooltipContent = useMemo(() => (<Stack gap="0.5">- <Text>{t('widgets.workflow.projectWorkflows')}</Text>+ <Text>{t('widgets.workflow.switchWorkflow')}</Text><Text color="fg.muted">{linkDescription}</Text></Stack>),@@ -162,7 +369,7 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {return <Text fontWeight="700">{t('widgets.labels.workflow')}</Text>;}- // Center chrome already names the widget; the workflow name opens the project's workflows with this one selected.+ // Center chrome already names the widget; the workflow name switches between the project's workflows.const displayName = workflowName || t('widgets.workflow.untitled');const isLinked = isUpdatableSource(source, session);// A source this account cannot update is locked, whether bundled or owned by another account.@@ -182,42 +389,82 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {<Text color="fg.subtle" flexShrink={1} minW="0" overflow="hidden">/</Text>- <Tooltip content={tooltipContent} onOpenChange={onTooltipOpenChange}>- <Button- aria-describedby={linkDescriptionId}- aria-label={t('widgets.workflow.openProjectWorkflows', { name: displayName })}- // The button recipe refuses to shrink; the name must give way before the actions island overlaps it.- flexShrink={1}- maxW="16rem"- minW="0"- overflow="hidden"- size="sm"- variant="ghost"- onClick={openProjectWorkflows}+ {/* The list mounts only while open: the chrome re-renders on editor changes the list does not show. */}+ <Menu.Root+ ids={triggerIds}+ lazyMount+ positioning={WORKFLOW_SWITCHER_POSITIONING}+ unmountOnExit+ onOpenChange={onMenuOpenChange}+ >+ {/* Not over the menu it describes: it opens below the trigger, where the tooltip would cover the list. */}+ <Tooltip+ content={tooltipContent}+ disabled={isMenuOpen}+ ids={triggerIds}+ keepsRootWhenDisabled+ onOpenChange={onTooltipOpenChange}>- <Icon as={LibraryIcon} boxSize="3.5" flexShrink={0} />- <MiddleTruncate color={workflowName ? undefined : 'fg.subtle'} fontWeight="600" minW="0" text={displayName} />- <Icon as={linkIcon} boxSize="3.5" color="fg.subtle" data-template-link={linkKind} flexShrink={0} />- </Button>- </Tooltip>+ <Menu.Trigger asChild>+ <Button+ aria-describedby={linkDescriptionId}+ aria-label={t('widgets.workflow.switchWorkflowTrigger', { name: displayName })}+ // The button recipe refuses to shrink; the name must give way before the actions island overlaps it.+ flexShrink={1}+ maxW="16rem"+ minW="0"+ overflow="hidden"+ size="sm"+ variant="ghost"+ onFocus={preloadWorkflowLibraryDialog}+ onPointerEnter={preloadWorkflowLibraryDialog}+ >+ <MiddleTruncate+ color={workflowName ? undefined : 'fg.subtle'}+ fontWeight="600"+ minW="0"+ text={displayName}+ />+ <Icon as={linkIcon} boxSize="3.5" color="fg.subtle" data-template-link={linkKind} flexShrink={0} />+ <Icon as={ChevronDownIcon} boxSize="3" flexShrink={0} />+ </Button>+ </Menu.Trigger>+ </Tooltip>+ <Portal>+ <Menu.Positioner>+ <WorkflowSwitcherContent activeWorkflowId={activeWorkflowId} onOpenLibrary={openProjectWorkflows} />+ </Menu.Positioner>+ </Portal>+ </Menu.Root><VisuallyHidden id={linkDescriptionId}>{linkDescription}</VisuallyHidden></HStack>);};+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;-/** Entries contributed to the shared widget actions menu. */+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) => {const { t } = useTranslation();const session = useAuthSession();const { getProjectGraph } = useWorkflowUi();const { widgets } = useWorkflowHostCommands();- const { createWorkflow } = useProjectGraphCommands();const notify = useWorkflowNotifications();const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);const source = useWorkflowProjectSelector((project) => project.activeWorkflow.source);+ const workflowName = useWorkflowProjectSelector((project) => project.activeWorkflow.document.name);+ const pngExport = useWorkflowPngExportState();+ // One export runs at a time, from here or the editor toolbar.+ const downloadPngUnavailableReason = pngExport.isExporting+ ? t('widgets.workflow.downloadPngRunning')+ : pngExport.isAvailable+ ? undefined+ : t('widgets.workflow.downloadPngUnavailable');const canUpdateSource = isUpdatableSource(source, session);const openDetailsPanel = useCallback(() => {@@ -247,6 +494,10 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {.then(() => notify.success(t('widgets.workflow.copyJsonSuccess'))).catch(() => notify.error(t('widgets.workflow.copyJsonFailed')));}, [getProjectGraph, notify, t]);+ const downloadPng = useCallback(+ () => void exportWorkflowPng({ notifications: notify, t, workflowName }),+ [notify, t, workflowName]+ );const saveToLibrary = useCallback(() => requestWorkflowPublication({ kind: 'save-as-new', workflowId: activeWorkflowId }),[activeWorkflowId]@@ -255,46 +506,92 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {() => requestWorkflowPublication({ kind: 'update-source', workflowId: activeWorkflowId }),[activeWorkflowId]);- const openLibrary = useCallback(() => setWorkflowLibraryOpen(true), []);const renameActiveWorkflow = useCallback(() => requestWorkflowRename(activeWorkflowId), [activeWorkflowId]);- // Nothing is replaced: a new workflow is added beside the others, so no confirmation stands in the way.- const newWorkflow = useCallback(() => createWorkflow(), [createWorkflow]);return (- <Menu.ItemGroup>- <Menu.ItemGroupLabel color="fg.subtle" fontSize="xs" textTransform="uppercase">- {t('widgets.labels.workflow')}- </Menu.ItemGroupLabel>- <Menu.Item value="details" onClick={openDetailsPanel}>- {t('widgets.workflow.detailsWithEllipsis')}- </Menu.Item>- <Menu.Item value="rename" onClick={renameActiveWorkflow}>- {t('widgets.workflow.renameWithEllipsis')}- </Menu.Item>- <Menu.Item value="library" onClick={openLibrary}>- {t('widgets.workflow.libraryWithEllipsis')}- </Menu.Item>- <Menu.Item value="save-to-library" onClick={saveToLibrary}>- {t('widgets.workflow.saveToLibraryWithEllipsis')}- </Menu.Item>- {canUpdateSource ? (- <Menu.Item value="update-template" onClick={updateTemplate}>- {t('widgets.workflow.updateTemplateWithEllipsis')}- </Menu.Item>- ) : null}- <Menu.Item value="import" onClick={requestWorkflowImport}>- {t('widgets.workflow.importJsonWithEllipsis')}- </Menu.Item>- <Menu.Item value="export" onClick={exportWorkflow}>- {t('widgets.workflow.exportJson')}- </Menu.Item>- <MenuItem unavailableReason={copyUnavailableReason} value="copy" onClick={copyWorkflow}>- {t('widgets.workflow.copyJson')}- </MenuItem>- <Menu.Item value="new" onClick={newWorkflow}>- {t('widgets.workflow.newWorkflow')}- </Menu.Item>- </Menu.ItemGroup>+ <>+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('widgets.workflow.menuThisWorkflow')}</Menu.ItemGroupLabel>+ <MenuActionItem+ icon={PencilIcon}+ label={t('widgets.workflow.renameWithEllipsis')}+ value="rename"+ onSelect={renameActiveWorkflow}+ />+ <MenuActionItem+ icon={InfoIcon}+ label={t('widgets.workflow.detailsWithEllipsis')}+ value="details"+ onSelect={openDetailsPanel}+ />+ {/* Saving always creates a template. Beside Update, a linked workflow's save says it makes a new one. */}+ <MenuActionItem+ icon={BookmarkIcon}+ label={t(+ canUpdateSource+ ? 'widgets.workflow.saveAsNewTemplateWithEllipsis'+ : 'widgets.workflow.saveToLibraryWithEllipsis'+ )}+ value="save-to-library"+ onSelect={saveToLibrary}+ />+ {canUpdateSource ? (+ <MenuActionItem+ icon={BookUpIcon}+ label={t('widgets.workflow.updateTemplateWithEllipsis')}+ value="update-template"+ onSelect={updateTemplate}+ />+ ) : null}+ </Menu.ItemGroup>+ <Menu.Separator />+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('widgets.workflow.menuImportExport')}</Menu.ItemGroupLabel>+ <MenuActionItem+ icon={UploadIcon}+ label={t('widgets.workflow.importJsonWithEllipsis')}+ value="import"+ onSelect={requestWorkflowImport}+ />+ <Menu.Root positioning={EXPORT_SUBMENU_POSITIONING}>+ <Menu.TriggerItem>+ <HStack gap="2" minW="0" w="full">+ <Icon as={FileDownIcon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Text flex="1" fontSize="md">+ {t('widgets.workflow.export')}+ </Text>+ <Icon as={ChevronRightIcon} boxSize="3" color="fg.subtle" flexShrink={0} />+ </HStack>+ </Menu.TriggerItem>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="12rem">+ <MenuActionItem+ icon={DownloadIcon}+ label={t('widgets.workflow.exportJson')}+ value="export-json"+ onSelect={exportWorkflow}+ />+ <MenuActionItem+ icon={CopyIcon}+ label={t('widgets.workflow.copyJson')}+ unavailableReason={copyUnavailableReason}+ value="copy-json"+ onSelect={copyWorkflow}+ />+ <MenuActionItem+ icon={CameraIcon}+ label={t('widgets.workflow.downloadPng')}+ unavailableReason={downloadPngUnavailableReason}+ value="download-png"+ onSelect={downloadPng}+ />+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </Menu.ItemGroup>+ </>);};@@ -341,7 +638,7 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {</IconButton></Tooltip>) : null}- {/* Center labels already open the project's workflows; other regions need this separate trigger and leave+ {/* 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 : (<Tooltip content={t('widgets.workflow.library')}>@@ -351,6 +648,8 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {size="sm"variant="ghost"onClick={openWorkflowLibrary}+ onFocus={preloadWorkflowLibraryDialog}+ onPointerEnter={preloadWorkflowLibraryDialog}><Icon as={LibraryIcon} boxSize="3.5" /></IconButton>@@ -413,6 +712,10 @@ export const WorkflowDialogHost = () => {const importRequestCount = workflowUiStore.useSelector((snapshot) => snapshot.importRequestCount);const isAddNodeOpen = workflowUiStore.useSelector((snapshot) => snapshot.isAddNodeOpen);const isLibraryOpen = workflowUiStore.useSelector((snapshot) => snapshot.isLibraryOpen);+ const [hasOpenedLibrary, setHasOpenedLibrary] = useState(isLibraryOpen);+ if (isLibraryOpen && !hasOpenedLibrary) {+ setHasOpenedLibrary(true);+ }const lastImportRequestRef = useRef(importRequestCount);// A rename request opens the dialog once, for the workflow it named, and only while that workflow is the active// one; closing records the request as handled.@@ -674,7 +977,9 @@ export const WorkflowDialogHost = () => {onAddNote={addNote}onOpenChange={setAddNodeOpen}/>- <WorkflowLibraryDialog isOpen={isLibraryOpen} onOpenChange={setWorkflowLibraryOpen} />+ {/* Loaded on the first opening and kept mounted after, so its exit transitions, reset on close and remembered+ place behave as for an always-mounted dialog. Its own busy overlay covers loading once it shows. */}+ {hasOpenedLibrary ? <WorkflowLibraryDialogLoader isOpen={isLibraryOpen} /> : null}<LibraryCopyChoiceHost /><RenameDialogkey={renameRequest?.requestId ?? 0}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.tsindex 4d9cd467b0..afe6763124 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts@@ -2,6 +2,7 @@ import type { ProjectGraphAction } from '@features/workflow/core/document';import type { ForLoopValidationReason } from '@features/workflow/core/forLoops';import type { ProjectGraphState, ProjectWorkflowSource, XYPosition } from '@features/workflow/core/types';import type { LogSource } from '@platform/logging/contracts';+import type { ReactNode } from 'react';export type WorkflowRegion = 'left' | 'right' | 'bottom' | 'center' | 'dialog' | 'popover' | 'floating';@@ -124,8 +125,20 @@ export interface GraphPreviewProvenance {* isLive distinguishes recompilation from current project state from replaying a saved compiled graph and controls* the dialog subtitle.*/+/** The host's Invoke for a graph preview's source, rendered by the host (the preview owns no route). */+export interface GraphPreviewInvoke {+ control: ReactNode;+ /** Whether that Invoke can run now; its control says why not. */+ isReady: boolean;+}+export interface GraphPreviewSourceState {graph: WorkflowPreviewGraph | null;+ /**+ * The workflow document the graph compiles from, when there is one: the preview draws it, so its labels, notes and+ * form show; `graph` stays what runs.+ */+ document?: ProjectGraphState;/** Human-readable result destination (e.g. "Gallery"), set for every source by the builder. */destinationLabel: string | null;invalidReasons: Array<string | ForLoopValidationReason>;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsxindex b76cdeaccc..9d3e54fa0f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CurrentImageFlowNode.tsx@@ -2,6 +2,9 @@ import type { GeneratedImageContract } from '@features/gallery';import type { NodeProps } from '@xyflow/react';import { Box, Flex, Text } from '@chakra-ui/react';+import { useDraggable } from '@dnd-kit/core';+import { getSelectedGalleryImageFromValues } from '@features/gallery/contracts';+import { getGalleryItemDragData, getGalleryItemDragId } from '@features/gallery/utility';import { useProgressImage } from '@features/queue/react';import {getWorkflowNodeHeaderProps,@@ -15,23 +18,75 @@ import {imageUrlToStreamingSource,progressImageToStreamingSource,} from '@platform/ui/streaming-image/streamingImageSource';-import { memo } from 'react';+import { memo, useId, useMemo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import type { CurrentImageFlowNode as CurrentImageFlowNodeType } from './flowAdapters';-const getLatestImage = (values: Record<string, unknown>): GeneratedImageContract | null => {- const recentImages = Array.isArray(values.recentImages) ? (values.recentImages as GeneratedImageContract[]) : [];+/** What the node shows when no run is drawing: the image the gallery has selected, as legacy did. */+interface CurrentImageView {+ height?: number;+ imageName: string;+ imageUrl: string;+ width?: number;+}- return recentImages[0] ?? null;+/**+ * The gallery's selected image. A selected video is passed over, as legacy did; with no image selected the node falls+ * back to the project's most recent image, so it is not empty while results exist.+ */+export const getCurrentImageView = (galleryValues: Record<string, unknown>): CurrentImageView | null => {+ const selected = getSelectedGalleryImageFromValues(galleryValues);+ const recentImages = Array.isArray(galleryValues.recentImages)+ ? (galleryValues.recentImages as GeneratedImageContract[])+ : [];+ const image = selected ?? recentImages[0];++ return image+ ? { height: image.height, imageName: image.imageName, imageUrl: image.imageUrl, width: image.width }+ : null;+};++const isSameImageView = (a: CurrentImageView | null, b: CurrentImageView | null): boolean =>+ a === b ||+ (a !== null &&+ b !== null &&+ a.imageName === b.imageName &&+ a.imageUrl === b.imageUrl &&+ a.width === b.width &&+ a.height === b.height);++/** The image under the node's frame, draggable wherever gallery images can be dropped. */+const DraggableCurrentImage = ({ children, image }: { children: ReactNode; image: CurrentImageView | null }) => {+ const disabledId = useId();+ const dragData = useMemo(+ () => (image ? getGalleryItemDragData([{ kind: 'image', name: image.imageName }]) : undefined),+ [image]+ );+ // Pointer drags only, as the Preview frame's: the image is no tab stop, so the canvas keeps its own keys.+ const { listeners, setNodeRef } = useDraggable({+ data: dragData,+ disabled: !image,+ id: image+ ? getGalleryItemDragId({ kind: 'image', name: image.imageName }, 'workflow-current-image', disabledId)+ : `workflow-current-image:disabled:${disabledId}`,+ });++ return (+ // `nodrag`: the canvas leaves the pointer to the image drag rather than moving the node.+ <Box ref={setNodeRef} className="nodrag" cursor={image ? 'grab' : undefined} {...listeners}>+ {children}+ </Box>+ );};const CurrentImageEditorNode = ({ data, selected }: NodeProps<CurrentImageFlowNodeType>) => {const { t } = useTranslation();- const galleryValues = useWorkflowProjectSelector((project) => project.galleryValues);+ // Only the shown image: other gallery changes (filters, scroll, other selections' metadata) do not render the node.+ const image = useWorkflowProjectSelector((project) => getCurrentImageView(project.galleryValues), isSameImageView);const progressImage = useProgressImage();const node = data.documentNode;- const latestImage = getLatestImage(galleryValues);+ const title = node.data.label || t('widgets.workflow.addNodeDialog.currentImageTitle');return (<Box@@ -42,32 +97,32 @@ const CurrentImageEditorNode = ({ data, selected }: NodeProps<CurrentImageFlowNo{...getWorkflowNodeShellProps({ selected })}><Flex {...getWorkflowNodeHeaderProps()}>- <Text fontSize="lg" fontWeight="700">- {node.data.label || t('widgets.workflow.addNodeDialog.currentImageTitle')}- </Text>+ <Text fontWeight="600">{title}</Text>{progressImage ? (<Text color="brand.solid" data-node-status-indicator="true" fontSize="xs" ms="auto">{t('widgets.workflow.generating')}</Text>) : null}</Flex>- <StreamingImageFrame- fallbackImage={imageUrlToStreamingSource({- alt: latestImage?.imageName ?? t('widgets.workflow.addNodeDialog.currentImageTitle'),- height: latestImage?.height,- kind: 'fallback',- src: latestImage?.imageUrl,- width: latestImage?.width,- })}- fit="contain"- h="18rem"- liveImage={progressImageToStreamingSource(progressImage)}- w="full"- >- <Flex align="center" color="fg.subtle" fontSize="xs" h="full" justify="center" px="4" textAlign="center">- {t('widgets.workflow.currentImageEmpty')}- </Flex>- </StreamingImageFrame>+ <DraggableCurrentImage image={progressImage ? null : image}>+ <StreamingImageFrame+ fallbackImage={imageUrlToStreamingSource({+ alt: image?.imageName ?? title,+ height: image?.height,+ kind: 'fallback',+ src: image?.imageUrl,+ width: image?.width,+ })}+ fit="contain"+ h="18rem"+ liveImage={progressImageToStreamingSource(progressImage)}+ w="full"+ >+ <Flex align="center" color="fg.subtle" fontSize="xs" h="full" justify="center" px="4" textAlign="center">+ {t('widgets.workflow.currentImageEmpty')}+ </Flex>+ </StreamingImageFrame>+ </DraggableCurrentImage></Box>);};@@ -88,8 +143,7 @@ const CurrentImageSnapshotNode = ({ data, selected }: NodeProps<CurrentImageFlowdata-workflow-export-node-title="true"data-workflow-export-static-node-content="true"flex="1"- fontSize="lg"- fontWeight="700"+ fontWeight="600"minW="0"text={node.data.label || t('widgets.workflow.addNodeDialog.currentImageTitle')}/>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 a45b76fa63..74b29b775a 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@@ -45,6 +45,12 @@ vi.mock('./workflowImageExport', () => ({}));const { EditorToolbar } = await import('./EditorToolbar');+const { registerWorkflowFlowInstance, releaseWorkflowFlowInstance } = await import('./flowInstanceStore');+const { registerWorkflowPngExportHost } = await import('./workflowPngExport');+// The export's run loads on first use; loading it here keeps that first load out of each test's waits.+await import('./workflowPngExportRun');+const flowInstance = toolbarMocks as unknown as Parameters<typeof registerWorkflowFlowInstance>[0];+let releaseExportHost: (() => void) | null = null;const i18n = createInstance();await i18n.use(initReactI18next).init({@@ -90,6 +96,13 @@ const render = async (document.body.append(host);root = createRoot(host);toolbarMocks.onExportPrepare.mockResolvedValue(host);+ // The editor lends the export its offscreen view and flow instance; here the mocks stand in for both.+ releaseExportHost?.();+ releaseExportHost = registerWorkflowPngExportHost({+ complete: toolbarMocks.onExportComplete,+ prepare: toolbarMocks.onExportPrepare,+ });+ registerWorkflowFlowInstance(flowInstance);await settle(() => {root?.render(@@ -99,8 +112,6 @@ const render = async ({...arrangeProps}nodeOpacity={nodeOpacity}tool="pan"- onExportPrepare={toolbarMocks.onExportPrepare}- onExportComplete={toolbarMocks.onExportComplete}onNodeOpacityChange={vi.fn()}onToolChange={vi.fn()}/>@@ -129,6 +140,9 @@ const buttonBoxes = (): string[] =>});afterEach(async () => {+ releaseExportHost?.();+ releaseExportHost = null;+ releaseWorkflowFlowInstance(flowInstance);await settle(() => root?.unmount());host?.remove();host = null;@@ -180,8 +194,6 @@ describe('editor toolbar', () => {canUndo={canUndo}nodeOpacity={1}tool="pan"- onExportPrepare={toolbarMocks.onExportPrepare}- onExportComplete={toolbarMocks.onExportComplete}onNodeOpacityChange={vi.fn()}onRedo={vi.fn()}onToolChange={vi.fn()}@@ -225,8 +237,6 @@ describe('editor toolbar', () => {nodeOpacity={1}tool="pan"updatableNodeCount={2}- onExportPrepare={toolbarMocks.onExportPrepare}- onExportComplete={toolbarMocks.onExportComplete}onNodeOpacityChange={vi.fn()}onToolChange={vi.fn()}onUpdateNodes={onUpdateNodes}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsxindex 1b9d66f83c..3c4cec313c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx@@ -22,11 +22,11 @@ import {ZoomInIcon,ZoomOutIcon,} from 'lucide-react';-import { useCallback, useId, useMemo, useRef, useState } from 'react';-import { flushSync } from 'react-dom';+import { useCallback, useId, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { WORKFLOW_FIT_PADDING } from './flowInstanceStore';+import { exportWorkflowPng, useWorkflowPngExportState } from './workflowPngExport';/*** Pane drag follows the selected pan/box/lasso tool; eraser clicks delete. Shift selects while panning, and middle@@ -51,15 +51,6 @@ const TOOLTIP_POSITIONING = { placement: 'right-start' } as const;*/const EDITOR_TOOLBAR_TOP = 'var(--wb-center-chrome-inset, var(--chakra-spacing-2))';-const waitForExportFrame = () =>- new Promise<void>((resolve) => {- if (document.visibilityState === 'hidden') {- window.setTimeout(resolve, 0);- } else {- window.requestAnimationFrame(() => resolve());- }- });-export const EditorToolbar = ({arrangeScope = null,canRedo = false,@@ -68,8 +59,6 @@ export const EditorToolbar = ({tool,updatableNodeCount = 0,onArrangeNodes,- onExportPrepare,- onExportComplete,onNodeOpacityChange,onRedo,onToolChange,@@ -87,25 +76,20 @@ export const EditorToolbar = ({updatableNodeCount?: number;onArrangeNodes?: () => void;onNodeOpacityChange: (opacity: number) => void;- onExportPrepare: () => Promise<HTMLElement>;- onExportComplete: () => void;onRedo?: () => void;onToolChange: (tool: EditorTool) => void;onUndo?: () => void;onUpdateNodes?: () => void;}) => {const { t } = useTranslation();- const { fitView, getNodes, getNodesBounds, zoomIn, zoomOut } = useReactFlow();+ const { fitView, zoomIn, zoomOut } = useReactFlow();const reduceMotion = useWorkflowPreferencesSelector((preferences) => preferences.reduceMotion);const workflowName = useWorkflowProjectSelector((project) => project.activeWorkflow.document.name);const notifications = useWorkflowNotifications();const opacityTriggerId = useId();- const isExportingWorkflowRef = useRef(false);const exportButtonRef = useRef<HTMLButtonElement>(null);- const [isExportingWorkflow, setIsExportingWorkflow] = useState(false);+ const { isExporting: isExportingWorkflow } = useWorkflowPngExportState();const fitViewDuration = reduceMotion ? 0 : 300;- const fallbackWorkflowName = t('widgets.workflow.untitled');- const exportFailedLabel = t('widgets.workflow.exportImageFailed');const opacityIds = useMemo(() => ({ trigger: opacityTriggerId }), [opacityTriggerId]);const opacityValue = useMemo(() => [Math.round(nodeOpacity * 100)], [nodeOpacity]);const onZoomInClick = useCallback(() => void zoomIn(), [zoomIn]);@@ -115,61 +99,15 @@ export const EditorToolbar = ({[fitView, fitViewDuration]);const onExportWorkflowClick = useCallback(() => {- if (isExportingWorkflowRef.current) {- return;- }-- isExportingWorkflowRef.current = true;const hadFocus = document.activeElement === exportButtonRef.current;- setIsExportingWorkflow(true);- void (async () => {- try {- const { exportWorkflowAsPng, preflightWorkflowImageExport } = await import('./workflowImageExport');- const bounds = getNodesBounds(getNodes());- // Refuse from the live editor's bounds before mounting the whole graph a second time.- let outcome = preflightWorkflowImageExport(bounds);- if (!outcome) {- const flowElement = await onExportPrepare();- await waitForExportFrame();- await waitForExportFrame();- outcome = await exportWorkflowAsPng({ bounds, fallbackWorkflowName, flowElement, workflowName });- }- if (outcome.status === 'busy') {- notifications.info(t('widgets.workflow.exportImageBusy'));- } else if (outcome.status === 'too-large') {- notifications.error(- t('widgets.workflow.exportImageTooLarge'),- t('widgets.workflow.exportImageTooLargeDetail')- );- } else if (outcome.status === 'exported' && outcome.reduced) {- notifications.info(- t('widgets.workflow.exportImageReduced'),- t('widgets.workflow.exportImageReducedDetail', { height: outcome.height, width: outcome.width })- );- }- } catch {- notifications.error(exportFailedLabel);- } finally {- isExportingWorkflowRef.current = false;- flushSync(() => setIsExportingWorkflow(false));- // The busy camera is disabled, which drops its focus; return it unless focus has moved on since.- if (hadFocus && document.activeElement === document.body) {- exportButtonRef.current?.focus();- }- onExportComplete();++ void exportWorkflowPng({ notifications, t, workflowName }).then(() => {+ // The busy camera is disabled, which drops its focus; return it unless focus has moved on since.+ if (hadFocus && document.activeElement === document.body) {+ exportButtonRef.current?.focus();}- })();- }, [- exportFailedLabel,- fallbackWorkflowName,- getNodes,- getNodesBounds,- notifications,- onExportPrepare,- onExportComplete,- t,- workflowName,- ]);+ });+ }, [notifications, t, workflowName]);const fitViewRef = useRef<HTMLButtonElement>(null);// The update button leaves with the last outdated node; keyboard focus steps to its stable neighbour first.const onUpdateNodesClick = useCallback(() => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsxindex 360a9a0456..e9844b25e4 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx@@ -10,13 +10,15 @@ import type { ProjectGraphAction } from '@features/workflow/utility';import openapi from '@api/openapi.json';/* eslint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop -- each render mounts a fresh flow on purpose */-import { ChakraProvider } from '@chakra-ui/react';+import { Box, ChakraProvider } from '@chakra-ui/react';+import { DndContext, type DragStartEvent } from '@dnd-kit/core';import { galleryImageUrls } from '@features/gallery/utility';import {savedWorkflowDetailQueryKey,savedWorkflowPickerQueryOptions,} from '@features/workflow/data/savedWorkflowQueries';import { parseOpenApiToTemplates } from '@features/workflow/data/templates';+import { flowThemeCss } from '@features/workflow/ui/graph-preview/flowTheme';import { WorkflowImageExportProvider } from '@features/workflow/ui/nodeChrome';import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';import {@@ -34,7 +36,7 @@ import { createInstance } from 'i18next';import { act, createRef, startTransition, useCallback, useEffect, useState, 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 { commands, userEvent } from 'vitest/browser';import type { rasterizeWorkflowImage as RasterizeWorkflowImage } from './workflowImageRaster';@@ -44,6 +46,7 @@ import { toFlowEdges, toFlowNodes } from './flowAdapters';import { InvocationFlowNode } from './InvocationFlowNode';import { LoopBodyBoundaryOverlay } from './LoopBodyBoundaryOverlay';import { NotesFlowNode } from './NotesFlowNode';+import { WorkflowEdge as WorkflowEdgeComponent } from './WorkflowEdge';import {EXPORT_SCALE,exportWorkflowAsPng,@@ -54,6 +57,12 @@ import { WorkflowImageExportView } from './WorkflowImageExportView';import '@xyflow/react/dist/style.css';+declare module 'vitest/browser' {+ interface BrowserCommands {+ mouseDragPath: (points: readonly { x: number; y: number }[], frameWidth: number) => Promise<void>;+ }+}+const exportMocks = vi.hoisted(() => ({progressImage: null as null | { dataUrl: string; height: number; width: number },rasterize: vi.fn(),@@ -382,28 +391,32 @@ describe('InvocationFlowNode chrome and export', () => {});});- it('bounds snapshots by rendered nodes instead of live editor result height', async () => {- const execution = createExecutionPort();- execution.set(completed(outputImage(400, 800)));- const adapter = createAdapter(execution.port);+ it('sizes a snapshot by the nodes it renders, not by the live editor’s bounds', async () => {+ // Live, the node is collapsed to its header; the snapshot draws every node open, so it is taller.+ const collapsedNodes = toFlowNodes(+ { ...projectGraph, nodes: [{ ...documentNode, data: { ...documentNode.data, isOpen: false } }] },+ [],+ templates+ );+ const adapter = createAdapter(createExecutionPort().port);let capturedHeight: number | undefined;exportMocks.rasterize.mockImplementation((_clone: HTMLElement, options: { height: number }) => {capturedHeight = options.height;return Promise.resolve(new Blob(['png'], { type: 'image/png' }));});- await render(adapter);+ await render(adapter, 1, false, collapsedNodes);const liveRect = host.querySelector<HTMLElement>('.react-flow__node')!.getBoundingClientRect();const liveBounds = { x: 20, y: 20, width: liveRect.width, height: liveRect.height };- await render(adapter, 1, true);+ await render(adapter, 1, true, collapsedNodes);const snapshotRect = host.querySelector<HTMLElement>('.react-flow__node')!.getBoundingClientRect();- expect(snapshotRect.height).toBeLessThan(liveRect.height);+ expect(snapshotRect.height).toBeGreaterThan(liveRect.height);await exportWorkflowAsPng({bounds: liveBounds,fallbackWorkflowName: 'Untitled Workflow',flowElement: host.querySelector<HTMLElement>('.react-flow')!,- workflowName: 'Pristine bounds',+ workflowName: 'Collapsed live',});expect(capturedHeight).toBe(Math.ceil(snapshotRect.height + 200) * EXPORT_SCALE);@@ -605,8 +618,6 @@ describe('InvocationFlowNode chrome and export', () => {expect(capturedClone?.textContent).not.toContain('Type: preview');expect(capturedClone?.textContent).not.toContain('Node pack: invokeai');expect(capturedClone?.textContent).not.toContain('Version: 1.0.0');- expect(capturedClone?.textContent).not.toContain('Classification: stable');- expect(capturedClone?.textContent).not.toContain('Category: Export category');expect(capturedClone?.textContent).not.toContain('Field: a');expect(capturedClone?.textContent).not.toContain('Type: Integer');expect(capturedClone?.textContent).not.toContain('Connection only');@@ -676,7 +687,17 @@ describe('InvocationFlowNode chrome and export', () => {for (const title of titles) {expect(getComputedStyle(title).whiteSpace).toBe('nowrap');expect(title.textContent?.length).toBeGreaterThan(100);- expect(title.scrollHeight).toBeLessThanOrEqual(title.clientHeight);+ // One line: every fragment of its text shares a top. (Its box is trimmed to the letters, so its ink overflows.)+ const lineTops = new Set<number>();+ const walker = document.createTreeWalker(title, NodeFilter.SHOW_TEXT);+ for (let text = walker.nextNode(); text; text = walker.nextNode()) {+ const range = document.createRange();+ range.selectNodeContents(text);+ for (const rect of range.getClientRects()) {+ lineTops.add(Math.round(rect.top));+ }+ }+ expect(lineTops.size).toBe(1);}const truncatedHead = invocationTitle!.firstElementChild as HTMLElement;expect(getComputedStyle(truncatedHead).textOverflow).toBe('ellipsis');@@ -952,7 +973,7 @@ describe('InvocationFlowNode chrome and export', () => {});- it('keeps running progress in the editor but omits it from the exported graph clone', async () => {+ it('shows running progress as the one ring in the status button, and omits it from the exported graph clone', async () => {const execution = createExecutionPort();const adapter = createAdapter(execution.port);let capturedClone: HTMLElement | undefined;@@ -968,11 +989,20 @@ describe('InvocationFlowNode chrome and export', () => {latestOutput: null,outputImageName: null,progress: 0.5,- progressMessage: null,+ progressMessage: 'Denoising',status: 'running',}));- expect(host.querySelector('[data-node-progress-strip="true"]')).not.toBeNull();+ const statusButton = host.querySelector<HTMLElement>('[data-node-status="running"]')!;+ const progressRings = host.querySelectorAll('.react-flow__node [data-scope="progress"][data-part="root"]');+ expect(statusButton.getAttribute('aria-label')).toBe('Status: Running (50%)');+ expect(progressRings).toHaveLength(1);+ expect(statusButton.contains(progressRings[0]!)).toBe(true);++ await act(() => userEvent.hover(statusButton));+ await vi.waitFor(() => expect(document.querySelector('[data-part="content"]')?.textContent).toContain('Denoising'));+ expect(document.querySelector('[data-part="content"]')?.textContent).toContain('Running (50%)');+ await act(() => userEvent.unhover(statusButton));await render(adapter, 1, true);@@ -984,7 +1014,32 @@ describe('InvocationFlowNode chrome and export', () => {workflowName: 'Running workflow',});- expect(capturedClone?.querySelector('[data-node-progress-strip="true"]')).toBeNull();+ expect(capturedClone?.querySelector('[data-node-status-indicator="true"]')).toBeNull();+ expect(capturedClone?.querySelector('[data-scope="progress"]')).toBeNull();+ });++ it('outlines exported nodes in the theme border colour with the resting shadow', async () => {+ const adapter = createAdapter(createExecutionPort().port);+ let exported: { border: string; shadow: string } | undefined;+ exportMocks.rasterize.mockImplementation((clone: HTMLElement) => {+ const shell = getComputedStyle(clone.querySelector<HTMLElement>('[data-workflow-node-shell="true"]')!);+ exported = { border: shell.borderColor, shadow: shell.boxShadow };+ return Promise.resolve(new Blob(['png'], { type: 'image/png' }));+ });++ await render(adapter, 1, true);+ const restingBorder = getComputedStyle(+ host.querySelector<HTMLElement>('[data-workflow-node-shell="true"]')!+ ).borderColor;+ await exportWorkflowAsPng({+ bounds: { x: 20, y: 20, width: 300, height: 260 },+ fallbackWorkflowName: 'Untitled Workflow',+ flowElement: host.querySelector<HTMLElement>('.react-flow')!,+ workflowName: 'Outlined',+ });++ expect(exported?.border).toBe(restingBorder);+ expect(exported?.shadow).not.toBe('none');});it('omits field validation diagnostics from the static export', async () => {@@ -1684,13 +1739,13 @@ describe('InvocationFlowNode failure outcome', () => {));- const failureIcon = await vi.waitFor(() => {- const icon = host.querySelector<HTMLElement>('[aria-label="Failed"]');- expect(icon).not.toBeNull();- return icon!;+ const failureButton = await vi.waitFor(() => {+ const button = host.querySelector<HTMLElement>('button[aria-label="Status: Failed"]');+ expect(button).not.toBeNull();+ return button!;});- await act(() => userEvent.hover(failureIcon));+ await act(() => userEvent.hover(failureButton));await vi.waitFor(() =>expect(document.querySelector('[data-part="content"]')?.textContent).toContain('Child workflow error: Child node failed'@@ -1929,9 +1984,9 @@ describe('InvocationFlowNode field entry', () => {setTimeout(resolve, 0);});});- const rowError = (input: HTMLInputElement) =>- input.closest('[data-scope="field"][data-part="root"]')?.querySelector('[data-part="error-text"]')?.textContent ??- null;+ /** What the node's status button says; the reason for a flagged field lives there, not under the field. */+ const nodeStatus = () =>+ host.querySelector('[data-node-status-indicator="true"]')?.getAttribute('aria-label') ?? null;it('keeps focus and caret in a text field while the deferred flow model catches up', async () => {const { field, store } = await renderEntryNode();@@ -1957,7 +2012,7 @@ describe('InvocationFlowNode field entry', () => {expect(prompt.value).toBe('');expect(fieldValue(store, 'prompt')).toBe('');expect(document.activeElement).toBe(prompt);- expect(rowError(prompt)).toBeNull();+ expect(nodeStatus()).toBeNull();// Undo from elsewhere (a toolbar button has focus) restores the text without pulling focus into a field.const weight = field('Weight');@@ -1999,13 +2054,13 @@ describe('InvocationFlowNode field entry', () => {expect(weight.value).toBe('');expect(fieldValue(store, 'weight')).toBeUndefined();expect(document.activeElement).toBe(weight);- expect(rowError(weight)).toBe('Required value.');+ expect(nodeStatus()).toBe('Status: Weight is required.');await keys('7{Home}-');await settle();expect(weight.value).toBe('-7');expect(fieldValue(store, 'weight')).toBe(-7);- expect(rowError(weight)).toBeNull();+ expect(nodeStatus()).toBeNull();await keys('{Home}{Delete}');await settle();@@ -2060,14 +2115,14 @@ describe('InvocationFlowNode field entry', () => {expect(steps.value).toBe('20.5');expect(fieldValue(store, 'steps')).toBe(20.5);expect(steps.getAttribute('aria-invalid')).toBe('true');- expect(rowError(steps)).toBe('Invalid value.');+ expect(nodeStatus()).toBe('Status: Steps: Invalid value.');await keys('{Backspace}{Backspace}');await settle();expect(steps.value).toBe('20');expect(fieldValue(store, 'steps')).toBe(20);expect(steps.getAttribute('aria-invalid')).toBeNull();- expect(rowError(steps)).toBeNull();+ expect(nodeStatus()).toBeNull();});});@@ -2097,22 +2152,24 @@ describe('InvocationFlowNode template version', () => {</ChakraProvider>));- const updateIcon = () => host.querySelector('.react-flow__node [role="img"][aria-label*="Version"]');+ const statusButton = () => host.querySelector('.react-flow__node [data-node-status-indicator="true"]');const borderColor = () => getComputedStyle(host.querySelector<HTMLElement>('.react-flow__node > div')!).borderColor;- it('marks a node whose template moved on with a warning border and an update tooltip, and leaves a current one alone', async () => {+ it('marks a node whose template moved on with a warning border and an update status, and leaves a current one alone', async () => {await render(flowNodes);- expect(updateIcon()).toBeNull();+ expect(statusButton()).toBeNull();const currentBorder = borderColor();await render(toFlowNodes(projectGraph, [], { preview: { ...template, version: '1.1.0' } }));- expect(updateIcon()?.getAttribute('aria-label')).toBe('Version 1.0.0 → 1.1.0: update available');+ expect(statusButton()?.getAttribute('aria-label')).toBe('Status: Version 1.0.0 → 1.1.0: update available');+ expect(statusButton()?.getAttribute('data-node-status')).toBe('updatable');expect(borderColor()).not.toBe(currentBorder);await render(toFlowNodes(projectGraph, [], { preview: { ...template, version: '2.0.0' } }));- expect(updateIcon()?.getAttribute('aria-label')).toBe(- 'Version 1.0.0 cannot be updated to 2.0.0; delete and re-add the node'+ expect(statusButton()?.getAttribute('aria-label')).toBe(+ 'Status: Version 1.0.0 cannot be updated to 2.0.0; delete and re-add the node');+ expect(statusButton()?.getAttribute('data-node-status')).toBe('versionMismatch');});it('waits neutrally for node definitions and warns of an unknown type only once they have loaded', async () => {@@ -2263,3 +2320,895 @@ describe('InvocationFlowNode batch nodes', () => {expect(header().textContent).toContain('(no group)');});});++const PROBED_COLORS = [+ 'accent.fg',+ 'accent.solid',+ 'bg',+ 'bg.muted',+ 'border.error',+ 'fg.error',+ 'fg.warning',+ 'fg',+] as const;++describe('InvocationFlowNode header, states and field rows', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width: 1000px; height: 520px;';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ const requiredInput = (+ name: string,+ title: string,+ overrides: Partial<InvocationTemplate['inputs'][string]> = {}+ ) => ({+ ...template.inputs.a!,+ input: 'any' as const,+ name,+ required: true,+ title,+ ...overrides,+ });+ const stateTemplate: InvocationTemplate = {+ ...template,+ description: 'Adds two numbers.',+ inputs: {+ a: requiredInput('a', 'A'),+ b: requiredInput('b', 'B', { input: 'connection' }),+ },+ };+ const stateNode = (id: string, x: number, value: number | undefined): WorkflowInvocationNode => ({+ ...documentNode,+ data: { ...documentNode.data, inputs: { a: { label: '', name: 'a', value } } },+ id,+ position: { x, y: 20 },+ });+ /** Each node's run state, as the execution port reports it. */+ const createExecutionMap = (states: Record<string, WorkflowNodeExecutionState>) => ({+ get: (nodeId: string) => states[nodeId] ?? null,+ subscribe: () => () => {},+ });+ const render = async (+ nodes: ReturnType<typeof toFlowNodes>,+ execution: Pick<WorkflowUiAdapter['nodeExecution'], 'get' | 'subscribe'> = createExecutionMap({})+ ) => {+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <WorkflowUiProvider adapter={createAdapter(execution)}>+ <Box css={flowThemeCss} h="full" w="full">+ <ReactFlow edges={[]} nodes={nodes} nodeTypes={nodeTypes} />+ </Box>+ </WorkflowUiProvider>+ {PROBED_COLORS.map((token) => (+ <Box key={token} color={token} data-color-probe={token} />+ ))}+ </QueryClientProvider>+ </ChakraProvider>+ )+ );+ // xyflow keeps a node `visibility: hidden` until it has measured it. Its box already has a size, but hit-tests and+ // pointer events pass through it, so a test that measures or points at a node waits for every node to show.+ await vi.waitFor(() =>+ expect(+ [...host.querySelectorAll<HTMLElement>('.react-flow__node')].every(+ (element) => getComputedStyle(element).visibility === 'visible'+ )+ ).toBe(true)+ );+ };+ const node = (id: string) => host.querySelector<HTMLElement>(`.react-flow__node[data-id="${id}"]`)!;+ const shell = (id: string) => node(id).querySelector<HTMLElement>('[data-workflow-node-shell="true"]')!;+ const header = (id: string) => shell(id).firstElementChild as HTMLElement;+ const statusButton = (id: string) => node(id).querySelector<HTMLElement>('[data-node-status-indicator="true"]');+ const panelText = () => document.querySelector('[data-scope="tooltip"][data-part="content"]')?.textContent ?? '';+ /** A theme colour as computed styles report it, independent of how the node composes it. */+ const themeColor = (token: (typeof PROBED_COLORS)[number]) =>+ getComputedStyle(host.querySelector<HTMLElement>(`[data-color-probe="${token}"]`)!).color;+ const failed: WorkflowNodeExecutionState = { ...completed(''), error: 'CUDA out of memory', status: 'failed' };++ it('explains the node in its info panel on hover and on keyboard focus, and shows no status at rest', async () => {+ const labelled = {+ ...stateNode('info-node', 20, 4),+ data: { ...stateNode('info-node', 20, 4).data, label: 'Sum', notes: 'Feeds the seed.' },+ };+ const infoTemplate = { ...stateTemplate, inputs: { a: stateTemplate.inputs.a! } };+ await render(toFlowNodes({ ...projectGraph, nodes: [labelled] }, [], { preview: infoTemplate }));++ expect(statusButton('info-node')).toBeNull();+ const infoButton = node('info-node').querySelector<HTMLButtonElement>('button[aria-label="Show details for Sum"]')!;+ expect(document.querySelector('[data-scope="tooltip"][data-part="content"]')).toBeNull();++ await act(() => userEvent.hover(infoButton));+ await vi.waitFor(() => expect(panelText()).toContain('Sum (Preview)'));+ for (const line of [+ 'Type: preview',+ 'Node pack: invokeai',+ 'Version: 1.0.0',+ 'Adds two numbers.',+ 'Feeds the seed.',+ ]) {+ expect(panelText()).toContain(line);+ }+ await act(() => userEvent.unhover(infoButton));+ await vi.waitFor(() => expect(panelText()).toBe(''));++ // Tab from the collapse button: the panel opens for keyboard focus too.+ await act(async () => {+ node('info-node').querySelector<HTMLButtonElement>('button[aria-label="Collapse node"]')!.focus();+ await userEvent.tab();+ });+ expect(document.activeElement).toBe(infoButton);+ await vi.waitFor(() => expect(panelText()).toContain('Sum (Preview)'));+ });++ it('says in the status panel what each blocking field needs, and asks for a model by name', async () => {+ await render(+ toFlowNodes({ ...projectGraph, nodes: [stateNode('invalid-node', 20, undefined)] }, [], {+ preview: stateTemplate,+ })+ );++ const button = statusButton('invalid-node')!;+ expect(button.getAttribute('aria-label')).toBe('Status: 2 fields need attention');+ await act(() => userEvent.hover(button));+ await vi.waitFor(() => expect(panelText()).toContain('A is required.'));+ expect(panelText()).toContain('B needs a connection.');+ expect(panelText()).not.toContain('Required value.');+ await act(() => userEvent.unhover(button));++ const modelTemplate: InvocationTemplate = {+ ...template,+ inputs: {+ model: requiredInput('model', 'Model', {+ input: 'direct',+ type: { batch: false, cardinality: 'SINGLE', name: 'ModelIdentifierField' },+ }),+ },+ };+ // A compact node draws no field controls but still reports what its fields need.+ await render(+ toFlowNodes(+ { ...projectGraph, nodes: [stateNode('model-node', 20, undefined)] },+ [],+ { preview: modelTemplate },+ undefined,+ true+ )+ );+ expect(statusButton('model-node')?.getAttribute('aria-label')).toBe('Status: Model is required. Pick a model.');+ });++ it('draws a failed node like an invalid one and leaves a completed node’s outline alone', async () => {+ const graph = {+ ...projectGraph,+ nodes: [+ stateNode('idle-node', 20, 1),+ stateNode('invalid-node', 340, undefined),+ stateNode('failed-node', 660, 1),+ { ...stateNode('completed-node', 20, 1), position: { x: 20, y: 260 } },+ ],+ };+ const connected = toFlowNodes(graph, [], { preview: stateTemplate }).map((flowNode) => ({+ ...flowNode,+ data: { ...flowNode.data, connectedTargetHandles: flowNode.id === 'invalid-node' ? [] : ['b'] },+ })) as ReturnType<typeof toFlowNodes>;+ await render(connected, createExecutionMap({ 'completed-node': completed(''), 'failed-node': failed }));++ const look = (id: string) => ({+ border: getComputedStyle(shell(id)).borderColor,+ headerBackground: getComputedStyle(header(id)).backgroundColor,+ headerColor: getComputedStyle(header(id)).color,+ });+ expect(look('failed-node')).toEqual(look('invalid-node'));+ expect(look('invalid-node').border).toBe(themeColor('border.error'));+ expect(look('invalid-node').headerBackground).not.toBe(look('idle-node').headerBackground);+ expect(look('completed-node')).toEqual(look('idle-node'));++ expect(statusButton('idle-node')).toBeNull();+ expect(statusButton('completed-node')?.getAttribute('aria-label')).toBe('Status: Completed');+ const failedButton = statusButton('failed-node')!;+ expect(failedButton.getAttribute('aria-label')).toBe('Status: Failed');+ // No status glyph is a circle, so none reads as the circled "i" of the info button beside it.+ const glyph = (button: HTMLElement) => button.querySelector('svg')!.getAttribute('class');+ expect(glyph(statusButton('invalid-node')!)).toContain('lucide-triangle-alert');+ expect(glyph(failedButton)).toContain('lucide-octagon-x');+ expect(glyph(statusButton('completed-node')!)).toContain('lucide-check');+ expect(glyph(node('failed-node').querySelector<HTMLElement>('[data-node-info-icon="true"]')!)).toContain(+ 'lucide-info'+ );+ await act(() => userEvent.hover(failedButton));+ await vi.waitFor(() => expect(panelText()).toContain('CUDA out of memory'));+ });++ it('rings a selected node in its state colour, a focused node in a ring of its own, and outlines it on hover', async () => {+ const outdatedNode = {+ ...stateNode('outdated-node', 660, 1),+ data: { ...stateNode('o', 0, 1).data, type: 'outdated' },+ };+ const graph = {+ ...projectGraph,+ nodes: [stateNode('valid-node', 20, 1), stateNode('invalid-node', 340, undefined), outdatedNode],+ };+ const templates = { outdated: { ...stateTemplate, type: 'outdated', version: '1.1.0' }, preview: stateTemplate };+ const nodes = toFlowNodes(graph, [], templates).map((flowNode) => ({+ ...flowNode,+ data: { ...flowNode.data, connectedTargetHandles: flowNode.id === 'invalid-node' ? [] : ['b'] },+ selected: true,+ })) as ReturnType<typeof toFlowNodes>;+ await render(nodes);++ const shadow = (id: string) => getComputedStyle(shell(id)).boxShadow;+ expect(shadow('valid-node')).toContain(themeColor('accent.solid'));+ expect(shadow('invalid-node')).toContain(themeColor('border.error'));+ expect(shadow('invalid-node')).not.toContain(themeColor('accent.solid'));+ expect(shadow('outdated-node')).toContain(themeColor('fg.warning'));+ expect(getComputedStyle(shell('outdated-node')).borderColor).toBe(themeColor('fg.warning'));+ expect(shadow('outdated-node')).not.toContain(themeColor('accent.solid'));+ expect(shadow('valid-node')).not.toContain(themeColor('fg'));++ await act(async () => {+ await userEvent.keyboard('{Shift}');+ node('invalid-node').focus();+ });+ await vi.waitFor(() => expect(shadow('invalid-node')).toContain(themeColor('fg')));+ expect(shadow('invalid-node')).toContain(themeColor('border.error'));++ await render(toFlowNodes({ ...projectGraph, nodes: [stateNode('valid-node', 20, 1)] }, [], { preview: template }));+ const restingBorder = getComputedStyle(shell('valid-node')).borderColor;+ await act(() => userEvent.hover(shell('valid-node')));+ await vi.waitFor(() => expect(getComputedStyle(shell('valid-node')).borderColor).toBe(themeColor('accent.solid')));+ expect(restingBorder).not.toBe(themeColor('accent.solid'));+ });++ it('keeps the space where a node title or an output title is split, as an untrimmed label draws it', async () => {+ const splitTemplate = {+ ...stateTemplate,+ outputs: { value: { ...stateTemplate.outputs.value!, title: 'Image to Latents' } },+ title: 'Latents to Image',+ };+ await render(+ toFlowNodes({ ...projectGraph, nodes: [stateNode('split-node', 20, 1)] }, [], { preview: splitTemplate })+ );++ for (const text of ['Latents to Image', 'Image to Latents']) {+ const label = node('split-node').querySelector<HTMLElement>(`[data-full-text="${text}"]`)!;+ const [head, tail] = [...label.children] as HTMLElement[];+ expect(getComputedStyle(head!).whiteSpace).toBe('pre');+ // The same label untrimmed, beside it in the same font: its spans hold their own white-space.+ const reference = label.cloneNode(true) as HTMLElement;+ reference.style.cssText = 'position: absolute; visibility: hidden; overflow: visible';+ for (const span of reference.children as HTMLCollectionOf<HTMLElement>) {+ span.style.cssText = 'text-box: normal; white-space: pre; flex-shrink: 0';+ }+ label.parentElement!.append(reference);+ const width = [...reference.children].reduce((sum, span) => sum + span.getBoundingClientRect().width, 0);+ reference.remove();+ expect(head!.getBoundingClientRect().width + tail!.getBoundingClientRect().width).toBeCloseTo(width, 0);+ }+ });++ it('opens rename inputs over their label without moving anything around them', async () => {+ await render(rowNodes(4));+ const nodeRect = () => node('row-node').getBoundingClientRect();+ const buttonRects = () =>+ [...header('row-node').querySelectorAll('button')].map((button) => button.getBoundingClientRect().toJSON());+ const rowRect = () => fieldTitle('A').closest('[data-node-field-row]')!.getBoundingClientRect();+ const before = { buttons: buttonRects(), node: nodeRect().height, row: rowRect().height };+ const titleFontSize = parseFloat(getComputedStyle(header('row-node').querySelector('[title]')!).fontSize);+ const labelFontSize = parseFloat(getComputedStyle(fieldTitle('A')).fontSize);++ await act(() => userEvent.dblClick(header('row-node').querySelector<HTMLElement>('[title]')!));+ const titleInput = host.querySelector<HTMLInputElement>('input[aria-label="Node label"]')!;+ expect(document.activeElement).toBe(titleInput);+ // Each rename input keeps the text size of the label it replaces.+ expect(parseFloat(getComputedStyle(titleInput).fontSize)).toBe(titleFontSize);+ expect(nodeRect().height).toBe(before.node);+ expect(buttonRects()).toEqual(before.buttons);+ // Its own surface, not the header's tint.+ expect(getComputedStyle(titleInput).backgroundColor).not.toBe(getComputedStyle(header('row-node')).backgroundColor);+ await act(() => userEvent.keyboard('{Escape}'));++ await act(() => userEvent.dblClick(fieldTitle('A')));+ const labelInput = host.querySelector<HTMLInputElement>('input[aria-label="Field label"]')!;+ expect(parseFloat(getComputedStyle(labelInput).fontSize)).toBe(labelFontSize);+ expect(labelInput.getBoundingClientRect().right).toBeLessThan(nodeRect().right);+ expect(rowRect().height).toBe(before.row);+ expect(nodeRect().height).toBe(before.node);+ await act(() => userEvent.keyboard('{Escape}'));+ expect(nodeRect().height).toBe(before.node);+ });++ it('sets the header’s end buttons as far from the right border as the collapse button is from the left', async () => {+ const graph = {+ ...projectGraph,+ nodes: [stateNode('valid-node', 20, 1), stateNode('invalid-node', 340, undefined)],+ };+ await render(+ toFlowNodes(graph, [], { preview: stateTemplate }).map((flowNode) => ({+ ...flowNode,+ data: { ...flowNode.data, connectedTargetHandles: flowNode.id === 'valid-node' ? ['b'] : [] },+ })) as ReturnType<typeof toFlowNodes>+ );++ for (const id of ['valid-node', 'invalid-node']) {+ const shellRect = shell(id).getBoundingClientRect();+ const border = parseFloat(getComputedStyle(shell(id)).borderLeftWidth);+ const buttons = [...header(id).querySelectorAll<HTMLElement>('button')].map((button) =>+ button.getBoundingClientRect()+ );+ const startInset = buttons[0]!.left - (shellRect.left + border);+ const endInset = shellRect.right - border - buttons.at(-1)!.right;+ expect(startInset).toBeGreaterThan(0);+ expect(endInset).toBeCloseTo(startInset, 1);+ }+ });++ it('strengthens a red or amber outline on hover instead of leaving it unchanged', async () => {+ const outdatedNode = {+ ...stateNode('outdated-node', 340, 1),+ data: { ...stateNode('o', 0, 1).data, type: 'outdated' },+ };+ const graph = { ...projectGraph, nodes: [stateNode('invalid-node', 20, undefined), outdatedNode] };+ const templates = { outdated: { ...stateTemplate, type: 'outdated', version: '1.1.0' }, preview: stateTemplate };+ await render(+ toFlowNodes(graph, [], templates).map((flowNode) => ({+ ...flowNode,+ data: { ...flowNode.data, connectedTargetHandles: ['b'] },+ })) as ReturnType<typeof toFlowNodes>+ );++ for (const [id, resting] of [+ ['invalid-node', themeColor('border.error')],+ ['outdated-node', themeColor('fg.warning')],+ ] as const) {+ expect(getComputedStyle(shell(id)).borderColor).toBe(resting);+ await act(() => userEvent.hover(header(id)));+ await vi.waitFor(() => {+ const hovered = getComputedStyle(shell(id)).borderColor;+ expect(hovered).not.toBe(resting);+ expect(hovered).not.toBe(themeColor('accent.solid'));+ });+ await act(() => userEvent.unhover(header(id)));+ }+ });++ /** A node with one editable field `A` (connectable) and one connection-only field `B`, fed by a connection. */+ const rowNodes = (value: number | undefined, exposed: string[] = []) =>+ toFlowNodes({ ...projectGraph, nodes: [stateNode('row-node', 20, value)] }, [], { preview: stateTemplate }).map(+ (flowNode) => ({+ ...flowNode,+ data: { ...flowNode.data, connectedTargetHandles: ['b'], exposedFieldNames: exposed },+ })+ ) as ReturnType<typeof toFlowNodes>;+ const fieldTitle = (name: string) =>+ [...node('row-node').querySelectorAll<HTMLElement>('[data-node-input-field-title="true"]')].find((title) =>+ title.textContent?.startsWith(name)+ )!;+ const rowActions = (name: string) =>+ fieldTitle(name)+ .closest('[data-scope="field"][data-part="root"]')!+ .querySelector<HTMLElement>('[data-node-field-actions]')!;+ const opacity = (element: HTMLElement) => getComputedStyle(element).opacity;++ it('shows a row’s actions in legacy order on hover and on keyboard focus, and keeps them operable by keyboard', async () => {+ const adapter = createAdapter(createExecutionMap({}));+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <WorkflowUiProvider adapter={adapter}>+ <Box css={flowThemeCss} h="full" w="full">+ <ReactFlow edges={[]} nodes={rowNodes(4)} nodeTypes={nodeTypes} />+ </Box>+ </WorkflowUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ )+ );++ const actions = rowActions('A');+ expect([...actions.querySelectorAll('button')].map((button) => button.getAttribute('aria-label'))).toEqual([+ 'Edit field description',+ 'Reset A to default value',+ 'Add A to the form',+ ]);+ // A connection-fed row keeps only the description: there is no value to reset or put in the form.+ expect([...rowActions('B').querySelectorAll('button')].map((button) => button.getAttribute('aria-label'))).toEqual([+ 'Edit field description',+ ]);+ expect(opacity(actions)).toBe('0');++ await act(() => userEvent.hover(fieldTitle('A')));+ await vi.waitFor(() => expect(opacity(actions)).toBe('1'));+ expect(opacity(rowActions('B'))).toBe('0');+ await act(() => userEvent.unhover(fieldTitle('A')));+ await vi.waitFor(() => expect(opacity(actions)).toBe('0'));++ // Keyboard: focus in the row's control shows the actions, and Tab reaches them.+ const control = node('row-node').querySelector<HTMLInputElement>('input[aria-label="A"]')!;+ await act(async () => {+ control.focus();+ await userEvent.keyboard('{Shift>}{Tab}{/Shift}');+ });+ expect(document.activeElement?.getAttribute('aria-label')).toBe('Add A to the form');+ await vi.waitFor(() => expect(opacity(actions)).toBe('1'));+ await act(() => userEvent.keyboard('{Enter}'));+ expect(adapter.commands.editGraph).toHaveBeenCalledWith({+ fieldIdentifier: { fieldName: 'a', nodeId: 'row-node' },+ type: 'exposeField',+ });+ });++ it('marks a field in the form on its label, blue with a link, instead of a lit button', async () => {+ await render(rowNodes(4, ['a']));++ const title = fieldTitle('A');+ expect(getComputedStyle(title).color).toBe(themeColor('accent.fg'));+ expect(title.querySelector('[role="img"][aria-label="In the form"]')).not.toBeNull();+ expect(getComputedStyle(fieldTitle('B')).color).not.toBe(themeColor('accent.fg'));+ const formButton = rowActions('A').querySelector<HTMLElement>('button[aria-label="Remove A from the form"]')!;+ expect(getComputedStyle(formButton).color).not.toBe(themeColor('accent.solid'));+ });++ it('marks an invalid field on its label and control border, with the reason on hover rather than under the field', async () => {+ await render(rowNodes(undefined));++ const title = fieldTitle('A');+ const control = node('row-node').querySelector<HTMLInputElement>('input[aria-label="A"]')!;+ expect(getComputedStyle(title).color).toBe(themeColor('fg.error'));+ expect(control.getAttribute('aria-invalid')).toBe('true');+ expect(getComputedStyle(control).borderColor).toBe(themeColor('border.error'));+ // The value sits in the node's recessed well, a step darker than the body, and keeps its error border on it.+ expect(getComputedStyle(control).backgroundColor).toBe(themeColor('bg'));+ expect(themeColor('bg')).not.toBe(themeColor('bg.muted'));+ expect(node('row-node').textContent).not.toContain('Required value.');+ // The reason is read with the control but not drawn under it.+ const description = node('row-node').querySelector<HTMLElement>('[data-part="error-text"]')!;+ expect(description.textContent).toBe('A is required.');+ // The field links it as the control's error message, as it does in the form view.+ expect(control.getAttribute('aria-errormessage')).toBe(description.id);+ expect(description.getBoundingClientRect().height).toBeLessThanOrEqual(1);++ await act(() => userEvent.hover(title));+ await vi.waitFor(() => expect(panelText()).toContain('A is required.'));+ });++ it('sets a last control as far from the node’s bottom as from its sides, and leaves a last label row tight', async () => {+ const controlLast = { ...stateTemplate, inputs: { a: stateTemplate.inputs.a! } };+ await render(toFlowNodes({ ...projectGraph, nodes: [stateNode('row-node', 20, 4)] }, [], { preview: controlLast }));++ const shellElement = node('row-node').querySelector<HTMLElement>('[data-workflow-node-shell="true"]')!;+ const inner = shellElement.getBoundingClientRect();+ const border = parseFloat(getComputedStyle(shellElement).borderBottomWidth);+ const control = node('row-node').querySelector<HTMLElement>('[data-node-field-control]')!.getBoundingClientRect();+ const sideGap = control.left - (inner.left + border);+ const bottomGap = inner.bottom - border - control.bottom;+ expect(sideGap).toBeGreaterThan(8);+ expect(bottomGap).toBeCloseTo(sideGap, 0);++ // Ending in B, a row with no control, keeps the rows' own bottom padding.+ await render(rowNodes(4));+ const lastRow = fieldTitle('B').closest<HTMLElement>('[data-node-field-row]')!;+ const firstRow = fieldTitle('A').closest<HTMLElement>('[data-node-field-row]')!;+ expect(getComputedStyle(lastRow).paddingBottom).toBe(getComputedStyle(firstRow).paddingBottom);+ });++ it('fills a text area’s faded bottom with the same well as the text area itself', async () => {+ const promptInput = requiredInput('a', 'A', {+ input: 'direct',+ type: { batch: false, cardinality: 'SINGLE', name: 'StringField' },+ uiComponent: 'textarea',+ });+ await render(+ toFlowNodes(+ {+ ...projectGraph,+ nodes: [+ {+ ...stateNode('row-node', 20, undefined),+ data: {+ ...stateNode('row-node', 20, undefined).data,+ inputs: { a: { label: '', name: 'a', value: 'text' } },+ },+ },+ ],+ },+ [],+ { preview: { ...stateTemplate, inputs: { a: promptInput } } }+ )+ );++ const textarea = node('row-node').querySelector<HTMLTextAreaElement>('textarea')!;+ const fade = node('row-node').querySelector<HTMLElement>('[data-resizable-textarea-fade]')!;+ const fadeEnd = [...getComputedStyle(fade).backgroundImage.matchAll(/(?:rgba?|oklch)\([^)]*\)/g)].at(-1)?.[0];+ expect(getComputedStyle(textarea).backgroundColor).toBe(themeColor('bg'));+ expect(getComputedStyle(fade).display).not.toBe('none');+ expect(fadeEnd).toBe(getComputedStyle(textarea).backgroundColor);+ });++ it('gives each port a 24×24 grab area centred on its 12px dot', async () => {+ await render(rowNodes(4));++ const handle = node('row-node').querySelector<HTMLElement>('.react-flow__handle[data-handleid="a"]')!;+ const dot = handle.getBoundingClientRect();+ const centre = { x: dot.left + dot.width / 2, y: dot.top + dot.height / 2 };+ expect(dot.width).toBe(12);+ // 10px out is past the dot but inside the grab area; 14px out is past both.+ expect(document.elementFromPoint(centre.x - 10, centre.y + 10)).toBe(handle);+ expect(document.elementFromPoint(centre.x - 14, centre.y)).not.toBe(handle);+ });++ it('keeps a batch port’s grab area an upright 24×24 square, not its dot’s diamond', async () => {+ const batchInput = requiredInput('a', 'A', {+ input: 'connection',+ type: { batch: true, cardinality: 'COLLECTION', name: 'IntegerField' },+ });+ await render(+ toFlowNodes({ ...projectGraph, nodes: [stateNode('row-node', 20, 4)] }, [], {+ preview: { ...stateTemplate, inputs: { a: batchInput } },+ })+ );++ const handle = node('row-node').querySelector<HTMLElement>('.react-flow__handle[data-handleid="a"]')!;+ expect(handle.style.transform).toContain('rotate(45deg)');+ const dot = handle.getBoundingClientRect();+ const centre = { x: dot.left + dot.width / 2, y: dot.top + dot.height / 2 };+ // A corner of the upright square is inside; a diamond's tip, 16px straight out, is not.+ expect(document.elementFromPoint(centre.x - 11, centre.y - 11)).toBe(handle);+ expect(document.elementFromPoint(centre.x, centre.y + 16)).not.toBe(handle);+ });++ it('reports a HiDiffusion ratio order problem once while marking both ratios', async () => {+ const denoiseTemplates = parseOpenApiToTemplates(openapi);+ const denoise = buildInvocationNode(denoiseTemplates.denoise_latents!, { x: 0, y: 0 });+ denoise.data.inputs.hidiffusion!.value = true;+ denoise.data.inputs.hidiffusion_auto_ratios!.value = false;+ denoise.data.inputs.hidiffusion_t1_ratio!.value = 0.2;+ denoise.data.inputs.hidiffusion_t2_ratio!.value = 0.7;+ await render(toFlowNodes({ ...projectGraph, nodes: [denoise] }, [], denoiseTemplates));++ for (const name of ['hidiffusion_t1_ratio', 'hidiffusion_t2_ratio']) {+ expect(+ host.querySelector(`input[id="${denoise.id}-${name}-value-number-input"]`)?.getAttribute('aria-invalid')+ ).toBe('true');+ }+ await act(() => userEvent.hover(host.querySelector<HTMLElement>('[data-node-status-indicator="true"]')!));+ await vi.waitFor(() => expect(panelText()).toContain('T2 ratio must be less'));+ expect(panelText().split('T2 ratio must be less')).toHaveLength(2);+ });+});++describe('InvocationFlowNode collapsed ports', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width: 1000px; height: 520px;';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ const placed = (id: string, x: number, y: number, isOpen: boolean): WorkflowInvocationNode => ({+ ...documentNode,+ data: { ...documentNode.data, isOpen },+ id,+ position: { x, y },+ });+ const edge = (id: string, source: string, target: string): WorkflowEdge => ({+ id,+ source,+ sourceHandle: 'value',+ target,+ targetHandle: 'a',+ type: 'default',+ });+ // a and b collapse with two edges between them; c stays open and is fed by a.+ const graphWith = (isOpen: boolean): ProjectGraphState => ({+ ...projectGraph,+ edges: [edge('ab1', 'a', 'b'), edge('ab2', 'a', 'b'), edge('ac', 'a', 'c')],+ nodes: [placed('a', 20, 20, isOpen), placed('b', 420, 20, isOpen), placed('c', 420, 260, true)],+ });+ const render = (graph: ProjectGraphState) =>+ act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={createAdapter(createExecutionPort().port, projectSnapshotFor(graph))}>+ <Box css={flowThemeCss} h="full" w="full">+ <ReactFlow+ edges={toFlowEdges(graph, [], 'default', undefined, templates)}+ edgeTypes={{ default: WorkflowEdgeComponent }}+ nodes={toFlowNodes(graph, [], templates)}+ nodeTypes={nodeTypes}+ />+ </Box>+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );+ const node = (id: string) => host.querySelector<HTMLElement>(`.react-flow__node[data-id="${id}"]`)!;+ const drawnEdgeIds = () =>+ [...host.querySelectorAll<SVGElement>('.react-flow__edge')].map((element) => element.getAttribute('data-id'));+ const centre = (rect: DOMRect) => ({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 });++ it('merges a collapsed node’s ports, draws its edges from them with a count, and restores them on expand', async () => {+ await render(graphWith(false));++ const sourcePort = node('a').querySelector<HTMLElement>('[data-collapsed-port="right"]')!;+ expect(node('b').querySelector('[data-collapsed-port="left"]')).not.toBeNull();+ await vi.waitFor(() => expect(drawnEdgeIds().sort()).toEqual(['ab1', 'ac']));+ expect(host.querySelector('[data-collapsed-edge-count]')?.getAttribute('data-collapsed-edge-count')).toBe('2');++ // The edge to the open node leaves the merged port's outer side.+ const path = host.querySelector<SVGPathElement>('.react-flow__edge[data-id="ac"] .react-flow__edge-path')!;+ const start = path.getPointAtLength(0).matrixTransform(path.getScreenCTM()!);+ const port = sourcePort.getBoundingClientRect();+ expect(Math.abs(start.x - port.right)).toBeLessThan(1);+ expect(Math.abs(start.y - centre(port).y)).toBeLessThan(1);++ // The field handles behind the merged port take no new connections; legacy asked for the node to be opened.+ const hiddenHandle = node('a').querySelector<HTMLElement>('.react-flow__handle[data-handleid="value"]')!;+ expect(getComputedStyle(hiddenHandle).visibility).toBe('hidden');+ expect(hiddenHandle.classList.contains('connectable')).toBe(false);++ await render(graphWith(true));+ await vi.waitFor(() => expect(drawnEdgeIds().sort()).toEqual(['ab1', 'ab2', 'ac']));+ expect(host.querySelector('[data-collapsed-port]')).toBeNull();+ expect(host.querySelector('[data-collapsed-edge-count]')).toBeNull();+ });++ /**+ * The middle of a label's lowercase letters, which is what a reader lines a port up with, from the font itself: a 1ex+ * inline box standing on the label's baseline spans exactly its x-height.+ */+ const letterBodyCentre = (label: HTMLElement) => {+ const text = [label, ...label.querySelectorAll<HTMLElement>('*')]+ .reverse()+ .find((element) =>+ [...element.childNodes].some((child) => child.nodeType === Node.TEXT_NODE && child.textContent?.trim())+ )!;+ const probe = document.createElement('span');+ probe.style.cssText = 'display: inline-block; height: 1ex; vertical-align: baseline; width: 0';+ text.append(probe);+ const box = probe.getBoundingClientRect();+ probe.remove();+ return box.top + box.height / 2;+ };++ it('centres each port on its label’s letters, edges on the ports, and a collapsed node’s merged ports on its title', async () => {+ await render(graphWith(true));+ await vi.waitFor(() => expect(drawnEdgeIds()).toContain('ac'));++ const target = node('c').querySelector<HTMLElement>('.react-flow__handle[data-handleid="a"]')!;+ const source = node('a').querySelector<HTMLElement>('.react-flow__handle[data-handleid="value"]')!;+ const rows = [+ {+ handle: target,+ label: target.parentElement!.querySelector<HTMLElement>('[data-node-input-field-title="true"]')!,+ },+ {+ handle: source,+ label: source.parentElement!.querySelector<HTMLElement>('[data-node-output-field-title="true"]')!,+ },+ ];+ for (const { handle, label } of rows) {+ expect(Math.abs(centre(handle.getBoundingClientRect()).y - letterBodyCentre(label))).toBeLessThanOrEqual(0.5);+ }++ const path = host.querySelector<SVGPathElement>('.react-flow__edge[data-id="ac"] .react-flow__edge-path')!;+ const start = path.getPointAtLength(0).matrixTransform(path.getScreenCTM()!);+ const end = path.getPointAtLength(path.getTotalLength()).matrixTransform(path.getScreenCTM()!);+ expect(Math.abs(start.y - centre(source.getBoundingClientRect()).y)).toBeLessThan(1);+ expect(Math.abs(end.y - centre(target.getBoundingClientRect()).y)).toBeLessThan(1);++ await render(graphWith(false));+ const header = node('a').querySelector<HTMLElement>('[data-workflow-node-shell="true"]')!.firstElementChild!;+ const title = [...header.querySelectorAll<HTMLElement>('p, span')].find(+ (element) => element.childElementCount === 0 && element.textContent === template.title+ )!;+ for (const side of ['left', 'right']) {+ const port = node('a').querySelector<HTMLElement>(`[data-collapsed-port="${side}"]`)!;+ expect(Math.abs(centre(port.getBoundingClientRect()).y - letterBodyCentre(title))).toBeLessThanOrEqual(0.5);+ }+ });++ it('draws every edge, as itself, in an image export of collapsed nodes', async () => {+ const graph = graphWith(false);+ const exportRef = createRef<HTMLDivElement>();+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={createAdapter(createExecutionPort().port, projectSnapshotFor(graph))}>+ <Box css={flowThemeCss} h="full" w="full">+ <WorkflowImageExportView+ containerRef={exportRef}+ edges={toFlowEdges(graph, [], 'default', undefined, templates)}+ edgeTypes={{ default: WorkflowEdgeComponent }}+ nodes={toFlowNodes(graph, [], templates)}+ nodeTypes={nodeTypes}+ />+ </Box>+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );++ const exported = () =>+ [...exportRef.current!.querySelectorAll<SVGGElement>('.react-flow__edge')].map((element) => element.dataset.id);+ await vi.waitFor(() => expect(exported().sort()).toEqual(['ab1', 'ab2', 'ac']));+ expect(exportRef.current!.querySelector('[data-collapsed-edge-count]')).toBeNull();+ const strokes = [...exportRef.current!.querySelectorAll<SVGPathElement>('.react-flow__edge-path')].map(+ (path) => path.style.stroke+ );+ // IntegerField's colour, not the neutral a merged edge draws in.+ expect(new Set(strokes)).toEqual(new Set(['rgb(248, 113, 113)']));+ });++ it('keeps a collapsed node in a large graph’s compact mode unconnectable and cheap', async () => {+ const graph = graphWith(false);+ const execution = createExecutionPort('a');+ execution.set(completed(''));+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={createAdapter(execution.port, projectSnapshotFor(graph))}>+ <Box css={flowThemeCss} h="full" w="full">+ <ReactFlow+ edges={toFlowEdges(graph, [], 'default', undefined, templates)}+ edgeTypes={{ default: WorkflowEdgeComponent }}+ nodes={toFlowNodes(graph, [], templates, undefined, true)}+ nodeTypes={nodeTypes}+ />+ </Box>+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );++ expect(node('a').querySelector('[data-collapsed-port="right"]')).not.toBeNull();+ const handles = [...node('a').querySelectorAll<HTMLElement>('.react-flow__handle')];+ expect(handles.length).toBeGreaterThan(0);+ expect(handles.some((handle) => handle.classList.contains('connectable'))).toBe(false);+ // The completed mark is a plain image named for its state: no button, no tooltip to mount.+ const status = node('a').querySelector<HTMLElement>('[data-node-status-indicator="true"]')!;+ expect(status.getAttribute('role')).toBe('img');+ expect(status.getAttribute('aria-label')).toBe('Status: Completed');+ expect(status.closest('button, [data-scope="tooltip"]')).toBeNull();+ });+});++describe('CurrentImageFlowNode', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width: 480px; height: 520px;';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ exportMocks.progressImage = null;+ });++ const image = (name: string) => ({+ height: 2,+ imageName: name,+ imageUrl: `${outputImage(2, 2)}#${name}`,+ queuedAt: '2026-01-01T00:00:00Z',+ sourceQueueItemId: 'queue-item',+ thumbnailUrl: outputImage(1, 1),+ width: 2,+ });+ const recent = image('recent.png');+ const chosen = image('chosen.png');+ /** A project port whose gallery values the test changes, as the Gallery widget does. */+ const createGalleryProject = (galleryValues: Record<string, unknown>) => {+ let snapshot = projectSnapshotFor(currentImageGraph, galleryValues);+ const listeners = new Set<() => void>();++ return {+ port: {+ getSnapshot: () => snapshot,+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ setGalleryValues: (next: Record<string, unknown>) => {+ snapshot = projectSnapshotFor(currentImageGraph, next);+ listeners.forEach((listener) => listener());+ },+ };+ };+ const render = (+ project: ReturnType<typeof createGalleryProject>,+ onDragStart: (event: DragStartEvent) => void = () => {}+ ) =>+ act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider+ adapter={+ { ...createAdapter(createExecutionPort().port), project: project.port } as unknown as WorkflowUiAdapter+ }+ >+ {/* Stands in for the shell's drag context, where gallery items are dragged. */}+ <DndContext onDragStart={onDragStart}>+ <ReactFlow edges={[]} nodes={currentImageNodes} nodeTypes={nodeTypes} />+ </DndContext>+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );+ const shownImage = () => host.querySelector<HTMLImageElement>('.react-flow__node img')?.src ?? null;++ it('shows the gallery’s selected image, passes over a selected video, and falls back to the latest image', async () => {+ const project = createGalleryProject({ recentImages: [recent, chosen] });+ await render(project);+ // Nothing selected: the project's most recent image.+ await vi.waitFor(() => expect(shownImage()).toBe(recent.imageUrl));++ await act(() =>+ project.setGalleryValues({ recentImages: [recent, chosen], selectedImageName: 'image:chosen.png' })+ );+ await vi.waitFor(() => expect(shownImage()).toBe(chosen.imageUrl));++ await act(() => project.setGalleryValues({ recentImages: [recent, chosen], selectedImageName: 'video:clip.mp4' }));+ await vi.waitFor(() => expect(shownImage()).toBe(recent.imageUrl));+ });++ it('offers the shown image as a gallery drag source', async () => {+ const onDragStart = vi.fn();+ await render(createGalleryProject({ recentImages: [recent] }), onDragStart);+ await vi.waitFor(() => expect(shownImage()).toBe(recent.imageUrl));+ const frame = host.querySelector('.react-flow__node img')!.getBoundingClientRect();+ const from = { x: frame.left + frame.width / 2, y: frame.top + frame.height / 2 };++ await commands.mouseDragPath([from, { x: from.x + 30, y: from.y + 30 }], window.innerWidth);+ expect(onDragStart).toHaveBeenCalledOnce();+ expect(onDragStart.mock.calls[0]![0].active.data.current).toEqual({+ items: [{ kind: 'image', name: 'recent.png' }],+ kind: 'gallery-item',+ });++ const source = host.querySelector('.react-flow__node img')!.closest<HTMLElement>('.nodrag');+ expect(source).not.toBeNull();+ // A pointer drag source only: no tab stop or button role for the canvas's keys to fight over.+ expect(source!.getAttribute('tabindex')).toBeNull();+ expect(source!.getAttribute('role')).toBeNull();+ });++ it('does not render again for gallery changes that leave the shown image alone', async () => {+ const renders = vi.spyOn(exportMocks, 'progressImage', 'get');+ const project = createGalleryProject({ recentImages: [recent], selectedBoardId: 'a' });+ await render(project);+ await vi.waitFor(() => expect(shownImage()).toBe(recent.imageUrl));+ const settled = renders.mock.calls.length;++ await act(() => project.setGalleryValues({ recentImages: [recent], selectedBoardId: 'b', galleryPage: 3 }));+ expect(renders.mock.calls.length).toBe(settled);+ renders.mockRestore();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.test.tsindex 2ec5253a73..d673e23b25 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.test.ts@@ -1,12 +1,14 @@import type { WorkflowInvocationNode } from '@features/workflow/contracts';+import type { WorkflowNodeExecutionState } from '@features/workflow/ui/contracts';import { describe, expect, it } from 'vitest';import {- getNodeExecutionError,+ getInvocationNodeState,shouldShowCallSavedWorkflowLoadingHint,shouldShowCallSavedWorkflowNoExposedFieldsHint,} from './InvocationFlowNode';+import { getNodeExecutionError } from './nodeStatusText';const node = (type: string, status?: WorkflowInvocationNode['data']['callSavedWorkflowStatus']) =>({ data: { type, callSavedWorkflowStatus: status } }) as WorkflowInvocationNode;@@ -44,6 +46,51 @@ describe('shouldShowCallSavedWorkflowNoExposedFieldsHint', () => {});});+describe('getInvocationNodeState', () => {+ const execution = (status: WorkflowNodeExecutionState['status']): WorkflowNodeExecutionState => ({+ error: status === 'failed' ? 'Out of memory' : null,+ latestOutput: null,+ outputImageName: null,+ progress: status === 'running' ? 0.4 : null,+ progressMessage: null,+ status,+ });+ const state = (overrides: Partial<Parameters<typeof getInvocationNodeState>[0]> = {}) =>+ getInvocationNodeState({ execution: null, hasFieldIssues: false, updateStatus: 'current', ...overrides });++ it('reports nothing for a current, valid node that has not run', () => {+ expect(state()).toEqual({+ chrome: { failed: false, invalid: false, outdated: false, running: false },+ status: null,+ });+ });++ it('shows the status that most needs attention while keeping every chrome fact', () => {+ expect(state({ execution: execution('running'), hasFieldIssues: true, updateStatus: 'updatable' })).toEqual({+ chrome: { failed: false, invalid: true, outdated: true, running: true },+ status: 'running',+ });+ expect(state({ execution: execution('failed'), hasFieldIssues: true }).status).toBe('failed');+ expect(state({ execution: execution('completed'), hasFieldIssues: true }).status).toBe('invalid');+ expect(state({ execution: execution('completed'), updateStatus: 'updatable' }).status).toBe('updatable');+ expect(state({ execution: execution('completed') }).status).toBe('completed');+ });++ it('separates an update the editor can apply from a version it cannot', () => {+ expect(state({ updateStatus: 'updatable' }).status).toBe('updatable');+ expect(state({ updateStatus: 'newer' }).status).toBe('versionMismatch');+ expect(state({ updateStatus: 'incompatible' }).status).toBe('versionMismatch');+ });++ it('marks a completed run in the status only, and a node of unknown type as invalid', () => {+ expect(state({ execution: execution('completed') }).chrome).toEqual(state().chrome);+ expect(state({ isMissingTemplate: true, updateStatus: null })).toEqual({+ chrome: { failed: false, invalid: true, outdated: false, running: false },+ status: null,+ });+ });+});+describe('getNodeExecutionError', () => {const translate = (key: string, options: { error: string }) => `${key}: ${options.error}`;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsxindex ef424cf908..c06dbf04c3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx@@ -8,15 +8,22 @@ import { getWorkflowFieldSeedMode, isSeedInputField } from '@features/workflow/gimport { FieldDescriptionPopover } from '@features/workflow/ui/fields/FieldDescriptionPopover';import { WorkflowFieldInput, WorkflowFieldSnapshot } from '@features/workflow/ui/fields/WorkflowFieldInput';import {+ getWorkflowNodeAppearance,getWorkflowNodeBodyProps,getWorkflowNodeHandleStyle,getWorkflowNodeHeaderProps,getWorkflowNodeShellProps,WORKFLOW_NODE_DENSITY,- WorkflowNodeInfoIcon,- WorkflowNodeOutcomeIcon,+ WORKFLOW_NODE_FIELD_CONTROL_ATTRIBUTE,+ WORKFLOW_NODE_LABEL_TEXT_CSS,+ WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS,+ WORKFLOW_NODE_FIELD_ROW_ATTRIBUTE,+ WorkflowNodeHeaderButton,+ WorkflowNodeInfoButton,+ WorkflowNodeStatusButton,useIsWorkflowImageExport,- type WorkflowNodeOutcome,+ type WorkflowNodeChromeState,+ type WorkflowNodeStatus,} from '@features/workflow/ui/nodeChrome';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {@@ -40,26 +47,56 @@ import {getWorkflowBatchGroupId,isWorkflowBatchNodeType,getOutputFieldRows,- getWorkflowFieldInvalidReason,+ getWorkflowFieldIssue,isDirectInputField,isExposableField,isWorkflowFieldValueDefault,+ type WorkflowNodeUpdateStatus,} from '@features/workflow/utility';+import { createDeferredModule } from '@platform/react/deferredModule';import { Tooltip } from '@platform/ui';import { Button } from '@platform/ui/Button';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';import { Handle, Position, useStore, type NodeProps } from '@xyflow/react';-import { ChevronDownIcon, ChevronRightIcon, PinIcon, PinOffIcon, RotateCcwIcon, TriangleAlertIcon } from 'lucide-react';-import { memo, useRef, useState, type ChangeEvent, type KeyboardEvent } from 'react';+import {+ ChevronDownIcon,+ ChevronRightIcon,+ CpuIcon,+ FlaskConicalIcon,+ HammerIcon,+ LinkIcon,+ MinusIcon,+ PlusIcon,+ RotateCcwIcon,+ TriangleAlertIcon,+ ZapIcon,+ type LucideIcon,+} from 'lucide-react';+import { memo, useRef, useState, type ChangeEvent, type KeyboardEvent, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import type { InvocationFlowNode as InvocationFlowNodeType, InvocationNodeTemplateView } from './flowAdapters';+import type * as NodePanelsModule from './NodePanels';import { getHandleTypeTooltip } from './handleTooltip';+import { getExecutionStatusText, getFieldIssueMessage, type InvocationNodeFieldIssue } from './nodeStatusText';const NODE_WIDTH = '18rem';/** Row padding-x in px; inline handles sit in the label rows, so they pull back out past it. */const ROW_PADDING_X = 12;+/** A field port's centre, on its row's label line. */+const PORT_TOP = `calc(${WORKFLOW_NODE_DENSITY.labelLine} / 2)`;+/**+ * An export's output title wraps instead of truncating, so it is not one line to centre on the port. Its first line's+ * letters are put there instead: the trimmed box starts at their x-height, `ex` is that height, and the padding sets+ * their middle on the port's centre.+ */+const EXPORT_OUTPUT_TITLE_CSS = {+ '@supports (text-box: trim-start ex alphabetic)': {+ pt: `calc(${PORT_TOP} - 0.5ex)`,+ textBox: 'trim-start ex alphabetic',+ },+} as const;/** Below this viewport zoom, field content renders as skeleton bars (ComfyUI-style) for performance/readability. */export const CONTENT_VISIBILITY_ZOOM = 0.4;@@ -93,123 +130,243 @@ export const shouldShowCallSavedWorkflowNoExposedFieldsHint = (node: WorkflowInv/** Static placeholder bar standing in for text/controls at far zoom. No animation — there may be hundreds. */const SkeletonBar = ({ h = '2', w }: { h?: string; w?: string }) => <Box bg="bg.emphasized" h={h} rounded="sm" w={w} />;-const hasMissingRequiredInputs = (- node: WorkflowInvocationNode,- templateInputs: FieldInputTemplate[],- connectedFieldNames: Set<string>-): boolean =>- templateInputs.some(- (inputTemplate) =>- getWorkflowFieldInvalidReason({- isConnected: connectedFieldNames.has(inputTemplate.name),- template: inputTemplate,- value: node.data.inputs[inputTemplate.name]?.value,- }) !== null- );+/** A field that keeps its node from running, named as the node shows it. */+const HIDIFFUSION_RATIO_FIELDS = ['hidiffusion_t1_ratio', 'hidiffusion_t2_ratio'] as const;+/** Invoke's validation reports the ratio order on T2 (buildGraph); the status lists it once, there. */+const HIDIFFUSION_RATIO_REPORTED_FIELD = 'hidiffusion_t2_ratio';-const getExecutionOutcome = (execution: NodeExecutionState | null): WorkflowNodeOutcome | null =>- execution?.status === 'completed' || execution?.status === 'failed' ? execution.status : null;+const EMPTY_FIELD_ISSUES: InvocationNodeFieldIssue[] = [];-export const getNodeExecutionError = (+/** Every field that keeps the node from running, in row order; the node, its rows and its status panel share it. */+const getInvocationNodeFieldIssues = (node: WorkflowInvocationNode,- error: string | null | undefined,- translate: (key: string, options: { error: string }) => string-): string | null | undefined => {- if (!error || node.data.type !== 'call_saved_workflow') {- return error;+ inputTemplates: readonly FieldInputTemplate[],+ connectedFieldNames: ReadonlySet<string>+): InvocationNodeFieldIssue[] => {+ let issues: InvocationNodeFieldIssue[] | null = null;+ const ratioIssue = inputTemplates.some((template) => isHiDiffusionRatioField(template.name))+ ? getHiDiffusionRatioOrderIssue(node, connectedFieldNames)+ : null;++ for (const template of inputTemplates) {+ const instance = node.data.inputs[template.name];+ const label = instance?.label || template.title;++ // A ratio order problem stands in for the ratios' own checks, as it always has on these rows.+ if (ratioIssue && isHiDiffusionRatioField(template.name)) {+ if (template.name === HIDIFFUSION_RATIO_REPORTED_FIELD) {+ (issues ??= []).push({+ issue: { kind: 'invalidValue', reason: ratioIssue },+ label,+ markedFieldNames: HIDIFFUSION_RATIO_FIELDS,+ template,+ });+ }+ continue;+ }++ const issue = getWorkflowFieldIssue({+ isConnected: connectedFieldNames.has(template.name),+ template,+ value: instance?.value,+ });++ if (issue) {+ (issues ??= []).push({ issue, label, markedFieldNames: [template.name], template });+ }}- return translate('nodes.childWorkflowError', { error });+ return issues ?? EMPTY_FIELD_ISSUES;+};++const invalidByFlowData = new WeakMap<InvocationFlowNodeType['data'], boolean>();++/**+ * Whether a node's fields or type keep it from running, as its chrome shows it. Cached per flow-node data, which the+ * flow model rebuilds only when the node's document, template or connections change, so the minimap can ask on every+ * render.+ */+export const isInvocationFlowNodeInvalid = (data: InvocationFlowNodeType['data']): boolean => {+ const cached = invalidByFlowData.get(data);++ if (cached !== undefined) {+ return cached;+ }++ const invalid = data.template+ ? getInvocationNodeFieldIssues(+ data.documentNode,+ data.template.inputTemplates,+ new Set(data.connectedTargetHandles)+ ).length > 0+ : data.templateStatus === 'loaded';+ invalidByFlowData.set(data, invalid);++ return invalid;+};++/**+ * One place turns what is known about a node into its chrome and its status button. The chrome facts stay+ * independent so they compose; the status button shows the one that most needs attention: a live run, then a failed+ * one, then what blocks the next run, then a version change, then a completed run.+ */+export const getInvocationNodeState = ({+ execution,+ hasFieldIssues,+ isMissingTemplate = false,+ updateStatus,+}: {+ execution: NodeExecutionState | null;+ hasFieldIssues: boolean;+ isMissingTemplate?: boolean;+ /** Null for a node without a template. */+ updateStatus: WorkflowNodeUpdateStatus | null;+}): { chrome: Omit<WorkflowNodeChromeState, 'selected'>; status: WorkflowNodeStatus | null } => {+ const executionStatus = execution?.status ?? null;+ const isOutdated = updateStatus !== null && updateStatus !== 'current';++ return {+ chrome: {+ failed: executionStatus === 'failed',+ invalid: hasFieldIssues || isMissingTemplate,+ outdated: isOutdated,+ running: executionStatus === 'running',+ },+ status:+ executionStatus === 'running' || executionStatus === 'failed'+ ? executionStatus+ : hasFieldIssues+ ? 'invalid'+ : updateStatus === 'updatable'+ ? 'updatable'+ : isOutdated+ ? 'versionMismatch'+ : executionStatus,+ };};const NodeShell = ({- hasMissingRequiredInput,+ chrome,children,- isMissing,- isOutdated,- isRunning,- outcome,selected,}: {- hasMissingRequiredInput?: boolean;+ chrome?: Omit<WorkflowNodeChromeState, 'selected'>;children: React.ReactNode;- isMissing?: boolean;- isOutdated?: boolean;- isRunning?: boolean;- outcome?: WorkflowNodeOutcome | null;selected: boolean;-}) => {- const isInvalid = isMissing || hasMissingRequiredInput;+}) => (+ <Box+ data-is-selected={selected}+ data-workflow-node-shell="true"+ position="relative"+ w={NODE_WIDTH}+ {...getWorkflowNodeShellProps({ ...chrome, selected })}+ >+ {children}+ </Box>+);- return (- <Box- data-is-selected={selected}- data-workflow-node-shell="true"- w={NODE_WIDTH}- {...getWorkflowNodeShellProps({- invalid: isInvalid,- outcome,- outdated: isOutdated,- running: isRunning,- selected,- })}- >- {children}- </Box>- );-};+// The panel bodies load on first open; hovering or focusing a header button starts the load, so the panel is usually+// ready by the time its tooltip opens. Tooltips mount their content per open, so a failed load is tried again on the+// next one; while loading, and if it fails, a panel shows its button's own label, so the state stays readable.+const nodePanels = createDeferredModule(() => import('./NodePanels'));+const preloadNodePanels = nodePanels.preload;++const DeferredNodePanel = ({+ label,+ render,+}: {+ label: string;+ render: (module: typeof NodePanelsModule) => ReactNode;+}) => <nodePanels.Deferred fallback={<Text>{label}</Text>} render={render} />;-/** The header's completed/failed mark, named for screen readers and tooltipped with the failure. */-const NodeOutcomeIcon = ({+/** The header's one status slot, hidden while there is nothing to report. */+const NodeStatusButton = ({execution,+ isPlain = false,+ issues,node,+ status,+ template,}: {execution: NodeExecutionState | null;+ /** A plain mark with no panel, for compact nodes; selecting the node opens it with its full header. */+ isPlain?: boolean;+ issues: readonly InvocationNodeFieldIssue[];node: WorkflowInvocationNode;+ status: WorkflowNodeStatus | null;+ template: InvocationNodeTemplateView['template'];}) => {const { t } = useTranslation();- const outcome = getExecutionOutcome(execution);- if (!outcome) {+ if (status === null) {return null;}- return (- <WorkflowNodeOutcomeIcon- error={getNodeExecutionError(node, execution?.error, t)}- label={outcome === 'completed' ? t('nodes.executionCompleted') : t('nodes.executionFailed')}- outcome={outcome}- />- );-};--/** Thin progress strip under the header while the node's invocation executes. */-const NodeProgressStrip = ({ execution }: { execution: NodeExecutionState | null }) => {- const isWorkflowImageExport = useIsWorkflowImageExport();+ const updateText = getUpdateStatusText(t, node, template);+ const summary =+ status === 'invalid'+ ? issues.length === 1+ ? getFieldIssueMessage(t, issues[0]!)+ : t('nodes.status.issueCount', { count: issues.length })+ : status === 'updatable' || status === 'versionMismatch'+ ? updateText+ : getExecutionStatusText(t, execution!);- if (isWorkflowImageExport || execution?.status !== 'running') {- return null;- }+ const label = t('nodes.status.label', { status: summary });return (- <Box bg="bg.muted" data-node-progress-strip="true" h="2px" overflow="hidden" position="relative" w="full">- <Box- bg="brand.solid"- h="full"- transition="width var(--wb-motion-duration-slow) ease"- w={execution.progress === null ? 'full' : `${Math.round(execution.progress * 100)}%`}- {...(execution.progress === null- ? {- animationDuration: 'var(--wb-motion-duration-slow)',- animationIterationCount: 'var(--wb-motion-animation-iteration-count)',- animationName: 'pulse',- }- : {})}- />- </Box>+ <WorkflowNodeStatusButton+ content={+ isPlain ? null : (+ <DeferredNodePanel+ label={label}+ render={(module) => (+ <module.NodeStatusPanel execution={execution} issues={issues} node={node} updateText={updateText} />+ )}+ />+ )+ }+ label={label}+ onPreload={preloadNodePanels}+ progress={execution?.status === 'running' ? execution.progress : null}+ status={status}+ />);};+/** The editor a label double-click opens: Enter or blur commits, Escape keeps the current name. */+/**+ * The rename input a double-click opens, for node titles and field labels alike. It lies over its label on the same+ * line, a little wider and taller than it, in the label's own text size and on its own surface (so a tinted header+ * does not tint it). The label keeps its place underneath, so nothing around it moves when the input opens or closes.+ */+const INLINE_RENAME_FIELD_PROPS = {+ left: '-6px',+ minW: '10rem',+ position: 'absolute',+ top: '50%',+ transform: 'translateY(-50%)',+ w: 'calc(100% + 12px)',+ zIndex: 1,+} as const;+const INLINE_RENAME_INPUT_PROPS = { bg: 'bg', color: 'fg', fontWeight: '400', px: '1.5' } as const;++const INLINE_RENAME_HIDDEN_LABEL_CSS = { '& > :first-child': { visibility: 'hidden' } } as const;++/** Holds a label and, while it is being renamed, the input over it. */+const InlineRename = ({ children, editor }: { children: ReactNode; editor: ReactNode }) => (+ <Box+ alignItems="center"+ display="flex"+ minW="0"+ position="relative"+ css={editor ? INLINE_RENAME_HIDDEN_LABEL_CSS : undefined}+ >+ {children}+ {editor}+ </Box>+);+/** The editor a label double-click opens: Enter or blur commits, Escape keeps the current name. */const InlineLabelInput = ({ariaLabel,@@ -219,7 +376,8 @@ const InlineLabelInput = ({onEnd,}: {ariaLabel: string;- fontSize?: 'xs';+ /** The text size of the label it replaces: the header's `md` for a node title, `sm` for a field label. */+ fontSize: 'md' | 'sm';initialValue: string;onCommit: (value: string) => void;onEnd: () => void;@@ -229,14 +387,13 @@ const InlineLabelInput = ({// Its own field: inside a value row it would otherwise take that control's id and invalid state.return (- <Field.Root flex="1" minW="0">+ <Field.Root {...INLINE_RENAME_FIELD_PROPS}><InputautoFocusaria-label={ariaLabel}className="nodrag"- flex="1"+ {...INLINE_RENAME_INPUT_PROPS}fontSize={fontSize}- minW="0"value={draft}onBlur={() => {if (!isCancelled.current && draft.trim() !== initialValue) {@@ -285,38 +442,41 @@ const NodeTitle = ({if (isWorkflowImageExport) {return (<MiddleTruncate+ {...WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS}data-workflow-export-node-title="true"data-workflow-export-static-node-content="true"- fontSize="lg"- fontWeight="700"+ fontWeight="600"minW="0"text={title}/>);}- if (isEditing) {- return (- <InlineLabelInput- ariaLabel={t('nodes.nodeLabel')}- // Start from the displayed title, including the template fallback for unset labels.- initialValue={title}- onCommit={(label) => editGraph({ label, nodeId: node.id, type: 'setNodeLabel' })}- onEnd={() => setIsEditing(false)}- />- );- }-return (- <MiddleTruncate- fontSize="lg"- fontWeight="700"- minW="0"- text={title}- // Keeps the full title MiddleTruncate would show, for a title cut short.- title={t('nodes.nodeTitleHint', { title })}- onDoubleClick={() => setIsEditing(true)}- />+ <InlineRename+ editor={+ isEditing ? (+ <InlineLabelInput+ ariaLabel={t('nodes.nodeLabel')}+ fontSize="md"+ // Start from the displayed title, including the template fallback for unset labels.+ initialValue={title}+ onCommit={(label) => editGraph({ label, nodeId: node.id, type: 'setNodeLabel' })}+ onEnd={() => setIsEditing(false)}+ />+ ) : null+ }+ >+ <MiddleTruncate+ {...WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS}+ fontWeight="600"+ minW="0"+ text={title}+ // Keeps the full title MiddleTruncate would show, for a title cut short.+ title={t('nodes.nodeTitleHint', { title })}+ onDoubleClick={() => setIsEditing(true)}+ />+ </InlineRename>);};@@ -324,12 +484,14 @@ const InputFieldTooltip = ({description,isConnected,isExposed,+ issue,label,template,}: {description: string;isConnected: boolean;isExposed: boolean;+ issue: InvocationNodeFieldIssue | null;label: string;template: FieldInputTemplate;}) => {@@ -337,13 +499,14 @@ const InputFieldTooltip = ({return (<Stack gap="0.5" maxW="18rem">- <Text fontWeight="700">{label}</Text>+ <Text fontWeight="600">{label}</Text><Text color="fg.subtle">{t('nodes.fieldInfo', { name: template.name, type: getFieldTypeLabel(template.type) })} ·{' '}{t(template.required ? 'nodes.required' : 'nodes.optional')} · {t(`nodes.inputModes.${template.input}`)}{isConnected ? ` · ${t('nodes.providedByConnection')}` : null}- {isExposed ? ` · ${t('nodes.pinnedToForm')}` : null}+ {isExposed ? ` · ${t('nodes.inForm')}` : null}</Text>+ {issue ? <Text color="fg.error">{getFieldIssueMessage(t, issue)}</Text> : null}{description ? <Text>{description}</Text> : null}<Text color="fg.subtle">{t('nodes.renameFieldHint')}</Text></Stack>@@ -388,8 +551,6 @@ const getUpdateStatusText = (: t('nodes.nodeVersionIncompatible', versions);};-const UPDATE_TOOLTIP_POSITIONING = { placement: 'top-end' } as const;-/** Legacy's group tints, so a zipped group reads as one colour across the canvas. */const BATCH_GROUP_COLORS: Record<string, string> = {'Group 1': 'green.fg',@@ -410,62 +571,52 @@ const BatchGroupSuffix = ({ node }: { node: WorkflowInvocationNode }) => {const groupId = getWorkflowBatchGroupId(node);return (- <Text color={BATCH_GROUP_COLORS[groupId] ?? 'fg.subtle'} flexShrink={0} fontSize="xs" fontWeight="600">+ <Text+ color={BATCH_GROUP_COLORS[groupId] ?? 'fg.subtle'}+ css={WORKFLOW_NODE_LABEL_TEXT_CSS}+ flexShrink={0}+ fontSize="xs"+ fontWeight="600"+ >({groupId === 'None' ? t('nodes.noBatchGroup') : groupId})</Text>);};-/** Header mark for a node whose version is not its template's; the tooltip says what can be done about it. */-const NodeUpdateIcon = ({- node,- template,-}: {- node: WorkflowInvocationNode;- template: InvocationNodeTemplateView['template'];-}) => {+const CLASSIFICATION_GLYPHS: Record<string, { color: string; icon: LucideIcon }> = {+ beta: { color: 'yellow.fg', icon: HammerIcon },+ internal: { color: 'purple.fg', icon: CpuIcon },+ prototype: { color: 'red.fg', icon: FlaskConicalIcon },+ special: { color: 'green.fg', icon: ZapIcon },+};++const CLASSIFICATION_TOOLTIP_POSITIONING = { placement: 'top-start' } as const;++/** Legacy's mark left of the title for a node that is not stable, explained on hover. */+const NodeClassificationIcon = ({ classification, isPlain = false }: { classification: string; isPlain?: boolean }) => {const { t } = useTranslation();- const label = getUpdateStatusText(t, node, template);+ const glyph = CLASSIFICATION_GLYPHS[classification];- if (label === null) {+ if (!glyph) {return null;}- return (- <Tooltip content={label} positioning={UPDATE_TOOLTIP_POSITIONING} showArrow>- <Icon aria-label={label} as={TriangleAlertIcon} boxSize="3.5" color="fg.warning" flexShrink={0} role="img" />- </Tooltip>- );-};+ const description = t(`nodes.classificationDescriptions.${classification}`);-const NodeInfoTooltipContent = ({- node,- template,-}: {- node: WorkflowInvocationNode;- template: InvocationNodeTemplateView['template'];-}) => {- const { t } = useTranslation();- const title = node.data.label ? `${node.data.label} (${template.title})` : template.title;- const nodePack = node.data.nodePack || template.nodePack;- const updateStatusText = getUpdateStatusText(t, node, template);+ const icon = (+ <Icon aria-label={description} as={glyph.icon} boxSize="3.5" color={glyph.color} flexShrink={0} role="img" />+ );- return (- <Stack gap="1" maxW="20rem">- <Text fontWeight="700">{title}</Text>- <Text color="fg.subtle">{t('nodes.nodeType', { type: template.type })}</Text>- <Text color="fg.subtle">{t('nodes.nodePackLabel', { name: nodePack })}</Text>- <Text color="fg.subtle">{t('nodes.nodeVersion', { version: node.data.version })}</Text>- {updateStatusText ? <Text color="fg.warning">{updateStatusText}</Text> : null}- <Text color="fg.subtle">{t('nodes.nodeClassification', { classification: template.classification })}</Text>- <Text color="fg.subtle">{t('nodes.nodeCategory', { category: template.category })}</Text>- {template.description ? <Text fontStyle="italic">{template.description}</Text> : null}- {node.data.notes ? <Text>{node.data.notes}</Text> : null}- </Stack>+ return isPlain ? (+ icon+ ) : (+ <Tooltip content={description} positioning={CLASSIFICATION_TOOLTIP_POSITIONING} showArrow>+ {icon}+ </Tooltip>);};-const NodeInfoIcon = ({+const NodeInfoButton = ({node,template,}: {@@ -473,11 +624,18 @@ const NodeInfoIcon = ({template: InvocationNodeTemplateView['template'];}) => {const { t } = useTranslation();+ const label = t('nodes.showNodeDetails', { title: node.data.label || template.title });return (- <WorkflowNodeInfoIcon- content={<NodeInfoTooltipContent node={node} template={template} />}- label={t('nodes.showNodeDetails', { title: node.data.label || template.title })}+ <WorkflowNodeInfoButton+ content={+ <DeferredNodePanel+ label={label}+ render={(module) => <module.NodeInfoPanel node={node} template={template} />}+ />+ }+ label={label}+ onPreload={preloadNodePanels}/>);};@@ -543,17 +701,123 @@ const ProvidedByConnectionNote = () => {);};+/**+ * A node's value controls sit in a well of the canvas colour, a step darker than the node body, so a value reads as+ * the thing to edit. The colour is defined once, as `--wb-control-well` on the row, which also carries+ * `data-control-well`, and every surface that paints a control's background reads it: the value surfaces below (text+ * and number inputs, text areas, select, combobox and listbox pickers such as the model picker, not switches, plain+ * buttons or media drop zones), the text area's faded bottom (`ResizableTextarea`) and the export snapshot's value+ * box. Borders, including the error border, are untouched.+ * Scoped to the node's rows, so the form view and the form builder's cards keep their own surfaces.+ */+const NODE_FIELD_WELL_VARIABLE = { '--wb-control-well': '{colors.bg}' } as const;+const NODE_FIELD_WELL_CSS = {+ '& :is(input:not([type="checkbox"], [type="radio"], [type="range"], [type="file"]), textarea, [data-scope="select"][data-part="trigger"], [data-scope="combobox"][data-part="control"], button[aria-haspopup="listbox"])':+ { bg: 'var(--wb-control-well)' },+} as const;++/** Row actions stay in the tab order; CSS shows them while the row is hovered, holds focus, or has a popover open. */+const INPUT_ROW_CSS = {+ ...NODE_FIELD_WELL_VARIABLE,+ '& [data-node-field-actions]': {+ opacity: 0,+ transition: 'opacity var(--wb-motion-duration-fast) ease',+ },+ '&:hover [data-node-field-actions], &:focus-within [data-node-field-actions], & [data-node-field-actions]:has([data-state="open"])':+ { opacity: 1 },+} as const;++/** Legacy's row actions, in its order: description, reset, add to or remove from the form. */+const InputFieldActions = ({+ fieldName,+ isExposed,+ label,+ node,+ showsControl,+ template,+}: {+ fieldName: string;+ isExposed: boolean;+ label: string;+ node: WorkflowInvocationNode;+ showsControl: boolean;+ template: FieldInputTemplate;+}) => {+ const { t } = useTranslation();+ const { editGraph } = useProjectGraphCommands();+ const instance = node.data.inputs[fieldName];+ const formLabel = isExposed ? t('nodes.removeFieldFromForm', { label }) : t('nodes.addFieldToForm', { label });+ const isDefault = showsControl && isWorkflowFieldValueDefault(template, instance?.value);++ return (+ <HStack data-node-field-actions="true" flexShrink={0} gap="0" ml="auto">+ <FieldDescriptionPopover+ description={instance?.description}+ fieldName={fieldName}+ nodeId={node.id}+ size="xs"+ templateDescription={template.description}+ />+ {showsControl ? (+ // As legacy: present but disabled at the default. A disabled button shows no tooltip, so none is mounted.+ <Tooltip content={t('nodes.resetToDefault')} disabled={isDefault}>+ <IconButton+ aria-label={t('nodes.resetFieldToDefault', { label })}+ className="nodrag"+ color="fg.subtle"+ disabled={isDefault}+ size="xs"+ variant="ghost"+ onClick={() =>+ editGraph({+ fieldName,+ nodeId: node.id,+ type: 'setFieldValue',+ value: cloneWorkflowFieldDefault(template),+ })+ }+ >+ <Icon as={RotateCcwIcon} boxSize="3" />+ </IconButton>+ </Tooltip>+ ) : null}+ {showsControl && isExposableField(template) ? (+ <Tooltip content={formLabel}>+ <IconButton+ aria-label={formLabel}+ className="nodrag"+ color="fg.subtle"+ size="xs"+ variant="ghost"+ onClick={() =>+ editGraph({+ fieldIdentifier: { fieldName, nodeId: node.id },+ type: isExposed ? 'unexposeField' : 'exposeField',+ })+ }+ >+ <Icon as={isExposed ? MinusIcon : PlusIcon} boxSize="3" />+ </IconButton>+ </Tooltip>+ ) : null}+ </HStack>+ );+};+const InputFieldRow = ({connectedFieldNames,isConnected,isExposed,isSkeleton,+ issue,node,template,}: {connectedFieldNames: ReadonlySet<string>;isConnected: boolean;isExposed: boolean;+ /** The field's entry in the node's issue list, null when it is fine. */+ issue: InvocationNodeFieldIssue | null;isSkeleton: boolean;node: WorkflowInvocationNode;template: FieldInputTemplate;@@ -562,53 +826,54 @@ const InputFieldRow = ({const { t } = useTranslation();const { editGraph } = useProjectGraphCommands();const instance = node.data.inputs[template.name];- const fieldIdentifier = { fieldName: template.name, nodeId: node.id };const showsControl = !isConnected && isDirectInputField(template);const label = instance?.label || template.title;const description = getEffectiveWorkflowFieldDescription(instance, template);const ratiosDisabled =isHiDiffusionNode(node.data.type) && isHiDiffusionRatioField(template.name) && areHiDiffusionRatiosAutomatic(node);- const invalidReason =- (isHiDiffusionRatioField(template.name) ? getHiDiffusionRatioOrderIssue(node, connectedFieldNames) : null) ??- getWorkflowFieldInvalidReason({- isConnected,- template,- value: instance?.value,- });- const isInvalid = invalidReason !== null;+ const isInvalid = issue !== null;const showInvalid = isInvalid && !isWorkflowImageExport;+ const showsInForm = isExposed && !isWorkflowImageExport;const handleTooltip = getHandleTypeTooltip(template.type, t('nodes.any'), t);- const canReset = !isWorkflowImageExport && showsControl && !isWorkflowFieldValueDefault(template, instance?.value);const [isEditingLabel, setIsEditingLabel] = useState(false);+ // Legacy's label: semibold where the row holds a value, muted where a connection feeds it; red when the field+ // blocks a run, blue with a link mark when the field is in the form.const fieldTitle = (<Text- color={showInvalid ? 'fg.error' : isConnected ? 'fg.muted' : 'fg'}+ alignItems="center"+ color={showInvalid ? 'fg.error' : showsInForm ? 'accent.fg' : showsControl ? 'fg' : 'fg.muted'}data-node-input-field-title="true"- fontSize="xs"- lineHeight="shorter"+ display="flex"+ fontSize="sm"+ fontWeight={showsControl ? '600' : '400'}+ gap="1"+ h={WORKFLOW_NODE_DENSITY.labelLine}+ lineHeight={WORKFLOW_NODE_DENSITY.labelLine}minW="0"- truncateonDoubleClick={isWorkflowImageExport ? undefined : () => setIsEditingLabel(true)}>- {label}- {template.required ? (- <Text as="span" color="fg.error">- {' *'}- </Text>- ) : null}+ <Text as="span" css={WORKFLOW_NODE_LABEL_TEXT_CSS}>+ {label}+ {template.required ? (+ <Text as="span" color="fg.error">+ {' *'}+ </Text>+ ) : null}+ </Text>+ {showsInForm ? <Icon aria-label={t('nodes.inForm')} as={LinkIcon} boxSize="3" flexShrink={0} role="img" /> : null}</Text>);if (isSkeleton) {return (<Box px={WORKFLOW_NODE_DENSITY.rowPaddingX} py={WORKFLOW_NODE_DENSITY.rowPaddingY}>- <HStack gap="1.5" h="5" position="relative">+ <HStack gap="1.5" h={WORKFLOW_NODE_DENSITY.labelLine} position="relative">{template.input !== 'direct' ? (<Tooltip content={handleTooltip} showArrow><Handleid={template.name}position={Position.Left}- style={{ ...getWorkflowNodeHandleStyle(template.type, 'left'), left: -ROW_PADDING_X, top: '50%' }}+ style={{ ...getWorkflowNodeHandleStyle(template.type, 'left'), left: -ROW_PADDING_X, top: PORT_TOP }}type="target"/></Tooltip>@@ -622,6 +887,9 @@ const InputFieldRow = ({return (<Box+ css={INPUT_ROW_CSS}+ {...{ [WORKFLOW_NODE_FIELD_ROW_ATTRIBUTE]: '' }}+ data-control-well=""data-workflow-export-field-content={isWorkflowImageExport ? 'true' : undefined}px={WORKFLOW_NODE_DENSITY.rowPaddingX}py={WORKFLOW_NODE_DENSITY.rowPaddingY}@@ -630,98 +898,76 @@ const InputFieldRow = ({<Field.Root gap="0" invalid={isInvalid && !isWorkflowImageExport} minW="0" w="full">{/* The handle lives inside the label row so it stays centered on thelabel even when the value control below grows the row. */}- <HStack gap="1.5" h="5" justify="space-between" minW="0" position="relative" w="full">+ <HStack+ gap="1.5"+ h={WORKFLOW_NODE_DENSITY.labelLine}+ justify="space-between"+ minW="0"+ position="relative"+ w="full"+ >{template.input !== 'direct' ? (<Tooltip content={handleTooltip} positioning={{ placement: 'right-end' }} showArrow><Handleid={template.name}position={Position.Left}- style={{ ...getWorkflowNodeHandleStyle(template.type, 'left'), left: -ROW_PADDING_X, top: '50%' }}+ style={{ ...getWorkflowNodeHandleStyle(template.type, 'left'), left: -ROW_PADDING_X, top: PORT_TOP }}type="target"/></Tooltip>) : null}{isWorkflowImageExport ? (fieldTitle- ) : isEditingLabel ? (- <InlineLabelInput- ariaLabel={t('nodes.fieldLabel')}- fontSize="xs"- initialValue={label}- // The template title is the unset label, so renaming back to it follows template changes again.- onCommit={(next) =>- editGraph({- fieldName: template.name,- label: next === template.title ? '' : next,- nodeId: node.id,- type: 'setFieldLabel',- })- }- onEnd={() => setIsEditingLabel(false)}- />) : (- <Tooltip- positioning={{ placement: 'top-start' }}- content={- <InputFieldTooltip- description={description}- isConnected={isConnected}- isExposed={isExposed}- label={label}- template={template}- />+ <InlineRename+ editor={+ isEditingLabel ? (+ <InlineLabelInput+ ariaLabel={t('nodes.fieldLabel')}+ fontSize="sm"+ initialValue={label}+ // The template title is the unset label, so renaming back to it follows template changes again.+ onCommit={(next) =>+ editGraph({+ fieldName: template.name,+ label: next === template.title ? '' : next,+ nodeId: node.id,+ type: 'setFieldLabel',+ })+ }+ onEnd={() => setIsEditingLabel(false)}+ />+ ) : null}>- {fieldTitle}- </Tooltip>- )}- <HStack flexShrink={0} gap="0" ml="auto">- {canReset ? (- <Tooltip content={t('nodes.resetToDefault')}>- <IconButton- aria-label={t('nodes.resetFieldToDefault', { label })}- className="nodrag"- color="fg.subtle"- size="sm"- variant="ghost"- onClick={() =>- editGraph({- fieldName: template.name,- nodeId: node.id,- type: 'setFieldValue',- value: cloneWorkflowFieldDefault(template),- })- }- >- <Icon as={RotateCcwIcon} boxSize="3" />- </IconButton>- </Tooltip>- ) : null}- {!isWorkflowImageExport ? (- <FieldDescriptionPopover- description={instance?.description}- fieldName={template.name}- nodeId={node.id}- templateDescription={template.description}- />- ) : null}- {!isWorkflowImageExport && isExposableField(template) ? (- <Tooltip content={isExposed ? t('nodes.removeFromForm') : t('nodes.addToForm')}>- <IconButton- aria-label={- isExposed ? t('nodes.removeFieldFromForm', { label }) : t('nodes.addFieldToForm', { label })- }- className="nodrag"- color={isExposed ? 'accent.solid' : 'fg.subtle'}- size="sm"- variant="ghost"- onClick={() => editGraph({ fieldIdentifier, type: isExposed ? 'unexposeField' : 'exposeField' })}- >- <Icon as={isExposed ? PinOffIcon : PinIcon} boxSize="3" />- </IconButton>+ <Tooltip+ disabled={isEditingLabel}+ positioning={{ placement: 'top-start' }}+ content={+ <InputFieldTooltip+ description={description}+ isConnected={isConnected}+ isExposed={isExposed}+ issue={issue}+ label={label}+ template={template}+ />+ }+ >+ {fieldTitle}</Tooltip>- ) : null}- </HStack>+ </InlineRename>+ )}+ {!isWorkflowImageExport ? (+ <InputFieldActions+ fieldName={template.name}+ isExposed={isExposed}+ label={label}+ node={node}+ showsControl={showsControl}+ template={template}+ />+ ) : null}</HStack>{showsControl ? (isWorkflowImageExport ? (@@ -731,7 +977,7 @@ const InputFieldRow = ({value={instance?.value}/>) : (- <Box mt="0.5" w="full">+ <Box css={NODE_FIELD_WELL_CSS} mt="0.5" w="full" {...{ [WORKFLOW_NODE_FIELD_CONTROL_ATTRIBUTE]: '' }}><WorkflowFieldInputdisabled={ratiosDisabled}id={`${node.id}-${template.name}-value`}@@ -756,9 +1002,8 @@ const InputFieldRow = ({) : !isWorkflowImageExport && isConnected && isSeedInputField(template) ? (<ProvidedByConnectionNote />) : null}- {invalidReason && !isWorkflowImageExport ? (- <Field.ErrorText fontSize="xs">{invalidReason}</Field.ErrorText>- ) : null}+ {/* The reason is read with the control; on screen it lives in the status panel and the label's hover. */}+ {showInvalid && issue ? <Field.ErrorText srOnly>{getFieldIssueMessage(t, issue)}</Field.ErrorText> : null}</Field.Root></Box>);@@ -783,16 +1028,16 @@ const OutputFieldRow = ({<Box px={WORKFLOW_NODE_DENSITY.rowPaddingX} py={WORKFLOW_NODE_DENSITY.rowPaddingY}><Flexalign="center"- h={isWorkflowImageExport ? 'auto' : '5'}+ h={isWorkflowImageExport ? 'auto' : WORKFLOW_NODE_DENSITY.labelLine}justify="flex-end"- minH={isWorkflowImageExport ? '5' : undefined}+ minH={isWorkflowImageExport ? WORKFLOW_NODE_DENSITY.labelLine : undefined}position="relative"><Tooltip content={handleTooltip} positioning={{ placement: 'left-start' }} showArrow><Handleid={template.name}position={Position.Right}- style={{ ...getWorkflowNodeHandleStyle(template.type, 'right'), right: -ROW_PADDING_X, top: '50%' }}+ style={{ ...getWorkflowNodeHandleStyle(template.type, 'right'), right: -ROW_PADDING_X, top: PORT_TOP }}type="source"/></Tooltip>@@ -801,12 +1046,13 @@ const OutputFieldRow = ({<SkeletonBar w="40%" /></Flex>) : isWorkflowImageExport ? (- <Box flexShrink={0} maxW="full" textAlign="end">+ <Box alignSelf="flex-start" flexShrink={0} maxW="full" textAlign="end"><Textcolor="fg.muted"+ css={EXPORT_OUTPUT_TITLE_CSS}data-workflow-export-output-title="true"fontSize="xs"- lineHeight="shorter"+ lineHeight={WORKFLOW_NODE_DENSITY.labelLine}maxW="full"overflowWrap="anywhere"textAlign="end"@@ -821,12 +1067,10 @@ const OutputFieldRow = ({<Tooltip content={value.full} positioning={{ placement: 'top-end' }}><Textcolor="fg.subtle"+ css={WORKFLOW_NODE_LABEL_TEXT_CSS}fontSize="xs"- lineHeight="shorter"+ lineHeight={WORKFLOW_NODE_DENSITY.labelLine}minW="0"- overflow="hidden"- textOverflow="ellipsis"- whiteSpace="nowrap">{value.short}</Text>@@ -837,9 +1081,11 @@ const OutputFieldRow = ({<MiddleTruncateas="span"color="fg.muted"+ {...WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS}+ data-node-output-field-title="true"fontSize="xs"justifyContent="flex-end"- lineHeight="shorter"+ lineHeight={WORKFLOW_NODE_DENSITY.labelLine}maxW="full"text={template.title}/>@@ -896,6 +1142,87 @@ const HiddenHandles = ({</Box>);+const MERGED_PORT_SIZE = 14;+/**+ * A field handle behind a merged port: present so its edges attach there, but neither seen nor connectable. It takes+ * the port's size, so an edge leaves the port's outer side as it leaves an open node's dot.+ */+const COLLAPSED_FIELD_HANDLE_STYLE = {+ height: MERGED_PORT_SIZE,+ minHeight: 0,+ minWidth: 0,+ visibility: 'hidden',+ width: MERGED_PORT_SIZE,+} as const;++/** Legacy's merged port: one per side of a collapsed node, a rounded square in the neutral port colour. */+const MergedPort = ({ side }: { side: 'left' | 'right' }) => (+ <Box+ aria-hidden+ bg="border.emphasized"+ boxShadow="0 0 0 1.5px var(--xy-background-color, {colors.bg})"+ boxSize={`${MERGED_PORT_SIZE}px`}+ data-collapsed-port={side}+ pointerEvents="none"+ position="absolute"+ rounded="3px"+ top="50%"+ transform={side === 'left' ? 'translate(-50%, -50%)' : 'translate(50%, -50%)'}+ {...(side === 'left' ? { left: '0' } : { right: '0' })}+ />+);++/**+ * A collapsed node shows one merged port per side, as legacy did. Every field keeps its handle, hidden at that port,+ * so the document's edges stay as they are and draw from it; expanding draws them from their own rows again. The+ * hidden handles cannot connect: a new connection needs the node open, as in legacy.+ */+const CollapsedPorts = ({+ connected,+ inputTemplates,+ outputTemplates,+}: {+ /** In a large graph's compact mode, only the handles with edges mount, as `CompactHiddenHandles` does. */+ connected?: { sources: readonly string[]; targets: readonly string[] };+ inputTemplates: FieldInputTemplate[];+ outputTemplates: FieldOutputTemplate[];+}) => {+ const targetTemplates = inputTemplates.filter((inputTemplate) => inputTemplate.input !== 'direct');+ const targetHandles = connected+ ? targetTemplates.filter((inputTemplate) => connected.targets.includes(inputTemplate.name))+ : targetTemplates;+ const sourceHandles = connected+ ? outputTemplates.filter((outputTemplate) => connected.sources.includes(outputTemplate.name))+ : outputTemplates;++ return (+ <>+ {targetTemplates.length > 0 ? <MergedPort side="left" /> : null}+ {targetHandles.map((inputTemplate) => (+ <Handle+ key={inputTemplate.name}+ id={inputTemplate.name}+ isConnectable={false}+ position={Position.Left}+ style={COLLAPSED_FIELD_HANDLE_STYLE}+ type="target"+ />+ ))}+ {outputTemplates.length > 0 ? <MergedPort side="right" /> : null}+ {sourceHandles.map((outputTemplate) => (+ <Handle+ key={outputTemplate.name}+ id={outputTemplate.name}+ isConnectable={false}+ position={Position.Right}+ style={COLLAPSED_FIELD_HANDLE_STYLE}+ type="source"+ />+ ))}+ </>+ );+};+const CompactHiddenHandles = ({connectedSourceHandles,connectedTargetHandles,@@ -980,36 +1307,66 @@ const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeTconst inputTemplates = templateView?.inputTemplates ?? [];const outputTemplates = templateView?.outputTemplates ?? [];const title = node.data.label || templateView?.template.title || node.data.type;- const isOutdated = templateView ? getNodeUpdateStatus(node, templateView.template) !== 'current' : false;-+ const fieldIssues = templateView+ ? getInvocationNodeFieldIssues(node, inputTemplates, new Set(data.connectedTargetHandles))+ : EMPTY_FIELD_ISSUES;+ const { chrome, status } = getInvocationNodeState({+ execution,+ hasFieldIssues: fieldIssues.length > 0,+ isMissingTemplate: !templateView && data.templateStatus === 'loaded',+ updateStatus: templateView ? getNodeUpdateStatus(node, templateView.template) : null,+ });+ const { tone } = getWorkflowNodeAppearance({ ...chrome, selected: false });+ const isCollapsed = templateView !== null && !node.data.isOpen;++ // Compact nodes stay cheap in a large graph: the status is a plain mark named for what it means, with no tooltip.return (- <NodeShell- isMissing={!templateView && data.templateStatus === 'loaded'}- isOutdated={isOutdated}- isRunning={execution?.status === 'running'}- outcome={getExecutionOutcome(execution)}- selected={selected ?? false}- >- <Flex {...getWorkflowNodeHeaderProps()}>- <MiddleTruncate fontSize="lg" fontWeight="700" minW="0" text={title} />+ <NodeShell chrome={chrome} selected={selected ?? false}>+ <Flex+ {...getWorkflowNodeHeaderProps({+ endsWithButton: templateView !== null && status !== null,+ roundedBottom: isCollapsed,+ tone,+ })}+ >+ {templateView ? <NodeClassificationIcon classification={templateView.template.classification} isPlain /> : null}+ <MiddleTruncate {...WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS} fontWeight="600" minW="0" text={title} /><BatchGroupSuffix node={node} /><Box flex="1" />- <NodeOutcomeIcon execution={execution} node={node} />- {templateView && isOutdated ? <NodeUpdateIcon node={node} template={templateView.template} /> : null}+ {templateView ? (+ <NodeStatusButton+ execution={execution}+ isPlain+ issues={fieldIssues}+ node={node}+ status={status}+ template={templateView.template}+ />+ ) : null}</Flex>- {templateView ? (- <CompactNodeBody inputCount={inputTemplates.length} outputCount={outputTemplates.length} />+ {isCollapsed ? (+ <CollapsedPorts+ connected={{ sources: data.connectedSourceHandles, targets: data.connectedTargetHandles }}+ inputTemplates={inputTemplates}+ outputTemplates={outputTemplates}+ />) : (- <Text color="fg.subtle" fontSize="xs" px="3" {...getWorkflowNodeBodyProps()} py="2">- {getTemplatelessNodeMessage(t, data, true)}- </Text>+ <>+ {templateView ? (+ <CompactNodeBody inputCount={inputTemplates.length} outputCount={outputTemplates.length} />+ ) : (+ <Text color="fg.subtle" fontSize="xs" px="3" {...getWorkflowNodeBodyProps()} py="2">+ {getTemplatelessNodeMessage(t, data, true)}+ </Text>+ )}+ <CompactHiddenHandles+ connectedSourceHandles={data.connectedSourceHandles}+ connectedTargetHandles={data.connectedTargetHandles}+ inputTemplates={inputTemplates}+ outputTemplates={outputTemplates}+ />+ </>)}- <CompactHiddenHandles- connectedSourceHandles={data.connectedSourceHandles}- connectedTargetHandles={data.connectedTargetHandles}- inputTemplates={inputTemplates}- outputTemplates={outputTemplates}- /></NodeShell>);};@@ -1027,23 +1384,20 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeconst isMissing = !isWorkflowImageExport && data.templateStatus === 'loaded';return (- <NodeShell isMissing={isMissing} selected={selected ?? false}>+ <NodeShell chrome={{ invalid: isMissing }} selected={selected ?? false}><HStack gap="1.5" minW={isWorkflowImageExport ? '0' : undefined} p="3">- {isMissing ? <Icon as={TriangleAlertIcon} boxSize="3.5" color="red.solid" /> : null}+ {isMissing ? <Icon as={TriangleAlertIcon} boxSize="3.5" color="fg.error" /> : null}<Stack flex={isWorkflowImageExport ? '1' : undefined} gap="0" minW={isWorkflowImageExport ? '0' : undefined}>{isWorkflowImageExport ? (<MiddleTruncatedata-workflow-export-node-title="true"data-workflow-export-static-node-content="true"- fontSize="lg"- fontWeight="700"+ fontWeight="600"minW="0"text={node.data.label || node.data.type}/>) : (- <Text fontSize="lg" fontWeight="700">- {node.data.label || node.data.type}- </Text>+ <Text fontWeight="600">{node.data.label || node.data.type}</Text>)}{!isWorkflowImageExport ? (<Text color="fg.subtle" fontSize="xs">@@ -1058,7 +1412,6 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode}const template = templateView.template;- const isOutdated = getNodeUpdateStatus(node, template) !== 'current';const connectedFieldNames = new Set(data.connectedTargetHandles);const exposedFieldNames = new Set(data.exposedFieldNames);const inputTemplates = templateView.inputTemplates;@@ -1066,56 +1419,73 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeconst outputTemplatesByName = new Map(outputTemplates.map((template) => [template.name, template]));const outputRows = getOutputFieldRows(getOutputFieldNamesByScope(outputTemplates));const isOpen = node.data.isOpen || isWorkflowImageExport;- const isRunning = execution?.status === 'running';- const isMissingRequiredInput = hasMissingRequiredInputs(node, inputTemplates, connectedFieldNames);+ const fieldIssues = getInvocationNodeFieldIssues(node, inputTemplates, connectedFieldNames);+ const issuesByField = new Map(+ fieldIssues.flatMap((fieldIssue) => fieldIssue.markedFieldNames.map((name) => [name, fieldIssue] as const))+ );+ // The static export draws the document only: no run, validity or version state.+ const { chrome, status } = isWorkflowImageExport+ ? { chrome: undefined, status: null }+ : getInvocationNodeState({+ execution,+ hasFieldIssues: fieldIssues.length > 0,+ updateStatus: getNodeUpdateStatus(node, template),+ });+ const { tone } = getWorkflowNodeAppearance({ ...chrome, selected: false });const isCompact = data.isCompact && !selected && !isWorkflowImageExport;const withFooter = !isWorkflowImageExport && !isZoomedOut && templateView.isExecutable && templateView.hasImageOutput;const resultExecution = isWorkflowImageExport ? null : execution;const latestResult = resultExecution?.latestOutput;+ const title = node.data.label || template.title;return (- <NodeShell- hasMissingRequiredInput={!isWorkflowImageExport && isMissingRequiredInput}- isOutdated={!isWorkflowImageExport && isOutdated}- isRunning={!isWorkflowImageExport && isRunning}- outcome={isWorkflowImageExport ? null : getExecutionOutcome(execution)}- selected={selected ?? false}- >- {/* The collapse chevron carries its own hit padding, so the header pulls its start padding in. */}+ <NodeShell chrome={chrome} selected={selected ?? false}>+ {/* Buttons at either end of the header sit at the same inset from the border. */}<Flex- {...getWorkflowNodeHeaderProps({ roundedBottom: !isOpen })}- gap="1"- ps={isWorkflowImageExport ? WORKFLOW_NODE_DENSITY.headerPaddingStart : '1'}+ {...getWorkflowNodeHeaderProps({+ // Far zoom drops the status and info buttons, leaving the title at the end.+ endsWithButton: !isWorkflowImageExport && !isZoomedOut,+ roundedBottom: !isOpen,+ startsWithButton: !isWorkflowImageExport,+ tone,+ })}+ gap="0.5">{!isWorkflowImageExport ? (- <IconButton+ <WorkflowNodeHeaderButtonaria-label={isOpen ? t('nodes.collapseNode') : t('nodes.expandNode')}className="nodrag"- size="sm"- variant="ghost"+ content={isOpen ? t('nodes.collapseNode') : t('nodes.expandNode')}onClick={() => editGraph({ isOpen: !isOpen, nodeId: node.id, type: 'setNodeIsOpen' })}><Icon as={isOpen ? ChevronDownIcon : ChevronRightIcon} boxSize="3.5" />- </IconButton>+ </WorkflowNodeHeaderButton>+ ) : null}+ {!isWorkflowImageExport && !isZoomedOut ? (+ <NodeClassificationIcon classification={template.classification} />) : null}{isZoomedOut ? (- <MiddleTruncate fontSize="lg" fontWeight="700" minW="0" text={node.data.label || template.title} />+ <MiddleTruncate {...WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS} fontWeight="600" minW="0" text={title} />) : (<>- <NodeTitle- isWorkflowImageExport={isWorkflowImageExport}- node={node}- title={node.data.label || template.title}- />+ <NodeTitle isWorkflowImageExport={isWorkflowImageExport} node={node} title={title} /><BatchGroupSuffix node={node} /><Box flex="1" />- {!isWorkflowImageExport ? <NodeOutcomeIcon execution={execution} node={node} /> : null}- {!isWorkflowImageExport && isOutdated ? <NodeUpdateIcon node={node} template={template} /> : null}- {!isWorkflowImageExport ? <NodeInfoIcon node={node} template={template} /> : null}+ {!isWorkflowImageExport ? (+ <>+ <NodeStatusButton+ execution={execution}+ issues={fieldIssues}+ node={node}+ status={status}+ template={template}+ />+ <NodeInfoButton node={node} template={template} />+ </>+ ) : null}</>)}</Flex>- <NodeProgressStrip execution={execution} />{isOpen && isCompact ? (<><CompactNodeBody inputCount={inputTemplates.length} outputCount={outputTemplates.length} />@@ -1139,6 +1509,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode<InputFieldRowkey={inputTemplate.name}connectedFieldNames={connectedFieldNames}+ issue={issuesByField.get(inputTemplate.name) ?? null}isConnected={connectedFieldNames.has(inputTemplate.name)}isExposed={exposedFieldNames.has(inputTemplate.name)}isSkeleton={isZoomedOut}@@ -1157,7 +1528,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode) : null}</Box>) : (- <HiddenHandles inputTemplates={inputTemplates} outputTemplates={outputTemplates} />+ <CollapsedPorts inputTemplates={inputTemplates} outputTemplates={outputTemplates} />)}{isOpen && withFooter ? <NodeFooter canUseCache={data.canUseCache} node={node} /> : null}</NodeShell>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodePanelLoading.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodePanelLoading.browser.test.tsxnew file mode 100644index 0000000000..4eceb28dd5--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodePanelLoading.browser.test.tsx@@ -0,0 +1,145 @@+import type { InvocationTemplate, WorkflowInvocationNode } from '@features/workflow/contracts';+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';+import type * as DeferredModuleModule from '@platform/react/deferredModule';++/* eslint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-array-as-prop -- each test mounts a fresh flow */+import { ChakraProvider } from '@chakra-ui/react';+import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';+import { createProjectGraph } from '@features/workflow/utility';+import { system } from '@theme/system';+import { ReactFlow } from '@xyflow/react';+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 { toFlowNodes } from './flowAdapters';+import { InvocationFlowNode } from './InvocationFlowNode';++import '@xyflow/react/dist/style.css';++// The later open's real import resolves from the module cache rather than an on-demand transform under suite load.+await import('./NodePanels');++// The panel body's chunk fails to load for the first open, as a stale or dropped chunk does: its import rejects. The+// rejection comes from the deferred module's import seam, because a `vi.mock` factory that rejects is not an import+// failure in browser mode: Vitest's module interception reports it as an unhandled error and never answers the request.+const panelLoad = vi.hoisted(() => ({ fails: false, rejected: 0 }));+vi.mock('@platform/react/deferredModule', async (importOriginal) => {+ const actual = await importOriginal<typeof DeferredModuleModule>();++ return {+ ...actual,+ // The node's panels are the only deferred module this view renders.+ createDeferredModule: <Module,>(importModule: () => Promise<Module>) =>+ actual.createDeferredModule(() => {+ if (!panelLoad.fails) {+ return importModule();+ }+ panelLoad.rejected += 1;+ return Promise.reject(new TypeError('Failed to fetch dynamically imported module'));+ }),+ };+});+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) =>+ key === 'nodes.status.label' ? `Status: ${String(options?.status)}` : key,+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const template: InvocationTemplate = {+ category: 'test',+ classification: 'stable',+ description: '',+ inputs: {},+ nodePack: 'invokeai',+ outputType: 'test',+ outputs: {},+ tags: [],+ title: 'Preview',+ type: 'preview',+ useCache: true,+ version: '1.1.0',+};+// An older version than its template, so the node has a status to report.+const node: WorkflowInvocationNode = {+ data: {+ inputs: {},+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type: 'preview',+ useCache: true,+ version: '1.0.0',+ },+ id: 'node',+ position: { x: 20, y: 60 },+ type: 'invocation',+};++const adapter = {+ capabilities: { getSnapshot: () => ({ canUseCache: true }), subscribe: () => () => {} },+ commands: { editGraph: vi.fn() },+ nodeExecution: {+ get: () => null,+ getOrigin: () => null,+ subscribe: () => () => {},+ subscribeOrigin: () => () => {},+ },+ project: { getSnapshot: () => ({ id: 'p' }), subscribe: () => () => {} },+} as unknown as WorkflowUiAdapter;++describe('node header panels when their body fails', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width: 480px; height: 360px;';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('shows the button’s label instead of crashing the editor, and the full panel on a later open', async () => {+ panelLoad.fails = true;+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <ReactFlow+ nodes={toFlowNodes({ ...createProjectGraph('panels'), nodes: [node] }, [], { preview: template })}+ nodeTypes={{ invocation: InvocationFlowNode }}+ />+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );+ const statusButton = () => host.querySelector<HTMLElement>('[data-node-status-indicator="true"]')!;+ const panel = () => document.querySelector('[data-scope="tooltip"][data-part="content"]');+ const label = statusButton().getAttribute('aria-label')!;++ await act(() => userEvent.hover(statusButton()));+ // The label shows while loading too; this is it standing in for a load that failed.+ await vi.waitFor(() => expect(panelLoad.rejected).toBeGreaterThan(0));+ await vi.waitFor(() => expect(panel()?.textContent).toBe(label));+ // The node is still there and still answers.+ expect(host.querySelector('.react-flow__node[data-id="node"]')).not.toBeNull();+ await act(() => userEvent.unhover(statusButton()));+ await vi.waitFor(() => expect(panel()).toBeNull());+ panelLoad.fails = false;++ await act(() => userEvent.hover(statusButton()));+ // The panel body: the version line on its own, not the button's "Status: …" label.+ await vi.waitFor(() => expect(panel()?.textContent).toBe('nodes.nodeUpdateAvailable'));+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodePanels.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodePanels.tsxnew file mode 100644index 0000000000..b5c7208102--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodePanels.tsx@@ -0,0 +1,80 @@+import type { WorkflowInvocationNode } from '@features/workflow/contracts';+import type { WorkflowNodeExecutionState as NodeExecutionState } from '@features/workflow/ui/contracts';++import { Stack, Text } from '@chakra-ui/react';+import { useTranslation } from 'react-i18next';++import type { InvocationNodeTemplateView } from './flowAdapters';++import {+ getExecutionStatusText,+ getFieldIssueMessage,+ getNodeExecutionError,+ type InvocationNodeFieldIssue,+} from './nodeStatusText';++/** The header panels' bodies, loaded on a node's first panel open: most nodes never open one. */++/** The status panel: the run, what blocks the next one, and the version, each when it applies. */+export const NodeStatusPanel = ({+ execution,+ issues,+ node,+ updateText,+}: {+ execution: NodeExecutionState | null;+ issues: readonly InvocationNodeFieldIssue[];+ node: WorkflowInvocationNode;+ updateText: string | null;+}) => {+ const { t } = useTranslation();+ const error = execution?.status === 'failed' ? getNodeExecutionError(node, execution.error, t) : null;++ return (+ <Stack gap="1" maxW="20rem">+ {execution ? (+ <Stack gap="0.5">+ <Text fontWeight="600">{getExecutionStatusText(t, execution)}</Text>+ {execution.status === 'running' && execution.progressMessage ? (+ <Text color="fg.muted">{execution.progressMessage}</Text>+ ) : null}+ {error ? <Text overflowWrap="anywhere">{error}</Text> : null}+ </Stack>+ ) : null}+ {issues.length > 0 ? (+ <Stack as="ul" gap="0.5" listStyleType="none">+ {issues.map((fieldIssue) => (+ <Text key={fieldIssue.template.name} as="li">+ {getFieldIssueMessage(t, fieldIssue)}+ </Text>+ ))}+ </Stack>+ ) : null}+ {updateText ? <Text>{updateText}</Text> : null}+ </Stack>+ );+};++/** Legacy's info panel: what the node is, where it comes from, and the author's notes. */+export const NodeInfoPanel = ({+ node,+ template,+}: {+ node: WorkflowInvocationNode;+ template: InvocationNodeTemplateView['template'];+}) => {+ const { t } = useTranslation();+ const title = node.data.label ? `${node.data.label} (${template.title})` : template.title;+ const nodePack = node.data.nodePack || template.nodePack;++ return (+ <Stack gap="1" maxW="20rem">+ <Text fontWeight="600">{title}</Text>+ <Text color="fg.muted">{t('nodes.nodeType', { type: template.type })}</Text>+ <Text color="fg.muted">{t('nodes.nodePackLabel', { name: nodePack })}</Text>+ <Text color="fg.muted">{t('nodes.nodeVersion', { version: node.data.version })}</Text>+ {template.description ? <Text fontStyle="italic">{template.description}</Text> : null}+ {node.data.notes ? <Text whiteSpace="pre-wrap">{node.data.notes}</Text> : null}+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEdge.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEdge.tsxindex 0ea4e6ca7b..df1a00ea4d 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEdge.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEdge.tsx@@ -29,15 +29,20 @@ const WorkflowEdgeComponent = ({}: EdgeProps) => {const { t } = useTranslation();const edgeData = (data as WorkflowEdgeData | undefined) ?? FALLBACK_EDGE_DATA;+ const collapsedCount = edgeData.collapsedEdgeIds?.length ?? 0;+ // One drawn edge for several fields carries no single type: it draws neutral, as legacy's did.+ const isMergedEdge = collapsedCount > 1;// Worded as the handle tooltips word the same type.const tooltip = edgeData.isLoopLinkage? t('nodes.loopLinkage')- : edgeData.fieldTypeLabel === null- ? t('nodes.unknownFieldType')- : edgeData.isBatch- ? `${edgeData.fieldTypeLabel} ${t('nodes.batch')}`- : edgeData.fieldTypeLabel;- const [edgePath] =+ : isMergedEdge+ ? t('nodes.collapsedConnections', { count: collapsedCount })+ : edgeData.fieldTypeLabel === null+ ? t('nodes.unknownFieldType')+ : edgeData.isBatch+ ? `${edgeData.fieldTypeLabel} ${t('nodes.batch')}`+ : edgeData.fieldTypeLabel;+ const [edgePath, labelX, labelY] =edgeData.pathType === 'step'? getSmoothStepPath({borderRadius: 0,@@ -61,11 +66,11 @@ const WorkflowEdgeComponent = ({animation: selected? 'dashdraw var(--wb-motion-duration-slow) linear var(--wb-motion-animation-iteration-count)': undefined,- stroke: edgeData.stroke,- strokeDasharray: selected ? '5' : edgeData.strokeDasharray,+ stroke: isMergedEdge ? FALLBACK_EDGE_DATA.stroke : edgeData.stroke,+ strokeDasharray: selected ? '5' : isMergedEdge ? undefined : edgeData.strokeDasharray,strokeLinecap: 'round',strokeLinejoin: 'round',- strokeWidth: edgeData.strokeWidth,+ strokeWidth: isMergedEdge ? FALLBACK_EDGE_DATA.strokeWidth : edgeData.strokeWidth,};return (@@ -93,6 +98,37 @@ const WorkflowEdgeComponent = ({<title>{tooltip}</title></path>) : null}+ {collapsedCount > 0 ? <CollapsedEdgeCount count={collapsedCount} x={labelX} y={labelY} /> : null}+ </g>+ );+};++const BADGE_HEIGHT = 16;++/** Legacy's count on an edge between two collapsed nodes: how many connections it stands for. */+const CollapsedEdgeCount = ({ count, x, y }: { count: number; x: number; y: number }) => {+ const width = Math.max(BADGE_HEIGHT, 8 + String(count).length * 7);++ return (+ <g aria-hidden data-collapsed-edge-count={count} pointerEvents="none" transform={`translate(${x} ${y})`}>+ <rect+ fill="var(--wb-node-surface)"+ height={BADGE_HEIGHT}+ rx={BADGE_HEIGHT / 2}+ stroke="var(--xy-edge-stroke)"+ width={width}+ x={-width / 2}+ y={-BADGE_HEIGHT / 2}+ />+ <text+ dominantBaseline="central"+ fill="var(--wb-edge-badge-fg)"+ fontSize="10.5"+ fontWeight="600"+ textAnchor="middle"+ >+ {count}+ </text></g>);};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorMiniMap.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorMiniMap.tsxnew file mode 100644index 0000000000..dd8bb48cef--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorMiniMap.tsx@@ -0,0 +1,91 @@+import type { Node } from '@xyflow/react';++import {+ FLOW_MINIMAP_ERROR_CLASS,+ FLOW_MINIMAP_RUNNING_CLASS,+ FlowMiniMap,+} from '@features/workflow/ui/graph-preview/FlowMiniMap';+import { useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { useCallback, useMemo, useSyncExternalStore } from 'react';++import type { InvocationFlowNode as InvocationFlowNodeType } from './flowAdapters';++import { isInvocationFlowNodeInvalid } from './InvocationFlowNode';++/**+ * The run state of this editor's nodes that the minimap shows, as `id:status` lines for the running and failed ones.+ * A string snapshot, so progress ticks and unrelated project changes do not render the minimap.+ */+const useMinimapRunStates = (nodeIds: readonly string[]): Map<string, 'failed' | 'running'> => {+ const { nodeExecution, project } = useWorkflowUi();+ const subscribe = useCallback(+ (listener: () => void) => {+ const unsubscribers = [+ ...nodeIds.map((nodeId) => nodeExecution.subscribe(nodeId, listener)),+ nodeExecution.subscribeOrigin(listener),+ project.subscribe(listener),+ ];++ return () => unsubscribers.forEach((unsubscribe) => unsubscribe());+ },+ [nodeExecution, nodeIds, project]+ );+ const getSnapshot = useCallback(() => {+ const origin = nodeExecution.getOrigin();+ const snapshot = project.getSnapshot();++ if (!origin || origin.projectId !== snapshot.id || origin.workflowId !== snapshot.activeWorkflowId) {+ return '';+ }++ return nodeIds+ .flatMap((nodeId) => {+ const status = nodeExecution.get(nodeId)?.status;++ return status === 'running' || status === 'failed' ? [`${nodeId}:${status}`] : [];+ })+ .join('\n');+ }, [nodeExecution, nodeIds, project]);+ const states = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);++ return useMemo(+ () =>+ new Map(+ states+ .split('\n')+ .filter(Boolean)+ .map((line) => {+ const separator = line.lastIndexOf(':');++ return [line.slice(0, separator), line.slice(separator + 1) as 'failed' | 'running'];+ })+ ),+ [states]+ );+};++/**+ * The editor's minimap: invalid and failed nodes in the error tone, the running node in the accent tone. `nodeIds` are+ * the document's invocation nodes, which the editor derives only when the node set changes, not on every drag frame.+ */+export const WorkflowEditorMiniMap = ({ nodeIds }: { nodeIds: readonly string[] }) => {+ const runStates = useMinimapRunStates(nodeIds);+ const nodeClassName = useCallback(+ (node: Node) => {+ if (node.type !== 'invocation') {+ return '';+ }++ const runState = runStates.get(node.id);++ return runState === 'running'+ ? FLOW_MINIMAP_RUNNING_CLASS+ : runState === 'failed' || isInvocationFlowNodeInvalid((node as InvocationFlowNodeType).data)+ ? FLOW_MINIMAP_ERROR_CLASS+ : '';+ },+ [runStates]+ );++ return <FlowMiniMap nodeClassName={nodeClassName} />;+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsxindex b4ab35924a..71bb0e93e0 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.browser.test.tsx@@ -12,13 +12,14 @@ 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 { commands, userEvent } from 'vitest/browser';import '@xyflow/react/dist/style.css';import { clearWorkflowClipboard, copyNodesToClipboard } from './clipboard';import { getWorkflowFlowInstance } from './flowInstanceStore';import { CONTENT_VISIBILITY_ZOOM } from './InvocationFlowNode';import { WorkflowEditorView } from './WorkflowEditorView';+import { useWorkflowPngExportState } from './workflowPngExport';import { clearWorkflowViewports, getWorkflowViewport, getWorkflowViewportKey } from './workflowViewportStore';const templatesSnapshot = vi.hoisted(() => {@@ -77,6 +78,16 @@ vi.mock('@features/workflow/react', async (importOriginal) => ({useInvocationTemplatesSelector: (selector: (snapshot: unknown) => unknown) => selector(templatesSnapshot),}));+declare module 'vitest/browser' {+ interface BrowserCommands {+ mouseDragPath: (points: readonly { x: number; y: number }[], frameWidth: number) => Promise<void>;+ }+}++const exportMocks = vi.hoisted(() => ({ rasterize: vi.fn() }));+vi.mock('./workflowImageRaster', () => ({ rasterizeWorkflowImage: exportMocks.rasterize }));+vi.mock('@platform/browser/downloadBlob', () => ({ downloadBlob: vi.fn() }));+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const i18n = createInstance();@@ -139,7 +150,10 @@ const createProjectStore = (graph: ProjectGraphState) => {const createAdapter = (project: ReturnType<typeof createProjectStore>,- { showMinimap = false }: { showMinimap?: boolean } = {}+ {+ nodeExecution,+ showMinimap = false,+ }: { nodeExecution?: WorkflowUiAdapter['nodeExecution']; showMinimap?: boolean } = {}): WorkflowUiAdapter => {const subscribe = () => () => {};@@ -159,7 +173,7 @@ const createAdapter = (undo: vi.fn(),},getProjectGraph: () => project.getSnapshot().projectGraph,- nodeExecution: { get: () => null, getOrigin: () => null, subscribe, subscribeOrigin: subscribe },+ nodeExecution: nodeExecution ?? { get: () => null, getOrigin: () => null, subscribe, subscribeOrigin: subscribe },notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },openAddModels: vi.fn(),performance: {@@ -200,11 +214,16 @@ const runtime = {typeId: 'workflow',} as const;+const PngExportAvailability = () => {+ const { isAvailable } = useWorkflowPngExportState();+ return <output hidden data-png-export-available={String(isAvailable)} />;+};+/** Mounts the editor over the project port and returns the adapter, whose commands the test inspects. */const renderEditor = async (root: Root,project: ReturnType<typeof createProjectStore>,- options?: { showMinimap?: boolean }+ options?: Parameters<typeof createAdapter>[1]) => {const adapter = createAdapter(project, options);@@ -214,6 +233,7 @@ const renderEditor = async (<ChakraProvider value={system}><QueryClientProvider client={new QueryClient()}><WorkflowUiProvider adapter={adapter}>+ <PngExportAvailability /><WorkflowEditorView runtime={runtime} /></WorkflowUiProvider></QueryClientProvider>@@ -265,6 +285,33 @@ describe('WorkflowEditorView first open', () => {return { addedFieldInputs, zoom: getWorkflowViewport(viewportKey)!.zoom };};+ it('keeps PNG export unavailable while a large workflow prepares, then enables it after flow initialization', async () => {+ const frames: FrameRequestCallback[] = [];+ const frame = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => frames.push(callback));++ try {+ const graph = {+ ...createProjectGraph('large'),+ nodes: Array.from({ length: 300 }, (_, index) => addNode(`node-${index}`, index * 300, 0)),+ };+ await renderEditor(root, createProjectStore(graph));++ expect(getWorkflowFlowInstance()).toBeNull();+ expect(host.querySelector('[data-png-export-available]')?.getAttribute('data-png-export-available')).toBe(+ 'false'+ );+ frame.mockRestore();+ await act(() => frames.forEach((callback) => callback(performance.now())));++ await expect.poll(getWorkflowFlowInstance).not.toBeNull();+ await expect+ .poll(() => host.querySelector('[data-png-export-available]')?.getAttribute('data-png-export-available'))+ .toBe('true');+ } finally {+ frame.mockRestore();+ }+ });+it('never mounts field controls for a graph whose fit lands zoomed out', async () => {const nodes = Array.from({ length: 6 }, (_, index) => addNode(`node-${index}`, index * 600, (index % 2) * 400));const fitted = await openFitted({ ...createProjectGraph('wide'), nodes });@@ -676,3 +723,256 @@ describe('WorkflowEditorView paste', () => {expect(action?.edges).toEqual([expect.objectContaining({ source: 'outside', target: action?.nodes[0]?.id })]);});});++describe('WorkflowEditorView edges and minimap', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width: 480px; height: 520px;';+ document.body.append(host);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ clearWorkflowViewports();+ });++ const edge = (id: string, source: string, target: string) => ({+ id,+ source,+ sourceHandle: 'value',+ target,+ targetHandle: 'a',+ type: 'default' as const,+ });+ const collapsed = (node: WorkflowInvocationNode): WorkflowInvocationNode => ({+ ...node,+ data: { ...node.data, isOpen: false },+ });+ const edgeElement = (id: string) => host.querySelector<SVGGElement>(`.react-flow__edge[data-id="${id}"]`);+ const edgeOpacity = (id: string) =>+ getComputedStyle(edgeElement(id)!.querySelector<SVGPathElement>('.react-flow__edge-path')!).opacity;+ const editor = () => host.querySelector<HTMLElement>('.react-flow')!.parentElement!;++ it('keeps a selected node’s edges at full strength and dims the rest to a quarter', async () => {+ const graph = {+ ...createProjectGraph('emphasis'),+ edges: [edge('ab', 'a', 'b'), edge('cd', 'c', 'd')],+ nodes: [addNode('a', 0, 0), addNode('b', 400, 0), addNode('c', 0, 300), addNode('d', 400, 300)],+ };+ await renderEditor(root, createProjectStore(graph));+ await expect.poll(() => edgeElement('cd')).not.toBeNull();+ const restingOpacity = edgeOpacity('cd');++ await act(() => userEvent.click(host.querySelector<HTMLElement>('.react-flow__node[data-id="a"]')!));+ await expect.poll(() => editor().hasAttribute('data-node-selected')).toBe(true);+ expect(edgeElement('ab')!.classList.contains('workflow-selected-node-edge')).toBe(true);+ await expect.poll(() => edgeOpacity('cd')).toBe('0.25');+ await expect.poll(() => edgeOpacity('ab')).toBe('1');++ await act(() =>+ userEvent.click(host.querySelector<HTMLElement>('.react-flow__pane')!, { position: { x: 460, y: 500 } })+ );+ await expect.poll(() => editor().hasAttribute('data-node-selected')).toBe(false);+ await expect.poll(() => edgeOpacity('cd')).toBe(restingOpacity);+ expect(restingOpacity).not.toBe('0.25');+ });++ it('exports edges at the same strength whether or not a node is selected in the editor', async () => {+ const graph = {+ ...createProjectGraph('emphasis-export'),+ edges: [edge('ab', 'a', 'b'), edge('cd', 'c', 'd')],+ nodes: [addNode('a', 0, 0), addNode('b', 400, 0), addNode('c', 0, 300), addNode('d', 400, 300)],+ };+ await renderEditor(root, createProjectStore(graph));+ await expect.poll(() => edgeElement('cd')).not.toBeNull();+ const exportedOpacities = async () => {+ let opacities: string[] = [];+ exportMocks.rasterize.mockReset();+ exportMocks.rasterize.mockImplementation((clone: HTMLElement) => {+ opacities = [...clone.querySelectorAll<SVGPathElement>('.react-flow__edge .react-flow__edge-path')].map(+ (path) => getComputedStyle(path).opacity+ );+ return Promise.resolve(new Blob(['png'], { type: 'image/png' }));+ });+ await act(() =>+ userEvent.click(host.querySelector<HTMLElement>('button[aria-label="widgets.workflow.exportAsPng"]')!)+ );+ await expect.poll(() => exportMocks.rasterize.mock.calls.length).toBe(1);+ await expect+ .poll(() => host.querySelector('button[aria-label="widgets.workflow.exportAsPng"]:disabled'))+ .toBeNull();+ return opacities;+ };++ const unselected = await exportedOpacities();+ expect(unselected).toHaveLength(2);+ await act(() => userEvent.click(host.querySelector<HTMLElement>('.react-flow__node[data-id="a"]')!));+ await expect.poll(() => editor().hasAttribute('data-node-selected')).toBe(true);++ expect(await exportedOpacities()).toEqual(unselected);+ });++ it('selects and deletes every edge a collapsed edge stands for, and draws them again when they return', async () => {+ const graph = {+ ...createProjectGraph('collapsed-edges'),+ edges: [edge('e1', 'a', 'b'), edge('e2', 'a', 'b')],+ nodes: [collapsed(addNode('a', 0, 0)), collapsed(addNode('b', 400, 160))],+ };+ const project = createProjectStore(graph);+ const adapter = await renderEditor(root, project);+ const drawn = () =>+ [...host.querySelectorAll('.react-flow__edge')].map((element) => element.getAttribute('data-id'));+ await expect.poll(drawn).toEqual(['e1']);+ const selectMergedEdge = async () => {+ await act(() =>+ userEvent.click(edgeElement('e1')!.querySelector('.react-flow__edge-interaction')!, { force: true })+ );+ await expect.poll(() => edgeElement('e1')!.classList.contains('selected')).toBe(true);+ };++ // Its ends cannot be dragged: a reconnection would move one of the edges it stands for.+ expect(edgeElement('e1')!.querySelector('.react-flow__edgeupdater')).toBeNull();++ // The Delete command (palette or hotkey) and the Delete key delete the same set.+ await selectMergedEdge();+ await act(() => commandHandlers.get('workflows.deleteSelection')!());+ expect(adapter.commands.editGraph).toHaveBeenCalledWith({ edgeIds: ['e1', 'e2'], type: 'removeEdges' });+ vi.mocked(adapter.commands.editGraph).mockClear();+ await act(() => userEvent.keyboard('{Delete}'));+ expect(adapter.commands.editGraph).toHaveBeenCalledWith({ edgeIds: ['e1', 'e2'], type: 'removeEdges' });++ // Undo hands the editor the same edges again: they draw as one collapsed edge with its count.+ await act(() => project.setGraph({ ...graph, edges: [] }));+ await expect.poll(drawn).toEqual([]);+ await act(() => project.setGraph(graph));+ await expect.poll(drawn).toEqual(['e1']);+ expect(host.querySelector('[data-collapsed-edge-count]')?.getAttribute('data-collapsed-edge-count')).toBe('2');+ });++ it('keeps a merged line selected when it is clicked again, so Delete still removes every edge it stands for', async () => {+ const graph = {+ ...createProjectGraph('collapsed-reclick'),+ edges: [edge('e1', 'a', 'b'), edge('e2', 'a', 'b')],+ nodes: [collapsed(addNode('a', 0, 0)), collapsed(addNode('b', 400, 160))],+ };+ const adapter = await renderEditor(root, createProjectStore(graph));+ await expect.poll(() => edgeElement('e1')).not.toBeNull();+ const clickMergedLine = () =>+ act(() => userEvent.click(edgeElement('e1')!.querySelector('.react-flow__edge-interaction')!, { force: true }));++ await clickMergedLine();+ await clickMergedLine();+ await expect.poll(() => edgeElement('e1')!.classList.contains('selected')).toBe(true);+ await act(() => userEvent.keyboard('{Delete}'));++ expect(adapter.commands.editGraph).toHaveBeenCalledWith({ edgeIds: ['e1', 'e2'], type: 'removeEdges' });+ });++ it('leaves a merged line’s edges agreeing after a box selection, so deleting takes all or none of them', async () => {+ const graph = {+ ...createProjectGraph('collapsed-box'),+ edges: [edge('e1', 'a', 'b'), edge('e2', 'a', 'b'), edge('cd', 'c', 'd')],+ nodes: [+ collapsed(addNode('a', 0, 0)),+ collapsed(addNode('b', 400, 160)),+ addNode('c', 0, 320),+ addNode('d', 400, 480),+ ],+ };+ const adapter = await renderEditor(root, createProjectStore(graph));+ await expect.poll(() => edgeElement('cd')).not.toBeNull();+ const flowRect = host.querySelector<HTMLElement>('.react-flow')!.getBoundingClientRect();++ // Shift-drag across the whole graph box-selects every node. (The selection's own rectangle then covers the+ // merged line, so it takes no click until the selection is cleared; the click case is in flowAdapters.test.)+ await userEvent.keyboard('{Shift>}');+ await commands.mouseDragPath(+ [+ { x: flowRect.left + 2, y: flowRect.top + 2 },+ { x: flowRect.left + 40, y: flowRect.top + 40 },+ { x: flowRect.right - 2, y: flowRect.bottom - 2 },+ ],+ window.innerWidth+ );+ await userEvent.keyboard('{/Shift}');+ await expect+ .poll(() => host.querySelector('.react-flow__node[data-id="a"]')!.classList.contains('selected'))+ .toBe(true);++ await act(() => commandHandlers.get('workflows.deleteSelection')!());+ const removedEdges = vi+ .mocked(adapter.commands.editGraph)+ .mock.calls.flatMap(([action]) => (action.type === 'removeEdges' ? action.edgeIds : []));+ expect(removedEdges.includes('e1')).toBe(removedEdges.includes('e2'));+ });++ it('lets only the open end of an edge from a collapsed node be dragged', async () => {+ const graph = {+ ...createProjectGraph('collapsed-to-open'),+ edges: [edge('ac', 'a', 'c')],+ nodes: [collapsed(addNode('a', 0, 0)), addNode('c', 400, 160)],+ };+ await renderEditor(root, createProjectStore(graph));+ await expect.poll(() => edgeElement('ac')).not.toBeNull();++ expect(edgeElement('ac')!.querySelector('.react-flow__edgeupdater-source')).toBeNull();+ expect(edgeElement('ac')!.querySelector('.react-flow__edgeupdater-target')).not.toBeNull();+ });++ it('tints invalid and failed nodes in the error tone and the running node in the accent tone on the minimap', async () => {+ const graph = {+ ...createProjectGraph('minimap-states'),+ nodes: [+ addNode('idle', 0, 0),+ { ...addNode('unknown', 300, 0), data: { ...addNode('unknown', 300, 0).data, type: 'not_installed' } },+ addNode('running', 0, 300),+ addNode('failed', 300, 300),+ ],+ };+ const runState = (status: 'failed' | 'running') => ({+ error: null,+ latestOutput: null,+ outputImageName: null,+ progress: null,+ progressMessage: null,+ status,+ });+ // Stable snapshots, as the real port keeps them between changes.+ const origin = { projectId: PROJECT_ID, workflowId: graph.id };+ const states: Record<string, ReturnType<typeof runState>> = {+ failed: runState('failed'),+ running: runState('running'),+ };+ const subscribe = () => () => {};+ await renderEditor(root, createProjectStore(graph), {+ nodeExecution: {+ get: (nodeId) => states[nodeId] ?? null,+ getOrigin: () => origin,+ subscribe,+ subscribeOrigin: subscribe,+ },+ showMinimap: true,+ });++ const minimapNodes = () => [...host.querySelectorAll<SVGRectElement>('.react-flow__minimap-node')];+ await expect.poll(() => minimapNodes().length).toBe(4);+ const classes = minimapNodes().map((rect) =>+ rect.classList.contains('workflow-minimap-error')+ ? 'error'+ : rect.classList.contains('workflow-minimap-running')+ ? 'running'+ : 'plain'+ );+ expect(classes).toEqual(['plain', 'error', 'running', 'error']);+ const fills = minimapNodes().map((rect) => getComputedStyle(rect).fill);+ expect(fills[1]).not.toBe(fills[0]);+ expect(fills[2]).not.toBe(fills[0]);+ expect(fills[2]).not.toBe(fills[1]);+ expect(fills[3]).toBe(fills[1]);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex f492baa20c..ddd1816703 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -5,7 +5,7 @@ import { Box, Flex, HStack, Spinner, Stack, Text } from '@chakra-ui/react';import { getArrangedLayout } from '@features/workflow/core/graphLayout';import '@xyflow/react/dist/style.css';import { ensureInvocationTemplatesLoaded, useInvocationTemplatesSelector } from '@features/workflow/react';-import { FlowMiniMap, flowThemeCss, getFlowColorMode } from '@features/workflow/ui/graph-preview';+import { flowThemeCss, getFlowColorMode } from '@features/workflow/ui/graph-preview/flowTheme';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {useWorkflowCapabilitiesSelector,@@ -27,6 +27,7 @@ import {validateConnection,} from '@features/workflow/utility';import { useModifierHeld } from '@platform/react/useModifierHeld';+import { useMountEffect } from '@platform/react/useMountEffect';import { shallowEqual } from '@platform/state/selectors';import {Background,@@ -82,6 +83,8 @@ import { fitWorkflowBounds } from './fitWorkflowBounds';import {toFlowEdges,toFlowNodes,+ withCollapsedGroupSelection,+ withCollapsedEdgeSiblings,withNodeSelection,type FlowEdgeType,type InvocationTemplateStatus,@@ -111,7 +114,9 @@ import { reportNodeHover, reportNodeSelection, workflowSelectionStore } from './import { useEraser } from './useEraser';import { useLasso } from './useLasso';import { WorkflowEdge } from './WorkflowEdge';+import { WorkflowEditorMiniMap } from './WorkflowEditorMiniMap';import { WORKFLOW_HOTKEYS } from './workflowHotkeys';+import { registerWorkflowPngExportHost } from './workflowPngExport';import { WorkflowSelectionRequestRuntime } from './WorkflowSelectionRequestRuntime';import { getWorkflowViewport, getWorkflowViewportKey, setWorkflowViewport } from './workflowViewportStore';@@ -505,7 +510,9 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {}const removedNodeIds = new Set(existingNodeIds);- const requestedEdgeIds = new Set(edgeIds);+ const requestedEdgeIds = new Set(+ withCollapsedEdgeSiblings({ edges: projectGraph.edges, nodes: projectGraph.nodes }, edgeIds)+ );const existingEdgeIds = projectGraph.edges.filter((edge) =>@@ -796,7 +803,11 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {const deleteSelection = () => {const nodeIds = flowNodes.filter((node) => node.selected).map((node) => node.id);- const edgeIds = flowEdges.filter((edge) => edge.selected).map((edge) => edge.id);+ // Widened as the Delete key's path is, so both delete exactly the edges a selected collapsed edge stands for.+ const edgeIds = withCollapsedEdgeSiblings(+ projectGraph,+ flowEdges.filter((edge) => edge.selected).map((edge) => edge.id)+ );if (nodeIds.length > 0) {editGraph({ nodeIds, type: 'removeNodes' });@@ -884,15 +895,25 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {const onEdgesChange = useCallback((changes: EdgeChange<WorkflowFlowEdge>[]) => {+ // Selection changes already keep collapsed siblings together before XYFlow removes the selected edges.const removedEdgeIds = changes.flatMap((change) => (change.type === 'remove' ? [change.id] : []));-if (removedEdgeIds.length > 0) {editGraph({ edgeIds: removedEdgeIds, type: 'removeEdges' });}- setFlowModel((current) => (current ? { ...current, edges: applyEdgeChanges(changes, current.edges) } : current));+ setFlowModel((current) =>+ current+ ? {+ ...current,+ edges: applyEdgeChanges(+ withCollapsedGroupSelection(projectGraph, changes, current.edges) as EdgeChange<WorkflowFlowEdge>[],+ current.edges+ ),+ }+ : current+ );},- [editGraph]+ [editGraph, projectGraph]);// The edge whose end is being dragged; it must not count against its own reconnection.@@ -953,7 +974,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {(oldEdge: WorkflowFlowEdge, connection: Connection) => {const edge = toDocumentEdge(connection);- if (!edge) {+ // A collapsed edge is never reconnectable (see toFlowEdges); moving it would move one of the edges it draws for.+ if (!edge || oldEdge.data?.collapsedEdgeIds) {return;}@@ -980,7 +1002,13 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {reconnectingEdgeRef.current = null;- if (!reconnecting || reconnecting.edgeId !== edge.id || reconnecting.didReconnect || state.toHandle) {+ if (+ !reconnecting ||+ reconnecting.edgeId !== edge.id ||+ reconnecting.didReconnect ||+ state.toHandle ||+ edge.data?.collapsedEdgeIds+ ) {return;}@@ -1236,6 +1264,10 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {{opacity: 1,},+ // With a node selected, every edge it does not touch drops to a quarter so its own connections stand out.+ // Only the live flow, a direct child: the image export's offscreen flow sits in this box too.+ '&[data-node-selected] > .react-flow .react-flow__edge:not(.selected, .workflow-selected-node-edge, :hover) .react-flow__edge-path':+ { opacity: 0.25 },'& .react-flow__edge.workflow-selected-node-edge .react-flow__edge-path': {animation: 'dashdraw var(--wb-motion-duration-slow) linear var(--wb-motion-animation-iteration-count)',strokeDasharray: '5',@@ -1328,6 +1360,19 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {setContextMenu(null);}, [contextMenu, editGraph, templates]);+ // Keyed by the id list, so edits and moves that keep the node set hand the minimap the same array.+ const invocationNodeIdKey = useMemo(+ () =>+ projectGraph.nodes+ .filter((node) => node.type === 'invocation')+ .map((node) => node.id)+ .join('\n'),+ [projectGraph.nodes]+ );+ const invocationNodeIds = useMemo(+ () => (invocationNodeIdKey ? invocationNodeIdKey.split('\n') : []),+ [invocationNodeIdKey]+ );const updatableNodeCount = useMemo(() => getUpdatableNodeIds(projectGraph, templates).length,[projectGraph, templates]@@ -1376,6 +1421,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {ref={attachEditorElement}bg="bg.inset"css={editorCss}+ data-node-selected={selectedNodeIds.length > 0 ? '' : undefined}h="full"position="relative"w="full"@@ -1385,6 +1431,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {onPointerMove={onEditorPointerMove}{...pointerToolHandlers}>+ {flowInstance ? <WorkflowPngExportRegistration complete={onExportComplete} prepare={onExportPrepare} /> : null}<ReactFlow<WorkflowFlowNode, WorkflowFlowEdge>colorMode={getFlowColorMode(themeId)}connectionLineType={edgeType === 'step' ? ConnectionLineType.Step : ConnectionLineType.Bezier}@@ -1441,8 +1488,6 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {tool={tool}updatableNodeCount={updatableNodeCount}onArrangeNodes={onArrangeNodes}- onExportPrepare={onExportPrepare}- onExportComplete={onExportComplete}onNodeOpacityChange={setNodeOpacity}onRedo={redo}onToolChange={setTool}@@ -1451,7 +1496,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {/>{/* An empty graph's minimap is a bare panel that reads as a broken element. */}{workflowShowMinimap && projectGraph.nodes.length > 0 && (!isLargeGraph || isMinimapReady) ? (- <FlowMiniMap />+ <WorkflowEditorMiniMap nodeIds={invocationNodeIds} />) : null}</ReactFlow>{ExportView ? (@@ -1521,3 +1566,9 @@ export const WorkflowEditorView = ({ runtime }: { runtime: WorkflowRuntimeApi })</Flex>);};++/** Export becomes available only after the on-screen flow has initialized. */+const WorkflowPngExportRegistration = ({ complete, prepare }: Parameters<typeof registerWorkflowPngExportHost>[0]) => {+ useMountEffect(() => registerWorkflowPngExportHost({ complete, prepare }));+ return null;+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowImageExportView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowImageExportView.tsxindex b777df0f2d..2164278d38 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowImageExportView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowImageExportView.tsx@@ -15,15 +15,21 @@ export const WorkflowImageExportView = ({() => props.nodes?.map((node) => (node.selected ? { ...node, selected: false } : node)),[props.nodes]);+ // Every node draws open here, so every edge draws as itself: none hidden behind a collapsed edge, none merged.const edges = useMemo(() =>- props.edges?.map((edge) => ({- ...edge,- animated: undefined,- className: undefined,- selected: false,- style: undefined,- })),+ props.edges?.map(({ data, hidden: _hidden, ...edge }) => {+ const { collapsedEdgeIds: _collapsedEdgeIds, ...edgeData } = data ?? {};++ return {+ ...edge,+ animated: undefined,+ className: undefined,+ data: data ? (edgeData as typeof data) : data,+ selected: false,+ style: undefined,+ };+ }),[props.edges]);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.tsindex 905868d858..1ddd337e53 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.test.ts@@ -16,7 +16,15 @@ import {} from '@features/workflow/utility';import { describe, expect, it } from 'vitest';-import { getWorkflowEdgeData, toFlowEdges, toFlowNodes, withNodeSelection } from './flowAdapters';+import {+ getCollapsedEdgeLayout,+ getWorkflowEdgeData,+ toFlowEdges,+ toFlowNodes,+ withCollapsedEdgeSiblings,+ withCollapsedGroupSelection,+ withNodeSelection,+} from './flowAdapters';const single = (name: string): FieldType => ({ batch: false, cardinality: 'SINGLE', name });const collection = (name: string): FieldType => ({ batch: false, cardinality: 'COLLECTION', name });@@ -371,3 +379,133 @@ describe('flowAdapters identity preservation', () => {expect(highlighted[0]?.style).toEqual({ strokeWidth: 2 });});});++describe('collapsed edges', () => {+ const collapsed = (id: string): WorkflowInvocationNode => ({+ ...createNode(id),+ data: { ...createNode(id).data, isOpen: false },+ });+ // a and b are collapsed with two edges between them; c is open, fed by collapsed a.+ const doc = createDoc({+ edges: [createEdge('ab1', 'a', 'b'), createEdge('ab2', 'a', 'b', 'value', 'b2'), createEdge('ac', 'a', 'c')],+ nodes: [collapsed('a'), collapsed('b'), createNode('c')],+ });++ it('draws the edges between two collapsed nodes as one, with its count, and leaves the rest as they are', () => {+ const edges = toFlowEdges(doc, [], 'default', undefined, createTemplates());+ const byId = new Map(edges.map((edge) => [edge.id, edge]));++ expect(byId.get('ab1')?.hidden).toBeUndefined();+ expect(byId.get('ab1')?.data?.collapsedEdgeIds).toEqual(['ab1', 'ab2']);+ expect(byId.get('ab2')?.hidden).toBe(true);+ expect(byId.get('ac')?.hidden).toBeUndefined();+ expect(byId.get('ac')?.data?.collapsedEdgeIds).toBeUndefined();+ // Every flow edge keeps its document endpoints: collapsing changes only how they draw.+ expect(+ edges.map(({ id, source, sourceHandle, target, targetHandle }) => ({+ id,+ source,+ sourceHandle,+ target,+ targetHandle,+ }))+ ).toEqual(+ doc.edges.map(({ id, source, sourceHandle, target, targetHandle }) => ({+ id,+ source,+ sourceHandle,+ target,+ targetHandle,+ }))+ );+ });++ it('keeps each edge’s own type data, so a view drawing every node open draws it as itself', () => {+ const typed = toFlowEdges(doc, [], 'default', undefined, createTemplates());+ const open = toFlowEdges(+ { ...doc, nodes: [createNode('a'), createNode('b'), createNode('c')] },+ [],+ 'default',+ undefined,+ createTemplates()+ );++ for (const edge of typed) {+ const { collapsedEdgeIds: _collapsedEdgeIds, ...data } = edge.data ?? {};+ expect(data).toEqual(open.find((other) => other.id === edge.id)?.data);+ }+ });++ it('lets no end at a merged port be dragged, and keeps the open end of a single edge movable', () => {+ const fed = { ...doc, edges: [...doc.edges, createEdge('cb', 'c', 'b')] };+ const ends = new Map(+ toFlowEdges(fed, [], 'default', undefined, createTemplates()).map((edge) => [edge.id, edge.reconnectable])+ );++ expect(ends.get('ab1')).toBe(false);+ expect(ends.get('ab2')).toBe(false);+ expect(ends.get('ac')).toBe('target');+ expect(ends.get('cb')).toBe('source');+ expect(toFlowEdges(createDoc(), [], 'default', undefined, createTemplates())[0]?.reconnectable).toBeUndefined();+ });++ it('selects a group as one, so its drawn edge and the edges it stands for always agree', () => {+ // An edge selected while both nodes were open stays selected when they collapse: so is the rest of its group.+ const openDoc = { ...doc, nodes: [createNode('a'), createNode('b'), createNode('c')] };+ const selectedWhileOpen = toFlowEdges(openDoc).map((edge) => ({ ...edge, selected: edge.id === 'ab2' }));+ const collapsedEdges = toFlowEdges(doc, selectedWhileOpen);++ expect(collapsedEdges.filter((edge) => edge.selected).map((edge) => edge.id)).toEqual(['ab1', 'ab2']);+ expect(collapsedEdges.find((edge) => edge.id === 'ac')?.selected).toBe(false);+ });++ it('selects a group by its drawn edge, ignoring changes xyflow reports for the hidden edges', () => {+ const state = (selected: string[]) => ['ab1', 'ab2', 'ac'].map((id) => ({ id, selected: selected.includes(id) }));+ const select = (id: string, selected: boolean) => ({ id, selected, type: 'select' as const });++ expect(getCollapsedEdgeLayout(doc)).toBe(getCollapsedEdgeLayout(doc));+ // Selecting the drawn edge selects the edge it hides.+ expect(withCollapsedGroupSelection(doc, [select('ab1', true), select('ac', false)], state(['ac']))).toEqual([+ select('ab1', true),+ select('ac', false),+ select('ab2', true),+ ]);+ // Clicking the selected drawn edge again: xyflow reports only the hidden edge's deselect. The group stays.+ expect(withCollapsedGroupSelection(doc, [select('ab2', false)], state(['ab1', 'ab2']))).toEqual([]);+ // Clicking the drawn edge while the group is half selected (a hidden edge selected with others): xyflow selects it+ // and deselects the rest, the hidden edge among them. That deselect is dropped: the group is selected, the rest not.+ expect(+ withCollapsedGroupSelection(+ doc,+ [select('ab1', true), select('ab2', false), select('ac', false)],+ state(['ab2', 'ac'])+ )+ ).toEqual([select('ab1', true), select('ac', false)]);+ // Clearing everything deselects the drawn edge, and so the group.+ expect(+ withCollapsedGroupSelection(+ doc,+ [select('ab1', false), select('ab2', false), select('ac', false)],+ state(['ab1', 'ab2', 'ac'])+ )+ ).toEqual([select('ab1', false), select('ac', false), select('ab2', false)]);+ // Nothing collapsed: the changes pass through.+ const open = [select('e1', true)];+ expect(withCollapsedGroupSelection(createDoc(), open, [{ id: 'e1', selected: false }])).toEqual(open);+ });++ it('restores every edge when either node opens', () => {+ const opened = { ...doc, nodes: [createNode('a'), collapsed('b'), createNode('c')] };+ const edges = toFlowEdges(opened, toFlowEdges(doc), 'default', undefined, createTemplates());++ expect(edges.every((edge) => edge.hidden === undefined && edge.data?.collapsedEdgeIds === undefined)).toBe(true);+ });++ it('widens a collapsed edge to every edge it stands for, and leaves other edges alone', () => {+ expect(withCollapsedEdgeSiblings(doc, ['ab2'])).toEqual(['ab1', 'ab2']);+ expect(withCollapsedEdgeSiblings(doc, ['ac', 'ab1'])).toEqual(['ac', 'ab1', 'ab2']);+ expect(+ withCollapsedEdgeSiblings({ ...doc, nodes: [createNode('a'), collapsed('b'), createNode('c')] }, ['ab1'])+ ).toEqual(['ab1']);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.tsindex 32f9c72cc2..bb605eb5e4 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts@@ -9,6 +9,7 @@ import type {WorkflowCurrentImageNode,WorkflowEdge,WorkflowInvocationNode,+ WorkflowNode,WorkflowNotesNode,} from '@features/workflow/contracts';import type { Edge as FlowEdge, Node as FlowNode } from '@xyflow/react';@@ -352,6 +353,11 @@ export type WorkflowFlowEdgeType = FlowEdgeType | 'loop_linkage';/** The edge component names the edge from these facts, so the copy follows the UI language. */export interface WorkflowEdgeData extends Record<string, unknown> {+ /**+ * Set on the one edge drawn between two collapsed nodes: every document edge it stands for, itself first. The rest+ * are hidden, and selecting or deleting the drawn edge acts on all of them.+ */+ collapsedEdgeIds?: string[];/** The carried field type's name; null for a loop linkage or a type no template declares. */fieldTypeLabel: string | null;pathType: FlowEdgeType;@@ -431,6 +437,7 @@ export const getWorkflowEdgeData = (};const isSameEdgeData = (a: WorkflowEdgeData | undefined, b: WorkflowEdgeData): boolean =>+ sameNames(a?.collapsedEdgeIds ?? EMPTY_NAMES, b.collapsedEdgeIds ?? EMPTY_NAMES) &&a?.fieldTypeLabel === b.fieldTypeLabel &&a.isBatch === b.isBatch &&a.isLoopLinkage === b.isLoopLinkage &&@@ -439,6 +446,155 @@ const isSameEdgeData = (a: WorkflowEdgeData | undefined, b: WorkflowEdgeData): ba.strokeDasharray === b.strokeDasharray &&a.strokeWidth === b.strokeWidth;+const isCollapsedInvocation = (node: WorkflowNode | undefined): boolean =>+ node?.type === 'invocation' && !node.data.isOpen;++/** How collapsed nodes reshape a document's edges in the editor; the document itself is never changed. */+export interface CollapsedEdgeLayout {+ /** Nodes drawn collapsed. */+ collapsedNodeIds: ReadonlySet<string>;+ /**+ * Each edge between two collapsed nodes, keyed to every edge between the same pair in document order (legacy's+ * collapsed edge). The first draws for all of them; selecting or deleting any acts on all.+ */+ groupByEdge: ReadonlyMap<string, readonly string[]>;+}++const NO_COLLAPSED_EDGES: CollapsedEdgeLayout = { collapsedNodeIds: new Set(), groupByEdge: new Map() };+const collapsedEdgeLayoutCache = new WeakMap<+ ProjectGraphState['nodes'],+ { edges: ProjectGraphState['edges']; layout: CollapsedEdgeLayout }+>();++/** Cached per document nodes and edges, which change identity only when the graph changes. */+export const getCollapsedEdgeLayout = (document: Pick<ProjectGraphState, 'edges' | 'nodes'>): CollapsedEdgeLayout => {+ const cached = collapsedEdgeLayoutCache.get(document.nodes);++ if (cached?.edges === document.edges) {+ return cached.layout;+ }++ const collapsedNodeIds = new Set(document.nodes.filter(isCollapsedInvocation).map((node) => node.id));+ const groups = new Map<string, string[]>();++ if (collapsedNodeIds.size > 0) {+ for (const edge of document.edges) {+ if (edge.type !== 'loop_linkage' && collapsedNodeIds.has(edge.source) && collapsedNodeIds.has(edge.target)) {+ const key = `${edge.source}\u0000${edge.target}`;+ const group = groups.get(key);++ if (group) {+ group.push(edge.id);+ } else {+ groups.set(key, [edge.id]);+ }+ }+ }+ }++ const groupByEdge = new Map<string, readonly string[]>();++ for (const ids of groups.values()) {+ for (const id of ids) {+ groupByEdge.set(id, ids);+ }+ }++ const layout = collapsedNodeIds.size > 0 ? { collapsedNodeIds, groupByEdge } : NO_COLLAPSED_EDGES;+ collapsedEdgeLayoutCache.set(document.nodes, { edges: document.edges, layout });++ return layout;+};++/** Edge ids widened to every document edge a collapsed edge stands for, so selection and deletion act on all. */+export const withCollapsedEdgeSiblings = (+ document: Pick<ProjectGraphState, 'edges' | 'nodes'>,+ edgeIds: readonly string[]+): string[] => {+ const { groupByEdge } = getCollapsedEdgeLayout(document);++ return groupByEdge.size === 0 ? [...edgeIds] : [...new Set(edgeIds.flatMap((id) => groupByEdge.get(id) ?? [id]))];+};++/**+ * Edge changes with each collapsed group selected as one. A group follows its drawn edge: its state after this batch+ * (its current state, or the change addressed to it) goes to every member. Changes addressed to hidden members are+ * dropped: xyflow reports them only because their state differs, as when a click re-selects the drawn edge and+ * xyflow deselects everything else, so they would otherwise overturn the drawn edge. One lookup per call; the changes+ * pass through untouched when nothing is collapsed.+ */+export const withCollapsedGroupSelection = <Change extends { id?: string; type: string }>(+ document: Pick<ProjectGraphState, 'edges' | 'nodes'>,+ changes: readonly Change[],+ edges: readonly { id: string; selected?: boolean }[]+): (Change | { id: string; selected: boolean; type: 'select' })[] => {+ const { groupByEdge } = getCollapsedEdgeLayout(document);++ if (groupByEdge.size === 0 || !changes.some((change) => change.type === 'select')) {+ return [...changes];+ }++ const drawnChanges = new Map<string, boolean>();+ const touchedGroups = new Set<readonly string[]>();+ const kept = changes.filter((change) => {+ const group = change.type === 'select' && change.id !== undefined ? groupByEdge.get(change.id) : undefined;++ if (!group) {+ return true;+ }++ touchedGroups.add(group);++ if (group[0] === change.id) {+ drawnChanges.set(change.id, (change as unknown as { selected: boolean }).selected);+ return true;+ }++ return false;+ });++ if (touchedGroups.size === 0) {+ return kept;+ }++ const isSelected = new Map(edges.map((edge) => [edge.id, edge.selected ?? false]));+ const memberChanges: { id: string; selected: boolean; type: 'select' }[] = [];++ for (const group of touchedGroups) {+ const drawnId = group[0]!;+ const selected = drawnChanges.get(drawnId) ?? isSelected.get(drawnId) ?? false;++ for (const id of group.slice(1)) {+ if ((isSelected.get(id) ?? false) !== selected) {+ memberChanges.push({ id, selected, type: 'select' });+ }+ }+ }++ return [...kept, ...memberChanges];+};++/**+ * Which ends of an edge may be dragged to reconnect it. An end at a collapsed node's merged port stays put, as legacy's+ * did: that port stands for every field, so a drag there could not say which connection moves, and an edge between two+ * collapsed nodes may stand for several connections. The end at an open node still moves, as one ordinary edge.+ */+const getReconnectableEnds = (+ edge: WorkflowEdge,+ collapsedNodeIds: ReadonlySet<string>+): WorkflowFlowEdge['reconnectable'] => {+ const isSourceCollapsed = collapsedNodeIds.has(edge.source);+ const isTargetCollapsed = collapsedNodeIds.has(edge.target);++ return isSourceCollapsed && isTargetCollapsed+ ? false+ : isSourceCollapsed+ ? 'target'+ : isTargetCollapsed+ ? 'source'+ : undefined;+};+export const toFlowEdges = (document: ProjectGraphState,previousEdges: WorkflowFlowEdge[] = [],@@ -449,10 +605,20 @@ export const toFlowEdges = (index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges)): WorkflowFlowEdge[] => {const previousById = new Map(previousEdges.map((edge) => [edge.id, edge]));+ const { collapsedNodeIds, groupByEdge } = getCollapsedEdgeLayout(document);return getEdgesWithLoopLinkageAliases(document.nodes, document.edges).map((edge) => {const previous = previousById.get(edge.id);- const data = getWorkflowEdgeData(document, edge, edgeType, templates, index);+ const collapsedGroup = groupByEdge.get(edge.id);+ const hidden = collapsedGroup !== undefined && collapsedGroup[0] !== edge.id ? true : undefined;+ const typedData = getWorkflowEdgeData(document, edge, edgeType, templates, index);+ // The edge keeps its own type data, so a view drawing every node open (the image export) draws it as itself.+ const data: WorkflowEdgeData = collapsedGroup ? { ...typedData, collapsedEdgeIds: [...collapsedGroup] } : typedData;+ const reconnectable = getReconnectableEnds(edge, collapsedNodeIds);+ // A group is selected as one: its drawn edge and the edges it stands for always agree.+ const selected = collapsedGroup+ ? collapsedGroup.some((id) => previousById.get(id)?.selected)+ : (previous?.selected ?? false);const flowType: WorkflowFlowEdgeType = edge.type === 'loop_linkage' ? 'loop_linkage' : edgeType;const isConnectedToSelectedNode = selectedNodeIds.has(edge.source) || selectedNodeIds.has(edge.target);const animated = isConnectedToSelectedNode && !reduceMotion ? true : undefined;@@ -468,6 +634,9 @@ export const toFlowEdges = (previous.targetHandle === edge.targetHandle &&previous.animated === animated &&previous.className === className &&+ previous.hidden === hidden &&+ previous.reconnectable === reconnectable &&+ (previous.selected ?? false) === selected &&isSameEdgeData(previous.data, data) &&previous.style === style) {@@ -479,7 +648,9 @@ export const toFlowEdges = (animated,className,data,- selected: previous?.selected ?? false,+ hidden,+ reconnectable,+ selected,source: edge.source,sourceHandle: edge.sourceHandle,style,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/nodeStatusText.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/nodeStatusText.tsnew file mode 100644index 0000000000..44846b8d40--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/nodeStatusText.ts@@ -0,0 +1,49 @@+import type { FieldInputTemplate, WorkflowInvocationNode } from '@features/workflow/contracts';+import type { WorkflowNodeExecutionState as NodeExecutionState } from '@features/workflow/ui/contracts';+import type { TFunction } from 'i18next';++import { isModelFieldType, type WorkflowFieldIssue } from '@features/workflow/utility';++/** A node's status wording, shared by its header (labels) and its status panel, which loads on first open. */++/** A field that keeps its node from running, named as the node shows it. */+export interface InvocationNodeFieldIssue {+ issue: WorkflowFieldIssue;+ label: string;+ /** The rows the issue marks: its own, or both HiDiffusion ratios for their order. */+ markedFieldNames: readonly string[];+ template: FieldInputTemplate;+}++export const getNodeExecutionError = (+ node: WorkflowInvocationNode,+ error: string | null | undefined,+ translate: (key: string, options: { error: string }) => string+): string | null | undefined => {+ if (!error || node.data.type !== 'call_saved_workflow') {+ return error;+ }++ return translate('nodes.childWorkflowError', { error });+};++const getProgressPercent = (execution: NodeExecutionState): number | null =>+ execution.progress === null ? null : Math.round(execution.progress * 100);++/** What a field needs, in words: a model to pick, a value, a connection, or what its value breaks. */+export const getFieldIssueMessage = (t: TFunction, { issue, label, template }: InvocationNodeFieldIssue): string =>+ issue.kind === 'missingValue'+ ? t(isModelFieldType(template.type) ? 'nodes.status.pickModel' : 'nodes.status.fieldRequired', { field: label })+ : issue.kind === 'missingConnection'+ ? t('nodes.status.needsConnection', { field: label })+ : t('nodes.status.fieldInvalid', { field: label, reason: issue.reason });++export const getExecutionStatusText = (t: TFunction, execution: NodeExecutionState): string => {+ if (execution.status === 'running') {+ const percent = getProgressPercent(execution);++ return percent === null ? t('nodes.status.running') : t('nodes.status.runningProgress', { percent });+ }++ return execution.status === 'completed' ? t('nodes.executionCompleted') : t('nodes.executionFailed');+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.tsindex 199f31c465..8ede22f1d4 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowImageExport.ts@@ -486,12 +486,13 @@ const prepareExportClone = (clone: HTMLElement, bounds: Rect, plan: WorkflowImag.forEach((element) => {setExportElementStyle(element, 'display', 'none');});+ // Chakra names a flat dotted token's variable with the dot escaped (`bg.emphasized` -> `--chakra-colors-bg\.emphasized`).clone.querySelectorAll<HTMLElement>('[data-workflow-node-shell="true"]').forEach((element) => {- setExportElementStyle(element, 'border-color', 'var(--chakra-colors-border-emphasized)');+ setExportElementStyle(element, 'border-color', 'var(--chakra-colors-border\\.emphasized)');setExportElementStyle(element, 'box-shadow', 'var(--chakra-shadows-sm)');});clone.querySelectorAll<HTMLElement>('[data-connector-node-body="true"]').forEach((element) => {- setExportElementStyle(element, 'background-color', 'var(--chakra-colors-bg-emphasized)');+ setExportElementStyle(element, 'background-color', 'var(--chakra-colors-bg\\.emphasized)');});clone.querySelectorAll<HTMLElement>('[data-connector-node-icon="true"]').forEach((element) => {setExportElementStyle(element, 'color', 'var(--chakra-colors-fg)');diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowPngExport.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowPngExport.tsnew file mode 100644index 0000000000..61d0e16d32--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowPngExport.ts@@ -0,0 +1,71 @@+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';+import type { TFunction } from 'i18next';++import { createExternalStore } from '@platform/state/externalStore';+import { flushSync } from 'react-dom';++import { getWorkflowFlowInstance } from './flowInstanceStore';++/**+ * "Download workflow as PNG", shared by the editor toolbar and the widget's actions menu. The mounted editor lends the+ * offscreen view the image is drawn from; while none is mounted (the form alone is shown) the download is unavailable.+ * One export runs at a time from either entry point.+ */+export interface WorkflowPngExportHost {+ /** Mounts the offscreen full-graph view and returns its flow element. */+ prepare: () => Promise<HTMLElement>;+ /** Unmounts that view. */+ complete: () => void;+}++const exportStore = createExternalStore<{ host: WorkflowPngExportHost | null; isExporting: boolean }>({+ host: null,+ isExporting: false,+});++/** Registered by the editor for as long as it is mounted; the returned function releases it. */+export const registerWorkflowPngExportHost = (host: WorkflowPngExportHost): (() => void) => {+ exportStore.patchSnapshot({ host });++ return () => {+ if (exportStore.getSnapshot().host === host) {+ exportStore.patchSnapshot({ host: null });+ }+ };+};++export const useWorkflowPngExportState = () =>+ exportStore.useSelector((snapshot) => ({ isAvailable: snapshot.host !== null, isExporting: snapshot.isExporting }));++/**+ * Draws the active workflow to a PNG and downloads it, reporting refusals and reductions. The drawing loads on first+ * use, so this store stays small enough for the menus that start an export to load it at startup. Resolves once the+ * busy state has been cleared and rendered, so a caller can hand focus back to a control the busy state disabled.+ */+export const exportWorkflowPng = async ({+ notifications,+ t,+ workflowName,+}: {+ notifications: WorkflowUiAdapter['notifications'];+ t: TFunction;+ workflowName: string;+}): Promise<void> => {+ const { host, isExporting } = exportStore.getSnapshot();+ const flow = getWorkflowFlowInstance();++ if (isExporting || !host || !flow) {+ return;+ }++ exportStore.patchSnapshot({ isExporting: true });+ try {+ const { runWorkflowPngExport } = await import('./workflowPngExportRun');+ await runWorkflowPngExport({ bounds: flow.getNodesBounds(flow.getNodes()), host, notifications, t, workflowName });+ } catch {+ notifications.error(t('widgets.workflow.exportImageFailed'));+ } finally {+ flushSync(() => exportStore.patchSnapshot({ isExporting: false }));+ host.complete();+ }+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowPngExportRun.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowPngExportRun.tsnew file mode 100644index 0000000000..1db1b443a7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowPngExportRun.ts@@ -0,0 +1,57 @@+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';+import type { Rect } from '@xyflow/react';+import type { TFunction } from 'i18next';++import type { WorkflowPngExportHost } from './workflowPngExport';++import { exportWorkflowAsPng, preflightWorkflowImageExport } from './workflowImageExport';++const waitForExportFrame = () =>+ new Promise<void>((resolve) => {+ if (document.visibilityState === 'hidden') {+ window.setTimeout(resolve, 0);+ } else {+ window.requestAnimationFrame(() => resolve());+ }+ });++/**+ * The download `exportWorkflowPng` starts: refuses from the live editor's bounds before mounting the whole graph a+ * second time, draws it from the host's offscreen view, and reports the outcome. Unexpected failures reject.+ */+export const runWorkflowPngExport = async ({+ bounds,+ host,+ notifications,+ t,+ workflowName,+}: {+ bounds: Rect;+ host: WorkflowPngExportHost;+ notifications: WorkflowUiAdapter['notifications'];+ t: TFunction;+ workflowName: string;+}): Promise<void> => {+ let outcome = preflightWorkflowImageExport(bounds);+ if (!outcome) {+ const flowElement = await host.prepare();+ await waitForExportFrame();+ await waitForExportFrame();+ outcome = await exportWorkflowAsPng({+ bounds,+ fallbackWorkflowName: t('widgets.workflow.untitled'),+ flowElement,+ workflowName,+ });+ }+ if (outcome.status === 'busy') {+ notifications.info(t('widgets.workflow.exportImageBusy'));+ } else if (outcome.status === 'too-large') {+ notifications.error(t('widgets.workflow.exportImageTooLarge'), t('widgets.workflow.exportImageTooLargeDetail'));+ } else if (outcome.status === 'exported' && outcome.reduced) {+ notifications.info(+ t('widgets.workflow.exportImageReduced'),+ t('widgets.workflow.exportImageReducedDetail', { height: outcome.height, width: outcome.width })+ );+ }+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsxindex 537c3cca84..504ad4f782 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/FieldDescriptionPopover.tsx@@ -14,12 +14,15 @@ export const FieldDescriptionPopover = ({description,fieldName,nodeId,+ size = 'sm',templateDescription,}: {/** The current override, if any. */description: string | undefined;fieldName: string;nodeId: string;+ /** Node rows use `xs` to sit in their 20px label line; the form builder's card header uses `sm` like its other actions. */+ size?: 'sm' | 'xs';templateDescription: string;}) => {const { t } = useTranslation();@@ -45,7 +48,7 @@ export const FieldDescriptionPopover = ({aria-label={editLabel}className="nodrag"color={description ? 'accent.solid' : 'fg.subtle'}- size="sm"+ size={size}variant="ghost"><Icon as={FileTextIcon} boxSize="3" />diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex e91da8df82..16beb426c3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -2128,6 +2128,8 @@ export const WorkflowFieldSnapshot = ({if (template.type.name === 'StringField') {return (<Box+ // The node row's value well, so the export matches the editor.+ bg="var(--wb-control-well, transparent)"borderColor="border"borderRadius="control"borderWidth="1px"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsxindex 7482d405b0..fa2ab8f647 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/FlowMiniMap.tsx@@ -1,14 +1,27 @@+import type { ComponentProps } from 'react';+import { chakra } from '@chakra-ui/react';import { MiniMap } from '@xyflow/react';/** Style the MiniMap frame with Chakra tokens and its SVG fills with flowTheme variables. */const StyledMiniMap = chakra(MiniMap);-export const FlowMiniMap = () => (+/** Minimap node classes a caller may set; each tints the node in a state colour. */+export const FLOW_MINIMAP_ERROR_CLASS = 'workflow-minimap-error';+export const FLOW_MINIMAP_RUNNING_CLASS = 'workflow-minimap-running';++const MINIMAP_STATE_CSS = {+ [`& .react-flow__minimap-node.${FLOW_MINIMAP_ERROR_CLASS}`]: { fill: '{colors.border.error}' },+ [`& .react-flow__minimap-node.${FLOW_MINIMAP_RUNNING_CLASS}`]: { fill: '{colors.accent.solid}' },+};++export const FlowMiniMap = ({ nodeClassName }: Pick<ComponentProps<typeof MiniMap>, 'nodeClassName'>) => (<StyledMiniMapborderColor="border.subtle"borderWidth="1px"+ css={MINIMAP_STATE_CSS}m="3"+ nodeClassName={nodeClassName}overflow="hidden"pannableposition="bottom-right"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsxindex 62533d2a12..bcb817b373 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx@@ -1,5 +1,10 @@-import type { InvocationTemplatesSnapshot } from '@features/workflow/core/types';import type {+ InvocationTemplatesSnapshot,+ ProjectGraphState,+ WorkflowInvocationNode,+} from '@features/workflow/core/types';+import type {+ GraphPreviewInvoke,GraphPreviewSourceState,WorkflowInvocationSourceId,WorkflowPreviewGraph,@@ -13,16 +18,17 @@ import {} from '@features/workflow/ui/library/useWorkflowPublication';import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';import { createProjectGraph } from '@features/workflow/utility';+import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';import { system } from '@theme/system';import { act, StrictMode } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { page } from 'vitest/browser';+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';import { GraphPreviewDialog } from './GraphPreviewDialog';// Create mock dependencies with vi.hoisted because factories run before ordinary imports.-const { downloads, fitViewMock, TEMPLATES_SNAPSHOT, templatesSnapshotRef } = vi.hoisted(() => {+const { clipboard, downloads, TEMPLATES_SNAPSHOT, templatesSnapshotRef } = vi.hoisted(() => {const fieldInput = (name: string, defaultValue: unknown) => ({default: defaultValue,description: '',@@ -46,7 +52,7 @@ const { downloads, fitViewMock, TEMPLATES_SNAPSHOT, templatesSnapshotRef } = vi.uiModelType: null,uiOrder: null,});- const invocationTemplate = (type: string, inputs: Record<string, ReturnType<typeof fieldInput>>) => ({+ const invocationTemplate = (type: string, title: string, inputs: Record<string, ReturnType<typeof fieldInput>>) => ({category: 'test',classification: 'stable',description: '',@@ -55,7 +61,7 @@ const { downloads, fitViewMock, TEMPLATES_SNAPSHOT, templatesSnapshotRef } = vi.outputs: {},outputType: `${type}_output`,tags: [],- title: type,+ title,type,useCache: true,version: '1.0.0',@@ -68,44 +74,61 @@ const { downloads, fitViewMock, TEMPLATES_SNAPSHOT, templatesSnapshotRef } = vi.error: null,status: 'loaded',templates: {- denoise_latents: invocationTemplate('denoise_latents', {+ denoise_latents: invocationTemplate('denoise_latents', 'Denoise Latents', {cfg_scale: fieldInput('cfg_scale', 7),+ seed: fieldInput('seed', 0),steps: fieldInput('steps', 30),}),- integer: invocationTemplate('integer', { value: fieldInput('value', 0) }),- l2i: invocationTemplate('l2i', {}),+ integer: invocationTemplate('integer', 'Integer Primitive', { value: fieldInput('value', 0) }),+ l2i: invocationTemplate('l2i', 'Latents to Image', {}),+ sdxl_compel: invocationTemplate('sdxl_compel', 'SDXL Positive Conditioning', {}),},};return {+ clipboard: { canCopyText: vi.fn(() => true), copyText: vi.fn(() => Promise.resolve()) },downloads: { downloadBlob: vi.fn(), downloadText: vi.fn() },- // Provide an initialized flow spy to verify pending reveals actually call fitView.- fitViewMock: vi.fn(() => Promise.resolve(true)),TEMPLATES_SNAPSHOT: templatesSnapshot,- templatesSnapshotRef: { current: templatesSnapshot },+ templatesSnapshotRef: { current: templatesSnapshot, listeners: new Set<() => void>() },};});-// Stub flow rendering but retain onInit to exercise the dialog's pending-reveal handoff.-vi.mock('./GraphPreviewFlow', () => ({- GraphPreviewFlow: ({ onInit }: { onInit?: (instance: { fitView: typeof fitViewMock }) => void }) => {- onInit?.({ fitView: fitViewMock });- return <div data-flow-stub />;- },- documentToPreviewGraph: () => {- throw new Error('not used');- },-}));-vi.mock('@platform/browser/downloadBlob', () => downloads);+vi.mock('@platform/browser/clipboard', () => clipboard);-// Stub reactive templates so Open as disabled state follows the same loading contract as production.-vi.mock('@features/workflow/react', async (importOriginal) => ({+// The node card's model markers read the catalog; this suite's graphs need no model.+vi.mock('@features/models', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),- getInvocationTemplatesSnapshot: () => templatesSnapshotRef.current,- useInvocationTemplatesSnapshot: () => templatesSnapshotRef.current,+ ensureModelsLoaded: vi.fn(() => Promise.resolve()),+ ensureStartersLoaded: vi.fn(),+ useActiveInstallSources: () => new Set<string>(),+ useModelsSelector: (selector: (snapshot: unknown) => unknown) => selector({ models: [] }),+ useStartersSelector: (selector: (snapshot: unknown) => unknown) => selector({ response: { starter_models: [] } }),}));+// A store like production's, so the menu's disabled state follows the templates loading.+vi.mock('@features/workflow/react', async (importOriginal) => {+ const { useSyncExternalStore } = await import('react');+ const subscribe = (listener: () => void) => {+ templatesSnapshotRef.listeners.add(listener);++ return () => templatesSnapshotRef.listeners.delete(listener);+ };+ const getSnapshot = () => templatesSnapshotRef.current;++ return {+ ...(await importOriginal<Record<string, unknown>>()),+ getInvocationTemplatesSnapshot: getSnapshot,+ useInvocationTemplatesSnapshot: () => useSyncExternalStore(subscribe, getSnapshot),+ };+});++const setTemplatesSnapshot = (snapshot: InvocationTemplatesSnapshot) =>+ act(() => {+ templatesSnapshotRef.current = snapshot;+ templatesSnapshotRef.listeners.forEach((listener) => listener());+ });+const identity = vi.hoisted(() => ({session: { multiuserEnabled: false, phase: 'ready', user: null } as {multiuserEnabled: boolean;@@ -134,48 +157,35 @@ vi.mock('@features/workflow/data/api', async (importOriginal) => ({// Supply rendered English strings without starting the HTTP-backed i18n client.const TRANSLATIONS: Record<string, string> = {'common.close': 'Close',- 'common.json': 'JSON',- 'graphPreview.back': 'Back',- 'graphPreview.compiledFrom': 'Compiled from {{source}}.',- 'graphPreview.copied': 'Copied',+ 'graphPreview.aboutThisGraph': 'About this graph',+ 'graphPreview.cannotInvoke': "Can't invoke yet",+ 'graphPreview.editAsWorkflow': 'Edit as workflow',+ 'graphPreview.readyToInvoke': 'Ready to invoke',+ 'workflowLibrary.preview.graph': 'Graph',+ 'workflowLibrary.preview.graphJson': 'Graph JSON',+ 'workflowLibrary.preview.nodes': 'Nodes','graphPreview.copyFailed': 'Failed to copy JSON',- 'graphPreview.copyJson': 'Copy JSON',+ 'graphPreview.copyGraphJson': 'Copy graph JSON','graphPreview.destination': 'Destination',- 'graphPreview.downloadJson': 'Download JSON',- 'graphPreview.downloadJsonHint': 'For bug reports and sharing',- 'graphPreview.edges': 'Edges',- 'graphPreview.edgesIn': 'in · {{count}} inputs from {{sources}}',- 'graphPreview.edgesInNone': 'in · none',- 'graphPreview.edgesOut': 'out · {{field}} → {{target}}',+ 'graphPreview.downloadGraphJson': 'Download graph JSON','graphPreview.editInEditor': 'Edit in workflow editor','graphPreview.editInEditorFailed': 'No editable nodes in this graph.',- 'graphPreview.editInEditorHint': 'Replaces the current workflow','graphPreview.forkIntoProject': 'Fork into new project','graphPreview.forkIntoProjectFailed': 'No nodes to fork into a project.',- 'graphPreview.forkIntoProjectHint': 'Copies this graph into a fresh project',- 'graphPreview.graph': 'Graph',- 'graphPreview.graphJsonLabel': '{{title}} graph JSON',- 'graphPreview.inputCount': '{{count}} inputs',+ 'graphPreview.graphJsonCopied': 'Graph JSON copied','graphPreview.invalidTitle': "This graph can't compile yet.",- 'graphPreview.invokeRoute': 'Invoke {{route}}',- 'graphPreview.list': 'List','graphPreview.liveHint': 'Updates as you change settings.',+ 'graphPreview.more': 'More','graphPreview.noCompiledGraph': 'No compiled graph is available for "{{graphId}}" yet.',- 'graphPreview.nodeSummary.denoise': '{{steps}} steps · cfg {{cfg}}',- 'graphPreview.nodeSummary.noise': '{{width}} × {{height}}',- 'graphPreview.nodes': 'Nodes',- 'graphPreview.openAs': 'Open as',+ 'graphPreview.nodeSummary.denoise': '{{count}} steps · cfg {{cfg}}','graphPreview.openedFromPreview': 'Opened from graph preview',- 'graphPreview.resolvedInputs': 'Resolved inputs',- 'graphPreview.savedToLibrary': 'Saved to workflow library','graphPreview.saveToLibrary': 'Save to workflow library','graphPreview.saveToLibraryFailed': 'No saveable nodes in this graph.',- 'graphPreview.saveToLibraryHint': 'Reusable, leaves this project alone',- 'graphPreview.selectNode': 'Select a node for details.',- 'graphPreview.setBy': 'Set by',- 'graphPreview.showNode': 'show node',- 'graphPreview.thisGraph': 'This graph',- 'graphPreview.title': 'Graph preview',+ 'graphPreview.showNode': 'Show node',+ 'workflowLibrary.preview.inputs': 'Inputs',+ 'workflowLibrary.preview.nodePackMissing': 'Node pack missing',+ 'workflowLibrary.preview.valueNumber': '{{value}}',+ 'workflowLibrary.preview.youSetThis': 'You set this','workflowLibrary.publicVisibilityHelp': 'Visible to users of this InvokeAI instance.','workflowLibrary.publicVisibilityPartial':'The template was saved, but its public visibility could not be confirmed ({{message}}). Retry to make it public.',@@ -199,6 +209,7 @@ vi.mock('react-i18next', () => ({(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;const FIXTURE_GRAPH: WorkflowPreviewGraph = {+ backendGraph: { edges: [], id: 'backend-graph', nodes: { denoise_latents: { type: 'denoise_latents' } } },id: 'preview-graph',nodes: [{ id: 'seed', type: 'integer', inputs: { value: 42 } },@@ -218,6 +229,7 @@ const FIXTURE_GRAPH: WorkflowPreviewGraph = {version: 1,};+/** Generate's shape: compiled, live, with facts, a notice, a value that is not what runs and fields it set. */const FIXTURE_SOURCE: GraphPreviewSourceState = {destinationLabel: 'Gallery',getProvenance: (nodeId, fieldName) => {@@ -225,10 +237,6 @@ const FIXTURE_SOURCE: GraphPreviewSourceState = {return { label: 'Generate → Steps' };}- if (nodeId === 'denoise_latents' && fieldName === 'cfg_scale') {- return { label: 'Generate → CFG scale' };- }-return null;},graph: FIXTURE_GRAPH,@@ -244,8 +252,18 @@ const FIXTURE_SOURCE: GraphPreviewSourceState = {],};-/** A library entry: previewed before it has been opened into a project, so nothing has routed it anywhere. */-const NO_DESTINATION_SOURCE: GraphPreviewSourceState = {+/** The same source recompiled: `steps` changed, or the decoder gone. */+const withGraph = (graph: WorkflowPreviewGraph): GraphPreviewSourceState => ({ ...FIXTURE_SOURCE, graph });+const withSteps = (steps: number) =>+ withGraph({+ ...FIXTURE_GRAPH,+ nodes: FIXTURE_GRAPH.nodes.map((node) =>+ node.id === 'denoise_latents' ? { ...node, inputs: { ...node.inputs, steps } } : node+ ),+ });++/** A widget's last graph: nothing set, nothing live, routed nowhere. */+const PLAIN_SOURCE: GraphPreviewSourceState = {destinationLabel: null,graph: FIXTURE_GRAPH,invalidReasons: [],@@ -263,40 +281,61 @@ const INVALID_SOURCE: GraphPreviewSourceState = {summaryRows: [],};-// An unknown-only graph converts to an empty document; document-opening actions must stop.+// An unknown-only graph still draws; it converts to an empty document, so document-opening actions must stop.const UNKNOWN_NODE_GRAPH: WorkflowPreviewGraph = {id: 'unknown-node-graph',- nodes: [{ id: 'mystery', type: 'unknown_type', inputs: {} }],+ nodes: [{ id: 'mystery', type: 'unknown_type', inputs: { strength: 3 } }],edges: [],version: 1,};-const UNKNOWN_NODE_SOURCE: GraphPreviewSourceState = {- destinationLabel: 'Gallery',- graph: UNKNOWN_NODE_GRAPH,- invalidReasons: [],- isLive: false,- notices: [],- summaryRows: [],-};+const UNKNOWN_NODE_SOURCE: GraphPreviewSourceState = { ...PLAIN_SOURCE, graph: UNKNOWN_NODE_GRAPH };-// Long enough to exercise the side panel's ~40-char truncation policy for-// resolved-input strings.-const LONG_STRING_VALUE =- 'a value long enough to need truncation in the resolved inputs list, well past forty characters';+const invocation = (id: string, type: string, inputs: Record<string, unknown>, label = ''): WorkflowInvocationNode => ({+ data: {+ inputs: Object.fromEntries(Object.entries(inputs).map(([name, value]) => [name, { label: '', name, value }])),+ isIntermediate: true,+ isOpen: true,+ label,+ nodePack: 'invokeai',+ notes: '',+ type,+ useCache: true,+ version: '1.0.0',+ },+ id,+ position: { x: 0, y: 0 },+ type: 'invocation',+});-const LONG_VALUE_GRAPH: WorkflowPreviewGraph = {- id: 'long-value-graph',- nodes: [{ id: 'note', type: 'integer', inputs: { value: LONG_STRING_VALUE } }],- edges: [],- version: 1,+/** The workflow surface's shape: the document the graph compiles from, its form exposing the steps. */+const DOCUMENT: ProjectGraphState = {+ ...createProjectGraph('workflow-doc', 'Portrait workflow'),+ form: {+ elements: {+ root: { data: { children: ['steps-field'], layout: 'column' }, id: 'root', type: 'container' },+ 'steps-field': {+ data: {+ fieldIdentifier: { fieldName: 'steps', nodeId: 'denoise_latents' },+ showDescription: false,+ showShuffle: false,+ },+ id: 'steps-field',+ parentId: 'root',+ type: 'node-field',+ },+ },+ rootElementId: 'root',+ },+ nodes: [invocation('denoise_latents', 'denoise_latents', { cfg_scale: 4, steps: 28 }, 'Sampler')],};-const LONG_VALUE_SOURCE: GraphPreviewSourceState = {+const DOCUMENT_SOURCE: GraphPreviewSourceState = {destinationLabel: 'Gallery',- graph: LONG_VALUE_GRAPH,+ document: DOCUMENT,+ graph: FIXTURE_GRAPH,invalidReasons: [],- isLive: false,+ isLive: true,notices: [],summaryRows: [],};@@ -368,12 +407,17 @@ const createWorkflowUiAdapter = (): WorkflowUiAdapter => {const createGraphPreviewPort = (): WorkflowGraphPreviewPort => ({focusSource: vi.fn(),- getRoute: () => ({ canInvoke: true, label: 'Generate → Gallery' }),- invoke: vi.fn(() => Promise.resolve(true)),openDocumentInNewProject: vi.fn(),openWorkflowEditor: vi.fn(),});+/** A host's Invoke: the dialog places it and says whether it can run. */+const hostInvoke = (isReady: boolean): GraphPreviewInvoke => ({+ control: <button data-host-invoke="">Host Invoke</button>,+ isReady,+});+const READY = hostInvoke(true);+describe('GraphPreviewDialog', () => {let host: HTMLDivElement;let root: Root;@@ -386,7 +430,7 @@ describe('GraphPreviewDialog', () => {source: GraphPreviewSourceState,isOpen: boolean,sourceId: WorkflowInvocationSourceId,- hideInvoke: boolean+ invoke: GraphPreviewInvoke | null) => (<StrictMode><ChakraProvider value={system}>@@ -394,7 +438,7 @@ describe('GraphPreviewDialog', () => {<WorkflowGraphPreviewProvider adapter={graphPreviewPort}><GraphPreviewDialoggraphId="preview-graph-id"- hideInvoke={hideInvoke}+ invoke={invoke ?? undefined}isOpen={isOpen}source={source}sourceId={sourceId}@@ -412,10 +456,10 @@ describe('GraphPreviewDialog', () => {source: GraphPreviewSourceState,isOpen = true,sourceId: WorkflowInvocationSourceId = 'generate',- hideInvoke = false+ invoke: GraphPreviewInvoke | null = READY) => {await act(() => {- root.render(dialogTree(source, isOpen, sourceId, hideInvoke));+ root.render(dialogTree(source, isOpen, sourceId, invoke));});};@@ -427,41 +471,63 @@ describe('GraphPreviewDialog', () => {onExitComplete = vi.fn();graphPreviewPort = createGraphPreviewPort();workflowUiAdapter = createWorkflowUiAdapter();+ clipboard.copyText.mockClear();downloads.downloadBlob.mockReset();downloads.downloadText.mockReset();createLibraryWorkflowRecordMock.mockReset();setLibraryWorkflowPublicMock.mockReset();identity.session = { multiuserEnabled: false, phase: 'ready', user: null };- fitViewMock.mockClear();templatesSnapshotRef.current = TEMPLATES_SNAPSHOT;});afterEach(async () => {await act(() => root.unmount());- // The "Open as" menu's content portals to `document.body`, outside the- // React root this suite unmounts above — sweep it so a leftover node- // from one test can't answer a `[role="menuitem"]` query in the next.+ // The More menu's content portals to `document.body`, outside the React root this suite unmounts above; sweep it+ // so a leftover node from one test can't answer a `[role="menuitem"]` query in the next.document.querySelectorAll('[data-scope="menu"]').forEach((element) => element.remove());host.remove();});- const switchToMode = async (mode: 'graph' | 'list' | 'json') => {- const tab = [...document.querySelectorAll<HTMLButtonElement>('[role="tab"]')].find((candidate) =>- candidate.id.endsWith(`-tab-${mode}`)- );- expect(tab).not.toBeUndefined();+ const resizeViewport = async (width: number, height: number) => {+ const previous = { height: window.innerHeight, width: window.innerWidth };- await act(() => {- tab?.click();+ await page.viewport(width, height);+ onTestFinished(() => page.viewport(previous.width, previous.height));+ };+ /** The dialog's opening animation scales it; measure once it has played. */+ const settleOpening = () =>+ act(async () => {+ await vi.waitFor(() => {+ const content = document.querySelector('[data-scope="dialog"][data-part="content"]')!;++ expect(+ content.getAnimations({ subtree: true }).filter((animation) => animation.playState === 'running')+ ).toEqual([]);+ });});- // List mode loads on demand; wait for its rows before acting on them.- if (mode === 'list') {- await expect.element(page.getByRole('list').getByRole('button').first()).toBeVisible();- }+ const stage = () => document.querySelector<HTMLElement>('[data-graph-preview-stage]');+ const rail = () => document.querySelector<HTMLElement>('[data-graph-preview-rail]');+ const title = () => document.querySelector('[data-scope="dialog"][data-part="title"]')?.textContent ?? null;+ const description = () =>+ document.querySelector('[data-scope="dialog"][data-part="description"]')?.textContent ?? null;+ const previewNode = (id: string) => stage()?.querySelector<HTMLElement>(`.react-flow__node[data-id="${id}"]`) ?? null;+ const drawnNodeIds = () =>+ [...(stage()?.querySelectorAll<HTMLElement>('.react-flow__node') ?? [])].map((node) => node.dataset.id);+ const nodeCard = () => stage()?.querySelector<HTMLElement>('[data-preview-node-card]') ?? null;+ const press = (key: string) => act(() => userEvent.keyboard(key));++ const waitForGraph = () =>+ act(async () => {+ await vi.waitFor(() => expect(stage()?.querySelector('.react-flow__node')).not.toBeNull());+ });++ const openCard = async (nodeId: string) => {+ await act(() => userEvent.click(previewNode(nodeId)!));+ await vi.waitFor(() => expect(nodeCard()?.dataset.previewNodeCard).toBe(nodeId));};- const clickButtonWithText = async (text: string) => {- const button = [...document.querySelectorAll('button')].find((candidate) =>+ const clickButtonWithText = async (text: string, scope: ParentNode = document) => {+ const button = [...scope.querySelectorAll('button')].find((candidate) =>(candidate.textContent ?? '').includes(text));expect(button).not.toBeUndefined();@@ -472,8 +538,8 @@ describe('GraphPreviewDialog', () => {};// Wait for lazy menu portal mounting before querying items.- const openAsMenu = async () => {- await clickButtonWithText('Open as');+ const openMoreMenu = async () => {+ await act(() => document.querySelector<HTMLButtonElement>('[data-preview-more]')?.click());await act(async () => {await new Promise<void>((resolve) => {setTimeout(resolve, 40);@@ -490,9 +556,8 @@ describe('GraphPreviewDialog', () => {const item = findMenuItemWithText(text);expect(item).not.toBeUndefined();- await act(() => {- (item as HTMLElement | undefined)?.click();- });+ // Zag selects only the highlighted item, so this takes a real pointer click, which hovers it first.+ await act(() => userEvent.click(item as HTMLElement));};// Await the detached save handler's async chain before asserting serialization, creation, and notification.@@ -514,224 +579,459 @@ describe('GraphPreviewDialog', () => {return { promise, reject, resolve };};- it('renders summary rows, node count, and the live subtitle', async () => {+ it('titles itself with the source and says when it follows the settings', async () => {await renderDialog(FIXTURE_SOURCE);- const text = document.body.textContent ?? '';+ expect(title()).toBe('Generate');+ expect(description()).toBe('Updates as you change settings.');- expect(text).toContain('This graph');- expect(text).toContain('Gallery');- expect(text).toContain('3');- expect(text).toContain('Updates as you change settings.');+ await renderDialog(PLAIN_SOURCE);++ expect(description()).toBeNull();});- it('omits the destination row when the source was never routed anywhere', async () => {- await renderDialog(NO_DESTINATION_SOURCE);+ it('names a document source by its workflow', async () => {+ await renderDialog(DOCUMENT_SOURCE, true, 'workflow');- const panel = document.querySelector('[role="region"][aria-label="This graph"]');- // A "Destination —" row states nothing; the node count still shows.- expect(panel?.textContent ?? '').not.toContain('Destination');- expect(panel?.textContent ?? '').toContain('Nodes');+ expect(title()).toBe('Portrait workflow');});- it('reports when its close transition has finished, so hosts can drop the mount', async () => {+ it('draws a compiled graph as the library does: helpers folded, set fields and the result marked', async () => {await renderDialog(FIXTURE_SOURCE);+ await waitForGraph();- expect(onExitComplete).not.toHaveBeenCalled();+ // The seed primitive folds into a pill on the denoiser, showing what runs rather than the compiled placeholder.+ expect(drawnNodeIds()).toEqual(['denoise_latents', 'l2i']);+ expect(previewNode('denoise_latents')?.querySelector('[data-preview-pill="seed"]')?.textContent?.trim()).toBe(+ 'Integer Primitive regenerated each run'+ );+ // The steps came from a setting: the node is marked as set; the decoder is what the graph makes.+ expect(previewNode('denoise_latents')?.querySelector('[data-marker="exposed"]')).not.toBeNull();+ expect(previewNode('l2i')?.querySelector('[data-marker="result"]')).not.toBeNull();+ expect(stage()?.querySelector('[data-preview-legend]')?.textContent).toContain('You set this');+ });- await renderDialog(FIXTURE_SOURCE, false);+ it('draws nodes this server has no template for', async () => {+ await renderDialog(UNKNOWN_NODE_SOURCE);+ await waitForGraph();- // The exit animation runs in real time; polling inside `act` keeps its- // final commit inside an open act scope.- await act(async () => {- await vi.waitFor(() => {- expect(onExitComplete).toHaveBeenCalled();- });- });+ expect(drawnNodeIds()).toEqual(['mystery']);+ expect(previewNode('mystery')?.textContent).toContain('Node pack missing');++ await openCard('mystery');++ expect(nodeCard()?.textContent).toContain('strength');});- it('stays landscape on a tall viewport instead of growing into a full-height column', async () => {- const original = { height: window.innerHeight, width: window.innerWidth };+ it('lists the source’s notices beside the graph, and a notice shows its node', async () => {+ await renderDialog(FIXTURE_SOURCE);+ await waitForGraph();- try {- // Resized deliberately: at the default test viewport (~866px tall) an- // 80vh dialog and a 46rem-capped one measure within pixels of each other,- // so nothing asserted at that size can tell the two sizings apart.- await page.viewport(1280, 1400);- await renderDialog(FIXTURE_SOURCE);+ expect(rail()?.querySelector('[data-graph-preview-notice]')?.textContent).toContain('Seed is randomized');- const content = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]');- expect(content).not.toBeNull();+ await clickButtonWithText('Show node', rail()!);- const box = content?.getBoundingClientRect();+ // The seed is folded in the simplified view, so the graph opens in full with the seed's card.+ await vi.waitFor(() => expect(nodeCard()?.dataset.previewNodeCard).toBe('seed'));+ expect(drawnNodeIds()).toEqual(['seed', 'denoise_latents', 'l2i']);+ expect(nodeCard()?.textContent).toContain('regenerated each run');- // A viewport-proportional height would be ~1100px here; the cap is 46rem.- expect(box?.height ?? 0).toBeLessThanOrEqual(46 * 16 + 1);- // Which leaves the dialog the shape a graph reads in.- expect(box?.width ?? 0).toBeGreaterThan(box?.height ?? 0);- } finally {- await page.viewport(original.width, original.height);- }+ // Asked again after the card closed, it shows the node again.+ await press('{Escape}');+ expect(nodeCard()).toBeNull();+ await clickButtonWithText('Show node', rail()!);+ await vi.waitFor(() => expect(nodeCard()?.dataset.previewNodeCard).toBe('seed'));});- it('shows the seed notice inline in the summary panel', async () => {+ it('links a set field to its setting, which it focuses before closing', async () => {await renderDialog(FIXTURE_SOURCE);+ await waitForGraph();+ await openCard('denoise_latents');++ const links = [...nodeCard()!.querySelectorAll('[data-preview-field-source]')].map((link) => link.textContent);+ expect(links).toEqual(['Generate → Steps']);+ // Named as the setting that set it.+ expect([...nodeCard()!.querySelectorAll('dt')].some((label) => label.textContent?.startsWith('Steps'))).toBe(true);++ await clickButtonWithText('Generate → Steps', nodeCard()!);- const panel = document.querySelector('[role="region"][aria-label="This graph"]');- expect(panel?.textContent ?? '').toContain('Seed is randomized');+ expect(graphPreviewPort.focusSource).toHaveBeenCalledWith('generate');+ expect(onOpenChange).toHaveBeenCalledWith(false);});- it('switches to JSON mode', async () => {+ it('keeps an open card through live recompiles while its node survives, and closes it once the node is gone', async () => {await renderDialog(FIXTURE_SOURCE);+ await waitForGraph();+ await openCard('denoise_latents');+ expect(nodeCard()?.textContent).toContain('28');++ // A value changes: the same drawing, the card showing the new value.+ await renderDialog(withSteps(12));- expect(document.querySelector('[data-flow-stub]')).not.toBeNull();+ expect(nodeCard()?.dataset.previewNodeCard).toBe('denoise_latents');+ expect(nodeCard()?.textContent).toContain('12');+ expect(nodeCard()?.textContent).not.toContain('28');- await switchToMode('json');+ // The structure changes (the decoder goes): drawn afresh, the card still open on its node.+ await renderDialog(+ withGraph({ ...FIXTURE_GRAPH, edges: FIXTURE_GRAPH.edges.slice(0, 1), nodes: FIXTURE_GRAPH.nodes.slice(0, 2) })+ );+ await vi.waitFor(() => expect(drawnNodeIds()).not.toContain('l2i'));+ await vi.waitFor(() => expect(nodeCard()?.dataset.previewNodeCard).toBe('denoise_latents'));++ await renderDialog(+ withGraph({+ ...FIXTURE_GRAPH,+ edges: [],+ nodes: FIXTURE_GRAPH.nodes.filter((node) => node.id !== 'denoise_latents'),+ })+ );+ await waitForGraph();+ await vi.waitFor(() => expect(drawnNodeIds()).not.toContain('denoise_latents'));- expect(document.querySelector('[data-flow-stub]')).toBeNull();- expect(document.body.textContent ?? '').toContain('"denoise_latents"');+ expect(nodeCard()).toBeNull();});- it('shows the first invalid reason and no flow pane when compile is blocked', async () => {- await renderDialog(INVALID_SOURCE);+ it('closes an open card on Escape before the dialog', async () => {+ await renderDialog(FIXTURE_SOURCE);+ await waitForGraph();+ await openCard('denoise_latents');++ await press('{Escape}');++ expect(nodeCard()).toBeNull();+ expect(onOpenChange).not.toHaveBeenCalled();++ await press('{Escape}');- expect(document.body.textContent ?? '').toContain('Height must be a multiple of 8.');- expect(document.querySelector('[data-flow-stub]')).toBeNull();+ expect(onOpenChange).toHaveBeenCalledWith(false);});- it('renders the side panel only in graph mode', async () => {- // The fixture's own notice text ("...This graph runs differently each- // time.") contains the panel's heading as a substring, so this checks- // for the panel's `Scrollable` region (`aria-label="This graph"`)- // instead of a raw text match.- const findSidePanel = () => document.querySelector('[role="region"][aria-label="This graph"]');+ const tabs = () => [...(stage()?.querySelectorAll<HTMLElement>('[role="tab"]') ?? [])];+ const selectTab = async (view: 'nodes' | 'inputs' | 'graph') => {+ const tab = tabs().find((candidate) => candidate.id.endsWith(`-tab-${view}`));+ expect(tab, `no ${view} tab`).not.toBeUndefined();+ await act(() => tab!.click());+ };+ const moreButton = () => document.querySelector<HTMLElement>('[data-preview-more]');++ it('offers Nodes and Graph for a compiled source, and Inputs too for a document, whose form it reads', async () => {await renderDialog(FIXTURE_SOURCE);+ await waitForGraph();++ expect(tabs().map((tab) => tab.textContent)).toEqual(['Nodes', 'Graph']);++ await renderDialog(DOCUMENT_SOURCE, true, 'workflow');+ await waitForGraph();++ // Drawn from the document: the author's label names the node.+ expect(previewNode('denoise_latents')?.textContent).toContain('Sampler');+ expect(tabs().map((tab) => tab.textContent)).toEqual(['Nodes', 'Inputs 1', 'Graph']);++ await selectTab('inputs');++ expect(stage()?.querySelector('[data-preview-input="steps-field"]')?.textContent).toContain('steps');+ });++ it('keeps the tabs and More where they are in every view; only find comes and goes', async () => {+ await resizeViewport(1288, 942);+ await renderDialog(DOCUMENT_SOURCE, true, 'workflow');+ await waitForGraph();+ await settleOpening();++ const tabStrip = () => stage()!.querySelector<HTMLElement>('[role="tablist"]')!.getBoundingClientRect().toJSON();+ const more = () => moreButton()!.getBoundingClientRect().toJSON();+ const nodes = { more: more(), tabs: tabStrip() };++ expect(stage()?.querySelector('[data-preview-find]')).not.toBeNull();++ for (const view of ['inputs', 'graph', 'nodes'] as const) {+ await selectTab(view);+ await vi.waitFor(() => expect({ more: more(), tabs: tabStrip() }).toEqual(nodes));+ expect(stage()?.querySelector('[data-preview-find]') !== null).toBe(view === 'nodes');+ }+ });++ it('shows the compiled backend graph in the Graph view, serialized only once that view shows', async () => {+ const backendGraph = FIXTURE_GRAPH.backendGraph as Record<string, unknown>;+ const toJSON = vi.fn(() => backendGraph);- // Graph mode (the default): the panel is present.- expect(findSidePanel()).not.toBeNull();+ await renderDialog(withGraph({ ...FIXTURE_GRAPH, backendGraph: { toJSON } }));+ await waitForGraph();- await switchToMode('list');- expect(findSidePanel()).toBeNull();+ expect(toJSON).not.toHaveBeenCalled();- await switchToMode('json');- expect(findSidePanel()).toBeNull();+ await selectTab('graph');- await switchToMode('graph');- expect(findSidePanel()).not.toBeNull();+ await vi.waitFor(() =>+ expect(stage()?.querySelector('[data-preview-json] code')?.textContent).toBe(+ JSON.stringify(backendGraph, null, 2)+ )+ );});- it('disables Copy JSON when there is no compiled graph to copy', async () => {+ it('shows why a compiled source cannot compile, in the Nodes and Graph views alike', async () => {await renderDialog(INVALID_SOURCE);- const copyButton = [...document.querySelectorAll('button')].find((candidate) =>- (candidate.textContent ?? '').includes('Copy JSON')+ const reason = "This graph can't compile yet. Height must be a multiple of 8.";++ expect(stage()?.querySelector('[role="tabpanel"] [role="alert"]')?.textContent).toBe(reason);++ await selectTab('graph');++ expect(stage()?.querySelector('[role="tabpanel"] [role="alert"]')?.textContent).toBe(reason);+ // The menu stays where it is and says why there is no JSON to export.+ await openMoreMenu();+ expect(findMenuItemWithText('Copy graph JSON')?.textContent).toContain("This graph can't compile yet.");+ });++ it('draws a document that does not compile, with the reason beside it', async () => {+ await renderDialog(+ { ...DOCUMENT_SOURCE, graph: null, invalidReasons: ['Height must be a multiple of 8.'] },+ true,+ 'workflow');+ await waitForGraph();- expect(copyButton).toBeInstanceOf(HTMLButtonElement);- expect((copyButton as HTMLButtonElement).disabled).toBe(true);+ expect(drawnNodeIds()).toEqual(['denoise_latents']);+ expect(rail()?.querySelector('[data-graph-preview-blocked]')?.textContent).toBe(+ "This graph can't compile yet. Height must be a multiple of 8."+ );+ });++ it('says when a widget has no compiled graph yet', async () => {+ await renderDialog({ ...PLAIN_SOURCE, graph: null });++ expect(stage()?.querySelector('[role="tabpanel"]')?.textContent).toBe(+ 'No compiled graph is available for "preview-graph-id" yet.'+ );});- it('selecting a node from the list opens the inspector with resolved inputs and edges', async () => {+ it('opens at the library dialog’s size, so the two previews read the same', async () => {+ await resizeViewport(1288, 942);await renderDialog(FIXTURE_SOURCE);+ await settleOpening();- await switchToMode('list');- expect(document.querySelector('[data-flow-stub]')).toBeNull();+ const box = document.querySelector('[data-scope="dialog"][data-part="content"]')!.getBoundingClientRect();- await clickButtonWithText('denoise_latents');+ // The window less 4rem wide (under the 80rem cap) and 80% of its height.+ expect(Math.round(box.width)).toBe(1288 - 4 * 16);+ expect(Math.round(box.height)).toBe(Math.round(942 * 0.8));+ });++ it('fits a graph clear of the stage’s controls, on opening and on Fit', async () => {+ await resizeViewport(1288, 942);+ // Two results at opposite corners, spanning about the stage's shape: fitted to the whole stage, the top-left one+ // would sit under the legend.+ const corners: WorkflowPreviewGraph = {+ edges: [],+ id: 'corners',+ nodes: [+ { id: 'top-left', inputs: {}, type: 'l2i' },+ { id: 'bottom-right', inputs: {}, type: 'l2i' },+ ],+ version: 1,+ };++ await renderDialog({+ ...PLAIN_SOURCE,+ graph: corners,+ positionHints: { 'bottom-right': { x: 1890, y: 1038 }, 'top-left': { x: 0, y: 0 } },+ });+ await waitForGraph();++ const expectClear = (selector: string) => {+ const controls = [...stage()!.querySelectorAll(selector)].map((control) => control.getBoundingClientRect());++ for (const node of stage()!.querySelectorAll('.react-flow__node')) {+ const box = node.getBoundingClientRect();++ for (const control of controls) {+ const overlaps =+ box.left < control.right &&+ control.left < box.right &&+ box.top < control.bottom &&+ control.top < box.bottom;++ expect(overlaps, `${(node as HTMLElement).dataset.id} under a control`).toBe(false);+ }+ }+ };++ await settleOpening();+ // Opening: fitted or, when too tall to read fitted, from the top; either way the legend covers no node.+ expect(stage()?.querySelector('[data-preview-legend]')).not.toBeNull();+ expectClear('[data-preview-legend]');++ await clickButtonWithText('workflowLibrary.preview.fit', stage()!);+ // Fitted: the whole graph in the stage's open area, clear of every control.+ await vi.waitFor(() => expectClear('[data-preview-overlay]'));+ });- // List selection reveals the node in graph mode, not list mode.- const graphTab = [...document.querySelectorAll<HTMLElement>('[role="tab"]')].find((candidate) =>- candidate.id.endsWith('-tab-graph')+ it('exposes the preview controls and drawn nodes with accessible names', async () => {+ const wasDark = document.documentElement.classList.contains('dark');+ document.documentElement.classList.add('dark');+ onTestFinished(() => {+ if (!wasDark) {+ document.documentElement.classList.remove('dark');+ }+ });+ await renderDialog(PLAIN_SOURCE);+ await waitForGraph();+ await settleOpening();+ const dialog = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;+ expect(await auditAccessibility(dialog, { rules: { 'label-content-name-mismatch': { enabled: true } } })).toEqual(+ []);- expect(graphTab?.getAttribute('aria-selected')).toBe('true');- expect(document.querySelector('[data-flow-stub]')).not.toBeNull();-- const text = document.body.textContent ?? '';- expect(text).toContain('denoise_latents');- expect(text).toContain('Resolved inputs');- expect(text).toContain('28');- expect(text).toContain('Set by');- expect(text).toContain('Generate → Steps');-- // Exercise both incoming and outgoing edge details, not merely their heading.- expect(text).toContain('Edges');- expect(text).toContain('in · 1 inputs from seed');- expect(text).toContain('out · latents → l2i');-- // List-mode reveal must wait for the remounted flow's onInit rather than use the destroyed previous instance.- expect(fitViewMock).toHaveBeenCalledWith(expect.objectContaining({ nodes: [{ id: 'denoise_latents' }] }));});- it('lists nodes as a named list and marks the selected node when returning to list mode', async () => {- await renderDialog(FIXTURE_SOURCE);+ it('widens every chip for its longest title where the stage has the room', async () => {+ // Keep the title between the minimum and maximum chip widths, independent of the host's fonts and root size.+ const typography = document.createElement('style');+ typography.textContent = ':root { font-size: 16px !important; --chakra-fonts-body: monospace; }';+ document.head.append(typography);+ onTestFinished(() => typography.remove());+ templatesSnapshotRef.current = {+ ...TEMPLATES_SNAPSHOT,+ templates: {+ ...TEMPLATES_SNAPSHOT.templates,+ sdxl_compel: { ...TEMPLATES_SNAPSHOT.templates.sdxl_compel!, title: 'Positive Conditioning' },+ },+ };+ await resizeViewport(1288, 942);+ const graph: WorkflowPreviewGraph = {+ edges: [+ {+ id: 'e',+ sourceField: 'conditioning',+ sourceNodeId: 'prompt',+ targetField: 'latents',+ targetNodeId: 'decode',+ },+ ],+ id: 'wide',+ nodes: [+ { id: 'prompt', inputs: {}, type: 'sdxl_compel' },+ { id: 'decode', inputs: {}, type: 'l2i' },+ ],+ version: 1,+ };++ await renderDialog({ ...PLAIN_SOURCE, graph });+ await waitForGraph();++ const width = (id: string) => previewNode(id)!.offsetWidth;+ const title = previewNode('prompt')!.querySelector<HTMLElement>('[data-preview-chip] p')!;- await switchToMode('list');- const list = () => document.querySelector<HTMLElement>('[role="list"][aria-label="Nodes"]');+ // One width for every chip, past the narrowest, and the long title whole.+ expect(width('prompt')).toBeGreaterThan(136);+ expect(width('decode')).toBe(width('prompt'));+ expect(title.scrollWidth).toBeLessThanOrEqual(title.clientWidth);+ });++ it('keeps its drawing when a host hands a new source object around the same graph each render', async () => {+ // A host that rebuilds the source on every render, its callbacks fresh each time.+ const asked: string[] = [];+ const rebuilt = () => ({+ ...FIXTURE_SOURCE,+ getProvenance: (nodeId: string, fieldName: string) => {+ asked.push(nodeId);+ return FIXTURE_SOURCE.getProvenance!(nodeId, fieldName);+ },+ });++ await renderDialog(rebuilt());+ await waitForGraph();+ await openCard('denoise_latents');+ const chip = previewNode('l2i');+ asked.length = 0;++ for (let render = 0; render < 3; render += 1) {+ await renderDialog(rebuilt());+ }- expect(list()).not.toBeNull();- expect(list()!.querySelectorAll('[role="listitem"]').length).toBeGreaterThan(1);- expect(list()!.querySelector('[aria-current="true"]')).toBeNull();+ // Nothing rebuilt: the seed's fields (no card shows them) were not asked about again; the drawing and card stay.+ expect(asked).not.toContain('seed');+ expect(previewNode('l2i')).toBe(chip);+ expect(nodeCard()?.dataset.previewNodeCard).toBe('denoise_latents');+ });- await clickButtonWithText('denoise_latents');- await switchToMode('list');+ it('starts no model or starter request, open or closed', async () => {+ const { ensureModelsLoaded, ensureStartersLoaded } = await import('@features/models');- const current = list()!.querySelector<HTMLElement>('[data-list-primary][aria-current="true"]');+ vi.mocked(ensureModelsLoaded).mockClear();+ vi.mocked(ensureStartersLoaded).mockClear();+ await renderDialog(FIXTURE_SOURCE, false);+ await renderDialog(FIXTURE_SOURCE);+ await waitForGraph();- expect(current?.textContent).toContain('denoise_latents');- // The selected node is the list's single tab stop, so keyboard users land on it.- expect(current?.tabIndex).toBe(0);- expect(list()!.querySelectorAll('[data-list-primary][tabindex="0"]')).toHaveLength(1);+ expect(ensureModelsLoaded).not.toHaveBeenCalled();+ expect(ensureStartersLoaded).not.toHaveBeenCalled();});- it('show node selects the seed node and inspector shows the randomized override', async () => {+ it('reports when its close transition has finished, so hosts can drop the mount', async () => {await renderDialog(FIXTURE_SOURCE);- await clickButtonWithText('show node');+ expect(onExitComplete).not.toHaveBeenCalled();- const text = document.body.textContent ?? '';- expect(text).toContain('integer');- expect(text).toContain('seed');- expect(text).toContain('regenerated each run');+ await renderDialog(FIXTURE_SOURCE, false);- // Graph-mode reveal uses the already-mounted instance immediately.- expect(fitViewMock).toHaveBeenCalledWith(expect.objectContaining({ nodes: [{ id: 'seed' }] }));+ // The exit animation runs in real time; polling inside `act` keeps its final commit inside an open act scope.+ await act(async () => {+ await vi.waitFor(() => {+ expect(onExitComplete).toHaveBeenCalled();+ });+ });});- it('clicking a provenance link focuses the source and closes the dialog', async () => {+ it('reopens on the nodes, unfiltered, with no card open', async () => {+ const findField = () => document.querySelector<HTMLInputElement>('[data-preview-find]');+await renderDialog(FIXTURE_SOURCE);+ await waitForGraph();+ await act(() => userEvent.fill(findField()!, 'latents'));+ await openCard('denoise_latents');- await switchToMode('list');- await clickButtonWithText('denoise_latents');- await clickButtonWithText('Generate → Steps');+ await renderDialog(FIXTURE_SOURCE, false);+ await act(async () => {+ await vi.waitFor(() => expect(onExitComplete).toHaveBeenCalled());+ });+ await renderDialog(FIXTURE_SOURCE, true);+ await waitForGraph();- expect(graphPreviewPort.focusSource).toHaveBeenCalledWith('generate');- expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(nodeCard()).toBeNull();+ expect(findField()?.value).toBe('');});- it('clears the selected node when the dialog closes and reopens', async () => {+ it('More → Copy graph JSON copies the compiled backend graph', async () => {await renderDialog(FIXTURE_SOURCE);- await switchToMode('list');- await clickButtonWithText('denoise_latents');- expect(document.body.textContent ?? '').toContain('Resolved inputs');+ await openMoreMenu();+ await clickMenuItemWithText('Copy graph JSON');+ await flushAsync();- // Model the controlled close/reopen round trip to verify selection resets.- await clickButtonWithText('Close');- expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(clipboard.copyText).toHaveBeenCalledWith(JSON.stringify(FIXTURE_GRAPH.backendGraph, null, 2));+ expect(workflowUiAdapter.notifications.success).toHaveBeenCalledWith('Graph JSON copied');+ });- await renderDialog(FIXTURE_SOURCE, false);- await renderDialog(FIXTURE_SOURCE, true);+ it('More → Download graph JSON downloads the compiled backend graph', async () => {+ await renderDialog(FIXTURE_SOURCE);- const text = document.body.textContent ?? '';- expect(text).toContain('Select a node for details.');- expect(text).not.toContain('Resolved inputs');+ await openMoreMenu();+ await clickMenuItemWithText('Download graph JSON');++ expect(downloads.downloadText).toHaveBeenCalledWith(+ JSON.stringify(FIXTURE_GRAPH.backendGraph, null, 2),+ 'graph.json',+ 'application/json'+ );});- it('Open as → Edit in workflow editor adds the document as a project workflow, opens the editor, closes the dialog', async () => {+ it('More → Edit in workflow editor adds the document as a project workflow, opens the editor, closes the dialog', async () => {await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Edit in workflow editor');expect(workflowUiAdapter.commands.addWorkflow).toHaveBeenCalledTimes(1);@@ -743,10 +1043,10 @@ describe('GraphPreviewDialog', () => {expect(onOpenChange).toHaveBeenCalledWith(false);});- it('Open as → Fork into new project hands the named document to the port and closes the dialog', async () => {+ it('More → Fork into new project hands the named document to the port and closes the dialog', async () => {await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Fork into new project');expect(graphPreviewPort.openDocumentInNewProject).toHaveBeenCalledTimes(1);@@ -759,72 +1059,123 @@ describe('GraphPreviewDialog', () => {expect(onOpenChange).toHaveBeenCalledWith(false);});- it('Open as → Download JSON downloads the backend graph', async () => {- await renderDialog(FIXTURE_SOURCE);+ it('More → Fork into new project copies a document source, keeping its labels and form', async () => {+ await renderDialog(+ { ...DOCUMENT_SOURCE, graph: null, invalidReasons: ['Height must be a multiple of 8.'] },+ true,+ 'workflow'+ );- await openAsMenu();- await clickMenuItemWithText('Download JSON');+ await openMoreMenu();+ await clickMenuItemWithText('Fork into new project');- expect(downloads.downloadText).toHaveBeenCalledTimes(1);- const [content, fileName, type] = vi.mocked(downloads.downloadText).mock.calls[0] ?? [];- expect(content).toContain('"denoise_latents"');- expect(fileName).toBe('graph.json');- expect(type).toBe('application/json');+ const [document_] = vi.mocked(graphPreviewPort.openDocumentInNewProject).mock.calls[0] ?? [];+ // A copy of its own, even while it does not compile.+ expect(document_?.id).not.toBe(DOCUMENT.id);+ expect(document_?.name).toBe('Portrait workflow');+ expect(document_?.nodes.map((node) => (node.type === 'invocation' ? node.data.label : null))).toEqual(['Sampler']);+ expect(document_?.form).toEqual(DOCUMENT.form);});it('hides Edit in workflow editor for the workflow source', async () => {await renderDialog(FIXTURE_SOURCE, true, 'workflow');- await openAsMenu();+ await openMoreMenu();expect(findMenuItemWithText('Edit in workflow editor')).toBeUndefined();expect(findMenuItemWithText('Save to workflow library')).not.toBeUndefined();- expect(findMenuItemWithText('Download JSON')).not.toBeUndefined();+ expect(findMenuItemWithText('Download graph JSON')).not.toBeUndefined();});- it('renders the footer Invoke button by default', async () => {+ const footer = () => document.querySelector<HTMLElement>('[data-graph-preview-footer]');+ const readiness = () => footer()?.querySelector<HTMLElement>('[data-graph-preview-readiness]') ?? null;+ const railFacts = () =>+ [...(rail()?.querySelectorAll('[data-graph-preview-facts] dt') ?? [])].map(+ (label) => `${label.textContent}: ${label.nextElementSibling?.textContent}`+ );++ it('says only whether it can invoke in the footer, the run’s facts and destination in the rail', async () => {await renderDialog(FIXTURE_SOURCE);- const buttonText = [...document.querySelectorAll('button')].map((button) => button.textContent ?? '');- expect(buttonText.some((text) => text.includes('Invoke Generate → Gallery'))).toBe(true);+ expect(readiness()?.textContent).toBe('Ready to invoke');+ expect(readiness()?.querySelector('[aria-live="polite"]')?.textContent).toBe('Ready to invoke');+ expect(footer()?.querySelector('[data-host-invoke]')).not.toBeNull();+ // Above the notices, as label and value; the destination said there, not again under the title.+ expect(railFacts()).toEqual(['Steps: 28', 'Model: SDXL', 'Destination: Gallery']);+ expect(+ rail()!+ .querySelector('[data-graph-preview-facts]')!+ .compareDocumentPosition(rail()!.querySelector('[data-graph-preview-notice]')!) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy();+ expect(description()).toBe('Updates as you change settings.');++ await renderDialog(FIXTURE_SOURCE, true, 'generate', hostInvoke(false));++ expect(readiness()?.textContent).toBe("Can't invoke yet");+ expect(railFacts()).toEqual(['Steps: 28', 'Model: SDXL', 'Destination: Gallery']);});- it('keeps the footer Invoke button inert while the route cannot be invoked', async () => {- graphPreviewPort = {- ...createGraphPreviewPort(),- getRoute: () => ({ canInvoke: false, label: 'Generate → Gallery', validationMessage: 'Preparing generation…' }),- };+ it('shows the rail for facts alone, and none for a source with nothing to say beside the graph', async () => {+ await renderDialog({ ...PLAIN_SOURCE, destinationLabel: 'Gallery' });++ expect(railFacts()).toEqual(['Destination: Gallery']);++ await renderDialog(PLAIN_SOURCE);++ expect(rail()).toBeNull();+ });++ it('offers a compiled source as a workflow to edit, left of Invoke', async () => {await renderDialog(FIXTURE_SOURCE);- const button = [...document.querySelectorAll('button')].find((candidate) =>- (candidate.textContent ?? '').includes('Invoke Generate → Gallery')- );- expect(button?.getAttribute('aria-disabled')).toBe('true');- expect(button?.getAttribute('title')).toBe('Preparing generation…');+ expect([...footer()!.querySelectorAll('button')].map((button) => button.textContent)).toEqual([+ 'Edit as workflow',+ 'Host Invoke',+ ]);+ await clickButtonWithText('Edit as workflow', footer()!);++ expect(workflowUiAdapter.commands.addWorkflow).toHaveBeenCalledTimes(1);+ expect(graphPreviewPort.openWorkflowEditor).toHaveBeenCalledTimes(1);+ expect(onOpenChange).toHaveBeenCalledWith(false);- await clickButtonWithText('Invoke Generate → Gallery');+ // A document is already a workflow.+ await renderDialog(DOCUMENT_SOURCE, true, 'workflow');- expect(graphPreviewPort.invoke).not.toHaveBeenCalled();- expect(onOpenChange).not.toHaveBeenCalled();+ expect(footer()?.querySelector('[data-graph-preview-edit-as-workflow]')).toBeNull();+ });++ it('closes from the header, with no footer Close', async () => {+ await renderDialog(FIXTURE_SOURCE);++ const close = document.querySelector<HTMLButtonElement>('[data-scope="dialog"][data-part="close-trigger"]');++ // In the header, beside the title.+ expect(close?.parentElement?.contains(document.querySelector('[data-scope="dialog"][data-part="title"]'))).toBe(+ true+ );+ expect(footer()?.textContent).not.toContain('Close');+ await act(() => close!.click());++ expect(onOpenChange).toHaveBeenCalledWith(false);});- it('hideInvoke hides only the footer Invoke button — Copy JSON and Open as stay', async () => {- await renderDialog(FIXTURE_SOURCE, true, 'generate', true);+ it('without a host Invoke has no footer; the facts stay in the rail', async () => {+ await renderDialog(FIXTURE_SOURCE, true, 'generate', null);- const buttonText = [...document.querySelectorAll('button')].map((button) => button.textContent ?? '');- expect(buttonText.some((text) => text.includes('Invoke'))).toBe(false);- expect(buttonText.some((text) => text.includes('Copy JSON'))).toBe(true);- expect(buttonText.some((text) => text.includes('Open as'))).toBe(true);+ expect(footer()).toBeNull();+ expect(railFacts()).toEqual(['Steps: 28', 'Model: SDXL', 'Destination: Gallery']);+ expect(document.querySelector('[data-preview-more]')).not.toBeNull();});- it('Open as → Save to workflow library names the document from the source label and notifies success', async () => {+ it('More → Save to workflow library names the document from the source label and notifies success', async () => {createLibraryWorkflowRecordMock.mockImplementation((workflow: Record<string, unknown>) =>Promise.resolve({ name: workflow.name, revision: 1, workflow, workflow_id: 'library-workflow-1' }));await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');await flushAsync();@@ -843,7 +1194,7 @@ describe('GraphPreviewDialog', () => {expect(setLibraryWorkflowPublicMock).not.toHaveBeenCalled();});- it('Open as → Save to workflow library offers the public visibility choice in multiuser mode', async () => {+ it('More → Save to workflow library offers the public visibility choice in multiuser mode', async () => {identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } };createLibraryWorkflowRecordMock.mockImplementation((workflow: Record<string, unknown>, options: { reservedId?: string }) =>@@ -861,7 +1212,7 @@ describe('GraphPreviewDialog', () => {await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');const checkbox = document.querySelector<HTMLInputElement>('input[type="checkbox"][name="isPublic"]');@@ -903,7 +1254,7 @@ describe('GraphPreviewDialog', () => {await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');const checkbox = document.querySelector<HTMLInputElement>('input[type="checkbox"][name="isPublic"]');expect(checkbox).not.toBeNull();@@ -936,12 +1287,12 @@ describe('GraphPreviewDialog', () => {expect(workflowUiAdapter.commands.setWorkflowSource).not.toHaveBeenCalled();});- it('Open as → Save to workflow library retries a lost answer once under the same reserved id, never claiming success', async () => {+ it('More → Save to workflow library retries a lost answer once under the same reserved id, never claiming success', async () => {createLibraryWorkflowRecordMock.mockRejectedValue(new Error('network down'));await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');await flushAsync();@@ -952,10 +1303,10 @@ describe('GraphPreviewDialog', () => {expect(workflowUiAdapter.notifications.success).not.toHaveBeenCalled();});- it('Open as → Save to workflow library bails with an error notification when the graph has no saveable nodes', async () => {+ it('More → Save to workflow library bails with an error notification when the graph has no saveable nodes', async () => {await renderDialog(UNKNOWN_NODE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');await flushAsync();@@ -969,7 +1320,7 @@ describe('GraphPreviewDialog', () => {templatesSnapshotRef.current = { error: null, status: 'loading', templates: {} };await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();const item = findMenuItemWithText('Save to workflow library');expect(item).not.toBeUndefined();@@ -980,13 +1331,12 @@ describe('GraphPreviewDialog', () => {templatesSnapshotRef.current = { error: null, status: 'loading', templates: {} };await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();let item = findMenuItemWithText('Fork into new project');expect(item?.getAttribute('aria-disabled')).toBe('true');- templatesSnapshotRef.current = TEMPLATES_SNAPSHOT;- await renderDialog(FIXTURE_SOURCE);+ await setTemplatesSnapshot(TEMPLATES_SNAPSHOT);item = findMenuItemWithText('Fork into new project');expect(item?.getAttribute('aria-disabled')).not.toBe('true');@@ -1013,7 +1363,7 @@ describe('GraphPreviewDialog', () => {setLibraryWorkflowPublicMock.mockReturnValue(visibilityRequest.promise);await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');const checkbox = document.querySelector<HTMLInputElement>('input[type="checkbox"][name="isPublic"]');expect(checkbox).not.toBeNull();@@ -1045,7 +1395,7 @@ describe('GraphPreviewDialog', () => {.mockReturnValueOnce(retry.promise);await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');await flushAsync();@@ -1081,7 +1431,7 @@ describe('GraphPreviewDialog', () => {);await renderDialog(FIXTURE_SOURCE);- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');await flushAsync();@@ -1092,7 +1442,7 @@ describe('GraphPreviewDialog', () => {throw new Error('Expected the first preview publication request');}- await openAsMenu();+ await openMoreMenu();await clickMenuItemWithText('Save to workflow library');await flushAsync();@@ -1103,19 +1453,4 @@ describe('GraphPreviewDialog', () => {expect(getUnresolvedWorkflowPublication('project-1', firstRequest.workflowId)).toBeNull();});-- it('truncates a long resolved-input string and exposes the full value via title', async () => {- await renderDialog(LONG_VALUE_SOURCE);-- await switchToMode('list');- await clickButtonWithText('note');-- const truncated = `${LONG_STRING_VALUE.slice(0, 40)}…`;- const valueElement = [...document.querySelectorAll('dd')].find((element) => element.textContent === truncated);-- expect(valueElement).not.toBeUndefined();- expect(valueElement?.getAttribute('title')).toBe(LONG_STRING_VALUE);- // The untruncated value never appears verbatim in the rendered text.- expect(document.body.textContent ?? '').not.toContain(LONG_STRING_VALUE);- });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsxindex d0a2a50bb6..209ac9a4d2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.tsx@@ -1,329 +1,546 @@-import type { GraphPreviewSourceState, WorkflowInvocationSourceId } from '@features/workflow/ui/contracts';-import type { ReactFlowInstance } from '@xyflow/react';-import type { ReactNode } from 'react';+import type { InvocationTemplates, ProjectGraphState } from '@features/workflow/core/types';+import type { WorkflowPreviewMetrics, WorkflowPreviewModel } from '@features/workflow/core/workflowPreview';+import type {+ GraphPreviewInvoke,+ GraphPreviewSourceState,+ WorkflowInvocationSourceId,+} from '@features/workflow/ui/contracts';-import { Box, Center, Icon, Portal, Spinner, Stack, Text } from '@chakra-ui/react';+import { Box, DataList, HStack, Icon, Portal, Stack, type SystemStyleObject, Text } from '@chakra-ui/react';import { localizeForLoopValidationReason } from '@features/workflow/core/forLoops';+import { buildWorkflowPreviewModel, compiledGraphToPreviewDocument } from '@features/workflow/core/workflowPreview';+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { useNodesNeedingModel } from '@features/workflow/ui/modelRequirementStatus';import { useWorkflowGraphPreview } from '@features/workflow/ui/WorkflowUiContext';-import { canCopyText, copyText } from '@platform/browser/clipboard';-import { Button, JsonPreview, SegmentTabs, segmentTabsPanelId, segmentTabsTabId, toaster } from '@platform/ui';+import { Button, CloseButton } from '@platform/ui/Button';import { Dialog } from '@platform/ui/Dialog';-import { CheckIcon, ChevronUpIcon, CopyIcon, TriangleAlertIcon } from 'lucide-react';-import { lazy, Suspense, useCallback, useId, useMemo, useRef, useState } from 'react';+import { Scrollable } from '@platform/ui/Scrollable';+import { SegmentTabs, segmentTabsPanelId, segmentTabsTabId } from '@platform/ui/SegmentTabs';+import { CheckIcon, InfoIcon, TriangleAlertIcon } from 'lucide-react';+import { Suspense, useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { GraphPreviewFlow } from './GraphPreviewFlow';-import { GraphPreviewOpenAsMenu } from './GraphPreviewOpenAsMenu';-import { GraphPreviewSidePanel } from './GraphPreviewSidePanel';+import type { WorkflowDocumentGraphHandle, WorkflowPreviewFieldSources } from './WorkflowDocumentGraph';+import type { WorkflowPreviewView } from './WorkflowPreviewStage';-// Loaded through this module so the snapshot shares the dialog's chunk; a second entry splits the flow out of it.+import { getGraphJsonText } from './graphJson';+import { GraphPreviewMoreMenu, useGraphAsWorkflow } from './GraphPreviewMoreMenu';+import { WorkflowDocumentGraph } from './WorkflowDocumentGraph';+import { WorkflowPreviewInputs } from './WorkflowPreviewInputs';+import {+ getWorkflowPreviewViewTabs,+ useWorkflowPreviewFind,+ WorkflowPreviewBar,+ WorkflowPreviewFindField,+ WorkflowPreviewJson,+ WorkflowPreviewStageLoading,+ WorkflowPreviewStageMessage,+ WORKFLOW_PREVIEW_DIALOG_SIZE,+} from './WorkflowPreviewStage';++// Loaded through this module so the snapshot and the library's graph share the dialog's chunk; a second entry splits+// the flow out of it.export { GraphPreviewSnapshot } from './GraphPreviewSnapshot';+export { WorkflowDocumentGraph } from './WorkflowDocumentGraph';interface GraphPreviewDialogProps {graphId: string;isOpen: boolean;source: GraphPreviewSourceState;sourceId?: WorkflowInvocationSourceId;- /** e.g. "Generate" — used in the header subtitle and the JSON preview label. */+ /** e.g. "Generate": the title, unless the source's document has a name of its own. */sourceLabel: string;- /** Hides the footer Invoke button only — Copy JSON and the Open-as menu stay. For sources with no invocation route (e.g. a library entry, previewed before it's ever opened into a project). */- hideInvoke?: boolean;+ /** The host's Invoke for this source, in the footer; none for a source that is not run from here (a review). */+ invoke?: GraphPreviewInvoke;onOpenChange: (isOpen: boolean) => void;/** Conditional hosts must unmount after close completion so exit animation can run. */onExitComplete?: () => void;}-type PreviewMode = 'graph' | 'list' | 'json';--const modeItems = [- { labelKey: 'graphPreview.graph', value: 'graph' },- { labelKey: 'graphPreview.list', value: 'list' },- { labelKey: 'common.json', value: 'json' },-] as const satisfies readonly { labelKey: string; value: PreviewMode }[];+/** Stage and rail side by side; a narrow dialog puts the rail under the stage. */+const BODY_CSS: SystemStyleObject = {+ display: 'grid',+ flex: '1',+ gap: '3',+ py: '1',+ gridTemplateColumns: 'minmax(0, 1fr)',+ gridTemplateRows: 'minmax(0, 1fr) auto',+ minH: '0',+ // As wide as the library's detail rail.+ md: { gridTemplateColumns: 'minmax(0, 1fr) 18rem', gridTemplateRows: 'minmax(0, 1fr)' },+};+const RAIL_CSS: SystemStyleObject = { maxH: '10rem', md: { maxH: 'none' } };+const STAGE_LOADING = <WorkflowPreviewStageLoading />;-const COPY_RESET_DELAY_MS = 1500;-const SELECT_AND_REVEAL_FIT_VIEW_OPTIONS = { duration: 150, maxZoom: 1 } as const;+/** "Generate → Seed" names the setting "Seed": the label a set field takes in the drawing. */+const getSettingName = (provenance: string) => provenance.split('→').at(-1)!.trim() || provenance;-// List mode brings the virtualized list; load it when chosen so the workflow route's startup does not carry it.-const GraphPreviewList = lazy(() =>- import('./GraphPreviewList').then((module) => ({ default: module.GraphPreviewList }))-);-const ListFallback = () => {- const { t } = useTranslation();+/** What the drawing was built from, and what was built. */+interface ModelState {+ graph: GraphPreviewSourceState['graph'];+ sourceDocument: ProjectGraphState | undefined;+ templates: InvocationTemplates | null;+ isPresent: boolean;+ document: ProjectGraphState | null;+ model: WorkflowPreviewModel | null;+}- return (- <Center aria-label={t('common.loading')} h="full" role="status">- <Spinner color="fg.subtle" size="lg" />- </Center>- );+const NO_MODEL: ModelState = {+ document: null,+ graph: null,+ isPresent: false,+ model: null,+ sourceDocument: undefined,+ templates: null,};-const LIST_FALLBACK = <ListFallback />;-const PreviewPane = ({ children }: { children: ReactNode }) => (- <Box flex="1" h="full" minH="0" minW="0" w="full" rounded="md" borderWidth={1} overflow="hidden">- {children}- </Box>-);--/** The strip above the graph when compilation is blocked — notices about a *valid* graph (e.g. randomized seed) live inline in the summary panel instead. */-const InvalidBanner = ({ children }: { children: ReactNode }) => (- <Box- alignItems="center"- bg="bg.muted"- color="fg.muted"- display="flex"- fontSize="lg"- gap="2"- px="3"- py="2"- rounded="md"- >- <Icon as={TriangleAlertIcon} boxSize="4" flexShrink={0} />- <Box flex="1" minW="0">- {children}- </Box>- </Box>-);+interface Drawing {+ key: number;+ structureKey: string | null;+ /** The node whose card was open when the structure changed, which the new drawing opens again. */+ carriedNodeId: string | null;+}+/**+ * A compiled graph, or the workflow document it compiles from, drawn as the library previews a workflow: the same+ * graph, node card, find, Inputs view (for a document) and JSON view, with the source's facts and notices in a rail+ * beside it. A live source redraws in place as it recompiles: a value change redraws only the chips it changes; a+ * structure change draws afresh, keeping an open card whose node survives. Nothing is built while it is closed.+ */export const GraphPreviewDialog = ({graphId,isOpen,source,sourceId,sourceLabel,- hideInvoke = false,+ invoke,onOpenChange,onExitComplete,}: GraphPreviewDialogProps) => {const { t } = useTranslation();const graphPreview = useWorkflowGraphPreview();- const modeTabsIdBase = useId();- const [mode, setMode] = useState<PreviewMode>('graph');- const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);- const [hasCopied, setHasCopied] = useState(false);- const copyResetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const flowInstanceRef = useRef<ReactFlowInstance | null>(null);- const dialogRoute = graphPreview.getRoute(sourceId);- const canInvoke = dialogRoute?.canInvoke === true;- const validationMessage = dialogRoute?.validationMessage- ? localizeForLoopValidationReason(dialogRoute.validationMessage, t)- : undefined;- const hasInvalidReasons = source.invalidReasons.length > 0;+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const viewTabsId = useId();+ const graphRef = useRef<WorkflowDocumentGraphHandle>(null);+ const [view, setView] = useState<WorkflowPreviewView>('nodes');+ // Open, or still playing its close: until the exit completes the content shows what it showed.+ const [isPresent, setIsPresent] = useState(isOpen);+ if (isOpen && !isPresent) {+ setIsPresent(true);+ }- const graph = source.graph;- const selectedNode = graph?.nodes.find((node) => node.id === selectedNodeId) ?? null;+ const { document: sourceDocument, getProvenance, graph, positionHints, resolvedInputOverrides } = source;+ const templates = templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null;+ /**+ * One model path: a compiled graph is drawn as a document whose form is what the person set, named by the setting.+ * Rebuilt when the graph or document itself changes (not the source object around them: a host may hand a fresh one+ * each render); its provenance, overrides and position hints come with each compile. Each rebuild hands the last+ * model on, so what a recompile did not change keeps its identity. Nothing is built while the dialog is closed.+ */+ const [modelState, setModelState] = useState<ModelState>(NO_MODEL);+ let built = modelState;+ if (+ modelState.graph !== graph ||+ modelState.sourceDocument !== sourceDocument ||+ modelState.isPresent !== isPresent ||+ (isPresent && modelState.templates !== templates)+ ) {+ const document = !isPresent+ ? null+ : (sourceDocument ??+ (graph+ ? compiledGraphToPreviewDocument(graph, {+ getSetLabel: getProvenance+ ? (nodeId, fieldName) => {+ const provenance = getProvenance(nodeId, fieldName);- // Reset selection on every close path so reopening starts clean.- const closeAndReset = useCallback(- (open: boolean) => {- if (!open) {- setSelectedNodeId(null);- }+ return provenance ? getSettingName(provenance.label) : null;+ }+ : undefined,+ overrides: resolvedInputOverrides,+ positionHints,+ })+ : null));- onOpenChange(open);- },- [onOpenChange]+ built = {+ document,+ graph,+ isPresent,+ model: document && templates ? buildWorkflowPreviewModel(document, templates, undefined, modelState.model) : null,+ sourceDocument,+ templates,+ };+ setModelState(built);+ }+ const { document, model } = built;+ // The drawing at a wider chip, where the graph's stage has the room.+ const relayout = useCallback(+ (metrics: WorkflowPreviewMetrics, previous: WorkflowPreviewModel | null) =>+ buildWorkflowPreviewModel(document!, templates!, metrics, previous),+ [document, templates]);-- const handleOpenChange = useCallback((event: { open: boolean }) => closeAndReset(event.open), [closeAndReset]);- const handleModeChange = useCallback((value: PreviewMode) => setMode(value), []);- const closeDialog = useCallback(() => closeAndReset(false), [closeAndReset]);- const invokeRoute = useCallback(() => {- void graphPreview.invoke(sourceId).then((submitted) => {- if (submitted) {- closeAndReset(false);- }+ const needsModel = useNodesNeedingModel(model);+ // The open card, as the graph reports it, so a structure change can carry it into the new drawing.+ const [cardNodeId, setCardNodeId] = useState<string | null>(null);+ const structureKey = model?.structureKey ?? null;+ const [drawing, setDrawing] = useState<Drawing>({ carriedNodeId: null, key: 0, structureKey });+ if (drawing.structureKey !== structureKey) {+ setDrawing({+ carriedNodeId: cardNodeId !== null && model?.nodes.has(cardNodeId) ? cardNodeId : null,+ key: drawing.key + 1,+ structureKey,});- }, [graphPreview, closeAndReset, sourceId]);+ }+ const find = useWorkflowPreviewFind(graphRef, drawing.key);+ // A node a notice or an input asked to show opens selected in its drawing; asking again opens it again.+ const [shownNode, setShownNode] = useState<{ drawing: number; nodeId: string; request: number } | null>(null);+ const requestedNodeId = shownNode?.drawing === drawing.key ? shownNode.nodeId : null;- // Queue reveals for the next flow initialization; the previous mount's instance may already be destroyed.- const pendingRevealNodeIdRef = useRef<string | null>(null);-- const handleFlowInit = useCallback((instance: ReactFlowInstance) => {- flowInstanceRef.current = instance;-- const pendingNodeId = pendingRevealNodeIdRef.current;+ const closeDialog = useCallback(() => onOpenChange(false), [onOpenChange]);+ const handleOpenChange = useCallback((event: { open: boolean }) => onOpenChange(event.open), [onOpenChange]);+ const { reset: resetFind } = find;+ // Reopened, the preview starts on the graph again, unfiltered, no card open.+ const handleExitComplete = useCallback(() => {+ setIsPresent(false);+ setView('nodes');+ setShownNode(null);+ setCardNodeId(null);+ resetFind();+ onExitComplete?.();+ }, [onExitComplete, resetFind, setCardNodeId]);+ const handleEscapeKeyDown = useCallback((event: KeyboardEvent) => {+ // One keypress can arrive twice (StrictMode registers the open dialog's layer twice); only the first acts.+ if (event.defaultPrevented) {+ return;+ }- if (pendingNodeId !== null) {- pendingRevealNodeIdRef.current = null;- void instance.fitView({ ...SELECT_AND_REVEAL_FIT_VIEW_OPTIONS, nodes: [{ id: pendingNodeId }] });+ if (graphRef.current?.closeNodeCard()) {+ event.preventDefault();}}, []);- const handleFlowNodeSelect = useCallback((nodeId: string | null) => setSelectedNodeId(nodeId), []);- const handleBack = useCallback(() => setSelectedNodeId(null), []);- const handleProvenanceClick = useCallback(() => {- graphPreview.focusSource(sourceId);- closeAndReset(false);- }, [graphPreview, sourceId, closeAndReset]);-- // Switching from list/JSON starts a flow remount; defer fitView until its fresh instance initializes.- const selectAndReveal = useCallback(- (nodeId: string) => {- setSelectedNodeId(nodeId);-- const instance = flowInstanceRef.current;- const isFlowMounted = mode === 'graph' && instance !== null;+ const fieldSources = useMemo<WorkflowPreviewFieldSources | undefined>(+ () =>+ getProvenance+ ? {+ describe: (nodeId, fieldName) => getProvenance(nodeId, fieldName)?.label ?? null,+ onSelect: () => {+ graphPreview.focusSource(sourceId);+ onOpenChange(false);+ },+ }+ : undefined,+ [getProvenance, graphPreview, onOpenChange, sourceId]+ );- if (isFlowMounted) {- void instance.fitView({ ...SELECT_AND_REVEAL_FIT_VIEW_OPTIONS, nodes: [{ id: nodeId }] });- } else {- pendingRevealNodeIdRef.current = nodeId;- }+ const { canConvert, editInEditor } = useGraphAsWorkflow({+ graph,+ onClose: closeDialog,+ sourceDocument,+ sourceLabel,+ });- setMode('graph');+ const selectView = useCallback(+ (next: WorkflowPreviewView) => {+ setShownNode(null);+ setCardNodeId(null);+ resetFind();+ setView(next);+ },+ [resetFind, setCardNodeId]+ );+ const showNode = useCallback(+ (nodeId: string) => {+ resetFind();+ setView('nodes');+ setShownNode((current) => ({ drawing: drawing.key, nodeId, request: (current?.request ?? 0) + 1 }));},- [mode]+ [drawing.key, resetFind]);+ const getJsonText = useCallback(() => (graph ? getGraphJsonText(graph) : ''), [graph]);- const canCopy = canCopyText();- const copyJson = useCallback(() => {- const json = JSON.stringify(graph?.backendGraph ?? graph, null, 2);+ // Only a document has a form to show. The Graph view always shows: the compiled graph, or why there is none.+ const hasInputs = sourceDocument !== undefined;+ const viewTabs = useMemo(+ () => getWorkflowPreviewViewTabs(model, { hasGraph: true, hasInputs }, t),+ [hasInputs, model, t]+ );+ const shownView = view === 'inputs' && !hasInputs ? 'nodes' : view;+ const blockedReason =+ source.invalidReasons.length > 0+ ? `${t('graphPreview.invalidTitle')} ${source.invalidReasons+ .map((reason) => localizeForLoopValidationReason(reason, t))+ .join(' ')}`+ : null;+ // A document still draws when it does not compile; a compiled source has nothing to draw.+ const isBlocked = blockedReason !== null && !sourceDocument;+ const showsNodes = shownView === 'nodes' && !isBlocked && model !== null && model.nodes.size > 0;+ // The run's facts: the source's summary, then where results go.+ const facts = [+ ...source.summaryRows,+ ...(source.destinationLabel === null+ ? []+ : [{ id: 'destination', label: t('graphPreview.destination'), value: source.destinationLabel }]),+ ];+ // The rail says what the graph alone does not: the run's facts, notices, and why a drawn document does not compile.+ const hasRail = facts.length > 0 || source.notices.length > 0 || (blockedReason !== null && !isBlocked);+ // The footer decides the run: whether it can, Invoke, and for a compiled source the way to edit it as a workflow.+ const canEditAsWorkflow = invoke !== undefined && !sourceDocument && sourceId !== 'workflow' && graph !== null;+ const subtitle = source.isLive ? t('graphPreview.liveHint') : null;+ const title = sourceDocument?.name.trim() || sourceLabel;+ const initialNodeId = requestedNodeId ?? drawing.carriedNodeId;++ const stageBody = (() => {+ if (shownView === 'graph') {+ return graph ? (+ <Suspense fallback={STAGE_LOADING}>+ <WorkflowPreviewJson+ copyFailedLabel={t('graphPreview.copyFailed')}+ copyLabel={t('graphPreview.copyGraphJson')}+ getText={getJsonText}+ label={t('workflowLibrary.preview.graphJson')}+ />+ </Suspense>+ ) : blockedReason !== null ? (+ <WorkflowPreviewStageMessage isAlert>{blockedReason}</WorkflowPreviewStageMessage>+ ) : (+ <WorkflowPreviewStageMessage>{t('graphPreview.noCompiledGraph', { graphId })}</WorkflowPreviewStageMessage>+ );+ }- copyText(json)- .then(() => {- setHasCopied(true);+ if (isBlocked) {+ return <WorkflowPreviewStageMessage isAlert>{blockedReason}</WorkflowPreviewStageMessage>;+ }++ if (!sourceDocument && !graph) {+ return (+ <WorkflowPreviewStageMessage>{t('graphPreview.noCompiledGraph', { graphId })}</WorkflowPreviewStageMessage>+ );+ }- if (copyResetTimerRef.current !== null) {- clearTimeout(copyResetTimerRef.current);- }+ if (!model) {+ return templatesSnapshot.status === 'error' ? (+ <WorkflowPreviewStageMessage isAlert>+ {t('workflowLibrary.preview.unreadable', { message: templatesSnapshot.error ?? t('common.unknownError') })}+ </WorkflowPreviewStageMessage>+ ) : (+ STAGE_LOADING+ );+ }- // Keep copy-feedback timing in the event handler; a post-unmount state update is ignored.- copyResetTimerRef.current = setTimeout(() => setHasCopied(false), COPY_RESET_DELAY_MS);- })- .catch(() => toaster.create({ title: t('graphPreview.copyFailed'), type: 'error' }));- }, [graph, t]);+ if (model.nodes.size === 0) {+ return <WorkflowPreviewStageMessage>{t('workflowLibrary.preview.empty')}</WorkflowPreviewStageMessage>;+ }- const modeTabs = useMemo(() => modeItems.map((item) => ({ id: item.value, label: t(item.labelKey) })), [t]);- const jsonLabel = useMemo(() => t('graphPreview.graphJsonLabel', { title: sourceLabel }), [t, sourceLabel]);- const subtitle = useMemo(() => {- const compiledFrom = t('graphPreview.compiledFrom', { source: sourceLabel });- return source.isLive ? `${compiledFrom} ${t('graphPreview.liveHint')}` : compiledFrom;- }, [t, sourceLabel, source.isLive]);+ return shownView === 'inputs' ? (+ <WorkflowPreviewInputs model={model} onShowNode={showNode} />+ ) : (+ <WorkflowDocumentGraph+ key={`${drawing.key}:${shownNode?.request ?? 0}`}+ ref={graphRef}+ fieldSources={fieldSources}+ focusInitialCard={requestedNodeId !== null}+ initialNodeId={initialNodeId}+ model={model}+ needsModel={needsModel}+ relayout={relayout}+ onCardChange={setCardNodeId}+ onMatchCountChange={find.onMatchCountChange}+ />+ );+ })();return (- <Dialog.Root open={isOpen} size="xl" onExitComplete={onExitComplete} onOpenChange={handleOpenChange}>+ <Dialog.Root+ lazyMount+ open={isOpen}+ size="xl"+ unmountOnExit+ onEscapeKeyDown={handleEscapeKeyDown}+ onExitComplete={handleExitComplete}+ onOpenChange={handleOpenChange}+ ><Portal><Dialog.Backdrop /><Dialog.Positioner>- <Dialog.Content h="min(46rem, 85vh)" maxH="85vh" maxW="min(72rem, calc(100vw - 4rem))">- <Dialog.Header alignItems="center" flexDirection="row" justifyContent="space-between">+ <Dialog.Content {...WORKFLOW_PREVIEW_DIALOG_SIZE}>+ <Dialog.Header alignItems="flex-start" flexDirection="row" gap="3" justifyContent="space-between"><Stack gap="0.5" minW="0">- <Dialog.Title>{t('graphPreview.title')}</Dialog.Title>- <Dialog.Description>{subtitle}</Dialog.Description>+ <Dialog.Title truncate>{title}</Dialog.Title>+ {subtitle ? <Dialog.Description>{subtitle}</Dialog.Description> : null}</Stack>- <SegmentTabs- activeId={mode}- ariaLabel={t('graphPreview.title')}- idBase={modeTabsIdBase}- isCompact- tabs={modeTabs}- onSelect={handleModeChange}- />+ <Dialog.CloseTrigger asChild>+ <CloseButton insetEnd="auto" position="static" top="auto" />+ </Dialog.CloseTrigger></Dialog.Header>- <Dialog.Body- aria-labelledby={segmentTabsTabId(modeTabsIdBase, mode)}- display="flex"- flex="1"- flexDirection="column"- gap="3"- id={segmentTabsPanelId(modeTabsIdBase)}- minH="0"- role="tabpanel"- >- {hasInvalidReasons ? (- <InvalidBanner>- <Text>- {t('graphPreview.invalidTitle')} {localizeForLoopValidationReason(source.invalidReasons[0], t)}- </Text>- </InvalidBanner>- ) : null}- {hasInvalidReasons ? null : (- <Box display="flex" flex="1" gap="3" minH="0">- <PreviewPane>- {!graph ? (- <Text color="fg.muted" fontSize="lg">- {t('graphPreview.noCompiledGraph', { graphId })}- </Text>- ) : mode === 'json' ? (- <JsonPreview h="full" label={jsonLabel} maxH="100%" value={graph} />- ) : mode === 'list' ? (- // The inset keeps the first row off the pane's rounded border.- <Box display="flex" flexDirection="column" h="full" pt="2">- <Suspense fallback={LIST_FALLBACK}>- <GraphPreviewList graph={graph} selectedNodeId={selectedNodeId} onSelect={selectAndReveal} />- </Suspense>- </Box>- ) : (- <GraphPreviewFlow- graph={graph}- positionHints={source.positionHints}- selectedNodeId={selectedNodeId}- onInit={handleFlowInit}- onNodeSelect={handleFlowNodeSelect}- />- )}- </PreviewPane>- {mode === 'graph' ? (- <GraphPreviewSidePanel- source={source}- selectedNode={selectedNode}- onBack={handleBack}- onProvenanceClick={handleProvenanceClick}- onShowNode={selectAndReveal}- />- ) : null}- </Box>- )}- </Dialog.Body>- <Dialog.Footer justifyContent="space-between">- <Box display="flex" gap="2">- <Button- unavailableReason={canCopy ? undefined : t('common.copyUnavailable')}- disabled={!graph}- variant="outline"- onClick={copyJson}- >- <Icon- as={hasCopied ? CheckIcon : CopyIcon}- boxSize="3.5"- color={hasCopied ? 'green.solid' : undefined}+ <Dialog.Body css={BODY_CSS}>+ <Stack+ borderColor="border.subtle"+ borderWidth="1px"+ data-graph-preview-stage=""+ gap="0"+ gridColumn={hasRail ? undefined : '1 / -1'}+ gridRow={hasRail ? undefined : '1 / -1'}+ minH="0"+ minW="0"+ overflow="hidden"+ rounded="md"+ >+ {/* Tabs at the start and More at the end in every view; only find comes and goes between them. */}+ <WorkflowPreviewBar>+ <SegmentTabs+ activeId={shownView}+ ariaLabel={t('workflowLibrary.preview.view')}+ idBase={viewTabsId}+ isCompact+ tabs={viewTabs}+ onSelect={selectView}/>- {hasCopied ? t('graphPreview.copied') : t('graphPreview.copyJson')}- </Button>- {graph ? (- <GraphPreviewOpenAsMenu+ <Box flex="1" />+ {showsNodes ? <WorkflowPreviewFindField find={find} /> : null}+ <GraphPreviewMoreMenugraph={graph}+ sourceDocument={sourceDocument}sourceId={sourceId}sourceLabel={sourceLabel}onClose={closeDialog}- >- <Button variant="outline">- {t('graphPreview.openAs')}- <Icon as={ChevronUpIcon} boxSize="3.5" />+ />+ </WorkflowPreviewBar>+ <Box+ aria-labelledby={segmentTabsTabId(viewTabsId, shownView)}+ flex="1"+ id={segmentTabsPanelId(viewTabsId)}+ minH="0"+ position="relative"+ role="tabpanel"+ >+ {stageBody}+ </Box>+ </Stack>+ {hasRail ? (+ <Scrollable css={RAIL_CSS} data-graph-preview-rail="" label={t('graphPreview.aboutThisGraph')} minH="0">+ <Stack gap="4" pb="1">+ {facts.length > 0 ? (+ <DataList.Root data-graph-preview-facts="" gap="1.5" orientation="horizontal">+ {facts.map((fact) => (+ <DataList.Item key={fact.id} alignItems="center" gap="2" minW="0">+ <DataList.ItemLabel color="fg.muted" flex="0 0 5.5rem" fontSize="xs" minW="0">+ {fact.label}+ </DataList.ItemLabel>+ <DataList.ItemValue flex="1" fontSize="xs" minW="0" overflowWrap="anywhere">+ {fact.value}+ </DataList.ItemValue>+ </DataList.Item>+ ))}+ </DataList.Root>+ ) : null}+ {blockedReason !== null && !isBlocked ? (+ <HStack align="flex-start" color="fg.warning" data-graph-preview-blocked="" gap="2" role="alert">+ <Icon aria-hidden as={TriangleAlertIcon} boxSize="3.5" flexShrink={0} mt="0.5" />+ <Text fontSize="md">{blockedReason}</Text>+ </HStack>+ ) : null}+ {source.notices.map((notice) => (+ <Notice key={notice.id} message={notice.message} nodeId={notice.nodeId} onShowNode={showNode} />+ ))}+ </Stack>+ </Scrollable>+ ) : null}+ </Dialog.Body>+ {invoke ? (+ <Dialog.Footer alignItems="center" data-graph-preview-footer="" gap="3" justifyContent="space-between">+ <ReadinessLine isReady={invoke.isReady} />+ <HStack flexShrink={0} gap="2">+ {canEditAsWorkflow ? (+ <Button+ data-graph-preview-edit-as-workflow=""+ disabled={!canConvert}+ variant="outline"+ onClick={editInEditor}+ >+ {t('graphPreview.editAsWorkflow')}</Button>- </GraphPreviewOpenAsMenu>- ) : null}- </Box>- <Box display="flex" gap="2">- {!hideInvoke && dialogRoute ? (- <Button- aria-disabled={!canInvoke}- cursor={canInvoke ? undefined : 'not-allowed'}- opacity={canInvoke ? undefined : 0.6}- title={validationMessage}- onClick={canInvoke ? invokeRoute : undefined}- >- {t('graphPreview.invokeRoute', { route: dialogRoute.label })}- </Button>- ) : null}- <Button variant="ghost" onClick={closeDialog}>- {t('common.close')}- </Button>- </Box>- </Dialog.Footer>+ ) : null}+ {invoke.control}+ </HStack>+ </Dialog.Footer>+ ) : null}</Dialog.Content></Dialog.Positioner></Portal></Dialog.Root>);};++/** Something about the source the graph alone does not say (a seed drawn each run), with a jump to its node. */+const Notice = ({+ message,+ nodeId,+ onShowNode,+}: {+ message: string;+ nodeId?: string;+ onShowNode: (nodeId: string) => void;+}) => {+ const { t } = useTranslation();+ const handleShowNode = useCallback(() => {+ if (nodeId) {+ onShowNode(nodeId);+ }+ }, [nodeId, onShowNode]);++ return (+ <HStack align="flex-start" data-graph-preview-notice="" gap="2">+ <Icon aria-hidden as={InfoIcon} boxSize="3.5" color="fg.muted" flexShrink={0} mt="0.5" />+ <Stack align="flex-start" gap="0.5" minW="0">+ <Text color="fg.muted" fontSize="md">+ {message}+ </Text>+ {nodeId ? (+ <Button+ color="accent.fg"+ fontSize="sm"+ fontWeight="400"+ h="auto"+ px="0"+ size="xs"+ variant="plain"+ onClick={handleShowNode}+ >+ {t('graphPreview.showNode')}+ </Button>+ ) : null}+ </Stack>+ </HStack>+ );+};++/**+ * The footer's readiness line: whether Invoke can run (its control's card says why not), a polite live region of its+ * own so a recompile says nothing until the answer changes.+ */+const ReadinessLine = ({ isReady }: { isReady: boolean }) => {+ const { t } = useTranslation();++ return (+ <HStack data-graph-preview-readiness="" flex="1" gap="2" minW="0">+ <Icon+ aria-hidden+ as={isReady ? CheckIcon : TriangleAlertIcon}+ boxSize="3.5"+ color={isReady ? 'fg.success' : 'fg.warning'}+ flexShrink={0}+ />+ <Text+ aria-live="polite"+ data-graph-preview-status=""+ fontSize="md"+ fontWeight="600"+ minW="0"+ role="status"+ truncate+ >+ {isReady ? t('graphPreview.readyToInvoke') : t('graphPreview.cannotInvoke')}+ </Text>+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsxindex 28b71abab0..c6e4db62c8 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewFlow.tsx@@ -1,17 +1,9 @@+import type { XYPosition } from '@features/workflow/core/types';import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';-import type {- Edge as FlowEdge,- Node as FlowNode,- NodeMouseHandler,- NodeProps,- NodeTypes,- ReactFlowInstance,-} from '@xyflow/react';+import type { Edge as FlowEdge, Node as FlowNode, NodeProps, NodeTypes, ReactFlowInstance } from '@xyflow/react';import type { TFunction } from 'i18next';import { Badge, Box, Stack, Text } from '@chakra-ui/react';-import { isInvocationNode, type ProjectGraphState, type XYPosition } from '@features/workflow/contracts';-import { getCanonicalWorkflowEdges } from '@features/workflow/core/forLoops';import { getLayeredPositions } from '@features/workflow/core/graphLayout';import '@xyflow/react/dist/style.css';import { LOOP_LINKAGE_STROKE } from '@features/workflow/ui/loopLinkage';@@ -23,47 +15,16 @@ import { useTranslation } from 'react-i18next';import { flowThemeCss, getFlowColorMode } from './flowTheme';import { getNodeSubtitle } from './nodeSummaries';-/** Use caller position hints when available; compiled contracts otherwise receive topological layout. */+/**+ * The graph a library thumbnail photographs (`GraphPreviewSnapshot`): each node's type and a summary, fitted. Caller+ * position hints place nodes where given; the rest take a topological layout.+ */type PreviewFlowNode = FlowNode<- { inputCount: number; isSelected: boolean; nodeId: string; nodeType: string; subtitle: string | null },+ { inputCount: number; nodeId: string; nodeType: string; subtitle: string | null },'preview'>;-/** Build a template-free contract view for documents outside the active editor, including library previews. */-export const documentToPreviewGraph = (- document: ProjectGraphState,- fallbackLabel: string-): { graph: WorkflowPreviewGraph; positionHints: Record<string, XYPosition> } => {- const invocationNodes = document.nodes.filter(isInvocationNode);- const invocationNodeIds = new Set(invocationNodes.map((node) => node.id));-- return {- graph: {- edges: getCanonicalWorkflowEdges(document)- .filter((edge) => invocationNodeIds.has(edge.source.node_id) && invocationNodeIds.has(edge.destination.node_id))- .map((edge) => ({- id: edge.id,- sourceField: edge.source.field,- sourceNodeId: edge.source.node_id,- targetField: edge.destination.field,- targetNodeId: edge.destination.node_id,- ...(edge.type ? { type: edge.type } : {}),- })),- id: document.id,- label: document.name || fallbackLabel,- nodes: invocationNodes.map((node) => ({- id: node.id,- inputs: Object.fromEntries(Object.values(node.data.inputs).map((instance) => [instance.name, instance.value])),- type: node.data.type,- })),- updatedAt: document.updatedAt,- version: 1,- },- positionHints: Object.fromEntries(document.nodes.map((node) => [node.id, node.position])),- };-};-const handleStyle = { background: 'var(--wb-flow-grid)', border: 'none' } as const;const reactFlowProOptions = { hideAttribution: true } as const;const reactFlowStyle = { background: 'transparent' } as const;@@ -72,18 +33,7 @@ const PreviewNode = ({ data }: NodeProps<PreviewFlowNode>) => {const { t } = useTranslation();return (- <Box- bg="bg"- borderColor={data.isSelected ? 'accent.solid' : 'border.emphasized'}- borderWidth="1px"- fontSize="md"- minW="14rem"- outlineColor="accent.solid"- outlineStyle={data.isSelected ? 'solid' : undefined}- outlineWidth="1px"- rounded="lg"- shadow="sm"- >+ <Box bg="bg" borderColor="border.emphasized" borderWidth="1px" fontSize="md" minW="14rem" rounded="lg" shadow="sm"><Handle position={Position.Left} style={handleStyle} type="target" /><Handle position={Position.Right} style={handleStyle} type="source" /><Stack gap="0.5" px="3" py="2">@@ -103,8 +53,7 @@ const nodeTypes: NodeTypes = { preview: PreviewNode };const toPreviewNodes = (graph: WorkflowPreviewGraph,t: TFunction,- positionHints?: Record<string, XYPosition>,- selectedNodeId?: string | null+ positionHints?: Record<string, XYPosition>): PreviewFlowNode[] => {const positions = getLayeredPositions(graph.nodes,@@ -114,7 +63,6 @@ const toPreviewNodes = (return graph.nodes.map((node) => ({data: {inputCount: Object.keys(node.inputs).length,- isSelected: node.id === selectedNodeId,nodeId: node.id,nodeType: node.type,subtitle: getNodeSubtitle(node, t),@@ -122,8 +70,6 @@ const toPreviewNodes = (id: node.id,position: positionHints?.[node.id] ?? positions[node.id] ?? { x: 0, y: 0 },type: 'preview' as const,- // Selection here is preview data, not xyflow's, so raise the selected node above overlapping neighbours manually.- ...(node.id === selectedNodeId ? { zIndex: 1 } : {}),}));};@@ -141,34 +87,21 @@ const toPreviewEdges = (graph: WorkflowPreviewGraph): FlowEdge[] =>export const GraphPreviewFlow = ({graph,positionHints,- selectedNodeId = null,onInit,- onNodeSelect,}: {graph: WorkflowPreviewGraph;positionHints?: Record<string, XYPosition>;- selectedNodeId?: string | null;- onInit?: (instance: ReactFlowInstance) => void;- onNodeSelect?: (nodeId: string | null) => void;+ onInit: (instance: ReactFlowInstance) => void;}) => {const { t } = useTranslation();const themeId = useWorkflowPreferencesSelector((preferences) => preferences.themeId);const backgroundId = useId().replace(/:/g, '');- const nodes = useMemo(- () => toPreviewNodes(graph, t, positionHints, selectedNodeId),- [graph, t, positionHints, selectedNodeId]- );+ const nodes = useMemo(() => toPreviewNodes(graph, t, positionHints), [graph, t, positionHints]);const edges = useMemo(() => toPreviewEdges(graph), [graph]);- const handleNodeClick = useCallback<NodeMouseHandler<PreviewFlowNode>>(- (_event, node) => onNodeSelect?.(node.id),- [onNodeSelect]- );- const handlePaneClick = useCallback(() => onNodeSelect?.(null), [onNodeSelect]);- // xyflow types `onInit` against this component's node/edge generics; the caller- // (`GraphPreviewDialog`) only calls generic instance methods (`fitView`), so the- // narrower instance is safe to widen back to the public, type-erased signature.+ // xyflow types `onInit` against this component's node/edge generics; the snapshot only calls generic instance+ // methods (`fitView`), so the narrower instance is safe to widen back to the public, type-erased signature.const handleInit = useCallback(- (instance: ReactFlowInstance<PreviewFlowNode, FlowEdge>) => onInit?.(instance as unknown as ReactFlowInstance),+ (instance: ReactFlowInstance<PreviewFlowNode, FlowEdge>) => onInit(instance as unknown as ReactFlowInstance),[onInit]);@@ -190,8 +123,6 @@ export const GraphPreviewFlow = ({proOptions={reactFlowProOptions}style={reactFlowStyle}onInit={handleInit}- onNodeClick={handleNodeClick}- onPaneClick={handlePaneClick}><BackgroundbgColor="var(--xy-background-color)"diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsxdeleted file mode 100644index 25b7e2d661..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewList.tsx+++ /dev/null@@ -1,72 +0,0 @@-import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';-import type { ListRowProps } from '@platform/ui/list/List';--import { getTopologicalOrder } from '@features/workflow/core/graphLayout';-import { List } from '@platform/ui/list/List';-import { ListItem } from '@platform/ui/list/ListItem';-import { listRowsFromItems } from '@platform/ui/list/listRows';-import { memo, useCallback, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import { getNodeSubtitle } from './nodeSummaries';--type PreviewListNode = WorkflowPreviewGraph['nodes'][number];--const getNodeId = (node: PreviewListNode): string => node.id;--const GraphPreviewListRow = memo(function GraphPreviewListRow({- node,- onSelect,- ...rowProps-}: ListRowProps & { node: PreviewListNode; onSelect: (nodeId: string) => void }) {- const { t } = useTranslation();- const subtitle =- getNodeSubtitle(node, t) ??- `${node.id} · ${t('graphPreview.inputCount', { count: Object.keys(node.inputs).length })}`;- const handlePress = useCallback(() => onSelect(node.id), [node.id, onSelect]);-- return <ListItem {...rowProps} description={subtitle} title={node.type} onPress={handlePress} />;-});--/** Every node in topological order, for keyboard and screen-reader access to the shared inspector. */-export const GraphPreviewList = ({- graph,- selectedNodeId,- onSelect,-}: {- graph: WorkflowPreviewGraph;- selectedNodeId: string | null;- onSelect: (nodeId: string) => void;-}) => {- const { t } = useTranslation();- // Recompute sorted rows only when the graph changes, not on unrelated live-source renders.- const rows = useMemo(() => {- const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));- const order = getTopologicalOrder(- graph.nodes,- graph.edges.map((edge) => ({ sourceNodeId: edge.sourceNodeId, targetNodeId: edge.targetNodeId }))- );- const orderedNodes = order- .map((nodeId) => nodesById.get(nodeId))- .filter((node): node is PreviewListNode => node !== undefined);-- return listRowsFromItems(orderedNodes, getNodeId);- }, [graph]);- const renderItem = useCallback(- (node: PreviewListNode, rowProps: ListRowProps) => (- <GraphPreviewListRow {...rowProps} node={node} onSelect={onSelect} />- ),- [onSelect]- );-- return (- <List- activeKey={selectedNodeId}- dividers- label={t('graphPreview.nodes')}- renderItem={renderItem}- revealActiveOnMount- rows={rows}- />- );-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewMoreMenu.tsxsimilarity index 65%rename from invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsxrename to invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewMoreMenu.tsxindex 17cf10c6bf..e461120723 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewMoreMenu.tsx@@ -3,6 +3,7 @@ import type { WorkflowInvocationSourceId, WorkflowPreviewGraph } from '@featuresimport { Checkbox, chakra, Input, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { useAuthSession } from '@features/identity';+import { cloneProjectGraph, createWorkflowId } from '@features/workflow/core/document';import { previewGraphToDocument } from '@features/workflow/core/graphToDocument';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';import {@@ -10,24 +11,25 @@ import {useWorkflowPublication,type WorkflowPublicationFailure,} from '@features/workflow/ui/library/useWorkflowPublication';-import { MenuActionItem } from '@features/workflow/ui/MenuActionItem';import {useWorkflowGraphPreview,useWorkflowHostCommands,useWorkflowNotifications,useWorkflowUi,} from '@features/workflow/ui/WorkflowUiContext';+import { canCopyText, copyText } from '@platform/browser/clipboard';import { downloadText } from '@platform/browser/downloadBlob';import { useMountEffect } from '@platform/react/useMountEffect';-import { Button, CloseButton } from '@platform/ui/Button';+import { Button, CloseButton, IconButton } from '@platform/ui/Button';import { Dialog } from '@platform/ui/Dialog';import { Field } from '@platform/ui/Field';-import { MenuContent } from '@platform/ui/Menu';-import { BookmarkIcon, DownloadIcon, GitForkIcon, PencilRulerIcon } from 'lucide-react';-import { useCallback, useRef, useState, type FormEvent, type ReactNode } from 'react';+import { MenuActionItem, MenuContent } from '@platform/ui/Menu';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { BookmarkIcon, CopyIcon, DownloadIcon, EllipsisIcon, GitForkIcon, PencilRulerIcon } from 'lucide-react';+import { useCallback, useRef, useState, type FormEvent } from 'react';import { useTranslation } from 'react-i18next';-const MENU_POSITIONING = { placement: 'top-end' } as const;+import { getGraphJsonText } from './graphJson';interface PreviewSaveRequest {document: ProjectGraphState;@@ -35,29 +37,109 @@ interface PreviewSaveRequest {name: string;}-interface GraphPreviewOpenAsMenuProps {- children: ReactNode;- graph: WorkflowPreviewGraph;+interface GraphPreviewMoreMenuProps {+ /** What runs: its compiled backend graph is what the JSON items export; null while it does not compile. */+ graph: WorkflowPreviewGraph | null;+ /** The workflow document the graph compiles from, which the Open-as items copy; else they convert `graph`. */+ sourceDocument?: ProjectGraphState;sourceId?: WorkflowInvocationSourceId;sourceLabel: string;- /** Dialog close after a successful "edit in editor". */+ /** Closes the dialog once the graph has opened elsewhere (the editor, a new project). */onClose: () => void;}/**- * Convert previews into editor/library/project documents or download raw JSON. Keep the trigger in the dialog to- * avoid another platform-barrel dependency.+ * The preview's graph as a workflow of its own, for the More menu's Open-as items and the footer's "Edit as workflow".*/-export const GraphPreviewOpenAsMenu = ({- children,+export const useGraphAsWorkflow = ({graph,+ sourceDocument,+ sourceLabel,+ onClose,+}: Pick<GraphPreviewMoreMenuProps, 'graph' | 'onClose' | 'sourceDocument' | 'sourceLabel'>) => {+ const { t } = useTranslation();+ const { workflows } = useWorkflowHostCommands();+ const graphPreview = useWorkflowGraphPreview();+ const notifications = useWorkflowNotifications();+ // A hook (not `getInvocationTemplatesSnapshot()`) so the items' disabled state updates live if the menu is opened+ // while templates are still loading.+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ // Converting a compiled graph needs the templates; copying a document does not.+ const canConvert = sourceDocument !== undefined || (graph !== null && templatesSnapshot.status === 'loaded');++ /**+ * The graph as a new workflow document of its own: a copy of the source's document where it has one, so its labels,+ * notes and form survive; else the compiled graph converted, without the node types this server lacks. Null, with+ * the reason shown, when nothing would be left.+ */+ const toNewDocument = useCallback(+ (failedKey: string): ProjectGraphState | null => {+ if (sourceDocument) {+ return {+ ...cloneProjectGraph(sourceDocument),+ id: createWorkflowId('workflow'),+ name: sourceDocument.name || sourceLabel,+ };+ }++ if (!graph) {+ return null;+ }++ const converted = previewGraphToDocument(graph, templatesSnapshot.templates);++ if (converted.document.nodes.length === 0) {+ notifications.error(t(failedKey));+ return null;+ }++ if (converted.skippedNodeTypes.length > 0) {+ notifications.info(+ t('graphPreview.nodesSkipped', {+ count: converted.skippedNodeTypes.length,+ types: converted.skippedNodeTypes.join(', '),+ })+ );+ }++ converted.document.name = graph.label ?? sourceLabel;++ return converted.document;+ },+ [graph, notifications, sourceDocument, sourceLabel, t, templatesSnapshot]+ );++ /** Adds the graph to the project as a workflow and opens it in the editor, closing the preview. */+ const editInEditor = useCallback(() => {+ const document = toNewDocument('graphPreview.editInEditorFailed');++ if (!document) {+ return;+ }++ // The preview becomes a workflow of its own beside the project's others (or takes over an untouched blank).+ workflows.addWorkflow(document, { label: t('graphPreview.openedFromPreview'), reusePlaceholder: true });+ graphPreview.openWorkflowEditor();+ onClose();+ }, [toNewDocument, t, workflows, graphPreview, onClose]);++ return { canConvert, editInEditor, toNewDocument };+};++/**+ * The graph preview's More menu: the compiled graph's JSON (what a bug report needs), and the graph opened as an editor+ * workflow, a library workflow or a project of its own.+ */+export const GraphPreviewMoreMenu = ({+ graph,+ sourceDocument,sourceId,sourceLabel,onClose,-}: GraphPreviewOpenAsMenuProps) => {+}: GraphPreviewMoreMenuProps) => {const { t } = useTranslation();+ const menuIds = useTooltipTriggerIds();const session = useAuthSession();- const { workflows } = useWorkflowHostCommands();const { project } = useWorkflowUi();const graphPreview = useWorkflowGraphPreview();const notifications = useWorkflowNotifications();@@ -67,12 +149,7 @@ export const GraphPreviewOpenAsMenu = ({const activePublicationRef = useRef<{ projectId: string; workflowId: string } | null>(null);const singleUserPublicationTargetsRef = useRef(new Set<{ projectId: string; workflowId: string }>());const isMountedRef = useRef(false);- // A hook (not `getInvocationTemplatesSnapshot()`) so the "Edit in workflow- // editor" item's disabled state updates live if the menu is opened while- // templates are still loading.- const templatesSnapshot = useInvocationTemplatesSnapshot();const canEditInEditor = sourceId !== 'workflow';- const isTemplatesLoaded = templatesSnapshot.status === 'loaded';useMountEffect(() => {isMountedRef.current = true;@@ -92,42 +169,24 @@ export const GraphPreviewOpenAsMenu = ({};});- const handleEditInEditor = useCallback(() => {- const { document, skippedNodeTypes } = previewGraphToDocument(graph, templatesSnapshot.templates);-- if (document.nodes.length === 0) {- notifications.error(t('graphPreview.editInEditorFailed'));- return;- }-- if (skippedNodeTypes.length > 0) {- notifications.info(- t('graphPreview.nodesSkipped', { count: skippedNodeTypes.length, types: skippedNodeTypes.join(', ') })- );- }-- // The preview becomes a workflow of its own beside the project's others (or takes over an untouched blank).- workflows.addWorkflow(document, { label: t('graphPreview.openedFromPreview'), reusePlaceholder: true });- graphPreview.openWorkflowEditor();- onClose();- }, [graph, templatesSnapshot, notifications, t, workflows, graphPreview, onClose]);+ const {+ canConvert,+ editInEditor: handleEditInEditor,+ toNewDocument,+ } = useGraphAsWorkflow({+ graph,+ sourceDocument,+ sourceLabel,+ onClose,+ });const saveToLibrary = useCallback(async () => {- const { document, skippedNodeTypes } = previewGraphToDocument(graph, templatesSnapshot.templates);+ const document = toNewDocument('graphPreview.saveToLibraryFailed');- if (document.nodes.length === 0) {- notifications.error(t('graphPreview.saveToLibraryFailed'));+ if (!document) {return;}- if (skippedNodeTypes.length > 0) {- notifications.info(- t('graphPreview.nodesSkipped', { count: skippedNodeTypes.length, types: skippedNodeTypes.join(', ') })- );- }-- document.name = graph.label ?? sourceLabel;-if (session.multiuserEnabled) {setSaveRequest({ document, name: document.name });return;@@ -161,7 +220,7 @@ export const GraphPreviewOpenAsMenu = ({} else {singleUserPublicationTargetsRef.current.delete(activePublication);}- }, [graph, templatesSnapshot, sourceLabel, saveDocumentAsNew, notifications, project, session.multiuserEnabled, t]);+ }, [toNewDocument, saveDocumentAsNew, notifications, project, session.multiuserEnabled, t]);const handleSaveToLibrary = useCallback(() => void saveToLibrary(), [saveToLibrary]);const closeSaveDialog = useCallback(() => {@@ -248,72 +307,91 @@ export const GraphPreviewOpenAsMenu = ({);const handleForkIntoProject = useCallback(() => {- const { document, skippedNodeTypes } = previewGraphToDocument(graph, templatesSnapshot.templates);+ const document = toNewDocument('graphPreview.forkIntoProjectFailed');- if (document.nodes.length === 0) {- notifications.error(t('graphPreview.forkIntoProjectFailed'));+ if (!document) {return;}- if (skippedNodeTypes.length > 0) {- notifications.info(- t('graphPreview.nodesSkipped', { count: skippedNodeTypes.length, types: skippedNodeTypes.join(', ') })- );- }-- document.name = graph.label ?? sourceLabel;-// The port creates + activates a fresh project before loading the// document, so the project this preview came from is left untouched.graphPreview.openDocumentInNewProject(document, t('graphPreview.openedFromPreview'));onClose();- }, [graph, templatesSnapshot, sourceLabel, notifications, t, graphPreview, onClose]);+ }, [toNewDocument, t, graphPreview, onClose]);+ const handleCopyJson = useCallback(() => {+ if (!graph) {+ return;+ }++ copyText(getGraphJsonText(graph))+ .then(() => notifications.success(t('graphPreview.graphJsonCopied')))+ .catch(() => notifications.error(t('graphPreview.copyFailed')));+ }, [graph, notifications, t]);const handleDownloadJson = useCallback(() => {+ if (!graph) {+ return;+ }+const fileName = `${(graph.label ?? 'graph').trim().replaceAll(/\s+/g, '-').toLowerCase()}.json`;- downloadText(JSON.stringify(graph.backendGraph ?? graph, null, 2), fileName, 'application/json');+ downloadText(getGraphJsonText(graph), fileName, 'application/json');}, [graph]);+ // Nothing compiled, nothing to export: the menu says why rather than hiding the items.+ const jsonUnavailable = !graph ? t('graphPreview.invalidTitle') : undefined;return (<>- <Menu.Root positioning={MENU_POSITIONING}>- <Menu.Trigger asChild>{children}</Menu.Trigger>+ <Menu.Root ids={menuIds}>+ {/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, the menu never+ takes focus and the first pointer move onto it closes it. */}+ <Menu.Trigger asChild>+ <Tooltip content={t('graphPreview.more')} ids={menuIds}>+ <IconButton aria-label={t('graphPreview.more')} data-preview-more="" size="sm" variant="outline">+ <EllipsisIcon />+ </IconButton>+ </Tooltip>+ </Menu.Trigger><Portal><Menu.Positioner>- <MenuContent minW="16rem">+ <MenuContent minW="min(14rem, var(--available-width))" maxW="var(--available-width)">+ <MenuActionItem+ icon={CopyIcon}+ label={t('graphPreview.copyGraphJson')}+ unavailableReason={jsonUnavailable ?? (canCopyText() ? undefined : t('common.copyUnavailable'))}+ value="copy-graph-json"+ onSelect={handleCopyJson}+ />+ <MenuActionItem+ icon={DownloadIcon}+ label={t('graphPreview.downloadGraphJson')}+ unavailableReason={jsonUnavailable}+ value="download-graph-json"+ onSelect={handleDownloadJson}+ />+ <Menu.Separator borderColor="border.subtle" />{canEditInEditor ? (<MenuActionItem- hint={t('graphPreview.editInEditorHint')}+ disabled={!canConvert}icon={PencilRulerIcon}- isDisabled={!isTemplatesLoaded}label={t('graphPreview.editInEditor')}value="edit-in-editor"onSelect={handleEditInEditor}/>) : null}<MenuActionItem- hint={t('graphPreview.saveToLibraryHint')}+ disabled={!canConvert}icon={BookmarkIcon}- isDisabled={!isTemplatesLoaded}label={t('graphPreview.saveToLibrary')}value="save-to-library"onSelect={handleSaveToLibrary}/><MenuActionItem- hint={t('graphPreview.forkIntoProjectHint')}+ disabled={!canConvert}icon={GitForkIcon}- isDisabled={!isTemplatesLoaded}label={t('graphPreview.forkIntoProject')}value="fork-into-project"onSelect={handleForkIntoProject}/>- <MenuActionItem- hint={t('graphPreview.downloadJsonHint')}- icon={DownloadIcon}- label={t('graphPreview.downloadJson')}- value="download-json"- onSelect={handleDownloadJson}- /></MenuContent></Menu.Positioner></Portal>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsxdeleted file mode 100644index 0c2240e6fa..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewSidePanel.tsx+++ /dev/null@@ -1,291 +0,0 @@-import type { GraphPreviewSourceState, WorkflowPreviewGraph } from '@features/workflow/ui/contracts';-import type { TFunction } from 'i18next';--import { Badge, Box, DataList, Icon, Stack, Text } from '@chakra-ui/react';-import { Button, IconButton, Scrollable } from '@platform/ui';-import { ArrowLeftIcon, SquareDashedIcon } from 'lucide-react';-import { useCallback } from 'react';-import { useTranslation } from 'react-i18next';--type PreviewGraphNode = WorkflowPreviewGraph['nodes'][number];--/** Keep the outer scroll container mounted while switching between graph summary and node inspection. */-export const GraphPreviewSidePanel = ({- source,- selectedNode,- onBack,- onProvenanceClick,- onShowNode,-}: {- source: GraphPreviewSourceState;- selectedNode: PreviewGraphNode | null;- onBack: () => void;- onProvenanceClick: () => void;- /** Selects a notice's node in the flow and brings it into view. */- onShowNode: (nodeId: string) => void;-}) => {- const { t } = useTranslation();-- return (- // Use minH=0 to retain flex stretch sizing and a genuinely overflowing scroll viewport.- <Scrollable flexShrink={0} label={t('graphPreview.thisGraph')} minH="0" w="19rem">- {selectedNode ? (- <NodeInspector node={selectedNode} source={source} onBack={onBack} onProvenanceClick={onProvenanceClick} />- ) : (- <GraphSummary source={source} onShowNode={onShowNode} />- )}- </Scrollable>- );-};--/** A notice row in the summary (e.g. randomized seed) — quiet, inline with the rows it annotates, with an optional jump to the node that caused it. */-const SummaryNotice = ({- message,- nodeId,- onShowNode,-}: {- message: string;- nodeId?: string;- onShowNode: (nodeId: string) => void;-}) => {- const { t } = useTranslation();- const handleShowNode = useCallback(() => {- if (nodeId) {- onShowNode(nodeId);- }- }, [nodeId, onShowNode]);-- return (- <Box alignItems="flex-start" display="flex" gap="1.5">- <Icon as={SquareDashedIcon} boxSize="3" color="orange.fg" flexShrink={0} mt="0.5" />- <Stack gap="0.5" minW="0">- <Text color="fg.muted" fontSize="xs">- {message}- </Text>- {nodeId ? (- <Button- alignSelf="flex-start"- fontSize="xs"- fontWeight="normal"- h="auto"- px="1"- size="sm"- variant="plain"- onClick={handleShowNode}- >- {t('graphPreview.showNode')}- </Button>- ) : null}- </Stack>- </Box>- );-};--const GraphSummary = ({- source,- onShowNode,-}: {- source: GraphPreviewSourceState;- onShowNode: (nodeId: string) => void;-}) => {- const { t } = useTranslation();- const nodeCount = source.graph?.nodes.length;-- return (- <Stack gap="2" p="2">- <Stack gap="0.5">- <Text fontSize="lg" fontWeight="semibold">- {t('graphPreview.thisGraph')}- </Text>- <Text color="fg.muted" fontSize="xs">- {t('graphPreview.selectNode')}- </Text>- </Stack>- <DataList.Root gap="1.5" orientation="horizontal">- <DataList.Item>- <DataList.ItemLabel fontSize="xs">{t('graphPreview.nodes')}</DataList.ItemLabel>- <DataList.ItemValue fontSize="xs" minW="0">- {nodeCount !== undefined ? String(nodeCount) : '—'}- </DataList.ItemValue>- </DataList.Item>-- {source.destinationLabel === null ? null : (- <DataList.Item>- <DataList.ItemLabel fontSize="xs">{t('graphPreview.destination')}</DataList.ItemLabel>- <DataList.ItemValue fontSize="xs" minW="0">- {source.destinationLabel}- </DataList.ItemValue>- </DataList.Item>- )}- {source.summaryRows.map((row) => (- <DataList.Item key={row.id}>- <DataList.ItemLabel fontSize="xs">{row.label}</DataList.ItemLabel>- <DataList.ItemValue fontSize="xs" minW="0">- {row.value}- </DataList.ItemValue>- </DataList.Item>- ))}- </DataList.Root>- {source.notices.map((notice) => (- <SummaryNotice key={notice.id} message={notice.message} nodeId={notice.nodeId} onShowNode={onShowNode} />- ))}- </Stack>- );-};--const TRUNCATE_LENGTH = 40;--/** Truncates a display string past {@link TRUNCATE_LENGTH}, reporting whether it did — callers use that to decide whether the untruncated value needs a `title` tooltip. */-const truncateForDisplay = (value: string): { display: string; isTruncated: boolean } => {- if (value.length <= TRUNCATE_LENGTH) {- return { display: value, isTruncated: false };- }-- return { display: `${value.slice(0, TRUNCATE_LENGTH)}…`, isTruncated: true };-};--/** string/number/boolean → `String`; object with a string `name` → the name; other object/array → JSON; `undefined` → `null` (caller skips the row). Untruncated — pass through {@link truncateForDisplay} for display. */-const stringifyResolvedValue = (value: unknown): string | null => {- if (value === undefined) {- return null;- }-- if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {- return String(value);- }-- if (value !== null && typeof value === 'object' && typeof (value as { name?: unknown }).name === 'string') {- return (value as { name: string }).name;- }-- return JSON.stringify(value);-};--const getDistinctProvenanceLabels = (node: PreviewGraphNode, source: GraphPreviewSourceState): string[] => {- if (!source.getProvenance) {- return [];- }-- const labels = new Set<string>();-- for (const field of Object.keys(node.inputs)) {- const provenance = source.getProvenance(node.id, field);-- if (provenance) {- labels.add(provenance.label);- }- }-- return [...labels];-};--const getEdgesInLine = (node: PreviewGraphNode, graph: WorkflowPreviewGraph | null, t: TFunction): string => {- const incoming = graph?.edges.filter((edge) => edge.targetNodeId === node.id) ?? [];-- if (incoming.length === 0) {- return t('graphPreview.edgesInNone');- }-- const sources = [...new Set(incoming.map((edge) => edge.sourceNodeId))].join(', ');-- return t('graphPreview.edgesIn', { count: incoming.length, sources });-};--const NodeInspector = ({- node,- source,- onBack,- onProvenanceClick,-}: {- node: PreviewGraphNode;- source: GraphPreviewSourceState;- onBack: () => void;- onProvenanceClick: () => void;-}) => {- const { t } = useTranslation();- const provenanceLabels = getDistinctProvenanceLabels(node, source);- const outgoingEdges = source.graph?.edges.filter((edge) => edge.sourceNodeId === node.id) ?? [];- const resolvedFields = Object.entries(node.inputs)- .map(([field, value]) => ({- field,- value: source.resolvedInputOverrides?.[node.id]?.[field] ?? stringifyResolvedValue(value),- }))- .filter((entry): entry is { field: string; value: string } => entry.value !== null);-- return (- <Stack gap="3" p="2">- <Box alignItems="center" display="flex" gap="2">- <IconButton aria-label={t('graphPreview.back')} size="sm" variant="ghost" onClick={onBack}>- <ArrowLeftIcon />- </IconButton>- <Stack gap="0" minW="0">- <Badge fontFamily="mono" w="fit-content">- {node.type}- </Badge>- <Text color="fg.muted" fontSize="xs" truncate>- {node.id}- </Text>- </Stack>- </Box>-- {provenanceLabels.length > 0 ? (- <Stack gap="1">- <Text color="fg.muted" fontSize="xs" fontWeight="semibold">- {t('graphPreview.setBy')}- </Text>- <Stack gap="0.5">- {provenanceLabels.map((label) => (- <Button- key={label}- alignSelf="flex-start"- fontSize="xs"- fontWeight="normal"- h="auto"- px="1"- size="sm"- variant="plain"- onClick={onProvenanceClick}- >- {label}- </Button>- ))}- </Stack>- </Stack>- ) : null}-- <Stack gap="1">- <Text color="fg.muted" fontSize="xs" fontWeight="semibold">- {t('graphPreview.resolvedInputs')}- </Text>- <DataList.Root gap="1.5" orientation="horizontal">- {resolvedFields.map(({ field, value }) => {- const { display, isTruncated } = truncateForDisplay(value);-- return (- <DataList.Item key={field}>- <DataList.ItemLabel fontSize="xs">{field}</DataList.ItemLabel>- <DataList.ItemValue fontSize="xs" minW="0" title={isTruncated ? value : undefined}>- {display}- </DataList.ItemValue>- </DataList.Item>- );- })}- </DataList.Root>- </Stack>-- <Stack gap="1">- <Text color="fg.muted" fontSize="xs" fontWeight="semibold">- {t('graphPreview.edges')}- </Text>- <Stack gap="0.5">- <Text fontSize="xs">{getEdgesInLine(node, source.graph, t)}</Text>- {outgoingEdges.map((edge) => (- <Text key={edge.id} fontSize="xs">- {t('graphPreview.edgesOut', { field: edge.sourceField, target: edge.targetNodeId })}- </Text>- ))}- </Stack>- </Stack>- </Stack>- );-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowDocumentGraph.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowDocumentGraph.tsxnew file mode 100644index 0000000000..5687d0d988--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowDocumentGraph.tsx@@ -0,0 +1,1507 @@+import type {+ WorkflowPreviewLayout,+ WorkflowPreviewMetrics,+ WorkflowPreviewModel,+ WorkflowPreviewNode,+ WorkflowPreviewPill,+} from '@features/workflow/core/workflowPreview';+import type {+ Edge as FlowEdge,+ EdgeProps,+ EdgeTypes,+ Node as FlowNode,+ NodeMouseHandler,+ NodeProps,+ NodeTypes,+ ReactFlowInstance,+ Viewport,+} from '@xyflow/react';+import type { TFunction } from 'i18next';++import { Box, chakra, HStack, Icon, Stack, type SystemStyleObject, Text } from '@chakra-ui/react';+import {+ chooseWorkflowPreviewChipWidth,+ findWorkflowPreviewNodes,+ getWorkflowPreviewMetrics,+ WORKFLOW_PREVIEW_METRICS,+} from '@features/workflow/core/workflowPreview';+import '@xyflow/react/dist/style.css';+import { LOOP_LINKAGE_STROKE } from '@features/workflow/ui/loopLinkage';+import { useWorkflowPreferencesSelector } from '@features/workflow/ui/WorkflowUiContext';+import { createKeyedTransientStore, type KeyedTransientStore } from '@platform/state/externalStore';+import { Button, IconButton } from '@platform/ui/Button';+import { Tooltip } from '@platform/ui/Tooltip';+import {+ Background,+ BackgroundVariant,+ getBezierPath,+ getViewportForBounds,+ Handle,+ MiniMap,+ Position,+ ReactFlow,+ ReactFlowProvider,+ useReactFlow,+ useStore,+} from '@xyflow/react';+import { FlagIcon, MinusIcon, PencilLineIcon, PlusIcon, TriangleAlertIcon, XIcon } from 'lucide-react';+import {+ createContext,+ memo,+ type KeyboardEvent as ReactKeyboardEvent,+ type Ref,+ type RefObject,+ use,+ useCallback,+ useId,+ useImperativeHandle,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { flushSync } from 'react-dom';+import { useTranslation } from 'react-i18next';++import { flowThemeCss, getFlowColorMode } from './flowTheme';+import { formatWorkflowPreviewValue, getWorkflowNodeSummary } from './nodeSummaries';++/**+ * The library preview's graph of a saved workflow document (`buildWorkflowPreviewModel`): compact title chips, opened+ * simplified when anything folds, at a readable zoom. Selecting a node opens a card beside it and lights its+ * connections. Selection and find matches reach nodes and edges through a keyed store, so a change re-renders only the+ * nodes whose emphasis changes; dimming the rest is the container's CSS.+ */++export interface WorkflowDocumentGraphHandle {+ /** Closes the node card; false when none was open, so Escape can go on to leave the preview. */+ closeNodeCard: () => boolean;+ /** Emphasises the nodes matching a title or type id; a blank query clears it. */+ find: (query: string) => void;+ /** Centres the next match after the current one. */+ revealNextMatch: () => void;+}++export interface WorkflowDocumentGraphProps {+ ref?: Ref<WorkflowDocumentGraphHandle>;+ /** The drawing, laid out at the narrowest chips; the graph widens them where its stage has the room. */+ model: WorkflowPreviewModel;+ /** The same drawing laid out at other metrics (a wider chip), handed the last such layout to keep what it can. */+ relayout: (metrics: WorkflowPreviewMetrics, previous: WorkflowPreviewModel | null) => WorkflowPreviewModel;+ /** Nodes with a model requirement this server has not resolved. */+ needsModel: ReadonlySet<string>;+ /** A node to open selected, its card showing (an input's node, from the Inputs view). */+ initialNodeId?: string | null;+ /**+ * Whether the initial node's card takes focus (default). A card carried over from a previous drawing takes it only+ * when focus was lost with that drawing.+ */+ focusInitialCard?: boolean;+ /** Hears which node's card is open, as it opens and closes. */+ onCardChange?: (nodeId: string | null) => void;+ /** Hears how many drawn nodes match the find query, whenever the query or the drawn nodes change. */+ onMatchCountChange?: (count: number) => void;+ /** Where a compiled source's fields were set ("Generate → Steps"); the node card links each to its setting. */+ fieldSources?: WorkflowPreviewFieldSources;+}++export interface WorkflowPreviewFieldSources {+ /** The setting a field's value comes from, or null. */+ describe: (nodeId: string, fieldName: string) => string | null;+ /** Goes to the settings; the graph's host closes. */+ onSelect: () => void;+}++type Emphasis = 'selected' | 'related' | 'match' | 'current';+type EmphasisStore = KeyedTransientStore<string, Emphasis>;++interface ChipData extends Record<string, unknown> {+ node: WorkflowPreviewNode;+ pills: readonly WorkflowPreviewPill[];+ needsModel: boolean;+ summary: string | null;+}++type ChipNode = FlowNode<ChipData, 'chip'>;+type PreviewEdgeData = {+ isLoopLinkage: boolean;+ isRerouted: boolean;+ /** How far below the chip's middle (above, when negative) the edge meets its target. */+ entryOffset: number;+} & Record<string, unknown>;+type PreviewFlowEdge = FlowEdge<PreviewEdgeData, 'preview'>;++const { nodeHeight: NODE_HEIGHT, pillHeight: PILL_HEIGHT } = WORKFLOW_PREVIEW_METRICS;+/** A chip's title sits inside 10px of padding and a border of up to 2px on each side. */+const CHIP_TITLE_INSET = 24;+/** The smallest a chip's title may appear on screen. */+const MIN_TITLE_PX = 10;+/** Chip titles are the `md` size: 0.75rem. */+const TITLE_REM = 0.75;+const MIN_ZOOM = 0.1;+const MAX_ZOOM = 2;+const FIT_PADDING = 0.04;+/** A simplified graph shorter than this share of the stage spreads its rows out, up to the stretch limit. */+const ROW_SPREAD_SHARE = 0.6;+const MAX_ROW_STRETCH = 2.5;+const MINIMAP_STYLE = { height: 80, margin: 0, position: 'static', width: 128 } as const;+/** The gap left before the graph's start when it opens at the readable zoom rather than fitted. */+const START_INSET = 24;+/** Edges into one chip meet it this far apart, ordered as their sources sit, within a band this tall. */+const ENTRY_STEP = 6;+const ENTRY_SPAN = 24;+/** Between a control and the nodes fitted beside it. */+const CONTROL_GAP = 8;+const CARD_WIDTH = 300;+const CARD_GAP = 12;+const CARD_MARGIN = 8;+/**+ * The stage's controls sit over the graph; an open node card sits over them, in the same layer, so its chips and Close+ * are never under a control (it is placed clear of them where it can be).+ */+const OVERLAY_Z = 5;+const CARD_Z = 6;+/** The height a card is placed for until it has been measured. */+const CARD_ESTIMATED_HEIGHT = 300;+const ZOOM_STEP_DURATION = 150;+const REVEAL_DURATION = 200;++const EmphasisContext = createContext<EmphasisStore | null>(null);++const useEmphasis = (id: string): Emphasis | undefined => {+ const store = use(EmphasisContext);++ if (!store) {+ throw new Error('Preview graph parts render inside WorkflowDocumentGraph.');+ }++ return store.useValue(id);+};++/** The lowest zoom at which chip titles stay at least `MIN_TITLE_PX` on screen, at the page's root font size. */+const getReadableZoom = () => {+ const rootPx = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;++ return Math.min(1, MIN_TITLE_PX / (rootPx * TITLE_REM));+};++const prefersReducedMotion = () => globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;+const motion = (duration: number) => (prefersReducedMotion() ? 0 : duration);++/**+ * A node's flow box: its chip. Edges meet the chip's middle, so the pills it stacks above it sit outside the box+ * xyflow measures and draws to.+ */+const getChipBox = (layout: WorkflowPreviewLayout, id: string) => {+ const { x, y } = layout.positions[id] ?? { x: 0, y: 0 };++ return { height: NODE_HEIGHT, width: layout.nodeWidth, x, y };+};++/** What a node takes up on the stage: its chip and the pills above it. */+const getNodeBox = (layout: WorkflowPreviewLayout, id: string) => {+ const chip = getChipBox(layout, id);+ const pillsHeight = (layout.pills[id]?.length ?? 0) * PILL_HEIGHT;++ return { ...chip, height: chip.height + pillsHeight, y: chip.y - pillsHeight };+};++const getLayoutBounds = (layout: WorkflowPreviewLayout) => {+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const id of layout.nodeIds) {+ const box = getNodeBox(layout, id);++ minX = Math.min(minX, box.x);+ minY = Math.min(minY, box.y);+ maxX = Math.max(maxX, box.x + box.width);+ maxY = Math.max(maxY, box.y + box.height);+ }++ return layout.nodeIds.length === 0+ ? { height: 0, width: 0, x: 0, y: 0 }+ : { height: maxY - minY, width: maxX - minX, x: minX, y: minY };+};++/** The stage's bands the controls cover: the legend along the top, zoom and the node count along the bottom. */+interface StageArea {+ width: number;+ height: number;+ top: number;+ bottom: number;+}++/**+ * The stage, less the bands its controls cover (`[data-preview-overlay]` above or below its middle) and a gap, so a+ * graph fitted or started in what is left never sits under a control.+ */+const measureStageArea = (stage: HTMLElement): StageArea => {+ const box = stage.getBoundingClientRect();+ let top = 0;+ let bottom = 0;++ for (const control of stage.querySelectorAll('[data-preview-overlay]')) {+ const rect = control.getBoundingClientRect();++ if (rect.height === 0) {+ continue;+ }++ if (rect.top + rect.height / 2 < box.top + box.height / 2) {+ top = Math.max(top, rect.bottom - box.top + CONTROL_GAP);+ } else {+ bottom = Math.max(bottom, box.bottom - rect.top + CONTROL_GAP);+ }+ }++ return { bottom, height: stage.clientHeight, top, width: stage.clientWidth };+};++/** The whole layout, fitted into the stage's open area. */+const getFittedViewport = (bounds: ReturnType<typeof getLayoutBounds>, area: StageArea) => {+ const open = Math.max(1, area.height - area.top - area.bottom);+ const fitted = getViewportForBounds(bounds, area.width, open, MIN_ZOOM, 1, FIT_PADDING);++ return { ...fitted, y: fitted.y + area.top };+};++/**+ * Fitted when that keeps titles readable; otherwise the readable zoom, starting at the graph's left edge (and its top,+ * when it is also too tall), with the minimap for the rest. Either way clear of the controls.+ */+const getOpeningViewport = (+ layout: WorkflowPreviewLayout,+ area: StageArea+): { isClipped: boolean; viewport: Viewport } => {+ const bounds = getLayoutBounds(layout);+ const fitted = getFittedViewport(bounds, area);+ const readable = getReadableZoom();++ if (fitted.zoom >= readable) {+ return { isClipped: false, viewport: fitted };+ }++ const zoom = readable;+ const scaledHeight = bounds.height * zoom;+ const open = area.height - area.top - area.bottom;++ return {+ isClipped: true,+ viewport: {+ x: START_INSET - bounds.x * zoom,+ y:+ scaledHeight + START_INSET * 2 <= open+ ? area.top + (open - scaledHeight) / 2 - bounds.y * zoom+ : area.top + START_INSET - bounds.y * zoom,+ zoom,+ },+ };+};++const handleStyle = {+ background: 'transparent',+ border: 'none',+ height: 1,+ minHeight: 1,+ minWidth: 1,+ width: 1,+} as const;+const proOptions = { hideAttribution: true } as const;+const flowStyle = { background: 'transparent' } as const;+const NO_PILLS: readonly WorkflowPreviewPill[] = [];++const CONTAINER_CSS: SystemStyleObject = {+ ...flowThemeCss,+ '& .react-flow__node': { cursor: 'pointer' },+ '& .react-flow__node:focus-visible': { outline: 'none' },+ '& .react-flow__node:focus-visible [data-preview-chip]': {+ outlineColor: 'accent.solid',+ outlineOffset: '2px',+ outlineStyle: 'solid',+ outlineWidth: '2px',+ },+ '& [data-preview-node]': { transitionDuration: 'fast', transitionProperty: 'opacity' },+ '& [data-preview-edge]': { transitionDuration: 'fast', transitionProperty: 'opacity, stroke' },+ '& [data-preview-edge][data-emphasis]': { stroke: 'accent.solid', strokeWidth: '2' },+ '&[data-dimmed] [data-preview-node]:not([data-emphasis])': { opacity: 0.38 },+ '&[data-dimmed] [data-preview-edge]:not([data-emphasis])': { opacity: 0.25 },+ '@media (prefers-reduced-motion: reduce)': {+ '& [data-preview-node], & [data-preview-edge]': { transitionDuration: '0ms' },+ },+};++const CHIP_EMPHASIS: Record<Emphasis, SystemStyleObject> = {+ current: { borderColor: 'accent.solid', boxShadow: '0 0 0 2px {colors.accent.solid}' },+ match: { borderColor: 'accent.solid' },+ related: { borderColor: 'accent.emphasized' },+ selected: { borderColor: 'accent.solid', boxShadow: '0 0 0 1px {colors.accent.solid}' },+};++const MarkerIcon = ({ marker }: { marker: 'exposed' | 'needsModel' | 'result' }) =>+ marker === 'exposed' ? (+ <Icon as={PencilLineIcon} aria-hidden boxSize="2.5" color="accent.fg" data-marker={marker} flexShrink={0} />+ ) : marker === 'needsModel' ? (+ <Icon as={TriangleAlertIcon} aria-hidden boxSize="2.5" color="fg.warning" data-marker={marker} flexShrink={0} />+ ) : (+ <Icon as={FlagIcon} aria-hidden boxSize="2.5" color="fg.muted" data-marker={marker} flexShrink={0} />+ );++const PillLabel = ({ pill }: { pill: WorkflowPreviewPill }) => {+ const { t } = useTranslation();++ return (+ <>+ {pill.label}+ {pill.value ? (+ <chakra.span color="fg" ms="1">+ {' '}+ {formatWorkflowPreviewValue(pill.value, t)}+ </chakra.span>+ ) : null}+ </>+ );+};++const PreviewChip = memo(function PreviewChip({ id, data }: NodeProps<ChipNode>) {+ const emphasis = useEmphasis(id);+ const { needsModel, node, pills, summary } = data;++ // The flow node is the chip, so edges meet its middle; the pills stack above it, outside the box xyflow measures.+ return (+ <Box data-emphasis={emphasis} data-preview-node={id} h="full" position="relative" w="full">+ {pills.length > 0 ? (+ <Stack bottom="100%" gap="1" insetStart="0" pb="1" position="absolute" w="full">+ {pills.map((pill) => (+ <Box+ key={pill.nodeId}+ alignSelf="flex-start"+ bg="accent.subtle"+ borderColor="accent.muted"+ borderWidth="1px"+ color="accent.fg"+ data-preview-pill={pill.nodeId}+ fontSize="sm"+ h="5.5"+ lineHeight="1.25rem"+ maxW="full"+ px="2"+ rounded="full"+ truncate+ >+ <PillLabel pill={pill} />{' '}+ </Box>+ ))}+ </Stack>+ ) : null}+ <Stack+ bg={node.isUnknown ? 'bg.error' : 'bg.panel'}+ borderColor={node.isUnknown ? 'border.error' : node.isResult ? 'fg.muted' : 'border.emphasized'}+ borderWidth={node.isResult ? '2px' : '1px'}+ css={emphasis ? CHIP_EMPHASIS[emphasis] : undefined}+ data-preview-chip=""+ gap="0.5"+ h={`${NODE_HEIGHT}px`}+ justify="center"+ position="relative"+ px="2.5"+ rounded="lg"+ w="full"+ >+ <Handle isConnectable={false} position={Position.Left} style={handleStyle} type="target" />+ <Handle isConnectable={false} position={Position.Right} style={handleStyle} type="source" />+ <Text+ color={node.isUnknown ? 'fg.error' : 'fg'}+ fontFamily={node.title === node.type ? 'mono' : undefined}+ fontSize="md"+ fontWeight="600"+ lineHeight="1.2"+ truncate+ >+ {node.title}{' '}+ </Text>+ {node.isUnknown || summary || node.isExposed || needsModel || node.isResult ? (+ <HStack color={node.isUnknown ? 'fg.error' : 'fg.muted'} fontSize="xs" gap="1" lineHeight="1.2" minW="0">+ {node.isExposed ? <MarkerIcon marker="exposed" /> : null}+ {needsModel ? <MarkerIcon marker="needsModel" /> : null}+ {node.isResult ? <MarkerIcon marker="result" /> : null}+ <Text fontFamily={node.isUnknown && node.title !== node.type ? 'mono' : undefined} truncate>+ {summary}+ </Text>+ </HStack>+ ) : null}+ </Stack>+ </Box>+ );+});++const PreviewEdge = memo(function PreviewEdge({+ id,+ data,+ sourcePosition,+ sourceX,+ sourceY,+ targetPosition,+ targetX,+ targetY,+}: EdgeProps<PreviewFlowEdge>) {+ const emphasis = useEmphasis(id);+ const [path] = getBezierPath({+ sourcePosition,+ sourceX,+ sourceY,+ targetPosition,+ targetX,+ targetY: targetY + (data?.entryOffset ?? 0),+ });+ const isLoopLinkage = data?.isLoopLinkage === true;++ return (+ <path+ className="react-flow__edge-path"+ d={path}+ data-emphasis={emphasis}+ data-preview-edge={id}+ data-rerouted={data?.isRerouted ? '' : undefined}+ fill="none"+ stroke={isLoopLinkage ? LOOP_LINKAGE_STROKE : undefined}+ strokeDasharray={isLoopLinkage ? '6 4' : data?.isRerouted ? '4 4' : undefined}+ />+ );+});++const nodeTypes: NodeTypes = { chip: PreviewChip };+const edgeTypes: EdgeTypes = { preview: PreviewEdge };++const ZoomControls = ({ onFit }: { onFit: () => void }) => {+ const { t } = useTranslation();+ const { zoomIn, zoomOut } = useReactFlow();+ const zoom = useStore((state) => state.transform[2]);+ const handleZoomIn = useCallback(() => void zoomIn({ duration: motion(ZOOM_STEP_DURATION) }), [zoomIn]);+ const handleZoomOut = useCallback(() => void zoomOut({ duration: motion(ZOOM_STEP_DURATION) }), [zoomOut]);++ return (+ <Box bottom="3" data-preview-overlay="" insetStart="3" position="absolute" zIndex={OVERLAY_Z}>+ <HStack+ bg="bg.panel"+ borderColor="border.subtle"+ borderWidth="1px"+ gap="0.5"+ p="0.5"+ role="group"+ aria-label={t('workflowLibrary.preview.zoomControls')}+ rounded="md"+ shadow="sm"+ >+ <Tooltip content={t('workflowLibrary.preview.zoomOut')}>+ <IconButton+ aria-label={t('workflowLibrary.preview.zoomOut')}+ disabled={zoom <= MIN_ZOOM}+ size="xs"+ variant="ghost"+ onClick={handleZoomOut}+ >+ <MinusIcon />+ </IconButton>+ </Tooltip>+ <Text fontSize="md" fontVariantNumeric="tabular-nums" textAlign="center" w="10">+ {t('workflowLibrary.preview.zoomPercent', { percent: Math.round(zoom * 100) })}+ </Text>+ <Tooltip content={t('workflowLibrary.preview.zoomIn')}>+ <IconButton+ aria-label={t('workflowLibrary.preview.zoomIn')}+ disabled={zoom >= MAX_ZOOM}+ size="xs"+ variant="ghost"+ onClick={handleZoomIn}+ >+ <PlusIcon />+ </IconButton>+ </Tooltip>+ <Button size="xs" variant="ghost" onClick={onFit}>+ {t('workflowLibrary.preview.fit')}+ </Button>+ </HStack>+ </Box>+ );+};++const Legend = ({ exposed, needsModel, result }: { exposed: boolean; needsModel: boolean; result: boolean }) => {+ const { t } = useTranslation();++ if (!exposed && !needsModel && !result) {+ return null;+ }++ return (+ <Box data-preview-overlay="" insetStart="3" position="absolute" top="3" zIndex={OVERLAY_Z}>+ <HStack+ aria-label={t('workflowLibrary.preview.legend')}+ as="ul"+ color="fg.muted"+ data-preview-legend=""+ fontSize="sm"+ gap="3.5"+ listStyleType="none"+ role="list"+ >+ {exposed ? (+ <HStack as="li" gap="1.5">+ <MarkerIcon marker="exposed" />+ {t('workflowLibrary.preview.youSetThis')}+ </HStack>+ ) : null}+ {needsModel ? (+ <HStack as="li" gap="1.5">+ <MarkerIcon marker="needsModel" />+ {t('workflowLibrary.preview.needsModel')}+ </HStack>+ ) : null}+ {result ? (+ <HStack as="li" gap="1.5">+ <MarkerIcon marker="result" />+ {t('workflowLibrary.preview.result')}+ </HStack>+ ) : null}+ </HStack>+ </Box>+ );+};++/** A From or To chip: selects that neighbour and brings it into view. */+const NeighbourChip = ({+ nodeId,+ title,+ onShowNode,+}: {+ nodeId: string;+ title: string;+ onShowNode: (nodeId: string) => void;+}) => {+ const handleClick = useCallback(() => onShowNode(nodeId), [nodeId, onShowNode]);++ return (+ <Button h="5" maxW="full" px="2" rounded="full" size="xs" variant="outline" onClick={handleClick}>+ <Text as="span" truncate>+ {title}+ </Text>+ </Button>+ );+};++const LAST_FIELD_ROW = { borderBottomWidth: '0' } as const;+const NO_RECTS: readonly never[] = [];++interface Rect {+ left: number;+ top: number;+ width: number;+ height: number;+}++const overlapArea = (a: Rect, b: Rect) =>+ Math.max(0, Math.min(a.left + a.width, b.left + b.width) - Math.max(a.left, b.left)) *+ Math.max(0, Math.min(a.top + a.height, b.top + b.height) - Math.max(a.top, b.top));++/**+ * Covering its own node, even a strip of it (a card clamped into the stage), costs far more than covering the rest: the+ * card describes that node.+ */+const OWN_NODE_WEIGHT = 50;++/**+ * Where a node's card goes: beside the node, right or left, else below or above it, whichever covers the least of the+ * drawn nodes (its own node most of all) and of the stage's controls, kept inside the stage.+ */+const placeCard = (+ layout: WorkflowPreviewLayout,+ nodeId: string,+ [x, y, zoom]: readonly [number, number, number],+ width: number,+ height: number,+ measuredHeight: number | null,+ controls: readonly Rect[]+) => {+ const toScreen = (box: ReturnType<typeof getNodeBox>) => ({+ height: box.height * zoom,+ left: box.x * zoom + x,+ top: box.y * zoom + y,+ width: box.width * zoom,+ });+ // Beside the chip or below it; above it goes above its pills too, which the card must not cover either.+ const chip = toScreen(getChipBox(layout, nodeId));+ const node = toScreen(getNodeBox(layout, nodeId));+ const cardHeight = Math.min(measuredHeight ?? CARD_ESTIMATED_HEIGHT, height - CARD_MARGIN * 2);+ const clamp = (left: number, top: number) => ({+ height: cardHeight,+ left: Math.max(CARD_MARGIN, Math.min(left, width - CARD_MARGIN - CARD_WIDTH)),+ top: Math.max(CARD_MARGIN, Math.min(top, height - CARD_MARGIN - cardHeight)),+ width: CARD_WIDTH,+ });+ const candidates = [+ clamp(chip.left + chip.width + CARD_GAP, chip.top),+ clamp(chip.left - CARD_GAP - CARD_WIDTH, chip.top),+ clamp(chip.left, chip.top + chip.height + CARD_GAP),+ clamp(chip.left, node.top - CARD_GAP - cardHeight),+ ];+ const others = layout.nodeIds.filter((id) => id !== nodeId).map((id) => toScreen(getNodeBox(layout, id)));+ const cost = (card: (typeof candidates)[number]) =>+ overlapArea(card, node) * OWN_NODE_WEIGHT ++ controls.reduce((sum, control) => sum + overlapArea(card, control) * 2, 0) ++ others.reduce((sum, other) => sum + overlapArea(card, other), 0);++ return candidates.reduce((best, candidate) => (cost(candidate) < cost(best) ? candidate : best));+};++const NodeCard = ({+ fieldSources,+ layout,+ model,+ needsModel,+ node,+ onClose,+ onShowNode,+ ref,+}: {+ fieldSources: WorkflowPreviewFieldSources | undefined;+ layout: WorkflowPreviewLayout;+ model: WorkflowPreviewModel;+ needsModel: boolean;+ /** A node the layout draws. */+ node: WorkflowPreviewNode;+ onClose: () => void;+ onShowNode: (nodeId: string) => void;+ ref: RefObject<HTMLDivElement | null>;+}) => {+ const { t } = useTranslation();+ const titleId = useId();+ const transform = useStore((state) => state.transform);+ const width = useStore((state) => state.width);+ const height = useStore((state) => state.height);+ const nodeId = node.id;+ const neighbours = layout.neighbours[nodeId] ?? { sources: [], targets: [] };+ // Placed for its real height and the controls' boxes once measured (before paint), so a long note does not run over+ // the node and the card keeps clear of the controls where it can. A live source's new values measure again.+ const [measured, setMeasured] = useState<{ controls: readonly Rect[]; height: number; nodeId: string } | null>(null);+ const isMeasured = measured?.nodeId === nodeId;+ const { left, top } = placeCard(+ layout,+ nodeId,+ transform,+ width,+ height,+ isMeasured ? measured.height : null,+ isMeasured ? measured.controls : NO_RECTS+ );++ useLayoutEffect(() => {+ const card = ref.current;+ const stage = card?.parentElement;++ if (!card || !stage) {+ return;+ }++ const origin = stage.getBoundingClientRect();+ const controls = [...stage.querySelectorAll('[data-preview-overlay]')].map((control) => {+ const box = control.getBoundingClientRect();++ return { height: box.height, left: box.left - origin.left, top: box.top - origin.top, width: box.width };+ });++ setMeasured({ controls, height: card.scrollHeight, nodeId: node.id });+ }, [node, ref]);++ const neighbourChips = (ids: readonly string[]) => (+ <HStack flexWrap="wrap" gap="1">+ {ids.map((id) => (+ <NeighbourChip key={id} nodeId={id} title={model.nodes.get(id)?.title ?? id} onShowNode={onShowNode} />+ ))}+ </HStack>+ );++ return (+ <Stack+ ref={ref}+ aria-labelledby={titleId}+ bg="bg.panel"+ borderColor="border.emphasized"+ borderWidth="1px"+ className="nowheel nopan nodrag"+ data-preview-node-card={nodeId}+ gap="2.5"+ left={`${left}px`}+ maxH={`${height - top - CARD_MARGIN}px`}+ overflowY="auto"+ p="3"+ position="absolute"+ role="dialog"+ rounded="lg"+ shadow="lg"+ tabIndex={-1}+ top={`${top}px`}+ w={`${CARD_WIDTH}px`}+ zIndex={CARD_Z}+ >+ <HStack align="flex-start" gap="2">+ <Stack flex="1" gap="0.5" minW="0">+ <Text fontSize="lg" fontWeight="600" id={titleId} overflowWrap="anywhere">+ {node.title}+ </Text>+ <Text color="fg.muted" fontFamily="mono" fontSize="xs" overflowWrap="anywhere">+ {node.type}+ </Text>+ </Stack>+ <Tooltip content={t('common.close')}>+ <IconButton aria-label={t('common.close')} size="xs" variant="ghost" onClick={onClose}>+ <XIcon />+ </IconButton>+ </Tooltip>+ </HStack>+ {node.isUnknown ? (+ <Text color="fg.error" fontSize="md">+ {t('workflowLibrary.preview.unknownNode')}+ </Text>+ ) : null}+ {needsModel ? (+ <HStack color="fg.warning" fontSize="md" gap="1.5">+ <MarkerIcon marker="needsModel" />+ {t('workflowLibrary.preview.needsModelNote')}+ </HStack>+ ) : null}+ {node.notes ? (+ <Text color="fg.muted" fontSize="md" overflowWrap="anywhere" whiteSpace="pre-wrap">+ {node.notes}+ </Text>+ ) : null}+ {node.fields.length > 0 ? (+ <Stack as="dl" gap="0">+ {node.fields.map((field) => {+ const source = fieldSources?.describe(nodeId, field.name) ?? null;++ return (+ <HStack+ key={field.name}+ align="flex-start"+ borderBottomWidth="1px"+ borderColor="border.subtle"+ fontSize="md"+ gap="2.5"+ justify="space-between"+ py="1"+ _last={LAST_FIELD_ROW}+ >+ <HStack as="dt" color={field.isExposed ? 'fg' : 'fg.muted'} gap="1.5" minW="0">+ {field.isExposed ? <MarkerIcon marker="exposed" /> : null}+ <Text truncate>{field.label}</Text>+ {field.isExposed ? <Text srOnly>{t('workflowLibrary.preview.youSetThisInline')}</Text> : null}+ </HStack>+ <Stack as="dd" align="flex-end" gap="0" maxW="55%" minW="0">+ <Text maxW="full" textAlign="end" truncate>+ {formatWorkflowPreviewValue(field.value, t)}+ </Text>+ {source && fieldSources ? (+ <Button+ color="accent.fg"+ data-preview-field-source=""+ fontSize="sm"+ fontWeight="400"+ h="auto"+ maxW="full"+ minW="0"+ px="0"+ size="xs"+ variant="plain"+ onClick={fieldSources.onSelect}+ >+ <Text as="span" truncate>+ {source}+ </Text>+ </Button>+ ) : null}+ </Stack>+ </HStack>+ );+ })}+ </Stack>+ ) : null}+ {neighbours.sources.length > 0 ? (+ <Stack gap="1">+ <Text color="fg.muted" fontSize="sm">+ {t('workflowLibrary.preview.from')}+ </Text>+ {neighbourChips(neighbours.sources)}+ </Stack>+ ) : null}+ {neighbours.targets.length > 0 ? (+ <Stack gap="1">+ <Text color="fg.muted" fontSize="sm">+ {t('workflowLibrary.preview.to')}+ </Text>+ {neighbourChips(neighbours.targets)}+ </Stack>+ ) : null}+ </Stack>+ );+};++const StyledMiniMap = chakra(MiniMap);++/**+ * The chip's second line: what the node's type says about its values, else where its model stands, else its first+ * exposed input with a short value. An unknown node shows its type id: as its title when unlabelled, else here.+ */+const getChipSummary = (node: WorkflowPreviewNode, needsModel: boolean, t: TFunction): string | null => {+ if (node.isUnknown) {+ return node.title === node.type ? t('workflowLibrary.preview.nodePackMissing') : node.type;+ }++ const typed = getWorkflowNodeSummary(node.values, t);++ if (typed) {+ return typed;+ }++ if (needsModel) {+ return t('workflowLibrary.preview.modelNotInstalled');+ }++ if (node.modelRequirements.some((requirement) => requirement.kind === 'slot')) {+ return t('workflowLibrary.preview.modelToPick');+ }++ return node.exposedSummary+ ? `${node.exposedSummary.label} ${formatWorkflowPreviewValue(node.exposedSummary.value, t)}`+ : null;+};++/** The layout with its rows spread `stretch` times further apart, keeping each chip's height and its pills. */+const stretchRows = (layout: WorkflowPreviewLayout, stretch: number): WorkflowPreviewLayout =>+ stretch === 1+ ? layout+ : {+ ...layout,+ positions: Object.fromEntries(+ Object.entries(layout.positions).map(([id, position]) => [id, { x: position.x, y: position.y * stretch }])+ ),+ };++/**+ * How far to spread a simplified graph's rows: a wide, short layered graph fitted to the stage would leave most of its+ * height empty and its edges bunched, so rows spread until the graph takes `ROW_SPREAD_SHARE` of it.+ */+const getRowStretch = (layout: WorkflowPreviewLayout, zoom: number, stageHeight: number) => {+ const tops = layout.nodeIds.map((id) => layout.positions[id]!.y);+ const highest = Math.min(...tops);+ const span = Math.max(...tops) - highest;++ // Spread, the chips span `span * stretch`, below the pills over the highest one and above the lowest one's height.+ return span <= 0+ ? 1+ : Math.min(MAX_ROW_STRETCH, Math.max(1, ((stageHeight * ROW_SPREAD_SHARE) / zoom - NODE_HEIGHT - highest) / span));+};++const getNodeName = (+ node: WorkflowPreviewNode,+ needsModel: boolean,+ pills: readonly WorkflowPreviewPill[],+ summary: string | null,+ t: TFunction+) =>+ [+ ...pills.map((pill) => (pill.value ? `${pill.label} ${formatWorkflowPreviewValue(pill.value, t)}` : pill.label)),+ node.title,+ summary,+ node.isUnknown ? t('workflowLibrary.preview.unknownNodeMarker') : null,+ node.isExposed ? t('workflowLibrary.preview.youSetThisInline') : null,+ needsModel ? t('workflowLibrary.preview.needsModelInline') : null,+ node.isResult ? t('workflowLibrary.preview.resultInline') : null,+ ]+ .filter((part) => part !== null)+ .join(' ');++/** `next`, with each item that equals its predecessor of the same id replaced by that predecessor. */+const keepUnchanged = <Item extends { id: string }>(+ previous: readonly Item[],+ next: Item[],+ isSame: (a: Item, b: Item) => boolean+): Item[] => {+ const byId = new Map(previous.map((item) => [item.id, item]));++ return next.map((item) => {+ const prior = byId.get(item.id);++ return prior && isSame(prior, item) ? prior : item;+ });+};++/** The same items, in the same order. */+const isSameItems = <Item,>(a: readonly Item[], b: readonly Item[]) =>+ a.length === b.length && a.every((item, index) => item === b[index]);++const isSameChip = (a: ChipNode, b: ChipNode) =>+ a.ariaLabel === b.ariaLabel &&+ a.position.x === b.position.x &&+ a.position.y === b.position.y &&+ a.width === b.width &&+ a.height === b.height &&+ a.data.node === b.data.node &&+ a.data.pills === b.data.pills &&+ a.data.needsModel === b.data.needsModel &&+ a.data.summary === b.data.summary;++const isSameEdge = (a: PreviewFlowEdge, b: PreviewFlowEdge) =>+ a.ariaLabel === b.ariaLabel &&+ a.source === b.source &&+ a.target === b.target &&+ a.data?.isLoopLinkage === b.data?.isLoopLinkage &&+ a.data?.isRerouted === b.data?.isRerouted &&+ a.data?.entryOffset === b.data?.entryOffset;++/**+ * Where each edge meets its target, as an offset from the chip's middle: a chip fed by several nodes takes them a few+ * px apart, top to bottom as their sources sit, rather than at one point, so they arrive without crossing there.+ */+const getEntryOffsets = (layout: WorkflowPreviewLayout): Map<string, number> => {+ const byTarget = new Map<string, WorkflowPreviewLayout['edges'][number][]>();++ for (const edge of layout.edges) {+ byTarget.set(edge.target, [...(byTarget.get(edge.target) ?? []), edge]);+ }++ const offsets = new Map<string, number>();+ const sourceY = (edge: WorkflowPreviewLayout['edges'][number]) => layout.positions[edge.source]?.y ?? 0;++ for (const entering of byTarget.values()) {+ const step = entering.length < 2 ? 0 : Math.min(ENTRY_STEP, ENTRY_SPAN / (entering.length - 1));++ [...entering]+ .sort((a, b) => sourceY(a) - sourceY(b))+ .forEach((edge, index) => offsets.set(edge.id, (index - (entering.length - 1) / 2) * step));+ }++ return offsets;+};++/** The widest of the titles, set as a chip sets them, in px. */+const measureTitlesWidth = (titles: readonly string[], stage: HTMLElement) => {+ const context = document.createElement('canvas').getContext('2d');++ if (!context) {+ return 0;+ }++ const rootPx = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;++ context.font = `600 ${TITLE_REM * rootPx}px ${getComputedStyle(stage).fontFamily}`;++ return Math.max(0, ...titles.map((title) => context.measureText(title).width));+};++const GraphView = ({+ fieldSources,+ initialNodeId = null,+ focusInitialCard = true,+ model: sourceModel,+ needsModel,+ ref,+ relayout,+ onCardChange,+ onMatchCountChange,+}: WorkflowDocumentGraphProps) => {+ const { t } = useTranslation();+ /**+ * The drawing's chip width, chosen as it opens (`handleInit`), when the stage's size is known; the drawing is that+ * model laid out at that width, again for each new value of a live source.+ */+ const [chipWidth, setChipWidth] = useState(sourceModel.all.nodeWidth);+ const [laidOut, setLaidOut] = useState({ model: sourceModel, source: sourceModel, width: chipWidth });+ let model = laidOut.model;+ if (laidOut.source !== sourceModel || laidOut.width !== chipWidth) {+ model =+ chipWidth === sourceModel.all.nodeWidth+ ? sourceModel+ : relayout(getWorkflowPreviewMetrics(chipWidth), laidOut.width === chipWidth ? laidOut.model : null);+ setLaidOut({ model, source: sourceModel, width: chipWidth });+ }+ // A node asked for that this document does not have opens nothing.+ const startNodeId = initialNodeId !== null && model.nodes.has(initialNodeId) ? initialNodeId : null;+ const themeId = useWorkflowPreferencesSelector((preferences) => preferences.themeId);+ const flow = useReactFlow();+ const [emphasis] = useState(createKeyedTransientStore<string, Emphasis>);+ // Opens simplified, unless the node asked for is a folded helper or hidden plumbing: then everything shows.+ const [isSimplified, setIsSimplified] = useState(+ model.simplified !== null && (startNodeId === null || model.simplified.nodeIds.includes(startNodeId))+ );+ const [isClipped, setIsClipped] = useState(false);+ const [rowStretch, setRowStretch] = useState(1);+ const [cardNodeId, setCardNodeIdState] = useState<string | null>(startNodeId);+ // Called from handlers only: the host hears every change of card, as it happens.+ const setCardNodeId = useCallback(+ (nodeId: string | null) => {+ setCardNodeIdState(nodeId);+ onCardChange?.(nodeId);+ },+ [onCardChange]+ );+ const [findState, setFindState] = useState<{ cursor: number; matches: readonly string[]; query: string }>({+ cursor: -1,+ matches: [],+ query: '',+ });+ const containerRef = useRef<HTMLDivElement>(null);+ const cardRef = useRef<HTMLDivElement>(null);+ const baseLayout = (isSimplified ? model.simplified : null) ?? model.all;+ const layout = useMemo(() => stretchRows(baseLayout, rowStretch), [baseLayout, rowStretch]);++ const builtNodes = useMemo(+ () =>+ layout.nodeIds.map((id): ChipNode => {+ const node = model.nodes.get(id)!;+ const pills = layout.pills[id] ?? NO_PILLS;+ const nodeNeedsModel = needsModel.has(id);+ const summary = getChipSummary(node, nodeNeedsModel, t);++ return {+ ariaLabel: getNodeName(node, nodeNeedsModel, pills, summary, t),+ ariaRole: 'button',+ connectable: false,+ data: { needsModel: nodeNeedsModel, node, pills, summary },+ draggable: false,+ height: NODE_HEIGHT,+ id,+ position: layout.positions[id]!,+ selectable: false,+ type: 'chip',+ width: layout.nodeWidth,+ };+ }),+ [layout, model, needsModel, t]+ );+ const builtEdges = useMemo(() => {+ const entryOffsets = getEntryOffsets(layout);++ return layout.edges.map((edge): PreviewFlowEdge => ({+ ariaLabel: t('workflowLibrary.preview.edgeLabel', {+ source: model.nodes.get(edge.source)!.title,+ target: model.nodes.get(edge.target)!.title,+ }),+ data: {+ entryOffset: entryOffsets.get(edge.id) ?? 0,+ isLoopLinkage: edge.isLoopLinkage,+ isRerouted: edge.isRerouted,+ },+ id: edge.id,+ source: edge.source,+ target: edge.target,+ type: 'preview',+ }));+ }, [layout, model, t]);+ /**+ * The chips and edges handed to the flow keep their identity while nothing they show changed, so a live source's+ * recompile re-renders only the chips whose values, pills or markers did (the model keeps unchanged nodes' identity).+ */+ const [drawn, setDrawn] = useState({ edges: builtEdges, nodes: builtNodes });+ let { edges, nodes } = drawn;+ const keptNodes = keepUnchanged(drawn.nodes, builtNodes, isSameChip);+ const keptEdges = keepUnchanged(drawn.edges, builtEdges, isSameEdge);+ if (!isSameItems(keptNodes, drawn.nodes) || !isSameItems(keptEdges, drawn.edges)) {+ nodes = keptNodes;+ edges = keptEdges;+ setDrawn({ edges, nodes });+ }+ const ariaLabelConfig = useMemo(+ () => ({+ 'minimap.ariaLabel': t('workflowLibrary.preview.minimap'),+ 'node.a11yDescription.default': t('workflowLibrary.preview.nodeHint'),+ 'node.a11yDescription.keyboardDisabled': t('workflowLibrary.preview.nodeHint'),+ }),+ [t]+ );++ /** Writes one emphasis map over the previous one, notifying only the nodes and edges that change. */+ const applyEmphasis = useCallback(+ (next: ReadonlyMap<string, Emphasis>) => {+ for (const [key] of emphasis.entries()) {+ if (!next.has(key)) {+ emphasis.delete(key);+ }+ }++ for (const [key, value] of next) {+ emphasis.set(key, value);+ }+ },+ [emphasis]+ );+ const emphasiseSelection = useCallback(+ (nodeId: string, shown: WorkflowPreviewLayout) => {+ const next = new Map<string, Emphasis>([[nodeId, 'selected']]);++ for (const edge of shown.edges) {+ if (edge.source === nodeId || edge.target === nodeId) {+ next.set(edge.id, 'related');+ next.set(edge.source === nodeId ? edge.target : edge.source, 'related');+ }+ }++ next.set(nodeId, 'selected');+ applyEmphasis(next);+ },+ [applyEmphasis]+ );+ const emphasiseMatches = useCallback(+ (matches: readonly string[], cursor: number) =>+ applyEmphasis(new Map(matches.map((id, index) => [id, index === cursor ? 'current' : 'match'] as const))),+ [applyEmphasis]+ );++ const centreOn = useCallback(+ (nodeId: string, shown: WorkflowPreviewLayout) => {+ const box = getNodeBox(shown, nodeId);++ void flow.setCenter(box.x + box.width / 2, box.y + box.height / 2, {+ duration: motion(REVEAL_DURATION),+ zoom: Math.max(flow.getZoom(), getReadableZoom()),+ });+ },+ [flow]+ );++ const openCard = useCallback(+ (nodeId: string) => {+ flushSync(() => setCardNodeId(nodeId));+ emphasiseSelection(nodeId, layout);+ cardRef.current?.focus({ preventScroll: true });+ },+ [emphasiseSelection, layout, setCardNodeId]+ );+ const closeCard = useCallback(+ (returnFocus: boolean) => {+ const nodeId = cardNodeId;++ if (nodeId === null) {+ return false;+ }++ flushSync(() => setCardNodeId(null));+ emphasiseMatches(findState.matches, findState.cursor);++ if (returnFocus) {+ containerRef.current+ ?.querySelector<HTMLElement>(`.react-flow__node[data-id="${CSS.escape(nodeId)}"]`)+ ?.focus({ preventScroll: true });+ }++ return true;+ },+ [cardNodeId, emphasiseMatches, findState, setCardNodeId]+ );+ const showNode = useCallback(+ (nodeId: string) => {+ centreOn(nodeId, layout);+ openCard(nodeId);+ },+ [centreOn, layout, openCard]+ );++ /**+ * Opens a layout at its fitted or readable zoom, spreading a simplified graph's rows to the stage's height first, and+ * returns the layout as drawn.+ */+ const applyOpeningViewport = useCallback(+ (base: WorkflowPreviewLayout, instance: Pick<ReactFlowInstance, 'setViewport'>, isFullView: boolean) => {+ const element = containerRef.current;++ if (!element) {+ return base;+ }++ const area = measureStageArea(element);+ const unstretched = getOpeningViewport(base, area);+ const stretch =+ isFullView || unstretched.isClipped+ ? 1+ : getRowStretch(base, unstretched.viewport.zoom, area.height - area.top - area.bottom);+ const shown = stretchRows(base, stretch);+ const opening = stretch === 1 ? unstretched : getOpeningViewport(shown, area);++ setRowStretch(stretch);+ setIsClipped(opening.isClipped);+ void instance.setViewport(opening.viewport);++ return shown;+ },+ []+ );+ /**+ * The chip width for this drawing: wide enough for its longest title where the stage leaves the room (the graph+ * still fitted at a legible zoom), one width for every chip so columns stay aligned.+ */+ const chooseChipWidth = useCallback(+ (stage: HTMLElement) => {+ const area = measureStageArea(stage);+ const layoutOf = (laid: WorkflowPreviewModel) => (isSimplified ? laid.simplified : null) ?? laid.all;+ const titles = layoutOf(model).nodeIds.map((id) => model.nodes.get(id)!.title);+ const readable = getReadableZoom();++ return chooseWorkflowPreviewChipWidth(+ measureTitlesWidth(titles, stage) + CHIP_TITLE_INSET,+ (width) =>+ getFittedViewport(getLayoutBounds(layoutOf(relayout(getWorkflowPreviewMetrics(width), null))), area).zoom >=+ readable+ );+ },+ [isSimplified, model, relayout]+ );+ const handleInit = useCallback(+ (instance: ReactFlowInstance<ChipNode, PreviewFlowEdge>) => {+ const stage = containerRef.current;+ const width = stage ? chooseChipWidth(stage) : chipWidth;+ const opening = width === chipWidth ? model : relayout(getWorkflowPreviewMetrics(width), null);+ const openingBase = (isSimplified ? opening.simplified : null) ?? opening.all;++ setChipWidth(width);+ const shown = applyOpeningViewport(openingBase, instance, openingBase === opening.all);++ if (startNodeId !== null && shown.positions[startNodeId]) {+ const box = getNodeBox(shown, startNodeId);++ emphasiseSelection(startNodeId, shown);+ onCardChange?.(startNodeId);+ void instance.setCenter(box.x + box.width / 2, box.y + box.height / 2, {+ zoom: Math.max(instance.getZoom(), getReadableZoom()),+ });++ const active = document.activeElement;++ if (focusInitialCard || active === null || active === document.body) {+ cardRef.current?.focus({ preventScroll: true });+ }+ }+ },+ [+ applyOpeningViewport,+ chipWidth,+ chooseChipWidth,+ emphasiseSelection,+ focusInitialCard,+ isSimplified,+ model,+ onCardChange,+ relayout,+ startNodeId,+ ]+ );+ const toggleSimplified = useCallback(() => {+ const next = !isSimplified;+ const shown = (next ? model.simplified : null) ?? model.all;+ const matches = findWorkflowPreviewNodes(model, shown, findState.query);++ setIsSimplified(next);+ setCardNodeId(null);+ setFindState({ cursor: -1, matches, query: findState.query });+ emphasiseMatches(matches, -1);+ onMatchCountChange?.(matches.length);+ applyOpeningViewport(shown, flow, shown === model.all);+ }, [+ applyOpeningViewport,+ emphasiseMatches,+ findState.query,+ flow,+ isSimplified,+ model,+ onMatchCountChange,+ setCardNodeId,+ ]);+ // Fitted, the whole graph is in view: the minimap has nothing left to show.+ const handleFit = useCallback(() => {+ const element = containerRef.current;++ if (!element) {+ return;+ }++ setIsClipped(false);+ void flow.setViewport(getFittedViewport(getLayoutBounds(layout), measureStageArea(element)), {+ duration: motion(REVEAL_DURATION),+ });+ }, [flow, layout]);++ useImperativeHandle(+ ref,+ () => ({+ closeNodeCard: () => closeCard(true),+ find: (query) => {+ const matches = findWorkflowPreviewNodes(model, layout, query);++ setCardNodeId(null);+ setFindState({ cursor: -1, matches, query });+ emphasiseMatches(matches, -1);+ onMatchCountChange?.(matches.length);+ },+ revealNextMatch: () => {+ if (findState.matches.length === 0) {+ return;+ }++ const cursor = (findState.cursor + 1) % findState.matches.length;++ setFindState({ ...findState, cursor });+ emphasiseMatches(findState.matches, cursor);+ centreOn(findState.matches[cursor]!, layout);+ },+ }),+ [centreOn, closeCard, emphasiseMatches, findState, layout, model, onMatchCountChange, setCardNodeId]+ );++ const handleNodeClick = useCallback<NodeMouseHandler<ChipNode>>((_event, node) => openCard(node.id), [openCard]);+ const handlePaneClick = useCallback(() => void closeCard(false), [closeCard]);+ const closeCardFromButton = useCallback(() => void closeCard(true), [closeCard]);+ // The node wrappers are xyflow's focusable buttons; Enter and Space on one open its card.+ const handleKeyDown = useCallback(+ (event: ReactKeyboardEvent<HTMLDivElement>) => {+ const target = event.target as HTMLElement;++ if ((event.key === 'Enter' || event.key === ' ') && target.classList.contains('react-flow__node')) {+ event.preventDefault();++ if (target.dataset.id) {+ openCard(target.dataset.id);+ }+ }+ },+ [openCard]+ );++ const cardNode = cardNodeId !== null && layout.positions[cardNodeId] ? model.nodes.get(cardNodeId) : undefined;+ const shownNodes = layout.nodeIds.map((id) => model.nodes.get(id)!);+ const foldedCount = model.nodes.size - layout.nodeIds.length;++ return (+ <EmphasisContext value={emphasis}>+ <Box+ ref={containerRef}+ bg="bg.inset"+ css={CONTAINER_CSS}+ data-dimmed={cardNodeId !== null || findState.matches.length > 0 ? '' : undefined}+ h="full"+ position="relative"+ w="full"+ onKeyDown={handleKeyDown}+ >+ {/* The stage's controls come before the nodes, so the keyboard reaches them without passing every node. */}+ <Legend+ exposed={shownNodes.some((node) => node.isExposed)}+ needsModel={shownNodes.some((node) => needsModel.has(node.id))}+ result={shownNodes.some((node) => node.isResult)}+ />+ <ZoomControls onFit={handleFit} />+ <Box bottom="3" data-preview-overlay="" insetEnd="3" position="absolute" zIndex={OVERLAY_Z}>+ <Stack align="flex-end" gap="2">+ {isClipped ? (+ <StyledMiniMap+ ariaLabel={t('workflowLibrary.preview.minimap')}+ borderColor="border.subtle"+ borderWidth="1px"+ overflow="hidden"+ pannable+ rounded="md"+ shadow="sm"+ // Laid out in this panel, above the node count, rather than as a corner panel of its own.+ style={MINIMAP_STYLE}+ zoomable+ />+ ) : null}+ <HStack+ bg="bg.panel"+ borderColor="border.subtle"+ borderWidth="1px"+ data-preview-node-count=""+ gap="2.5"+ minH="8"+ ps="3"+ pe={model.simplified ? '1' : '3'}+ py="0.5"+ rounded="md"+ shadow="sm"+ >+ <Text color="fg.muted" fontSize="md">+ {!model.simplified+ ? t('workflowLibrary.nodeCount', { count: model.nodes.size })+ : isSimplified+ ? `${t('workflowLibrary.preview.showingNodes', {+ count: model.nodes.size,+ shown: layout.nodeIds.length,+ })} · ${t('workflowLibrary.preview.helpersFolded', { count: foldedCount })}`+ : t('workflowLibrary.preview.showingAll', { count: model.nodes.size })}+ </Text>+ {model.simplified ? (+ <Button size="xs" variant="outline" onClick={toggleSimplified}>+ {isSimplified+ ? t('workflowLibrary.preview.showAll', { count: model.nodes.size })+ : t('workflowLibrary.preview.simplify')}+ </Button>+ ) : null}+ </HStack>+ </Stack>+ </Box>+ <ReactFlow+ ariaLabelConfig={ariaLabelConfig}+ colorMode={getFlowColorMode(themeId)}+ deleteKeyCode={null}+ edges={edges}+ edgesFocusable={false}+ edgeTypes={edgeTypes}+ elementsSelectable={false}+ maxZoom={MAX_ZOOM}+ minZoom={MIN_ZOOM}+ multiSelectionKeyCode={null}+ nodes={nodes}+ nodesConnectable={false}+ nodesDraggable={false}+ nodesFocusable+ nodeTypes={nodeTypes}+ panActivationKeyCode={null}+ proOptions={proOptions}+ selectionKeyCode={null}+ style={flowStyle}+ zoomOnDoubleClick={false}+ onInit={handleInit}+ onNodeClick={handleNodeClick}+ onPaneClick={handlePaneClick}+ >+ <Background+ bgColor="var(--xy-background-color)"+ color="var(--wb-flow-grid)"+ gap={24}+ size={1.5}+ variant={BackgroundVariant.Dots}+ />+ </ReactFlow>+ {/* Over the controls, in their layer: the graph's own layer would paint it under them. */}+ {cardNode ? (+ <NodeCard+ ref={cardRef}+ fieldSources={fieldSources}+ layout={layout}+ model={model}+ needsModel={needsModel.has(cardNode.id)}+ node={cardNode}+ onClose={closeCardFromButton}+ onShowNode={showNode}+ />+ ) : null}+ </Box>+ </EmphasisContext>+ );+};++/** One provider per graph, so the controls and the card read this graph's viewport. */+export const WorkflowDocumentGraph = (props: WorkflowDocumentGraphProps) => (+ <ReactFlowProvider>+ <GraphView {...props} />+ </ReactFlowProvider>+);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewInputs.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewInputs.tsxnew file mode 100644index 0000000000..66e753a2d7--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewInputs.tsx@@ -0,0 +1,233 @@+import type {+ WorkflowPreviewFormItem,+ WorkflowPreviewInput,+ WorkflowPreviewModel,+} from '@features/workflow/core/workflowPreview';+import type { ModelRequirementDeps } from '@features/workflow/ui/modelRequirementStatus';++import { Box, Center, HStack, Icon, Spinner, Stack, type SystemStyleObject, Text } from '@chakra-ui/react';+import { resolveWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';+import {+ REQUIREMENT_STATUS_PRESENTATION,+ useLoadedModelRequirementDeps,+} from '@features/workflow/ui/modelRequirementStatus';+import { Button } from '@platform/ui/Button';+import { Scrollable } from '@platform/ui/Scrollable';+import { useCallback, useId, useLayoutEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { formatWorkflowPreviewValue } from './nodeSummaries';++/**+ * The preview's Inputs view of a workflow document: its form as its author arranged it, read-only, with the saved+ * values. It answers "what do I fill in" without reading the graph; each input names the node it sets, which opens that+ * node in the graph.+ */++const VALUE_CSS: SystemStyleObject = {+ bg: 'bg.subtle',+ borderColor: 'border.subtle',+ borderWidth: '1px',+ fontSize: 'md',+ lineHeight: '1.45',+ minH: '7.5',+ overflowWrap: 'anywhere',+ px: '2.5',+ py: '1.5',+ rounded: 'md',+ whiteSpace: 'pre-wrap',+};+const EMPTY_VALUE_CSS: SystemStyleObject = { ...VALUE_CSS, borderStyle: 'dashed', color: 'fg.muted' };+// The theme has no `border.warning`; warning borders use the warning foreground.+const NEEDS_VALUE_CSS: SystemStyleObject = { ...VALUE_CSS, borderColor: 'fg.warning' };+/** About four lines of value; a longer text scrolls inside its box rather than being cut. */+const TEXT_VALUE_CSS: SystemStyleObject = { ...VALUE_CSS, maxH: '6.5rem', overflowY: 'auto' };++const InputValue = ({ deps, input }: { deps: ModelRequirementDeps; input: WorkflowPreviewInput }) => {+ const { t } = useTranslation();+ // A model the field names, or the kind it asks for while empty, that this server does not have.+ const missing = resolveWorkflowModelRequirements(input.modelRequirements, deps).find(+ (resolved) => resolved.status !== 'installed'+ );++ if (missing) {+ const presentation = REQUIREMENT_STATUS_PRESENTATION[missing.status];++ return (+ <HStack color={presentation.color} css={NEEDS_VALUE_CSS} data-input-value="missing" gap="2">+ {presentation.icon ? (+ <Icon aria-hidden as={presentation.icon} boxSize="3" flexShrink={0} />+ ) : (+ <Spinner aria-hidden borderWidth="1.5px" boxSize="3" flexShrink={0} />+ )}+ <Text minW="0">+ {input.value ? formatWorkflowPreviewValue(input.value, t) : missing.requirement.label} ·{' '}+ {t(presentation.labelKey)}+ </Text>+ </HStack>+ );+ }++ if (!input.value) {+ return (+ <Text css={EMPTY_VALUE_CSS} data-input-value="empty">+ {input.isModelField ? t('workflowLibrary.preview.pickAfterOpening') : t('workflowLibrary.preview.emptyValue')}+ </Text>+ );+ }++ const text = formatWorkflowPreviewValue(input.value, t);++ return input.value.kind === 'text' ? (+ <TextValue text={text} />+ ) : (+ <Text css={VALUE_CSS} data-input-value="">+ {text}+ </Text>+ );+};++/** A text value: a long one scrolls inside its box, which then takes focus so the keyboard can scroll it too. */+const TextValue = ({ text }: { text: string }) => {+ const ref = useRef<HTMLParagraphElement>(null);+ const [overflows, setOverflows] = useState(false);++ // Whether the box overflows decides whether it is a tab stop; measured before paint, once per text.+ useLayoutEffect(() => {+ const element = ref.current;++ if (element) {+ setOverflows(element.scrollHeight > element.clientHeight + 1);+ }+ }, [text]);++ return (+ <Text ref={ref} css={TEXT_VALUE_CSS} data-input-value="" tabIndex={overflows ? 0 : undefined}>+ {text}+ </Text>+ );+};++const InputField = ({+ deps,+ input,+ onShowNode,+}: {+ deps: ModelRequirementDeps;+ input: WorkflowPreviewInput;+ onShowNode: (nodeId: string) => void;+}) => {+ const { t } = useTranslation();+ const labelId = useId();+ const showNode = useCallback(() => onShowNode(input.nodeId), [input.nodeId, onShowNode]);++ return (+ <Stack aria-labelledby={labelId} data-preview-input={input.id} flex="1" gap="1" minW="0" role="group">+ <HStack align="baseline" gap="2" justify="space-between" minW="0">+ <Text fontSize="md" fontWeight="500" id={labelId} minW="0" truncate>+ {input.label}+ </Text>+ <Button+ aria-label={t('workflowLibrary.preview.showNode', { node: input.nodeTitle })}+ color="accent.fg"+ flexShrink={1}+ fontSize="sm"+ fontWeight="400"+ h="auto"+ minW="0"+ px="0"+ size="xs"+ variant="plain"+ onClick={showNode}+ >+ <Text as="span" truncate>+ {input.nodeTitle}+ </Text>+ </Button>+ </HStack>+ <InputValue deps={deps} input={input} />+ </Stack>+ );+};++const FormItems = ({+ deps,+ items,+ onShowNode,+}: {+ deps: ModelRequirementDeps;+ items: readonly WorkflowPreviewFormItem[];+ onShowNode: (nodeId: string) => void;+}) =>+ items.map((item) => {+ switch (item.kind) {+ case 'heading':+ return (+ <Text+ key={item.id}+ as="h3"+ borderBottomWidth="1px"+ borderColor="border.subtle"+ fontSize="lg"+ fontWeight="600"+ pb="2"+ pt="1.5"+ >+ {item.text}+ </Text>+ );+ case 'text':+ return (+ <Text key={item.id} color="fg.muted" fontSize="md" whiteSpace="pre-wrap">+ {item.text}+ </Text>+ );+ case 'divider':+ return <Box key={item.id} aria-hidden bg="border.subtle" flexShrink={0} h="1px" />;+ case 'container':+ return item.layout === 'row' ? (+ <HStack key={item.id} align="flex-start" flexWrap="wrap" gap="3" minW="0">+ <FormItems deps={deps} items={item.children} onShowNode={onShowNode} />+ </HStack>+ ) : (+ <Stack key={item.id} gap="3.5" minW="0">+ <FormItems deps={deps} items={item.children} onShowNode={onShowNode} />+ </Stack>+ );+ case 'input':+ return <InputField key={item.id} deps={deps} input={item.input} onShowNode={onShowNode} />;+ }+ });++export const WorkflowPreviewInputs = ({+ model,+ onShowNode,+}: {+ model: WorkflowPreviewModel;+ /** Shows the node an input sets, selected in the graph. */+ onShowNode: (nodeId: string) => void;+}) => {+ const { t } = useTranslation();+ const deps = useLoadedModelRequirementDeps();++ if (model.inputs.length === 0) {+ return (+ <Center h="full" p="6">+ <Text color="fg.muted" fontSize="lg" maxW="28rem" textAlign="center">+ {t('workflowLibrary.preview.noInputs')}+ </Text>+ </Center>+ );+ }++ return (+ <Scrollable h="full" label={t('workflowLibrary.preview.inputs')}>+ <Stack gap="3.5" maxW="40rem" mx="auto" px="6" py="5">+ <Text color="fg.muted" fontSize="md">+ {t('workflowLibrary.preview.inputsIntro')}+ </Text>+ <FormItems deps={deps} items={model.form} onShowNode={onShowNode} />+ </Stack>+ </Scrollable>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewJson.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewJson.tsxnew file mode 100644index 0000000000..58c4d546d9--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewJson.tsx@@ -0,0 +1,38 @@+import { Box } from '@chakra-ui/react';+import { JsonPreview } from '@platform/ui/JsonPreview';+import { useMemo } from 'react';++/**+ * The stage's JSON view: the JSON the stage's menu copies and downloads, serialized when the view shows. Loaded on+ * demand (`WorkflowPreviewJson` in `./WorkflowPreviewStage`).+ */+const WorkflowPreviewJsonView = ({+ copyFailedLabel,+ copyLabel,+ getText,+ label,+}: {+ copyFailedLabel: string;+ copyLabel: string;+ /** Serializes the JSON; called once per value it closes over. */+ getText: () => string;+ /** Names the JSON's scroll region. */+ label: string;+}) => {+ const text = useMemo(() => getText(), [getText]);++ return (+ <Box data-preview-json="" h="full">+ <JsonPreview+ copyFailedLabel={copyFailedLabel}+ copyLabel={copyLabel}+ h="full"+ label={label}+ maxH="100%"+ text={text}+ />+ </Box>+ );+};++export default WorkflowPreviewJsonView;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewStage.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewStage.tsxnew file mode 100644index 0000000000..6b5c62c5ea--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/WorkflowPreviewStage.tsx@@ -0,0 +1,222 @@+import type { WorkflowPreviewModel } from '@features/workflow/core/workflowPreview';+import type { WorkflowDocumentGraphHandle } from '@features/workflow/ui/graph-preview/WorkflowDocumentGraph';+import type { TFunction } from 'i18next';++import { Center, HStack, Icon, Input, InputGroup, Spinner, type SystemStyleObject, Text } from '@chakra-ui/react';+import { createDeferredModule } from '@platform/react/deferredModule';+import { LoadError } from '@platform/ui/LoadError';+import { SearchIcon } from 'lucide-react';+import {+ type ChangeEvent,+ type ComponentProps,+ type KeyboardEvent as ReactKeyboardEvent,+ type ReactNode,+ type RefObject,+ useCallback,+ useState,+} from 'react';+import { useTranslation } from 'react-i18next';++import type * as WorkflowPreviewJsonModule from './WorkflowPreviewJson';++/**+ * The parts every workflow preview stage shares (the library's preview mode and the graph preview dialog): the bar+ * over the stage, its find field, its Nodes / Inputs / Graph views and the messages the stage shows in their place.+ * The bar keeps its tabs at the start and its menu at the end in every view; only the find field, shown with the+ * nodes, comes and goes in the space between, so nothing a reader aims at moves.+ */++/**+ * What the stage shows: the nodes (the diagram), the form's inputs, or the graph: the compiled JSON the server is sent,+ * which is what "graph" means here.+ */+export type WorkflowPreviewView = 'nodes' | 'inputs' | 'graph';++/**+ * The size of the dialogs a workflow preview shows in (the library, and the graph preview), so both previews read the+ * same: most of the window, wide and landscape.+ */+export const WORKFLOW_PREVIEW_DIALOG_SIZE = {+ h: '80vh',+ maxH: '80vh',+ maxW: 'min(80rem, calc(100vw - 4rem))',+} as const;++/** The Graph view and the platform's JSON preview load when that view first shows, outside every startup chunk. */+const workflowPreviewJson = createDeferredModule(() => import('./WorkflowPreviewJson'));++export const WorkflowPreviewJson = (props: ComponentProps<typeof WorkflowPreviewJsonModule.default>) => {+ const [attempt, setAttempt] = useState(0);+ const retry = useCallback(() => setAttempt((value) => value + 1), []);+ const render = useCallback((module: typeof WorkflowPreviewJsonModule) => <module.default {...props} />, [props]);+ const renderError = useCallback(() => <WorkflowPreviewLoadError onRetry={retry} />, [retry]);++ return (+ <workflowPreviewJson.Deferred key={attempt} fallback={STAGE_LOADING} render={render} renderError={renderError} />+ );+};++/** A failed preview stays local to its stage, leaving the surrounding tabs and close action available. */+export const WorkflowPreviewLoadError = ({ onRetry }: { onRetry: () => void }) => {+ const { t } = useTranslation();++ return (+ <LoadError isRetrying={false} layout="state" message={t('workflowLibrary.preview.loadFailed')} onRetry={onRetry} />+ );+};++const FIND_START_ELEMENT = <Icon aria-hidden as={SearchIcon} boxSize="3.5" color="fg.subtle" />;++export const WorkflowPreviewBar = ({ children }: { children: ReactNode }) => (+ <HStack+ borderBottomWidth="1px"+ borderColor="border.subtle"+ data-preview-stage-bar=""+ flexShrink={0}+ flexWrap="wrap"+ gap="2.5"+ minH="11"+ px="3"+ py="1.5"+ >+ {children}+ </HStack>+);++/**+ * The view tabs: Nodes; Inputs, counting the form's inputs once the document is read, where there is a form; Graph,+ * where there is a compiled graph (or a document to compile) to show.+ */+export const getWorkflowPreviewViewTabs = (+ model: WorkflowPreviewModel | null,+ { hasGraph, hasInputs }: { hasGraph: boolean; hasInputs: boolean },+ t: TFunction+) => [+ { id: 'nodes' as const, label: t('workflowLibrary.preview.nodes') },+ ...(hasInputs+ ? [+ {+ id: 'inputs' as const,+ label: model ? (+ <>+ {t('workflowLibrary.preview.inputs')}{' '}+ <Text as="span" opacity={0.75}>+ {model.inputs.length}+ </Text>+ </>+ ) : (+ t('workflowLibrary.preview.inputs')+ ),+ },+ ]+ : []),+ ...(hasGraph ? [{ id: 'graph' as const, label: t('workflowLibrary.preview.graph') }] : []),+];++export interface WorkflowPreviewFind {+ query: string;+ matches: number;+ onChange: (event: ChangeEvent<HTMLInputElement>) => void;+ onKeyDown: (event: ReactKeyboardEvent<HTMLInputElement>) => void;+ /** The graph's `onMatchCountChange`: only it knows whether every node is drawn. */+ onMatchCountChange: (count: number) => void;+ /** Empties the field, for a graph drawn afresh. */+ reset: () => void;+}++/**+ * The find field's state. It belongs to the drawing it searched (`drawing` names it): another document, or this one+ * replaced, starts unfiltered.+ */+export const useWorkflowPreviewFind = (+ graphRef: RefObject<WorkflowDocumentGraphHandle | null>,+ drawing: number+): WorkflowPreviewFind => {+ const [find, setFind] = useState({ drawing: -1, matches: 0, query: '' });+ const onChange = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ const query = event.currentTarget.value;++ setFind({ drawing, matches: 0, query });+ graphRef.current?.find(query);+ },+ [drawing, graphRef]+ );+ const onKeyDown = useCallback(+ (event: ReactKeyboardEvent<HTMLInputElement>) => {+ if (event.key === 'Enter') {+ event.preventDefault();+ graphRef.current?.revealNextMatch();+ }+ },+ [graphRef]+ );+ const onMatchCountChange = useCallback((matches: number) => setFind((current) => ({ ...current, matches })), []);+ const reset = useCallback(() => setFind({ drawing, matches: 0, query: '' }), [drawing]);++ return {+ matches: find.matches,+ onChange,+ onKeyDown,+ onMatchCountChange,+ query: find.drawing === drawing ? find.query : '',+ reset,+ };+};++export const WorkflowPreviewFindField = ({ css, find }: { css?: SystemStyleObject; find: WorkflowPreviewFind }) => {+ const { t } = useTranslation();++ return (+ <HStack css={css} gap="2" minW="0">+ {find.query ? (+ <Text aria-live="polite" color="fg.muted" fontSize="md" whiteSpace="nowrap">+ {find.matches === 0+ ? t('workflowLibrary.preview.findNone')+ : t('workflowLibrary.preview.findMatches', { count: find.matches })}+ </Text>+ ) : null}+ <InputGroup startElement={FIND_START_ELEMENT} w="11rem">+ <Input+ aria-label={t('workflowLibrary.preview.find')}+ data-preview-find=""+ placeholder={t('workflowLibrary.preview.find')}+ type="search"+ value={find.query}+ onChange={find.onChange}+ onKeyDown={find.onKeyDown}+ />+ </InputGroup>+ </HStack>+ );+};++/** A message in the graph's place: why there is nothing to draw. `alert` for a failure the reader should hear. */+export const WorkflowPreviewStageMessage = ({+ children,+ isAlert = false,+}: {+ children: ReactNode;+ isAlert?: boolean;+}) => (+ <Center h="full" p="6">+ <Text color="fg.muted" fontSize="lg" maxW="32rem" role={isAlert ? 'alert' : undefined} textAlign="center">+ {children}+ </Text>+ </Center>+);++export const WorkflowPreviewStageLoading = () => {+ const { t } = useTranslation();++ return (+ <Center aria-live="polite" flexDirection="column" gap="2" h="full" role="status">+ <Spinner color="fg.subtle" size="lg" />+ <Text color="fg.muted" fontSize="md">+ {t('workflowLibrary.preview.loading')}+ </Text>+ </Center>+ );+};++const STAGE_LOADING = <WorkflowPreviewStageLoading />;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.tsindex f594c17a30..80e06dfef9 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/flowTheme.ts@@ -1,7 +1,7 @@import type { SystemStyleObject } from '@chakra-ui/react';import type { WorkbenchThemeId } from '@theme/themes';-import { WORKFLOW_NODE_SURFACE_TOKEN } from '@features/workflow/ui/nodeChrome';+import { WORKFLOW_NODE_DIAMOND_ROTATION, WORKFLOW_NODE_SURFACE_TOKEN } from '@features/workflow/ui/nodeChrome';import { THEMES_BY_ID } from '@theme/themes';/**@@ -9,6 +9,7 @@ import { THEMES_BY_ID } from '@theme/themes';* and inline handles.*/export const flowThemeCss: SystemStyleObject = {+ '--wb-edge-badge-fg': '{colors.fg}','--wb-flow-grid': '{colors.fg.grid}','--wb-node-surface': `{colors.${WORKFLOW_NODE_SURFACE_TOKEN}}`,'--xy-attribution-background-color': 'transparent',@@ -22,6 +23,21 @@ export const flowThemeCss: SystemStyleObject = {'--xy-minimap-node-background-color': '{colors.bg.emphasized}','--xy-selection-background-color': '{colors.accent.solid/10}','--xy-selection-border': '1px dashed {colors.accent.solid}',+ // A port keeps its 12px dot but takes pointers over 24×24 centred on it. It inherits the handle's pointer events,+ // so a handle that cannot connect (previews) stays inert.+ '& .react-flow__handle::before': {+ content: '""',+ height: '24px',+ left: '50%',+ position: 'absolute',+ top: '50%',+ transform: 'translate(-50%, -50%)',+ width: '24px',+ },+ // A batch port's diamond is the handle rotated 45°; turn its grab area back so every port's is the same square.+ [`& .react-flow__handle[style*="${WORKFLOW_NODE_DIAMOND_ROTATION}"]::before`]: {+ transform: 'translate(-50%, -50%) rotate(-45deg)',+ },};/** The xyflow color mode matching a workbench theme. */diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/graphJson.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/graphJson.tsnew file mode 100644index 0000000000..5cbd06b35c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/graphJson.ts@@ -0,0 +1,8 @@+import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';++/**+ * The graph the server is sent, as the preview's Graph view and the graph preview's menu give it: what a bug report+ * needs.+ */+export const getGraphJsonText = (graph: WorkflowPreviewGraph): string =>+ JSON.stringify(graph.backendGraph ?? graph, null, 2);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.tsdeleted file mode 100644index 0c178971ff..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/index.ts+++ /dev/null@@ -1,4 +0,0 @@-export { FlowMiniMap } from './FlowMiniMap';-export { flowThemeCss, getFlowColorMode } from './flowTheme';-export { GraphPreviewDialog } from './GraphPreviewDialog';-export { documentToPreviewGraph, GraphPreviewFlow } from './GraphPreviewFlow';diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.test.tsindex 574de1aca7..16112dc9bb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.test.ts@@ -1,10 +1,30 @@import type { TFunction } from 'i18next';+import { createInstance } from 'i18next';import { describe, expect, it } from 'vitest';-import { getNodeSubtitle } from './nodeSummaries';+import { formatWorkflowPreviewValue, getNodeSubtitle, getWorkflowNodeSummary } from './nodeSummaries';-const t = ((key: string, options?: Record<string, unknown>) => `${key}:${JSON.stringify(options ?? {})}`) as TFunction;+const englishCatalogModules = import.meta.glob('../../../../../public/locales/en.json', {+ eager: true,+ import: 'default',+});+const englishCatalog = Object.values(englishCatalogModules)[0] as Record<string, unknown>;++/** The English catalog, read as `lng`: numbers follow that language's digits and grouping. */+const translatorFor = async (lng: string): Promise<TFunction> => {+ const i18n = createInstance();+ await i18n.init({+ initAsync: false,+ interpolation: { escapeValue: false },+ lng,+ resources: { [lng]: { translation: englishCatalog } },+ });++ return i18n.t.bind(i18n) as TFunction;+};++const t = await translatorFor('en');describe('getNodeSubtitle', () => {it('returns the denoise summary when steps and cfg_scale are numbers', () => {@@ -13,13 +33,19 @@ describe('getNodeSubtitle', () => {t);- expect(subtitle).toBe('graphPreview.nodeSummary.denoise:{"cfg":4,"steps":28}');+ expect(subtitle).toBe('28 steps · cfg 4');+ });++ it('reads a single step as one', () => {+ expect(+ getNodeSubtitle({ id: 'denoise_latents', inputs: { cfg_scale: 1, steps: 1 }, type: 'denoise_latents' }, t)+ ).toBe('1 step · cfg 1');});it('returns the noise summary when width and height are numbers', () => {const subtitle = getNodeSubtitle({ id: 'noise', inputs: { height: 512, width: 768 }, type: 'noise' }, t);- expect(subtitle).toBe('graphPreview.nodeSummary.noise:{"height":512,"width":768}');+ expect(subtitle).toBe('768 × 512');});it('returns null for denoise_latents when the numeric fields are missing', () => {@@ -34,3 +60,41 @@ describe('getNodeSubtitle', () => {expect(subtitle).toBeNull();});});++describe('getWorkflowNodeSummary', () => {+ it('reads frames and steps before CFG and steps, and steps alone last', () => {+ expect(getWorkflowNodeSummary({ cfg_scale: 3, num_frames: 121, steps: 30 }, t)).toBe('121 frames · 30 steps');+ expect(getWorkflowNodeSummary({ cfg_scale: 3.5, steps: 30 }, t)).toBe('30 steps · cfg 3.5');+ expect(getWorkflowNodeSummary({ steps: 8 }, t)).toBe('8 steps');+ });++ it('pluralizes frames and steps separately', () => {+ expect(getWorkflowNodeSummary({ frame_count: 1, steps: 1 }, t)).toBe('1 frame · 1 step');+ expect(getWorkflowNodeSummary({ frames: 1, steps: 20 }, t)).toBe('1 frame · 20 steps');+ expect(getWorkflowNodeSummary({ num_frames: 49, steps: 1 }, t)).toBe('49 frames · 1 step');+ expect(getWorkflowNodeSummary({ cfg_scale: 2, steps: 1 }, t)).toBe('1 step · cfg 2');+ expect(getWorkflowNodeSummary({ steps: 1 }, t)).toBe('1 step');+ });++ it('falls back to a size, then to the model the node names, then to nothing', () => {+ expect(getWorkflowNodeSummary({ height: 704, width: 1280 }, t)).toBe('1280 × 704');+ expect(getWorkflowNodeSummary({ model: { key: 'k', name: 'LTX-2 dev' } }, t)).toBe('LTX-2 dev');+ expect(getWorkflowNodeSummary({ prompt: 'a cat', width: 512 }, t)).toBeNull();+ });++ it('writes counts and CFG in the translation language', async () => {+ const german = await translatorFor('de');++ expect(getWorkflowNodeSummary({ num_frames: 1200, steps: 30 }, german)).toBe('1.200 frames · 30 steps');+ expect(getWorkflowNodeSummary({ cfg_scale: 3.5, steps: 30 }, german)).toBe('30 steps · cfg 3,5');+ });+});++describe('formatWorkflowPreviewValue', () => {+ it('writes a number in the translation language, not the browser’s', async () => {+ const value = { kind: 'number', value: 1234.5 } as const;++ expect(formatWorkflowPreviewValue(value, t)).toBe('1,234.5');+ expect(formatWorkflowPreviewValue(value, await translatorFor('de'))).toBe('1.234,5');+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.ts b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.tsindex 652fbd58de..88f183dd36 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/nodeSummaries.ts@@ -1,3 +1,4 @@+import type { WorkflowPreviewValue } from '@features/workflow/core/workflowPreview';import type { TFunction } from 'i18next';/** Return null when no type-specific summary exists so callers use the generic node/input summary. */@@ -9,7 +10,7 @@ export const getNodeSubtitle = (const { cfg_scale: cfg, steps } = node.inputs;if (typeof cfg === 'number' && typeof steps === 'number') {- return t('graphPreview.nodeSummary.denoise', { cfg, steps });+ return t('graphPreview.nodeSummary.denoise', { cfg, count: steps });}return null;@@ -27,3 +28,73 @@ export const getNodeSubtitle = (return null;};++const FRAME_FIELDS = ['num_frames', 'frames', 'frame_count'] as const;++const getNumber = (values: Readonly<Record<string, unknown>>, name: string): number | null => {+ const value = values[name];++ return typeof value === 'number' && Number.isFinite(value) ? value : null;+};++const getModelName = (values: Readonly<Record<string, unknown>>): string | null => {+ for (const value of Object.values(values)) {+ if (typeof value === 'object' && value !== null && typeof (value as { key?: unknown }).key === 'string') {+ const { name } = value as { name?: unknown };++ if (typeof name === 'string' && name) {+ return name;+ }+ }+ }++ return null;+};++/**+ * A saved workflow node's second line in the library preview, from the values it holds itself: steps (with frames or+ * CFG), a size, or the model it names. Null when none applies; the node then shows its title alone.+ */+export const getWorkflowNodeSummary = (values: Readonly<Record<string, unknown>>, t: TFunction): string | null => {+ const steps = getNumber(values, 'steps');++ if (steps !== null) {+ const frames = FRAME_FIELDS.map((name) => getNumber(values, name)).find((value) => value !== null) ?? null;+ const cfg = getNumber(values, 'cfg_scale');++ return frames !== null+ ? t('workflowLibrary.preview.summaryFramesSteps', {+ frames: t('workflowLibrary.preview.summaryFrames', { count: frames }),+ steps: t('workflowLibrary.preview.summarySteps', { count: steps }),+ })+ : cfg !== null+ ? t('graphPreview.nodeSummary.denoise', { cfg, count: steps })+ : t('workflowLibrary.preview.summarySteps', { count: steps });+ }++ const width = getNumber(values, 'width');+ const height = getNumber(values, 'height');++ if (width !== null && height !== null) {+ return t('graphPreview.nodeSummary.noise', { height, width });+ }++ return getModelName(values);+};++/** A preview value as the library shows it: a model or image by name, a list by its length, a switch as on or off. */+export const formatWorkflowPreviewValue = (value: WorkflowPreviewValue, t: TFunction): string => {+ switch (value.kind) {+ case 'boolean':+ return value.value ? t('workflowLibrary.preview.valueOn') : t('workflowLibrary.preview.valueOff');+ case 'list':+ return t('workflowLibrary.preview.valueItems', { count: value.count });+ case 'number':+ return t('workflowLibrary.preview.valueNumber', { value: value.value });+ case 'image':+ case 'model':+ return value.name;+ case 'text':+ return value.text;+ }+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsxindex 406a215eb6..b36de676ef 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx@@ -1,126 +1,182 @@import type { ProjectWorkflowEntry } from '@features/workflow/core/types';+import type { WorkflowPreviewView } from '@features/workflow/ui/graph-preview/WorkflowPreviewStage';+import type { WorkflowLibraryLayout } from '@features/workflow/ui/WorkflowUiContext';-import { Badge, Box, Flex, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { Badge, Box, DataList, HStack, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { useAuthSession } from '@features/identity';+import { getModelBaseLabel } from '@features/models';+import {+ isBundledLibraryWorkflowId,+ savedWorkflowDetailQueryOptions,+ type WorkflowRecordDTO,+} from '@features/workflow/queries';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';-import { MenuActionItem } from '@features/workflow/ui/MenuActionItem';+import { useModelRequirementDeps } from '@features/workflow/ui/modelRequirementStatus';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';-import { useOpenAddModels, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import {+ useOpenAddModels,+ useWorkflowNotifications,+ useWorkflowProjectSelector,+} from '@features/workflow/ui/WorkflowUiContext';import { requestWorkflowPublication } from '@features/workflow/ui/workflowUiStore';import { Button, IconButton } from '@platform/ui/Button';import { ConfirmDialog } from '@platform/ui/ConfirmDialog';-import { MenuContent } from '@platform/ui/Menu';+import { MenuActionItem, MenuContent } from '@platform/ui/Menu';import { RenameDialog } from '@platform/ui/RenameDialog';import { Scrollable } from '@platform/ui/Scrollable';import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { useQuery } from '@tanstack/react-query';import {BookmarkIcon,CopyIcon,EllipsisIcon,- ImageOffIcon,PencilIcon,- PlusIcon,RefreshCwIcon,Trash2Icon,WorkflowIcon,} from 'lucide-react';-import { useCallback, useMemo, useRef, useState } from 'react';+import { type RefObject, useCallback, useId, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import {- isBundledLibraryWorkflowId,- isUpdatableSource,- toProjectWorkflowLibraryEntries,-} from './projectWorkflowEntries';+import type { ProjectWorkflowLibraryEntry } from './projectWorkflowEntries';+import type { WorkflowLibraryPanesPreview } from './WorkflowLibraryBrowsePanes';+import type { WorkflowCardContextMenuHandler, WorkflowCardMenuAnchor } from './WorkflowLibraryCard';+import type { WorkflowContextMenuTarget } from './WorkflowLibraryContextMenu';+import type { WorkflowLibraryListTrailingField } from './WorkflowLibraryList';+import type { WorkflowLibraryPreviewStageHandle, WorkflowLibraryPreviewStatus } from './WorkflowLibraryPreviewStage';+import type { WorkflowPreviewStepperProps } from './WorkflowPreviewStepper';++import { isUpdatableSource, toProjectWorkflowLibraryEntries } from './projectWorkflowEntries';import { formatTimeSince, useDataTimeSnapshot } from './relativeTime';+import { useOpenLibraryWorkflow } from './useOpenLibraryWorkflow';import {- getWorkflowLibraryCardId,- getWorkflowLibraryCardMenuContentId,- keepCardMenuOpenForRetarget,- type WorkflowCardMenuAnchor,- type WorkflowLibraryCardProps,-} from './WorkflowLibraryCard';-import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';+ useWorkflowPreviewModel,+ WORKFLOW_SILHOUETTE_THUMBNAIL_CSS,+ WorkflowAuthorNotes,+ WorkflowInputsBadge,+ WorkflowInputsSummary,+ WorkflowPreviewThumbnailButton,+ WorkflowProvenance,+} from './WorkflowDetailOverview';import {- resolveEntryRequirements,- useModelRequirementDeps,- useWorkflowLibraryMissingCounts,- WorkflowRequirementsList,-} from './WorkflowRequirementsList';+ WORKFLOW_DETAIL_WIDE_ONLY_CSS,+ WORKFLOW_PREVIEW_TRIGGER_CSS,+ WorkflowDetailRailPlaceholder,+ WorkflowDetailSheet,+ WorkflowMissingNodePacks,+} from './WorkflowDetailSheet';+import { WORKFLOW_LIBRARY_PANES_CSS } from './WorkflowLibraryBrowsePanes';+import { keepMenuOpenWhenSiblingMenuCloses } from './WorkflowLibraryCard';+import { WorkflowCardContextMenu } from './WorkflowLibraryContextMenu';+import { WorkflowDetailFact } from './WorkflowLibraryDetailPanel';+import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';+import { WorkflowLibraryList } from './WorkflowLibraryList';+import { WorkflowLibraryPreviewStage } from './WorkflowLibraryPreviewStage';+import { WorkflowThumbnailPlaceholder } from './WorkflowLibraryThumbnail';+import { getMissingNodePacks, resolveEntryRequirements, WorkflowRequirementsList } from './WorkflowRequirementsList';import { WORKFLOW_THUMBNAIL_ASPECT_RATIO, WorkflowThumbnailImage } from './workflowThumbnail';/**- * The project's own workflows, presented through the library's card contract. Everything here is a local- * collection command; the library is only consulted for the selected workflow's source, and only on request.+ * The project's own workflows, presented through the library's card contract. The dialog filters and orders them+ * (`queryProjectWorkflowEntries`) for its toolbar, tags and result line. Everything here is a local collection+ * command; the library is only consulted for the selected workflow's source, and only on request.*/-const DETAIL_RAIL_WIDTH = '18rem';-const COLUMNS_CSS = {- '@container workflow-library-content (width < 42rem) and ((height >= 32rem) or (width < 32rem))': {- flexDirection: 'column',- },- '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {- flex: '0 0 auto',- },-} as const;-const DETAIL_RAIL_CSS = {- '@container workflow-library-content (width < 42rem) and ((height >= 32rem) or (width < 32rem))': {- width: '100%',- },- '@container workflow-library-content (width < 42rem) and (height >= 32rem)': {- flexBasis: '45%',- },- '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {- flex: '0 0 auto',- height: '20rem',- },-} as const;+const NO_NODE_PACKS: readonly string[] = [];+/** The large preview is wide-only; the expanded sheet's summary carries a small one. */+const THUMBNAIL_SLOT_CSS = { ...WORKFLOW_DETAIL_WIDE_ONLY_CSS, ...WORKFLOW_SILHOUETTE_THUMBNAIL_CSS };+/** Keeps the selected rail from re-rendering for template fields it does not show. */+const selectTemplateSummary = (record: WorkflowRecordDTO) => ({ name: record.name, revision: record.revision });export interface ProjectWorkflowsViewProps {- contextMenuPoint: WorkflowCardMenuAnchor | null;- /** What opened the menu last, kept through its close so focus returns there. */- contextMenuTriggerId: string | null;+ /** Where the card actions menu is anchored; null while it is closed. */+ contextMenuAnchor: WorkflowCardMenuAnchor | null;+ /** The workflow the card actions menu was raised for, kept through its close. */+ contextMenuTarget: WorkflowContextMenuTarget | null;+ /** The project's workflows the toolbar and tags let through, in the toolbar's order. */+ entries: readonly ProjectWorkflowLibraryEntry[];+ layout: WorkflowLibraryLayout;+ /** Missing-model counts for `entries`, by workflow id. */+ missingCounts: ReadonlyMap<string, number>;+ /** The explicit choice; the rail falls back to the active workflow, then the first match. */selectedWorkflowId: string | null;+ /** The date the list's rows show, from the current order. */+ trailingField: WorkflowLibraryListTrailingField;onClose: () => void;- onContextMenu: WorkflowLibraryCardProps['onContextMenu'];+ onContextMenu: WorkflowCardContextMenuHandler;onContextMenuClose: () => void;- onPreview: (entry: ProjectWorkflowEntry) => void;+ /** Enters preview mode on a workflow, selecting it; on a given view, else the one last shown. */+ onPreview: (workflowId: string, view?: WorkflowPreviewView) => void;onSelect: (workflowId: string | null) => void;+ preview: WorkflowLibraryPanesPreview;+ /** The stage's handle, through which the dialog's Escape reaches it. */+ previewStageRef: RefObject<WorkflowLibraryPreviewStageHandle | null>;}export const ProjectWorkflowsView = ({- contextMenuPoint,- contextMenuTriggerId,+ contextMenuAnchor,+ contextMenuTarget,+ entries,+ layout,+ missingCounts,selectedWorkflowId,+ trailingField,onClose,onContextMenu,onContextMenuClose,onPreview,onSelect,+ preview,+ previewStageRef,}: ProjectWorkflowsViewProps) => {const { t } = useTranslation();const workflows = useWorkflowProjectSelector((project) => project.workflows);const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);- const templatesSnapshot = useInvocationTemplatesSnapshot();- const { createWorkflow, duplicateWorkflow, removeWorkflow, renameWorkflow, selectWorkflow } =- useProjectGraphCommands();+ const { duplicateWorkflow, removeWorkflow, renameWorkflow, selectWorkflow } = useProjectGraphCommands();const [renameTarget, setRenameTarget] = useState<string | null>(null);const [removeTarget, setRemoveTarget] = useState<string | null>(null);- const entries = useMemo(- () =>- toProjectWorkflowLibraryEntries(- workflows,- templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null- ),- [templatesSnapshot, workflows]- );- const missingCounts = useWorkflowLibraryMissingCounts(entries);+ // A filter that hides the selection (and the active workflow) moves the rail to the first match.const activeSelectionId = entries.some((entry) => entry.item.workflow_id === selectedWorkflowId)? selectedWorkflowId- : activeWorkflowId;+ : entries.some((entry) => entry.item.workflow_id === activeWorkflowId)+ ? activeWorkflowId+ : (entries[0]?.item.workflow_id ?? null);const selectedEntry = entries.find((entry) => entry.item.workflow_id === activeSelectionId) ?? null;+ // The card menu acts on the workflow it was raised for; one the filters hide has nothing to act on.+ const menuEntry = contextMenuTarget+ ? (entries.find((entry) => entry.item.workflow_id === contextMenuTarget.workflowId)?.projectWorkflow ?? null)+ : null;+ // Stepping walks the project's workflows as the toolbar and tags filter and order them.+ const position = selectedEntry ? entries.indexOf(selectedEntry) : -1;+ const stepPreview = useCallback(+ (delta: -1 | 1) => {+ const next = position < 0 ? undefined : entries[position + delta];++ if (next) {+ onSelect(next.item.workflow_id);+ }+ },+ [entries, onSelect, position]+ );+ const stepper = useMemo(+ () =>+ preview.isActive+ ? {+ canStepNext: position >= 0 && position < entries.length - 1,+ canStepPrevious: position > 0,+ onStep: stepPreview,+ position: position >= 0 ? position : null,+ total: entries.length,+ }+ : null,+ [entries.length, position, preview.isActive, stepPreview]+ );+ const previewStatus = useMemo<WorkflowLibraryPreviewStatus>(+ () => (selectedEntry ? { document: selectedEntry.projectWorkflow.document, kind: 'ready' } : { kind: 'pending' }),+ [selectedEntry]+ );const openWorkflow = useCallback((workflowId: string) => {selectWorkflow(workflowId);@@ -128,9 +184,6 @@ export const ProjectWorkflowsView = ({},[onClose, selectWorkflow]);- const handleNewWorkflow = useCallback(() => {- onSelect(createWorkflow());- }, [createWorkflow, onSelect]);const handleDuplicate = useCallback((workflowId: string, name: string) => {const copyId = duplicateWorkflow(workflowId, t('workflowLibrary.duplicateName', { name }));@@ -141,12 +194,16 @@ export const ProjectWorkflowsView = ({},[duplicateWorkflow, onSelect, t]);+ // Removing another workflow, from its card's menu, keeps the selection.const confirmRemove = useCallback(() => {if (removeTarget) {removeWorkflow(removeTarget);- onSelect(null);++ if (removeTarget === selectedWorkflowId) {+ onSelect(null);+ }}- }, [onSelect, removeTarget, removeWorkflow]);+ }, [onSelect, removeTarget, removeWorkflow, selectedWorkflowId]);const closeRename = useCallback(() => setRenameTarget(null), []);const closeRemove = useCallback(() => setRemoveTarget(null), []);const submitRename = useCallback(@@ -163,46 +220,71 @@ export const ProjectWorkflowsView = ({return (<>- <Stack flex="1" gap="2" minH="0" minW="0">- <HStack gap="2" justify="space-between" minW="0">- <Text color="fg.muted" fontSize="md" minW="0" truncate>- {t('workflowLibrary.projectWorkflowCount', { count: workflows.length })}- </Text>- <HStack flexShrink={0} gap="1">- <Button variant="outline" onClick={handleNewWorkflow}>- <PlusIcon />- {t('workflowLibrary.newWorkflow')}- </Button>- </HStack>- </HStack>- <HStack css={COLUMNS_CSS} align="stretch" flex="1" gap="3" minH="0" minW="0">- <WorkflowLibraryGrid+ <HStack css={WORKFLOW_LIBRARY_PANES_CSS} align="stretch" flex="1" gap="3" minH="0" minW="0">+ {layout === 'list' ? (+ <WorkflowLibraryListactiveWorkflowId={activeWorkflowId}entries={entries}error={null}missingCounts={missingCounts}- openMenuAnchor={contextMenuPoint}+ openMenuAnchor={contextMenuAnchor}selectedWorkflowId={activeSelectionId}status="loaded"onContextMenu={onContextMenu}onOpen={openWorkflow}+ onPreview={onPreview}onSelect={onSelect}+ trailingField={trailingField}/>- <ProjectWorkflowDetailPanel- contextMenuPoint={contextMenuPoint}- contextMenuTriggerId={contextMenuTriggerId}- entry={selectedEntry ? selectedEntry.projectWorkflow : null}- isActive={selectedEntry?.item.workflow_id === activeWorkflowId}- missingCount={selectedEntry ? (missingCounts.get(selectedEntry.item.workflow_id) ?? 0) : 0}- onContextMenuClose={onContextMenuClose}- onDuplicate={handleDuplicate}+ ) : (+ <WorkflowLibraryGrid+ activeWorkflowId={activeWorkflowId}+ entries={entries}+ error={null}+ missingCounts={missingCounts}+ openMenuAnchor={contextMenuAnchor}+ selectedWorkflowId={activeSelectionId}+ status="loaded"+ onContextMenu={onContextMenu}onOpen={openWorkflow}onPreview={onPreview}- onRemove={setRemoveTarget}- onRename={setRenameTarget}+ onSelect={onSelect}/>- </HStack>- </Stack>+ )}+ {preview.isActive ? (+ <WorkflowLibraryPreviewStage+ ref={previewStageRef}+ name={selectedEntry?.projectWorkflow.document.name || t('workflowLibrary.untitled')}+ placeLabel={preview.placeLabel}+ status={previewStatus}+ workflowId={activeSelectionId}+ view={preview.view}+ onLeave={preview.onLeave}+ onViewChange={preview.onViewChange}+ />+ ) : null}+ <ProjectWorkflowDetailPanel+ entry={selectedEntry ? selectedEntry.projectWorkflow : null}+ stepper={stepper}+ isActive={selectedEntry?.item.workflow_id === activeWorkflowId}+ missingCount={selectedEntry ? (missingCounts.get(selectedEntry.item.workflow_id) ?? 0) : 0}+ onDuplicate={handleDuplicate}+ onOpen={openWorkflow}+ onPreview={onPreview}+ onRemove={setRemoveTarget}+ onRename={setRenameTarget}+ />+ </HStack>+ <ProjectWorkflowContextMenu+ anchor={contextMenuAnchor}+ entry={menuEntry}+ target={contextMenuTarget}+ onDuplicate={handleDuplicate}+ onMenuClose={onContextMenuClose}+ onOpen={openWorkflow}+ onRemove={setRemoveTarget}+ onRename={setRenameTarget}+ /><RenameDialoginitialName={renameEntry?.document.name ?? ''}@@ -227,168 +309,62 @@ export const ProjectWorkflowsView = ({);};-interface ProjectWorkflowDetailPanelProps {- contextMenuPoint: WorkflowCardMenuAnchor | null;- /** What opened the menu last, kept through its close so focus returns there. */- contextMenuTriggerId: string | null;+interface ProjectWorkflowActionsOptions {+ /** The workflow the actions act on: the rail's selection, or the card a context menu was raised on. */entry: ProjectWorkflowEntry | null;- isActive: boolean;- missingCount: number;- onContextMenuClose: () => void;onDuplicate: (workflowId: string, name: string) => void;onOpen: (workflowId: string) => void;- onPreview: (entry: ProjectWorkflowEntry) => void;+ /** Asks to remove it; the view owns the confirmation. */onRemove: (workflowId: string) => void;+ /** Asks to rename it; the view owns the dialog. */onRename: (workflowId: string) => void;}-const ProjectWorkflowDetailPanel = ({- contextMenuPoint,- contextMenuTriggerId,+/** One project workflow's menu items, and the handlers the rail's own buttons share with them. */+const useProjectWorkflowActions = ({entry,- isActive,- missingCount,- onContextMenuClose,onDuplicate,onOpen,- onPreview,onRemove,onRename,-}: ProjectWorkflowDetailPanelProps) => {- const panelRef = useRef<HTMLDivElement>(null);- // Portaled action menus belong to this dialog's visible bounds, rather than the whole viewport.- const menuPositioning = useMemo(- () => ({- boundary: () => panelRef.current?.closest<HTMLElement>('[data-scope="dialog"][data-part="content"]') ?? [],- }),- []- );+}: ProjectWorkflowActionsOptions) => {const { t } = useTranslation();const session = useAuthSession();- const deps = useModelRequirementDeps();- const templatesSnapshot = useInvocationTemplatesSnapshot();- const openAddModels = useOpenAddModels();- const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);- const dataTime = useDataTimeSnapshot(entry);-- const libraryEntry = useMemo(- () =>- entry- ? toProjectWorkflowLibraryEntries(- [entry],- templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null- )[0]!- : null,- [entry, templatesSnapshot]- );- const resolved = useMemo(- () =>- libraryEntry?.enrichment.status === 'ready' ? resolveEntryRequirements(libraryEntry.enrichment, deps) : null,- [deps, libraryEntry]- );-- // A pointer point is a fixed rect; the tile button is the menu's trigger, so the menu follows it as it scrolls.- const contextMenuPositioning = useMemo(- () =>- contextMenuPoint?.kind === 'point'- ? {- ...menuPositioning,- getAnchorRect: () => ({ height: 1, width: 1, x: contextMenuPoint.x, y: contextMenuPoint.y }),- placement: 'bottom-start' as const,- }- : { ...menuPositioning, placement: 'bottom-end' as const },- [contextMenuPoint, menuPositioning]- );- const handleContextMenuOpenChange = useCallback(- (event: { open: boolean }) => {- if (!event.open) {- onContextMenuClose();- }- },- [onContextMenuClose]- );- // Focus returns to whatever opened the menu: the title's menu button, or the right-clicked card.- const contextMenuIds = useMemo(- () =>- entry- ? {- content: getWorkflowLibraryCardMenuContentId(entry.document.id),- trigger: contextMenuTriggerId ?? getWorkflowLibraryCardId(entry.document.id),- }- : undefined,- [contextMenuTriggerId, entry]- );- const moreActionsIds = useTooltipTriggerIds();- const handleThumbnailError = useCallback(- () => setFailedThumbnailUrl(libraryEntry?.item.thumbnail_url ?? null),- [libraryEntry]- );const entryId = entry?.document.id ?? null;const entryName = entry?.document.name || t('workflowLibrary.untitled');- const handleOpen = useCallback(() => entryId && onOpen(entryId), [entryId, onOpen]);+ const canUpdateSource = isUpdatableSource(entry?.source, session);+ const open = useCallback(() => entryId && onOpen(entryId), [entryId, onOpen]);const handleRename = useCallback(() => entryId && onRename(entryId), [entryId, onRename]);const handleDuplicate = useCallback(() => entryId && onDuplicate(entryId, entryName),[entryId, entryName, onDuplicate]);const handleRemove = useCallback(() => entryId && onRemove(entryId), [entryId, onRemove]);- const handlePreview = useCallback(() => entry && onPreview(entry), [entry, onPreview]);const handleSaveToLibrary = useCallback(() => entryId && requestWorkflowPublication({ kind: 'save-as-new', workflowId: entryId }),[entryId]);- const handleUpdateTemplate = useCallback(+ const updateTemplate = useCallback(() => entryId && requestWorkflowPublication({ kind: 'update-source', workflowId: entryId }),[entryId]);- if (!entry || !libraryEntry) {- return (- <Box- css={DETAIL_RAIL_CSS}- borderColor="border.subtle"- borderWidth="1px"- flexShrink={0}- minH="0"- rounded="md"- w={DETAIL_RAIL_WIDTH}- />- );- }-- const workflowId = entry.document.id;- const name = entryName;- const thumbnailUrl = libraryEntry.item.thumbnail_url;- const showThumbnail = Boolean(thumbnailUrl) && thumbnailUrl !== failedThumbnailUrl;- const lastRun = entry.lastRun ? formatTimeSince(entry.lastRun.completedAt, dataTime) : '';- const source = entry.source;- const canUpdateSource = isUpdatableSource(source, session);-const actionItems = (<>+ <MenuActionItem icon={WorkflowIcon} label={t('workflowLibrary.open')} value="open" onSelect={open} /><MenuActionItem- hint={t('workflowLibrary.openProjectWorkflowHint')}- icon={WorkflowIcon}- label={t('workflowLibrary.open')}- value="open"- onSelect={handleOpen}- />- <MenuActionItem- hint={t('workflowLibrary.renameProjectWorkflowHint')}icon={PencilIcon}label={t('workflowLibrary.renameWithEllipsis')}value="rename"onSelect={handleRename}/><MenuActionItem- hint={t('workflowLibrary.duplicateProjectWorkflowHint')}icon={CopyIcon}label={t('workflowLibrary.duplicate')}value="duplicate"onSelect={handleDuplicate}/><MenuActionItem- hint={t('workflowLibrary.saveToLibraryHint')}icon={BookmarkIcon}label={t('workflowLibrary.saveToLibraryWithEllipsis')}value="save-to-library"@@ -396,15 +372,13 @@ const ProjectWorkflowDetailPanel = ({/>{canUpdateSource ? (<MenuActionItem- hint={t('workflowLibrary.updateTemplateHint')}icon={RefreshCwIcon}label={t('workflowLibrary.updateTemplate')}value="update-template"- onSelect={handleUpdateTemplate}+ onSelect={updateTemplate}/>) : null}<MenuActionItem- hint={t('workflowLibrary.removeHint')}icon={Trash2Icon}label={t('workflowLibrary.removeWithEllipsis')}tone="danger"@@ -414,142 +388,427 @@ const ProjectWorkflowDetailPanel = ({</>);+ return { actionItems, canUpdateSource, open, updateTemplate };+};++interface ProjectWorkflowContextMenuProps extends Omit<ProjectWorkflowActionsOptions, 'entry'> {+ anchor: WorkflowCardMenuAnchor | null;+ /** The target's workflow; null once the filters hide it, when the shell has already closed the menu. */+ entry: ProjectWorkflowEntry | null;+ target: WorkflowContextMenuTarget | null;+ onMenuClose: () => void;+}++/** A project card's actions menu; its rename and remove dialogs are the view's, as the rail's are. */+const ProjectWorkflowContextMenu = ({+ anchor,+ entry,+ target,+ onMenuClose,+ ...actions+}: ProjectWorkflowContextMenuProps) => {+ const { actionItems } = useProjectWorkflowActions({ entry, ...actions });++ return (+ <WorkflowCardContextMenu anchor={anchor} target={target} onClose={onMenuClose}>+ {actionItems}+ </WorkflowCardContextMenu>+ );+};++interface ProjectWorkflowDetailPanelProps extends ProjectWorkflowActionsOptions {+ isActive: boolean;+ missingCount: number;+ onPreview: (workflowId: string, view?: WorkflowPreviewView) => void;+ /** Preview mode's stepper (`WorkflowDetailSheet`); none outside preview mode. */+ stepper: WorkflowPreviewStepperProps | null;+}++/**+ * The selected project workflow: preview, name with Open, facts, and the library template it is linked to. The+ * template's current record is read only for the selected workflow, through the saved-workflow detail query the+ * workflow header shares; the query client is account-scoped.+ */+const ProjectWorkflowDetailPanel = ({+ entry,+ stepper,+ isActive,+ missingCount,+ onDuplicate,+ onOpen,+ onPreview,+ onRemove,+ onRename,+}: ProjectWorkflowDetailPanelProps) => {+ const panelRef = useRef<HTMLDivElement>(null);+ // Portaled action menus belong to this dialog's visible bounds, rather than the whole viewport.+ const menuPositioning = useMemo(+ () => ({+ boundary: () => panelRef.current?.closest<HTMLElement>('[data-scope="dialog"][data-part="content"]') ?? [],+ }),+ []+ );+ const { t } = useTranslation();+ const deps = useModelRequirementDeps();+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const openAddModels = useOpenAddModels();+ const notify = useWorkflowNotifications();+ const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);+ const [isUpdateConfirmOpen, setIsUpdateConfirmOpen] = useState(false);+ const dataTime = useDataTimeSnapshot(entry);+ const statusLineId = useId();++ const libraryEntry = useMemo(+ () =>+ entry+ ? toProjectWorkflowLibraryEntries(+ [entry],+ templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null+ )[0]!+ : null,+ [entry, templatesSnapshot]+ );+ const resolved = useMemo(+ () =>+ libraryEntry?.enrichment.status === 'ready' ? resolveEntryRequirements(libraryEntry.enrichment, deps) : null,+ [deps, libraryEntry]+ );+ const missingNodePacks =+ libraryEntry?.enrichment.status === 'ready' && templatesSnapshot.status === 'loaded'+ ? getMissingNodePacks(libraryEntry.enrichment, templatesSnapshot.templates)+ : NO_NODE_PACKS;++ const source = entry?.source;+ const isBundledSource = source !== undefined && isBundledLibraryWorkflowId(source.libraryWorkflowId);+ // Bundled templates are rewritten at every server start, so only a user template's revision is comparable.+ const comparesRevision = source !== undefined && !isBundledSource && source.revision !== null;+ /*+ * The template's name and revision come from the full saved-workflow record, workflow JSON included: the server has+ * no metadata-only read by id. Sharing this query (the Call Saved Workflow field and the workflow header use it)+ * costs no second request. It lives in the account-scoped query client with gcTime Infinity, and+ * CallSavedWorkflowSyncRuntime invalidates it when the library cache changes; `select` keeps this rail rendering+ * only for the two fields it shows.+ */+ const template = useQuery({+ ...savedWorkflowDetailQueryOptions(comparesRevision ? source.libraryWorkflowId : ''),+ enabled: comparesRevision,+ select: selectTemplateSummary,+ });+ const templateRevision = comparesRevision ? (template.data?.revision ?? null) : null;+ const isTemplateNewer =+ templateRevision !== null &&+ source?.revision !== null &&+ source !== undefined &&+ templateRevision > source.revision;+ // A template that is gone or no longer readable has nothing to update from.+ const canUpdateFromTemplate = source !== undefined && !(comparesRevision && template.isError);++ const handleReplaced = useCallback(() => notify.success(t('workflowLibrary.updatedFromTemplate')), [notify, t]);+ const { loadPhase, replace } = useOpenLibraryWorkflow(handleReplaced);+ const isReplacing = loadPhase !== 'idle';+ // The rail's More and the sheet's More act on the selection; a card's own menu has its own instance.+ const {+ actionItems,+ canUpdateSource,+ open: handleOpen,+ updateTemplate: handleUpdateTemplate,+ } = useProjectWorkflowActions({ entry, onDuplicate, onOpen, onRemove, onRename });+ const moreActionsIds = useTooltipTriggerIds();+ const handleThumbnailError = useCallback(+ () => setFailedThumbnailUrl(libraryEntry?.item.thumbnail_url ?? null),+ [libraryEntry]+ );+ const entryId = entry?.document.id ?? null;+ const entryName = entry?.document.name || t('workflowLibrary.untitled');+ const handlePreview = useCallback(() => entry && onPreview(entry.document.id), [entry, onPreview]);+ const handlePreviewInputs = useCallback(() => entry && onPreview(entry.document.id, 'inputs'), [entry, onPreview]);+ const previewModel = useWorkflowPreviewModel(entry?.document ?? null);+ const openUpdateConfirm = useCallback(() => setIsUpdateConfirmOpen(true), []);+ const closeUpdateConfirm = useCallback(() => setIsUpdateConfirmOpen(false), []);+ // The copy keeps its id and position; the replacement is one undo step.+ const confirmUpdateFromTemplate = useCallback(async () => {+ if (!entryId || !source) {+ return;+ }++ await replace(+ {+ name: template.data?.name || entryName,+ workflow_id: source.libraryWorkflowId,+ ...(templateRevision === null ? {} : { revision: templateRevision }),+ },+ entryId+ );+ }, [entryId, entryName, replace, source, template.data, templateRevision]);++ if (!entry || !libraryEntry) {+ return <WorkflowDetailRailPlaceholder />;+ }++ const workflowId = entry.document.id;+ const name = entryName;+ const thumbnailUrl = libraryEntry.item.thumbnail_url;+ const showThumbnail = Boolean(thumbnailUrl) && thumbnailUrl !== failedThumbnailUrl;+ const lastRun = entry.lastRun ? formatTimeSince(entry.lastRun.completedAt, dataTime) : '';+ const edited = entry.document.updatedAt ? formatTimeSince(entry.document.updatedAt, dataTime) : '';+ const enrichment = libraryEntry.enrichment.status === 'ready' ? libraryEntry.enrichment : null;+ const primaryBase = enrichment?.requirements.primaryBase ?? null;+ const statusLine = isActive+ ? lastRun+ ? t('workflowLibrary.activeRanWhen', { when: lastRun })+ : t('workflowLibrary.activeWorkflowLine')+ : lastRun+ ? t('workflowLibrary.ranWhen', { when: lastRun })+ : '';++ const summaryFacts = [+ primaryBase ? getModelBaseLabel(primaryBase) : null,+ enrichment ? t('workflowLibrary.nodeCount', { count: enrichment.nodeCount }) : null,+ missingNodePacks.length > 0+ ? t('workflowLibrary.nodePacksMissing', { count: missingNodePacks.length })+ : missingCount > 0+ ? t('workflowLibrary.modelsToInstall', { count: missingCount })+ : enrichment+ ? t('workflowLibrary.readyToRun')+ : null,+ isTemplateNewer ? t('workflowLibrary.templateNewer') : null,+ statusLine || null,+ ]+ .filter((fact) => fact !== null)+ .join(' · ');++ const updateConfirm = (+ <ConfirmDialog+ body={t('workflowLibrary.updateFromTemplateBody', { name })}+ confirmLabel={t('workflowLibrary.updateFromTemplateConfirm')}+ isOpen={isUpdateConfirmOpen}+ title={t('workflowLibrary.updateFromTemplate')}+ onClose={closeUpdateConfirm}+ onConfirm={confirmUpdateFromTemplate}+ />+ );+return (- <Stack- borderColor="border.subtle"- borderWidth="1px"- css={DETAIL_RAIL_CSS}- ref={panelRef}- data-project-workflow-detail={workflowId}- flexShrink={0}- gap="0"- minH="0"- rounded="md"- w={DETAIL_RAIL_WIDTH}- >- <Scrollable flex="1" label={name} minH="0">- <Stack gap="2" minW="0" p="2.5">- <Stack gap="1" minW="0">- <Box aspectRatio={WORKFLOW_THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" rounded="md" w="full">- {showThumbnail ? (- <WorkflowThumbnailImage src={thumbnailUrl} onError={handleThumbnailError} />- ) : (- <Flex align="center" direction="column" gap="1" h="full" justify="center" w="full">- <Icon aria-hidden as={ImageOffIcon} boxSize="5" color="fg.subtle" opacity={0.6} />- <Text color="fg.subtle" fontSize="xs">- {t('workflowLibrary.notRunYet')}- </Text>- </Flex>- )}+ <>+ <WorkflowDetailSheet+ ref={panelRef}+ actions={actionItems}+ data-project-workflow-detail={workflowId}+ facts={summaryFacts}+ isOpenDisabled={isActive}+ menuPositioning={menuPositioning}+ name={name}+ openLabel={t('workflowLibrary.open')}+ thumbnailSrc={showThumbnail ? thumbnailUrl : null}+ workflowDocument={entry.document}+ stepper={stepper}+ workflowId={workflowId}+ onOpen={handleOpen}+ >+ <Scrollable flex="1" label={name} minH="0">+ <Stack gap="2.5" minW="0" p="2.5">+ {/* The expanded sheet's summary is its compact heading: no large preview, no second name. */}+ <Box css={THUMBNAIL_SLOT_CSS} w="full">+ <Box+ aspectRatio={WORKFLOW_THUMBNAIL_ASPECT_RATIO}+ bg="bg.muted"+ data-thumbnail-kind={showThumbnail ? 'image' : 'silhouette'}+ overflow="hidden"+ position="relative"+ rounded="md"+ w="full"+ >+ {showThumbnail ? (+ <WorkflowThumbnailImage src={thumbnailUrl} onError={handleThumbnailError} />+ ) : (+ <WorkflowThumbnailPlaceholder+ caption={t('workflowLibrary.notRunYet')}+ workflowDocument={entry.document}+ />+ )}+ <WorkflowPreviewThumbnailButton name={name} onPreview={handlePreview} />+ </Box></Box>- {lastRun ? (- <Text color="fg.subtle" fontSize="xs">- {t('workflowLibrary.lastRun', { when: lastRun })}++ <Stack css={WORKFLOW_DETAIL_WIDE_ONLY_CSS} gap="0.5" minW="0">+ <Text fontSize="lg" fontWeight="600" minW="0" overflowWrap="anywhere">+ {name}</Text>+ <WorkflowProvenance document={entry.document} kind={t('workflowLibrary.preview.kindProject')} />+ {statusLine ? (+ <Text color="fg.muted" fontSize="xs" id={statusLineId}>+ {statusLine}+ </Text>+ ) : null}+ </Stack>++ {primaryBase || enrichment || missingNodePacks.length > 0 ? (+ <HStack flexWrap="wrap" gap="1" minW="0">+ {primaryBase ? <Badge variant="subtle">{getModelBaseLabel(primaryBase)}</Badge> : null}+ {enrichment ? (+ <Badge variant="subtle">{t('workflowLibrary.nodeCount', { count: enrichment.nodeCount })}</Badge>+ ) : null}+ <WorkflowInputsBadge model={previewModel} />+ {missingNodePacks.length > 0 ? (+ <Badge bg="bg.error" color="fg.error" data-workflow-missing-node-packs variant="subtle">+ {t('workflowLibrary.nodePacksMissing', { count: missingNodePacks.length })}+ </Badge>+ ) : null}+ </HStack>) : null}- </Stack>- <HStack gap="1.5" minW="0">- <Text fontSize="lg" fontWeight="600" minW="0" overflowWrap="anywhere">- {name}- </Text>- {isActive ? (- <Badge flexShrink={0} variant="solid">- {t('workflowLibrary.activeWorkflow')}- </Badge>+ {entry.document.description ? (+ <Text color="fg.muted" fontSize="xs" overflowWrap="anywhere">+ {entry.document.description}+ </Text>) : null}- </HStack>- {entry.document.description ? (- <Text color="fg.muted" fontSize="xs" overflowWrap="anywhere">- {entry.document.description}- </Text>- ) : null}-- <Text color="fg.subtle" fontSize="xs" data-workflow-source={source?.libraryWorkflowId ?? 'none'}>- {source- ? isBundledLibraryWorkflowId(source.libraryWorkflowId)- ? t('workflowLibrary.sourceBundled')- : source.revision === null- ? t('workflowLibrary.sourceUnknownRevision')- : t('workflowLibrary.sourceRevision', { revision: source.revision })- : t('workflowLibrary.sourceNone')}- </Text>-- {libraryEntry.tags.length > 0 ? (- <HStack flexWrap="wrap" gap="1" minW="0">- {libraryEntry.tags.map((tag) => (- <Badge key={tag} variant="subtle">- {tag}- </Badge>- ))}- </HStack>- ) : null}-- <WorkflowRequirementsList errorMessage={null} resolved={resolved} onFindModel={openAddModels} />- </Stack>- </Scrollable>+ <WorkflowInputsSummary model={previewModel} onSeeAll={handlePreviewInputs} />+ <WorkflowAuthorNotes notes={entry.document.notes} />- <Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" p="2.5">- <HStack gap="2" minW="0">- <Button disabled={isActive} flex="1" minW="0" size="lg" onClick={handleOpen}>- {isActive ? t('workflowLibrary.activeWorkflow') : t('workflowLibrary.open')}+ <Stack+ borderColor="border.subtle"+ borderWidth="1px"+ data-linked-template={source?.libraryWorkflowId ?? 'none'}+ gap="1.5"+ minW="0"+ p="2"+ rounded="md"+ >+ <HStack gap="1.5" justify="space-between" minW="0">+ <Text color="fg.muted" fontSize="xs" fontWeight="600">+ {t('workflowLibrary.linkedTemplate')}+ </Text>+ {isTemplateNewer ? (+ <Badge bg="bg.warning" color="fg.warning" data-template-newer flexShrink={0} variant="subtle">+ {t('workflowLibrary.templateNewer')}+ </Badge>+ ) : null}+ </HStack>+ <Text color="fg.muted" fontSize="xs" data-workflow-source={source?.libraryWorkflowId ?? 'none'}>+ {source+ ? isBundledSource+ ? t('workflowLibrary.sourceBundled')+ : source.revision === null+ ? t('workflowLibrary.sourceUnknownRevision')+ : template.data?.name+ ? t('workflowLibrary.sourceNamedRevision', {+ name: template.data.name,+ revision: source.revision,+ })+ : t('workflowLibrary.sourceRevision', { revision: source.revision })+ : t('workflowLibrary.sourceNone')}+ </Text>+ {templateRevision !== null ? (+ <Text color="fg.muted" data-template-revision={templateRevision} fontSize="xs">+ {t('workflowLibrary.templateRevision', { revision: templateRevision })}+ </Text>+ ) : null}+ {source ? (+ // Stacked full width: side by side the two labels wrap unevenly in the 18rem rail.+ <Stack gap="1.5" minW="0">+ <Button+ disabled={!canUpdateFromTemplate || isReplacing}+ loading={isReplacing}+ size="xs"+ variant={isTemplateNewer ? 'solid' : 'outline'}+ w="full"+ onClick={openUpdateConfirm}+ >+ {t('workflowLibrary.updateFromTemplate')}+ </Button>+ {canUpdateSource ? (+ <Button size="xs" variant="outline" w="full" onClick={handleUpdateTemplate}>+ {t('workflowLibrary.updateTemplate')}+ </Button>+ ) : null}+ </Stack>+ ) : null}+ </Stack>++ {libraryEntry.tags.length > 0 ? (+ <HStack flexWrap="wrap" gap="1" minW="0">+ {libraryEntry.tags.map((tag) => (+ <Badge key={tag} variant="outline">+ {tag}+ </Badge>+ ))}+ </HStack>+ ) : null}++ <WorkflowMissingNodePacks packs={missingNodePacks} />+ <WorkflowRequirementsList errorMessage={null} resolved={resolved} onFindModel={openAddModels} />+ {missingCount > 0 ? (+ <Text color="fg.warning" fontSize="xs">+ {t('workflowLibrary.modelsToInstall', { count: missingCount })}+ </Text>+ ) : null}++ <DataList.Root data-project-workflow-facts gap="1.5" orientation="horizontal">+ <WorkflowDetailFact label={t('workflowLibrary.factLastRun')}>+ {lastRun || t('workflowLibrary.notRunYet')}+ </WorkflowDetailFact>+ {edited ? (+ <WorkflowDetailFact label={t('workflowLibrary.factEdited')}>{edited}</WorkflowDetailFact>+ ) : null}+ </DataList.Root>+ </Stack>+ </Scrollable>++ {/* The pinned footer ends in the primary action, as a picker's commit button; the narrow sheet's summary+ carries Open and More instead. */}+ <Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" minW="0" p="2.5">+ <Button+ css={WORKFLOW_PREVIEW_TRIGGER_CSS}+ data-workflow-preview-trigger=""+ minW="0"+ size="lg"+ variant="outline"+ w="full"+ onClick={handlePreview}+ >+ <WorkflowIcon />+ {t('workflowLibrary.preview.action')}</Button>- <Menu.Root ids={moreActionsIds} positioning={menuPositioning}>- {/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, the- menu never takes focus and the first pointer move onto it closes it. */}- <Menu.Trigger asChild>- <Tooltip content={t('workflowLibrary.moreActions')} ids={moreActionsIds}>- <IconButton aria-label={t('workflowLibrary.moreActions')} size="lg" variant="outline">- <EllipsisIcon />- </IconButton>- </Tooltip>- </Menu.Trigger>- <Portal>- <Menu.Positioner>- <MenuContent minW="min(16rem, var(--available-width))" maxW="var(--available-width)">- {actionItems}- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- </HStack>- <Button- disabled={libraryEntry.enrichment.status !== 'ready'}- size="lg"- variant="outline"- w="full"- onClick={handlePreview}- >- <WorkflowIcon />- {t('workflowLibrary.previewGraph')}- </Button>- {missingCount > 0 ? (- <Text color="fg.warning" fontSize="xs">- {t('workflowLibrary.installModels', { count: missingCount })}- </Text>- ) : null}- </Stack>-- <Menu.Root- ids={contextMenuIds}- open={contextMenuPoint !== null}- positioning={contextMenuPositioning}- onOpenChange={handleContextMenuOpenChange}- onPointerDownOutside={keepCardMenuOpenForRetarget}- >- <Portal>- <Menu.Positioner>- <MenuContent- data-workflow-context-menu- minW="min(16rem, var(--available-width))"- maxW="var(--available-width)"+ <HStack css={WORKFLOW_DETAIL_WIDE_ONLY_CSS} gap="2" minW="0">+ {/* The active workflow is already open: the primary slot, disabled, says why through the status line. */}+ <Button+ aria-describedby={isActive ? statusLineId : undefined}+ data-project-workflow-open+ disabled={isActive}+ flex="1"+ minW="0"+ size="lg"+ onClick={handleOpen}+ >+ {t('workflowLibrary.open')}+ </Button>+ <Menu.Root+ ids={moreActionsIds}+ positioning={menuPositioning}+ onRequestDismiss={keepMenuOpenWhenSiblingMenuCloses}>- {actionItems}- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>- </Stack>+ {/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, the+ menu never takes focus and the first pointer move onto it closes it. */}+ <Menu.Trigger asChild>+ <Tooltip content={t('workflowLibrary.moreActions')} ids={moreActionsIds}>+ <IconButton aria-label={t('workflowLibrary.moreActions')} size="lg" variant="outline">+ <EllipsisIcon />+ </IconButton>+ </Tooltip>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="min(13rem, var(--available-width))" maxW="var(--available-width)">+ {actionItems}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </HStack>+ </Stack>+ </WorkflowDetailSheet>+ {updateConfirm}+ </>);};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowDetailOverview.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowDetailOverview.tsxnew file mode 100644index 0000000000..2b4c537b80--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowDetailOverview.tsx@@ -0,0 +1,225 @@+import type { ProjectGraphState } from '@features/workflow/core/types';+import type { WorkflowPreviewModel } from '@features/workflow/core/workflowPreview';++import { Badge, chakra, HStack, Stack, type SystemStyleObject, Text } from '@chakra-ui/react';+import { buildWorkflowPreviewModel } from '@features/workflow/core/workflowPreview';+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { Button } from '@platform/ui/Button';+import { useCallback, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * The detail rail's account of a workflow before it is opened: where it comes from, what its author says about it,+ * and what a person fills in. Read from the same preview model the stage draws, so the rail and the preview agree.+ */++const NOTES_LINES = 3;+/** First labels per heading the "You set" lines name before "+N". */+const LABELS_PER_GROUP = 3;+const SECTION_LABEL_PROPS = { color: 'fg.muted', fontSize: 'xs', fontWeight: '600' } as const;++/** The workflow's preview model once its document and the node templates are known. */+export const useWorkflowPreviewModel = (document: ProjectGraphState | null): WorkflowPreviewModel | null => {+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const templates = templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null;++ return useMemo(+ () => (document && templates ? buildWorkflowPreviewModel(document, templates) : null),+ [document, templates]+ );+};++/** "Template · by Invoke · v1.0.0": only the parts that are known. */+export const WorkflowProvenance = ({ document, kind }: { document: ProjectGraphState | null; kind: string }) => {+ const { t } = useTranslation();+ const author = document?.author.trim();+ const version = document?.workflowVersion.trim();+ const line = [+ kind,+ author ? t('workflowLibrary.preview.byAuthor', { author }) : null,+ version ? t('workflowLibrary.preview.version', { version }) : null,+ ]+ .filter((part) => part !== null)+ .join(' · ');++ return (+ <Text color="fg.muted" data-workflow-provenance="" fontSize="xs">+ {line}+ </Text>+ );+};++/** The "N inputs" fact beside the node count. */+export const WorkflowInputsBadge = ({ model }: { model: WorkflowPreviewModel | null }) => {+ const { t } = useTranslation();++ return model && model.inputs.length > 0 ? (+ <Badge data-workflow-inputs-count="" variant="subtle">+ {t('workflowLibrary.preview.inputCount', { count: model.inputs.length })}+ </Badge>+ ) : null;+};++/** The workflow's own notes, three lines until "Read all notes" opens them in place. */+export const WorkflowAuthorNotes = ({ notes }: { notes: string }) => {+ const { t } = useTranslation();+ const notesId = useId();+ const textRef = useRef<HTMLParagraphElement>(null);+ const [expandedNotes, setExpandedNotes] = useState<string | null>(null);+ const [clampedNotes, setClampedNotes] = useState<string | null>(null);+ const isExpanded = expandedNotes === notes;+ const toggle = useCallback(() => setExpandedNotes(isExpanded ? null : notes), [isExpanded, notes]);++ // Whether three lines cut the notes off decides the toggle; measured before paint, once per text.+ useLayoutEffect(() => {+ const element = textRef.current;++ if (element && !isExpanded) {+ setClampedNotes(element.scrollHeight > element.clientHeight + 1 ? notes : null);+ }+ }, [isExpanded, notes]);++ if (!notes.trim()) {+ return null;+ }++ return (+ <Stack data-workflow-author-notes="" gap="1" minW="0">+ <Text {...SECTION_LABEL_PROPS}>{t('workflowLibrary.preview.authorNotes')}</Text>+ <Text+ ref={textRef}+ color="fg.muted"+ fontSize="xs"+ id={notesId}+ lineClamp={isExpanded ? undefined : NOTES_LINES}+ overflowWrap="anywhere"+ whiteSpace="pre-wrap"+ >+ {notes}+ </Text>+ {clampedNotes === notes || isExpanded ? (+ <Button+ alignSelf="flex-start"+ aria-controls={notesId}+ aria-expanded={isExpanded}+ color="accent.fg"+ fontSize="xs"+ h="auto"+ px="0"+ size="xs"+ variant="plain"+ onClick={toggle}+ >+ {isExpanded ? t('workflowLibrary.preview.showLessNotes') : t('workflowLibrary.preview.readAllNotes')}+ </Button>+ ) : null}+ </Stack>+ );+};++/** "You set": a line per form heading naming its first inputs, and the way into the preview's Inputs view. */+export const WorkflowInputsSummary = ({+ model,+ onSeeAll,+}: {+ model: WorkflowPreviewModel | null;+ onSeeAll: () => void;+}) => {+ const { i18n, t } = useTranslation();+ const listFormat = useMemo(+ () => new Intl.ListFormat(i18n.resolvedLanguage, { style: 'short', type: 'unit' }),+ [i18n.resolvedLanguage]+ );++ if (!model || model.inputs.length === 0) {+ return null;+ }++ return (+ <Stack data-workflow-inputs-summary="" gap="1" minW="0">+ <Text {...SECTION_LABEL_PROPS}>{t('workflowLibrary.preview.youSet')}</Text>+ {model.inputGroups.map((group, index) => {+ const shown = group.labels.slice(0, LABELS_PER_GROUP);+ const rest = group.labels.length - shown.length;+ const labels = listFormat.format(+ rest > 0 ? [...shown, t('workflowLibrary.preview.more', { count: rest })] : shown+ );++ return (+ <Text key={index} fontSize="xs" overflowWrap="anywhere">+ {group.heading ? (+ <Text as="span" color="fg.muted">+ {group.heading} ·{' '}+ </Text>+ ) : null}+ {labels}+ </Text>+ );+ })}+ <Button+ alignSelf="flex-start"+ color="accent.fg"+ data-workflow-see-inputs=""+ fontSize="xs"+ h="auto"+ px="0"+ size="xs"+ variant="plain"+ onClick={onSeeAll}+ >+ {t('workflowLibrary.preview.seeAllInputs', { count: model.inputs.length })}+ </Button>+ </Stack>+ );+};++/**+ * For the rail's thumbnail slot: preview mode draws the graph on the stage, so a thumbnail that only drew the same+ * graph's silhouette steps aside (`data-thumbnail-kind`); a real cover image stays.+ */+export const WORKFLOW_SILHOUETTE_THUMBNAIL_CSS: SystemStyleObject = {+ '&:is([data-previewing] *):has([data-thumbnail-kind="silhouette"])': { display: 'none' },+};+const THUMBNAIL_BUTTON_CSS: SystemStyleObject = {+ cursor: 'pointer',+ inset: '0',+ position: 'absolute',+ rounded: 'md',+ _focusVisible: { outlineColor: 'accent.solid', outlineOffset: '-2px', outlineStyle: 'solid', outlineWidth: '2px' },+ '[data-previewing] &': { display: 'none' },+};++/**+ * The rail thumbnail as the way into the preview: a press anywhere on it previews the workflow, and its corner names+ * the action. Laid over the thumbnail, under any controls drawn after it.+ */+export const WorkflowPreviewThumbnailButton = ({ name, onPreview }: { name: string; onPreview: () => void }) => {+ const { t } = useTranslation();++ return (+ <chakra.button+ aria-label={t('workflowLibrary.preview.previewNamed', { name })}+ css={THUMBNAIL_BUTTON_CSS}+ data-thumbnail-preview=""+ type="button"+ onClick={onPreview}+ >+ <HStack+ aria-hidden+ bg="bg.panel/90"+ borderColor="border.emphasized"+ borderWidth="1px"+ bottom="1.5"+ fontSize="sm"+ gap="1.5"+ h="5.5"+ insetEnd="1.5"+ position="absolute"+ px="2"+ rounded="md"+ >+ {t('workflowLibrary.preview.action')}+ </HStack>+ </chakra.button>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowDetailSheet.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowDetailSheet.tsxnew file mode 100644index 0000000000..d5eff6a26c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowDetailSheet.tsx@@ -0,0 +1,407 @@+import type { ProjectGraphState } from '@features/workflow/contracts';++import { Box, HStack, Menu, Portal, Stack, type StackProps, type SystemStyleObject, Text } from '@chakra-ui/react';+import { Button, IconButton } from '@platform/ui/Button';+import { MenuContent } from '@platform/ui/Menu';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { ChevronDownIcon, ChevronUpIcon, EllipsisIcon } from 'lucide-react';+import {+ type KeyboardEvent as ReactKeyboardEvent,+ type ReactNode,+ type RefObject,+ useCallback,+ useId,+ useMemo,+ useRef,+ useState,+} from 'react';+import { flushSync } from 'react-dom';+import { useTranslation } from 'react-i18next';++import type { WorkflowPreviewStepperProps } from './WorkflowPreviewStepper';++import { keepMenuOpenWhenSiblingMenuCloses } from './WorkflowLibraryCard';+import { WORKFLOW_LIBRARY_NARROW } from './WorkflowLibraryRail';+import { WorkflowThumbnailPlaceholder } from './WorkflowLibraryThumbnail';+import { WorkflowPreviewStepper } from './WorkflowPreviewStepper';+import { WORKFLOW_THUMBNAIL_ASPECT_RATIO, WorkflowThumbnailImage } from './workflowThumbnail';++/**+ * The selected workflow's detail rail, beside the grid in the wide layout and a bottom sheet in the narrow one+ * (`WORKFLOW_LIBRARY_NARROW`). The sheet is a one-row summary (thumbnail, name, facts, Open, More) pinned under the+ * grid; its "Details and requirements" disclosure lays the full rail over the grid, which keeps its scroll position.+ * The layout switch is CSS alone: in the narrow layout the rail's root stops generating a box (`display: contents`),+ * so its details and summary become items of the panes grid (`WORKFLOW_DETAIL_PANES_CSS`). Expanding never animates.+ * Expanded, the sheet is compact: the pinned summary is its header (small thumbnail, the full name, Open), and the+ * details above it drop the rail's large preview and heading (`WORKFLOW_DETAIL_WIDE_ONLY_CSS`), leaving chips,+ * description, requirements and facts in one scrolling column.+ */++const DETAIL_RAIL_WIDTH = '18rem';+/**+ * A content box too short for the panes to share its height: the column scrolls as a whole, the grid or list takes a+ * fixed viewport of its own, and the rail takes a height the dialog body of a 320px-tall window still fits.+ */+export const WORKFLOW_LIBRARY_FLOW_LAYOUT =+ '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)';++/** The grid and the detail rail side by side; in the narrow layout, the grid over the sheet's summary. */+export const WORKFLOW_DETAIL_PANES_CSS: SystemStyleObject = {+ [WORKFLOW_LIBRARY_FLOW_LAYOUT]: { flex: '0 0 auto' },+ [WORKFLOW_LIBRARY_NARROW]: {+ display: 'grid',+ gridTemplateColumns: 'minmax(0, 1fr)',+ gridTemplateRows: 'minmax(0, 1fr) auto',+ rowGap: '2',+ '& > :not([data-detail-sheet])': { gridArea: '1 / 1' },+ // Under the expanded details the grid or list keeps its layout and scroll position, but leaves the tab order. The+ // rule names its target by attribute: a `:not(...)` target makes every :has() check restyle the whole collection,+ // which rows mounting while scrolling trigger each frame.+ '&:has(> [data-detail-sheet][data-expanded]) > [data-workflow-library-collection]': { visibility: 'hidden' },+ },+};++const RAIL_CSS: SystemStyleObject = {+ [WORKFLOW_LIBRARY_FLOW_LAYOUT]: { flex: '0 0 auto', height: '17rem' },+ [WORKFLOW_LIBRARY_NARROW]: { display: 'contents' },+};+const DETAILS_CSS: SystemStyleObject = {+ [WORKFLOW_LIBRARY_NARROW]: {+ bg: 'bg.subtle',+ borderColor: 'border.subtle',+ borderWidth: '1px',+ // Sized by the grid's row alone: in a flow layout the row is the grid's fixed viewport, which the details'+ // content must not stretch.+ contain: 'size',+ display: 'none',+ gridArea: '1 / 1',+ rounded: 'md',+ zIndex: 1,+ '&[data-expanded]': { display: 'flex' },+ },+};+const SUMMARY_CSS: SystemStyleObject = {+ display: 'none',+ [WORKFLOW_LIBRARY_NARROW]: {+ bg: 'bg.subtle',+ borderColor: 'border.subtle',+ borderWidth: '1px',+ bottom: '0',+ display: 'flex',+ flexDirection: 'column',+ gap: '1',+ gridArea: '2 / 1',+ p: '2',+ // A flow layout scrolls the column; the summary and its Open stay in view at its foot.+ position: 'sticky',+ rounded: 'md',+ zIndex: 2,+ // The column's bottom scroll padding keeps focused controls clear of this summary; the summary's own controls+ // are always in view, so focusing them must not scroll the column.+ '& button': { scrollMarginBottom: '-6rem' },+ },+};+const PLACEHOLDER_CSS: SystemStyleObject = { ...RAIL_CSS, [WORKFLOW_LIBRARY_NARROW]: { display: 'none' } };++/**+ * The rail's Preview button: kept mounted in preview mode, which the stage already shows, so leaving can hand focus back+ * to it. The dialog body marks preview mode.+ */+export const WORKFLOW_PREVIEW_TRIGGER_CSS: SystemStyleObject = { '[data-previewing] &': { display: 'none' } };++/** Rail chrome the sheet's summary already carries: the large preview, the heading with Open, and More. */+export const WORKFLOW_DETAIL_WIDE_ONLY_CSS: SystemStyleObject = { [WORKFLOW_LIBRARY_NARROW]: { display: 'none' } };++/** The empty rail while nothing is selected; the narrow layout shows no sheet. */+export const WorkflowDetailRailPlaceholder = () => (+ <Box+ borderColor="border.subtle"+ borderWidth="1px"+ css={PLACEHOLDER_CSS}+ flexShrink={0}+ minH="0"+ rounded="md"+ w={DETAIL_RAIL_WIDTH}+ />+);++/** Names the node packs a workflow needs and this server lacks, beside the requirements. */+export const WorkflowMissingNodePacks = ({ packs }: { packs: readonly string[] }) => {+ const { i18n, t } = useTranslation();+ const listFormat = useMemo(+ () => new Intl.ListFormat(i18n.resolvedLanguage, { type: 'conjunction' }),+ [i18n.resolvedLanguage]+ );++ return packs.length > 0 ? (+ <Text color="fg.error" data-workflow-missing-node-pack-names fontSize="xs" overflowWrap="anywhere">+ {t('workflowLibrary.missingNodePackNames', { count: packs.length, packs: listFormat.format(packs) })}+ </Text>+ ) : null;+};++/** A small 3:2 thumbnail, the image while it loads, else the silhouette: the sheet's summary and the list's rows. */+export const WorkflowSummaryThumbnail = ({+ src,+ w = '16',+ workflowDocument,+}: {+ src: string | null | undefined;+ /** Width; the height follows at 3:2. */+ w?: string;+ workflowDocument: ProjectGraphState | null;+}) => {+ const [failedSrc, setFailedSrc] = useState<string | null>(null);+ const handleError = useCallback(() => setFailedSrc(src ?? null), [src]);++ return (+ <Box+ aria-hidden+ aspectRatio={WORKFLOW_THUMBNAIL_ASPECT_RATIO}+ bg="bg.muted"+ flexShrink={0}+ overflow="hidden"+ rounded="sm"+ w={w}+ >+ {src && src !== failedSrc ? (+ <WorkflowThumbnailImage src={src} onError={handleError} />+ ) : (+ <WorkflowThumbnailPlaceholder workflowDocument={workflowDocument} />+ )}+ </Box>+ );+};++const isRendered = (element: Element | null | undefined): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0;++/**+ * Whether an Escape keydown belongs to an expanded sheet, which collapses rather than letting the dialog close. Only+ * the narrow layout renders the disclosure, so a sheet left expanded across a widening never swallows Escape.+ */+export const isWorkflowDetailSheetEscape = (event: KeyboardEvent): boolean =>+ event.target instanceof Element &&+ isRendered(event.target.closest('[data-detail-sheet][data-expanded]')?.querySelector('[data-detail-sheet-toggle]'));++export interface WorkflowDetailSheetProps extends Omit<StackProps, 'children' | 'css'> {+ ref: RefObject<HTMLDivElement | null>;+ /** The shown workflow; moving the selection collapses an expanded sheet. */+ workflowId: string;+ /** The full rail: its scroll area and action footer. */+ children: ReactNode;+ name: string;+ /** The summary's facts line, such as "SDXL · 23 nodes · Ready to run"; empty for none. */+ facts: string;+ thumbnailSrc: string | null | undefined;+ workflowDocument: ProjectGraphState | null;+ openLabel: string;+ /** Disables the summary's Open; the facts line is its reason. */+ isOpenDisabled?: boolean;+ onOpen: () => void;+ /** The rail's actions menu items, offered again from the summary's More. */+ actions: ReactNode;+ menuPositioning: Menu.RootProps['positioning'];+ /**+ * Preview mode's stepper, which steps the workflow this rail describes: atop the rail, or beside the name in the+ * narrow sheet's summary.+ */+ stepper?: WorkflowPreviewStepperProps | null;+}++export const WorkflowDetailSheet = ({+ actions,+ children,+ facts,+ isOpenDisabled = false,+ menuPositioning,+ name,+ openLabel,+ ref,+ thumbnailSrc,+ workflowDocument,+ workflowId,+ onOpen,+ stepper,+ ...railProps+}: WorkflowDetailSheetProps) => {+ const { t } = useTranslation();+ const detailsId = useId();+ const factsId = useId();+ const moreActionsIds = useTooltipTriggerIds();+ const detailsRef = useRef<HTMLDivElement>(null);+ const toggleRef = useRef<HTMLButtonElement>(null);+ // Keyed by workflow, so a new selection (a duplicate, a delete, another place) starts collapsed.+ const [expandedWorkflowId, setExpandedWorkflowId] = useState<string | null>(null);+ const isExpanded = expandedWorkflowId === workflowId;+ // Where expanding scrolled the dialog's columns from; collapsing puts them back, so the toolbar returns to view.+ const scrollBeforeExpandRef = useRef<ReadonlyArray<readonly [HTMLElement, number]>>([]);++ const collapse = useCallback(() => {+ flushSync(() => setExpandedWorkflowId(null));++ for (const [element, scrollTop] of scrollBeforeExpandRef.current) {+ element.scrollTop = scrollTop;+ }++ scrollBeforeExpandRef.current = [];+ toggleRef.current?.focus({ preventScroll: true });+ }, []);+ const handleToggle = useCallback(() => {+ if (isExpanded) {+ collapse();+ return;+ }++ const scrolled: [HTMLElement, number][] = [];++ for (let element = detailsRef.current?.parentElement; element; element = element.parentElement) {+ scrolled.push([element, element.scrollTop]);+ }++ scrollBeforeExpandRef.current = scrolled;+ flushSync(() => setExpandedWorkflowId(workflowId));+ // Into the details just shown, so Tab walks them before returning to the summary's actions below. The container+ // takes focus, not its scroll region: Chromium only focuses scrollers that overflow, which the compact details+ // may stop doing as they settle.+ const details = detailsRef.current;++ details?.focus();++ // A flow layout scrolls the column: bring the details' top into view rather than leaving them under the summary.+ details?.scrollIntoView({ block: 'start', inline: 'nearest' });+ }, [collapse, isExpanded, workflowId]);+ const handleKeyDown = useCallback(+ (event: ReactKeyboardEvent<HTMLDivElement>) => {+ // Captured: controls inside the details (tooltip triggers) stop Escape from bubbling. Portalled menus and+ // dialogs reach here through React too, so only keys from the sheet's own DOM collapse it.+ if (+ event.key === 'Escape' &&+ isExpanded &&+ event.target instanceof Node &&+ event.currentTarget.contains(event.target) &&+ isRendered(toggleRef.current)+ ) {+ collapse();+ }+ },+ [collapse, isExpanded]+ );++ return (+ <Stack+ ref={ref}+ borderColor="border.subtle"+ borderWidth="1px"+ css={RAIL_CSS}+ data-detail-sheet+ data-expanded={isExpanded ? '' : undefined}+ flexShrink={0}+ gap="0"+ minH="0"+ rounded="md"+ w={DETAIL_RAIL_WIDTH}+ onKeyDownCapture={handleKeyDown}+ {...railProps}+ >+ <Stack+ ref={detailsRef}+ css={DETAILS_CSS}+ data-detail-sheet-details+ aria-label={name}+ data-expanded={isExpanded ? '' : undefined}+ flex="1"+ gap="0"+ id={detailsId}+ role="group"+ tabIndex={-1}+ minH="0"+ minW="0"+ >+ {stepper ? (+ <Box+ borderBottomWidth="1px"+ borderColor="border.subtle"+ css={WORKFLOW_DETAIL_WIDE_ONLY_CSS}+ data-detail-rail-stepper=""+ flexShrink={0}+ px="2.5"+ py="2.5"+ >+ <WorkflowPreviewStepper {...stepper} />+ </Box>+ ) : null}+ {children}+ </Stack>+ <Box css={SUMMARY_CSS} data-detail-sheet-summary minW="0">+ <HStack gap="2.5" minW="0">+ <WorkflowSummaryThumbnail src={thumbnailSrc} workflowDocument={workflowDocument} />+ <Stack flex="1" gap="0.5" minW="0">+ {/* Expanded, the summary heads the details, so the name reads in full. */}+ <Text fontSize="md" fontWeight="600" minW="0" overflowWrap="anywhere" truncate={!isExpanded}>+ {name}+ </Text>+ {facts ? (+ // One line keeps the summary short enough to stay pinned in a 320px-tall window; the details list+ // every fact.+ <Text color="fg.muted" fontSize="xs" id={factsId} minW="0" truncate>+ {facts}+ </Text>+ ) : null}+ </Stack>+ {stepper ? (+ <Box data-detail-sheet-stepper="">+ <WorkflowPreviewStepper {...stepper} />+ </Box>+ ) : null}+ <Button+ aria-describedby={isOpenDisabled && facts ? factsId : undefined}+ data-detail-sheet-open+ disabled={isOpenDisabled}+ flexShrink={0}+ size="sm"+ onClick={onOpen}+ >+ {openLabel}+ </Button>+ <Menu.Root+ ids={moreActionsIds}+ positioning={menuPositioning}+ onRequestDismiss={keepMenuOpenWhenSiblingMenuCloses}+ >+ {/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, the+ menu never takes focus and the first pointer move onto it closes it. */}+ <Menu.Trigger asChild>+ <Tooltip content={t('workflowLibrary.moreActions')} ids={moreActionsIds}>+ <IconButton aria-label={t('workflowLibrary.moreActions')} flexShrink={0} size="sm" variant="outline">+ <EllipsisIcon />+ </IconButton>+ </Tooltip>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="min(13rem, var(--available-width))" maxW="var(--available-width)">+ {actions}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </HStack>+ <Button+ ref={toggleRef}+ alignSelf="flex-start"+ aria-controls={detailsId}+ aria-expanded={isExpanded}+ data-detail-sheet-toggle+ gap="1"+ size="xs"+ variant="plain"+ onClick={handleToggle}+ >+ {isExpanded ? <ChevronDownIcon /> : <ChevronUpIcon />}+ {isExpanded ? t('workflowLibrary.hideDetails') : t('workflowLibrary.detailsAndRequirements')}+ </Button>+ </Box>+ </Stack>+ );+};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 98c02f1dd2..a3679b061b 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@@ -11,15 +11,19 @@ import { setWorkflowLibraryTab } from '@features/workflow/ui/workflowUiStore';import { createProjectGraph } from '@features/workflow/utility';import { accountLifecycle } from '@platform/state/accountLifecycle';import { ApiError } from '@platform/transport/http';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act, StrictMode, Profiler, type ComponentProps } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';import { page, userEvent } from 'vitest/browser';import type * as DetailModule from './WorkflowLibraryDetailPanel';+import type * as GridModule from './WorkflowLibraryGrid';+import type * as GridLayoutModule from './workflowLibraryGridLayout';import { WorkflowLibraryDialog } from './WorkflowLibraryDialog';+import { getWorkflowLibraryGridBounds } from './workflowLibraryGridLayout';const transport = vi.hoisted(() => ({list: vi.fn<(params: ListWorkflowsParams) => Promise<WorkflowLibraryPage>>(),@@ -34,13 +38,16 @@ vi.mock('@features/workflow/data/api', async (original) => ({getWorkflowTagCounts: () => Promise.resolve({ fixture1000: 1000 }),getAllWorkflowTags: () => Promise.resolve(['fixture1000']),}));-const commits = vi.hoisted(() => ({ shell: 0, toolbar: 0, detail: 0 }));+const commits = vi.hoisted(() => ({ shell: 0, toolbar: 0, detail: 0, grid: 0, gridRenders: 0 }));const recordToolbarCommit = () => {commits.toolbar += 1;};const recordDetailCommit = () => {commits.detail += 1;};+const recordGridCommit = () => {+ commits.grid += 1;+};vi.mock('@features/workflow/data/libraryBrowseStore', async (original) => {const actual = await original<typeof browse>();return {@@ -65,6 +72,28 @@ vi.mock('@platform/ui/Dialog', async (original) => {},};});+// The grid lays out its columns once per render of its own; counting that call counts its renders.+vi.mock('./workflowLibraryGridLayout', async (original) => {+ const actual = await original<typeof GridLayoutModule>();+ return {+ ...actual,+ getWorkflowLibraryGridColumns: (...args: Parameters<typeof actual.getWorkflowLibraryGridColumns>) => {+ commits.gridRenders += 1;+ return actual.getWorkflowLibraryGridColumns(...args);+ },+ };+});+vi.mock('./WorkflowLibraryGrid', async (original) => {+ const actual = await original<typeof GridModule>();+ return {+ ...actual,+ WorkflowLibraryGrid: (props: ComponentProps<typeof actual.WorkflowLibraryGrid>) => (+ <Profiler id="grid" onRender={recordGridCommit}>+ <actual.WorkflowLibraryGrid {...props} />+ </Profiler>+ ),+ };+});vi.mock('./WorkflowLibraryDetailPanel', async (original) => {const actual = await original<typeof DetailModule>();return {@@ -107,12 +136,9 @@ vi.mock('@features/identity', async (original) => ({}));vi.mock('react-i18next', () => ({useTranslation: () => ({- t: (key: string, values?: { count?: number; source?: string }) =>- key === 'workflowLibrary.nodeCount'- ? `${values?.count} nodes`- : key === 'graphPreview.compiledFrom'- ? `Compiled from ${values?.source}`- : key,+ i18n: { language: 'en', resolvedLanguage: 'en' },+ t: (key: string, values?: { count?: number }) =>+ key === 'workflowLibrary.nodeCount' ? `${values?.count} nodes` : key,}),}));@@ -128,13 +154,34 @@ const project = {isWorkflowRunning: false,};const port = <T,>(snapshot: T) => ({ getSnapshot: () => snapshot, subscribe: () => () => {} });+const PREFERENCES = {+ themeId: 'classic',+ workflowLibraryCardSize: 'small',+ workflowLibraryLayout: 'grid',+ workflowLibrarySort: 'updated',+ workflowLibrarySortDirection: 'desc',+ workflowLibraryThumbnailFit: 'cover',+} as WorkflowPreferences;+/** The layout each test opens the library in; set before `open`. */+let layout: WorkflowPreferences['workflowLibraryLayout'] = 'grid';+const LIST_PREFERENCES: WorkflowPreferences = { ...PREFERENCES, workflowLibraryLayout: 'list' };+const preferenceListeners = new Set<() => void>();+/** Switches the layout of an open library, as the view menu does through the account's preferences. */+const switchLayout = (next: WorkflowPreferences['workflowLibraryLayout']) => {+ layout = next;+ for (const listener of preferenceListeners) {+ listener();+ }+};const adapter = {project: port(project),- preferences: port({- themeId: 'classic',- workflowLibrarySort: 'updated',- workflowLibraryThumbnailFit: 'cover',- } as WorkflowPreferences),+ preferences: {+ getSnapshot: () => (layout === 'list' ? LIST_PREFERENCES : PREFERENCES),+ subscribe: (listener: () => void) => {+ preferenceListeners.add(listener);+ return () => preferenceListeners.delete(listener);+ },+ },commands: {},getProjectGraph: () => graph,setLibraryPreferences: vi.fn(),@@ -144,13 +191,13 @@ const adapter = {const galleryHost = { galleryValues: {}, notifications: { add: vi.fn(), reportError: vi.fn() }, projectName: '' };const previewAdapter = {openDocumentInNewProject: vi.fn(),- getRoute: () => null,- invoke: () => Promise.resolve(false),focusSource: vi.fn(),openWorkflowEditor: vi.fn(),};(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+// The project rail reads linked templates through Query; nothing here links one.+const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });let root: Root;let host: HTMLDivElement;let count = 1000;@@ -172,9 +219,25 @@ const list = ({ page, perPage = 20 }: ListWorkflowsParams) =>),});const card = (index: number) => document.querySelector<HTMLElement>(`[data-workflow-card="wf-${index}"]`);+const listRow = (index: number) =>+ document.getElementById(`workflow-library-card-wf-${index}`)?.closest<HTMLElement>('[data-list-row]') ?? null;+/** A windowed list row by server position, whether its page is resident or not. */+const positionRow = (index: number) =>+ document.querySelector<HTMLElement>(`[data-workflow-library-list] [data-list-row="position:${index}"]`);+const listViewport = () => document.querySelector<HTMLElement>('[data-workflow-library-list] [data-list-viewport]');+/** A rail tag's checkbox row; its label, not the hidden input, takes the pointer. */+const tagCheckbox = (tag: string) => document.querySelector<HTMLElement>(`[data-library-tag="${tag}"]`)!;const viewport = () =>card(0)?.closest<HTMLElement>('[data-scope="scroll-area"][data-part="viewport"]') ??document.querySelector<HTMLElement>('[data-part="viewport"][aria-label="workflowLibrary.title"]');+/** The grid's measured column count and row pitch, from its first mounted row. */+const gridGeometry = (scroll: HTMLElement) => {+ const row = scroll.querySelector<HTMLElement>('[data-index]')!;+ return {+ columns: row.querySelectorAll('[data-workflow-card]').length,+ rowHeight: row.getBoundingClientRect().height,+ };+};const waitFor = (assert: () => void) =>act(async () => {await vi.waitFor(assert, { timeout: 5000 });@@ -185,23 +248,26 @@ const open = async () => {await Promise.resolve();root.render(<StrictMode>- <ChakraProvider value={system}>- <WorkflowUiProvider adapter={adapter}>- <GalleryHostProvider host={galleryHost}>- <WorkflowGraphPreviewProvider adapter={previewAdapter}>- <WorkflowLibraryDialog isOpen onOpenChange={vi.fn()} />- </WorkflowGraphPreviewProvider>- </GalleryHostProvider>- </WorkflowUiProvider>- </ChakraProvider>+ <QueryClientProvider client={queryClient}>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <GalleryHostProvider host={galleryHost}>+ <WorkflowGraphPreviewProvider adapter={previewAdapter}>+ <WorkflowLibraryDialog isOpen onOpenChange={vi.fn()} />+ </WorkflowGraphPreviewProvider>+ </GalleryHostProvider>+ </WorkflowUiProvider>+ </ChakraProvider>+ </QueryClientProvider></StrictMode>);});- await waitFor(() => expect(card(0)).not.toBeNull());+ await waitFor(() => expect(card(0) ?? listRow(0)).not.toBeNull());};beforeEach(async () => {accountLifecycle.invalidate();count = 1000;+ layout = 'grid';transport.list.mockReset().mockImplementation(list);transport.delete.mockReset().mockResolvedValue(undefined);transport.record.mockReset().mockImplementation((id: string) =>@@ -220,6 +286,7 @@ beforeEach(async () => {root = createRoot(host);});afterEach(async () => {+ preferenceListeners.clear();await act(() => root.unmount());host.remove();accountLifecycle.invalidate();@@ -227,8 +294,11 @@ afterEach(async () => {it('shows middle-range failure and successful Retry inside the viewport with bounded cards', async () => {await open();+ // The middle stays offline until Retry itself is pressed: a range read the grid repeats on its own in between (a+ // loaded runner re-measures late) must keep failing, or the notice could clear before the click lands.+ let isMiddleOffline = true;transport.list.mockImplementation((params: ListWorkflowsParams) => {- if (params.page >= 20) {+ if (isMiddleOffline && params.page >= 20) {return Promise.reject(new Error('middle offline'));}return list(params);@@ -244,7 +314,13 @@ it('shows middle-range failure and successful Retry inside the viewport with bouconst box = scroll.getBoundingClientRect();expect(rect.top).toBeGreaterThanOrEqual(box.top);expect(rect.bottom).toBeLessThanOrEqual(box.bottom);- transport.list.mockImplementation(list);+ retry.addEventListener(+ 'click',+ () => {+ isMiddleOffline = false;+ },+ { capture: true }+ );await act(() => userEvent.click(retry));await waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull());expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBeGreaterThan(300);@@ -278,8 +354,9 @@ it.each(['coalesced', 'superseded', 'canceled intent', 'wheel intent'])(});// Scroll to the last resident row, then focus its last menu control.const scroll = viewport()!;+ const { columns, rowHeight } = gridGeometry(scroll);await act(() => {- scroll.scrollTop = 19 * 200;+ scroll.scrollTop = Math.floor(59 / columns) * rowHeight;scroll.dispatchEvent(new Event('scroll'));});await waitFor(() => expect(document.querySelector('[data-workflow-card-menu="wf-59"]')).not.toBeNull());@@ -323,13 +400,15 @@ it.each(['coalesced', 'superseded', 'canceled intent', 'wheel intent'])(const detail = () => document.querySelector<HTMLElement>('[data-workflow-detail="wf-0"]')!;const previewButton = () =>Array.from(detail().querySelectorAll('button')).find(- (button) => button.textContent === 'workflowLibrary.previewGraph'+ (button) => button.textContent === 'workflowLibrary.preview.action')!;+/** The rail counts nodes once the selected document has been read. */+const isDocumentReady = () => /\d+ nodes/.test(detail().textContent ?? '');it('uses the newer selected metadata and document when the resident list arrives later', async () => {count = 1;await open();- await waitFor(() => expect(previewButton().disabled).toBe(false));+ await waitFor(() => expect(isDocumentReady()).toBe(true));let release!: () => void;const gate = new Promise<void>((resolve) => {release = resolve;@@ -364,22 +443,23 @@ it('uses the newer selected metadata and document when the resident list arrivesexpect(card(0)?.textContent).toContain('Older resident refresh');expect(detail().textContent).toContain('Fresh selection');expect(detail().textContent).toContain('Fresh description');- expect(previewButton().disabled).toBe(false);+ expect(isDocumentReady()).toBe(true);});+ // The preview draws the selected copy's document, not the older resident one.await act(() => userEvent.click(previewButton()));- await waitFor(() => expect(document.body.textContent).toContain('Compiled from Fresh selection'));- await waitFor(() => expect(document.querySelectorAll('.react-flow__node')).toHaveLength(2));- await act(() => userEvent.click(page.getByRole('tab', { name: 'common.json', exact: true })));- await waitFor(() => {- expect(document.body.textContent).toContain('fresh-node-0');- expect(document.body.textContent).toContain('fresh-node-1');- });+ const stage = () => document.querySelector<HTMLElement>('[data-preview-stage]');+ await waitFor(() =>+ expect([...stage()!.querySelectorAll<HTMLElement>('.react-flow__node')].map((node) => node.dataset.id)).toEqual([+ 'fresh-node-0',+ 'fresh-node-1',+ ])+ );});it('shows the selected transient error over equal-revision resident pending state and recovers', async () => {count = 1;await open();- await waitFor(() => expect(previewButton().disabled).toBe(false));+ await waitFor(() => expect(isDocumentReady()).toBe(true));transport.list.mockImplementation(async (params: ListWorkflowsParams) => {const result = await list(params);return { ...result, items: result.items.map((entry) => ({ ...entry, name: 'Refreshed resident' })) };@@ -391,7 +471,7 @@ it('shows the selected transient error over equal-revision resident pending statexpect(card(0)?.textContent).toContain('Refreshed resident');expect(detail().textContent).toContain('selected record offline');expect(detail().textContent).toContain('Workflow 0');- expect(previewButton().disabled).toBe(true);+ expect(isDocumentReady()).toBe(false);});transport.record.mockResolvedValue({...item(0),@@ -405,7 +485,7 @@ it('shows the selected transient error over equal-revision resident pending statawait waitFor(() => {expect(detail().textContent).not.toContain('selected record offline');expect(detail().textContent).toContain('Workflow 0');- expect(previewButton().disabled).toBe(false);+ expect(isDocumentReady()).toBe(true);});});@@ -441,7 +521,7 @@ const scrollTo = async (scroll: HTMLElement, top: number) => {);};it.each([- [1280, 800, 3],+ [1280, 800, 4],[512, 800, 2],[320, 400, 1],])(@@ -463,14 +543,35 @@ it.each([expect(Number(before.id?.slice(3))).toBeGreaterThan(400);expect(before.offset).toBeGreaterThan(10);const requests = transport.list.mock.calls.length;- await act(() => userEvent.click(page.getByRole('button', { name: 'fixture1000', exact: false })));- await settle();+ await act(() => userEvent.click(tagCheckbox('fixture1000')));+ // Conditions, not elapsed time: under a loaded runner the tag view's listing and the resize's re-layout can take+ // longer than any fixed wait.+ await waitFor(() => {+ expect(browse.getWorkflowLibraryBrowseSnapshot()).toMatchObject({ status: 'loaded', startIndex: 0 });+ expect(browse.getWorkflowLibraryBrowseSnapshot().filter.tags).toEqual(['fixture1000']);+ expect(card(0)).not.toBeNull();+ });await page.viewport(width!, height!);+ await waitFor(() => expect(gridGeometry(viewport()!).columns).toBe(columns));await settle();- const all = page.getByRole('button', { name: 'workflowLibrary.allTag', exact: false });+ // The wide rail clears with its Clear; the narrow layout (under a 56rem dialog) clears inside the Tags popover.+ const isNarrow = width! < 960;const modal = document.querySelector<HTMLElement>('[role=dialog]')!;const outerOffset = modal.scrollTop;- await act(() => userEvent.click(all));+ if (isNarrow) {+ const trigger = document.querySelector<HTMLElement>('[data-workflow-library-tags-trigger]')!;+ await act(() => userEvent.click(trigger));+ await waitFor(() => expect(document.querySelector('[data-workflow-library-tag-popover]')).not.toBeNull());+ const popover = document.querySelector<HTMLElement>('[data-workflow-library-tag-popover]')!;+ await act(() =>+ userEvent.click(+ [...popover.querySelectorAll('button')].find((button) => button.textContent === 'workflowLibrary.clearTags')!+ )+ );+ await act(() => userEvent.keyboard('{Escape}'));+ } else {+ await act(() => userEvent.click(page.getByRole('button', { name: 'workflowLibrary.clearTags', exact: true })));+ }await settle();const restored = viewport()!;const expectedIndex = Math.floor(Number(before.id?.slice(3)) / columns!) * columns!;@@ -480,7 +581,12 @@ it.each([if (width === 1280) {expect(Math.abs(firstVisibleRow(restored).offset - before.offset)).toBeLessThan(3);}- expect(document.activeElement).toBe(all.element());+ // Clear leaves with the last checked tag and hands focus to the first tag; closing the popover, to the Tags button.+ expect(document.activeElement).toBe(+ isNarrow+ ? document.querySelector('[data-workflow-library-tags-trigger]')+ : tagCheckbox('fixture1000').querySelector('input')+ );expect(modal.scrollTop).toBe(outerOffset);expect(document.querySelectorAll('[data-workflow-card]').length).toBeLessThan(48);expect(browse.getWorkflowLibraryBrowseRetention().metadataEntries).toBeLessThanOrEqual(540);@@ -498,15 +604,20 @@ it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return',async (scenario) => {await open();const scroll = viewport()!;+ const { columns } = gridGeometry(scroll);+ // The return window starts at the anchor's overscan rows.+ const overscan = getWorkflowLibraryGridBounds(columns).overscanRows * columns;await scrollTo(scroll, 39600);await settle();const before = firstVisibleRow(scroll);const anchorIndex = Number(before.id?.slice(3));+ // Reads of the unfiltered view; how many pages the tag view's viewport needs depends on its column count.+ const returnCalls = () => transport.list.mock.calls.filter(([params]) => !params.tags?.length);// A real position read may finish just as a user leaves. Retained metadata and the last visible anchor// are independent; returning must wait for the anchor's window instead of restoring placeholder geometry.await act(async () => {await browse.loadWorkflowLibraryRange(700, 705);- browse.setWorkflowLibraryBrowseFilter({ tag: 'fixture1000' });+ browse.setWorkflowLibraryBrowseFilter({ tags: ['fixture1000'] });});await waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));let release!: () => void;@@ -524,8 +635,8 @@ it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return',return list(params);});transport.list.mockClear();- await act(() => browse.setWorkflowLibraryBrowseFilter({ tag: null }));- await waitFor(() => expect(transport.list.mock.calls.length).toBe(3));+ await act(() => browse.setWorkflowLibraryBrowseFilter({ tags: [] }));+ await waitFor(() => expect(returnCalls().length).toBe(3));expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(700);const returned = viewport()!;expect(returned.scrollTop).toBe(0);@@ -545,10 +656,10 @@ it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return',await scrollTo(returned, 0);canceledOffset = returned.scrollTop;} else if (scenario === 'filter' || scenario === 'rapid return') {- await act(() => browse.setWorkflowLibraryBrowseFilter({ tag: 'fixture1000' }));+ await act(() => browse.setWorkflowLibraryBrowseFilter({ tags: ['fixture1000'] }));if (scenario === 'rapid return') {- await act(() => browse.setWorkflowLibraryBrowseFilter({ tag: null }));- await waitFor(() => expect(transport.list.mock.calls.length).toBe(6));+ await act(() => browse.setWorkflowLibraryBrowseFilter({ tags: [] }));+ await waitFor(() => expect(returnCalls().length).toBe(6));}} else if (scenario === 'account') {await act(() => accountLifecycle.invalidate());@@ -564,7 +675,7 @@ it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return',await waitFor(() =>expect(document.querySelector('[role=alert]')?.textContent).toContain('return window offline'));- expect(transport.list.mock.calls).toHaveLength(3);+ expect(returnCalls()).toHaveLength(3);failReturn = false;await act(() => userEvent.click(document.querySelector<HTMLElement>('[role=alert] button')!));await settle();@@ -574,11 +685,11 @@ it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return',await waitFor(() => expect(firstVisibleRow(active).id).toBe(before.id));expect(Math.abs(firstVisibleRow(active).offset - before.offset)).toBeLessThan(3);expect(document.activeElement).toBe(focus);- const pages = transport.list.mock.calls.map(([params]) => params.page);+ const pages = returnCalls().map(([params]) => params.page);expect(scenario === 'rapid return' ? pages.slice(3) : pages).toEqual([- Math.floor((anchorIndex - 6) / 20),- Math.floor((anchorIndex - 6) / 20) + 1,- Math.floor((anchorIndex - 6) / 20) + 2,+ Math.floor((anchorIndex - overscan) / 20),+ Math.floor((anchorIndex - overscan) / 20) + 1,+ Math.floor((anchorIndex - overscan) / 20) + 2,]);} else if (scenario === 'retry') {expect(browse.getWorkflowLibraryBrowseSnapshot().error).toBeNull();@@ -591,7 +702,7 @@ it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return',expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(0);expect(firstVisibleRow(returned).id).toBe('wf-0');} else if (scenario === 'filter') {- expect(browse.getWorkflowLibraryBrowseSnapshot().filter.tag).toBe('fixture1000');+ expect(browse.getWorkflowLibraryBrowseSnapshot().filter.tags).toEqual(['fixture1000']);expect(firstVisibleRow(viewport()!).id).toBe('wf-0');expect(browse.getWorkflowLibraryBrowseSnapshot().startIndex).toBe(0);} else if (scenario === 'account') {@@ -601,10 +712,12 @@ it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return',expect(returned.isConnected).toBe(false);}const canceled = !['finish', 'unmount'].includes(scenario);- expect(transport.list.mock.calls.slice(0, 3).every(([params]) => params.signal?.aborted)).toBe(canceled);- expect(transport.list.mock.calls).toHaveLength(- ['wheel', 'pointer', 'key', 'rapid return', 'retry'].includes(scenario) ? 6 : 3- );+ expect(+ returnCalls()+ .slice(0, 3)+ .every(([params]) => params.signal?.aborted)+ ).toBe(canceled);+ expect(returnCalls()).toHaveLength(['wheel', 'pointer', 'key', 'rapid return', 'retry'].includes(scenario) ? 6 : 3);if (scenario === 'account' || scenario === 'unmount') {expect(browse.getWorkflowLibraryBrowseRetention().parsedDocuments).toBe(0);}@@ -614,20 +727,30 @@ it.each(['finish', 'retry', 'wheel', 'pointer', 'key', 'filter', 'rapid return',15000);-it('records fractional scroll without rendering the shell or committing toolbar and detail', async () => {+it('records fractional scroll without rendering the shell, the grid, the toolbar or the detail', async () => {await open();await settle();const scroll = viewport()!;- await scrollTo(scroll, 20);+ // Neither edge of the viewport may cross a row boundary over the 5px move, or the visible range changes.+ const { rowHeight } = gridGeometry(scroll);+ const inRow = (offset: number) => offset % rowHeight > 2 && offset % rowHeight < rowHeight - 8;+ const start = Array.from({ length: Math.floor(rowHeight) }, (_, offset) => offset).find(+ (offset) => inRow(offset) && inRow(offset + scroll.clientHeight)+ )!;+ await scrollTo(scroll, start);await settle();const before = browse.getWorkflowLibraryBrowseSnapshot();const first = firstVisibleRow(scroll).id;expect(commits.shell).toBeGreaterThan(0);expect(commits.toolbar).toBeGreaterThan(0);expect(commits.detail).toBeGreaterThan(0);- commits.shell = commits.toolbar = commits.detail = 0;- await scrollTo(scroll, 25);+ commits.shell = commits.toolbar = commits.detail = commits.grid = commits.gridRenders = 0;+ await scrollTo(scroll, start + 5);await settle();+ // Scrolling within one row, start to settle, never renders the grid: it follows rows, not the offset. The one+ // commit its Profiler may still record is the scroll area's own scrolling state, below the grid's render.+ expect(commits.gridRenders).toBe(0);+ expect(commits.grid).toBeLessThanOrEqual(1);const after = browse.getWorkflowLibraryBrowseSnapshot();expect(firstVisibleRow(scroll).id).toBe(first);expect(after.entries).toBe(before.entries);@@ -643,8 +766,7 @@ it('fills a tall viewport crossing four server pages and settles without refetchawait open();await settle();const scroll = viewport()!;- const rows = Array.from(scroll.querySelectorAll<HTMLElement>('[data-index]'));- const rowHeight = rows[0]!.getBoundingClientRect().height;+ const { columns, rowHeight } = gridGeometry(scroll);await scrollTo(scroll, rowHeight * 6.95);await settle();const bounds = scroll.getBoundingClientRect();@@ -653,9 +775,9 @@ it('fills a tall viewport crossing four server pages and settles without refetchreturn rect.bottom > bounds.top && rect.top < bounds.bottom;});const indexes = renderedRows.map((row) => Number(row.dataset.index));- expect((Math.max(...indexes) - Math.min(...indexes) + 1) * 3).toBeGreaterThan(41);+ expect((Math.max(...indexes) - Math.min(...indexes) + 1) * columns).toBeGreaterThan(41);for (const row of renderedRows) {- expect(row.querySelectorAll('[data-workflow-card]')).toHaveLength(3);+ expect(row.querySelectorAll('[data-workflow-card]')).toHaveLength(columns);expect(row.querySelector('[aria-busy=true]')).toBeNull();}await waitFor(() => expect(browse.getWorkflowLibraryBrowseRetention().activeReads).toBe(0));@@ -717,6 +839,35 @@ it('releases a confirmed deleted focused card while preserving valid focus outsiexpect(document.querySelector('[data-workflow-detail="wf-0"]')).toBeNull();});+it('keeps the selected card ready after its page leaves the window and returns', async () => {+ await open();+ const scroll = viewport()!;+ const readiness = () => card(0)?.querySelector('[data-workflow-readiness]');+ // The first card is the rail's selection; its card and the rail both show it enriched.+ await waitFor(() => expect(readiness()).not.toBeNull());+ expect(document.querySelector('[data-workflow-detail="wf-0"]')).not.toBeNull();++ await scrollTo(scroll, 39600);+ await settle();+ // Page 0 left the resident window; the selected copy alone keeps the workflow.+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.some((entry) => entry.item.workflow_id === 'wf-0')).toBe(+ false+ );+ const reads = transport.record.mock.calls.filter(([id]) => id === 'wf-0').length;++ await scrollTo(scroll, 0);+ await waitFor(() => expect(card(0)).not.toBeNull());+ await settle();+ const requests = transport.list.mock.calls.length;+ await settle();++ // The returning list copy takes the selected enrichment: no placeholder, no second read, no request loop.+ expect(readiness()).not.toBeNull();+ expect(card(0)?.querySelector('[data-enrichment-placeholder]')).toBeNull();+ expect(transport.record.mock.calls.filter(([id]) => id === 'wf-0')).toHaveLength(reads);+ expect(transport.list.mock.calls).toHaveLength(requests);+});+it('returns detail selection to the first resident entry when the previous choice is absent', async () => {await open();const scroll = viewport()!;@@ -724,12 +875,246 @@ it('returns detail selection to the first resident entry when the previous choicawait settle();const resident = browse.getWorkflowLibraryBrowseSnapshot().entries[0]!.item.workflow_id;const before = firstVisibleRow(scroll);- await act(() => userEvent.click(page.getByRole('button', { name: 'fixture1000', exact: false })));+ await act(() => userEvent.click(tagCheckbox('fixture1000')));await settle();const requests = transport.list.mock.calls.length;- await act(() => userEvent.click(page.getByRole('button', { name: 'workflowLibrary.allTag', exact: false })));+ await act(() => userEvent.click(page.getByRole('button', { name: 'workflowLibrary.clearTags', exact: true })));await settle();expect(document.querySelector(`[data-workflow-detail="${resident}"]`)).not.toBeNull();expect(firstVisibleRow(viewport()!).id).toBe(before.id);expect(transport.list.mock.calls).toHaveLength(requests);});++// Chromium may hold back a resize report that misses its frame's depth limit until some later rendering update.+it('restores a returning grid whose resize observer never reports', async () => {+ await open();+ const scroll = viewport()!;+ await scrollTo(scroll, 39600);+ await settle();+ const before = firstVisibleRow(scroll);+ await act(() => userEvent.click(tagCheckbox('fixture1000')));+ await settle();+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ disconnect() {}+ observe() {}+ unobserve() {}+ }+ );+ onTestFinished(() => {+ vi.unstubAllGlobals();+ });++ await act(() => userEvent.click(page.getByRole('button', { name: 'workflowLibrary.clearTags', exact: true })));++ await waitFor(() => expect(firstVisibleRow(viewport()!).id).toBe(before.id));+});++describe('list layout', () => {+ /** A comfortable list row's pitch: its 52px item and the 2px gap. */+ const ROW_PX = 54;++ it('lists every server position, loading the window around the rows on screen as it scrolls', async () => {+ layout = 'list';+ await open();+ const scroll = listViewport()!;+ expect(scroll.querySelector('[role="listitem"]')?.getAttribute('aria-setsize')).toBe('1000');++ await scrollTo(scroll, 500 * ROW_PX);+ // Positions past the resident window show as busy placeholders until their pages arrive.+ await waitFor(() => expect(listRow(500)).not.toBeNull());+ // Once the window settles every mounted row, overscan included, is resident.+ await waitFor(() => expect(scroll.querySelector('[data-workflow-list-placeholder]')).toBeNull());+ const snapshot = browse.getWorkflowLibraryBrowseSnapshot();+ expect(snapshot.startIndex).toBeGreaterThan(400);+ expect(snapshot.startIndex).toBeLessThanOrEqual(500);+ expect(snapshot.entries.length).toBeLessThanOrEqual(60);+ expect(transport.list.mock.calls.some(([params]) => params.page === 25)).toBe(true);+ // Enrichment follows the rows on screen.+ await waitFor(() => expect(transport.record.mock.calls.some(([id]) => id === 'wf-501')).toBe(true));+ await waitFor(() => expect(listRow(501)?.querySelector('[data-workflow-readiness]')).not.toBeNull());+ expect(scroll.querySelectorAll('[data-list-row]').length).toBeLessThan(48);+ });++ it('shows placeholders for positions whose page is not resident', async () => {+ layout = 'list';+ await open();+ const scroll = listViewport()!;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ transport.list.mockImplementation(async (params: ListWorkflowsParams) => {+ if (params.page > 0) {+ await gate;+ }+ return list(params);+ });++ await scrollTo(scroll, 300 * ROW_PX);+ await waitFor(() => expect(positionRow(300)?.querySelector('[data-workflow-list-placeholder]')).not.toBeNull());+ const placeholder = positionRow(300)!;+ const button = placeholder.querySelector<HTMLElement>('[data-list-primary]')!;+ // A busy row with its set position and a button that says it is loading, never an unnamed item.+ expect(placeholder.getAttribute('aria-posinset')).toBe('301');+ expect(placeholder.hasAttribute('data-busy')).toBe(true);+ expect(button.getAttribute('aria-disabled')).toBe('true');+ expect(button.getAttribute('aria-label')).toBe('workflowLibrary.loading');++ release();+ await waitFor(() => expect(listRow(300)).not.toBeNull());+ // The same row and button take the entry: nothing remounts under focus.+ expect(positionRow(300)).toBe(placeholder);+ expect(placeholder.querySelector('[data-list-primary]')).toBe(button);+ expect(button.hasAttribute('aria-label')).toBe(false);+ expect(placeholder.querySelector('[data-workflow-list-placeholder]')).toBeNull();+ });++ it('moves focus to the last and first positions with End and Home, keeping it there while their pages load', async () => {+ layout = 'list';+ await open();+ const scroll = listViewport()!;+ const button = (index: number) => positionRow(index)?.querySelector<HTMLElement>('[data-list-primary]') ?? null;+ await act(() => userEvent.click(button(0)!));+ await settle();+ const pageReads = (from: number) => transport.list.mock.calls.slice(from).map(([params]) => params.page);++ let before = transport.list.mock.calls.length;+ await act(() => userEvent.keyboard('{End}'));+ await waitFor(() => expect(listRow(999)).not.toBeNull());+ await settle();+ // The row focused before its page arrived is the row that holds it: focus and scroll stay at the end.+ expect(document.activeElement).toBe(button(999));+ expect(document.activeElement).toBe(listRow(999)?.querySelector('[data-list-primary]'));+ expect(scroll.scrollTop).toBeGreaterThan(990 * ROW_PX - scroll.clientHeight);+ expect(pageReads(before)).not.toContain(0);+ expect(new Set(pageReads(before)).size).toBeLessThanOrEqual(3);++ before = transport.list.mock.calls.length;+ await act(() => userEvent.keyboard('{Home}'));+ await waitFor(() => expect(listRow(0)).not.toBeNull());+ await settle();+ expect(document.activeElement).toBe(button(0));+ expect(scroll.scrollTop).toBe(0);+ expect(pageReads(before)).not.toContain(49);+ });++ it('switches from the grid with the selection evicted and still offers one tab stop, which Tab reaches', async () => {+ await open();+ await act(() => userEvent.click(card(1)!));+ await waitFor(() => expect(document.querySelector('[data-workflow-detail="wf-1"]')).not.toBeNull());+ await scrollTo(viewport()!, 39600);+ await settle();+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.some((entry) => entry.item.workflow_id === 'wf-1')).toBe(+ false+ );++ await act(() => switchLayout('list'));+ await waitFor(() => expect(listViewport()).not.toBeNull());+ await settle();+ const stops = [...document.querySelectorAll<HTMLElement>('[data-workflow-library-list] [tabindex="0"]')];+ expect(stops).toHaveLength(1);++ await act(() => document.querySelector<HTMLElement>('button[aria-label="workflowLibrary.viewOptions"]')!.focus());+ await act(() => userEvent.keyboard('{Tab}'));+ expect(document.activeElement).toBe(stops[0]);+ });++ it('keeps the selected row with its name while its page is evicted, and its facts once it returns', async () => {+ layout = 'list';+ await open();+ const scroll = listViewport()!;+ const primary = () => listRow(1)?.querySelector<HTMLElement>('[data-list-primary]');+ await act(() => userEvent.click(primary()!));+ await waitFor(() => expect(document.querySelector('[data-workflow-detail="wf-1"]')).not.toBeNull());+ expect(primary()?.getAttribute('aria-current')).toBe('true');++ await scrollTo(scroll, 600 * ROW_PX);+ await waitFor(() => expect(listRow(600)).not.toBeNull());+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.some((entry) => entry.item.workflow_id === 'wf-1')).toBe(+ false+ );+ // Focused and selected, it stays mounted with its name, its facts waiting for its page.+ expect(document.activeElement).toBe(primary());+ expect(listRow(1)?.textContent).toContain('Workflow 1');++ await scrollTo(scroll, 0);+ await waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.some((entry) => entry.item.workflow_id === 'wf-1')).toBe(+ true+ )+ );+ await waitFor(() => expect(listRow(1)?.querySelector('[data-workflow-readiness]')).not.toBeNull());+ expect(primary()?.getAttribute('aria-current')).toBe('true');+ expect(document.querySelector('[data-workflow-detail="wf-1"]')).not.toBeNull();+ });++ it('marks no other workflow when the server moves the selection out of the window', async () => {+ layout = 'list';+ await open();+ await act(() => userEvent.click(listRow(1)!.querySelector<HTMLElement>('[data-list-primary]')!));+ await waitFor(() => expect(document.querySelector('[data-workflow-detail="wf-1"]')).not.toBeNull());+ // A rename under name order: wf-1 moves to position 900 and wf-900 takes position 1.+ const swap = (index: number) => (index === 1 ? 900 : index === 900 ? 1 : index);+ transport.list.mockImplementation(({ page, perPage = 20 }: ListWorkflowsParams) =>+ Promise.resolve({+ items: Array.from({ length: Math.min(perPage, Math.max(0, count - page * perPage)) }, (_, offset) =>+ item(swap(page * perPage + offset))+ ),+ page,+ pages: Math.ceil(count / perPage),+ total: count,+ })+ );++ await act(() => invalidateWorkflowLibraryCache());+ await waitFor(() => expect(positionRow(1)?.textContent).toContain('Workflow 900'));+ await settle();++ expect(positionRow(1)?.querySelector('[aria-current]')).toBeNull();+ expect(document.querySelectorAll('[data-workflow-library-list] [aria-current="true"]')).toHaveLength(0);+ expect(document.querySelector('[data-workflow-detail="wf-1"]')).not.toBeNull();+ // The list still has its one roving tab stop.+ expect(document.querySelectorAll('[data-workflow-library-list] [data-list-primary][tabindex="0"]')).toHaveLength(1);+ });++ it('scrolls within a row without rendering the shell, the toolbar or the detail', async () => {+ layout = 'list';+ await open();+ await settle();+ const scroll = listViewport()!;+ // Neither edge of the viewport may cross a row boundary over the 5px move, or the visible range changes.+ const inRow = (offset: number) => offset % ROW_PX > 2 && offset % ROW_PX < ROW_PX - 8;+ const start = Array.from({ length: ROW_PX }, (_, offset) => 20 * ROW_PX + offset).find(+ (offset) => inRow(offset) && inRow(offset + scroll.clientHeight)+ )!;+ await scrollTo(scroll, start);+ await settle();+ const before = browse.getWorkflowLibraryBrowseSnapshot();+ commits.shell = commits.toolbar = commits.detail = 0;+ await scrollTo(scroll, start + 5);+ await settle();++ expect(browse.getWorkflowLibraryBrowseSnapshot()).toBe(before);+ expect(commits.shell).toBe(0);+ expect(commits.toolbar).toBe(0);+ expect(commits.detail).toBe(0);+ });++ it('returns to its position after another filter, as the grid does', async () => {+ layout = 'list';+ await open();+ const scroll = listViewport()!;+ await scrollTo(scroll, 420 * ROW_PX + 20);+ await waitFor(() => expect(listRow(420)).not.toBeNull());+ await settle();++ await act(() => userEvent.click(tagCheckbox('fixture1000')));+ await waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().filter.tags).toEqual(['fixture1000']));+ await act(() => userEvent.click(tagCheckbox('fixture1000')));+ await waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().filter.tags).toEqual([]));+ await waitFor(() => expect(listRow(420)).not.toBeNull());+ expect(Math.abs(listViewport()!.scrollTop - (420 * ROW_PX + 20))).toBeLessThan(ROW_PX);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowsePanes.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowsePanes.tsxnew file mode 100644index 0000000000..94c8d459aa--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryBrowsePanes.tsx@@ -0,0 +1,407 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';+import type { WorkflowLibraryBrowseSnapshot, WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibraryListItem } from '@features/workflow/queries';+import type { WorkflowPreviewView } from '@features/workflow/ui/graph-preview/WorkflowPreviewStage';+import type { WorkflowLibraryLayout } from '@features/workflow/ui/WorkflowUiContext';++import { HStack, type SystemStyleObject, Text } from '@chakra-ui/react';+import { useAuthSession } from '@features/identity';+import {+ getWorkflowLibraryBrowseSnapshot,+ loadWorkflowLibraryRange,+ selectWorkflowLibraryEntry,+ setWorkflowLibrarySelectedDemand,+ useWorkflowLibraryBrowseSelector,+} from '@features/workflow/data/libraryBrowseStore';+import { workflowUiStore, type WorkflowLibraryTab } from '@features/workflow/ui/workflowUiStore';+import { useMountEffect } from '@platform/react/useMountEffect';+import { memo, type RefObject, useCallback, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import type { WorkflowCardContextMenuHandler, WorkflowCardMenuAnchor } from './WorkflowLibraryCard';+import type { WorkflowContextMenuTarget } from './WorkflowLibraryContextMenu';+import type { WorkflowLibraryListTrailingField } from './WorkflowLibraryList';+import type { WorkflowLibraryPreviewStageHandle, WorkflowLibraryPreviewStatus } from './WorkflowLibraryPreviewStage';++import { useWorkflowLibraryDuplicateGuard } from './useWorkflowLibraryEntryActions';+import { WORKFLOW_DETAIL_PANES_CSS } from './WorkflowDetailSheet';+import { WorkflowLibraryContextMenu } from './WorkflowLibraryContextMenu';+import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';+import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';+import { WorkflowLibraryList } from './WorkflowLibraryList';+import { WorkflowLibraryPreviewStage } from './WorkflowLibraryPreviewStage';+import { WORKFLOW_LIBRARY_WIDE } from './WorkflowLibraryRail';+import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';++/**+ * The template places' result line, grid or list, detail rail and card actions menu. They alone subscribe to the+ * listing's entries, so range loads and enrichment results re-render this subtree, never the dialog shell, its rail or+ * its toolbar.+ */++/**+ * The card grid (or the list) and the detail rail, in both views. In the wide layout their box dissolves into the+ * dialog body's grid (see `WorkflowLibraryDialog`): the cards take the centre column under the toolbar, and the detail+ * rail becomes a flush column from under the header to the dialog's bottom edge, separated by a 1px border rather than+ * drawn as a card. The narrow layout keeps the sheet's own grid (`WORKFLOW_DETAIL_PANES_CSS`).+ */+export const WORKFLOW_LIBRARY_PANES_CSS: SystemStyleObject = {+ ...WORKFLOW_DETAIL_PANES_CSS,+ [WORKFLOW_LIBRARY_WIDE]: {+ display: 'contents',+ '& > :first-child': { gridArea: 'panes', mb: '3', minH: '0' },+ // Per side, not the shorthand: `borderWidth: 0` after `borderStartWidth` would reset the start border too.+ '& > :last-child': {+ borderBottomWidth: '0',+ borderEndWidth: '0',+ borderRadius: '0',+ borderStartWidth: '1px',+ borderTopWidth: '0',+ gridArea: 'detail',+ minH: '0',+ },+ },+};++type AuthSession = ReturnType<typeof useAuthSession>;++/**+ * What the account may do to a library entry: only its own templates (on a multi-user server, the ones it owns) are+ * writable, and visibility changes only from My library on a multi-user server.+ */+const getLibraryEntryAccess = (+ entry: WorkflowLibraryEntry | null | undefined,+ session: AuthSession,+ tab: WorkflowLibraryTab+) => {+ const isOwner =+ session.phase === 'ready' &&+ (session.multiuserEnabled ? Boolean(entry?.item.user_id && entry.item.user_id === session.user?.user_id) : true);+ const isWritable = entry?.item.category === 'user' && isOwner;++ return { canChangeVisibility: isWritable && tab === 'user' && session.multiuserEnabled, isReadOnly: !isWritable };+};++/** Flat and shallow-comparable, so place totals, tag counts and scroll anchors do not re-render the panes. */+const selectPanes = (snapshot: WorkflowLibraryBrowseSnapshot) => ({+ viewKey: JSON.stringify(snapshot.filter),+ entries: snapshot.entries,+ startIndex: snapshot.startIndex ?? 0,+ filter: snapshot.filter,+ total: snapshot.total,+ selectedEntry: snapshot.selectedEntry,+ error: snapshot.error,+ status: snapshot.status,+});++export interface WorkflowLibraryResultLineProps {+ /** Matching workflows; null while unknown. */+ count: number | null;+ /** The checked tags as a localized "a or b" list; empty when none. */+ tagsText: string;+}++/**+ * "N workflows · tags" above the cards. Nothing about requirements: on a server-paginated place only the enriched+ * window is known, so any aggregate would change while scrolling.+ */+export const WorkflowLibraryResultLine = memo(function WorkflowLibraryResultLine({+ count,+ tagsText,+}: WorkflowLibraryResultLineProps) {+ const { t } = useTranslation();++ return (+ <Text+ aria-live="polite"+ color="fg.muted"+ data-workflow-library-results+ flexShrink={0}+ fontSize="sm"+ minH="4"+ minW="0"+ truncate+ >+ {count === null+ ? null+ : tagsText+ ? t('workflowLibrary.resultCountWithTags', { count, tags: tagsText })+ : t('workflowLibrary.resultCount', { count })}+ </Text>+ );+});++export interface WorkflowLibraryBrowsePanesProps {+ /** Whether the dialog is open; selected-detail demand runs only then. */+ isOpen: boolean;+ layout: WorkflowLibraryLayout;+ tab: WorkflowLibraryTab;+ /** The date the list's rows show, from the current order. */+ trailingField: WorkflowLibraryListTrailingField;+ tagsText: string;+ emptyMessage: string | undefined;+ /** Where the card actions menu is anchored; null while it is closed. */+ contextMenuAnchor: WorkflowCardMenuAnchor | null;+ /** The workflow the card actions menu was raised for, kept through its close. */+ contextMenuTarget: WorkflowContextMenuTarget | null;+ /** The user's explicit choice; the panes fall back to the selected pin or the first resident entry. */+ selectedWorkflowId: string | null;+ removedWorkflowId: string | null;+ projectWorkflows: readonly ProjectWorkflowEntry[];+ onClose: () => void;+ onContextMenu: WorkflowCardContextMenuHandler;+ onContextMenuClose: () => void;+ /** Receives the deleted workflow, from the rail or a card's menu. */+ onDeleted: (workflowId: string) => void;+ onOpen: (workflowId: string) => void;+ onOpenItem: (item: WorkflowLibraryListItem) => void;+ /** Enters preview mode on a workflow, selecting it; on a given view, else the one last shown. */+ onPreview: (workflowId: string, view?: WorkflowPreviewView) => void;+ onSelect: (workflowId: string) => void;+ preview: WorkflowLibraryPanesPreview;+ /** The stage's handle, through which the dialog's Escape reaches it. */+ previewStageRef: RefObject<WorkflowLibraryPreviewStageHandle | null>;+}++/** Preview mode, which the shell owns: the stage replaces the collection while the detail rail stays. */+export interface WorkflowLibraryPanesPreview {+ isActive: boolean;+ /** The place the stage's back button returns to. */+ placeLabel: string;+ onLeave: (workflowId: string | null) => void;+ view: WorkflowPreviewView;+ onViewChange: (view: WorkflowPreviewView) => void;+}++/** What the stage shows for an entry: its enriched document, or why there is none yet. */+const getLibraryPreviewStatus = (entry: WorkflowLibraryEntry | null): WorkflowLibraryPreviewStatus =>+ entry?.enrichment.status === 'ready'+ ? { document: entry.enrichment.document, kind: 'ready' }+ : entry?.enrichment.status === 'error'+ ? { kind: 'error', message: entry.enrichment.message }+ : { kind: 'pending' };++export const WorkflowLibraryBrowsePanes = memo(function WorkflowLibraryBrowsePanes({+ contextMenuAnchor,+ contextMenuTarget,+ emptyMessage,+ isOpen,+ layout,+ projectWorkflows,+ removedWorkflowId,+ selectedWorkflowId,+ tab,+ tagsText,+ trailingField,+ preview,+ previewStageRef,+ onClose,+ onContextMenu,+ onContextMenuClose,+ onDeleted,+ onOpen,+ onOpenItem,+ onPreview,+ onSelect,+}: WorkflowLibraryBrowsePanesProps) {+ const { entries, error, filter, selectedEntry, startIndex, status, total, viewKey } =+ useWorkflowLibraryBrowseSelector(selectPanes);+ const authSession = useAuthSession();+ const { t } = useTranslation();+ const missingCounts = useWorkflowLibraryMissingCounts(entries);++ // Derive a fallback selection when filtering/deletion removes the selected row.+ const desiredWorkflowId = selectedWorkflowId ?? selectedEntry?.item.workflow_id ?? null;+ const activeWorkflowId =+ selectedEntry?.item.workflow_id === desiredWorkflowId ||+ entries.some((entry) => entry.item.workflow_id === desiredWorkflowId)+ ? desiredWorkflowId+ : (entries[0]?.item.workflow_id ?? null);+ const activeEntry = selectWorkflowLibraryEntry({ entries, selectedEntry }, activeWorkflowId) ?? null;+ const activeAccess = getLibraryEntryAccess(activeEntry, authSession, tab);+ // The menu acts on the card it was raised for, resident or the selected pin; once that leaves, it has nothing to+ // act on and stays closed (the shell clears its anchor).+ const menuEntry = contextMenuTarget+ ? (selectWorkflowLibraryEntry({ entries, selectedEntry }, contextMenuTarget.workflowId) ?? null)+ : null;+ const browseWindow = useMemo(() => ({ startIndex, total, filter }), [startIndex, total, filter]);+ const duplicateGuard = useWorkflowLibraryDuplicateGuard();+ const selectionIntent = useRef(0);+ const selectEntry = useCallback(+ (workflowId: string) => {+ selectionIntent.current += 1;+ onSelect(workflowId);+ },+ [onSelect]+ );+ const handleDuplicated = useCallback(+ (workflowId: string) => {+ // Copies belong to My library; the other places keep their current selection.+ if (tab === 'user') {+ selectEntry(workflowId);+ }+ },+ [selectEntry, tab]+ );++ // The selection's server position, while its page is resident; a pinned selection outside the window has none.+ const residentIndex = entries.findIndex((entry) => entry.item.workflow_id === activeWorkflowId);+ const position = residentIndex >= 0 ? startIndex + residentIndex : null;+ const previewStatus = useMemo(() => getLibraryPreviewStatus(activeEntry), [activeEntry]);+ const stepPreview = useCallback(+ (delta: -1 | 1, isCurrent: () => boolean) => {+ const target = position === null ? -1 : position + delta;++ if (target < 0 || target >= total) {+ return;+ }++ const resident = entries[target - startIndex];++ if (resident) {+ selectEntry(resident.item.workflow_id);+ return;+ }++ // Past the resident window: a new selection or query cancels the intent, even before search debounces.+ const intent = selectionIntent.current;+ const query = workflowUiStore.getSnapshot().libraryQuery;+ void loadWorkflowLibraryRange(target, target).then((ready) => {+ const snapshot = getWorkflowLibraryBrowseSnapshot();+ const loaded = snapshot.entries[target - (snapshot.startIndex ?? 0)];++ if (+ ready &&+ loaded &&+ isCurrent() &&+ selectionIntent.current === intent &&+ snapshot.filter === filter &&+ workflowUiStore.getSnapshot().libraryQuery === query+ ) {+ selectEntry(loaded.item.workflow_id);+ }+ });+ },+ [entries, filter, position, selectEntry, startIndex, total]+ );++ const stepper = useMemo(+ () =>+ preview.isActive+ ? {+ canStepNext: position !== null && position < total - 1,+ canStepPrevious: position !== null && position > 0,+ onStep: stepPreview,+ position,+ total,+ }+ : null,+ [position, preview.isActive, stepPreview, total]+ );++ return (+ <>+ <WorkflowLibraryResultLine count={status === 'loaded' ? total : null} tagsText={tagsText} />+ <HStack css={WORKFLOW_LIBRARY_PANES_CSS} align="stretch" flex="1" gap="3" minH="0" minW="0">+ {isOpen ? (+ <SelectedDemand key={`${authSession.user?.user_id}:${viewKey}:${activeWorkflowId}`} id={activeWorkflowId} />+ ) : null}+ {layout === 'list' ? (+ <WorkflowLibraryList+ isActive={isOpen}+ key={`${authSession.user?.user_id}:${viewKey}`}+ window={browseWindow}+ removedWorkflowId={removedWorkflowId}+ emptyMessage={emptyMessage}+ entries={entries}+ error={error}+ isHidden={preview.isActive}+ missingCounts={missingCounts}+ openMenuAnchor={contextMenuAnchor}+ showVisibilityStatus={authSession.multiuserEnabled}+ selectedWorkflowId={activeWorkflowId}+ status={status}+ onContextMenu={onContextMenu}+ onOpen={onOpen}+ onPreview={onPreview}+ onSelect={selectEntry}+ trailingField={trailingField}+ />+ ) : (+ <WorkflowLibraryGrid+ key={`${authSession.user?.user_id}:${viewKey}`}+ window={browseWindow}+ removedWorkflowId={removedWorkflowId}+ emptyMessage={emptyMessage}+ entries={entries}+ error={error}+ isHidden={preview.isActive}+ missingCounts={missingCounts}+ openMenuAnchor={contextMenuAnchor}+ showVisibilityStatus={authSession.multiuserEnabled}+ selectedWorkflowId={activeWorkflowId}+ status={status}+ onContextMenu={onContextMenu}+ onOpen={onOpen}+ onPreview={onPreview}+ onSelect={selectEntry}+ />+ )}+ {preview.isActive ? (+ <WorkflowLibraryPreviewStage+ ref={previewStageRef}+ name={activeEntry?.item.name || t('workflowLibrary.untitled')}+ placeLabel={preview.placeLabel}+ status={previewStatus}+ workflowId={activeWorkflowId}+ view={preview.view}+ onLeave={preview.onLeave}+ onViewChange={preview.onViewChange}+ />+ ) : null}+ <WorkflowLibraryDetailPanel+ entry={activeEntry}+ canChangeVisibility={activeAccess.canChangeVisibility}+ duplicateGuard={duplicateGuard}+ isReadOnly={activeAccess.isReadOnly}+ projectWorkflows={projectWorkflows}+ onClose={onClose}+ onDeleted={onDeleted}+ onDuplicated={handleDuplicated}+ onOpen={onOpenItem}+ onPreview={onPreview}+ stepper={stepper}+ />+ </HStack>+ <WorkflowLibraryContextMenu+ anchor={contextMenuAnchor}+ duplicateGuard={duplicateGuard}+ entry={menuEntry}+ isReadOnly={getLibraryEntryAccess(menuEntry, authSession, tab).isReadOnly}+ projectWorkflows={projectWorkflows}+ target={contextMenuTarget}+ onClose={onClose}+ onDeleted={onDeleted}+ onDuplicated={handleDuplicated}+ onMenuClose={onContextMenuClose}+ onOpen={onOpenItem}+ />+ </>+ );+});++let selectedLease = 0;+const SelectedDemand = ({ id }: { id: string | null }) => {+ useMountEffect(() => {+ const lease = ++selectedLease;+ setWorkflowLibrarySelectedDemand(id);+ return () => {+ queueMicrotask(() => {+ if (lease === selectedLease) {+ setWorkflowLibrarySelectedDemand(null);+ }+ });+ };+ });+ return null;+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsxindex d12ff8b936..18742fbb03 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx@@ -1,35 +1,66 @@import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';-import { Badge, Box, Flex, HStack, Icon, Skeleton, Stack, Text } from '@chakra-ui/react';-import { getModelBaseLabel } from '@features/models';-import { IconButton } from '@platform/ui/Button';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { Tooltip } from '@platform/ui/Tooltip';-import { EllipsisIcon, ImageOffIcon } from 'lucide-react';-import { useCallback, useState, type MouseEvent } from 'react';+import { Badge, Box, HStack, Icon, Stack, Text, type SystemStyleObject } from '@chakra-ui/react';+import { Button, IconButton } from '@platform/ui/Button';+import { ClippedTooltip, Tooltip } from '@platform/ui/Tooltip';+import { EllipsisIcon, FolderCheckIcon, WorkflowIcon } from 'lucide-react';+import { memo, use, useCallback, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { WORKFLOW_THUMBNAIL_ASPECT_RATIO, WorkflowThumbnailImage } from './workflowThumbnail';+import { formatTimeSince, useDataTimeSnapshot } from './relativeTime';+import { getWorkflowLibraryEntryFacts, WorkflowLibraryFactsLine } from './WorkflowLibraryFacts';+import { WorkflowThumbnailPlaceholder } from './WorkflowLibraryThumbnail';+import {+ WORKFLOW_THUMBNAIL_ASPECT_RATIO,+ WorkflowLibraryCardSizeContext,+ WorkflowThumbnailImage,+} from './workflowThumbnail';/**- * Select on click, open on double-click, and select/context-menu on right-click or from the title's own menu- * button. Reserve enrichment height so async facts cannot reflow the grid.+ * A library card is presentation only: the grid handles its click (select), double-click (open), right-click and menu+ * button (its own actions menu, which leaves the selection alone) and quick actions by delegation from the data attributes below, so a card renders again only+ * when its own entry or state changes. Reserve enrichment height so async facts cannot reflow the grid. Pointer hover+ * (and focus within the card) reveals quick actions over the top of the image: Open and Preview are pointer+ * conveniences outside the tab order that never take focus (the grid hands it to the card on press), and the menu+ * button beside them is the card's keyboard-reachable control.*/const CARD_HOVER = { bg: 'bg.muted', borderColor: 'border.emphasized' } as const;+/** The selected card keeps its accent border under the pointer; only its fill moves one step. */+const SELECTED_CARD_HOVER = { bg: 'bg.muted', borderColor: 'accent.solid' } as const;const CARD_FOCUS_VISIBLE = { outline: '2px solid {colors.accent.solid}', outlineOffset: '-2px' } as const;const CARD_TRANSITION ='border-color var(--wb-motion-duration-medium) ease, background var(--wb-motion-duration-medium) ease';-/** The card's DOM id, which the rail's context menu names as its trigger so it nests under the dialog's layer. */+/**+ * Quick actions show while the pointer is over the card, focus is inside it, or its menu is open, and take the pointer+ * only while shown: a transparent control would swallow a press meant for the card. Without hover (touch), the+ * pointer-only actions never show and the menu button always does, so a tap on the image still selects.+ */+const QUICK_ACTION_SHOWN = { opacity: 1, pointerEvents: 'auto' } as const;+const CARD_ROOT_CSS: SystemStyleObject = {+ '& [data-card-quick-action]': {+ opacity: 0,+ pointerEvents: 'none',+ transition: 'opacity var(--wb-motion-duration-fast) ease',+ },+ '&:focus-within [data-card-quick-action], &[data-menu-open] [data-card-quick-action]': QUICK_ACTION_SHOWN,+ '@media (hover: hover)': { '&:hover [data-card-quick-action]': QUICK_ACTION_SHOWN },+ '@media (hover: none)': {+ '& [data-card-quick-action][data-pointer-only]': { display: 'none' },+ '& [data-card-quick-action]': QUICK_ACTION_SHOWN,+ },+};++/** The card's DOM id, which its actions menu names as its trigger so it nests under the dialog's layer. */export const getWorkflowLibraryCardId = (workflowId: string): string => `workflow-library-card-${workflowId}`;-/** The title's menu button; when it opened the menu, it is the trigger focus returns to. */+/** The card's menu button; when it opened the menu, it is the trigger focus returns to. */export const getWorkflowLibraryCardMenuId = (workflowId: string): string =>`${getWorkflowLibraryCardId(workflowId)}-menu`;/**- * The rail's actions menu content, named so the tile button can point at it: the dialog's focus trap only lets+ * The card's actions menu content, named so the tile button can point at it: the dialog's focus trap only lets* focus into portalled content that an expanded control inside the dialog names with aria-controls.*/export const getWorkflowLibraryCardMenuContentId = (workflowId: string): string =>@@ -40,9 +71,14 @@ export type WorkflowCardMenuAnchor =| { kind: 'point'; workflowId: string; x: number; y: number }| { kind: 'trigger'; workflowId: string; triggerId: string };+export type WorkflowCardContextMenuHandler = (workflowId: string, anchor: WorkflowCardMenuAnchor) => void;++/** A quick action's `data-card-action`; the grid reads it with the card root's `data-workflow-card-root`. */+export type WorkflowCardQuickAction = 'open' | 'preview';+/**- * A right-click on a card, or a click on a tile's menu button, re-anchors or toggles the open menu through its own- * handler rather than dismissing it as an outside press.+ * A right-click on a card (or its quick actions) or a list row, or a click on a tile's or row's menu button, re-anchors+ * or toggles the open menu through its own handler rather than dismissing it as an outside press.*/export const keepCardMenuOpenForRetarget = (event: {detail: { originalEvent: Event };@@ -55,85 +91,117 @@ export const keepCardMenuOpenForRetarget = (event: {}if (- (original.button === 2 && original.target.closest('[data-workflow-card]') !== null) ||+ (original.button === 2 &&+ original.target.closest(+ '[data-workflow-card],[data-workflow-card-actions],[data-workflow-library-list] [data-list-row]'+ ) !== null) ||(original.button === 0 && original.target.closest('[data-workflow-card-menu]') !== null)) {event.preventDefault();}};-/** The title row's fixed height; the sibling menu button sits on it from outside the card button. */-const TITLE_ROW_HEIGHT = '6';-/** Body padding (2.5) plus the facts row (4) plus the gap (1) below the title row, in px. */-const TITLE_ROW_BOTTOM_PX = 30;+/**+ * Preview and More sit on an opaque panel fill so they read over any thumbnail. That fill replaces the outline recipe's+ * translucent hover and expanded tint, so they lay the same tint over the panel (`bg.muted` equals `bg.panel`).+ */+const QUICK_ACTION_INTERACTION = { bg: 'color-mix(in oklab, {colors.gray.hoverTint} 10%, {colors.bg.panel})' } as const;++/**+ * The library's menus (a card's, the rail's More, the sheet's More) are siblings, never nested. Zag handles an outside+ * press a frame after its pointerdown, so a quick press on one menu's trigger while another is open opens the new menu+ * first; the old one then leaves the layer stack with the new one above it and would dismiss it as its nested layer.+ * A dismissal requested by a closing menu is ignored; a closing dialog still dismisses its menus.+ */+export const keepMenuOpenWhenSiblingMenuCloses = (event: {+ detail: { targetLayer: HTMLElement | undefined };+ preventDefault(): void;+}): void => {+ if (event.detail.targetLayer?.matches('[data-scope="menu"][data-part="content"]')) {+ event.preventDefault();+ }+};++const NAME_FONT_SIZE = { large: 'lg', small: 'md' } as const;+const QUICK_ACTION_SIZE = { large: 'sm', small: 'xs' } as const;export interface WorkflowLibraryCardProps {entry: WorkflowLibraryEntry;/** The project's active workflow; the card says so in the header. */isActive?: boolean;+ /** The project already holds a copy of this library template. */+ isInProject?: boolean;/** Which of the tile's controls has the actions menu open, if any; that control names the menu for the dialog. */menuOpenedBy?: 'card' | 'button' | null;isSelected: boolean;- /** Project workflows reuse this card, but have no library visibility state. */+ /** Multi-user servers badge public templates; project workflows have no library visibility. */showVisibilityStatus?: boolean;- /** Models this workflow needs that are not installed; 0 hides the badge. */+ /** Project workflows say when they last ran instead of their node count. */+ showLastRun?: boolean;+ /** Models this workflow needs that are not installed; 0 when none. */missingCount: number;- onContextMenu: (workflowId: string, anchor: WorkflowCardMenuAnchor) => void;- onOpen: (workflowId: string) => void;- onSelect: (workflowId: string) => void;+ /** Node packs the workflow uses that this server lacks; null while node templates are unknown. */+ missingNodePackCount?: number | null;+ /** Shows the Preview quick action. */+ canPreview?: boolean;}-export const WorkflowLibraryCard = ({+const isTextClipped = (element: HTMLElement | null): boolean =>+ element !== null && element.scrollWidth > element.clientWidth;++/** Memoised: every enrichment completion and range load re-renders the grid, but rarely a given card's props. */+export const WorkflowLibraryCard = memo(function WorkflowLibraryCard({+ canPreview = false,entry,isActive = false,+ isInProject = false,isSelected,menuOpenedBy = null,missingCount,- onContextMenu,- onOpen,- onSelect,+ missingNodePackCount = null,+ showLastRun = false,showVisibilityStatus = false,-}: WorkflowLibraryCardProps) => {+}: WorkflowLibraryCardProps) {const { t } = useTranslation();+ const size = use(WorkflowLibraryCardSizeContext);const [hasThumbnailFailed, setHasThumbnailFailed] = useState(false);+ const nameRef = useRef<HTMLParagraphElement>(null);const { enrichment, item } = entry;const workflowId = item.workflow_id;+ const dataTime = useDataTimeSnapshot(showLastRun ? item : null);- const handleSelect = useCallback(() => onSelect(workflowId), [onSelect, workflowId]);- const handleOpen = useCallback(() => onOpen(workflowId), [onOpen, workflowId]);- const handleContextMenu = useCallback(- (event: MouseEvent<HTMLElement>) => {- event.preventDefault();-- // A keyboard-raised menu (Shift+F10, the Menu key) carries no pointer- // position; anchor it inside the card instead of at the viewport corner.- const rect = event.currentTarget.getBoundingClientRect();- const fromKeyboard = event.clientX === 0 && event.clientY === 0;-- onContextMenu(- workflowId,- fromKeyboard- ? { kind: 'point', workflowId, x: rect.left + 16, y: rect.top + 16 }- : { kind: 'point', workflowId, x: event.clientX, y: event.clientY }- );- },- [onContextMenu, workflowId]- );- const handleMenuButton = useCallback(- () =>- onContextMenu(workflowId, { kind: 'trigger', triggerId: getWorkflowLibraryCardMenuId(workflowId), workflowId }),- [onContextMenu, workflowId]- );+ // Pointer-only parts (Open, Preview, the name's tooltip) mount on the first pointer visit: a row of cards mounts in+ // one scroll frame, and these controls would roughly double what each card costs to mount.+ const [isPointerArmed, setIsPointerArmed] = useState(false);+ const armPointer = useCallback(() => setIsPointerArmed(true), []);const handleThumbnailError = useCallback(() => setHasThumbnailFailed(true), []);+ const isNameClipped = useCallback(() => isTextClipped(nameRef.current), []);const showThumbnail = Boolean(item.thumbnail_url) && !hasThumbnailFailed;- const primaryBase = enrichment.status === 'ready' ? enrichment.requirements.primaryBase : null;-+ const ready = enrichment.status === 'ready' ? enrichment : null;+ const lastRun = showLastRun && item.last_run_at ? formatTimeSince(item.last_run_at, dataTime) : '';+ const facts = getWorkflowLibraryEntryFacts({ entry, isInProject, lastRun, missingCount, missingNodePackCount }, t);+ const name = item.name || t('workflowLibrary.untitled');const menuContentId = getWorkflowLibraryCardMenuContentId(workflowId);+ const quickActionSize = QUICK_ACTION_SIZE[size];+ const nameText = (+ <Text ref={nameRef} flex="1" fontSize={NAME_FONT_SIZE[size]} fontWeight="600" minW="0" truncate>+ {name}+ </Text>+ );- // The menu button is a sibling of the card button, never nested in it: a button cannot hold another control.+ // The quick actions and menu button are siblings of the card button, never nested in it: a button cannot hold+ // another control.return (- <Box minW="0" position="relative" w="full">+ <Box+ css={CARD_ROOT_CSS}+ data-workflow-card-root={workflowId}+ data-menu-open={menuOpenedBy !== null ? '' : undefined}+ onPointerEnter={isPointerArmed ? undefined : armPointer}+ minW="0"+ position="relative"+ w="full"+ ><Boxas="button"aria-controls={menuOpenedBy === 'card' ? menuContentId : undefined}@@ -151,33 +219,43 @@ export const WorkflowLibraryCard = ({transition={CARD_TRANSITION}w="full"_focusVisible={CARD_FOCUS_VISIBLE}- _hover={CARD_HOVER}- onClick={handleSelect}- onContextMenu={handleContextMenu}- onDoubleClick={handleOpen}+ _hover={isSelected ? SELECTED_CARD_HOVER : CARD_HOVER}>- <Box aspectRatio={WORKFLOW_THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" w="full">+ <Box aspectRatio={WORKFLOW_THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" position="relative" w="full">{showThumbnail ? (<WorkflowThumbnailImage src={item.thumbnail_url} onError={handleThumbnailError} />) : (- <Flex align="center" direction="column" gap="1" h="full" justify="center" w="full">- <Icon aria-hidden as={ImageOffIcon} boxSize="5" color="fg.subtle" opacity={0.6} />- <Text color="fg.subtle" fontSize="xs">- {t('workflowLibrary.notRunYet')}- </Text>- </Flex>+ <WorkflowThumbnailPlaceholder workflowDocument={ready?.document ?? null} />)}+ {isInProject ? (+ <HStack+ bg="bg.panel/85"+ color="fg.muted"+ data-workflow-in-project+ insetStart="1.5"+ position="absolute"+ px="1"+ py="0.5"+ rounded="sm"+ bottom="1.5"+ >+ <Icon aria-hidden as={FolderCheckIcon} boxSize="3" />+ <Text srOnly>{t('workflowLibrary.inProject')}</Text>+ </HStack>+ ) : null}</Box><Stack gap="1" minW="0" p="2.5" w="full">- <HStack gap="1.5" h={TITLE_ROW_HEIGHT} minW="0" pe="7">- <MiddleTruncate fontSize="md" fontWeight="600" minW="0" text={item.name || t('workflowLibrary.untitled')} />- {showVisibilityStatus && item.category === 'user' ? (- <Badge- data-workflow-visibility={item.is_public === true ? 'public' : 'private'}- flexShrink={0}- variant="subtle"- >- {t(item.is_public === true ? 'workflowLibrary.public' : 'workflowLibrary.private')}+ <HStack gap="1.5" h="6" minW="0">+ {isPointerArmed ? (+ <ClippedTooltip content={name} isClipped={isNameClipped}>+ {nameText}+ </ClippedTooltip>+ ) : (+ nameText+ )}+ {showVisibilityStatus && item.is_public === true ? (+ <Badge data-workflow-visibility="public" flexShrink={0} variant="subtle">+ {t('workflowLibrary.public')}</Badge>) : null}{isActive ? (@@ -186,48 +264,75 @@ export const WorkflowLibraryCard = ({</Badge>) : null}</HStack>- <HStack gap="1.5" h="4" minW="0">- {enrichment.status === 'pending' ? (- // Show placeholders only while enriching; unreadable workflows leave facts absent.- <Skeleton data-enrichment-placeholder h="3" rounded="sm" w="14" />- ) : null}- {primaryBase ? (- <Badge flexShrink={0} variant="subtle">- {getModelBaseLabel(primaryBase)}- </Badge>- ) : null}- {enrichment.status === 'ready' ? (- <Text color="fg.muted" fontSize="xs" truncate>- {t('workflowLibrary.nodeCount', { count: enrichment.nodeCount })}- </Text>- ) : null}- {missingCount > 0 ? (- <Badge bg="bg.warning" color="fg.warning" flexShrink={0} variant="subtle">- {t('workflowLibrary.installModels', { count: missingCount })}- </Badge>- ) : null}- </HStack>+ <WorkflowLibraryFactsLine facts={facts} /></Stack></Box>- <Tooltip content={t('workflowLibrary.moreActions')}>- <IconButton- aria-controls={menuOpenedBy === 'button' ? menuContentId : undefined}- aria-expanded={menuOpenedBy === 'button'}- aria-haspopup="menu"- aria-label={t('workflowLibrary.moreActions')}- bottom={`${TITLE_ROW_BOTTOM_PX}px`}- color="fg.muted"- data-workflow-card-menu={workflowId}- id={getWorkflowLibraryCardMenuId(workflowId)}- insetEnd="2.5"- position="absolute"- size="sm"- variant="ghost"- onClick={handleMenuButton}- >- <EllipsisIcon />- </IconButton>- </Tooltip>+ <HStack+ // Over the top of the image, clear of the card's centre (there a press selects the card, and a strip the hover+ // revealed would take it instead) and of the in-project marker at the image's bottom corner.+ top="1.5"+ data-workflow-card-actions={workflowId}+ gap="1"+ insetEnd="1.5"+ insetStart="1.5"+ justify="flex-end"+ pointerEvents="none"+ position="absolute"+ >+ {/* The active project workflow is already open; its rail disables Open too. */}+ {isPointerArmed && !isActive ? (+ <Button+ aria-hidden+ data-card-action={'open' satisfies WorkflowCardQuickAction}+ data-card-quick-action+ data-pointer-only+ size={quickActionSize}+ tabIndex={-1}+ variant="solid"+ >+ {/* Parity with the rail: opening asks what to do once the project holds a copy. */}+ {isInProject ? t('workflowLibrary.openWithEllipsis') : t('workflowLibrary.open')}+ </Button>+ ) : null}+ {isPointerArmed && canPreview ? (+ <Tooltip content={t('workflowLibrary.preview.actionHint')}>+ <IconButton+ aria-hidden+ aria-label={t('workflowLibrary.preview.action')}+ bg="bg.panel"+ _hover={QUICK_ACTION_INTERACTION}+ data-card-action={'preview' satisfies WorkflowCardQuickAction}+ data-card-quick-action+ data-pointer-only+ size={quickActionSize}+ tabIndex={-1}+ variant="outline"+ >+ <WorkflowIcon />+ </IconButton>+ </Tooltip>+ ) : null}+ {/* Always mounted with its own tooltip: it is the card's keyboard control (Tab order, focus restore and the+ grid's Tab handling find it by id), and wrapping it later would remount it under focus. */}+ <Tooltip content={t('workflowLibrary.moreActions')}>+ <IconButton+ aria-controls={menuOpenedBy === 'button' ? menuContentId : undefined}+ aria-expanded={menuOpenedBy === 'button'}+ aria-haspopup="menu"+ aria-label={t('workflowLibrary.moreActions')}+ bg="bg.panel"+ _expanded={QUICK_ACTION_INTERACTION}+ _hover={QUICK_ACTION_INTERACTION}+ data-card-quick-action+ data-workflow-card-menu={workflowId}+ id={getWorkflowLibraryCardMenuId(workflowId)}+ size={quickActionSize}+ variant="outline"+ >+ <EllipsisIcon />+ </IconButton>+ </Tooltip>+ </HStack></Box>);-};+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryContextMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryContextMenu.tsxnew file mode 100644index 0000000000..ee45a2f295--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryContextMenu.tsx@@ -0,0 +1,174 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibraryListItem } from '@features/workflow/queries';++import { Menu, Portal } from '@chakra-ui/react';+import { MenuContent } from '@platform/ui/Menu';+import { memo, useCallback, useMemo, useState, type ReactNode } from 'react';++import { useWorkflowLibraryEntryActions, type WorkflowLibraryDuplicateGuard } from './useWorkflowLibraryEntryActions';+import {+ getWorkflowLibraryCardId,+ getWorkflowLibraryCardMenuContentId,+ keepCardMenuOpenForRetarget,+ keepMenuOpenWhenSiblingMenuCloses,+ type WorkflowCardMenuAnchor,+} from './WorkflowLibraryCard';++/**+ * The workflow a card's or row's actions menu was raised for, and the control that raised it. It outlives the open+ * menu: the menu learns it closed only after React has rendered the close, so the trigger it restores focus to must+ * still be the one that opened it, and the dialogs its items open belong to the same workflow.+ */+export interface WorkflowContextMenuTarget {+ /** The tile's or row's More button when it raised the menu; null for a right-click or Shift+F10 on the card. */+ triggerId: string | null;+ workflowId: string;+}++export interface WorkflowCardContextMenuProps {+ /** Where the open menu is anchored; null while it is closed. */+ anchor: WorkflowCardMenuAnchor | null;+ children: ReactNode;+ target: WorkflowContextMenuTarget | null;+ onClose: () => void;+}++/**+ * A card's or row's actions menu, for the workflow it was raised on whether or not that is the selection. Naming the+ * card (or its More button) as the trigger makes the menu a nested layer of the library dialog: the dialog's focus+ * trap then lets the menu keep focus, and closing returns it there. A pointer point is a fixed rect; a More button+ * anchors the menu itself, so the menu follows it as the collection scrolls.+ */+export const WorkflowCardContextMenu = ({ anchor, children, target, onClose }: WorkflowCardContextMenuProps) => {+ /*+ * A press on another control (the rail's More, the search field) closes the menu and keeps focus there. Zag skips+ * focus return for such a press only on an uncontrolled close; this menu is controlled, so it names no trigger to+ * return to until it opens again.+ */+ const [returnsFocus, setReturnsFocus] = useState(true);+ const [openedAt, setOpenedAt] = useState(anchor);+ if (anchor !== openedAt) {+ setOpenedAt(anchor);+ if (anchor !== null) {+ setReturnsFocus(true);+ }+ }+ const handlePointerDownOutside = useCallback(+ (event: Parameters<NonNullable<Menu.RootProps['onPointerDownOutside']>>[0]) => {+ keepCardMenuOpenForRetarget(event);+ if (!event.defaultPrevented && event.detail.focusable) {+ setReturnsFocus(false);+ }+ },+ []+ );+ const ids = useMemo(() => {+ if (!target) {+ return undefined;+ }+ const content = getWorkflowLibraryCardMenuContentId(target.workflowId);++ return {+ content,+ trigger: returnsFocus ? (target.triggerId ?? getWorkflowLibraryCardId(target.workflowId)) : `${content}-closed`,+ };+ }, [returnsFocus, target]);+ const positioning = useMemo(() => {+ // The menu belongs to the library dialog's visible bounds, rather than the whole viewport.+ const boundary = () =>+ (ids ? document.getElementById(ids.trigger) : null)?.closest<HTMLElement>(+ '[data-scope="dialog"][data-part="content"]'+ ) ?? [];++ return anchor?.kind === 'point'+ ? {+ boundary,+ getAnchorRect: () => ({ height: 1, width: 1, x: anchor.x, y: anchor.y }),+ placement: 'bottom-start' as const,+ }+ : { boundary, placement: 'bottom-end' as const };+ }, [anchor, ids]);+ const handleOpenChange = useCallback(+ (event: { open: boolean }) => {+ if (!event.open) {+ onClose();+ }+ },+ [onClose]+ );++ return (+ <Menu.Root+ ids={ids}+ open={anchor !== null}+ positioning={positioning}+ onOpenChange={handleOpenChange}+ onPointerDownOutside={handlePointerDownOutside}+ onRequestDismiss={keepMenuOpenWhenSiblingMenuCloses}+ >+ <Portal>+ <Menu.Positioner>+ <MenuContent+ data-workflow-context-menu+ minW="min(13rem, var(--available-width))"+ maxW="var(--available-width)"+ >+ {children}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ );+};++export interface WorkflowLibraryContextMenuProps {+ anchor: WorkflowCardMenuAnchor | null;+ duplicateGuard: WorkflowLibraryDuplicateGuard;+ /** The target's entry; null once it has left the resident window, when the shell has already closed the menu. */+ entry: WorkflowLibraryEntry | null;+ isReadOnly: boolean;+ projectWorkflows: readonly ProjectWorkflowEntry[];+ target: WorkflowContextMenuTarget | null;+ /** The shell closes the library when a fork takes the user to a new project. */+ onClose: () => void;+ onDeleted: (workflowId: string) => void;+ onDuplicated: (workflowId: string) => void;+ onMenuClose: () => void;+ onOpen: (item: WorkflowLibraryListItem) => void;+}++/** A library card's actions menu with the dialogs its items open; memoised like the rail, which browsing re-renders. */+export const WorkflowLibraryContextMenu = memo(function WorkflowLibraryContextMenu({+ anchor,+ duplicateGuard,+ entry,+ isReadOnly,+ projectWorkflows,+ target,+ onClose,+ onDeleted,+ onDuplicated,+ onMenuClose,+ onOpen,+}: WorkflowLibraryContextMenuProps) {+ const { actionItems, dialogs } = useWorkflowLibraryEntryActions({+ duplicateGuard,+ entry,+ isReadOnly,+ projectWorkflows,+ onClose,+ onDeleted,+ onDuplicated,+ onOpen,+ });++ return (+ <>+ <WorkflowCardContextMenu anchor={anchor} target={target} onClose={onMenuClose}>+ {actionItems}+ </WorkflowCardContextMenu>+ {dialogs}+ </>+ );+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsxindex 7be9e7b97b..9051bf81cf 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx@@ -13,14 +13,27 @@ import { createProjectGraph, serializeWorkflowJson } from '@features/workflow/utimport { accountLifecycle } from '@platform/state/accountLifecycle';import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';import { system } from '@theme/system';-import { act, StrictMode, type ReactNode } from 'react';+import { act, StrictMode, type ComponentProps, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';import { loadGraphPreview } from './libraryPreviewSource';+import { useWorkflowLibraryDuplicateGuard } from './useWorkflowLibraryEntryActions';import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';+/**+ * The rail as the template panes mount it, with their duplicate guard. Write access is the panes' decision+ * (`getLibraryEntryAccess`); for this single-user owner, only the account's own templates are writable.+ */+const PanesRail = (props: Omit<ComponentProps<typeof WorkflowLibraryDetailPanel>, 'duplicateGuard' | 'isReadOnly'>) => (+ <WorkflowLibraryDetailPanel+ {...props}+ duplicateGuard={useWorkflowLibraryDuplicateGuard()}+ isReadOnly={props.entry?.item.category !== 'user'}+ />+);+/*** Use mutable catalog fixtures but real install-source expansion to verify deduplicated catalog sources reach* installMany.@@ -105,6 +118,20 @@ const pickedGalleryItem = vi.hoisted(() => ({current: { kind: 'image', name: 'picked.gif', thumbnailUrl: '' } as Record<string, unknown>,}));+/** Visibility is a multi-user notion; most cases here are an owner on a multi-user server. */+const identity = vi.hoisted(() => ({+ session: { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } } as {+ multiuserEnabled: boolean;+ phase: 'ready';+ user: { user_id: string } | null;+ },+}));++vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useAuthSession: () => identity.session,+}));+// Node definitions are loaded, so a template's document compiles for the snapshot.vi.mock('@features/workflow/react', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),@@ -143,14 +170,11 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.deleteConfirmBody': 'Delete "{{name}}" from the workflow library? This cannot be undone.','workflowLibrary.deleteConfirmTitle': 'Delete workflow','workflowLibrary.deleteFailed': 'Failed to delete workflow',- 'workflowLibrary.deleteHint': 'Removes it from your library','workflowLibrary.downloadJson': 'Download JSON',- 'workflowLibrary.downloadJsonHint': 'For bug reports and sharing','workflowLibrary.duplicate': 'Duplicate','workflowLibrary.duplicateFailed': 'Failed to duplicate workflow','workflowLibrary.rename': 'Rename','workflowLibrary.renameFailed': 'Rename failed',- 'workflowLibrary.renameTemplateHint': "Changes the template's name in the library",'workflowLibrary.renameTemplateTitle': 'Rename template','workflowLibrary.renameWithEllipsis': 'Rename…','workflowLibrary.renamed': 'Template renamed',@@ -164,12 +188,10 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.thumbnailUpdateFailed': 'Failed to update thumbnail','workflowLibrary.thumbnailUpdated': 'Thumbnail updated','workflowLibrary.thumbnailUpdating': 'Updating thumbnail…',- 'workflowLibrary.duplicateHint': 'Saves a copy under Yours, original untouched','workflowLibrary.duplicateName': '{{name}} copy','workflowLibrary.duplicated': 'Saved a copy under Yours','workflowLibrary.findModel': 'Find {{name}} in the model manager','workflowLibrary.forkIntoProject': 'Fork into new project',- 'workflowLibrary.forkIntoProjectHint': 'Copies it into a new project','workflowLibrary.installModels_one': 'Install 1 model','workflowLibrary.installModels_other': 'Install {{count}} models','workflowLibrary.installQueued': 'Model installs queued',@@ -178,9 +200,8 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.moreActions': 'More actions','workflowLibrary.notRunYet': 'Not run yet','workflowLibrary.open': 'Open',- 'workflowLibrary.openHint': 'Adds a copy to this project','workflowLibrary.openWithEllipsis': 'Open…',- 'workflowLibrary.previewGraph': 'Preview graph',+ 'workflowLibrary.preview.action': 'Preview','workflowLibrary.requirementInstallable': 'Not installed','workflowLibrary.requirementInstalled': 'Installed','workflowLibrary.requirementInstalling': 'Installing…',@@ -195,6 +216,12 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.visibilityUpdateFailed': 'Failed to update workflow visibility','workflowLibrary.visibilityUnknown': 'Visibility unknown','workflowLibrary.retry': 'Retry',+ 'workflowLibrary.modelsToInstall_one': '{{count}} model to install',+ 'workflowLibrary.modelsToInstall_other': '{{count}} models to install',+ 'workflowLibrary.nodeCount_one': '{{count}} node',+ 'workflowLibrary.nodeCount_other': '{{count}} nodes',+ 'workflowLibrary.openedWhen': 'Opened {{when}}',+ 'workflowLibrary.readyToRun': 'Ready to run',};const interpolate = (template: string, options?: Record<string, unknown>): string =>@@ -207,7 +234,9 @@ const translate = (key: string, options?: Record<string, unknown>): string => {return interpolate(plural ?? TRANSLATIONS[key] ?? key, options);};-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ i18n: { language: 'en', resolvedLanguage: 'en' }, t: translate }),+}));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -375,10 +404,10 @@ describe('WorkflowLibraryDetailPanel', () => {let host: HTMLDivElement;let root: Root;let onClose: () => void;- let onDeleted: () => void;+ let onDeleted: (workflowId: string) => void;let onDuplicated: (workflowId: string) => void;let onOpen: (item: WorkflowLibraryEntry['item']) => void;- let onPreview: (selected: WorkflowLibraryEntry) => void;+ let onPreview: (workflowId: string) => void;/** See `WorkflowLibraryDialog.browser.test.tsx`: keeps Chakra's observer-driven commits inside the act scope. */const settleFrame = () =>@@ -396,14 +425,11 @@ describe('WorkflowLibraryDetailPanel', () => {<WorkflowUiProvider adapter={ADAPTER}><GalleryHostProvider host={GALLERY_HOST}><WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>- <WorkflowLibraryDetailPanel- contextMenuPoint={null}- contextMenuTriggerId={null}+ <PanesRailentry={selected}canChangeVisibility={canChangeVisibility}projectWorkflows={projectWorkflows}onClose={onClose}- onContextMenuClose={NOOP}onDeleted={onDeleted}onDuplicated={onDuplicated}onOpen={onOpen}@@ -465,7 +491,7 @@ describe('WorkflowLibraryDetailPanel', () => {});};- const menuItem = (value: string) => document.querySelector<HTMLElement>(`[data-menu-item="${value}"]`);+ const menuItem = (value: string) => document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`);const clickMenuItem = async (value: string) => {await openMenu();@@ -473,10 +499,9 @@ describe('WorkflowLibraryDetailPanel', () => {const item = menuItem(value);expect(item, `no menu item "${value}"`).not.toBeNull();- await act(async () => {- item?.click();- await settleFrame();- });+ // Zag selects only the highlighted item, so this takes a real pointer click, which hovers it first.+ await act(() => userEvent.click(item!));+ await act(settleFrame);};beforeEach(() => {@@ -488,6 +513,7 @@ describe('WorkflowLibraryDetailPanel', () => {onDuplicated = vi.fn((_workflowId: string) => {});onOpen = vi.fn();onPreview = vi.fn();+ identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } };accountLifecycle.invalidate();models.activeInstallSources.current = new Set();@@ -953,15 +979,46 @@ describe('WorkflowLibraryDetailPanel', () => {expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item);});- it('swaps the primary action for an install when starter models can fill the gaps', async () => {+ it('offers an install under the requirements when starter models can fill the gaps, keeping Open', async () => {await renderPanel(IMAGE_TO_VIDEO);expect(requirementStatuses()).toEqual(['installable', 'installable', 'installed']);// The rows say which state they are in, not just how they are styled.expect(document.querySelectorAll('[aria-label="Not installed"]')).toHaveLength(2);expect(document.querySelectorAll('[aria-label="Installed"]')).toHaveLength(1);- expect(buttonWithText('Install 2 models')).not.toBeUndefined();- expect(buttonWithText('Open')).toBeUndefined();+ const install = buttonWithText('Install 2 models');+ const requirements = document.querySelector('[data-requirement-status]')!;+ expect(requirements.compareDocumentPosition(install!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(buttonWithText('Open')).not.toBeUndefined();+ });++ it('summarises the template on one line for the narrow layout’s sheet, with its own Open', async () => {+ const summary = () => panel()!.querySelector<HTMLElement>('[data-detail-sheet-summary]')!;+ const summaryFacts = () => summary().querySelectorAll('p')[1]?.textContent;++ await renderPanel(IMAGE_TO_VIDEO);+ expect(summary().textContent).toContain('Image to video');+ expect(summaryFacts()).toBe('3 nodes · 2 models to install');++ const openedAt = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString();+ await renderPanel({ ...TEXT_TO_IMAGE, item: { ...TEXT_TO_IMAGE.item, opened_at: openedAt } });+ expect(summaryFacts()).toMatch(/^1 node · Ready to run · Opened \S/);++ await act(async () => {+ summary().querySelector<HTMLButtonElement>('[data-detail-sheet-open]')!.click();+ await settleFrame();+ });+ expect(onOpen).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ workflow_id: TEXT_TO_IMAGE.item.workflow_id })+ );+ });++ it('leaves visibility out of the rail on a single-user server', async () => {+ identity.session = { multiuserEnabled: false, phase: 'ready', user: null };+ await renderPanel(TEXT_TO_IMAGE, NO_COPIES, true);++ expect(document.querySelector('[data-workflow-visibility]')).toBeNull();+ expect(document.querySelector('[data-workflow-detail] input[type="checkbox"]')).toBeNull();});it('queues one install per source, deduped across requirements that share a dependency', async () => {@@ -1100,10 +1157,9 @@ describe('WorkflowLibraryDetailPanel', () => {await openMenu();expect(menuItem('duplicate')?.getAttribute('aria-disabled')).toBe('true');- await act(async () => {- menuItem('duplicate')?.click();- await settleFrame();- });+ // Forced past the pointer's actionability wait, so the press reaches the disabled item.+ await act(() => userEvent.click(menuItem('duplicate')!, { force: true }));+ await act(settleFrame);await act(async () => {release(RAW_WORKFLOW);@@ -1236,9 +1292,6 @@ describe('WorkflowLibraryDetailPanel', () => {it('deletes only after the confirmation is accepted', async () => {await renderPanel(TEXT_TO_IMAGE);- await openMenu();- expect(menuItem('delete')?.textContent).toContain('Removes it from your library');-await clickMenuItem('delete');const confirm = document.querySelector<HTMLElement>('[role="alertdialog"]');@@ -1257,7 +1310,7 @@ describe('WorkflowLibraryDetailPanel', () => {expect(queries.deleteLibraryWorkflow).toHaveBeenCalledWith('wf-text-to-image', expect.anything());expect(queries.invalidateWorkflowLibraryCache).toHaveBeenCalledTimes(1);- expect(onDeleted).toHaveBeenCalledTimes(1);+ expect(onDeleted).toHaveBeenCalledExactlyOnceWith('wf-text-to-image');});it('animates the delete confirmation out when the deleted workflow leaves the panel', async () => {@@ -1309,12 +1362,12 @@ describe('WorkflowLibraryDetailPanel', () => {expect(queries.invalidateWorkflowLibraryCache).not.toHaveBeenCalled();});- it('hands the selected entry to the preview action', async () => {+ it('asks to preview the selected workflow', async () => {await renderPanel(IMAGE_TO_VIDEO);- await clickButton('Preview graph');+ await clickButton('Preview');- expect(onPreview).toHaveBeenCalledWith(IMAGE_TO_VIDEO);+ expect(onPreview).toHaveBeenCalledWith(IMAGE_TO_VIDEO.item.workflow_id);});it('links only the rows the account is missing, and takes them to Add Models', async () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsxindex 289893cf04..69cce094ad 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx@@ -2,78 +2,62 @@ import type { StarterInstallSource } from '@features/models';import type { ProjectWorkflowEntry } from '@features/workflow/core/types';import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';import type { WorkflowLibraryListItem } from '@features/workflow/queries';+import type { WorkflowPreviewView } from '@features/workflow/ui/graph-preview/WorkflowPreviewStage';-import { Badge, Box, HStack, Menu, Portal, Stack, Switch, Text } from '@chakra-ui/react';-import { getStarterModelInstallSources, useInstallActions } from '@features/models';-import { getWorkflowRecordCategory } from '@features/workflow/data/api';+import { Badge, Box, DataList, HStack, Menu, Portal, Stack, Switch, Text } from '@chakra-ui/react';+import { useAuthSession } from '@features/identity';+import { getModelBaseLabel, getStarterModelInstallSources, useInstallActions } from '@features/models';import {- createLibraryWorkflow,- deleteLibraryWorkflow,- getLibraryWorkflowCached,getLibraryWorkflowRecord,- getLibraryWorkflowRecordCached,invalidateWorkflowLibraryCache,setLibraryWorkflowPublic,- updateLibraryWorkflow,} from '@features/workflow/queries';-import { MenuActionItem } from '@features/workflow/ui/MenuActionItem';-import {- useOpenAddModels,- useWorkflowGraphPreview,- useWorkflowNotifications,-} from '@features/workflow/ui/WorkflowUiContext';-import { parseWorkflowJson } from '@features/workflow/utility';-import { downloadText } from '@platform/browser/downloadBlob';+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { useModelRequirementDeps } from '@features/workflow/ui/modelRequirementStatus';+import { useOpenAddModels, useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';import {assertAccountScopeCurrent,captureAccountScope,isAccountScopeCurrent,} from '@platform/state/accountLifecycle';import { getApiErrorMessage } from '@platform/transport/http';-import {- Button,- ConfirmDialog,- IconButton,- MenuContent,- RenameDialog,- Scrollable,- Tooltip,- useTooltipTriggerIds,-} from '@platform/ui';-import { CopyIcon, DownloadIcon, EllipsisIcon, GitForkIcon, PencilIcon, Trash2Icon, WorkflowIcon } from 'lucide-react';-import { useCallback, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react';+import { Button, IconButton, MenuContent, Scrollable, Tooltip, useTooltipTriggerIds } from '@platform/ui';+import { DownloadIcon, EllipsisIcon, WorkflowIcon } from 'lucide-react';+import { memo, useCallback, useLayoutEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';-import { planLibraryWorkflowOpen } from './useOpenLibraryWorkflow';+import type { WorkflowPreviewStepperProps } from './WorkflowPreviewStepper';++import { formatTimeSince, useDataTimeSnapshot } from './relativeTime';+import { useWorkflowLibraryEntryActions, type WorkflowLibraryDuplicateGuard } from './useWorkflowLibraryEntryActions';import {- getWorkflowLibraryCardId,- getWorkflowLibraryCardMenuContentId,- keepCardMenuOpenForRetarget,- type WorkflowCardMenuAnchor,-} from './WorkflowLibraryCard';-import { WorkflowLibraryThumbnail } from './WorkflowLibraryThumbnail';+ useWorkflowPreviewModel,+ WORKFLOW_SILHOUETTE_THUMBNAIL_CSS,+ WorkflowAuthorNotes,+ WorkflowInputsBadge,+ WorkflowInputsSummary,+ WorkflowProvenance,+} from './WorkflowDetailOverview';import {- resolveEntryRequirements,- useModelRequirementDeps,- WorkflowRequirementsList,-} from './WorkflowRequirementsList';--/** Install missing models before offering Open; keep the detail rail mounted across selections to prevent flashing. */--const DETAIL_RAIL_WIDTH = '18rem';-const DETAIL_RAIL_CSS = {- '@container workflow-library-content (width < 42rem) and ((height >= 32rem) or (width < 32rem))': {- width: '100%',- },- '@container workflow-library-content (width < 42rem) and (height >= 32rem)': {- flexBasis: '45%',- },- '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {- flex: '0 0 auto',- height: '20rem',- },-} as const;+ WORKFLOW_DETAIL_WIDE_ONLY_CSS,+ WORKFLOW_PREVIEW_TRIGGER_CSS,+ WorkflowDetailRailPlaceholder,+ WorkflowDetailSheet,+ WorkflowMissingNodePacks,+} from './WorkflowDetailSheet';+import { keepMenuOpenWhenSiblingMenuCloses } from './WorkflowLibraryCard';+import { WorkflowLibraryThumbnail } from './WorkflowLibraryThumbnail';+import { getMissingNodePacks, resolveEntryRequirements, WorkflowRequirementsList } from './WorkflowRequirementsList';++/**+ * The selected template: preview, name with Open, facts, requirements with Install, and its standing in the library+ * and this project. Keep the detail rail mounted across selections to prevent flashing. The narrow layout shows it as+ * a bottom sheet (`WorkflowDetailSheet`).+ */+const INSTALL_HOVER = { opacity: 0.85 } as const;+/** The large preview is wide-only; the expanded sheet's summary carries a small one. */+const THUMBNAIL_SLOT_CSS = { ...WORKFLOW_DETAIL_WIDE_ONLY_CSS, ...WORKFLOW_SILHOUETTE_THUMBNAIL_CSS };type VisibilityState =| { requestId: object; previousItem: WorkflowLibraryListItem; isPublic: boolean; status: 'pending' | 'success' }@@ -86,44 +70,56 @@ type VisibilityState =};export interface WorkflowLibraryDetailPanelProps {- /** Where a card's right-click asked for the actions menu; null while it is closed. */- contextMenuPoint: WorkflowCardMenuAnchor | null;- /** What opened the menu last, kept through its close so focus returns there. */- contextMenuTriggerId: string | null;/** Allows the authenticated owner to change visibility, only on Yours. */canChangeVisibility?: boolean;entry: WorkflowLibraryEntry | null;- /** Hides writes to a public template owned by another account. */- isReadOnly?: boolean;+ /** Shared with the card menus, so one workflow gets one copy per press. */+ duplicateGuard: WorkflowLibraryDuplicateGuard;+ /** Hides writes to bundled templates and to other accounts' (`getLibraryEntryAccess`). */+ isReadOnly: boolean;/** The shell closes the library when a fork takes the user to a new project. */onClose: () => void;- onContextMenuClose: () => void;- onDeleted: () => void;+ /** Receives the deleted workflow's id. */+ onDeleted: (workflowId: string) => void;/** Carries the copy's id so the shell can select it once the list refreshes. */onDuplicated: (workflowId: string) => void;/** Adds the first copy, or asks what to do when the project already holds one. */onOpen: (item: WorkflowLibraryListItem) => void;- onPreview: (entry: WorkflowLibraryEntry) => void;+ /** Enters preview mode on the entry (on a given view, else the last shown); its stage shows loading and unreadable+ * documents too. */+ onPreview: (workflowId: string, view?: WorkflowPreviewView) => void;/** The project's workflows, so the rail can say when opening will ask about existing copies. */projectWorkflows: readonly ProjectWorkflowEntry[];+ /** Preview mode's stepper (`WorkflowDetailSheet`); none outside preview mode. */+ stepper?: WorkflowPreviewStepperProps | null;}-const toFileSlug = (name: string): string => name.trim().replaceAll(/\s+/g, '-').toLowerCase() || 'workflow';--export const WorkflowLibraryDetailPanel = ({+/** One label/value row of a detail rail's facts list. */+export const WorkflowDetailFact = ({ children, label }: { children: ReactNode; label: string }) => (+ <DataList.Item alignItems="center" gap="2" minW="0">+ <DataList.ItemLabel color="fg.muted" flex="0 0 5.5rem" fontSize="xs" minW="0">+ {label}+ </DataList.ItemLabel>+ <DataList.ItemValue flex="1" fontSize="xs" minW="0" overflowWrap="anywhere">+ {children}+ </DataList.ItemValue>+ </DataList.Item>+);++/** Memoised: browsing re-renders the dialog on every range load and enrichment, rarely changing the selection. */+export const WorkflowLibraryDetailPanel = memo(function WorkflowLibraryDetailPanel({canChangeVisibility = false,- contextMenuPoint,- contextMenuTriggerId,+ duplicateGuard,entry,- isReadOnly = false,+ isReadOnly,onClose,- onContextMenuClose,onDeleted,onDuplicated,onOpen,onPreview,projectWorkflows,-}: WorkflowLibraryDetailPanelProps) => {+ stepper,+}: WorkflowLibraryDetailPanelProps) {const panelRef = useRef<HTMLDivElement>(null);// Portaled action menus belong to this dialog's visible bounds, rather than the whole viewport.const menuPositioning = useMemo(@@ -135,14 +131,25 @@ export const WorkflowLibraryDetailPanel = ({const { t } = useTranslation();const deps = useModelRequirementDeps();const notify = useWorkflowNotifications();- const { openDocumentInNewProject } = useWorkflowGraphPreview();const openAddModels = useOpenAddModels();const { installMany } = useInstallActions();- // The name is captured on request: a delete moves the selection, or empties this panel, before the dialog closes.- const [deleteTargetName, setDeleteTargetName] = useState<string | null>(null);- // Guard duplicate creation until the copy exists, including copies landing outside the visible category.- const [isDuplicatePending, setIsDuplicatePending] = useState(false);- const isDuplicatePendingRef = useRef(false);+ // The rail's More and the sheet's More act on the selection; a card's own menu has its own instance.+ const {+ actionItems,+ dialogs,+ open: handleOpen,+ openLabel,+ projectCopies,+ } = useWorkflowLibraryEntryActions({+ duplicateGuard,+ entry,+ isReadOnly,+ projectWorkflows,+ onClose,+ onDeleted,+ onDuplicated,+ onOpen,+ });const [visibilityStates, setVisibilityStates] = useState<Map<string, VisibilityState>>(() => new Map());const visibilityInputRef = useRef<HTMLInputElement>(null);const restoreVisibilityFocus = useRef<string | null>(null);@@ -155,22 +162,25 @@ export const WorkflowLibraryDetailPanel = ({[deps, enrichment]);const installableCount = resolved?.filter((requirement) => requirement.status === 'installable').length ?? 0;-- const hasCopies = useMemo(- () => (entry ? planLibraryWorkflowOpen(projectWorkflows, entry.item.workflow_id).kind === 'choose' : false),- [entry, projectWorkflows]+ const session = useAuthSession();+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const missingNodePacks = useMemo(+ () =>+ enrichment?.status === 'ready' && templatesSnapshot.status === 'loaded'+ ? getMissingNodePacks(enrichment, templatesSnapshot.templates)+ : [],+ [enrichment, templatesSnapshot]);- const handleOpen = useCallback(() => {- if (entry) {- onOpen(entry.item);- }- }, [entry, onOpen]);+ const dataTime = useDataTimeSnapshot(entry?.item);+ const moreActionsIds = useTooltipTriggerIds();- const handlePreview = useCallback(() => {- if (entry && entry.enrichment.status === 'ready') {- onPreview(entry);- }- }, [entry, onPreview]);+ const handlePreview = useCallback(() => entry && onPreview(entry.item.workflow_id), [entry, onPreview]);+ const handlePreviewInputs = useCallback(+ () => entry && onPreview(entry.item.workflow_id, 'inputs'),+ [entry, onPreview]+ );+ const workflowDocument = enrichment?.status === 'ready' ? enrichment.document : null;+ const previewModel = useWorkflowPreviewModel(workflowDocument);// Close the library before navigating to Add Models.const handleFindModel = useCallback(@@ -219,210 +229,6 @@ export const WorkflowLibraryDetailPanel = ({}, [deps, installMany, notify, resolved, t]);const handleInstall = useCallback(() => void install(), [install]);- /** Duplicate the library record directly without loading or modifying the active project graph. */- const duplicate = useCallback(async () => {- if (!entry || isDuplicatePendingRef.current) {- return;- }-- const owner = captureAccountScope();- const { name } = entry.item;-- isDuplicatePendingRef.current = true;- setIsDuplicatePending(true);-- try {- const raw = await getLibraryWorkflowCached(entry.item.workflow_id, {- expectedRevision: entry.item.revision,- signal: owner.signal,- });-- assertAccountScopeCurrent(owner);-- const { id: _id, ...copy } = raw;- const meta = typeof copy.meta === 'object' && copy.meta !== null ? (copy.meta as Record<string, unknown>) : {};- const workflowId = await createLibraryWorkflow(- {- ...copy,- // A copy of a default is still the user's own workflow.- meta: { ...meta, category: 'user' },- name: t('workflowLibrary.duplicateName', { name: name || t('workflowLibrary.untitled') }),- },- owner.signal- );-- assertAccountScopeCurrent(owner);- invalidateWorkflowLibraryCache();- // The copy is forced into the user category, so from the Browse tab it- // lands out of sight — the notice is the only thing that says it worked.- notify.success(t('workflowLibrary.duplicated'));- onDuplicated(workflowId);- } catch (error) {- if (isAccountScopeCurrent(owner)) {- notify.error(t('workflowLibrary.duplicateFailed'), getApiErrorMessage(error, t('common.unknownError')));- }- } finally {- if (isAccountScopeCurrent(owner)) {- isDuplicatePendingRef.current = false;- setIsDuplicatePending(false);- }- }- }, [entry, notify, onDuplicated, t]);- const handleDuplicate = useCallback(() => void duplicate(), [duplicate]);-- const [isRenameOpen, setIsRenameOpen] = useState(false);- const openRename = useCallback(() => setIsRenameOpen(true), []);- const closeRename = useCallback(() => setIsRenameOpen(false), []);- // A rename is a content write at the record's current revision: the live record, never a cached one, is the base.- const submitRename = useCallback(- async (nextName: string) => {- if (!entry || isReadOnly) {- return;- }-- const owner = captureAccountScope();-- try {- const record = await getLibraryWorkflowRecord(entry.item.workflow_id, owner.signal);-- assertAccountScopeCurrent(owner);- await updateLibraryWorkflow(- entry.item.workflow_id,- { ...record.workflow, name: nextName },- { expectedRevision: record.revision, signal: owner.signal }- );- assertAccountScopeCurrent(owner);- invalidateWorkflowLibraryCache(entry.item.workflow_id);- notify.success(t('workflowLibrary.renamed'));- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- notify.error(t('workflowLibrary.renameFailed'), getApiErrorMessage(error, t('common.unknownError')));- // Rejecting keeps the dialog, and the typed name, open for another try.- throw error;- }- },- [entry, isReadOnly, notify, t]- );-- const fork = useCallback(async () => {- if (!entry) {- return;- }-- const owner = captureAccountScope();-- try {- const record = await getLibraryWorkflowRecordCached(entry.item.workflow_id, {- expectedRevision: entry.item.revision,- signal: owner.signal,- });-- assertAccountScopeCurrent(owner);-- const { document } = parseWorkflowJson({ ...record.workflow, id: record.workflow_id });-- // The port creates and activates a fresh project first, so the project- // the library was opened from is left exactly as it was.- openDocumentInNewProject(document, entry.item.name, {- libraryWorkflowId: record.workflow_id,- ...(getWorkflowRecordCategory(record) === 'user' ? { ownerUserId: record.user_id } : {}),- revision: record.revision,- });- onClose();- } catch (error) {- if (isAccountScopeCurrent(owner)) {- notify.error(t('workflowLibrary.loadFailed'), getApiErrorMessage(error, t('common.unknownError')));- }- }- }, [entry, notify, onClose, openDocumentInNewProject, t]);- const handleFork = useCallback(() => void fork(), [fork]);-- const download = useCallback(async () => {- if (!entry) {- return;- }-- const owner = captureAccountScope();-- try {- const raw = await getLibraryWorkflowCached(entry.item.workflow_id, {- expectedRevision: entry.item.revision,- signal: owner.signal,- });-- assertAccountScopeCurrent(owner);- downloadText(JSON.stringify(raw, null, 2), `${toFileSlug(entry.item.name)}.json`, 'application/json');- } catch (error) {- if (isAccountScopeCurrent(owner)) {- notify.error(t('workflowLibrary.loadFailed'), getApiErrorMessage(error, t('common.unknownError')));- }- }- }, [entry, notify, t]);- const handleDownload = useCallback(() => void download(), [download]);-- const openDeleteConfirm = useCallback(() => {- if (entry && !isReadOnly) {- setDeleteTargetName(entry.item.name || t('workflowLibrary.untitled'));- }- }, [entry, isReadOnly, t]);- const closeDeleteConfirm = useCallback(() => setDeleteTargetName(null), []);-- // A pointer point is a fixed rect; the tile button is the menu's trigger, so the menu follows it as it scrolls.- const contextMenuPositioning = useMemo(- () =>- contextMenuPoint?.kind === 'point'- ? {- ...menuPositioning,- getAnchorRect: () => ({ height: 1, width: 1, x: contextMenuPoint.x, y: contextMenuPoint.y }),- placement: 'bottom-start' as const,- }- : { ...menuPositioning, placement: 'bottom-end' as const },- [contextMenuPoint, menuPositioning]- );- const handleContextMenuOpenChange = useCallback(- (event: { open: boolean }) => {- if (!event.open) {- onContextMenuClose();- }- },- [onContextMenuClose]- );- // Focus returns to whatever opened the menu: the title's menu button, or the right-clicked card.- const contextMenuIds = useMemo(- () =>- entry- ? {- content: getWorkflowLibraryCardMenuContentId(entry.item.workflow_id),- trigger: contextMenuTriggerId ?? getWorkflowLibraryCardId(entry.item.workflow_id),- }- : undefined,- [contextMenuTriggerId, entry]- );- const moreActionsIds = useTooltipTriggerIds();-- const confirmDelete = useCallback(async () => {- if (!entry || isReadOnly) {- return;- }-- const owner = captureAccountScope();-- try {- await deleteLibraryWorkflow(entry.item.workflow_id, owner.signal);-- assertAccountScopeCurrent(owner);- invalidateWorkflowLibraryCache();- onDeleted();- } catch (error) {- if (isAccountScopeCurrent(owner)) {- notify.error(t('workflowLibrary.deleteFailed'), getApiErrorMessage(error, t('common.unknownError')));- }- }- }, [entry, isReadOnly, notify, onDeleted, t]);-const item = entry?.item ?? null;const tags = entry?.tags ?? [];const name = item ? item.name || t('workflowLibrary.untitled') : '';@@ -586,152 +392,105 @@ export const WorkflowLibraryDetailPanel = ({},[itemIsPublic, updateVisibility]);- const openLabel = hasCopies ? t('workflowLibrary.openWithEllipsis') : t('workflowLibrary.open');-- // One item set behind both the rail's overflow button and a card's right-click.- const actionItems = (- <>- <MenuActionItem- hint={hasCopies ? t('workflowLibrary.openExistingCopiesHint') : t('workflowLibrary.openHint')}- icon={WorkflowIcon}- label={openLabel}- value="open"- onSelect={handleOpen}- />- <MenuActionItem- hint={t('workflowLibrary.duplicateHint')}- icon={CopyIcon}- isDisabled={isDuplicatePending}- label={t('workflowLibrary.duplicate')}- value="duplicate"- onSelect={handleDuplicate}- />- <MenuActionItem- hint={t('workflowLibrary.forkIntoProjectHint')}- icon={GitForkIcon}- label={t('workflowLibrary.forkIntoProject')}- value="fork-into-project"- onSelect={handleFork}- />- <MenuActionItem- hint={t('workflowLibrary.downloadJsonHint')}- icon={DownloadIcon}- label={t('workflowLibrary.downloadJson')}- value="download-json"- onSelect={handleDownload}- />- {item?.category === 'user' && !isReadOnly ? (- <MenuActionItem- hint={t('workflowLibrary.renameTemplateHint')}- icon={PencilIcon}- label={t('workflowLibrary.renameWithEllipsis')}- value="rename"- onSelect={openRename}- />- ) : null}- {item?.category === 'user' && !isReadOnly ? (- // Bundled defaults are not the account's to delete.- <MenuActionItem- hint={t('workflowLibrary.deleteHint')}- icon={Trash2Icon}- label={t('workflowLibrary.delete')}- tone="danger"- value="delete"- onSelect={openDeleteConfirm}- />- ) : null}- </>- );+ // Visibility only means something to other accounts on a multi-user server.+ const showVisibility = session.multiuserEnabled && item?.category === 'user';+ const primaryBase = enrichment?.status === 'ready' ? enrichment.requirements.primaryBase : null;+ const isCallable = item?.call_saved_workflow_compatibility?.is_callable === true;+ const linkedRevision = projectCopies.length === 1 ? (projectCopies[0]?.source?.revision ?? null) : null;+ const openedWhen = item?.opened_at ? formatTimeSince(item.opened_at, dataTime) : '';+ const updatedWhen = item?.updated_at ? formatTimeSince(item.updated_at, dataTime) : '';+ const createdWhen = item?.created_at ? formatTimeSince(item.created_at, dataTime) : '';++ const readiness =+ enrichment?.status !== 'ready'+ ? null+ : missingNodePacks.length > 0+ ? t('workflowLibrary.nodePacksMissing', { count: missingNodePacks.length })+ : installableCount > 0+ ? t('workflowLibrary.modelsToInstall', { count: installableCount })+ : t('workflowLibrary.readyToRun');+ const summaryFacts = [+ primaryBase ? getModelBaseLabel(primaryBase) : null,+ enrichment?.status === 'ready' ? t('workflowLibrary.nodeCount', { count: enrichment.nodeCount }) : null,+ readiness,+ openedWhen ? t('workflowLibrary.openedWhen', { when: openedWhen }) : null,+ ]+ .filter((fact) => fact !== null)+ .join(' · ');return (<>{item ? (- <Stack- borderColor="border.subtle"- borderWidth="1px"- css={DETAIL_RAIL_CSS}+ <WorkflowDetailSheetref={panelRef}+ actions={actionItems}data-workflow-detail={item.workflow_id}- flexShrink={0}- gap="0"- minH="0"- rounded="md"- w={DETAIL_RAIL_WIDTH}+ facts={summaryFacts}+ menuPositioning={menuPositioning}+ name={name}+ openLabel={openLabel}+ thumbnailSrc={item.thumbnail_url}+ workflowDocument={enrichment?.status === 'ready' ? enrichment.document : null}+ stepper={stepper}+ workflowId={item.workflow_id}+ onOpen={handleOpen}><Scrollable flex="1" label={name} minH="0">- <Stack gap="2" minW="0" p="2.5">- <WorkflowLibraryThumbnail- key={item.workflow_id}- canEdit={item.category === 'user' && !isReadOnly}- item={item}- workflowDocument={enrichment?.status === 'ready' ? enrichment.document : null}- />-- {/*- * Wrap full names, including delimiter-free strings, in the detail rail; zero content min-width permits- * containment without truncation.- */}- <Text fontSize="lg" fontWeight="600" minW="0" overflowWrap="anywhere">- {name}- </Text>-- {item.category === 'user' ? (- <Stack gap="1">- <HStack align="center" justify="space-between" minW="0">- <Text color="fg.muted" fontSize="xs">- {t('workflowLibrary.visibility')}- </Text>- <Badge- data-workflow-visibility={visibilityUnknown ? 'unknown' : itemIsPublic ? 'public' : 'private'}- variant="subtle"- >- {t(- visibilityUnknown- ? 'workflowLibrary.visibilityUnknown'- : itemIsPublic- ? 'workflowLibrary.public'- : 'workflowLibrary.private'- )}- </Badge>- </HStack>- {canChangeVisibility && !visibilityUnknown ? (- <Stack gap="1">- <Switch.Root- checked={itemIsPublic === true}- colorPalette="accent"- disabled={isVisibilityPending || visibilityUnknown}- readOnly- >- <Switch.HiddenInput- key={itemIsPublic ? 'public' : 'private'}- onClick={handleVisibilityClick}- ref={visibilityInputRef}- />- <Switch.Control>- <Switch.Thumb />- </Switch.Control>- <Switch.Label srOnly>{t('workflowLibrary.publicWorkflow')}</Switch.Label>- </Switch.Root>- <Text color="fg.subtle" fontSize="xs">- {t('workflowLibrary.publicVisibilityHelp')}- </Text>- </Stack>+ <Stack gap="2.5" minW="0" p="2.5">+ {/* The expanded sheet's summary is its compact heading: no large preview, no second name. */}+ <Box css={THUMBNAIL_SLOT_CSS} w="full">+ <WorkflowLibraryThumbnail+ key={item.workflow_id}+ canEdit={!isReadOnly}+ item={item}+ workflowDocument={workflowDocument}+ onPreview={handlePreview}+ />+ </Box>++ <Stack css={WORKFLOW_DETAIL_WIDE_ONLY_CSS} gap="0.5" minW="0">+ {/*+ * Wrap full names, including delimiter-free strings, in the detail rail; zero content min-width+ * permits containment without truncation.+ */}+ <Text fontSize="lg" fontWeight="600" minW="0" overflowWrap="anywhere">+ {name}+ </Text>+ <WorkflowProvenance+ document={workflowDocument}+ kind={t(+ item.category === 'default'+ ? 'workflowLibrary.preview.kindTemplate'+ : isReadOnly+ ? 'workflowLibrary.preview.kindShared'+ : 'workflowLibrary.preview.kindLibrary'+ )}+ />+ {openedWhen ? (+ <Text color="fg.muted" fontSize="xs">+ {t('workflowLibrary.openedWhen', { when: openedWhen })}+ </Text>+ ) : null}+ </Stack>++ {primaryBase || enrichment?.status === 'ready' || isCallable || missingNodePacks.length > 0 ? (+ <HStack flexWrap="wrap" gap="1" minW="0">+ {primaryBase ? <Badge variant="subtle">{getModelBaseLabel(primaryBase)}</Badge> : null}+ {enrichment?.status === 'ready' ? (+ <Badge variant="subtle">{t('workflowLibrary.nodeCount', { count: enrichment.nodeCount })}</Badge>) : null}- {visibilityError ? (- <Text color="fg.error" fontSize="xs" role="alert">- {t('workflowLibrary.visibilityUpdateFailed')}: {visibilityError}- </Text>+ <WorkflowInputsBadge model={previewModel} />+ {isCallable ? (+ <Badge data-workflow-callable variant="subtle">+ {t('workflowLibrary.callable')}+ </Badge>) : null}- {visibilityUnknown ? (- <Button- size="xs"- disabled={visibilityState?.status === 'reconciling'}- onClick={handleRetryVisibilityRead}- >- {t('workflowLibrary.retry')}- </Button>+ {missingNodePacks.length > 0 ? (+ <Badge bg="bg.error" color="fg.error" data-workflow-missing-node-packs variant="subtle">+ {t('workflowLibrary.nodePacksMissing', { count: missingNodePacks.length })}+ </Badge>) : null}- </Stack>+ </HStack>) : null}{item.description ? (@@ -743,41 +502,130 @@ export const WorkflowLibraryDetailPanel = ({{tags.length > 0 ? (<HStack flexWrap="wrap" gap="1" minW="0">{tags.map((tag) => (- <Badge key={tag} variant="subtle">+ <Badge key={tag} variant="outline">{tag}</Badge>))}</HStack>) : null}+ <WorkflowInputsSummary model={previewModel} onSeeAll={handlePreviewInputs} />+ <WorkflowAuthorNotes notes={workflowDocument?.notes ?? ''} />+ <WorkflowMissingNodePacks packs={missingNodePacks} /><WorkflowRequirementsListerrorMessage={enrichment?.status === 'error' ? enrichment.message : null}resolved={resolved}onFindModel={handleFindModel}/>- </Stack>- </Scrollable>-- <Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" p="2.5">- <HStack gap="2" minW="0">{installableCount > 0 ? (- <Button- bg="bg.warning"- color="fg.warning"- flex="1"- minW="0"- size="lg"- _hover={INSTALL_HOVER}- onClick={handleInstall}- >+ <Button bg="bg.warning" color="fg.warning" size="sm" _hover={INSTALL_HOVER} onClick={handleInstall}>+ <DownloadIcon />{t('workflowLibrary.installModels', { count: installableCount })}</Button>- ) : (- <Button flex="1" minW="0" size="lg" onClick={handleOpen}>- {openLabel}- </Button>- )}- <Menu.Root ids={moreActionsIds} positioning={menuPositioning}>+ ) : null}++ <DataList.Root data-workflow-detail-facts gap="1.5" orientation="horizontal">+ <WorkflowDetailFact label={t('workflowLibrary.factInProject')}>+ {projectCopies.length === 0+ ? t('workflowLibrary.projectCopiesNone')+ : linkedRevision !== null+ ? t('workflowLibrary.projectCopyRevision', { count: 1, revision: linkedRevision })+ : t('workflowLibrary.projectCopies', { count: projectCopies.length })}+ </WorkflowDetailFact>+ {updatedWhen ? (+ <WorkflowDetailFact label={t('workflowLibrary.factUpdated')}>+ {t('workflowLibrary.whenAtRevision', { revision: item.revision, when: updatedWhen })}+ </WorkflowDetailFact>+ ) : null}+ {createdWhen ? (+ <WorkflowDetailFact label={t('workflowLibrary.factCreated')}>{createdWhen}</WorkflowDetailFact>+ ) : null}+ {showVisibility ? (+ <WorkflowDetailFact label={t('workflowLibrary.visibility')}>+ <HStack gap="2" justify="space-between" minW="0" w="full">+ <Text+ data-workflow-visibility={visibilityUnknown ? 'unknown' : itemIsPublic ? 'public' : 'private'}+ >+ {t(+ visibilityUnknown+ ? 'workflowLibrary.visibilityUnknown'+ : itemIsPublic+ ? 'workflowLibrary.public'+ : 'workflowLibrary.private'+ )}+ </Text>+ {canChangeVisibility && !visibilityUnknown ? (+ <Switch.Root+ checked={itemIsPublic === true}+ colorPalette="accent"+ disabled={isVisibilityPending || visibilityUnknown}+ readOnly+ >+ <Switch.HiddenInput+ key={itemIsPublic ? 'public' : 'private'}+ onClick={handleVisibilityClick}+ ref={visibilityInputRef}+ />+ <Switch.Control>+ <Switch.Thumb />+ </Switch.Control>+ <Switch.Label srOnly>{t('workflowLibrary.publicWorkflow')}</Switch.Label>+ </Switch.Root>+ ) : null}+ </HStack>+ </WorkflowDetailFact>+ ) : null}+ </DataList.Root>+ {showVisibility ? (+ <Stack gap="1">+ {canChangeVisibility && !visibilityUnknown ? (+ <Text color="fg.muted" fontSize="xs">+ {t('workflowLibrary.publicVisibilityHelp')}+ </Text>+ ) : null}+ {visibilityError ? (+ <Text color="fg.error" fontSize="xs" role="alert">+ {t('workflowLibrary.visibilityUpdateFailed')}: {visibilityError}+ </Text>+ ) : null}+ {visibilityUnknown ? (+ <Button+ size="xs"+ disabled={visibilityState?.status === 'reconciling'}+ onClick={handleRetryVisibilityRead}+ >+ {t('workflowLibrary.retry')}+ </Button>+ ) : null}+ </Stack>+ ) : null}+ </Stack>+ </Scrollable>++ {/* The pinned footer ends in the primary action, as a picker's commit button; the narrow sheet's summary+ carries Open and More instead. */}+ <Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" minW="0" p="2.5">+ <Button+ css={WORKFLOW_PREVIEW_TRIGGER_CSS}+ data-workflow-preview-trigger=""+ minW="0"+ size="lg"+ variant="outline"+ w="full"+ onClick={handlePreview}+ >+ <WorkflowIcon />+ {t('workflowLibrary.preview.action')}+ </Button>+ <HStack css={WORKFLOW_DETAIL_WIDE_ONLY_CSS} gap="2" minW="0">+ <Button data-workflow-detail-open flex="1" minW="0" size="lg" onClick={handleOpen}>+ {openLabel}+ </Button>+ <Menu.Root+ ids={moreActionsIds}+ positioning={menuPositioning}+ onRequestDismiss={keepMenuOpenWhenSiblingMenuCloses}+ >{/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, themenu never takes focus and the first pointer move onto it closes it. */}<Menu.Trigger asChild>@@ -789,77 +637,20 @@ export const WorkflowLibraryDetailPanel = ({</Menu.Trigger><Portal><Menu.Positioner>- <MenuContent minW="min(16rem, var(--available-width))" maxW="var(--available-width)">+ <MenuContent minW="min(13rem, var(--available-width))" maxW="var(--available-width)">{actionItems}</MenuContent></Menu.Positioner></Portal></Menu.Root></HStack>- <Button- disabled={enrichment?.status !== 'ready'}- size="lg"- variant="outline"- w="full"- onClick={handlePreview}- >- <WorkflowIcon />- {t('workflowLibrary.previewGraph')}- </Button></Stack>-- {/* Naming the card as the trigger makes this a nested layer of the dialog: the- dialog's focus trap then lets the menu keep focus, and closing returns it to the card. */}- <Menu.Root- ids={contextMenuIds}- open={contextMenuPoint !== null}- positioning={contextMenuPositioning}- onOpenChange={handleContextMenuOpenChange}- onPointerDownOutside={keepCardMenuOpenForRetarget}- >- <Portal>- <Menu.Positioner>- <MenuContent- data-workflow-context-menu- minW="min(16rem, var(--available-width))"- maxW="var(--available-width)"- >- {actionItems}- </MenuContent>- </Menu.Positioner>- </Portal>- </Menu.Root>-- <RenameDialog- initialName={name}- isOpen={isRenameOpen && !isReadOnly}- label={t('workflowLibrary.templateName')}- submitLabel={t('workflowLibrary.rename')}- title={t('workflowLibrary.renameTemplateTitle')}- onClose={closeRename}- onSubmit={submitRename}- />- </Stack>+ </WorkflowDetailSheet>) : (- <Box- css={DETAIL_RAIL_CSS}- borderColor="border.subtle"- borderWidth="1px"- flexShrink={0}- minH="0"- rounded="md"- w={DETAIL_RAIL_WIDTH}- />+ <WorkflowDetailRailPlaceholder />)}- {/* Outside the rail: a delete empties or retargets it while this dialog animates out. */}- <ConfirmDialog- body={t('workflowLibrary.deleteConfirmBody', { name: deleteTargetName ?? '' })}- confirmLabel={t('workflowLibrary.delete')}- isOpen={deleteTargetName !== null && !isReadOnly}- title={t('workflowLibrary.deleteConfirmTitle')}- onClose={closeDeleteConfirm}- onConfirm={confirmDelete}- />+ {/* Outside the rail: a delete empties or retargets it while its confirmation animates out. */}+ {dialogs}</>);-};+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsxindex e0f915aa5d..63752ed7f9 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx@@ -1,10 +1,13 @@import type { StarterModel } from '@features/models';import type { WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';import type {+ FieldInputTemplate,InvocationTemplate,InvocationTemplatesSnapshot,ProjectGraphState,ProjectWorkflowEntry,+ WorkflowEdge,+ WorkflowInvocationNode,} from '@features/workflow/core/types';import type * as libraryBrowseStoreModule from '@features/workflow/data/libraryBrowseStore';import type {@@ -12,6 +15,7 @@ import type {WorkflowLibraryEntry,WorkflowLibraryEntryEnrichment,} from '@features/workflow/data/libraryBrowseStore';+import type * as workflowQueriesModule from '@features/workflow/queries';import type {WorkflowGraphPreviewPort,WorkflowPreferences,@@ -21,27 +25,44 @@ import type {import { ChakraProvider } from '@chakra-ui/react';import { GalleryHostProvider, type GalleryHost } from '@features/gallery/picker';+import extendVideo from '@features/workflow/core/fixtures/extend-video-ltx2.json';+import { buildWorkflowPreviewModel } from '@features/workflow/core/workflowPreview';import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';import {openWorkflowLibraryAtProjectWorkflow,setWorkflowLibraryOpen,+ setWorkflowLibrarySearch,setWorkflowLibraryTab,workflowUiStore,} from '@features/workflow/ui/workflowUiStore';-import { buildInvocationNode, createProjectGraph, projectGraphReducer } from '@features/workflow/utility';+import {+ buildInvocationNode,+ createProjectGraph,+ parseWorkflowJson,+ projectGraphReducer,+ serializeWorkflowJson,+} from '@features/workflow/utility';+import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';import { settleAnimations } from '@platform/browser/settleAnimations.testing';import { accountLifecycle } from '@platform/state/accountLifecycle';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';import { act, StrictMode } from 'react';import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';+import { afterEach, beforeAll, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';import { page, userEvent } from 'vitest/browser';-// Warm the mocked lazy module to avoid first-compile timing variability in preview wiring tests.-import '@features/workflow/ui/graph-preview/GraphPreviewDialog';import { LibraryCopyChoiceHost } from './LibraryCopyChoiceDialog';+import { loadGraphPreview } from './libraryPreviewSource';+import { keepCardMenuOpenForRetarget } from './WorkflowLibraryCard';import { WorkflowLibraryDialog } from './WorkflowLibraryDialog';+/** Zag selects only the highlighted item, so a menu item takes a real pointer click, which hovers it first. */+const selectMenuItem = async (item: HTMLElement | null | undefined) => {+ expect(item, 'no such menu item').toBeTruthy();+ await act(() => userEvent.click(item!));+};+/** In the app the workbench derives this from its Gallery adapter; the library's thumbnail slot reads it. */const GALLERY_HOST: GalleryHost = {galleryValues: {},@@ -66,12 +87,70 @@ const PREVIEW_NODE_TEMPLATE: InvocationTemplate = {version: '1.0.0',};+const previewField = (+ name: string,+ typeName: string,+ overrides: Partial<FieldInputTemplate> = {}+): FieldInputTemplate => ({+ description: '',+ exclusiveMaximum: null,+ exclusiveMinimum: null,+ fieldKind: 'input',+ input: 'any',+ maximum: null,+ minimum: null,+ multipleOf: null,+ name,+ options: null,+ required: false,+ title: name.replace(/^./, (letter) => letter.toUpperCase()).replaceAll('_', ' '),+ type: { batch: false, cardinality: 'SINGLE', name: typeName },+ uiChoiceLabels: null,+ uiComponent: null,+ uiHidden: false,+ uiModelBase: null,+ uiModelFormat: null,+ uiModelType: null,+ uiOrder: null,+ ...overrides,+});+const previewTemplate = (type: string, title: string, inputs: FieldInputTemplate[]): InvocationTemplate => ({+ ...PREVIEW_NODE_TEMPLATE,+ inputs: Object.fromEntries(inputs.map((input) => [input.name, input])),+ outputType: `${type}_output`,+ title,+ type,+});++/** The node types the graph preview fixtures use; `mask_refine` stays unknown, as a missing node pack's would. */+const GRAPH_TEMPLATES: Record<string, InvocationTemplate> = {+ collect: previewTemplate('collect', 'Collect', [previewField('item', 'AnyField')]),+ denoise_latents: previewTemplate('denoise_latents', 'Denoise Latents', [+ previewField('steps', 'IntegerField'),+ previewField('cfg_scale', 'FloatField'),+ previewField('positive', 'ConditioningField'),+ previewField('unet', 'UNetField'),+ ]),+ l2i: previewTemplate('l2i', 'Latents to Image', [previewField('latents', 'LatentsField')]),+ main_model_loader: previewTemplate('main_model_loader', 'Main Model', [+ previewField('model', 'ModelIdentifierField', { required: true, uiModelBase: ['flux'], uiModelType: ['main'] }),+ ]),+ string: previewTemplate('string', 'String Primitive', [previewField('value', 'StringField')]),+};++/** The node templates the dialog reads; a test that previews a real template swaps in that template's set. */+const templatesState = vi.hoisted(() => ({ current: null as unknown as InvocationTemplatesSnapshot }));const TEMPLATES_SNAPSHOT: InvocationTemplatesSnapshot = {error: null,status: 'loaded',- templates: { integer: PREVIEW_NODE_TEMPLATE },+ templates: { integer: PREVIEW_NODE_TEMPLATE, ...GRAPH_TEMPLATES },};+beforeEach(() => {+ templatesState.current = TEMPLATES_SNAPSHOT;+ installs.active = new Set();+});+const identity = vi.hoisted(() => ({session: { multiuserEnabled: false, phase: 'ready', user: null } as {multiuserEnabled: boolean;@@ -82,52 +161,70 @@ const identity = vi.hoisted(() => ({vi.mock('@features/workflow/react', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),- useInvocationTemplatesSnapshot: () => TEMPLATES_SNAPSHOT,+ useInvocationTemplatesSnapshot: () => templatesState.current,}));-vi.mock('@features/identity', async (importOriginal) => ({+/** The library templates the project rail reads by id; an absent id fails as a missing record does. */+const templateRecords = vi.hoisted(() => new Map<string, { name: string; revision: number }>());++/** The library writes a card menu's Rename and Delete make; each answers as the server would. */+const libraryWrites = vi.hoisted(() => ({+ cached: vi.fn((workflowId: string, _options: { expectedRevision: number }) =>+ Promise.resolve({ id: workflowId, meta: { category: 'user' }, name: workflowId })+ ),+ create: vi.fn((_workflow: { name: string }, _signal?: AbortSignal) => Promise.resolve('wf-landscape-copy')),+ delete: vi.fn((_workflowId: string, _signal?: AbortSignal) => Promise.resolve()),+ record: vi.fn((workflowId: string, _signal?: AbortSignal) =>+ Promise.resolve({ revision: 3, workflow: { id: workflowId, name: workflowId }, workflow_id: workflowId })+ ),+ update: vi.fn((_workflowId: string, _workflow: { name: string }, _options: { expectedRevision: number }) =>+ Promise.resolve()+ ),+}));++vi.mock('@features/workflow/queries', async (importOriginal) => {+ const original = await importOriginal<typeof workflowQueriesModule>();++ return {+ ...original,+ createLibraryWorkflow: libraryWrites.create,+ deleteLibraryWorkflow: libraryWrites.delete,+ getLibraryWorkflowCached: libraryWrites.cached,+ getLibraryWorkflowRecord: libraryWrites.record,+ invalidateWorkflowLibraryCache: vi.fn(),+ updateLibraryWorkflow: libraryWrites.update,+ savedWorkflowDetailQueryOptions: (workflowId: string) => ({+ ...original.savedWorkflowDetailQueryOptions(workflowId),+ queryFn: () => {+ const record = templateRecords.get(workflowId);++ return record+ ? Promise.resolve(record as unknown as workflowQueriesModule.WorkflowRecordDTO)+ : Promise.reject(new Error('not found'));+ },+ }),+ };+});++/** The preview's Download workflow JSON; the editor's serializer is real. */+const downloads = vi.hoisted(() => ({ downloadText: vi.fn((_text: string, _name: string, _type: string) => {}) }));++vi.mock('@platform/browser/downloadBlob', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),- useAuthSession: () => identity.session,+ downloadText: downloads.downloadText,}));-// Stub preview rendering while exposing compiled graph, hideInvoke, and close behavior owned by dialog wiring.-vi.mock('@features/workflow/ui/graph-preview/GraphPreviewDialog', () => ({- GraphPreviewDialog: ({- graphId,- hideInvoke,- isOpen,- source,- sourceLabel,- onExitComplete,- onOpenChange,- }: {- graphId: string;- hideInvoke?: boolean;- isOpen: boolean;- source: { graph: { nodes: { id: string; type: string }[] } | null };- sourceLabel: string;- onExitComplete?: () => void;- onOpenChange: (isOpen: boolean) => void;- }) => (- <div- data-graph-id={graphId}- data-hide-invoke={String(hideInvoke)}- data-preview-dialog- data-preview-open={String(isOpen)}- data-source-label={sourceLabel}- >- {(source.graph?.nodes ?? []).map((node) => node.type).join(',')}- <button onClick={() => onOpenChange(false)}>Close preview</button>- {/* Stands in for Ark's presence machine: the real dialog reports the end- of its close transition, which is what releases the mount. */}- <button onClick={() => onExitComplete?.()}>Finish preview exit</button>- </div>- ),+vi.mock('@features/identity', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useAuthSession: () => identity.session,}));// Drive a real external browse store to retain subscription and selector behavior while spying on commands.const browse = vi.hoisted(() => ({- ensureWorkflowLibraryBrowseLoaded: vi.fn(() => Promise.resolve()),+ ensureWorkflowLibraryBrowseLoaded: vi.fn((_opening: Partial<WorkflowLibraryBrowseSnapshot['filter']>) =>+ Promise.resolve()+ ),+ loadWorkflowLibraryPlaceTotals: vi.fn((_places: readonly string[]) => Promise.resolve()),// Assigned by the module factory below, which owns the store instance.getSnapshot: null as null | (() => WorkflowLibraryBrowseSnapshot),loadWorkflowLibraryRange: vi.fn((_start: number, _end: number) => Promise.resolve(true)),@@ -136,28 +233,41 @@ const browse = vi.hoisted(() => ({}));vi.mock('@features/workflow/data/libraryBrowseStore', async (original) => {- const { selectWorkflowLibraryEntry } = await original<typeof libraryBrowseStoreModule>();+ const {+ getWorkflowLibraryOrder,+ getWorkflowLibrarySortDefaultDirection,+ selectWorkflowLibraryEntry,+ WORKFLOW_LIBRARY_ENRICHMENT_DEMAND,+ WORKFLOW_LIBRARY_METADATA_WINDOW,+ } = await original<typeof libraryBrowseStoreModule>();const { createExternalStore } = await import('@platform/state/externalStore');const store = createExternalStore<WorkflowLibraryBrowseSnapshot>({entries: [],error: null,- filter: { category: 'user', search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'user', search: '', sort: 'updated', tags: [] },page: 0,pages: 0,status: 'idle',tagCounts: [],total: 0,- userTotal: null,+ placeTotals: {},});browse.getSnapshot = store.getSnapshot;browse.setSnapshot = store.setSnapshot;return {+ getWorkflowLibraryOrder,+ getWorkflowLibrarySortDefaultDirection,+ holdWorkflowLibraryBrowse: () => () => {},selectWorkflowLibraryEntry,+ WORKFLOW_LIBRARY_ENRICHMENT_DEMAND,+ WORKFLOW_LIBRARY_METADATA_WINDOW,ensureWorkflowLibraryBrowseLoaded: browse.ensureWorkflowLibraryBrowseLoaded,+ loadWorkflowLibraryPlaceTotals: browse.loadWorkflowLibraryPlaceTotals,getWorkflowLibraryBrowseSnapshot: store.getSnapshot,loadWorkflowLibraryRange: browse.loadWorkflowLibraryRange,+ refreshWorkflowLibraryBrowse: vi.fn(() => Promise.resolve()),rememberWorkflowLibraryScroll: vi.fn(),setWorkflowLibraryVisibleDemand: vi.fn(),setWorkflowLibrarySelectedDemand: vi.fn(),@@ -170,14 +280,23 @@ vi.mock('@features/workflow/data/libraryBrowseStore', async (original) => {const loader = vi.hoisted(() => ({open: vi.fn((_item: unknown, _mode: 'first-copy' | 'add-copy') => Promise.resolve()),phase: { current: 'idle' as 'applying' | 'fetching' | 'idle' },+ replace: vi.fn((_item: unknown, _workflowId: string) => Promise.resolve()),resume: vi.fn((_workflowId: string) => {}),}));vi.mock('./useOpenLibraryWorkflow', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),- useOpenLibraryWorkflow: () => ({ loadPhase: loader.phase.current, open: loader.open, resume: loader.resume }),+ useOpenLibraryWorkflow: () => ({+ loadPhase: loader.phase.current,+ open: loader.open,+ replace: loader.replace,+ resume: loader.resume,+ }),}));+/** Install sources the model store reports as downloading; empty unless a test starts one. */+const installs = vi.hoisted(() => ({ active: new Set<string>() }));+// Use fixed model-store data so missing-model badges test dialog wiring rather than live catalogs.const FLUX_STARTER: StarterModel = {base: 'flux',@@ -192,7 +311,7 @@ vi.mock('@features/models', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),ensureModelsLoaded: vi.fn(() => Promise.resolve()),ensureStartersLoaded: vi.fn(),- useActiveInstallSources: () => new Set<string>(),+ useActiveInstallSources: () => installs.active,useInstallActions: () => ({ install: vi.fn(), installMany: vi.fn(), pendingSources: new Set() }),useModelsSelector: (selector: (snapshot: unknown) => unknown) => selector({ models: [] }),useStartersSelector: (selector: (snapshot: unknown) => unknown) =>@@ -201,27 +320,13 @@ vi.mock('@features/models', async (importOriginal) => ({// Provide English/plural strings without booting the HTTP-backed i18n client.const TRANSLATIONS: Record<string, string> = {- 'workflowLibrary.openProjectWorkflowHint': 'Makes it the active workflow',- 'workflowLibrary.renameProjectWorkflowHint': 'Changes its name in this project; a linked template keeps its own',- 'workflowLibrary.duplicateProjectWorkflowHint': 'A copy beside it in this project',- 'workflowLibrary.saveToLibraryHint': 'Creates a new template from this workflow',- 'workflowLibrary.updateTemplateHint': 'Writes this workflow over its library template',- 'workflowLibrary.removeHint': 'Removes it from this project only',- 'workflowLibrary.renameTemplateHint': "Changes the template's name in the library",- 'workflowLibrary.duplicateHint': 'Saves a copy under Yours, original untouched',- 'workflowLibrary.downloadJsonHint': 'For bug reports and sharing',- 'workflowLibrary.forkIntoProjectHint': 'Copies it into a new project',- 'workflowLibrary.deleteHint': 'Removes it from your library',-+ 'common.cancel': 'Cancel','common.close': 'Close','workflowLibrary.activeWorkflow': 'Active',- 'workflowLibrary.addAnotherCopy': 'Add another copy',- 'workflowLibrary.addAnotherCopyHint': 'A second, independent copy in this project',- 'workflowLibrary.chooseProjectCopy': 'Open which copy?',- 'workflowLibrary.allTag': 'All','workflowLibrary.applying': 'Applying workflow…',- 'workflowLibrary.browse': 'Browse','workflowLibrary.delete': 'Delete',+ 'workflowLibrary.deleteConfirmBody': 'Delete "{{name}}" from the workflow library? This cannot be undone.',+ 'workflowLibrary.deleteConfirmTitle': 'Delete workflow','workflowLibrary.downloadJson': 'Download JSON','workflowLibrary.duplicate': 'Duplicate','workflowLibrary.duplicateName': '{{name}} copy',@@ -237,15 +342,11 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.nodeCount_other': '{{count}} nodes','workflowLibrary.notRunYet': 'Not run yet','workflowLibrary.open': 'Open',- 'workflowLibrary.openHint': 'Adds a copy to this project','workflowLibrary.openWithEllipsis': 'Open…',- 'workflowLibrary.previewGraph': 'Preview graph','workflowLibrary.private': 'Private','workflowLibrary.public': 'Public','workflowLibrary.publicWorkflow': 'Public workflow','workflowLibrary.visibilityUpdateFailed': 'Failed to update workflow visibility',- 'workflowLibrary.projectWorkflowCount_one': '{{count}} workflow in this project',- 'workflowLibrary.projectWorkflowCount_other': '{{count}} workflows in this project','workflowLibrary.remove': 'Remove','workflowLibrary.removeConfirmBody':'Remove "{{name}}" from this project? Its library template, if any, is not affected.',@@ -267,18 +368,161 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.sourceBundled': 'From a bundled template (read-only)','workflowLibrary.sourceNone': 'Not linked to a library template','workflowLibrary.sourceRevision': 'Linked to library template at revision {{revision}}',- 'workflowLibrary.shared': 'Shared',- 'workflowLibrary.thisProject': 'This project','workflowLibrary.thumbnailFit': 'Thumbnail display','workflowLibrary.thumbnailFitContain': 'Fit','workflowLibrary.thumbnailFitCover': 'Fill','workflowLibrary.thisProjectHint':'Workflows saved with this project. Edits autosave here; the library changes only when you save to it.','workflowLibrary.title': 'Workflows',+ 'workflowLibrary.cardSize': 'Card size',+ 'workflowLibrary.cardSizeLarge': 'Large cards',+ 'workflowLibrary.cardSizeSmall': 'Small cards',+ 'workflowLibrary.clearTags': 'Clear',+ 'workflowLibrary.emptyRecent': 'Nothing opened yet. Workflows you open from My library or Templates appear here.',+ 'workflowLibrary.emptyShared': 'Nothing shared yet. Public workflows on this server appear here.',+ 'workflowLibrary.emptyUser': 'No saved workflows yet. Use Save to library… in the editor to keep one here.',+ 'workflowLibrary.placeDefault': 'Templates',+ 'workflowLibrary.placeProject': 'In this project',+ 'workflowLibrary.placeRecent': 'Recent',+ 'workflowLibrary.placeShared': 'Shared with me',+ 'workflowLibrary.placeUser': 'My library',+ 'workflowLibrary.places': 'Places',+ 'workflowLibrary.resultCount_one': '{{count}} workflow',+ 'workflowLibrary.resultCount_other': '{{count}} workflows',+ 'workflowLibrary.resultCountWithTags_one': '{{count}} workflow · {{tags}}',+ 'workflowLibrary.resultCountWithTags_other': '{{count}} workflows · {{tags}}',+ 'workflowLibrary.sortAToZ': 'A to Z',+ 'workflowLibrary.sortControl': 'Sort: {{sort}}, {{direction}}',+ 'workflowLibrary.sortFirstToLast': 'First to last',+ 'workflowLibrary.sortLastRun': 'Last run',+ 'workflowLibrary.sortLastToFirst': 'Last to first',+ 'workflowLibrary.sortNewestFirst': 'Newest first',+ 'workflowLibrary.sortOldestFirst': 'Oldest first',+ 'workflowLibrary.sortProjectOrder': 'Project order',+ 'workflowLibrary.sortZToA': 'Z to A',+ 'workflowLibrary.tags': 'Tags',+ 'workflowLibrary.tagsAnyHint': 'Showing workflows with any checked tag',+ 'workflowLibrary.viewOptions': 'View options',+ 'workflowLibrary.layoutGroup': 'View',+ 'workflowLibrary.layoutGrid': 'Grid',+ 'workflowLibrary.layoutList': 'List','workflowLibrary.untitled': 'Untitled Workflow','workflowLibrary.updateTemplate': 'Update library template','workflowLibrary.workflowName': 'Workflow name',- 'workflowLibrary.yours': 'Yours',+ 'workflowLibrary.activeRanWhen': 'Active workflow · ran {{when}}',+ 'workflowLibrary.activeWorkflowLine': 'Active workflow',+ 'workflowLibrary.callable': 'Callable',+ 'workflowLibrary.factCreated': 'Created',+ 'workflowLibrary.factEdited': 'Edited',+ 'workflowLibrary.factInProject': 'In this project',+ 'workflowLibrary.factLastRun': 'Last run',+ 'workflowLibrary.factUpdated': 'Updated',+ 'workflowLibrary.inProject': 'In project',+ 'workflowLibrary.linkedTemplate': 'Linked template',+ 'workflowLibrary.modelsToInstall_one': '{{count}} model to install',+ 'workflowLibrary.modelsToInstall_other': '{{count}} models to install',+ 'workflowLibrary.nodePacksMissing_one': '{{count}} node pack missing',+ 'workflowLibrary.nodePacksMissing_other': '{{count}} node packs missing',+ 'workflowLibrary.openedWhen': 'Opened {{when}}',+ 'workflowLibrary.projectCopies_one': '{{count}} copy',+ 'workflowLibrary.projectCopies_other': '{{count}} copies',+ 'workflowLibrary.projectCopiesNone': 'None',+ 'workflowLibrary.projectCopyRevision_one': '{{count}} copy · revision {{revision}}',+ 'workflowLibrary.ranWhen': 'Ran {{when}}',+ 'workflowLibrary.readyToRun': 'Ready to run',+ 'workflowLibrary.templateNewer': 'Template is newer',+ 'workflowLibrary.templateRevision': 'Library template is at revision {{revision}}',+ 'workflowLibrary.updateFromTemplate': 'Update from template',+ 'workflowLibrary.updateFromTemplateBody': 'Replace "{{name}}" with the library template’s current version?',+ 'workflowLibrary.updateFromTemplateConfirm': 'Update',+ 'workflowLibrary.updatedFromTemplate': 'Updated from template',+ 'workflowLibrary.whenAtRevision': '{{when}} · revision {{revision}}',+ 'workflowLibrary.detailsAndRequirements': 'Details and requirements',+ 'workflowLibrary.hideDetails': 'Hide details',+ 'workflowLibrary.sortAndViewOptions': 'Sort and view options',+ 'workflowLibrary.sortDirectionGroup': 'Direction',+ 'workflowLibrary.missingNodePackNames_one': 'Missing node pack: {{packs}}',+ 'workflowLibrary.missingNodePackNames_other': 'Missing node packs: {{packs}}',+ 'workflowLibrary.sourceNamedRevision': 'Linked to {{name}}, revision {{revision}}',+ 'graphPreview.nodeSummary.denoise_one': '{{count}} step · cfg {{cfg}}',+ 'graphPreview.nodeSummary.denoise_other': '{{count}} steps · cfg {{cfg}}',+ 'workflowLibrary.preview.action': 'Preview',+ 'workflowLibrary.preview.actionHint': 'Preview',+ 'workflowLibrary.preview.atFirst': 'This is the first workflow here',+ 'workflowLibrary.preview.atLast': 'This is the last workflow here',+ 'workflowLibrary.preview.backTo': 'Back to {{place}}',+ 'workflowLibrary.preview.copyJson': 'Copy workflow JSON',+ 'workflowLibrary.preview.downloadJson': 'Download workflow JSON',+ 'workflowLibrary.preview.edgeLabel': '{{source}} to {{target}}',+ 'workflowLibrary.preview.exportMenu': 'Export',+ 'workflowLibrary.preview.find': 'Find a node',+ 'workflowLibrary.preview.findMatches_one': '{{count}} match',+ 'workflowLibrary.preview.findMatches_other': '{{count}} matches',+ 'workflowLibrary.preview.findNone': 'No matches',+ 'workflowLibrary.preview.fit': 'Fit',+ 'workflowLibrary.preview.from': 'From',+ 'workflowLibrary.preview.helpersFolded_one': '{{count}} helper folded',+ 'workflowLibrary.preview.helpersFolded_other': '{{count}} helpers folded',+ 'workflowLibrary.preview.legend': 'Markers',+ 'workflowLibrary.preview.loading': 'Loading workflow…',+ 'workflowLibrary.preview.minimap': 'Minimap',+ 'workflowLibrary.preview.needsModel': 'Needs a model',+ 'workflowLibrary.preview.needsModelInline': 'needs a model',+ 'workflowLibrary.preview.needsModelNote': "Needs a model that isn't installed",+ 'workflowLibrary.preview.next': 'Next workflow',+ 'workflowLibrary.preview.nodePackMissing': 'Node pack missing',+ 'workflowLibrary.preview.position': '{{position}} of {{total}}',+ 'workflowLibrary.preview.previous': 'Previous workflow',+ 'workflowLibrary.preview.region': 'Preview of {{name}}',+ 'workflowLibrary.preview.result': 'Result',+ 'workflowLibrary.preview.resultInline': 'result',+ 'workflowLibrary.preview.showAll': 'Show all {{count}}',+ 'workflowLibrary.preview.showingAll_other': 'Showing all {{count}} nodes, as drawn',+ 'workflowLibrary.preview.showingNodes_one': 'Showing {{shown}} of {{count}} node',+ 'workflowLibrary.preview.showingNodes_other': 'Showing {{shown}} of {{count}} nodes',+ 'workflowLibrary.preview.simplify': 'Simplify',+ 'workflowLibrary.preview.stepper': 'Step through workflows',+ 'workflowLibrary.preview.to': 'To',+ 'workflowLibrary.preview.unknownNode': "Unknown node type: its node pack isn't installed on this server.",+ 'workflowLibrary.preview.unknownNodeMarker': 'unknown node type',+ 'workflowLibrary.preview.unreadable': "This workflow can't be previewed: {{message}}",+ 'workflowLibrary.preview.youSetThis': 'You set this',+ 'workflowLibrary.preview.valueNumber': '{{value}}',+ 'workflowLibrary.preview.youSetThisInline': 'you set this',+ 'workflowLibrary.preview.zoomIn': 'Zoom in',+ 'workflowLibrary.preview.zoomOut': 'Zoom out',+ 'workflowLibrary.preview.zoomPercent': '{{percent}}%',+ 'workflowLibrary.preview.authorNotes': "Author's notes",+ 'workflowLibrary.preview.byAuthor': 'by {{author}}',+ 'workflowLibrary.preview.emptyValue': 'Empty',+ 'graphPreview.copyFailed': 'Failed to copy JSON',+ 'graphPreview.copyGraphJson': 'Copy graph JSON',+ 'graphPreview.invalidTitle': "This graph can't compile yet.",+ 'nodes.forLoopLinkageInvalid': 'Loop linkage must connect a For to its ForReturn',+ 'nodes.forLoopValidationFailed': 'For loop validation failed',+ 'workflowLibrary.preview.graph': 'Graph',+ 'workflowLibrary.preview.graphJson': 'Graph JSON',+ 'workflowLibrary.preview.nodes': 'Nodes',+ 'workflowLibrary.preview.inputCount_one': '{{count}} input',+ 'workflowLibrary.preview.inputCount_other': '{{count}} inputs',+ 'workflowLibrary.preview.inputs': 'Inputs',+ 'workflowLibrary.preview.kindLibrary': 'My library',+ 'workflowLibrary.preview.kindProject': 'In this project',+ 'workflowLibrary.preview.kindShared': 'Shared',+ 'workflowLibrary.preview.kindTemplate': 'Template',+ 'workflowLibrary.preview.modelNotInstalled': 'Model not installed',+ 'workflowLibrary.preview.modelToPick': 'Model to pick',+ 'workflowLibrary.preview.more': '+{{count}}',+ 'workflowLibrary.preview.noInputs': 'This workflow exposes no inputs. Its values are set on its nodes.',+ 'workflowLibrary.preview.pickAfterOpening': 'Pick one after opening',+ 'workflowLibrary.preview.previewNamed': 'Preview {{name}}',+ 'workflowLibrary.preview.readAllNotes': 'Read all notes',+ 'workflowLibrary.preview.seeAllInputs_other': 'See all {{count}} inputs',+ 'workflowLibrary.preview.showLessNotes': 'Show less',+ 'workflowLibrary.preview.showNode': '{{node}}: show in the graph',+ 'workflowLibrary.preview.version': 'v{{version}}',+ 'workflowLibrary.preview.youSet': 'You set',+ 'workflowLibrary.preview.positionUnknown': "Its place in these results isn't loaded",};const interpolate = (template: string, options?: Record<string, unknown>): string =>@@ -291,7 +535,9 @@ const translate = (key: string, options?: Record<string, unknown>): string => {return interpolate(plural ?? TRANSLATIONS[key] ?? key, options);};-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: translate }) }));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ i18n: { language: 'en', resolvedLanguage: 'en' }, t: translate }),+}));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -363,6 +609,99 @@ const PREVIEW_FIXTURE = entry(readyEnrichment(1, null, NO_REQUIREMENTS, PREVIEW_DOCUMENT));+const graphNode = (+ id: string,+ type: string,+ position: { x: number; y: number },+ inputs: Record<string, unknown> = {},+ fieldLabels: Record<string, string> = {}+): WorkflowInvocationNode => ({+ data: {+ inputs: Object.fromEntries(+ Object.entries(inputs).map(([name, value]) => [name, { label: fieldLabels[name] ?? '', name, value }])+ ),+ isIntermediate: true,+ isOpen: true,+ label: '',+ nodePack: 'invokeai',+ notes: '',+ type,+ useCache: true,+ version: '1.0.0',+ },+ id,+ position,+ type: 'invocation',+});+const graphEdge = (source: string, target: string, sourceHandle: string, targetHandle: string): WorkflowEdge => ({+ id: `${source}-${target}`,+ source,+ sourceHandle,+ target,+ targetHandle,+ type: 'default',+});+const exposedField = (id: string, nodeId: string, fieldName: string) => ({+ data: { fieldIdentifier: { fieldName, nodeId }, showDescription: false, showShuffle: false },+ id,+ parentId: 'root',+ type: 'node-field' as const,+});++/**+ * Six nodes: an exposed prompt primitive collected into the denoiser, a model loader with no model picked, a decoder,+ * and a refiner whose node pack this server lacks (so the workflow would not compile). Simplified, the prompt folds+ * into a pill on the denoiser and the collect hides: four nodes show.+ */+const GRAPH_DOCUMENT: ProjectGraphState = {+ ...createProjectGraph('graph-fixture', 'Graph Fixture'),+ edges: [+ graphEdge('prompt', 'collect', 'value', 'item'),+ graphEdge('collect', 'denoise', 'collection', 'positive'),+ graphEdge('model', 'denoise', 'unet', 'unet'),+ graphEdge('denoise', 'decode', 'latents', 'latents'),+ graphEdge('decode', 'refine', 'image', 'image'),+ ],+ author: 'Invoke',+ form: {+ elements: {+ 'field-model': exposedField('field-model', 'model', 'model'),+ 'field-prompt': exposedField('field-prompt', 'prompt', 'value'),+ 'field-steps': exposedField('field-steps', 'denoise', 'steps'),+ 'heading-model': { data: { content: 'Model' }, id: 'heading-model', parentId: 'root', type: 'heading' },+ 'heading-prompt': { data: { content: 'Prompting' }, id: 'heading-prompt', parentId: 'root', type: 'heading' },+ root: {+ data: {+ children: ['heading-prompt', 'field-prompt', 'field-steps', 'heading-model', 'field-model'],+ layout: 'column',+ },+ id: 'root',+ type: 'container',+ },+ },+ rootElementId: 'root',+ },+ notes: Array.from({ length: 12 }, (_, line) => `Note line ${line + 1}: keep the refine pass for portraits.`).join(+ '\n'+ ),+ workflowVersion: '1.2.0',+ nodes: [+ graphNode(+ 'prompt',+ 'string',+ { x: 0, y: 0 },+ { value: 'a lighthouse at dusk, long exposure' },+ { value: 'Prompt' }+ ),+ graphNode('collect', 'collect', { x: 320, y: 0 }),+ graphNode('model', 'main_model_loader', { x: 0, y: 240 }),+ graphNode('denoise', 'denoise_latents', { x: 640, y: 120 }, { cfg_scale: 3.5, steps: 30 }),+ graphNode('decode', 'l2i', { x: 960, y: 120 }),+ graphNode('refine', 'mask_refine', { x: 1280, y: 120 }),+ ],+};+const GRAPH_ENTRY = entry('wf-graph', 'Graph Fixture', readyEnrichment(6, 'flux', NO_REQUIREMENTS, GRAPH_DOCUMENT));+/** ~80 characters with no break opportunity the rail could exploit. */const LONG_NAME = 'Cinematic Portrait Restoration And Upscaling Pipeline With Refiner And Face Detail';const LONG_NAMED = entry('wf-long-name', LONG_NAME, readyEnrichment(3, 'sdxl'));@@ -370,7 +709,7 @@ const LONG_NAMED = entry('wf-long-name', LONG_NAME, readyEnrichment(3, 'sdxl'));const LOADED_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {entries: [PORTRAIT, LANDSCAPE, SKETCH, UPSCALE],error: null,- filter: { category: 'user', search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'user', search: '', sort: 'updated', tags: [] },page: 0,pages: 2,status: 'loaded',@@ -379,7 +718,7 @@ const LOADED_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {{ count: 1, tag: 'upscale' },],total: 24,- userTotal: 4,+ placeTotals: { user: 4 },};const withSnapshot = (patch: Partial<WorkflowLibraryBrowseSnapshot>): WorkflowLibraryBrowseSnapshot => ({@@ -450,8 +789,15 @@ const COMMANDS = {setWorkflowSource: vi.fn(),undo: vi.fn(),};-/** Only the library's own preferences matter here; saving one republishes it, as the account store does. */-const LIBRARY_PREFERENCES = { workflowLibrarySort: 'updated', workflowLibraryThumbnailFit: 'cover' } as const;+/** Only the library's own preferences (and the theme the preview graph draws in) matter here; saving one republishes it, as the account store does. */+const LIBRARY_PREFERENCES = {+ themeId: 'classic',+ workflowLibraryCardSize: 'small',+ workflowLibraryLayout: 'grid',+ workflowLibrarySort: 'updated',+ workflowLibrarySortDirection: 'desc',+ workflowLibraryThumbnailFit: 'cover',+} as const;const preferences = createMutablePort<WorkflowPreferences>(LIBRARY_PREFERENCES as unknown as WorkflowPreferences);const setLibraryPreferences = vi.fn((patch: Partial<WorkflowPreferences>) =>preferences.setSnapshot({ ...preferences.port.getSnapshot(), ...patch })@@ -466,6 +812,7 @@ const UI_ADAPTER = {project: project.port,} as unknown as WorkflowUiAdapter;const GRAPH_PREVIEW = { openDocumentInNewProject: vi.fn() } as unknown as WorkflowGraphPreviewPort;+const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });/** The library as the workflow dialog host mounts it: open while the UI store says so. */const StoreBoundLibraryDialog = () => {@@ -489,16 +836,18 @@ describe('WorkflowLibraryDialog', () => {await act(async () => {root.render(<StrictMode>- <ChakraProvider value={system}>- <WorkflowUiProvider adapter={UI_ADAPTER}>- <GalleryHostProvider host={GALLERY_HOST}>- <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>- <WorkflowLibraryDialog isOpen={isOpen} onOpenChange={onOpenChange} />- <LibraryCopyChoiceHost />- </WorkflowGraphPreviewProvider>- </GalleryHostProvider>- </WorkflowUiProvider>- </ChakraProvider>+ <QueryClientProvider client={queryClient}>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={UI_ADAPTER}>+ <GalleryHostProvider host={GALLERY_HOST}>+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>+ <WorkflowLibraryDialog isOpen={isOpen} onOpenChange={onOpenChange} />+ <LibraryCopyChoiceHost />+ </WorkflowGraphPreviewProvider>+ </GalleryHostProvider>+ </WorkflowUiProvider>+ </ChakraProvider>+ </QueryClientProvider></StrictMode>);await settleFrame();@@ -518,12 +867,13 @@ describe('WorkflowLibraryDialog', () => {});});- /** Poll lazy preview resolution inside act to avoid timing-dependent waits and suspended-resource warnings. */- const waitForPreviewDialog = () =>+ const stage = () => document.querySelector<HTMLElement>('[data-preview-stage]');+ /** Poll the lazy graph inside act to avoid timing-dependent waits and suspended-resource warnings. */+ const waitForPreviewGraph = () =>act(async () => {await vi.waitFor(() => {- expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();+ expect(stage()?.querySelector('.react-flow__node')).not.toBeNull();},// Allow time for Vite's dynamic-import round trip even when the module is warm.{ timeout: 2000 }@@ -554,12 +904,21 @@ describe('WorkflowLibraryDialog', () => {await act(() => button?.click());};- const clickSegment = async (value: string) => {- const tab = document.querySelector<HTMLButtonElement>(`[role="tab"][id$="-tab-${value}"]`);- expect(tab).not.toBeNull();+ const placeButton = (value: string) => document.querySelector<HTMLButtonElement>(`[data-library-place="${value}"]`);+ const tagCheckbox = (tag: string) =>+ document.querySelector<HTMLInputElement>(`[data-library-tag="${tag}"] input[type="checkbox"]`);+ const clickTag = async (tag: string) => {+ const label = document.querySelector<HTMLElement>(`[data-library-tag="${tag}"]`);+ expect(label).not.toBeNull();++ await act(() => userEvent.click(label!));+ };+ const clickPlace = async (value: string) => {+ const place = placeButton(value);+ expect(place).not.toBeNull();await act(async () => {- tab?.click();+ place?.click();await settleFrame();});};@@ -573,6 +932,9 @@ describe('WorkflowLibraryDialog', () => {};const gridViewport = () => document.querySelector<HTMLElement>('[role="region"][aria-label="Workflows"]');+ /** Whether an element takes part in the layout, and so the tab order: each layout hides the other's controls. */+ const isShown = (element: Element | null | undefined): element is HTMLElement =>+ element instanceof HTMLElement && element.getClientRects().length > 0;const expectContained = (element: HTMLElement | Range, container: HTMLElement) => {const box = element.getBoundingClientRect();@@ -586,21 +948,6 @@ describe('WorkflowLibraryDialog', () => {).toBeLessThanOrEqual(bounds.bottom + 1);};- const expectWrappedRenameHint = async (menu: HTMLElement, dialog: HTMLElement) => {- await act(() => userEvent.keyboard('{Home}{ArrowDown}'));- const rename = menu.querySelector<HTMLElement>('[data-menu-item="rename"]')!;- await vi.waitFor(() => {- expect(menu.getAttribute('aria-activedescendant')).toBe(rename.id);- const hint = rename.querySelector('p')!;- expect(hint.textContent).toBe(TRANSLATIONS['workflowLibrary.renameProjectWorkflowHint']);- const text = document.createRange();- text.selectNodeContents(hint);- expect(text.getClientRects().length).toBeGreaterThan(1);- expectContained(text, menu);- expectContained(text, dialog);- });- };-beforeEach(async () => {await resizeViewport(1280, 800);host = document.createElement('div');@@ -609,13 +956,20 @@ describe('WorkflowLibraryDialog', () => {onOpenChange = vi.fn((_isOpen: boolean) => {});identity.session = { multiuserEnabled: false, phase: 'ready', user: null };browse.ensureWorkflowLibraryBrowseLoaded.mockClear();+ browse.loadWorkflowLibraryPlaceTotals.mockClear();browse.setWorkflowLibraryBrowseFilter.mockClear();loader.open.mockClear();+ loader.replace.mockClear();loader.resume.mockClear();+ queryClient.clear();+ templateRecords.clear();loader.phase.current = 'idle';for (const command of Object.values(COMMANDS)) {command.mockClear();}+ for (const write of Object.values(libraryWrites)) {+ write.mockClear();+ }project.setSnapshot(projectSnapshot(PROJECT_WORKFLOWS));preferences.setSnapshot(LIBRARY_PREFERENCES as unknown as WorkflowPreferences);setLibraryPreferences.mockClear();@@ -630,19 +984,53 @@ describe('WorkflowLibraryDialog', () => {host.remove();});- it('renders one card per entry with its name and enriched node count', async () => {- await openWith(LOADED_SNAPSHOT);-- expect(cards()).toHaveLength(4);+ it('renders one card per entry with its base model, readiness and leading fact', async () => {+ await openWith(withSnapshot({ entries: [...LOADED_SNAPSHOT.entries, PREVIEW_FIXTURE] }));++ expect(cards()).toHaveLength(5);++ // The project holds a copy of Portrait, so that is its fact; the rail still counts its nodes.+ const portrait = card('wf-portrait')!;+ expect(portrait.textContent).toContain('Portrait Studio');+ expect(portrait.textContent).toContain('SDXL');+ expect(portrait.textContent).toContain('In project');+ expect(portrait.querySelector('[data-workflow-in-project]')).not.toBeNull();+ expect(portrait.querySelector('[data-workflow-readiness]')?.getAttribute('data-workflow-readiness')).toBe('ready');+ expect(document.querySelector('[data-workflow-detail]')?.textContent).toContain('12 nodes');++ const landscape = card('wf-landscape')!;+ expect(landscape.textContent).toContain('FLUX');+ expect(landscape.textContent).toContain('1 model to install');+ expect(landscape.querySelector('[data-workflow-readiness]')?.getAttribute('data-workflow-readiness')).toBe(+ 'models'+ );+ expect(landscape.querySelector('[data-workflow-in-project]')).toBeNull();- const text = document.body.textContent ?? '';+ const ready = card('wf-preview-fixture')!;+ expect(ready.textContent).toContain('1 node');+ expect(ready.querySelector('[data-workflow-readiness]')?.getAttribute('data-workflow-readiness')).toBe('ready');+ });- expect(text).toContain('Portrait Studio');- expect(text).toContain('12 nodes');- expect(text).toContain('SDXL');- expect(text).toContain('Landscape Pass');- expect(text).toContain('7 nodes');- expect(text).toContain('FLUX');+ it('marks a workflow whose node types the server lacks with the missing pack count, naming them in the rail', async () => {+ const unknown = (type: string) =>+ buildInvocationNode({ ...PREVIEW_NODE_TEMPLATE, nodePack: 'face-tools', title: type, type }, { x: 400, y: 0 });+ const document_: ProjectGraphState = {+ ...PREVIEW_DOCUMENT,+ nodes: [...PREVIEW_DOCUMENT.nodes, unknown('face_mask'), unknown('face_crop')],+ };+ const custom = entry('wf-custom', 'Custom Nodes', readyEnrichment(3, null, NO_REQUIREMENTS, document_));+ await openWith(withSnapshot({ entries: [custom, LANDSCAPE] }));++ const tile = card('wf-custom')!;+ expect(tile.querySelector('[data-workflow-readiness]')?.getAttribute('data-workflow-readiness')).toBe('nodePacks');+ expect(tile.textContent).toContain('1 node pack missing');+ expect(tile.textContent).not.toContain('3 nodes');+ expect(document.querySelector('[data-workflow-detail] [data-workflow-missing-node-packs]')?.textContent).toBe(+ '1 node pack missing'+ );+ expect(document.querySelector('[data-workflow-detail] [data-workflow-missing-node-pack-names]')?.textContent).toBe(+ 'Missing node pack: face-tools'+ );});it('shows a quiet placeholder while enrichment is pending and omits the badges when it failed', async () => {@@ -660,12 +1048,23 @@ describe('WorkflowLibraryDialog', () => {expect(failed?.querySelector('[data-enrichment-placeholder]')).toBeNull();});- it('renders the thumbnail when present and the not-run-yet placeholder when absent', async () => {- await openWith(LOADED_SNAPSHOT);+ it('renders the thumbnail when present, else the node silhouette, else the plain placeholder', async () => {+ await openWith(withSnapshot({ entries: [...LOADED_SNAPSHOT.entries, PREVIEW_FIXTURE] }));expect(card('wf-portrait')?.querySelector('img')).not.toBeNull();- expect(card('wf-landscape')?.querySelector('img')).toBeNull();- expect(card('wf-landscape')?.textContent).toContain('Not run yet');+ expect(card('wf-portrait')?.querySelector('[data-workflow-silhouette]')).toBeNull();+ // One node, one faint box drawn into a single background image, hidden from assistive technology.+ const silhouette = card('wf-preview-fixture')?.querySelector<HTMLElement>('[data-workflow-silhouette]');+ expect(silhouette?.getAttribute('aria-hidden')).toBe('true');+ expect(silhouette?.dataset.workflowSilhouette).toBe('1');+ expect(silhouette?.childElementCount).toBe(0);+ expect(silhouette?.style.backgroundImage).toContain('data:image/svg+xml');+ // No nodes, or no document yet: the plain no-image placeholder.+ for (const workflowId of ['wf-landscape', 'wf-sketch']) {+ expect(card(workflowId)?.querySelector('img')).toBeNull();+ expect(card(workflowId)?.querySelector('[data-workflow-silhouette]')).toBeNull();+ expect(card(workflowId)?.querySelector('svg.lucide-image-off')).not.toBeNull();+ }});it('kicks the first load when it opens and leaves the store alone while closed', async () => {@@ -681,60 +1080,157 @@ describe('WorkflowLibraryDialog', () => {expect(browse.ensureWorkflowLibraryBrowseLoaded).toHaveBeenCalled();});- it('opens in the account’s stored sort, offered on Yours only, and refetches in the order chosen', async () => {+ // The toolbar's sort select; the narrow layout's places select is another combobox.+ const sortTrigger = () => document.querySelector<HTMLButtonElement>('[data-workflow-library-sort]');+ /** Opens the Sort menu and returns its radio items: the keys, then the two directions. */+ const openSortMenu = async () => {+ const trigger = sortTrigger()!;+ await act(() => userEvent.click(trigger));+ await vi.waitFor(() => expect(trigger.getAttribute('aria-expanded')).toBe('true'));+ const menu = document.getElementById(trigger.getAttribute('aria-controls') ?? '')!;+ return [...menu.querySelectorAll<HTMLElement>('[role="menuitemradio"]')];+ };+ const chooseSortItem = async (label: string) => {+ const item = (await openSortMenu()).find((candidate) => candidate.textContent === label);+ expect(item, label).not.toBeUndefined();+ await act(() => userEvent.click(item!));+ };++ it('opens in the account’s stored order and refetches in the key chosen, starting in its natural direction', async () => {preferences.setSnapshot({...LIBRARY_PREFERENCES,workflowLibrarySort: 'opened',} as unknown as WorkflowPreferences);+ await openWith(withSnapshot({ filter: { ...LOADED_SNAPSHOT.filter, sort: 'opened' } }));++ expect(browse.ensureWorkflowLibraryBrowseLoaded).toHaveBeenCalledWith({+ direction: 'desc',+ place: 'user',+ search: '',+ sort: 'opened',+ tags: [],+ });+ // My library's own first page counts it; the probes cover the other places.+ expect(browse.loadWorkflowLibraryPlaceTotals).toHaveBeenCalledWith(['recent', 'default']);+ // The control shows the key; its name spells out the key and the direction its glyph shows.+ expect(sortTrigger()?.textContent).toBe('Last opened');+ expect(sortTrigger()?.getAttribute('aria-label')).toBe('Sort: Last opened, Newest first');+ const items = await openSortMenu();+ expect(items.map((item) => item.textContent)).toEqual([+ 'Last opened',+ 'Last updated',+ 'Last run',+ 'Date created',+ 'Name',+ 'Newest first',+ 'Oldest first',+ ]);+ await act(() => userEvent.click(items.find((item) => item.textContent === 'Name')!));++ expect(setLibraryPreferences).toHaveBeenCalledWith({+ workflowLibrarySort: 'name',+ workflowLibrarySortDirection: 'asc',+ });+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ direction: 'asc', sort: 'name' });+ });++ it('reverses My library’s order from the Sort menu and keeps the direction with the account', async () => {await openWith(LOADED_SNAPSHOT);- const sortTrigger = () => document.querySelector<HTMLElement>('[role="combobox"][aria-labelledby]');- const sortLabel = () => document.getElementById(sortTrigger()?.getAttribute('aria-labelledby') ?? '')?.textContent;- expect(browse.ensureWorkflowLibraryBrowseLoaded).toHaveBeenCalledWith('opened');- expect(sortLabel()).toBe('Sort by');- expect(sortTrigger()?.textContent).toContain('Last opened');+ await chooseSortItem('Oldest first');- await act(() => userEvent.click(sortTrigger()!));- const nameOption = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(- (option) => option.textContent === 'Name'- );- await act(() => userEvent.click(nameOption!));+ expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibrarySortDirection: 'asc' });+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ direction: 'asc' });+ });++ it('lists Templates by name only, reversing them for the visit without touching the account’s order', async () => {+ setWorkflowLibraryTab('default');+ await openWith(withSnapshot({ filter: { ...LOADED_SNAPSHOT.filter, place: 'default' } }));++ expect(sortTrigger()?.getAttribute('aria-label')).toBe('Sort: Name, A to Z');+ const items = await openSortMenu();+ // Names list A to Z first; the only key is fixed.+ expect(items.map((item) => item.textContent)).toEqual(['Name', 'A to Z', 'Z to A']);+ expect(items[0]?.hasAttribute('data-disabled')).toBe(true);+ await act(() => userEvent.click(items[2]!));++ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ direction: 'desc', sort: 'name' });+ expect(setLibraryPreferences).not.toHaveBeenCalled();+ });++ it('opens Recent in its fixed order, most recently opened first', async () => {+ await openWith(LOADED_SNAPSHOT);++ await clickPlace('recent');- expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibrarySort: 'name' });- expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ sort: 'name' });+ expect(workflowUiStore.getSnapshot().libraryTab).toBe('recent');+ expect(placeButton('recent')?.getAttribute('aria-pressed')).toBe('true');+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({+ direction: 'desc',+ place: 'recent',+ search: '',+ sort: 'updated',+ tags: [],+ });+ expect(sortTrigger()?.textContent).toBe('Last opened');+ expect(sortTrigger()?.disabled).toBe(true);+ });- // Bundled templates always list by name, and the project's own workflows have no library order.- await act(() => browse.setSnapshot?.(withSnapshot({ filter: { ...LOADED_SNAPSHOT.filter, category: 'default' } })));- expect(sortTrigger()).toBeNull();- await clickSegment('project');- expect(sortTrigger()).toBeNull();+ it('keeps the toolbar one row of equal-height controls 8px apart, New workflow last', async () => {+ await resizeViewport(1600, 1000);+ setWorkflowLibraryTab('project');+ await openWith(LOADED_SNAPSHOT);+ const toolbar = document.querySelector<HTMLElement>('[data-workflow-library-toolbar]')!;+ const shown = [...toolbar.children].filter((child) => isShown(child as HTMLElement)) as HTMLElement[];+ const boxes = shown.map((child) => child.getBoundingClientRect());++ expect(shown.map((child) => child.textContent)).toEqual(['', 'Project order', '', 'New workflow']);+ // Same-named control sizes share one outer height.+ expect(new Set(boxes.map((box) => Math.round(box.height))).size).toBe(1);+ expect(new Set(boxes.map((box) => Math.round(box.top)))).toEqual(new Set([Math.round(boxes[0]!.top)]));+ for (let index = 1; index < boxes.length; index += 1) {+ expect(Math.round(boxes[index]!.left - boxes[index - 1]!.right)).toBe(8);+ }});- it('fills thumbnails by default and letterboxes them once Fit is chosen', async () => {+ it('fills thumbnails by default and letterboxes them once Fit is chosen from the view options', async () => {await openWith(LOADED_SNAPSHOT);const thumbnail = () => card('wf-portrait')!.querySelector('img')!;- const fitOption = () =>- document.querySelector<HTMLInputElement>(- '[role="radiogroup"][aria-label="Thumbnail display"] input[value="contain"]'- );+ const fitItem = () => document.querySelector<HTMLElement>('[role="menuitemradio"][data-value="contain"]');expect(getComputedStyle(thumbnail()).objectFit).toBe('cover');- expect(fitOption()?.checked).toBe(false);- await act(() => userEvent.click(fitOption()!.closest('label')!));+ await act(() => userEvent.click(document.querySelector<HTMLElement>('button[aria-label="View options"]')!));+ await vi.waitFor(() => expect(fitItem()).not.toBeNull());+ expect(fitItem()?.getAttribute('aria-checked')).toBe('false');+ await act(() => userEvent.click(fitItem()!));expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibraryThumbnailFit: 'contain' });- expect(fitOption()?.checked).toBe(true);expect(getComputedStyle(thumbnail()).objectFit).toBe('contain');});+ it('switches cards to the large size from the view options and keeps the choice with the account', async () => {+ await openWith(LOADED_SNAPSHOT);+ const sizeItem = (value: string) =>+ document.querySelector<HTMLElement>(`[role="menuitemradio"][data-value="${value}"]`);++ await act(() => userEvent.click(document.querySelector<HTMLElement>('button[aria-label="View options"]')!));+ await vi.waitFor(() => expect(sizeItem('large')).not.toBeNull());+ expect(sizeItem('small')?.getAttribute('aria-checked')).toBe('true');+ await act(() => userEvent.click(sizeItem('large')!));++ expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibraryCardSize: 'large' });+ expect(sizeItem('large')?.getAttribute('aria-checked')).toBe('true');+ });+it('switches to the bundled defaults once when the account has no workflows of its own', async () => {- await openWith(withSnapshot({ userTotal: 0 }));+ await openWith(withSnapshot({ placeTotals: { user: 0 } }));await wait(0);- expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ category: 'default', tag: null });- // The segment follows the store's category, so the tab moves with it.+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ place: 'default', tags: [] });+ // The rail follows the store's place.expect(workflowUiStore.getSnapshot().libraryTab).toBe('default');+ expect(placeButton('default')?.getAttribute('aria-pressed')).toBe('true');});it('keeps Shared selected when the owner has no workflows of their own', async () => {@@ -742,53 +1238,110 @@ describe('WorkflowLibraryDialog', () => {setWorkflowLibraryTab('shared');await openWith(withSnapshot({- filter: { category: 'user', isPublic: true, search: '', sort: 'updated', tag: null },- userTotal: 0,+ filter: { direction: 'desc', place: 'shared', search: '', sort: 'updated', tags: [] },+ placeTotals: { user: 0 },}));await wait(0);- expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalled();+ expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalledWith(+ expect.objectContaining({ place: 'default' })+ );expect(workflowUiStore.getSnapshot().libraryTab).toBe('shared');});- it('leaves the category alone when the account already has workflows', async () => {+ it('leaves the place alone when the account already has workflows', async () => {await openWith(LOADED_SNAPSHOT);await wait(0);- expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalled();+ expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalledWith(+ expect.objectContaining({ place: 'default' })+ );});- it('resets the tag when the category segment changes', async () => {- await openWith(withSnapshot({ filter: { category: 'user', search: '', sort: 'updated', tag: 'portrait' } }));+ it('switches to Templates only for the place the library opened on', async () => {+ setWorkflowLibraryTab('project');+ await openWith(withSnapshot({ placeTotals: { user: 0 } }));+ // Opening on This project probes every library place, once.+ expect(browse.loadWorkflowLibraryPlaceTotals).toHaveBeenCalledWith(['recent', 'user', 'default']);- await clickSegment('default');+ await clickPlace('user');+ await wait(0);+ await clickPlace('project');+ await clickPlace('user');+ await wait(0);- // The store applies filter patches literally, so clearing the tag on a- // category switch is the dialog's job.- expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ category: 'default', tag: null });+ // An empty My library chosen in the rail stays chosen, and leaving This project probes nothing again.+ expect(workflowUiStore.getSnapshot().libraryTab).toBe('user');+ expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalledWith(+ expect.objectContaining({ place: 'default' })+ );+ expect(new Set(browse.loadWorkflowLibraryPlaceTotals.mock.calls.map(([places]) => places.join()))).toEqual(+ new Set(['recent,user,default'])+ );});- it('opens the Shared tab with the public user-workflow filter', async () => {- identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } };+ it('clears the checked tags but keeps the search when the place changes', async () => {await openWith(LOADED_SNAPSHOT);+ await clickTag('portrait');+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ onTestFinished(() => {+ vi.useRealTimers();+ });+ const input = document.querySelector<HTMLInputElement>('input[type="search"]')!;+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ await act(async () => {+ setValue?.call(input, 'portrait');+ input.dispatchEvent(new Event('input', { bubbles: true }));+ await Promise.resolve();+ });+ browse.setWorkflowLibraryBrowseFilter.mockClear();- await clickSegment('shared');+ // Before the search's debounce: the place change carries the typed search, not the store's.+ await act(() => placeButton('default')!.click());- expect(workflowUiStore.getSnapshot().libraryTab).toBe('shared');- expect(document.querySelector('[role="tab"][id$="-tab-shared"]')?.getAttribute('aria-selected')).toBe('true');+ // The store applies filter patches literally, so clearing the tags on a place switch is the dialog's job.expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({- category: 'user',- isPublic: true,- tag: null,+ direction: 'desc',+ place: 'default',+ search: 'portrait',+ sort: 'updated',+ tags: [],});+ expect(input.value).toBe('portrait');+ await act(() => vi.advanceTimersByTimeAsync(1000));+ vi.useRealTimers();+ // The cancelled debounce never lands on the new place.+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledTimes(1);+ expect(workflowUiStore.getSnapshot().libraryQuery.tags).toEqual([]);+ });++ it('shows place totals in the rail and opens Shared with the public filter', async () => {+ identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } };+ await openWith(withSnapshot({ placeTotals: { default: 25, recent: 3, shared: 9, user: 4 } }));++ expect(+ [...document.querySelectorAll<HTMLElement>('[data-library-place]')].map((place) => place.textContent)+ ).toEqual(['In this project3', 'Recent3', 'My library4', 'Templates25', 'Shared with me9']);+ expect(browse.loadWorkflowLibraryPlaceTotals).toHaveBeenCalledWith(['recent', 'default', 'shared']);++ await clickPlace('shared');++ expect(workflowUiStore.getSnapshot().libraryTab).toBe('shared');+ expect(placeButton('shared')?.getAttribute('aria-pressed')).toBe('true');+ expect(placeButton('user')?.getAttribute('aria-pressed')).toBe('false');+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith(expect.objectContaining({ place: 'shared' }));+ // The centre column is named by the place it shows.+ expect(document.querySelector('section[aria-labelledby]')?.getAttribute('aria-labelledby')).toBe(+ placeButton('shared')?.querySelector('[id]')?.id+ );});- it('hides the Shared tab when multiuser mode is disabled', async () => {+ it('hides Shared with me when multiuser mode is disabled', async () => {identity.session = { multiuserEnabled: false, phase: 'ready', user: null };await openWith(LOADED_SNAPSHOT);- expect(document.querySelector('[role="tab"][id$="-tab-shared"]')).toBeNull();+ expect(placeButton('shared')).toBeNull();});it('hides template editing controls for another user’s Shared workflow', async () => {@@ -797,7 +1350,7 @@ describe('WorkflowLibraryDialog', () => {await openWith(withSnapshot({entries: [NON_OWNER_SHARED],- filter: { category: 'user', isPublic: true, search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'shared', search: '', sort: 'updated', tags: [] },}));@@ -809,8 +1362,8 @@ describe('WorkflowLibraryDialog', () => {});await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).not.toBeNull());- expect(document.querySelector('[data-menu-item="rename"]')).toBeNull();- expect(document.querySelector('[data-menu-item="delete"]')).toBeNull();+ expect(document.querySelector('[role="menuitem"][data-value="rename"]')).toBeNull();+ expect(document.querySelector('[role="menuitem"][data-value="delete"]')).toBeNull();expect(document.querySelector('[aria-label="workflowLibrary.thumbnailChoose"]')).toBeNull();expect(document.querySelector('[data-thumbnail-remove]')).toBeNull();});@@ -821,7 +1374,7 @@ describe('WorkflowLibraryDialog', () => {await openWith(withSnapshot({entries: [{ ...PORTRAIT, item: { ...PORTRAIT.item, user_id: 'user-a' } }],- filter: { category: 'user', isPublic: true, search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'shared', search: '', sort: 'updated', tags: [] },}));@@ -833,8 +1386,8 @@ describe('WorkflowLibraryDialog', () => {});await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).not.toBeNull());- expect(document.querySelector('[data-menu-item="rename"]')).not.toBeNull();- expect(document.querySelector('[data-menu-item="delete"]')).not.toBeNull();+ expect(document.querySelector('[role="menuitem"][data-value="rename"]')).not.toBeNull();+ expect(document.querySelector('[role="menuitem"][data-value="delete"]')).not.toBeNull();expect(document.querySelector('[aria-label="workflowLibrary.thumbnailChoose"]')).not.toBeNull();expect(document.querySelector('[data-workflow-detail] input[type="checkbox"]')).toBeNull();});@@ -845,11 +1398,14 @@ describe('WorkflowLibraryDialog', () => {await openWith(withSnapshot({entries: [OWNER_PRIVATE],- filter: { category: 'user', search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'user', search: '', sort: 'updated', tags: [] },}));- expect(card('wf-portrait')?.textContent).toContain('Private');+ // Only public templates carry a visibility badge; the rail states it either way.+ expect(card('wf-portrait')?.textContent).not.toContain('Private');+ expect(card('wf-portrait')?.querySelector('[data-workflow-visibility]')).toBeNull();+ expect(document.querySelector('[data-workflow-detail] [data-workflow-visibility]')?.textContent).toBe('Private');const ownerSwitch = document.querySelector<HTMLInputElement>('[data-workflow-detail] input[type="checkbox"]');expect(ownerSwitch).not.toBeNull();expect(ownerSwitch?.checked).toBe(false);@@ -860,7 +1416,7 @@ describe('WorkflowLibraryDialog', () => {await openWith(withSnapshot({entries: [{ ...OWNER_PRIVATE, item: { ...OWNER_PRIVATE.item, user_id: 'user-a' } }],- filter: { category: 'user', search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'user', search: '', sort: 'updated', tags: [] },}));@@ -871,8 +1427,8 @@ describe('WorkflowLibraryDialog', () => {await settleFrame();});await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).not.toBeNull());- expect(document.querySelector('[data-menu-item="rename"]')).toBeNull();- expect(document.querySelector('[data-menu-item="delete"]')).toBeNull();+ expect(document.querySelector('[role="menuitem"][data-value="rename"]')).toBeNull();+ expect(document.querySelector('[role="menuitem"][data-value="delete"]')).toBeNull();expect(document.querySelector('[aria-label="workflowLibrary.thumbnailChoose"]')).toBeNull();});@@ -882,12 +1438,21 @@ describe('WorkflowLibraryDialog', () => {await openWith(withSnapshot({entries: [OWNER_PUBLIC],- filter: { category: 'user', isPublic: true, search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'shared', search: '', sort: 'updated', tags: [] },}));- expect(card('wf-portrait')?.textContent).toContain('Public');+ expect(card('wf-portrait')?.querySelector('[data-workflow-visibility]')?.textContent).toBe('Public');+ expect(document.querySelector('[data-workflow-detail] input[type="checkbox"]')).toBeNull();+ });++ it('keeps visibility out of single-user cards and rails, even for a public template', async () => {+ identity.session = { multiuserEnabled: false, phase: 'ready', user: null };+ await openWith(withSnapshot({ entries: [OWNER_PUBLIC] }));++ expect(document.querySelector('[data-workflow-visibility]')).toBeNull();expect(document.querySelector('[data-workflow-detail] input[type="checkbox"]')).toBeNull();+ expect(document.querySelector('[data-workflow-detail]')?.textContent).not.toContain('Visibility');});it('keeps Yours template editing available in single-user mode', async () => {@@ -896,7 +1461,7 @@ describe('WorkflowLibraryDialog', () => {await openWith(withSnapshot({entries: [PORTRAIT],- filter: { category: 'user', search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'user', search: '', sort: 'updated', tags: [] },}));@@ -908,22 +1473,102 @@ describe('WorkflowLibraryDialog', () => {});await vi.waitFor(() => expect(document.querySelector('[role="menu"]')).not.toBeNull());- expect(document.querySelector('[data-menu-item="rename"]')).not.toBeNull();- expect(document.querySelector('[data-menu-item="delete"]')).not.toBeNull();+ expect(document.querySelector('[role="menuitem"][data-value="rename"]')).not.toBeNull();+ expect(document.querySelector('[role="menuitem"][data-value="delete"]')).not.toBeNull();expect(document.querySelector('[aria-label="workflowLibrary.thumbnailChoose"]')).not.toBeNull();expect(document.querySelector('[data-workflow-detail] input[type="checkbox"]')).toBeNull();});- it('selects and clears a tag from the chip row', async () => {+ it('asks for any of the checked tags, names them in the result line, and clears them', async () => {+ await openWith(LOADED_SNAPSHOT);+ // StrictMode's remount of the browse session clears the listing's query once on mount.+ browse.setWorkflowLibraryBrowseFilter.mockClear();+ const results = () => document.querySelector('[data-workflow-library-results]')?.textContent;++ expect(results()).toBe('24 workflows');+ expect(document.body.textContent).toContain('Showing workflows with any checked tag');++ await clickTag('portrait');+ await clickTag('upscale');++ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenNthCalledWith(1, { tags: ['portrait'] });+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenNthCalledWith(2, { tags: ['portrait', 'upscale'] });+ expect(tagCheckbox('portrait')?.checked).toBe(true);+ expect(results()).toBe('24 workflows · portrait or upscale');++ await clickText('Clear');++ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenLastCalledWith({ tags: [] });+ expect(tagCheckbox('portrait')?.checked).toBe(false);+ expect(buttonWithText('Clear')).toBeUndefined();+ });++ it('keeps a checked tag the counts stop listing until it is unchecked, then keeps focus in the rail', async () => {await openWith(LOADED_SNAPSHOT);+ await clickTag('portrait');+ await act(() => browse.setSnapshot?.(withSnapshot({ tagCounts: [] })));++ expect(tagCheckbox('portrait')?.checked).toBe(true);+ await act(() => tagCheckbox('portrait')!.focus());+ await act(() => userEvent.keyboard(' '));++ expect(tagCheckbox('portrait')).toBeNull();+ expect(document.activeElement).toBe(placeButton('user'));+ });++ it('clears the listing’s search and tags on close, so reopening on a library place loads unfiltered', async () => {+ await act(() => browse.setSnapshot?.(LOADED_SNAPSHOT));+ setWorkflowLibraryOpen(true);+ await act(async () => {+ root.render(+ <StrictMode>+ <QueryClientProvider client={queryClient}>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={UI_ADAPTER}>+ <GalleryHostProvider host={GALLERY_HOST}>+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>+ <StoreBoundLibraryDialog />+ </WorkflowGraphPreviewProvider>+ </GalleryHostProvider>+ </WorkflowUiProvider>+ </ChakraProvider>+ </QueryClientProvider>+ </StrictMode>+ );+ await settleFrame();+ });+ const search = () => document.querySelector<HTMLInputElement>('input[type="search"]');+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ await act(async () => {+ setValue?.call(search(), 'photo');+ search()!.dispatchEvent(new Event('input', { bubbles: true }));+ await Promise.resolve();+ });+ await clickTag('portrait');+ await expect.poll(() => browse.setWorkflowLibraryBrowseFilter.mock.calls).toContainEqual([{ search: 'photo' }]);+ browse.setWorkflowLibraryBrowseFilter.mockClear();- await clickText('portrait2');+ await act(async () => {+ document.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!.click();+ await settleFrame();+ });- expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ tag: 'portrait' });+ // The listing drops the query as the dialog closes, not when it next opens.+ expect(workflowUiStore.getSnapshot().isLibraryOpen).toBe(false);+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenLastCalledWith({ search: '', tags: [] });+ browse.ensureWorkflowLibraryBrowseLoaded.mockClear();- await clickText('All');+ await act(async () => {+ setWorkflowLibraryOpen(true);+ await settleFrame();+ });- expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ tag: null });+ expect(workflowUiStore.getSnapshot().libraryTab).toBe('user');+ expect(browse.ensureWorkflowLibraryBrowseLoaded).toHaveBeenCalledWith(+ expect.objectContaining({ place: 'user', search: '', tags: [] })+ );+ expect(search()?.value).toBe('');+ expect(tagCheckbox('portrait')?.checked).toBe(false);});it('pushes the search term to the store once, after the debounce', async () => {@@ -935,6 +1580,8 @@ describe('WorkflowLibraryDialog', () => {// React tracks the input's value through its own setter, so assigning// `.value` directly would be swallowed as a no-op change.const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ // StrictMode's remount of the browse session clears the listing's query once on mount.+ browse.setWorkflowLibraryBrowseFilter.mockClear();for (const value of ['p', 'ph', 'pho', 'phot', 'photo']) {await act(async () => {@@ -946,7 +1593,7 @@ describe('WorkflowLibraryDialog', () => {expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalled();- await wait(400);+ await expect.poll(() => browse.setWorkflowLibraryBrowseFilter.mock.calls).toEqual([[{ search: 'photo' }]]);expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledTimes(1);expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ search: 'photo' });@@ -1076,7 +1723,7 @@ describe('WorkflowLibraryDialog', () => {);await openWith(withSnapshot({ entries, total: entries.length, pages: 51 }));if (view === 'project') {- await clickSegment('project');+ await clickPlace('project');await vi.waitFor(() => expect(card('wf-user')).not.toBeNull());await act(() => card('wf-user')!.click());expect(document.querySelector('[data-project-workflow-detail="wf-user"]')).not.toBeNull();@@ -1085,15 +1732,22 @@ describe('WorkflowLibraryDialog', () => {const dialog = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;const detail = dialog.querySelector<HTMLElement>('[data-workflow-detail], [data-project-workflow-detail]')!;const metadata = detail.querySelector<HTMLElement>('[role="region"]')!;+ const summary = detail.querySelector<HTMLElement>('[data-detail-sheet-summary]')!;+ const toggle = summary.querySelector<HTMLButtonElement>('[data-detail-sheet-toggle]')!;const grid = gridViewport()!;const close = dialog.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!;- const open = [...detail.querySelectorAll<HTMLButtonElement>('button')].find(- (button) => button.textContent === 'Open'- )!;- const preview = [...detail.querySelectorAll<HTMLButtonElement>('button')].find(- (button) => button.textContent === 'Preview graph'- )!;- const menu = detail.querySelector<HTMLButtonElement>('button[aria-label="More actions"]')!;+ const preview = detail.querySelector<HTMLButtonElement>('[data-workflow-preview-trigger]')!;+ // The wide rail carries Open and More itself; the narrow layout's sheet summary carries them instead.+ const railActions = () => {+ const owner = isNarrow() ? summary : metadata.closest<HTMLElement>('[data-detail-sheet-details]')!;+ return {+ menu: owner.querySelector<HTMLButtonElement>('button[aria-label="More actions"]')!,+ open: [...owner.querySelectorAll<HTMLButtonElement>('button')].find(+ (button) => button.textContent === 'Open'+ )!,+ };+ };+ const isNarrow = () => dialog.getBoundingClientRect().width < 56 * 16;for (const [width, height] of [[1280, 800],@@ -1105,33 +1759,46 @@ describe('WorkflowLibraryDialog', () => {expect(window.innerWidth).toBe(width);expect(window.innerHeight).toBe(height);await vi.waitFor(() => {- // Enough for readable metadata and a substantial part of a card, rather than merely nonzero boxes.- expect(metadata.clientHeight, 'selected metadata scroll viewport').toBeGreaterThanOrEqual(80);+ const narrow = isNarrow();+ // Enough for a substantial part of a card, rather than merely nonzero boxes.expect(grid.clientHeight, 'workflow grid scroll viewport').toBeGreaterThanOrEqual(120);expect(grid.clientHeight, 'finite virtual grid viewport').toBeLessThanOrEqual(640);- expect(detail.clientHeight, 'finite detail pane').toBeLessThanOrEqual(640);- if (width <= 512 || height === 320) {+ if (height <= 400) {expect(grid.clientHeight, 'flow grid has a finite viewport').toBe(256);- expect(detail.getBoundingClientRect().height, 'flow detail does not grow with metadata').toBe(320);+ }+ if (narrow) {+ // The sheet's summary stays in view under the grid; its details wait behind the disclosure.+ expect(isShown(summary), 'sheet summary').toBe(true);+ expect(isShown(metadata), 'collapsed sheet details').toBe(false);+ expectContained(summary, dialog);+ } else {+ expect(isShown(summary), 'wide layout has no sheet').toBe(false);+ // Enough for readable metadata.+ expect(metadata.clientHeight, 'selected metadata scroll viewport').toBeGreaterThanOrEqual(80);+ expect(detail.clientHeight, 'finite detail pane').toBeLessThanOrEqual(640);+ if (height <= 400) {+ expect(detail.getBoundingClientRect().height, 'flow detail does not grow with metadata').toBe(272);+ }+ expect(grid.getBoundingClientRect().right).toBeLessThanOrEqual(detail.getBoundingClientRect().left);}expect(dialog.scrollWidth).toBeLessThanOrEqual(dialog.clientWidth + 1);expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(width);expect(dialog.getBoundingClientRect().top).toBeGreaterThanOrEqual(0);expect(dialog.getBoundingClientRect().bottom).toBeLessThanOrEqual(height);- if ((width >= 640 && height >= 400) || height >= 640) {- for (const action of [open, preview, menu, close]) {+ // Short windows scroll the centre column to the rail's actions; the focus walk below proves they stay+ // reachable and unclipped.+ if (height >= 640) {+ const { menu, open } = railActions();+ for (const action of narrow ? [open, menu, toggle, close] : [open, preview, menu, close]) {expectContained(action, dialog);}}for (const control of dialog.querySelectorAll<HTMLElement>(- 'input[type="search"], [role="combobox"], [role="tab"], [aria-label="Thumbnail display"]'+ 'input[type="search"], [role="combobox"], [data-library-place], [data-workflow-library-sort], [data-workflow-library-narrow-options]')) {- expectContained(control, dialog);- }- if ((width === 700 && height >= 640) || width <= 512) {- expect(grid.getBoundingClientRect().bottom).toBeLessThanOrEqual(detail.getBoundingClientRect().top);- } else {- expect(grid.getBoundingClientRect().right).toBeLessThanOrEqual(detail.getBoundingClientRect().left);+ if (isShown(control)) {+ expectContained(control, dialog);+ }}expect(grid.scrollWidth).toBeLessThanOrEqual(grid.clientWidth + 1);expect(cards().length).toBeGreaterThan(0);@@ -1141,7 +1808,7 @@ describe('WorkflowLibraryDialog', () => {const bounds = grid.getBoundingClientRect();expect(box.left).toBeGreaterThanOrEqual(bounds.left);expect(box.right).toBeLessThanOrEqual(bounds.right + 1);- expect(box.width).toBeGreaterThanOrEqual(180);+ expect(box.width).toBeGreaterThanOrEqual(150);const row = element.closest<HTMLElement>('[data-index]')!;expectContained(element, row);const nextRow = row.nextElementSibling;@@ -1156,7 +1823,8 @@ describe('WorkflowLibraryDialog', () => {expectContained(element, dialog);for (let parent = element.parentElement; parent && parent !== dialog; parent = parent.parentElement) {const style = getComputedStyle(parent);- if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {+ // A box-less ancestor (`display: contents`) clips nothing.+ if (style.display !== 'contents' && /(auto|scroll|hidden|clip)/.test(style.overflowY)) {expectContained(element, parent);}}@@ -1176,14 +1844,23 @@ describe('WorkflowLibraryDialog', () => {expect(cards().length).toBeLessThan(40);expect(grid.clientHeight).toBeLessThanOrEqual(640);});+ if (isNarrow()) {+ // The full rail opens over the grid from the sheet's disclosure, focus moving into it.+ await act(() => toggle.focus());+ await act(() => userEvent.keyboard('{Enter}'));+ expect(toggle.getAttribute('aria-expanded')).toBe('true');+ expect(isShown(metadata)).toBe(true);+ expect(metadata.clientHeight, 'expanded sheet metadata scroll viewport').toBeGreaterThanOrEqual(80);+ }+ const { menu, open } = railActions();await act(() => metadata.focus());expect(document.activeElement).toBe(metadata);expectUnclipped(metadata);await act(() => userEvent.keyboard('{End}'));await vi.waitFor(() => {expect(metadata.scrollTop).toBeGreaterThan(0);- const lastMetadata =- metadata.querySelector<HTMLElement>('[data-workflow-source]') ?? [...metadata.querySelectorAll('p')].at(-1)!;+ // The facts list closes both rails.+ const lastMetadata = [...metadata.querySelectorAll<HTMLElement>('dd')].at(-1)!;const ending = document.createRange();ending.selectNodeContents(lastMetadata);const text = lastMetadata.firstChild!;@@ -1204,8 +1881,8 @@ describe('WorkflowLibraryDialog', () => {expect(reached.size).toBe(4);const toolbarTargets = [dialog.querySelector<HTMLElement>('input[type="search"]'),- dialog.querySelector<HTMLElement>('[role="combobox"]'),- dialog.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]'),+ [...dialog.querySelectorAll<HTMLElement>('[role="combobox"]')].find(isShown),+ [...dialog.querySelectorAll<HTMLElement>('[data-library-place][aria-pressed="true"]')].find(isShown),[...dialog.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === 'New workflow'),@@ -1243,9 +1920,6 @@ describe('WorkflowLibraryDialog', () => {// Open state precedes the entry slide's final geometry.await act(() => settleAnimations(menuContent));expectContained(menuContent, dialog);- if (view === 'project' && targetWidth === 320) {- await expectWrappedRenameHint(menuContent, dialog);- }await act(() => userEvent.keyboard('{End}'));const lastAction = [...menuContent.querySelectorAll<HTMLElement>('[role="menuitem"]')].at(-1)!;await vi.waitFor(() => {@@ -1257,11 +1931,12 @@ describe('WorkflowLibraryDialog', () => {await act(() => preview.focus());expectUnclipped(preview);await act(() => userEvent.keyboard('{Enter}'));- await waitForPreviewDialog();- expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();- // The preview renderer is stubbed; close it through its existing harness controls before using the rail.- await clickText('Close preview');- await clickText('Finish preview exit');+ expect(document.activeElement).toBe(stage());+ // Escape leaves the preview, not the library, and hands focus back to the control that opened it.+ await act(() => userEvent.keyboard('{Escape}'));+ expect(stage()).toBeNull();+ expect(document.activeElement).toBe(preview);+ expect(onOpenChange).not.toHaveBeenCalled();await act(() => open.focus());expectUnclipped(open);await act(() => userEvent.keyboard('{Enter}'));@@ -1298,7 +1973,7 @@ describe('WorkflowLibraryDialog', () => {await resizeViewport(320, 320);await openWith(LOADED_SNAPSHOT);if (view === 'project') {- await clickSegment('project');+ await clickPlace('project');}await vi.waitFor(() => expect(card(view === 'project' ? 'wf-alpha' : 'wf-landscape')).not.toBeNull());const source = card(view === 'project' ? 'wf-alpha' : 'wf-landscape')!;@@ -1312,9 +1987,6 @@ describe('WorkflowLibraryDialog', () => {const dialog = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;await act(() => settleAnimations(menu));expectContained(menu, dialog);- if (view === 'project') {- await expectWrappedRenameHint(menu, dialog);- }await act(() => userEvent.keyboard('{End}'));const lastAction = [...menu.querySelectorAll<HTMLElement>('[role="menuitem"]')].at(-1)!;await vi.waitFor(() => {@@ -1323,12 +1995,15 @@ describe('WorkflowLibraryDialog', () => {expectContained(lastAction, dialog);});await resizeViewport(700, 320);+ // Let the grid take its new width while the menu is open, as a resize does outside the test's act scopes.+ await wait(50);await vi.waitFor(() => {expect(menu.getAttribute('data-state')).toBe('open');expectContained(menu, dialog);});await act(() => userEvent.keyboard('{Escape}'));- await vi.waitFor(() => expect(document.activeElement).toBe(source));+ // A wider grid can reflow the card into another row, which mounts it afresh: focus returns to the card by its id.+ await vi.waitFor(() => expect(document.activeElement?.id).toBe(source.id));expect(document.querySelector('[data-workflow-context-menu][data-state="open"]')).toBeNull();});@@ -1358,6 +2033,26 @@ describe('WorkflowLibraryDialog', () => {expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'first-copy');});+ it('opens the selected workflow on double click while its metadata page is evicted', async () => {+ preferences.setSnapshot({ ...preferences.port.getSnapshot(), workflowLibraryLayout: 'list' });+ await openWith(withSnapshot({ entries: [PORTRAIT, LANDSCAPE], total: 24 }));+ const primary = () => document.getElementById('workflow-library-card-wf-landscape')!;+ await act(() => primary().click());+ await act(() =>+ browse.setSnapshot?.(+ withSnapshot({+ entries: [SKETCH],+ selectedEntry: LANDSCAPE,+ startIndex: 20,+ total: 24,+ })+ )+ );+ await act(() => primary().dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));++ expect(loader.open).toHaveBeenCalledExactlyOnceWith(LANDSCAPE.item, 'first-copy');+ });+it('dedupes entries that share a workflow id', async () => {await openWith(withSnapshot({ entries: [PORTRAIT, LANDSCAPE, { ...PORTRAIT }] }));@@ -1378,13 +2073,13 @@ describe('WorkflowLibraryDialog', () => {await openWith({entries: [],error: null,- filter: { category: 'user', search: '', sort: 'updated', tag: null },+ filter: { direction: 'desc', place: 'user', search: '', sort: 'updated', tags: [] },page: 0,pages: 0,status: 'idle',tagCounts: [],total: 0,- userTotal: null,+ placeTotals: {},});const text = document.body.textContent ?? '';@@ -1393,11 +2088,17 @@ describe('WorkflowLibraryDialog', () => {expect(text).not.toContain('No workflows match these filters.');});- it('shows the empty state only when nothing loaded', async () => {+ it('shows the empty state only when nothing loaded, saying why when nothing filters the place', async () => {await openWith(withSnapshot({ entries: [], status: 'loaded', total: 0 }));expect(cards()).toHaveLength(0);+ expect(document.body.textContent ?? '').toContain('No saved workflows yet.');++ await clickTag('portrait');expect(document.body.textContent ?? '').toContain('No workflows match these filters.');++ await clickPlace('recent');+ expect(document.body.textContent ?? '').toContain('Nothing opened yet.');});it('shows the selected workflow in the rail and follows the selection', async () => {@@ -1427,10 +2128,12 @@ describe('WorkflowLibraryDialog', () => {await settleFrame();});- // The button selects its tile and opens the same actions the right-click offers, anchored to the button.- expect(document.querySelector<HTMLElement>('[data-workflow-detail]')?.dataset.workflowDetail).toBe('wf-landscape');+ // The button opens the same actions the right-click offers, anchored to the button, and leaves the selection.+ expect(document.querySelector<HTMLElement>('[data-workflow-detail]')?.dataset.workflowDetail).toBe('wf-portrait');const open = () =>- document.querySelector<HTMLElement>('[data-workflow-context-menu][data-state="open"] [data-menu-item="open"]');+ document.querySelector<HTMLElement>(+ '[data-workflow-context-menu][data-state="open"] [role="menuitem"][data-value="open"]'+ );await vi.waitFor(() => expect(open()).not.toBeNull());await vi.waitFor(() => expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull(), { timeout: 2000 });@@ -1458,7 +2161,7 @@ describe('WorkflowLibraryDialog', () => {await openWith(LOADED_SNAPSHOT);const first = document.querySelector<HTMLButtonElement>('[data-workflow-card-menu="wf-landscape"]');- const second = document.querySelector<HTMLButtonElement>('[data-workflow-card-menu="wf-portrait"]');+ const second = document.querySelector<HTMLButtonElement>('[data-workflow-card-menu="wf-sketch"]');expect(second).not.toBeNull();await pressTileMenuButton(first);@@ -1470,7 +2173,9 @@ describe('WorkflowLibraryDialog', () => {expect(first?.getAttribute('aria-expanded')).toBe('false');expect(document.querySelector<HTMLElement>('[data-workflow-detail]')?.dataset.workflowDetail).toBe('wf-portrait');await vi.waitFor(() =>- expect(document.querySelector('[data-workflow-context-menu][data-state="open"]')).not.toBeNull()+ expect(document.querySelector('[data-workflow-context-menu][data-state="open"]')?.id).toBe(+ second?.getAttribute('aria-controls')+ ));});@@ -1488,61 +2193,358 @@ describe('WorkflowLibraryDialog', () => {await vi.waitFor(() => expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull(), { timeout: 2000 });});- it('opens the rail actions for a card from a right-click and runs them', async () => {- await openWith(LOADED_SNAPSHOT);+ describe('a card menu acts on its own card, never moving the selection', () => {+ const detail = () => document.querySelector<HTMLElement>('[data-workflow-detail]')?.dataset.workflowDetail;+ const openMenu = () => document.querySelector<HTMLElement>('[data-workflow-context-menu][data-state="open"]');+ const alertDialog = () => document.querySelector<HTMLElement>('[role="alertdialog"]');+ const confirmIn = async (label: string) => {+ const confirm = [...(alertDialog()?.querySelectorAll('button') ?? [])].find(+ (candidate) => (candidate.textContent ?? '').trim() === label+ );+ expect(confirm).not.toBeUndefined();+ await act(async () => {+ confirm?.click();+ await settleFrame();+ });+ };- await act(() =>- card('wf-landscape')?.dispatchEvent(- new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })- )- );+ /** Raises Landscape's menu by one of its three paths and returns the control that names it. */+ const raise = async (path: 'right-click' | 'Shift+F10' | 'More button') => {+ const source = card('wf-landscape')!;+ if (path === 'More button') {+ const more = document.querySelector<HTMLElement>('[data-workflow-card-menu="wf-landscape"]')!;+ await pressTileMenuButton(more);+ return more;+ }+ await act(() => source.focus());+ await act(() =>+ source.dispatchEvent(+ // A keyboard-raised menu (Shift+F10, the Menu key) reports no pointer position.+ path === 'Shift+F10'+ ? new MouseEvent('contextmenu', { bubbles: true, cancelable: true })+ : new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })+ )+ );+ return source;+ };- // The right-click selects the card, so the rail (which owns the actions) shows it.- expect(document.querySelector<HTMLElement>('[data-workflow-detail]')?.dataset.workflowDetail).toBe('wf-landscape');+ it.each(['right-click', 'Shift+F10', 'More button'] as const)(+ 'opens from a %s on another card, keeping the rail, and renames that workflow',+ async (path) => {+ await openWith(LOADED_SNAPSHOT);+ await act(() => card('wf-upscale')?.click());+ expect(detail()).toBe('wf-upscale');++ const trigger = await raise(path);++ await vi.waitFor(() => expect(openMenu()?.id).toBe('workflow-library-card-wf-landscape-actions'));+ expect(trigger.getAttribute('aria-controls')).toBe(openMenu()?.id);+ expect(trigger.getAttribute('aria-expanded')).toBe('true');+ expect(detail()).toBe('wf-upscale');+ expect(card('wf-upscale')?.getAttribute('aria-pressed')).toBe('true');+ expect(card('wf-landscape')?.getAttribute('aria-pressed')).toBe('false');++ await selectMenuItem(openMenu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="rename"]'));+ await act(settleFrame);+ const input = await vi.waitFor(() => {+ const element = document.querySelector<HTMLInputElement>('input[name="renameValue"]');+ expect(element?.value).toBe('Landscape Pass');+ return element!;+ });+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ await act(async () => {+ setValue?.call(input, 'Landscape, tuned');+ input.dispatchEvent(new Event('input', { bubbles: true }));+ await Promise.resolve();+ });+ await act(async () => {+ input.closest('form')?.querySelector<HTMLButtonElement>('button[type="submit"]')?.click();+ await settleFrame();+ });- const open = () => document.querySelector<HTMLElement>('[data-workflow-context-menu] [data-menu-item="open"]');+ expect(libraryWrites.update).toHaveBeenCalledExactlyOnceWith(+ 'wf-landscape',+ expect.objectContaining({ name: 'Landscape, tuned' }),+ expect.objectContaining({ expectedRevision: 3 })+ );+ expect(detail()).toBe('wf-upscale');+ }+ );- await vi.waitFor(() => expect(open()).not.toBeNull());- await act(() => open()?.click());+ it('runs Open on the card it was raised for', async () => {+ await openWith(LOADED_SNAPSHOT);+ await raise('right-click');- expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'first-copy');- });+ const open = () => openMenu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="open"]');+ await vi.waitFor(() => expect(open()).not.toBeUndefined());+ await selectMenuItem(open());- // The question mounts while the menu that asked it is still closing; the menu's teardown must not dismiss it.- it('keeps the copy question a card menu raised for a template the project already holds', async () => {- await openWith(LOADED_SNAPSHOT);+ expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'first-copy');+ expect(detail()).toBe('wf-portrait');+ });- await act(() =>- card('wf-portrait')?.dispatchEvent(- new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })- )- );+ it('deletes another card and keeps the selection; deleting the selected one clears it', async () => {+ await openWith(LOADED_SNAPSHOT);+ await act(() => card('wf-upscale')?.click());+ await raise('right-click');- const open = () => document.querySelector<HTMLElement>('[data-workflow-context-menu] [data-menu-item="open"]');+ await vi.waitFor(() =>+ expect(openMenu()?.querySelector('[role="menuitem"][data-value="delete"]')).not.toBeNull()+ );+ await selectMenuItem(openMenu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="delete"]'));+ await act(settleFrame);+ await vi.waitFor(() => expect(alertDialog()?.textContent).toContain('Landscape Pass'));+ await confirmIn('Delete');++ expect(libraryWrites.delete).toHaveBeenCalledExactlyOnceWith('wf-landscape', expect.anything());+ // The listing refreshes without it, as the store does after the invalidation.+ await act(() => browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT, SKETCH, UPSCALE], total: 23 })));+ expect(card('wf-landscape')).toBeNull();+ expect(detail()).toBe('wf-upscale');++ // The selected card's own menu deletes it as the rail does: the selection clears to the first entry.+ await act(() =>+ card('wf-upscale')?.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })+ )+ );+ await vi.waitFor(() =>+ expect(openMenu()?.querySelector('[role="menuitem"][data-value="delete"]')).not.toBeNull()+ );+ await selectMenuItem(openMenu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="delete"]'));+ await act(settleFrame);+ await vi.waitFor(() => expect(alertDialog()?.textContent).toContain('Upscale Chain'));+ await confirmIn('Delete');+ expect(libraryWrites.delete).toHaveBeenLastCalledWith('wf-upscale', expect.anything());+ await act(() => browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT, SKETCH], total: 22 })));+ expect(detail()).toBe('wf-portrait');+ });- await vi.waitFor(() => expect(open()).not.toBeNull());- await act(async () => {- open()?.click();- await settleFrame();+ it('keeps a confirmation opened from a menu on its own workflow when a refresh drops that card', async () => {+ await openWith(LOADED_SNAPSHOT);+ await raise('right-click');+ await vi.waitFor(() =>+ expect(openMenu()?.querySelector('[role="menuitem"][data-value="delete"]')).not.toBeNull()+ );+ await selectMenuItem(openMenu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="delete"]'));+ await act(settleFrame);+ await vi.waitFor(() => expect(alertDialog()?.textContent).toContain('Landscape Pass'));++ // A refresh drops the card (a re-sort, a newer record): the menu host loses its entry, not the dialog its target.+ await act(() => browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT, SKETCH, UPSCALE], total: 23 })));+ await settleAnimations();+ expect(alertDialog()?.getAttribute('data-state')).toBe('open');+ expect(alertDialog()?.textContent).toContain('Landscape Pass');+ await confirmIn('Cancel');+ await vi.waitFor(() => expect(alertDialog()).toBeNull());++ // The cancelled confirmation does not come back with the next writable card's menu.+ await act(() =>+ card('wf-upscale')?.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })+ )+ );+ await vi.waitFor(() => expect(openMenu()?.id).toBe('workflow-library-card-wf-upscale-actions'));await settleFrame();+ expect(alertDialog()).toBeNull();+ expect(libraryWrites.delete).not.toHaveBeenCalled();});- await vi.waitFor(() => expect(document.querySelector('[data-workflow-context-menu]')).toBeNull());- expect(document.querySelector('[data-library-copy-choice]')).not.toBeNull();- expect(loader.open).not.toHaveBeenCalled();- });+ it("offers Rename and Delete by the card's own access, not the selection's", async () => {+ identity.session = { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } };+ const othersShared = { ...NON_OWNER_SHARED, item: { ...NON_OWNER_SHARED.item, workflow_id: 'wf-shared' } };+ await openWith(withSnapshot({ entries: [OWNER_PRIVATE, othersShared] }));+ const items = () =>+ [...(openMenu()?.querySelectorAll<HTMLElement>('[role="menuitem"]') ?? [])].map((item) => item.dataset.value);+ const raiseOn = async (workflowId: string) => {+ await act(() =>+ card(workflowId)?.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })+ )+ );+ await vi.waitFor(() => expect(openMenu()?.id).toBe(`workflow-library-card-${workflowId}-actions`));+ };- it('closes the card context menu on Escape and hands focus back to the card', async () => {- await openWith(LOADED_SNAPSHOT);+ // The account's own template is selected; another account's is not the account's to change.+ expect(detail()).toBe('wf-portrait');+ await raiseOn('wf-shared');+ expect(items()).toEqual(['open', 'duplicate', 'fork-into-project', 'download-json']);+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(openMenu()).toBeNull());++ // And the other way round: with the read-only one selected, the own card's menu still offers its writes.+ await act(() => card('wf-shared')?.click());+ expect(detail()).toBe('wf-shared');+ await raiseOn('wf-portrait');+ expect(items()).toContain('rename');+ expect(items()).toContain('delete');+ });- // A keyboard-raised menu reports no pointer position.- await act(() =>- card('wf-landscape')?.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }))+ it.each(['default', 'shared'] as const)(+ 'keeps the selection when duplicating outside the %s place',+ async (place) => {+ setWorkflowLibraryTab(place);+ await openWith(withSnapshot({ filter: { ...LOADED_SNAPSHOT.filter, place } }));+ await act(() => card('wf-landscape')!.click());+ await act(() =>+ card('wf-sketch')!.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })+ )+ );+ await vi.waitFor(() => expect(openMenu()).not.toBeNull());+ await selectMenuItem(openMenu()?.querySelector<HTMLElement>('[data-value="duplicate"]'));+ await vi.waitFor(() => expect(libraryWrites.create).toHaveBeenCalledOnce());+ await act(settleFrame);+ expect(detail()).toBe('wf-landscape');+ });- const menu = () => document.querySelector<HTMLElement>('[data-workflow-context-menu]');+ it('duplicates the card it was raised for, once per press, and selects the copy', async () => {+ let finishCopy!: (workflowId: string) => void;+ libraryWrites.create.mockImplementationOnce(+ () =>+ new Promise<string>((resolve) => {+ finishCopy = resolve;+ })+ );+ await openWith(LOADED_SNAPSHOT);+ const duplicateItem = () => openMenu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="duplicate"]');+ const raiseOn = async (workflowId: string) => {+ await act(() =>+ card(workflowId)?.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })+ )+ );+ await vi.waitFor(() => expect(openMenu()?.id).toBe(`workflow-library-card-${workflowId}-actions`));+ };- // The positioner places the menu a frame after it mounts; anchored inside the card, not at the viewport corner.+ await raiseOn('wf-landscape');+ await selectMenuItem(duplicateItem());+ await act(settleFrame);+ expect(libraryWrites.cached).toHaveBeenCalledExactlyOnceWith(+ 'wf-landscape',+ expect.objectContaining({ expectedRevision: 1 })+ );+ await vi.waitFor(() => expect(libraryWrites.create).toHaveBeenCalledOnce());+ expect(libraryWrites.create.mock.calls[0]![0].name).toBe('Landscape Pass copy');++ // While that copy is in flight, the same workflow offers no second Duplicate; another workflow still does.+ await raiseOn('wf-landscape');+ expect(duplicateItem()?.hasAttribute('data-disabled')).toBe(true);+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(openMenu()).toBeNull());+ await raiseOn('wf-sketch');+ expect(duplicateItem()?.hasAttribute('data-disabled')).toBe(false);+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(openMenu()).toBeNull());++ await act(async () => {+ finishCopy('wf-landscape-copy');+ await settleFrame();+ });+ // Listed after the first entry, so only the selection, not the rail's first-entry fallback, shows the copy.+ const copy = entry('wf-landscape-copy', 'Landscape Pass copy', readyEnrichment(7, 'flux'));+ await act(() => browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT, LANDSCAPE, copy, SKETCH, UPSCALE] })));+ expect(detail()).toBe('wf-landscape-copy');+ expect(libraryWrites.create).toHaveBeenCalledOnce();+ });++ it('closes when its card leaves the listing', async () => {+ await openWith(LOADED_SNAPSHOT);+ await raise('right-click');+ await vi.waitFor(() => expect(openMenu()).not.toBeNull());++ await act(() => browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT, SKETCH, UPSCALE], total: 23 })));++ await vi.waitFor(() => expect(openMenu()).toBeNull());+ // Coming back later does not reopen it.+ await act(() => browse.setSnapshot?.(LOADED_SNAPSHOT));+ await settleFrame();+ expect(openMenu()).toBeNull();+ expect(card('wf-landscape')?.closest('[data-menu-open]')).toBeNull();+ });++ it('keeps one menu open: the rail’s More and a card’s menu close each other', async () => {+ await openWith(LOADED_SNAPSHOT);+ const railMore = document.querySelector<HTMLElement>('[data-workflow-detail] [aria-label="More actions"]')!;+ const isRailMenuOpen = () => railMore.getAttribute('aria-expanded') === 'true';++ await act(() => userEvent.click(railMore));+ await vi.waitFor(() => expect(isRailMenuOpen()).toBe(true));++ await act(() => userEvent.click(card('wf-landscape')!, { button: 'right' }));+ await vi.waitFor(() => expect(openMenu()?.id).toBe('workflow-library-card-wf-landscape-actions'));+ expect(isRailMenuOpen()).toBe(false);++ // One press, however quick: the card's menu closes before the rail's opens over it.+ await act(() => userEvent.click(railMore));+ await vi.waitFor(() => expect(isRailMenuOpen()).toBe(true));+ await vi.waitFor(() => expect(openMenu()).toBeNull());+ expect(card('wf-landscape')?.getAttribute('aria-expanded')).toBeNull();+ // The press that closed the card's menu keeps focus in the menu it opened, rather than back on the card.+ await vi.waitFor(() => expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull());+ await settleFrame();+ expect(isRailMenuOpen()).toBe(true);+ });++ it('leaves focus in the field a press moved it to when that press closes the menu', async () => {+ await openWith(LOADED_SNAPSHOT);+ await raise('right-click');+ await vi.waitFor(() => expect(openMenu()).not.toBeNull());+ const search = document.querySelector<HTMLInputElement>(+ 'input[placeholder="Search names, tags, or descriptions"]'+ )!;++ await act(() => userEvent.click(search));++ await vi.waitFor(() => expect(openMenu()).toBeNull());+ await settleFrame();+ expect(document.activeElement).toBe(search);++ // The next menu returns focus to its card again.+ await raise('right-click');+ await vi.waitFor(() => expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull());+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.activeElement).toBe(card('wf-landscape')));+ });+ });++ // The question mounts while the menu that asked it is still closing; the menu's teardown must not dismiss it.+ it('keeps the copy question a card menu raised for a template the project already holds', async () => {+ await openWith(LOADED_SNAPSHOT);++ await act(() =>+ card('wf-portrait')?.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 80 })+ )+ );++ const open = () =>+ document.querySelector<HTMLElement>('[data-workflow-context-menu] [role="menuitem"][data-value="open"]');++ await vi.waitFor(() => expect(open()).not.toBeNull());+ await selectMenuItem(open());+ await act(async () => {+ await settleFrame();+ await settleFrame();+ });++ await vi.waitFor(() => expect(document.querySelector('[data-workflow-context-menu]')).toBeNull());+ expect(document.querySelector('[data-library-copy-choice]')).not.toBeNull();+ expect(loader.open).not.toHaveBeenCalled();+ });++ it('closes the card context menu on Escape and hands focus back to the card', async () => {+ await openWith(LOADED_SNAPSHOT);++ // A keyboard-raised menu reports no pointer position.+ await act(() =>+ card('wf-landscape')?.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }))+ );++ const menu = () => document.querySelector<HTMLElement>('[data-workflow-context-menu]');++ // The positioner places the menu a frame after it mounts; anchored inside the card, not at the viewport corner.await vi.waitFor(() =>expect(menu()?.getBoundingClientRect().left ?? 0).toBeGreaterThan(card('wf-landscape')!.getBoundingClientRect().left@@ -1560,216 +2562,1440 @@ describe('WorkflowLibraryDialog', () => {it('opens the selected workflow from the rail, the keyboard-reachable path', async () => {await openWith(LOADED_SNAPSHOT);+ const railOpen = () => document.querySelector<HTMLButtonElement>('[data-workflow-detail-open]');+// Portrait needs nothing installed, but the project already holds a copy of it: Open asks what to do.- await clickText('Open…');+ expect(railOpen()?.textContent).toBe('Open…');+ await act(() => railOpen()?.click());expect(workflowUiStore.getSnapshot().libraryCopyChoice?.item.workflow_id).toBe(PORTRAIT.item.workflow_id);expect(loader.open).not.toHaveBeenCalled();// Upscale has no copy yet (and nothing to install first), so Open adds one.await act(() => card('wf-upscale')?.click());- await clickText('Open');+ expect(railOpen()?.textContent).toBe('Open');+ await act(() => railOpen()?.click());expect(loader.open).toHaveBeenCalledWith(UPSCALE.item, 'first-copy');});+ it('lists the selected template’s facts: callable, opened, copies here, updated and created', async () => {+ const hoursAgo = (hours: number) => new Date(Date.now() - hours * 60 * 60 * 1000).toISOString();+ const portrait = {+ ...PORTRAIT,+ item: {+ ...PORTRAIT.item,+ call_saved_workflow_compatibility: { is_callable: true, message: null, reason: 'ok' },+ created_at: hoursAgo(24 * 3),+ opened_at: hoursAgo(2),+ revision: 7,+ updated_at: hoursAgo(5),+ },+ };+ await openWith(withSnapshot({ entries: [portrait, LANDSCAPE] }));++ const detail = () => document.querySelector<HTMLElement>('[data-workflow-detail]')!;+ expect(detail().textContent).toContain('Opened 2 hours ago');+ expect(detail().querySelector('[data-workflow-callable]')?.textContent).toBe('Callable');+ const facts = () => detail().querySelector<HTMLElement>('[data-workflow-detail-facts]')!.textContent;+ // The project's one copy of Portrait was loaded at revision 4.+ expect(facts()).toContain('In this project1 copy · revision 4');+ expect(facts()).toContain('Updated5 hours ago · revision 7');+ expect(facts()).toContain('Created3 days ago');++ await act(() => card('wf-landscape')?.click());+ expect(facts()).toContain('In this projectNone');+ expect(detail().querySelector('[data-workflow-callable]')).toBeNull();+ });+it('badges the cards with the models their workflows still need', async () => {await openWith(LOADED_SNAPSHOT);- expect(card('wf-landscape')?.textContent).toContain('Install 1 model');- expect(card('wf-portrait')?.textContent).not.toContain('Install');+ expect(card('wf-landscape')?.textContent).toContain('1 model to install');+ expect(card('wf-portrait')?.textContent).not.toContain('to install');+ // The rail offers the install where it lists what the workflow requires.+ await act(() => card('wf-landscape')?.click());+ expect(buttonWithText('Install 1 model')?.closest('[data-workflow-detail]')).not.toBeNull();});- it('records the workflow the rail asked to preview', async () => {+ const quickAction = (workflowId: string, action: 'open' | 'preview') =>+ card(workflowId)+ ?.closest('[data-workflow-card-root]')+ ?.querySelector<HTMLButtonElement>(`[data-card-action="${action}"]`) ?? null;++ it('selects a small card from a real click at its centre after the pointer rests on it, never opening it', async () => {await openWith(LOADED_SNAPSHOT);+ const target = card('wf-upscale')!;+ const box = target.getBoundingClientRect();+ const centre = { x: box.width / 2, y: box.height / 2 };++ // Resting reveals the quick actions; none of them may sit under the card's centre.+ await act(() => userEvent.hover(target, { position: centre }));+ await vi.waitFor(() => expect(getComputedStyle(quickAction('wf-upscale', 'open')!).opacity).toBe('1'));+ const hit = document.elementFromPoint(box.left + centre.x, box.top + centre.y);+ expect(hit?.closest('[data-workflow-card]')).toBe(target);++ await act(() => userEvent.click(target, { position: centre }));+ expect(document.querySelector<HTMLElement>('[data-workflow-detail]')?.dataset.workflowDetail).toBe('wf-upscale');+ expect(target.getAttribute('aria-pressed')).toBe('true');+ expect(loader.open).not.toHaveBeenCalled();+ });++ it('keeps hidden quick actions from taking the pointer until the card shows them', async () => {+ await openWith(LOADED_SNAPSHOT);+ await act(() => userEvent.unhover(card('wf-landscape')!));+ const open = () => quickAction('wf-landscape', 'open');+ const menu = document.querySelector<HTMLElement>('[data-workflow-card-menu="wf-landscape"]')!;- await clickText('Preview graph');+ // At rest the strip is transparent and lets presses through to the card beneath.+ expect(getComputedStyle(menu).pointerEvents).toBe('none');- // Task 8 mounts the preview dialog from this pending selection.- expect(document.querySelector('[data-pending-preview="wf-portrait"]')).not.toBeNull();+ await act(() => userEvent.hover(card('wf-landscape')!));+ await vi.waitFor(() => expect(getComputedStyle(open()!).pointerEvents).toBe('auto'));+ await act(() => userEvent.click(open()!));+ expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'first-copy');});- it("mounts the lazy preview dialog with the entry's compiled graph and hides Invoke", async () => {- await openWith(withSnapshot({ entries: [PORTRAIT, PREVIEW_FIXTURE] }));+ it.each(['classic', 'light'])(+ 'steps the opaque Preview and More quick actions on hover, and More while its menu is open (%s)',+ async (theme) => {+ // The default theme is the root's; others are named by its data-theme.+ if (theme !== 'classic') {+ document.documentElement.dataset.theme = theme;+ onTestFinished(() => {+ delete document.documentElement.dataset.theme;+ });+ }+ await openWith(LOADED_SNAPSHOT);+ const preview = () => quickAction('wf-landscape', 'preview')!;+ const more = document.querySelector<HTMLElement>('[data-workflow-card-menu="wf-landscape"]')!;++ // Over the card, the actions show on their panel fill.+ await act(() => userEvent.hover(card('wf-landscape')!));+ await vi.waitFor(() => expect(getComputedStyle(preview()).opacity).toBe('1'));+ await act(() => settleAnimations(preview()));+ const rest = getComputedStyle(preview()).backgroundColor;+ expect(getComputedStyle(more).backgroundColor).toBe(rest);++ await act(() => userEvent.hover(preview()));+ await vi.waitFor(() => expect(getComputedStyle(preview()).backgroundColor).not.toBe(rest));++ await act(() => userEvent.hover(more));+ await vi.waitFor(() => expect(getComputedStyle(more).backgroundColor).not.toBe(rest));++ await pressTileMenuButton(more);+ await vi.waitFor(() => expect(more.getAttribute('aria-expanded')).toBe('true'));+ // With the pointer on the open menu, not the button, the button still shows the state.+ const menu = await vi.waitFor(() => {+ const element = document.querySelector<HTMLElement>('[data-workflow-context-menu][data-state="open"]');+ expect(element).not.toBeNull();+ return element!;+ });+ await act(() => settleAnimations(menu));+ await act(() => userEvent.hover(menu));+ expect(more.matches(':hover')).toBe(false);+ await vi.waitFor(() => expect(getComputedStyle(more).backgroundColor).not.toBe(rest));+ }+ );- await act(() => card('wf-preview-fixture')?.click());- await clickText('Preview graph');- await waitForPreviewDialog();+ it('opens from the Open quick action without taking focus, asking first when the project holds a copy', async () => {+ await openWith(LOADED_SNAPSHOT);- const preview = document.querySelector('[data-preview-dialog]');- expect(preview).not.toBeNull();- expect(preview?.getAttribute('data-graph-id')).toBe('wf-preview-fixture');- expect(preview?.getAttribute('data-hide-invoke')).toBe('true');- expect(preview?.getAttribute('data-source-label')).toBe('Preview Fixture');- // The document's one `integer` node made it through compilation.- expect(preview?.textContent).toContain('integer');+ // The project holds a copy of Portrait: the quick action says so and asks, as the rail does.+ await act(() => userEvent.hover(card('wf-portrait')!));+ expect(quickAction('wf-portrait', 'open')?.textContent).toBe('Open…');+ await act(() => userEvent.click(quickAction('wf-portrait', 'open')!));+ expect(workflowUiStore.getSnapshot().libraryCopyChoice?.item.workflow_id).toBe('wf-portrait');+ expect(loader.open).not.toHaveBeenCalled();+ // A pointer-only control hands focus to its card, so the question it raised returns focus there.+ await vi.waitFor(() => expect(document.querySelector('[data-library-copy-choice]')).not.toBeNull());+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.activeElement).toBe(card('wf-portrait')));++ await act(() => userEvent.hover(card('wf-upscale')!));+ expect(quickAction('wf-upscale', 'open')?.textContent).toBe('Open');+ await act(() => userEvent.click(quickAction('wf-upscale', 'open')!));+ expect(loader.open).toHaveBeenCalledWith(UPSCALE.item, 'first-copy');+ expect(document.activeElement).toBe(card('wf-upscale'));});- it('commits the first preview in the click that opens it once the library has loaded the dialog', async () => {+ it('keeps Open and Preview out of the tab order: Tab goes from a card to its menu button', async () => {await openWith(withSnapshot({ entries: [PORTRAIT, PREVIEW_FIXTURE] }));- await act(() => card('wf-preview-fixture')?.click());- await vi.dynamicImportSettled();+ await act(() => userEvent.hover(card('wf-preview-fixture')!));+ expect(quickAction('wf-preview-fixture', 'open')?.tabIndex).toBe(-1);+ expect(quickAction('wf-preview-fixture', 'preview')?.tabIndex).toBe(-1);- // A Suspense reveal here lets StrictMode replay the open dialog's effects after its focus trap started.- act(() => (buttonWithText('Preview graph') as HTMLButtonElement).click());+ await act(() => card('wf-preview-fixture')!.focus());+ await act(() => userEvent.keyboard('{Tab}'));- expect(document.querySelector('[data-preview-dialog]')?.getAttribute('data-preview-open')).toBe('true');+ expect(document.activeElement?.getAttribute('data-workflow-card-menu')).toBe('wf-preview-fixture');});- it('disables the Preview action for an entry whose enrichment is not ready', async () => {+ it('suppresses the native menu on the actions strip and menu button, and keeps an open menu for retargeting', async () => {await openWith(LOADED_SNAPSHOT);+ const menuButton = document.querySelector<HTMLElement>('[data-workflow-card-menu="wf-landscape"]')!;+ const strip = menuButton.closest<HTMLElement>('[data-workflow-card-actions]')!;- await act(() => card('wf-sketch')?.click());+ const contextMenu = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 300, clientY: 300 });+ await act(() => menuButton.dispatchEvent(contextMenu));+ expect(contextMenu.defaultPrevented).toBe(true);+ await vi.waitFor(() =>+ expect(document.querySelector('[data-workflow-context-menu][data-state="open"]')).not.toBeNull()+ );+ expect(document.querySelector('[data-workflow-detail]')?.getAttribute('data-workflow-detail')).toBe('wf-portrait');++ // An open menu treats a right-click on a card's strip, or a press on a menu button, as a retarget, not a dismissal.+ const retargets = (target: Element, button: number) => {+ const preventDefault = vi.fn();+ const original = new PointerEvent('pointerdown', { bubbles: true, button });+ target.addEventListener(+ 'pointerdown',+ (event) => keepCardMenuOpenForRetarget({ detail: { originalEvent: event }, preventDefault }),+ { once: true }+ );+ target.dispatchEvent(original);+ return preventDefault.mock.calls.length > 0;+ };+ expect(retargets(strip, 2)).toBe(true);+ expect(retargets(menuButton, 0)).toBe(true);+ expect(retargets(strip, 0)).toBe(false);+ expect(retargets(document.querySelector('[data-workflow-detail]')!, 2)).toBe(false);+ });- const button = buttonWithText('Preview graph') as HTMLButtonElement | undefined;- expect(button?.disabled).toBe(true);+ it('keeps focus on the same workflow when a card-size change moves it to another row', async () => {+ await resizeViewport(1280, 800);+ const entries = Array.from({ length: 24 }, (_, index) => ({+ ...PORTRAIT,+ item: { ...PORTRAIT.item, workflow_id: `size-${index}` },+ }));+ await openWith({ ...LOADED_SNAPSHOT, entries, total: 24, pages: 2 });+ const before = card('size-11')!;+ await act(() => before.focus());+ const rowBefore = before.closest('[data-index]')?.getAttribute('data-index');++ await act(async () => {+ preferences.setSnapshot({ ...preferences.port.getSnapshot(), workflowLibraryCardSize: 'large' });+ await settleFrame();+ });++ await vi.waitFor(() => {+ const after = card('size-11')!;+ expect(after.closest('[data-index]')?.getAttribute('data-index')).not.toBe(rowBefore);+ expect(document.activeElement).toBe(after);+ });});- it('keeps the preview mounted through its exit transition, then resets the pending preview', async () => {- await openWith(withSnapshot({ entries: [PORTRAIT, PREVIEW_FIXTURE] }));+ it('pins the scroll area’s overflow properties above the cards, so scrolling restyles none of them', async () => {+ const entries = Array.from({ length: 60 }, (_, index) => ({+ ...PORTRAIT,+ item: { ...PORTRAIT.item, workflow_id: `pin-${index}` },+ }));+ await openWith({ ...LOADED_SNAPSHOT, entries, total: 60, pages: 3 });+ const viewport = gridViewport()!;+ await act(async () => {+ viewport.scrollTop = 400;+ viewport.dispatchEvent(new Event('scroll'));+ await settleFrame();+ });++ // Whatever custom properties the scroll area writes on its viewport, none may reach the cards changing.+ const viewportProperties = () => [...viewport.style].filter((name) => name.startsWith('--'));+ await vi.waitFor(() => expect(viewportProperties().length).toBeGreaterThan(0));+ const style = getComputedStyle(cards()[0]!);+ for (const name of viewportProperties()) {+ expect(['', '0px'], name).toContain(style.getPropertyValue(name).trim());+ }+ });++ describe('preview mode', () => {+ const stageButton = (label: string) =>+ [...(stage()?.querySelectorAll<HTMLButtonElement>('button') ?? [])].find(+ (button) => button.getAttribute('aria-label') === label || button.textContent === label+ ) ?? null;+ const previewNodes = () => [...(stage()?.querySelectorAll<HTMLElement>('.react-flow__node') ?? [])];+ const previewNode = (id: string) =>+ stage()?.querySelector<HTMLElement>(`.react-flow__node[data-id="${id}"]`) ?? null;+ const emphasis = (id: string) =>+ stage()?.querySelector<HTMLElement>(`[data-preview-node="${id}"]`)?.dataset.emphasis ?? null;+ const nodeCard = () => stage()?.querySelector<HTMLElement>('[data-preview-node-card]') ?? null;+ // The stepper sits with the rail's workflow: atop the rail, or in the narrow sheet's summary.+ const stepper = () => [...document.querySelectorAll<HTMLElement>('[data-preview-stepper]')].find(isShown) ?? null;+ const stepButton = (label: string) =>+ stepper()?.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`) ?? null;+ const positionText = () => stepper()?.querySelector('[data-preview-position]')?.textContent || null;+ const railId = () => document.querySelector<HTMLElement>('[data-workflow-detail]')?.dataset.workflowDetail;+ const railPreview = () => document.querySelector<HTMLButtonElement>('[data-workflow-preview-trigger]');+ const collection = () => document.querySelector<HTMLElement>('[data-workflow-library-collection]');+ const press = (key: string) => act(() => userEvent.keyboard(key));+ const previewGraph = async (+ snapshot: WorkflowLibraryBrowseSnapshot = withSnapshot({ entries: [GRAPH_ENTRY], total: 1 })+ ) => {+ await openWith(snapshot);+ await act(() => card('wf-graph')?.click());+ await clickText('Preview');+ await waitForPreviewGraph();+ };++ // The library preloads the graph chunk as it opens; a cold import can outlast `waitFor` under load.+ beforeAll(() =>+ Promise.all([loadGraphPreview(), import('@features/workflow/ui/graph-preview/WorkflowPreviewJson')])+ );++ beforeEach(() => {+ browse.loadWorkflowLibraryRange.mockClear();+ downloads.downloadText.mockClear();+ });++ it('takes the places rail and the collection, keeps the detail rail, and opens no second dialog', async () => {+ await openWith(withSnapshot({ entries: [PORTRAIT, GRAPH_ENTRY], total: 2 }));+ await act(() => card('wf-graph')?.click());+ await clickText('Preview');++ expect(stage()?.getAttribute('aria-label')).toBe('Preview of Graph Fixture');+ expect(document.activeElement).toBe(stage());+ expect(document.querySelectorAll('[data-scope="dialog"][data-part="content"]')).toHaveLength(1);+ expect(getComputedStyle(collection()!).visibility).toBe('hidden');+ expect(getComputedStyle(document.querySelector('[data-library-rail-slot]')!).visibility).toBe('hidden');+ // The rail still describes the workflow and still opens it; its Preview button has nothing left to do.+ expect(railId()).toBe('wf-graph');+ expect(isShown(document.querySelector('[data-workflow-detail-open]'))).toBe(true);+ expect(isShown(railPreview())).toBe(false);+ await waitForPreviewGraph();+ expect(previewNodes()).toHaveLength(4);+ });++ it('has accessible library and preview surfaces', async () => {+ const wasDark = document.documentElement.classList.contains('dark');+ document.documentElement.classList.add('dark');+ onTestFinished(() => {+ document.documentElement.classList.toggle('dark', wasDark);+ });+ await openWith(withSnapshot({ entries: [PORTRAIT, GRAPH_ENTRY], total: 2 }));+ const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]')!;+ expect(+ await auditAccessibility(dialog(), { rules: { 'label-content-name-mismatch': { enabled: true } } })+ ).toEqual([]);+ await act(() => card('wf-graph')!.click());+ await act(() => railPreview()!.click());+ await waitForPreviewGraph();+ expect(+ await auditAccessibility(dialog(), { rules: { 'label-content-name-mismatch': { enabled: true } } })+ ).toEqual([]);+ });++ it('selects cards with Space and previews from the named Preview button; Escape returns to the collection', async () => {+ await openWith(LOADED_SNAPSHOT);+ await act(() => card('wf-landscape')!.focus());+ await press(' ');+ expect(stage()).toBeNull();+ expect(railId()).toBe('wf-landscape');+ expect(railPreview()?.tabIndex).toBe(0);+ await act(() => railPreview()!.focus());+ await press(' ');++ expect(stage()).not.toBeNull();+ expect(railId()).toBe('wf-landscape');++ await press('{Escape}');+ expect(stage()).toBeNull();+ expect(document.activeElement).toBe(railPreview());+ expect(onOpenChange).not.toHaveBeenCalled();++ await act(() => userEvent.hover(card('wf-portrait')!));+ await act(() => userEvent.click(quickAction('wf-portrait', 'preview')!));+ expect(stage()).not.toBeNull();+ expect(railId()).toBe('wf-portrait');++ await press('{Escape}');+ expect(stage()).toBeNull();+ await press('{Escape}');+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('returns to the collection as it left it: scroll position, selection and the control that opened it', async () => {+ const entries = Array.from({ length: 40 }, (_, index) => ({+ ...PORTRAIT,+ item: { ...PORTRAIT.item, workflow_id: `scroll-${index}`, name: `Scroll ${index}` },+ }));+ await openWith(withSnapshot({ entries, total: entries.length }));+ const viewport = gridViewport()!;+ await act(async () => {+ viewport.scrollTop = 600;+ viewport.dispatchEvent(new Event('scroll'));+ await settleFrame();+ });+ await act(() => card('scroll-12')!.click());+ await act(() => userEvent.click(railPreview()!));++ await act(() => stageButton('Back to My library')!.click());++ expect(stage()).toBeNull();+ expect(gridViewport()!.scrollTop).toBe(600);+ expect(railId()).toBe('scroll-12');+ expect(document.activeElement).toBe(railPreview());+ });++ it('steps through the results in order, selecting each, and stops at the ends', async () => {+ await openWith(withSnapshot({ total: 4 }));+ await clickText('Preview');++ expect(railId()).toBe('wf-portrait');+ expect(positionText()).toBe('1 of 4');+ expect(stepButton('Previous workflow')?.getAttribute('aria-disabled')).toBe('true');++ await act(() => userEvent.click(stepButton('Next workflow')!));+ expect(railId()).toBe('wf-landscape');+ expect(positionText()).toBe('2 of 4');+ expect(document.activeElement).toBe(stepButton('Next workflow'));++ // The arrow keys step while focus is on the stepper, which keeps it as the rail moves on.+ await act(() => stepButton('Next workflow')!.focus());+ await press('{ArrowDown}');+ expect(railId()).toBe('wf-sketch');+ expect(document.activeElement).toBe(stepButton('Next workflow'));+ // It sits atop the rail, above the workflow's name, and steps the workflow the rail describes.+ const rail = document.querySelector<HTMLElement>('[data-workflow-detail]')!;+ expect(rail.contains(stepper())).toBe(true);+ expect(stage()?.querySelector('[data-preview-stepper]')).toBeNull();+ expect(stage()?.querySelector('[role="status"]')?.textContent).toBe('Loading workflow…');++ await press('{ArrowDown}');+ expect(railId()).toBe('wf-upscale');+ expect(positionText()).toBe('4 of 4');+ expect(stage()?.querySelector('[role="alert"]')?.textContent).toBe(+ "This workflow can't be previewed: unreadable"+ );+ expect(stepButton('Next workflow')?.getAttribute('aria-disabled')).toBe('true');+ await press('{ArrowDown}');+ expect(railId()).toBe('wf-upscale');++ await press('{ArrowUp}');+ expect(railId()).toBe('wf-sketch');++ // Leaving after stepping hands focus to the card now selected.+ await press('{Escape}');+ expect(document.activeElement).toBe(card('wf-sketch'));+ });++ it('reads the next position past the resident window, and shows no position for a selection outside it', async () => {+ await openWith(withSnapshot({ entries: [PORTRAIT, LANDSCAPE], total: 24 }));+ await act(() => card('wf-landscape')!.click());+ await clickText('Preview');+ expect(positionText()).toBe('2 of 24');++ browse.loadWorkflowLibraryRange.mockImplementationOnce(() => {+ browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT, LANDSCAPE, SKETCH], total: 24 }));+ return Promise.resolve(true);+ });+ await act(async () => {+ stepButton('Next workflow')!.click();+ await settleFrame();+ });+ expect(browse.loadWorkflowLibraryRange).toHaveBeenCalledWith(2, 2);+ expect(railId()).toBe('wf-sketch');+ expect(positionText()).toBe('3 of 24');++ await press('{Escape}');+ // A pinned selection whose page left the window: its position is unknown, so neither the count nor stepping.+ await act(() => browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT], selectedEntry: SKETCH, total: 24 })));+ await clickText('Preview');+ expect(railId()).toBe('wf-sketch');+ expect(positionText()).toBeNull();+ expect(stepButton('Previous workflow')?.getAttribute('aria-disabled')).toBe('true');+ expect(stepButton('Next workflow')?.getAttribute('aria-disabled')).toBe('true');+ // The reason says why: not that this is the first or last workflow.+ for (const label of ['Previous workflow', 'Next workflow']) {+ const reason = stepButton(label)?.querySelector('span[hidden]')?.textContent;+ expect(reason).toBe("Its place in these results isn't loaded");+ }+ });++ it('ignores a step past the loaded window that arrives after the preview has closed', async () => {+ await openWith(withSnapshot({ entries: [PORTRAIT, LANDSCAPE], total: 24 }));+ await act(() => card('wf-landscape')!.click());+ await clickText('Preview');+ let arrive!: () => void;+ browse.loadWorkflowLibraryRange.mockImplementationOnce(+ () =>+ new Promise<boolean>((resolve) => {+ arrive = () => {+ browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT, LANDSCAPE, SKETCH], total: 24 }));+ resolve(true);+ };+ })+ );+ await act(() => stepButton('Next workflow')!.click());+ await press('{Escape}');++ await act(async () => {+ arrive();+ await settleFrame();+ });++ expect(stage()).toBeNull();+ expect(railId()).toBe('wf-landscape');+ });++ it.each(['selection', 'search', 'filter'] as const)('ignores a late step after a new %s intent', async (change) => {+ await openWith(withSnapshot({ entries: [PORTRAIT, LANDSCAPE], total: 24 }));+ await act(() => card('wf-landscape')!.click());+ await clickText('Preview');+ let arrive!: () => void;+ browse.loadWorkflowLibraryRange.mockImplementationOnce(+ () =>+ new Promise<boolean>((resolve) => {+ arrive = () => {+ browse.setSnapshot?.({ ...browse.getSnapshot!(), entries: [PORTRAIT, LANDSCAPE, SKETCH], total: 24 });+ resolve(true);+ };+ })+ );+ await act(() => stepButton('Next workflow')!.click());+ await act(() => {+ if (change === 'selection') {+ card('wf-portrait')!.dispatchEvent(new MouseEvent('click', { bubbles: true }));+ } else if (change === 'search') {+ setWorkflowLibrarySearch('cat');+ } else {+ browse.setSnapshot?.({+ ...browse.getSnapshot!(),+ filter: { ...browse.getSnapshot!().filter, search: 'cat' },+ });+ }+ });+ if (change === 'selection') {+ expect(railId()).toBe('wf-portrait');+ }+ await act(async () => {+ arrive();+ await settleFrame();+ });++ expect(railId()).toBe(change === 'selection' ? 'wf-portrait' : 'wf-landscape');+ });++ it('draws the saved document simplified, with editor titles and markers, and every node on Show all', async () => {+ await previewGraph();++ expect(previewNodes().map((node) => node.getAttribute('aria-label'))).toEqual([+ 'Main Model Model not installed you set this needs a model',+ 'Prompt Denoise Latents 30 steps · cfg 3.5 you set this',+ 'Latents to Image',+ 'mask_refine Node pack missing unknown node type result',+ ]);+ expect(previewNode('denoise')?.textContent).toBe('Prompt Denoise Latents 30 steps · cfg 3.5');+ expect(previewNode('refine')?.textContent).toBe('mask_refine Node pack missing');+ expect([...stage()!.querySelectorAll('[data-preview-legend] li')].map((item) => item.textContent)).toEqual([+ 'You set this',+ 'Needs a model',+ 'Result',+ ]);+ expect(stage()?.querySelector('[data-preview-node-count]')?.textContent).toBe(+ 'Showing 4 of 6 nodes · 2 helpers folded' + 'Show all 6'+ );++ await act(() => stageButton('Show all 6')!.click());+ await vi.waitFor(() => expect(previewNodes()).toHaveLength(6));+ expect(previewNode('prompt')?.getAttribute('aria-label')).toBe('String Primitive you set this');+ expect(stage()?.querySelector('[data-preview-node-count]')?.textContent).toBe(+ 'Showing all 6 nodes, as drawn' + 'Simplify'+ );++ await act(() => stageButton('Simplify')!.click());+ await vi.waitFor(() => expect(previewNodes()).toHaveLength(4));+ });++ it('opens a node card beside the node, lighting its connections; Escape closes the card before the preview', async () => {+ await previewGraph();+ await act(() => previewNode('denoise')!.focus());+ await press('{Enter}');++ const card = nodeCard()!;+ expect(card.getAttribute('role')).toBe('dialog');+ expect(document.activeElement).toBe(card);+ expect(card.textContent).toContain('denoise_latents');+ expect(+ [...card.querySelectorAll('dl > div')].map((row) => [+ row.querySelector('dt')?.textContent,+ row.querySelector('dd')?.textContent,+ ])+ ).toEqual([+ ['Stepsyou set this', '30'],+ ['Cfg scale', '3.5'],+ ]);+ expect(emphasis('denoise')).toBe('selected');+ expect(emphasis('model')).toBe('related');+ expect(emphasis('decode')).toBe('related');+ expect(emphasis('refine')).toBeNull();+ // The card sits beside its node, not over it.+ const nodeBox = previewNode('denoise')!.getBoundingClientRect();+ const cardBox = card.getBoundingClientRect();+ expect(+ cardBox.left >= nodeBox.right ||+ cardBox.right <= nodeBox.left ||+ cardBox.top >= nodeBox.bottom ||+ cardBox.bottom <= nodeBox.top+ ).toBe(true);++ await press('{Escape}');+ expect(nodeCard()).toBeNull();+ expect(document.activeElement).toBe(previewNode('denoise'));+ expect(emphasis('model')).toBeNull();+ expect(stage()).not.toBeNull();++ // A neighbour's chip selects that node instead.+ await act(() => userEvent.click(previewNode('denoise')!));+ await act(() =>+ [...nodeCard()!.querySelectorAll('button')].find((button) => button.textContent === 'Latents to Image')!.click()+ );+ expect(nodeCard()?.dataset.previewNodeCard).toBe('decode');+ expect(emphasis('refine')).toBe('related');++ await press('{Escape}');+ await press('{Escape}');+ expect(stage()).toBeNull();+ expect(onOpenChange).not.toHaveBeenCalled();+ });++ it('finds nodes by title or type id, and Enter brings each match into view in turn', async () => {+ await previewGraph();+ const find = stage()!.querySelector<HTMLInputElement>('input[aria-label="Find a node"]')!;++ await act(() => userEvent.type(find, 'latents'));+ expect(stage()?.textContent).toContain('2 matches');+ expect(emphasis('denoise')).toBe('match');+ expect(emphasis('decode')).toBe('match');+ expect(emphasis('model')).toBeNull();++ await press('{Enter}');+ expect(emphasis('denoise')).toBe('current');+ await press('{Enter}');+ expect(emphasis('denoise')).toBe('match');+ expect(emphasis('decode')).toBe('current');++ await act(() => userEvent.clear(find));+ expect(emphasis('decode')).toBeNull();+ await act(() => userEvent.type(find, 'nothing here'));+ expect(stage()?.textContent).toContain('No matches');+ });++ it('opens a graph too wide to fit legibly at a readable zoom from its start, with a minimap', async () => {+ const chain: ProjectGraphState = {+ ...createProjectGraph('chain', 'Long chain'),+ edges: Array.from({ length: 29 }, (_, index) =>+ graphEdge(`step-${index}`, `step-${index + 1}`, 'latents', 'latents')+ ),+ nodes: Array.from({ length: 30 }, (_, index) => graphNode(`step-${index}`, 'l2i', { x: index * 400, y: 0 })),+ };+ await previewGraph(+ withSnapshot({+ entries: [entry('wf-graph', 'Long chain', readyEnrichment(30, null, NO_REQUIREMENTS, chain))],+ total: 1,+ })+ );++ expect(stage()?.querySelector('.react-flow__minimap')).not.toBeNull();+ // Titles are 12px at the default root size: the readable floor keeps them at 10px.+ expect(stage()?.textContent).toContain(`${Math.round((10 / 12) * 100)}%`);+ const first = previewNode('step-0')!.getBoundingClientRect();+ const pane = stage()!.querySelector('.react-flow')!.getBoundingClientRect();+ expect(first.left).toBeGreaterThanOrEqual(pane.left);+ expect(first.left - pane.left).toBeLessThan(64);+ });++ it('exports the saved workflow document from its menu, in the editor’s own export shape', async () => {+ await previewGraph();+ const exportItem = (value: string) =>+ document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`);+ await act(() => userEvent.click(stageButton('Export')!));+ await vi.waitFor(() => expect(exportItem('download-workflow-json')).not.toBeNull());+ expect(exportItem('copy-workflow-json')).not.toBeNull();++ await selectMenuItem(exportItem('download-workflow-json'));++ expect(downloads.downloadText).toHaveBeenCalledWith(+ JSON.stringify(serializeWorkflowJson(GRAPH_DOCUMENT), null, 2),+ 'Graph Fixture.json',+ 'application/json'+ );+ });++ const tabs = () => [...(stage()?.querySelectorAll<HTMLElement>('[role="tab"]') ?? [])];+ const selectTab = (name: string) =>+ act(() => userEvent.click(tabs().find((tab) => tab.textContent?.startsWith(name))!));+ const previewInputs = () => [...(stage()?.querySelectorAll<HTMLElement>('[data-preview-input]') ?? [])];+ const inputRow = (label: string) =>+ previewInputs().find((input) => input.querySelector('p')?.textContent === label) ?? null;++ it('switches between Nodes, Inputs and Graph as tabs, keeping the choice until the library closes', async () => {+ await previewGraph();++ expect(tabs().map((tab) => [tab.textContent, tab.getAttribute('aria-selected')])).toEqual([+ ['Nodes', 'true'],+ ['Inputs 3', 'false'],+ ['Graph', 'false'],+ ]);+ const panel = () => stage()!.querySelector<HTMLElement>('[role="tabpanel"]')!;+ expect(panel().getAttribute('aria-labelledby')).toBe(tabs()[0]!.id);++ await selectTab('Inputs');+ expect(panel().getAttribute('aria-labelledby')).toBe(tabs()[1]!.id);+ expect(previewInputs()).toHaveLength(3);+ // Finding a node belongs to the nodes.+ expect(stage()?.querySelector('[data-preview-find]')).toBeNull();++ // Leaving and previewing again keeps Inputs; closing the library goes back to Nodes.+ await press('{Escape}');+ await clickText('Preview');+ expect(tabs()[1]?.getAttribute('aria-selected')).toBe('true');+ await act(async () => {+ document.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!.click();+ await settleFrame();+ });+ await renderDialog(false);+ await renderDialog(true);+ await clickText('Preview');+ expect(tabs()[0]?.getAttribute('aria-selected')).toBe('true');+ });++ it('keeps the tabs and Export where they are in every view; only find comes and goes', async () => {+ await resizeViewport(1280, 800);+ await previewGraph();+ // The dialog's opening animation scales it; measure once it has played.+ await act(async () => {+ await vi.waitFor(() =>+ expect(+ document+ .querySelector('[data-scope="dialog"][data-part="content"]')!+ .getAnimations({ subtree: true })+ .filter((animation) => animation.playState === 'running')+ ).toEqual([])+ );+ });++ const where = () => ({+ export: stageButton('Export')!.getBoundingClientRect().toJSON(),+ tabs: stage()!.querySelector('[role="tablist"]')!.getBoundingClientRect().toJSON(),+ });+ const onNodes = where();++ expect(isShown(stage()!.querySelector('[data-preview-find]'))).toBe(true);+ // The tabs lead, after the back button; find and Export close the bar.+ expect(onNodes.tabs.right).toBeLessThan(+ stage()!.querySelector('[data-preview-find]')!.getBoundingClientRect().left+ );++ for (const name of ['Inputs', 'Graph', 'Nodes']) {+ await selectTab(name);+ expect(where()).toEqual(onNodes);+ expect(stage()?.querySelector('[data-preview-find]') !== null).toBe(name === 'Nodes');+ }+ });- await act(() => card('wf-preview-fixture')?.click());- await clickText('Preview graph');- await waitForPreviewDialog();+ it('shows in Graph the graph the workflow compiles to, or in words why it does not compile', async () => {+ const json = () => stage()?.querySelector('[data-preview-json] code')?.textContent ?? null;- expect(document.querySelector('[data-preview-dialog]')?.getAttribute('data-preview-open')).toBe('true');+ await previewGraph();+ await selectTab('Graph');+ await act(async () => {+ await vi.waitFor(() => expect(json()).not.toBeNull(), { timeout: 5000 });+ });++ // What the server is sent: the backend graph, its nodes by id.+ expect(Object.keys((JSON.parse(json()!) as { nodes: Record<string, unknown> }).nodes)).toEqual(+ expect.arrayContaining(['denoise', 'decode'])+ );++ // A workflow that cannot compile says why; its nodes still show.+ const broken = {+ ...GRAPH_DOCUMENT,+ // A plain connection on a loop's linkage handle: the editor refuses to compile it.+ edges: [...GRAPH_DOCUMENT.edges, graphEdge('decode', 'denoise', 'loop_linkage', 'latents')],+ };+ await act(() =>+ browse.setSnapshot?.(+ withSnapshot({+ entries: [entry('wf-graph', 'Graph Fixture', readyEnrichment(6, 'flux', NO_REQUIREMENTS, broken))],+ total: 1,+ })+ )+ );+ expect(json()).toBeNull();+ expect(stage()?.querySelector('[role="tabpanel"] [role="alert"]')?.textContent).toBe(+ "This graph can't compile yet. For loop validation failed: Loop linkage must connect a For to its ForReturn."+ );+ await selectTab('Nodes');+ await waitForPreviewGraph();+ });- await clickText('Close preview');+ it('shows the form read-only: saved values, a model to install, and the node each input sets', async () => {+ await previewGraph();+ await selectTab('Inputs');++ expect([...stage()!.querySelectorAll('h3')].map((heading) => heading.textContent)).toEqual([+ 'Prompting',+ 'Model',+ ]);+ const value = (label: string) => inputRow(label)?.querySelector<HTMLElement>('[data-input-value]');+ expect(value('Prompt')?.textContent).toBe('a lighthouse at dusk, long exposure');+ // A text that fits its box is no tab stop.+ expect(value('Prompt')?.hasAttribute('tabindex')).toBe(false);+ expect(value('Steps')?.textContent).toBe('30');+ // No model picked, and none this server could use: the rail's wording and warning tone.+ expect(value('Model')?.dataset.inputValue).toBe('missing');+ expect(value('Model')?.textContent).toBe('FLUX checkpoint · Not installed');+ // The border is the theme's warning colour in its own right, not a fallback to the text colour: it holds when+ // the text is recoloured (as it is for a model that cannot be installed).+ const warningProbe = document.createElement('span');+ warningProbe.style.color = 'var(--chakra-colors-fg\\.warning)';+ document.body.append(warningProbe);+ const warningColor = getComputedStyle(warningProbe).color;+ warningProbe.remove();+ value('Model')!.style.color = 'rgb(1, 2, 3)';+ expect(getComputedStyle(value('Model')!).borderColor).toBe(warningColor);+ value('Model')!.style.removeProperty('color');++ // An input's node opens selected in the graph; a folded helper's opens with every node shown.+ await act(() => userEvent.click(inputRow('Steps')!.querySelector('button')!));+ await waitForPreviewGraph();+ expect(tabs()[0]?.getAttribute('aria-selected')).toBe('true');+ expect(nodeCard()?.dataset.previewNodeCard).toBe('denoise');+ expect(document.activeElement).toBe(nodeCard());++ await selectTab('Inputs');+ await act(() => userEvent.click(inputRow('Prompt')!.querySelector('button')!));+ await waitForPreviewGraph();+ expect(nodeCard()?.dataset.previewNodeCard).toBe('prompt');+ expect(previewNodes()).toHaveLength(6);+ });++ it('says when a workflow exposes no inputs', async () => {+ await openWith(withSnapshot({ entries: [PREVIEW_FIXTURE], total: 1 }));+ await clickText('Preview');+ await selectTab('Inputs');++ expect(tabs()[1]?.textContent).toBe('Inputs 0');+ expect(stage()?.textContent).toContain('This workflow exposes no inputs. Its values are set on its nodes.');+ });++ it('describes the workflow in the rail: where it comes from, what you set and the author’s notes', async () => {+ await openWith(withSnapshot({ entries: [GRAPH_ENTRY], total: 1 }));+ const rail = () => document.querySelector<HTMLElement>('[data-workflow-detail="wf-graph"]')!;++ expect(rail().querySelector('[data-workflow-provenance]')?.textContent).toBe('My library · by Invoke · v1.2.0');+ expect(rail().querySelector('[data-workflow-inputs-count]')?.textContent).toBe('3 inputs');+ expect(+ [...rail().querySelectorAll('[data-workflow-inputs-summary] p:not(:first-child)')].map(+ (line) => line.textContent+ )+ ).toEqual(['Prompting · Prompt, Steps', 'Model · Model']);++ const notes = rail().querySelector<HTMLElement>('[data-workflow-author-notes]')!;+ const toggle = () => notes.querySelector<HTMLButtonElement>('button')!;+ const text = notes.querySelector<HTMLElement>('p:nth-of-type(2)')!;+ expect(toggle().textContent).toBe('Read all notes');+ expect(text.scrollHeight).toBeGreaterThan(text.clientHeight);+ await act(() => userEvent.click(toggle()));+ expect(toggle().getAttribute('aria-expanded')).toBe('true');+ expect(text.scrollHeight).toBeLessThanOrEqual(text.clientHeight + 1);++ await act(() => userEvent.click(rail().querySelector<HTMLButtonElement>('[data-workflow-see-inputs]')!));+ expect(stage()).not.toBeNull();+ expect(tabs()[1]?.getAttribute('aria-selected')).toBe('true');+ });++ it('makes the rail thumbnail a way into the preview, and keeps only a real image beside the stage', async () => {+ await openWith(withSnapshot({ entries: [GRAPH_ENTRY, PORTRAIT], total: 2 }));+ await act(() => card('wf-graph')!.click());+ const thumbnailButton = () => document.querySelector<HTMLButtonElement>('[data-thumbnail-preview]');+ const slot = () => document.querySelector<HTMLElement>('[data-workflow-detail] [data-thumbnail-kind]')!;++ expect(thumbnailButton()?.getAttribute('aria-label')).toBe('Preview Graph Fixture');+ expect(thumbnailButton()?.textContent).toBe('Preview');+ await act(() => userEvent.click(thumbnailButton()!));++ expect(stage()).not.toBeNull();+ // The silhouette only drew the graph the stage now shows.+ expect(slot().dataset.thumbnailKind).toBe('silhouette');+ expect(isShown(slot())).toBe(false);++ await act(() => stepButton('Next workflow')!.click());+ expect(slot().dataset.thumbnailKind).toBe('image');+ expect(isShown(slot())).toBe(true);+ expect(isShown(thumbnailButton())).toBe(false);+ });++ it('fits a narrow dialog: the stage over the collection, the bar without the find field, the sheet below', async () => {+ await resizeViewport(760, 760);+ await previewGraph();++ expect(isShown(stage()!.querySelector('[data-preview-find]'))).toBe(false);+ expect(tabs().every(isShown)).toBe(true);+ expect(isShown(document.querySelector('[data-workflow-library-toolbar]'))).toBe(false);+ const summary = document.querySelector<HTMLElement>('[data-detail-sheet-summary]')!;+ expect(isShown(summary.querySelector('[data-detail-sheet-open]'))).toBe(true);+ expect(stage()!.getBoundingClientRect().bottom).toBeLessThanOrEqual(summary.getBoundingClientRect().top + 1);+ // The stepper sits beside the name in the sheet's summary, the rail's copy hidden.+ expect(summary.contains(stepper())).toBe(true);+ expect(positionText()).toBe('1 of 1');+ expect(isShown(document.querySelector('[data-detail-rail-stepper]'))).toBe(false);+ });++ it('marks a terminal node as the result beside its other markers', async () => {+ const document_ = {+ ...GRAPH_DOCUMENT,+ form: {+ ...GRAPH_DOCUMENT.form,+ elements: {+ ...GRAPH_DOCUMENT.form.elements,+ 'field-decode': exposedField('field-decode', 'refine', 'strength'),+ },+ },+ nodes: GRAPH_DOCUMENT.nodes.map((node) =>+ node.id === 'refine' ? graphNode('refine', 'l2i', node.position) : node+ ),+ };+ await previewGraph(+ withSnapshot({+ entries: [entry('wf-graph', 'Graph Fixture', readyEnrichment(6, 'flux', NO_REQUIREMENTS, document_))],+ total: 1,+ })+ );++ const markers = [...previewNode('refine')!.querySelectorAll<HTMLElement>('[data-marker]')];+ expect(markers.map((marker) => marker.dataset.marker)).toEqual(['exposed', 'result']);+ expect(markers.every((marker) => marker.getClientRects().length > 0)).toBe(true);+ });++ it('previews the Extend Video LTX-2 template legibly: fitted, prompts named by the form, nodes summed up', async () => {+ await resizeViewport(1440, 900);+ templatesState.current = {+ error: null,+ status: 'loaded',+ templates: extendVideo.templates as unknown as InvocationTemplatesSnapshot['templates'],+ };+ const document_ = parseWorkflowJson(extendVideo.workflow).document;+ await previewGraph(+ withSnapshot({+ entries: [entry('wf-graph', 'Extend Video - LTX-2', readyEnrichment(15, 'ltx2', NO_REQUIREMENTS, document_))],+ total: 1,+ })+ );++ const pane = stage()!.querySelector('.react-flow')!.getBoundingClientRect();+ expect(previewNodes()).toHaveLength(8);+ for (const node of previewNodes()) {+ const box = node.getBoundingClientRect();+ expect(box.left, node.dataset.id).toBeGreaterThanOrEqual(pane.left);+ expect(box.right, node.dataset.id).toBeLessThanOrEqual(pane.right);+ }+ expect(stage()?.querySelector('.react-flow__minimap')).toBeNull();+ // Titles stay at least 10px on screen.+ const title = previewNode('denoise_latents')!.querySelector('[data-preview-chip] p')!;+ const scale = title.getBoundingClientRect().height / (title as HTMLElement).offsetHeight;+ expect(Number.parseFloat(getComputedStyle(title).fontSize) * scale).toBeGreaterThanOrEqual(9.9);+ // Rows spread over the stage's open area (between its legend and its bottom controls) rather than a band along+ // its top.+ const legendBottom = stage()!.querySelector('[data-preview-legend]')!.getBoundingClientRect().bottom;+ const controlsTop = Math.min(+ ...[...stage()!.querySelectorAll('[data-preview-overlay]')]+ .map((control) => control.getBoundingClientRect())+ .filter((box) => box.top > pane.top + pane.height / 2)+ .map((box) => box.top)+ );+ const tops = previewNodes().map((node) => node.getBoundingClientRect().top);+ expect(Math.max(...tops) - Math.min(...tops)).toBeGreaterThan((controlsTop - legendBottom) * 0.4);++ expect(+ [...previewNode('pos_cond')!.querySelectorAll('[data-preview-pill]')].map((pill) => pill.textContent?.trim())+ ).toEqual(['Negative Prompt', 'Prompt']);+ const summary = (id: string) => previewNode(id)?.querySelector('[data-preview-chip] div p')?.textContent;+ expect(summary('extend_conditioning')).toBe('Context Frames 17');+ expect(summary('ideal_dimensions')).toBe('Target Resolution 704p (short edge 704)');+ expect(summary('denoise_latents')).toBe('Number of Frames 121');+ // Its empty model fields ask for LTX-2 models this catalog cannot install: there is a model to pick, not one to fetch.+ expect(summary('model_loader')).toBe('Model to pick');+ });++ it('meets each chip at its middle, not its pills’, and keeps the pills above it and in view', async () => {+ await resizeViewport(1440, 900);+ const templates = extendVideo.templates as unknown as InvocationTemplatesSnapshot['templates'];+ templatesState.current = { error: null, status: 'loaded', templates };+ const document_ = parseWorkflowJson(extendVideo.workflow).document;+ await previewGraph(+ withSnapshot({+ entries: [entry('wf-graph', 'Extend Video - LTX-2', readyEnrichment(15, 'ltx2', NO_REQUIREMENTS, document_))],+ total: 1,+ })+ );++ const pane = stage()!.querySelector('.react-flow')!.getBoundingClientRect();+ const chip = (id: string) => previewNode(id)!.querySelector('[data-preview-chip]')!.getBoundingClientRect();+ // Chips are 48px tall in flow units; the rendered height gives the zoom.+ const zoom = () => chip('denoise_latents').height / 48;+ // The ends of an edge's path, on screen.+ const ends = (edgeId: string) => {+ const path = stage()!.querySelector<SVGPathElement>(`[data-preview-edge="${CSS.escape(edgeId)}"]`)!;+ const toScreen = (point: DOMPoint) => new DOMPoint(point.x, point.y).matrixTransform(path.getScreenCTM()!);++ return {+ end: toScreen(path.getPointAtLength(path.getTotalLength())),+ start: toScreen(path.getPointAtLength(0)),+ };+ };+ const { edges, pills } = buildWorkflowPreviewModel(document_, templates).simplified!;++ expect(pills.denoise_latents).toHaveLength(2);+ // xyflow draws and places edges once it has measured the chips, a frame after they widen to the chosen width.+ await act(() =>+ vi.waitFor(() => {+ expect(stage()!.querySelectorAll('[data-preview-edge]')).toHaveLength(edges.length);+ for (const edge of edges) {+ const { end, start } = ends(edge.id);+ const source = chip(edge.source);+ const target = chip(edge.target);+ const label = `${edge.source} -> ${edge.target}`;++ // An edge leaves its source chip's middle and meets its target chip's middle, give or take the few px a+ // chip fed by several nodes spreads their entries over. Its ends may sit a little inside the chip, which+ // is drawn over them (xyflow measures handles once, and the stage may still be scaling in as it does).+ expect(start.x, label).toBeGreaterThan(source.right - source.width / 4);+ expect(start.x, label).toBeLessThanOrEqual(source.right + 1);+ expect(Math.abs(start.y - (source.top + source.height / 2)), label).toBeLessThanOrEqual(1.5);+ expect(end.x, label).toBeGreaterThanOrEqual(target.left - 1);+ expect(end.x, label).toBeLessThan(target.left + target.width / 4);+ expect(Math.abs(end.y - (target.top + target.height / 2)), label).toBeLessThanOrEqual(12 * zoom() + 1.5);+ }+ })+ );++ // Entries into the denoiser, fed by five nodes, keep apart, top to bottom as their sources sit.+ const entering = edges.filter((edge) => edge.target === 'denoise_latents');+ const byEntry = [...entering].sort((a, b) => ends(a.id).end.y - ends(b.id).end.y);+ const bySource = [...entering].sort((a, b) => chip(a.source).top - chip(b.source).top);+ expect(entering).toHaveLength(5);+ expect(byEntry.map((edge) => edge.source)).toEqual(bySource.map((edge) => edge.source));+ expect(ends(byEntry[4]!.id).end.y - ends(byEntry[0]!.id).end.y).toBeGreaterThan(12 * zoom());++ // Pills stack above their chip, inside the fitted stage.+ for (const pill of stage()!.querySelectorAll<HTMLElement>('[data-preview-pill]')) {+ const box = pill.getBoundingClientRect();+ const owner = chip(pill.closest<HTMLElement>('.react-flow__node')!.dataset.id!);++ expect(box.bottom).toBeLessThanOrEqual(owner.top);+ expect(box.top).toBeGreaterThanOrEqual(pane.top);+ }+ });++ it('reopens on the collection and on Nodes after a close that bypasses the library’s own controls', async () => {+ // The copy question closes the library through the UI store, as the workflow dialog host's store binding does.+ await act(() => browse.setSnapshot?.(LOADED_SNAPSHOT));+ setWorkflowLibraryOpen(true);+ const render = () =>+ act(async () => {+ root.render(+ <StrictMode>+ <QueryClientProvider client={queryClient}>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={UI_ADAPTER}>+ <GalleryHostProvider host={GALLERY_HOST}>+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>+ <StoreBoundLibraryDialog />+ </WorkflowGraphPreviewProvider>+ </GalleryHostProvider>+ </WorkflowUiProvider>+ </ChakraProvider>+ </QueryClientProvider>+ </StrictMode>+ );+ await settleFrame();+ });+ await render();+ await clickText('Preview');+ await selectTab('Inputs');+ expect(stage()).not.toBeNull();- // Keep the closing preview mounted until its exit animation finishes.- expect(document.querySelector('[data-preview-dialog]')?.getAttribute('data-preview-open')).toBe('false');- expect(document.querySelector('[data-pending-preview]')).not.toBeNull();+ await act(async () => {+ setWorkflowLibraryOpen(false);+ await settleFrame();+ });+ await act(async () => {+ setWorkflowLibraryOpen(true);+ await settleFrame();+ });- await clickText('Finish preview exit');+ expect(stage()).toBeNull();+ expect(getComputedStyle(collection()!).visibility).toBe('visible');+ await clickText('Preview');+ expect(tabs()[0]?.getAttribute('aria-selected')).toBe('true');+ });- expect(document.querySelector('[data-preview-dialog]')).toBeNull();- expect(document.querySelector('[data-pending-preview]')).toBeNull();- });+ it('paints a node card over the stage’s controls, its chips and Close never under them', async () => {+ // A short stage: a card clamped to its foot reaches the zoom controls (denoise's, placed to its left) or the node+ // count (refine's).+ await resizeViewport(1280, 540);+ await previewGraph();+ const hitsCard = (element: Element | null | undefined) => {+ const box = element!.getBoundingClientRect();+ const hit = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2);+ return (+ hit?.closest('[data-preview-node-card]') !== null && hit?.closest('[data-preview-node-card]') !== undefined+ );+ };- it('keeps a re-opened preview mounted when the previous exit reports in late', async () => {- await openWith(withSnapshot({ entries: [PORTRAIT, PREVIEW_FIXTURE] }));+ for (const id of ['denoise', 'refine', 'model']) {+ await act(() => userEvent.click(previewNode(id)!));+ const card = nodeCard()!;+ expect(card.dataset.previewNodeCard).toBe(id);+ const chips = [...card.querySelectorAll('button')].filter(+ (button) => button.getAttribute('aria-label') === null+ );+ expect(chips.length).toBeGreaterThan(0);+ for (const chip of chips) {+ expect(hitsCard(chip), `${id}: ${chip.textContent}`).toBe(true);+ }+ expect(hitsCard(card.querySelector('button[aria-label="Close"]')), `${id}: Close`).toBe(true);+ await press('{Escape}');+ }+ });- await act(() => card('wf-preview-fixture')?.click());- await clickText('Preview graph');- await waitForPreviewDialog();+ it('counts find matches over the nodes drawn, after Show all as before it', async () => {+ await previewGraph();+ const find = stage()!.querySelector<HTMLInputElement>('input[aria-label="Find a node"]')!;- await clickText('Close preview');- // Previewing again mid-transition re-opens the same dialog…- await clickText('Preview graph');+ // The prompt primitive is folded into a pill until every node shows.+ await act(() => userEvent.type(find, 'string'));+ expect(stage()?.textContent).toContain('No matches');+ await act(() => userEvent.click(stageButton('Show all 6')!));+ expect(stage()?.textContent).toContain('1 match');+ expect(emphasis('prompt')).toBe('match');+ });- expect(document.querySelector('[data-preview-dialog]')?.getAttribute('data-preview-open')).toBe('true');+ it('reaches the stage’s controls before its nodes in keyboard order', async () => {+ await previewGraph();+ await act(() => stageButton('Export')!.focus());+ const reached: string[] = [];- // …and the exit report from the *previous* close must not unmount it.- await clickText('Finish preview exit');+ for (let step = 0; step < 8; step += 1) {+ await press('{Tab}');+ const focused = document.activeElement as HTMLElement;+ reached.push(focused.classList.contains('react-flow__node') ? 'node' : (focused.textContent ?? ''));+ }- expect(document.querySelector('[data-preview-dialog]')?.getAttribute('data-preview-open')).toBe('true');- });+ expect(reached.indexOf('Show all 6')).toBeGreaterThanOrEqual(0);+ expect(reached.indexOf('Show all 6')).toBeLessThan(reached.indexOf('node'));+ });- it('does not resurrect the preview after the library dialog closes and reopens', async () => {- await openWith(withSnapshot({ entries: [PORTRAIT, PREVIEW_FIXTURE] }));+ it('marks a node as needing a model only as the rail counts one: not while its model installs', async () => {+ installs.active = new Set([FLUX_STARTER.source]);+ await previewGraph();- await act(() => card('wf-preview-fixture')?.click());- await clickText('Preview graph');- await waitForPreviewDialog();+ expect(previewNode('model')?.getAttribute('aria-label')).toBe('Main Model Model to pick you set this');+ expect(stage()?.querySelector('[data-preview-legend]')?.textContent).not.toContain('Needs a model');+ });- expect(document.querySelector('[data-preview-dialog]')).not.toBeNull();+ it('scrolls a long saved value inside its box rather than cutting it off', async () => {+ const prompt = 'a lighthouse at dusk, long exposure, film grain, soft haze over the harbour. '.repeat(20).trim();+ const document_ = {+ ...GRAPH_DOCUMENT,+ nodes: GRAPH_DOCUMENT.nodes.map((node) =>+ node.id === 'prompt'+ ? graphNode('prompt', 'string', node.position, { value: prompt }, { value: 'Prompt' })+ : node+ ),+ };+ await previewGraph(+ withSnapshot({+ entries: [entry('wf-graph', 'Graph Fixture', readyEnrichment(6, 'flux', NO_REQUIREMENTS, document_))],+ total: 1,+ })+ );+ await selectTab('Inputs');- // Use the dialog's real Close path, then reopen through controlled props to verify reset and mount cleanup.- const closeButton = document.querySelector<HTMLButtonElement>('button[aria-label="Close"]');- expect(closeButton).not.toBeNull();- // Settle deferred Dialog close transitions inside act.- await act(async () => {- closeButton?.click();- await settleFrame();+ const value = inputRow('Prompt')!.querySelector<HTMLElement>('[data-input-value]')!;+ expect(value.textContent).toBe(prompt);+ expect(getComputedStyle(value).overflowY).toBe('auto');+ expect(value.scrollHeight).toBeGreaterThan(value.clientHeight);+ expect(value.tabIndex).toBe(0);});- await renderDialog(false);- expect(document.querySelector('[data-preview-dialog]')).toBeNull();+ it('starts from the collection again after the library closes and reopens', async () => {+ await openWith(LOADED_SNAPSHOT);+ await clickText('Preview');+ expect(stage()).not.toBeNull();- await renderDialog(true);- expect(document.querySelector('[data-preview-dialog]')).toBeNull();+ await act(async () => {+ document.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!.click();+ await settleFrame();+ });+ await renderDialog(false);+ await renderDialog(true);++ expect(stage()).toBeNull();+ expect(getComputedStyle(collection()!).visibility).toBe('visible');+ });});- it('sits the close control at the end of the tab row, not floating over the tag chips', async () => {+ it('puts the title and Close in the header, the places in the rail and the toolbar over the grid', async () => {await resizeViewport(1280, 800);await openWith(LOADED_SNAPSHOT);- const close = document.querySelector<HTMLButtonElement>('button[aria-label="Close"]');- const segments = document.querySelector<HTMLElement>('[role="tablist"][aria-label="Workflows"]');- const search = document.querySelector<HTMLElement>('input[type="search"]');- expect(close).not.toBeNull();- expect(segments).not.toBeNull();-- // On the tab row's baseline rather than the dialog's absolute top corner…- const closeBox = close!.getBoundingClientRect();- const segmentBox = segments!.getBoundingClientRect();- const closeCenter = closeBox.top + closeBox.height / 2;-- expect(closeCenter).toBeGreaterThanOrEqual(segmentBox.top);- expect(closeCenter).toBeLessThanOrEqual(segmentBox.bottom);- // …after the tabs, at the end of the row, with the search before them.- expect(closeBox.left).toBeGreaterThanOrEqual(segmentBox.right);- expect(search!.getBoundingClientRect().right).toBeLessThanOrEqual(segmentBox.left);- });-- it.each([- ['user', false, 'This project'],- ['project', false, 'Yours'],- ['shared', true, 'Shared'],- ] as const)(- 'keeps the %s header inside a 320px-wide dialog, with Close on the title row and every tab label whole',- async (tab, isMultiuser, targetTab) => {- identity.session = isMultiuser- ? { multiuserEnabled: true, phase: 'ready', user: { user_id: 'user-a' } }- : { multiuserEnabled: false, phase: 'ready', user: null };- await resizeViewport(320, 640);- await openWith(LOADED_SNAPSHOT);- if (tab === 'project') {- await clickSegment('project');- }+ const content = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;+ const title = content.querySelector<HTMLElement>('[data-part="title"]')!;+ const close = content.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!;+ const rail = content.querySelector<HTMLElement>('[data-workflow-library-rail]')!;+ const toolbar = content.querySelector<HTMLElement>('[data-workflow-library-toolbar]')!;+ const search = toolbar.querySelector<HTMLElement>('input[type="search"]')!;+ const closeBox = close.getBoundingClientRect();+ const titleBox = title.getBoundingClientRect();++ // Close shares the title's row at the dialog's end, above the rail and the toolbar.+ expect(closeBox.top + closeBox.height / 2).toBeGreaterThanOrEqual(titleBox.top);+ expect(closeBox.top + closeBox.height / 2).toBeLessThanOrEqual(titleBox.bottom);+ expect(closeBox.right).toBeGreaterThan(toolbar.getBoundingClientRect().right - 40);+ expect(closeBox.bottom).toBeLessThanOrEqual(toolbar.getBoundingClientRect().top);+ expect(rail.getBoundingClientRect().right).toBeLessThanOrEqual(toolbar.getBoundingClientRect().left);+ expect(toolbar.getBoundingClientRect().bottom).toBeLessThanOrEqual(gridViewport()!.getBoundingClientRect().top);+ // The search takes the toolbar's free width.+ expect(search.getBoundingClientRect().width).toBeGreaterThan(toolbar.getBoundingClientRect().width / 2);+ // The search is where typing starts.+ await vi.waitFor(() => expect(document.activeElement).toBe(search));+ });++ const NARROW_WINDOWS = [+ [900, 700],+ [640, 400],+ ] as const;++ it.each(NARROW_WINDOWS)(+ 'collapses the places, tags and order controls into the toolbar in a %i×%i window',+ async (width, height) => {+ await resizeViewport(width, height);+ await openWith(withSnapshot({ placeTotals: { default: 25, recent: 3, user: 4 } }));+ browse.setWorkflowLibraryBrowseFilter.mockClear();const content = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;- const contentBox = content.getBoundingClientRect();+ const toolbar = content.querySelector<HTMLElement>('[data-workflow-library-toolbar]')!;+ const search = toolbar.querySelector<HTMLElement>('input[type="search"]')!;+ const placeSelect = toolbar.querySelector<HTMLElement>('[data-workflow-library-place-select] [role="combobox"]')!;+ const options = toolbar.querySelector<HTMLButtonElement>('[data-workflow-library-narrow-options]')!;+ const tagsButton = () => content.querySelector<HTMLButtonElement>('[data-workflow-library-tags-trigger]')!;+ const results = () => content.querySelector('[data-workflow-library-results]')?.textContent;++ // The rail and the wide layout's order, size and view controls leave the layout; nothing scrolls sideways.+ for (const wide of [+ content.querySelector('[data-workflow-library-rail]'),+ sortTrigger(),+ content.querySelector('button[aria-label="View options"]'),+ ]) {+ expect(wide).not.toBeNull();+ expect(isShown(wide)).toBe(false);+ }expect(content.scrollWidth).toBeLessThanOrEqual(content.clientWidth + 1);- const title = content.querySelector<HTMLElement>('[data-part="title"]')!;- const close = content.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!;- const tabs = [...content.querySelectorAll<HTMLElement>('[role="tab"]')];- const find = (selector: string) => content.querySelector<HTMLElement>(selector);- // Search, sort and the tag strip belong to the template tabs; the project tab shows its hint instead.- const rowControls =- tab === 'user'- ? [- find('input[type="search"]'),- find('[role="combobox"][aria-labelledby]'),- // The tag strip, the header's only scroll region.- find('[role="region"]:not([role="tabpanel"] *)'),- ]- : [];- const header = [close, ...tabs, find('[aria-label="Thumbnail display"]'), ...rowControls];- expect(tabs.map((element) => element.textContent)).toEqual(- isMultiuser ? ['This project', 'Browse', 'Yours', 'Shared'] : ['This project', 'Browse', 'Yours']+ expect(toolbar.scrollWidth).toBeLessThanOrEqual(toolbar.clientWidth + 1);+ for (const control of [placeSelect, search, options, tagsButton()]) {+ expect(isShown(control)).toBe(true);+ expectContained(control, content);+ }+ // The places select leads the toolbar and names the place with its count.+ expect(placeSelect.getBoundingClientRect().right).toBeLessThanOrEqual(search.getBoundingClientRect().left);+ expect(placeSelect.textContent).toBe('My library4');++ // Sort, direction, card size and fit share one menu, which stays open across choices.+ await act(() => userEvent.click(options));+ await vi.waitFor(() => expect(options.getAttribute('aria-expanded')).toBe('true'));+ const menu = document.getElementById(options.getAttribute('aria-controls') ?? '')!;+ const radio = (label: string) =>+ [...menu.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find((item) => item.textContent === label)!;+ expect([...menu.querySelectorAll('[role="menuitemradio"]')].map((item) => item.textContent)).toEqual([+ 'Last opened',+ 'Last updated',+ 'Last run',+ 'Date created',+ 'Name',+ 'Newest first',+ 'Oldest first',+ 'Grid',+ 'List',+ 'Small cards',+ 'Large cards',+ 'Fill',+ 'Fit',+ ]);+ expect(radio('Last updated').getAttribute('aria-checked')).toBe('true');+ expect(radio('Newest first').getAttribute('aria-checked')).toBe('true');+ await act(() => userEvent.click(radio('Name')));+ expect(setLibraryPreferences).toHaveBeenCalledWith({+ workflowLibrarySort: 'name',+ workflowLibrarySortDirection: 'asc',+ });+ await act(() => userEvent.click(radio('Oldest first')));+ expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibrarySortDirection: 'asc' });+ await act(() => userEvent.click(radio('Large cards')));+ expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibraryCardSize: 'large' });+ expect(menu.isConnected && isShown(menu)).toBe(true);+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.activeElement).toBe(options));++ // Tags open in a popover; with the rail gone, the Tags button counts the checked tags and the result line names+ // them. Nothing else is added under the toolbar.+ expect(tagsButton().textContent).toBe('Tags');+ await act(() => userEvent.click(tagsButton()));+ await vi.waitFor(() => expect(tagsButton().getAttribute('aria-expanded')).toBe('true'));+ const popover = document.getElementById(tagsButton().getAttribute('aria-controls') ?? '')!;+ expect(popover.textContent).toContain('Showing workflows with any checked tag');+ await act(() => userEvent.click(popover.querySelector<HTMLElement>('[data-library-tag="portrait"]')!));+ await act(() => userEvent.click(popover.querySelector<HTMLElement>('[data-library-tag="upscale"]')!));+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenLastCalledWith({ tags: ['portrait', 'upscale'] });+ const resultLine = content.querySelector<HTMLElement>('[data-workflow-library-results]')!;+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.activeElement).toBe(tagsButton()));+ expect(tagsButton().textContent).toBe('Tags2');+ expect(results()).toBe('24 workflows · portrait or upscale');+ expect(toolbar.nextElementSibling).toBe(resultLine);++ // Clear inside the popover keeps focus on its first tag, and closing it returns focus to the Tags button.+ await act(() => userEvent.click(tagsButton()));+ await vi.waitFor(() => expect(tagsButton().getAttribute('aria-expanded')).toBe('true'));+ const reopened = document.getElementById(tagsButton().getAttribute('aria-controls') ?? '')!;+ await act(() =>+ userEvent.click([...reopened.querySelectorAll('button')].find((b) => b.textContent === 'Clear')!)+ );+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenLastCalledWith({ tags: [] });+ expect(document.activeElement).toBe(+ reopened.querySelector('[data-library-tag="portrait"] input[type="checkbox"]')+ );+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.activeElement).toBe(tagsButton()));+ expect(results()).toBe('24 workflows');++ // Choosing a place from the select moves there, keeping the search and dropping the tags.+ await act(() => userEvent.click(placeSelect));+ const templates = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(+ (option) => option.textContent === 'Templates25');- expect(header).not.toContain(null);+ expect(templates).not.toBeUndefined();+ await act(() => userEvent.click(templates!));+ expect(workflowUiStore.getSnapshot().libraryTab).toBe('default');+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenLastCalledWith(+ expect.objectContaining({ place: 'default', tags: [] })+ );+ expect(placeSelect.textContent).toBe('Templates25');+ }+ );++ it.each(NARROW_WINDOWS)(+ 'shows the selection as a bottom sheet whose details open over the grid in a %i×%i window',+ async (width, height) => {+ const entries = [+ PORTRAIT,+ ...Array.from({ length: 40 }, (_, index) => ({+ ...LANDSCAPE,+ item: { ...LANDSCAPE.item, workflow_id: `sheet-${index}` },+ })),+ ];+ await resizeViewport(width, height);+ await openWith(withSnapshot({ entries, total: entries.length, pages: 1 }));- for (const element of header as HTMLElement[]) {- const box = element.getBoundingClientRect();- expect(box.left, element.textContent ?? '').toBeGreaterThanOrEqual(contentBox.left);- expect(box.right, element.textContent ?? '').toBeLessThanOrEqual(contentBox.right);+ const content = document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]')!;+ const sheet = content.querySelector<HTMLElement>('[data-workflow-detail="wf-portrait"]')!;+ const summary = sheet.querySelector<HTMLElement>('[data-detail-sheet-summary]')!;+ const details = sheet.querySelector<HTMLElement>('[data-detail-sheet-details]')!;+ const toggle = summary.querySelector<HTMLButtonElement>('[data-detail-sheet-toggle]')!;+ const more = summary.querySelector<HTMLButtonElement>('button[aria-label="More actions"]')!;+ const grid = gridViewport()!;+ const search = content.querySelector<HTMLElement>('[data-workflow-library-toolbar] input[type="search"]')!;+ // The column that scrolls in a short window: the sheet's nearest scrolling ancestor.+ let centre = sheet.parentElement!;+ while (!/(auto|scroll)/.test(getComputedStyle(centre).overflowY)) {+ centre = centre.parentElement!;}- for (const label of tabs.map((element) => element.firstElementChild as HTMLElement)) {- expect(label.scrollWidth, label.textContent ?? '').toBeLessThanOrEqual(label.clientWidth);++ // Collapsed: a summary row with the name, facts, Open and More under the grid; the full rail is out of the+ // layout and the tab order.+ expect(isShown(summary)).toBe(true);+ expect(isShown(details)).toBe(false);+ expectContained(summary, content);+ expect(summary.getBoundingClientRect().left).toBeGreaterThanOrEqual(grid.getBoundingClientRect().left - 1);+ expect(summary.getBoundingClientRect().bottom).toBeGreaterThan(grid.getBoundingClientRect().top);+ expect(summary.textContent).toContain('Portrait Studio');+ expect(summary.querySelector('[data-detail-sheet-open]')?.textContent).toBe('Open…');+ expect(toggle.textContent).toBe('Details and requirements');+ expect(toggle.getAttribute('aria-expanded')).toBe('false');+ expect(toggle.getAttribute('aria-controls')).toBe(details.id);++ // The summary's More offers the rail's actions.+ await act(() => userEvent.click(more));+ await vi.waitFor(() => expect(more.getAttribute('aria-expanded')).toBe('true'));+ const actions = document.getElementById(more.getAttribute('aria-controls') ?? '')!;+ expect(actions.querySelector('[role="menuitem"][data-value="duplicate"]')).not.toBeNull();+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.activeElement).toBe(more));++ await act(() => {+ grid.scrollTop = 200;+ grid.dispatchEvent(new Event('scroll'));+ });+ const scrollTop = grid.scrollTop;+ expect(scrollTop).toBeGreaterThan(0);+ // From the top of the column, as the library opens; the pointer would scroll the toggle into view first.+ await act(() => {+ centre.scrollTop = 0;+ toggle.focus({ preventScroll: true });+ });+ const centreScrollTop = centre.scrollTop;++ // Expanded: the full rail covers the grid, which keeps its scroll position but leaves the tab order.+ await act(() => userEvent.keyboard('{Enter}'));+ expect(toggle.getAttribute('aria-expanded')).toBe('true');+ expect(toggle.textContent).toBe('Hide details');+ expect(isShown(details)).toBe(true);+ const detailsBox = details.getBoundingClientRect();+ const gridBox = grid.getBoundingClientRect();+ expect(detailsBox.top).toBeLessThanOrEqual(gridBox.top + 1);+ expect(detailsBox.left).toBeLessThanOrEqual(gridBox.left + 1);+ expect(detailsBox.right).toBeGreaterThanOrEqual(gridBox.right - 1);+ expect(getComputedStyle(grid).visibility).toBe('hidden');+ expect(grid.scrollTop).toBe(scrollTop);+ expect(details.contains(document.activeElement)).toBe(true);+ if (height <= 400) {+ // The short window's column scrolls the details into view.+ expect(centre.scrollTop).toBeGreaterThan(centreScrollTop);}+ // Compact: the summary heads the details with the full name; no large preview or second name above.+ expect(getComputedStyle(summary.querySelector('p')!).whiteSpace).not.toBe('nowrap');+ expect(+ [...details.querySelectorAll('p')].some((text) => text.textContent === 'Portrait Studio' && isShown(text))+ ).toBe(false);+ expect([...details.querySelectorAll('img')].some(isShown)).toBe(false);+ expect(details.querySelector('[data-requirement-status], [data-workflow-detail-facts]')).not.toBeNull();+ expect(+ [...details.querySelectorAll('button')].some((button) => button.textContent === 'Preview' && isShown(button))+ ).toBe(true);- // Close shares the title's row, so it stays where a dialog's Close is expected.- const titleBox = title.getBoundingClientRect();- const closeCenter = close.getBoundingClientRect().top + close.getBoundingClientRect().height / 2;- expect(closeCenter).toBeGreaterThanOrEqual(titleBox.top);- expect(closeCenter).toBeLessThanOrEqual(titleBox.bottom);+ // A menu over the expanded sheet takes Escape for itself.+ await act(() => userEvent.click(more));+ await vi.waitFor(() => expect(more.getAttribute('aria-expanded')).toBe('true'));+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(more.getAttribute('aria-expanded')).toBe('false'));+ expect(toggle.getAttribute('aria-expanded')).toBe('true');- // A real pointer click reaches the other tab on its own row.- const target = tabs.find((element) => element.textContent === targetTab)!;- await act(() => userEvent.click(target));- expect(target.getAttribute('aria-selected')).toBe('true');+ // Escape from inside the sheet collapses it and returns focus to the disclosure, leaving the library open.+ await act(() => details.focus());+ await act(() => userEvent.keyboard('{Escape}'));+ expect(toggle.getAttribute('aria-expanded')).toBe('false');+ expect(document.activeElement).toBe(toggle);+ expect(isShown(details)).toBe(false);+ expect(getComputedStyle(grid).visibility).toBe('visible');+ expect(grid.scrollTop).toBe(scrollTop);+ // Expanding may scroll a short window's column to the details; collapsing scrolls it back to the toolbar.+ expect(centre.scrollTop).toBe(centreScrollTop);+ expectContained(search, content);+ expect(onOpenChange).not.toHaveBeenCalledWith(false);++ // Collapsed, Escape closes the library as usual.+ await act(() => userEvent.keyboard('{Escape}'));+ expect(onOpenChange).toHaveBeenCalledWith(false);});@@ -1800,6 +4026,208 @@ describe('WorkflowLibraryDialog', () => {expect(heading?.getBoundingClientRect().height ?? 0).toBeGreaterThan(20);});+ describe('list layout', () => {+ const row = (workflowId: string) =>+ document.getElementById(`workflow-library-card-${workflowId}`)?.closest<HTMLElement>('[data-list-row]') ?? null;+ const primary = (workflowId: string) => row(workflowId)?.querySelector<HTMLElement>('[data-list-primary]') ?? null;+ const rail = () => document.querySelector<HTMLElement>('[data-workflow-detail]')?.dataset.workflowDetail;+ const menu = () => document.querySelector<HTMLElement>('[data-workflow-context-menu][data-state="open"]');+ const openAsList = async (snapshot: WorkflowLibraryBrowseSnapshot) => {+ preferences.setSnapshot({ ...preferences.port.getSnapshot(), workflowLibraryLayout: 'list' });+ await openWith(snapshot);+ await vi.waitFor(() => expect(row('wf-portrait')).not.toBeNull());+ };++ it('starts as the grid, switches to rows from the view menu and keeps the choice with the account', async () => {+ await openWith(LOADED_SNAPSHOT);+ const item = (label: string) =>+ [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find(+ (candidate) => candidate.textContent === label+ );++ expect(cards()).toHaveLength(4);+ expect(document.querySelector('[data-workflow-library-list]')).toBeNull();+ await act(() => userEvent.click(document.querySelector<HTMLElement>('button[aria-label="View options"]')!));+ await vi.waitFor(() => expect(item('List')).not.toBeUndefined());+ expect(item('Grid')?.getAttribute('aria-checked')).toBe('true');+ await act(() => userEvent.click(item('List')!));++ expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibraryLayout: 'list' });+ await vi.waitFor(() => expect(row('wf-portrait')).not.toBeNull());+ expect(cards()).toHaveLength(0);+ expect(row('wf-landscape')?.textContent).toContain('Landscape Pass');+ expect(row('wf-landscape')?.textContent).toContain('1 model to install');+ expect(+ row('wf-landscape')?.querySelector('[data-workflow-readiness]')?.getAttribute('data-workflow-readiness')+ ).toBe('models');+ // The project holds a copy of Portrait; the server's 20 positions past the window wait as placeholders.+ expect(row('wf-portrait')?.querySelector('[data-workflow-in-project]')).not.toBeNull();+ expect(row('wf-sketch')?.querySelector('[data-enrichment-placeholder]')).not.toBeNull();+ expect(+ document+ .querySelector('[data-workflow-library-list] [role="list"]')+ ?.querySelector('[aria-setsize]')+ ?.getAttribute('aria-setsize')+ ).toBe('24');+ // Card size and thumbnail display shape only the grid.+ expect(item('Small cards')).toBeUndefined();+ expect(item('Fill')).toBeUndefined();+ });++ it('hides the list, keeping its scroll position, under the narrow sheet’s expanded details', async () => {+ await resizeViewport(900, 700);+ const entries = Array.from({ length: 30 }, (_, index) => ({+ ...LANDSCAPE,+ item: { ...LANDSCAPE.item, workflow_id: `sheet-${index}`, name: `Sheet ${index}` },+ }));+ await openAsList(withSnapshot({ entries: [PORTRAIT, ...entries], pages: 1, total: 31 }));+ const list = document.querySelector<HTMLElement>('[data-workflow-library-list]')!;+ const scroll = list.querySelector<HTMLElement>('[data-list-viewport]')!;+ await act(async () => {+ scroll.scrollTop = 300;+ scroll.dispatchEvent(new Event('scroll'));+ await settleFrame();+ });+ const toggle = document.querySelector<HTMLButtonElement>('[data-detail-sheet-toggle]')!;+ expect(getComputedStyle(list).visibility).toBe('visible');++ await act(() => toggle.focus({ preventScroll: true }));+ await act(() => userEvent.keyboard('{Enter}'));+ expect(toggle.getAttribute('aria-expanded')).toBe('true');+ expect(getComputedStyle(list).visibility).toBe('hidden');+ expect(scroll.scrollTop).toBe(300);++ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(getComputedStyle(list).visibility).toBe('visible'));+ });++ it('selects on a press, opens on a double-click, and moves the selection with ArrowDown and Enter', async () => {+ await openAsList(LOADED_SNAPSHOT);++ await act(() => userEvent.click(primary('wf-landscape')!));+ expect(rail()).toBe('wf-landscape');+ expect(primary('wf-landscape')?.getAttribute('aria-current')).toBe('true');++ await act(() => {+ primary('wf-landscape')?.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));+ });+ expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'first-copy');++ await act(() => userEvent.keyboard('{ArrowDown}'));+ expect(document.activeElement).toBe(primary('wf-sketch'));+ await act(() => userEvent.keyboard('{Enter}'));+ expect(rail()).toBe('wf-sketch');+ });++ it('raises the same actions menu from a right-click and the More button, handing focus back to its source', async () => {+ await openAsList(LOADED_SNAPSHOT);++ await act(() => primary('wf-landscape')?.focus());+ await act(() =>+ primary('wf-landscape')?.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 300, clientY: 200 })+ )+ );+ // The menu is the row's, not the selection's: the rail stays on the first entry.+ expect(rail()).toBe('wf-portrait');+ await vi.waitFor(() => expect(menu()?.querySelector('[role="menuitem"][data-value="open"]')).not.toBeNull());+ // The row's button names the menu, so the dialog's focus trap lets focus into it.+ expect(primary('wf-landscape')?.getAttribute('aria-expanded')).toBe('true');+ expect(primary('wf-landscape')?.getAttribute('aria-controls')).toBe(menu()?.id);+ await vi.waitFor(() => expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull(), {+ timeout: 2000,+ });+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(menu()).toBeNull());+ await vi.waitFor(() => expect(document.activeElement).toBe(primary('wf-landscape')));++ const more = row('wf-sketch')?.querySelector<HTMLButtonElement>('[data-workflow-card-menu]') ?? null;+ await pressTileMenuButton(more);+ expect(rail()).toBe('wf-portrait');+ await vi.waitFor(() => expect(menu()?.querySelector('[role="menuitem"][data-value="open"]')).not.toBeNull());+ expect(more?.getAttribute('aria-expanded')).toBe('true');+ expect(more?.getAttribute('aria-controls')).toBe(menu()?.id);+ expect(primary('wf-sketch')?.hasAttribute('aria-expanded')).toBe(false);+ await vi.waitFor(() => expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull(), {+ timeout: 2000,+ });+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(menu()).toBeNull());+ await vi.waitFor(() => expect(document.activeElement).toBe(more));+ });++ it('selects a row with Space and previews from a keyboard reachable Preview button', async () => {+ await openAsList(LOADED_SNAPSHOT);+ await act(() => primary('wf-landscape')!.focus());+ await act(() => userEvent.keyboard(' '));+ expect(document.querySelector('[data-preview-stage]')).toBeNull();+ expect(rail()).toBe('wf-landscape');+ const preview = document.querySelector<HTMLButtonElement>('[data-workflow-preview-trigger]')!;+ expect(preview.tabIndex).toBe(0);+ await act(() => preview.focus());+ await act(() => userEvent.keyboard(' '));++ expect(document.querySelector('[data-preview-stage]')).not.toBeNull();+ expect(rail()).toBe('wf-landscape');++ await act(() => userEvent.keyboard('{Escape}'));+ expect(document.querySelector('[data-preview-stage]')).toBeNull();+ expect(document.activeElement).toBe(preview);+ });++ it("deletes another row from that row's menu and keeps the selection", async () => {+ await openAsList(LOADED_SNAPSHOT);+ await act(() => userEvent.click(primary('wf-upscale')!));+ expect(rail()).toBe('wf-upscale');++ await act(() => userEvent.click(primary('wf-landscape')!, { button: 'right' }));+ await vi.waitFor(() => expect(menu()?.id).toBe('workflow-library-card-wf-landscape-actions'));+ expect(rail()).toBe('wf-upscale');+ expect(primary('wf-upscale')?.getAttribute('aria-current')).toBe('true');++ await selectMenuItem(menu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="delete"]'));+ await act(settleFrame);+ const alert = await vi.waitFor(() => {+ const element = document.querySelector<HTMLElement>('[role="alertdialog"]');+ expect(element?.textContent).toContain('Landscape Pass');+ return element!;+ });+ await act(async () => {+ [...alert.querySelectorAll('button')].find((button) => button.textContent?.trim() === 'Delete')?.click();+ await settleFrame();+ });++ expect(libraryWrites.delete).toHaveBeenCalledExactlyOnceWith('wf-landscape', expect.anything());+ await act(() => browse.setSnapshot?.(withSnapshot({ entries: [PORTRAIT, SKETCH, UPSCALE], total: 23 })));+ await vi.waitFor(() => expect(row('wf-landscape')).toBeNull());+ expect(rail()).toBe('wf-upscale');+ });++ it('opens from the Open quick action without taking focus off the row, asking first when the project holds a copy', async () => {+ await openAsList(LOADED_SNAPSHOT);++ await act(() => userEvent.hover(primary('wf-portrait')!));+ const quickOpen = row('wf-portrait')?.querySelector<HTMLElement>('[data-row-action="open"]');+ expect(quickOpen?.textContent).toBe('Open…');+ expect(quickOpen?.tabIndex).toBe(-1);+ await act(() => userEvent.click(quickOpen!));++ expect(workflowUiStore.getSnapshot().libraryCopyChoice?.item.workflow_id).toBe('wf-portrait');+ expect(loader.open).not.toHaveBeenCalled();+ // The question returns focus to the row it was raised from.+ await vi.waitFor(() => expect(document.querySelector('[data-library-copy-choice]')).not.toBeNull());+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.activeElement).toBe(primary('wf-portrait')));++ await act(() => userEvent.hover(primary('wf-upscale')!));+ const upscaleOpen = row('wf-upscale')?.querySelector<HTMLElement>('[data-row-action="open"]');+ expect(upscaleOpen?.textContent).toBe('Open');+ await act(() => userEvent.click(upscaleOpen!));+ expect(loader.open).toHaveBeenCalledWith(UPSCALE.item, 'first-copy');+ expect(document.activeElement).toBe(primary('wf-upscale'));+ });+ });+it('shows the busy overlay while a workflow is being applied', async () => {loader.phase.current = 'applying';@@ -1826,19 +4254,21 @@ describe('WorkflowLibraryDialog — This project', () => {await act(async () => {root.render(<StrictMode>- <ChakraProvider value={system}>- <WorkflowUiProvider adapter={UI_ADAPTER}>- <GalleryHostProvider host={GALLERY_HOST}>- <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>- {storeBound ? (- <StoreBoundLibraryDialog />- ) : (- <WorkflowLibraryDialog isOpen onOpenChange={onOpenChange} />- )}- </WorkflowGraphPreviewProvider>- </GalleryHostProvider>- </WorkflowUiProvider>- </ChakraProvider>+ <QueryClientProvider client={queryClient}>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={UI_ADAPTER}>+ <GalleryHostProvider host={GALLERY_HOST}>+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>+ {storeBound ? (+ <StoreBoundLibraryDialog />+ ) : (+ <WorkflowLibraryDialog isOpen onOpenChange={onOpenChange} />+ )}+ </WorkflowGraphPreviewProvider>+ </GalleryHostProvider>+ </WorkflowUiProvider>+ </ChakraProvider>+ </QueryClientProvider></StrictMode>);await settleFrame();@@ -1867,7 +4297,7 @@ describe('WorkflowLibraryDialog — This project', () => {await click(card(workflowId));};- const menuItem = (value: string) => document.querySelector<HTMLElement>(`[data-menu-item="${value}"]`);+ const menuItem = (value: string) => document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`);const railMenuTrigger = () => rail()?.querySelector<HTMLElement>('[aria-label="More actions"]');// The trigger's data-state belongs to its tooltip; the menu's own state is aria-expanded. The menu opens on a// later frame, so read it only once its items are in the document.@@ -1882,7 +4312,7 @@ describe('WorkflowLibraryDialog — This project', () => {await vi.waitFor(() => {expect(railMenuTrigger()?.getAttribute('aria-expanded')).toBe('true');- expect(document.querySelector('[data-menu-item]')).not.toBeNull();+ expect(document.querySelector('[role="menuitem"]')).not.toBeNull();},{ timeout: 2000 });@@ -1898,7 +4328,7 @@ describe('WorkflowLibraryDialog — This project', () => {};const clickRailMenuItem = async (value: string) => {await openRailMenu();- await click(menuItem(value));+ await selectMenuItem(menuItem(value));};beforeEach(() => {@@ -1907,14 +4337,19 @@ describe('WorkflowLibraryDialog — This project', () => {root = createRoot(host);onOpenChange = vi.fn((_isOpen: boolean) => {});browse.ensureWorkflowLibraryBrowseLoaded.mockClear();+ browse.loadWorkflowLibraryPlaceTotals.mockClear();browse.setWorkflowLibraryBrowseFilter.mockClear();loader.open.mockClear();+ loader.replace.mockClear();loader.resume.mockClear();+ queryClient.clear();+ templateRecords.clear();loader.phase.current = 'idle';for (const command of Object.values(COMMANDS)) {command.mockClear();}project.setSnapshot(projectSnapshot(PROJECT_WORKFLOWS));+ preferences.setSnapshot(LIBRARY_PREFERENCES as unknown as WorkflowPreferences);browse.setSnapshot?.(LOADED_SNAPSHOT);accountLifecycle.invalidate();// The library opens on the project's own workflows, as it does from the workflow header.@@ -1931,21 +4366,71 @@ describe('WorkflowLibraryDialog — This project', () => {expect(document.querySelector('[data-library-tab="project"]')).not.toBeNull();expect(cards().map((element) => element.dataset.workflowCard)).toEqual(['wf-alpha', 'wf-bundled', 'wf-user']);- expect(document.body.textContent).toContain('3 workflows in this project');+ expect(document.querySelector('[data-workflow-library-results]')?.textContent).toBe('3 workflows');const badges = [...document.querySelectorAll<HTMLElement>('[data-workflow-card] [data-active-workflow]')];expect(badges).toHaveLength(1);expect(badges[0]?.closest<HTMLElement>('[data-workflow-card]')?.dataset.workflowCard).toBe('wf-alpha');expect(badges[0]?.textContent).toBe('Active');- // The project view is local; no library page is requested and no search is offered.+ // The project view is local; no library page is requested. The rail's totals are the only library reads.expect(browse.ensureWorkflowLibraryBrowseLoaded).not.toHaveBeenCalled();- expect(document.querySelector('input[type="search"]')).toBeNull();+ expect(browse.loadWorkflowLibraryPlaceTotals).toHaveBeenCalled();+ // The project's workflows carry no tags, so the rail lists none; its footer explains autosave.+ expect(document.querySelector('[data-library-tag]')).toBeNull();+ expect(document.querySelector('[data-workflow-library-rail]')?.textContent).toContain(+ 'Edits autosave here; the library changes only when you save to it.'+ );expect(document.querySelector('[data-workflow-card] [data-workflow-visibility]')).toBeNull();expect(document.body.textContent).not.toContain('Public workflow');++ // The active workflow is already open: its card offers no Open quick action, as its rail disables Open.+ const quickOpen = (workflowId: string) =>+ card(workflowId)?.closest('[data-workflow-card-root]')?.querySelector('[data-card-action="open"]') ?? null;+ await act(() => userEvent.hover(card('wf-alpha')!));+ await act(() => userEvent.hover(card('wf-user')!));+ expect(quickOpen('wf-alpha')).toBeNull();+ expect(quickOpen('wf-user')).not.toBeNull();});- it('starts a fresh workflow from the header', async () => {+ it('lists the project’s workflows as rows: Active on the open one, which offers no Open, and a run date', async () => {+ preferences.setSnapshot({ ...preferences.port.getSnapshot(), workflowLibraryLayout: 'list' });+ await renderDialog();+ const row = (workflowId: string) =>+ document.querySelector<HTMLElement>(`[data-workflow-library-list] [data-list-row="${workflowId}"]`);++ await vi.waitFor(() => expect(row('wf-alpha')).not.toBeNull());+ expect(+ [...document.querySelectorAll<HTMLElement>('[data-workflow-library-list] [data-list-row]')].map(+ (element) => element.dataset.listRow+ )+ ).toEqual(['wf-alpha', 'wf-bundled', 'wf-user']);+ expect(cards()).toHaveLength(0);+ expect(row('wf-alpha')?.querySelector('[data-active-workflow]')?.textContent).toBe('Active');+ expect(row('wf-user')?.querySelector('[data-active-workflow]')).toBeNull();+ // Project rows never mark a template copy: the view is the project's own collection.+ expect(document.querySelector('[data-workflow-library-list] [data-workflow-in-project]')).toBeNull();++ // The active workflow is already open: no Open on its row, as its rail disables Open.+ const quickOpen = (workflowId: string) => row(workflowId)!.querySelector<HTMLElement>('[data-row-action="open"]')!;+ await act(() => userEvent.hover(row('wf-alpha')!.querySelector('[data-list-primary]')!));+ expect(getComputedStyle(quickOpen('wf-alpha')).visibility).toBe('hidden');+ await act(() => userEvent.hover(row('wf-user')!.querySelector('[data-list-primary]')!));+ expect(getComputedStyle(quickOpen('wf-user')).visibility).toBe('visible');++ // Pressing a row selects it for the rail; a double-click opens it and closes the library.+ await click(row('wf-user')!.querySelector<HTMLElement>('[data-list-primary]'));+ expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-user');+ await act(() => {+ row('wf-bundled')+ ?.querySelector('[data-list-primary]')+ ?.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));+ });+ expect(COMMANDS.selectWorkflow).toHaveBeenCalledWith('wf-bundled');+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('starts a fresh workflow from the toolbar', async () => {await renderDialog();await clickText('New workflow');@@ -1954,6 +4439,90 @@ describe('WorkflowLibraryDialog — This project', () => {expect(onOpenChange).not.toHaveBeenCalled();});+ it('searches, filters by tag and orders the project’s workflows locally', async () => {+ project.setSnapshot(+ projectSnapshot([+ { document: { ...ALPHA.document, tags: 'portrait' } },+ { ...BUNDLED_COPY, document: { ...BUNDLED_COPY.document, tags: 'Portrait, upscale' } },+ USER_COPY,+ ])+ );+ await renderDialog();+ const ids = () => cards().map((element) => element.dataset.workflowCard);+ const search = document.querySelector<HTMLInputElement>('input[type="search"]')!;+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;++ // Tags come from the project's own workflows, case variants merged.+ expect(+ [...document.querySelectorAll<HTMLElement>('[data-library-tag]')].map((tag) => tag.dataset.libraryTag)+ ).toEqual(['portrait', 'upscale']);++ await act(async () => {+ setValue?.call(search, 'copy');+ search.dispatchEvent(new Event('input', { bubbles: true }));+ await settleFrame();+ });+ // No debounce and no library request: the collection is local.+ expect(ids()).toEqual(['wf-bundled', 'wf-user']);+ expect(document.querySelector('[data-workflow-library-results]')?.textContent).toBe('2 workflows');++ await click(document.querySelector<HTMLElement>('[data-library-tag="portrait"]'));+ expect(ids()).toEqual(['wf-bundled']);++ await act(async () => {+ setValue?.call(search, '');+ search.dispatchEvent(new Event('input', { bubbles: true }));+ await settleFrame();+ });+ expect(ids()).toEqual(['wf-alpha', 'wf-bundled']);++ const sortButton = document.querySelector<HTMLButtonElement>('[data-workflow-library-sort]')!;+ expect(sortButton.getAttribute('aria-label')).toBe('Sort: Project order, First to last');+ await click(sortButton);+ await vi.waitFor(() => expect(sortButton.getAttribute('aria-expanded')).toBe('true'));+ await click(+ [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')].find(+ (item) => item.textContent === 'Last to first'+ )+ );+ expect(ids()).toEqual(['wf-bundled', 'wf-alpha']);+ expect(workflowUiStore.getSnapshot().libraryProjectOrder).toEqual({ direction: 'desc', sort: 'order' });+ expect(browse.setWorkflowLibraryBrowseFilter).not.toHaveBeenCalled();+ });++ it('clears the search and tags on close but reopens on the same place', async () => {+ project.setSnapshot(projectSnapshot([{ document: { ...ALPHA.document, tags: 'portrait' } }, USER_COPY]));+ await renderDialog({ storeBound: true });+ const search = () => document.querySelector<HTMLInputElement>('input[type="search"]')!;+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;++ await act(async () => {+ setValue?.call(search(), 'alp');+ search().dispatchEvent(new Event('input', { bubbles: true }));+ await settleFrame();+ });+ await click(document.querySelector<HTMLElement>('[data-library-tag="portrait"]'));+ expect(cards()).toHaveLength(1);+ expect(document.querySelector<HTMLInputElement>('[data-library-tag] input')?.checked).toBe(true);++ await click(document.querySelector<HTMLElement>('button[aria-label="Close"]'));+ expect(workflowUiStore.getSnapshot()).toMatchObject({+ isLibraryOpen: false,+ libraryQuery: { search: '', tags: [] },+ libraryTab: 'project',+ });++ await act(async () => {+ setWorkflowLibraryOpen(true);+ await settleFrame();+ });++ expect(search().value).toBe('');+ expect(document.querySelector<HTMLInputElement>('[data-library-tag] input')?.checked).toBe(false);+ expect(cards()).toHaveLength(2);+ expect(document.querySelector('[data-library-tab="project"]')).not.toBeNull();+ });+it('opens a workflow from a double-click or the rail, then closes', async () => {await renderDialog();@@ -1965,7 +4534,8 @@ describe('WorkflowLibraryDialog — This project', () => {await selectCard('wf-bundled');expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-bundled');- await clickText('Open');+ // The rail's Open, not a card's pointer-only quick action.+ await click([...(rail()?.querySelectorAll('button') ?? [])].find((button) => button.textContent === 'Open'));expect(COMMANDS.selectWorkflow).toHaveBeenLastCalledWith('wf-bundled');expect(onOpenChange).toHaveBeenCalledTimes(2);@@ -1982,11 +4552,73 @@ describe('WorkflowLibraryDialog — This project', () => {expect(element).not.toBeNull();return element!;});+ // The menu button takes the pointer once the card shows it, as for a user moving onto the card first.+ await act(() => userEvent.hover(card('wf-bundled')!));await act(() => userEvent.click(button));await vi.waitFor(() =>- expect(document.querySelector('[data-workflow-context-menu] [data-menu-item="rename"]')).not.toBeNull()+ expect(+ document.querySelector('[data-workflow-context-menu] [role="menuitem"][data-value="rename"]')+ ).not.toBeNull()+ );+ // The menu is the tile's; the rail keeps the active workflow.+ expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-alpha');+ });++ it("duplicates another workflow from its card's menu and selects the copy", async () => {+ await renderDialog();+ await selectCard('wf-bundled');++ await act(() => userEvent.click(card('wf-user')!, { button: 'right' }));+ const contextMenu = await vi.waitFor(() => {+ const element = document.querySelector<HTMLElement>('[data-workflow-context-menu][data-state="open"]');+ expect(element?.id).toBe('workflow-library-card-wf-user-actions');+ return element!;+ });+ await selectMenuItem(contextMenu.querySelector<HTMLElement>('[role="menuitem"][data-value="duplicate"]'));++ expect(COMMANDS.duplicateWorkflow).toHaveBeenCalledExactlyOnceWith('wf-user', 'User copy copy');+ expect(workflowUiStore.getSnapshot().librarySelection).toEqual({ projectId: PROJECT_ID, workflowId: 'wf-copy' });+ });++ it("renames and removes another workflow from its card's menu, keeping the selected one", async () => {+ await renderDialog();+ await selectCard('wf-bundled');+ const contextMenu = () => document.querySelector<HTMLElement>('[data-workflow-context-menu][data-state="open"]');+ const raiseOnUserCopy = async () => {+ await act(() => userEvent.click(card('wf-user')!, { button: 'right' }));+ await vi.waitFor(() => expect(contextMenu()?.id).toBe('workflow-library-card-wf-user-actions'));+ expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-bundled');+ };++ await raiseOnUserCopy();+ await selectMenuItem(contextMenu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="rename"]'));+ const input = await vi.waitFor(() => {+ const element = document.querySelector<HTMLInputElement>('input[name="renameValue"]');+ expect(element?.value).toBe('User copy');+ return element!;+ });+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ await act(async () => {+ setValue?.call(input, 'User copy, tuned');+ input.dispatchEvent(new Event('input', { bubbles: true }));+ await Promise.resolve();+ });+ await click(input.closest('form')?.querySelector<HTMLButtonElement>('button[type="submit"]'));+ expect(COMMANDS.renameWorkflow).toHaveBeenCalledExactlyOnceWith('wf-user', 'User copy, tuned');++ await vi.waitFor(() => expect(alertDialog()).toBeNull());+ await raiseOnUserCopy();+ await selectMenuItem(contextMenu()?.querySelector<HTMLElement>('[role="menuitem"][data-value="remove"]'));+ expect(alertDialog()?.textContent).toContain('Remove "User copy" from this project?');+ await click(+ [...(alertDialog()?.querySelectorAll('button') ?? [])].find(+ (candidate) => (candidate.textContent ?? '').trim() === 'Remove'+ ));++ expect(COMMANDS.removeWorkflow).toHaveBeenCalledExactlyOnceWith('wf-user');+ expect(workflowUiStore.getSnapshot().librarySelection).toEqual({ projectId: PROJECT_ID, workflowId: 'wf-bundled' });expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-bundled');});@@ -1999,14 +4631,40 @@ describe('WorkflowLibraryDialog — This project', () => {await vi.waitFor(() => expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull(), { timeout: 2000 });});- it('shows the active workflow in the rail with Open disabled, since it is already open', async () => {+ it('shows the active workflow in the rail with Open disabled, saying why, since it is already open', async () => {await renderDialog();expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-alpha');- expect((buttonWithText('Active') as HTMLButtonElement | undefined)?.disabled).toBe(true);+ const open = rail()?.querySelector<HTMLButtonElement>('[data-project-workflow-open]');+ expect(open?.textContent).toBe('Open');+ expect(open?.disabled).toBe(true);+ expect(document.getElementById(open?.getAttribute('aria-describedby') ?? '')?.textContent).toBe('Active workflow');expect(rail()?.querySelector('[data-workflow-source]')?.textContent).toBe('Not linked to a library template');});+ it('offers the selected project workflow as a sheet in a narrow window, its Open disabled while active', async () => {+ const previous = { height: window.innerHeight, width: window.innerWidth };+ await page.viewport(900, 700);+ onTestFinished(() => page.viewport(previous.width, previous.height));+ await renderDialog();++ const summary = rail()!.querySelector<HTMLElement>('[data-detail-sheet-summary]')!;+ const open = summary.querySelector<HTMLButtonElement>('[data-detail-sheet-open]')!;+ expect(summary.getClientRects().length).toBeGreaterThan(0);+ // The wide rail's own Open leaves the layout; the summary's says why it is disabled.+ expect(rail()!.querySelector<HTMLElement>('[data-project-workflow-open]')!.getClientRects()).toHaveLength(0);+ expect(open.disabled).toBe(true);+ expect(document.getElementById(open.getAttribute('aria-describedby') ?? '')?.textContent).toContain(+ 'Active workflow'+ );++ await selectCard('wf-bundled');+ expect(open.disabled).toBe(false);+ expect(open.hasAttribute('aria-describedby')).toBe(false);+ await click(open);+ expect(COMMANDS.selectWorkflow).toHaveBeenCalledWith('wf-bundled');+ });+it('renames through the dialog', async () => {await renderDialog();await selectCard('wf-bundled');@@ -2054,6 +4712,8 @@ describe('WorkflowLibraryDialog — This project', () => {await click(confirm);expect(COMMANDS.removeWorkflow).toHaveBeenCalledWith('wf-bundled');+ // Removing the selected workflow clears the selection.+ expect(workflowUiStore.getSnapshot().librarySelection).toBeNull();});it('offers a template update only for a source the account can write', async () => {@@ -2074,11 +4734,83 @@ describe('WorkflowLibraryDialog — This project', () => {);expect(menuItem('update-template')).not.toBeNull();- await click(menuItem('update-template'));+ await selectMenuItem(menuItem('update-template'));++ expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({ kind: 'update-source', workflowId: 'wf-user' });+ });++ it('says when the linked template is newer, and updates the copy from it after confirmation', async () => {+ templateRecords.set('wf-portrait', { name: 'Portrait Studio', revision: 6 });+ await renderDialog();+ await selectCard('wf-user');++ const linked = () => rail()?.querySelector<HTMLElement>('[data-linked-template="wf-portrait"]');+ await vi.waitFor(() =>+ expect(linked()?.querySelector('[data-template-newer]')?.textContent).toBe('Template is newer')+ );+ // The card names the template once its record arrives; the sheet's summary says it is newer too.+ expect(linked()?.querySelector('[data-workflow-source]')?.textContent).toBe(+ 'Linked to Portrait Studio, revision 4'+ );+ expect(linked()?.querySelector('[data-template-revision]')?.textContent).toBe('Library template is at revision 6');+ expect(rail()?.querySelector('[data-detail-sheet-summary]')?.textContent).toContain('Template is newer');++ const linkedButton = (text: string) =>+ [...(linked()?.querySelectorAll('button') ?? [])].find((button) => button.textContent === text);+ await click(linkedButton('Update from template'));+ expect(alertDialog()?.textContent).toContain('Replace "User copy"');+ expect(loader.replace).not.toHaveBeenCalled();+ await click(+ [...(alertDialog()?.querySelectorAll('button') ?? [])].find((button) => button.textContent === 'Update')+ );+ expect(loader.replace).toHaveBeenCalledWith(+ { name: 'Portrait Studio', revision: 6, workflow_id: 'wf-portrait' },+ 'wf-user'+ );+ // Updating the library template writes this copy over the template it is linked to, named as in the menu.+ await click(linkedButton('Update library template'));expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({ kind: 'update-source', workflowId: 'wf-user' });});+ it('keeps the linked template card quiet when the copy is current or the template is bundled', async () => {+ templateRecords.set('wf-portrait', { name: 'Portrait Studio', revision: 4 });+ await renderDialog();+ await selectCard('wf-user');++ await vi.waitFor(() => expect(rail()?.querySelector('[data-template-revision="4"]')).not.toBeNull());+ expect(rail()?.querySelector('[data-template-newer]')).toBeNull();++ // A bundled template is never read for its revision, and only its update is offered.+ await selectCard('wf-bundled');+ const linked = rail()?.querySelector<HTMLElement>('[data-linked-template="default_text_to_image"]');+ expect(linked?.querySelector('[data-template-revision]')).toBeNull();+ const buttons = [...(linked?.querySelectorAll('button') ?? [])].map((button) => button.textContent);+ expect(buttons).toEqual(['Update from template']);++ // An unlinked workflow has nothing to update from or save to.+ await selectCard('wf-alpha');+ expect(rail()?.querySelector('[data-linked-template="none"]')?.querySelectorAll('button')).toHaveLength(0);+ });++ it('leads a project card with its last run and lists the run and edit times in the rail', async () => {+ const completedAt = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString();+ project.setSnapshot(+ projectSnapshot([+ { ...ALPHA, lastRun: { completedAt, imageName: 'missing.png', submittedAt: completedAt } },+ USER_COPY,+ ])+ );+ await renderDialog();++ await vi.waitFor(() => expect(card('wf-alpha')?.textContent).toContain('Ran 2 hours ago'));+ expect(card('wf-user')?.textContent).toContain('1 node');+ expect(rail()?.textContent).toContain('Active workflow · ran 2 hours ago');+ const facts = rail()?.querySelector<HTMLElement>('[data-project-workflow-facts]');+ expect(facts?.textContent).toContain('Last run2 hours ago');+ expect(facts?.textContent).toContain('Edited');+ });+it('reopens on the active workflow, so its template update writes the workflow being edited', async () => {const LANDSCAPE_COPY: ProjectWorkflowEntry = {document: { ...createProjectGraph('wf-landscape'), name: 'Landscape copy' },@@ -2125,20 +4857,75 @@ describe('WorkflowLibraryDialog — This project', () => {expect(menuItem('save-to-library')).not.toBeNull();});- it('previews a project workflow from its own document', async () => {+ it('draws a project workflow afresh when its document is replaced under the same id, dropping the open card', async () => {+ const stage = () => document.querySelector<HTMLElement>('[data-preview-stage]');+ const nodes = () => [...(stage()?.querySelectorAll<HTMLElement>('.react-flow__node') ?? [])];await renderDialog();await selectCard('wf-user');+ await clickText('Preview');+ await act(async () => {+ await vi.waitFor(() => expect(nodes()).toHaveLength(1), { timeout: 2000 });+ });+ await act(() => userEvent.click(nodes()[0]!));+ expect(stage()?.querySelector('[data-preview-node-card]')).not.toBeNull();- await clickText('Preview graph');+ // As Update from template does: the same workflow id, another document whose nodes the card's node is not among.await act(async () => {- await vi.waitFor(() => expect(document.querySelector('[data-preview-dialog]')).not.toBeNull(), {- timeout: 2000,- });+ project.setSnapshot(+ projectSnapshot(+ PROJECT_WORKFLOWS.map((workflow) =>+ workflow === USER_COPY+ ? { ...USER_COPY, document: { ...GRAPH_DOCUMENT, id: 'wf-user', name: 'User copy' } }+ : workflow+ )+ )+ );+ await settleFrame();+ });++ await act(async () => {+ await vi.waitFor(+ () => expect(nodes().map((node) => node.dataset.id)).toEqual(['model', 'denoise', 'decode', 'refine']),+ {+ timeout: 2000,+ }+ );+ });+ expect(stage()?.querySelector('[data-preview-node-card]')).toBeNull();+ expect(stage()?.querySelector('[data-preview-node-count]')?.textContent).toContain('Showing 4 of 6 nodes');+ });++ it('previews a project workflow from its own document and steps through the project’s workflows', async () => {+ const stage = () => document.querySelector<HTMLElement>('[data-preview-stage]');+ const stageButton = (label: string) =>+ [...(stage()?.querySelectorAll<HTMLButtonElement>('button') ?? [])].find(+ (button) => button.getAttribute('aria-label') === label+ );+ await renderDialog();+ // Pointer-only quick actions mount on the card's first pointer visit.+ await vi.waitFor(() => expect(card('wf-user')).not.toBeNull());+ await act(() => userEvent.hover(card('wf-user')!));+ const quickPreview = card('wf-user')+ ?.closest('[data-workflow-card-root]')+ ?.querySelector<HTMLButtonElement>('[data-card-action="preview"]');+ await click(quickPreview);++ expect(stage()?.getAttribute('aria-label')).toBe('Preview of User copy');+ expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-user');+ expect(rail()?.querySelector('[data-workflow-provenance]')?.textContent).toBe('In this project · v1.0.0');+ // The project's own document: its one integer node, drawn without any library read.+ await act(async () => {+ await vi.waitFor(() => expect(stage()?.querySelectorAll('.react-flow__node')).toHaveLength(1), { timeout: 2000 });});+ const stepper = rail()!.querySelector<HTMLElement>('[data-detail-rail-stepper] [data-preview-stepper]')!;+ expect(stepper.querySelector('[data-preview-position]')?.textContent).toBe('3 of 3');++ await click(stepper.querySelector<HTMLButtonElement>('button[aria-label="Previous workflow"]'));+ expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-bundled');+ expect(stage()?.getAttribute('aria-label')).toBe('Preview of Bundled copy');- const preview = document.querySelector('[data-preview-dialog]');- expect(preview?.getAttribute('data-graph-id')).toBe('wf-user');- expect(preview?.getAttribute('data-source-label')).toBe('User copy');- expect(preview?.textContent).toContain('integer');+ await click(stageButton('Back to In this project'));+ expect(stage()).toBeNull();+ expect(document.activeElement).toBe(card('wf-bundled'));});});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex f78a4ea759..d3ec8698ff 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -1,34 +1,30 @@-import type { ProjectWorkflowEntry } from '@features/workflow/core/types';import type {+ WorkflowLibraryBrowseFilter,WorkflowLibraryBrowseSnapshot,- WorkflowLibraryEntry,+ WorkflowLibraryPlace,WorkflowLibrarySort,} from '@features/workflow/data/libraryBrowseStore';import type { WorkflowLibraryListItem } from '@features/workflow/queries';-import type { WorkflowThumbnailFit } from '@features/workflow/ui/WorkflowUiContext';-import type { ChangeEvent } from 'react';+import type { WorkflowPreviewView } from '@features/workflow/ui/graph-preview/WorkflowPreviewStage';+import type { WorkflowLibraryLayout, WorkflowThumbnailFit } from '@features/workflow/ui/WorkflowUiContext';-import {- Box,- createListCollection,- HStack,- Input,- Portal,- Spinner,- Stack,- type SystemStyleObject,- Text,-} from '@chakra-ui/react';+import { Box, HStack, Portal, Spinner, Stack, type SystemStyleObject, Text } from '@chakra-ui/react';+import { useOptionalGalleryHostProjectContext } from '@features/gallery/react';import { useAuthSession } from '@features/identity';import {ensureWorkflowLibraryBrowseLoaded,getWorkflowLibraryBrowseSnapshot,+ getWorkflowLibraryOrder,+ getWorkflowLibrarySortDefaultDirection,+ holdWorkflowLibraryBrowse,+ loadWorkflowLibraryPlaceTotals,selectWorkflowLibraryEntry,setWorkflowLibraryBrowseFilter,- setWorkflowLibrarySelectedDemand,useWorkflowLibraryBrowseSelector,} from '@features/workflow/data/libraryBrowseStore';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { WORKFLOW_PREVIEW_DIALOG_SIZE } from '@features/workflow/ui/graph-preview/WorkflowPreviewStage';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {useWorkflowPreferencesSelector,useWorkflowProjectSelector,@@ -36,135 +32,240 @@ import {} from '@features/workflow/ui/WorkflowUiContext';import {requestLibraryCopyChoice,+ setWorkflowLibraryProjectOrder,+ setWorkflowLibrarySearch,setWorkflowLibrarySelection,setWorkflowLibraryTab,+ setWorkflowLibraryTags,workflowUiStore,+ type ProjectWorkflowSort,type WorkflowLibraryTab,} from '@features/workflow/ui/workflowUiStore';import { useMountEffect } from '@platform/react/useMountEffect';-import { CloseButton, SegmentTabs, segmentTabsPanelId, segmentTabsTabId } from '@platform/ui';+import { CloseButton } from '@platform/ui/Button';import { Dialog } from '@platform/ui/Dialog';-import { SegmentedControl } from '@platform/ui/SegmentedControl';-import { Select } from '@platform/ui/Select';-import { Suspense, useCallback, useId, useMemo, useRef, useState } from 'react';+import { useCallback, useId, useMemo, useRef, useState } from 'react';+import { flushSync } from 'react-dom';import { useTranslation } from 'react-i18next';+import type { WorkflowLibraryPanesPreview } from './WorkflowLibraryBrowsePanes';import type { WorkflowCardMenuAnchor } from './WorkflowLibraryCard';+import type { WorkflowContextMenuTarget } from './WorkflowLibraryContextMenu';+import type { WorkflowLibraryListTrailingField } from './WorkflowLibraryList';+import type { WorkflowLibraryPreviewStageHandle } from './WorkflowLibraryPreviewStage';+import type { WorkflowLibraryCardSize } from './workflowThumbnail';+import { preloadGraphPreview } from './libraryPreviewSource';import {- buildLibraryGraphPreviewSource,- DeferredGraphPreviewDialog,- preloadGraphPreview,-} from './libraryPreviewSource';+ countProjectWorkflowTags,+ queryProjectWorkflowEntries,+ toProjectWorkflowLibraryEntries,+} from './projectWorkflowEntries';import { ProjectWorkflowsView } from './ProjectWorkflowsView';import { planLibraryWorkflowOpen, useOpenLibraryWorkflow } from './useOpenLibraryWorkflow';-import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';-import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';-import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';+import { isWorkflowDetailSheetEscape } from './WorkflowDetailSheet';+import { WorkflowLibraryBrowsePanes, WorkflowLibraryResultLine } from './WorkflowLibraryBrowsePanes';+import { getWorkflowLibraryCardId } from './WorkflowLibraryCard';+import {+ getWorkflowLibraryPlaceLabelId,+ getWorkflowLibraryPlaceLabelKey,+ WORKFLOW_LIBRARY_NARROW,+ WORKFLOW_LIBRARY_WIDE,+ WorkflowLibraryPlaceSelect,+ WorkflowLibraryRail,+ WorkflowLibraryTagButton,+} from './WorkflowLibraryRail';+import { WorkflowLibraryToolbar, type WorkflowLibrarySortOption } from './WorkflowLibraryToolbar';import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';-import { WorkflowThumbnailFitContext } from './workflowThumbnail';+import { WorkflowLibraryCardSizeContext, WorkflowThumbnailFitContext } from './workflowThumbnail';const SEARCH_DEBOUNCE_MS = 300;-// Short windows need the panes' full shared height; reclaim modal margins before compressing the toolbar.+// Short windows need the panes' full shared height; reclaim modal margins.const CONTENT_CSS: SystemStyleObject = {- containerName: 'workflow-library-content',- containerType: 'size',- overflowY: 'auto',+ containerName: 'workflow-library-dialog',+ containerType: 'inline-size','@media (height < 40rem)': {h: 'calc(100dvh - 2rem)',maxH: 'calc(100dvh - 2rem)',- maxW: 'min(72rem, calc(100vw - 1rem))',+ maxW: 'min(80rem, calc(100vw - 1rem))',},};-// A 180px card, 18rem rail, gap and body padding need 32rem; below that, keep the stacked layout.+/**+ * Wide (`WORKFLOW_LIBRARY_WIDE`): the body is one grid, matching the artboard. The places rail and the detail rail+ * are flush full-height columns from under the header to the dialog's bottom edge, each separated by a 1px border;+ * the toolbar, result line and cards share the centre column between them. The centre and panes boxes dissolve+ * (`display: contents`) so their parts become the grid's items, and the body is the container the cards and detail+ * rail lay out against (`workflow-library-content`); a body too short for them scrolls as a whole.+ */const BODY_CSS: SystemStyleObject = {- '@container workflow-library-content (width < 42rem) and ((height >= 32rem) or (width < 32rem))': {- flexDirection: 'column',+ display: 'flex',+ // Preview mode: the stage covers the places rail and the collection, which stay laid out (scroll positions, the+ // column widths the detail rail keeps) but leave the tab order and the accessibility tree.+ '&[data-previewing] > [data-library-rail-slot], &[data-previewing] [data-workflow-library-toolbar], &[data-previewing] [data-workflow-library-results], &[data-previewing] [data-workflow-library-collection]':+ { visibility: 'hidden' },+ // Narrow, the stage takes the toolbar's height too; the collection under it keeps its own.+ [WORKFLOW_LIBRARY_NARROW]: {+ '&[data-previewing] [data-workflow-library-toolbar], &[data-previewing] [data-workflow-library-results]': {+ display: 'none',+ },},- // Finite panes enter modal scroll flow when they cannot share the remaining height.- '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {- flex: '0 0 auto',+ [WORKFLOW_LIBRARY_WIDE]: {+ columnGap: '3',+ containerName: 'workflow-library-content',+ containerType: 'size',+ display: 'grid',+ gridTemplateAreas: '"rail toolbar detail" "rail results detail" "rail panes detail"',+ gridTemplateColumns: 'auto minmax(0, 1fr) auto',+ gridTemplateRows: 'auto auto minmax(0, 1fr)',+ overflowY: 'auto',+ rowGap: '2',+ '& [data-workflow-library-toolbar]': { gridArea: 'toolbar', mt: '3' },+ '& [data-workflow-library-results]': { gridArea: 'results' },},};+const RAIL_SLOT_CSS: SystemStyleObject = {+ [WORKFLOW_LIBRARY_NARROW]: { display: 'none' },+ [WORKFLOW_LIBRARY_WIDE]: { gridArea: 'rail' },+};+/**+ * Narrow (`WORKFLOW_LIBRARY_NARROW`): the centre column is the container the cards and the sheet lay out against, and+ * it scrolls when they cannot share its height; the places rail gives way to the toolbar's select and Tags button.+ */+const CENTRE_CSS: SystemStyleObject = {+ containerName: 'workflow-library-content',+ containerType: 'size',+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ gap: '2',+ minH: '0',+ minW: '0',+ overflowY: 'auto',+ p: '3',+ // When the column scrolls (a flow layout), scrolling into view keeps clear of its padding and of the sheet's sticky+ // summary.+ [WORKFLOW_LIBRARY_NARROW]: { scrollPaddingBottom: '6rem', scrollPaddingTop: '3' },+ [WORKFLOW_LIBRARY_WIDE]: { containerType: 'normal', display: 'contents' },+};-const TAB_ITEMS: ReadonlyArray<{ labelKey: string; value: WorkflowLibraryTab }> = [- { labelKey: 'workflowLibrary.thisProject', value: 'project' },- { labelKey: 'workflowLibrary.browse', value: 'default' },- { labelKey: 'workflowLibrary.yours', value: 'user' },- { labelKey: 'workflowLibrary.shared', value: 'shared' },-];+const LIBRARY_SORTS: readonly WorkflowLibrarySort[] = ['opened', 'updated', 'lastRun', 'created', 'name'];+const PROJECT_SORTS: readonly ProjectWorkflowSort[] = ['order', 'name', 'updated', 'lastRun'];+const SORT_LABEL_KEYS: Record<WorkflowLibrarySort | ProjectWorkflowSort, string> = {+ created: 'workflowLibrary.sortCreated',+ lastRun: 'workflowLibrary.sortLastRun',+ name: 'workflowLibrary.sortName',+ opened: 'workflowLibrary.sortOpened',+ order: 'workflowLibrary.sortProjectOrder',+ updated: 'workflowLibrary.sortUpdated',+};-const SORT_ITEMS: ReadonlyArray<{ labelKey: string; value: WorkflowLibrarySort }> = [- { labelKey: 'workflowLibrary.sortUpdated', value: 'updated' },- { labelKey: 'workflowLibrary.sortOpened', value: 'opened' },- { labelKey: 'workflowLibrary.sortCreated', value: 'created' },- { labelKey: 'workflowLibrary.sortName', value: 'name' },-];+/** What a direction means for a key: dates newest or oldest first, names A to Z, the project's order or reversed. */+const getDirectionLabelKey = (sort: WorkflowLibrarySort | ProjectWorkflowSort, direction: 'asc' | 'desc') => {+ if (sort === 'name') {+ return direction === 'asc' ? 'workflowLibrary.sortAToZ' : 'workflowLibrary.sortZToA';+ }-const THUMBNAIL_FIT_ITEMS: ReadonlyArray<{ labelKey: string; value: WorkflowThumbnailFit }> = [- { labelKey: 'workflowLibrary.thumbnailFitCover', value: 'cover' },- { labelKey: 'workflowLibrary.thumbnailFitContain', value: 'contain' },-];+ if (sort === 'order') {+ return direction === 'asc' ? 'workflowLibrary.sortFirstToLast' : 'workflowLibrary.sortLastToFirst';+ }-const SORT_SELECT_WIDTH = '9.5rem';+ return direction === 'asc' ? 'workflowLibrary.sortOldestFirst' : 'workflowLibrary.sortNewestFirst';+};-/**- * Title, search, tabs and Close need about 36rem side by side. Below that header width Close stays beside the title,- * the search and the tabs take full rows of their own (in focus order), and the tag chips sit above Sort and Fit.- */-const NARROW_HEADER = '@container workflow-library-header (width < 36rem)';-const HEADER_CSS: SystemStyleObject = { containerName: 'workflow-library-header', containerType: 'inline-size' };-const HEADER_TOP_CSS: SystemStyleObject = {- alignItems: 'center',- columnGap: '3',- display: 'grid',- gridTemplateAreas: '"title lead tabs close"',- gridTemplateColumns: 'auto minmax(0, 1fr) auto auto',- rowGap: '2',- [NARROW_HEADER]: {- gridTemplateAreas: '"title close" "lead lead" "tabs tabs"',- gridTemplateColumns: 'minmax(0, 1fr) auto',- },+const flipDirection = (direction: 'asc' | 'desc') => (direction === 'asc' ? 'desc' : 'asc');++/** The date a list row shows: the one the current order sorts by, else when the workflow last changed. */+const TRAILING_FIELDS: Partial<Record<WorkflowLibrarySort | ProjectWorkflowSort, WorkflowLibraryListTrailingField>> = {+ created: 'created_at',+ lastRun: 'last_run_at',+ opened: 'opened_at',};-const HEADER_FILTERS_CSS: SystemStyleObject = {- [NARROW_HEADER]: { flexWrap: 'wrap', justifyContent: 'flex-end', rowGap: '2' },++const PLACE_EMPTY_KEYS: Partial<Record<WorkflowLibraryTab, string>> = {+ recent: 'workflowLibrary.emptyRecent',+ shared: 'workflowLibrary.emptyShared',+ user: 'workflowLibrary.emptyUser',};-// An empty strip (the project tab, or no tags) keeps only its spacer role, so it adds no row.-const TAG_STRIP_CSS: SystemStyleObject = { [NARROW_HEADER]: { flexBasis: 'full', '&:empty': { flexBasis: '0' } } };-const SORT_SELECT_CSS: SystemStyleObject = { [NARROW_HEADER]: { flex: '1', minW: '0', w: 'auto' } };--/** Flat and shallow-comparable, so unrelated store patches do not re-render the shell. */-const selectBrowseView = (snapshot: WorkflowLibraryBrowseSnapshot) => ({- viewKey: JSON.stringify(snapshot.filter),- category: snapshot.filter.category,- entries: snapshot.entries,- startIndex: snapshot.startIndex ?? 0,++const EMPTY_PROJECT_ENTRIES: ReturnType<typeof toProjectWorkflowLibraryEntries> = [];++/**+ * Only what the shell lays out: the filter (for the toolbar's order), the rail's totals and tag counts. Entries, range+ * windows, enrichment and selected pins belong to `WorkflowLibraryBrowsePanes`, so they never re-render the shell.+ */+const selectShell = (snapshot: WorkflowLibraryBrowseSnapshot) => ({filter: snapshot.filter,- total: snapshot.total,- selectedEntry: snapshot.selectedEntry,- error: snapshot.error,- isPublic: snapshot.filter.isPublic,- status: snapshot.status,- tag: snapshot.filter.tag,+ placeTotals: snapshot.placeTotals,tagCounts: snapshot.tagCounts,});const selectLibraryNavigation = (snapshot: ReturnType<typeof workflowUiStore.getSnapshot>) => ({+ projectOrder: snapshot.libraryProjectOrder,+ query: snapshot.libraryQuery,selection: snapshot.librarySelection,tab: snapshot.libraryTab,});/**- * On a template tab's first open, load the first page and choose defaults for empty accounts only if filters have- * not changed during the probe. The project view never loads library pages.+ * Mounted while a template place shows: on opening, or on leaving This project. It applies the opening filter, and on+ * leaving (closing, or switching to This project) drops the search and tags from the listing, so the next opening+ * never paints a filtered view first. The project view never loads library pages.*/-const WorkflowLibraryBrowseSession = ({ sort }: { sort: WorkflowLibrarySort }) => {+const WorkflowLibraryBrowseSession = ({+ opening,+ onLeave,+}: {+ opening: WorkflowLibraryBrowseFilter;+ /** Stable; cancels the search still waiting to reach the listing. */+ onLeave: () => void;+}) => {useMountEffect(() => {- void ensureWorkflowLibraryBrowseLoaded(sort).then(() => {- const { filter, userTotal } = getWorkflowLibraryBrowseSnapshot();+ // While it holds the listing, a recorded open or run refreshes the view on screen at once.+ const release = holdWorkflowLibraryBrowse();+ void ensureWorkflowLibraryBrowseLoaded(opening);- if (userTotal === 0 && filter.category === 'user' && !filter.isPublic && !filter.search) {- setWorkflowLibraryBrowseFilter({ category: 'default', tag: null });+ return () => {+ release();+ onLeave();+ setWorkflowLibraryBrowseFilter({ search: '', tags: [] });+ };+ });++ return null;+};++/**+ * Once per opening: the rail's place totals, leaving out the place whose unfiltered first page counts it anyway, and,+ * only when the library opened on My library, the switch to Templates for an account with no workflows of its own+ * (unless the user moved or filtered meanwhile).+ */+const WorkflowLibraryOpeningSession = ({+ opening,+ place,+ places,+}: {+ opening: WorkflowLibraryBrowseFilter;+ place: WorkflowLibraryTab;+ places: readonly WorkflowLibraryPlace[];+}) => {+ useMountEffect(() => {+ void loadWorkflowLibraryPlaceTotals(places.filter((candidate) => candidate !== place));++ if (place !== 'user') {+ return;+ }++ void ensureWorkflowLibraryBrowseLoaded(opening).then(() => {+ const { filter, placeTotals } = getWorkflowLibraryBrowseSnapshot();++ if (+ placeTotals.user === 0 &&+ workflowUiStore.getSnapshot().libraryTab === 'user' &&+ filter.place === 'user' &&+ !filter.search &&+ filter.tags.length === 0+ ) {+ setWorkflowLibraryBrowseFilter({ place: 'default', tags: [] });setWorkflowLibraryTab('default');}});@@ -173,10 +274,8 @@ const WorkflowLibraryBrowseSession = ({ sort }: { sort: WorkflowLibrarySort }) =return null;};-/** A preview request from either view: a library entry's enriched document or a project workflow's own. */-type PreviewRequest =- | { kind: 'library'; entry: WorkflowLibraryEntry }- | { kind: 'project'; entry: ProjectWorkflowEntry };+const SINGLE_USER_PLACES: readonly WorkflowLibraryPlace[] = ['recent', 'user', 'default'];+const MULTIUSER_PLACES: readonly WorkflowLibraryPlace[] = ['recent', 'user', 'default', 'shared'];export const WorkflowLibraryDialog = ({isOpen,@@ -185,78 +284,129 @@ export const WorkflowLibraryDialog = ({isOpen: boolean;onOpenChange: (isOpen: boolean) => void;}) => {- const { t } = useTranslation();- const {- category,- entries,- error,- isPublic,- status,- tag,- tagCounts,- startIndex,- filter,- total,- selectedEntry,- viewKey,- } = useWorkflowLibraryBrowseSelector(selectBrowseView);- const { selection, tab } = workflowUiStore.useSelector(selectLibraryNavigation);+ const { i18n, t } = useTranslation();+ const tagListFormat = useMemo(+ () => new Intl.ListFormat(i18n.resolvedLanguage, { type: 'disjunction' }),+ [i18n.resolvedLanguage]+ );+ const { filter, placeTotals, tagCounts } = useWorkflowLibraryBrowseSelector(selectShell);+ const { projectOrder, query, selection, tab } = workflowUiStore.useSelector(selectLibraryNavigation);const authSession = useAuthSession();+ const projectContext = useOptionalGalleryHostProjectContext();const projectId = useWorkflowProjectSelector((project) => project.id);const projectWorkflows = useWorkflowProjectSelector((project) => project.workflows);const templatesSnapshot = useInvocationTemplatesSnapshot();+ const { createWorkflow } = useProjectGraphCommands();const { setLibraryPreferences } = useWorkflowUi();const sort = useWorkflowPreferencesSelector((preferences) => preferences.workflowLibrarySort);+ const sortDirection = useWorkflowPreferencesSelector((preferences) => preferences.workflowLibrarySortDirection);+ const layout = useWorkflowPreferencesSelector((preferences) => preferences.workflowLibraryLayout);+ const cardSize = useWorkflowPreferencesSelector((preferences) => preferences.workflowLibraryCardSize);const thumbnailFit = useWorkflowPreferencesSelector((preferences) => preferences.workflowLibraryThumbnailFit);- const [searchInput, setSearchInput] = useState('');const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(null);const [removedWorkflowId, setRemovedWorkflowId] = useState<string | null>(null);- // Clear pending preview entries on every library-close path because the persistent shell otherwise resurrects- // them on reopen.- const [previewRequest, setPreviewRequest] = useState<PreviewRequest | null>(null);- // Close before clearing the request so the lazy dialog remains mounted through its exit transition.- const [isPreviewOpen, setIsPreviewOpen] = useState(false);- const [contextMenuPoint, setContextMenuPoint] = useState<WorkflowCardMenuAnchor | null>(null);- // The element focus returns to when the menu closes. It outlives the open menu: the menu is told it closed only- // after React has rendered the close, so the trigger it restores focus to must still be the one that opened it.- const [contextMenuTriggerId, setContextMenuTriggerId] = useState<string | null>(null);+ /**+ * Preview mode, for the life of this opening: the workflow it opened on and the control that opened it, which takes+ * focus back on leaving. Closing clears it (below), since the persistent shell would otherwise reopen on it.+ */+ const [preview, setPreview] = useState<{ opener: HTMLElement | null; workflowId: string } | null>(null);+ // Graph or Inputs: the stage opens on Graph and keeps the choice until the library closes.+ const [previewView, setPreviewView] = useState<WorkflowPreviewView>('nodes');+ // However the library closes (its own controls, the copy question, the host), it reopens on the collection, on Graph.+ if (!isOpen && (preview !== null || previewView !== 'nodes')) {+ setPreview(null);+ setPreviewView('nodes');+ }+ const contentRef = useRef<HTMLDivElement | null>(null);+ const stageRef = useRef<WorkflowLibraryPreviewStageHandle | null>(null);+ // A card's or row's actions menu acts on the workflow it was raised for and leaves the selection alone. The anchor+ // says where it is open; the target outlives it, for focus return and the dialogs its items open.+ const [contextMenuAnchor, setContextMenuAnchor] = useState<WorkflowCardMenuAnchor | null>(null);+ const [contextMenuTarget, setContextMenuTarget] = useState<WorkflowContextMenuTarget | null>(null);const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const searchInputRef = useRef<HTMLInputElement>(null);+ const placeIdBase = useId();++ const isProjectTab = tab === 'project';+ const places = authSession.multiuserEnabled ? MULTIUSER_PLACES : SINGLE_USER_PLACES;+ const cancelPendingSearch = useCallback(() => {+ if (searchTimerRef.current !== null) {+ clearTimeout(searchTimerRef.current);+ searchTimerRef.current = null;+ }+ }, []);const closeDialog = useCallback(() => {- // Closing the library removes its preview immediately; the parent surface is leaving too.- setPreviewRequest(null);- setIsPreviewOpen(false);- setContextMenuPoint(null);+ // Closing the library removes its preview immediately; the parent surface is leaving too. The search it would+ // have applied is cleared with the rest of the query.+ cancelPendingSearch();+ setContextMenuAnchor(null);onOpenChange(false);- }, [onOpenChange]);+ }, [cancelPendingSearch, onOpenChange]);const { loadPhase, open } = useOpenLibraryWorkflow(closeDialog);const isLoadPending = loadPhase !== 'idle';- const missingCounts = useWorkflowLibraryMissingCounts(entries);-- // Derive a fallback selection when filtering/deletion removes the selected row.- const desiredWorkflowId = selectedWorkflowId ?? selectedEntry?.item.workflow_id ?? null;- const activeWorkflowId =- selectedEntry?.item.workflow_id === desiredWorkflowId ||- entries.some((entry) => entry.item.workflow_id === desiredWorkflowId)- ? desiredWorkflowId- : (entries[0]?.item.workflow_id ?? null);- const activeEntry = selectWorkflowLibraryEntry({ entries, selectedEntry }, activeWorkflowId) ?? null;- const isCurrentLibraryOwner =- authSession.phase === 'ready' &&- (authSession.multiuserEnabled- ? Boolean(activeEntry?.item.user_id && activeEntry.item.user_id === authSession.user?.user_id)- : true);- const canEditLibraryEntry = activeEntry?.item.category === 'user' && isCurrentLibraryOwner;- const isReadOnlyLibraryEntry = activeEntry?.item.category === 'user' && !isCurrentLibraryOwner;- const canChangeVisibility =- tab === 'user' &&- authSession.phase === 'ready' &&- authSession.multiuserEnabled &&- activeEntry?.item.category === 'user' &&- isCurrentLibraryOwner;++ // This project filters and orders locally; the template places' results are the server's.+ const projectEntries = useMemo(+ () =>+ isProjectTab+ ? queryProjectWorkflowEntries(+ toProjectWorkflowLibraryEntries(+ projectWorkflows,+ templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null+ ),+ { order: projectOrder, search: query.search, tags: query.tags }+ )+ : EMPTY_PROJECT_ENTRIES,+ [isProjectTab, projectOrder, projectWorkflows, query, templatesSnapshot]+ );+ const projectTagCounts = useMemo(() => countProjectWorkflowTags(projectWorkflows), [projectWorkflows]);++ // A menu whose workflow left the view (a filter, a removal, a window that moved on) has nothing to act on: close it.+ // The template places hold their entries in the browse store; only this flag reaches the shell.+ const contextMenuWorkflowId = contextMenuAnchor?.workflowId ?? null;+ const isLibraryMenuTargetShown = useWorkflowLibraryBrowseSelector(+ (snapshot) =>+ contextMenuWorkflowId === null ||+ isProjectTab ||+ selectWorkflowLibraryEntry(snapshot, contextMenuWorkflowId) !== undefined+ );+ if (+ contextMenuWorkflowId !== null &&+ !(isProjectTab+ ? projectEntries.some((entry) => entry.item.workflow_id === contextMenuWorkflowId)+ : isLibraryMenuTargetShown)+ ) {+ setContextMenuAnchor(null);+ }+ const missingCounts = useWorkflowLibraryMissingCounts(projectEntries);+// The project selection belongs to the project it was made in; another project starts from its active workflow.const projectSelectionId = selection?.projectId === projectId ? selection.workflowId : null;+ // The order the toolbar shows. Before a template place's first listing the store still holds another place's+ // filter, so the account's stored order stands in for it.+ const libraryOrder = getWorkflowLibraryOrder(+ !isProjectTab && filter.place === tab+ ? filter+ : { direction: sortDirection, place: tab === 'project' ? 'user' : tab, sort }+ );+ const shownOrder = isProjectTab ? projectOrder : libraryOrder;+ const trailingField = TRAILING_FIELDS[shownOrder.sort] ?? 'updated_at';+ const directionLabels = useMemo(+ () => ({+ asc: t(getDirectionLabelKey(shownOrder.sort, 'asc')),+ desc: t(getDirectionLabelKey(shownOrder.sort, 'desc')),+ }),+ [shownOrder.sort, t]+ );+ const sortOptions = useMemo<readonly WorkflowLibrarySortOption[]>(() => {+ const keys: readonly (WorkflowLibrarySort | ProjectWorkflowSort)[] =+ tab === 'project' ? PROJECT_SORTS : tab === 'recent' ? ['opened'] : tab === 'default' ? ['name'] : LIBRARY_SORTS;++ return keys.map((key) => ({ label: t(SORT_LABEL_KEYS[key]), value: key }));+ }, [t, tab]);+const handleDialogOpenChange = useCallback((event: { open: boolean }) => {if (isLoadPending) {@@ -271,113 +421,194 @@ export const WorkflowLibraryDialog = ({},[isLoadPending, onOpenChange, closeDialog]);+ const getInitialFocus = useCallback(() => searchInputRef.current, []);+ // Escape inside an expanded detail sheet collapses the sheet (its own handler) instead of closing the library; in+ // preview mode it closes a node card, else leaves the preview. Only the next Escape closes the library.+ const handleEscapeKeyDown = useCallback(+ (event: KeyboardEvent) => {+ // One keypress can arrive twice (StrictMode registers the open dialog's layer twice); only the first acts, and the+ // default it prevented keeps the second from closing the library.+ if (event.defaultPrevented) {+ return;+ }- const handlePreviewRequest = useCallback((entry: WorkflowLibraryEntry) => {- setPreviewRequest({ entry, kind: 'library' });- setIsPreviewOpen(true);- }, []);- const handleProjectPreviewRequest = useCallback((entry: ProjectWorkflowEntry) => {- setPreviewRequest({ entry, kind: 'project' });- setIsPreviewOpen(true);- }, []);+ if (isWorkflowDetailSheetEscape(event)) {+ event.preventDefault();+ } else if (preview) {+ event.preventDefault();+ stageRef.current?.handleEscape();+ }+ },+ [preview]+ );+ const setContentRef = useCallback((element: HTMLDivElement | null) => {+ contentRef.current = element;- const handlePreviewOpenChange = useCallback((open: boolean) => {- if (!open) {- setIsPreviewOpen(false);+ if (element) {+ preloadGraphPreview();}}, []);- // Guarded on `isPreviewOpen`: previewing another card while the last one is- // still animating out re-opens the same dialog, and an exit report that- // arrives after that must not pull the mount out from under it.- const handlePreviewExitComplete = useCallback(() => {- if (!isPreviewOpen) {- setPreviewRequest(null);- }- }, [isPreviewOpen]);+ // Previewing selects the workflow, so the rail describes what the stage shows. The stage takes focus from the+ // control that asked, which the collection's hiding would otherwise drop to the document.+ const enterPreview = useCallback(+ (workflowId: string, view?: WorkflowPreviewView) => {+ const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;- // Only ready enrichment has a document; guard stale preview entries after revalidation.- const previewSource = useMemo(() => {- if (!previewRequest || templatesSnapshot.status !== 'loaded') {- return null;- }+ flushSync(() => {+ if (view) {+ setPreviewView(view);+ }- if (previewRequest.kind === 'project') {- return buildLibraryGraphPreviewSource(previewRequest.entry.document, templatesSnapshot.templates);- }+ if (isProjectTab) {+ setWorkflowLibrarySelection({ projectId, workflowId });+ } else {+ setSelectedWorkflowId(workflowId);+ }- return previewRequest.entry.enrichment.status === 'ready'- ? buildLibraryGraphPreviewSource(previewRequest.entry.enrichment.document, templatesSnapshot.templates)- : null;- }, [previewRequest, templatesSnapshot]);- const previewGraphId =- previewRequest?.kind === 'project'- ? previewRequest.entry.document.id- : (previewRequest?.entry.item.workflow_id ?? '');- const previewLabel =- (previewRequest?.kind === 'project' ? previewRequest.entry.document.name : previewRequest?.entry.item.name) ||- t('workflowLibrary.untitled');+ setContextMenuAnchor(null);+ setPreview({ opener, workflowId });+ });+ contentRef.current?.querySelector<HTMLElement>('[data-preview-stage]')?.focus({ preventScroll: true });+ },+ [isProjectTab, projectId]+ );+ // Back to the collection as it was. Focus returns to the control that opened the preview while it still shows that+ // workflow; after stepping, to the card or row now selected.+ const leavePreview = useCallback(+ (workflowId: string | null) => {+ const opener = preview?.opener ?? null;+ const isRendered = (element: HTMLElement | null | undefined): element is HTMLElement =>+ element?.isConnected === true && element.getClientRects().length > 0;++ flushSync(() => setPreview(null));++ const selected = workflowId ? document.getElementById(getWorkflowLibraryCardId(workflowId)) : null;+ const target =+ workflowId === preview?.workflowId && isRendered(opener)+ ? opener+ : isRendered(selected)+ ? selected+ : isRendered(opener)+ ? opener+ : searchInputRef.current;++ target?.focus();+ },+ [preview]+ );+ const panesPreview = useMemo<WorkflowLibraryPanesPreview>(+ () => ({+ isActive: preview !== null,+ onLeave: leavePreview,+ onViewChange: setPreviewView,+ placeLabel: t(getWorkflowLibraryPlaceLabelKey(tab)),+ view: previewView,+ }),+ [leavePreview, preview, previewView, t, tab]+ );- const handleSearchChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {- const { value } = event.currentTarget;+ const handleSearchChange = useCallback(+ (value: string) => {+ setWorkflowLibrarySearch(value);+ cancelPendingSearch();++ // This project filters as you type; template places ask the server once typing pauses.+ if (!isProjectTab) {+ searchTimerRef.current = setTimeout(() => {+ searchTimerRef.current = null;+ setWorkflowLibraryBrowseFilter({ search: value });+ }, SEARCH_DEBOUNCE_MS);+ }+ },+ [cancelPendingSearch, isProjectTab]+ );- setSearchInput(value);+ const handlePlaceChange = useCallback(+ (place: WorkflowLibraryTab) => {+ setContextMenuAnchor(null);+ cancelPendingSearch();+ setWorkflowLibraryTab(place);- if (searchTimerRef.current !== null) {- clearTimeout(searchTimerRef.current);- }+ // Before the first template listing, the browse session applies the opening filter when it mounts.+ if (place !== 'project' && getWorkflowLibraryBrowseSnapshot().status !== 'idle') {+ setWorkflowLibraryBrowseFilter({ direction: sortDirection, place, search: query.search, sort, tags: [] });+ }+ },+ [cancelPendingSearch, query.search, sort, sortDirection]+ );- // A post-unmount search debounce may update the browse store for the next opening.- searchTimerRef.current = setTimeout(() => setWorkflowLibraryBrowseFilter({ search: value }), SEARCH_DEBOUNCE_MS);- }, []);+ const handleTagsChange = useCallback(+ (tags: readonly string[]) => {+ setWorkflowLibraryTags(tags);- const handleTabChange = useCallback(- (value: WorkflowLibraryTab) => {- setContextMenuPoint(null);+ if (!isProjectTab) {+ setWorkflowLibraryBrowseFilter({ tags });+ }+ },+ [isProjectTab]+ );- if (value === 'project') {- setWorkflowLibraryTab('project');+ const handleSortChange = useCallback(+ (value: string) => {+ if (isProjectTab) {+ const next = PROJECT_SORTS.find((key) => key === value);++ if (next) {+ setWorkflowLibraryProjectOrder({+ direction: next === 'order' || next === 'name' ? 'asc' : 'desc',+ sort: next,+ });+ }return;}- const nextCategory = value === 'default' ? 'default' : 'user';- const nextIsPublic = value === 'shared' ? true : undefined;+ const next = LIBRARY_SORTS.find((key) => key === value);- setWorkflowLibraryTab(value);+ // Only My library and Shared offer a choice; a new key starts in its natural direction.+ if (next && (tab === 'user' || tab === 'shared')) {+ const direction = getWorkflowLibrarySortDefaultDirection(next);- if (category !== nextCategory || isPublic !== nextIsPublic) {- setWorkflowLibraryBrowseFilter({ category: nextCategory, isPublic: nextIsPublic, tag: null });+ setLibraryPreferences({ workflowLibrarySort: next, workflowLibrarySortDirection: direction });+ setWorkflowLibraryBrowseFilter({ direction, sort: next });}},- [category, isPublic]+ [isProjectTab, setLibraryPreferences, tab]);- const handleTagSelect = useCallback((nextTag: string | null) => setWorkflowLibraryBrowseFilter({ tag: nextTag }), []);- const sortCollection = useMemo(- () => createListCollection({ items: SORT_ITEMS.map((item) => ({ label: t(item.labelKey), value: item.value })) }),- [t]- );- const sortValue = useMemo(() => [sort], [sort]);- const handleSortChange = useCallback(- ({ value }: { value: string[] }) => {- const next = SORT_ITEMS.find((item) => item.value === value[0])?.value;+ const handleDirectionToggle = useCallback(() => {+ if (isProjectTab) {+ setWorkflowLibraryProjectOrder({ ...projectOrder, direction: flipDirection(projectOrder.direction) });+ return;+ }- if (next) {- setLibraryPreferences({ workflowLibrarySort: next });- setWorkflowLibraryBrowseFilter({ sort: next });- }- },+ const direction = flipDirection(libraryOrder.direction);++ if (tab === 'default') {+ // Templates always list by name; reversing them lasts until another place applies the account's order.+ setWorkflowLibraryBrowseFilter({ direction, sort: 'name' });+ } else if (tab === 'user' || tab === 'shared') {+ setLibraryPreferences({ workflowLibrarySortDirection: direction });+ setWorkflowLibraryBrowseFilter({ direction });+ }+ }, [isProjectTab, libraryOrder.direction, projectOrder, setLibraryPreferences, tab]);++ const handleLayoutChange = useCallback(+ (workflowLibraryLayout: WorkflowLibraryLayout) => setLibraryPreferences({ workflowLibraryLayout }),[setLibraryPreferences]);- const thumbnailFitOptions = useMemo(- () => THUMBNAIL_FIT_ITEMS.map((item) => ({ label: t(item.labelKey), value: item.value })),- [t]+ const handleCardSizeChange = useCallback(+ (workflowLibraryCardSize: WorkflowLibraryCardSize) => setLibraryPreferences({ workflowLibraryCardSize }),+ [setLibraryPreferences]);const handleThumbnailFitChange = useCallback(- (value: string) =>- setLibraryPreferences({ workflowLibraryThumbnailFit: value === 'contain' ? 'contain' : 'cover' }),+ (workflowLibraryThumbnailFit: WorkflowThumbnailFit) => setLibraryPreferences({ workflowLibraryThumbnailFit }),[setLibraryPreferences]);+ const handleNewWorkflow = useCallback(+ () => setWorkflowLibrarySelection({ projectId, workflowId: createWorkflow() }),+ [createWorkflow, projectId]+ );// The first copy is added directly; with one already in the project, the host asks what opening should do.const handleOpenItem = useCallback(@@ -393,9 +624,7 @@ export const WorkflowLibraryDialog = ({);const handleOpenWorkflow = useCallback((workflowId: string) => {- const entry = getWorkflowLibraryBrowseSnapshot().entries.find(- (candidate) => candidate.item.workflow_id === workflowId- );+ const entry = selectWorkflowLibraryEntry(getWorkflowLibraryBrowseSnapshot(), workflowId);if (entry) {handleOpenItem(entry.item);@@ -404,264 +633,243 @@ export const WorkflowLibraryDialog = ({[handleOpenItem]);- const handleDeleted = useCallback(() => {- setRemovedWorkflowId(activeWorkflowId);- setSelectedWorkflowId(null);- setContextMenuPoint(null);- }, [activeWorkflowId]);+ // Deleting another workflow, from its card's menu, keeps the selection.+ const handleDeleted = useCallback((workflowId: string) => {+ setRemovedWorkflowId(workflowId);+ setSelectedWorkflowId((current) => (current === workflowId ? null : current));+ setContextMenuAnchor(null);+ }, []);const handleCardContextMenu = useCallback(- (workflowId: string, point: WorkflowCardMenuAnchor) => {- if (tab === 'project') {- setWorkflowLibrarySelection({ projectId, workflowId });- } else {- setSelectedWorkflowId(workflowId);- }-- setContextMenuTriggerId(point.kind === 'trigger' ? point.triggerId : null);+ (workflowId: string, anchor: WorkflowCardMenuAnchor) => {+ const target = { triggerId: anchor.kind === 'trigger' ? anchor.triggerId : null, workflowId };// The menu button that opened the menu closes it again.if (- point.kind === 'trigger' &&- contextMenuPoint?.kind === 'trigger' &&- contextMenuPoint.triggerId === point.triggerId+ anchor.kind === 'trigger' &&+ contextMenuAnchor?.kind === 'trigger' &&+ contextMenuAnchor.triggerId === anchor.triggerId) {- setContextMenuPoint(null);+ setContextMenuAnchor(null);return;}- // An open menu does not follow a new anchor: close it and reopen it at the- // new point once that close has rendered, as a native menu relocates.- if (contextMenuPoint) {- setContextMenuPoint(null);- requestAnimationFrame(() => setContextMenuPoint(point));+ // An open menu does not follow a new anchor: close it and reopen it at the new point once that close has+ // rendered, as a native menu relocates. The closing menu keeps its own workflow's items and focus return.+ if (contextMenuAnchor) {+ setContextMenuAnchor(null);+ requestAnimationFrame(() => {+ setContextMenuTarget(target);+ setContextMenuAnchor(anchor);+ });} else {- setContextMenuPoint(point);+ setContextMenuTarget(target);+ setContextMenuAnchor(anchor);}},- [contextMenuPoint, projectId, tab]+ [contextMenuAnchor]);- const closeContextMenu = useCallback(() => setContextMenuPoint(null), []);+ const closeContextMenu = useCallback(() => setContextMenuAnchor(null), []);const handleProjectSelect = useCallback((workflowId: string | null) => setWorkflowLibrarySelection(workflowId ? { projectId, workflowId } : null),[projectId]);- const browseWindow = useMemo(() => ({ startIndex, total, filter }), [startIndex, total, filter]);- const isProjectTab = tab === 'project';- const tabsIdBase = useId();- const activeTab: WorkflowLibraryTab = tab;- const tabItems = useMemo(- () =>- TAB_ITEMS.filter((item) => item.value !== 'shared' || authSession.multiuserEnabled).map((item) => ({- id: item.value,- label: t(item.labelKey),- })),- [authSession.multiuserEnabled, t]+ // Read once, when a session mounts.+ const openingFilter = useMemo<WorkflowLibraryBrowseFilter>(+ () => ({+ direction: sortDirection,+ place: tab === 'project' ? 'user' : tab,+ search: query.search,+ sort,+ tags: query.tags,+ }),+ [query, sort, sortDirection, tab]);+ // The result line counts what the grid can show: every match on This project, the server's total elsewhere. The+ // missing-model count is exact only while every match is resident, so a partial window shows none.+ const tagsText = query.tags.length > 0 ? tagListFormat.format(query.tags) : '';+ // With no search or tags, an empty place says why, rather than that nothing matched.+ const emptyKey = query.search || query.tags.length > 0 ? undefined : PLACE_EMPTY_KEYS[tab];+ const emptyMessage = emptyKey ? t(emptyKey) : undefined;+return (- <>- <Dialog.Root open={isOpen} size="xl" onOpenChange={handleDialogOpenChange}>- <Portal>- <Dialog.Backdrop />- <Dialog.Positioner>- <Dialog.Content- ref={preloadGraphPreview}- css={CONTENT_CSS}- aria-busy={isLoadPending}- h="80vh"- maxH="80vh"- maxW="min(72rem, calc(100vw - 4rem))"- position="relative"+ <Dialog.Root+ initialFocusEl={getInitialFocus}+ open={isOpen}+ size="xl"+ onEscapeKeyDown={handleEscapeKeyDown}+ onOpenChange={handleDialogOpenChange}+ >+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content+ ref={setContentRef}+ css={CONTENT_CSS}+ aria-busy={isLoadPending}+ {...WORKFLOW_PREVIEW_DIALOG_SIZE}+ position="relative"+ >+ {isLoadPending ? (+ <Stack+ alignItems="center"+ aria-live="polite"+ bg="bg/85"+ inset="0"+ justifyContent="center"+ position="absolute"+ role="status"+ zIndex="modal"+ >+ <Spinner color="accent.solid" size="2xl" />+ <Text fontSize="md" fontWeight="600">+ {loadPhase === 'fetching' ? t('workflowLibrary.fetching') : t('workflowLibrary.applying')}+ </Text>+ </Stack>+ ) : null}+ <Dialog.Header+ alignItems="center"+ borderBottomWidth="1px"+ borderColor="border.subtle"+ display="flex"+ flex="none"+ gap="3"+ h="12"+ px="4"+ py="0">- {isLoadPending ? (- <Stack- alignItems="center"- aria-live="polite"- bg="bg/85"- inset="0"- justifyContent="center"- position="absolute"- role="status"- zIndex="modal"- >- <Spinner color="accent.solid" size="2xl" />- <Text fontSize="md" fontWeight="600">- {loadPhase === 'fetching' ? t('workflowLibrary.fetching') : t('workflowLibrary.applying')}+ <HStack align="baseline" flex="1" gap="2.5" minW="0">+ <Dialog.Title flexShrink={0}>{t('workflowLibrary.title')}</Dialog.Title>+ {projectContext?.projectName ? (+ <Text color="fg.muted" fontSize="md" minW="0" truncate>+ {projectContext.projectName}</Text>- </Stack>- ) : null}- <Dialog.Header>- <Stack css={HEADER_CSS} gap="2" minW="0" w="full">- <Box css={HEADER_TOP_CSS} minW="0">- <Dialog.Title gridArea="title" minW="0" truncate>- {t('workflowLibrary.title')}- </Dialog.Title>- {isProjectTab ? (- <Text color="fg.subtle" fontSize="md" gridArea="lead" minW="0" truncate>- {t('workflowLibrary.thisProjectHint')}- </Text>- ) : (- <Input- aria-label={t('workflowLibrary.searchPlaceholder')}- gridArea="lead"- minW="0"- placeholder={t('workflowLibrary.searchPlaceholder')}- type="search"- value={searchInput}- onChange={handleSearchChange}- />- )}- <Box gridArea="tabs" minW="0">- <SegmentTabs- activeId={activeTab}- ariaLabel={t('workflowLibrary.title')}- idBase={tabsIdBase}- isCompact- tabs={tabItems}- onSelect={handleTabChange}- />- </Box>- <Dialog.CloseTrigger asChild>- <CloseButton- disabled={isLoadPending}- gridArea="close"- insetEnd="auto"- position="static"- top="auto"+ ) : null}+ </HStack>+ <Dialog.CloseTrigger asChild>+ <CloseButton disabled={isLoadPending} insetEnd="auto" position="static" top="auto" />+ </Dialog.CloseTrigger>+ </Dialog.Header>+ <Dialog.Body+ css={BODY_CSS}+ data-library-tab={tab}+ data-previewing={preview ? '' : undefined}+ flex="1"+ gap="0"+ minH="0"+ p="0"+ >+ <Box css={RAIL_SLOT_CSS} data-library-rail-slot="" display="flex" minH="0">+ <WorkflowLibraryRail+ checkedTags={query.tags}+ footer={isProjectTab ? t('workflowLibrary.thisProjectHint') : undefined}+ idBase={placeIdBase}+ place={tab}+ placeTotals={placeTotals}+ projectTotal={projectWorkflows.length}+ showShared={authSession.multiuserEnabled}+ tagCounts={isProjectTab ? projectTagCounts : tagCounts}+ onPlaceChange={handlePlaceChange}+ onTagsChange={handleTagsChange}+ />+ </Box>+ <Box as="section" aria-labelledby={getWorkflowLibraryPlaceLabelId(placeIdBase, tab)} css={CENTRE_CSS}>+ <WorkflowLibraryToolbar+ narrowLead={+ <>+ <WorkflowLibraryPlaceSelect+ place={tab}+ placeTotals={placeTotals}+ projectTotal={projectWorkflows.length}+ showShared={authSession.multiuserEnabled}+ onPlaceChange={handlePlaceChange}/>- </Dialog.CloseTrigger>- </Box>- <HStack css={HEADER_FILTERS_CSS} gap="3" minW="0">- <Box css={TAG_STRIP_CSS} flex="1" minW="0">- {isProjectTab ? null : (- <WorkflowLibraryTagChips selectedTag={tag} tagCounts={tagCounts} onSelect={handleTagSelect} />- )}- </Box>- {/* Bundled templates always list by name, and project workflows keep their own order. */}- {category === 'user' && !isProjectTab ? (- <Select- aria-label={t('workflowLibrary.sortLabel')}- collection={sortCollection}- css={SORT_SELECT_CSS}- flexShrink={0}- size="sm"- value={sortValue}- w={SORT_SELECT_WIDTH}- onValueChange={handleSortChange}+ <WorkflowLibraryTagButton+ checkedTags={query.tags}+ getFallbackFocus={getInitialFocus}+ tagCounts={isProjectTab ? projectTagCounts : tagCounts}+ onTagsChange={handleTagsChange}/>- ) : null}- <SegmentedControl- ariaLabel={t('workflowLibrary.thumbnailFit')}- flexShrink={0}- isFullWidth={false}- options={thumbnailFitOptions}- size="sm"- value={thumbnailFit}- onChange={handleThumbnailFitChange}- />- </HStack>- </Stack>- </Dialog.Header>- <Dialog.Body- css={BODY_CSS}- aria-labelledby={segmentTabsTabId(tabsIdBase, activeTab)}- data-library-tab={tab}- data-pending-preview={previewGraphId || undefined}- display="flex"- flex="1"- gap="3"- id={segmentTabsPanelId(tabsIdBase)}- minH="0"- role="tabpanel"- >+ </>+ }+ cardSize={cardSize}+ direction={shownOrder.direction}+ directionLabels={directionLabels}+ isDirectionFixed={tab === 'recent'}+ isSortFixed={tab === 'recent' || tab === 'default'}+ layout={layout}+ search={query.search}+ searchInputRef={searchInputRef}+ sort={shownOrder.sort}+ sortOptions={sortOptions}+ thumbnailFit={thumbnailFit}+ onCardSizeChange={handleCardSizeChange}+ onDirectionToggle={handleDirectionToggle}+ onLayoutChange={handleLayoutChange}+ onNewWorkflow={isProjectTab ? handleNewWorkflow : undefined}+ onSearchChange={handleSearchChange}+ onSortChange={handleSortChange}+ onThumbnailFitChange={handleThumbnailFitChange}+ /><WorkflowThumbnailFitContext value={thumbnailFit}>- {isProjectTab ? (- <ProjectWorkflowsView- contextMenuPoint={contextMenuPoint}- contextMenuTriggerId={contextMenuTriggerId}- selectedWorkflowId={projectSelectionId}- onClose={closeDialog}- onContextMenu={handleCardContextMenu}- onContextMenuClose={closeContextMenu}- onPreview={handleProjectPreviewRequest}- onSelect={handleProjectSelect}- />- ) : (- <>- {isOpen ? (- <SelectedDemand- key={`${authSession.user?.user_id}:${viewKey}:${activeWorkflowId}`}- id={activeWorkflowId}+ <WorkflowLibraryCardSizeContext value={cardSize}>+ {isProjectTab ? (+ <>+ <WorkflowLibraryResultLine count={projectEntries.length} tagsText={tagsText} />+ <ProjectWorkflowsView+ contextMenuAnchor={contextMenuAnchor}+ contextMenuTarget={contextMenuTarget}+ entries={projectEntries}+ layout={layout}+ missingCounts={missingCounts}+ selectedWorkflowId={projectSelectionId}+ trailingField={trailingField}+ onClose={closeDialog}+ onContextMenu={handleCardContextMenu}+ onContextMenuClose={closeContextMenu}+ onPreview={enterPreview}+ onSelect={handleProjectSelect}+ preview={panesPreview}+ previewStageRef={stageRef}/>- ) : null}- <WorkflowLibraryGrid- key={`${authSession.user?.user_id}:${viewKey}`}- window={browseWindow}- removedWorkflowId={removedWorkflowId}- entries={entries}- error={error}- missingCounts={missingCounts}- openMenuAnchor={contextMenuPoint}- showVisibilityStatus- selectedWorkflowId={activeWorkflowId}- status={status}- onContextMenu={handleCardContextMenu}- onOpen={handleOpenWorkflow}- onSelect={setSelectedWorkflowId}- />- <WorkflowLibraryDetailPanel- contextMenuPoint={contextMenuPoint}- contextMenuTriggerId={contextMenuTriggerId}- entry={activeEntry}- canChangeVisibility={canChangeVisibility}- isReadOnly={isReadOnlyLibraryEntry || !canEditLibraryEntry}+ </>+ ) : (+ <WorkflowLibraryBrowsePanes+ contextMenuAnchor={contextMenuAnchor}+ contextMenuTarget={contextMenuTarget}+ emptyMessage={emptyMessage}+ isOpen={isOpen}+ layout={layout}projectWorkflows={projectWorkflows}+ removedWorkflowId={removedWorkflowId}+ selectedWorkflowId={selectedWorkflowId}+ tab={tab}+ tagsText={tagsText}+ trailingField={trailingField}+ preview={panesPreview}+ previewStageRef={stageRef}onClose={closeDialog}+ onContextMenu={handleCardContextMenu}onContextMenuClose={closeContextMenu}onDeleted={handleDeleted}- onDuplicated={setSelectedWorkflowId}- onOpen={handleOpenItem}- onPreview={handlePreviewRequest}+ onOpen={handleOpenWorkflow}+ onOpenItem={handleOpenItem}+ onPreview={enterPreview}+ onSelect={setSelectedWorkflowId}/>- </>- )}+ )}+ </WorkflowLibraryCardSizeContext></WorkflowThumbnailFitContext>- </Dialog.Body>- {isOpen && !isProjectTab ? <WorkflowLibraryBrowseSession sort={sort} /> : null}- </Dialog.Content>- </Dialog.Positioner>- </Portal>- </Dialog.Root>- {previewRequest && previewSource ? (- <Suspense fallback={null}>- <DeferredGraphPreviewDialog- graphId={previewGraphId}- hideInvoke- isOpen={isPreviewOpen}- source={previewSource}- sourceLabel={previewLabel}- onExitComplete={handlePreviewExitComplete}- onOpenChange={handlePreviewOpenChange}- />- </Suspense>- ) : null}- </>+ </Box>+ </Dialog.Body>+ {isOpen ? <WorkflowLibraryOpeningSession opening={openingFilter} place={tab} places={places} /> : null}+ {isOpen && !isProjectTab ? (+ <WorkflowLibraryBrowseSession opening={openingFilter} onLeave={cancelPendingSearch} />+ ) : null}+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>);};--let selectedLease = 0;-const SelectedDemand = ({ id }: { id: string | null }) => {- useMountEffect(() => {- const lease = ++selectedLease;- setWorkflowLibrarySelectedDemand(id);- return () => {- queueMicrotask(() => {- if (lease === selectedLease) {- setWorkflowLibrarySelectedDemand(null);- }- });- };- });- return null;-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryFacts.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryFacts.tsxnew file mode 100644index 0000000000..8cf6e542ba--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryFacts.tsx@@ -0,0 +1,141 @@+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type { TFunction } from 'i18next';++import { Badge, Box, HStack, Skeleton, Text } from '@chakra-ui/react';+import { getModelBaseLabel } from '@features/models';+import { useTranslation } from 'react-i18next';++/**+ * The facts line a card and a list row share: base model, a readiness dot and one leading fact. The derivation is one+ * function so the two layouts can never disagree about what a workflow needs.+ */++/** What the facts line leads with once enrichment is ready. */+export type WorkflowLibraryReadiness = 'ready' | 'models' | 'nodePacks';++const READINESS_COLOR: Record<WorkflowLibraryReadiness, string> = {+ models: 'fg.warning',+ nodePacks: 'fg.error',+ ready: 'fg.success',+};++/**+ * Fact text in the readiness hue, pulled 30% toward the foreground: darker on light themes and lighter on dark ones,+ * so 10px text keeps 4.5:1 on the muted and emphasized fills of hovered and selected cards. The dot keeps the pure hue.+ */+const READINESS_TEXT_COLOR: Record<Exclude<WorkflowLibraryReadiness, 'ready'>, string> = {+ models: 'color-mix(in oklab, {colors.fg.warning} 70%, {colors.fg})',+ nodePacks: 'color-mix(in oklab, {colors.fg.error} 70%, {colors.fg})',+};++export interface WorkflowLibraryEntryFactsInput {+ entry: WorkflowLibraryEntry;+ /** The project already holds a copy of this library template. */+ isInProject: boolean;+ /** Models this workflow needs that are not installed; 0 when none. */+ missingCount: number;+ /** Node packs the workflow uses that this server lacks; null while node templates are unknown. */+ missingNodePackCount: number | null;+ /** When a project workflow last ran, already formatted; empty when it never ran or the caller does not say. */+ lastRun: string;+}++export interface WorkflowLibraryEntryFacts {+ isPending: boolean;+ primaryBase: string | null;+ /** Null until enrichment and node templates are known. */+ readiness: WorkflowLibraryReadiness | null;+ fact: string | null;+}++/** Missing node packs outrank missing models; a runnable workflow says it is in the project, ran, or its size. */+export const getWorkflowLibraryEntryFacts = (+ { entry, isInProject, lastRun, missingCount, missingNodePackCount }: WorkflowLibraryEntryFactsInput,+ t: TFunction+): WorkflowLibraryEntryFacts => {+ const ready = entry.enrichment.status === 'ready' ? entry.enrichment : null;+ const readiness: WorkflowLibraryReadiness | null =+ ready === null || missingNodePackCount === null+ ? null+ : missingNodePackCount > 0+ ? 'nodePacks'+ : missingCount > 0+ ? 'models'+ : 'ready';+ const fact =+ ready === null+ ? null+ : readiness === 'nodePacks'+ ? t('workflowLibrary.nodePacksMissing', { count: missingNodePackCount ?? 0 })+ : missingCount > 0+ ? t('workflowLibrary.modelsToInstall', { count: missingCount })+ : isInProject+ ? t('workflowLibrary.inProject')+ : lastRun+ ? t('workflowLibrary.ranWhen', { when: lastRun })+ : t('workflowLibrary.nodeCount', { count: ready.nodeCount });++ return {+ fact,+ isPending: entry.enrichment.status === 'pending',+ primaryBase: ready?.requirements.primaryBase ?? null,+ readiness,+ };+};++/**+ * On an accent fill (the selected list row) every readiness hue measures under 1.4:1, so the dot sits on a 2px ring+ * of the panel colour, against which each hue keeps at least 3:1 in every theme, and the fact text takes the row's.+ */+const ON_ACCENT_DOT_RING = '0 0 0 2px {colors.bg.panel}';++/** One 16px line, so async facts never change a card's or row's height. */+export const WorkflowLibraryFactsLine = ({+ facts,+ isOnAccent = false,+}: {+ facts: WorkflowLibraryEntryFacts;+ /** The line sits on the accent fill, which the readiness hues do not read on. */+ isOnAccent?: boolean;+}) => {+ const { t } = useTranslation();+ const { fact, isPending, primaryBase, readiness } = facts;++ return (+ <HStack gap="1.5" h="4" minW="0">+ {isPending ? (+ // Show placeholders only while enriching; unreadable workflows leave facts absent.+ <Skeleton data-enrichment-placeholder h="3" rounded="sm" w="14" />+ ) : null}+ {primaryBase ? (+ <Badge flexShrink={0} variant="subtle">+ {getModelBaseLabel(primaryBase)}+ </Badge>+ ) : null}+ {readiness ? (+ <Box+ bg={READINESS_COLOR[readiness]}+ boxShadow={isOnAccent ? ON_ACCENT_DOT_RING : undefined}+ boxSize="1.5"+ data-workflow-readiness={readiness}+ flexShrink={0}+ rounded="full"+ >+ {readiness === 'ready' ? <Text srOnly>{t('workflowLibrary.readyToRun')}</Text> : null}+ </Box>+ ) : null}+ {fact ? (+ <Text+ color={+ isOnAccent ? 'inherit' : readiness && readiness !== 'ready' ? READINESS_TEXT_COLOR[readiness] : 'fg.muted'+ }+ fontSize="xs"+ minW="0"+ truncate+ >+ {fact}+ </Text>+ ) : null}+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsxindex f1c4e0f5d6..8dcdd9884a 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx@@ -1,51 +1,138 @@import type { WorkflowLibraryBrowseSnapshot, WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';-import { Box, Text } from '@chakra-ui/react';+import { Box, type SystemStyleObject, Text } from '@chakra-ui/react';import {getWorkflowLibraryBrowseSnapshot,loadWorkflowLibraryRange,rememberWorkflowLibraryScroll,- setWorkflowLibraryVisibleDemand,} from '@features/workflow/data/libraryBrowseStore';+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';import { useMountEffect } from '@platform/react/useMountEffect';import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';import { Scrollable } from '@platform/ui';import { Button } from '@platform/ui/Button';-import { type ComponentProps, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';-import { defaultRangeExtractor, useVirtualizer } from 'react-hook-tanstack-virtual';+import {+ type ComponentProps,+ type ReactNode,+ use,+ useCallback,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { defaultRangeExtractor, useVirtualizer, type VirtualItem, type Virtualizer } from 'react-hook-tanstack-virtual';import { useTranslation } from 'react-i18next';+import { WORKFLOW_LIBRARY_FLOW_LAYOUT } from './WorkflowDetailSheet';import {WorkflowLibraryCard,getWorkflowLibraryCardId,getWorkflowLibraryCardMenuId,+ type WorkflowCardContextMenuHandler,type WorkflowCardMenuAnchor,- type WorkflowLibraryCardProps,} from './WorkflowLibraryCard';+import {+ dedupeWorkflowLibraryEntries,+ getWorkflowLibraryDemandIds,+ useFrozenWhileHidden,+ useLinkedLibraryTemplates,+ WorkflowLibraryDemand,+} from './workflowLibraryCollection';+import {+ getWorkflowLibraryCardWidth,+ getWorkflowLibraryGridBounds,+ getWorkflowLibraryGridColumns,+ GRID_GAP_PX,+} from './workflowLibraryGridLayout';+import { getMissingNodePacks } from './WorkflowRequirementsList';+import { WORKFLOW_THUMBNAIL_ASPECT_RATIO, WorkflowLibraryCardSizeContext } from './workflowThumbnail';++/**+ * What the grid renders from: the mounted rows and the visible range, never the scroll offset, so scrolling within a+ * row re-renders nothing and only crossing a row boundary or a measurement does. Scroll start and stop count only+ * while a restoration waits for scrolling to settle. The methods, the element cache and the instance are stable+ * across snapshots.+ */+type GridVirtualizer = Virtualizer<HTMLDivElement, Element>;++const selectVirtualizerView = (+ watchesScrollEnd: boolean,+ instance: GridVirtualizer,+ snapshot: Pick<+ GridVirtualizer,+ | 'cancelScroll'+ | 'elementsCache'+ | 'isScrolling'+ | 'measure'+ | 'measureElement'+ | 'range'+ | 'scrollRect'+ | 'scrollToIndex'+ | 'scrollToOffset'+ > & { totalSize: number; virtualItems: VirtualItem[] }+) => ({+ cancelScroll: snapshot.cancelScroll,+ elementsCache: snapshot.elementsCache,+ instance,+ // Not read by the grid: a change re-renders it, so the restoration effect sees the scroll it started settle.+ isScrolling: watchesScrollEnd && snapshot.isScrolling,+ measure: snapshot.measure,+ measureElement: snapshot.measureElement,+ rangeEnd: snapshot.range?.endIndex ?? 0,+ rangeStart: snapshot.range?.startIndex ?? 0,+ scrollToIndex: snapshot.scrollToIndex,+ scrollToOffset: snapshot.scrollToOffset,+ totalSize: snapshot.totalSize,+ viewportHeight: snapshot.scrollRect?.height ?? 0,+ virtualItems: snapshot.virtualItems,+});-/** Two rows before and after the viewport, plus one focused/menu row. */-const OVERSCAN_ROWS = 2;-// A partial row and four overscan rows still fit 60 metadata positions at three columns.-const MAX_VISIBLE_ROWS = 15;+/**+ * A card's height below its image at the default 16px root size: borders, body padding, title and facts rows, and+ * the row's bottom gap come to 78px; the 3:2 image is 2px narrower than the card. Rounding down keeps the estimate+ * a lower bound, so a viewport capped at N estimated rows never spans more than N + 1 real ones.+ */+const ROW_CHROME_PX = 76;const NO_MISSING_COUNTS: ReadonlyMap<string, number> = new Map();// A flow layout still needs a finite virtual viewport, independent of the collection's total row height.const GRID_CSS = {- '@container workflow-library-content ((width < 32rem) and (height < 32rem)) or (height < 20rem)': {+ [WORKFLOW_LIBRARY_FLOW_LAYOUT]: {flex: '1 1 16rem',height: '16rem',},} as const;+/**+ * The scroll area writes its overflow offsets as inherited custom properties on the viewport at every scroll event,+ * which restyles every element below it. The grid uses none of them; pinning them on the content wrapper stops that+ * restyle at the wrapper, which dominated scrolling (about half the main thread) before.+ */+const CONTENT_PROPS = {+ css: {+ '--scroll-area-overflow-x-start': '0px',+ '--scroll-area-overflow-x-end': '0px',+ '--scroll-area-overflow-y-start': '0px',+ '--scroll-area-overflow-y-end': '0px',+ },+};export interface WorkflowLibraryGridProps {/** The project's active workflow, marked on its card in the This-project view. */activeWorkflowId?: string | null;entries: readonly WorkflowLibraryEntry[];+ /** What an empty result says; defaults to no matches for the filters. */+ emptyMessage?: string;window?: {startIndex: number;total: number;filter: WorkflowLibraryBrowseSnapshot['filter'];};error: string | null;+ /**+ * Under the preview stage: the grid keeps its layout and scroll position, and its demand stays on the positions it+ * showed, so a preview stepping elsewhere in the results does not pull the window back.+ */+ isHidden?: boolean;/** What has the actions menu open, so that tile's control can name it. */openMenuAnchor?: WorkflowCardMenuAnchor | null;/** Project workflows reuse the grid but have no library visibility state. */@@ -55,36 +142,26 @@ export interface WorkflowLibraryGridProps {selectedWorkflowId: string | null;removedWorkflowId?: string | null;status: WorkflowLibraryBrowseSnapshot['status'];- onContextMenu: WorkflowLibraryCardProps['onContextMenu'];+ onContextMenu: WorkflowCardContextMenuHandler;onOpen: (workflowId: string) => void;+ /** Offers a Preview quick action on each card; absent hides it. */+ onPreview?: (workflowId: string) => void;onSelect: (workflowId: string) => void;}-/** Keep duplicate server identities from corrupting card reconciliation. */-const dedupeByWorkflowId = (entries: readonly WorkflowLibraryEntry[]): WorkflowLibraryEntry[] => {- const seen = new Set<string>();- const unique: WorkflowLibraryEntry[] = [];-- for (const entry of entries) {- if (!seen.has(entry.item.workflow_id)) {- seen.add(entry.item.workflow_id);- unique.push(entry);- }- }-- return unique;-};-export const WorkflowLibraryGrid = ({activeWorkflowId = null,+ emptyMessage,entries,window: browseWindow,error,+ isHidden = false,missingCounts = NO_MISSING_COUNTS,openMenuAnchor = null,showVisibilityStatus = false,onContextMenu,onOpen,+ onPreview,onSelect,selectedWorkflowId,removedWorkflowId = null,@@ -92,6 +169,12 @@ export const WorkflowLibraryGrid = ({}: WorkflowLibraryGridProps) => {const { t } = useTranslation();const viewportRef = useRef<HTMLDivElement | null>(null);+ const cardSize = use(WorkflowLibraryCardSizeContext);+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const templates = templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null;+ // Only library cards mark templates the project holds; the project view is that collection.+ const isProjectCollection = browseWindow === undefined;+ const linkedTemplates = useLinkedLibraryTemplates(isProjectCollection);const pendingFocus = useRef<{index: number;@@ -136,17 +219,42 @@ export const WorkflowLibraryGrid = ({return browseWindow?.filter === snapshot.filter ? (snapshot.scrollAnchor ?? null) : null;});const restorePending = useRef(restoreAnchor !== null);+ const remeasurePending = useRef(false);+ // The ref is read when the virtualizer publishes a snapshot; a restoration starting later shows at the next one.+ const selectView = useCallback(+ (snapshot: Parameters<typeof selectVirtualizerView>[2], instance: GridVirtualizer) =>+ selectVirtualizerView(restorePending.current, instance, snapshot),+ []+ );+ /** The card or menu button that last held focus in the grid, to hand focus to its remount. */+ const lastFocused = useRef<{ element: HTMLElement; id: string; menu: boolean } | null>(null);+ const retainFocus = useCallback(() => {+ const last = lastFocused.current;+ const active = document.activeElement;+ if (!last || last.element.isConnected || (active !== null && active !== document.body)) {+ return;+ }+ // A column change moves the card into another row, which mounts it afresh under the same id.+ const next = document.getElementById(+ last.menu ? getWorkflowLibraryCardMenuId(last.id) : getWorkflowLibraryCardId(last.id)+ );+ if (next) {+ lastFocused.current = { ...last, element: next };+ next.focus({ preventScroll: true });+ }+ }, []);const mounted = useRef(false);const positionedAt = useRef<{ row: number; width: number } | null>(null);const [focusCard, setFocusCard] = useState<{ entry: WorkflowLibraryEntry; index: number } | null>(null);if (focusCard?.entry.item.workflow_id === removedWorkflowId && focusCard !== null) {setFocusCard(null);}- const visibleEntries = useMemo(() => dedupeByWorkflowId(entries), [entries]);+ const visibleEntries = useMemo(() => dedupeWorkflowLibraryEntries(entries), [entries]);const startIndex = browseWindow?.startIndex ?? 0;const total = browseWindow?.total ?? visibleEntries.length;- const columns = Math.max(1, Math.min(3, Math.floor(width / 180)));- const rowHeight = (Math.max(1, (width - 12 * columns) / columns) * 9) / 16 + 82;+ const columns = getWorkflowLibraryGridColumns(width, cardSize);+ const { maxViewportRows, overscanRows } = getWorkflowLibraryGridBounds(columns);+ const rowHeight = getWorkflowLibraryCardWidth(width, columns) / WORKFLOW_THUMBNAIL_ASPECT_RATIO + ROW_CHROME_PX;const getScrollElement = useCallback(() => viewportRef.current, []);const rangeExtractor = useCallback((range: Parameters<typeof defaultRangeExtractor>[0]) => {@@ -168,37 +276,56 @@ export const WorkflowLibraryGrid = ({},[focusCard, openMenuAnchor, startIndex, visibleEntries, columns, total]);- const virtualizer = useVirtualizer({- count: Math.ceil(total / columns),- estimateSize: () => rowHeight,- getScrollElement,- enabled: width > 0,- onChange: (instance) => {- if (!mounted.current || !browseWindow || !width || restorePending.current || !isAccountScopeCurrent(owner)) {- return;- }- const offset = instance.scrollOffset ?? 0;- const row = instance.getVirtualItems().find((item) => item.end > offset);- if (row && row.size > 0) {- rememberWorkflowLibraryScroll(browseWindow.filter, {- index: row.index * columns,- fraction: Math.max(0, Math.min(1, (offset - row.start) / row.size)),- });- }+ const virtualizer = useVirtualizer(+ {+ count: Math.ceil(total / columns),+ estimateSize: () => rowHeight,+ getScrollElement,+ enabled: width > 0,+ onChange: (instance) => {+ if (remeasurePending.current && !instance.isScrolling) {+ remeasurePending.current = false;+ for (const element of instance.elementsCache.values()) {+ instance.measureElement(element);+ }+ }+ if (!mounted.current || !browseWindow || !width || restorePending.current || !isAccountScopeCurrent(owner)) {+ return;+ }+ const offset = instance.scrollOffset ?? 0;+ const row = instance.getVirtualItems().find((item) => item.end > offset);+ if (row && row.size > 0) {+ rememberWorkflowLibraryScroll(browseWindow.filter, {+ index: row.index * columns,+ fraction: Math.max(0, Math.min(1, (offset - row.start) / row.size)),+ });+ }+ },+ overscan: overscanRows,+ rangeExtractor,+ useFlushSync: false,},- overscan: OVERSCAN_ROWS,- rangeExtractor,- useFlushSync: false,- });- const { measure, measureElement, elementsCache, isScrolling, virtualItems, totalSize, cancelScroll } = virtualizer;+ selectView+ );+ const { measure, measureElement, elementsCache, instance, virtualItems, totalSize, cancelScroll } = virtualizer;useMountEffect(() => {const viewport = viewportRef.current;if (!viewport) {return;}mounted.current = true;- const observer = new MutationObserver(attemptFocus);+ const observer = new MutationObserver(() => {+ retainFocus();+ attemptFocus();+ });observer.observe(viewport, { childList: true, subtree: true });+ // Focus leaving the grid for another element ends retention; a removed card's focus falls to the body instead.+ const releaseFocus = (event: FocusEvent) => {+ if (!(event.target instanceof Node) || !viewport.contains(event.target)) {+ lastFocused.current = null;+ }+ };+ document.addEventListener('focusin', releaseFocus);const cancel = () => {pendingFocus.current = null;if (restorePending.current) {@@ -224,21 +351,30 @@ export const WorkflowLibraryGrid = ({document.removeEventListener('pointerdown', cancel, true);document.removeEventListener('wheel', cancel, true);document.removeEventListener('focusin', attemptFocus);+ document.removeEventListener('focusin', releaseFocus);};});useLayoutEffect(() => {measure();}, [measure, rowHeight]);useLayoutEffect(() => {- // Clearing sizes does not retrigger ResizeObserver for unchanged mounted rows.- // measureElement defers reads during scrolling, so retry once scrolling settles.- if (isScrolling) {+ // Clearing sizes does not retrigger ResizeObserver for unchanged mounted rows. measureElement defers reads during+ // scrolling, so the virtualizer's change callback retries once scrolling settles.+ if (instance.isScrolling) {+ remeasurePending.current = true;return;}+ remeasurePending.current = false;for (const element of elementsCache.values()) {measureElement(element);}- }, [measureElement, elementsCache, rowHeight, isScrolling]);+ }, [measureElement, elementsCache, instance, rowHeight]);+ // Measure the mounted width before the first paint rather than waiting for the observer's first report: Chromium can+ // hold back a report that misses its frame's resize-observer depth limit until some later rendering update, and+ // until the width is known the grid demands nothing (a returning grid would sit on placeholders).+ useLayoutEffect(() => {+ setWidth(viewportRef.current?.clientWidth ?? 0);+ }, []);useMountEffect(() => {const viewport = viewportRef.current;if (!viewport) {@@ -316,39 +452,71 @@ export const WorkflowLibraryGrid = ({visibleEntries,]);// Do not let the mount's unknown width/top range replace the cached window needed for restoration.- const firstVisibleRow = restoreRow ?? virtualizer.range?.startIndex ?? 0;+ const firstVisibleRow = restoreRow ?? virtualizer.rangeStart;const lastVisibleRow =- restoreRow === null- ? (virtualizer.range?.endIndex ?? 0)- : restoreRow + Math.ceil((virtualizer.scrollRect?.height ?? 0) / rowHeight);+ restoreRow === null ? virtualizer.rangeEnd : restoreRow + Math.ceil(virtualizer.viewportHeight / rowHeight);const visibleFirst = firstVisibleRow * columns;const visibleLast = Math.min(total - 1, (lastVisibleRow + 1) * columns - 1);- const first = Math.max(0, firstVisibleRow - OVERSCAN_ROWS) * columns;- const last = Math.min(total - 1, (lastVisibleRow + OVERSCAN_ROWS + 1) * columns - 1);- const ids = useMemo(() => {- const visible: string[] = [];- const overscan: string[] = [];- for (const [index, entry] of visibleEntries.entries()) {- const position = startIndex + index;- if (position >= first && position <= last) {- // The owner's bounded enrichment slots must reach every visible card before either overscan edge.- const demand = position >= visibleFirst && position <= visibleLast ? visible : overscan;- demand.push(entry.item.workflow_id);- }- }- return visible.concat(overscan);- }, [visibleEntries, startIndex, first, last, visibleFirst, visibleLast]);+ const first = Math.max(0, firstVisibleRow - overscanRows) * columns;+ const last = Math.min(total - 1, (lastVisibleRow + overscanRows + 1) * columns - 1);+ const ids = useMemo(+ () => getWorkflowLibraryDemandIds(visibleEntries, startIndex, { first, last, visibleFirst, visibleLast }),+ [visibleEntries, startIndex, first, last, visibleFirst, visibleLast]+ );+ const demandKey = useFrozenWhileHidden(`${first}:${last}:${ids.join(',')}`, isHidden);const hasEntries = visibleEntries.length > 0;// Idle precedes the first open-time load; render loading rather than an empty result.const isPending = status === 'idle' || status === 'loading';+ const handleRetry = useCallback(() => {+ void loadWorkflowLibraryRange(first, last, true);+ }, [first, last]);+ const ensureCardPosition = useCallback(+ (id: string, action: () => void) => {+ const resident = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);+ const index = resident >= 0 ? startIndex + resident : focusCard?.index;+ if (browseWindow && index !== undefined && resident < 0) {+ void loadWorkflowLibraryRange(index, index).then((ready) => {+ if (ready) {+ action();+ }+ });+ } else {+ action();+ }+ },+ [browseWindow, visibleEntries, startIndex, focusCard]+ );+ const handleSelect = useCallback(+ (id: string) => ensureCardPosition(id, () => onSelect(id)),+ [ensureCardPosition, onSelect]+ );+ const handleOpen = useCallback(+ (id: string) => ensureCardPosition(id, () => onOpen(id)),+ [ensureCardPosition, onOpen]+ );+ const handlePreview = useCallback(+ (id: string) => ensureCardPosition(id, () => onPreview?.(id)),+ [ensureCardPosition, onPreview]+ );+ const handleContextMenu = useCallback(+ (id: string, anchor: WorkflowCardMenuAnchor) => {+ const index = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);+ const entry = visibleEntries[index];+ if (entry) {+ setFocusCard({ entry: { ...entry, enrichment: { status: 'pending' } }, index: startIndex + index });+ }+ ensureCardPosition(id, () => onContextMenu(id, anchor));+ },+ [visibleEntries, startIndex, ensureCardPosition, onContextMenu]+ );const viewportProps = useMemo<ComponentProps<typeof Scrollable>['viewportProps']>(() => ({onKeyDown: (event) => {+ const target = event.target as HTMLElement;if (event.key !== 'Tab' || event.altKey || event.ctrlKey || event.metaKey) {return;}- const target = event.target as HTMLElement;const isCard = target.hasAttribute('data-workflow-card');const isMenu = target.hasAttribute('data-workflow-card-menu');if ((!isCard || !event.shiftKey) && (!isMenu || event.shiftKey)) {@@ -392,11 +560,70 @@ export const WorkflowLibraryGrid = ({});}},+ // Cards carry no handlers (they stay memoised across window and enrichment updates); their events land here.+ onClick: (event) => {+ const target = event.target as Element;+ const action = target.closest<HTMLElement>('[data-card-action]');+ const id = target.closest<HTMLElement>('[data-workflow-card-root]')?.dataset.workflowCardRoot;+ if (!id) {+ return;+ }+ if (action?.dataset.cardAction === 'open') {+ handleOpen(id);+ } else if (action?.dataset.cardAction === 'preview') {+ handleSelect(id);+ handlePreview(id);+ } else if (target.closest('[data-workflow-card-menu]')) {+ handleContextMenu(id, { kind: 'trigger', triggerId: getWorkflowLibraryCardMenuId(id), workflowId: id });+ } else if (target.closest('[data-workflow-card]')) {+ handleSelect(id);+ }+ },+ onDoubleClick: (event) => {+ const id = (event.target as Element).closest<HTMLElement>('[data-workflow-card]')?.dataset.workflowCard;+ if (id) {+ handleOpen(id);+ }+ },+ onContextMenu: (event) => {+ const target = event.target as Element;+ if (!target.closest('[data-workflow-card],[data-workflow-card-actions]')) {+ return;+ }+ const id = target.closest<HTMLElement>('[data-workflow-card-root]')?.dataset.workflowCardRoot;+ if (!id) {+ return;+ }+ event.preventDefault();+ // A keyboard-raised menu (Shift+F10, the Menu key) carries no pointer position; anchor it inside the card+ // instead of at the viewport corner.+ const rect = document.getElementById(getWorkflowLibraryCardId(id))?.getBoundingClientRect();+ handleContextMenu(+ id,+ event.clientX === 0 && event.clientY === 0 && rect+ ? { kind: 'point', workflowId: id, x: rect.left + 16, y: rect.top + 16 }+ : { kind: 'point', workflowId: id, x: event.clientX, y: event.clientY }+ );+ },+ // Pointer-only quick actions never take focus: it moves to their card, so a dialog they open returns there.+ onMouseDown: (event) => {+ const target = event.target as Element;+ const id = target.closest('[data-card-action]')+ ? target.closest<HTMLElement>('[data-workflow-card-root]')?.dataset.workflowCardRoot+ : undefined;+ if (id) {+ event.preventDefault();+ document.getElementById(getWorkflowLibraryCardId(id))?.focus({ preventScroll: true });+ }+ },onFocusCapture: (event) => {const card = (event.target as HTMLElement).closest<HTMLElement>('[data-workflow-card],[data-workflow-card-menu]');const id = card?.dataset.workflowCard ?? card?.dataset.workflowCardMenu;+ if (card && id) {+ lastFocused.current = { element: card, id, menu: card.hasAttribute('data-workflow-card-menu') };+ }const index = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);const entry = visibleEntries[index];if (entry) {@@ -404,60 +631,35 @@ export const WorkflowLibraryGrid = ({}},}),- [browseWindow, virtualizer, visibleEntries, startIndex, focusCard, total, columns, attemptFocus]- );- const handleRetry = useCallback(() => {- void loadWorkflowLibraryRange(first, last, true);- }, [first, last]);- const ensureCardPosition = useCallback(- (id: string, action: () => void) => {- const resident = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);- const index = resident >= 0 ? startIndex + resident : focusCard?.index;- if (browseWindow && index !== undefined && resident < 0) {- void loadWorkflowLibraryRange(index, index).then((ready) => {- if (ready) {- action();- }- });- } else {- action();- }- },- [browseWindow, visibleEntries, startIndex, focusCard]- );- const handleSelect = useCallback(- (id: string) => ensureCardPosition(id, () => onSelect(id)),- [ensureCardPosition, onSelect]- );- const handleOpen = useCallback(- (id: string) => ensureCardPosition(id, () => onOpen(id)),- [ensureCardPosition, onOpen]- );- const handleContextMenu = useCallback(- (id: string, anchor: WorkflowCardMenuAnchor) => {- const index = visibleEntries.findIndex((entry) => entry.item.workflow_id === id);- const entry = visibleEntries[index];- if (entry) {- setFocusCard({ entry: { ...entry, enrichment: { status: 'pending' } }, index: startIndex + index });- }- ensureCardPosition(id, () => onContextMenu(id, anchor));- },- [visibleEntries, startIndex, ensureCardPosition, onContextMenu]+ [+ browseWindow,+ virtualizer,+ visibleEntries,+ startIndex,+ focusCard,+ total,+ columns,+ attemptFocus,+ handleContextMenu,+ handleOpen,+ handlePreview,+ handleSelect,+ ]);return (<Scrollablecss={GRID_CSS}+ data-workflow-library-collection=""flex="1"label={t('workflowLibrary.title')}minH="0"- maxH={browseWindow ? `${rowHeight * MAX_VISIBLE_ROWS}px` : undefined}+ maxH={browseWindow ? `${rowHeight * maxViewportRows}px` : undefined}minW="0"viewportRef={viewportRef}viewportProps={viewportProps}+ contentProps={CONTENT_PROPS}>- {browseWindow && width > 0 ? (- <GridDemand key={`${first}:${last}:${ids.join(',')}`} ids={ids} start={first} end={last} />- ) : null}+ {browseWindow && width > 0 ? <WorkflowLibraryDemand key={demandKey} ids={ids} start={first} end={last} /> : null}<Box display="flex" flexDirection="column" gap="3" minW="0" pr="2" w="full">{hasEntries && error ? (// Keep recovery within the viewport even for a failed distant range.@@ -483,19 +685,12 @@ export const WorkflowLibraryGrid = ({{hasEntries ? (<Box h={`${totalSize}px`} position="relative" minW="0" w="full">{virtualItems.map((row) => (- <Box+ <GridRowkey={row.key}- data-index={row.index}- ref={virtualizer.measureElement}- display="grid"- gap="3"- gridTemplateColumns={`repeat(${columns}, minmax(0, 1fr))`}- position="absolute"- top="0"- left="0"- w="full"- pb="3"- transform={`translateY(${row.start}px)`}+ columns={columns}+ index={row.index}+ measureRef={virtualizer.measureElement}+ start={row.start}>{Array.from({ length: columns }, (_, column) => {const index = row.index * columns + column;@@ -505,13 +700,14 @@ export const WorkflowLibraryGrid = ({const entry =visibleEntries[index - startIndex] ?? (focusCard?.index === index ? focusCard.entry : undefined);if (!entry) {- return <Box key={index} h={`${rowHeight - 12}px`} aria-busy="true" bg="bg.subtle" rounded="lg" />;+ return <GridPlaceholder key={index} height={rowHeight - GRID_GAP_PX} />;}return (<WorkflowLibraryCardkey={entry.item.workflow_id}entry={entry}isActive={entry.item.workflow_id === activeWorkflowId}+ isInProject={linkedTemplates.has(entry.item.workflow_id)}isSelected={entry.item.workflow_id === selectedWorkflowId}menuOpenedBy={openMenuAnchor?.workflowId === entry.item.workflow_id@@ -521,14 +717,18 @@ export const WorkflowLibraryGrid = ({: null}missingCount={missingCounts.get(entry.item.workflow_id) ?? 0}+ missingNodePackCount={+ templates && entry.enrichment.status === 'ready'+ ? getMissingNodePacks(entry.enrichment, templates).length+ : null+ }+ showLastRun={isProjectCollection}showVisibilityStatus={showVisibilityStatus}- onContextMenu={handleContextMenu}- onOpen={handleOpen}- onSelect={handleSelect}+ canPreview={onPreview !== undefined}/>);})}- </Box>+ </GridRow>))}</Box>) : null}@@ -539,7 +739,7 @@ export const WorkflowLibraryGrid = ({) : null}{!hasEntries && !isPending ? (<Text color="fg.subtle" fontSize="md" py="6" textAlign="center">- {error ?? t('workflowLibrary.empty')}+ {error ?? emptyMessage ?? t('workflowLibrary.empty')}</Text>) : null}</Box>@@ -547,20 +747,48 @@ export const WorkflowLibraryGrid = ({);};-// Mount leases keep external-store writes out of render and release detail demand when the viewport leaves.-let demandLease = 0;-const GridDemand = ({ ids, start, end }: { ids: readonly string[]; start: number; end: number }) => {- useMountEffect(() => {- const lease = ++demandLease;- setWorkflowLibraryVisibleDemand(ids);- void loadWorkflowLibraryRange(start, end);- return () => {- queueMicrotask(() => {- if (lease === demandLease) {- setWorkflowLibraryVisibleDemand([]);- }- });- };- });- return null;+const GRID_ROW_CSS: SystemStyleObject = {+ display: 'grid',+ gap: '3',+ left: '0',+ pb: '3',+ position: 'absolute',+ top: '0',+ w: 'full',+};++/**+ * A virtual row. Its offset and column count go in the style attribute: as style props, every new offset would add a+ * CSS rule while scrolling, and each insertion restyles the whole document.+ */+const GridRow = ({+ children,+ columns,+ index,+ measureRef,+ start,+}: {+ children: ReactNode;+ columns: number;+ index: number;+ measureRef: (element: HTMLElement | null) => void;+ start: number;+}) => {+ const style = useMemo(+ () => ({ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`, transform: `translateY(${start}px)` }),+ [columns, start]+ );++ return (+ <Box ref={measureRef} css={GRID_ROW_CSS} data-index={index} style={style}>+ {children}+ </Box>+ );+};++/** A position whose metadata is not resident yet, as tall as a card. */+const GridPlaceholder = ({ height }: { height: number }) => {+ const style = useMemo(() => ({ height: `${height}px` }), [height]);++ return <Box aria-busy="true" bg="bg.subtle" rounded="lg" style={style} />;};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryList.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryList.browser.test.tsxnew file mode 100644index 0000000000..d144384d30--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryList.browser.test.tsx@@ -0,0 +1,264 @@+/* eslint-disable react-perf/jsx-no-new-object-as-prop */+import type * as BrowseStoreModule from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';++import { ChakraProvider } from '@chakra-ui/react';+import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';+import { createProjectGraph } from '@features/workflow/utility';+import { system } from '@theme/system';+import { act, type ComponentProps } 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 { WorkflowLibraryList } from './WorkflowLibraryList';++const store = vi.hoisted(() => ({+ loadWorkflowLibraryRange: vi.fn((_start: number, _end: number, _force?: boolean) => Promise.resolve(true)),+ refreshWorkflowLibraryBrowse: vi.fn(() => Promise.resolve()),+ rememberWorkflowLibraryScroll: vi.fn(),+ setWorkflowLibraryVisibleDemand: vi.fn(),+}));++vi.mock('@features/workflow/data/libraryBrowseStore', async (original) => ({+ ...(await original<typeof BrowseStoreModule>()),+ loadWorkflowLibraryRange: store.loadWorkflowLibraryRange,+ refreshWorkflowLibraryBrowse: store.refreshWorkflowLibraryBrowse,+ rememberWorkflowLibraryScroll: store.rememberWorkflowLibraryScroll,+ setWorkflowLibraryVisibleDemand: store.setWorkflowLibraryVisibleDemand,+}));+vi.mock('@features/workflow/react', async (original) => ({+ ...(await original<Record<string, unknown>>()),+ useInvocationTemplatesSnapshot: () => ({ error: null, status: 'loaded', templates: {} }),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const graph = createProjectGraph('list-fixture');+const ADAPTER = {+ project: {+ getSnapshot: () => ({ activeWorkflowId: graph.id, id: 'project', workflows: [{ document: graph }] }),+ subscribe: () => () => {},+ },+} as unknown as WorkflowUiAdapter;+const FILTER = { direction: 'desc', place: 'user', search: '', sort: 'updated', tags: [] } as const;++const entry = (index: number): WorkflowLibraryEntry => ({+ enrichment: { document: graph, nodeCount: 3, requirements: { primaryBase: null, requirements: [] }, status: 'ready' },+ item: { category: 'user', description: '', name: `Workflow ${index}`, revision: 1, workflow_id: `wf-${index}` },+ tags: [],+});+const page = (start: number, count = 20) => Array.from({ length: count }, (_, offset) => entry(start + offset));++let host: HTMLDivElement;+let root: Root;++beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'display:flex;flex-direction:column;height:400px;width:720px;';+ document.body.append(host);+ root = createRoot(host);+ store.loadWorkflowLibraryRange.mockClear();+ store.refreshWorkflowLibraryBrowse.mockClear();+ store.rememberWorkflowLibraryScroll.mockClear();+ store.setWorkflowLibraryVisibleDemand.mockClear();+});++afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+});++type ListProps = ComponentProps<typeof WorkflowLibraryList>;++const render = async (props: Partial<ListProps>) => {+ const merged: ListProps = {+ entries: page(0),+ error: null,+ onContextMenu: vi.fn(),+ onOpen: vi.fn(),+ onPreview: vi.fn(),+ onSelect: vi.fn(),+ selectedWorkflowId: null,+ status: 'loaded',+ window: { filter: FILTER, startIndex: 0, total: 100 },+ ...props,+ };+ await act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={ADAPTER}>+ <WorkflowLibraryList {...merged} />+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );+};++const primaryOf = (workflowId: string) => document.getElementById(`workflow-library-card-${workflowId}`);+const rowAt = (index: number) => host.querySelector<HTMLElement>(`[data-list-row="position:${index}"]`);++describe('WorkflowLibraryList', () => {+ it('keeps the selected row with its name while its page is evicted, until the workflow is removed', async () => {+ await render({ selectedWorkflowId: 'wf-1' });+ expect(primaryOf('wf-1')?.getAttribute('aria-current')).toBe('true');++ // The window moved on: position 1 is no longer resident, but the selection keeps its row.+ await render({+ entries: page(60),+ selectedWorkflowId: 'wf-1',+ window: { filter: FILTER, startIndex: 60, total: 100 },+ });+ expect(primaryOf('wf-1')?.textContent).toContain('Workflow 1');+ expect(rowAt(1)?.querySelector('[data-list-primary]')).toBe(primaryOf('wf-1'));+ expect(primaryOf('wf-1')?.getAttribute('aria-current')).toBe('true');++ // Removed (deleted from the rail): the kept copy goes, and the position is a placeholder again.+ await render({+ entries: page(60),+ removedWorkflowId: 'wf-1',+ selectedWorkflowId: null,+ window: { filter: FILTER, startIndex: 60, total: 100 },+ });+ expect(primaryOf('wf-1')).toBeNull();+ expect(rowAt(1)?.querySelector('[data-workflow-list-placeholder]')).not.toBeNull();+ });++ it('names placeholder rows as loading and keeps one tab stop when the selection is not resident', async () => {+ await render({+ entries: page(60),+ selectedWorkflowId: 'wf-1',+ window: { filter: FILTER, startIndex: 60, total: 100 },+ });++ const placeholder = rowAt(0)!;+ expect(placeholder.querySelector('[data-workflow-list-placeholder]')).not.toBeNull();+ expect(placeholder.querySelector('[data-list-primary]')?.getAttribute('aria-label')).toBe(+ 'workflowLibrary.loading'+ );+ // The selection was made outside the window: the List's tab stop falls back to its first row, a real button.+ const stops = host.querySelectorAll('[data-workflow-library-list] [tabindex="0"]');+ expect(stops).toHaveLength(1);+ expect(stops[0]).toBe(placeholder.querySelector('[data-list-primary]'));+ });++ it('keeps the browser’s own menu off placeholder rows without raising the actions menu', async () => {+ const onContextMenu = vi.fn();+ await render({ entries: page(60), onContextMenu, window: { filter: FILTER, startIndex: 60, total: 100 } });+ const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 40, clientY: 20 });++ await act(() => rowAt(0)!.querySelector('[data-list-primary]')!.dispatchEvent(event));+ expect(event.defaultPrevented).toBe(true);+ expect(onContextMenu).not.toHaveBeenCalled();+ });++ it('keeps every row’s width when the pointer reveals Open and Preview', async () => {+ await render({ selectedWorkflowId: 'wf-0' });+ const button = primaryOf('wf-1')!;+ const width = button.getBoundingClientRect().width;+ const open = rowAt(1)!.querySelector<HTMLElement>('[data-row-action="open"]')!;+ expect(getComputedStyle(open).visibility).toBe('hidden');++ await userEvent.hover(button);+ expect(getComputedStyle(open).visibility).toBe('visible');+ expect(button.getBoundingClientRect().width).toBe(width);+ // Every row's controls take the same room, so the date column stays aligned.+ expect(primaryOf('wf-2')!.getBoundingClientRect().width).toBe(width);++ await userEvent.unhover(button);+ expect(button.getBoundingClientRect().width).toBe(width);+ });++ it('names the last run once in the This-project view: as the date column when sorted by it, else in the facts', async () => {+ const ran = { ...entry(0), item: { ...entry(0).item, last_run_at: '2026-01-01T00:00:00Z' } };+ await render({ entries: [ran], trailingField: 'last_run_at', window: undefined });+ expect(primaryOf('wf-0')?.textContent).toContain('workflowLibrary.nodeCount');+ expect(primaryOf('wf-0')?.textContent).not.toContain('workflowLibrary.ranWhen');++ await render({ entries: [ran], trailingField: 'updated_at', window: undefined });+ expect(primaryOf('wf-0')?.textContent).toContain('workflowLibrary.ranWhen');+ });++ it('releases closed-list demand without overwriting its scroll anchor, and reacquires on reopen', async () => {+ await render({});+ await expect.poll(() => store.setWorkflowLibraryVisibleDemand.mock.calls.at(-1)?.[0].length).toBeGreaterThan(0);+ const viewport = host.querySelector<HTMLElement>('[data-list-viewport]')!;+ await act(() => {+ viewport.scrollTop = 270;+ viewport.dispatchEvent(new Event('scroll'));+ });+ await expect.poll(() => store.rememberWorkflowLibraryScroll.mock.calls.length).toBeGreaterThan(0);+ const anchor = store.rememberWorkflowLibraryScroll.mock.calls.at(-1);++ // Closing retains the collection while the dialog's hidden layout collapses its viewport.+ await render({ isActive: false });+ host.style.display = 'none';+ await expect.poll(() => store.setWorkflowLibraryVisibleDemand.mock.calls.at(-1)?.[0]).toEqual([]);+ store.loadWorkflowLibraryRange.mockClear();+ await act(() => {+ viewport.scrollTop = 0;+ viewport.dispatchEvent(new Event('scroll'));+ });+ expect(store.rememberWorkflowLibraryScroll.mock.calls.at(-1)).toEqual(anchor);+ expect(store.loadWorkflowLibraryRange).not.toHaveBeenCalled();++ host.style.display = 'flex';+ await render({ isActive: true });+ await expect.poll(() => store.setWorkflowLibraryVisibleDemand.mock.calls.at(-1)?.[0].length).toBeGreaterThan(0);+ });++ it('persists the final fractional scroll offset after its viewport detaches', async () => {+ await render({});+ const viewport = host.querySelector<HTMLElement>('[data-list-viewport]')!;+ await act(() => {+ viewport.scrollTop = 281;+ viewport.dispatchEvent(new Event('scroll'));+ });+ store.rememberWorkflowLibraryScroll.mockClear();+ await act(() => root.render(null));+ expect(store.rememberWorkflowLibraryScroll).toHaveBeenLastCalledWith(FILTER, {+ fraction: 11 / 54,+ index: 5,+ });+ });++ it('retries a failed range in place, forcing a reread of the positions on screen', async () => {+ await render({ error: 'middle offline' });+ const retry = host.querySelector<HTMLElement>('[role="alert"] button')!;+ expect(host.querySelector('[role="alert"]')?.textContent).toContain('middle offline');++ await act(() => userEvent.click(retry));+ expect(store.loadWorkflowLibraryRange).toHaveBeenLastCalledWith(0, expect.any(Number), true);+ });++ it('reloads a failed first listing, busy until it settles', async () => {+ let settle!: () => void;+ store.refreshWorkflowLibraryBrowse.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ settle = resolve;+ })+ );+ await render({+ entries: [],+ error: 'offline',+ status: 'error',+ window: { filter: FILTER, startIndex: 0, total: 0 },+ });+ const retry = () => host.querySelector<HTMLButtonElement>('[role="alert"] button')!;+ expect(host.querySelector('[role="alert"]')?.textContent).toContain('offline');++ await act(() => userEvent.click(retry()));+ expect(store.refreshWorkflowLibraryBrowse).toHaveBeenCalledTimes(1);+ expect(store.loadWorkflowLibraryRange).not.toHaveBeenCalledWith(expect.anything(), expect.anything(), true);+ expect(retry().disabled).toBe(true);++ await act(async () => {+ settle();+ await Promise.resolve();+ });+ expect(retry().disabled).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryList.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryList.tsxnew file mode 100644index 0000000000..a1130a3937--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryList.tsx@@ -0,0 +1,686 @@+// ListItem takes its slots as JSX, and the List calls renderItem afresh on each render; rows are what is memoised.+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop */+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type { ListRange, ListRowProps } from '@platform/ui/list/List';+import type { ListContextMenuAnchor } from '@platform/ui/list/ListItem';+import type { ListRow } from '@platform/ui/list/listRows';+import type { FocusEvent, MouseEvent, UIEvent } from 'react';++import { Badge, Box, HStack, Icon, type SystemStyleObject, Text } from '@chakra-ui/react';+import {+ getWorkflowLibraryBrowseSnapshot,+ loadWorkflowLibraryRange,+ refreshWorkflowLibraryBrowse,+ rememberWorkflowLibraryScroll,+} from '@features/workflow/data/libraryBrowseStore';+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { Button, IconButton } from '@platform/ui/Button';+import { getListContentHeight, List } from '@platform/ui/list/List';+import { ListItem } from '@platform/ui/list/ListItem';+import { Tooltip } from '@platform/ui/Tooltip';+import { EllipsisIcon, FolderCheckIcon, WorkflowIcon } from 'lucide-react';+import { memo, useCallback, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { WorkflowLibraryGridProps } from './WorkflowLibraryGrid';++import { formatTimeSince, useDataTimeSnapshot } from './relativeTime';+import { WORKFLOW_LIBRARY_FLOW_LAYOUT, WorkflowSummaryThumbnail } from './WorkflowDetailSheet';+import {+ getWorkflowLibraryCardId,+ getWorkflowLibraryCardMenuContentId,+ getWorkflowLibraryCardMenuId,+ type WorkflowCardMenuAnchor,+} from './WorkflowLibraryCard';+import {+ dedupeWorkflowLibraryEntries,+ getWorkflowLibraryDemandIds,+ useFrozenWhileHidden,+ useLinkedLibraryTemplates,+ WorkflowLibraryDemand,+} from './workflowLibraryCollection';+import { getWorkflowLibraryEntryFacts, WorkflowLibraryFactsLine } from './WorkflowLibraryFacts';+import { getMissingNodePacks } from './WorkflowRequirementsList';++/**+ * The library's list layout: the platform List over the same collection the grid shows. A templates place lists every+ * server position, rows outside the resident window as placeholders, and loads the window around the List's visible+ * range through the shared demand module; the This-project view lists its own entries. Rows select on press, open on+ * double-click, and raise the same actions menu as a card from a right-click, Shift+F10 or their More button.+ */++/** The date column a row shows, chosen by the caller from the current order; null shows none. */+export type WorkflowLibraryListTrailingField = 'updated_at' | 'opened_at' | 'created_at' | 'last_run_at' | null;++export interface WorkflowLibraryListProps extends WorkflowLibraryGridProps {+ trailingField?: WorkflowLibraryListTrailingField;+ isActive?: boolean;+}++interface WorkflowLibraryListItem {+ /** Null while the position's metadata is not resident. */+ entry: WorkflowLibraryEntry | null;+ index: number;+}++const ROW_PITCH = getListContentHeight([{ kind: 'item' }], 'comfortable');+/** Rows loaded past each edge of the visible range; the List mounts as many, so they show data once scrolled to. */+const DEMAND_OVERSCAN_ROWS = 8;+const NO_MISSING_COUNTS: ReadonlyMap<string, number> = new Map();+/**+ * Row controls take the row's text colour and a border and hover tint mixed from it, so they read on the selected+ * row's accent fill as on the panel, without a fill of their own.+ */+const ROW_ACTION_CSS: SystemStyleObject = {+ borderColor: 'color-mix(in oklab, currentColor 35%, transparent)',+ color: 'inherit',+ _hover: { bg: 'color-mix(in oklab, currentColor 12%, transparent)' },+ _expanded: { bg: 'color-mix(in oklab, currentColor 12%, transparent)' },+};+/**+ * A position not yet resident: a thumbnail well and a line in a translucent tint of the text colour, static so fast+ * scrolls paint nothing, and never a solid block on any row surface.+ */+const PLACEHOLDER_THUMBNAIL_PROPS = {+ aspectRatio: 3 / 2,+ bg: 'fg/10',+ flexShrink: 0,+ rounded: 'sm',+ w: '3.375rem',+} as const;+const PLACEHOLDER_LINE_PROPS = { bg: 'fg/10', display: 'block', h: '2', rounded: 'full', w: '8rem' } as const;++/**+ * Open and Preview are always mounted and keep their width, so rows never reflow under the pointer; they show while the+ * pointer is over the row, focus is inside it or its menu is open. One that does not apply (Open on the active project+ * workflow, both on a placeholder) stays hidden. Without hover (touch) they never show and More, always visible,+ * carries the row's actions.+ */+const LIST_CSS: SystemStyleObject = {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ gap: '2',+ minH: '0',+ minW: '0',+ '& [data-row-quick-action]': { visibility: 'hidden' },+ '& [data-list-row]:focus-within [data-row-quick-action]:not([data-unavailable]), & [data-list-row][data-menu-open] [data-row-quick-action]:not([data-unavailable])':+ { visibility: 'visible' },+ '@media (hover: hover)': {+ '& [data-list-row]:hover [data-row-quick-action]:not([data-unavailable])': { visibility: 'visible' },+ },+ '@media (hover: none)': { '& [data-row-quick-action]': { display: 'none' } },+ // The scrolling column gives the list no height of its own; without one it would mount every row.+ [WORKFLOW_LIBRARY_FLOW_LAYOUT]: { flex: '1 1 16rem', height: '16rem' },+};++const toScrollAnchor = (offset: number) => {+ const index = Math.max(0, Math.floor(offset / ROW_PITCH));++ return { fraction: Math.max(0, Math.min(1, (offset - index * ROW_PITCH) / ROW_PITCH)), index };+};++const rowOf = (target: EventTarget) =>+ target instanceof Element ? target.closest<HTMLElement>('[data-list-row]') : null;++/** A row's server position: rows carry their 1-based set position, and the list has no section headers. */+const positionOf = (row: HTMLElement) => Number(row.getAttribute('aria-posinset')) - 1;++interface KeptRow {+ entry: WorkflowLibraryEntry;+ index: number;+}++const isKept = (kept: KeptRow | null, entry: WorkflowLibraryEntry, index: number): boolean =>+ kept?.index === index &&+ kept.entry.item.workflow_id === entry.item.workflow_id &&+ kept.entry.item.revision === entry.item.revision;++const keep = (entry: WorkflowLibraryEntry, index: number): KeptRow => ({+ entry: { ...entry, enrichment: { status: 'pending' } },+ index,+});++const entryAt = (rows: readonly ListRow<WorkflowLibraryListItem>[], index: number): WorkflowLibraryEntry | null => {+ const row = rows[index];++ return row?.kind === 'item' ? row.item.entry : null;+};++/** A windowed row's key: its server position, whether or not its metadata is resident. */+const positionKey = (index: number) => `position:${index}`;++export const WorkflowLibraryList = ({+ activeWorkflowId = null,+ emptyMessage,+ entries,+ error,+ isHidden = false,+ isActive = true,+ missingCounts = NO_MISSING_COUNTS,+ openMenuAnchor = null,+ removedWorkflowId = null,+ selectedWorkflowId,+ showVisibilityStatus = false,+ status,+ trailingField = 'updated_at',+ window: browseWindow,+ onContextMenu,+ onOpen,+ onPreview,+ onSelect,+}: WorkflowLibraryListProps) => {+ const { t } = useTranslation();+ const wrapperRef = useRef<HTMLDivElement>(null);+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const templates = templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null;+ const isWindowed = browseWindow !== undefined;+ // Only library rows mark templates the project holds; the project view is that collection.+ const linkedTemplates = useLinkedLibraryTemplates(!isWindowed);+ const filter = browseWindow?.filter;+ const visibleEntries = useMemo(() => dedupeWorkflowLibraryEntries(entries), [entries]);+ const startIndex = browseWindow?.startIndex ?? 0;+ const total = browseWindow?.total ?? visibleEntries.length;++ /**+ * Rows kept while their page is not resident, with their positions: the one last focused or given a menu, and the+ * selected one. Each stays rendered with its name, so focus and the List's tab stop never land on a placeholder.+ * The copies drop their parsed documents, like the grid's pinned card, so memory stays within the window.+ */+ const [focusedRow, setFocusedRow] = useState<KeptRow | null>(null);+ const [selectedRow, setSelectedRow] = useState<KeptRow | null>(null);+ if (focusedRow !== null && focusedRow.entry.item.workflow_id === removedWorkflowId) {+ setFocusedRow(null);+ }+ if (selectedRow !== null && selectedRow.entry.item.workflow_id === removedWorkflowId) {+ setSelectedRow(null);+ }+ // The selection can change from outside (the rail, the store's first-entry fallback): record it while resident.+ const selectedResidentIndex =+ isWindowed && selectedWorkflowId !== null+ ? visibleEntries.findIndex((entry) => entry.item.workflow_id === selectedWorkflowId)+ : -1;+ const selectedResident = visibleEntries[selectedResidentIndex];+ if (+ selectedResident &&+ selectedResident.item.workflow_id !== removedWorkflowId &&+ !isKept(selectedRow, selectedResident, startIndex + selectedResidentIndex)+ ) {+ setSelectedRow(keep(selectedResident, startIndex + selectedResidentIndex));+ }+ const retain = useCallback(+ (entry: WorkflowLibraryEntry, index: number) => {+ if (isWindowed) {+ setFocusedRow((current) => (isKept(current, entry, index) ? current : keep(entry, index)));+ }+ },+ [isWindowed]+ );++ const rows = useMemo((): ListRow<WorkflowLibraryListItem>[] => {+ if (!isWindowed) {+ return visibleEntries.map((entry, index) => ({+ item: { entry, index },+ key: entry.item.workflow_id,+ kind: 'item',+ }));+ }++ // A kept row whose workflow is resident elsewhere (the order changed) would duplicate its key.+ const residentIds = new Set(visibleEntries.map((entry) => entry.item.workflow_id));+ const keptRows = new Map<number, WorkflowLibraryEntry>();+ for (const kept of [selectedRow, focusedRow]) {+ if (kept !== null && kept.index < total && !residentIds.has(kept.entry.item.workflow_id)) {+ residentIds.add(kept.entry.item.workflow_id);+ keptRows.set(kept.index, kept.entry);+ }+ }++ // Keyed by position, so a placeholder and the entry that replaces it are one row: its button, and focus on it,+ // survive the page arriving.+ return Array.from({ length: total }, (_, index): ListRow<WorkflowLibraryListItem> => ({+ item: { entry: visibleEntries[index - startIndex] ?? keptRows.get(index) ?? null, index },+ key: positionKey(index),+ kind: 'item',+ }));+ }, [focusedRow, isWindowed, selectedRow, startIndex, total, visibleEntries]);++ // The selected row's key: the position showing the selected workflow, resident or kept. A kept position another+ // workflow now holds (the server reordered while the selection was out of the window) marks nothing, so the List's+ // tab stop falls back rather than highlight the wrong row.+ const selectedIndex =+ selectedResident !== undefined+ ? startIndex + selectedResidentIndex+ : selectedRow !== null && selectedRow.entry.item.workflow_id === selectedWorkflowId+ ? selectedRow.index+ : -1;+ const activeKey = !isWindowed+ ? selectedWorkflowId+ : selectedIndex >= 0 && entryAt(rows, selectedIndex)?.item.workflow_id === selectedWorkflowId+ ? positionKey(selectedIndex)+ : null;++ // The visible range the List reports; null until its viewport has measured.+ const [range, setRange] = useState<ListRange | null>(null);+ const rangeReports = useRef(0);+ const handleRangeChange = useCallback(+ (next: ListRange) => {+ const viewport = wrapperRef.current?.querySelector<HTMLElement>('[data-list-viewport]');+ if (!isActive || (viewport && viewport.clientHeight === 0)) {+ return;+ }+ setRange(next);+ rangeReports.current += 1;++ // The first report is the restored position itself; later ones keep the view's anchor current, so leaving for+ // another filter (which unmounts this list after the store has moved on) still returns here.+ if (filter && viewport && rangeReports.current > 1) {+ rememberWorkflowLibraryScroll(filter, toScrollAnchor(viewport.scrollTop));+ }+ },+ [filter, isActive]+ );+ // Passive unmount cleanup runs after DOM refs detach; retain only offsets observed while the list is visible.+ const visibleScrollOffset = useRef<number | null>(null);+ const handleScrollCapture = useCallback(+ (event: UIEvent<HTMLDivElement>) => {+ const viewport = event.target as HTMLElement;+ if (isActive && viewport.matches('[data-list-viewport]') && viewport.clientHeight > 0) {+ visibleScrollOffset.current = viewport.scrollTop;+ }+ },+ [isActive]+ );+ const persistScrollOffset = useCallback(() => {+ if (filter && visibleScrollOffset.current !== null) {+ rememberWorkflowLibraryScroll(filter, toScrollAnchor(visibleScrollOffset.current));+ }+ }, [filter]);+ // Shares the grid's anchor for this filter; its position converts to a row offset, close enough across layouts.+ const [initialScrollOffset] = useState(() => {+ const snapshot = getWorkflowLibraryBrowseSnapshot();+ const anchor = filter !== undefined && filter === snapshot.filter ? snapshot.scrollAnchor : null;++ return anchor ? (anchor.index + anchor.fraction) * ROW_PITCH : undefined;+ });++ const visibleFirst = range?.startIndex ?? 0;+ const visibleLast = Math.min(total - 1, range?.endIndex ?? 0);+ const first = Math.max(0, visibleFirst - DEMAND_OVERSCAN_ROWS);+ const last = Math.min(total - 1, visibleLast + DEMAND_OVERSCAN_ROWS);+ const ids = useMemo(+ () => getWorkflowLibraryDemandIds(visibleEntries, startIndex, { first, last, visibleFirst, visibleLast }),+ [visibleEntries, startIndex, first, last, visibleFirst, visibleLast]+ );+ const demandKey = useFrozenWhileHidden(`${first}:${last}:${ids.join(',')}`, isHidden);+ const hasEntries = visibleEntries.length > 0;+ // Idle precedes the first open-time load; show loading rather than an empty result.+ const isPending = status === 'idle' || status === 'loading';+ const listStatus = !hasEntries && isPending ? 'loading' : !hasEntries && error ? 'error' : 'ready';++ const handleRetry = useCallback(() => {+ void loadWorkflowLibraryRange(first, last, true);+ }, [first, last]);+ // With nothing resident there is no window to reread: the first listing itself failed. The button stays busy until+ // that listing settles.+ const [isReloading, setIsReloading] = useState(false);+ const handleReload = useCallback(() => {+ setIsReloading(true);+ void refreshWorkflowLibraryBrowse().finally(() => setIsReloading(false));+ }, []);++ /** A row acted on outside the resident window (a retained one) reloads its position first, as a pinned card does. */+ const ensurePosition = useCallback(+ (id: string, index: number, action: () => void) => {+ const resident = getWorkflowLibraryBrowseSnapshot().entries.some((entry) => entry.item.workflow_id === id);++ if (isWindowed && !resident) {+ void loadWorkflowLibraryRange(index, index).then((ready) => {+ if (ready) {+ action();+ }+ });+ } else {+ action();+ }+ },+ [isWindowed]+ );+ const actions = useMemo<WorkflowLibraryListRowActions>(+ () => ({+ menu: (entry, index, anchor) => {+ retain(entry, index);+ ensurePosition(entry.item.workflow_id, index, () => onContextMenu(entry.item.workflow_id, anchor));+ },+ open: (id, index) => ensurePosition(id, index, () => onOpen(id)),+ preview: (id, index) =>+ ensurePosition(id, index, () => {+ onSelect(id);+ onPreview?.(id);+ }),+ select: (id, index) => ensurePosition(id, index, () => onSelect(id)),+ }),+ [ensurePosition, onContextMenu, onOpen, onPreview, onSelect, retain]+ );++ const handleDoubleClick = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ const target = event.target as Element;+ const row = rowOf(target);+ const index = row ? positionOf(row) : -1;+ const entry = entryAt(rows, index);++ if (entry && target.closest('[data-list-primary]')) {+ actions.open(entry.item.workflow_id, index);+ }+ },+ [actions, rows]+ );+ // Pointer-only quick actions never take focus: it moves to their row, so a dialog they open returns there.+ const handleMouseDown = useCallback((event: MouseEvent<HTMLDivElement>) => {+ const target = event.target as Element;++ if (target.closest('[data-row-quick-action]')) {+ event.preventDefault();+ rowOf(target)?.querySelector<HTMLElement>('[data-list-primary]')?.focus({ preventScroll: true });+ }+ }, []);+ const handleFocusCapture = useCallback(+ (event: FocusEvent<HTMLDivElement>) => {+ const row = rowOf(event.target);+ const index = row ? positionOf(row) : -1;+ const entry = entryAt(rows, index);++ if (entry) {+ retain(entry, index);+ }+ },+ [retain, rows]+ );++ const canPreview = onPreview !== undefined;+ const renderItem = ({ entry, index }: WorkflowLibraryListItem, rowProps: ListRowProps) => {+ const id = entry?.item.workflow_id;++ return (+ <WorkflowLibraryListRow+ {...rowProps}+ actions={actions}+ canPreview={canPreview}+ entry={entry}+ index={index}+ isActiveWorkflow={id !== undefined && id === activeWorkflowId}+ isInProject={id !== undefined && linkedTemplates.has(id)}+ menuOpenedBy={+ id !== undefined && openMenuAnchor?.workflowId === id+ ? openMenuAnchor.kind === 'trigger'+ ? 'button'+ : 'row'+ : null+ }+ missingCount={id === undefined ? 0 : (missingCounts.get(id) ?? 0)}+ missingNodePackCount={+ templates && entry?.enrichment.status === 'ready'+ ? getMissingNodePacks(entry.enrichment, templates).length+ : null+ }+ showLastRun={!isWindowed}+ showVisibilityStatus={showVisibilityStatus}+ trailingField={trailingField}+ />+ );+ };++ return (+ <Box+ ref={wrapperRef}+ css={LIST_CSS}+ data-workflow-library-collection=""+ data-workflow-library-list=""+ onDoubleClick={handleDoubleClick}+ onFocusCapture={handleFocusCapture}+ onMouseDown={handleMouseDown}+ onScrollCapture={handleScrollCapture}+ >+ {isActive && isWindowed && range !== null && total > 0 ? (+ <WorkflowLibraryDemand key={demandKey} end={last} ids={ids} start={first} />+ ) : null}+ {hasEntries && error ? (+ <HStack color="fg.subtle" flexShrink={0} fontSize="xs" gap="2" justify="center" role="alert">+ <Text>{error}</Text>+ {isWindowed ? (+ <Button size="sm" variant="ghost" onClick={handleRetry}>+ {t('common.retry')}+ </Button>+ ) : null}+ </HStack>+ ) : null}+ <List+ activeKey={activeKey}+ density="comfortable"+ dividers+ emptyState={+ <Text color="fg.subtle" fontSize="md" py="6" textAlign="center">+ {emptyMessage ?? t('workflowLibrary.empty')}+ </Text>+ }+ errorState={+ <HStack color="fg.subtle" fontSize="md" gap="2" py="6" role="alert">+ <Text>{error}</Text>+ {isWindowed ? (+ <Button loading={isReloading} size="sm" variant="ghost" onClick={handleReload}>+ {t('common.retry')}+ </Button>+ ) : null}+ </HStack>+ }+ initialScrollOffset={initialScrollOffset}+ inset="none"+ label={t('workflowLibrary.title')}+ renderItem={renderItem}+ rows={rows}+ status={listStatus}+ surface="bg.panel"+ onRangeChange={isWindowed ? handleRangeChange : undefined}+ onScrollOffsetPersist={isWindowed ? persistScrollOffset : undefined}+ />+ </Box>+ );+};++interface WorkflowLibraryListRowActions {+ menu: (entry: WorkflowLibraryEntry, index: number, anchor: WorkflowCardMenuAnchor) => void;+ open: (id: string, index: number) => void;+ preview: (id: string, index: number) => void;+ select: (id: string, index: number) => void;+}++interface WorkflowLibraryListRowProps extends ListRowProps {+ actions: WorkflowLibraryListRowActions;+ canPreview: boolean;+ /** Null while the position's metadata is not resident: the row is a busy placeholder with the same controls. */+ entry: WorkflowLibraryEntry | null;+ index: number;+ /** The project's active workflow: badged, and offers no Open since it is already open. */+ isActiveWorkflow: boolean;+ isInProject: boolean;+ /** Which of the row's controls has the actions menu open, if any; that control names the menu for the dialog. */+ menuOpenedBy: 'row' | 'button' | null;+ missingCount: number;+ missingNodePackCount: number | null;+ showLastRun: boolean;+ showVisibilityStatus: boolean;+ trailingField: WorkflowLibraryListTrailingField;+}++const ignoreContextMenu = () => {};+const PLACEHOLDER_LEADING = <Box {...PLACEHOLDER_THUMBNAIL_PROPS} data-workflow-list-placeholder="" />;+const PLACEHOLDER_DESCRIPTION = <Box as="span" {...PLACEHOLDER_LINE_PROPS} />;++/**+ * One component for a position whether or not its page is resident, so the ListItem and its primary button persist+ * when the page arrives. Memoised: range loads, enrichment and scrolling re-render the list, but rarely a given row.+ */+const WorkflowLibraryListRow = memo(function WorkflowLibraryListRow({+ actions,+ canPreview,+ entry,+ index,+ isActiveWorkflow,+ isInProject,+ menuOpenedBy,+ missingCount,+ missingNodePackCount,+ showLastRun,+ showVisibilityStatus,+ trailingField,+ ...rowProps+}: WorkflowLibraryListRowProps) {+ const { t } = useTranslation();+ const item = entry?.item ?? null;+ const id = item?.workflow_id ?? null;+ const dataTime = useDataTimeSnapshot(item);++ // With the date column showing the last run, the facts line leads with the node count rather than repeat it.+ const lastRun =+ showLastRun && trailingField !== 'last_run_at' && item?.last_run_at+ ? formatTimeSince(item.last_run_at, dataTime)+ : '';+ const facts = entry+ ? getWorkflowLibraryEntryFacts({ entry, isInProject, lastRun, missingCount, missingNodePackCount }, t)+ : null;+ const timestamp = item && trailingField ? item[trailingField] : null;+ const menuContentId = id === null ? undefined : getWorkflowLibraryCardMenuContentId(id);+ const isPublic = showVisibilityStatus && item?.is_public === true;++ const handlePress = useCallback(() => id !== null && actions.select(id, index), [actions, id, index]);+ const handleContextMenu = useCallback(+ ({ x, y }: ListContextMenuAnchor) =>+ entry !== null && actions.menu(entry, index, { kind: 'point', workflowId: entry.item.workflow_id, x, y }),+ [actions, entry, index]+ );+ const handleOpen = useCallback(() => id !== null && actions.open(id, index), [actions, id, index]);+ const handlePreview = useCallback(() => id !== null && actions.preview(id, index), [actions, id, index]);+ const handleMore = useCallback(+ () =>+ entry !== null &&+ actions.menu(entry, index, {+ kind: 'trigger',+ triggerId: getWorkflowLibraryCardMenuId(entry.item.workflow_id),+ workflowId: entry.item.workflow_id,+ }),+ [actions, entry, index]+ );++ return (+ <ListItem+ {...rowProps}+ actions={+ // A placeholder keeps the same controls, hidden, so the row's width does not change when its page arrives.+ <HStack aria-hidden={entry === null || undefined} gap="1" visibility={entry === null ? 'hidden' : undefined}>+ <Button+ aria-hidden+ css={ROW_ACTION_CSS}+ data-row-action="open"+ data-row-quick-action+ // The active project workflow is already open; its rail disables Open too.+ data-unavailable={entry === null || isActiveWorkflow || undefined}+ size="xs"+ tabIndex={-1}+ variant="outline"+ onClick={handleOpen}+ >+ {/* Parity with the rail: opening asks what to do once the project holds a copy. */}+ {isInProject ? t('workflowLibrary.openWithEllipsis') : t('workflowLibrary.open')}+ </Button>+ {canPreview ? (+ <Tooltip content={t('workflowLibrary.preview.actionHint')}>+ <IconButton+ aria-hidden+ aria-label={t('workflowLibrary.preview.action')}+ css={ROW_ACTION_CSS}+ data-row-action="preview"+ data-row-quick-action+ data-unavailable={entry === null || undefined}+ size="xs"+ tabIndex={-1}+ variant="outline"+ onClick={handlePreview}+ >+ <WorkflowIcon />+ </IconButton>+ </Tooltip>+ ) : null}+ {/* The row's keyboard control after its button: it shares the row's roving tab stop. */}+ <Tooltip content={t('workflowLibrary.moreActions')}>+ <IconButton+ aria-controls={menuOpenedBy === 'button' ? menuContentId : undefined}+ aria-expanded={menuOpenedBy === 'button'}+ aria-haspopup="menu"+ aria-label={t('workflowLibrary.moreActions')}+ css={ROW_ACTION_CSS}+ data-workflow-card-menu={id ?? undefined}+ id={id === null ? undefined : getWorkflowLibraryCardMenuId(id)}+ size="xs"+ tabIndex={entry === null ? -1 : rowProps.tabIndex}+ variant="outline"+ onClick={handleMore}+ >+ <EllipsisIcon />+ </IconButton>+ </Tooltip>+ </HStack>+ }+ badges={+ isPublic || isActiveWorkflow || isInProject ? (+ <>+ {isPublic ? (+ <Badge data-workflow-visibility="public" variant="subtle">+ {t('workflowLibrary.public')}+ </Badge>+ ) : null}+ {isActiveWorkflow ? (+ <Badge data-active-workflow variant="solid">+ {t('workflowLibrary.activeWorkflow')}+ </Badge>+ ) : null}+ {isInProject ? (+ <Box as="span" data-workflow-in-project display="inline-flex" opacity={0.8}>+ <Icon aria-hidden as={FolderCheckIcon} boxSize="3" />+ <Text srOnly>{t('workflowLibrary.inProject')}</Text>+ </Box>+ ) : null}+ </>+ ) : null+ }+ controls={menuOpenedBy === 'row' ? menuContentId : undefined}+ description={+ facts ? <WorkflowLibraryFactsLine facts={facts} isOnAccent={rowProps.isActive} /> : PLACEHOLDER_DESCRIPTION+ }+ id={id === null ? undefined : getWorkflowLibraryCardId(id)}+ isBusy={entry === null || rowProps.isBusy}+ isExpanded={menuOpenedBy === 'row' || undefined}+ isMenuOpen={menuOpenedBy !== null}+ leading={+ entry ? (+ // 54px wide, so the 3:2 well is the 36px a comfortable row's media takes.+ <WorkflowSummaryThumbnail+ src={entry.item.thumbnail_url}+ w="3.375rem"+ workflowDocument={entry.enrichment.status === 'ready' ? entry.enrichment.document : null}+ />+ ) : (+ PLACEHOLDER_LEADING+ )+ }+ // A placeholder has no name yet; its button says it is loading.+ pressLabel={entry === null ? t('workflowLibrary.loading') : undefined}+ title={item ? item.name || t('workflowLibrary.untitled') : ''}+ titleTruncate="end"+ trailing={timestamp ? formatTimeSince(timestamp, dataTime) : null}+ // A placeholder has no actions yet; it still keeps the browser's own menu from opening over the list.+ onContextMenu={entry === null ? ignoreContextMenu : handleContextMenu}+ onPress={handlePress}+ />+ );+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryPreviewStage.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryPreviewStage.tsxnew file mode 100644index 0000000000..7d5bbdbebb--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryPreviewStage.tsx@@ -0,0 +1,344 @@+import type { ProjectGraphState } from '@features/workflow/core/types';+import type { WorkflowDocumentGraphHandle } from '@features/workflow/ui/graph-preview/WorkflowDocumentGraph';++import { Box, Menu, Portal, Stack, type SystemStyleObject } from '@chakra-ui/react';+import { localizeForLoopValidationReason } from '@features/workflow/core/forLoops';+import { hasMultipleWorkflowReturnNodes } from '@features/workflow/core/workflowJson';+import {+ buildWorkflowPreviewModel,+ type WorkflowPreviewMetrics,+ type WorkflowPreviewModel,+} from '@features/workflow/core/workflowPreview';+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { getGraphJsonText } from '@features/workflow/ui/graph-preview/graphJson';+import { WorkflowPreviewInputs } from '@features/workflow/ui/graph-preview/WorkflowPreviewInputs';+import {+ getWorkflowPreviewViewTabs,+ WorkflowPreviewBar,+ WorkflowPreviewFindField,+ WorkflowPreviewStageLoading,+ WorkflowPreviewStageMessage,+ type WorkflowPreviewView,+ useWorkflowPreviewFind,+ WorkflowPreviewJson,+} from '@features/workflow/ui/graph-preview/WorkflowPreviewStage';+import { useNodesNeedingModel } from '@features/workflow/ui/modelRequirementStatus';+import { copyWorkflowJson, downloadWorkflowJson } from '@features/workflow/ui/workflowTransfer';+import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';+import { canCopyText } from '@platform/browser/clipboard';+import { Button, IconButton } from '@platform/ui/Button';+import { MenuActionItem, MenuContent } from '@platform/ui/Menu';+import { SegmentTabs, segmentTabsPanelId, segmentTabsTabId } from '@platform/ui/SegmentTabs';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import { ChevronLeftIcon, CopyIcon, DownloadIcon, EllipsisIcon } from 'lucide-react';+import { type Ref, Suspense, useCallback, useId, useImperativeHandle, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { buildLibraryGraphPreviewSource, DeferredWorkflowDocumentGraph } from './libraryPreviewSource';+import { keepMenuOpenWhenSiblingMenuCloses } from './WorkflowLibraryCard';+import { WORKFLOW_LIBRARY_NARROW, WORKFLOW_LIBRARY_WIDE } from './WorkflowLibraryRail';++/**+ * Preview mode's stage: it takes the places rail's and the collection's place in the dialog while the detail rail stays+ * where it is (and steps through the view's results). The bar leaves (back to the place), switches the view, finds a+ * node and exports the saved workflow; the body draws the selected workflow's document. The collection stays laid out underneath, hidden, so leaving+ * returns to it exactly as it was.+ */++export interface WorkflowLibraryPreviewStageHandle {+ /** Escape in preview mode: closes an open node card, else leaves the preview. */+ handleEscape: () => void;+}++export type WorkflowLibraryPreviewStatus =+ | { kind: 'pending' }+ | { kind: 'error'; message: string }+ | { kind: 'ready'; document: ProjectGraphState };++export interface WorkflowLibraryPreviewStageProps {+ ref: Ref<WorkflowLibraryPreviewStageHandle>;+ /** The place the preview leaves back to, for the back button. */+ placeLabel: string;+ /** The previewed workflow; null when the view has nothing selected. */+ workflowId: string | null;+ name: string;+ status: WorkflowLibraryPreviewStatus;+ /** Leaves preview mode; receives the workflow shown last, whose card or row then takes focus. */+ onLeave: (workflowId: string | null) => void;+ /** The view, which the library keeps while it is open. */+ view: WorkflowPreviewView;+ onViewChange: (view: WorkflowPreviewView) => void;+}++/**+ * Wide: over the places rail and the centre column, from under the header to the dialog's foot, reaching across the+ * column gap to the detail rail's border. Narrow: the panes grid lays it over the collection.+ */+const STAGE_CSS: SystemStyleObject = {+ bg: 'bg',+ minH: '0',+ minW: '0',+ zIndex: 1,+ [WORKFLOW_LIBRARY_WIDE]: { gridColumn: 'rail-start / toolbar-end', gridRow: '1 / -1', me: '-3' },+};+// A narrow dialog keeps the bar to leaving, the view and export; finding a node needs the room.+const FIND_CSS: SystemStyleObject = { [WORKFLOW_LIBRARY_NARROW]: { display: 'none' } };+// The stage takes focus as preview mode starts, so a reader hears its name; it draws no ring of its own.+const NO_OUTLINE = { outline: 'none' } as const;++export const WorkflowLibraryPreviewStage = ({+ name,+ placeLabel,+ ref,+ status,+ view,+ workflowId,+ onLeave,+ onViewChange,+}: WorkflowLibraryPreviewStageProps) => {+ const { t } = useTranslation();+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const notify = useWorkflowNotifications();+ const exportMenuIds = useTooltipTriggerIds();+ const viewTabsId = useId();+ // The node an input named, opened selected when the view switches to the graph; it belongs to its workflow.+ const [shownNode, setShownNode] = useState<{ nodeId: string; workflowId: string | null } | null>(null);+ const initialNodeId = shownNode?.workflowId === workflowId ? shownNode.nodeId : null;+ const stageRef = useRef<HTMLDivElement>(null);+ const graphRef = useRef<WorkflowDocumentGraphHandle>(null);++ const document = status.kind === 'ready' ? status.document : null;+ const templates = templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null;+ const model = useMemo(+ () => (document && templates ? buildWorkflowPreviewModel(document, templates) : null),+ [document, templates]+ );+ /**+ * Each document the stage draws is a new drawing: a workflow replaced under the same id (updated from its template)+ * must not inherit the last one's selected node, find matches, simplified state or viewport.+ */+ const [drawing, setDrawing] = useState({ key: 0, model });+ if (drawing.model !== model) {+ setDrawing({ key: drawing.key + 1, model });+ }+ const needsModel = useNodesNeedingModel(model);+ // The drawing at a wider chip, where the stage has the room.+ const relayout = useCallback(+ (metrics: WorkflowPreviewMetrics, previous: WorkflowPreviewModel | null) =>+ buildWorkflowPreviewModel(document!, templates!, metrics, previous),+ [document, templates]+ );+ const find = useWorkflowPreviewFind(graphRef, drawing.key);+ const menuPositioning = useMemo(+ () => ({+ boundary: () => stageRef.current?.closest<HTMLElement>('[data-scope="dialog"][data-part="content"]') ?? [],+ }),+ []+ );++ const leave = useCallback(() => onLeave(workflowId), [onLeave, workflowId]);+ useImperativeHandle(+ ref,+ () => ({+ handleEscape: () => {+ if (!graphRef.current?.closeNodeCard()) {+ leave();+ }+ },+ }),+ [leave]+ );++ const exportDocument = useCallback(+ (action: 'copy' | 'download') => {+ if (!document) {+ return;+ }++ // The editor's own export refuses the same documents: a workflow return node must be unique to round-trip.+ if (hasMultipleWorkflowReturnNodes(document)) {+ notify.error(+ action === 'copy' ? t('widgets.workflow.copyJsonFailed') : t('projects.exportFailed'),+ t('workflowLibrary.multipleWorkflowReturnNodesForTransfer')+ );+ return;+ }++ if (action === 'download') {+ downloadWorkflowJson(document);+ return;+ }++ copyWorkflowJson(document)+ .then(() => notify.success(t('widgets.workflow.copyJsonSuccess')))+ .catch(() => notify.error(t('widgets.workflow.copyJsonFailed')));+ },+ [document, notify, t]+ );+ const copyJson = useCallback(() => exportDocument('copy'), [exportDocument]);+ // Each switch draws the graph afresh, so the find field starts over with it.+ const { reset: resetFind } = find;+ const selectView = useCallback(+ (next: WorkflowPreviewView) => {+ setShownNode(null);+ resetFind();+ onViewChange(next);+ },+ [onViewChange, resetFind]+ );+ const showNode = useCallback(+ (nodeId: string) => {+ selectView('nodes');+ setShownNode({ nodeId, workflowId });+ },+ [selectView, workflowId]+ );+ const viewTabs = useMemo(() => getWorkflowPreviewViewTabs(model, { hasGraph: true, hasInputs: true }, t), [model, t]);+ // The Graph view compiles the document as it would run, only while that view shows (once per document).+ const compiled = useMemo(+ () => (view === 'graph' && document && templates ? buildLibraryGraphPreviewSource(document, templates) : null),+ [document, templates, view]+ );+ const compiledGraph = compiled?.graph ?? null;+ const getJsonText = useCallback(() => (compiledGraph ? getGraphJsonText(compiledGraph) : ''), [compiledGraph]);+ const downloadJson = useCallback(() => exportDocument('download'), [exportDocument]);++ const showsNodes = view === 'nodes' && model !== null && model.nodes.size > 0;++ return (+ <Stack+ ref={stageRef}+ aria-label={t('workflowLibrary.preview.region', { name })}+ as="section"+ css={STAGE_CSS}+ data-preview-stage={workflowId ?? ''}+ gap="0"+ tabIndex={-1}+ _focusVisible={NO_OUTLINE}+ >+ <WorkflowPreviewBar>+ <Button+ aria-label={t('workflowLibrary.preview.backTo', { place: placeLabel })}+ data-preview-back=""+ gap="1.5"+ px="2"+ variant="ghost"+ onClick={leave}+ >+ <ChevronLeftIcon />+ {placeLabel}+ </Button>+ <SegmentTabs+ activeId={view}+ ariaLabel={t('workflowLibrary.preview.view')}+ idBase={viewTabsId}+ isCompact+ tabs={viewTabs}+ onSelect={selectView}+ />+ <Box flex="1" />+ {showsNodes ? <WorkflowPreviewFindField css={FIND_CSS} find={find} /> : null}+ <Menu.Root+ ids={exportMenuIds}+ positioning={menuPositioning}+ onRequestDismiss={keepMenuOpenWhenSiblingMenuCloses}+ >+ {/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, the menu+ never takes focus and the first pointer move onto it closes it. */}+ <Menu.Trigger asChild>+ <Tooltip content={t('workflowLibrary.preview.exportMenu')} ids={exportMenuIds}>+ <IconButton+ aria-label={t('workflowLibrary.preview.exportMenu')}+ data-preview-export=""+ disabled={!document}+ size="sm"+ variant="outline"+ >+ <EllipsisIcon />+ </IconButton>+ </Tooltip>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="min(13rem, var(--available-width))" maxW="var(--available-width)">+ <MenuActionItem+ icon={CopyIcon}+ label={t('workflowLibrary.preview.copyJson')}+ unavailableReason={canCopyText() ? undefined : t('common.copyUnavailable')}+ value="copy-workflow-json"+ onSelect={copyJson}+ />+ <MenuActionItem+ icon={DownloadIcon}+ label={t('workflowLibrary.preview.downloadJson')}+ value="download-workflow-json"+ onSelect={downloadJson}+ />+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </WorkflowPreviewBar>+ <Box+ aria-labelledby={segmentTabsTabId(viewTabsId, view)}+ data-preview-stage-body=""+ flex="1"+ id={segmentTabsPanelId(viewTabsId)}+ minH="0"+ position="relative"+ role="tabpanel"+ >+ {status.kind === 'error' ? (+ <WorkflowPreviewStageMessage isAlert>+ {t('workflowLibrary.preview.unreadable', { message: status.message })}+ </WorkflowPreviewStageMessage>+ ) : workflowId === null ? (+ <WorkflowPreviewStageMessage>{t('workflowLibrary.preview.nothingSelected')}</WorkflowPreviewStageMessage>+ ) : compiled ? (+ compiledGraph ? (+ <Suspense fallback={STAGE_LOADING}>+ <WorkflowPreviewJson+ copyFailedLabel={t('graphPreview.copyFailed')}+ copyLabel={t('graphPreview.copyGraphJson')}+ getText={getJsonText}+ label={t('workflowLibrary.preview.graphJson')}+ />+ </Suspense>+ ) : (+ // Why it would not run, in words: the Nodes and Inputs views still show the document.+ <WorkflowPreviewStageMessage isAlert>+ {t('graphPreview.invalidTitle')}{' '}+ {compiled.invalidReasons.map((reason) => localizeForLoopValidationReason(reason, t)).join(' ')}+ </WorkflowPreviewStageMessage>+ )+ ) : model?.nodes.size === 0 ? (+ <WorkflowPreviewStageMessage>{t('workflowLibrary.preview.empty')}</WorkflowPreviewStageMessage>+ ) : model && view === 'inputs' ? (+ <WorkflowPreviewInputs model={model} onShowNode={showNode} />+ ) : model ? (+ <Suspense fallback={STAGE_LOADING}>+ <DeferredWorkflowDocumentGraph+ key={`${drawing.key}:${initialNodeId ?? ''}`}+ ref={graphRef}+ initialNodeId={initialNodeId}+ model={model}+ needsModel={needsModel}+ relayout={relayout}+ onMatchCountChange={find.onMatchCountChange}+ />+ </Suspense>+ ) : templatesSnapshot.status === 'error' ? (+ <WorkflowPreviewStageMessage isAlert>+ {t('workflowLibrary.preview.unreadable', {+ message: templatesSnapshot.error ?? t('common.unknownError'),+ })}+ </WorkflowPreviewStageMessage>+ ) : (+ <WorkflowPreviewStageLoading />+ )}+ </Box>+ </Stack>+ );+};++const STAGE_LOADING = <WorkflowPreviewStageLoading />;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryRail.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryRail.tsxnew file mode 100644index 0000000000..5804494844--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryRail.tsx@@ -0,0 +1,458 @@+import type { WorkflowLibraryPlace, WorkflowTagCount } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibraryTab } from '@features/workflow/ui/workflowUiStore';+import type { LucideIcon } from 'lucide-react';++import { Box, Checkbox, createListCollection, HStack, Icon, Popover, Portal, Stack, Text } from '@chakra-ui/react';+import { Button } from '@platform/ui/Button';+import { PopoverContent } from '@platform/ui/Popover';+import { Scrollable } from '@platform/ui/Scrollable';+import { Select } from '@platform/ui/Select';+import { BookOpenIcon, ClockIcon, FolderIcon, LayoutTemplateIcon, UsersIcon } from 'lucide-react';+import { useCallback, useId, useMemo, useRef } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * The library's left rail: the places it browses, then the current place's tags as any-of checkboxes. Counts are+ * the place's own, never narrowed by the search or the checked tags, so checking a tag never changes its neighbours.+ */++const RAIL_WIDTH = '12.25rem';++/**+ * The library's one layout breakpoint, on the dialog's container (`containerName: workflow-library-dialog`): below+ * 56rem (a window under about 960px) the rail, a usable card column and the 18rem detail rail no longer fit side by+ * side. There the places become a select in the toolbar, the tags a popover behind a Tags button that counts the+ * checked ones, the order and view controls one options menu, and the detail rail a bottom sheet+ * (`WorkflowDetailSheet`).+ */+export const WORKFLOW_LIBRARY_NARROW = '@container workflow-library-dialog (width < 56rem)';+/** The complement of `WORKFLOW_LIBRARY_NARROW`: the rail, centre column and detail rail side by side. */+export const WORKFLOW_LIBRARY_WIDE = '@container workflow-library-dialog (width >= 56rem)';+/** Controls that only the wide layout shows. */+export const WORKFLOW_LIBRARY_WIDE_ONLY_CSS = { [WORKFLOW_LIBRARY_NARROW]: { display: 'none' } } as const;++const TAG_HOVER = { bg: 'bg.muted' } as const;++const PLACES: ReadonlyArray<{ icon: LucideIcon; labelKey: string; value: WorkflowLibraryTab }> = [+ { icon: FolderIcon, labelKey: 'workflowLibrary.placeProject', value: 'project' },+ { icon: ClockIcon, labelKey: 'workflowLibrary.placeRecent', value: 'recent' },+ { icon: BookOpenIcon, labelKey: 'workflowLibrary.placeUser', value: 'user' },+ { icon: LayoutTemplateIcon, labelKey: 'workflowLibrary.placeDefault', value: 'default' },+ { icon: UsersIcon, labelKey: 'workflowLibrary.placeShared', value: 'shared' },+];++/** A place's name, as the rail lists it. */+export const getWorkflowLibraryPlaceLabelKey = (place: WorkflowLibraryTab): string =>+ PLACES.find((candidate) => candidate.value === place)!.labelKey;++/** The id of a place's label in the rail, which names the centre column showing that place. */+export const getWorkflowLibraryPlaceLabelId = (idBase: string, place: WorkflowLibraryTab) => `${idBase}-place-${place}`;++export interface WorkflowLibraryRailProps {+ /** Prefix for the place labels' ids; see `getWorkflowLibraryPlaceLabelId`. */+ idBase: string;+ place: WorkflowLibraryTab;+ /** Unfiltered totals per library place; an absent place shows no count. */+ placeTotals: Readonly<Partial<Record<WorkflowLibraryPlace, number>>>;+ /** In this project's count. */+ projectTotal: number;+ showShared: boolean;+ tagCounts: readonly WorkflowTagCount[];+ checkedTags: readonly string[];+ /** A sentence under the rail, for the place it describes. */+ footer?: string;+ onPlaceChange: (place: WorkflowLibraryTab) => void;+ onTagsChange: (tags: readonly string[]) => void;+}++const SectionLabel = ({ children, id }: { children: string; id: string }) => (+ <Text color="fg.muted" fontSize="xs" fontWeight="600" id={id} pb="1" px="2" textTransform="uppercase">+ {children}+ </Text>+);++// Localized labels wrap rather than clip, so every place and tag reads in full.+const LABEL_WRAP = { overflowWrap: 'anywhere', whiteSpace: 'normal' } as const;++const PlaceButton = ({+ count,+ icon,+ isCurrent,+ label,+ labelId,+ place,+ onSelect,+}: {+ count: string | undefined;+ icon: LucideIcon;+ labelId: string;+ isCurrent: boolean;+ label: string;+ place: WorkflowLibraryTab;+ onSelect: (place: WorkflowLibraryTab) => void;+}) => {+ const handleClick = useCallback(() => onSelect(place), [onSelect, place]);++ return (+ <Button+ aria-pressed={isCurrent}+ data-library-place={place}+ gap="2"+ h="auto"+ justifyContent="start"+ minH="7"+ py="1"+ variant={isCurrent ? 'subtle' : 'ghost'}+ w="full"+ onClick={handleClick}+ >+ <Icon aria-hidden as={icon} boxSize="3.5" flexShrink={0} />+ <Text css={LABEL_WRAP} flex="1" id={labelId} minW="0" textAlign="start">+ {label}+ </Text>+ {count === undefined ? null : (+ // On the current place's tinted background the muted tone falls under 4.5:1; the label's own colour holds.+ <Text+ as="span"+ color={isCurrent ? 'inherit' : 'fg.muted'}+ flexShrink={0}+ fontSize="xs"+ fontVariantNumeric="tabular-nums"+ >+ {count}+ </Text>+ )}+ </Button>+ );+};++const TagCheckbox = ({+ count,+ isChecked,+ isListed,+ tag,+ onToggle,+}: {+ count: string;+ isChecked: boolean;+ isListed: boolean;+ tag: string;+ onToggle: (tag: string, isChecked: boolean) => void;+}) => {+ const handleChange = useCallback(+ ({ checked }: { checked: boolean | 'indeterminate' }) => onToggle(tag, checked === true),+ [onToggle, tag]+ );++ return (+ <Checkbox.Root+ alignItems="center"+ checked={isChecked}+ data-library-tag={tag}+ data-unlisted={isListed ? undefined : ''}+ gap="2"+ minW="0"+ px="2"+ py="1"+ rounded="sm"+ size="sm"+ w="full"+ _hover={TAG_HOVER}+ onCheckedChange={handleChange}+ >+ <Checkbox.HiddenInput />+ <Checkbox.Control flexShrink={0}>+ <Checkbox.Indicator />+ </Checkbox.Control>+ <Checkbox.Label css={LABEL_WRAP} flex="1" fontSize="sm" fontWeight="normal" minW="0">+ {tag}+ </Checkbox.Label>+ <Text as="span" color="fg.muted" flexShrink={0} fontSize="xs" fontVariantNumeric="tabular-nums">+ {count}+ </Text>+ </Checkbox.Root>+ );+};++export interface WorkflowLibraryTagGroupProps {+ tagCounts: readonly WorkflowTagCount[];+ checkedTags: readonly string[];+ onTagsChange: (tags: readonly string[]) => void;+ /** Takes focus when the control holding it leaves and no listed tag remains to take it. */+ getFallbackFocus: () => HTMLElement | null | undefined;+}++/** The current place's tags as any-of checkboxes with Clear, shared by the rail and the narrow layout's popover. */+export const WorkflowLibraryTagGroup = ({+ checkedTags,+ getFallbackFocus,+ tagCounts,+ onTagsChange,+}: WorkflowLibraryTagGroupProps) => {+ const { i18n, t } = useTranslation();+ const numberFormat = useMemo(() => new Intl.NumberFormat(i18n.resolvedLanguage), [i18n.resolvedLanguage]);+ const groupRef = useRef<HTMLDivElement>(null);+ const tagsLabelId = useId();+ const tagsHintId = useId();+ // A checked tag the counts no longer list (a failed count, a deleted workflow) stays visible, so it can be cleared.+ const listedTags = useMemo(() => new Set(tagCounts.map(({ tag }) => tag)), [tagCounts]);+ /**+ * Controls that leave on this change (Clear with the last checked tag, an unlisted tag once unchecked) hand focus to+ * the first listed tag, or the fallback when no tag stays, rather than letting it fall to the page.+ */+ const keepFocus = useCallback(() => {+ (+ groupRef.current?.querySelector<HTMLElement>('[data-library-tag]:not([data-unlisted]) input[type="checkbox"]') ??+ getFallbackFocus()+ )?.focus();+ }, [getFallbackFocus]);+ const handleToggle = useCallback(+ (tag: string, isChecked: boolean) => {+ if (!isChecked && !listedTags.has(tag)) {+ keepFocus();+ }++ onTagsChange(isChecked ? [...checkedTags, tag] : checkedTags.filter((candidate) => candidate !== tag));+ },+ [checkedTags, keepFocus, listedTags, onTagsChange]+ );+ const handleClear = useCallback(() => {+ keepFocus();+ onTagsChange([]);+ }, [keepFocus, onTagsChange]);+ const tags = [...tagCounts, ...checkedTags.filter((tag) => !listedTags.has(tag)).map((tag) => ({ count: 0, tag }))];++ if (tags.length === 0) {+ return null;+ }++ return (+ <Stack ref={groupRef} aria-describedby={tagsHintId} aria-labelledby={tagsLabelId} gap="0" minW="0" role="group">+ <HStack justify="space-between" minW="0">+ <SectionLabel id={tagsLabelId}>{t('workflowLibrary.tags')}</SectionLabel>+ {checkedTags.length > 0 ? (+ <Button flexShrink={0} mb="1" size="xs" variant="plain" onClick={handleClear}>+ {t('workflowLibrary.clearTags')}+ </Button>+ ) : null}+ </HStack>+ {tags.map(({ count, tag }) => (+ <TagCheckbox+ key={tag}+ count={numberFormat.format(count)}+ isChecked={checkedTags.includes(tag)}+ isListed={listedTags.has(tag)}+ tag={tag}+ onToggle={handleToggle}+ />+ ))}+ <Text color="fg.muted" fontSize="xs" id={tagsHintId} pt="1.5" px="2">+ {t('workflowLibrary.tagsAnyHint')}+ </Text>+ </Stack>+ );+};++export const WorkflowLibraryRail = ({+ checkedTags,+ footer,+ idBase,+ place,+ placeTotals,+ projectTotal,+ showShared,+ tagCounts,+ onPlaceChange,+ onTagsChange,+}: WorkflowLibraryRailProps) => {+ const { i18n, t } = useTranslation();+ const numberFormat = useMemo(() => new Intl.NumberFormat(i18n.resolvedLanguage), [i18n.resolvedLanguage]);+ const formatTotal = (total: number | undefined) => (total === undefined ? undefined : numberFormat.format(total));+ const railRef = useRef<HTMLDivElement>(null);+ const placesLabelId = useId();+ const getCurrentPlace = useCallback(+ () => railRef.current?.querySelector<HTMLElement>('[data-library-place][aria-pressed="true"]'),+ []+ );++ return (+ <Stack+ ref={railRef}+ borderColor="border.subtle"+ borderEndWidth="1px"+ data-workflow-library-rail+ flexShrink={0}+ gap="0"+ minH="0"+ w={RAIL_WIDTH}+ >+ {/* Unlabelled: the nav and the tag group inside it name themselves. */}+ <Scrollable flex="1" minH="0">+ <Stack gap="4" minW="0" px="3" py="3">+ <Box as="nav" aria-labelledby={placesLabelId} minW="0">+ <SectionLabel id={placesLabelId}>{t('workflowLibrary.places')}</SectionLabel>+ <Stack as="ul" gap="0.5" listStyle="none" minW="0">+ {PLACES.filter((item) => item.value !== 'shared' || showShared).map((item) => (+ <Box as="li" key={item.value} minW="0">+ <PlaceButton+ count={formatTotal(item.value === 'project' ? projectTotal : placeTotals[item.value])}+ icon={item.icon}+ labelId={getWorkflowLibraryPlaceLabelId(idBase, item.value)}+ isCurrent={place === item.value}+ label={t(item.labelKey)}+ place={item.value}+ onSelect={onPlaceChange}+ />+ </Box>+ ))}+ </Stack>+ </Box>+ <WorkflowLibraryTagGroup+ checkedTags={checkedTags}+ getFallbackFocus={getCurrentPlace}+ tagCounts={tagCounts}+ onTagsChange={onTagsChange}+ />+ </Stack>+ </Scrollable>+ {footer ? (+ <Text borderColor="border.subtle" borderTopWidth="1px" color="fg.muted" fontSize="xs" pb="3" px="3" pt="2.5">+ {footer}+ </Text>+ ) : null}+ </Stack>+ );+};++interface PlaceOption {+ count: string | undefined;+ label: string;+ value: WorkflowLibraryTab;+}++const PlaceOptionLabel = ({ count, label }: Pick<PlaceOption, 'count' | 'label'>) => (+ <Box as="span" alignItems="baseline" display="inline-flex" gap="2" minW="0" w="full">+ <Box as="span" flex="1" minW="0" truncate>+ {label}+ </Box>+ {count === undefined ? null : (+ <Text as="span" color="fg.muted" flexShrink={0} fontSize="xs" fontVariantNumeric="tabular-nums">+ {count}+ </Text>+ )}+ </Box>+);+const renderPlaceOption = (option: PlaceOption) => <PlaceOptionLabel count={option.count} label={option.label} />;++export type WorkflowLibraryPlaceSelectProps = Pick<+ WorkflowLibraryRailProps,+ 'place' | 'placeTotals' | 'projectTotal' | 'showShared' | 'onPlaceChange'+>;++/** The narrow layout's places: a select at the start of the toolbar naming the current place and its count. */+export const WorkflowLibraryPlaceSelect = ({+ place,+ placeTotals,+ projectTotal,+ showShared,+ onPlaceChange,+}: WorkflowLibraryPlaceSelectProps) => {+ const { i18n, t } = useTranslation();+ const options = useMemo(() => {+ const numberFormat = new Intl.NumberFormat(i18n.resolvedLanguage);++ return PLACES.filter((item) => item.value !== 'shared' || showShared).map((item): PlaceOption => {+ const total = item.value === 'project' ? projectTotal : placeTotals[item.value];++ return {+ count: total === undefined ? undefined : numberFormat.format(total),+ label: t(item.labelKey),+ value: item.value,+ };+ });+ }, [i18n.resolvedLanguage, placeTotals, projectTotal, showShared, t]);+ const collection = useMemo(() => createListCollection({ items: options }), [options]);+ const value = useMemo(() => [place], [place]);+ const current = options.find((option) => option.value === place);+ const valueText = useMemo(+ () => (current ? <PlaceOptionLabel count={current.count} label={current.label} /> : undefined),+ [current]+ );+ const handleValueChange = useCallback(+ ({ value: [next] }: { value: string[] }) => {+ const option = options.find((candidate) => candidate.value === next);++ if (option) {+ onPlaceChange(option.value);+ }+ },+ [onPlaceChange, options]+ );++ return (+ <Select+ aria-label={t('workflowLibrary.places')}+ collection={collection}+ data-workflow-library-place-select+ flexShrink={0}+ maxW="14rem"+ minW="9rem"+ renderItem={renderPlaceOption}+ value={value}+ valueText={valueText}+ w="auto"+ onValueChange={handleValueChange}+ />+ );+};++const TAG_FILTER_POSITIONING = { placement: 'bottom-start' } as const;++/**+ * The narrow layout's tags button, in the toolbar after the places select: "Tags N" opens the tag checkboxes in a+ * popover. Absent while the place has no tags and none is checked.+ */+export const WorkflowLibraryTagButton = ({+ checkedTags,+ getFallbackFocus,+ tagCounts,+ onTagsChange,+}: WorkflowLibraryTagGroupProps) => {+ const { i18n, t } = useTranslation();+ const triggerRef = useRef<HTMLButtonElement>(null);+ // Inside the popover the trigger outlives every tag; it leaves only with the whole button.+ const getPopoverFallback = useCallback(() => triggerRef.current ?? getFallbackFocus(), [getFallbackFocus]);++ if (tagCounts.length === 0 && checkedTags.length === 0) {+ return null;+ }++ return (+ <Popover.Root lazyMount positioning={TAG_FILTER_POSITIONING} unmountOnExit>+ <Popover.Trigger asChild>+ <Button ref={triggerRef} data-workflow-library-tags-trigger flexShrink={0} gap="1.5" variant="outline">+ {t('workflowLibrary.tags')}+ {checkedTags.length > 0 ? (+ <Text as="span" color="fg.muted" fontVariantNumeric="tabular-nums">+ {new Intl.NumberFormat(i18n.resolvedLanguage).format(checkedTags.length)}+ </Text>+ ) : null}+ </Button>+ </Popover.Trigger>+ <Portal>+ <Popover.Positioner>+ <PopoverContent data-workflow-library-tag-popover p="1.5" w="16rem">+ <Scrollable maxH="min(20rem, calc(var(--available-height) - 1rem))">+ <WorkflowLibraryTagGroup+ checkedTags={checkedTags}+ getFallbackFocus={getPopoverFallback}+ tagCounts={tagCounts}+ onTagsChange={onTagsChange}+ />+ </Scrollable>+ </PopoverContent>+ </Popover.Positioner>+ </Portal>+ </Popover.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsxdeleted file mode 100644index 1d911c5323..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx+++ /dev/null@@ -1,90 +0,0 @@-import type { WorkflowTagCount } from '@features/workflow/data/libraryBrowseStore';--import { HStack, Text } from '@chakra-ui/react';-import { Button, Scrollable } from '@platform/ui';-import { useCallback } from 'react';-import { useTranslation } from 'react-i18next';--/** Tag counts cover the whole backend category, not merely loaded infinite-scroll pages. */--// A ScrollArea root defaults to `height: 100%` and grows to its content's-// max-content width, so a chip strip needs both an explicit height and an-// inline-size containment or it stretches the dialog header.-const CHIP_STRIP_CONTAIN_CSS = { contain: 'inline-size' } as const;-const CHIP_STRIP_CONTENT_PROPS = { h: 'full' } as const;--interface WorkflowLibraryTagChipsProps {- selectedTag: string | null;- tagCounts: readonly WorkflowTagCount[];- onSelect: (tag: string | null) => void;-}--const TagChip = ({- count,- isSelected,- label,- tag,- onSelect,-}: {- count: number | null;- isSelected: boolean;- label: string;- tag: string | null;- onSelect: (tag: string | null) => void;-}) => {- const handleClick = useCallback(() => onSelect(tag), [onSelect, tag]);-- return (- <Button- aria-pressed={isSelected}- flexShrink={0}- rounded="full"- size="sm"- variant={isSelected ? 'subtle' : 'ghost'}- onClick={handleClick}- >- {label}- {count === null ? null : (- <Text as="span" color="fg.subtle" fontSize="xs">- {count}- </Text>- )}- </Button>- );-};--export const WorkflowLibraryTagChips = ({ selectedTag, tagCounts, onSelect }: WorkflowLibraryTagChipsProps) => {- const { t } = useTranslation();-- // A lone "All" chip filters nothing. The strip stays while a tag is still- // applied, so a category whose counts failed to load can always be cleared.- if (tagCounts.length === 0 && selectedTag === null) {- return null;- }-- return (- <Scrollable- contentProps={CHIP_STRIP_CONTENT_PROPS}- css={CHIP_STRIP_CONTAIN_CSS}- flexShrink={0}- h="1.75rem"- label={t('workflowLibrary.tagsLabel')}- minW="0"- orientation="horizontal"- w="full"- >- <HStack align="center" gap="1" h="full" minW="0">- <TagChip- count={null}- isSelected={selectedTag === null}- label={t('workflowLibrary.allTag')}- tag={null}- onSelect={onSelect}- />- {tagCounts.map(({ count, tag }) => (- <TagChip key={tag} count={count} isSelected={selectedTag === tag} label={tag} tag={tag} onSelect={onSelect} />- ))}- </HStack>- </Scrollable>- );-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsxindex eea3e3f8f8..c370cb3bea 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx@@ -24,11 +24,13 @@ import { getApiErrorMessage } from '@platform/transport/http';import { IconButton } from '@platform/ui/Button';import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';import { CameraIcon, ImageOffIcon, Trash2Icon, UploadIcon } from 'lucide-react';-import { Suspense, useCallback, useRef, useState, type MouseEvent } from 'react';+import { Suspense, useCallback, useMemo, useRef, useState, type MouseEvent } from 'react';import { useTranslation } from 'react-i18next';import { buildLibraryGraphPreviewSource, DeferredGraphPreviewSnapshot, loadGraphPreview } from './libraryPreviewSource';import { formatTimeSince, useDataTimeSnapshot } from './relativeTime';+import { WorkflowPreviewThumbnailButton } from './WorkflowDetailOverview';+import { getWorkflowSilhouetteImage } from './workflowSilhouette';import { WORKFLOW_THUMBNAIL_ASPECT_RATIO, WorkflowThumbnailImage } from './workflowThumbnail';const IMAGE_ONLY = ['image'] as const;@@ -43,13 +45,61 @@ const WELL_CSS: SystemStyleObject = {w: 'full',};+/** A faint dot ground under the silhouette: one tiny tile image, cheaper to paint while scrolling than a gradient. */+const DOT_TILE = `url("data:image/svg+xml,${encodeURIComponent(+ '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12"><circle cx="6" cy="6" r="0.75" fill="rgb(140 144 156 / 0.35)"/></svg>'+)}")`;+const SILHOUETTE_CSS: SystemStyleObject = {+ backgroundPosition: 'center, center',+ backgroundRepeat: 'no-repeat, repeat',+ backgroundSize: '100% 100%, 12px 12px',+ h: 'full',+ w: 'full',+};++/**+ * What a well shows without an image: the workflow's node layout as faint boxes on a dotted ground, or, before its+ * document is known or when it has no nodes, the plain no-image placeholder. The silhouette is one element with a+ * cached background image, so cards scrolling through the grid cost one box each.+ */+export const WorkflowThumbnailPlaceholder = ({+ caption,+ workflowDocument,+}: {+ /** Shown under the no-image icon; the silhouette needs none. */+ caption?: string;+ workflowDocument: ProjectGraphState | null;+}) => {+ const image = workflowDocument ? getWorkflowSilhouetteImage(workflowDocument) : null;+ const style = useMemo(() => (image ? { backgroundImage: `${image.url}, ${DOT_TILE}` } : undefined), [image]);++ if (!image) {+ return (+ <Flex align="center" direction="column" gap="1" h="full" justify="center" w="full">+ <Icon aria-hidden as={ImageOffIcon} boxSize="5" color="fg.subtle" opacity={0.6} />+ {caption ? (+ <Text color="fg.subtle" fontSize="xs">+ {caption}+ </Text>+ ) : null}+ </Flex>+ );+ }++ // The image goes in a plain style attribute: as a style prop, every distinct graph would mint its own CSS class.+ return <Box aria-hidden css={SILHOUETTE_CSS} data-workflow-silhouette={image.rectCount} style={style} />;+};+/** Key by workflow id: an action in flight for one workflow must not show as busy on the next selection. */export const WorkflowLibraryThumbnail = ({canEdit,item,workflowDocument,+ onPreview,}: {canEdit: boolean;+ /** Makes the thumbnail the way into the preview. */+ onPreview?: () => void;/** The template's parsed workflow once its row has loaded; the snapshot renders its graph. */workflowDocument: ProjectGraphState | null;item: WorkflowLibraryListItem;@@ -239,12 +289,7 @@ export const WorkflowLibraryThumbnail = ({{showThumbnail ? (<WorkflowThumbnailImage src={item.thumbnail_url} onError={handleThumbnailError} />) : (- <Flex align="center" direction="column" gap="1" h="full" justify="center" w="full">- <Icon aria-hidden as={ImageOffIcon} boxSize="5" color="fg.subtle" opacity={0.6} />- <Text color="fg.subtle" fontSize="xs">- {t('workflowLibrary.notRunYet')}- </Text>- </Flex>+ <WorkflowThumbnailPlaceholder caption={t('workflowLibrary.notRunYet')} workflowDocument={workflowDocument} />)}{isBusy ? (<Flex align="center" bg="bg.muted/90" inset="0" justify="center" position="absolute">@@ -255,9 +300,12 @@ export const WorkflowLibraryThumbnail = ({);return (- <Stack gap="1" minW="0">+ <Stack data-thumbnail-kind={showThumbnail ? 'image' : 'silhouette'} gap="1" minW="0"><Box aria-busy={isBusy || undefined} css={WELL_CSS}>{wellContent}+ {onPreview ? (+ <WorkflowPreviewThumbnailButton name={item.name || t('workflowLibrary.untitled')} onPreview={onPreview} />+ ) : null}{/* Bundled defaults keep their shipped image; the account's own templates choose theirs from the gallery. */}{isEditable ? (<HStackdiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryToolbar.tsxnew file mode 100644index 0000000000..3a5ef7f67c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryToolbar.tsx@@ -0,0 +1,312 @@+import type { WorkflowLibraryLayout, WorkflowThumbnailFit } from '@features/workflow/ui/WorkflowUiContext';+import type { ChangeEvent, ReactNode, RefObject } from 'react';++import { Box, HStack, Icon, Input, InputGroup, Menu, Portal, Text } from '@chakra-ui/react';+import { Button, IconButton } from '@platform/ui/Button';+import { MenuContent } from '@platform/ui/Menu';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import {+ ArrowDownWideNarrowIcon,+ ArrowUpNarrowWideIcon,+ ChevronDownIcon,+ LayoutGridIcon,+ ListIcon,+ PlusIcon,+ SearchIcon,+ SlidersHorizontalIcon,+} from 'lucide-react';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import type { WorkflowLibraryCardSize } from './workflowThumbnail';++import { WORKFLOW_LIBRARY_NARROW, WORKFLOW_LIBRARY_WIDE_ONLY_CSS } from './WorkflowLibraryRail';++/**+ * The library's one toolbar, the same on every place: one row of equal-height controls 8px apart. Wide: search, the+ * Sort menu (key and direction, its glyph showing the direction), the view menu (grid or list, its glyph showing which,+ * and for the grid card size and thumbnail fit) and, on This project, New workflow at the row's end. Narrow+ * (`WORKFLOW_LIBRARY_NARROW`): the places select and Tags button lead, and one menu holds the order and view choices.+ */++const SEARCH_START_ELEMENT = <Icon aria-hidden as={SearchIcon} boxSize="3.5" color="fg.subtle" />;+const MENU_POSITIONING = { placement: 'bottom-end' } as const;+const NARROW_ONLY_CSS = { display: 'none', [WORKFLOW_LIBRARY_NARROW]: { display: 'inline-flex' } } as const;+const NARROW_LEAD_CSS = {+ display: 'none',+ [WORKFLOW_LIBRARY_NARROW]: { alignItems: 'center', display: 'flex', gap: '2' },+} as const;+// The key's natural direction first: dates newest first, names A to Z, the project's own order first to last.+const DESCENDING_FIRST = ['desc', 'asc'] as const;+const ASCENDING_FIRST = ['asc', 'desc'] as const;+const CARD_SIZES = ['small', 'large'] as const;+const LAYOUTS = ['grid', 'list'] as const;++export interface WorkflowLibrarySortOption {+ label: string;+ value: string;+}++export interface WorkflowLibraryToolbarProps {+ /** The narrow layout's places select and Tags button, leading the row; the wide layout shows them in the rail. */+ narrowLead?: ReactNode;+ search: string;+ /** The dialog's initial focus. */+ searchInputRef: RefObject<HTMLInputElement | null>;+ sortOptions: readonly WorkflowLibrarySortOption[];+ sort: string;+ /** A place with one fixed order shows it without offering a choice. */+ isSortFixed: boolean;+ direction: 'asc' | 'desc';+ /** What each direction means for the current key, such as "Newest first". */+ directionLabels: Readonly<Record<'asc' | 'desc', string>>;+ isDirectionFixed: boolean;+ /** Grid of cards or list rows; card size and thumbnail fit apply to the grid only. */+ layout: WorkflowLibraryLayout;+ cardSize: WorkflowLibraryCardSize;+ thumbnailFit: WorkflowThumbnailFit;+ /** Offered on This project only. */+ onNewWorkflow?: () => void;+ onSearchChange: (search: string) => void;+ onSortChange: (sort: string) => void;+ onDirectionToggle: () => void;+ onLayoutChange: (layout: WorkflowLibraryLayout) => void;+ onCardSizeChange: (cardSize: WorkflowLibraryCardSize) => void;+ onThumbnailFitChange: (fit: WorkflowThumbnailFit) => void;+}++export const WorkflowLibraryToolbar = ({+ cardSize,+ direction,+ directionLabels,+ isDirectionFixed,+ isSortFixed,+ layout,+ narrowLead,+ search,+ searchInputRef,+ sort,+ sortOptions,+ thumbnailFit,+ onCardSizeChange,+ onDirectionToggle,+ onLayoutChange,+ onNewWorkflow,+ onSearchChange,+ onSortChange,+ onThumbnailFitChange,+}: WorkflowLibraryToolbarProps) => {+ const { t } = useTranslation();+ const viewIds = useTooltipTriggerIds();+ const narrowOptionsIds = useTooltipTriggerIds();+ const sortLabel = sortOptions.find((option) => option.value === sort)?.label ?? '';+ const sortName = t('workflowLibrary.sortControl', { direction: directionLabels[direction], sort: sortLabel });++ const handleSearchChange = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => onSearchChange(event.currentTarget.value),+ [onSearchChange]+ );+ const handleSortChange = useCallback(({ value }: { value: string }) => onSortChange(value), [onSortChange]);+ const handleDirectionChange = useCallback(+ ({ value }: { value: string }) => {+ if (value !== direction) {+ onDirectionToggle();+ }+ },+ [direction, onDirectionToggle]+ );+ const handleLayoutChange = useCallback(+ ({ value }: { value: string }) => onLayoutChange(value === 'list' ? 'list' : 'grid'),+ [onLayoutChange]+ );+ const handleCardSizeChange = useCallback(+ ({ value }: { value: string }) => onCardSizeChange(value === 'large' ? 'large' : 'small'),+ [onCardSizeChange]+ );+ const handleFitChange = useCallback(+ ({ value }: { value: string }) => onThumbnailFitChange(value === 'contain' ? 'contain' : 'cover'),+ [onThumbnailFitChange]+ );++ // The order: the key, then its two directions spelled out for that key (Newest first / Oldest first, A to Z / Z to A).+ const orderGroups = (+ <>+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('workflowLibrary.sortLabel')}</Menu.ItemGroupLabel>+ <Menu.RadioItemGroup value={sort} onValueChange={handleSortChange}>+ {sortOptions.map((option) => (+ <Menu.RadioItem key={option.value} disabled={isSortFixed} value={option.value}>+ <Menu.ItemIndicator />+ <Menu.ItemText>{option.label}</Menu.ItemText>+ </Menu.RadioItem>+ ))}+ </Menu.RadioItemGroup>+ </Menu.ItemGroup>+ <Menu.Separator />+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('workflowLibrary.sortDirectionGroup')}</Menu.ItemGroupLabel>+ <Menu.RadioItemGroup value={direction} onValueChange={handleDirectionChange}>+ {(sort === 'name' || sort === 'order' ? ASCENDING_FIRST : DESCENDING_FIRST).map((value) => (+ <Menu.RadioItem key={value} disabled={isDirectionFixed} value={value}>+ <Menu.ItemIndicator />+ <Menu.ItemText>{directionLabels[value]}</Menu.ItemText>+ </Menu.RadioItem>+ ))}+ </Menu.RadioItemGroup>+ </Menu.ItemGroup>+ </>+ );+ // Card size and thumbnail display shape only the grid; the list shows neither.+ const gridViewGroups = (+ <>+ <Menu.Separator />+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('workflowLibrary.cardSize')}</Menu.ItemGroupLabel>+ <Menu.RadioItemGroup value={cardSize} onValueChange={handleCardSizeChange}>+ {CARD_SIZES.map((value) => (+ <Menu.RadioItem key={value} value={value}>+ <Menu.ItemIndicator />+ <Menu.ItemText>+ {t(value === 'large' ? 'workflowLibrary.cardSizeLarge' : 'workflowLibrary.cardSizeSmall')}+ </Menu.ItemText>+ </Menu.RadioItem>+ ))}+ </Menu.RadioItemGroup>+ </Menu.ItemGroup>+ <Menu.Separator />+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('workflowLibrary.thumbnailFit')}</Menu.ItemGroupLabel>+ <Menu.RadioItemGroup value={thumbnailFit} onValueChange={handleFitChange}>+ <Menu.RadioItem value="cover">+ <Menu.ItemIndicator />+ <Menu.ItemText>{t('workflowLibrary.thumbnailFitCover')}</Menu.ItemText>+ </Menu.RadioItem>+ <Menu.RadioItem value="contain">+ <Menu.ItemIndicator />+ <Menu.ItemText>{t('workflowLibrary.thumbnailFitContain')}</Menu.ItemText>+ </Menu.RadioItem>+ </Menu.RadioItemGroup>+ </Menu.ItemGroup>+ </>+ );+ const viewGroups = (+ <>+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel>{t('workflowLibrary.layoutGroup')}</Menu.ItemGroupLabel>+ <Menu.RadioItemGroup value={layout} onValueChange={handleLayoutChange}>+ {LAYOUTS.map((value) => (+ <Menu.RadioItem key={value} value={value}>+ <Menu.ItemIndicator />+ <Menu.ItemText>+ {t(value === 'list' ? 'workflowLibrary.layoutList' : 'workflowLibrary.layoutGrid')}+ </Menu.ItemText>+ </Menu.RadioItem>+ ))}+ </Menu.RadioItemGroup>+ </Menu.ItemGroup>+ {layout === 'grid' ? gridViewGroups : null}+ </>+ );++ return (+ // One row; only a very narrow dialog wraps the menus under the search.+ <HStack data-workflow-library-toolbar flexShrink={0} flexWrap="wrap" gap="2" minW="0">+ {narrowLead ? (+ <Box css={NARROW_LEAD_CSS} flexShrink={0} maxW="full" minW="0">+ {narrowLead}+ </Box>+ ) : null}+ <InputGroup flex="1" minW="8rem" startElement={SEARCH_START_ELEMENT}>+ <Input+ ref={searchInputRef}+ aria-label={t('workflowLibrary.searchPlaceholder')}+ placeholder={t('workflowLibrary.searchPlaceholder')}+ type="search"+ value={search}+ onChange={handleSearchChange}+ />+ </InputGroup>+ {/* Its text names the key; the glyph shows the direction, and the accessible name spells out both. */}+ <Box css={WORKFLOW_LIBRARY_WIDE_ONLY_CSS} flexShrink={0}>+ <Menu.Root closeOnSelect={false} positioning={MENU_POSITIONING}>+ <Menu.Trigger asChild>+ <Button+ aria-label={sortName}+ data-workflow-library-sort+ disabled={isSortFixed && isDirectionFixed}+ gap="1.5"+ variant="outline"+ >+ <Icon+ aria-hidden+ as={direction === 'asc' ? ArrowUpNarrowWideIcon : ArrowDownWideNarrowIcon}+ boxSize="3.5"+ color="fg.muted"+ />+ <Text as="span" whiteSpace="nowrap">+ {sortLabel}+ </Text>+ <Icon aria-hidden as={ChevronDownIcon} boxSize="3.5" color="fg.muted" />+ </Button>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent maxH="var(--available-height)" minW="13rem" overflowY="auto">+ {orderGroups}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </Box>+ <Box css={WORKFLOW_LIBRARY_WIDE_ONLY_CSS} flexShrink={0}>+ <Menu.Root closeOnSelect={false} ids={viewIds} positioning={MENU_POSITIONING}>+ {/* Inside a dialog the tooltip must sit inside the menu trigger: wrapped the other way round, the menu never+ takes focus and the first pointer move onto it closes it. */}+ <Menu.Trigger asChild>+ <Tooltip content={t('workflowLibrary.viewOptions')} ids={viewIds}>+ <IconButton aria-label={t('workflowLibrary.viewOptions')} data-workflow-library-view variant="outline">+ {layout === 'list' ? <ListIcon /> : <LayoutGridIcon />}+ </IconButton>+ </Tooltip>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="12rem">{viewGroups}</MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </Box>+ {/* The narrow layout's one menu for every order and view choice; it stays open across choices. */}+ <Box css={NARROW_ONLY_CSS} flexShrink={0}>+ <Menu.Root closeOnSelect={false} ids={narrowOptionsIds} positioning={MENU_POSITIONING}>+ <Menu.Trigger asChild>+ <Tooltip content={t('workflowLibrary.sortAndViewOptions')} ids={narrowOptionsIds}>+ <IconButton+ aria-label={t('workflowLibrary.sortAndViewOptions')}+ data-workflow-library-narrow-options+ variant="outline"+ >+ <SlidersHorizontalIcon />+ </IconButton>+ </Tooltip>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>+ <MenuContent maxH="var(--available-height)" minW="13rem" overflowY="auto">+ {orderGroups}+ <Menu.Separator />+ {viewGroups}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </Box>+ {onNewWorkflow ? (+ <Button flexShrink={0} onClick={onNewWorkflow}>+ <PlusIcon />+ {t('workflowLibrary.newWorkflow')}+ </Button>+ ) : null}+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPreviewStepper.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPreviewStepper.tsxnew file mode 100644index 0000000000..4da722798f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPreviewStepper.tsx@@ -0,0 +1,113 @@+import { HStack, Text } from '@chakra-ui/react';+import { useMountEffect } from '@platform/react/useMountEffect';+import { IconButton } from '@platform/ui/Button';+import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';+import { type KeyboardEvent as ReactKeyboardEvent, useCallback, useRef } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * Preview mode's stepper: it steps the workflow the detail rail describes through the view's current results, so it+ * sits with that workflow's name (atop the rail, or beside the name in the narrow sheet's summary). Up and Down on it+ * step too.+ */++export interface WorkflowPreviewStepperProps {+ /** The workflow's place in the view's current results (0-based); null while unknown. */+ position: number | null;+ total: number;+ canStepPrevious: boolean;+ canStepNext: boolean;+ /**+ * Steps through the results. A step that must first read its position asks `isCurrent` before selecting what+ * arrived: false once the stepper has gone (the preview closed) or a later step has replaced it.+ */+ onStep: (delta: -1 | 1, isCurrent: () => boolean) => void;+}++export const WorkflowPreviewStepper = ({+ canStepNext,+ canStepPrevious,+ position,+ total,+ onStep,+}: WorkflowPreviewStepperProps) => {+ const { t } = useTranslation();+ // The latest step, and whether this stepper still shows: a read that lands after either changed selects nothing.+ const stepToken = useRef(0);+ const isMounted = useRef(false);+ useMountEffect(() => {+ isMounted.current = true;++ return () => {+ isMounted.current = false;+ };+ });+ const step = useCallback(+ (delta: -1 | 1) => {+ const token = ++stepToken.current;++ onStep(delta, () => isMounted.current && stepToken.current === token);+ },+ [onStep]+ );+ const stepPrevious = useCallback(() => step(-1), [step]);+ const stepNext = useCallback(() => step(1), [step]);+ const handleKeyDown = useCallback(+ (event: ReactKeyboardEvent<HTMLDivElement>) => {+ if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {+ event.preventDefault();+ step(event.key === 'ArrowUp' ? -1 : 1);+ }+ },+ [step]+ );+ // Stepping needs the workflow's place in the results; at an end there is nowhere further to go.+ const unavailable = (canStep: boolean, endKey: string) =>+ position === null ? t('workflowLibrary.preview.positionUnknown') : canStep ? undefined : t(endKey);++ return (+ <HStack+ aria-label={t('workflowLibrary.preview.stepper')}+ data-preview-stepper=""+ flexShrink={0}+ gap="1"+ justify="space-between"+ minW="0"+ role="group"+ onKeyDown={handleKeyDown}+ >+ <Text+ aria-live="polite"+ color="fg.muted"+ data-preview-position=""+ fontSize="md"+ fontVariantNumeric="tabular-nums"+ whiteSpace="nowrap"+ >+ {position !== null ? t('workflowLibrary.preview.position', { position: position + 1, total }) : null}+ </Text>+ <HStack gap="0.5">+ <IconButton+ aria-label={t('workflowLibrary.preview.previous')}+ size="sm"+ tooltip={t('workflowLibrary.preview.previous')}+ unavailableReason={unavailable(canStepPrevious, 'workflowLibrary.preview.atFirst')}+ variant="ghost"+ onClick={stepPrevious}+ >+ <ChevronUpIcon />+ </IconButton>+ <IconButton+ aria-label={t('workflowLibrary.preview.next')}+ size="sm"+ tooltip={t('workflowLibrary.preview.next')}+ unavailableReason={unavailable(canStepNext, 'workflowLibrary.preview.atLast')}+ variant="ghost"+ onClick={stepNext}+ >+ <ChevronDownIcon />+ </IconButton>+ </HStack>+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.browser.test.tsxindex 10417b4729..3acaae27cc 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.browser.test.tsx@@ -17,6 +17,7 @@ import { system } from '@theme/system';import { act, StrictMode } 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 { loadGraphPreview } from './libraryPreviewSource';import { WorkflowPublicationHost } from './WorkflowPublicationHost';@@ -51,9 +52,12 @@ vi.mock('@features/workflow/data/api', async (importOriginal) => ({...api,}));+// One snapshot, as the real store hands out until the templates change.+const TEMPLATES_SNAPSHOT = vi.hoisted(() => ({ error: null, status: 'loaded' as const, templates: {} }));+vi.mock('@features/workflow/react', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),- useInvocationTemplatesSnapshot: () => ({ error: null, status: 'loaded', templates: {} }),+ useInvocationTemplatesSnapshot: () => TEMPLATES_SNAPSHOT,}));const TRANSLATIONS: Record<string, string> = {@@ -158,8 +162,6 @@ const BUNDLED: ProjectWorkflowEntry = { ...UNLINKED, source: { libraryWorkflowIdconst OTHER: ProjectWorkflowEntry = { document: { ...createProjectGraph('wf-2'), name: 'Beta' } };const GRAPH_PREVIEW: WorkflowGraphPreviewPort = {focusSource: vi.fn(),- getRoute: () => null,- invoke: () => Promise.resolve(false),openDocumentInNewProject: vi.fn(),openWorkflowEditor: vi.fn(),};@@ -649,6 +651,37 @@ describe('WorkflowPublicationHost', () => {expect(dialogs()).toHaveLength(0);});+ it('opens the graph preview over the review under StrictMode and returns to the review, which stays open', async () => {+ await loadGraphPreview();+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ revision: 5 }));+ await renderHost([LINKED_UNKNOWN]);+ await request('update-source');+ await click(choice('review'));++ const preview = () =>+ document.querySelector<HTMLElement>('[data-graph-preview-stage]')?.closest<HTMLElement>('[role="dialog"]') ??+ null;+ const openPreview = async () => {+ await click(buttonWithText(reviewDialog(), 'workflowLibrary.previewGraph'));+ await vi.waitFor(() => expect(preview()?.dataset.state).toBe('open'));+ await vi.waitFor(() => expect(preview()?.contains(document.activeElement)).toBe(true));+ };+ const expectBackInReview = async () => {+ await vi.waitFor(() => expect(preview()).toBeNull());+ expect(reviewDialog()).not.toBeNull();+ await vi.waitFor(() => expect(reviewDialog()?.contains(document.activeElement)).toBe(true));+ };++ await openPreview();+ await act(() => userEvent.keyboard('{Escape}'));+ await flush();+ await expectBackInReview();++ await openPreview();+ await click(preview()?.querySelector<HTMLButtonElement>('[data-scope="dialog"][data-part="close-trigger"]'));+ await expectBackInReview();+ });+it('dates the revision against the arriving review record instead of the loading view mount', async () => {await loadGraphPreview();vi.useFakeTimers({ toFake: ['Date'] });diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsxindex d10673e55f..be36f5c99c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsx@@ -5,7 +5,7 @@ import type { FormEvent } from 'react';import { Checkbox, chakra, Input, Portal, Stack, Text } from '@chakra-ui/react';import { getAuthSession, useAuthSession } from '@features/identity';import { savedWorkflowDetailQueryOptions } from '@features/workflow/data/savedWorkflowQueries';-import { getLibraryWorkflowRecord } from '@features/workflow/queries';+import { getLibraryWorkflowRecord, isBundledLibraryWorkflowId } from '@features/workflow/queries';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';import { clearWorkflowPublicationIntent, workflowUiStore } from '@features/workflow/ui/workflowUiStore';@@ -30,7 +30,7 @@ import {DeferredGraphPreviewDialog,preloadGraphPreview,} from './libraryPreviewSource';-import { isBundledLibraryWorkflowId, isUpdatableSource } from './projectWorkflowEntries';+import { isUpdatableSource } from './projectWorkflowEntries';import { formatTimeSince, useDataTimeSnapshot } from './relativeTime';import {discardUnresolvedWorkflowPublication,@@ -577,7 +577,6 @@ export const WorkflowPublicationHost = () => {<Suspense fallback={null}><DeferredGraphPreviewDialoggraphId={activeStage.record.workflow_id}- hideInvokeisOpen={activeStage.isPreviewOpen}source={reviewPreviewSource}sourceLabel={activeStage.record.name || t('workflowLibrary.untitled')}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.test.tsnew file mode 100644index 0000000000..28bde9d0a5--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.test.ts@@ -0,0 +1,75 @@+import type { InvocationTemplate, ProjectGraphState } from '@features/workflow/core/types';+import type { WorkflowLibraryEntryEnrichment } from '@features/workflow/data/libraryBrowseStore';++import { buildInvocationNode, createProjectGraph } from '@features/workflow/utility';+import { describe, expect, it } from 'vitest';++import { getMissingNodePacks } from './WorkflowRequirementsList';++const template = (type: string, nodePack: string): InvocationTemplate => ({+ category: 'test',+ classification: 'stable',+ description: '',+ inputs: {},+ nodePack,+ outputs: {},+ outputType: 'integer_output',+ tags: [],+ title: type,+ type,+ useCache: true,+ version: '1.0.0',+});++const ready = (document: ProjectGraphState): Extract<WorkflowLibraryEntryEnrichment, { status: 'ready' }> => ({+ document,+ nodeCount: document.nodes.length,+ requirements: { primaryBase: null, requirements: [] },+ status: 'ready',+});++describe('getMissingNodePacks', () => {+ const known = template('integer', 'invokeai');+ const document: ProjectGraphState = {+ ...createProjectGraph('packs'),+ nodes: [+ buildInvocationNode(known, { x: 0, y: 0 }),+ buildInvocationNode(template('face_mask', 'face-tools'), { x: 400, y: 0 }),+ buildInvocationNode(template('face_crop', 'face-tools'), { x: 800, y: 0 }),+ buildInvocationNode(template('wobble', 'wobbly'), { x: 1200, y: 0 }),+ ],+ };++ it('names each pack whose node types the server lacks, once', () => {+ expect(getMissingNodePacks(ready(document), { integer: known })).toEqual(['face-tools', 'wobbly']);+ });++ it.each(['toString', 'constructor', '__proto__'])('requires an own template for node type %s', (type) => {+ const inheritedName = template(type, 'custom-tools');+ const enrichment = ready({+ ...createProjectGraph('inherited-type'),+ nodes: [buildInvocationNode(inheritedName, { x: 0, y: 0 })],+ });++ expect(getMissingNodePacks(enrichment, {})).toEqual(['custom-tools']);+ expect(getMissingNodePacks(enrichment, { [type]: inheritedName })).toEqual([]);+ const unavailable = Object.defineProperty({}, type, { value: undefined });+ expect(getMissingNodePacks(enrichment, unavailable)).toEqual(['custom-tools']);+ });++ it('answers from cache for the same enrichment and templates, and recomputes for new templates', () => {+ const enrichment = ready(document);+ const templates = { integer: known };+ const first = getMissingNodePacks(enrichment, templates);++ expect(getMissingNodePacks(enrichment, templates)).toBe(first);+ expect(+ getMissingNodePacks(enrichment, {+ ...templates,+ face_crop: template('face_crop', 'face-tools'),+ face_mask: template('face_mask', 'face-tools'),+ wobble: template('wobble', 'wobbly'),+ })+ ).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsxindex c13cbb4e5e..e0161f6dfa 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.tsx@@ -1,81 +1,26 @@-import type { ModelConfig, StarterModel } from '@features/models';-import type {- ModelRequirementStatus,- ResolvedModelRequirement,- WorkflowModelRequirement,-} from '@features/workflow/core/modelRequirements';+import type { ResolvedModelRequirement, WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';+import type { InvocationTemplates } from '@features/workflow/core/types';import type { WorkflowLibraryEntry, WorkflowLibraryEntryEnrichment } from '@features/workflow/data/libraryBrowseStore';-import type { ElementType } from 'react';+import type { ModelRequirementDeps } from '@features/workflow/ui/modelRequirementStatus';import { DataList, Icon, Skeleton, Spinner, Stack, Text } from '@chakra-ui/react';-import {- ensureModelsLoaded,- ensureStartersLoaded,- useActiveInstallSources,- useModelsSelector,- useStartersSelector,-} from '@features/models';import { getAddModelsSearchTerm, resolveWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';-import { useMountEffect } from '@platform/react/useMountEffect';+import { REQUIREMENT_STATUS_PRESENTATION, useModelRequirementDeps } from '@features/workflow/ui/modelRequirementStatus';import { Tooltip } from '@platform/ui/Tooltip';-import { CheckIcon, DownloadIcon, TriangleAlertIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';/** Highlight installable requirements only; other missing states have no actionable download. */const SKELETON_ROW_COUNT = 2;-const EMPTY_STARTERS: readonly StarterModel[] = [];const EMPTY_COUNTS: ReadonlyMap<string, number> = new Map();-const selectInstalledModels = (snapshot: { models: ModelConfig[] }): readonly ModelConfig[] => snapshot.models;-const selectStarterModels = (snapshot: {- response: { starter_models: StarterModel[] } | null;-}): readonly StarterModel[] => snapshot.response?.starter_models ?? EMPTY_STARTERS;--interface StatusPresentation {- color: string;- icon: ElementType | null;- labelKey: string;-}--const STATUS_PRESENTATION: Record<ModelRequirementStatus, StatusPresentation> = {- // Amber, per the mock, is the "you can fix this" signal and nothing else.- installable: { color: 'fg.warning', icon: DownloadIcon, labelKey: 'workflowLibrary.requirementInstallable' },- installed: { color: 'fg.muted', icon: CheckIcon, labelKey: 'workflowLibrary.requirementInstalled' },- installing: { color: 'fg.muted', icon: null, labelKey: 'workflowLibrary.requirementInstalling' },- unresolvable: { color: 'fg.muted', icon: TriangleAlertIcon, labelKey: 'workflowLibrary.requirementMissing' },-};-/** The extractor's own dedupe identity, reused so rows keep stable React keys. */const getRequirementKey = (requirement: WorkflowModelRequirement): string =>requirement.kind === 'exact'? `exact:${requirement.identifier.key}:${requirement.identifier.hash ?? ''}`: `slot:${requirement.base ?? ''}:${requirement.modelType ?? ''}`;-export interface ModelRequirementDeps {- installedModels: readonly ModelConfig[];- starterModels: readonly StarterModel[];- activeInstallSources: ReadonlySet<string>;-}--/** Share catalog loading and resolution inputs between details and grid badges. */-export const useModelRequirementDeps = (): ModelRequirementDeps => {- const installedModels = useModelsSelector(selectInstalledModels);- const starterModels = useStartersSelector(selectStarterModels);- const activeInstallSources = useActiveInstallSources();-- useMountEffect(() => {- void ensureModelsLoaded();- ensureStartersLoaded();- });-- return useMemo(- () => ({ activeInstallSources, installedModels, starterModels }),- [activeInstallSources, installedModels, starterModels]- );-};-type ReadyEnrichment = Extract<WorkflowLibraryEntryEnrichment, { status: 'ready' }>;/**@@ -105,6 +50,37 @@ export const resolveEntryRequirements = (return resolved;};+const nodePackCache = new WeakMap<ReadyEnrichment, { templates: InvocationTemplates; packs: readonly string[] }>();++/**+ * The node packs a workflow uses that this server does not have: the packs of its invocation nodes whose type is+ * absent from the loaded templates. Cached by enrichment and templates identity, so a card computes it once.+ */+export const getMissingNodePacks = (enrichment: ReadyEnrichment, templates: InvocationTemplates): readonly string[] => {+ const cached = nodePackCache.get(enrichment);++ if (cached && cached.templates === templates) {+ return cached.packs;+ }++ const packs = new Set<string>();++ for (const node of enrichment.document.nodes) {+ if (+ node.type === 'invocation' &&+ (!Object.hasOwn(templates, node.data.type) || templates[node.data.type] === undefined)+ ) {+ packs.add(node.data.nodePack || node.data.type);+ }+ }++ const result = [...packs].sort();++ nodePackCache.set(enrichment, { packs: result, templates });++ return result;+};+/** Count only models the install action can download so card badges agree with the offered operation. */export const useWorkflowLibraryMissingCounts = (entries: readonly WorkflowLibraryEntry[]@@ -144,7 +120,7 @@ const RequirementRow = ({onFindModel?: (query: string) => void;}) => {const { t } = useTranslation();- const presentation = STATUS_PRESENTATION[resolved.status];+ const presentation = REQUIREMENT_STATUS_PRESENTATION[resolved.status];const statusLabel = t(presentation.labelKey);const { label } = resolved.requirement;const searchTerm = getAddModelsSearchTerm(resolved);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.tsindex cd274a8092..9ec1a85ad8 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryPreviewSource.ts@@ -1,57 +1,119 @@import type { GraphPreviewSourceState, InvocationTemplates, ProjectGraphState } from '@features/workflow/contracts';import type * as GraphPreviewDialogModule from '@features/workflow/ui/graph-preview/GraphPreviewDialog';+import { Center, Portal, Spinner } from '@chakra-ui/react';import { ForLoopGraphValidationError } from '@features/workflow/core/forLoops';import { compileProjectGraph } from '@features/workflow/graph';-import { type ComponentType, createElement, lazy, useState } from 'react';+import { createDeferredModule } from '@platform/react/deferredModule';+import { useMountEffect } from '@platform/react/useMountEffect';+import { CloseButton } from '@platform/ui/Button';+import { Dialog } from '@platform/ui/Dialog';+import { LoadError } from '@platform/ui/LoadError';+import { type ComponentType, createElement, type ReactNode, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';type GraphPreviewModule = typeof GraphPreviewDialogModule;-let loadedGraphPreview: GraphPreviewModule | null = null;-let graphPreviewModule: Promise<GraphPreviewModule> | null = null;--/** The preview chunk (xyflow and its stylesheet), kept out of the library and publication chunks until needed. */-export const loadGraphPreview = (): Promise<GraphPreviewModule> =>- (graphPreviewModule ??= import('@features/workflow/ui/graph-preview/GraphPreviewDialog').then(- (module) => {- loadedGraphPreview = module;- return module;- },- (error: unknown) => {- graphPreviewModule = null;- throw error;- }- ));--/** Starts the preview chunk when a dialog that can open the preview mounts. */-export const preloadGraphPreview = (): void => {- void loadGraphPreview().catch(() => {});+/** The xyflow preview chunk is shared by the dialog, snapshot and in-place library graph. */+const graphPreview = createDeferredModule(() => import('@features/workflow/ui/graph-preview/GraphPreviewDialog'));+export const loadGraphPreview = graphPreview.load;+export const preloadGraphPreview = graphPreview.preload;++const PreviewLoadError = ({ onRetry }: { onRetry: () => void }) => {+ const { t } = useTranslation();+ return createElement(LoadError, {+ isRetrying: false,+ layout: 'state',+ message: t('workflowLibrary.preview.loadFailed'),+ onRetry,+ });};-/**- * Renders the loaded component directly and falls back to `lazy` only before the chunk arrives. A first `lazy` render- * always suspends; an open dialog revealed by Suspense gets its effects replayed in StrictMode after its focus trap- * started, and the library's trap then took focus back and dismissed the preview.- */-const deferGraphPreview = <Props extends object>(pick: (module: GraphPreviewModule) => ComponentType<Props>) => {- const Lazy = lazy(() => loadGraphPreview().then((module) => ({ default: pick(module) })));+// Keep the fallback out of the preview chunk too, so it can still close when that chunk is unavailable.+const PreviewLoadDialog = ({+ isOpen,+ onOpenChange,+ onRetry,+ title,+}: {+ isOpen: boolean;+ onOpenChange: (open: boolean) => void;+ onRetry: () => void;+ title: string;+}) => {+ const handleOpenChange = useCallback(({ open }: { open: boolean }) => onOpenChange(open), [onOpenChange]);+ return createElement(Dialog.Root, {+ open: isOpen,+ onOpenChange: handleOpenChange,+ // eslint-disable-next-line react/no-children-prop -- createElement must satisfy the required RootProps.children in this non-JSX module+ children: createElement(+ Portal,+ null,+ createElement(Dialog.Backdrop),+ createElement(+ Dialog.Positioner,+ null,+ createElement(+ Dialog.Content,+ null,+ createElement(Dialog.Header, null, createElement(Dialog.Title, null, title)),+ createElement(Dialog.Body, null, createElement(PreviewLoadError, { onRetry })),+ createElement(Dialog.CloseTrigger, { asChild: true }, createElement(CloseButton))+ )+ )+ ),+ });+};- return function DeferredGraphPreview(props: Props) {- // Chosen once per mount: switching from `Lazy` to the loaded component would remount it.- const [component] = useState(() => (loadedGraphPreview ? pick(loadedGraphPreview) : Lazy));+const deferGraphPreview = <Props extends object>(+ pick: (module: GraphPreviewModule) => ComponentType<Props>,+ failure: (props: Props, retry: () => void, error: unknown) => ReactNode,+ fallback: ReactNode+) =>+ function DeferredGraphPreview(props: Props) {+ const [attempt, setAttempt] = useState(0);+ const retry = useCallback(() => setAttempt((value) => value + 1), []);+ const render = useCallback((module: GraphPreviewModule) => createElement(pick(module), props), [props]);+ const renderError = useCallback((error: unknown) => failure(props, retry, error), [props, retry]);- return createElement(component, props);+ return createElement(graphPreview.Deferred, { key: attempt, fallback, render, renderError });};++export const DeferredGraphPreviewDialog = deferGraphPreview(+ (module) => module.GraphPreviewDialog,+ (props, onRetry) =>+ createElement(PreviewLoadDialog, {+ isOpen: props.isOpen,+ onOpenChange: props.onOpenChange,+ onRetry,+ title: props.sourceLabel,+ }),+ null+);++const SnapshotLoadFailure = ({ error, onError }: { error: Error; onError: (error: Error) => void }) => {+ useMountEffect(() => {+ onError(error);+ });+ return null;};-export const DeferredGraphPreviewDialog = deferGraphPreview((module) => module.GraphPreviewDialog);-export const DeferredGraphPreviewSnapshot = deferGraphPreview((module) => module.GraphPreviewSnapshot);+export const DeferredGraphPreviewSnapshot = deferGraphPreview(+ (module) => module.GraphPreviewSnapshot,+ (props, _retry, error) =>+ createElement(SnapshotLoadFailure, {+ error: error instanceof Error ? error : new Error(String(error)),+ onError: props.onError,+ }),+ null+);+export const DeferredWorkflowDocumentGraph = deferGraphPreview(+ (module) => module.WorkflowDocumentGraph,+ (_props, onRetry) => createElement(PreviewLoadError, { onRetry }),+ createElement(Center, { h: 'full', role: 'status' }, createElement(Spinner))+);-/**- * Preview the entry's saved document without active-project destination or live updates; catch malformed cached- * data despite ready enrichment.- */-export const buildLibraryGraphPreviewSource = (+const compileLibraryGraphPreviewSource = (document: ProjectGraphState,templates: InvocationTemplates): GraphPreviewSourceState => {@@ -61,6 +123,7 @@ export const buildLibraryGraphPreviewSource = (return {destinationLabel: null,+ document,graph,invalidReasons: [],isLive: false,@@ -71,6 +134,7 @@ export const buildLibraryGraphPreviewSource = (} catch (error) {return {destinationLabel: null,+ document,graph: null,invalidReasons: [error instanceof ForLoopGraphValidationError@@ -85,3 +149,30 @@ export const buildLibraryGraphPreviewSource = (};}};++const compiledSources = new WeakMap<+ ProjectGraphState,+ { source: GraphPreviewSourceState; templates: InvocationTemplates }+>();++/**+ * Preview the entry's saved document without active-project destination or live updates; catch malformed cached+ * data despite ready enrichment. The preview draws the document; the compiled graph is what its Graph view shows and+ * its JSON items export. Compiled once per document and templates.+ */+export const buildLibraryGraphPreviewSource = (+ document: ProjectGraphState,+ templates: InvocationTemplates+): GraphPreviewSourceState => {+ const cached = compiledSources.get(document);++ if (cached?.templates === templates) {+ return cached.source;+ }++ const source = compileLibraryGraphPreviewSource(document, templates);++ compiledSources.set(document, { source, templates });++ return source;+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.test.tsindex 08ad09e6ae..1e4e3c5136 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.test.ts@@ -1,9 +1,16 @@import type { AuthSession } from '@features/identity';-import type { ProjectWorkflowSource } from '@features/workflow/core/types';+import type { ProjectWorkflowEntry, ProjectWorkflowSource } from '@features/workflow/core/types';+import type { ProjectWorkflowOrder } from '@features/workflow/ui/workflowUiStore';+import { createProjectGraph } from '@features/workflow/utility';import { describe, expect, it } from 'vitest';-import { isUpdatableSource } from './projectWorkflowEntries';+import {+ countProjectWorkflowTags,+ isUpdatableSource,+ queryProjectWorkflowEntries,+ toProjectWorkflowLibraryEntries,+} from './projectWorkflowEntries';const session = (overrides: Partial<AuthSession> = {}): AuthSession => ({accountEpoch: 1,@@ -57,3 +64,85 @@ describe('isUpdatableSource', () => {expect(isUpdatableSource(foreignSource, session({ ...admin, phase: 'unknown' }))).toBe(false);});});++const workflow = (+ id: string,+ fields: { description?: string; lastRun?: string; name: string; tags?: string; updatedAt: string }+): ProjectWorkflowEntry => ({+ document: {+ ...createProjectGraph(id),+ description: fields.description ?? '',+ name: fields.name,+ tags: fields.tags ?? '',+ updatedAt: fields.updatedAt,+ },+ ...(fields.lastRun+ ? { lastRun: { completedAt: fields.lastRun, imageName: `${id}.png`, submittedAt: fields.lastRun } }+ : {}),+});++/** Project order: Upscale, portrait, Background, Sketch. */+const PROJECT = [+ workflow('upscale', { name: 'Upscale', tags: 'upscale, SDXL', updatedAt: '2026-11-03T00:00:00Z' }),+ workflow('portrait', {+ description: 'Soft studio light',+ lastRun: '2026-11-05T00:00:00Z',+ name: 'portrait',+ tags: 'sdxl',+ updatedAt: '2026-11-01T00:00:00Z',+ }),+ workflow('background', {+ lastRun: '2026-11-08T00:00:00Z',+ name: 'Background',+ tags: 'flux',+ updatedAt: '2026-11-02T00:00:00Z',+ }),+ workflow('sketch', { name: 'Sketch', updatedAt: '2026-11-04T00:00:00Z' }),+];+const ENTRIES = toProjectWorkflowLibraryEntries(PROJECT, null);+const ids = (search: string, tags: readonly string[], order: ProjectWorkflowOrder) =>+ queryProjectWorkflowEntries(ENTRIES, { order, search, tags }).map((entry) => entry.item.workflow_id);+const PROJECT_ORDER: ProjectWorkflowOrder = { direction: 'asc', sort: 'order' };++describe('queryProjectWorkflowEntries', () => {+ it('matches the search in names, descriptions and tags, and any checked tag, ignoring case', () => {+ expect(ids('STUDIO', [], PROJECT_ORDER)).toEqual(['portrait']);+ // A tag matches the search within it, as the server's search does.+ expect(ids('flu', [], PROJECT_ORDER)).toEqual(['background']);+ expect(ids(' ground ', [], PROJECT_ORDER)).toEqual(['background']);+ expect(ids('', ['sdxl', 'Flux'], PROJECT_ORDER)).toEqual(['upscale', 'portrait', 'background']);+ expect(ids('up', ['sdxl'], PROJECT_ORDER)).toEqual(['upscale']);+ // A tag is a whole token here, not a substring.+ expect(ids('', ['sd'], PROJECT_ORDER)).toEqual([]);+ });++ it('orders by project order, name, last update or last run in either direction', () => {+ expect(ids('', [], PROJECT_ORDER)).toEqual(['upscale', 'portrait', 'background', 'sketch']);+ expect(ids('', [], { direction: 'desc', sort: 'order' })).toEqual(['sketch', 'background', 'portrait', 'upscale']);+ expect(ids('', [], { direction: 'asc', sort: 'name' })).toEqual(['background', 'portrait', 'sketch', 'upscale']);+ expect(ids('', [], { direction: 'desc', sort: 'updated' })).toEqual([+ 'sketch',+ 'upscale',+ 'background',+ 'portrait',+ ]);+ // Never-run workflows come last either way, as the server orders them, in project order among themselves.+ expect(ids('', [], { direction: 'desc', sort: 'lastRun' })).toEqual([+ 'background',+ 'portrait',+ 'upscale',+ 'sketch',+ ]);+ expect(ids('', [], { direction: 'asc', sort: 'lastRun' })).toEqual(['portrait', 'background', 'upscale', 'sketch']);+ });+});++describe('countProjectWorkflowTags', () => {+ it('counts each workflow once per tag, merging case variants under the first casing, most used first', () => {+ expect(countProjectWorkflowTags(PROJECT)).toEqual([+ { count: 2, tag: 'SDXL' },+ { count: 1, tag: 'flux' },+ { count: 1, tag: 'upscale' },+ ]);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.tsindex 1b4340493a..d7d5061f7e 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.ts@@ -1,10 +1,12 @@import type { AuthSession } from '@features/identity';import type { InvocationTemplates, ProjectWorkflowEntry, ProjectWorkflowSource } from '@features/workflow/core/types';-import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibraryEntry, WorkflowTagCount } from '@features/workflow/data/libraryBrowseStore';+import type { ProjectWorkflowOrder } from '@features/workflow/ui/workflowUiStore';import { galleryImageUrls } from '@features/gallery/utility';-import { parseWorkflowTags } from '@features/workflow/core/libraryTags';+import { parseWorkflowTags, sortTagCounts } from '@features/workflow/core/libraryTags';import { extractWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';+import { isBundledLibraryWorkflowId } from '@features/workflow/queries';/*** A project workflow presented through the library's card and detail contracts. The mapping is cached per entry@@ -21,10 +23,6 @@ const cache = new WeakMap<{ entry: ProjectWorkflowLibraryEntry; templates: InvocationTemplates | null }>();-/** Bundled template ids are a server invariant (`default_` prefix); they are read-only whoever asks. */-export const isBundledLibraryWorkflowId = (libraryWorkflowId: string): boolean =>- libraryWorkflowId.startsWith('default_');-/** Whether a source can be written to at all; the server still has the final word (ownership, deletion). */export const isUpdatableSource = (source: ProjectWorkflowSource | undefined, session: AuthSession): boolean =>source !== undefined &&@@ -84,3 +82,78 @@ export const findProjectCopiesOf = (workflows: readonly ProjectWorkflowEntry[],libraryWorkflowId: string): ProjectWorkflowEntry[] => workflows.filter((entry) => entry.source?.libraryWorkflowId === libraryWorkflowId);++/**+ * How many of the project's workflows carry each tag, most used first. Case variants are one tag, labelled with the+ * casing seen first, and a workflow listing a tag twice counts once.+ */+export const countProjectWorkflowTags = (workflows: readonly ProjectWorkflowEntry[]): WorkflowTagCount[] => {+ const counts = new Map<string, WorkflowTagCount>();++ for (const { document } of workflows) {+ const seen = new Set<string>();++ for (const tag of parseWorkflowTags(document.tags)) {+ const key = tag.toLocaleLowerCase();++ if (!seen.has(key)) {+ seen.add(key);+ const existing = counts.get(key);+ counts.set(key, { count: (existing?.count ?? 0) + 1, tag: existing?.tag ?? tag });+ }+ }+ }++ return sortTagCounts([...counts.values()]);+};++export interface ProjectWorkflowQuery {+ /** Matched case-insensitively within names, descriptions and tags, as the server matches library searches. */+ search: string;+ /** Any-of, compared case-insensitively. */+ tags: readonly string[];+ order: ProjectWorkflowOrder;+}++const compareText = (left: string, right: string) => left.localeCompare(right, undefined, { sensitivity: 'base' });+/** ISO instants order as plain strings. */+const compareInstants = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0);++/**+ * The project's workflows filtered and ordered like the library places, but locally. Workflows that never ran come+ * after the runs in either direction, as the server orders a missing `last_run_at`. Ties keep project order.+ */+export const queryProjectWorkflowEntries = <Entry extends ProjectWorkflowLibraryEntry>(+ entries: readonly Entry[],+ { order, search, tags }: ProjectWorkflowQuery+): readonly Entry[] => {+ const needle = search.trim().toLocaleLowerCase();+ const wanted = new Set(tags.map((tag) => tag.toLocaleLowerCase()));+ const filtered =+ needle || wanted.size > 0+ ? entries.filter(+ ({ item, tags: entryTags }) =>+ (!needle ||+ item.name.toLocaleLowerCase().includes(needle) ||+ item.description.toLocaleLowerCase().includes(needle) ||+ entryTags.some((tag) => tag.toLocaleLowerCase().includes(needle))) &&+ (wanted.size === 0 || entryTags.some((tag) => wanted.has(tag.toLocaleLowerCase())))+ )+ : entries;+ const sign = order.direction === 'asc' ? 1 : -1;++ switch (order.sort) {+ case 'order':+ return order.direction === 'asc' ? filtered : [...filtered].reverse();+ case 'name':+ return [...filtered].sort((left, right) => sign * compareText(left.item.name, right.item.name));+ case 'updated':+ return [...filtered].sort(+ (left, right) => sign * compareInstants(left.item.updated_at ?? '', right.item.updated_at ?? '')+ );+ case 'lastRun':+ return [...filtered].sort(({ item: { last_run_at: left } }, { item: { last_run_at: right } }) =>+ left && right ? sign * compareInstants(left, right) : Number(!left) - Number(!right)+ );+ }+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.browser.test.tsxindex 2c11bc90cb..0c9e65de8d 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.browser.test.tsx@@ -1,4 +1,5 @@/* eslint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- the probe wires fakes directly */+import type * as WorkflowApi from '@features/workflow/data/api';import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';import { workflowFitViewRequestStore } from '@features/workflow/ui/editor/flowInstanceStore';@@ -31,7 +32,9 @@ vi.mock('@features/identity', async (importOriginal) => ({useAuthSession: () => identity.session,}));-vi.mock('@features/workflow/queries', () => ({+vi.mock('@features/workflow/queries', async () => ({+ isBundledLibraryWorkflowId: (await vi.importActual<typeof WorkflowApi>('@features/workflow/data/api'))+ .isBundledLibraryWorkflowId,getLibraryWorkflowRecordCached: (workflowId: string) => {library.beforeAnswer();return library.getLibraryWorkflowRecordCached(workflowId);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useWorkflowLibraryEntryActions.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/useWorkflowLibraryEntryActions.tsxnew file mode 100644index 0000000000..2540ac8cf3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useWorkflowLibraryEntryActions.tsx@@ -0,0 +1,379 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type { WorkflowLibraryListItem } from '@features/workflow/queries';++import { getWorkflowRecordCategory } from '@features/workflow/data/api';+import {+ createLibraryWorkflow,+ deleteLibraryWorkflow,+ getLibraryWorkflowCached,+ getLibraryWorkflowRecord,+ getLibraryWorkflowRecordCached,+ invalidateWorkflowLibraryCache,+ updateLibraryWorkflow,+} from '@features/workflow/queries';+import { useWorkflowGraphPreview, useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';+import { parseWorkflowJson } from '@features/workflow/utility';+import { downloadText } from '@platform/browser/downloadBlob';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';+import { MenuActionItem } from '@platform/ui/Menu';+import { RenameDialog } from '@platform/ui/RenameDialog';+import { CopyIcon, DownloadIcon, GitForkIcon, PencilIcon, Trash2Icon, WorkflowIcon } from 'lucide-react';+import { useCallback, useMemo, useRef, useState, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { findProjectCopiesOf } from './projectWorkflowEntries';++/**+ * Workflows whose duplicate is in flight. One guard serves every surface that offers Duplicate (the rail and a card's+ * menu), so one workflow gets one copy per press, and a pending copy of one workflow leaves the others free.+ */+export interface WorkflowLibraryDuplicateGuard {+ pendingIds: ReadonlySet<string>;+ /** False when that workflow's duplicate is already in flight. */+ begin: (workflowId: string) => boolean;+ end: (workflowId: string) => void;+}++/** Owned by the surface that hosts every Duplicate of a view: the template panes. */+export const useWorkflowLibraryDuplicateGuard = (): WorkflowLibraryDuplicateGuard => {+ const [pendingIds, setPendingIds] = useState<ReadonlySet<string>>(() => new Set());+ // The ref answers a second press before the first press's render lands.+ const pendingRef = useRef(new Set<string>());+ const begin = useCallback((workflowId: string) => {+ if (pendingRef.current.has(workflowId)) {+ return false;+ }++ pendingRef.current.add(workflowId);+ setPendingIds(new Set(pendingRef.current));+ return true;+ }, []);+ const end = useCallback((workflowId: string) => {+ pendingRef.current.delete(workflowId);+ setPendingIds(new Set(pendingRef.current));+ }, []);++ return useMemo(() => ({ begin, end, pendingIds }), [begin, end, pendingIds]);+};++export interface WorkflowLibraryEntryActionsOptions {+ duplicateGuard: WorkflowLibraryDuplicateGuard;+ /** The workflow the actions act on: the rail's selection, or the card a context menu was raised on. */+ entry: WorkflowLibraryEntry | null;+ /** Whether the account may not rename or delete `entry` (`getLibraryEntryAccess`); the server still enforces. */+ isReadOnly: boolean;+ /** The project's workflows, so Open can say it will ask about existing copies. */+ projectWorkflows: readonly ProjectWorkflowEntry[];+ /** The shell closes the library when a fork takes the user to a new project. */+ onClose: () => void;+ /** Receives the deleted workflow's id. */+ onDeleted: (workflowId: string) => void;+ /** Carries the copy's id so the shell can select it once the list refreshes. */+ onDuplicated: (workflowId: string) => void;+ /** Adds the first copy, or asks what to do when the project already holds one. */+ onOpen: (item: WorkflowLibraryListItem) => void;+}++export interface WorkflowLibraryEntryActions {+ /** The menu items: Open, Duplicate, Fork, Download JSON and, for the account's own templates, Rename and Delete. */+ actionItems: ReactNode;+ /** The rename and delete dialogs the items open; render them outside anything a delete empties. */+ dialogs: ReactNode;+ open: () => void;+ /** "Open…" once the project holds a copy, since opening then asks what to do (`planLibraryWorkflowOpen`). */+ openLabel: string;+ projectCopies: readonly ProjectWorkflowEntry[];+}++/**+ * The workflow a dialog was opened for, and its name then. Write access was checked when it opened; the dialog+ * answers to this target alone, so a refresh that drops the entry neither hides it nor leaves it to reappear later.+ */+interface DialogTarget {+ name: string;+ workflowId: string;+}++const toFileSlug = (name: string): string => name.trim().replaceAll(/\s+/g, '-').toLowerCase() || 'workflow';++/**+ * One library workflow's actions and the dialogs they open. Every action reads the record by id and revision, so it+ * acts on `entry` whether or not it is the selection; each caller (the detail rail, a card's context menu) owns its+ * own instance, and with it its own rename and delete dialogs.+ */+export const useWorkflowLibraryEntryActions = ({+ duplicateGuard,+ entry,+ isReadOnly,+ projectWorkflows,+ onClose,+ onDeleted,+ onDuplicated,+ onOpen,+}: WorkflowLibraryEntryActionsOptions): WorkflowLibraryEntryActions => {+ const { t } = useTranslation();+ const notify = useWorkflowNotifications();+ const { openDocumentInNewProject } = useWorkflowGraphPreview();+ // Captured on request: a delete moves the selection, or empties the rail, before its dialog closes, and a list+ // refresh can drop a context menu's target while a dialog it opened is still up.+ const [deleteTarget, setDeleteTarget] = useState<DialogTarget | null>(null);+ const [renameTarget, setRenameTarget] = useState<DialogTarget | null>(null);++ const item = entry?.item ?? null;+ const projectCopies = useMemo(+ () => (item ? findProjectCopiesOf(projectWorkflows, item.workflow_id) : []),+ [item, projectWorkflows]+ );+ const hasCopies = projectCopies.length > 0;+ const openLabel = hasCopies ? t('workflowLibrary.openWithEllipsis') : t('workflowLibrary.open');++ const open = useCallback(() => {+ if (item) {+ onOpen(item);+ }+ }, [item, onOpen]);++ /** Duplicate the library record directly without loading or modifying the active project graph. */+ const duplicate = useCallback(async () => {+ // Guard until the copy exists, including copies landing outside the visible category.+ if (!item || !duplicateGuard.begin(item.workflow_id)) {+ return;+ }++ const owner = captureAccountScope();++ try {+ const raw = await getLibraryWorkflowCached(item.workflow_id, {+ expectedRevision: item.revision,+ signal: owner.signal,+ });++ assertAccountScopeCurrent(owner);++ const { id: _id, ...copy } = raw;+ const meta = typeof copy.meta === 'object' && copy.meta !== null ? (copy.meta as Record<string, unknown>) : {};+ const workflowId = await createLibraryWorkflow(+ {+ ...copy,+ // A copy of a default is still the user's own workflow.+ meta: { ...meta, category: 'user' },+ name: t('workflowLibrary.duplicateName', { name: item.name || t('workflowLibrary.untitled') }),+ },+ owner.signal+ );++ assertAccountScopeCurrent(owner);+ invalidateWorkflowLibraryCache();+ // The copy is forced into the user category, so from the Browse tab it+ // lands out of sight — the notice is the only thing that says it worked.+ notify.success(t('workflowLibrary.duplicated'));+ onDuplicated(workflowId);+ } catch (error) {+ if (isAccountScopeCurrent(owner)) {+ notify.error(t('workflowLibrary.duplicateFailed'), getApiErrorMessage(error, t('common.unknownError')));+ }+ } finally {+ duplicateGuard.end(item.workflow_id);+ }+ }, [duplicateGuard, item, notify, onDuplicated, t]);+ const handleDuplicate = useCallback(() => void duplicate(), [duplicate]);++ const openRename = useCallback(() => {+ if (item && !isReadOnly) {+ setRenameTarget({ name: item.name || t('workflowLibrary.untitled'), workflowId: item.workflow_id });+ }+ }, [isReadOnly, item, t]);+ const closeRename = useCallback(() => setRenameTarget(null), []);+ // A rename is a content write at the record's current revision: the live record, never a cached one, is the base.+ const submitRename = useCallback(+ async (nextName: string) => {+ if (!renameTarget) {+ return;+ }++ const owner = captureAccountScope();+ const { workflowId } = renameTarget;++ try {+ const record = await getLibraryWorkflowRecord(workflowId, owner.signal);++ assertAccountScopeCurrent(owner);+ await updateLibraryWorkflow(+ workflowId,+ { ...record.workflow, name: nextName },+ { expectedRevision: record.revision, signal: owner.signal }+ );+ assertAccountScopeCurrent(owner);+ invalidateWorkflowLibraryCache(workflowId);+ notify.success(t('workflowLibrary.renamed'));+ } catch (error) {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ notify.error(t('workflowLibrary.renameFailed'), getApiErrorMessage(error, t('common.unknownError')));+ // Rejecting keeps the dialog, and the typed name, open for another try.+ throw error;+ }+ },+ [notify, renameTarget, t]+ );++ const fork = useCallback(async () => {+ if (!item) {+ return;+ }++ const owner = captureAccountScope();++ try {+ const record = await getLibraryWorkflowRecordCached(item.workflow_id, {+ expectedRevision: item.revision,+ signal: owner.signal,+ });++ assertAccountScopeCurrent(owner);++ const { document } = parseWorkflowJson({ ...record.workflow, id: record.workflow_id });++ // The port creates and activates a fresh project first, so the project+ // the library was opened from is left exactly as it was.+ openDocumentInNewProject(document, item.name, {+ libraryWorkflowId: record.workflow_id,+ ...(getWorkflowRecordCategory(record) === 'user' ? { ownerUserId: record.user_id } : {}),+ revision: record.revision,+ });+ onClose();+ } catch (error) {+ if (isAccountScopeCurrent(owner)) {+ notify.error(t('workflowLibrary.loadFailed'), getApiErrorMessage(error, t('common.unknownError')));+ }+ }+ }, [item, notify, onClose, openDocumentInNewProject, t]);+ const handleFork = useCallback(() => void fork(), [fork]);++ const download = useCallback(async () => {+ if (!item) {+ return;+ }++ const owner = captureAccountScope();++ try {+ const raw = await getLibraryWorkflowCached(item.workflow_id, {+ expectedRevision: item.revision,+ signal: owner.signal,+ });++ assertAccountScopeCurrent(owner);+ downloadText(JSON.stringify(raw, null, 2), `${toFileSlug(item.name)}.json`, 'application/json');+ } catch (error) {+ if (isAccountScopeCurrent(owner)) {+ notify.error(t('workflowLibrary.loadFailed'), getApiErrorMessage(error, t('common.unknownError')));+ }+ }+ }, [item, notify, t]);+ const handleDownload = useCallback(() => void download(), [download]);++ const openDeleteConfirm = useCallback(() => {+ if (item && !isReadOnly) {+ setDeleteTarget({ name: item.name || t('workflowLibrary.untitled'), workflowId: item.workflow_id });+ }+ }, [isReadOnly, item, t]);+ const closeDeleteConfirm = useCallback(() => setDeleteTarget(null), []);+ const confirmDelete = useCallback(async () => {+ if (!deleteTarget) {+ return;+ }++ const owner = captureAccountScope();+ const { workflowId } = deleteTarget;++ try {+ await deleteLibraryWorkflow(workflowId, owner.signal);++ assertAccountScopeCurrent(owner);+ invalidateWorkflowLibraryCache();+ onDeleted(workflowId);+ } catch (error) {+ if (isAccountScopeCurrent(owner)) {+ notify.error(t('workflowLibrary.deleteFailed'), getApiErrorMessage(error, t('common.unknownError')));+ }+ }+ }, [deleteTarget, notify, onDeleted, t]);++ // Bundled defaults and other accounts' templates are not the account's to rename or delete.+ const canWrite = item !== null && !isReadOnly;+ const actionItems = (+ <>+ <MenuActionItem icon={WorkflowIcon} label={openLabel} value="open" onSelect={open} />+ <MenuActionItem+ icon={CopyIcon}+ disabled={item !== null && duplicateGuard.pendingIds.has(item.workflow_id)}+ label={t('workflowLibrary.duplicate')}+ value="duplicate"+ onSelect={handleDuplicate}+ />+ <MenuActionItem+ icon={GitForkIcon}+ label={t('workflowLibrary.forkIntoProject')}+ value="fork-into-project"+ onSelect={handleFork}+ />+ <MenuActionItem+ icon={DownloadIcon}+ label={t('workflowLibrary.downloadJson')}+ value="download-json"+ onSelect={handleDownload}+ />+ {canWrite ? (+ <MenuActionItem+ icon={PencilIcon}+ label={t('workflowLibrary.renameWithEllipsis')}+ value="rename"+ onSelect={openRename}+ />+ ) : null}+ {canWrite ? (+ <MenuActionItem+ icon={Trash2Icon}+ label={t('workflowLibrary.delete')}+ tone="danger"+ value="delete"+ onSelect={openDeleteConfirm}+ />+ ) : null}+ </>+ );++ const dialogs = (+ <>+ <RenameDialog+ initialName={renameTarget?.name ?? ''}+ isOpen={renameTarget !== null}+ label={t('workflowLibrary.templateName')}+ submitLabel={t('workflowLibrary.rename')}+ title={t('workflowLibrary.renameTemplateTitle')}+ onClose={closeRename}+ onSubmit={submitRename}+ />+ <ConfirmDialog+ body={t('workflowLibrary.deleteConfirmBody', { name: deleteTarget?.name ?? '' })}+ confirmLabel={t('workflowLibrary.delete')}+ isOpen={deleteTarget !== null}+ title={t('workflowLibrary.deleteConfirmTitle')}+ onClose={closeDeleteConfirm}+ onConfirm={confirmDelete}+ />+ </>+ );++ return { actionItems, dialogs, open, openLabel, projectCopies };+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryCollection.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryCollection.tsxnew file mode 100644index 0000000000..9ee906e32f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryCollection.tsx@@ -0,0 +1,115 @@+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';++import { loadWorkflowLibraryRange, setWorkflowLibraryVisibleDemand } from '@features/workflow/data/libraryBrowseStore';+import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import { useMountEffect } from '@platform/react/useMountEffect';+import { useMemo, useState } from 'react';++/**+ * What the grid and the list layouts share over one collection: duplicate-safe entries, the templates the project+ * holds copies of, and the server-window demand for the positions on screen.+ */++const NO_LINKED_TEMPLATES: ReadonlySet<string> = new Set();++/** Keep duplicate server identities from corrupting card and row reconciliation. */+export const dedupeWorkflowLibraryEntries = (entries: readonly WorkflowLibraryEntry[]): WorkflowLibraryEntry[] => {+ const seen = new Set<string>();+ const unique: WorkflowLibraryEntry[] = [];++ for (const entry of entries) {+ if (!seen.has(entry.item.workflow_id)) {+ seen.add(entry.item.workflow_id);+ unique.push(entry);+ }+ }++ return unique;+};++/** The library templates the project holds copies of, as one string so unrelated project edits keep it equal. */+const selectLinkedTemplateKey = (project: { workflows: readonly { source?: { libraryWorkflowId: string } }[] }) =>+ project.workflows+ .flatMap((workflow) => (workflow.source ? [workflow.source.libraryWorkflowId] : []))+ .sort()+ .join('\n');++/** Library templates the project holds a copy of; the project's own collection marks none. */+export const useLinkedLibraryTemplates = (isProjectCollection: boolean): ReadonlySet<string> => {+ const linkedTemplateKey = useWorkflowProjectSelector(selectLinkedTemplateKey);++ return useMemo(+ () => (isProjectCollection || !linkedTemplateKey ? NO_LINKED_TEMPLATES : new Set(linkedTemplateKey.split('\n'))),+ [isProjectCollection, linkedTemplateKey]+ );+};++export interface WorkflowLibraryDemandRange {+ /** First and last server positions to keep resident, overscan included. */+ first: number;+ last: number;+ /** The positions on screen, which enrichment reaches before either overscan edge. */+ visibleFirst: number;+ visibleLast: number;+}++/** Resident identities in the range: visible ones first, so the bounded enrichment slots reach them before overscan. */+export const getWorkflowLibraryDemandIds = (+ entries: readonly WorkflowLibraryEntry[],+ startIndex: number,+ { first, last, visibleFirst, visibleLast }: WorkflowLibraryDemandRange+): string[] => {+ const visible: string[] = [];+ const overscan: string[] = [];++ for (const [index, entry] of entries.entries()) {+ const position = startIndex + index;++ if (position >= first && position <= last) {+ const demand = position >= visibleFirst && position <= visibleLast ? visible : overscan;+ demand.push(entry.item.workflow_id);+ }+ }++ return visible.concat(overscan);+};++// Mount leases keep external-store writes out of render and release detail demand when the viewport leaves.+let demandLease = 0;++/**+ * Demands one window: key it by its range and identities, so each change remounts it. The newest mount owns the+ * visible demand; an unmount clears it only if no newer mount took over in the meantime.+ */+export const WorkflowLibraryDemand = ({ ids, start, end }: { ids: readonly string[]; start: number; end: number }) => {+ useMountEffect(() => {+ const lease = ++demandLease;+ setWorkflowLibraryVisibleDemand(ids);+ void loadWorkflowLibraryRange(start, end);+ return () => {+ queueMicrotask(() => {+ if (lease === demandLease) {+ setWorkflowLibraryVisibleDemand([]);+ }+ });+ };+ });+ return null;+};++/**+ * A demand key that stops following its window while the collection is hidden under the preview stage: the demand+ * keeps the positions it showed, so a preview stepping elsewhere in the results does not pull the window back, and+ * showing the collection again demands its window afresh only if that window changed meanwhile.+ */+export const useFrozenWhileHidden = (key: string, isHidden: boolean): string => {+ const [frozenKey, setFrozenKey] = useState<string | null>(null);++ if (isHidden && frozenKey === null) {+ setFrozenKey(key);+ } else if (!isHidden && frozenKey !== null) {+ setFrozenKey(null);+ }++ return (isHidden ? frozenKey : null) ?? key;+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryGridLayout.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryGridLayout.test.tsnew file mode 100644index 0000000000..1804ec67f3--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryGridLayout.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import {+ getWorkflowLibraryCardWidth,+ getWorkflowLibraryGridBounds,+ getWorkflowLibraryGridColumns,+ MAX_GRID_COLUMNS,+} from './workflowLibraryGridLayout';++describe('getWorkflowLibraryGridColumns', () => {+ it('fits as many cards as the size allows, from one to six', () => {+ expect(getWorkflowLibraryGridColumns(0, 'small')).toBe(1);+ expect(getWorkflowLibraryGridColumns(500, 'small')).toBe(3);+ expect(getWorkflowLibraryGridColumns(1000, 'small')).toBe(6);+ expect(getWorkflowLibraryGridColumns(3000, 'small')).toBe(6);+ expect(getWorkflowLibraryGridColumns(1000, 'large')).toBe(4);+ expect(getWorkflowLibraryGridColumns(3000, 'large')).toBe(6);+ });++ it.each([+ ['small', 150],+ ['large', 220],+ ] as const)('never narrows a %s card below %ipx once there is room for two', (size, minimum) => {+ for (let width = 200; width <= 2400; width += 7) {+ const columns = getWorkflowLibraryGridColumns(width, size);++ if (columns > 1) {+ expect(getWorkflowLibraryCardWidth(width, columns)).toBeGreaterThanOrEqual(minimum);+ }+ if (columns < MAX_GRID_COLUMNS) {+ // One more column would not have fitted.+ expect(getWorkflowLibraryCardWidth(width, columns + 1)).toBeLessThan(minimum);+ }+ }+ });+});++describe('getWorkflowLibraryGridBounds', () => {+ it('keeps the spanned rows within 48 enriched identities and, with overscan, 60 resident positions', () => {+ for (let columns = 1; columns <= MAX_GRID_COLUMNS; columns += 1) {+ const { maxViewportRows, overscanRows } = getWorkflowLibraryGridBounds(columns);+ // A viewport capped at R estimated rows spans at most R + 1 rows.+ const spannedRows = maxViewportRows + 1;++ expect(overscanRows).toBeGreaterThanOrEqual(1);+ expect(spannedRows * columns).toBeLessThanOrEqual(48);+ expect((spannedRows + 2 * overscanRows) * columns).toBeLessThanOrEqual(60);+ }+ });++ it('keeps fifteen rows and two overscan rows at three columns, and seven rows with one at six', () => {+ expect(getWorkflowLibraryGridBounds(3)).toEqual({ maxViewportRows: 15, overscanRows: 2 });+ expect(getWorkflowLibraryGridBounds(6)).toEqual({ maxViewportRows: 7, overscanRows: 1 });+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryGridLayout.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryGridLayout.tsnew file mode 100644index 0000000000..e8284affd1--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibraryGridLayout.ts@@ -0,0 +1,59 @@+import {+ WORKFLOW_LIBRARY_ENRICHMENT_DEMAND,+ WORKFLOW_LIBRARY_METADATA_WINDOW,+} from '@features/workflow/data/libraryBrowseStore';++import type { WorkflowLibraryCardSize } from './workflowThumbnail';++/**+ * Column count and virtualizer bounds for the library grid. The browse store retains at most 60 consecutive metadata+ * positions and enriches at most 48 demanded identities, visible cards first (`libraryBrowseStore.ts`); every+ * column count must keep the rows a capped viewport can show inside both.+ */++/** The tallest viewport, in estimated rows, at one to three columns. */+const MAX_VIEWPORT_ROWS = 15;++export const MAX_GRID_COLUMNS = 6;+/** Space between cards, horizontally and below each row (Chakra `3`). */+export const GRID_GAP_PX = 12;+/** The grid's end padding beside the scrollbar (Chakra `2`). */+export const GRID_END_PADDING_PX = 8;++const MIN_CARD_WIDTH: Record<WorkflowLibraryCardSize, number> = { large: 220, small: 150 };++/** As many columns as fit at the size's minimum card width, from one up to six. */+export const getWorkflowLibraryGridColumns = (viewportWidth: number, size: WorkflowLibraryCardSize): number =>+ Math.max(+ 1,+ Math.min(+ MAX_GRID_COLUMNS,+ Math.floor((viewportWidth - GRID_END_PADDING_PX + GRID_GAP_PX) / (MIN_CARD_WIDTH[size] + GRID_GAP_PX))+ )+ );++export const getWorkflowLibraryCardWidth = (viewportWidth: number, columns: number): number =>+ Math.max(1, (viewportWidth - GRID_END_PADDING_PX - GRID_GAP_PX * (columns - 1)) / columns);++export interface WorkflowLibraryGridBounds {+ /** Rows mounted and demanded on either side of the viewport. */+ overscanRows: number;+ /** The viewport's height cap, in estimated rows; it can span one more, partially visible, row. */+ maxViewportRows: number;+}++/**+ * Up to four columns keep two overscan rows; five and six keep one so the viewport still spans several rows. With+ * `maxViewportRows` R and overscan O at C columns, (R + 1) × C visible cards fit the demand bound and+ * (R + 1 + 2O) × C positions fit the metadata window: six columns allow 7 rows (48 visible, 60 resident).+ */+export const getWorkflowLibraryGridBounds = (columns: number): WorkflowLibraryGridBounds => {+ const overscanRows = columns >= 5 ? 1 : 2;+ const maxViewportRows = Math.min(+ MAX_VIEWPORT_ROWS,+ Math.floor(WORKFLOW_LIBRARY_ENRICHMENT_DEMAND / columns) - 1,+ Math.floor(WORKFLOW_LIBRARY_METADATA_WINDOW / columns) - 1 - 2 * overscanRows+ );++ return { maxViewportRows, overscanRows };+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowSilhouette.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowSilhouette.test.tsnew file mode 100644index 0000000000..034a84c7df--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowSilhouette.test.ts@@ -0,0 +1,69 @@+import type { WorkflowNode } from '@features/workflow/core/types';++import { createProjectGraph } from '@features/workflow/utility';+import { describe, expect, it } from 'vitest';++import { getWorkflowSilhouetteImage, layoutWorkflowSilhouette, MAX_SILHOUETTE_RECTS } from './workflowSilhouette';++const notes = (id: string, x: number, y: number): WorkflowNode => ({+ data: { label: '', notes: '' },+ id,+ position: { x, y },+ type: 'notes',+});++describe('layoutWorkflowSilhouette', () => {+ it('draws nothing for a document without positioned nodes', () => {+ expect(layoutWorkflowSilhouette([])).toEqual([]);+ expect(layoutWorkflowSilhouette([notes('a', Number.NaN, 0)])).toEqual([]);+ });++ it('fits the graph inside the padded 3:2 well, centred, keeping node proportions', () => {+ // Two 320×160 notes 640 apart: a 960×160 graph whose width binds, at 0.76 of the well's 1.5 units.+ const [left, right] = layoutWorkflowSilhouette([notes('a', 0, 0), notes('b', 640, 0)]);++ expect(left!.x).toBeCloseTo(0.12);+ expect(left!.width).toBeCloseTo(0.25333);+ expect(left!.y).toBeCloseTo(0.405);+ expect(left!.height).toBeCloseTo(0.19);+ expect(right!.x + right!.width).toBeCloseTo(0.88);+ expect(right!.y).toBeCloseTo(left!.y);+ });++ it('keeps a lone node from filling the well', () => {+ const [rect] = layoutWorkflowSilhouette([notes('a', 5000, -300)]);++ expect(rect!.width).toBeCloseTo(0.304);+ expect(rect!.x + rect!.width / 2).toBeCloseTo(0.5);+ expect(rect!.y + rect!.height / 2).toBeCloseTo(0.5);+ });++ it('draws a bounded, order-independent subset of a large graph inside the well', () => {+ const nodes = Array.from({ length: 500 }, (_, index) =>+ notes(`n${index}`, (index % 25) * 400, Math.floor(index / 25) * 200)+ );+ const rects = layoutWorkflowSilhouette(nodes);++ expect(rects).toHaveLength(MAX_SILHOUETTE_RECTS);+ expect(layoutWorkflowSilhouette([...nodes].reverse())).toEqual(rects);+ for (const rect of rects) {+ expect(rect.x).toBeGreaterThanOrEqual(0);+ expect(rect.y).toBeGreaterThanOrEqual(0);+ expect(rect.x + rect.width).toBeLessThanOrEqual(1);+ expect(rect.y + rect.height).toBeLessThanOrEqual(1);+ }+ // The subset spans the graph rather than clustering at one edge.+ expect(Math.min(...rects.map((rect) => rect.x))).toBeCloseTo(0.12);+ expect(Math.max(...rects.map((rect) => rect.x))).toBeGreaterThan(0.7);+ });++ it('draws a document once, as one SVG data URI holding a rect per drawn node', () => {+ const document = { ...createProjectGraph('silhouette'), nodes: [notes('a', 0, 0), notes('b', 640, 0)] };+ const image = getWorkflowSilhouetteImage(document);++ expect(image?.rectCount).toBe(2);+ expect(decodeURIComponent(image!.url).match(/<rect /g)).toHaveLength(2);+ expect(getWorkflowSilhouetteImage(document)).toBe(image);+ expect(getWorkflowSilhouetteImage(createProjectGraph('empty'))).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowSilhouette.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowSilhouette.tsnew file mode 100644index 0000000000..5d4b3d36ac--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowSilhouette.ts@@ -0,0 +1,162 @@+import type { ProjectGraphState, WorkflowNode } from '@features/workflow/core/types';++/**+ * A workflow's shape for a thumbnail well that has no image: one rect per node, in fractions of a 3:2 well. Node+ * documents carry positions but no measured sizes, so each node kind gets a nominal size (invocation height grows+ * with its inputs). Large graphs keep their full extent but draw an evenly spaced, deterministic subset of nodes.+ */++export interface WorkflowSilhouetteRect {+ /** Left edge, as a fraction of the well's width. */+ x: number;+ /** Top edge, as a fraction of the well's height. */+ y: number;+ width: number;+ height: number;+}++/** Enough to read as a graph at card size; more only adds paint cost. */+export const MAX_SILHOUETTE_RECTS = 24;++/** The well the rects are laid out in, matching WORKFLOW_THUMBNAIL_ASPECT_RATIO. */+const WELL_ASPECT_RATIO = 3 / 2;+/** Space kept clear on every side, as a fraction of each well dimension. */+const PADDING = 0.12;+/** A single node must not fill the well. */+const MAX_SCALE_NODE_WIDTHS = 2.5;+/** Rects smaller than this vanish at card size. */+const MIN_RECT_FRACTION = 0.02;++const NOMINAL_NODE_WIDTH = 320;++const getNominalSize = (node: WorkflowNode): { width: number; height: number } => {+ switch (node.type) {+ case 'invocation':+ return {+ height: 72 + 28 * Math.min(Object.keys(node.data.inputs).length, 12),+ width: NOMINAL_NODE_WIDTH,+ };+ case 'notes':+ return { height: 160, width: NOMINAL_NODE_WIDTH };+ case 'current_image':+ return { height: NOMINAL_NODE_WIDTH, width: NOMINAL_NODE_WIDTH };+ case 'connector':+ return { height: 40, width: 40 };+ }+};++const isFinitePosition = (node: WorkflowNode): boolean =>+ Number.isFinite(node.position.x) && Number.isFinite(node.position.y);++/** Every `step`-th node in reading order, so the subset spreads across the graph and repeats for the same input. */+const sampleNodes = (nodes: readonly WorkflowNode[]): readonly WorkflowNode[] => {+ if (nodes.length <= MAX_SILHOUETTE_RECTS) {+ return nodes;+ }++ const ordered = [...nodes].sort(+ (left, right) =>+ left.position.x - right.position.x ||+ left.position.y - right.position.y ||+ (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)+ );+ const step = ordered.length / MAX_SILHOUETTE_RECTS;++ return Array.from({ length: MAX_SILHOUETTE_RECTS }, (_, index) => ordered[Math.floor(index * step)]!);+};++/** Empty when the document has no positioned nodes; callers then show their own placeholder. */+export const layoutWorkflowSilhouette = (nodes: readonly WorkflowNode[]): WorkflowSilhouetteRect[] => {+ const positioned = nodes.filter(isFinitePosition);++ if (positioned.length === 0) {+ return [];+ }++ let minX = Number.POSITIVE_INFINITY;+ let minY = Number.POSITIVE_INFINITY;+ let maxX = Number.NEGATIVE_INFINITY;+ let maxY = Number.NEGATIVE_INFINITY;++ for (const node of positioned) {+ const { height, width } = getNominalSize(node);++ minX = Math.min(minX, node.position.x);+ minY = Math.min(minY, node.position.y);+ maxX = Math.max(maxX, node.position.x + width);+ maxY = Math.max(maxY, node.position.y + height);+ }++ // Work in units where the well is WELL_ASPECT_RATIO wide and 1 high, then divide back into fractions.+ const availableWidth = WELL_ASPECT_RATIO * (1 - 2 * PADDING);+ const availableHeight = 1 - 2 * PADDING;+ const graphWidth = maxX - minX;+ const graphHeight = maxY - minY;+ const scale = Math.min(+ availableWidth / graphWidth,+ availableHeight / graphHeight,+ availableWidth / (MAX_SCALE_NODE_WIDTHS * NOMINAL_NODE_WIDTH)+ );+ const offsetX = (WELL_ASPECT_RATIO - graphWidth * scale) / 2;+ const offsetY = (1 - graphHeight * scale) / 2;++ return sampleNodes(positioned).map((node) => {+ const { height, width } = getNominalSize(node);++ return {+ height: Math.max(MIN_RECT_FRACTION, height * scale),+ width: Math.max(MIN_RECT_FRACTION, (width * scale) / WELL_ASPECT_RATIO),+ x: (offsetX + (node.position.x - minX) * scale) / WELL_ASPECT_RATIO,+ y: offsetY + (node.position.y - minY) * scale,+ };+ });+};++/** The image's coordinate space: the 3:2 well, 150 by 100 units. */+const IMAGE_WIDTH = 150;+const IMAGE_HEIGHT = 100;+/** A mid grey at low opacity reads on both the light and the dark well; a data URI cannot use theme variables. */+const RECT_STYLE = 'fill="rgb(140 144 156 / 0.16)" stroke="rgb(140 144 156 / 0.42)" stroke-width="0.6"';++export interface WorkflowSilhouetteImage {+ /** A CSS `url()` value holding the silhouette as an SVG data URI. */+ url: string;+ rectCount: number;+}++const round = (value: number) => Math.round(value * 10) / 10;++/** Absent when the document has nothing to draw. */+export const toWorkflowSilhouetteImage = (rects: readonly WorkflowSilhouetteRect[]): WorkflowSilhouetteImage | null => {+ if (rects.length === 0) {+ return null;+ }++ const shapes = rects+ .map(+ (rect) =>+ `<rect x="${round(rect.x * IMAGE_WIDTH)}" y="${round(rect.y * IMAGE_HEIGHT)}" width="${round(rect.width * IMAGE_WIDTH)}" height="${round(rect.height * IMAGE_HEIGHT)}" rx="1.5"/>`+ )+ .join('');+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${IMAGE_WIDTH} ${IMAGE_HEIGHT}" preserveAspectRatio="none"><g ${RECT_STYLE}>${shapes}</g></svg>`;++ return { rectCount: rects.length, url: `url("data:image/svg+xml,${encodeURIComponent(svg)}")` };+};++/**+ * One image per parsed document. A document object stands for one revision of one workflow (an edit or a newer+ * revision parses a new one), and the cache lets go of it with the document, so a card scrolling back into view or+ * re-rendering never lays the graph out again.+ */+const images = new WeakMap<ProjectGraphState, WorkflowSilhouetteImage | null>();++export const getWorkflowSilhouetteImage = (document: ProjectGraphState): WorkflowSilhouetteImage | null => {+ let image = images.get(document);++ if (image === undefined) {+ image = toWorkflowSilhouetteImage(layoutWorkflowSilhouette(document.nodes));+ images.set(document, image);+ }++ return image;+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowThumbnail.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowThumbnail.tsxindex 58655a4b7f..291882c7b2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowThumbnail.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowThumbnail.tsx@@ -6,12 +6,18 @@ import { createContext, use } from 'react';/** Every workflow thumbnail well is 3:2, whatever the image inside it. */export const WORKFLOW_THUMBNAIL_ASPECT_RATIO = 3 / 2;+/** How large the library's cards are: `small` packs more per row, `large` favours the cover image. */+export type WorkflowLibraryCardSize = 'small' | 'large';+/*** The account's Fill/Fit choice for every thumbnail under the library dialog. A context rather than a store read per* card: one subscription in the dialog, and surfaces mounted without it show the default fill.*/export const WorkflowThumbnailFitContext = createContext<WorkflowThumbnailFit>('cover');+/** The account's card-size choice for every grid under the library dialog; surfaces mounted without it show small. */+export const WorkflowLibraryCardSizeContext = createContext<WorkflowLibraryCardSize>('small');+/** A thumbnail filling its well, cropped (`cover`) or letterboxed (`contain`) as the account chose. */export const WorkflowThumbnailImage = ({ onError, src }: { onError: () => void; src: string | null | undefined }) => {const fit = use(WorkflowThumbnailFitContext);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/modelRequirementStatus.ts b/invokeai/frontend/webv2/src/features/workflow/ui/modelRequirementStatus.tsnew file mode 100644index 0000000000..5ac5b2778c--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/modelRequirementStatus.ts@@ -0,0 +1,104 @@+import type { ModelConfig, StarterModel } from '@features/models';+import type { ModelRequirementStatus } from '@features/workflow/core/modelRequirements';+import type { WorkflowPreviewModel } from '@features/workflow/core/workflowPreview';+import type { ElementType } from 'react';++import {+ ensureModelsLoaded,+ ensureStartersLoaded,+ useActiveInstallSources,+ useModelsSelector,+ useStartersSelector,+} from '@features/models';+import { resolveWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';+import { useMountEffect } from '@platform/react/useMountEffect';+import { CheckIcon, DownloadIcon, TriangleAlertIcon } from 'lucide-react';+import { useMemo } from 'react';++/**+ * Where a workflow's model requirements stand against this server's catalog, for every view that lists them: the+ * library's rail and badges, and the preview's graph and Inputs view.+ */++const EMPTY_STARTERS: readonly StarterModel[] = [];+const NO_NODES: ReadonlySet<string> = new Set();++const selectInstalledModels = (snapshot: { models: ModelConfig[] }): readonly ModelConfig[] => snapshot.models;+const selectStarterModels = (snapshot: {+ response: { starter_models: StarterModel[] } | null;+}): readonly StarterModel[] => snapshot.response?.starter_models ?? EMPTY_STARTERS;++interface StatusPresentation {+ color: string;+ icon: ElementType | null;+ labelKey: string;+}++/** How each requirement state reads wherever a requirement is listed: the rail, and the preview's Inputs view. */+export const REQUIREMENT_STATUS_PRESENTATION: Record<ModelRequirementStatus, StatusPresentation> = {+ // Amber, per the mock, is the "you can fix this" signal and nothing else.+ installable: { color: 'fg.warning', icon: DownloadIcon, labelKey: 'workflowLibrary.requirementInstallable' },+ installed: { color: 'fg.muted', icon: CheckIcon, labelKey: 'workflowLibrary.requirementInstalled' },+ installing: { color: 'fg.muted', icon: null, labelKey: 'workflowLibrary.requirementInstalling' },+ unresolvable: { color: 'fg.muted', icon: TriangleAlertIcon, labelKey: 'workflowLibrary.requirementMissing' },+};++export interface ModelRequirementDeps {+ installedModels: readonly ModelConfig[];+ starterModels: readonly StarterModel[];+ activeInstallSources: ReadonlySet<string>;+}++/**+ * The catalog as far as it is loaded, without loading any of it: for the preview, which shows requirements only where+ * the surface around it (the library's rail) has loaded what they need.+ */+export const useLoadedModelRequirementDeps = (): ModelRequirementDeps => {+ const installedModels = useModelsSelector(selectInstalledModels);+ const starterModels = useStartersSelector(selectStarterModels);+ const activeInstallSources = useActiveInstallSources();++ return useMemo(+ () => ({ activeInstallSources, installedModels, starterModels }),+ [activeInstallSources, installedModels, starterModels]+ );+};++/** The catalog for the library's rail and badges, loading the installed and starter models as they mount. */+export const useModelRequirementDeps = (): ModelRequirementDeps => {+ useMountEffect(() => {+ void ensureModelsLoaded();+ ensureStartersLoaded();+ });++ return useLoadedModelRequirementDeps();+};++/**+ * The preview's nodes that need a model, as the rail counts one, from the catalog as loaded: a model a node names, or the kind an empty field asks+ * for, that is not installed and can be (not one installing now, nor one before the catalog has said either way).+ */+export const useNodesNeedingModel = (model: WorkflowPreviewModel | null): ReadonlySet<string> => {+ const deps = useLoadedModelRequirementDeps();++ return useMemo(() => {+ if (!model) {+ return NO_NODES;+ }++ const ids = new Set<string>();++ for (const node of model.nodes.values()) {+ if (+ node.modelRequirements.length > 0 &&+ resolveWorkflowModelRequirements(node.modelRequirements, deps).some(+ (requirement) => requirement.status === 'installable'+ )+ ) {+ ids.add(node.id);+ }+ }++ return ids.size > 0 ? ids : NO_NODES;+ }, [deps, model]);+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.test.tsnew file mode 100644index 0000000000..7cf46d6764--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest';++import { flowThemeCss } from './graph-preview/flowTheme';+import { getWorkflowNodeAppearance, getWorkflowNodeHandleStyle, WORKFLOW_NODE_DIAMOND_ROTATION } from './nodeChrome';++describe('getWorkflowNodeAppearance', () => {+ it('draws a failed node exactly like an invalid one, selected or not', () => {+ for (const selected of [false, true]) {+ expect(getWorkflowNodeAppearance({ failed: true, selected })).toEqual(+ getWorkflowNodeAppearance({ invalid: true, selected })+ );+ }+ expect(getWorkflowNodeAppearance({ failed: true, selected: true })).toMatchObject({+ border: 'border.error',+ selectionRing: 'border.error',+ tone: 'error',+ });+ });++ it('keeps the outline neutral for a running node and glows instead', () => {+ expect(getWorkflowNodeAppearance({ running: true, selected: false })).toEqual({+ ...getWorkflowNodeAppearance({ selected: false }),+ glows: true,+ });+ });++ it('composes states instead of letting one overwrite another', () => {+ const invalidOutdatedRunning = getWorkflowNodeAppearance({+ invalid: true,+ outdated: true,+ running: true,+ selected: true,+ });++ expect(invalidOutdatedRunning).toEqual({+ border: 'border.error',+ glows: true,+ hoverBorder: expect.stringContaining('border.error'),+ selectionRing: 'border.error',+ tone: 'error',+ });+ // An outdated node keeps its amber in its selection ring and takes a stronger amber under the pointer.+ expect(getWorkflowNodeAppearance({ outdated: true, selected: true })).toEqual({+ border: 'fg.warning',+ glows: false,+ hoverBorder: expect.stringContaining('fg.warning'),+ selectionRing: 'fg.warning',+ tone: 'warning',+ });+ });++ it('gives every tone a hover outline of its own family that differs from its resting outline', () => {+ for (const state of [{ invalid: true }, { failed: true }, { outdated: true }]) {+ const { border, hoverBorder } = getWorkflowNodeAppearance({ ...state, selected: false });++ expect(hoverBorder).not.toBe(border);+ expect(hoverBorder).toContain(border);+ expect(hoverBorder).not.toContain('accent');+ }+ });++ it('turns only a neutral outline accent on hover, and rings only a selected node', () => {+ expect(getWorkflowNodeAppearance({ selected: false })).toEqual({+ border: 'border.emphasized',+ glows: false,+ hoverBorder: 'accent.solid',+ selectionRing: null,+ tone: 'neutral',+ });+ expect(getWorkflowNodeAppearance({ selected: true }).selectionRing).toBe('accent.solid');+ });+});++describe('batch port grab area', () => {+ it('turns back the rotation a batch handle is drawn with, so its grab area stays upright', () => {+ const transform = getWorkflowNodeHandleStyle(+ { batch: true, cardinality: 'COLLECTION', name: 'IntegerField' },+ 'left'+ ).transform;+ const counterRotation = Object.keys(flowThemeCss).find(+ (selector) => selector.includes('::before') && selector.includes('style*=')+ );++ expect(transform).toContain(WORKFLOW_NODE_DIAMOND_ROTATION);+ expect(counterRotation).toBe(`& .react-flow__handle[style*="${WORKFLOW_NODE_DIAMOND_ROTATION}"]::before`);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsxindex 75dd455766..8bae1740fc 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/nodeChrome.tsx@@ -1,11 +1,12 @@-import type { BoxProps, FlexProps } from '@chakra-ui/react';+import type { BoxProps, FlexProps, IconButtonProps } from '@chakra-ui/react';import type { FieldType } from '@features/workflow/contracts';+import type { LucideIcon } from 'lucide-react';import type { CSSProperties, ReactNode } from 'react';-import { Box, Icon } from '@chakra-ui/react';+import { Box, Icon, IconButton, ProgressCircle, Spinner } from '@chakra-ui/react';import { getFieldTypeColor, isModelFieldType } from '@features/workflow/utility';import { Tooltip } from '@platform/ui';-import { CircleAlertIcon, CircleCheckIcon, InfoIcon } from 'lucide-react';+import { CheckIcon, InfoIcon, OctagonXIcon, SquareArrowUpIcon, TriangleAlertIcon } from 'lucide-react';import { createContext, useContext } from 'react';const WorkflowImageExportContext = createContext(false);@@ -22,10 +23,6 @@ export const useIsWorkflowImageExport = () => useContext(WorkflowImageExportCont/** Share node styling across editor, static previews, and form builder to prevent visual drift. */-const NODE_HOVER_RING = '0 0 0 2px {colors.accent.solid/50}, {shadows.md}';-const NODE_RUNNING_RING = '0 0 0 2px {colors.brand.solid/70}, 0 0 10px {colors.brand.solid/50}';-const NODE_SELECTED_RING = '0 0 0 2px {colors.accent.solid}, {shadows.md}';-/** The node body surface. `flowThemeCss` bridges it to `--wb-node-surface` for inline xyflow styles. */export const WORKFLOW_NODE_SURFACE_TOKEN = 'bg.muted';@@ -33,53 +30,145 @@ export const WORKFLOW_NODE_SURFACE_TOKEN = 'bg.muted';export const WORKFLOW_NODE_DENSITY = {bodyPaddingY: '1',headerGap: '2',- headerPaddingEnd: '2',- headerPaddingStart: '2.5',- headerPaddingY: '1.5',+ /** A header's inset from the border to a button at its start or end; the same on both sides. */+ headerButtonInset: '1',+ /** A header's inset from the border to text at its start or end. */+ headerTextInset: '2.5',+ /**+ * A field row's label line: the height of the line that holds the label and its port, which is centred on it, and+ * the label's line height. The browser lays text out on whole pixels in the node's own coordinates, before the flow's+ * zoom, so a shorter line box centred in a taller line starts between pixels and its glyphs round a pixel away from+ * the port; zoomed in, that pixel grows.+ */+ labelLine: '20px',rowPaddingX: '3',rowPaddingY: '0.5',} as const;-/** How the node's last invocation ended, once it is no longer running. */-export type WorkflowNodeOutcome = 'completed' | 'failed';+/**+ * A label's text box, trimmed to its letters' body: from the x-height to the baseline. Centred in its line, it puts the+ * port and any icon beside it on the lowercase letters people read, where the full line box would leave them about a+ * pixel high, because the font's ascent above the letters is larger than its descent below them. Overflow is clipped+ * only horizontally, for an ellipsis, so ascenders and descenders still draw. A browser without `text-box` keeps the+ * line box.+ */+const WORKFLOW_NODE_LABEL_TEXT_BOX_CSS = {+ // A clipped box is not a scroll container, so it shrinks below its text's width only with a zero minimum.+ minW: '0',+ // Horizontal, then vertical.+ overflow: 'clip visible',+ textBox: 'trim-both ex alphabetic',+} as const;+/** A one-line label: the trimmed box, ending in an ellipsis when it is cut short. */+export const WORKFLOW_NODE_LABEL_TEXT_CSS = {+ ...WORKFLOW_NODE_LABEL_TEXT_BOX_CSS,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+} as const;++/**+ * The same for a `MiddleTruncate` label, whose text sits in the spans inside its root. Only the box is trimmed there:+ * the spans keep the component's own white-space and ellipsis, which hold the space at the head and tail's split. The+ * root's overflow is a prop, since it overrides the component's own.+ */+export const WORKFLOW_NODE_SPLIT_LABEL_TEXT_PROPS = {+ css: { '& > span': WORKFLOW_NODE_LABEL_TEXT_BOX_CSS },+ overflow: 'clip visible',+} as const;++/** Independent facts about a node; `getWorkflowNodeAppearance` composes them, so no state overwrites another. */export interface WorkflowNodeChromeState {+ /** A value is missing or invalid, or the node's type is unknown. */invalid?: boolean;+ /** The node's last invocation failed. It is drawn like an invalid node, so it shows when zoomed out. */+ failed?: boolean;/** The node's version differs from its template's; it still runs, so the tint is a warning, not an error. */outdated?: boolean;- outcome?: WorkflowNodeOutcome | null;running?: boolean;selected: boolean;}-const getNodeBorderColor = ({ invalid, outcome, outdated, running }: WorkflowNodeChromeState): string => {- if (invalid) {- return 'red.solid';- }- if (running) {- return 'brand.solid';- }- // A failed run outranks a stale version: the nodes that cannot be updated are the ones most likely to fail.- if (outcome === 'failed') {- return 'border.error';- }- if (outdated) {- return 'border.warning';- }- if (outcome === 'completed') {- return 'fg.success';- }-- return 'border.emphasized';+/** The colour family of a node's outline and header. */+export type WorkflowNodeTone = 'error' | 'neutral' | 'warning';++export interface WorkflowNodeAppearance {+ tone: WorkflowNodeTone;+ border: string;+ /** The outline under the pointer: accent on a neutral node; a toned node takes a stronger step of its own tone. */+ hoverBorder: string;+ /** The selection ring, outside the border, in the node's state colour (accent when neutral); null when unselected. */+ selectionRing: string | null;+ /** The running glow, independent of tone and selection. */+ glows: boolean;+}++// The theme has no `border.warning`; warning borders use the warning foreground.+const TONE_BORDERS: Record<WorkflowNodeTone, string> = {+ error: 'border.error',+ neutral: 'border.emphasized',+ warning: 'fg.warning',};-export const getWorkflowNodeChromeProps = (state: WorkflowNodeChromeState): BoxProps => ({- borderColor: getNodeBorderColor(state),- borderWidth: '1px',- shadow: state.selected ? NODE_SELECTED_RING : state.running ? NODE_RUNNING_RING : 'sm',- transition: 'border-color var(--wb-motion-duration-fast) ease, box-shadow var(--wb-motion-duration-fast) ease',- _hover: state.selected ? undefined : { shadow: NODE_HOVER_RING },-});+/**+ * A tone's hover step: its colour pulled toward the foreground, so it brightens on dark themes and deepens on light+ * ones and always differs from the resting outline.+ */+const getStrongerToneColor = (token: string): string => `color-mix(in oklab, {colors.${token}} 60%, {colors.fg})`;++export const getWorkflowNodeAppearance = ({+ failed,+ invalid,+ outdated,+ running,+ selected,+}: WorkflowNodeChromeState): WorkflowNodeAppearance => {+ const tone: WorkflowNodeTone = invalid || failed ? 'error' : outdated ? 'warning' : 'neutral';+ // A toned node keeps its colour in its selection ring, as legacy drew it, and under the pointer.+ const stateColor = tone === 'neutral' ? 'accent.solid' : TONE_BORDERS[tone];++ return {+ border: TONE_BORDERS[tone],+ glows: Boolean(running),+ hoverBorder: tone === 'neutral' ? 'accent.solid' : getStrongerToneColor(TONE_BORDERS[tone]),+ selectionRing: selected ? stateColor : null,+ tone,+ };+};++/**+ * The surface behind the node, so a ring's gap reads as space between the node and its ring: the canvas inside a flow,+ * the panel outside one (the form builder's cards).+ */+const RING_GAP = 'var(--xy-background-color, {colors.bg.panel})';+const NODE_RUNNING_GLOW = '0 0 0 2px {colors.brand.solid/70}, 0 0 10px {colors.brand.solid/50}';+/**+ * Keyboard focus draws a ring of its own just beyond the selection ring, so focus, selection and tone read at once. It+ * is set from CSS on the flow node's own focus, so focusing a node renders nothing. Every ring stays within 6px of the+ * border, where a port's dot covers it: an edge leaves the dot's outer side, so no ring is drawn across an edge.+ */+const NODE_FOCUS_RING_PROPERTY = '--wb-node-focus-ring';+const NODE_FOCUS_RING = `0 0 0 4px ${RING_GAP}, 0 0 0 6px {colors.fg}`;++export const getWorkflowNodeChromeProps = (state: WorkflowNodeChromeState): BoxProps => {+ const { border, glows, hoverBorder, selectionRing } = getWorkflowNodeAppearance(state);+ // Earlier shadows paint on top: the selection ring over the focus ring's gap, both over the glow.+ const shadows = [+ selectionRing ? `0 0 0 2px ${RING_GAP}, 0 0 0 4px {colors.${selectionRing}}` : null,+ `var(${NODE_FOCUS_RING_PROPERTY}, 0 0 #0000)`,+ glows ? NODE_RUNNING_GLOW : null,+ '{shadows.sm}',+ ];++ return {+ borderColor: border,+ borderWidth: '1px',+ shadow: shadows.filter(Boolean).join(', '),+ transition: 'border-color var(--wb-motion-duration-fast) ease, box-shadow var(--wb-motion-duration-fast) ease',+ _hover: { borderColor: hoverBorder },+ css: { '.react-flow__node:focus-visible &': { [NODE_FOCUS_RING_PROPERTY]: NODE_FOCUS_RING } },+ };+};/** The node surface itself: chrome plus background, radius, and base type size. */export const getWorkflowNodeShellProps = (state: WorkflowNodeChromeState): BoxProps => ({@@ -89,24 +178,81 @@ export const getWorkflowNodeShellProps = (state: WorkflowNodeChromeState): BoxPr...getWorkflowNodeChromeProps(state),});-/** Titled header strip. `roundedBottom` for collapsed nodes where nothing renders beneath it. */-export const getWorkflowNodeHeaderProps = ({ roundedBottom = false }: { roundedBottom?: boolean } = {}): FlexProps => ({+const HEADER_TONES: Record<WorkflowNodeTone, Pick<FlexProps, 'bg' | 'color'>> = {+ error: { bg: 'bg.error', color: 'fg.error' },+ neutral: { bg: 'bg.subtle' },+ warning: { bg: 'bg.warning', color: 'fg.warning' },+};++/**+ * Titled header strip, 30px high, tinted by the node's tone; its title and ghost buttons take the tone's foreground.+ * `roundedBottom` for collapsed nodes where nothing renders beneath it.+ */+export const getWorkflowNodeHeaderProps = ({+ endsWithButton = false,+ roundedBottom = false,+ startsWithButton = false,+ tone = 'neutral',+}: {+ /** The header ends in a ghost button (status, info): it sits as far from the right border as one at the start. */+ endsWithButton?: boolean;+ roundedBottom?: boolean;+ /** The header starts with a ghost button (collapse). */+ startsWithButton?: boolean;+ tone?: WorkflowNodeTone;+} = {}): FlexProps => ({alignItems: 'center',- bg: 'bg.subtle',borderBottomRadius: roundedBottom ? 'lg' : undefined,borderBottomWidth: roundedBottom ? '0' : '1px',borderColor: 'border.subtle',borderTopRadius: 'lg',gap: WORKFLOW_NODE_DENSITY.headerGap,- pe: WORKFLOW_NODE_DENSITY.headerPaddingEnd,- ps: WORKFLOW_NODE_DENSITY.headerPaddingStart,- py: WORKFLOW_NODE_DENSITY.headerPaddingY,+ minH: '1.875rem',+ pe: endsWithButton ? WORKFLOW_NODE_DENSITY.headerButtonInset : WORKFLOW_NODE_DENSITY.headerTextInset,+ ps: startsWithButton ? WORKFLOW_NODE_DENSITY.headerButtonInset : WORKFLOW_NODE_DENSITY.headerTextInset,+ py: '0.5',+ ...HEADER_TONES[tone],});+/** A header tint of the button's own colour, so a red or amber header never gets a grey block. */+const HEADER_BUTTON_FILL = 'color-mix(in oklab, currentColor 14%, transparent)';++/** The header's 22px ghost icon buttons (collapse, status, info), coloured by the header they sit on. */+const WORKFLOW_NODE_HEADER_BUTTON_PROPS = {+ boxSize: '1.375rem',+ color: 'inherit',+ flexShrink: 0,+ minW: '1.375rem',+ p: '0',+ rounded: 'sm',+ size: 'xs',+ variant: 'ghost',+ _expanded: { bg: HEADER_BUTTON_FILL },+ _focusVisible: { bg: HEADER_BUTTON_FILL },+ _hover: { bg: HEADER_BUTTON_FILL },+} as const satisfies IconButtonProps;++/** Marks a field row, and the control or static value inside it, for the body's bottom inset. */+export const WORKFLOW_NODE_FIELD_ROW_ATTRIBUTE = 'data-node-field-row';+export const WORKFLOW_NODE_FIELD_CONTROL_ATTRIBUTE = 'data-node-field-control';++/**+ * When the body ends in a field's control, the space under that control matches the rows' side inset, so the control+ * sits evenly inside the node. Both come from `rowPaddingX`; the last row's bottom padding makes up the difference+ * from the body's own. A body ending in a label-only row keeps its tighter rhythm.+ */+const BODY_LAST_CONTROL_CSS = {+ [`& > [${WORKFLOW_NODE_FIELD_ROW_ATTRIBUTE}]:last-child:has([${WORKFLOW_NODE_FIELD_CONTROL_ATTRIBUTE}], [data-workflow-export-field-value])`]:+ {+ pb: `calc({spacing.${WORKFLOW_NODE_DENSITY.rowPaddingX}} - {spacing.${WORKFLOW_NODE_DENSITY.bodyPaddingY}})`,+ },+};+/** Header supplies the divider. Inferred styles avoid BoxProps direction conflicts when spread into Stack/Flex. */export const getWorkflowNodeBodyProps = ({ roundedBottom = true }: { roundedBottom?: boolean } = {}) => ({bg: WORKFLOW_NODE_SURFACE_TOKEN,borderBottomRadius: roundedBottom ? ('lg' as const) : ('none' as const),+ css: BODY_LAST_CONTROL_CSS,py: WORKFLOW_NODE_DENSITY.bodyPaddingY,});@@ -127,6 +273,9 @@ const getHandleVisual = (type: FieldType) => ({isFilled: type.cardinality === 'SINGLE',});+/** A batch port's diamond: the handle's own rotation, which `flowThemeCss` turns back for the port's grab area. */+export const WORKFLOW_NODE_DIAMOND_ROTATION = 'rotate(45deg)';+/** Inline handle diamonds must retain side-specific xyflow centering before rotation. */export const getWorkflowNodeHandleStyle = (type: FieldType, side: 'left' | 'right'): CSSProperties => {const visual = getHandleVisual(type);@@ -137,7 +286,9 @@ export const getWorkflowNodeHandleStyle = (type: FieldType, side: 'left' | 'righborderRadius: visual.isAngular ? HANDLE_ANGULAR_RADIUS : '50%',boxShadow: `0 0 0 ${HANDLE_RING_WIDTH}px var(--wb-node-surface)`,height: WORKFLOW_NODE_HANDLE_SIZE,- transform: visual.isDiamond ? `translate(${side === 'left' ? '-' : ''}50%, -50%) rotate(45deg)` : undefined,+ transform: visual.isDiamond+ ? `translate(${side === 'left' ? '-' : ''}50%, -50%) ${WORKFLOW_NODE_DIAMOND_ROTATION}`+ : undefined,width: WORKFLOW_NODE_HANDLE_SIZE,};};@@ -153,50 +304,132 @@ export const WorkflowNodeHandleDot = ({ side, type }: { side: 'left' | 'right';borderWidth={visual.isFilled ? '0' : `${HANDLE_BORDER_WIDTH}px`}boxShadow={`0 0 0 ${HANDLE_RING_WIDTH}px {colors.${WORKFLOW_NODE_SURFACE_TOKEN}}`}boxSize={`${WORKFLOW_NODE_HANDLE_SIZE}px`}+ data-node-port-dot={side}position="absolute"top="50%"- transform={`translate(${side === 'left' ? '-50%' : '50%'}, -50%)${visual.isDiamond ? ' rotate(45deg)' : ''}`}+ transform={`translate(${side === 'left' ? '-50%' : '50%'}, -50%)${visual.isDiamond ? ` ${WORKFLOW_NODE_DIAMOND_ROTATION}` : ''}`}{...(side === 'left' ? { left: '0' } : { right: '0' })}/>);};-const INFO_TOOLTIP_POSITIONING = { placement: 'top-end' } as const;+const PANEL_POSITIONING = { placement: 'top-end' } as const;+/** A plain status mark takes a header button's box, so the header's end inset holds. */+const WORKFLOW_NODE_STATUS_MARK_SIZE = { boxSize: '1.375rem' } as const;-/** The quiet header info affordance: a `fg.subtle` icon whose tooltip carries the node details. */-export const WorkflowNodeInfoIcon = ({ content, label }: { content: ReactNode; label: string }) => (- <Tooltip content={content} positioning={INFO_TOOLTIP_POSITIONING} showArrow>- <Icon aria-label={label} as={InfoIcon} boxSize="3.5" color="fg.subtle" data-node-info-icon="true" />+/** A header ghost button whose tooltip is its hover and focus panel; like every tooltip, it mounts only while open. */+export const WorkflowNodeHeaderButton = ({+ children,+ closeOnClick = true,+ content,+ ...props+}: Omit<IconButtonProps, 'content'> & { 'aria-label': string; closeOnClick?: boolean; content: ReactNode }) => (+ <Tooltip closeOnClick={closeOnClick} content={content} positioning={PANEL_POSITIONING} showArrow>+ <IconButton {...WORKFLOW_NODE_HEADER_BUTTON_PROPS} {...props}>+ {children}+ </IconButton></Tooltip>);-/** Header mark for a node whose invocation finished; the failure tooltip carries the backend message. */-export const WorkflowNodeOutcomeIcon = ({- error,+/** The header info button; its panel carries the node details. */+export const WorkflowNodeInfoButton = ({+ content,+ label,+ onPreload,+}: {+ content: ReactNode;+ label: string;+ /** Starts loading a lazy panel body when the pointer or focus arrives, before the tooltip opens. */+ onPreload?: () => void;+}) => (+ <WorkflowNodeHeaderButton+ aria-label={label}+ closeOnClick={false}+ content={content}+ data-node-info-icon="true"+ onFocus={onPreload}+ onPointerEnter={onPreload}+ >+ <Icon as={InfoIcon} boxSize="3.5" />+ </WorkflowNodeHeaderButton>+);++/** What a node's status button reports; only one shows, the caller picks which. */+export type WorkflowNodeStatus = 'completed' | 'failed' | 'invalid' | 'running' | 'updatable' | 'versionMismatch';++/** No status glyph is a circle, so none reads as the info button's circled "i" beside it. */+const STATUS_GLYPHS: Record<Exclude<WorkflowNodeStatus, 'running'>, { color: string; icon: LucideIcon }> = {+ completed: { color: 'fg.success', icon: CheckIcon },+ failed: { color: 'fg.error', icon: OctagonXIcon },+ invalid: { color: 'fg.error', icon: TriangleAlertIcon },+ updatable: { color: 'fg.warning', icon: SquareArrowUpIcon },+ versionMismatch: { color: 'fg.warning', icon: TriangleAlertIcon },+};++/** The one progress indicator a running node has: a ring, or a spinner while progress is unknown. */+const NodeProgressRing = ({ progress }: { progress: number | null }) =>+ progress === null ? (+ <Spinner aria-hidden borderWidth="2px" boxSize="3.5" />+ ) : (+ <ProgressCircle.Root aria-hidden size="xs" value={Math.round(progress * 100)}>+ <ProgressCircle.Circle>+ <ProgressCircle.Track stroke="{colors.border.emphasized}" />+ <ProgressCircle.Range stroke="currentColor" />+ </ProgressCircle.Circle>+ </ProgressCircle.Root>+ );++/**+ * The header status button: its glyph keeps its status colour, and its panel says what the status means. With no panel+ * content it is a plain mark named by `label`, with no button or tooltip to mount.+ */+export const WorkflowNodeStatusButton = ({+ content,label,- outcome,+ onPreload,+ progress = null,+ status,}: {- error?: string | null;+ content: ReactNode;label: string;- outcome: WorkflowNodeOutcome;-}) => {- const icon = (- <Icon+ /** Starts loading a lazy panel body when the pointer or focus arrives, before the tooltip opens. */+ onPreload?: () => void;+ progress?: number | null;+ status: WorkflowNodeStatus;+}) =>+ content === null ? (+ <Boxaria-label={label}- as={outcome === 'completed' ? CircleCheckIcon : CircleAlertIcon}- boxSize="3.5"- color={outcome === 'completed' ? 'fg.success' : 'fg.error'}+ color={status === 'running' ? 'brand.fg' : STATUS_GLYPHS[status].color}+ data-node-status={status}data-node-status-indicator="true"+ display="grid"flexShrink={0}+ placeItems="center"role="img"- />- );-- return outcome === 'failed' ? (- <Tooltip content={error || label} positioning={INFO_TOOLTIP_POSITIONING} showArrow>- {icon}- </Tooltip>+ {...WORKFLOW_NODE_STATUS_MARK_SIZE}+ >+ {status === 'running' ? (+ <NodeProgressRing progress={progress} />+ ) : (+ <Icon aria-hidden as={STATUS_GLYPHS[status].icon} boxSize="3.5" />+ )}+ </Box>) : (- icon+ <WorkflowNodeHeaderButton+ aria-label={label}+ closeOnClick={false}+ color={status === 'running' ? 'brand.fg' : STATUS_GLYPHS[status].color}+ content={content}+ data-node-status={status}+ data-node-status-indicator="true"+ onFocus={onPreload}+ onPointerEnter={onPreload}+ >+ {status === 'running' ? (+ <NodeProgressRing progress={progress} />+ ) : (+ <Icon as={STATUS_GLYPHS[status].icon} boxSize="3.5" />+ )}+ </WorkflowNodeHeaderButton>);-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.tsindex 1015f7c8e8..b64fc3d253 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts@@ -19,8 +19,19 @@ export type AddNodeConnectionFilter =/** Bridge transient menu actions to always-mounted workflow dialogs and file input through session UI state. */-/** The library dialog's views: project workflows, bundled templates, owned templates, or public templates. */-export type WorkflowLibraryTab = 'project' | 'default' | 'user' | 'shared';+/**+ * The library dialog's places: project workflows, recently opened templates, owned templates, bundled templates, or+ * public templates.+ */+export type WorkflowLibraryTab = 'project' | 'recent' | 'user' | 'default' | 'shared';++/** How This project orders its workflows: the project's own order, or a key. Client side, kept for the session. */+export type ProjectWorkflowSort = 'order' | 'name' | 'updated' | 'lastRun';++export interface ProjectWorkflowOrder {+ direction: 'asc' | 'desc';+ sort: ProjectWorkflowSort;+}/** What a surface asked the publication host to do with one project workflow. */export type WorkflowPublicationIntent =@@ -32,8 +43,12 @@ export interface WorkflowUiSnapshot {addNodePosition: XYPosition | null;isAddNodeOpen: boolean;isLibraryOpen: boolean;- /** Which view the library dialog shows; remembered for the session. */+ /** Which place the library dialog shows; remembered for the session. */libraryTab: WorkflowLibraryTab;+ /** The library's search text and checked tags. Closing the dialog clears both; a place change clears the tags. */+ libraryQuery: { search: string; tags: readonly string[] };+ /** This project's order; the template places' order is an account preference. */+ libraryProjectOrder: ProjectWorkflowOrder;/*** The project workflow selected on the This-project view; only meaningful for the project it was made in, and only* for the opening it was made in. Null shows the active workflow.@@ -81,6 +96,8 @@ export interface WorkflowLoadRequest {let nextWorkflowLoadRequestId = 0;+const EMPTY_LIBRARY_QUERY: WorkflowUiSnapshot['libraryQuery'] = { search: '', tags: [] };+const INITIAL_WORKFLOW_UI_SNAPSHOT: WorkflowUiSnapshot = {addNodeConnection: null,addNodePosition: null,@@ -88,6 +105,8 @@ const INITIAL_WORKFLOW_UI_SNAPSHOT: WorkflowUiSnapshot = {isAddNodeOpen: false,renameRequest: null,isLibraryOpen: false,+ libraryProjectOrder: { direction: 'asc', sort: 'order' },+ libraryQuery: EMPTY_LIBRARY_QUERY,librarySelection: null,libraryTab: 'project',pendingWorkflowLoad: null,@@ -107,22 +126,49 @@ registerAccountOwnedResource({/*** Opens or closes the library. An opening that names no workflow starts This project on the active workflow: a* selection left from an earlier opening would point the rail's actions (Update library template among them) at a- * workflow the user has since moved away from.+ * workflow the user has since moved away from. Closing clears the search and the checked tags, so the next opening+ * never starts on a filtered, possibly empty, view; the place stays.*/export const setWorkflowLibraryOpen = (isOpen: boolean): void => {const wasOpen = workflowUiStore.getSnapshot().isLibraryOpen;workflowUiStore.patchSnapshot(- isOpen && !wasOpen ? { isLibraryOpen: true, librarySelection: null } : { isLibraryOpen: isOpen }+ isOpen+ ? wasOpen+ ? { isLibraryOpen: true }+ : { isLibraryOpen: true, librarySelection: null }+ : { isLibraryOpen: false, libraryQuery: EMPTY_LIBRARY_QUERY });};+/** Switches place. Tags belong to the place they were checked in, so they clear; the search carries over. */export const setWorkflowLibraryTab = (libraryTab: WorkflowLibraryTab): void => {- if (workflowUiStore.getSnapshot().libraryTab !== libraryTab) {- workflowUiStore.patchSnapshot({ libraryTab });+ const { libraryQuery, libraryTab: current } = workflowUiStore.getSnapshot();++ if (current !== libraryTab) {+ workflowUiStore.patchSnapshot({+ libraryQuery: libraryQuery.tags.length > 0 ? { ...libraryQuery, tags: [] } : libraryQuery,+ libraryTab,+ });}};+export const setWorkflowLibrarySearch = (search: string): void => {+ const { libraryQuery } = workflowUiStore.getSnapshot();++ if (libraryQuery.search !== search) {+ workflowUiStore.patchSnapshot({ libraryQuery: { ...libraryQuery, search } });+ }+};++export const setWorkflowLibraryTags = (tags: readonly string[]): void => {+ workflowUiStore.patchSnapshot({ libraryQuery: { ...workflowUiStore.getSnapshot().libraryQuery, tags } });+};++export const setWorkflowLibraryProjectOrder = (libraryProjectOrder: ProjectWorkflowOrder): void => {+ workflowUiStore.patchSnapshot({ libraryProjectOrder });+};+export const setWorkflowLibrarySelection = (selection: { projectId: string; workflowId: string } | null): void => {workflowUiStore.patchSnapshot({ librarySelection: selection });};diff --git a/invokeai/frontend/webv2/src/platform/react/deferredModule.browser.test.tsx b/invokeai/frontend/webv2/src/platform/react/deferredModule.browser.test.tsxnew file mode 100644index 0000000000..3d0537a5d9--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/react/deferredModule.browser.test.tsx@@ -0,0 +1,137 @@+import { DEFAULT_LOGGING_CONFIG } from '@platform/logging/contracts';+import { configureLogging, getLogSnapshot, resetLogging } from '@platform/logging/logger';+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop -- each mount is a fresh render */+import { act, Component, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createDeferredModule } from './deferredModule';++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const view = { Greeting: () => <p>loaded view</p> };++class HostBoundary extends Component<{ children: ReactNode }, { message: string | null }> {+ state: { message: string | null } = { message: null };+ static getDerivedStateFromError(error: unknown) {+ return { message: error instanceof Error ? error.message : String(error) };+ }+ render() {+ return this.state.message === null ? this.props.children : <p>host caught: {this.state.message}</p>;+ }+}++const Broken = (): ReactNode => {+ throw new Error('render failed');+};++describe('createDeferredModule', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ resetLogging();+ configureLogging(DEFAULT_LOGGING_CONFIG);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ resetLogging();+ });++ it('shows its fallback while loading and after a failed load, and loads again on the next mount', async () => {+ let finishFirst: (error: Error) => void = () => {};+ const importModule = vi+ .fn<() => Promise<typeof view>>()+ .mockImplementationOnce(+ () =>+ new Promise((_resolve, reject) => {+ finishFirst = reject;+ })+ )+ .mockResolvedValue(view);+ const deferred = createDeferredModule(importModule);+ const mount = (key: string) =>+ act(() =>+ root.render(<deferred.Deferred key={key} fallback={<p>fallback</p>} render={(module) => <module.Greeting />} />)+ );+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ await mount('first');+ expect(host.textContent).toBe('fallback');+ await act(async () => {+ finishFirst(new Error('Failed to fetch dynamically imported module'));+ await Promise.resolve();+ });+ expect(host.textContent).toBe('fallback');+ expect(getLogSnapshot().entries).toMatchObject([+ {+ error: { message: 'Failed to fetch dynamically imported module' },+ level: 'warn',+ name: 'deferred-module.load-failed',+ source: { area: 'deferred-module', namespace: 'app' },+ },+ ]);++ await mount('second');+ await vi.waitFor(() => expect(host.textContent).toBe('loaded view'));+ expect(importModule).toHaveBeenCalledTimes(2);+ expect(getLogSnapshot().entries).toHaveLength(1);++ // Once loaded, a mount renders the module directly.+ await mount('third');+ expect(host.textContent).toBe('loaded view');+ expect(importModule).toHaveBeenCalledTimes(2);+ consoleError.mockRestore();+ });++ it('passes an error the loaded module throws while rendering to the host, loading or loaded', async () => {+ const deferred = createDeferredModule(() => Promise.resolve({ Broken }));+ const mount = (key: string) =>+ act(() =>+ root.render(+ <HostBoundary key={key}>+ <deferred.Deferred fallback={<p>fallback</p>} render={(module) => <module.Broken />} />+ </HostBoundary>+ )+ );+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ // The first mount renders through its lazy load.+ await mount('loading');+ await vi.waitFor(() => expect(host.textContent).toBe('host caught: render failed'));++ // Later mounts render the loaded module directly.+ await mount('loaded');+ expect(host.textContent).toBe('host caught: render failed');+ consoleError.mockRestore();+ });++ it('distinguishes a pending load from a rejected import without failing its host', async () => {+ let rejectImport: (error: Error) => void = () => {};+ const deferred = createDeferredModule(+ () =>+ new Promise((_resolve, reject) => {+ rejectImport = reject;+ })+ );+ const renderError = vi.fn((error: unknown) => <p>load failed: {String(error)}</p>);++ await act(() =>+ root.render(+ <HostBoundary>+ <deferred.Deferred fallback={<p>loading</p>} render={() => <p>loaded</p>} renderError={renderError} />+ </HostBoundary>+ )+ );+ expect(host.textContent).toBe('loading');+ expect(renderError).not.toHaveBeenCalled();++ await act(() => rejectImport(new Error('offline')));+ await vi.waitFor(() => expect(host.textContent).toBe('load failed: Error: offline'));+ });+});diff --git a/invokeai/frontend/webv2/src/platform/react/deferredModule.tsx b/invokeai/frontend/webv2/src/platform/react/deferredModule.tsxnew file mode 100644index 0000000000..22a086e67e--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/react/deferredModule.tsx@@ -0,0 +1,109 @@+import type { ReactNode } from 'react';++import { createLogger } from '@platform/logging/logger';+import { lazy, Suspense, useState } from 'react';++const logger = createLogger({ area: 'deferred-module', namespace: 'app' });++export interface DeferredModule<Module> {+ /** Starts the load if none is running or done; resolves to the module. A failed load is tried again on the next call. */+ load: () => Promise<Module>;+ /** Starts the load ahead of use, as on hover or focus, ignoring a failure. */+ preload: () => void;+ /**+ * Renders `render(module)`. Once the module has loaded it renders directly. Before that, each mount owns its own+ * lazy load, so a load that failed is tried again on the next mount, where a module-level `lazy` would keep its first+ * failure for the page's lifetime. While loading it shows `fallback`; a failed load shows `renderError(error)`+ * when provided, else `fallback`. An error the loaded+ * module throws while rendering reaches the host's error boundary instead.+ */+ Deferred: (props: {+ fallback: ReactNode;+ renderError?: (error: unknown) => ReactNode;+ render: (module: Module) => ReactNode;+ }) => ReactNode;+}++interface DeferredSource<Module> {+ getLoaded: () => Module | null;+ load: () => Promise<Module>;+}++type RenderModule<Module> = (module: Module) => ReactNode;++interface LazyViewProps<Module> {+ fallback: ReactNode;+ renderError?: (error: unknown) => ReactNode;+ renderModule: RenderModule<Module>;+}++// A top-level component, so it closes over nothing: the module's state is read through `source` on each mount.+const DeferredView = <Module,>({+ fallback,+ renderError,+ render,+ source,+}: {+ fallback: ReactNode;+ renderError?: (error: unknown) => ReactNode;+ render: RenderModule<Module>;+ source: DeferredSource<Module>;+}) => {+ // A failed load resolves to a view of the fallback rather than rejecting, so it never reaches an error boundary;+ // errors the loaded module throws while rendering still do.+ const [LazyView] = useState(() =>+ source.getLoaded() === null+ ? lazy(() =>+ source.load().then(+ (module) => ({ default: ({ renderModule }: LazyViewProps<Module>) => renderModule(module) }),+ (error: unknown) => {+ logger.warn({+ error,+ message: 'A view loaded on demand failed to load; showing its fallback',+ name: 'deferred-module.load-failed',+ });+ return {+ default: ({ fallback: failed, renderError }: LazyViewProps<Module>) =>+ renderError ? renderError(error) : failed,+ };+ }+ )+ )+ : null+ );+ return LazyView ? (+ <Suspense fallback={fallback}>+ <LazyView fallback={fallback} renderError={renderError} renderModule={render} />+ </Suspense>+ ) : (+ // Mounted without a lazy view only once the module had loaded, and a loaded module stays loaded.+ render(source.getLoaded()!)+ );+};++/** A code-split module for views that open on demand, such as panels and menus. */+export const createDeferredModule = <Module,>(importModule: () => Promise<Module>): DeferredModule<Module> => {+ let loaded: Module | null = null;+ let pending: Promise<Module> | null = null;+ // Made once per deferred module, so `Deferred` passes the same object on every render.+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop+ const source: DeferredSource<Module> = {+ getLoaded: () => loaded,+ load: () =>+ (pending ??= importModule().then(+ (module) => (loaded = module),+ (error: unknown) => {+ pending = null;+ throw error;+ }+ )),+ };++ return {+ Deferred: ({ fallback, renderError, render }) => (+ <DeferredView fallback={fallback} render={render} renderError={renderError} source={source} />+ ),+ load: source.load,+ preload: () => void source.load().catch(() => {}),+ };+};diff --git a/invokeai/frontend/webv2/src/platform/ui/Dialog.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/Dialog.browser.test.tsxnew file mode 100644index 0000000000..e6cd4e3757--- /dev/null+++ b/invokeai/frontend/webv2/src/platform/ui/Dialog.browser.test.tsx@@ -0,0 +1,176 @@+import { ChakraProvider, Portal } from '@chakra-ui/react';+import { system } from '@theme/system';+import { act, StrictMode, useCallback, useState } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { userEvent } from 'vitest/browser';++import { Dialog } from './Dialog';++(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;+});++const nextFrame = () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => resolve());+ });++/**+ * 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.+ */+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), []);++ 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}>+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content aria-label="Child">+ <Dialog.Body>+ {/* The child's first tabbable, where a trap armed after focus entered the child would return it. */}+ <button type="button">Graph</button>+ </Dialog.Body>+ <Dialog.Footer>+ <button type="button" onClick={closeChild}>+ Close+ </button>+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ ) : null}+ </>+ );+};++/** 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), []);++ 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>+ );+};++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>+ )+ );+ 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('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);++ await act(() => userEvent.click(document.body, { position: { x: 4, y: 4 } }));++ await expect.poll(() => parent.getAttribute('data-state')).toBe('closed');+ });++ 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>+ )+ );+ 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 act(() => host!.querySelector('button')!.focus());++ await expect.poll(() => onFocusOutside.mock.calls.length).toBe(1);+ await act(nextFrame);+ expect(dialog.getAttribute('data-state')).toBe('open');+ });+});diff --git a/invokeai/frontend/webv2/src/platform/ui/Dialog.tsx b/invokeai/frontend/webv2/src/platform/ui/Dialog.tsxindex 344b7c2c19..7d89f77905 100644--- a/invokeai/frontend/webv2/src/platform/ui/Dialog.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Dialog.tsx@@ -1,6 +1,7 @@// eslint-disable-next-line no-restricted-imports -- the one wrapper the restriction routes every dialog throughimport { Dialog as ChakraDialog, useDialogContext } from '@chakra-ui/react';import { useMountEffect } from '@platform/react/useMountEffect';+import { useCallback } from 'react';import { registerModalPresence } from './modalPresence';@@ -28,12 +29,34 @@ const keepOpenThroughMenuTeardown = (event: LayerDismissEvent) => {}};-const DialogRoot = ({ children, ...props }: Dialog.RootProps) => (- <ChakraDialog.Root {...props} onRequestDismiss={keepOpenThroughMenuTeardown}>- {props.modal === false ? null : <ModalPresence />}- {children}- </ChakraDialog.Root>-);+type FocusOutsideEvent = Parameters<NonNullable<ChakraDialog.RootProps['onFocusOutside']>>[0];++const DialogRoot = ({ children, onFocusOutside, ...props }: Dialog.RootProps) => {+ const isModal = props.modal !== false;+ /**+ * A modal dialog traps focus, so focus landing outside it is never the user leaving; Escape, a close control or a+ * press outside are. Focus still lands outside programmatically, mostly under StrictMode: a dialog that mounts open+ * arms a second focus trap after focus has entered it, and on close that trap returns focus into the closed dialog,+ * which would dismiss the dialog that opened it.+ */+ const handleFocusOutside = useCallback(+ (event: FocusOutsideEvent) => {+ onFocusOutside?.(event);++ if (isModal) {+ event.preventDefault();+ }+ },+ [isModal, onFocusOutside]+ );++ return (+ <ChakraDialog.Root {...props} onFocusOutside={handleFocusOutside} onRequestDismiss={keepOpenThroughMenuTeardown}>+ {isModal ? <ModalPresence /> : null}+ {children}+ </ChakraDialog.Root>+ );+};/*** Chakra's dialog parts with a root that announces modal presence while open, so application shortcuts behind itdiff --git a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx b/invokeai/frontend/webv2/src/platform/ui/Menu.tsxindex 33184c700e..15c9469e49 100644--- a/invokeai/frontend/webv2/src/platform/ui/Menu.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/Menu.tsx@@ -24,6 +24,18 @@ import { useRegisterWidgetOverlay } from './widgetOverlays';type MenuContentProps = ComponentProps<typeof Menu.Content>;+/**+ * The layout of menu content whose list scrolls (`ScrollableMenuContent`, or `ScrollableMenuList` inside it): it grows to+ * the context menus' cap or the room the positioner measured beside its anchor, then the list scrolls. The column gives+ * the list the content's padded box, so its last row is never cut off by the padding, and rows after it stay in view.+ */+export const SCROLLABLE_MENU_CONTENT_PROPS = {+ display: 'flex',+ flexDirection: 'column',+ maxH: 'min(28rem, var(--available-height))',+ overflow: 'hidden',+} as const;+/** Menu content closes with its owning widget; the theme recipe owns chrome. */export const MenuContent = (props: MenuContentProps) => {const menu = useMenuContext();diff --git a/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsx b/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsxindex 78131a7ce0..77082f4e76 100644--- a/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ResizableTextarea.tsx@@ -33,12 +33,53 @@ const resizeHandleAfter = {w: '10',} as const;-// Fades content under the handle; the edge strips keep the border and its rounded corners opaque.+/*+ * The content under the handle fades out. A host that paints its controls on an opaque well marks itself with+ * `data-control-well` and sets the colour as `--wb-control-well`; the fade then ends in that colour. Any other host+ * gets a mask that fades the control to whatever lies behind it, and its edge strips keep the border and the rounded+ * corners opaque.+ *+ * The well's fade is an overlay rather than a mask because of scaled hosts such as the node editor. There the text+ * area's inner bottom edge falls inside a device pixel, and that pixel row holds both the bottom border and text the+ * clip lets through. A mask can only show or hide the whole row, and a fill that stops at the inner edge leaves a+ * share of the row's text uncovered, so either way a slice of text shows below the fade. The overlay instead covers+ * the bottom 1rem, border included, and repaints the border on top. Its fill is solid for the last 0.25rem.+ */const resizeHandleFade = {maskImage: ['linear-gradient(to bottom, black calc(100% - 1rem), transparent calc(100% - 0.25rem), transparent calc(100% - 1px), black calc(100% - 1px))','linear-gradient(to right, black {radii.control}, transparent {radii.control}, transparent calc(100% - {radii.control}), black calc(100% - {radii.control}))',].join(', '),+ '[data-control-well] &': { maskImage: 'none' },+} as const;++// The fill covers the border's rows too. The border goes back on top as a separate box: Chromium draws a gradient fill+// short of a box's own opaque border, which would uncover that row again. The border follows the text area's own+// border states (`formControlInteraction` in the theme recipes), later entries winning as they do there.+const wellFade = {+ backgroundImage: 'linear-gradient(to bottom, transparent, var(--wb-control-well) calc(100% - 0.25rem))',+ borderBottomRadius: 'control',+ bottom: '0',+ display: 'none',+ h: '1rem',+ insetX: '0',+ pointerEvents: 'none',+ position: 'absolute',+ _after: {+ borderBottomRadius: 'inherit',+ borderColor: 'border',+ borderStyle: 'solid',+ borderWidth: '0 1px 1px',+ content: '""',+ inset: '0',+ position: 'absolute',+ transitionDuration: 'fast',+ transitionProperty: 'border-color',+ },+ '[data-control-well] &': { display: 'block' },+ '[data-part="viewport"]:hover ~ &::after': { borderColor: 'border.emphasized' },+ '[data-part="viewport"]:focus-visible ~ &::after': { borderColor: 'accent.solid' },+ '[data-part="viewport"]:is([aria-invalid="true"], [data-invalid]) ~ &::after': { borderColor: 'border.error' },} as const;const resizeHandleFocusVisible = { bg: 'accent.solid/20', outline: '2px solid {colors.accent.solid}' } as const;@@ -156,6 +197,7 @@ export const ResizableTextarea = ({</ScrollArea.Viewport>{/* Zag needs a content element to remeasure; the textarea itself is the viewport. */}<ScrollArea.Content h="0" minW="0" overflow="hidden" position="absolute" />+ <Box aria-hidden data-resizable-textarea-fade="" css={wellFade} /><ScrollArea.Scrollbar><ScrollArea.Thumb /></ScrollArea.Scrollbar>diff --git a/invokeai/frontend/webv2/src/platform/ui/ScrollableMenuContent.tsx b/invokeai/frontend/webv2/src/platform/ui/ScrollableMenuContent.tsxindex dc1d820baf..6cf871362f 100644--- a/invokeai/frontend/webv2/src/platform/ui/ScrollableMenuContent.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ScrollableMenuContent.tsx@@ -1,11 +1,8 @@import type { ComponentProps, ReactNode } from 'react';-import { MenuContent } from './Menu';+import { MenuContent, SCROLLABLE_MENU_CONTENT_PROPS } from './Menu';import { Scrollable } from './Scrollable';-/** A long menu's height: the context menus' cap, shrunk to the room the positioner measured beside its anchor. */-const SCROLLABLE_MENU_MAX_H = 'min(28rem, var(--available-height))';-/*** Re-implements Zag's highlight-follow. Zag scrolls a highlighted item into view only when the menu content itself* scrolls; here the themed Scrollable viewport inside it does, because the app keeps its overlay scrollbar over native@@ -29,18 +26,19 @@ const followHighlightedItem = (viewport: HTMLDivElement | null) => {return () => observer.disconnect();};-/**- * Menu content for long lists, such as boards to move items to: it grows to the shared cap or the available height,- * then scrolls in a Scrollable. The column layout gives the Scrollable the content's padded box, so the last row is- * never cut off by the content's padding.- */+/** A menu's scrolling list, in content laid out with `SCROLLABLE_MENU_CONTENT_PROPS`, above any rows that stay in view. */+export const ScrollableMenuList = ({ children }: { children: ReactNode }) => (+ <Scrollable minH="0" viewportRef={followHighlightedItem}>+ {children}+ </Scrollable>+);++/** Menu content for long lists, such as boards to move items to: the list scrolls within the menu's cap. */export const ScrollableMenuContent = ({children,...props}: ComponentProps<typeof MenuContent> & { children: ReactNode }) => (- <MenuContent display="flex" flexDirection="column" maxH={SCROLLABLE_MENU_MAX_H} overflow="hidden" {...props}>- <Scrollable minH="0" viewportRef={followHighlightedItem}>- {children}- </Scrollable>+ <MenuContent {...SCROLLABLE_MENU_CONTENT_PROPS} {...props}>+ <ScrollableMenuList>{children}</ScrollableMenuList></MenuContent>);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 ae918a63b2..ca9ba2a70f 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@@ -12,7 +12,7 @@ import type { ListRow } from './listRows';import { List, type ListRowProps } from './List';import { ListItem } from './ListItem';import { LIST_ROW_GAP_PX } from './listLayout';-import { listRowsFromSections } from './listRows';+import { listRowsFromItems, listRowsFromSections } from './listRows';vi.mock('react-i18next', () => ({useTranslation: () => ({@@ -413,6 +413,65 @@ describe('List scroll offset persistence', () => {});});+describe('List range reporting', () => {+ it('reports the visible range on mount and when a scroll moves it, not on every scroll event', async () => {+ const onRangeChange = vi.fn();+ // No section headers, so every index is a row slot.+ const rows = listRowsFromItems(section('main', 'Main', 200).items, (item) => item.id);+ const element = (+ <ChakraProvider value={system}>+ <List+ density="comfortable"+ label="subjects"+ renderItem={(item: Item, rowProps: ListRowProps) => <ListItem {...rowProps} title={item.name} />}+ rows={rows}+ onRangeChange={onRangeChange}+ />+ </ChakraProvider>+ );++ await render(element);+ // The rows the viewport actually shows, read from the rendered slots.+ const shownRange = () => {+ const bounds = viewport().getBoundingClientRect();+ const shown = [...host.querySelectorAll<HTMLElement>('[data-index]')]+ .filter((slot) => {+ const box = slot.getBoundingClientRect();+ return box.bottom > bounds.top + 0.5 && box.top < bounds.bottom - 0.5;+ })+ .map((slot) => Number(slot.dataset.index));+ return { endIndex: Math.max(...shown), startIndex: Math.min(...shown) };+ };+ expect(onRangeChange).toHaveBeenCalledTimes(1);+ expect(onRangeChange).toHaveBeenLastCalledWith(shownRange());++ // Thirty scroll events over 90px cross only a few row boundaries; each report is a new range.+ for (let step = 1; step <= 30; step += 1) {+ await scrollTo(ROW_PX * 50 + step * 3);+ }+ const reports = onRangeChange.mock.calls.map((call) => call[0] as { endIndex: number; startIndex: number });+ expect(reports.length).toBeGreaterThan(1);+ expect(reports.length).toBeLessThan(8);+ reports.slice(1).forEach((range, index) => expect(range).not.toEqual(reports[index]));+ expect(reports.at(-1)).toEqual(shownRange());+ });+});++describe('List scrolling cost', () => {+ it('pins the scroll area’s overflow properties above the rows, so scrolling restyles none of them', async () => {+ await render(<Harness rows={listRowsFromItems(section('main', 'Main', 60).items, (item) => item.id)} />);+ await scrollTo(400);++ // Whatever custom properties the scroll area writes on its viewport, none may reach the rows changing.+ const viewportProperties = () => [...viewport().style].filter((name) => name.startsWith('--'));+ await vi.waitFor(() => expect(viewportProperties().length).toBeGreaterThan(0));+ const style = getComputedStyle(host.querySelector('[data-list-row]')!);+ for (const name of viewportProperties()) {+ expect(['', '0px'], name).toContain(style.getPropertyValue(name).trim());+ }+ });+});+describe('ListItem checkbox', () => {it('names the checkbox after the row and reports toggles without pressing the row', async () => {const onCheckedChange = vi.fn();diff --git a/invokeai/frontend/webv2/src/platform/ui/list/List.tsx b/invokeai/frontend/webv2/src/platform/ui/list/List.tsxindex d840e91e64..366ac299c0 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/List.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/List.tsx@@ -69,6 +69,19 @@ const PINNED_HEADER_WRAPPER_STYLE: CSSProperties = {zIndex: 1,};+/**+ * The scroll area writes its overflow offsets as inherited custom properties on the viewport at every scroll event,+ * which restyles every element below it. Rows use none of them; pinning them on the row container stops that restyle+ * there, which otherwise costs each scroll frame a style pass over every mounted row.+ */+const ROW_CONTAINER_CSS = {+ '--scroll-area-overflow-x-start': '0px',+ '--scroll-area-overflow-x-end': '0px',+ '--scroll-area-overflow-y-start': '0px',+ '--scroll-area-overflow-y-end': '0px',+};+const ROW_CONTAINER_WITH_DIVIDERS_CSS = [ROW_CONTAINER_CSS, IN_SLOT_DIVIDER_HIDING_CSS];+export type ListSurface = 'bg' | 'bg.subtle' | 'bg.panel';/**@@ -123,6 +136,17 @@ export interface ListProps<T> {revealActiveOnMount?: boolean;/** Receives the final scroll offset on unmount; must be referentially stable. */onScrollOffsetPersist?: (offset: number) => void;+ /**+ * Receives the visible row-index range (headers and items share the index space) on mount and whenever it changes,+ * never per scrolled pixel; rows within the overscan around it are mounted too. For callers that load rows on+ * demand, such as a server-windowed collection. Must be referentially stable.+ */+ onRangeChange?: (range: ListRange) => void;+}++export interface ListRange {+ startIndex: number;+ endIndex: number;}const findItemIndex = <T,>(rows: readonly ListRow<T>[], from: number, step: 1 | -1): number => {@@ -159,6 +183,7 @@ export const List = <T,>({rows,status = 'ready',surface = 'bg',+ onRangeChange,onScrollOffsetPersist,}: ListProps<T>) => {const { t } = useTranslation();@@ -229,6 +254,22 @@ export const List = <T,>({return Math.max(0, offset - (hasHeaders ? LIST_SECTION_HEADER_HEIGHT_PX : 0));}, [activeIndex, estimateSize, hasHeaders]);const getScrollElement = useCallback(() => viewportRef.current, []);+ const reportedRange = useRef<ListRange | null>(null);+ // The virtualizer also notifies for scroll start and stop and for measurements; report only a moved range.+ const handleVirtualizerChange = useCallback(+ (instance: { range: { startIndex: number; endIndex: number } | null }) => {+ const range = instance.range;+ const last = reportedRange.current;++ if (!onRangeChange || !range || (last?.startIndex === range.startIndex && last.endIndex === range.endIndex)) {+ return;+ }++ reportedRange.current = { endIndex: range.endIndex, startIndex: range.startIndex };+ onRangeChange(reportedRange.current);+ },+ [onRangeChange]+ );// A viewport that unmounts (empty or loading state) takes no blur with it; forget ownership so a later remount// cannot pull focus away from wherever the user went meanwhile.const attachViewport = useCallback((element: HTMLDivElement | null) => {@@ -244,6 +285,7 @@ export const List = <T,>({getItemKey,getScrollElement,initialOffset: initialScrollOffset ?? getActiveRowOffset,+ onChange: onRangeChange ? handleVirtualizerChange : undefined,overscan: OVERSCAN_ROWS,rangeExtractor,scrollPaddingStart: hasHeaders ? LIST_SECTION_HEADER_HEIGHT_PX : 0,@@ -414,7 +456,7 @@ export const List = <T,>({<Boxaria-busy={isBusy || undefined}aria-label={label}- css={dividers ? IN_SLOT_DIVIDER_HIDING_CSS : undefined}+ css={dividers ? ROW_CONTAINER_WITH_DIVIDERS_CSS : ROW_CONTAINER_CSS}role="list"style={containerStyle}>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 89af4ec851..28d73cff10 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,20 @@ describe('ListItem', () => {expect(surface()).not.toBe(resting);});+ 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()} />);++ // Collapsed, the button names nothing: aria-controls follows the expanded state.+ expect(document.getElementById('row-a')).toBe(primary());+ expect(primary().hasAttribute('aria-controls')).toBe(false);+ expect(primary().hasAttribute('aria-expanded')).toBe(false);++ await render(<ListItem controls="row-a-menu" id="row-a" isExpanded title="A workflow" onPress={vi.fn()} />);++ expect(primary().getAttribute('aria-controls')).toBe('row-a-menu');+ expect(primary().getAttribute('aria-expanded')).toBe('true');+ });+it('renders a static row without a press handler as plain content, not a button', async () => {await render(<ListItem title="Read only" />);diff --git a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsxindex 07453c08b9..d68b1c6db8 100644--- a/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/list/ListItem.tsx@@ -54,6 +54,17 @@ export interface ListItemProps {checkLabel?: string;/** Identifies the row to its owning List for focus management. */itemKey?: string;+ /**+ * DOM id of the primary button, so a menu or dialog opened from outside the row can name it as the trigger focus+ * returns to.+ */+ id?: string;+ /**+ * Id of the popup the primary button discloses, named with aria-controls only while the button is expanded+ * (`isExpanded`, or `isMenuOpen` for a row whose press opens its menu). A modal dialog's focus trap admits focus only+ * into portalled content that an expanded control inside it names.+ */+ controls?: string;/** `presentation` when a caller's own list item wraps this row together with content that belongs to it. */role?: 'listitem' | 'presentation';/** Roving tabindex from the owning List; standalone rows are tab stops. */@@ -86,9 +97,11 @@ export const ListItem = ({actions,badges,checkLabel,+ controls,density = 'regular',description,detail,+ id,isActive = false,isBusy = false,isChecked = false,@@ -122,6 +135,7 @@ 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 openContextMenu = useCallback((row: HTMLElement, point?: { x: number; y: number }) => {@@ -261,13 +275,15 @@ export const ListItem = ({) : null}{isInteractive ? (<chakra.button+ aria-controls={isPrimaryExpanded ? controls : undefined}aria-current={isActive || undefined}aria-disabled={isBusy || undefined}- aria-expanded={onContextMenu && !onPress ? isMenuOpen : isExpanded}+ aria-expanded={isPrimaryExpanded}aria-haspopup={onContextMenu && !onPress ? 'menu' : undefined}aria-label={pressLabel}css={styles.primary}data-list-primary=""+ id={id}tabIndex={tabIndex}type="button"onClick={handlePress}diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.tsindex 3772035a0c..9ba6e34a52 100644--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.test.ts@@ -1,15 +1,26 @@-import type { MainModelConfig } from '@features/generation/contracts';+import type {+ ComponentModelConfig,+ GenerateWidgetValues,+ MainModelConfig,+ VaeModelConfig,+} from '@features/generation/contracts';import type { AccountScope } from '@platform/state/accountLifecycle';+import { galleryKeys } from '@features/gallery/queries';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';import { getDefaultGenerateSettings } from '@features/generation/settings';-import { describe, expect, it, vi } from 'vitest';+import { queryClient } from '@platform/query/client';+import { captureAccountScope } from '@platform/state/accountLifecycle';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { CanvasRegionalGuidanceLayerContract } from './canvas-engine/api';import type { WorkbenchCommands, WorkbenchQueries } from './workbenchStore';import { submitActiveInvocation, type ActiveInvocationSubmissionRuntime } from './activeInvocationSubmission';-import { isInvocationPreparing } from './invocationPreparation';+import { beginInvocationPreparation, endInvocationPreparation, isInvocationPreparing } from './invocationPreparation';+import { submitResolvedInvocation } from './invocationSubmit';import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';+import { createWorkbenchStore } from './workbenchStore';// A loaded definition for the one node the workflow route needs; readiness reads templates imperatively.vi.mock('@features/workflow/react', async (importOriginal) => ({@@ -63,6 +74,9 @@ const createCanvasState = () =>const createGenerateState = () => withGenerateModel(createInitialWorkbenchState());+const withActiveSource = (state: ReturnType<typeof createInitialWorkbenchState>, sourceId: 'workflow') =>+ workbenchReducer(state, { sourceId, type: 'setInvocationSource' });+// The Automate preset mounts the Workflow widget; one node makes the graph runnable.const createWorkflowState = () => {let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'automate', type: 'applyPreset' });@@ -113,6 +127,81 @@ describe('active invocation submission', () => {expect(prepends).toEqual([undefined, true]);});+ it('runs a given source’s route with that source fixed, telling the caller once it has started', async () => {+ const routes: { mode: string; sourceId: string; sourceLocked: boolean }[] = [];+ const runtime: ActiveInvocationSubmissionRuntime = {+ assertCurrent: () => undefined,+ capture: () => owner,+ flushDrafts: () => undefined,+ isCurrent: () => true,+ loadPrepareCanvasInvocation: () => Promise.reject(new Error('Only Canvas loads the Canvas chunk')),+ submit: ({ route }) => {+ routes.push({ mode: route.mode, sourceId: route.sourceId, sourceLocked: route.sourceLocked });+ },+ };+ const state = createGenerateState();+ const onStarted = vi.fn();++ // Workflow is the active source; the preview runs Generate's route.+ await submitActiveInvocation(+ { ...createArgs(withActiveSource(state, 'workflow')), onStarted, sourceId: 'generate' },+ runtime+ );++ expect(routes).toEqual([{ mode: 'dialog', sourceId: 'generate', sourceLocked: true }]);+ expect(onStarted).toHaveBeenCalledTimes(1);+ });++ it('runs the Video preview to Gallery without changing the locked top-bar Canvas route', async () => {+ const videoModel = {+ key: 'wan-model',+ name: 'Wan',+ type: 'main' as const,+ base: 'wan' as const,+ format: 'diffusers',+ variant: 't2v_a14b' as const,+ file_size: 1,+ hash: 'wan-hash',+ path: 'wan',+ source: 'wan',+ source_type: 'path' as const,+ };+ let state: ReturnType<typeof createInitialWorkbenchState> = createGenerateState();+ state = workbenchReducer(state, { region: 'left', type: 'toggleRegionWidget', widgetId: 'video' });+ state = workbenchReducer(state, {+ type: 'patchWidgetValues',+ widgetId: 'video',+ values: { model: videoModel, positivePrompt: 'a fox' },+ });+ state.projects[0]!.invocation = {+ sourceId: 'generate',+ sourceLocked: true,+ destination: 'canvas',+ destinationLocked: true,+ };+ const submit = vi.fn();+ const runtime: ActiveInvocationSubmissionRuntime = {+ assertCurrent: () => undefined,+ capture: () => owner,+ flushDrafts: () => undefined,+ isCurrent: () => true,+ loadPrepareCanvasInvocation: () => Promise.reject(new Error('Video needs no Canvas preparation')),+ submit,+ };+ await submitActiveInvocation({ ...createArgs(state), getModels: () => [videoModel], sourceId: 'video' }, runtime);+ expect(submit).toHaveBeenCalledWith(+ expect.objectContaining({+ route: expect.objectContaining({ destination: 'gallery', mode: 'dialog', sourceId: 'video' }),+ })+ );+ expect(state.projects[0]!.invocation).toEqual({+ sourceId: 'generate',+ sourceLocked: true,+ destination: 'canvas',+ destinationLocked: true,+ });+ });+it('single-flights a canvas submission before its lazy module loads and until preparation settles', async () => {let resolveModule = (_value: { prepareCanvasInvocation: () => Promise<void> }): void => undefined;const modulePromise = new Promise<{ prepareCanvasInvocation: () => Promise<void> }>((resolve) => {@@ -234,3 +323,183 @@ describe('active invocation submission', () => {expect(isInvocationPreparing(state.activeProjectId)).toBe(false);});});++/**+ * A graph preview runs its own source's route (`sourceId`), resolved for real: these cases came from the preview's+ * former submission path and hold for this one.+ */+describe('active invocation submission for a graph preview’s source', () => {+ const formatControlLayerError = ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`;+ const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };+ const animaVae: VaeModelConfig = { base: 'qwen-image', key: 'anima-vae', name: 'Anima VAE', type: 'vae' };+ const qwen3Encoder: ComponentModelConfig = {+ base: 'any',+ key: 'qwen3-encoder',+ name: 'Qwen3 Encoder',+ type: 'qwen3_encoder',+ variant: 'qwen3_06b',+ };++ const projectWith = (values: GenerateWidgetValues) => {+ const state = workbenchReducer(createInitialWorkbenchState(), { type: 'setGenerateSettings', values });++ return state.projects.find((candidate) => candidate.id === state.activeProjectId)!;+ };+ type TestProject = ReturnType<typeof projectWith>;+ // Mount Canvas, so the route counts that source available.+ const withCanvasMounted = (project: TestProject): TestProject => ({+ ...project,+ widgetRegions: {+ ...project.widgetRegions,+ center: { ...project.widgetRegions.center, activeInstanceId: 'canvas', instanceIds: ['canvas'] },+ },+ });+ const animaProject = () =>+ projectWith({+ ...getDefaultGenerateSettings(animaModel),+ model: animaModel,+ modelKey: animaModel.key,+ positivePrompt: 'an anima prompt',+ qwen3EncoderModel: qwen3Encoder,+ vae: animaVae,+ });++ /** The real submission with the real route, Canvas preparation recorded rather than run. */+ const submitPreview = async (project: TestProject, sourceId: 'canvas' | 'generate') => {+ const store = createWorkbenchStore();+ const submitResolved = vi.spyOn(store.commands.generation, 'submitResolved');+ const prepareCanvasInvocation = vi.fn(() => Promise.resolve());+ const onStarted = vi.fn();+ const runtime: ActiveInvocationSubmissionRuntime = {+ assertCurrent: () => undefined,+ // The current account, which the submission checks before it dispatches.+ capture: captureAccountScope,+ flushDrafts: () => undefined,+ isCurrent: () => true,+ loadPrepareCanvasInvocation: () => Promise.resolve({ prepareCanvasInvocation }),+ submit: submitResolvedInvocation,+ };++ await submitActiveInvocation(+ {+ commands: store.commands,+ formatControlLayerError,+ formatUpscaleMetadataFailure: (name: string) => name,+ getModels: () => undefined,+ onStarted,+ queries: {+ getSnapshot: () => ({+ activeProject: project,+ backendConnection: { status: 'connected' },+ scopedDefaults: {},+ }),+ } as unknown as WorkbenchQueries,+ sourceId,+ },+ runtime+ );++ return {+ prepared: prepareCanvasInvocation.mock.calls as unknown as [{ projectId: string }][],+ started: onStarted.mock.calls.length,+ submitted: submitResolved.mock.calls.length,+ };+ };++ beforeEach(() => {+ queryClient.clear();+ // A fresh listing of the readable boards, as the destinations check leaves it: none named.+ queryClient.setQueryData(+ galleryKeys.boards(captureAccountScope(), {+ includeArchived: true,+ includeDateBoards: false,+ orderBy: 'created_at',+ orderDir: 'DESC',+ }),+ []+ );+ });++ it('runs a Canvas source through Canvas preparation, not a resolved snapshot', async () => {+ const project = withCanvasMounted(animaProject());+ const { prepared, started, submitted } = await submitPreview(project, 'canvas');++ expect(started).toBe(1);+ expect(submitted).toBe(0);+ expect(prepared).toHaveLength(1);+ expect(prepared[0]?.[0]).toMatchObject({ projectId: project.id });+ });++ it('prepares nothing for a Canvas preview of a blank prompt around a layout region while Generate is active', async () => {+ const ideogramModel: MainModelConfig = {+ base: 'ideogram-4',+ format: 'diffusers',+ key: 'ideogram-4-model',+ name: 'Ideogram 4',+ type: 'main',+ };+ const region: CanvasRegionalGuidanceLayerContract = {+ autoNegative: false,+ blendMode: 'normal',+ id: 'region',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: { height: 64, imageName: 'region.png', width: 64 }, fill: { color: '#00ff00', style: 'solid' } },+ name: 'Region',+ negativePrompt: null,+ opacity: 1,+ positivePrompt: 'a red kite',+ referenceImages: [],+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 32, y: 32 },+ type: 'regional_guidance',+ };+ const preview = async (positivePrompt: string) => {+ const project = withCanvasMounted(+ projectWith({+ ...getDefaultGenerateSettings(ideogramModel),+ model: ideogramModel,+ modelKey: ideogramModel.key,+ positivePrompt,+ })+ );+ const { prepared, started } = await submitPreview(+ {+ ...project,+ canvas: {+ ...project.canvas,+ document: {+ ...project.canvas.document,+ bbox: { height: 512, width: 512, x: 0, y: 0 },+ stacks: { ...project.canvas.document.stacks, regional_guidance: [region] },+ },+ },+ invocation: { ...project.invocation, sourceId: 'generate' },+ },+ 'canvas'+ );++ return { prepared: prepared.length, started };+ };++ // Nothing uploads for a submission the compiler would reject; with a prompt the same preview goes ahead.+ expect(await preview('')).toEqual({ prepared: 0, started: 0 });+ expect(await preview('a beach at noon')).toEqual({ prepared: 1, started: 1 });+ });++ it('starts nothing while another submission for the project holds the lease', async () => {+ const project = animaProject();+ const lease = beginInvocationPreparation(project.id);++ try {+ expect(await submitPreview(project, 'generate')).toEqual({ prepared: [], started: 0, submitted: 0 });+ } finally {+ endInvocationPreparation(lease!);+ }++ expect(await submitPreview(project, 'generate')).toMatchObject({ started: 1, submitted: 1 });+ });++ it('starts nothing for a route that cannot run (a source the layout does not hold)', async () => {+ expect(await submitPreview(animaProject(), 'canvas')).toEqual({ prepared: [], started: 0, submitted: 0 });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.tsindex ab11197947..1384c81274 100644--- a/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts+++ b/invokeai/frontend/webv2/src/workbench/activeInvocationSubmission.ts@@ -8,7 +8,7 @@ import {isAccountScopeCurrent,} from '@platform/state/accountLifecycle';-import type { ResultDestination } from './invocationContracts';+import type { InvocationSourceId, ResultDestination } from './invocationContracts';import type { SubmitResolvedInvocationDeps } from './invocationSubmit';import type { PrepareCanvasInvocationArgs } from './widgets/canvas/invoke/prepareCanvasInvocation';import type { WorkbenchCommands, WorkbenchQueries } from './workbenchStore';@@ -28,6 +28,13 @@ export interface ActiveInvocationSubmissionArgs {/** Invoke Front: the backend runs this batch ahead of the user's other pending work. */prepend?: boolean;queries: WorkbenchQueries;+ /**+ * Runs this source's route, its source fixed, as a graph preview of that source does, rather than the active route.+ * Video uses Gallery; other sources keep the active route's destination.+ */+ sourceId?: InvocationSourceId;+ /** Hears that the submission has started: it is valid and holds the project's preparation lease. */+ onStarted?: () => void;}export interface ActiveInvocationSubmissionRuntime {@@ -73,17 +80,23 @@ export const submitActiveInvocation = async (getModels,prepend,queries,+ sourceId,+ onStarted,}: ActiveInvocationSubmissionArgs,activeRuntime: ActiveInvocationSubmissionRuntime = runtime): Promise<void> => {const owner = activeRuntime.capture();activeRuntime.flushDrafts();const snapshot = queries.getSnapshot();- const invocation = destinationOverride- ? { ...snapshot.activeProject.invocation, destination: destinationOverride }- : snapshot.activeProject.invocation;+ const active = snapshot.activeProject.invocation;+ const invocation = {+ ...active,+ ...(destinationOverride ? { destination: destinationOverride } : {}),+ ...(sourceId ? { sourceId, sourceLocked: true } : {}),+ ...(sourceId === 'video' ? { destination: 'gallery' as const } : {}),+ };const models = getModels();- const route = resolveInvocationRoute(snapshot.activeProject, 'global', invocation, models);+ const route = resolveInvocationRoute(snapshot.activeProject, sourceId ? 'dialog' : 'global', invocation, models);if (!isInvocationRouteValid(route) || snapshot.backendConnection.status !== 'connected') {return;@@ -97,6 +110,8 @@ export const submitActiveInvocation = async (return;}+ onStarted?.();+try {const prepareCanvasInvocation = isCanvasSubmission? (await activeRuntime.loadPrepareCanvasInvocation()).prepareCanvasInvocationdiff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.tsdeleted file mode 100644index 3391ab26fc..0000000000--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.test.ts+++ /dev/null@@ -1,286 +0,0 @@-import type {- GenerateWidgetValues,- MainModelConfig,- VaeModelConfig,- ComponentModelConfig,-} from '@features/generation/contracts';-import type { CanvasRegionalGuidanceLayerContract } from '@workbench/canvas-engine/api';--import { galleryKeys } from '@features/gallery/queries';-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';-import { getDefaultGenerateSettings } from '@features/generation/settings';-import { queryClient } from '@platform/query/client';-import { captureAccountScope } from '@platform/state/accountLifecycle';-import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';-import { createWorkbenchStore } from '@workbench/workbenchStore';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { resolveAndSubmitGraphPreviewInvocation } from './graphPreviewInvocation';-import { beginInvocationPreparation, endInvocationPreparation } from './invocationPreparation';--// Production words rejections from the locale; tests only need the structured rejection to reach the notice.-const formatControlLayerError = ({ code, layerName }: { code: string; layerName: string }) => `${layerName}: ${code}`;-const formatUpscaleMetadataFailure = (name: string) => `metadataFailed: ${name}`;--// Seed capabilities to match app boot; submission fails closed without them.-seedArchitectureCapabilities();--const animaModel: MainModelConfig = { base: 'anima', key: 'anima-model', name: 'Anima', type: 'main' };-const animaVae: VaeModelConfig = { base: 'qwen-image', key: 'anima-vae', name: 'Anima VAE', type: 'vae' };-const qwen3Encoder: ComponentModelConfig = {- base: 'any',- key: 'qwen3-encoder',- name: 'Qwen3 Encoder',- type: 'qwen3_encoder',- variant: 'qwen3_06b',-};--const createGenerateValues = (overrides: Partial<GenerateWidgetValues> = {}): GenerateWidgetValues => ({- ...getDefaultGenerateSettings(animaModel),- model: animaModel,- modelKey: animaModel.key,- positivePrompt: 'an anima prompt',- qwen3EncoderModel: qwen3Encoder,- vae: animaVae,- ...overrides,-});--const getActiveProject = (values: GenerateWidgetValues) => {- const state = workbenchReducer(createInitialWorkbenchState(), { type: 'setGenerateSettings', values });- const project = state.projects.find((candidate) => candidate.id === state.activeProjectId);-- expect(project).toBeDefined();-- return project!;-};--// Mount Canvas in the project so resolveInvocationRoute considers that source available.-const withCanvasWidgetMounted = (- project: ReturnType<typeof getActiveProject>-): ReturnType<typeof getActiveProject> => ({- ...project,- widgetRegions: {- ...project.widgetRegions,- center: {- ...project.widgetRegions.center,- activeInstanceId: 'canvas',- instanceIds: ['canvas'],- },- },-});--/** A fresh listing of every readable board, as `ensureGalleryBoardDestinations` leaves it: the boards named are destinations. */-const listGalleryBoardsInCache = (...boardIds: string[]) =>- queryClient.setQueryData(- galleryKeys.boards(captureAccountScope(), {- includeArchived: true,- includeDateBoards: false,- orderBy: 'created_at',- orderDir: 'DESC',- }),- boardIds.map((id) => ({- archived: false,- assetCount: 0,- assetVideoCount: 0,- id,- imageCount: 0,- isInbox: false,- kind: 'board' as const,- name: id,- projectId: null,- videoCount: 0,- }))- );--describe('resolveAndSubmitGraphPreviewInvocation', () => {- beforeEach(() => {- queryClient.clear();- listGalleryBoardsInCache();- });-- it('routes a canvas source through prepareCanvasInvocation and does not dispatch a resolved snapshot', () => {- const project = withCanvasWidgetMounted(getActiveProject(createGenerateValues()));- const commands = createWorkbenchStore().commands;- const submitResolved = vi.spyOn(commands.generation, 'submitResolved');- const prepareCanvasInvocation = vi.fn();-- const submitted = resolveAndSubmitGraphPreviewInvocation({- commands,- formatControlLayerError,- formatUpscaleMetadataFailure,- scopedDefaults: {},- models: undefined,- owner: captureAccountScope(),- prepareCanvasInvocation,- project,- sourceId: 'canvas',- });-- expect(submitted).toBe(true);- expect(submitResolved).not.toHaveBeenCalled();- expect(prepareCanvasInvocation).toHaveBeenCalledTimes(1);- expect(prepareCanvasInvocation.mock.calls[0]?.[0]).toMatchObject({ projectId: project.id });- });-- it('prepares nothing for a Canvas preview of a blank prompt around a layout region while Generate is selected', () => {- const ideogramModel: MainModelConfig = {- base: 'ideogram-4',- format: 'diffusers',- key: 'ideogram-4-model',- name: 'Ideogram 4',- type: 'main',- };- const region: CanvasRegionalGuidanceLayerContract = {- autoNegative: false,- blendMode: 'normal',- id: 'region',- isEnabled: true,- isLocked: false,- mask: { bitmap: { height: 64, imageName: 'region.png', width: 64 }, fill: { color: '#00ff00', style: 'solid' } },- name: 'Region',- negativePrompt: null,- opacity: 1,- positivePrompt: 'a red kite',- referenceImages: [],- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 32, y: 32 },- type: 'regional_guidance',- };- const previewWithPrompt = (positivePrompt: string) => {- const project = withCanvasWidgetMounted(- getActiveProject({- ...getDefaultGenerateSettings(ideogramModel),- model: ideogramModel,- modelKey: ideogramModel.key,- positivePrompt,- })- );- const prepareCanvasInvocation = vi.fn();- const submitted = resolveAndSubmitGraphPreviewInvocation({- commands: createWorkbenchStore().commands,- formatControlLayerError,- formatUpscaleMetadataFailure,- scopedDefaults: {},- models: undefined,- owner: captureAccountScope(),- prepareCanvasInvocation,- project: {- ...project,- canvas: {- ...project.canvas,- document: {- ...project.canvas.document,- bbox: { height: 512, width: 512, x: 0, y: 0 },- stacks: { ...project.canvas.document.stacks, regional_guidance: [region] },- },- },- invocation: { ...project.invocation, sourceId: 'generate' },- },- sourceId: 'canvas',- });- return { prepared: prepareCanvasInvocation.mock.calls.length, submitted };- };-- // Nothing uploads for a submission the compiler would reject; with a prompt the same preview goes ahead.- expect(previewWithPrompt('')).toEqual({ prepared: 0, submitted: false });- expect(previewWithPrompt('a beach at noon')).toEqual({ prepared: 1, submitted: true });- });-- it('dispatches submitResolvedInvocationSnapshot for a non-canvas source and never prepares the canvas', () => {- const project = getActiveProject(createGenerateValues());- const commands = createWorkbenchStore().commands;- const submitResolved = vi.spyOn(commands.generation, 'submitResolved');- const prepareCanvasInvocation = vi.fn();-- const submitted = resolveAndSubmitGraphPreviewInvocation({- commands,- formatControlLayerError,- formatUpscaleMetadataFailure,- scopedDefaults: {},- models: undefined,- owner: captureAccountScope(),- prepareCanvasInvocation,- project,- sourceId: 'generate',- });-- expect(submitted).toBe(true);- expect(prepareCanvasInvocation).not.toHaveBeenCalled();- expect(submitResolved).toHaveBeenCalledTimes(1);- expect(submitResolved.mock.calls[0]?.[0]).toMatchObject({- route: expect.objectContaining({ sourceId: 'generate' }),- });- });-- it('returns false and does not submit while another submission for the project is preparing', () => {- const project = getActiveProject(createGenerateValues());- const commands = createWorkbenchStore().commands;- const submitResolved = vi.spyOn(commands.generation, 'submitResolved');- const heldLease = beginInvocationPreparation(project.id);- expect(heldLease).not.toBeNull();-- try {- const submitted = resolveAndSubmitGraphPreviewInvocation({- commands,- formatControlLayerError,- formatUpscaleMetadataFailure,- scopedDefaults: {},- models: undefined,- owner: captureAccountScope(),- prepareCanvasInvocation: vi.fn(),- project,- sourceId: 'generate',- });-- expect(submitted).toBe(false);- expect(submitResolved).not.toHaveBeenCalled();- } finally {- endInvocationPreparation(heldLease!);- }- });-- it('returns false and does not submit when there is no sourceId', () => {- const project = getActiveProject(createGenerateValues());- const commands = createWorkbenchStore().commands;- const submitResolved = vi.spyOn(commands.generation, 'submitResolved');- const prepareCanvasInvocation = vi.fn();-- const submitted = resolveAndSubmitGraphPreviewInvocation({- commands,- formatControlLayerError,- formatUpscaleMetadataFailure,- scopedDefaults: {},- models: undefined,- owner: captureAccountScope(),- prepareCanvasInvocation,- project,- sourceId: undefined,- });-- expect(submitted).toBe(false);- expect(submitResolved).not.toHaveBeenCalled();- expect(prepareCanvasInvocation).not.toHaveBeenCalled();- });-- it('returns false and does not submit when the resolved route is invalid', () => {- const project = getActiveProject(createGenerateValues({ qwen3EncoderModel: undefined }));- const commands = createWorkbenchStore().commands;- const submitResolved = vi.spyOn(commands.generation, 'submitResolved');- const prepareCanvasInvocation = vi.fn();-- const submitted = resolveAndSubmitGraphPreviewInvocation({- commands,- formatControlLayerError,- formatUpscaleMetadataFailure,- scopedDefaults: {},- models: undefined,- owner: captureAccountScope(),- prepareCanvasInvocation,- project,- sourceId: 'generate',- });-- expect(submitted).toBe(false);- expect(submitResolved).not.toHaveBeenCalled();- expect(prepareCanvasInvocation).not.toHaveBeenCalled();- });-});diff --git a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts b/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.tsdeleted file mode 100644index 3e203b6c02..0000000000--- a/invokeai/frontend/webv2/src/workbench/graphPreviewInvocation.ts+++ /dev/null@@ -1,78 +0,0 @@-import type { ModelConfig } from '@features/models';-import type { AccountScope } from '@platform/state/accountLifecycle';--import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';--import type { InvocationSourceId } from './invocationContracts';-import type { SubmitResolvedInvocationDeps } from './invocationSubmit';-import type { Project } from './projectContracts';-import type { prepareCanvasInvocation } from './widgets/canvas/invoke/prepareCanvasInvocation';-import type { WorkbenchCommands } from './workbenchStore';--import { isInvocationRouteValid, resolveInvocationRoute } from './invocation';-import { beginInvocationPreparation, endInvocationPreparation } from './invocationPreparation';-import { submitResolvedInvocation } from './invocationSubmit';--export interface GraphPreviewInvokeDeps {- commands: Pick<WorkbenchCommands, 'generation' | 'notifications'>;- /** Words a blocked canvas preview's control layer for the notice. */- formatControlLayerError: Parameters<typeof prepareCanvasInvocation>[0]['formatControlLayerError'];- /** Words a Model only upscale preview whose input metadata could not be read. */- formatUpscaleMetadataFailure: SubmitResolvedInvocationDeps['formatUpscaleMetadataFailure'];- models: readonly ModelConfig[] | undefined;- owner: AccountScope;- prepareCanvasInvocation: typeof prepareCanvasInvocation;- project: Project;- scopedDefaults: SubmitResolvedInvocationDeps['scopedDefaults'];- sourceId: InvocationSourceId | undefined;-}--/**- * Resolves and submits a preview against the post-draft-flush project snapshot. Shares the active submission's- * preparation lease, so it reports false while another submission for the project is still preparing.- */-export const resolveAndSubmitGraphPreviewInvocation = ({- commands,- formatControlLayerError,- formatUpscaleMetadataFailure,- models,- owner,- prepareCanvasInvocation: prepareCanvas,- project,- scopedDefaults,- sourceId,-}: GraphPreviewInvokeDeps): boolean => {- if (!sourceId || !isAccountScopeCurrent(owner)) {- return false;- }-- const route = resolveInvocationRoute(- project,- 'dialog',- { ...project.invocation, sourceId, sourceLocked: true },- models- );-- if (!isInvocationRouteValid(route)) {- return false;- }-- const preparationLease = beginInvocationPreparation(project.id);-- if (!preparationLease) {- return false;- }-- void submitResolvedInvocation({- commands,- formatControlLayerError,- formatUpscaleMetadataFailure,- models,- owner,- prepareCanvasInvocation: prepareCanvas,- project,- route,- scopedDefaults,- }).finally(() => endInvocationPreparation(preparationLease));- return true;-};diff --git a/invokeai/frontend/webv2/src/workbench/projects/README.md b/invokeai/frontend/webv2/src/workbench/projects/README.mdindex e2d722a29a..406d745473 100644--- a/invokeai/frontend/webv2/src/workbench/projects/README.md+++ b/invokeai/frontend/webv2/src/workbench/projects/README.md@@ -129,6 +129,8 @@ BFCache entry separately from history reload. See the package [performance guidefor capabilities, artifacts and limits. These smoke results do not expand the Chromium unload guarantee above toall browser versions, real Safari, crashes or storage failure.+Linked workflow runs capture their library id and owner in the queue snapshot at enqueue. Completion credits that saved binding, even if the project copy is later relinked or removed. Recovered runs without a captured binding skip the optional last-run update; they never infer a template from the current project copy. This metadata stays local to the submission snapshot and is stripped from backend enqueue requests.+## Image and queue metadata recallCanvas generation captures its document after paint persistence, together with its detached generation composites. Image `canvas_v3_metadata` version 1 holds that authored document, portable control-model identities and Canvas settings, without project identity, staging, undo history or stored media URLs. Controls that ran are pinned to the resolved model, kind, weight and schedule; the core metadata's `control_layers`, `controlnets` and `t2iAdapters` describe the executed composites. The queue recall cache keeps the same canvas record beside Generate values under its existing account and byte limits. Manual Save Canvas records the exported document and authored Canvas and common Generate settings, model, prompts, concepts and reference images, labelled `metadata_source: canvas_save`; it records neither an executed seed nor a generation mode. Its destination follows the Gallery settings at click time. After paint persistence and export, metadata is captured synchronously from the originating project only if its document is still the one exported, so settings edits during the save are recorded with the unchanged document. A changed document, a closed project or an expired account prevents upload.diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.tsindex 8763247806..bdd4449a41 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunJournal.browser.test.ts@@ -228,7 +228,20 @@ describe('IndexedDB queue run journal', () => {const store = createWorkbenchStore();const projectId = store.getState().activeProjectId;const baseItem = createItem({ backendBatchId: 'batch-1', backendItemIds: [11], status: 'running' });- const item = { ...baseItem, snapshot: { ...baseItem.snapshot, prepend: true } };+ const item = {+ ...baseItem,+ snapshot: {+ ...baseItem.snapshot,+ prepend: true,+ backendSubmission: {+ batchCount: 1,+ graph: { edges: [], id: 'backend-graph-1', nodes: {} },+ kind: 'workflow' as const,+ projectWorkflowId: 'original-project-workflow',+ libraryWorkflowSource: { libraryWorkflowId: 'original-template', ownerUserId: 'user-a' },+ },+ },+ };await journal.record(projectId, item);const loaded = await journal.listForProject(projectId);@@ -244,6 +257,7 @@ describe('IndexedDB queue run journal', () => {backendItemIds: [11],id: item.id,snapshot: expect.objectContaining({+ backendSubmission: item.snapshot.backendSubmission,canvas: item.snapshot.canvas,graph: { id: 'graph-1', label: 'Graph' },prepend: true,diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.test.tsindex 6b0c48a6d3..21988661b0 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.test.ts@@ -1,9 +1,24 @@+import type { ProjectWorkflowSource } from '@features/workflow/contracts';+import type { Project } from '@workbench/projectContracts';import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';import { createDefaultVideoWidgetValues } from '@features/video';-import { expect, it, vi } from 'vitest';+import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';+import { createBlankWorkflowDocument, createProjectWorkflowCollection } from '@workbench/projectWorkflows';+import { beforeEach, describe, expect, it, vi } from 'vitest';-import { withQueueRecallCache } from './queueRunPersistence';+const mocks = vi.hoisted(() => ({ apiFetch: vi.fn() }));++vi.mock('@platform/transport/http', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ apiFetch: mocks.apiFetch,+}));++import {+ getCompletedLibraryWorkflowRun,+ withLibraryWorkflowRunTouch,+ withQueueRecallCache,+} from './queueRunPersistence';it('retains exact recall when a terminal item disappears before journal settlement', async () => {const put = vi.fn().mockResolvedValue({ kind: 'stored' });@@ -50,3 +65,172 @@ it('does not prevent run cleanup when the optional recall cache fails', async ());await expect(persistence.settle('p', 'q')).resolves.toEqual({ kind: 'removed' });});++type RunProject = Pick<Project, 'queue' | 'workflows'>;++const document = createBlankWorkflowDocument();++const project = (+ status: WorkbenchQueueItem['status'],+ { projectWorkflowId = document.id, source }: { projectWorkflowId?: string; source?: ProjectWorkflowSource } = {}+): RunProject => {+ const workflows = createProjectWorkflowCollection(document);+ const queueItem = {+ cancellable: false,+ id: 'run-1',+ snapshot: {+ backendSubmission: {+ batchCount: 1,+ graph: {},+ kind: 'workflow',+ projectWorkflowId,+ ...(source ? { libraryWorkflowSource: { ...source } } : {}),+ },+ },+ status,+ } as unknown as WorkbenchQueueItem;++ return {+ queue: { items: [queueItem] },+ workflows: {+ ...workflows,+ entries: workflows.entries.map((entry) => ({ ...entry, ...(source ? { source } : {}) })),+ },+ };+};++const linked = { source: { libraryWorkflowId: 'wf-user-1', ownerUserId: 'user-a', revision: 3 } };++describe('getCompletedLibraryWorkflowRun', () => {+ const decide = (before: RunProject, after: RunProject, viewerUserId: string | null = null) =>+ getCompletedLibraryWorkflowRun(before, after, 'run-1', viewerUserId);++ it('names the linked template when a run completes', () => {+ expect(decide(project('running', linked), project('completed', linked))).toBe('wf-user-1');+ expect(decide(project('running', linked), project('completed', linked), 'user-a')).toBe('wf-user-1');+ });++ it('credits the enqueued template after relinking or removing the project workflow', () => {+ const before = project('running', linked);+ const after = project('completed', linked);+ after.workflows.entries[0]!.source = { libraryWorkflowId: 'other-template', ownerUserId: 'user-b', revision: 4 };+ expect(decide(before, after, 'user-a')).toBe('wf-user-1');+ after.workflows.entries = [];+ expect(decide(before, after, 'user-a')).toBe('wf-user-1');+ });++ it('bumps a completion only once', () => {+ expect(decide(project('completed', linked), project('completed', linked))).toBe(null);+ });++ it('leaves unlinked workflows and templates another account owns alone', () => {+ expect(decide(project('running'), project('completed'))).toBe(null);+ expect(decide(project('running', linked), project('completed', linked), 'user-b')).toBe(null);+ });++ it('ignores runs that did not complete or predate captured library bindings', () => {+ expect(decide(project('running', linked), project('cancelled', linked))).toBe(null);+ expect(decide(project('running', linked), project('completed', { projectWorkflowId: document.id }))).toBe(null);+ });+});++describe('withLibraryWorkflowRunTouch', () => {+ const payload = { projectId: 'project-1', queueItemId: 'run-1' };+ let current: RunProject;+ let disposed: boolean;++ const setup = (source: ProjectWorkflowSource = linked.source) => {+ current = project('running', { source });+ disposed = false;+ const routeResults = vi.fn(() => {+ current = project('completed', { source });+ });++ return {+ route: withLibraryWorkflowRunTouch(routeResults, {+ getProject: (projectId) => (projectId === payload.projectId ? current : undefined),+ isDisposed: () => disposed,+ owner: captureAccountScope(),+ viewerUserId: null,+ }),+ routeResults,+ };+ };++ /** The workflow data module loads lazily; let the import and the request it starts settle. */+ const settle = async () => {+ await vi.dynamicImportSettled();+ await new Promise((resolve) => {+ setTimeout(resolve, 0);+ });+ };++ beforeEach(() => {+ mocks.apiFetch.mockReset().mockResolvedValue(new Response(null, { status: 204 }));+ accountLifecycle.activate('user-a');+ });++ it('marks the template run once per completion', async () => {+ const { route, routeResults } = setup();++ route(payload);+ route(payload);+ await settle();++ expect(routeResults).toHaveBeenCalledTimes(2);+ expect(mocks.apiFetch).toHaveBeenCalledTimes(1);+ expect(mocks.apiFetch).toHaveBeenCalledWith(+ '/api/v1/workflows/i/wf-user-1/last_run_at',+ expect.objectContaining({ method: 'PUT' })+ );+ });++ it('never marks a bundled template', async () => {+ setup({ libraryWorkflowId: 'default_text_to_image', revision: null }).route(payload);+ await settle();++ expect(mocks.apiFetch).not.toHaveBeenCalled();+ });++ it('sends nothing once the runtime is disposed or the account changed, even while the module loads', async () => {+ const afterDispose = setup();+ disposed = true;+ afterDispose.route(payload);++ const afterAccountChange = setup();+ accountLifecycle.activate('user-b');+ afterAccountChange.route(payload);++ const changedWhileLoading = setup();+ changedWhileLoading.route(payload);+ accountLifecycle.activate('user-c');+ await settle();++ expect(afterDispose.routeResults).toHaveBeenCalledTimes(1);+ expect(afterAccountChange.routeResults).toHaveBeenCalledTimes(1);+ expect(changedWhileLoading.routeResults).toHaveBeenCalledTimes(1);+ expect(mocks.apiFetch).not.toHaveBeenCalled();+ });++ it('keeps a failed request and a failing project read out of result routing', async () => {+ mocks.apiFetch.mockRejectedValue(new Error('offline'));+ const { route, routeResults } = setup();++ expect(() => route(payload)).not.toThrow();+ await settle();++ const throwing = withLibraryWorkflowRunTouch(routeResults, {+ getProject: () => {+ throw new Error('snapshot unavailable');+ },+ isDisposed: () => false,+ owner: captureAccountScope(),+ viewerUserId: null,+ });++ expect(() => throwing(payload)).not.toThrow();+ await settle();+ expect(routeResults).toHaveBeenCalledTimes(2);+ expect(mocks.apiFetch).toHaveBeenCalledTimes(1);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.ts b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.tsindex 75aae385c7..10106e63a1 100644--- a/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.ts+++ b/invokeai/frontend/webv2/src/workbench/queue-integration/queueRunPersistence.ts@@ -1,5 +1,8 @@+import type { Project } from '@workbench/projectContracts';import type { WorkbenchQueueItem } from '@workbench/queueHistoryContracts';+import { type AccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import type { QueueRecallCache, QueueRecallSnapshotInput } from './queueRecallCache';import type { QueueRunJournal } from './queueRunJournal';@@ -44,3 +47,111 @@ export const withQueueRecallCache = <T extends Pick<QueueRunJournal, 'record' |},};};++type RunProject = Pick<Project, 'queue'>;++/**+ * The library template whose `last_run_at` a routed result should bump: the run must have just turned completed+ * (a cancelled run, or a second routing of the same completion, bumps nothing) and come from a project workflow+ * linked to a library template when queued. Older snapshots without a captured binding skip this bookkeeping.+ * Dependency-free so editor boot never loads workflow data; the caller drops bundled templates once it loads.+ * On a multiuser server (`viewerUserId` set) a template whose recorded+ * owner is another account is skipped; a link without a recorded owner is sent, and the server refuses it (403)+ * unless the caller owns the template or is an administrator, whose run then bumps the owner's row.+ */+export const getCompletedLibraryWorkflowRun = (+ before: RunProject | undefined,+ after: RunProject | undefined,+ queueItemId: string,+ viewerUserId: string | null+): string | null => {+ const previous = before?.queue.items.find((item) => item.id === queueItemId);+ const queueItem = after?.queue.items.find((item) => item.id === queueItemId);+ const submission = queueItem?.snapshot.backendSubmission;++ if (+ !after ||+ !queueItem ||+ queueItem.status !== 'completed' ||+ previous?.status === 'completed' ||+ submission?.kind !== 'workflow' ||+ !submission.projectWorkflowId+ ) {+ return null;+ }++ const source = submission.libraryWorkflowSource;++ if (+ !source ||+ typeof source.libraryWorkflowId !== 'string' ||+ (viewerUserId !== null && source.ownerUserId !== undefined && source.ownerUserId !== viewerUserId)+ ) {+ return null;+ }++ return source.libraryWorkflowId;+};++export interface LibraryWorkflowRunTouchOptions {+ getProject(projectId: string): RunProject | undefined;+ isDisposed(): boolean;+ /** The account the queue runtime runs for; nothing is sent once it is no longer current. */+ owner: AccountScope;+ /** The signed-in user on a multiuser server; null in single-user mode. */+ viewerUserId: string | null;+}++/**+ * Routes a run's results, then marks the template it ran from as run (fire and forget). Ordering by last run is a+ * convenience: nothing here can throw into the queue path, and a failed or stale request is dropped. The workflow+ * data module loads only for a completed linked run, so it stays out of the editor's startup bundle.+ */+export const withLibraryWorkflowRunTouch =+ <Payload extends { projectId: string; queueItemId: string }>(+ routeResults: (payload: Payload) => void,+ { getProject, isDisposed, owner, viewerUserId }: LibraryWorkflowRunTouchOptions+ ) =>+ (payload: Payload): void => {+ let before: RunProject | undefined | null = null;++ try {+ before = getProject(payload.projectId);+ } catch {+ // Without the state before routing a repeat cannot be told from a completion; skip the bump.+ }++ routeResults(payload);++ if (before === null) {+ return;+ }++ const isCurrent = () => !isDisposed() && isAccountScopeCurrent(owner);+ let libraryWorkflowId: string | null = null;++ try {+ libraryWorkflowId = getCompletedLibraryWorkflowRun(+ before,+ getProject(payload.projectId),+ payload.queueItemId,+ viewerUserId+ );+ } catch {+ // The run already routed; a failed bump only leaves the template's last run where it was.+ }++ if (!libraryWorkflowId || !isCurrent()) {+ return;+ }++ const touch = async (workflowId: string): Promise<void> => {+ const { isBundledLibraryWorkflowId, touchLibraryWorkflowLastRunAt } = await import('@features/workflow/queries');++ if (!isBundledLibraryWorkflowId(workflowId) && isCurrent()) {+ await touchLibraryWorkflowLastRunAt(workflowId, owner.signal);+ }+ };++ void touch(libraryWorkflowId).catch(() => {});+ };diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsindex 2dac88bc1b..bca1f4d7a8 100644--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -9,8 +9,17 @@ export type { ProjectSortId, ProjectsViewId } from '@workbench/launchpad/projectexport type { WorkbenchLanguage } from '@platform/i18n/languages';-/** What the workflow library's own templates are ordered by (dates newest first, names A to Z). */-export type WorkflowLibrarySortId = 'updated' | 'opened' | 'created' | 'name';+/** What the workflow library's own templates are ordered by. */+export type WorkflowLibrarySortId = 'updated' | 'opened' | 'created' | 'name' | 'lastRun';++/** The library order's direction; changing the key resets it to the key's natural one (dates newest first, names A to Z). */+export type WorkflowLibrarySortDirection = 'asc' | 'desc';++/** How large the workflow library's cards are. */+export type WorkflowLibraryCardSize = 'small' | 'large';++/** Whether the workflow library shows its workflows as a card grid or as list rows. */+export type WorkflowLibraryLayout = 'grid' | 'list';/** How workflow thumbnails fill their 3:2 box: cropped to fill it, or letterboxed to fit whole. */export type WorkflowLibraryThumbnailFit = 'cover' | 'contain';@@ -142,6 +151,10 @@ export interface WorkbenchPreferences {workflowEdgesBehindNodes: boolean;/** Order of the workflow library's own templates. */workflowLibrarySort: WorkflowLibrarySortId;+ workflowLibrarySortDirection: WorkflowLibrarySortDirection;+ workflowLibraryCardSize: WorkflowLibraryCardSize;+ /** The workflow library's and This project's layout; card size and thumbnail fit apply to the grid. */+ workflowLibraryLayout: WorkflowLibraryLayout;/** How workflow library and project cards show their thumbnails. */workflowLibraryThumbnailFit: WorkflowLibraryThumbnailFit;/** Raise text and border contrast on every theme (a11y). */diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex a03abab7df..dec3174526 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -368,17 +368,59 @@ describe('normalizeWorkbenchPreferences prompt editing', () => {});describe('normalizeWorkbenchPreferences workflow library', () => {- it('orders by last update and fills thumbnails unless a known choice is stored', () => {- expect(store.normalizeWorkbenchPreferences({})).toMatchObject({+ const DEFAULTS = {+ workflowLibraryCardSize: 'small',+ workflowLibraryLayout: 'grid',+ workflowLibrarySort: 'updated',+ workflowLibrarySortDirection: 'desc',+ workflowLibraryThumbnailFit: 'cover',+ };++ it('lists most recently updated first in a grid of small filled cards unless a known choice is stored', () => {+ expect(store.normalizeWorkbenchPreferences({})).toMatchObject(DEFAULTS);+ expect(+ store.normalizeWorkbenchPreferences({+ workflowLibraryCardSize: 'huge',+ workflowLibraryLayout: 'table',+ workflowLibrarySort: 'size',+ workflowLibrarySortDirection: 'DESC',+ workflowLibraryThumbnailFit: 'stretch',+ })+ ).toMatchObject(DEFAULTS);+ expect(+ store.normalizeWorkbenchPreferences({+ workflowLibraryCardSize: 'large',+ workflowLibraryLayout: 'list',+ workflowLibrarySort: 'lastRun',+ workflowLibrarySortDirection: 'asc',+ workflowLibraryThumbnailFit: 'contain',+ })+ ).toMatchObject({+ workflowLibraryCardSize: 'large',+ workflowLibraryLayout: 'list',+ workflowLibrarySort: 'lastRun',+ workflowLibrarySortDirection: 'asc',+ workflowLibraryThumbnailFit: 'contain',+ });+ });++ it('gives a key stored before directions existed its natural direction', () => {+ expect(store.normalizeWorkbenchPreferences({ workflowLibrarySort: 'name' })).toMatchObject({+ workflowLibrarySort: 'name',+ workflowLibrarySortDirection: 'asc',+ });+ expect(store.normalizeWorkbenchPreferences({ workflowLibrarySort: 'updated' })).toMatchObject({workflowLibrarySort: 'updated',- workflowLibraryThumbnailFit: 'cover',+ workflowLibrarySortDirection: 'desc',});+ expect(store.normalizeWorkbenchPreferences({ workflowLibrarySort: 'opened' })).toMatchObject({+ workflowLibrarySort: 'opened',+ workflowLibrarySortDirection: 'desc',+ });+ // A stored direction wins.expect(- store.normalizeWorkbenchPreferences({ workflowLibrarySort: 'size', workflowLibraryThumbnailFit: 'stretch' })- ).toMatchObject({ workflowLibrarySort: 'updated', workflowLibraryThumbnailFit: 'cover' });- expect(- store.normalizeWorkbenchPreferences({ workflowLibrarySort: 'opened', workflowLibraryThumbnailFit: 'contain' })- ).toMatchObject({ workflowLibrarySort: 'opened', workflowLibraryThumbnailFit: 'contain' });+ store.normalizeWorkbenchPreferences({ workflowLibrarySort: 'name', workflowLibrarySortDirection: 'desc' })+ ).toMatchObject({ workflowLibrarySortDirection: 'desc' });});});diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex dafaeb6756..2dc2c75329 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -81,7 +81,10 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {workflowEdgeStyle: 'curved',workflowEdgesBehindNodes: false,workflowGroupNodesByCategory: true,+ workflowLibraryCardSize: 'small',+ workflowLibraryLayout: 'grid',workflowLibrarySort: 'updated',+ workflowLibrarySortDirection: 'desc',workflowLibraryThumbnailFit: 'cover',workflowShowMinimap: true,workflowSnapToGrid: false,@@ -157,7 +160,14 @@ const isProjectSortId = (value: unknown): value is ProjectSortId =>value === 'edited' || value === 'created' || value === 'name';const isWorkflowLibrarySortId = (value: unknown): value is WorkflowLibrarySortId =>- value === 'updated' || value === 'opened' || value === 'created' || value === 'name';+ value === 'updated' || value === 'opened' || value === 'created' || value === 'name' || value === 'lastRun';++/**+ * A stored direction, or the stored key's natural one (dates newest first, names A to Z): accounts that chose a key+ * before directions existed keep the order they had.+ */+const normalizeWorkflowLibrarySortDirection = (direction: unknown, sort: WorkflowLibrarySortId) =>+ direction === 'asc' || direction === 'desc' ? direction : sort === 'name' ? 'asc' : 'desc';const normalizePinnedProjectIds = (values: unknown): string[] =>Array.isArray(values) ? [...new Set(values.filter((value): value is string => typeof value === 'string'))] : [];@@ -401,7 +411,10 @@ type WorkbenchPreferencesInput = Omit<| 'queueJobsScope'| 'startupDestination'| 'workflowEdgeStyle'+ | 'workflowLibraryCardSize'+ | 'workflowLibraryLayout'| 'workflowLibrarySort'+ | 'workflowLibrarySortDirection'| 'workflowLibraryThumbnailFit'> & {launchpadProjectsSort?: unknown;@@ -409,7 +422,10 @@ type WorkbenchPreferencesInput = Omit<queueJobsScope?: unknown;startupDestination?: unknown;workflowEdgeStyle?: unknown;+ workflowLibraryCardSize?: unknown;+ workflowLibraryLayout?: unknown;workflowLibrarySort?: unknown;+ workflowLibrarySortDirection?: unknown;workflowLibraryThumbnailFit?: unknown;/** Pre-beta name of `betaNoticeAcknowledged`; accounts that dismissed the alpha notice skip the beta one. */alphaNoticeAcknowledged?: unknown;@@ -533,9 +549,19 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferencestypeof preferences?.workflowGroupNodesByCategory === 'boolean'? preferences.workflowGroupNodesByCategory: DEFAULT_PREFERENCES.workflowGroupNodesByCategory,+ workflowLibraryCardSize:+ preferences?.workflowLibraryCardSize === 'large' ? 'large' : DEFAULT_PREFERENCES.workflowLibraryCardSize,+ workflowLibraryLayout:+ preferences?.workflowLibraryLayout === 'list' ? 'list' : DEFAULT_PREFERENCES.workflowLibraryLayout,workflowLibrarySort: isWorkflowLibrarySortId(preferences?.workflowLibrarySort)? preferences.workflowLibrarySort: DEFAULT_PREFERENCES.workflowLibrarySort,+ workflowLibrarySortDirection: normalizeWorkflowLibrarySortDirection(+ preferences?.workflowLibrarySortDirection,+ isWorkflowLibrarySortId(preferences?.workflowLibrarySort)+ ? preferences.workflowLibrarySort+ : DEFAULT_PREFERENCES.workflowLibrarySort+ ),workflowLibraryThumbnailFit:preferences?.workflowLibraryThumbnailFit === 'contain'? 'contain'diff --git a/invokeai/frontend/webv2/src/workbench/shell/WhatsNewDialog.tsx b/invokeai/frontend/webv2/src/workbench/shell/WhatsNewDialog.tsxindex 986d36088e..c7c7acba7f 100644--- a/invokeai/frontend/webv2/src/workbench/shell/WhatsNewDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/WhatsNewDialog.tsx@@ -58,12 +58,6 @@ const HIGHLIGHTS: readonly { descriptionKey: string; icon: LucideIcon; multiuserconst readItems = (value: unknown): string[] =>Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];-/**- * The modal traps focus, so focus outside it is never the user leaving. Under StrictMode the first, lazily loaded- * mount restores focus to the launcher button mid-open, and the stale dismiss layer closed the notes on that.- */-const keepOpenOnFocusOutside = (event: { preventDefault: () => void }) => event.preventDefault();-export const WhatsNewDialog = ({ onExitComplete }: { onExitComplete?: () => void }) => {const { t } = useTranslation();const { isOpen, isUnseen, version } = useWhatsNew();@@ -102,7 +96,6 @@ export const WhatsNewDialog = ({ onExitComplete }: { onExitComplete?: () => voidscrollBehavior="inside"size="lg"onExitComplete={onExitComplete}- onFocusOutside={keepOpenOnFocusOutside}onOpenChange={handleOpenChange}><Portal>diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.focus.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.focus.browser.test.tsxindex f45a660e9c..a2884c40ab 100644--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.focus.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.focus.browser.test.tsx@@ -133,7 +133,7 @@ vi.mock('./PasteMediaRuntime', () => ({ PasteMediaRuntime: () => null }));vi.mock('./ProjectConflictBanner', () => ({ ProjectConflictBanner: () => null }));vi.mock('./QueueRecoveryBanner', () => ({ QueueRecoveryBanner: () => null }));vi.mock('./StatusBar', () => ({ StatusBar: () => null }));-vi.mock('./topbar', () => ({ TopBar: () => null }));+vi.mock('./topbar', () => ({ GraphPreviewInvokeScope: () => null, TopBar: () => null }));import { WorkbenchShell } from './WorkbenchShell';diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsxindex 52c8276d1a..6d695385ef 100644--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx@@ -17,6 +17,7 @@ import { WidgetIcon } from '@workbench/iconResolver';import { PROJECT_CONTENT_PANEL_ID } from '@workbench/projects/projectTabsA11y';import { WidgetBar, type WidgetBarGroup } from '@workbench/widget-frame';import { FloatingWidgetLayer } from '@workbench/widget-frame/FloatingWidgetLayer';+import { GraphPreviewInvokeScopeContext } from '@workbench/widget-frame/graphPreviewInvoke';import {getRegionDropState,isWidgetDndData,@@ -58,7 +59,7 @@ import { PasteMediaRuntime } from './PasteMediaRuntime';import { ProjectConflictBanner } from './ProjectConflictBanner';import { QueueRecoveryBanner } from './QueueRecoveryBanner';import { StatusBar } from './StatusBar';-import { TopBar } from './topbar';+import { GraphPreviewInvokeScope, TopBar } from './topbar';const DND_MODIFIERS = [restrictToWindowEdges];@@ -298,68 +299,70 @@ export const WorkbenchShell = () => {onDragStart={handleDragStart}><GalleryDragScope value>- <Flex direction="column" h="100vh" w="100vw">- <WorkbenchNotificationToaster />- <LayoutUndoNotices />- <DocumentTitleProgress />- <TopBar />- <ProjectConflictBanner />- <QueueRecoveryBanner />+ <GraphPreviewInvokeScopeContext value={GraphPreviewInvokeScope}>+ <Flex direction="column" h="100vh" w="100vw">+ <WorkbenchNotificationToaster />+ <LayoutUndoNotices />+ <DocumentTitleProgress />+ <TopBar />+ <ProjectConflictBanner />+ <QueueRecoveryBanner />- <Flex aria-labelledby="workbench-project-heading" as="main" flex="1" minH="0" overflow="hidden">- <VisuallyHidden as="h1" id="workbench-project-heading">- {projectName}- </VisuallyHidden>- {/* Use a named content region: the project switcher is no longer a tablist. */}- <Flex- aria-labelledby="workbench-project-heading"- flex="1"- id={PROJECT_CONTENT_PANEL_ID}- minH="0"- overflow="hidden"- role="region"- >- <WidgetBar- edgeRegion={isLeftPanelShown ? 'left' : 'center'}- groups={leftRailGroups}- menuItems={leftMenuItems}- projectId={projectId}- side="left"- onDock={handleDock}- onRemoveFloating={handleRemoveFloating}- onSelect={handleSelect}- onToggle={handleToggleLeft}- />- {isLeftPanelShown ? <LeftPanel instanceId={leftRegion.activeInstanceId} /> : null}- <CenterArea />- {isRightPanelShown ? <RightPanel instanceId={rightRegion.activeInstanceId} /> : null}- <WidgetBar- edgeRegion={isRightPanelShown ? 'right' : 'center'}- groups={rightRailGroups}- menuItems={rightMenuItems}- projectId={projectId}- side="right"- onDock={handleDock}- onRemoveFloating={handleRemoveFloating}- onSelect={handleSelect}- onToggle={handleToggleRight}- />+ <Flex aria-labelledby="workbench-project-heading" as="main" flex="1" minH="0" overflow="hidden">+ <VisuallyHidden as="h1" id="workbench-project-heading">+ {projectName}+ </VisuallyHidden>+ {/* Use a named content region: the project switcher is no longer a tablist. */}+ <Flex+ aria-labelledby="workbench-project-heading"+ flex="1"+ id={PROJECT_CONTENT_PANEL_ID}+ minH="0"+ overflow="hidden"+ role="region"+ >+ <WidgetBar+ edgeRegion={isLeftPanelShown ? 'left' : 'center'}+ groups={leftRailGroups}+ menuItems={leftMenuItems}+ projectId={projectId}+ side="left"+ onDock={handleDock}+ onRemoveFloating={handleRemoveFloating}+ onSelect={handleSelect}+ onToggle={handleToggleLeft}+ />+ {isLeftPanelShown ? <LeftPanel instanceId={leftRegion.activeInstanceId} /> : null}+ <CenterArea />+ {isRightPanelShown ? <RightPanel instanceId={rightRegion.activeInstanceId} /> : null}+ <WidgetBar+ edgeRegion={isRightPanelShown ? 'right' : 'center'}+ groups={rightRailGroups}+ menuItems={rightMenuItems}+ projectId={projectId}+ side="right"+ onDock={handleDock}+ onRemoveFloating={handleRemoveFloating}+ onSelect={handleSelect}+ onToggle={handleToggleRight}+ />+ </Flex></Flex>- </Flex>- <BottomPanel />- <StatusBar dropState={bottomDropState} />- </Flex>- <FloatingWidgetLayer />- <GalleryDragCursor />- <PasteMediaRuntime />- {/*- * Allow pointer events through the full-size drag overlay so another finger can reach Preview pinch- * handlers.- */}- <DragOverlay style={DRAG_OVERLAY_STYLE}>- {activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}- </DragOverlay>+ <BottomPanel />+ <StatusBar dropState={bottomDropState} />+ </Flex>+ <FloatingWidgetLayer />+ <GalleryDragCursor />+ <PasteMediaRuntime />+ {/*+ * Allow pointer events through the full-size drag overlay so another finger can reach Preview pinch+ * handlers.+ */}+ <DragOverlay style={DRAG_OVERLAY_STYLE}>+ {activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}+ </DragOverlay>+ </GraphPreviewInvokeScopeContext></GalleryDragScope></DndContext>);diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/GraphPreviewInvokeScope.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/GraphPreviewInvokeScope.browser.test.tsxnew file mode 100644index 0000000000..b5c816efbd--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/GraphPreviewInvokeScope.browser.test.tsx@@ -0,0 +1,318 @@+import type { GraphPreviewSourceState, InvocationTemplatesSnapshot } from '@features/workflow/contracts';+import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workflow/react';+import type * as UseShortcutBindingModule from '@workbench/hotkeys/useShortcutBinding';+import type { InvocationIssue, InvocationState } from '@workbench/shell/topbar/useInvocationState';+import type * as UseInvocationStateModule from '@workbench/shell/topbar/useInvocationState';++import { ChakraProvider } from '@chakra-ui/react';+import { GraphPreviewDialog } from '@features/workflow/preview';+import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/react';+import { createProjectGraph } from '@features/workflow/utility';+import { system } from '@theme/system';+import { act, StrictMode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++import { GraphPreviewInvokeScope } from './GraphPreviewInvokeScope';+import { InvokeButton } from './InvokeButton';++/**+ * The View graph dialog's Invoke: the top bar's control bound to the previewed source's route. The route state is the+ * workbench's (`useInvocationState`, tested on its own); here it is the state a blocked or ready Canvas route+ * publishes, so the control, its card and the dialog meet as they do in the app.+ */+const harness = vi.hoisted(() => ({+ requestedSources: [] as (string | undefined)[],+ revealed: [] as string[],+ fixed: [] as string[],+ state: null as unknown as InvocationState,+}));++vi.mock('@workbench/shell/topbar/useInvocationState', async (importOriginal) => ({+ ...(await importOriginal<typeof UseInvocationStateModule>()),+ useInvocationState: ({ sourceId }: { sourceId?: string } = {}) => {+ harness.requestedSources.push(sourceId);+ return harness.state;+ },+}));+vi.mock('@workbench/queue-integration/useActiveQueueProgress', () => ({+ useActiveQueueProgress: () => ({ progress: null, queueItems: [], summary: { current: 0, remaining: 0, total: 0 } }),+}));+vi.mock('@workbench/useNotify', () => ({ useNotify: () => ({ error: () => {} }) }));+vi.mock('@workbench/hotkeys/useShortcutBinding', async (importOriginal) => ({+ ...(await importOriginal<typeof UseShortcutBindingModule>()),+ // The app's Invoke shortcut is bound, as it is by default.+ useShortcutBinding: (commandId: string) =>+ commandId === 'app.invoke' ? { aria: 'Control+Enter', display: 'Ctrl+Enter', parts: ['ctrl', 'enter'] } : null,+}));+// Each layer issue offers a fix that stays and a way to the layer that leads away, as the real actions do.+vi.mock('@workbench/shell/topbar/invokeIssueActions', () => ({+ useInvokeIssueActions: () => (issue: InvocationIssue) =>+ issue.target.kind === 'layer'+ ? [+ { id: 'fix', label: 'Fix', run: () => harness.fixed.push('control-2'), stays: true },+ { id: 'show', label: 'Show layer', run: () => harness.revealed.push('control-2') },+ ]+ : [],+}));+vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ ensureModelsLoaded: vi.fn(() => Promise.resolve()),+ ensureStartersLoaded: vi.fn(),+ useActiveInstallSources: () => new Set<string>(),+ useModelsSelector: (selector: (snapshot: unknown) => unknown) => selector({ models: [] }),+ useStartersSelector: (selector: (snapshot: unknown) => unknown) => selector({ response: { starter_models: [] } }),+}));++const TEMPLATES_SNAPSHOT = vi.hoisted((): InvocationTemplatesSnapshot => ({+ error: null,+ status: 'loaded',+ templates: {},+}));++vi.mock('@features/workflow/react', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useInvocationTemplatesSnapshot: () => TEMPLATES_SNAPSHOT,+}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { count?: number }) => (options?.count === undefined ? key : `${key}(${options.count})`),+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const LAYER_ISSUE: InvocationIssue = {+ message: 'Control layer "Depth 1": Choose a model.',+ target: { kind: 'layer', layerId: 'control-2' },+};++const makeState = (overrides: Partial<InvocationState> = {}): InvocationState => ({+ batchCount: 1,+ invocation: { destination: 'gallery', destinationLocked: false, sourceId: 'canvas', sourceLocked: true },+ invoke: vi.fn(() => Promise.resolve()),+ issues: [],+ isPreparing: false,+ isValid: true,+ placedTypeIds: new Set(),+ promptExpansion: {+ count: 1,+ error: null,+ isDynamic: false,+ isError: false,+ isLoading: false,+ isRetrying: false,+ prompts: [],+ retry: vi.fn(),+ },+ sourceValues: {},+ sources: [],+ visibleTypeIds: new Set(),+ ...overrides,+});++const SOURCE: GraphPreviewSourceState = {+ destinationLabel: 'Gallery',+ graph: {+ edges: [],+ id: 'canvas-graph',+ nodes: [{ id: 'decode', inputs: {}, type: 'l2i' }],+ version: 1,+ },+ invalidReasons: [],+ isLive: false,+ notices: [],+ summaryRows: [],+};++const project = createProjectGraph('workflow-1');+const ADAPTER = {+ capabilities: { getSnapshot: () => ({ canUseCache: true }), subscribe: () => () => {} },+ commands: { addWorkflow: vi.fn() },+ getProjectGraph: () => project,+ nodeExecution: { get: () => null, getOrigin: () => null, subscribe: () => () => {}, subscribeOrigin: () => () => {} },+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ performance: { mark: vi.fn(), measure: vi.fn(), time: (_n: string, _s: unknown, run: () => unknown) => run() },+ preferences: {+ getSnapshot: () => ({ reduceMotion: false, themeId: 'classic', workflowEdgeStyle: 'curved' }),+ subscribe: () => () => {},+ },+ project: {+ getSnapshot: () => ({+ activeWorkflow: { document: project },+ id: 'project-1',+ projectGraph: project,+ workflows: [],+ }),+ subscribe: () => () => {},+ },+ widgets: { open: vi.fn(), patchValues: vi.fn() },+} as unknown as WorkflowUiAdapter;+const PORT: WorkflowGraphPreviewPort = {+ focusSource: vi.fn(),+ openDocumentInNewProject: vi.fn(),+ openWorkflowEditor: vi.fn(),+};++const Preview = ({ onOpenChange }: { onOpenChange: (isOpen: boolean) => void }) => (+ <GraphPreviewInvokeScope+ // oxlint-disable-next-line react-perf/jsx-no-new-function-as-prop -- one preview per test render.+ render={(invoke) => (+ <GraphPreviewDialog+ graphId="canvas-graph"+ invoke={invoke}+ isOpen+ source={SOURCE}+ sourceId="canvas"+ sourceLabel="Canvas"+ onOpenChange={onOpenChange}+ />+ )}+ sourceId="canvas"+ onOpenChange={onOpenChange}+ />+);++describe('a graph preview’s Invoke', () => {+ let host: HTMLDivElement;+ let root: Root;+ let onOpenChange: ReturnType<typeof vi.fn<(isOpen: boolean) => void>>;+ /** The top bar's own Invoke, for the active route, mounted beside the dialog as in the app. */+ let topBarState: InvocationState;++ const render = (state: InvocationState) => {+ harness.state = state;++ return act(() =>+ root.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <InvokeButton state={topBarState} />+ <WorkflowUiProvider adapter={ADAPTER}>+ <WorkflowGraphPreviewProvider adapter={PORT}>+ <Preview onOpenChange={onOpenChange} />+ </WorkflowGraphPreviewProvider>+ </WorkflowUiProvider>+ </ChakraProvider>+ </StrictMode>+ )+ );+ };++ const footer = () => document.querySelector<HTMLElement>('[data-graph-preview-footer]');+ const dialogContent = () => document.querySelector<HTMLElement>('[data-scope="dialog"][data-part="content"]');+ const previewInvoke = () => footer()?.querySelector<HTMLButtonElement>('button[aria-keyshortcuts]') ?? null;+ const card = () => document.querySelector<HTMLElement>('[data-invoke-card-mode]');+ const settle = () =>+ act(async () => {+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 50);+ });+ });++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ onOpenChange = vi.fn<(isOpen: boolean) => void>();+ topBarState = makeState({+ invocation: { destination: 'gallery', destinationLocked: false, sourceId: 'generate', sourceLocked: false },+ });+ harness.requestedSources = [];+ harness.revealed = [];+ harness.fixed = [];+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('is the top bar’s control for the previewed source, the same height as the footer’s other button', async () => {+ const previous = { height: window.innerHeight, width: window.innerWidth };+ await page.viewport(1288, 942);+ onTestFinished(() => page.viewport(previous.width, previous.height));+ await render(makeState());++ expect(harness.requestedSources).toContain('canvas');+ expect(previewInvoke()?.textContent).toContain('topbar.invoke.invoke');+ const editAsWorkflow = footer()!.querySelector<HTMLElement>('[data-graph-preview-edit-as-workflow]')!;+ expect(previewInvoke()!.getBoundingClientRect().height).toBe(editAsWorkflow.getBoundingClientRect().height);+ // On one line with the status.+ const status = footer()!.querySelector<HTMLElement>('[data-graph-preview-status]')!.getBoundingClientRect();+ const button = previewInvoke()!.getBoundingClientRect();+ expect(Math.abs(status.top + status.height / 2 - (button.top + button.height / 2))).toBeLessThan(2);+ });++ it('advertises no app shortcut, which does nothing in a dialog, while the top bar’s Invoke still does', async () => {+ await render(makeState());++ const topBar = host.querySelector<HTMLButtonElement>(':scope > button')!;++ expect(topBar.getAttribute('aria-keyshortcuts')).toBe('Control+Enter ArrowDown');+ expect(topBar.querySelector('kbd')).not.toBeNull();+ expect(previewInvoke()?.getAttribute('aria-keyshortcuts')).toBe('ArrowDown');+ expect(previewInvoke()?.querySelector('kbd')).toBeNull();+ });++ it('runs the previewed route once and closes, leaving the top bar’s Invoke alone', async () => {+ const state = makeState({ invoke: vi.fn((options) => Promise.resolve(options?.onStarted?.())) });+ await render(state);++ await act(() => userEvent.click(previewInvoke()!));++ expect(state.invoke).toHaveBeenCalledTimes(1);+ expect(topBarState.invoke).not.toHaveBeenCalled();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('opens its issue card above the dialog, with the route fixed, and closes the dialog for a way out', async () => {+ await render(makeState({ issues: [LAYER_ISSUE], isValid: false }));++ expect(previewInvoke()?.textContent).toContain('topbar.invoke.issueCount(1)');+ await act(() => userEvent.click(previewInvoke()!));+ await vi.waitFor(() => expect(card()?.textContent).toContain('Choose a model.'));+ await settle();++ // Above the dialog: what is under the card's centre is the card.+ const box = card()!.getBoundingClientRect();+ expect(card()!.contains(document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2))).toBe(true);+ expect(dialogContent()?.contains(card())).toBe(false);+ // The route is the preview's: shown, with nothing to switch or lock.+ expect(card()!.querySelector('[data-invoke-route-fixed]')).not.toBeNull();+ expect(card()!.querySelector('[data-routing-lock]')).toBeNull();+ // Focus went into the card, past the dialog's trap.+ expect(card()!.contains(document.activeElement)).toBe(true);++ // A fix acts in place: the card and the dialog stay.+ await act(() => userEvent.click([...card()!.querySelectorAll('button')].find((b) => b.textContent === 'Fix')!));+ expect(harness.fixed).toEqual(['control-2']);+ expect(onOpenChange).not.toHaveBeenCalled();++ await act(() =>+ userEvent.click([...card()!.querySelectorAll('button')].find((b) => b.textContent === 'Show layer')!)+ );++ expect(harness.revealed).toEqual(['control-2']);+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('closes on Escape its card first, then the dialog', async () => {+ await render(makeState({ issues: [LAYER_ISSUE], isValid: false }));+ await act(() => userEvent.click(previewInvoke()!));+ await vi.waitFor(() => expect(card()).not.toBeNull());+ await settle();++ await act(() => userEvent.keyboard('{Escape}'));+ await act(async () => {+ await vi.waitFor(() => expect(card()).toBeNull());+ });++ expect(onOpenChange).not.toHaveBeenCalled();++ await act(() => userEvent.keyboard('{Escape}'));++ expect(onOpenChange).toHaveBeenCalledWith(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/GraphPreviewInvokeScope.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/GraphPreviewInvokeScope.tsxnew file mode 100644index 0000000000..d141d5a93a--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/GraphPreviewInvokeScope.tsx@@ -0,0 +1,31 @@+import type { GraphPreviewInvokeScopeProps } from '@workbench/widget-frame/graphPreviewInvoke';++import { useCallback, useMemo } from 'react';++import { InvokeButton } from './InvokeButton';+import { type InvocationState, useInvocationState } from './useInvocationState';++/**+ * A graph preview's Invoke: this top bar's control, for the previewed source's route rather than the active one, its+ * issue card, fixes, preparing state and iterations included. The route is the preview's, so the card shows it without+ * a picker or lock, and the control takes a dialog footer's button size. A run that starts, or an issue's action that+ * leads elsewhere, closes the preview. The shell provides it to widget frames (`GraphPreviewInvokeScopeContext`).+ */+export const GraphPreviewInvokeScope = ({ render, sourceId, onOpenChange }: GraphPreviewInvokeScopeProps) => {+ const state = useInvocationState({ sourceId });+ const close = useCallback(() => onOpenChange(false), [onOpenChange]);+ const { invoke, isValid } = state;+ const previewState = useMemo<InvocationState>(+ () => ({ ...state, invoke: (options) => invoke({ ...options, onStarted: close }) }),+ [close, invoke, state]+ );+ const slot = useMemo(+ () => ({+ control: <InvokeButton isRouteFixed size="md" state={previewState} onJump={close} />,+ isReady: isValid,+ }),+ [close, isValid, previewState]+ );++ return render(slot);+};diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsxindex 1fc89b0d9d..e61d2af8b4 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.tsx@@ -69,12 +69,28 @@ interface PendingOpen {* keyboard focus-visible restores play to signal that more work can queue. While issues block it, the button turns* secondary and opens the list of them, each with the way to its fix.*/-export const InvokeButton = ({ state }: { state: InvocationState }) => {+export const InvokeButton = ({+ isRouteFixed = false,+ size = 'lg',+ state,+ onJump,+}: {+ /** The route is the host's to fix (a graph preview's source): the card shows it, with no source, destination or lock to change. */+ isRouteFixed?: boolean;+ /** The control height: the top bar's own, or the host's (a dialog footer's buttons). */+ size?: 'lg' | 'md';+ state: InvocationState;+ /** Hears an issue's action leading elsewhere, after the card has closed (a host dialog closes too). */+ onJump?: () => void;+}) => {const { t } = useTranslation();const notify = useNotify();const { invoke, isPreparing, isValid, issues } = state;- const shortcutBinding = useShortcutBinding('app.invoke');- const frontBinding = useShortcutBinding('app.invokeFront');+ // App shortcuts do nothing while a modal is open, and they run the active route: a host's copy advertises none.+ const appShortcut = useShortcutBinding('app.invoke');+ const appFrontShortcut = useShortcutBinding('app.invokeFront');+ const shortcutBinding = isRouteFixed ? null : appShortcut;+ const frontBinding = isRouteFixed ? null : appFrontShortcut;const shortcutParts = shortcutBinding?.parts ?? null;// Shift+click queues at the front: holding it over a ready button says so before the click.const isShiftHeld = useModifierHeld('Shift');@@ -102,7 +118,7 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {const [isHovered, setIsHovered] = useState(false);const [isFocused, setIsFocused] = useState(false);const canInvoke = isValid && !isPreparing;- const isLocked = isRoutingLocked(state.invocation);+ const isLocked = !isRouteFixed && isRoutingLocked(state.invocation);// Blocked by issues: the count replaces the shortcut, and activation opens the issue list.const showsIssues = !isValid && !isPreparing && issues.length > 0;@@ -342,7 +358,8 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {const handleJump = useCallback(() => {clearTimers();setMode('closed');- }, [clearTimers]);+ onJump?.();+ }, [clearTimers, onJump]);const getButton = useCallback(() => buttonRef.current, []);// The button is the popover's anchor, not its trigger: pressing it while open is its own toggle, not an outside press.const persistentElements = useMemo(() => [getButton], [getButton]);@@ -400,7 +417,7 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {cursor={isPreparing ? 'not-allowed' : undefined}data-blocked={showsIssues ? '' : undefined}flexShrink={0}- size="lg"+ size={size}// Blocked is not disabled: the button opens what is in the way. It steps back from the primary color so it// no longer reads as ready.variant={showsIssues ? 'outline' : 'solid'}@@ -486,6 +503,7 @@ export const InvokeButton = ({ state }: { state: InvocationState }) => {{PopoverBody ? (<PopoverBodyfrontShortcut={frontBinding?.display ?? null}+ isRouteFixed={isRouteFixed}shortcutParts={shortcutParts}state={state}onJump={handleJump}diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokePopoverBody.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokePopoverBody.tsxindex fec56cb6ae..e04256655f 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokePopoverBody.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokePopoverBody.tsx@@ -19,11 +19,14 @@ import { TopbarShortcutKeys } from './TopbarShortcutKeys';/** The Invoke card: what runs, where it goes, and each issue in the way with its fixes. Loads on first hover or focus. */export const InvokePopoverBody = ({frontShortcut,+ isRouteFixed,onJump,shortcutParts,state,}: {frontShortcut: string | null;+ /** The host fixes the route: it reads as text, with nothing to switch or lock. */+ isRouteFixed: boolean;/** An action that leads elsewhere closes the list, leaving focus where the action put it. */onJump: () => void;shortcutParts: string[] | null;@@ -74,7 +77,7 @@ export const InvokePopoverBody = ({</Kbd>) : null}</HStack>- <InvokeRoute state={state} />+ {isRouteFixed ? <FixedRoute state={state} /> : <InvokeRoute state={state} />}<Text color="fg.muted" fontSize="xs">{summary}</Text>@@ -197,6 +200,27 @@ const InvokeRoute = ({ state }: { state: InvocationState }) => {);};+/** The route as text: where Invoke runs from and where its results go, set by the host rather than here. */+const FixedRoute = ({ state }: { state: InvocationState }) => {+ const { t } = useTranslation();+ const { invocation } = state;++ return (+ <Stack data-invoke-route="" data-invoke-route-fixed="" gap="2.5">+ <Stack align="start" gap="1">+ <Text {...ROUTE_LABEL_PROPS}>{t('topbar.routing.source')}</Text>+ <Text {...ROUTE_VALUE_PROPS}>{t(ROUTE_LABEL_KEYS[invocation.sourceId])}</Text>+ </Stack>+ <Stack align="start" gap="1">+ <Text {...ROUTE_LABEL_PROPS}>{t('topbar.routing.destination')}</Text>+ <Text {...ROUTE_VALUE_PROPS}>+ {t(ROUTE_LABEL_KEYS[invocation.sourceId === 'video' ? 'gallery' : invocation.destination])}+ </Text>+ </Stack>+ </Stack>+ );+};+const InvokeIssueList = ({ issues, onJump }: { issues: readonly InvocationIssue[]; onJump: () => void }) => {const getActions = useInvokeIssueActions();diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/index.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/index.tsindex 40f2ccdd93..89d9745aa0 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/index.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/index.ts@@ -1 +1,2 @@+export { GraphPreviewInvokeScope } from './GraphPreviewInvokeScope';export { TopBar } from './TopBar';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 305644e241..0b0a2c5345 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@@ -150,12 +150,18 @@ const buildGenerateProject = (): Project => {let host: HTMLDivElement | null = null;let root: Root | null = null;-const Probe = (): ReactNode => {- const state = useInvocationState();+const Probe = ({ sourceId }: { sourceId?: 'video' }): ReactNode => {+ const state = useInvocationState({ sourceId });return (<>- <span data-batch-count={state.batchCount} data-prompt-count={state.promptExpansion.count} data-testid="reasons">+ <span+ data-batch-count={state.batchCount}+ data-destination={state.invocation.destination}+ data-issue-targets={state.issues.map((issue) => issue.target.kind).join(' ')}+ data-prompt-count={state.promptExpansion.count}+ data-testid="reasons"+ >{state.issues.map((issue) => issue.message).join(' | ')}</span><span data-testid="issue-layers">@@ -171,13 +177,13 @@ const Probe = (): ReactNode => {);};-const renderProbe = async (project: Project) => {+const renderProbe = async (project: Project, sourceId?: 'video') => {harness.project = project;host = document.createElement('div');document.body.append(host);root = createRoot(host);await act(() => {- root?.render(<Probe />);+ root?.render(<Probe sourceId={sourceId} />);});};@@ -294,6 +300,17 @@ describe('useInvocationState and the remembered control-model picks', () => {});describe('useInvocationState and Video dynamic prompts', () => {+ it('fixes the Video dialog route to Gallery without offering a global destination fix', async () => {+ const project = buildGenerateProject();+ project.invocation = { sourceId: 'generate', sourceLocked: true, destination: 'canvas', destinationLocked: true };+ await renderProbe(project, 'video');+ expect(host?.querySelector('[data-testid="reasons"]')?.getAttribute('data-destination')).toBe('gallery');+ expect(host?.querySelector('[data-testid="reasons"]')?.getAttribute('data-issue-targets')).not.toContain(+ 'destination'+ );+ expect(project.invocation.destination).toBe('canvas');+ });+const renderVideo = async (videoValues: Record<string, unknown>) => {setArchitectureCapabilities(architectureCapabilitiesFixture);let state = workbenchReducer(createInitialWorkbenchState(), {diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.tsindex ae6a97f858..a835da3abd 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/useInvocationState.ts@@ -1,6 +1,6 @@import type { DynamicPromptsExpansion } from '@features/generation/react';import type { GraphWidgetSource } from '@workbench/graphWidgets';-import type { InvocationRoute, ResultDestination } from '@workbench/invocationContracts';+import type { InvocationRoute, InvocationSourceId, ResultDestination } from '@workbench/invocationContracts';import type { WidgetTypeId } from '@workbench/widgetContracts';import { useDynamicPrompts } from '@features/generation/react';@@ -130,9 +130,15 @@ export interface InvokeOptions {destinationOverride?: ResultDestination;/** Queue ahead of the user's other pending work, as Invoke Front does. */prepend?: boolean;+ /** Hears that the run has started (valid, and holding the project's preparation lease). */+ onStarted?: () => void;}-export const useInvocationState = (): InvocationState => {+/**+ * Invoke's state for the active route; given a `sourceId`, for that source's route instead, its source fixed (a graph+ * preview's Invoke), with the active route's destination. Video's fixed route always uses Gallery.+ */+export const useInvocationState = ({ sourceId }: { sourceId?: InvocationSourceId } = {}): InvocationState => {const { t } = useTranslation();const routeInput = useActiveProjectSelector(selectInvocationRouteInput);const visibleTypeIds = useActiveProjectSelector(getVisibleWidgetTypeIds, areTypeIdSetsEqual);@@ -143,7 +149,18 @@ export const useInvocationState = (): InvocationState => {const models = useModelsSelector((snapshot) => snapshot.models);const modelsStatus = useModelsSelector((snapshot) => snapshot.status);const availabilityModels = modelsStatus === 'loaded' ? models : undefined;- const { invocation } = routeInput;+ const invocation = useMemo(+ () =>+ sourceId+ ? {+ ...routeInput.invocation,+ ...(sourceId === 'video' ? { destination: 'gallery' as const } : {}),+ sourceId,+ sourceLocked: true,+ }+ : routeInput.invocation,+ [routeInput.invocation, sourceId]+ );const isPreparing = useIsInvocationPreparing(routeInput.projectId);useMountEffect(() => {@@ -156,8 +173,8 @@ export const useInvocationState = (): InvocationState => {subscribeRouteSources,getRouteSourcesSnapshot,useCallback(- () => resolveInvocationRouteInput(routeInput, 'global', invocation, availabilityModels),- [availabilityModels, invocation, routeInput]+ () => resolveInvocationRouteInput(routeInput, sourceId ? 'dialog' : 'global', invocation, availabilityModels),+ [availabilityModels, invocation, routeInput, sourceId]));const isConnected = backendConnectionStatus === 'connected';@@ -208,17 +225,19 @@ export const useInvocationState = (): InvocationState => {const isValid = isInvocationRouteValid(resolvedRoute) && isConnected && expansionReason === null;const invoke = useCallback(- ({ destinationOverride, prepend }: InvokeOptions = {}) =>+ ({ destinationOverride, onStarted, prepend }: InvokeOptions = {}) =>submitActiveInvocation({commands,destinationOverride,+ onStarted,prepend,+ sourceId,formatControlLayerError: (rejection) => describeControlLayerIssue(t, rejection),formatUpscaleMetadataFailure: (name) => t('widgets.gallery.itemActions.upscale.metadataFailed', { name }),getModels: () => availabilityModels,queries,}),- [availabilityModels, commands, queries, t]+ [availabilityModels, commands, queries, sourceId, t]);return {diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsxindex cfcfb8f750..18dd3ee606 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/GraphPreviewHost.tsx@@ -1,3 +1,4 @@+import type { GraphPreviewInvoke } from '@features/workflow/contracts';import type { GraphBearingSurfaceContract } from '@workbench/widgetContracts';import { ensureModelsLoaded, useModelsSelector } from '@features/models';@@ -12,11 +13,14 @@ import { buildGraphPreviewSource } from './graphPreviewSource';/** Subscribe to the whole project only while the preview is open so graph compilation follows settings edits. */export const GraphPreviewHost = ({+ invoke,isOpen,surface,onExitComplete,onOpenChange,}: {+ /** The top bar's Invoke for this surface (`GraphPreviewInvokeScopeContext`); none without a shell to provide it. */+ invoke?: GraphPreviewInvoke;isOpen: boolean;surface: GraphBearingSurfaceContract;/** Fires when the close transition has played out — the menu drops the mount here. */@@ -43,6 +47,7 @@ export const GraphPreviewHost = ({return (<GraphPreviewDialoggraphId={surface.graphId}+ invoke={invoke}isOpen={isOpen}source={source}sourceId={surface.sourceId}diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsxindex c9aec1cea1..b70fe6b2d7 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetActionsMenu.tsx@@ -1,3 +1,4 @@+import type { GraphPreviewInvoke } from '@features/workflow/contracts';import type {GraphBearingSurfaceContract,WidgetInstanceRuntimeMeta,@@ -17,9 +18,11 @@ import { createGraphBearingSurface } from '@workbench/graphSurfaces';import { resolveWidgetLabel } from '@workbench/widgetLabels';import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';import { GitBranchIcon, MoreHorizontalIcon, TargetIcon } from 'lucide-react';-import { Component, lazy, Suspense, useCallback, useMemo, useState, type ReactNode } from 'react';+import { Component, createElement, lazy, Suspense, use, useCallback, useMemo, useState, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';+import { GraphPreviewInvokeScopeContext } from './graphPreviewInvoke';+/*** Combine graph actions and manifest headerMenu contributions in one menu. Floating has its own {@link* WidgetFloatButton} mode toggle.@@ -27,6 +30,33 @@ import { useTranslation } from 'react-i18next';const GraphPreviewHost = lazy(() => import('./GraphPreviewHost'));+/** The preview with its Invoke, which the shell provides (`GraphPreviewInvokeScopeContext`); without one, none. */+const GraphPreview = ({+ isOpen,+ surface,+ onExitComplete,+ onOpenChange,+}: {+ isOpen: boolean;+ surface: GraphBearingSurfaceContract;+ onExitComplete: () => void;+ onOpenChange: (isOpen: boolean) => void;+}) => {+ const InvokeScope = use(GraphPreviewInvokeScopeContext);+ const host = (invoke?: GraphPreviewInvoke) => (+ <GraphPreviewHost+ invoke={invoke}+ isOpen={isOpen}+ surface={surface}+ onExitComplete={onExitComplete}+ onOpenChange={onOpenChange}+ />+ );++ // The shell's component, the same one every render: created as an element, not declared here.+ return InvokeScope ? createElement(InvokeScope, { onOpenChange, render: host, sourceId: surface.sourceId }) : host();+};+/** Contain preview errors as a toast and closed dialog, preserving the widget. Reopening creates a fresh boundary. */class GraphPreviewBoundary extends Component<{ children: ReactNode; onError: (error: Error) => void },@@ -164,7 +194,7 @@ export const WidgetActionsMenu = ({{surface && isPreviewMounted ? (<GraphPreviewBoundary onError={handlePreviewError}><Suspense fallback={null}>- <GraphPreviewHost+ <GraphPreviewisOpen={isPreviewOpen}surface={surface}onExitComplete={handlePreviewExitComplete}diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewInvoke.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewInvoke.tsnew file mode 100644index 0000000000..3ec2fc2741--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewInvoke.ts@@ -0,0 +1,19 @@+import type { GraphPreviewInvoke } from '@features/workflow/contracts';+import type { InvocationSourceId } from '@workbench/invocationContracts';++import { type ComponentType, createContext, type ReactNode } from 'react';++export interface GraphPreviewInvokeScopeProps {+ sourceId: InvocationSourceId;+ /** Closed when a run starts, or an issue's action leads elsewhere. */+ onOpenChange: (isOpen: boolean) => void;+ /** Renders the preview with the Invoke made for it. */+ render: (invoke: GraphPreviewInvoke) => ReactNode;+}++/**+ * Where a widget's graph preview gets its Invoke: the shell provides the top bar's (`GraphPreviewInvokeScope`), so the+ * widget frame never imports the top bar's code. A frame importing it would share that boot code with the lazy preview+ * and split it out of the editor's boot chunk into requests of its own.+ */+export const GraphPreviewInvokeScopeContext = createContext<ComponentType<GraphPreviewInvokeScopeProps> | null>(null);diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.tsindex aa9405acaf..414c681caf 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.test.ts@@ -8,9 +8,11 @@ import type { TFunction } from 'i18next';import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';import { getDefaultGenerateSettings } from '@features/generation/settings';import { createGraphBearingSurface } from '@workbench/graphSurfaces';+import { getActiveProjectGraph } from '@workbench/projectWorkflows';import { BUILT_IN_PROJECT_SETTINGS } from '@workbench/settings/projectSettings';import { canvasWidgetManifest } from '@workbench/widgets/canvas/manifest';import { generateWidgetManifest } from '@workbench/widgets/generate/manifest';+import { videoWidgetManifest } from '@workbench/widgets/video/manifest';import { workflowWidgetManifest } from '@workbench/widgets/workflow/manifest';import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';import { describe, expect, it, vi } from 'vitest';@@ -72,6 +74,18 @@ const canvasSurface = createGraphBearingSurface(canvasWidgetManifest, 'center',seedArchitectureCapabilities();describe('buildGraphPreviewSource', () => {+ it('reports Gallery for Video while the top-bar route goes to Canvas', () => {+ const source = buildGraphPreviewSource({+ models,+ project: { ...project, invocation: { ...project.invocation, destination: 'canvas' } },+ projectSettings: BUILT_IN_PROJECT_SETTINGS,+ surface: createGraphBearingSurface(videoWidgetManifest, 'left', 'Video')!,+ t,+ templates: idleTemplates,+ });+ expect(source.destinationLabel).toBe('Gallery');+ });+it('live-compiles the generate source and reports a seed notice when randomized', () => {const source = buildGraphPreviewSource({models,@@ -127,7 +141,7 @@ describe('buildGraphPreviewSource', () => {expect(source.isLive).toBe(true);});- it('compiles the workflow source from the live document with position hints', () => {+ it('compiles the workflow source from the live document, which it hands the preview to draw', () => {const source = buildGraphPreviewSource({models: undefined,project,@@ -138,7 +152,8 @@ describe('buildGraphPreviewSource', () => {});expect(source.isLive).toBe(true);- expect(source.positionHints).toBeDefined();+ expect(source.graph).not.toBeNull();+ expect(source.document).toBe(getActiveProjectGraph(project));});it('returns null graph for workflow when templates are not loaded', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.tsindex 438aa0aab6..85d049f9fd 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/graphPreviewSource.ts@@ -64,20 +64,20 @@ const buildWorkflowSource = (project: Project,templates: InvocationTemplatesSnapshot): GraphPreviewSourceWithoutDestination => {+ const document = getActiveProjectGraph(project);+if (templates.status !== 'loaded') {- return { ...EMPTY_SOURCE_BASE, graph: null, isLive: true };+ return { ...EMPTY_SOURCE_BASE, document, graph: null, isLive: true };}- const document = getActiveProjectGraph(project);- const positionHints = Object.fromEntries(document.nodes.map((node) => [node.id, node.position]));-try {const graph = compileProjectGraph(document, templates.templates);- return { ...EMPTY_SOURCE_BASE, graph, isLive: true, positionHints };+ return { ...EMPTY_SOURCE_BASE, document, graph, isLive: true };} catch (error) {return {...EMPTY_SOURCE_BASE,+ document,graph: null,invalidReasons: [error instanceof ForLoopGraphValidationError@@ -87,7 +87,6 @@ const buildWorkflowSource = (: String(error),],isLive: true,- positionHints,};}};@@ -169,7 +168,9 @@ export const buildGraphPreviewSource = ({t,templates,}: GraphPreviewSourceDeps): GraphPreviewSourceState => {- const destinationLabel = getDestinationLabel(project.invocation.destination);+ const destinationLabel = getDestinationLabel(+ surface.sourceId === 'video' ? 'gallery' : project.invocation.destination+ );switch (surface.sourceId) {case 'workflow':diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 9abbf925a5..007b6aa907 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -5296,6 +5296,29 @@ describe('workbenchReducer Phase 5 generation flow', () => {expect(getActiveProjectGraph(getActiveProject(state)).nodes).toEqual([]);});+ it('captures the library binding on the queued snapshot', () => {+ let state = primeWorkflow(42, 'increment', 1);+ const original = workflowIdOf(state);+ const source = { libraryWorkflowId: 'template-original', ownerUserId: 'user-a', revision: 3 };+ state = {+ ...state,+ projects: state.projects.map((project) => ({+ ...project,+ workflows: {+ ...project.workflows,+ entries: project.workflows.entries.map((entry) => ({ ...entry, source })),+ },+ })),+ };+ state = submitFrom(state, original);+ const submission = getActiveProject(state).queue.items[0]?.snapshot.backendSubmission;+ source.libraryWorkflowId = 'template-relinked';+ expect(submission).toMatchObject({+ kind: 'workflow',+ libraryWorkflowSource: { libraryWorkflowId: 'template-original', ownerUserId: 'user-a' },+ });+ });+it('queues nothing and says so when the captured workflow was removed meanwhile', () => {let state = primeWorkflow(42, 'increment', 1);const original = workflowIdOf(state);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 1b3c5ff3e5..c1ac699df1 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -4033,6 +4033,9 @@ const enqueueCompiledSnapshot = (const expansionSampleSeed = expandedPositivePrompts ? (compiled.positivePromptsSampleSeed ?? null) : null;// Compilation already reserved the starting seed; failures and cancellations do not roll the sequence back.const seedPlan = submissionPlan?.seedPlan ?? null;+ const libraryWorkflowSource = compiled.projectWorkflowId+ ? project.workflows.entries.find((entry) => entry.document.id === compiled.projectWorkflowId)?.source+ : undefined;const backendSubmission: QueueCompiledSubmission = !backendGraph? { error: `${route.sourceId} queue item is missing a compiled backend graph.`, kind: 'invalid' }: route.sourceId === 'workflow'@@ -4044,6 +4047,14 @@ const enqueueCompiledSnapshot = (...(compiled.workflow.batchData.length ? { batchData: compiled.workflow.batchData } : {}),graph: backendGraph,kind: 'workflow',+ ...(libraryWorkflowSource+ ? {+ libraryWorkflowSource: {+ libraryWorkflowId: libraryWorkflowSource.libraryWorkflowId,+ ...(libraryWorkflowSource.ownerUserId ? { ownerUserId: libraryWorkflowSource.ownerUserId } : {}),+ },+ }+ : {}),...(compiled.workflowJson ? { workflow: compiled.workflowJson } : {}),// Capture the originating project workflow so results and seed advances return to it even after the// active workflow changes.diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 468111efbd..4d6b527663 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -300,6 +300,17 @@ const WORKFLOW_CORE_MODULES = ['/workbench/projectWorkflows.ts',] as const;+// The workflow queries entry and the library transport behind it are one chunk: the editor's boot hosts (publication,+// copy choice, pending load) and the lazy library dialog both read the transport, and the Launchpad palette reaches the+// entry lazily, so splitting the transport out by importer costs every editor boot a request.+const WORKFLOW_QUERIES_MODULES = [+ '/features/workflow/data/api.ts',+ '/features/workflow/data/libraryCache.ts',+ '/features/workflow/data/publication.ts',+ '/features/workflow/data/savedWorkflowQueries.ts',+ '/features/workflow/queries.ts',+] as const;+// Keep widget metadata separate so Launchpad settings cannot import editor boot UI.const WIDGET_METADATA_MODULES = ['/features/gallery/settingsContribution.ts',@@ -586,6 +597,12 @@ export default defineConfig({priority: 30,test: (id) => matchesAnySuffix(id, WORKFLOW_CORE_MODULES),},+ {+ includeDependenciesRecursively: false,+ name: 'workflow-queries',+ priority: 30,+ test: (id) => matchesAnySuffix(id, WORKFLOW_QUERIES_MODULES),+ },{includeDependenciesRecursively: false,name: 'widget-metadata',diff --git a/tests/app/services/workflow_records/test_workflow_library_queries.py b/tests/app/services/workflow_records/test_workflow_library_queries.pyindex b370d93a66..0a6b493866 100644--- a/tests/app/services/workflow_records/test_workflow_library_queries.py+++ b/tests/app/services/workflow_records/test_workflow_library_queries.py@@ -200,18 +200,21 @@ def test_each_order_key_sorts_by_its_column("created_at": "2026-01-01 00:00:00.000","updated_at": "2026-01-03 00:00:00.000","opened_at": "2026-01-02 00:00:00.000",+ "last_run_at": "2026-01-01 00:00:00.000","is_public": True,},"a": {"created_at": "2026-01-02 00:00:00.000","updated_at": "2026-01-01 00:00:00.000","opened_at": "2026-01-03 00:00:00.000",+ "last_run_at": "2026-01-03 00:00:00.000","is_public": False,},"b": {"created_at": "2026-01-03 00:00:00.000","updated_at": "2026-01-02 00:00:00.000","opened_at": "2026-01-01 00:00:00.000",+ "last_run_at": "2026-01-02 00:00:00.000","is_public": False,},}@@ -227,6 +230,24 @@ def test_each_order_key_sorts_by_its_column(assert [item.name for item in listed] == sorted(rows, key=key)[email protected]("direction", list(SQLiteDirection))[email protected]("order_by", [WorkflowRecordOrderBy.OpenedAt, WorkflowRecordOrderBy.LastRunAt])+def test_workflows_never_opened_or_run_sort_last_in_both_directions(+ workflow_records: WorkflowRecordsStorage,+ database: Database,+ order_by: WorkflowRecordOrderBy,+ direction: SQLiteDirection,+) -> None:+ times = {"never-1": None, "late": "2026-01-02 00:00:00.000", "never-2": None, "early": "2026-01-01 00:00:00.000"}+ for name, value in times.items():+ _set(database, workflow_records.create(_workflow(name), user_id=USER).workflow_id, **{order_by.value: value})++ listed = [item.name for item in workflow_records.get_many(order_by, direction, [WorkflowCategory.User]).items]++ assert listed[:2] == (["late", "early"] if direction == SQLiteDirection.Descending else ["early", "late"])+ assert sorted(listed[2:]) == ["never-1", "never-2"]++def test_tags_are_counted_one_by_one_under_the_filters(workflow_records: WorkflowRecordsStorage) -> None:workflow_records.create(_workflow("A", tags="alpha, beta"), user_id=USER)workflow_records.create(_workflow("B", tags="beta"), user_id=USER, is_public=True)