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
fix(workflows): v7 alpha workflow editor feedback — paste, board pickers, library sort and templates (#9964)
Josh Corbett01554a0ce25f
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 fa478426e5..5b5e79b702 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.+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.The picker's **Utility** group has three special nodes:@@ -53,6 +53,8 @@ Each project keeps its own workflows, and one of them is **active**: the one sho* **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.+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.+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. For a workflow opened from one of your own templates, **Update library template** replaces that template instead. 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.@@ -88,6 +90,7 @@ These work while the workflow editor has focus. On macOS, use **Cmd** in place o|---|---|| **Shift+A** or **Space** | Add a node || **Ctrl+C** / **Ctrl+V** | Copy / paste nodes, with the connections between them |+| **Ctrl+Shift+V** | Paste nodes, keeping the connections that fed them from the rest of the graph || **Ctrl+D** | Duplicate the selected nodes || **Ctrl+A** | Select all nodes || **Delete** / **Backspace** | Delete the selected nodes |diff --git a/invokeai/app/services/shared/database/queries/workflows.py b/invokeai/app/services/shared/database/queries/workflows.pyindex 737870a3b2..61b02c6005 100644--- a/invokeai/app/services/shared/database/queries/workflows.py+++ b/invokeai/app/services/shared/database/queries/workflows.py@@ -25,7 +25,7 @@ from sqlalchemy import (update,)-from invokeai.app.services.shared.database.dialect import CaseInsensitiveLike, like_contains+from invokeai.app.services.shared.database.dialect import CaseInsensitiveLike, CaseInsensitiveOrder, like_containsfrom invokeai.app.services.shared.database.queries.base import IN_CHUNK, QueryModule, locking, mapped, read, writefrom invokeai.app.services.shared.database.schema.workflows import workflow_libraryfrom invokeai.app.services.shared.database.types import now_text@@ -127,11 +127,12 @@ _SUMMARY_COLUMNS = (_LIST_COLUMNS = (*_SUMMARY_COLUMNS, _W.description, _W.category, _W.tags)_SUMMARY_NAMES = tuple(column.name for column in _SUMMARY_COLUMNS)_LIST_NAMES = tuple(column.name for column in _LIST_COLUMNS)-_ORDER_COLUMNS = {+# Names sort ignoring case, as model names do.+_ORDER_COLUMNS: dict[WorkflowRecordOrderBy, ColumnElement[Any]] = {WorkflowRecordOrderBy.CreatedAt: _W.created_at,WorkflowRecordOrderBy.UpdatedAt: _W.updated_at,WorkflowRecordOrderBy.OpenedAt: _W.opened_at,- WorkflowRecordOrderBy.Name: _W.name,+ WorkflowRecordOrderBy.Name: CaseInsensitiveOrder(_W.name),WorkflowRecordOrderBy.IsPublic: _W.is_public,}diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 4f023a0f6b..f83b5c8d8f 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -235,12 +235,12 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 201529,+ "largestAssetRawBytes": 208822,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 444643,+ "scriptRawBytes": 451936,"scriptRequestCount": 6,- "totalRawBytes": 460056+ "totalRawBytes": 467349},"domContentLoadedMedianMs": 101.40000009536743,"id": "editor-workflow",@@ -273,12 +273,12 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 201529,+ "largestAssetRawBytes": 208822,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 444643,+ "scriptRawBytes": 451936,"scriptRequestCount": 6,- "totalRawBytes": 460056+ "totalRawBytes": 467349},"domContentLoadedMedianMs": 99.89999961853027,"id": "editor-workflow",@@ -1245,6 +1245,7 @@"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",@@ -2345,6 +2346,7 @@"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",@@ -3624,6 +3626,7 @@"source:src/features/workflow/ui/editor/WorkflowEditorView.tsx","source:src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx","source:src/features/workflow/ui/editor/clipboard.ts",+ "source:src/features/workflow/ui/editor/fitWorkflowBounds.ts","source:src/features/workflow/ui/editor/flowAdapters.ts","source:src/features/workflow/ui/editor/flowInstanceStore.ts","source:src/features/workflow/ui/editor/handleTooltip.ts",@@ -3662,6 +3665,7 @@"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",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 6b04ac9322..434381d92d 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1686,6 +1686,9 @@"outputCount_other": "{{count}} outputs","selectForFields": "Select for fields","unknownNodeType": "Unknown node type. Select the node for details.",+ "unknownNodeTypeOnBackend": "Unknown node type \"{{type}}\". It cannot run on this backend.",+ "loadingNode": "Loading node…",+ "nodeDefinitionsUnavailable": "Node definitions could not be loaded.","unknownFieldType": "Unknown field type","loopLinkage": "Loop linkage","batch": "batch",@@ -1784,6 +1787,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","contextCollapse": "Collapse","contextExpand": "Expand","contextAddConnector": "Add connector",@@ -1879,7 +1883,8 @@"uninstalledDescription": "Restart InvokeAI for node removal to take full effect.","uninstalledTitle": "Node pack uninstalled","couldNotUninstall": "Could not uninstall the node pack.",- "uninstalled": "Uninstalled"+ "uninstalled": "Uninstalled",+ "boardAuto": "Auto ({{board}})"},"launchpad": {"browserIssues": {@@ -3594,7 +3599,7 @@"deleteSelection": "Delete workflow selection","duplicateSelection": "Duplicate workflow selection","pasteSelection": "Paste workflow selection",- "pasteSelectionWithEdges": "Paste workflow selection with edges",+ "pasteSelectionWithEdges": "Paste workflow selection with connections","redo": "Redo workflow edit","selectAll": "Select all workflow nodes","undo": "Undo workflow edit"@@ -3694,6 +3699,8 @@"latestOutput": "Latest output","library": "Workflow library","libraryWithEllipsis": "Workflow library…",+ "linkedTemplate": "Linked to library template \"{{name}}\"",+ "linkedTemplateUnnamed": "Linked to a library template","loadingGraph": "Loading $t(widgets.workflow.loadingGraphNodes, {\"count\": {{nodeCount}} }) and $t(widgets.workflow.loadingGraphEdges, {\"count\": {{edgeCount}} }).","loadingGraphEdges_one": "{{count, number}} edge","loadingGraphEdges_other": "{{count, number}} edges",@@ -3750,8 +3757,10 @@"nodeOpacity": "Node opacity","nodeOpacityValue": "Node opacity · {{value}}%","pan": "Pan (drag to move the viewport)",+ "redo": "Redo","zoomIn": "Zoom in",- "zoomOut": "Zoom out"+ "zoomOut": "Zoom out",+ "undo": "Undo"},"type": "Type","untitled": "Untitled Workflow",@@ -5096,7 +5105,7 @@"open": "Open copy","openCopyLabel": "{{name}} (open now)","replace": "Replace copy",- "replaceHint": "Replacing keeps the copy's name and swaps in the library's graph; undo restores the previous one.",+ "replaceHint": "Replacing keeps the copy's name and swaps in the library's graph. Until you reload, Undo in the workflow editor brings the previous graph back.","title": "“{{name}}” is already in this project"},"open": "Open",@@ -5142,7 +5151,9 @@"saveBusy": "\"{{name}}\" is already being saved.","saveFailed": "Failed to save workflow","saveToLibraryConfirm": "Save",- "saveToLibraryExplanation": "Creates a new library template from this workflow. Its current input values become the template's defaults. The project workflow keeps its name and stays in this project.",+ "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…",@@ -5176,6 +5187,7 @@"updateConfirm": "Update template","updateConfirmBody": "Replace this workflow's library template with its current graph, form, and input values?","updateConfirmCallers": "Workflows that call this template will use the new version.",+ "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",@@ -5184,7 +5196,15 @@"workflowMetadataOmitted": "Workflow metadata omitted","workflowMetadataOmittedBody": "Workflow metadata was omitted because the workflow contains multiple workflow_return nodes.","workflowName": "Workflow name",- "yours": "Yours"+ "yours": "Yours",+ "sortLabel": "Sort by",+ "sortUpdated": "Last updated",+ "sortOpened": "Last opened",+ "sortCreated": "Date created",+ "sortName": "Name",+ "thumbnailFit": "Thumbnail display",+ "thumbnailFitCover": "Fill",+ "thumbnailFitContain": "Fit"},"settingsDialog": {"search": "Search settings…",diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex 0de6404aad..fda932d3f2 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -1140,6 +1140,34 @@ test('the image map serves videos only on request and keeps its two endpoints co});});+test('the workflow list orders as the server does: names ignoring case, dates with never-opened last', async () => {+ await withRepresentativeBackend(async (backend) => {+ for (const name of ['charlie', 'Delta', 'alpha', 'Bravo']) {+ await getJson(backend, '/api/v1/workflows/', {+ body: JSON.stringify({ workflow: { name, tags: 'casing' } }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });+ }+ const names = async (direction) =>+ (await getJson(backend, `/api/v1/workflows/?tags=casing&order_by=name&direction=${direction}`)).items.map(+ (item) => item.name+ );++ assert.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());+ });+});+test('workflow thumbnails round-trip their bytes and refresh the listed URL on every replacement', async () => {await withRepresentativeBackend(async (backend) => {const path = '/api/v1/workflows/i/fixture-workflow-002/thumbnail';diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 7fdf396a09..a48aeba84c 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -2974,12 +2974,26 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {// The API pages from 0; the client asks for page 0 first.const page = Math.max(0, Number(url.searchParams.get('page') ?? 0) || 0);const perPage = Math.max(1, Number(url.searchParams.get('per_page') ?? 20) || 20);- 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)))- );+ 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.+ 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 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)))+ )+ .sort(+ (left, right) =>+ sign * (compare(sortKey(left), sortKey(right)) || 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/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxindex 810183313c..f9575e01cd 100644--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -31,8 +31,12 @@ import {import { useIsInvocationPreparing } from '@workbench/invocationPreparation';import { markWorkbenchPerf, measureWorkbenchPerf, timeWorkbenchPerf } from '@workbench/performanceMarks';import { getProjectSyncSnapshot, subscribeProjectSync } from '@workbench/projects/syncStore';-import { getActiveProjectWorkflow } from '@workbench/projectWorkflows';-import { getWorkbenchPreferences, subscribeWorkbenchPreferences } from '@workbench/settings/store';+import { getActiveProjectWorkflow, getProjectWorkflowHistory } from '@workbench/projectWorkflows';+import {+ getWorkbenchPreferences,+ patchWorkbenchPreferences,+ subscribeWorkbenchPreferences,+} from '@workbench/settings/store';import { useNotify } from '@workbench/useNotify';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';import { getProjectWidgetValues } from '@workbench/widgetState';@@ -55,6 +59,8 @@ const selectWorkflowPreferences = (preferences: WorkbenchPreferences) => ({workflowEdgeStyle: preferences.workflowEdgeStyle,workflowEdgesBehindNodes: preferences.workflowEdgesBehindNodes,workflowGroupNodesByCategory: preferences.workflowGroupNodesByCategory,+ workflowLibrarySort: preferences.workflowLibrarySort,+ workflowLibraryThumbnailFit: preferences.workflowLibraryThumbnailFit,workflowShowMinimap: preferences.workflowShowMinimap,workflowSnapToGrid: preferences.workflowSnapToGrid,workflowValidateConnections: preferences.workflowValidateConnections,@@ -217,10 +223,13 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })source: store,select: (snapshot) => {const activeWorkflow = getActiveProjectWorkflow(snapshot.activeProject);+ const history = getProjectWorkflowHistory(snapshot.activeProject, activeWorkflow.document.id);return {activeWorkflow,activeWorkflowId: activeWorkflow.document.id,+ canRedo: history.future.length > 0,+ canUndo: history.past.length > 0,galleryValues: getProjectWidgetValues(snapshot.activeProject, 'gallery'),id: snapshot.activeProject.id,isWorkflowRunning: hasPendingWorkflowQueueItem(snapshot.activeProject.queue.items),@@ -306,6 +315,9 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })persistence,preferences,project,+ setLibraryPreferences: (patch) => {+ void patchWorkbenchPreferences(patch);+ },widgets: {// Workflow opens widgets from its buttons: the opened widget takes focus and the region highlight.open: (options) => {diff --git a/invokeai/frontend/webv2/src/features/gallery/react.ts b/invokeai/frontend/webv2/src/features/gallery/react.tsindex a65393dc88..dd57c281ba 100644--- a/invokeai/frontend/webv2/src/features/gallery/react.ts+++ b/invokeai/frontend/webv2/src/features/gallery/react.ts@@ -6,8 +6,10 @@ export {type GalleryItemActionsOptions,type GalleryItemContextMenuProps,type GalleryItemContextMenuTarget,+ type GalleryHostProjectContext,type GalleryUiAdapter,useHostGalleryBoards,+ useOptionalGalleryHostProjectContext,} from './ui/GalleryUiContext';export type { GalleryProjectRef } from './core/types';// Only the eager UI port lives here. This entry is bundled with the eager gallery-state chunk; reaching a lazydiff --git a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsxindex 3a40670449..eee380504e 100644--- a/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/gallery/ui/GalleryUiContext.tsx@@ -227,6 +227,23 @@ export const GalleryHostProvider = ({ children, host }: { children: ReactNode; h<GalleryHostContext value={host}>{children}</GalleryHostContext>);+/** The project a gallery host lists boards against: what board pickers outside the gallery need to group them. */+export type GalleryHostProjectContext = Pick<GalleryHost, 'projectId' | 'projectName' | 'projects'>;++/** `useGalleryHost`'s project context, or null without a gallery host, for surfaces that work without one. */+export const useOptionalGalleryHostProjectContext = (): GalleryHostProjectContext | null => {+ const source = use(GalleryHostContext) ?? use(GalleryUiContext);+ const hasSource = source !== null;+ const projectId = source?.projectId;+ const projectName = source?.projectName;+ const projects = source?.projects;++ return useMemo(+ () => (hasSource ? { projectId, projectName: projectName ?? '', projects } : null),+ [hasSource, projectId, projectName, projects]+ );+};+export const useGalleryHost = (): GalleryHost => {const host = use(GalleryHostContext);const adapter = use(GalleryUiContext);diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.test.tsindex eca5bfd93e..d4fbd4ffb4 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.test.ts@@ -98,6 +98,14 @@ describe('projectGraphReducer', () => {expect(node.position).toEqual({ x: 5, y: 6 });});+ it('starts gallery image outputs saving to the gallery and every other node intermediate', () => {+ expect(buildInvocationNode({ ...template, type: 'save_image' }, { x: 0, y: 0 }).data.isIntermediate).toBe(false);+ expect(buildInvocationNode({ ...template, type: 'save_image_to_file' }, { x: 0, y: 0 }).data.isIntermediate).toBe(+ false+ );+ expect(buildInvocationNode({ ...template, type: 'img_resize' }, { x: 0, y: 0 }).data.isIntermediate).toBe(true);+ });+it('removing nodes drops their edges and exposed form fields', () => {const { doc, nodeAId, nodeBId } = createDocWithNodes();let next = projectGraphReducer(doc, { edge: createEdge(nodeAId, nodeBId), type: 'addEdge' });@@ -155,6 +163,25 @@ describe('projectGraphReducer', () => {expect(next.edges).toEqual([firstEdge, secondEdge]);});+ it('addGraphElements connects pasted nodes to existing sources but never fills one input twice', () => {+ const { doc, nodeAId, nodeBId } = createDocWithNodes();+ const pasted = buildInvocationNode(template, { x: 64, y: 64 });+ const collect = buildInvocationNode({ ...template, type: 'collect' }, { x: 96, y: 96 });+ const fromA = { ...createEdge(nodeAId, pasted.id), id: 'edge-from-a' };+ const fromB = { ...createEdge(nodeBId, pasted.id), id: 'edge-from-b' };+ const fromGone = { ...createEdge('deleted-node', pasted.id), id: 'edge-from-gone', targetHandle: 'b' };+ const itemFromA = { ...createEdge(nodeAId, collect.id), id: 'item-from-a', targetHandle: 'item' };+ const itemFromB = { ...createEdge(nodeBId, collect.id), id: 'item-from-b', targetHandle: 'item' };+ const next = projectGraphReducer(doc, {+ edges: [fromA, fromB, fromGone, itemFromA, itemFromB],+ nodes: [pasted, collect],+ type: 'addGraphElements',+ });++ // The first edge into `a` wins; a collect's `item` keeps every connection; a missing source is dropped.+ expect(next.edges.map((edge) => edge.id)).toEqual(['edge-from-a', 'item-from-a', 'item-from-b']);+ });+it('addGraphElements drops colliding node ids and their edges', () => {const { doc, nodeAId, nodeBId } = createDocWithNodes();const existingNode = doc.nodes[0];@@ -549,6 +576,19 @@ describe('node updates', () => {expect(isFieldExposed(update.document.form, { fieldName: 'z', nodeId: 'add-1' })).toBe(false);});+ it('keeps a Save Image node intermediate when the user chose that before the update', () => {+ const saveTemplate: InvocationTemplate = { ...template, type: 'save_image' };+ const stored: WorkflowInvocationNode = {+ ...buildInvocationNode(saveTemplate, { x: 0, y: 0 }),+ data: { ...buildInvocationNode(saveTemplate, { x: 0, y: 0 }).data, isIntermediate: true },+ id: 'save-1',+ };+ const doc: ProjectGraphState = { ...createProjectGraph('update-test'), nodes: [stored] };+ const updated = updateWorkflowNodes(doc, { save_image: { ...saveTemplate, version: '1.1.0' } }).document.nodes[0];++ expect(updated?.type === 'invocation' && updated.data).toMatchObject({ isIntermediate: true, version: '1.1.0' });+ });+it('fills a cleared value from the template but keeps dynamic and extra-input node inputs', () => {const cleared: WorkflowInvocationNode = {...oldNode(),diff --git a/invokeai/frontend/webv2/src/features/workflow/core/document.ts b/invokeai/frontend/webv2/src/features/workflow/core/document.tsindex b16f05ff36..3869568f98 100644--- a/invokeai/frontend/webv2/src/features/workflow/core/document.ts+++ b/invokeai/frontend/webv2/src/features/workflow/core/document.ts@@ -189,6 +189,9 @@ export const readLegacyPlaceholderGraph = (candidate: unknown): ProjectGraphStat);};+/** Nodes whose whole purpose is a gallery image start saving to the gallery; every other output stays intermediate. */+const GALLERY_OUTPUT_NODE_TYPES: ReadonlySet<string> = new Set(['save_image', 'save_image_to_file']);+export const buildInvocationNode = (template: InvocationTemplate, position: XYPosition): WorkflowInvocationNode => {const inputs: Record<string, WorkflowFieldInstance> = {};@@ -203,7 +206,7 @@ export const buildInvocationNode = (template: InvocationTemplate, position: XYPoreturn {data: {inputs,- isIntermediate: true,+ isIntermediate: !GALLERY_OUTPUT_NODE_TYPES.has(template.type),isOpen: true,label: '',nodePack: template.nodePack,@@ -926,16 +929,43 @@ const applyProjectGraphAction = (document: ProjectGraphState, action: ProjectGra// ids win, incoming duplicates are dropped along with their edges.const existingNodeIds = new Set(document.nodes.map((node) => node.id));const nodes = action.nodes.filter((node) => !existingNodeIds.has(node.id));- const acceptedNodeIds = new Set(nodes.map((node) => node.id));- const existingEdgeIds = new Set(document.edges.map((edge) => edge.id));- const edges = action.edges.filter(- (edge) => !existingEdgeIds.has(edge.id) && acceptedNodeIds.has(edge.source) && acceptedNodeIds.has(edge.target)- );if (nodes.length === 0) {return document;}+ const acceptedNodesById = new Map(nodes.map((node) => [node.id, node]));+ const droppedNodeIds = new Set(+ action.nodes.filter((node) => existingNodeIds.has(node.id)).map((node) => node.id)+ );+ const existingEdgeIds = new Set(document.edges.map((edge) => edge.id));+ const filledInputs = new Set<string>();+ const edges = action.edges.filter((edge) => {+ const target = acceptedNodesById.get(edge.target);+ // Pasted nodes can be fed by nodes already in the document (paste with connections), but never by an+ // existing node that merely shares a dropped duplicate's id, and never by a node that no longer exists.+ const sourceExists =+ acceptedNodesById.has(edge.source) || (existingNodeIds.has(edge.source) && !droppedNodeIds.has(edge.source));++ if (!target || !sourceExists || existingEdgeIds.has(edge.id)) {+ return false;+ }++ // A non-collect input holds at most one connection, as in `addEdgeToDocument`.+ if (isInvocationNode(target) && target.data.type === 'collect' && edge.targetHandle === 'item') {+ return true;+ }++ const inputKey = `${edge.target}\u0000${edge.targetHandle}`;++ if (filledInputs.has(inputKey)) {+ return false;+ }++ filledInputs.add(inputKey);+ return true;+ });+return { ...document, edges: [...document.edges, ...edges], nodes: [...document.nodes, ...nodes] };}case 'removeNodes': {diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.tsindex 3da988bb07..2783f78b94 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/api.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.ts@@ -44,7 +44,7 @@ export interface ListWorkflowsParams {tags?: string[];isPublic?: boolean;callable?: boolean;- orderBy?: 'updated_at' | 'name';+ orderBy?: 'created_at' | 'name' | 'opened_at' | 'updated_at';direction?: 'ASC' | 'DESC';signal?: AbortSignal;}@@ -251,8 +251,20 @@ export const deleteLibraryWorkflowThumbnail = async (workflowId: string, signal?await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/thumbnail`, { method: 'DELETE', signal });};+const openedListeners = new Set<() => void>();++/** Registers a listener fired once the server has recorded an open: lists ordered by last opened have moved. */+export const onLibraryWorkflowOpened = (listener: () => void): (() => void) => {+ openedListeners.add(listener);+ return () => openedListeners.delete(listener);+};+export const touchLibraryWorkflowOpenedAt = async (workflowId: string, signal?: AbortSignal): Promise<void> => {await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/opened_at`, { method: 'PUT', signal });++ for (const listener of openedListeners) {+ listener();+ }};export interface GetWorkflowTagCountsParams {diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.tsindex fe3f561050..16d2df76cd 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts@@ -6,11 +6,23 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type { WorkflowLibraryListItem, WorkflowLibraryPage } from './api';import type * as libraryBrowseStoreModule from './libraryBrowseStore';-const api = vi.hoisted(() => ({- getAllWorkflowTags: vi.fn(),- getWorkflowTagCounts: vi.fn(),- listLibraryWorkflows: vi.fn(),-}));+const api = vi.hoisted(() => {+ const openedListeners = 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(),+ /** What `touchLibraryWorkflowOpenedAt` does once the server recorded an open. */+ notifyOpened: () => openedListeners.forEach((listener) => listener()),+ onLibraryWorkflowOpened: (listener: () => void) => {+ openedListeners.add(listener);+ return () => openedListeners.delete(listener);+ },+ };+});const libraryCache = vi.hoisted(() => ({getLibraryWorkflowCached: vi.fn(),@@ -132,6 +144,7 @@ let invalidate: () => void;beforeEach(async () => {vi.resetModules();+ api.clearOpenedListeners();api.getAllWorkflowTags.mockReset().mockResolvedValue([]);api.getWorkflowTagCounts.mockReset().mockResolvedValue({});api.listLibraryWorkflows.mockReset().mockResolvedValue(buildPage([]));@@ -152,7 +165,7 @@ beforeEach(async () => {describe('workflow library page fetching', () => {it('sends the active category, tag, and search filter to the list endpoint', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');expect(api.listLibraryWorkflows).toHaveBeenCalledWith(expect.objectContaining({ category: 'user', page: 0, perPage: 20, query: undefined, tags: undefined })@@ -170,7 +183,7 @@ describe('workflow library page fetching', () => {});it('ignores a repeated filter patch that changes nothing', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');api.listLibraryWorkflows.mockClear();browse.setWorkflowLibraryBrowseFilter({ category: 'user', search: '' });@@ -185,7 +198,7 @@ describe('workflow library page fetching', () => {));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(2);browse.loadNextWorkflowLibraryPage();@@ -211,7 +224,7 @@ 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();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');browse.setWorkflowLibraryBrowseFilter({ tag: 'lora' });const snapshot = browse.getWorkflowLibraryBrowseSnapshot();@@ -220,7 +233,7 @@ describe('workflow library page fetching', () => {});it('drops a stale in-flight page when the filter changes mid-flight', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');const stale = createDeferred<WorkflowLibraryPage>();api.listLibraryWorkflows.mockReturnValueOnce(stale.promise);@@ -244,7 +257,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();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');const snapshot = browse.getWorkflowLibraryBrowseSnapshot();expect(snapshot.status).toBe('error');@@ -254,18 +267,115 @@ 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();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.tags).toEqual(['lora', 'sdxl']);});});+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');++ expect(listCalls()).toEqual([+ expect.objectContaining({ category: 'user', direction: 'DESC', orderBy: 'opened_at', page: 0 }),+ ]);+ });++ it('refetches page 0 in a new sort, and returns to an earlier sort from the cache', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ api.listLibraryWorkflows.mockClear();++ browse.setWorkflowLibraryBrowseFilter({ 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' });++ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded');+ await flushAsyncWork();+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();+ });++ it('rereads the current view by last opened once when an open is recorded after the dialog reopened', async () => {+ api.listLibraryWorkflows.mockImplementation(({ perPage }: { perPage: number }) =>+ Promise.resolve(buildPage(perPage === 1 ? [] : [buildItem('a'), buildItem('x')]))+ );+ await browse.ensureWorkflowLibraryBrowseLoaded('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 flushAsyncWork();+ expect(listCalls()).toEqual([]);++ // The server records the open (twice, from two opens): the open dialog reorders with one read.+ api.notifyOpened();+ api.notifyOpened();++ await vi.waitFor(() =>+ expect(browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item.workflow_id)).toEqual([+ 'x',+ 'a',+ ])+ );+ await flushAsyncWork();+ expect(listCalls()).toHaveLength(1);+ });++ it('drops hidden views by last opened on an open without reading them until revisited', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded('opened');+ browse.setWorkflowLibraryBrowseFilter({ sort: 'updated' });+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));+ api.listLibraryWorkflows.mockClear();++ api.notifyOpened();+ await flushAsyncWork();+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();++ browse.setWorkflowLibraryBrowseFilter({ sort: 'opened' });+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loading');+ });++ it('keeps views in other orders when a workflow is opened', async () => {+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ api.listLibraryWorkflows.mockClear();++ api.notifyOpened();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await flushAsyncWork();++ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();+ });++ 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 vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));++ expect(listCalls().at(-1)).toEqual(+ expect.objectContaining({ category: 'default', direction: 'ASC', orderBy: 'name' })+ );++ api.listLibraryWorkflows.mockClear();+ browse.setWorkflowLibraryBrowseFilter({ sort: 'opened' });+ await flushAsyncWork();+ expect(api.listLibraryWorkflows).not.toHaveBeenCalled();+ });+});+describe('workflow library tag counts', () => {it('stores sorted, non-zero counts for the active category', async () => {api.getAllWorkflowTags.mockResolvedValue(['lora', 'sdxl', 'unused']);api.getWorkflowTagCounts.mockResolvedValue({ lora: 2, sdxl: 5, unused: 0 });- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');expect(api.getAllWorkflowTags).toHaveBeenCalledWith(expect.objectContaining({ categories: ['user'] }));expect(api.getWorkflowTagCounts).toHaveBeenCalledWith(@@ -278,7 +388,7 @@ describe('workflow library tag counts', () => {});it('refetches counts for the new category and not for a search-only change', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');api.getAllWorkflowTags.mockClear();browse.setWorkflowLibraryBrowseFilter({ search: 'cat' });@@ -299,7 +409,7 @@ describe('workflow library entry enrichment', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(2));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');});@@ -317,7 +427,7 @@ describe('workflow library entry enrichment', () => {workflowId === 'bad' ? Promise.reject(new Error('payload gone')) : Promise.resolve(buildRawWorkflow(1)));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries[1]?.enrichment.status).toBe('ready');});@@ -331,7 +441,7 @@ describe('workflow library entry enrichment', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));libraryCache.getLibraryWorkflowCached.mockResolvedValue('not a workflow');- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('error');});@@ -350,7 +460,7 @@ describe('workflow library entry enrichment', () => {return deferred.promise;});- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => {expect(deferrals.size).toBe(4);});@@ -379,7 +489,7 @@ describe('workflow library entry enrichment', () => {buildPage(Array.from({ length: 6 }, (_unused, index) => buildItem(`item-${index}`))));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries.every((entry) => entry.enrichment.status === 'error')@@ -399,7 +509,7 @@ describe('workflow library entry enrichment', () => {});api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('error');});@@ -421,7 +531,7 @@ describe('workflow library entry enrichment', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('gone')]));libraryCache.getLibraryWorkflowCached.mockReturnValueOnce(stalled.promise);- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('kept')]));libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(3));@@ -446,7 +556,7 @@ describe('workflow library entry enrichment', () => {workflowId === 'slow' ? slow.promise : Promise.resolve(buildRawWorkflow(1)));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment.status).toBe('ready');});@@ -466,7 +576,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();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');api.listLibraryWorkflows.mockClear();invalidate();@@ -488,42 +598,97 @@ describe('workflow library browse refresh', () => {expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('idle');});- it('publishes the refreshed list when an infinite-scroll append races the refresh', async () => {- const refreshedFirstPage = createDeferred<WorkflowLibraryPage>();- let firstPageCalls = 0;-- api.listLibraryWorkflows.mockImplementation(({ page, perPage }: { page: number; perPage: number }) => {- if (perPage === 1) {- return Promise.resolve(buildPage([], { total: 0 }));- }-- if (page > 0) {- return Promise.resolve(buildPage([buildItem('scrolled')], { page, pages: 3, total: 4 }));+ describe('racing infinite scroll', () => {+ // Deleting `b` elsewhere shifts every later row up one place.+ const BEFORE_DELETE = [+ ['a', 'b'],+ ['c', 'd'],+ ['e', 'f'],+ ];+ const AFTER_DELETE = [['a', 'c'], ['d', 'e'], ['f']];+ const listPage = (library: string[][], page: number) =>+ buildPage(+ (library[page] ?? []).map((id) => buildItem(id)),+ {+ page,+ pages: library.length,+ total: library.flat().length,+ }+ );+ const entryIds = () => browse.getWorkflowLibraryBrowseSnapshot().entries.map((entry) => entry.item.workflow_id);++ /** Holds every page request open so each test chooses the completion order. */+ const holdPageRequests = async () => {+ const held: { page: number; response: Deferred<WorkflowLibraryPage> }[] = [];++ api.listLibraryWorkflows.mockImplementation(({ page, perPage }: { page: number; perPage: number }) => {+ if (perPage === 1) {+ return Promise.resolve(buildPage([], { total: 0 }));+ }++ const response = createDeferred<WorkflowLibraryPage>();++ held.push({ page, response });++ return response.promise;+ });++ const loading = browse.ensureWorkflowLibraryBrowseLoaded('updated');++ held[0]?.response.resolve(listPage(BEFORE_DELETE, 0));+ await loading;++ return held;+ };++ it.each(['the scrolled page', 'the revalidation'])(+ 'rereads a page requested before a revalidation and drops its stale response when %s lands first',+ async (first) => {+ const held = await holdPageRequests();++ browse.loadNextWorkflowLibraryPage();+ // The delete's revalidation starts while the scrolled page is in flight.+ const refreshing = browse.refreshWorkflowLibraryBrowse();+ const [, scrolled, ...reads] = held;+ const answerScroll = () => scrolled?.response.resolve(listPage(BEFORE_DELETE, 1));+ const answerReads = () => reads.forEach(({ page, response }) => response.resolve(listPage(AFTER_DELETE, page)));++ if (first === 'the scrolled page') {+ answerScroll();+ await flushAsyncWork();+ answerReads();+ } else {+ answerReads();+ await flushAsyncWork();+ answerScroll();+ }+ await refreshing;+ await flushAsyncWork();++ expect(entryIds()).toEqual(['a', 'c', 'd', 'e']);+ expect(browse.getWorkflowLibraryBrowseSnapshot()).toMatchObject({ page: 1, status: 'loaded', total: 5 });}+ );- firstPageCalls += 1;+ it('holds a scroll during a revalidation, then loads the next page of the revalidated list', async () => {+ const held = await holdPageRequests();+ const refreshing = browse.refreshWorkflowLibraryBrowse();- return firstPageCalls === 1- ? Promise.resolve(buildPage([buildItem('kept'), buildItem('deleted')], { pages: 3, total: 5 }))- : refreshedFirstPage.promise;- });+ browse.loadNextWorkflowLibraryPage();+ expect(held.map(({ page }) => page)).toEqual([0, 0]);+ expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loadingMore');- await browse.ensureWorkflowLibraryBrowseLoaded();+ held[1]?.response.resolve(listPage(AFTER_DELETE, 0));+ await vi.waitFor(() => expect(held).toHaveLength(3));+ expect(held[2]?.page).toBe(1);- // A delete invalidated the cache; the user scrolls while the refresh is in flight.- const refreshing = browse.refreshWorkflowLibraryBrowse();+ held[2]?.response.resolve(listPage(AFTER_DELETE, 1));+ await refreshing;+ await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().status).toBe('loaded'));- browse.loadNextWorkflowLibraryPage();- await vi.waitFor(() => {- expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(3);+ expect(entryIds()).toEqual(['a', 'c', 'd', 'e']);+ expect(browse.getWorkflowLibraryBrowseSnapshot().page).toBe(1);});-- refreshedFirstPage.resolve(buildPage([buildItem('kept')], { pages: 2, total: 3 }));- await refreshing;-- const snapshot = browse.getWorkflowLibraryBrowseSnapshot();- expect(snapshot.entries.map((entry) => entry.item.workflow_id)).toEqual(['kept']);- expect(snapshot.status).toBe('loaded');});it('refetches every loaded page and keeps unchanged entry identities', async () => {@@ -531,7 +696,7 @@ describe('workflow library browse refresh', () => {Promise.resolve(buildPage([buildItem(`page-${page}`)], { page, pages: 2, total: 2 })));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');browse.loadNextWorkflowLibraryPage();await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(2);@@ -554,7 +719,7 @@ describe('workflow library browse refresh', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a')]));libraryCache.getLibraryWorkflowCached.mockResolvedValue(buildRawWorkflow(1));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.enrichment).toMatchObject({ nodeCount: 1 });});@@ -573,7 +738,7 @@ 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();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');browse.setWorkflowLibraryBrowseFilter({ category: 'default', search: 'cat', tag: 'lora' });await vi.waitFor(() => {expect(browse.getWorkflowLibraryBrowseSnapshot().entries).toHaveLength(1);@@ -584,7 +749,7 @@ describe('workflow library browse account ownership', () => {expect(browse.getWorkflowLibraryBrowseSnapshot()).toEqual({entries: [],error: null,- filter: { category: 'user', search: '', tag: null },+ filter: { category: 'user', search: '', sort: 'updated', tag: null },page: 0,pages: 0,status: 'idle',@@ -601,7 +766,7 @@ describe('workflow library user total probe', () => {Promise.resolve(perPage === 1 ? buildPage([buildItem('a')], { total: 7 }) : buildPage([])));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');expect(api.listLibraryWorkflows).toHaveBeenCalledWith(expect.objectContaining({ category: 'user', page: 0, perPage: 1 })@@ -610,8 +775,8 @@ describe('workflow library user total probe', () => {});it('probes only once across repeated ensure calls', async () => {- await browse.ensureWorkflowLibraryBrowseLoaded();- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');expect(api.listLibraryWorkflows.mock.calls.filter(([params]) => params.perPage === 1)).toHaveLength(1);});@@ -628,7 +793,7 @@ describe('workflow library view cache', () => {const browseYoursThenBrowse = async () => {listByCategory({ default: [buildItem('x', { category: 'default' })], user: userItems });- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => expect(allEnriched()).toBe(true));const yours = browse.getWorkflowLibraryBrowseSnapshot().entries;diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.tsindex 943a36797e..a58cf6264b 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.ts@@ -19,7 +19,7 @@ import { getApiErrorMessage } from '@platform/transport/http';import type { WorkflowLibraryCategory, WorkflowLibraryListItem, WorkflowLibraryPage } from './api';-import { getAllWorkflowTags, getWorkflowTagCounts, listLibraryWorkflows } from './api';+import { getAllWorkflowTags, getWorkflowTagCounts, listLibraryWorkflows, onLibraryWorkflowOpened } from './api';import {getLibraryWorkflowCached,onWorkflowLibraryCacheInvalidated,@@ -36,10 +36,15 @@ 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';+export interface WorkflowLibraryBrowseFilter {category: WorkflowLibraryCategory;tag: string | null;search: string;+ /** Applies to the user category only; see `getListOrder`. */+ sort: WorkflowLibrarySort;}export type WorkflowLibraryEntryEnrichment =@@ -76,7 +81,27 @@ 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: '', tag: null };+const INITIAL_FILTER: WorkflowLibraryBrowseFilter = { category: 'user', search: '', sort: 'updated', tag: null };++const ORDER_BY: Record<WorkflowLibrarySort, 'created_at' | 'name' | 'opened_at' | 'updated_at'> = {+ created: 'created_at',+ name: 'name',+ opened: 'opened_at',+ updated: 'updated_at',+};++/**+ * 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.+ */+const getListOrder = ({+ category,+ sort,+}: WorkflowLibraryBrowseFilter): { direction: 'ASC' | 'DESC'; orderBy: (typeof ORDER_BY)[WorkflowLibrarySort] } => {+ const effective = category === 'default' ? 'name' : sort;++ return { direction: effective === 'name' ? 'ASC' : 'DESC', orderBy: ORDER_BY[effective] };+};const INITIAL_SNAPSHOT: WorkflowLibraryBrowseSnapshot = {entries: EMPTY_ENTRIES,@@ -102,6 +127,7 @@ const store = createExternalStore<WorkflowLibraryBrowseSnapshot>(INITIAL_SNAPSHOinterface CachedBrowseView {entries: readonly WorkflowLibraryEntry[];fetchedAt: number;+ orderBy: ReturnType<typeof getListOrder>['orderBy'];page: number;pages: number;tagCounts: readonly WorkflowTagCount[];@@ -114,8 +140,8 @@ const viewCache = new Map<string, CachedBrowseView>();/** When the current view's pages last arrived from the server. */let currentViewFetchedAt = 0;-const getFilterKey = ({ category, search, tag }: WorkflowLibraryBrowseFilter): string =>- JSON.stringify([category, search, tag]);+const getFilterKey = (filter: WorkflowLibraryBrowseFilter): string =>+ JSON.stringify([filter.category, filter.search, filter.tag, getListOrder(filter).orderBy]);const rememberCurrentView = (): void => {const { entries, filter, page, pages, status, tagCounts, total } = store.getSnapshot();@@ -128,7 +154,15 @@ const rememberCurrentView = (): void => {const key = getFilterKey(filter);viewCache.delete(key);- viewCache.set(key, { entries, fetchedAt: currentViewFetchedAt, page, pages, tagCounts, total });+ viewCache.set(key, {+ entries,+ fetchedAt: currentViewFetchedAt,+ orderBy: getListOrder(filter).orderBy,+ page,+ pages,+ tagCounts,+ total,+ });// Maps iterate in insertion order, so the first key is the least recently left view.while (viewCache.size > VIEW_CACHE_LIMIT) {@@ -146,11 +180,16 @@ const rememberCurrentView = (): void => {const initialLoadFlight = createTrailingSingleFlight();const refreshFlight = createTrailingSingleFlight();-/** Fence responses by filter/account generation, not request order; same-view append and refresh must both publish. */-let filterGeneration = 0;+/**+ * Fences page responses by generation, not request order. A filter change, an account change, or a revalidation of+ * the current view starts a new generation, so a page requested before it cannot publish over what it read.+ */+let listGeneration = 0;+/** The generation of the revalidation reading the current view's pages; infinite scroll waits for it. */+let revalidatingGeneration: number | null = null;-const isFilterCurrent = (generation: number, owner: AccountScope): boolean =>- generation === filterGeneration && isAccountScopeCurrent(owner);+const isListCurrent = (generation: number, owner: AccountScope): boolean =>+ generation === listGeneration && isAccountScopeCurrent(owner);// #region Entries@@ -349,6 +388,7 @@ const fetchPage = (owner: AccountScope): Promise<WorkflowLibraryPage> =>listLibraryWorkflows({+ ...getListOrder(filter),category: filter.category,page,perPage: PER_PAGE,@@ -358,16 +398,16 @@ const fetchPage = (});const loadFirstPage = async (filter: WorkflowLibraryBrowseFilter, owner: AccountScope): Promise<void> => {- const generation = filterGeneration;+ const generation = listGeneration;try {const result = await fetchPage(filter, 0, owner);- if (isFilterCurrent(generation, owner)) {+ if (isListCurrent(generation, owner)) {publishPage(result, 'replace');}} catch (error) {- if (isFilterCurrent(generation, owner)) {+ if (isListCurrent(generation, owner)) {libraryLogger.warn({error,message: 'Failed to load workflows',@@ -379,16 +419,16 @@ const loadFirstPage = async (filter: WorkflowLibraryBrowseFilter, owner: Account};const loadMorePages = async (filter: WorkflowLibraryBrowseFilter, page: number, owner: AccountScope): Promise<void> => {- const generation = filterGeneration;+ const generation = listGeneration;try {const result = await fetchPage(filter, page, owner);- if (isFilterCurrent(generation, owner)) {+ if (isListCurrent(generation, owner)) {publishPage(result, 'append');}} catch (error) {- if (isFilterCurrent(generation, owner)) {+ if (isListCurrent(generation, owner)) {libraryLogger.warn({error,message: 'Failed to load more workflows',@@ -454,7 +494,7 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBrorememberCurrentView();// Everything already in flight was requested for the previous filter.- filterGeneration += 1;+ listGeneration += 1;hasTemplateLoadFailed = false;const cached = viewCache.get(getFilterKey(filter));@@ -497,7 +537,10 @@ export const setWorkflowLibraryBrowseFilter = (patch: Partial<WorkflowLibraryBro}};-/** Appends the next page; a no-op while a page is in flight or on the last page. */+/**+ * Appends the next page; a no-op while a page is in flight or on the last page. During a revalidation the request+ * waits for it and then reads the next page of the revalidated list, because offsets may have shifted.+ */export const loadNextWorkflowLibraryPage = (): void => {const { filter, page, pages, status } = store.getSnapshot();@@ -506,20 +549,30 @@ export const loadNextWorkflowLibraryPage = (): void => {}store.patchSnapshot({ status: 'loadingMore' });- void loadMorePages(filter, page + 1, captureAccountScope());++ if (revalidatingGeneration !== listGeneration) {+ void loadMorePages(filter, page + 1, captureAccountScope());+ }};-/** First open: page 0, the category's tag counts, and the user-total probe. */-export const ensureWorkflowLibraryBrowseLoaded = (): Promise<void> => {+/**+ * 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.+ */+export const ensureWorkflowLibraryBrowseLoaded = (sort: WorkflowLibrarySort): Promise<void> => {const { status } = store.getSnapshot();if (status !== 'idle' && status !== 'error') {+ setWorkflowLibraryBrowseFilter({ sort });+return initialLoadFlight.inflight() ?? Promise.resolve();}return initialLoadFlight.run(async () => {const owner = captureAccountScope();- const { filter } = store.getSnapshot();+ const filter = { ...store.getSnapshot().filter, sort };++ store.patchSnapshot({ filter });hasTemplateLoadFailed = false;store.patchSnapshot({ error: null, status: 'loading' });@@ -528,7 +581,10 @@ export const ensureWorkflowLibraryBrowseLoaded = (): Promise<void> => {});};-/** Revalidates every page the user has scrolled through, plus the tag counts. */+/**+ * Revalidates every page the user has scrolled through, plus the tag counts. It supersedes a page still in flight and+ * reads that page itself; a scroll during it waits and then appends from the revalidated list.+ */export const refreshWorkflowLibraryBrowse = (): Promise<void> =>refreshFlight.run(async () => {const { filter, page, status } = store.getSnapshot();@@ -538,34 +594,48 @@ export const refreshWorkflowLibraryBrowse = (): Promise<void> =>}const owner = captureAccountScope();- const generation = filterGeneration;++ listGeneration += 1;++ const generation = listGeneration;+ const lastPage = status === 'loadingMore' ? page + 1 : page;++ revalidatingGeneration = generation;// An explicit revalidation is also the retry path for a failed enrichment.hasTemplateLoadFailed = false;try {const results = await Promise.all(- Array.from({ length: page + 1 }, (_unused, index) => fetchPage(filter, index, owner))+ Array.from({ length: lastPage + 1 }, (_unused, index) => fetchPage(filter, index, owner)));const last = results[results.length - 1];- if (last && isFilterCurrent(generation, owner)) {+ if (last && isListCurrent(generation, owner)) {const items = results.flatMap((result) => result.items);+ // A scroll that arrived during this read; one already in flight when it began is part of `lastPage`.+ const isScrollWaiting = status !== 'loadingMore' && store.getSnapshot().status === 'loadingMore';currentViewFetchedAt = Date.now();+ revalidatingGeneration = null;store.patchSnapshot({entries: mergeEntries(retryFailedEnrichment(store.getSnapshot().entries), items),error: null,// Deletions can shrink the library below the page the user was on.- page: Math.min(page, Math.max(0, last.pages - 1)),+ page: Math.min(lastPage, Math.max(0, last.pages - 1)),pages: last.pages,status: 'loaded',total: last.total,});pumpEnrichment();++ if (isScrollWaiting) {+ loadNextWorkflowLibraryPage();+ }}} catch (error) {- if (isFilterCurrent(generation, owner)) {+ if (isListCurrent(generation, owner)) {+ revalidatingGeneration = null;libraryLogger.warn({error,message: 'Failed to refresh workflows',@@ -584,12 +654,11 @@ export const useWorkflowLibraryBrowseSelector = store.useSelector;// #endregion-/** Coalesce mutation invalidations into one visible-page refresh because local changes can shift ordering. */+/** Coalesce library changes into one current-view refresh because they can shift ordering. */let isRefreshScheduled = false;-onWorkflowLibraryCacheInvalidated(() => {- // A mutation can change any view; the current one refreshes below, the others fetch afresh when revisited.- viewCache.clear();+/** Marks the current view outdated, so leaving it before the refresh lands does not cache it, and refreshes it. */+const scheduleCurrentViewRefresh = (): void => {currentViewFetchedAt = 0;if (isRefreshScheduled || store.getSnapshot().status === 'idle') {@@ -600,16 +669,37 @@ onWorkflowLibraryCacheInvalidated(() => {queueMicrotask(() => {isRefreshScheduled = false;- // The account may have reset between the invalidation and this microtask.+ // The account may have reset between the change and this microtask.if (store.getSnapshot().status !== 'idle') {void refreshWorkflowLibraryBrowse();}});+};++onWorkflowLibraryCacheInvalidated(() => {+ // A mutation can change any view; the current one refreshes, the others fetch afresh when revisited.+ viewCache.clear();+ scheduleCurrentViewRefresh();+});++// 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(() => {+ for (const [key, view] of viewCache) {+ if (view.orderBy === 'opened_at') {+ viewCache.delete(key);+ }+ }++ if (getListOrder(store.getSnapshot().filter).orderBy === 'opened_at') {+ scheduleCurrentViewRefresh();+ }});registerAccountOwnedResource({clear: () => {- filterGeneration += 1;+ listGeneration += 1;+ revalidatingGeneration = null;enrichmentQueue.length = 0;queuedWorkflowIds.clear();templatesFlight = null;diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.tsindex 4ae9f8b86d..23e3344a84 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts@@ -12,6 +12,7 @@ const api = vi.hoisted(() => ({getLibraryWorkflowRecord: vi.fn(),getWorkflowTagCounts: vi.fn(),listLibraryWorkflows: vi.fn(),+ onLibraryWorkflowOpened: () => () => {},}));const templates = vi.hoisted(() => ({@@ -104,7 +105,7 @@ describe('workflow library record freshness', () => {api.listLibraryWorkflows.mockResolvedValue(buildPage([buildItem('a', 1)]));api.getLibraryWorkflowRecord.mockResolvedValue(buildRecord('a', 1));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => expect(enrichedNodeCount()).toBe(1));// Opening what the list shows reuses the record enrichment read.@@ -142,7 +143,7 @@ describe('workflow library record freshness', () => {.mockResolvedValue(buildPage([buildItem('a', 2)]));api.getLibraryWorkflowRecord.mockResolvedValue(buildRecord('a', 2));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');await vi.waitFor(() => expect(browse.getWorkflowLibraryBrowseSnapshot().entries[0]?.item.revision).toBe(2));await vi.waitFor(() => expect(enrichedNodeCount()).toBe(2));// A caller still holding the old row is served the newer record without another report.@@ -282,7 +283,7 @@ describe('workflow library invalidation fencing', () => {.mockReturnValueOnce(retry.promise).mockResolvedValue(buildRecord('a', 1));- await browse.ensureWorkflowLibraryBrowseLoaded();+ await browse.ensureWorkflowLibraryBrowseLoaded('updated');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.api.listLibraryWorkflows.mockReturnValue(createDeferred<WorkflowLibraryPage>().promise);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 b753c1c81c..3d1d1e3937 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@@ -8,6 +8,7 @@ import type {import { ChakraProvider, Menu } 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';@@ -15,11 +16,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { WorkflowUiProvider } from './WorkflowUiContext';import { clearWorkflowPublicationIntent, workflowUiStore } from './workflowUiStore';-import { WorkflowHeaderActions, WorkflowMenuItems } from './WorkflowWidgetChrome';+import { WorkflowHeaderActions, WorkflowMenuItems, WorkflowWidgetLabel } from './WorkflowWidgetChrome';-const { copyWorkflowJsonMock, downloadWorkflowJsonMock } = vi.hoisted(() => ({+const { copyWorkflowJsonMock, downloadWorkflowJsonMock, getLibraryWorkflowRecordMock } = vi.hoisted(() => ({copyWorkflowJsonMock: vi.fn(),downloadWorkflowJsonMock: vi.fn(),+ getLibraryWorkflowRecordMock: vi.fn(),+}));++vi.mock('@features/workflow/data/api', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getLibraryWorkflowRecord: getLibraryWorkflowRecordMock,}));vi.mock('./workflowTransfer', () => ({@@ -47,13 +54,22 @@ 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.linkedTemplateUnnamed': 'Linked to a library template',+ 'widgets.workflow.untitled': 'Untitled Workflow','widgets.workflow.updateTemplateWithEllipsis': 'Update library template…',+ 'workflowLibrary.sourceBundled': 'From a bundled template (read-only)',+ 'workflowLibrary.sourceNone': 'Not linked to a library template','workflowLibrary.multipleWorkflowReturnNodesForTransfer':'The workflow must contain exactly one workflow return node before it can be exported or copied.',};vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => TRANSLATIONS[key] ?? key }),+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) =>+ key === 'widgets.workflow.linkedTemplate'+ ? `Linked to library template "${String(options?.name)}"`+ : (TRANSLATIONS[key] ?? key),+ }),}));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -264,9 +280,9 @@ describe('WorkflowHeaderActions', () => {clearWorkflowPublicationIntent();});- const renderHeader = async () => {+ const renderHeader = async (source?: ProjectWorkflowSource) => {const graph = createProjectGraph('workflow-1');- const project = createMutablePort(projectSnapshot(graph));+ const project = createMutablePort(projectSnapshot(graph, source));// eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapterconst adapter = {commands: createCommands(),@@ -324,4 +340,82 @@ describe('WorkflowHeaderActions', () => {expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({ kind: 'save-as-new', workflowId: 'workflow-1' });});++ it('offers Update library template only for a template the account can write, and asks for that update', async () => {+ const updateButton = () => host.querySelector<HTMLButtonElement>('button[aria-label="Update library template…"]');++ await renderHeader();+ expect(updateButton()).toBeNull();++ await renderHeader({ libraryWorkflowId: 'default_text-to-image', revision: 1 });+ expect(updateButton()).toBeNull();++ await renderHeader({ libraryWorkflowId: 'library-1', revision: 2 });+ await act(() => updateButton()?.click());++ expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({+ kind: 'update-source',+ workflowId: 'workflow-1',+ });+ });+});++describe('WorkflowWidgetLabel', () => {+ let host: HTMLDivElement;+ let root: Root;++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ getLibraryWorkflowRecordMock.mockReset().mockResolvedValue({ name: 'Portrait template' });+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ const renderLabel = async (source?: ProjectWorkflowSource) => {+ const graph = { ...createProjectGraph('workflow-1'), name: 'Portraits' };+ const project = createMutablePort(projectSnapshot(graph, source));+ // 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;++ await act(() => {+ root.render(+ <QueryClientProvider client={new QueryClient()}>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <WorkflowWidgetLabel region="center" />+ </WorkflowUiProvider>+ </ChakraProvider>+ </QueryClientProvider>+ );+ });+ };+ const workflowsButton = () => host.querySelector<HTMLElement>('[data-template-link]')!.closest('button')!;+ const linkDescription = () =>+ document.getElementById(workflowsButton().getAttribute('aria-describedby') ?? '')?.textContent ?? null;++ it('describes the link state on the workflow name: unlinked, bundled, or linked', async () => {+ await renderLabel();+ expect(linkDescription()).toBe('Not linked to a library template');++ await renderLabel({ libraryWorkflowId: 'default_text-to-image', revision: 1 });+ expect(linkDescription()).toBe('From a bundled template (read-only)');++ await renderLabel({ libraryWorkflowId: 'library-1', revision: 2 });+ expect(linkDescription()).toBe('Linked to a library template');+ });++ it('reads the linked template’s name only once the name’s tooltip is asked for', async () => {+ await renderLabel({ libraryWorkflowId: 'library-1', revision: 2 });+ expect(getLibraryWorkflowRecordMock).not.toHaveBeenCalled();++ await act(() => workflowsButton().focus());++ await vi.waitFor(() => expect(linkDescription()).toBe('Linked to library template "Portrait template"'));+ expect(getLibraryWorkflowRecordMock).toHaveBeenCalledWith('library-1', expect.anything());+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsxindex bbeaebebde..3614b95e76 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx@@ -1,6 +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 { WorkbenchThemeId } from '@theme/themes';import type { ComponentType, ReactNode } from 'react';@@ -15,12 +16,17 @@ import type {WorkflowWidgetCommands,} from './contracts';+/** How workflow thumbnails sit in their 3:2 box: cropped to fill it, or letterboxed whole. */+export type WorkflowThumbnailFit = 'cover' | 'contain';+export interface WorkflowPreferences {reduceMotion: boolean;themeId: WorkbenchThemeId;workflowEdgeStyle: 'curved' | 'square';workflowEdgesBehindNodes: boolean;workflowGroupNodesByCategory: boolean;+ workflowLibrarySort: WorkflowLibrarySort;+ workflowLibraryThumbnailFit: WorkflowThumbnailFit;workflowShowMinimap: boolean;workflowSnapToGrid: boolean;workflowValidateConnections: boolean;@@ -44,6 +50,9 @@ export interface WorkflowProjectSnapshot {/** The active workflow's entry: its document plus source and run metadata. */activeWorkflow: ProjectWorkflowEntry;activeWorkflowId: string;+ /** Whether the active workflow's session history has an edit to undo or redo. */+ canRedo: boolean;+ canUndo: boolean;/** Every workflow the project owns, in collection order; entries keep identity until edited. */workflows: readonly ProjectWorkflowEntry[];workflowValues: Record<string, unknown>;@@ -80,6 +89,10 @@ export interface WorkflowUiAdapter {commands: WorkflowCommands;widgets: WorkflowWidgetCommands;getProjectGraph(): ProjectGraphState;+ /** Saves the library's account-bound display choices. */+ setLibraryPreferences(+ patch: Partial<Pick<WorkflowPreferences, 'workflowLibrarySort' | 'workflowLibraryThumbnailFit'>>+ ): void;notifications: {error(title: string, message?: string): void;info(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 bb5b3f21eb..d4d5a39af0 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -1,6 +1,7 @@-import type { InvocationTemplate, XYPosition } from '@features/workflow/contracts';+import type { InvocationTemplate, ProjectWorkflowSource, XYPosition } from '@features/workflow/contracts';-import { Box, HStack, Icon, Menu, Text } from '@chakra-ui/react';+import { Box, HStack, Icon, Menu, Stack, Text, VisuallyHidden } from '@chakra-ui/react';+import { savedWorkflowDetailQueryOptions } from '@features/workflow/data/savedWorkflowQueries';import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {@@ -24,17 +25,22 @@ import { useMountEffect } from '@platform/react/useMountEffect';import { Button, IconButton, RenameDialog, Tooltip } from '@platform/ui';import { MenuItem } from '@platform/ui/Menu';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { useQuery } from '@tanstack/react-query';import {BookmarkIcon,+ BookUpIcon,CloudAlertIcon,CloudCheckIcon,CloudIcon,LibraryIcon,+ Link2Icon,+ Link2OffIcon,+ LockIcon,PlusIcon,RefreshCwIcon,TriangleAlertIcon,} from 'lucide-react';-import { useCallback, useEffect, useRef, useState, type ChangeEvent, type ElementType } from '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';@@ -84,15 +90,61 @@ const PERSISTENCE_VIEW: Record<saving: { color: 'fg.subtle', icon: RefreshCwIcon, labelKey: 'widgets.workflow.persistenceSaving' },};+/**+ * What the workflow's library link says: the template it updates, a bundled template, or none. The template's name+ * is not part of the project; it is read only once asked for, through the query the update confirmation uses.+ */+const useTemplateLinkDescription = (source: ProjectWorkflowSource | undefined, wantsName: boolean): string => {+ const { t } = useTranslation();+ const isLinked = isUpdatableSource(source);+ const templateName = useQuery({+ ...savedWorkflowDetailQueryOptions(isLinked ? source.libraryWorkflowId : ''),+ enabled: isLinked && wantsName,+ select: (record) => record.name,+ }).data;++ return isLinked+ ? templateName+ ? t('widgets.workflow.linkedTemplate', { name: templateName })+ : t('widgets.workflow.linkedTemplateUnnamed')+ : source+ ? t('workflowLibrary.sourceBundled')+ : t('workflowLibrary.sourceNone');+};++/**+ * 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.+ */export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {const { t } = useTranslation();const workflowName = useWorkflowProjectSelector((project) => project.projectGraph.name);const projectId = useWorkflowProjectSelector((project) => project.id);const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);+ const source = useWorkflowProjectSelector((project) => project.activeWorkflow.source);+ const [wantsTemplateName, setWantsTemplateName] = useState(false);+ const linkDescription = useTemplateLinkDescription(source, wantsTemplateName);+ const linkDescriptionId = useId();const openProjectWorkflows = useCallback(() => openWorkflowLibraryAtProjectWorkflow(projectId, activeWorkflowId),[activeWorkflowId, projectId]);+ const onTooltipOpenChange = useCallback((event: { open: boolean }) => {+ if (event.open) {+ setWantsTemplateName(true);+ }+ }, []);++ const tooltipContent = useMemo(+ () => (+ <Stack gap="0.5">+ <Text>{t('widgets.workflow.projectWorkflows')}</Text>+ <Text color="fg.muted">{linkDescription}</Text>+ </Stack>+ ),+ [linkDescription, t]+ );if (region !== 'center') {return <Text fontWeight="700">{t('widgets.labels.workflow')}</Text>;@@ -100,14 +152,20 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {// Center chrome already names the widget; the workflow name opens the project's workflows with this one selected.const displayName = workflowName || t('widgets.workflow.untitled');+ const isLinked = isUpdatableSource(source);+ // A source that cannot be updated is a bundled template's.+ const linkIcon = isLinked ? Link2Icon : source ? LockIcon : Link2OffIcon;return (- <HStack flex="1" gap="1" minW="0">- <Text color="fg.subtle" flexShrink={0}>+ // Sized by its content, so a narrow center shrinks it and the view menu beside it in proportion; a zero basis+ // would leave the name only what the view menu does not take.+ <HStack css={LABEL_CLIP_CSS} flex="1 1 auto" gap="1" minW="0">+ <Text color="fg.subtle" flexShrink={1} minW="0" overflow="hidden">/</Text>- <Tooltip content={t('widgets.workflow.projectWorkflows')}>+ <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}@@ -120,12 +178,23 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {><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={isLinked ? 'linked' : source ? 'bundled' : 'none'}+ flexShrink={0}+ /></Button></Tooltip>+ <VisuallyHidden id={linkDescriptionId}>{linkDescription}</VisuallyHidden></HStack>);};+// 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. */export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {const { t } = useTranslation();@@ -223,6 +292,7 @@ const selectPersistenceView = (persistence: WorkflowProjectPersistence) => ({export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {const { t } = useTranslation();const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);+ const canUpdateSource = useWorkflowProjectSelector((project) => isUpdatableSource(project.activeWorkflow.source));const { hasLocalRecovery, status } = useWorkflowPersistenceSelector(selectPersistenceView);const openAddNode = useCallback(() => setAddNodeOpen(true), []);const openWorkflowLibrary = useCallback(() => setWorkflowLibraryOpen(true), []);@@ -230,6 +300,10 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {() => requestWorkflowPublication({ kind: 'save-as-new', workflowId: activeWorkflowId }),[activeWorkflowId]);+ const updateTemplate = useCallback(+ () => requestWorkflowPublication({ kind: 'update-source', workflowId: activeWorkflowId }),+ [activeWorkflowId]+ );const view = PERSISTENCE_VIEW[status];// A pending save without browser recovery has no safety net at all; say so rather than showing the same cloud.const persistenceLabel =@@ -278,6 +352,19 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {<Icon as={BookmarkIcon} boxSize="3.5" /></IconButton></Tooltip>+ {canUpdateSource ? (+ <Tooltip content={t('widgets.workflow.updateTemplateWithEllipsis')}>+ <IconButton+ aria-label={t('widgets.workflow.updateTemplateWithEllipsis')}+ color="fg.muted"+ size="sm"+ variant="ghost"+ onClick={updateTemplate}+ >+ <Icon as={BookUpIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ ) : null}<Tooltip content={persistenceLabel}><BoxalignItems="center"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 57b9bd3d97..a45b76fa63 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.browser.test.tsx@@ -31,6 +31,7 @@ vi.mock('@features/workflow/ui/WorkflowUiContext', () => ({success: toolbarMocks.success,}),useWorkflowPreferencesSelector: () => false,+ useWorkflowUi: () => ({ CommandShortcut: ({ commandId }: { commandId: string }) => <kbd>{commandId}</kbd> }),useWorkflowProjectSelector: (selector: (project: unknown) => unknown) =>selector({ activeWorkflow: { document: { name: toolbarMocks.workflowName } } }),}));@@ -73,7 +74,14 @@ beforeEach(() => {const render = async (nodeOpacity: number,- arrangeProps: { arrangeScope?: 'all' | 'selection' | null; onArrangeNodes?: () => void } = {}+ arrangeProps: {+ arrangeScope?: 'all' | 'selection' | null;+ canRedo?: boolean;+ canUndo?: boolean;+ onArrangeNodes?: () => void;+ onRedo?: () => void;+ onUndo?: () => void;+ } = {}) => {applyThemeToRoot('mono');host = document.createElement('div');@@ -140,6 +148,62 @@ describe('editor toolbar', () => {expect(onArrangeNodes).toHaveBeenCalledTimes(1);});+ it('undoes and redoes from the toolbar only while the history has an edit to step over', async () => {+ const onRedo = vi.fn();+ const onUndo = vi.fn();+ const undo = () => host!.querySelector<HTMLButtonElement>('button[aria-label="Undo"]')!;+ const redo = () => host!.querySelector<HTMLButtonElement>('button[aria-label="Redo"]')!;++ await render(1, { canRedo: false, canUndo: false, onRedo, onUndo });+ expect(undo().getAttribute('aria-disabled')).toBe('true');+ expect(redo().getAttribute('aria-disabled')).toBe('true');+ await settle(() => undo().click());+ await settle(() => redo().click());+ expect(onUndo).not.toHaveBeenCalled();+ expect(onRedo).not.toHaveBeenCalled();++ await render(1, { canRedo: true, canUndo: true, onRedo, onUndo });+ await settle(() => undo().click());+ await settle(() => redo().click());+ expect(onUndo).toHaveBeenCalledOnce();+ expect(onRedo).toHaveBeenCalledOnce();+ });++ it('keeps keyboard focus on Undo when it steps back over the last edit', async () => {+ const renderHistory = (canUndo: boolean) =>+ settle(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <EditorToolbar+ canRedo={!canUndo}+ canUndo={canUndo}+ nodeOpacity={1}+ tool="pan"+ onExportPrepare={toolbarMocks.onExportPrepare}+ onExportComplete={toolbarMocks.onExportComplete}+ onNodeOpacityChange={vi.fn()}+ onRedo={vi.fn()}+ onToolChange={vi.fn()}+ onUndo={vi.fn()}+ />+ </ChakraProvider>+ </I18nextProvider>+ );+ });++ await render(1);+ await renderHistory(true);+ const undo = host!.querySelector<HTMLButtonElement>('button[aria-label="Undo"]')!;+ undo.focus();+ await settle(() => undo.click());+ // The history is now empty: the button says so but keeps focus, so the keyboard user is not dropped to the page.+ await renderHistory(false);++ expect(undo.getAttribute('aria-disabled')).toBe('true');+ expect(document.activeElement).toBe(undo);+ });+it('keeps every button on one shared square toolbar box', async () => {// Match custom control sizing; one wider child stretches every button in the column toolbar.await render(1);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsxindex a2b011fbee..1b9d66f83c 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/EditorToolbar.tsx@@ -1,6 +1,7 @@-import { Box, Icon, Popover, Portal, Slider, Stack, Text } from '@chakra-ui/react';+import { Box, HStack, Icon, Popover, Portal, Slider, Stack, Text } from '@chakra-ui/react';import {useWorkflowNotifications,+ useWorkflowUi,useWorkflowPreferencesSelector,useWorkflowProjectSelector,} from '@features/workflow/ui/WorkflowUiContext';@@ -16,6 +17,8 @@ import {LayoutGridIcon,CircleArrowUpIcon,MaximizeIcon,+ Redo2Icon,+ Undo2Icon,ZoomInIcon,ZoomOutIcon,} from 'lucide-react';@@ -23,6 +26,8 @@ import { useCallback, useId, useMemo, useRef, useState } from 'react';import { flushSync } from 'react-dom';import { useTranslation } from 'react-i18next';+import { WORKFLOW_FIT_PADDING } from './flowInstanceStore';+/*** Pane drag follows the selected pan/box/lasso tool; eraser clicks delete. Shift selects while panning, and middle* mouse pans during box selection.@@ -57,6 +62,8 @@ const waitForExportFrame = () =>export const EditorToolbar = ({arrangeScope = null,+ canRedo = false,+ canUndo = false,nodeOpacity,tool,updatableNodeCount = 0,@@ -64,11 +71,16 @@ export const EditorToolbar = ({onExportPrepare,onExportComplete,onNodeOpacityChange,+ onRedo,onToolChange,+ onUndo,onUpdateNodes,}: {/** What Arrange would lay out: the selection, the whole graph, or nothing (fewer than two nodes). */arrangeScope?: 'all' | 'selection' | null;+ /** Whether the workflow's session history has an edit to redo or undo. */+ canRedo?: boolean;+ canUndo?: boolean;nodeOpacity: number;tool: EditorTool;/** Nodes with a newer same-major template; the update button shows only while there are some. */@@ -77,7 +89,9 @@ export const EditorToolbar = ({onNodeOpacityChange: (opacity: number) => void;onExportPrepare: () => Promise<HTMLElement>;onExportComplete: () => void;+ onRedo?: () => void;onToolChange: (tool: EditorTool) => void;+ onUndo?: () => void;onUpdateNodes?: () => void;}) => {const { t } = useTranslation();@@ -96,7 +110,10 @@ export const EditorToolbar = ({const opacityValue = useMemo(() => [Math.round(nodeOpacity * 100)], [nodeOpacity]);const onZoomInClick = useCallback(() => void zoomIn(), [zoomIn]);const onZoomOutClick = useCallback(() => void zoomOut(), [zoomOut]);- const onFitViewClick = useCallback(() => void fitView({ duration: fitViewDuration }), [fitView, fitViewDuration]);+ const onFitViewClick = useCallback(+ () => void fitView({ duration: fitViewDuration, padding: WORKFLOW_FIT_PADDING }),+ [fitView, fitViewDuration]+ );const onExportWorkflowClick = useCallback(() => {if (isExportingWorkflowRef.current) {return;@@ -178,6 +195,23 @@ export const EditorToolbar = ({/>))}<ToolbarSeparator />+ <HistoryButton+ commandId="workflows.undo"+ disabled={!canUndo}+ icon={Undo2Icon}+ label={t('widgets.workflow.toolbar.undo')}+ tooltip={t('widgets.workflow.commands.undo')}+ onClick={onUndo}+ />+ <HistoryButton+ commandId="workflows.redo"+ disabled={!canRedo}+ icon={Redo2Icon}+ label={t('widgets.workflow.toolbar.redo')}+ tooltip={t('widgets.workflow.commands.redo')}+ onClick={onRedo}+ />+ <ToolbarSeparator /><ToolbarButton icon={ZoomInIcon} label={t('widgets.workflow.toolbar.zoomIn')} onClick={onZoomInClick} /><ToolbarButton icon={ZoomOutIcon} label={t('widgets.workflow.toolbar.zoomOut')} onClick={onZoomOutClick} /><ToolbarButton@@ -264,6 +298,49 @@ export const EditorToolbar = ({);};+/** A toolbar button whose tooltip also shows the editor command's current shortcut. */+const HistoryButton = ({+ commandId,+ disabled,+ icon,+ label,+ onClick,+ tooltip,+}: {+ commandId: string;+ disabled: boolean;+ icon: typeof HandIcon;+ label: string;+ onClick?: () => void;+ tooltip: string;+}) => {+ const { CommandShortcut } = useWorkflowUi();+ // The click event must not reach a command that takes an optional target, and an unavailable step does nothing.+ const onButtonClick = useCallback(() => {+ if (!disabled) {+ onClick?.();+ }+ }, [disabled, onClick]);+ const content = useMemo(+ () => (+ <HStack gap="2">+ <span>{tooltip}</span>+ <CommandShortcut commandId={commandId} />+ </HStack>+ ),+ [CommandShortcut, commandId, tooltip]+ );++ return (+ <Tooltip content={content} positioning={TOOLTIP_POSITIONING}>+ {/* aria-disabled, not disabled: stepping to the end of the history must not drop the button's focus. */}+ <IconButton aria-disabled={disabled || undefined} aria-label={label} variant="ghost" onClick={onButtonClick}>+ <Icon as={icon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ );+};+const EditorToolButton = ({icon,id,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.browser.test.tsxindex 988418c79f..5d797a4682 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@@ -2082,6 +2082,28 @@ describe('InvocationFlowNode template version', () => {'Version 1.0.0 cannot be updated to 2.0.0; delete and re-add the node');});++ it('waits neutrally for node definitions and warns of an unknown type only once they have loaded', async () => {+ await render(flowNodes);+ const knownBorder = borderColor();+ const nodeText = () => host.querySelector('.react-flow__node')!.textContent;++ for (const isCompact of [false, true]) {+ await render(toFlowNodes(projectGraph, [], undefined, undefined, isCompact, false, 'loading'));+ expect(borderColor()).toBe(knownBorder);+ expect(nodeText()).toContain('preview');+ expect(nodeText()).toContain('Loading node…');+ expect(nodeText()).not.toContain('Unknown node type');+ }++ await render(toFlowNodes(projectGraph, [], undefined, undefined, false, false, 'error'));+ expect(borderColor()).toBe(knownBorder);+ expect(nodeText()).toContain('Node definitions could not be loaded.');++ await render(toFlowNodes(projectGraph, [], undefined, undefined, false, false, 'loaded'));+ expect(borderColor()).not.toBe(knownBorder);+ expect(nodeText()).toContain('Unknown node type "preview". It cannot run on this backend.');+ });});describe('InvocationFlowNode batch nodes', () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsxindex eb8aafb781..2e02253959 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/InvocationFlowNode.tsx@@ -1,6 +1,7 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-array-as-prop, react-perf/jsx-no-jsx-as-prop */import type { FieldInputTemplate, FieldOutputTemplate, WorkflowInvocationNode } from '@features/workflow/contracts';import type { WorkflowNodeExecutionState as NodeExecutionState } from '@features/workflow/ui/contracts';+import type { TFunction } from 'i18next';import { Box, Checkbox, Field, Flex, HStack, Icon, IconButton, Input, Stack, Text } from '@chakra-ui/react';import { getWorkflowFieldSeedMode, isSeedInputField } from '@features/workflow/graph';@@ -916,6 +917,20 @@ const CompactNodeBody = ({ inputCount, outputCount }: { inputCount: number; outp);};+/** What a node without a template says: still loading, definitions unavailable, or a type this backend lacks. */+const getTemplatelessNodeMessage = (+ t: TFunction,+ { documentNode, templateStatus }: InvocationFlowNodeType['data'],+ isCompact: boolean+): string =>+ templateStatus === 'loading'+ ? t('nodes.loadingNode')+ : templateStatus === 'error'+ ? t('nodes.nodeDefinitionsUnavailable')+ : isCompact+ ? t('nodes.unknownNodeType')+ : t('nodes.unknownNodeTypeOnBackend', { type: documentNode.data.type });+const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeType>) => {const { t } = useTranslation();const node = data.documentNode;@@ -928,7 +943,7 @@ const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeTreturn (<NodeShell- isMissing={!templateView}+ isMissing={!templateView && data.templateStatus === 'loaded'}isOutdated={isOutdated}isRunning={execution?.status === 'running'}outcome={getExecutionOutcome(execution)}@@ -945,7 +960,7 @@ const CompactInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeT<CompactNodeBody inputCount={inputTemplates.length} outputCount={outputTemplates.length} />) : (<Text color="fg.subtle" fontSize="xs" px="3" {...getWorkflowNodeBodyProps()} py="2">- {t('nodes.unknownNodeType')}+ {getTemplatelessNodeMessage(t, data, true)}</Text>)}<CompactHiddenHandles@@ -968,10 +983,12 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNodeconst execution = useWorkflowNodeExecutionState(node.id);if (!templateView) {+ const isMissing = !isWorkflowImageExport && data.templateStatus === 'loaded';+return (- <NodeShell isMissing={!isWorkflowImageExport} selected={selected ?? false}>+ <NodeShell isMissing={isMissing} selected={selected ?? false}><HStack gap="1.5" minW={isWorkflowImageExport ? '0' : undefined} p="3">- {!isWorkflowImageExport ? <Icon as={TriangleAlertIcon} boxSize="3.5" color="red.solid" /> : null}+ {isMissing ? <Icon as={TriangleAlertIcon} boxSize="3.5" color="red.solid" /> : null}<Stack flex={isWorkflowImageExport ? '1' : undefined} gap="0" minW={isWorkflowImageExport ? '0' : undefined}>{isWorkflowImageExport ? (<MiddleTruncate@@ -989,7 +1006,7 @@ const ExpandedInvocationNode = ({ data, selected }: NodeProps<InvocationFlowNode)}{!isWorkflowImageExport ? (<Text color="fg.subtle" fontSize="xs">- Unknown node type "{node.data.type}". It cannot run on this backend.+ {getTemplatelessNodeMessage(t, data, false)}</Text>) : null}</Stack>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.browser.test.tsxindex c495c7a749..9525c22d70 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.browser.test.tsx@@ -85,4 +85,46 @@ describe('NodeContextMenu', () => {expect(hint('duplicate')).toBe('workflows.duplicateSelection');expect(hint('toggle-open')).toBeNull();});++ it('offers both pastes on empty canvas, disabled with an empty clipboard, anchored where the menu opened', async () => {+ const onPaste = vi.fn();+ const renderPane = (canPaste: boolean) =>+ act(() =>+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <NodeContextMenu+ canPaste={canPaste}+ menuState={paneMenuState}+ onAddConnector={vi.fn()}+ onClose={vi.fn()}+ onCopy={vi.fn()}+ onDelete={vi.fn()}+ onDuplicate={vi.fn()}+ onPaste={onPaste}+ onToggleOpen={vi.fn()}+ onUpdate={vi.fn()}+ />+ </WorkflowUiProvider>+ </ChakraProvider>+ )+ );+ const item = (value: string) => document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`)!;++ await renderPane(false);+ expect(item('paste').getAttribute('aria-disabled')).toBe('true');+ expect(item('paste-with-connections').getAttribute('aria-disabled')).toBe('true');++ await renderPane(true);+ await act(() => item('paste').click());+ await renderPane(true);+ await act(() => item('paste-with-connections').click());++ expect(onPaste.mock.calls).toEqual([+ [false, paneMenuState.position],+ [true, paneMenuState.position],+ ]);+ });});++const paneMenuState = { kind: 'pane', position: { x: 140, y: -60 }, x: 20, y: 20 } as const;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsxindex 9024074e74..a316a69fc9 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/NodeContextMenu.tsx@@ -9,6 +9,7 @@ import {CircleArrowUpIcon,ClipboardPasteIcon,CopyIcon,+ Link2Icon,CopyPlusIcon,PlusIcon,Trash2Icon,@@ -36,6 +37,9 @@ export interface PaneContextMenuState {export type WorkflowContextMenuState = NodeContextMenuState | PaneContextMenuState;+/** The empty-canvas menu anchors a paste at the flow point it was opened on; node and selection menus give none. */+export type WorkflowContextMenuPaste = (withConnections: boolean, position?: XYPosition) => void;+export const NodeContextMenu = ({canPaste,menuState,@@ -55,7 +59,7 @@ export const NodeContextMenu = ({onCopy: () => void;onDelete: () => void;onDuplicate: () => void;- onPaste: () => void;+ onPaste: WorkflowContextMenuPaste;onToggleOpen: () => void;onUpdate: () => void;}) => {@@ -83,7 +87,11 @@ export const NodeContextMenu = ({<Menu.Positioner><MenuContent minW="11rem">{!menuState ? null : menuState.kind === 'pane' ? (- <PaneAddConnectorMenuItem position={menuState.position} onAddConnector={onAddConnector} />+ <>+ <PasteMenuItems canPaste={canPaste} position={menuState.position} onPaste={onPaste} />+ <Menu.Separator borderColor="border.subtle" />+ <PaneAddConnectorMenuItem position={menuState.position} onAddConnector={onAddConnector} />+ </>) : (<><Menu.Item value="copy" onClick={onCopy}>@@ -93,13 +101,7 @@ export const NodeContextMenu = ({<CommandShortcut commandId="workflows.copySelection" /></Menu.ItemCommand></Menu.Item>- <Menu.Item disabled={!canPaste} value="paste" _disabled={DISABLED_PROPS} onClick={onPaste}>- <Icon as={ClipboardPasteIcon} boxSize="3.5" />- <Menu.ItemText>{t('nodes.contextPaste')}</Menu.ItemText>- <Menu.ItemCommand>- <CommandShortcut commandId="workflows.pasteSelection" />- </Menu.ItemCommand>- </Menu.Item>+ <PasteMenuItems canPaste={canPaste} onPaste={onPaste} /><Menu.Item value="duplicate" onClick={onDuplicate}><Icon as={CopyPlusIcon} boxSize="3.5" /><Menu.ItemText>{t('common.duplicate')}</Menu.ItemText>@@ -140,6 +142,45 @@ export const NodeContextMenu = ({const DISABLED_PROPS = { opacity: 0.4 };+const PasteMenuItems = ({+ canPaste,+ onPaste,+ position,+}: {+ canPaste: boolean;+ onPaste: WorkflowContextMenuPaste;+ position?: XYPosition;+}) => {+ const { t } = useTranslation();+ const { CommandShortcut } = useWorkflowUi();+ const onPastePlain = useCallback(() => onPaste(false, position), [onPaste, position]);+ const onPasteWithConnections = useCallback(() => onPaste(true, position), [onPaste, position]);++ return (+ <>+ <Menu.Item disabled={!canPaste} value="paste" _disabled={DISABLED_PROPS} onClick={onPastePlain}>+ <Icon as={ClipboardPasteIcon} boxSize="3.5" />+ <Menu.ItemText>{t('nodes.contextPaste')}</Menu.ItemText>+ <Menu.ItemCommand>+ <CommandShortcut commandId="workflows.pasteSelection" />+ </Menu.ItemCommand>+ </Menu.Item>+ <Menu.Item+ disabled={!canPaste}+ value="paste-with-connections"+ _disabled={DISABLED_PROPS}+ onClick={onPasteWithConnections}+ >+ <Icon as={Link2Icon} boxSize="3.5" />+ <Menu.ItemText>{t('nodes.contextPasteWithConnections')}</Menu.ItemText>+ <Menu.ItemCommand>+ <CommandShortcut commandId="workflows.pasteSelectionWithEdges" />+ </Menu.ItemCommand>+ </Menu.Item>+ </>+ );+};+const PaneAddConnectorMenuItem = ({onAddConnector,position,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 49abe420ee..3592940faf 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,8 +12,10 @@ 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 '@xyflow/react/dist/style.css';+import { clearWorkflowClipboard, copyNodesToClipboard } from './clipboard';import { getWorkflowFlowInstance } from './flowInstanceStore';import { CONTENT_VISIBILITY_ZOOM } from './InvocationFlowNode';import { WorkflowEditorView } from './WorkflowEditorView';@@ -139,6 +141,7 @@ const createAdapter = (project: ReturnType<typeof createProjectStore>): Workflowconst subscribe = () => () => {};return {+ CommandShortcut: () => null,capabilities: { getSnapshot: () => ({ canUseCache: true }), subscribe },commands: {addWorkflow: vi.fn(),@@ -178,14 +181,43 @@ const createAdapter = (project: ReturnType<typeof createProjectStore>): Workflow} as unknown as WorkflowUiAdapter;};+/** The editor's registered command handlers, so a test can run a command as the palette or a hotkey would. */+const commandHandlers = new Map<string, () => void>();+const runtime = {- commands: { register: () => () => {} },+ commands: {+ register: ({ handler, id }: { handler: () => void; id: string }) => {+ commandHandlers.set(id, handler);+ return () => commandHandlers.delete(id);+ },+ },hotkeys: { register: () => () => {} },instanceId: INSTANCE_ID,region: 'center',typeId: 'workflow',} as const;+/** 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>) => {+ const adapter = createAdapter(project);++ await act(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueryClientProvider client={new QueryClient()}>+ <WorkflowUiProvider adapter={adapter}>+ <WorkflowEditorView runtime={runtime} />+ </WorkflowUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ </I18nextProvider>+ )+ );++ return adapter;+};+describe('WorkflowEditorView first open', () => {let host: HTMLDivElement;let root: Root;@@ -203,21 +235,6 @@ describe('WorkflowEditorView first open', () => {clearWorkflowViewports();});- const renderEditor = (project: ReturnType<typeof createProjectStore>) =>- act(() =>- root.render(- <I18nextProvider i18n={i18n}>- <ChakraProvider value={system}>- <QueryClientProvider client={new QueryClient()}>- <WorkflowUiProvider adapter={createAdapter(project)}>- <WorkflowEditorView runtime={runtime} />- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </I18nextProvider>- )- );-/** Opens the graph, waits for its mount fit, and counts every field input ever added to a node. */const openFitted = async (graph: ProjectGraphState) => {let addedFieldInputs = 0;@@ -232,7 +249,7 @@ describe('WorkflowEditorView first open', () => {});observer.observe(host, { childList: true, subtree: true });- await renderEditor(createProjectStore(graph));+ await renderEditor(root, createProjectStore(graph));const viewportKey = getWorkflowViewportKey(PROJECT_ID, graph.id, INSTANCE_ID);await expect.poll(() => getWorkflowViewport(viewportKey)).not.toBeNull();@@ -258,6 +275,20 @@ describe('WorkflowEditorView first open', () => {expect(host.querySelectorAll('.react-flow__node input')).toHaveLength(2);});+ it('fits a graph clear of the floating toolbar, so the nodes beside it take their own clicks', async () => {+ const nodes = [addNode('left', 0, 0), addNode('right', 700, 0)];+ await openFitted({ ...createProjectGraph('beside-toolbar'), nodes });+ const toolbar = host.querySelector<HTMLElement>('[role="toolbar"]')!.getBoundingClientRect();+ const left = host.querySelector<HTMLElement>('.react-flow__node[data-id="left"]')!;+ const rect = left.getBoundingClientRect();++ // The fitted graph's left column sits level with the toolbar's column.+ expect(rect.top).toBeLessThan(toolbar.bottom);+ expect(rect.left).toBeGreaterThanOrEqual(toolbar.right);+ const hit = document.elementFromPoint(rect.left + 4, rect.top + rect.height / 2);+ expect(hit !== null && left.contains(hit)).toBe(true);+ });+it('gives the next workflow its own flow, without errors from the outgoing one', async () => {const workflowA = {...createProjectGraph('workflow-a'),@@ -267,7 +298,7 @@ describe('WorkflowEditorView first open', () => {const project = createProjectStore(workflowA);const nodeIds = () => [...host.querySelectorAll('.react-flow__node')].map((node) => node.getAttribute('data-id'));- await renderEditor(project);+ await renderEditor(root, project);await expect.poll(nodeIds).toHaveLength(12);// The flow registers its instance on init, which can land after the nodes are in the DOM.await expect.poll(getWorkflowFlowInstance).toBeTruthy();@@ -304,3 +335,231 @@ describe('WorkflowEditorView first open', () => {expect(logged).toEqual([]);});});++describe('WorkflowEditorView paste', () => {+ let host: HTMLDivElement;+ let outside: HTMLButtonElement;+ let root: Root;+ const graph = {+ ...createProjectGraph('paste'),+ edges: [+ {+ id: 'outside-to-a',+ source: 'outside',+ sourceHandle: 'value',+ target: 'node-a',+ targetHandle: 'a',+ type: 'default',+ },+ ],+ nodes: [addNode('node-a', 0, 0), addNode('node-b', 100, 50), addNode('outside', -300, 0)],+ } satisfies ProjectGraphState;++ beforeEach(() => {+ host = document.createElement('div');+ host.style.cssText = 'width: 480px; height: 520px;';+ outside = document.createElement('button');+ outside.textContent = 'Side panel control';+ document.body.append(host, outside);+ root = createRoot(host);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ outside.remove();+ clearWorkflowViewports();+ clearWorkflowClipboard();+ });++ /** Opens the editor with nodes A and B copied, and reports the pasted node positions of the next paste. */+ const openWithCopiedNodes = async (nodeIds = ['node-a', 'node-b']) => {+ const adapter = await renderEditor(root, createProjectStore(graph));+ await expect.poll(getWorkflowFlowInstance).toBeTruthy();+ await expect.poll(() => host.querySelectorAll('.react-flow__node').length).toBe(3);+ // The mount fit moves the view once; points are read in the view it settles on.+ await expect+ .poll(() => getWorkflowViewport(getWorkflowViewportKey(PROJECT_ID, graph.id, INSTANCE_ID)))+ .not.toBeNull();+ copyNodesToClipboard(graph, nodeIds);++ const pasted = () => {+ const action = vi+ .mocked(adapter.commands.editGraph)+ .mock.calls.map(([call]) => call)+ .find((call) => call.type === 'addGraphElements');++ return action?.type === 'addGraphElements' ? action : null;+ };++ return { pasted };+ };++ /** Moves the real pointer over an empty corner of the pane and returns where it landed. */+ const hoverPane = async (): Promise<{ x: number; y: number }> => {+ let pointer = { x: 0, y: 0 };+ const record = (event: PointerEvent) => {+ pointer = { x: event.clientX, y: event.clientY };+ };+ document.addEventListener('pointermove', record);+ await userEvent.hover(host.querySelector('.react-flow__pane')!, { position: { x: 440, y: 480 } });+ document.removeEventListener('pointermove', record);++ return pointer;+ };++ const viewCenter = () => {+ const rect = host.getBoundingClientRect();++ return getWorkflowFlowInstance()!.screenToFlowPosition({+ x: rect.left + rect.width / 2,+ y: rect.top + rect.height / 2,+ });+ };++ it("puts the group's top-left at the pointer when the editor has focus and the pointer is over it", async () => {+ const { pasted } = await openWithCopiedNodes();+ const pointer = await hoverPane();+ host.querySelector<HTMLElement>('.react-flow__node[data-id="node-a"]')!.focus();++ await act(() => commandHandlers.get('workflows.pasteSelection')!());++ const anchor = getWorkflowFlowInstance()!.screenToFlowPosition(pointer);+ expect(pasted()?.nodes.map((node) => node.position)).toEqual([+ { x: anchor.x, y: anchor.y },+ { x: anchor.x + 100, y: anchor.y + 50 },+ ]);+ });++ it('centers the group in the visible view when focus is outside the editor', async () => {+ const { pasted } = await openWithCopiedNodes();+ await hoverPane();+ outside.focus();++ await act(() => commandHandlers.get('workflows.pasteSelection')!());++ const center = viewCenter();+ expect(pasted()?.nodes.map((node) => node.position)).toEqual([+ { x: center.x - 50, y: center.y - 25 },+ { x: center.x + 50, y: center.y + 25 },+ ]);+ });++ it('centers the group when the pointer has left the editor, even with focus inside it', async () => {+ const { pasted } = await openWithCopiedNodes();+ await hoverPane();+ await userEvent.hover(outside);+ host.querySelector<HTMLElement>('.react-flow__node[data-id="node-a"]')!.focus();++ await act(() => commandHandlers.get('workflows.pasteSelection')!());++ const center = viewCenter();+ expect(pasted()?.nodes[0]?.position).toEqual({ x: center.x - 50, y: center.y - 25 });+ });++ /** Picks a context menu item the way a hand does, which also moves focus into the menu. */+ const chooseMenuItem = async (value: string) => {+ const item = await vi.waitFor(() => {+ const element = document.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`);+ expect(element?.getAttribute('aria-disabled')).not.toBe('true');+ return element!;+ });+ await userEvent.click(item);+ };++ /** A node menu offers no paste point of its own: the group lands centered in the view, not where it was opened. */+ const expectCenteredPaste = (pasted: () => { nodes: { position: { x: number; y: number } }[] } | null) => {+ const center = viewCenter();+ expect(pasted()?.nodes.map((node) => node.position)).toEqual([+ { x: center.x - 50, y: center.y - 25 },+ { x: center.x + 50, y: center.y + 25 },+ ]);+ };++ it.each([false, true])(+ 'centers a paste chosen from a node’s own menu (with connections: %s) instead of anchoring it at the node',+ async (withConnections) => {+ const { pasted } = await openWithCopiedNodes();+ const node = host.querySelector<HTMLElement>('.react-flow__node[data-id="node-b"]')!;+ const rect = node.getBoundingClientRect();++ await act(() =>+ node.dispatchEvent(+ new MouseEvent('contextmenu', {+ bubbles: true,+ cancelable: true,+ clientX: rect.left + 10,+ clientY: rect.top + 10,+ })+ )+ );+ await chooseMenuItem(withConnections ? 'paste-with-connections' : 'paste');++ expectCenteredPaste(pasted);+ }+ );++ it('centers a paste chosen from the selection’s menu instead of anchoring it where the menu opened', async () => {+ const { pasted } = await openWithCopiedNodes();+ const pane = host.querySelector<HTMLElement>('.react-flow__pane')!;+ const paneRect = pane.getBoundingClientRect();++ // Box-select every node, so the selection's own rectangle (and its menu) appears.+ await userEvent.click(host.querySelector<HTMLElement>('button[aria-label="widgets.workflow.toolbar.boxSelect"]')!);+ await userEvent.dragAndDrop(pane, pane, {+ sourcePosition: { x: paneRect.width - 4, y: 4 },+ targetPosition: { x: 60, y: paneRect.height - 4 },+ });+ const selection = await vi.waitFor(() => {+ const element = host.querySelector<HTMLElement>('.react-flow__nodesselection-rect');+ expect(element).not.toBeNull();+ return element!;+ });+ const rect = selection.getBoundingClientRect();++ await act(() =>+ selection.dispatchEvent(+ new MouseEvent('contextmenu', {+ bubbles: true,+ cancelable: true,+ clientX: rect.left + 10,+ clientY: rect.top + 10,+ })+ )+ );+ await chooseMenuItem('paste');++ expectCenteredPaste(pasted);+ });++ it('anchors a paste chosen from the empty canvas menu at the point the menu was opened on', async () => {+ const { pasted } = await openWithCopiedNodes();+ const pane = host.querySelector<HTMLElement>('.react-flow__pane')!;+ const paneRect = pane.getBoundingClientRect();+ const point = { x: paneRect.left + paneRect.width - 40, y: paneRect.top + paneRect.height - 40 };++ // Read before the menu opens: focusing it can scroll the test page, which moves every client point.+ const anchor = getWorkflowFlowInstance()!.screenToFlowPosition(point);++ await act(() =>+ pane.dispatchEvent(+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y })+ )+ );+ await chooseMenuItem('paste');++ expect(pasted()?.nodes.map((node) => node.position)).toEqual([+ { x: anchor.x, y: anchor.y },+ { x: anchor.x + 100, y: anchor.y + 50 },+ ]);+ });++ it('keeps the copied node fed by its outside source only when pasting with connections', async () => {+ const { pasted } = await openWithCopiedNodes(['node-a']);++ await act(() => commandHandlers.get('workflows.pasteSelectionWithEdges')!());++ const action = pasted();+ expect(action?.edges).toEqual([expect.objectContaining({ source: 'outside', target: action?.nodes[0]?.id })]);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.tsxindex 81dff92a13..4a78915f54 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.test.tsx@@ -102,7 +102,7 @@ describe('getZoomedOutMountViewport', () => {const container = { height: 900, width: 450 };it('keeps the default viewport while the fit could still land at a readable zoom', () => {- expect(getZoomedOutMountViewport([target('a', 0, 0), target('b', 1000, 0)], container)).toBeNull();+ expect(getZoomedOutMountViewport([target('a', 0, 0), target('b', 900, 0)], container)).toBeNull();expect(getZoomedOutMountViewport([target('a', 0, 0), target('b', 0, 2000)], container)).toBeNull();});@@ -115,11 +115,12 @@ describe('getZoomedOutMountViewport', () => {});it('counts the fit’s padding, which lowers the zoom it can land at', () => {- // 450 px less XYFlow's 10% padding leaves 410 px, which shows 1025 px of positions at the content zoom.- expect(getZoomedOutMountViewport([target('a', 0, 0), target('b', 1030, 0)], container)?.zoom).toBeLessThan(+ // 450 px less the toolbar's 56 px and XYFlow's 20 px on the right leaves 374 px, which shows 935 px of positions+ // at the content zoom.+ expect(getZoomedOutMountViewport([target('a', 0, 0), target('b', 940, 0)], container)?.zoom).toBeLessThan(CONTENT_VISIBILITY_ZOOM);- expect(getZoomedOutMountViewport([target('a', 0, 0), target('b', 1020, 0)], container)).toBeNull();+ expect(getZoomedOutMountViewport([target('a', 0, 0), target('b', 930, 0)], container)).toBeNull();});it('frames the positions in the container', () => {@@ -132,7 +133,8 @@ describe('getZoomedOutMountViewport', () => {{ x: -500, y: 100 },{ x: 2500, y: 700 },]) {- expect(position.x * zoom + x).toBeGreaterThanOrEqual(0);+ // Clear of the toolbar floating over the left edge.+ expect(position.x * zoom + x).toBeGreaterThanOrEqual(56);expect(position.x * zoom + x).toBeLessThanOrEqual(container.width);expect(position.y * zoom + y).toBeGreaterThanOrEqual(0);expect(position.y * zoom + y).toBeLessThanOrEqual(container.height);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex a9a0f2bbb5..625b1b1ec2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -38,6 +38,7 @@ import {applyEdgeChanges,applyNodeChanges,getViewportForBounds,+ useStoreApi,type Connection,type EdgeChange,type EdgeTypes,@@ -60,33 +61,44 @@ import {useState,startTransition,type MouseEvent as ReactMouseEvent,+ type PointerEvent as ReactPointerEvent,} from 'react';import { flushSync } from 'react-dom';import { useTranslation } from 'react-i18next';import type { WorkflowImageExportView } from './WorkflowImageExportView';-import { buildDuplicateElements, buildPasteElements, copyNodesToClipboard, useHasClipboardNodes } from './clipboard';+import {+ buildDuplicateElements,+ buildPasteElements,+ copyNodesToClipboard,+ useHasClipboardNodes,+ type WorkflowPastePlacement,+} from './clipboard';import { ConnectorFlowNode } from './ConnectorFlowNode';import { CurrentImageFlowNode } from './CurrentImageFlowNode';import { EditorToolbar, type EditorTool } from './EditorToolbar';+import { fitWorkflowBounds } from './fitWorkflowBounds';import {toFlowEdges,toFlowNodes,withNodeSelection,type FlowEdgeType,+ type InvocationTemplateStatus,type WorkflowFlowEdge,type WorkflowFlowNode,} from './flowAdapters';import {registerWorkflowFlowInstance,releaseWorkflowFlowInstance,+ WORKFLOW_FIT_PADDING,+ WORKFLOW_TOOLBAR_CLEARANCE_PX,type WorkflowFitViewTarget,type WorkflowFlowInstance,} from './flowInstanceStore';import { CONTENT_VISIBILITY_ZOOM, InvocationFlowNode } from './InvocationFlowNode';import LoopBodyBoundaryOverlay from './LoopBodyBoundaryOverlay';-import { NodeContextMenu, type WorkflowContextMenuState } from './NodeContextMenu';+import { NodeContextMenu, type WorkflowContextMenuPaste, type WorkflowContextMenuState } from './NodeContextMenu';import { NotesFlowNode } from './NotesFlowNode';import {isLargeWorkflowGraph,@@ -142,10 +154,9 @@ const toDocumentEdge = (connection: Connection): WorkflowDocumentEdge | null =>const DEFAULT_EDGE_OPTIONS = { style: { strokeWidth: 2 } };// Offset fresh graphs so the floating left toolbar does not cover their first column.-const DEFAULT_VIEWPORT = { x: 56, y: 0, zoom: 1 } as const;+const DEFAULT_VIEWPORT = { x: WORKFLOW_TOOLBAR_CLEARANCE_PX, y: 0, zoom: 1 } as const;const MIN_ZOOM = 0.1;const MAX_ZOOM = 2;-const FIT_PADDING = 0.1;/*** Where a newly shown graph opens until its mount fit lands, or null for the default viewport. That fit waits for the@@ -175,16 +186,17 @@ export const getZoomedOutMountViewport = (}const bounds = { height: maxY - minY, width: maxX - minX, x: minX, y: minY };- // The fit's zoom for these positions with its padding, as XYFlow resolves a fractional padding; node sizes only- // lower it.- const paddedSize = (size: number) => size - 2 * Math.floor((size - size / (1 + FIT_PADDING)) * 0.5);- const zoomUpperBound = Math.min(- paddedSize(container.width) / bounds.width,- paddedSize(container.height) / bounds.height- );+ // The fit's zoom for these positions with its padding, as XYFlow resolves a fractional side; node sizes only lower+ // it.+ const fractionalSide = (size: number, padding: number) => Math.floor((size - size / (1 + padding)) * 0.5);+ const { bottom, right, top } = WORKFLOW_FIT_PADDING;+ const paddedWidth = container.width - WORKFLOW_TOOLBAR_CLEARANCE_PX - fractionalSide(container.width, right);+ const paddedHeight =+ container.height - fractionalSide(container.height, top) - fractionalSide(container.height, bottom);+ const zoomUpperBound = Math.min(paddedWidth / bounds.width, paddedHeight / bounds.height);return zoomUpperBound < CONTENT_VISIBILITY_ZOOM- ? getViewportForBounds(bounds, container.width, container.height, MIN_ZOOM, MAX_ZOOM, FIT_PADDING)+ ? getViewportForBounds(bounds, container.width, container.height, MIN_ZOOM, MAX_ZOOM, WORKFLOW_FIT_PADDING): null;};@@ -207,6 +219,7 @@ const buildWorkflowFlowModel = ({isCompact = false,canUseCache = false,perfSource,+ templateStatus,time,}: {canUseCache?: boolean;@@ -215,6 +228,7 @@ const buildWorkflowFlowModel = ({isCompact?: boolean;invocationTemplates?: Parameters<typeof toFlowNodes>[2];perfSource: WorkflowPerfSource;+ templateStatus: InvocationTemplateStatus;previousEdges?: WorkflowFlowEdge[];previousNodes?: WorkflowFlowNode[];reduceMotion: boolean;@@ -230,7 +244,7 @@ const buildWorkflowFlowModel = ({toFlowEdges(document, previousEdges, edgeType, selectedNodeIds, invocationTemplates, reduceMotion, index)),nodes: time('workflow:to-flow-nodes', perfSource, () =>- toFlowNodes(document, previousNodes, invocationTemplates, index, isCompact, canUseCache)+ toFlowNodes(document, previousNodes, invocationTemplates, index, isCompact, canUseCache, templateStatus)),}));};@@ -306,9 +320,12 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);const projectId = useWorkflowProjectSelector((project) => project.id);const workflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);+ const canUndo = useWorkflowProjectSelector((project) => project.canUndo);+ const canRedo = useWorkflowProjectSelector((project) => project.canRedo);const ui = useWorkflowUi();const { mark: markWorkbenchPerf, measure: measureWorkbenchPerf, time: timeWorkbenchPerf } = ui.performance;const { editGraph, redo, undo } = useProjectGraphCommands();+ const flowStore = useStoreApi<WorkflowFlowNode, WorkflowFlowEdge>();const notify = useWorkflowNotifications();const { t } = useTranslation();const {@@ -334,6 +351,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {const templatesStatus = useInvocationTemplatesSelector((snapshot) => snapshot.status);const templates = useInvocationTemplatesSelector((snapshot) => snapshot.templates);const invocationTemplates = templatesStatus === 'loaded' ? templates : undefined;+ const templateStatus: InvocationTemplateStatus =+ templatesStatus === 'loaded' || templatesStatus === 'error' ? templatesStatus : 'loading';const canUseCache = useWorkflowCapabilitiesSelector((capabilities) => capabilities.canUseCache);const edgeType: FlowEdgeType = workflowEdgeStyle === 'square' ? 'step' : 'default';const isLargeGraph = isLargeWorkflowGraph({@@ -380,6 +399,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {isCompact: isLargeGraph,perfSource,reduceMotion,+ templateStatus,time: timeWorkbenchPerf,}));@@ -420,7 +440,14 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {projectGraph: ProjectGraphState;reduceMotion: boolean;selectedNodeIds: string[];+ templateStatus: InvocationTemplateStatus;} | null>(null);+ const editorRef = useRef<HTMLDivElement>(null);+ /** The last pointer position over this editor, kept outside state so pointer moves never re-render it. */+ const pointerRef = useRef<{ client: XYPosition | null; isOverEditor: boolean }>({+ client: null,+ isOverEditor: false,+ });const selectNodes = useCallback((nodeIds: string[]) => {@@ -568,7 +595,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {lastBuiltModel.edgeType === edgeType &&lastBuiltModel.invocationTemplates === invocationTemplates &&lastBuiltModel.reduceMotion === reduceMotion &&- lastBuiltModel.selectedNodeIds === nextSelectedNodeIds+ lastBuiltModel.selectedNodeIds === nextSelectedNodeIds &&+ lastBuiltModel.templateStatus === templateStatus) {return undefined;}@@ -580,6 +608,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {projectGraph,reduceMotion,selectedNodeIds: nextSelectedNodeIds,+ templateStatus,};startTransition(() => {@@ -595,6 +624,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {previousNodes: current?.nodes,reduceMotion,selectedNodeIds: nextSelectedNodeIdSet,+ templateStatus,time: timeWorkbenchPerf,});@@ -628,6 +658,7 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {reduceMotion,selectedNodeIds,shouldDeferInitialBuild,+ templateStatus,timeWorkbenchPerf,]);@@ -669,16 +700,51 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {[getActionNodeIds, notify, projectGraph, t]);- const pasteNodes = useCallback(() => {- const { edges, nodes } = buildPasteElements();+ /**+ * Where a paste without an explicit anchor lands: at the pointer while it is over this editor and focus is not+ * elsewhere (the editor, or nothing, holds it), otherwise centered in the visible view. A palette, menu, or side+ * panel holds focus while it runs the command, so those paste into the middle of what the user sees.+ */+ const getPastePlacement = useCallback((): WorkflowPastePlacement | undefined => {+ const container = editorRef.current;- if (nodes.length === 0) {- return;+ if (!flowInstance || !container) {+ return undefined;}- pendingSelectionRef.current = nodes.map((node) => node.id);- editGraph({ edges, nodes, type: 'addGraphElements' });- }, [editGraph]);+ const { client, isOverEditor } = pointerRef.current;+ const focused = document.activeElement;+ const isFocusFree = !focused || focused === document.body || container.contains(focused);++ if (client && isOverEditor && isFocusFree) {+ return { align: 'top-left', point: flowInstance.screenToFlowPosition(client) };+ }++ const rect = container.getBoundingClientRect();++ return {+ align: 'center',+ point: flowInstance.screenToFlowPosition({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }),+ };+ }, [flowInstance]);++ /** Pastes the clipboard with its top-left at `at`, or where `getPastePlacement` decides. */+ const pasteNodes = useCallback(+ (withConnections: boolean, at?: XYPosition) => {+ const { edges, nodes } = buildPasteElements({+ placement: at ? { align: 'top-left', point: at } : getPastePlacement(),+ withConnections,+ });++ if (nodes.length === 0) {+ return;+ }++ pendingSelectionRef.current = nodes.map((node) => node.id);+ editGraph({ edges, nodes, type: 'addGraphElements' });+ },+ [editGraph, getPastePlacement]+ );const duplicateNodes = useCallback((nodeId?: string) => {@@ -739,9 +805,12 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {copyNodes();return;}- case 'workflows.pasteSelection':+ case 'workflows.pasteSelection': {+ pasteNodes(false);+ return;+ }case 'workflows.pasteSelectionWithEdges': {- pasteNodes();+ pasteNodes(true);return;}case 'workflows.duplicateSelection': {@@ -1192,10 +1261,21 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {duplicateNodes(contextMenu?.kind === 'node' ? contextMenu.nodeId : undefined);setContextMenu(null);}, [contextMenu, duplicateNodes]);- const onContextMenuPaste = useCallback(() => {- pasteNodes();- setContextMenu(null);- }, [pasteNodes]);+ // Only the empty-canvas menu names a point; a node or selection menu pastes like any other menu, centered in the+ // view, so the copy never lands on the nodes it was opened on.+ const onContextMenuPaste = useCallback<WorkflowContextMenuPaste>(+ (withConnections, position) => {+ pasteNodes(withConnections, position);+ setContextMenu(null);+ },+ [pasteNodes]+ );+ const onEditorPointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {+ pointerRef.current = { client: { x: event.clientX, y: event.clientY }, isOverEditor: true };+ }, []);+ const onEditorPointerLeave = useCallback(() => {+ pointerRef.current = { ...pointerRef.current, isOverEditor: false };+ }, []);const onContextMenuToggleOpen = useCallback(() => {if (contextMenu?.kind === 'node' && contextMenu.nodeId && contextMenu.isNodeOpen !== null) {editGraph({ isOpen: !contextMenu.isNodeOpen, nodeId: contextMenu.nodeId, type: 'setNodeIsOpen' });@@ -1233,8 +1313,17 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {editGraph({ positions, type: 'setNodePositions' });// The flow shows the new positions after the model rebuilds; the bounds are known now, so fit them directly.- void flowInstance.fitBounds(bounds, { duration: reduceMotion ? 0 : 300 });- }, [arrangeScope, editGraph, flowInstance, projectGraph.edges, projectGraph.nodes, reduceMotion, selectedNodeIds]);+ void fitWorkflowBounds(flowInstance, bounds, flowStore.getState(), reduceMotion ? 0 : 300);+ }, [+ arrangeScope,+ editGraph,+ flowInstance,+ flowStore,+ projectGraph.edges,+ projectGraph.nodes,+ reduceMotion,+ selectedNodeIds,+ ]);if (isPreparing) {return <WorkflowEditorPreparingState edgeCount={projectGraph.edges.length} nodeCount={projectGraph.nodes.length} />;@@ -1246,12 +1335,16 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {return (<Box+ ref={editorRef}bg="bg.inset"css={editorCss}h="full"position="relative"w="full"onContextMenuCapture={onEditorContextMenuCapture}+ onPointerEnter={onEditorPointerMove}+ onPointerLeave={onEditorPointerLeave}+ onPointerMove={onEditorPointerMove}{...pointerToolHandlers}><ReactFlow<WorkflowFlowNode, WorkflowFlowEdge>@@ -1304,6 +1397,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {<LoopBodyBoundaryOverlay edges={projectGraph.edges} nodes={projectGraph.nodes} /><EditorToolbararrangeScope={arrangeScope}+ canRedo={canRedo}+ canUndo={canUndo}nodeOpacity={nodeOpacity}tool={tool}updatableNodeCount={updatableNodeCount}@@ -1311,7 +1406,9 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {onExportPrepare={onExportPrepare}onExportComplete={onExportComplete}onNodeOpacityChange={setNodeOpacity}+ onRedo={redo}onToolChange={setTool}+ onUndo={undo}onUpdateNodes={onUpdateNodes}/>{workflowShowMinimap && (!isLargeGraph || isMinimapReady) ? <FlowMiniMap /> : null}diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsxindex b2f4630e87..24d13d1289 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.browser.test.tsx@@ -7,7 +7,12 @@ import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { requestWorkflowFitView, workflowFitViewRequestStore, type WorkflowFlowInstance } from './flowInstanceStore';+import {+ requestWorkflowFitView,+ WORKFLOW_FIT_PADDING,+ workflowFitViewRequestStore,+ type WorkflowFlowInstance,+} from './flowInstanceStore';import { requestNodeSelection, workflowSelectionStore } from './selectionStore';import { WorkflowSelectionRequestRuntime } from './WorkflowSelectionRequestRuntime';@@ -25,6 +30,12 @@ vi.mock('@features/workflow/react', () => ({},}));+// The fits' padding is the editor view's concern; here a fit is the bounds it was asked for.+vi.mock('./fitWorkflowBounds', () => ({+ fitWorkflowBounds: (instance: WorkflowFlowInstance, bounds: unknown, _flow: unknown, duration: number) =>+ instance.fitBounds(bounds as Parameters<WorkflowFlowInstance['fitBounds']>[0], { duration }),+}));+const SCOPE = { projectId: 'project-1', workflowId: 'workflow-1' };(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -91,6 +102,7 @@ describe('WorkflowSelectionRequestRuntime', () => {duration: 300,maxZoom: 1.25,nodes: [{ id: 'pending-node' }],+ padding: WORKFLOW_FIT_PADDING,});await act(() => {@@ -110,7 +122,12 @@ describe('WorkflowSelectionRequestRuntime', () => {act(() => requestNodeSelection(['later-node']));expect(selectNodes).toHaveBeenLastCalledWith(['later-node']);- expect(fitView).toHaveBeenLastCalledWith({ duration: 0, maxZoom: 1.25, nodes: [{ id: 'later-node' }] });+ expect(fitView).toHaveBeenLastCalledWith({+ duration: 0,+ maxZoom: 1.25,+ nodes: [{ id: 'later-node' }],+ padding: WORKFLOW_FIT_PADDING,+ });await act(() => root?.unmount());root = null;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsxindex 2fe290d3e7..a24769d986 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowSelectionRequestRuntime.tsx@@ -8,9 +8,11 @@ import { useEffectEvent, useRef } from 'react';import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';+import { fitWorkflowBounds } from './fitWorkflowBounds';import {clearWorkflowFitViewRequest,workflowFitViewRequestStore,+ WORKFLOW_FIT_PADDING,type WorkflowFitViewTarget,type WorkflowFlowInstance,} from './flowInstanceStore';@@ -118,6 +120,7 @@ export const WorkflowSelectionRequestRuntime = ({duration: reduceMotion ? 0 : 300,maxZoom: 1.25,nodes: selectionRequest.nodeIds.map((id) => ({ id })),+ padding: WORKFLOW_FIT_PADDING,});clearNodeSelectionRequest();});@@ -151,7 +154,7 @@ export const WorkflowSelectionRequestRuntime = ({if (mountBounds) {pendingMountFit.current = null;- void flowInstance.fitBounds(mountBounds, { duration: 0 });+ void fitWorkflowBounds(flowInstance, mountBounds, store.getState(), 0);}const requestTargets = getRequestTargets();@@ -159,7 +162,7 @@ export const WorkflowSelectionRequestRuntime = ({if (requestBounds) {clearWorkflowFitViewRequest();- void flowInstance.fitBounds(requestBounds, { duration: reduceMotion ? 0 : 300 });+ void fitWorkflowBounds(flowInstance, requestBounds, store.getState(), reduceMotion ? 0 : 300);}});// Targets are the document's nodes; the flow shows them only after React commits the rebuilt model (and, for adiff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.test.tsindex 5accfd432e..76a9bdf938 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.test.ts@@ -1,4 +1,9 @@-import type { ProjectGraphState, WorkflowEdge, WorkflowInvocationNode } from '@features/workflow/contracts';+import type {+ ProjectGraphState,+ WorkflowConnectorNode,+ WorkflowEdge,+ WorkflowInvocationNode,+} from '@features/workflow/contracts';import { createProjectGraph } from '@features/workflow/utility';import { describe, expect, it } from 'vitest';@@ -31,6 +36,22 @@ const createEdge = (id: string, source: string, target: string): WorkflowEdge =>type: 'default',});+const createConnector = (id: string): WorkflowConnectorNode => ({+ data: { label: '' },+ id,+ position: { x: 50, y: 0 },+ type: 'connector',+});++const connectorEdge = (id: string, source: string, target: string): WorkflowEdge => ({+ id,+ source,+ sourceHandle: source.startsWith('connector') ? 'out' : 'value',+ target,+ targetHandle: target.startsWith('connector') ? 'in' : 'a',+ type: 'default',+});+const createDoc = (): ProjectGraphState => ({...createProjectGraph('clipboard-test'),edges: [createEdge('edge-1', 'node-a', 'node-b'), createEdge('edge-2', 'node-outside', 'node-a')],@@ -73,7 +94,7 @@ describe('workflow clipboard', () => {it('anchors the pasted group on an explicit position, preserving relative layout', () => {copyNodesToClipboard(createDoc(), ['node-a', 'node-b']);- const { nodes } = buildPasteElements({ x: 500, y: 500 });+ const { nodes } = buildPasteElements({ placement: { align: 'top-left', point: { x: 500, y: 500 } } });expect(nodes.map((node) => node.position)).toEqual([{ x: 500, y: 500 },@@ -81,6 +102,82 @@ describe('workflow clipboard', () => {]);});+ it("centers the group's node positions on a point, preserving relative layout", () => {+ copyNodesToClipboard(createDoc(), ['node-a', 'node-b']);++ const { nodes } = buildPasteElements({ placement: { align: 'center', point: { x: 500, y: 500 } } });++ // Positions span (0,0)–(100,50); their middle (50,25) lands on the point.+ expect(nodes.map((node) => node.position)).toEqual([+ { x: 450, y: 475 },+ { x: 550, y: 525 },+ ]);+ });++ it('keeps edges from outside nodes only when pasting with connections', () => {+ copyNodesToClipboard(createDoc(), ['node-a']);++ expect(buildPasteElements().edges).toEqual([]);++ const { edges, nodes } = buildPasteElements({ withConnections: true });++ expect(edges).toHaveLength(1);+ expect(edges[0]).toMatchObject({ source: 'node-outside', target: nodes[0]?.id });+ expect(edges[0]?.id).not.toBe('edge-2');+ });++ it('never carries a loop linkage into a pasted copy', () => {+ copyNodesToClipboard(+ {+ ...createDoc(),+ edges: [+ { ...createEdge('linkage', 'node-outside', 'node-a'), targetHandle: 'loop_linkage', type: 'loop_linkage' },+ { ...createEdge('aliased-linkage', 'node-outside', 'node-a'), targetHandle: 'loop_linkage' },+ ],+ },+ ['node-a']+ );++ expect(buildPasteElements({ withConnections: true }).edges).toEqual([]);+ });++ it('copies an unselected connector that bridges two copied nodes', () => {+ const doc: ProjectGraphState = {+ ...createProjectGraph('clipboard-connector-test'),+ edges: [+ connectorEdge('a-to-c1', 'node-a', 'connector-1'),+ connectorEdge('c1-to-c2', 'connector-1', 'connector-2'),+ connectorEdge('c2-to-b', 'connector-2', 'node-b'),+ connectorEdge('outside-to-c3', 'node-outside', 'connector-3'),+ connectorEdge('c3-to-b', 'connector-3', 'node-b'),+ connectorEdge('a-to-c4', 'node-a', 'connector-4'),+ connectorEdge('c4-to-outside', 'connector-4', 'node-outside'),+ ],+ nodes: [+ createNode('node-a', 0, 0),+ createNode('node-b', 100, 50),+ createNode('node-outside', -200, 0),+ createConnector('connector-1'),+ createConnector('connector-2'),+ createConnector('connector-3'),+ createConnector('connector-4'),+ ],+ };++ expect(copyNodesToClipboard(doc, ['node-a', 'node-b'])).toBe(2);++ const { edges, nodes } = buildPasteElements();+ const originalIdByPastedId = new Map(+ nodes.map((node, index) => [node.id, ['node-a', 'node-b', 'connector-1', 'connector-2'][index]])+ );++ // Connectors 3 (fed from outside) and 4 (leading outside) do not bridge the copy.+ expect(nodes.map((node) => node.type)).toEqual(['invocation', 'invocation', 'connector', 'connector']);+ expect(+ edges.map((edge) => `${originalIdByPastedId.get(edge.source)}->${originalIdByPastedId.get(edge.target)}`)+ ).toEqual(['node-a->connector-1', 'connector-1->connector-2', 'connector-2->node-b']);+ });+it('duplicates in place without touching the clipboard', () => {copyNodesToClipboard(createDoc(), ['node-a']);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.tsindex 9b64ff302a..809f95b62b 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/clipboard.ts@@ -1,6 +1,14 @@import type { ProjectGraphState, WorkflowEdge, WorkflowNode, XYPosition } from '@features/workflow/contracts';-import { createWorkflowId } from '@features/workflow/utility';+import { isConnectorNode } from '@features/workflow/contracts';+import {+ createWorkflowGraphIndex,+ createWorkflowId,+ getConnectorInputEdgeIndexed,+ getConnectorOutputEdgesIndexed,+ LOOP_LINKAGE_FIELD,+ type WorkflowGraphIndex,+} from '@features/workflow/utility';import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';@@ -12,14 +20,29 @@ import { createExternalStore } from '@platform/state/externalStore';interface WorkflowClipboardSnapshot {nodes: WorkflowNode[];edges: WorkflowEdge[];+ /** Edges from nodes outside the copy into it, kept by their original source id for paste with connections. */+ incomingEdges: WorkflowEdge[];}-const clipboardStore = createExternalStore<WorkflowClipboardSnapshot>({ edges: [], nodes: [] });+interface WorkflowGraphElements {+ nodes: WorkflowNode[];+ edges: WorkflowEdge[];+}++/** Where a pasted group lands: its top-left node position, or the middle of its node positions, at `point`. */+export interface WorkflowPastePlacement {+ align: 'center' | 'top-left';+ point: XYPosition;+}++const EMPTY_SNAPSHOT: WorkflowClipboardSnapshot = { edges: [], incomingEdges: [], nodes: [] };++const clipboardStore = createExternalStore<WorkflowClipboardSnapshot>(EMPTY_SNAPSHOT);const PASTE_OFFSET = 32;export const clearWorkflowClipboard = (): void => {- clipboardStore.setSnapshot({ edges: [], nodes: [] });+ clipboardStore.setSnapshot(EMPTY_SNAPSHOT);};registerAccountOwnedResource({@@ -27,30 +50,151 @@ registerAccountOwnedResource({name: 'workflow-clipboard',});+/**+ * Unselected connectors that carry a copied node's output on to another copied node. Copying them keeps A → C → B+ * intact when only A and B are selected.+ */+const getBridgingConnectorIds = (+ nodes: WorkflowNode[],+ index: WorkflowGraphIndex,+ copiedIds: ReadonlySet<string>+): Set<string> => {+ const upstreamCache = new Map<string, boolean>();+ const downstreamCache = new Map<string, boolean>();++ const isConnectorId = (id: string): boolean => {+ const node = index.nodesById.get(id);+ return node !== undefined && isConnectorNode(node);+ };++ const startsAtCopiedNode = (connectorId: string, visiting: Set<string>): boolean => {+ const cached = upstreamCache.get(connectorId);++ if (cached !== undefined) {+ return cached;+ }++ const source = getConnectorInputEdgeIndexed(connectorId, index)?.source;+ let result = false;++ if (source !== undefined && !visiting.has(source)) {+ visiting.add(source);+ result = copiedIds.has(source) || (isConnectorId(source) && startsAtCopiedNode(source, visiting));+ }++ upstreamCache.set(connectorId, result);+ return result;+ };++ const reachesCopiedNode = (connectorId: string, visiting: Set<string>): boolean => {+ const cached = downstreamCache.get(connectorId);++ if (cached !== undefined) {+ return cached;+ }++ let result = false;++ for (const edge of getConnectorOutputEdgesIndexed(connectorId, index)) {+ if (visiting.has(edge.target)) {+ continue;+ }++ visiting.add(edge.target);++ if (copiedIds.has(edge.target) || (isConnectorId(edge.target) && reachesCopiedNode(edge.target, visiting))) {+ result = true;+ break;+ }+ }++ downstreamCache.set(connectorId, result);+ return result;+ };++ const bridgingIds = new Set<string>();++ for (const node of nodes) {+ if (+ isConnectorNode(node) &&+ !copiedIds.has(node.id) &&+ startsAtCopiedNode(node.id, new Set([node.id])) &&+ reachesCopiedNode(node.id, new Set([node.id]))+ ) {+ bridgingIds.add(node.id);+ }+ }++ return bridgingIds;+};++const isLoopLinkageEdge = (edge: WorkflowEdge): boolean =>+ edge.type === 'loop_linkage' || edge.targetHandle === LOOP_LINKAGE_FIELD;++/** Copies the nodes, their internal edges, bridging connectors, and incoming edges; returns the selected count. */export const copyNodesToClipboard = (document: ProjectGraphState, nodeIds: string[]): number => {- const copiedIds = new Set(nodeIds);- const nodes = document.nodes.filter((node) => copiedIds.has(node.id));+ const selectedIds = new Set(nodeIds);+ const selectedCount = document.nodes.filter((node) => selectedIds.has(node.id)).length;- if (nodes.length === 0) {+ if (selectedCount === 0) {return 0;}- const edges = document.edges.filter((edge) => copiedIds.has(edge.source) && copiedIds.has(edge.target));+ const index = createWorkflowGraphIndex(document.nodes, document.edges);+ const copiedIds = new Set([...selectedIds, ...getBridgingConnectorIds(document.nodes, index, selectedIds)]);+ const nodes = document.nodes.filter((node) => copiedIds.has(node.id));+ const edges: WorkflowEdge[] = [];+ const incomingEdges: WorkflowEdge[] = [];++ for (const edge of document.edges) {+ if (!copiedIds.has(edge.target)) {+ continue;+ }++ if (copiedIds.has(edge.source)) {+ edges.push(edge);+ } else if (!isLoopLinkageEdge(edge)) {+ // A For links to exactly one ForReturn, so a pasted ForReturn never takes the original's linkage.+ incomingEdges.push(edge);+ }+ }- clipboardStore.setSnapshot(structuredClone({ edges, nodes }));+ clipboardStore.setSnapshot(structuredClone({ edges, incomingEdges, nodes }));- return nodes.length;+ return selectedCount;};export const hasClipboardNodes = (): boolean => clipboardStore.getSnapshot().nodes.length > 0;export const useHasClipboardNodes = (): boolean => clipboardStore.useSelector((snapshot) => snapshot.nodes.length > 0);+const getPlacementOffset = (nodes: WorkflowNode[], placement: WorkflowPastePlacement | undefined): XYPosition => {+ if (!placement) {+ return { x: PASTE_OFFSET, y: PASTE_OFFSET };+ }++ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const { position } of nodes) {+ minX = Math.min(minX, position.x);+ minY = Math.min(minY, position.y);+ maxX = Math.max(maxX, position.x);+ maxY = Math.max(maxY, position.y);+ }++ const anchor = placement.align === 'center' ? { x: (minX + maxX) / 2, y: (minY + maxY) / 2 } : { x: minX, y: minY };++ return { x: placement.point.x - anchor.x, y: placement.point.y - anchor.y };+};+const materializeElements = (payload: WorkflowClipboardSnapshot,- at?: XYPosition-): { nodes: WorkflowNode[]; edges: WorkflowEdge[] } => {- const { edges, nodes } = structuredClone(payload);+ { placement, withConnections = false }: { placement?: WorkflowPastePlacement; withConnections?: boolean } = {}+): WorkflowGraphElements => {+ const { edges, incomingEdges, nodes } = structuredClone(payload);if (nodes.length === 0) {return { edges: [], nodes: [] };@@ -62,22 +206,24 @@ const materializeElements = (idMap.set(node.id, createWorkflowId(node.type === 'invocation' ? node.data.type : node.type));}- let offset: XYPosition = { x: PASTE_OFFSET, y: PASTE_OFFSET };-- if (at) {- const minX = Math.min(...nodes.map((node) => node.position.x));- const minY = Math.min(...nodes.map((node) => node.position.y));-- offset = { x: at.x - minX, y: at.y - minY };- }+ const offset = getPlacementOffset(nodes, placement);+ const internalEdges = edges.map((edge) => ({+ ...edge,+ id: createWorkflowId('edge'),+ source: idMap.get(edge.source) ?? edge.source,+ target: idMap.get(edge.target) ?? edge.target,+ }));+ // Incoming edges keep their outside source; the reducer drops any whose source is not in the document.+ const connectedEdges = withConnections+ ? incomingEdges.map((edge) => ({+ ...edge,+ id: createWorkflowId('edge'),+ target: idMap.get(edge.target) ?? edge.target,+ }))+ : [];return {- edges: edges.map((edge) => ({- ...edge,- id: createWorkflowId('edge'),- source: idMap.get(edge.source) ?? edge.source,- target: idMap.get(edge.target) ?? edge.target,- })),+ edges: [...internalEdges, ...connectedEdges],nodes: nodes.map((node) => ({...node,id: idMap.get(node.id) ?? node.id,@@ -86,19 +232,21 @@ const materializeElements = (};};-/** Assign fresh IDs and offset positions, or anchor the group's top-left at the requested point. */-export const buildPasteElements = (at?: XYPosition): { nodes: WorkflowNode[]; edges: WorkflowEdge[] } =>- materializeElements(clipboardStore.getSnapshot(), at);+/**+ * Assign fresh IDs and place the group (a fixed offset from the original without a placement). With connections,+ * edges that fed the copied nodes from outside feed the pasted copies from the same sources.+ */+export const buildPasteElements = (+ options: { placement?: WorkflowPastePlacement; withConnections?: boolean } = {}+): WorkflowGraphElements => materializeElements(clipboardStore.getSnapshot(), options);/** Clone-in-place for the given nodes (and their internal edges) without touching the clipboard. */-export const buildDuplicateElements = (- document: ProjectGraphState,- nodeIds: string[]-): { nodes: WorkflowNode[]; edges: WorkflowEdge[] } => {+export const buildDuplicateElements = (document: ProjectGraphState, nodeIds: string[]): WorkflowGraphElements => {const copiedIds = new Set(nodeIds);return materializeElements({edges: document.edges.filter((edge) => copiedIds.has(edge.source) && copiedIds.has(edge.target)),+ incomingEdges: [],nodes: document.nodes.filter((node) => copiedIds.has(node.id)),});};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/fitWorkflowBounds.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/fitWorkflowBounds.tsnew file mode 100644index 0000000000..32b108bd21--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/fitWorkflowBounds.ts@@ -0,0 +1,22 @@+import type { Rect } from '@xyflow/react';++import { getViewportForBounds } from '@xyflow/react';++import { WORKFLOW_FIT_PADDING, type WorkflowFlowInstance } from './flowInstanceStore';++// Kept out of `flowInstanceStore`, which eager library code imports: an XYFlow value import there pulls the editor's+// flow runtime and its CSS into startup.+/**+ * Fits the view to graph bounds with {@link WORKFLOW_FIT_PADDING}. XYFlow's `fitBounds` takes only one padding for+ * every side, so the viewport is resolved here from the flow's size and zoom limits.+ */+export const fitWorkflowBounds = (+ instance: WorkflowFlowInstance,+ bounds: Rect,+ flow: { height: number; maxZoom: number; minZoom: number; width: number },+ duration: number+): Promise<boolean> =>+ instance.setViewport(+ getViewportForBounds(bounds, flow.width, flow.height, flow.minZoom, flow.maxZoom, WORKFLOW_FIT_PADDING),+ { duration }+ );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 d47ea8f669..905868d858 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@@ -198,6 +198,18 @@ describe('flowAdapters identity preservation', () => {expect(compactAgain[0]).toBe(compact[0]);});+ it('carries the template status onto invocation nodes and rebuilds them only when it changes', () => {+ const doc = createDoc();+ const loading = toFlowNodes(doc, [], undefined, undefined, false, false, 'loading');+ const stillLoading = toFlowNodes(doc, loading, undefined, undefined, false, false, 'loading');+ const failed = toFlowNodes(doc, stillLoading, undefined, undefined, false, false, 'error');++ expect(loading[0]?.type === 'invocation' && loading[0].data.templateStatus).toBe('loading');+ expect(stillLoading[0]).toBe(loading[0]);+ expect(failed[0]?.type === 'invocation' && failed[0].data.templateStatus).toBe('error');+ expect(failed[0]).not.toBe(loading[0]);+ });+it('precomputes resolved connector field types onto connector node data', () => {const fieldType = single('ImageField');const templates = createTemplates(fieldType);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.tsindex 3fa684b096..32f9c72cc2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowAdapters.ts@@ -34,6 +34,12 @@ import {* facts so nodes need no workbench subscriptions.*/+/**+ * Whether node definitions are known yet. A node without a template is unknown only once they have loaded; until then+ * it is waiting, and after a failed load nothing can be said about its type.+ */+export type InvocationTemplateStatus = 'error' | 'loaded' | 'loading';+export type InvocationFlowNode = FlowNode<{canUseCache: boolean;@@ -47,6 +53,7 @@ export type InvocationFlowNode = FlowNode</** Large workflows render unselected nodes without field controls until selected. */isCompact: boolean;template: InvocationNodeTemplateView | null;+ templateStatus: InvocationTemplateStatus;},'invocation'>;@@ -200,7 +207,8 @@ export const toFlowNodes = (templates?: InvocationTemplates,index: WorkflowGraphIndex = createWorkflowGraphIndex(document.nodes, document.edges),isCompact = false,- canUseCache = false+ canUseCache = false,+ templateStatus: InvocationTemplateStatus = 'loaded'): WorkflowFlowNode[] => {const previousById = new Map(previousNodes.map((node) => [node.id, node]));const connectedByNode = getConnectedHandlesByNode(document, index);@@ -229,6 +237,7 @@ export const toFlowNodes = (previous.data.documentNode === documentNode &&previous.data.isCompact === isCompact &&previous.data.template === template &&+ previous.data.templateStatus === templateStatus &&sameNames(previous.data.connectedSourceHandles, connectedSourceHandles) &&sameNames(previous.data.connectedTargetHandles, connectedTargetHandles) &&sameNames(previous.data.exposedFieldNames, exposedFieldNames)@@ -245,6 +254,7 @@ export const toFlowNodes = (exposedFieldNames,isCompact,template,+ templateStatus,},id: documentNode.id,measured,diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.tsindex 2397e701ba..6d3d7406d2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/flowInstanceStore.ts@@ -10,6 +10,21 @@ import type { WorkflowFlowEdge, WorkflowFlowNode } from './flowAdapters';export type WorkflowFlowInstance = ReactFlowInstance<WorkflowFlowNode, WorkflowFlowEdge>;+/**+ * How far the editor toolbar reaches into the graph from the editor's left edge (its 8px inset, its 38px column, and+ * a gap). Graph content a view is fitted to, or a fresh view opens on, starts right of it, so the toolbar never+ * covers a node.+ */+export const WORKFLOW_TOOLBAR_CLEARANCE_PX = 56;++/** Every fit of the editor's graph: XYFlow's 10% padding, with the toolbar's column kept clear on the left. */+export const WORKFLOW_FIT_PADDING = {+ bottom: 0.1,+ left: `${WORKFLOW_TOOLBAR_CLEARANCE_PX}px`,+ right: 0.1,+ top: 0.1,+} as const;+let flowInstance: WorkflowFlowInstance | null = null;export const registerWorkflowFlowInstance = (instance: WorkflowFlowInstance): void => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsxindex bb99756db0..2785ad7c79 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.browser.test.tsx@@ -8,8 +8,10 @@ import { getWorkflowFieldInvalidReason } from '@features/workflow/utility';import { toaster } from '@platform/ui';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { system } from '@theme/system';+import { createInstance } from 'i18next';import { act, cloneElement, startTransition, useCallback, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider } from 'react-i18next';import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { server, userEvent } from 'vitest/browser';@@ -974,17 +976,33 @@ describe('WorkflowFieldInput board field', () => {boardDto('team', { allowed_actions: ['read', 'add_media'], my_role: 'contributor', owner_username: 'Ana' }),boardDto('viewed', { allowed_actions: ['read'], my_role: 'viewer', owner_username: 'Ben' }),];- const renderBoardField = async (boardSharing: boolean | undefined) => {- const adapter = { boardSharing } as unknown as GalleryUiAdapter;+ const i18n = createInstance();+ beforeAll(async () => {+ // Through the provider only: registering it globally would translate the raw keys later suites assert on.+ await i18n.init({+ interpolation: { escapeValue: false },+ lng: 'en',+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },+ });+ });+ /** Opens the board select and reads its options and group headings, as the gallery would label them. */+ const renderBoardField = async (+ boardSharing: boolean | undefined,+ galleryHost: Partial<GalleryUiAdapter> = {},+ onChange: (value: unknown) => void = vi.fn()+ ) => {+ const adapter = { boardSharing, ...galleryHost } as unknown as GalleryUiAdapter;await act(() => {root.render(- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <GalleryUiProvider adapter={adapter}>- <WorkflowFieldInput template={BOARD_TEMPLATE} value="auto" onChange={vi.fn()} />- </GalleryUiProvider>- </QueryClientProvider>- </ChakraProvider>+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <QueryClientProvider client={queryClient}>+ <GalleryUiProvider adapter={adapter}>+ <WorkflowFieldInput template={BOARD_TEMPLATE} value="auto" onChange={onChange} />+ </GalleryUiProvider>+ </QueryClientProvider>+ </ChakraProvider>+ </I18nextProvider>);});const trigger = host.querySelector<HTMLElement>('[data-scope="select"][data-part="trigger"]');@@ -995,22 +1013,89 @@ describe('WorkflowFieldInput board field', () => {expect(queryClient.getQueryCache().findAll({ queryKey: ['gallery', 'boards'] })[0]?.state.status).toBe('success');});await act(() => userEvent.click(trigger));+ const texts = (part: string) =>+ Array.from(document.querySelectorAll<HTMLElement>(`[data-scope="select"][data-part="${part}"]`))+ .map((element) => element.textContent?.trim())+ .filter(Boolean);- return Array.from(document.querySelectorAll<HTMLElement>('[data-scope="select"][data-part="item"]')).map((item) =>- item.textContent?.trim()- );+ return { groups: texts('item-group-label'), items: texts('item') };};beforeEach(() => {workflowApiMock.apiFetchJson.mockResolvedValue(listing);});- it("offers the boards the caller may add to from the gallery's listing, naming other people's owners", async () => {- expect(await renderBoardField(true)).toEqual(['Auto', 'None', 'mine', 'team · Ana']);+ afterEach(() => {+ delete galleryValues.autoAddBoardId;+ delete galleryValues.projectBoardId;+ delete galleryValues.selectedBoardId;+ });++ it("offers the boards the caller may add to under the gallery's own groups", async () => {+ expect(await renderBoardField(true)).toEqual({+ groups: ['Library', 'Shared with me'],+ items: ['Auto (Uncategorized)', 'Uncategorized', 'mine', 'team'],+ });});it('folds every board into the caller’s own on a host without board sharing', async () => {- expect(await renderBoardField(false)).toEqual(['Auto', 'None', 'mine', 'team']);+ expect(await renderBoardField(false)).toEqual({+ groups: ['Library'],+ items: ['Auto (Uncategorized)', 'Uncategorized', 'mine', 'team'],+ });+ });++ it('names the board Auto resolves to, with the gallery’s label for the project inbox', async () => {+ const project = { projectId: 'project-1', projectName: 'Portraits', projects: [] };+ workflowApiMock.apiFetchJson.mockResolvedValue([+ boardDto('inbox', { board_name: 'Portraits', is_inbox: true, project_id: 'project-1' }),+ ...listing,+ ]);+ galleryValues.projectBoardId = 'inbox';++ expect(await renderBoardField(true, project)).toEqual({+ groups: ['Portraits', 'Library', 'Shared with me'],+ items: ['Auto (Inbox)', 'Uncategorized', 'Inbox', 'mine', 'team'],+ });++ // Close the first menu completely, so the second read sees only the reopened one.+ await act(() => userEvent.keyboard('{Escape}'));+ await vi.waitFor(() => expect(document.querySelector('[data-scope="select"][data-part="item"]')).toBeNull());+ galleryValues.autoAddBoardId = 'mine';+ expect((await renderBoardField(true, project)).items[0]).toBe('Auto (mine)');+ });++ it('names an archived auto-add board as compilation resolves it, not the inbox', async () => {+ const archived = boardDto('kept', { archived: true, board_name: 'Kept results' });+ workflowApiMock.apiFetchJson.mockImplementation((url: string) =>+ Promise.resolve(url.includes('include_archived=true') ? [...listing, archived] : listing)+ );+ galleryValues.projectBoardId = 'mine';+ galleryValues.autoAddBoardId = 'kept';++ await renderBoardField(true);++ // Archived boards stay out of the choices; Auto still sends results to the one chosen on purpose.+ await vi.waitFor(() =>+ expect(document.querySelector('[data-scope="select"][data-part="item"]')?.textContent?.trim()).toBe(+ 'Auto (Kept results)'+ )+ );+ expect(+ [...document.querySelectorAll('[data-scope="select"][data-part="item"]')].map((item) => item.textContent?.trim())+ ).not.toContain('Kept results');+ });++ it('writes a picked board as its id', async () => {+ const onChange = vi.fn();++ await renderBoardField(true, {}, onChange);+ const mine = Array.from(document.querySelectorAll<HTMLElement>('[data-scope="select"][data-part="item"]')).find(+ (item) => item.textContent?.trim() === 'mine'+ )!;+ await act(() => userEvent.click(mine));++ expect(onChange).toHaveBeenCalledWith({ board_id: 'mine' });});it('sends an upload to the project inbox when the selected board is not in the live listing', async () => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex 9deb042755..df585f98de 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -30,8 +30,10 @@ import {} from '@features/gallery';import {canOnBoard,+ getGalleryAutoAddBoardId,+ getGalleryBoardDestinationGroups,+ getGalleryBoardLabel,getSelectedGalleryImageFromValues,- isOwnGalleryBoard,toGalleryItemKey,} from '@features/gallery/contracts';import { FindInGalleryThumbnailButton } from '@features/gallery/mediaSlot';@@ -40,9 +42,10 @@ import {canAddToCachedGalleryBoard,ensureGalleryBoardDestinations,galleryBoardsOptions,+ getCachedGalleryBoard,invalidateGallery,} from '@features/gallery/queries';-import { useHostGalleryBoards } from '@features/gallery/react';+import { useHostGalleryBoards, useOptionalGalleryHostProjectContext } from '@features/gallery/react';import { galleryImageUrls, galleryVideoUrls } from '@features/gallery/utility';import { DEFAULT_LORA_WEIGHT_CONFIG, sanitizeBatchCount, SCHEDULER_OPTIONS } from '@features/generation/settings';import { isInvocationNode } from '@features/workflow/contracts';@@ -501,51 +504,128 @@ const SchedulerInput = ({ id, invalid, onChange, template, value }: WorkflowFiel/>);+interface BoardOption {+ /** The gallery destination group the board lists under; empty for the fixed Auto and Uncategorized choices. */+ group: string;+ label: string;+ value: string;+}++const FIXED_BOARD_GROUP = '';+const BoardInput = ({ id, invalid, onChange, template, value }: WorkflowFieldInputProps) => {+ const { t } = useTranslation();// The gallery's own listing, so grants, revocations and new boards reach the field as they reach the panel.const { data } = useQuery(galleryBoardsOptions());const listedBoards = useHostGalleryBoards(data);+ const host = useOptionalGalleryHostProjectContext();// Only boards a node's results may land on: someone else's board the caller can only view would refuse them after// the run.const boards = useMemo(() => listedBoards.filter((board) => board.kind === 'board' && canOnBoard(board, 'add_media')),[listedBoards]);-+ const queryClient = useQueryClient();+ // The auto-add board as chosen, before any refusal: one the live listing lacks may be archived, which compilation+ // still accepts, so its label waits on the listing of archived boards too (shared, and read only then).+ const chosenAutoBoardId = useWorkflowProjectSelector((project) =>+ getGalleryAutoAddBoardId(project.galleryValues, () => true)+ );+ const needsArchivedListing =+ data !== undefined &&+ chosenAutoBoardId !== null &&+ chosenAutoBoardId !== 'none' &&+ !listedBoards.some((board) => board.id === chosenAutoBoardId);+ useQuery({ ...galleryBoardsOptions({ includeArchived: true }), enabled: needsArchivedListing });+ // Compilation sends Auto to the gallery's auto-add board, deciding from the cached listings; the label names the+ // board the same decision resolves to now. Either listing arriving re-renders the field, which reads it again.+ const autoBoardId = useWorkflowProjectSelector((project) =>+ getGalleryAutoAddBoardId(project.galleryValues, (boardId) => canAddToCachedGalleryBoard(boardId, queryClient))+ );+ const translate = useCallback((key: string) => t(key), [t]);+ const groups = useMemo(+ () =>+ host+ ? getGalleryBoardDestinationGroups({+ boards,+ projectId: host.projectId ?? null,+ projectName: host.projectName,+ projectNames: new Map(host.projects?.map((project) => [project.id, project.name])),+ t: translate,+ })+ : [{ boards, id: 'boards', label: '' }],+ [boards, host, translate]+ );+ const autoBoard =+ autoBoardId === null+ ? undefined+ : (listedBoards.find((board) => board.id === autoBoardId) ?? getCachedGalleryBoard(autoBoardId, queryClient));+ const autoBoardLabel =+ autoBoardId === null || autoBoardId === 'none'+ ? t('widgets.gallery.uncategorized')+ : // The listing has not arrived yet.+ autoBoard+ ? getGalleryBoardLabel(autoBoard, translate)+ : '…';+ const options = useMemo<BoardOption[]>(+ () => [+ { group: FIXED_BOARD_GROUP, label: t('nodes.boardAuto', { board: autoBoardLabel }), value: 'auto' },+ { group: FIXED_BOARD_GROUP, label: t('widgets.gallery.uncategorized'), value: 'none' },+ ...groups.flatMap((group) =>+ // Without a gallery host there are no group headings; boards list after the fixed choices.+ group.boards.map((board) => ({+ group: host ? group.id : FIXED_BOARD_GROUP,+ label: getGalleryBoardLabel(board, translate),+ value: board.id,+ }))+ ),+ ],+ [autoBoardLabel, groups, host, t, translate]+ );+ const groupLabels = useMemo(() => new Map(groups.map((group) => [group.id, group.label])), [groups]);+ const renderGroupLabel = useCallback((group: string) => groupLabels.get(group) ?? null, [groupLabels]);+ const collection = useMemo(() => createListCollection({ items: options }), [options]);const selected =value === 'auto' || value === 'none'? value: typeof (value as { board_id?: unknown } | null)?.board_id === 'string'? (value as { board_id: string }).board_id: 'auto';- const options = useMemo(- () => [- { label: 'Auto', value: 'auto' },- { label: 'None', value: 'none' },- ...boards.map((board) => ({- label: isOwnGalleryBoard(board) || !board.ownerName ? board.name : `${board.name} · ${board.ownerName}`,- value: board.id,- })),- ],- [boards]+ const selectedValue = useMemo(+ () => (options.some((option) => option.value === selected) ? [selected] : []),+ [options, selected]);+ const selectIds = useMemo(() => (id ? { trigger: `${id}-select` } : undefined), [id]);const onBoardChange = useCallback(- (next: string) => onChange(next === 'auto' || next === 'none' ? next : { board_id: next }),+ ({ value: next }: { value: string[] }) => {+ const nextValue = next[0];++ if (nextValue !== undefined) {+ onChange(nextValue === 'auto' || nextValue === 'none' ? nextValue : { board_id: nextValue });+ }+ },[onChange]);return (- <SelectInput- id={id}+ <Select+ aria-label={template.title}+ className="nodrag"+ collection={collection}+ groupBy={getBoardOptionGroup}+ ids={selectIds}invalid={invalid}- options={options}- title={template.title}- value={selected}- onChange={onBoardChange}+ renderGroupLabel={renderGroupLabel}+ value={selectedValue}+ valueTextProps={SELECT_VALUE_TEXT_PROPS}+ w="full"+ onValueChange={onBoardChange}/>);};+const getBoardOptionGroup = (option: BoardOption): string => option.group;+const MEDIA_FIELD_CONFIG = {image: {fileAccept: 'image/*',diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsxindex a06fc909d1..a7f335a096 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx@@ -1,6 +1,6 @@import type { ProjectWorkflowEntry } from '@features/workflow/core/types';-import { Badge, Box, Flex, HStack, Icon, Image, Menu, Portal, Stack, Text } from '@chakra-ui/react';+import { Badge, Box, Flex, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';import { MenuActionItem } from '@features/workflow/ui/MenuActionItem';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';@@ -46,6 +46,7 @@ import {useWorkflowLibraryMissingCounts,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@@ -53,7 +54,6 @@ import {*/const DETAIL_RAIL_WIDTH = '18rem';-const THUMBNAIL_ASPECT_RATIO = 3 / 2;export interface ProjectWorkflowsViewProps {contextMenuPoint: WorkflowCardMenuAnchor | null;@@ -388,16 +388,9 @@ const ProjectWorkflowDetailPanel = ({<Scrollable flex="1" label={name} minH="0"><Stack gap="2" minW="0" p="2.5"><Stack gap="1" minW="0">- <Box aspectRatio={THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" rounded="md" w="full">+ <Box aspectRatio={WORKFLOW_THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" rounded="md" w="full">{showThumbnail ? (- <Image- alt=""- h="full"- objectFit="cover"- src={thumbnailUrl ?? undefined}- w="full"- onError={handleThumbnailError}- />+ <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} />diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsxindex d6cc71de5e..99307fc6ed 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx@@ -1,6 +1,6 @@import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';-import { Badge, Box, Flex, HStack, Icon, Image, Skeleton, Stack, Text } from '@chakra-ui/react';+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';@@ -9,6 +9,8 @@ import { EllipsisIcon, ImageOffIcon } from 'lucide-react';import { useCallback, useState, type MouseEvent } from 'react';import { useTranslation } from 'react-i18next';+import { WORKFLOW_THUMBNAIL_ASPECT_RATIO, 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.@@ -18,7 +20,6 @@ const CARD_HOVER = { bg: 'bg.muted', borderColor: 'border.emphasized' } as constconst 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';-const THUMBNAIL_ASPECT_RATIO = 3 / 2;/** The card's DOM id, which the rail's context menu names as its trigger so it nests under the dialog's layer. */export const getWorkflowLibraryCardId = (workflowId: string): string => `workflow-library-card-${workflowId}`;@@ -152,16 +153,9 @@ export const WorkflowLibraryCard = ({onContextMenu={handleContextMenu}onDoubleClick={handleOpen}>- <Box aspectRatio={THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" w="full">+ <Box aspectRatio={WORKFLOW_THUMBNAIL_ASPECT_RATIO} bg="bg.muted" overflow="hidden" w="full">{showThumbnail ? (- <Image- alt=""- h="full"- objectFit="cover"- src={item.thumbnail_url ?? undefined}- w="full"- onError={handleThumbnailError}- />+ <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} />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 9f49a275d9..aeb2001a0b 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@@ -13,6 +13,7 @@ import type {} from '@features/workflow/data/libraryBrowseStore';import type {WorkflowGraphPreviewPort,+ WorkflowPreferences,WorkflowReadPort,WorkflowUiAdapter,} from '@features/workflow/ui/WorkflowUiContext';@@ -31,8 +32,8 @@ import { accountLifecycle } from '@platform/state/accountLifecycle';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 { afterEach, 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';@@ -124,7 +125,7 @@ vi.mock('@features/workflow/data/libraryBrowseStore', async () => {const store = createExternalStore<WorkflowLibraryBrowseSnapshot>({entries: [],error: null,- filter: { category: 'user', search: '', tag: null },+ filter: { category: 'user', search: '', sort: 'updated', tag: null },page: 0,pages: 0,status: 'idle',@@ -223,10 +224,18 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.sampleOutput': 'Sample output','workflowLibrary.saveToLibraryWithEllipsis': 'Save to library…','workflowLibrary.searchPlaceholder': 'Search names, tags, or descriptions',+ 'workflowLibrary.sortCreated': 'Date created',+ 'workflowLibrary.sortLabel': 'Sort by',+ 'workflowLibrary.sortName': 'Name',+ 'workflowLibrary.sortOpened': 'Last opened',+ 'workflowLibrary.sortUpdated': 'Last updated','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.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',@@ -322,7 +331,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: '', tag: null },+ filter: { category: 'user', search: '', sort: 'updated', tag: null },page: 0,pages: 2,status: 'loaded',@@ -402,8 +411,16 @@ 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;+const preferences = createMutablePort<WorkflowPreferences>(LIBRARY_PREFERENCES as unknown as WorkflowPreferences);+const setLibraryPreferences = vi.fn((patch: Partial<WorkflowPreferences>) =>+ preferences.setSnapshot({ ...preferences.port.getSnapshot(), ...patch })+);const UI_ADAPTER = {commands: COMMANDS,+ preferences: preferences.port,+ setLibraryPreferences,getProjectGraph: () => project.port.getSnapshot().projectGraph,notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },openAddModels: vi.fn(),@@ -508,6 +525,14 @@ describe('WorkflowLibraryDialog', () => {});};+ /** The dialog sizes itself to the window, so layout tests set it; the runner's own size returns afterwards. */+ const resizeViewport = async (width: number, height: number) => {+ const previous = { height: window.innerHeight, width: window.innerWidth };++ await page.viewport(width, height);+ onTestFinished(() => page.viewport(previous.width, previous.height));+ };+const gridViewport = () => document.querySelector<HTMLElement>('[role="region"][aria-label="Workflows"]');/**@@ -549,6 +574,8 @@ describe('WorkflowLibraryDialog', () => {command.mockClear();}project.setSnapshot(projectSnapshot(PROJECT_WORKFLOWS));+ preferences.setSnapshot(LIBRARY_PREFERENCES as unknown as WorkflowPreferences);+ setLibraryPreferences.mockClear();// The dialog's tab and selection live in the session store; start every test from the account's clean slate.accountLifecycle.invalidate();// These are the template tabs' behaviours; the project view has its own suite below.@@ -611,6 +638,53 @@ 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 () => {+ preferences.setSnapshot({+ ...LIBRARY_PREFERENCES,+ workflowLibrarySort: 'opened',+ } as unknown as WorkflowPreferences);+ 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 act(() => userEvent.click(sortTrigger()!));+ const nameOption = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(+ (option) => option.textContent === 'Name'+ );+ await act(() => userEvent.click(nameOption!));++ expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibrarySort: 'name' });+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ sort: 'name' });++ // 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('fills thumbnails by default and letterboxes them once Fit is chosen', 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"]'+ );++ expect(getComputedStyle(thumbnail()).objectFit).toBe('cover');+ expect(fitOption()?.checked).toBe(false);++ await act(() => userEvent.click(fitOption()!.closest('label')!));++ expect(setLibraryPreferences).toHaveBeenCalledWith({ workflowLibraryThumbnailFit: 'contain' });+ expect(fitOption()?.checked).toBe(true);+ expect(getComputedStyle(thumbnail()).objectFit).toBe('contain');+ });+it('switches to the bundled defaults once when the account has no workflows of its own', async () => {await openWith(withSnapshot({ userTotal: 0 }));await wait(0);@@ -628,7 +702,7 @@ describe('WorkflowLibraryDialog', () => {});it('resets the tag when the category segment changes', async () => {- await openWith(withSnapshot({ filter: { category: 'user', search: '', tag: 'portrait' } }));+ await openWith(withSnapshot({ filter: { category: 'user', search: '', sort: 'updated', tag: 'portrait' } }));await clickSegment('default');@@ -733,7 +807,7 @@ describe('WorkflowLibraryDialog', () => {await openWith({entries: [],error: null,- filter: { category: 'user', search: '', tag: null },+ filter: { category: 'user', search: '', sort: 'updated', tag: null },page: 0,pages: 0,status: 'idle',@@ -1045,27 +1119,79 @@ describe('WorkflowLibraryDialog', () => {expect(document.querySelector('[data-preview-dialog]')).toBeNull();});- it('sits the close control on the header row, not floating over the tag chips', async () => {+ it('sits the close control at the end of the tab row, not floating over the tag chips', 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();- // Same row container as the title/search/tab cluster…- expect(segments?.parentElement?.parentElement?.contains(close as Node)).toBe(true);- // …and on its baseline rather than the dialog's absolute top corner.- const closeBox = close?.getBoundingClientRect();- const segmentBox = segments?.getBoundingClientRect();- const closeCenter = (closeBox?.top ?? 0) + (closeBox?.height ?? 0) / 2;-- expect(closeCenter).toBeGreaterThanOrEqual(segmentBox?.top ?? 0);- expect(closeCenter).toBeLessThanOrEqual(segmentBox?.bottom ?? 0);- // And it comes after the segment control, at the end of the row.- expect(closeBox?.left ?? 0).toBeGreaterThanOrEqual(segmentBox?.right ?? 0);+ // 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', 'project'] as const)(+ 'keeps the %s header inside a 320px-wide dialog, with Close on the title row and every tab label whole',+ async (tab) => {+ 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 contentBox = content.getBoundingClientRect();+ 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(['This project', 'Browse', 'Yours']);+ expect(header).not.toContain(null);++ 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);+ }+ for (const label of tabs.map((element) => element.firstElementChild as HTMLElement)) {+ expect(label.scrollWidth, label.textContent ?? '').toBeLessThanOrEqual(label.clientWidth);+ }++ // 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 real pointer click reaches the other tab on its own row.+ const target = tabs.find((element) => element.textContent === (tab === 'user' ? 'This project' : 'Yours'))!;+ await act(() => userEvent.click(target));+ expect(target.getAttribute('aria-selected')).toBe('true');+ }+ );+it('wraps a long workflow name in full instead of scrolling the rail sideways', async () => {await openWith(withSnapshot({ entries: [LONG_NAMED, PORTRAIT] }));diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex 3afec94e57..cbe90a3031 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -1,9 +1,24 @@import type { ProjectWorkflowEntry } from '@features/workflow/core/types';-import type { WorkflowLibraryBrowseSnapshot, WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';+import type {+ WorkflowLibraryBrowseSnapshot,+ WorkflowLibraryEntry,+ 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 { HStack, Input, Portal, Spinner, Stack, Text } from '@chakra-ui/react';+import {+ Box,+ createListCollection,+ HStack,+ Input,+ Portal,+ Spinner,+ Stack,+ type SystemStyleObject,+ Text,+} from '@chakra-ui/react';import {ensureWorkflowLibraryBrowseLoaded,getWorkflowLibraryBrowseSnapshot,@@ -11,7 +26,11 @@ import {useWorkflowLibraryBrowseSelector,} from '@features/workflow/data/libraryBrowseStore';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';-import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import {+ useWorkflowPreferencesSelector,+ useWorkflowProjectSelector,+ useWorkflowUi,+} from '@features/workflow/ui/WorkflowUiContext';import {requestLibraryCopyChoice,setWorkflowLibrarySelection,@@ -22,6 +41,8 @@ import {import { useMountEffect } from '@platform/react/useMountEffect';import { CloseButton, SegmentTabs, segmentTabsPanelId, segmentTabsTabId } from '@platform/ui';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 { useTranslation } from 'react-i18next';@@ -38,6 +59,7 @@ import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';import { useWorkflowLibraryMissingCounts } from './WorkflowRequirementsList';+import { WorkflowThumbnailFitContext } from './workflowThumbnail';const SEARCH_DEBOUNCE_MS = 300;@@ -47,6 +69,45 @@ const TAB_ITEMS: ReadonlyArray<{ labelKey: string; value: WorkflowLibraryTab }>{ labelKey: 'workflowLibrary.yours', value: 'user' },];+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' },+];++const THUMBNAIL_FIT_ITEMS: ReadonlyArray<{ labelKey: string; value: WorkflowThumbnailFit }> = [+ { labelKey: 'workflowLibrary.thumbnailFitCover', value: 'cover' },+ { labelKey: 'workflowLibrary.thumbnailFitContain', value: 'contain' },+];++const SORT_SELECT_WIDTH = '9.5rem';++/**+ * 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 HEADER_FILTERS_CSS: SystemStyleObject = {+ [NARROW_HEADER]: { flexWrap: 'wrap', justifyContent: 'flex-end', rowGap: '2' },+};+// 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) => ({category: snapshot.filter.category,@@ -66,9 +127,9 @@ const selectLibraryNavigation = (snapshot: ReturnType<typeof workflowUiStore.get* 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.*/-const WorkflowLibraryBrowseSession = () => {+const WorkflowLibraryBrowseSession = ({ sort }: { sort: WorkflowLibrarySort }) => {useMountEffect(() => {- void ensureWorkflowLibraryBrowseLoaded().then(() => {+ void ensureWorkflowLibraryBrowseLoaded(sort).then(() => {const { filter, userTotal } = getWorkflowLibraryBrowseSnapshot();if (userTotal === 0 && filter.category === 'user' && !filter.search) {@@ -99,6 +160,9 @@ export const WorkflowLibraryDialog = ({const projectId = useWorkflowProjectSelector((project) => project.id);const projectWorkflows = useWorkflowProjectSelector((project) => project.workflows);const templatesSnapshot = useInvocationTemplatesSnapshot();+ const { setLibraryPreferences } = useWorkflowUi();+ const sort = useWorkflowPreferencesSelector((preferences) => preferences.workflowLibrarySort);+ const thumbnailFit = useWorkflowPreferencesSelector((preferences) => preferences.workflowLibraryThumbnailFit);const [searchInput, setSearchInput] = useState('');const [selectedWorkflowId, setSelectedWorkflowId] = useState<string | null>(null);// Clear pending preview entries on every library-close path because the persistent shell otherwise resurrects@@ -226,6 +290,31 @@ export const WorkflowLibraryDialog = ({);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;++ if (next) {+ setLibraryPreferences({ workflowLibrarySort: next });+ setWorkflowLibraryBrowseFilter({ sort: next });+ }+ },+ [setLibraryPreferences]+ );+ const thumbnailFitOptions = useMemo(+ () => THUMBNAIL_FIT_ITEMS.map((item) => ({ label: t(item.labelKey), value: item.value })),+ [t]+ );+ const handleThumbnailFitChange = useCallback(+ (value: string) =>+ setLibraryPreferences({ workflowLibraryThumbnailFit: value === 'contain' ? 'contain' : 'cover' }),+ [setLibraryPreferences]+ );// The first copy is added directly; with one already in the project, the host asks what opening should do.const handleOpenItem = useCallback(@@ -330,17 +419,19 @@ export const WorkflowLibraryDialog = ({</Stack>) : null}<Dialog.Header>- <Stack gap="2" minW="0" w="full">- <HStack gap="3" minW="0">- <Dialog.Title flexShrink={0}>{t('workflowLibrary.title')}</Dialog.Title>+ <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" flex="1" fontSize="md" minW="0" truncate>+ <Text color="fg.subtle" fontSize="md" gridArea="lead" minW="0" truncate>{t('workflowLibrary.thisProjectHint')}</Text>) : (<Inputaria-label={t('workflowLibrary.searchPlaceholder')}- flex="1"+ gridArea="lead"minW="0"placeholder={t('workflowLibrary.searchPlaceholder')}type="search"@@ -348,28 +439,55 @@ export const WorkflowLibraryDialog = ({onChange={handleSearchChange}/>)}- <SegmentTabs- activeId={activeTab}- ariaLabel={t('workflowLibrary.title')}- idBase={tabsIdBase}- isCompact- tabs={tabItems}- onSelect={handleTabChange}- />-+ <Box gridArea="tabs" minW="0">+ <SegmentTabs+ activeId={activeTab}+ ariaLabel={t('workflowLibrary.title')}+ idBase={tabsIdBase}+ isCompact+ tabs={tabItems}+ onSelect={handleTabChange}+ />+ </Box><Dialog.CloseTrigger asChild><CloseButtondisabled={isLoadPending}- flexShrink={0}+ gridArea="close"insetEnd="auto"position="static"top="auto"/></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}+ />+ ) : null}+ <SegmentedControl+ ariaLabel={t('workflowLibrary.thumbnailFit')}+ flexShrink={0}+ isFullWidth={false}+ options={thumbnailFitOptions}+ size="sm"+ value={thumbnailFit}+ onChange={handleThumbnailFitChange}+ /></HStack>- {isProjectTab ? null : (- <WorkflowLibraryTagChips selectedTag={tag} tagCounts={tagCounts} onSelect={handleTagSelect} />- )}</Stack></Dialog.Header><Dialog.Body@@ -383,46 +501,48 @@ export const WorkflowLibraryDialog = ({minH="0"role="tabpanel">- {isProjectTab ? (- <ProjectWorkflowsView- contextMenuPoint={contextMenuPoint}- contextMenuTriggerId={contextMenuTriggerId}- selectedWorkflowId={projectSelectionId}- onClose={closeDialog}- onContextMenu={handleCardContextMenu}- onContextMenuClose={closeContextMenu}- onPreview={handleProjectPreviewRequest}- onSelect={handleProjectSelect}- />- ) : (- <>- <WorkflowLibraryGrid- entries={entries}- error={error}- missingCounts={missingCounts}- openMenuAnchor={contextMenuPoint}- selectedWorkflowId={activeWorkflowId}- status={status}- onContextMenu={handleCardContextMenu}- onOpen={handleOpenWorkflow}- onSelect={setSelectedWorkflowId}- />- <WorkflowLibraryDetailPanel+ <WorkflowThumbnailFitContext value={thumbnailFit}>+ {isProjectTab ? (+ <ProjectWorkflowsViewcontextMenuPoint={contextMenuPoint}contextMenuTriggerId={contextMenuTriggerId}- entry={activeEntry}- projectWorkflows={projectWorkflows}+ selectedWorkflowId={projectSelectionId}onClose={closeDialog}+ onContextMenu={handleCardContextMenu}onContextMenuClose={closeContextMenu}- onDeleted={handleDeleted}- onDuplicated={setSelectedWorkflowId}- onOpen={handleOpenItem}- onPreview={handlePreviewRequest}+ onPreview={handleProjectPreviewRequest}+ onSelect={handleProjectSelect}/>- </>- )}+ ) : (+ <>+ <WorkflowLibraryGrid+ entries={entries}+ error={error}+ missingCounts={missingCounts}+ openMenuAnchor={contextMenuPoint}+ selectedWorkflowId={activeWorkflowId}+ status={status}+ onContextMenu={handleCardContextMenu}+ onOpen={handleOpenWorkflow}+ onSelect={setSelectedWorkflowId}+ />+ <WorkflowLibraryDetailPanel+ contextMenuPoint={contextMenuPoint}+ contextMenuTriggerId={contextMenuTriggerId}+ entry={activeEntry}+ projectWorkflows={projectWorkflows}+ onClose={closeDialog}+ onContextMenuClose={closeContextMenu}+ onDeleted={handleDeleted}+ onDuplicated={setSelectedWorkflowId}+ onOpen={handleOpenItem}+ onPreview={handlePreviewRequest}+ />+ </>+ )}+ </WorkflowThumbnailFitContext></Dialog.Body>- {isOpen && !isProjectTab ? <WorkflowLibraryBrowseSession /> : null}+ {isOpen && !isProjectTab ? <WorkflowLibraryBrowseSession sort={sort} /> : null}</Dialog.Content></Dialog.Positioner></Portal>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsxindex d366f1d25a..05502faef6 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryThumbnail.tsx@@ -3,7 +3,7 @@ import type { ProjectGraphState, XYPosition } from '@features/workflow/contractsimport type { WorkflowLibraryListItem } from '@features/workflow/queries';import type { WorkflowPreviewGraph } from '@features/workflow/ui/contracts';-import { Box, Flex, HStack, Icon, Image, Spinner, Stack, Text, type SystemStyleObject } from '@chakra-ui/react';+import { Box, Flex, HStack, Icon, Spinner, Stack, Text, type SystemStyleObject } from '@chakra-ui/react';import { GalleryPickerPopover } from '@features/gallery/picker';import { localizeForLoopValidationReason } from '@features/workflow/core/forLoops';import {@@ -29,13 +29,13 @@ import { useTranslation } from 'react-i18next';import { buildLibraryGraphPreviewSource, DeferredGraphPreviewSnapshot, loadGraphPreview } from './libraryPreviewSource';import { formatRelativeTime } from './relativeTime';+import { WORKFLOW_THUMBNAIL_ASPECT_RATIO, WorkflowThumbnailImage } from './workflowThumbnail';-const THUMBNAIL_ASPECT_RATIO = 3 / 2;const IMAGE_ONLY = ['image'] as const;/** Busy controls stay focusable (`aria-disabled`), so the focus the picker returns to survives the action. */const preventClick = (event: MouseEvent) => event.preventDefault();const WELL_CSS: SystemStyleObject = {- aspectRatio: THUMBNAIL_ASPECT_RATIO,+ aspectRatio: WORKFLOW_THUMBNAIL_ASPECT_RATIO,bg: 'bg.muted',overflow: 'hidden',position: 'relative',@@ -235,14 +235,7 @@ export const WorkflowLibraryThumbnail = ({const wellContent = (<>{showThumbnail ? (- <Image- alt=""- h="full"- objectFit="cover"- src={item.thumbnail_url ?? undefined}- w="full"- onError={handleThumbnailError}- />+ <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} />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 4dc9e0a131..bbdb91667c 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@@ -59,6 +59,10 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.saveAsNew': 'Save as new','workflowLibrary.saveFailed': 'Failed to save workflow','workflowLibrary.saveToLibraryConfirm': 'Save',+ 'workflowLibrary.saveToLibraryRelink':+ 'Update library template will then write to the new template instead of "{{template}}".',+ 'workflowLibrary.saveToLibraryRelinkUnnamed':+ 'Update library template will then write to the new template instead of the one this workflow is linked to now.','workflowLibrary.saveToLibraryExplanation':"Creates a new library template from this workflow. Its current input values become the template's defaults.",'workflowLibrary.saveToLibraryTitle': 'Save to library',@@ -304,6 +308,29 @@ describe('WorkflowPublicationHost', () => {expect(saveDialog()).toBeNull();});+ it('says which template Update stops writing to when a linked workflow is saved as new, and only then', async () => {+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ name: 'Library alpha' }));+ const relinkNotice = () => saveDialog()?.querySelector('[data-save-to-library-relink]')?.textContent ?? null;++ await renderHost([LINKED]);+ await request('save-as-new');+ await flush();+ expect(relinkNotice()).toBe(+ 'Update library template will then write to the new template instead of "Library alpha".'+ );++ for (const entry of [UNLINKED, BUNDLED]) {+ await act(() => root.unmount());+ root = createRoot(host);+ accountLifecycle.invalidate();+ await renderHost([entry]);+ await request('save-as-new');+ await flush();+ expect(saveDialog()).not.toBeNull();+ expect(relinkNotice()).toBeNull();+ }+ });+it('keeps a rename made while the save was in flight instead of adopting the template name', async () => {const pending = deferred<WorkflowRecordDTO>();api.createLibraryWorkflowRecord.mockReturnValueOnce(pending.promise);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsxindex 187b029bb0..731f4c339a 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsx@@ -403,10 +403,27 @@ export const WorkflowPublicationHost = () => {<Text color="fg.muted" fontSize="md">{t('workflowLibrary.updateConfirmCallers')}</Text>+ <Text color="fg.muted" fontSize="md">+ {t('workflowLibrary.updateConfirmIrreversible')}+ </Text></Stack>),[confirmTemplateName, t]);+ // Saving as new re-links a workflow that already updates a template of the account's; the dialog says which.+ const relinkSource =+ activeStage.kind === 'save-as-new' && isUpdatableSource(stageEntry?.source) ? stageEntry.source : null;+ const relinkTemplateName = useQuery({+ ...savedWorkflowDetailQueryOptions(relinkSource?.libraryWorkflowId ?? ''),+ enabled: relinkSource !== null,+ select: (record) => record.name,+ }).data;+ const relinkNotice =+ relinkSource === null+ ? null+ : relinkTemplateName+ ? t('workflowLibrary.saveToLibraryRelink', { template: relinkTemplateName })+ : t('workflowLibrary.saveToLibraryRelinkUnnamed');const conflictOptions = useMemo(() => [{ label: t('workflowLibrary.saveAsNew'), onSelect: switchToSaveAsNew, value: 'save-as-new' },@@ -431,6 +448,7 @@ export const WorkflowPublicationHost = () => {<SaveToLibraryDialoginitialName={stageEntry?.document.name ?? ''}isOpen={activeStage.kind === 'save-as-new'}+ relinkNotice={relinkNotice}isPending={isBusy}onClose={close}onSubmit={handleSaveAsNew}@@ -680,19 +698,25 @@ const ChoiceButton = ({</Button>);-/** Names the new template. The explanation is the contract: current input values become the template's defaults. */+/**+ * Names the new template. The explanation is the contract: current input values become the template's defaults, and+ * the workflow then links to the new template under its name.+ */export const SaveToLibraryDialog = ({initialName,isOpen,isPending,onClose,onSubmit,+ relinkNotice,}: {initialName: string;isOpen: boolean;isPending: boolean;onClose: () => void;onSubmit: (name: string) => Promise<void> | void;+ /** For a workflow already linked to another writable template: where Update library template stops writing. */+ relinkNotice: string | null;}) => {const { t } = useTranslation();@@ -733,6 +757,11 @@ export const SaveToLibraryDialog = ({<Text color="fg.muted" fontSize="md">{t('workflowLibrary.saveToLibraryExplanation')}</Text>+ {relinkNotice ? (+ <Text color="fg.muted" data-save-to-library-relink fontSize="md">+ {relinkNotice}+ </Text>+ ) : null}</Stack></Dialog.Body><Dialog.Footer>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowThumbnail.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowThumbnail.tsxnew file mode 100644index 0000000000..58655a4b7f--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowThumbnail.tsx@@ -0,0 +1,20 @@+import type { WorkflowThumbnailFit } from '@features/workflow/ui/WorkflowUiContext';++import { Image } from '@chakra-ui/react';+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;++/**+ * 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');++/** 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);++ return <Image alt="" h="full" objectFit={fit} src={src ?? undefined} w="full" onError={onError} />;+};diff --git a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsxindex c9d17e26cf..f81b2ba58d 100644--- a/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/GalleryMaintenance.browser.test.tsx@@ -15,7 +15,7 @@ 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 { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { commands, userEvent } from 'vitest/browser';import type * as SettingsStoreModule from './store';@@ -180,6 +180,12 @@ describe('gallery maintenance in Data & workspace settings', () => {let root: Root;let queryClient: QueryClient;+ // The settings page lazy-loads the maintenance section; load it up front so the first poll is not timing a cold+ // chunk on a loaded machine.+ beforeAll(async () => {+ await import('./GalleryMaintenance');+ });+const renderSettings = async () => {await act(() =>root.render(diff --git a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts b/invokeai/frontend/webv2/src/workbench/settings/contracts.tsindex e9081b2859..e1a0418496 100644--- a/invokeai/frontend/webv2/src/workbench/settings/contracts.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/contracts.ts@@ -9,6 +9,12 @@ 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';++/** How workflow thumbnails fill their 3:2 box: cropped to fill it, or letterboxed to fit whole. */+export type WorkflowLibraryThumbnailFit = 'cover' | 'contain';+/*** Export document generation settings with the project; personal editor choices belong in {@link* WorkbenchPreferences} so imports cannot overwrite them.@@ -101,6 +107,10 @@ export interface WorkbenchPreferences {workflowEdgeStyle: 'curved' | 'square';/** Keep connections of a selected node beneath nodes instead of raising them over node controls. */workflowEdgesBehindNodes: boolean;+ /** Order of the workflow library's own templates. */+ workflowLibrarySort: WorkflowLibrarySortId;+ /** How workflow library and project cards show their thumbnails. */+ workflowLibraryThumbnailFit: WorkflowLibraryThumbnailFit;/** Raise text and border contrast on every theme (a11y). */highContrast: boolean;/** Account-bound overrides keyed by hotkey id (`app.invoke`, `gallery.galleryNavLeft`, etc.). */diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex 818d006975..b48ccfbbb1 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -403,6 +403,21 @@ 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({+ workflowLibrarySort: 'updated',+ workflowLibraryThumbnailFit: 'cover',+ });+ expect(+ store.normalizeWorkbenchPreferences({ workflowLibrarySort: 'size', workflowLibraryThumbnailFit: 'stretch' })+ ).toMatchObject({ workflowLibrarySort: 'updated', workflowLibraryThumbnailFit: 'cover' });+ expect(+ store.normalizeWorkbenchPreferences({ workflowLibrarySort: 'opened', workflowLibraryThumbnailFit: 'contain' })+ ).toMatchObject({ workflowLibrarySort: 'opened', workflowLibraryThumbnailFit: 'contain' });+ });+});+describe('normalizeWorkbenchPreferences appearance', () => {it('keeps high contrast off unless explicitly enabled', () => {expect(store.normalizeWorkbenchPreferences({}).highContrast).toBe(false);diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex d5637800b2..1c8a7b205c 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -7,6 +7,7 @@ import type {StoredRebalancePreset,ViewerAutoSwitchMode,WorkbenchPreferences,+ WorkflowLibrarySortId,} from '@workbench/settings/contracts';import { getUserStorageScope } from '@features/identity';@@ -79,6 +80,8 @@ export const DEFAULT_PREFERENCES: WorkbenchPreferences = {workflowEdgeStyle: 'curved',workflowEdgesBehindNodes: false,workflowGroupNodesByCategory: true,+ workflowLibrarySort: 'updated',+ workflowLibraryThumbnailFit: 'cover',workflowShowMinimap: true,workflowSnapToGrid: false,workflowValidateConnections: true,@@ -152,6 +155,9 @@ const isProjectsViewId = (value: unknown): value is ProjectsViewId => value ===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';+const normalizePinnedProjectIds = (values: unknown): string[] =>Array.isArray(values) ? [...new Set(values.filter((value): value is string => typeof value === 'string'))] : [];@@ -278,12 +284,19 @@ export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): Ptype WorkbenchPreferencesInput = Omit<Partial<WorkbenchPreferences>,- 'launchpadProjectsSort' | 'launchpadProjectsView' | 'queueJobsScope' | 'workflowEdgeStyle'+ | 'launchpadProjectsSort'+ | 'launchpadProjectsView'+ | 'queueJobsScope'+ | 'workflowEdgeStyle'+ | 'workflowLibrarySort'+ | 'workflowLibraryThumbnailFit'> & {launchpadProjectsSort?: unknown;launchpadProjectsView?: unknown;queueJobsScope?: unknown;workflowEdgeStyle?: unknown;+ workflowLibrarySort?: unknown;+ workflowLibraryThumbnailFit?: unknown;};export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferencesInput): WorkbenchPreferences => ({@@ -389,6 +402,13 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferencestypeof preferences?.workflowGroupNodesByCategory === 'boolean'? preferences.workflowGroupNodesByCategory: DEFAULT_PREFERENCES.workflowGroupNodesByCategory,+ workflowLibrarySort: isWorkflowLibrarySortId(preferences?.workflowLibrarySort)+ ? preferences.workflowLibrarySort+ : DEFAULT_PREFERENCES.workflowLibrarySort,+ workflowLibraryThumbnailFit:+ preferences?.workflowLibraryThumbnailFit === 'contain'+ ? 'contain'+ : DEFAULT_PREFERENCES.workflowLibraryThumbnailFit,workflowShowMinimap:typeof preferences?.workflowShowMinimap === 'boolean'? preferences.workflowShowMinimapdiff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsxindex e2e9d956bc..63fcdc72eb 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx@@ -2,7 +2,7 @@import { Box, ChakraProvider, HStack, Text } from '@chakra-ui/react';import { system } from '@theme/system';import { createInstance } from 'i18next';-import { act, type ReactNode } from 'react';+import { act, type ComponentType, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -59,6 +59,11 @@ const centerAreaMocks = vi.hoisted(() => {return {activeItem,+ /** Real widget chrome to place in the slots instead of the fixed-size stand-ins. */+ chromeSlots: null as null | {+ actions: ComponentType<{ region: 'center' }>;+ label: ComponentType<{ region: 'center' }>;+ },dockFloating: vi.fn(),focusFloating: vi.fn(),focusRegion: vi.fn(),@@ -67,11 +72,18 @@ const centerAreaMocks = vi.hoisted(() => {};});-vi.mock('@features/models', () => ({ useModelLoads: () => [] }));-vi.mock('@features/queue/contracts', () => ({+vi.mock('@features/models', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useModelLoads: () => [],+}));+vi.mock('@features/queue/contracts', async (importOriginal) => ({+ ...(await importOriginal<object>()),getProjectQueueIndicatorState: () => ({ hasOpenQueueWork: false, progressState: null, runningQueueItemId: null }),}));-vi.mock('@features/queue/react', () => ({ useQueueItemProgress: () => null }));+vi.mock('@features/queue/react', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ useQueueItemProgress: () => null,+}));vi.mock('@workbench/focusRegions', () => ({useFocusRegionProps: () => ({}),useHighlightedRegion: () => null,@@ -110,6 +122,21 @@ vi.mock('@workbench/widget-frame', () => ({// suspend on a chunk that does not exist under the mocked registry.WidgetIdentityIcon: () => <Box boxSize="3.5" />,WidgetChromeSlotById: ({ slot }: { slot: 'actions' | 'label' }) => {+ const Slot = centerAreaMocks.chromeSlots?.[slot];++ if (Slot) {+ // The frame adds the widget's settings and menu buttons after its own actions.+ return slot === 'actions' ? (+ <>+ <Slot region="center" />+ <Box aria-label="Widget settings" as="button" boxSize="6" flexShrink={0} />+ <Box aria-label="Widget menu" as="button" boxSize="6" flexShrink={0} />+ </>+ ) : (+ <Slot region="center" />+ );+ }+if (slot === 'actions') {return <Box data-testid="trailing-actions" flexShrink={0} w="189px" />;}@@ -156,9 +183,9 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const render = async (children: ReactNode) => {+const render = async (children: ReactNode, width = 571) => {host = document.createElement('div');- host.style.cssText = 'display:flex;height:320px;width:571px;';+ host.style.cssText = `display:flex;height:320px;width:${width}px;`;document.body.append(host);root = createRoot(host);@@ -262,3 +289,75 @@ describe('CenterArea with its last view floating', () => {expect(button('Show window')).toBeUndefined();});});++describe('CenterArea with the workflow editor chrome at a narrow width', () => {+ afterEach(() => {+ centerAreaMocks.chromeSlots = null;+ centerAreaMocks.activeItem.label = 'Preview';+ });++ const renderWorkflowChrome = async (source?: { libraryWorkflowId: string; revision: number }) => {+ const [{ loadWorkflowWidgetImplementation }, { WorkflowUiProvider }, { QueryClient, QueryClientProvider }] =+ await Promise.all([+ import('@features/workflow/widget'),+ import('@features/workflow/react'),+ import('@tanstack/react-query'),+ ]);+ const implementation = await loadWorkflowWidgetImplementation();+ const document = { id: 'workflow-1', name: 'A workflow whose name is far too long for a narrow center view' };+ const snapshot = {+ activeWorkflow: { document, source },+ activeWorkflowId: document.id,+ id: 'project-1',+ projectGraph: document,+ workflows: [{ document, source }],+ };+ const port = <T,>(value: T) => ({ getSnapshot: () => value, subscribe: () => () => {} });+ const adapter = {+ persistence: port({ error: null, hasLocalRecovery: true, lastSavedAt: null, status: 'saved' }),+ project: port(snapshot),+ } as unknown as Parameters<typeof WorkflowUiProvider>[0]['adapter'];+ const Label = implementation.headerLabel as ComponentType<{ region: 'center' }>;+ const Actions = implementation.headerActions as ComponentType<{ region: 'center' }>;++ centerAreaMocks.chromeSlots = { actions: Actions, label: Label };+ centerAreaMocks.activeItem.label = 'Workflow';+ // The width the project-file journey's default viewport gives the center view.+ await render(+ <QueryClientProvider client={new QueryClient()}>+ <WorkflowUiProvider adapter={adapter}>+ <CenterArea />+ </WorkflowUiProvider>+ </QueryClientProvider>,+ 320+ );+ };++ /** Whether a pointer at the element's centre lands on it, rather than on chrome painted over it. */+ const isHitTestable = (element: Element) => {+ const rect = element.getBoundingClientRect();+ const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2);++ return rect.width > 0 && hit !== null && element.contains(hit);+ };++ it.each([+ ['unlinked', undefined],+ ['linked, with its Update button', { libraryWorkflowId: 'library-1', revision: 2 }],+ ])('keeps the workflow name and every header action clickable when %s', async (_label, source) => {+ await renderWorkflowChrome(source);++ // Untranslated here: the button is the one carrying the workflow's library link.+ const workflowsButton = host!.querySelector('[data-template-link]')?.closest('button');+ const actions = [+ ...host!.querySelectorAll('[data-hotkey-widget-region="center"] > :last-child :is(button, [role="status"])'),+ ];++ expect(workflowsButton).not.toBeNull();+ expect(actions.length).toBe(source ? 6 : 5);+ expect(isHitTestable(workflowsButton!)).toBe(true);+ expect(+ actions.filter((action) => !isHitTestable(action)).map((action) => action.getAttribute('aria-label'))+ ).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsxindex a5bb797d7a..ae741d1479 100644--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx@@ -294,6 +294,8 @@ const CenterViewMenu = ({ref={triggerRef}aria-label={t('widgets.centerViewLabel', { label })}color="fg"+ // The button recipe refuses to shrink; a narrow center truncates the view name beside the widget's label.+ flexShrink={1}minW="0"overflow="hidden"position="relative"diff --git a/tests/app/services/workflow_records/test_workflow_library_queries.py b/tests/app/services/workflow_records/test_workflow_library_queries.pyindex 83839d42dc..b370d93a66 100644--- a/tests/app/services/workflow_records/test_workflow_library_queries.py+++ b/tests/app/services/workflow_records/test_workflow_library_queries.py@@ -156,10 +156,23 @@ def test_listings_tell_opened_workflows_apart(workflow_records: WorkflowRecordsS@pytest.mark.parametrize("direction", [SQLiteDirection.Ascending, SQLiteDirection.Descending])+def test_names_sort_ignoring_case(workflow_records: WorkflowRecordsStorage, direction: SQLiteDirection) -> None:+ for name in ["charlie", "Delta", "alpha", "Bravo"]:+ workflow_records.create(_workflow(name), user_id=USER)++ listed = workflow_records.get_many(WorkflowRecordOrderBy.Name, direction, [WorkflowCategory.User]).items++ expected = ["alpha", "Bravo", "charlie", "Delta"]+ assert [item.name for item in listed] == (expected if direction == SQLiteDirection.Ascending else expected[::-1])++[email protected]("direction", [SQLiteDirection.Ascending, SQLiteDirection.Descending])[email protected]("names", [["Same"] * 5, ["same", "SAME", "Same", "sAme", "samE"]], ids=["equal", "case"])def test_pages_of_equal_names_keep_one_order(- workflow_records: WorkflowRecordsStorage, direction: SQLiteDirection+ workflow_records: WorkflowRecordsStorage, direction: SQLiteDirection, names: list[str]) -> None:- created = [workflow_records.create(_workflow("Same"), user_id=USER).workflow_id for _ in range(5)]+ # Names equal but for case are equal keys: the workflow id alone orders them, on every page.+ created = [workflow_records.create(_workflow(name), user_id=USER).workflow_id for name in names]pages = [workflow_records.get_many(