Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): save workflows to the library explicitly
Josh Corbett4a2894dcfb6b
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.jsonindex 29f7576a17..9771d13dc2 100644--- a/invokeai/frontend/webv2/performance/architecture-baseline.json+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json@@ -2,17 +2,17 @@"build": {"launchpad": {"baseline": {- "brotliBytes": 897042,+ "brotliBytes": 898192,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 895775,+ "gzipBytes": 896907,"imageRawBytes": 156376,- "initialRawBytes": 2132017,+ "initialRawBytes": 2134258,"largestAssetRawBytes": 778953,"otherAssetRawBytes": 0,- "ownedRawBytes": 91552,- "requestCount": 37,- "scriptRequestCount": 21,+ "ownedRawBytes": 91583,+ "requestCount": 36,+ "scriptRequestCount": 20,"sourceOwners": ["package:@ark-ui/react","package:@chakra-ui/react",@@ -328,15 +328,15 @@},"editor": {"baseline": {- "brotliBytes": 1237634,+ "brotliBytes": 1247542,"cssRawBytes": 2159,"fontRawBytes": 219480,- "gzipBytes": 1231243,+ "gzipBytes": 1241055,"imageRawBytes": 156376,- "initialRawBytes": 3176267,+ "initialRawBytes": 3207749,"largestAssetRawBytes": 778953,"otherAssetRawBytes": 0,- "ownedRawBytes": 141925,+ "ownedRawBytes": 143588,"requestCount": 86,"scriptRequestCount": 70,"sourceOwners": [@@ -680,12 +680,7 @@"source:src/features/workflow/core/types.ts","source:src/features/workflow/core/validation.ts","source:src/features/workflow/core/workflowJson.ts",- "source:src/features/workflow/data/api.ts",- "source:src/features/workflow/data/libraryCache.ts",- "source:src/features/workflow/data/runCapture.ts",- "source:src/features/workflow/data/savedWorkflowQueries.ts","source:src/features/workflow/data/templates.ts",- "source:src/features/workflow/queries.ts","source:src/features/workflow/react.ts","source:src/features/workflow/ui/WorkflowUiContext.tsx","source:src/features/workflow/ui/workflowUiStore.ts",@@ -898,6 +893,7 @@"source:src/workbench/persistenceRuntime.ts","source:src/workbench/projectCanvasGate.ts","source:src/workbench/projectEvents.ts",+ "source:src/workbench/projectWorkflows.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",@@ -1056,7 +1052,7 @@"source": "src/app/WorkbenchApp.tsx"}},- "capturedAt": "2026-09-23",+ "capturedAt": "2026-09-26","developmentInvalidation": {"platformUiBarrel": {"specifier": "@platform/ui",diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.jsonindex 036383e1ba..b3b6c066f1 100644--- a/invokeai/frontend/webv2/performance/browser-baseline.json+++ b/invokeai/frontend/webv2/performance/browser-baseline.json@@ -1,6 +1,6 @@{"browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome",- "capturedAt": "2026-09-26",+ "capturedAt": "2026-09-27","routes": [{"activatedResourceBaseline": {@@ -14,13 +14,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 127.29999999981374,+ "domContentLoadedMedianMs": 118.5,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 127.5,- "longestTaskMaxMs": 83,+ "loadMedianMs": 118.59999999403954,+ "longestTaskMaxMs": 74,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -30,13 +30,13 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 31,- "scriptRawBytes": 1817020,+ "scriptRawBytes": 1817576,"scriptRequestCount": 27,- "totalRawBytes": 2016041+ "totalRawBytes": 2021078},- "routeReadyMedianMs": 273.20000000018626,+ "routeReadyMedianMs": 252.79999999701977,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "empty"},@@ -52,13 +52,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 127.0999999998603,+ "domContentLoadedMedianMs": 119.20000000298023,"id": "launchpad","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 127.19999999995343,- "longestTaskMaxMs": 79,+ "loadMedianMs": 119.29999999701977,+ "longestTaskMaxMs": 74,"owner": "app","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:launchpad",@@ -68,13 +68,13 @@"fontRawBytes": 23664,"imageRawBytes": 0,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 31,- "scriptRawBytes": 1817020,+ "scriptRawBytes": 1817576,"scriptRequestCount": 27,- "totalRawBytes": 2016041+ "totalRawBytes": 2021078},- "routeReadyMedianMs": 282.69999999995343,+ "routeReadyMedianMs": 265.8999999985099,"scriptSourceOwnerSet": "launchpad-static","stateProfile": "representative"},@@ -90,15 +90,15 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 130.39999999990687,+ "domContentLoadedMedianMs": 120.59999999403954,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 130.5999999998603,- "longestTaskMaxMs": 158,+ "loadMedianMs": 120.69999999552965,+ "longestTaskMaxMs": 147,"owner": "workbench",- "projectSwitchMedianMs": 34.5,+ "projectSwitchMedianMs": 30.799999997019768,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -106,13 +106,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 98,- "scriptRawBytes": 3801383,+ "scriptRawBytes": 3853510,"scriptRequestCount": 93,- "totalRawBytes": 4156780+ "totalRawBytes": 4213388},- "routeReadyMedianMs": 434.19999999995343,+ "routeReadyMedianMs": 402.80000000447035,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -128,15 +128,15 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 128.19999999995343,+ "domContentLoadedMedianMs": 119,"id": "editor-minimal","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,"layoutSwitchMedianMs": 0,- "loadMedianMs": 128.39999999990687,- "longestTaskMaxMs": 161,+ "loadMedianMs": 119.19999999552965,+ "longestTaskMaxMs": 146,"owner": "workbench",- "projectSwitchMedianMs": 47.60000000009313,+ "projectSwitchMedianMs": 43.5,"readyMark": "invokeai:ready:widget:center:preview","remediationTicket": "deepen-widget-registry-loading","resourceBaseline": {@@ -144,13 +144,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 98,- "scriptRawBytes": 3801383,+ "scriptRawBytes": 3853510,"scriptRequestCount": 93,- "totalRawBytes": 4156780+ "totalRawBytes": 4213388},- "routeReadyMedianMs": 432.69999999995343,+ "routeReadyMedianMs": 407.5,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"},@@ -159,20 +159,20 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 309188,+ "largestAssetRawBytes": 309158,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 503239,+ "scriptRawBytes": 503264,"scriptRequestCount": 9,- "totalRawBytes": 503239+ "totalRawBytes": 503264},- "domContentLoadedMedianMs": 126.9000000001397,+ "domContentLoadedMedianMs": 117.29999999701977,"id": "editor-canvas",- "layoutAckMedianMs": 2.5,- "layoutReturnSwitchMedianMs": 46.0999999998603,- "layoutSwitchMedianMs": 84.19999999995343,- "loadMedianMs": 127,- "longestTaskMaxMs": 153,+ "layoutAckMedianMs": 2.2000000029802322,+ "layoutReturnSwitchMedianMs": 43.599999994039536,+ "layoutSwitchMedianMs": 80.90000000596046,+ "loadMedianMs": 117.39999999850988,+ "longestTaskMaxMs": 149,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -182,13 +182,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 107,- "scriptRawBytes": 4304622,+ "scriptRawBytes": 4356774,"scriptRequestCount": 102,- "totalRawBytes": 4660019+ "totalRawBytes": 4716652},- "routeReadyMedianMs": 1126.8999999999069,+ "routeReadyMedianMs": 1093.5999999940395,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "empty"},@@ -197,20 +197,20 @@"cssRawBytes": 0,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 309188,+ "largestAssetRawBytes": 309158,"otherRawBytes": 0,"requestCount": 9,- "scriptRawBytes": 503239,+ "scriptRawBytes": 503264,"scriptRequestCount": 9,- "totalRawBytes": 503239+ "totalRawBytes": 503264},- "domContentLoadedMedianMs": 125,+ "domContentLoadedMedianMs": 120.80000000447035,"id": "editor-canvas",- "layoutAckMedianMs": 2.800000000046566,- "layoutReturnSwitchMedianMs": 44.5,- "layoutSwitchMedianMs": 82.30000000004657,- "loadMedianMs": 125.0999999998603,- "longestTaskMaxMs": 193,+ "layoutAckMedianMs": 2.2000000029802322,+ "layoutReturnSwitchMedianMs": 48.100000001490116,+ "layoutSwitchMedianMs": 84.20000000298023,+ "loadMedianMs": 120.80000000447035,+ "longestTaskMaxMs": 185,"owner": "canvas","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:canvas",@@ -220,13 +220,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 107,- "scriptRawBytes": 4304622,+ "scriptRawBytes": 4356774,"scriptRequestCount": 102,- "totalRawBytes": 4660019+ "totalRawBytes": 4716652},- "routeReadyMedianMs": 1119,+ "routeReadyMedianMs": 1113,"scriptSourceOwnerSet": "editor-canvas-static","stateProfile": "representative"},@@ -235,20 +235,20 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 178563,+ "largestAssetRawBytes": 179349,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 411638,+ "scriptRawBytes": 412553,"scriptRequestCount": 6,- "totalRawBytes": 427051+ "totalRawBytes": 427966},- "domContentLoadedMedianMs": 127.10000000009313,+ "domContentLoadedMedianMs": 119.60000000149012,"id": "editor-workflow",- "layoutAckMedianMs": 2.6000000000931323,- "layoutReturnSwitchMedianMs": 33.199999999953434,- "layoutSwitchMedianMs": 98.30000000004657,- "loadMedianMs": 127.20000000018626,- "longestTaskMaxMs": 158,+ "layoutAckMedianMs": 2.2999999970197678,+ "layoutReturnSwitchMedianMs": 32.399999998509884,+ "layoutSwitchMedianMs": 95.60000000149012,+ "loadMedianMs": 119.60000000149012,+ "longestTaskMaxMs": 149,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -258,13 +258,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 105,- "scriptRawBytes": 4213021,+ "scriptRawBytes": 4266063,"scriptRequestCount": 99,- "totalRawBytes": 4583831+ "totalRawBytes": 4641354},- "routeReadyMedianMs": 1131.8999999999069,+ "routeReadyMedianMs": 1099,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "empty"},@@ -273,20 +273,20 @@"cssRawBytes": 15413,"fontRawBytes": 0,"imageRawBytes": 0,- "largestAssetRawBytes": 178563,+ "largestAssetRawBytes": 179349,"otherRawBytes": 0,"requestCount": 7,- "scriptRawBytes": 411638,+ "scriptRawBytes": 412553,"scriptRequestCount": 6,- "totalRawBytes": 427051+ "totalRawBytes": 427966},- "domContentLoadedMedianMs": 127.89999999990687,+ "domContentLoadedMedianMs": 119,"id": "editor-workflow",- "layoutAckMedianMs": 2.699999999953434,- "layoutReturnSwitchMedianMs": 39,- "layoutSwitchMedianMs": 135.89999999990687,- "loadMedianMs": 128,- "longestTaskMaxMs": 382,+ "layoutAckMedianMs": 2.3000000044703484,+ "layoutReturnSwitchMedianMs": 37.899999998509884,+ "layoutSwitchMedianMs": 131.5,+ "loadMedianMs": 119.10000000149012,+ "longestTaskMaxMs": 358,"owner": "workflow","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:workflow",@@ -296,13 +296,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 105,- "scriptRawBytes": 4213021,+ "scriptRawBytes": 4266063,"scriptRequestCount": 99,- "totalRawBytes": 4583831+ "totalRawBytes": 4641354},- "routeReadyMedianMs": 1178,+ "routeReadyMedianMs": 1138,"scriptSourceOwnerSet": "editor-workflow-static","stateProfile": "representative"},@@ -318,13 +318,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 125.60000000009313,+ "domContentLoadedMedianMs": 118.89999999850988,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 46.199999999953434,- "loadMedianMs": 125.69999999995343,- "longestTaskMaxMs": 155,+ "layoutSwitchMedianMs": 42.100000001490116,+ "loadMedianMs": 119.10000000149012,+ "longestTaskMaxMs": 143,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -334,13 +334,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 98,- "scriptRawBytes": 3801383,+ "scriptRawBytes": 3853510,"scriptRequestCount": 93,- "totalRawBytes": 4156780+ "totalRawBytes": 4213388},- "routeReadyMedianMs": 1359.1000000000931,+ "routeReadyMedianMs": 1303.3999999985099,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "empty"},@@ -356,13 +356,13 @@"scriptRequestCount": 0,"totalRawBytes": 0},- "domContentLoadedMedianMs": 127.5,+ "domContentLoadedMedianMs": 118.39999999850988,"id": "editor-gallery","layoutAckMedianMs": 0,"layoutReturnSwitchMedianMs": 0,- "layoutSwitchMedianMs": 52.699999999953434,- "loadMedianMs": 127.69999999995343,- "longestTaskMaxMs": 158,+ "layoutSwitchMedianMs": 48.399999998509884,+ "loadMedianMs": 118.5,+ "longestTaskMaxMs": 144,"owner": "gallery","projectSwitchMedianMs": 0,"readyMark": "invokeai:ready:widget:center:gallery",@@ -372,13 +372,13 @@"fontRawBytes": 23664,"imageRawBytes": 156376,"largestAssetRawBytes": 778953,- "otherRawBytes": 173198,+ "otherRawBytes": 177679,"requestCount": 98,- "scriptRawBytes": 3801383,+ "scriptRawBytes": 3853510,"scriptRequestCount": 93,- "totalRawBytes": 4156780+ "totalRawBytes": 4213388},- "routeReadyMedianMs": 1343,+ "routeReadyMedianMs": 1344.2000000029802,"scriptSourceOwnerSet": "editor-minimal-static","stateProfile": "representative"}@@ -1189,7 +1189,7 @@"source:src/features/workflow/data/api.ts","source:src/features/workflow/data/libraryBrowseStore.ts","source:src/features/workflow/data/libraryCache.ts",- "source:src/features/workflow/data/runCapture.ts",+ "source:src/features/workflow/data/publication.ts","source:src/features/workflow/data/savedWorkflowQueries.ts","source:src/features/workflow/data/templates.ts","source:src/features/workflow/queries.ts",@@ -1201,19 +1201,20 @@"source:src/features/workflow/ui/editor/AddNodeDialog.tsx","source:src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx","source:src/features/workflow/ui/editor/flowInstanceStore.ts",+ "source:src/features/workflow/ui/editor/workflowViewportStore.ts",+ "source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx","source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx","source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx","source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",+ "source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx","source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx",- "source:src/features/workflow/ui/library/libraryAutosave.ts","source:src/features/workflow/ui/library/libraryPreviewSource.ts",- "source:src/features/workflow/ui/library/librarySyncBridge.ts",+ "source:src/features/workflow/ui/library/projectWorkflowEntries.ts","source:src/features/workflow/ui/library/relativeTime.ts",- "source:src/features/workflow/ui/library/useLoadLibraryWorkflow.ts",- "source:src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts",- "source:src/features/workflow/ui/library/workflowLibrarySyncStore.ts",+ "source:src/features/workflow/ui/library/useOpenLibraryWorkflow.ts",+ "source:src/features/workflow/ui/library/useWorkflowPublication.ts","source:src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts","source:src/features/workflow/ui/useProjectGraphCommands.ts","source:src/features/workflow/ui/workflowTransfer.ts",@@ -1593,6 +1594,7 @@"source:src/workbench/persistenceRuntime.ts","source:src/workbench/projectCanvasGate.ts","source:src/workbench/projectEvents.ts",+ "source:src/workbench/projectWorkflows.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",@@ -2247,7 +2249,7 @@"source:src/features/workflow/data/api.ts","source:src/features/workflow/data/libraryBrowseStore.ts","source:src/features/workflow/data/libraryCache.ts",- "source:src/features/workflow/data/runCapture.ts",+ "source:src/features/workflow/data/publication.ts","source:src/features/workflow/data/savedWorkflowQueries.ts","source:src/features/workflow/data/templates.ts","source:src/features/workflow/queries.ts",@@ -2259,19 +2261,20 @@"source:src/features/workflow/ui/editor/AddNodeDialog.tsx","source:src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.tsx","source:src/features/workflow/ui/editor/flowInstanceStore.ts",+ "source:src/features/workflow/ui/editor/workflowViewportStore.ts",+ "source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx","source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx","source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx","source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",+ "source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx","source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx",- "source:src/features/workflow/ui/library/libraryAutosave.ts","source:src/features/workflow/ui/library/libraryPreviewSource.ts",- "source:src/features/workflow/ui/library/librarySyncBridge.ts",+ "source:src/features/workflow/ui/library/projectWorkflowEntries.ts","source:src/features/workflow/ui/library/relativeTime.ts",- "source:src/features/workflow/ui/library/useLoadLibraryWorkflow.ts",- "source:src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts",- "source:src/features/workflow/ui/library/workflowLibrarySyncStore.ts",+ "source:src/features/workflow/ui/library/useOpenLibraryWorkflow.ts",+ "source:src/features/workflow/ui/library/useWorkflowPublication.ts","source:src/features/workflow/ui/pendingLibraryWorkflowLoadRuntime.ts","source:src/features/workflow/ui/useProjectGraphCommands.ts","source:src/features/workflow/ui/workflowTransfer.ts",@@ -2660,6 +2663,7 @@"source:src/workbench/persistenceRuntime.ts","source:src/workbench/projectCanvasGate.ts","source:src/workbench/projectEvents.ts",+ "source:src/workbench/projectWorkflows.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",@@ -3482,7 +3486,7 @@"source:src/features/workflow/data/api.ts","source:src/features/workflow/data/libraryBrowseStore.ts","source:src/features/workflow/data/libraryCache.ts",- "source:src/features/workflow/data/runCapture.ts",+ "source:src/features/workflow/data/publication.ts","source:src/features/workflow/data/savedWorkflowFieldUtils.ts","source:src/features/workflow/data/savedWorkflowQueries.ts","source:src/features/workflow/data/templates.ts",@@ -3528,19 +3532,19 @@"source:src/features/workflow/ui/graph-preview/index.ts","source:src/features/workflow/ui/graph-preview/nodeSummaries.ts","source:src/features/workflow/ui/implementation.ts",+ "source:src/features/workflow/ui/library/ProjectWorkflowsView.tsx","source:src/features/workflow/ui/library/WorkflowLibraryCard.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx","source:src/features/workflow/ui/library/WorkflowLibraryDialog.tsx","source:src/features/workflow/ui/library/WorkflowLibraryGrid.tsx","source:src/features/workflow/ui/library/WorkflowLibraryTagChips.tsx",+ "source:src/features/workflow/ui/library/WorkflowPublicationHost.tsx","source:src/features/workflow/ui/library/WorkflowRequirementsList.tsx",- "source:src/features/workflow/ui/library/libraryAutosave.ts","source:src/features/workflow/ui/library/libraryPreviewSource.ts",- "source:src/features/workflow/ui/library/librarySyncBridge.ts",+ "source:src/features/workflow/ui/library/projectWorkflowEntries.ts","source:src/features/workflow/ui/library/relativeTime.ts",- "source:src/features/workflow/ui/library/useLoadLibraryWorkflow.ts",- "source:src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts",- "source:src/features/workflow/ui/library/workflowLibrarySyncStore.ts",+ "source:src/features/workflow/ui/library/useOpenLibraryWorkflow.ts",+ "source:src/features/workflow/ui/library/useWorkflowPublication.ts","source:src/features/workflow/ui/linear/FormBuilderTab.tsx","source:src/features/workflow/ui/linear/LinearFormView.tsx","source:src/features/workflow/ui/linear/NodeFieldControl.tsx",@@ -3932,6 +3936,7 @@"source:src/workbench/persistenceRuntime.ts","source:src/workbench/projectCanvasGate.ts","source:src/workbench/projectEvents.ts",+ "source:src/workbench/projectWorkflows.ts","source:src/workbench/projects/accountOwnedWorkbenchDatabase.ts","source:src/workbench/projects/api.ts","source:src/workbench/projects/components/OpenProjectDialog.tsx",diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 4cebb0012e..83ca2f6afa 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -505,6 +505,7 @@"invalid": "\"{{name}}\" contains canvas data this version of Invoke cannot read, and it was not opened.","multiple": "{{count}} saved projects were not opened because this version of Invoke cannot read them: {{names}}.","legacyVersion": "\"{{name}}\" was saved by an older version of Invoke and cannot be opened here.",+ "malformed": "\"{{name}}\" is damaged and was not opened. Its saved copy is untouched and can be exported.","unsupportedVersion": "\"{{name}}\" was saved by a newer version of Invoke and cannot be opened here."},"newProject": "New project",@@ -2625,7 +2626,8 @@"syncSynced": "Synced (revision {{revision}})","syncConflict": "Needs conflict resolution","syncUpdateClient": "Update Invoke to sync",- "syncWaiting": "Waiting to sync"+ "syncWaiting": "Waiting to sync",+ "workflows": "Workflows"},"preview": {"commands": {@@ -2784,6 +2786,7 @@"chipLabel": "Autosave: {{status}}","label": "Autosave","lastSaved": "Last saved: {{time}}",+ "pending": "Unsaved changes","status": "Status: {{status}}"},"canvas": {@@ -3075,7 +3078,6 @@"about": "About","addNode": "Add node","author": "Author",- "autosavesToLibrary": "Autosaves to library","class": "Class","connectorNode": "Connector node","contact": "Contact",@@ -3089,18 +3091,23 @@"detailsWithEllipsis": "Workflow details…","exportJson": "Export workflow JSON","form": "Form",+ "importFailed": "Failed to import workflow",+ "importInvalid": "The file is not a valid workflow JSON.","importJsonWithEllipsis": "Import workflow JSON…",+ "importWarning": "Workflow import warning",+ "importedLabel": "Imported \"{{name}}\"","inspectorTabs": {"data": "Data","details": "Details","outputs": "Outputs","template": "Template"},+ "latestOutput": "Latest output","library": "Workflow library",- "librarySyncError": "Library save failed — click to retry",- "librarySyncSaved": "Saved to library",- "librarySyncSaving": "Saving to library…",- "librarySyncState": "Library sync state",+ "libraryWithEllipsis": "Workflow library…",+ "newWorkflow": "New workflow",+ "noRunRecorded": "This node has not run in this session.",+ "noTemplateKnown": "No template is known for \"{{type}}\" on this backend.","nodeData": "Node data","nodeInspector": "Node Inspector","nodeNotes": "Node notes",@@ -3108,31 +3115,38 @@"nodeTemplate": "Node template","notes": "Notes","notesNode": "Notes node",- "noTemplateKnown": "No template is known for \"{{type}}\" on this backend.",- "openLibrary": "Open workflow library. Current workflow: {{name}}",+ "openProjectWorkflows": "Open this project's workflows. Current workflow: {{name}}",+ "outputImage": "Output image","pack": "Pack","panelContent": "Workflow panel content","panelMode": "Workflow panel mode",+ "persistenceConflict": "Project has a sync conflict — resolve it to keep saving",+ "persistenceError": "Project save failed — retrying",+ "persistencePending": "Project changes waiting to save (recovery draft kept)",+ "persistencePendingNoRecovery": "Project changes waiting to save — no browser recovery available",+ "persistenceSaved": "Project saved to the server",+ "persistenceSaving": "Saving project…",+ "projectWorkflows": "This project's workflows","resizeNodeInspector": "Resize node inspector",- "latestOutput": "Latest output",- "noRunRecorded": "This node has not run in this session.",- "outputImage": "Output image","runStatus": {"completed": "Completed","failed": "Failed","running": "Running…"},- "status": "Status",- "newWorkflowWithEllipsis": "New workflow…","saveToLibrary": "Save to library",+ "saveToLibraryWithEllipsis": "Save to library…","selectNodeToInspect": "Select a node in the Workflow editor to inspect it.","selectedNodeInspector": "Selected node inspector",+ "status": "Status",+ "submitRemovedBody": "The workflow was removed from the project before it could be queued.",+ "submitRemovedTitle": "Workflow not queued","tags": "Tags","title": "Title","type": "Type",+ "untitled": "Untitled Workflow",+ "updateTemplateWithEllipsis": "Update library template…","version": "Version",- "workflowJson": "Workflow JSON",- "untitled": "Untitled Workflow"+ "workflowJson": "Workflow JSON"},"layers": {"actions": {@@ -4175,9 +4189,17 @@}},"workflowLibrary": {+ "activeWorkflow": "Active",+ "addAnotherCopy": "Add another copy",+ "addAnotherCopyHint": "A second, independent copy in this project",+ "addWorkflow": "Add workflow","allTag": "All","applying": "Applying workflow…","browse": "Browse",+ "chooseProjectCopy": "Open which copy?",+ "conflictStaleBody": "The library template behind \"{{name}}\" has changed since this copy was loaded or last saved.",+ "conflictTitle": "Template has changed",+ "conflictUnknownBody": "It is not known whether the library template behind \"{{name}}\" still matches this copy.","delete": "Delete","deleteConfirmBody": "Delete \"{{name}}\" from the workflow library? This cannot be undone.","deleteConfirmTitle": "Delete workflow",@@ -4189,6 +4211,7 @@"duplicateFailed": "Failed to duplicate workflow","duplicateHint": "Saves a copy under Yours, original untouched","duplicateName": "{{name}} copy",+ "duplicateProjectWorkflowHint": "A copy beside it in this project","duplicated": "Saved a copy under Yours","empty": "No workflows match these filters.","fetching": "Fetching workflow…",@@ -4205,31 +4228,83 @@"loadedLabel": "Loaded \"{{name}}\" from library","loading": "Loading workflows…","loadingMore": "Loading more…",+ "moreActions": "More actions","multipleWorkflowReturnNodes": "The workflow must contain exactly one workflow return node before it can be saved.","multipleWorkflowReturnNodesForTransfer": "The workflow must contain exactly one workflow return node before it can be exported or copied.",- "workflowMetadataOmitted": "Workflow metadata omitted",- "workflowMetadataOmittedBody": "Workflow metadata was omitted because the workflow contains multiple workflow_return nodes.",- "moreActions": "More actions",+ "newWorkflow": "New workflow","nodeCount_one": "{{count}} node","nodeCount_other": "{{count}} nodes","notRunYet": "Not run yet","open": "Open",- "openHint": "Replaces the current workflow",+ "openHint": "Adds a copy to this project",+ "openProjectChanged": "The project changed while \"{{name}}\" was loading; nothing was added.",+ "openProjectCopy": "Open project copy",+ "openProjectCopyHint": "Switches to the copy this project already has",+ "openProjectWorkflowHint": "Makes it the active workflow","previewGraph": "Preview graph",+ "projectWorkflowCount_one": "{{count}} workflow in this project",+ "projectWorkflowCount_other": "{{count}} workflows in this project",+ "remove": "Remove",+ "removeConfirmBody": "Remove \"{{name}}\" from this project? Its library template, if any, is not affected.",+ "removeConfirmTitle": "Remove workflow",+ "removeHint": "Removes it from this project only",+ "removeWithEllipsis": "Remove…",+ "rename": "Rename",+ "renameTitle": "Rename workflow",+ "renameWithEllipsis": "Rename…",+ "replaceTemplate": "Replace template","requirementInstallable": "Not installed","requirementInstalled": "Installed","requirementInstalling": "Installing…","requirementMissing": "Not available to install","requires": "Requires",+ "retry": "Retry",+ "retryBody": "Saving \"{{name}}\" did not get an answer from the library ({{message}}). Retry the same save, or discard it. If the library did receive it, that template already exists.",+ "retryDiscard": "Discard",+ "retryTitle": "Library did not answer",+ "reviewBody": "This is the current library template. Replacing it writes this project workflow over it.",+ "reviewFailed": "The current template could not be loaded.",+ "reviewLoading": "Loading the current template…",+ "reviewRevision": "Revision {{revision}} · updated {{when}}",+ "reviewTemplate": "Review current template",+ "reviewTitle": "Current library template","sampleOutput": "Sample output",+ "saveAsNew": "Save as new",+ "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.",+ "saveToLibraryHint": "Creates a new template from this workflow",+ "saveToLibraryTitle": "Save to library",+ "saveToLibraryWithEllipsis": "Save to library…","saved": "Workflow saved","savedCreatedBody": "Saved \"{{name}}\" to the library.","savedUpdatedBody": "Updated \"{{name}}\" in the library.","searchPlaceholder": "Search names, tags, or descriptions",+ "sourceBundled": "From a bundled template (read-only)",+ "sourceNone": "Not linked to a library template",+ "sourceRevision": "Linked to library template at revision {{revision}}",+ "sourceUnknownRevision": "Linked to a library template (revision unknown)","tagsLabel": "Filter by tag",+ "templateName": "Template name",+ "thisProject": "This project",+ "thisProjectHint": "Workflows saved with this project. Edits autosave here; the library changes only when you save to it.","title": "Workflows",+ "unavailableBundledBody": "\"{{name}}\" came from a bundled template, which cannot be changed. Save it as a new template instead.",+ "unavailableForbiddenBody": "The library template behind \"{{name}}\" belongs to someone else. Save it as a new template instead.",+ "unavailableMissingBody": "The library template behind \"{{name}}\" no longer exists. Save it as a new template instead.",+ "unavailableTitle": "Template cannot be updated","untitled": "Untitled Workflow",+ "updateConfirm": "Update template",+ "updateConfirmBody": "Replace the library template with the current graph, form, and input values of \"{{name}}\"?",+ "updateConfirmCallers": "Workflows that call this template will use the new version.",+ "updateTemplate": "Update library template",+ "updateTemplateHint": "Writes this workflow over its library template",+ "updateTitle": "Update library template",+ "workflowGone": "The workflow is no longer in this project.",+ "workflowMetadataOmitted": "Workflow metadata omitted",+ "workflowMetadataOmittedBody": "Workflow metadata was omitted because the workflow contains multiple workflow_return nodes.",+ "workflowName": "Workflow name","yours": "Yours"},"settingsDialog": {diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjsindex 9b01573e69..15c542a5fb 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.mjs@@ -573,10 +573,73 @@ const createRasterForest = (layers) => {];};+/** A schema-2 style graph; the workflow collection wraps it, or a legacy document carries it as `projectGraph`. */+const createWorkflowDocument = ({ description, graphId, index, name, workflowNodes }) => {+ const formRootId = `${graphId}-form-root`;++ return {+ author: 'InvokeAI',+ contact: '',+ description,+ edges: [],+ form: {+ elements: {+ [formRootId]: {+ data: { children: [], layout: 'column' },+ id: formRootId,+ type: 'container',+ },+ },+ rootElementId: formRootId,+ },+ id: graphId,+ name,+ nodes: workflowNodes,+ notes: '',+ tags: 'fixture',+ updatedAt: timestampAt(index),+ version: 2,+ workflowVersion: '1.0.0',+ };+};++/**+ * Project 0 is a current schema-3 document that owns two workflows (a second, blank one beside the representative+ * graph, so the This-project view has something to switch to). Project 1 stays a schema-2 document with a single+ * `projectGraph`, which the project-file journey loads, exports and imports through the migration boundary.+ */const createProjectDocument = ({ index, layers = [], workflowNodes = [] }) => {const id = `fixture-project-${ordinal(index, 3)}`;const graphId = `${id}-graph`;- const formRootId = `${graphId}-form-root`;+ const primaryWorkflow = createWorkflowDocument({+ description: index === 0 ? 'Representative 100-node workflow.' : '',+ graphId,+ index,+ name: index === 0 ? 'Representative Workflow' : 'Empty Workflow',+ workflowNodes,+ });+ const workflows =+ index === 1+ ? null+ : {+ activeWorkflowId: graphId,+ entries: [+ { document: primaryWorkflow },+ ...(index === 0+ ? [+ {+ document: createWorkflowDocument({+ description: 'A second, blank workflow beside the representative graph.',+ graphId: `${id}-graph-2`,+ index,+ name: 'Second Workflow',+ workflowNodes: [],+ }),+ },+ ]+ : []),+ ],+ };return {canvas: {@@ -608,6 +671,7 @@ const createProjectDocument = ({ index, layers = [], workflowNodes = [] }) => {sourceId: workflowNodes.length > 0 ? 'workflow' : 'generate',sourceLocked: false,},+ ...(workflows ? { documentSchemaVersion: 3 } : { documentSchemaVersion: 2 }),layout: {centerViewId: 'preview',panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },@@ -615,36 +679,17 @@ const createProjectDocument = ({ index, layers = [], workflowNodes = [] }) => {},name: `Fixture Project ${ordinal(index, 3)}`,promptHistory: [],- projectGraph: {- author: 'InvokeAI',- contact: '',- description: index === 0 ? 'Representative 100-node workflow.' : '',- edges: [],- form: {- elements: {- [formRootId]: {- data: { children: [], layout: 'column' },- id: formRootId,- type: 'container',- },- },- rootElementId: formRootId,- },- id: graphId,- name: index === 0 ? 'Representative Workflow' : 'Empty Workflow',- nodes: workflowNodes,- notes: '',- tags: 'fixture',- updatedAt: timestampAt(index),- version: 2,- workflowVersion: '1.0.0',- },+ ...(workflows ? { workflows } : { projectGraph: primaryWorkflow }),queue: { items: [] },settings: {},widgetGraphs: {},};};+/** The first workflow a project document carries, whichever schema it uses. */+export const getFixtureProjectWorkflowDocument = (data) =>+ data?.workflows?.entries?.[0]?.document ?? data?.projectGraph ?? null;+const createProjects = (count, workflowNodeCount, layerCount) =>range(count, (index) => {const data = createProjectDocument({@@ -678,6 +723,7 @@ const createWorkflows = (count) =>description: `Synthetic workflow library entry ${id}.`,name: `Fixture Workflow ${id}`,opened_at: index % 3 === 0 ? timestampAt(index) : null,+ revision: 1,tags: 'fixture,representative',thumbnail_url: null,updated_at: timestampAt(index),@@ -696,7 +742,8 @@ const createWorkflows = (count) =>version: '3.0.0',workflowVersion: '1.0.0',},- workflow_id: `fixture-workflow-${id}`,+ // Bundled ids carry the server's `default_` prefix; the client treats those templates as read-only.+ workflow_id: index % 4 === 0 ? `default_fixture-workflow-${id}` : `fixture-workflow-${id}`,};});@@ -797,7 +844,7 @@ export const getMockBackendFixtureCounts = (fixture) => ({nodes: countInvocationSchemas(fixture),projects: fixture.projects.length,queueItems: fixture.queueItems.length,- workflowNodes: fixture.projects[0]?.data?.projectGraph?.nodes?.length ?? 0,+ workflowNodes: getFixtureProjectWorkflowDocument(fixture.projects[0]?.data)?.nodes?.length ?? 0,});const findDuplicates = (values) => {diff --git a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjsindex 287220659a..590d04848e 100644--- a/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend-fixtures.test.mjs@@ -6,6 +6,7 @@ import {assertMockBackendFixture,collectCanvasLeaves,createMockBackendFixture,+ getFixtureProjectWorkflowDocument,getMockBackendFixtureCounts,MOCK_BACKEND_PROFILE_COUNTS,MOCK_BACKEND_PROFILE_NAMES,@@ -73,10 +74,13 @@ test('representative fixtures keep node discovery and heavy project data coherenconst project = fixture.projects[0];assert.deepEqual(catalogTypes, invocationTypes);+ assert.equal(project.data.documentSchemaVersion, 3);assert.deepEqual(- project.data.projectGraph.nodes.map((node) => node.data.type),+ getFixtureProjectWorkflowDocument(project.data).nodes.map((node) => node.data.type),invocationTypes);+ assert.equal(project.data.workflows.entries.length, 2);+ assert.equal(project.data.workflows.activeWorkflowId, project.data.workflows.entries[0].document.id);const leaves = collectCanvasLeaves(project.data.canvas.document);assert.equal(leaves.length, MOCK_BACKEND_PROFILE_COUNTS.representative.layers);assert.equal(new Set(leaves.map((layer) => layer.id)).size, 64);@@ -105,6 +109,8 @@ test('Fixture Project 002 carries the image and video references used by the procollectCanvasLeaves(project.data.canvas.document).every((layer) => layer.type === 'raster'),true);+ // A schema-2 document on purpose: the project-file journey migrates it on load and exports schema 3.+ assert.equal(project.data.documentSchemaVersion, 2);assert.deepEqual(project.data.projectGraph.nodes[0]?.data.inputs.video?.value, {video_name: MOCK_BACKEND_REPRESENTATIVE_VIDEO_NAME,});diff --git a/invokeai/frontend/webv2/scripts/mock-backend.mjs b/invokeai/frontend/webv2/scripts/mock-backend.mjsindex 9c589e0be6..7e7845513b 100644--- a/invokeai/frontend/webv2/scripts/mock-backend.mjs+++ b/invokeai/frontend/webv2/scripts/mock-backend.mjs@@ -7,6 +7,7 @@ import {assertMockBackendProfileName,collectCanvasLeaves,createMockBackendFixture,+ getFixtureProjectWorkflowDocument,getMockBackendFixtureCounts,MOCK_BACKEND_FIXED_EPOCH,} from './mock-backend-fixtures.mjs';@@ -131,6 +132,9 @@ const createState = (profile) => {queueItems: new Map(fixture.queueItems.map((item) => [item.item_id, clone(item)])),videos: new Map(fixture.videos.map((video) => [video.video_name, clone(video)])),workflows: new Map(fixture.workflows.map((workflow) => [workflow.workflow_id, clone(workflow)])),+ nextWorkflowNumber: fixture.workflows.length + 1,+ /** Every workflow-library request since the last reset, so journeys can prove which writes happened. */+ workflowRequests: [],};};@@ -220,7 +224,7 @@ const getStateCounts = (state) => ({nodes: invocationNodeCount(state),projects: state.projects.size,queueItems: state.queueItems.size,- workflowNodes: state.projects.values().next().value?.data?.projectGraph?.nodes?.length ?? 0,+ workflowNodes: getFixtureProjectWorkflowDocument(state.projects.values().next().value?.data)?.nodes?.length ?? 0,});const getProfileInfo = (state) => ({@@ -1912,36 +1916,168 @@ export const startMockBackend = async (port, { profile = 'empty' } = {}) => {: json(404, { detail: 'Video not found' });}- const workflowMatch = /^\/api\/v1\/workflows\/i\/([^/]+)(?:\/opened_at)?$/.exec(path);+ if (path.startsWith('/api/v1/workflows')) {+ state.workflowRequests.push({ method, path });+ }++ if (method === 'GET' && path === '/__workflow-requests') {+ return json(200, { requests: state.workflowRequests });+ }++ const workflowRecord = (workflow) => ({ ...workflow, thumbnail_url: workflow.thumbnail_url ?? null });+ const workflowListItem = ({ workflow: _workflow, ...item }) => workflowRecord(item);+ const workflowTags = (workflow) =>+ String(workflow.tags ?? '')+ .split(',')+ .map((tag) => tag.trim())+ .filter(Boolean);++ if (path === '/api/v1/workflows/tags') {+ const categories = url.searchParams.getAll('categories');+ const tags = new Set();++ for (const workflow of state.workflows.values()) {+ if (categories.length === 0 || categories.includes(workflow.category)) {+ workflowTags(workflow).forEach((tag) => tags.add(tag));+ }+ }++ return json(200, [...tags].sort());+ }++ if (path === '/api/v1/workflows/counts_by_tag') {+ const categories = url.searchParams.getAll('categories');+ const counts = {};++ for (const tag of url.searchParams.getAll('tags')) {+ counts[tag] = [...state.workflows.values()].filter(+ (workflow) =>+ (categories.length === 0 || categories.includes(workflow.category)) &&+ workflowTags(workflow).includes(tag)+ ).length;+ }++ return json(200, counts);+ }++ const workflowMatch = /^\/api\/v1\/workflows\/i\/([^/]+)(\/opened_at)?$/.exec(path);if (workflowMatch) {const workflowId = decodeURIComponent(workflowMatch[1]);+ const suffix = workflowMatch[2] ?? '';const workflow = state.workflows.get(workflowId);if (!workflow) {return json(404, { detail: 'Workflow not found' });}- return json(200, {- name: workflow.name,- workflow: workflow.workflow,- workflow_id: workflow.workflow_id,- });+ if (suffix === '/opened_at' && method === 'PUT') {+ workflow.opened_at = timestamp(state);+ return json(200, null);+ }++ if (method === 'GET') {+ return json(200, workflowRecord(workflow));+ }++ if (method === 'DELETE') {+ if (workflow.category === 'default') {+ return json(403, { detail: 'Bundled workflows cannot be deleted' });+ }+ state.workflows.delete(workflowId);+ return json(200, null);+ }++ if (method === 'PATCH') {+ const body = await readJsonBody(request);+ const submitted = body.workflow ?? {};++ if (submitted.id !== workflowId) {+ return json(400, { detail: 'The workflow id in the body does not match the URL' });+ }+ if (workflow.category === 'default') {+ return json(403, { detail: 'Bundled workflows cannot be modified' });+ }+ if (body.expected_revision !== undefined && body.expected_revision !== workflow.revision) {+ return json(409, {+ detail: {+ current_revision: workflow.revision,+ expected_revision: body.expected_revision,+ message: `Workflow ${workflowId} is at revision ${String(workflow.revision)}`,+ reason: 'revision-conflict',+ },+ });+ }++ const { id: _id, ...content } = submitted;++ workflow.workflow = { ...content, meta: { ...content.meta, category: 'user' } };+ workflow.name = content.name ?? workflow.name;+ workflow.description = content.description ?? workflow.description;+ workflow.tags = content.tags ?? workflow.tags;+ workflow.revision += 1;+ workflow.updated_at = timestamp(state);++ return json(200, workflowRecord(workflow));+ }+ }++ if (method === 'POST' && (path === '/api/v1/workflows' || path === '/api/v1/workflows/')) {+ const body = await readJsonBody(request);+ const { id: _id, ...content } = body.workflow ?? {};+ const reservedId = typeof body.workflow_id === 'string' ? body.workflow_id : null;++ if (reservedId !== null && !/^[0-9a-f-]{36}$/i.test(reservedId)) {+ return json(400, { detail: 'A reserved workflow id must be a UUID' });+ }++ const existing = reservedId === null ? null : state.workflows.get(reservedId);++ if (existing) {+ // A retried creation is accepted only for the same content; anything else under the id is a conflict.+ return JSON.stringify(existing.workflow) ===+ JSON.stringify({ ...content, meta: { ...content.meta, category: 'user' } })+ ? json(200, workflowRecord(existing))+ : json(409, { detail: { message: 'The workflow id is already in use', reason: 'id-conflict' } });+ }++ const workflowId = reservedId ?? `mock-workflow-${String(state.nextWorkflowNumber++).padStart(4, '0')}`;+ const created = {+ category: 'user',+ created_at: timestamp(state),+ description: content.description ?? '',+ is_public: true,+ name: content.name ?? '',+ opened_at: null,+ revision: 1,+ tags: content.tags ?? '',+ thumbnail_url: null,+ updated_at: null,+ user_id: MOCK_USER_ID,+ workflow: { ...content, meta: { ...content.meta, category: 'user' } },+ workflow_id: workflowId,+ };++ created.updated_at = created.created_at;+ state.workflows.set(workflowId, created);++ return json(200, workflowRecord(created));}if (method === 'GET' && (path === '/api/v1/workflows' || path === '/api/v1/workflows/')) {const categories = url.searchParams.getAll('categories');const query = url.searchParams.get('query')?.trim().toLocaleLowerCase() ?? '';- const page = Math.max(1, Number(url.searchParams.get('page') ?? 1) || 1);+ const tags = url.searchParams.getAll('tags');+ // 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))+ (!query || `${workflow.name} ${workflow.description}`.toLocaleLowerCase().includes(query)) &&+ (tags.length === 0 || tags.some((tag) => workflowTags(workflow).includes(tag))));const pages = Math.max(1, Math.ceil(items.length / perPage));- const pageItems = items- .slice((page - 1) * perPage, page * perPage)- .map(({ workflow: _workflow, ...item }) => item);+ const pageItems = items.slice(page * perPage, (page + 1) * perPage).map(workflowListItem);return json(200, { items: pageItems, page, pages, total: items.length });}diff --git a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjsindex 83baf3e3a7..787c0f7a83 100644--- a/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs+++ b/invokeai/frontend/webv2/scripts/run-project-file-journey.mjs@@ -195,7 +195,49 @@ const getBoardSnapshot = (projectId) => fetchJson(`/api/v1/projects/${encodeURICconst getLayerImageNames = (project) =>collectCanvasLeaves(project.data.canvas.document).map((layer) => layer.source.image.imageName);-const getDocumentVideoName = (project) => project.data.projectGraph.nodes[0]?.data.inputs.video?.value?.video_name;+/** The first workflow document of a project record, whichever document schema the record carries. */+const getWorkflowDocuments = (project) =>+ project.data.workflows?.entries?.map((entry) => entry.document) ?? [project.data.projectGraph].filter(Boolean);++const getDocumentVideoName = (project) =>+ getWorkflowDocuments(project)[0]?.nodes[0]?.data.inputs.video?.value?.video_name;++const workflowRequests = async () => (await fetchJson('/__workflow-requests')).requests;++const presetStrip = (page) => page.getByRole('tablist', { exact: true, name: 'Layout preset' });++const centerViewTrigger = (page, label) => page.getByRole('button', { exact: true, name: `Center view: ${label}` });++/** Preset names need not match their center views; pass the expected view explicitly. */+const selectLayoutPreset = async (page, preset, centerView) => {+ const name = new RegExp(`^${preset}(, unsaved changes)?$`);+ const strip = presetStrip(page);+ const selected = strip.getByRole('tab', { name, selected: true });++ if ((await selected.count()) === 0) {+ await strip.getByRole('tab', { name }).click();+ }++ await selected.waitFor();+ await centerViewTrigger(page, centerView).waitFor();+};++/** Poll the server record until the project's saved workflows satisfy `predicate`. */+const waitForSavedWorkflows = async (projectId, predicate, label) => {+ const deadline = Date.now() + 15_000;++ while (Date.now() < deadline) {+ const record = await fetchJson(`/api/v1/projects/${encodeURIComponent(projectId)}`);++ if (predicate(record)) {+ return record;+ }++ await delay(100);+ }++ throw new Error(`The project record never reached the expected state: ${label}.`);+};/** Import the archive at `archivePath` through the Launchpad, exactly as a person would. */const importArchive = async ({ archivePath, browser, contexts, errors, phase }) => {@@ -380,7 +422,15 @@ const runRoundTrip = async ({ backend, browser, contexts, errors, tempDirectorycontexts.delete(importContext);assertNoBrowserErrors(errors);+ // The fixture was a schema-2 document with one `projectGraph`; import canonicalizes it into the current+ // schema with that graph as the only workflow and no library write target.+ assert.equal(imported.data.documentSchemaVersion, 3);+ assert.equal(imported.data.workflows.entries.length, 1);+ assert.equal(imported.data.workflows.activeWorkflowId, imported.data.workflows.entries[0].document.id);+ assert.equal(imported.data.workflows.entries[0].source, undefined);+await runDuplication({ browser, contexts, errors, imported, importedBoardNames });+ await runWorkflowCollection({ browser, contexts, errors, imported });await runMissingBinaryImport({ browser, contexts, entries, errors, tempDirectory });return {@@ -449,6 +499,166 @@ const runDuplication = async ({ browser, contexts, errors, imported, importedBoaassertNoBrowserErrors(errors);};+/**+ * The primary workflow journey: open a template into the project, edit it, switch away and back, save it to the+ * library under a new name, restart, and find both workflows intact. Project edits and runs issue no library writes;+ * the This-project view fetches no templates.+ */+const runWorkflowCollection = async ({ browser, contexts, errors, imported }) => {+ const projectId = imported.project_id;+ const template = await fetchJson('/api/v1/workflows/', {+ body: JSON.stringify({+ workflow: {+ author: '',+ contact: '',+ description: 'A template the journey opens into the project.',+ edges: [],+ exposedFields: [],+ form: {+ elements: { root: { data: { children: [], layout: 'column' }, id: 'root', type: 'container' } },+ rootElementId: 'root',+ },+ meta: { category: 'user', version: '3.0.0' },+ name: 'Journey Template',+ nodes: [],+ notes: '',+ tags: 'journey',+ version: '1.0.0',+ },+ }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });+ const requestsBefore = (await workflowRequests()).length;++ const context = await browser.newContext();++ contexts.add(context);+ const page = await context.newPage();++ observeBrowserErrors(page, 'workflow-collection', errors);+ await page.goto(`${origin}/#/`, { waitUntil: 'domcontentloaded' });+ await page.getByRole('heading', { exact: true, name: 'Welcome to Invoke' }).waitFor();+ await page.goto(`${origin}/#/app?project=${encodeURIComponent(projectId)}`, { waitUntil: 'domcontentloaded' });+ await page.getByRole('main', { exact: true, name: imported.name }).waitFor();+ await selectLayoutPreset(page, 'Automate', 'Workflow');++ const workflowName = () => page.getByRole('button', { name: /^Open this project's workflows\. Current workflow: / });+ const dialog = page.getByRole('dialog', { exact: true, name: 'Workflows' });+ const cards = dialog.locator('[data-workflow-card]');+ const openProjectWorkflows = async () => {+ await workflowName().click();+ await dialog.waitFor();+ await dialog.locator('[data-library-tab="project"]').waitFor();+ };+ const currentWorkflowName = async () =>+ (await workflowName().getAttribute('aria-label')).replace("Open this project's workflows. Current workflow: ", '');++ // The migrated project owns exactly its old graph, marked active; opening the local view fetched nothing.+ await openProjectWorkflows();+ assert.equal(await cards.count(), 1);+ await cards.first().locator('[data-active-workflow]').waitFor();+ assert.equal(+ (await workflowRequests()).slice(requestsBefore).some((entry) => entry.method === 'GET'),+ false+ );++ // Add workflow leads to the template tabs; the template becomes an independent copy in this project.+ await dialog.getByRole('button', { exact: true, name: 'Add workflow' }).click();+ await dialog.locator('[data-library-tab="default"]').waitFor();+ await dialog.getByText('Yours', { exact: true }).click();+ await dialog.locator('[data-library-tab="user"]').waitFor();+ await dialog.locator(`[data-workflow-card="${template.workflow_id}"]`).click();+ await dialog+ .locator(`[data-workflow-detail="${template.workflow_id}"]`)+ .getByRole('button', { exact: true, name: 'Open' })+ .click();+ await dialog.waitFor({ state: 'hidden' });+ assert.equal(await currentWorkflowName(), 'Journey Template');++ // Editing the copy: rename it through the local view. The library is not written.+ await openProjectWorkflows();+ assert.equal(await cards.count(), 2);+ await dialog.getByRole('button', { exact: true, name: 'More actions' }).click();+ await page.getByRole('menuitem', { name: /^Rename…/ }).click();+ const renameDialog = page.getByRole('dialog', { exact: true, name: 'Rename workflow' });+ await renameDialog.waitFor();+ await renameDialog.getByRole('textbox').fill('Journey Template edited');+ await renameDialog.getByRole('button', { exact: true, name: 'Rename' }).click();+ await renameDialog.waitFor({ state: 'hidden' });+ await page.keyboard.press('Escape');+ await dialog.waitFor({ state: 'hidden' });+ assert.equal(await currentWorkflowName(), 'Journey Template edited');++ // Switching to the other workflow and back keeps both documents.+ await openProjectWorkflows();+ await cards.filter({ hasText: 'Empty Workflow' }).dblclick();+ await dialog.waitFor({ state: 'hidden' });+ assert.equal(await currentWorkflowName(), 'Empty Workflow');+ await openProjectWorkflows();+ await cards.filter({ hasText: 'Journey Template edited' }).dblclick();+ await dialog.waitFor({ state: 'hidden' });+ assert.equal(await currentWorkflowName(), 'Journey Template edited');++ const libraryWritesSoFar = (await workflowRequests())+ .slice(requestsBefore)+ .filter((entry) => entry.method === 'PATCH' || entry.method === 'POST' || entry.method === 'DELETE');++ assert.deepEqual(libraryWritesSoFar, [], 'project edits must not write to the workflow library');++ // Save the edited copy under a new library name, without duplicating it beforehand.+ await page.getByRole('button', { exact: true, name: 'Save to library…' }).click();+ const saveDialog = page.getByRole('dialog', { exact: true, name: 'Save to library' });+ await saveDialog.waitFor();+ await saveDialog.getByRole('textbox').fill('Journey Saved');+ await saveDialog.getByRole('button', { exact: true, name: 'Save' }).click();+ await page.getByText('Workflow saved', { exact: true }).waitFor();++ const libraryWrites = (await workflowRequests())+ .slice(requestsBefore)+ .filter((entry) => entry.method === 'PATCH' || entry.method === 'POST' || entry.method === 'DELETE');++ assert.deepEqual(libraryWrites, [{ method: 'POST', path: '/api/v1/workflows/' }]);++ const library = await fetchJson('/api/v1/workflows/?categories=user&page=0&per_page=50');+ const saved = library.items.find((item) => item.name === 'Journey Saved');++ assert.ok(saved, 'the save created a new template');+ assert.equal(saved.revision, 1);+ assert.equal(library.items.find((item) => item.workflow_id === template.workflow_id)?.name, 'Journey Template');++ // The project keeps both workflows; the saved copy now targets the new template, and the name stayed the copy's.+ const record = await waitForSavedWorkflows(+ projectId,+ (candidate) =>+ candidate.data.workflows?.entries?.length === 2 &&+ candidate.data.workflows.entries[1].source?.libraryWorkflowId === saved.workflow_id,+ 'two workflows with the saved copy linked to its new template'+ );++ assert.equal(record.data.documentSchemaVersion, 3);+ assert.deepEqual(+ record.data.workflows.entries.map((entry) => entry.document.name),+ ['Empty Workflow', 'Journey Template edited']+ );+ assert.deepEqual(record.data.workflows.entries[1].source, { libraryWorkflowId: saved.workflow_id, revision: 1 });+ assert.equal(record.data.workflows.activeWorkflowId, record.data.workflows.entries[1].document.id);++ // Restart: both workflows and the active selection come back from the server.+ await page.reload({ waitUntil: 'domcontentloaded' });+ await page.getByRole('main', { exact: true, name: imported.name }).waitFor();+ await selectLayoutPreset(page, 'Automate', 'Workflow');+ assert.equal(await currentWorkflowName(), 'Journey Template edited');+ await openProjectWorkflows();+ assert.equal(await cards.count(), 2);+ await page.keyboard.press('Escape');+ await dialog.waitFor({ state: 'hidden' });++ await context.close();+ contexts.delete(context);+ assertNoBrowserErrors(errors);+};+/** Count missing board media separately from missing document references. */const runMissingBinaryImport = async ({ browser, contexts, entries, errors, tempDirectory }) => {const damagedPath = await writeArchiveWithout(diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxindex 1ac542bea6..ab1427c369 100644--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -1,5 +1,7 @@-import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workflow/react';+import type { WorkflowGraphPreviewPort, WorkflowProjectPersistence, WorkflowUiAdapter } from '@features/workflow/react';+import type { ProjectSyncSnapshot } from '@workbench/projects/syncStore';import type { WorkbenchPreferences } from '@workbench/settings/contracts';+import type { WorkbenchSnapshot } from '@workbench/workbenchStore';import type { ReactNode } from 'react';import { flushGenerateDrafts } from '@features/generation/react';@@ -25,6 +27,8 @@ import {resolveInvocationRouteInput,} from '@workbench/invocation';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 { useNotify } from '@workbench/useNotify';import { useOpenWorkbenchWidget } from '@workbench/useOpenWorkbenchWidget';@@ -49,6 +53,63 @@ const selectWorkflowPreferences = (preferences: WorkbenchPreferences) => ({workflowValidateConnections: preferences.workflowValidateConnections,});+/**+ * The active project's own persistence, read from the same sync service the conflict banner uses. "Saved" means+ * the server acknowledged the document; a pending push with browser recovery is still only local.+ */+const selectProjectPersistence = ([workbench, sync]: readonly [+ WorkbenchSnapshot,+ ProjectSyncSnapshot,+]): WorkflowProjectPersistence => {+ const projectId = workbench.activeProject.id;+ const info = sync.projects[projectId];+ const autosave = workbench.autosave;+ const isUnacknowledged = info === undefined || info.revision === null || info.isPendingPush;+ const status: WorkflowProjectPersistence['status'] = info?.conflict+ ? 'conflict'+ : info?.schemaRefusal+ ? 'error'+ : autosave.status === 'error'+ ? 'error'+ : autosave.status === 'saving'+ ? 'saving'+ : autosave.status === 'pending' || isUnacknowledged+ ? 'pending'+ : 'saved';++ return {+ error: autosave.error ?? null,+ hasLocalRecovery: sync.localDraftStatus === 'ok',+ lastSavedAt: status === 'saved' ? (autosave.lastSavedAt ?? sync.lastSyncedAt) : null,+ status,+ };+};++/** One source over two stores: a change in either republishes a fresh pair, an unchanged pair keeps identity. */+const createPairedSource = <A, B>(+ a: { getSnapshot: () => A; subscribe: (listener: () => void) => () => void },+ b: { getSnapshot: () => B; subscribe: (listener: () => void) => () => void }+) => {+ const cache = { pair: [a.getSnapshot(), b.getSnapshot()] as readonly [A, B] };++ return {+ getSnapshot: (): readonly [A, B] => {+ const next = [a.getSnapshot(), b.getSnapshot()] as const;++ if (next[0] !== cache.pair[0] || next[1] !== cache.pair[1]) {+ cache.pair = next;+ }++ return cache.pair;+ },+ subscribe: (listener: () => void) => {+ const unsubscribers = [a.subscribe(listener), b.subscribe(listener)];++ return () => unsubscribers.forEach((unsubscribe) => unsubscribe());+ },+ };+};+const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNode }) => {const routeInput = useActiveProjectSelector(selectInvocationRouteInput);const models = useModelsSelector((snapshot) => snapshot.models);@@ -106,10 +167,10 @@ const WorkflowGraphPreviewAdapterProvider = ({ children }: { children: ReactNodethrow error;}},- openDocumentInNewProject: (document, label) => {- // Create first: replace targets the active project.+ openDocumentInNewProject: (document, label, source) => {+ // Create first: the new project's blank placeholder is what the document takes over.commands.projects.create();- commands.workflows.replace(document, label);+ commands.workflows.add(document, { label, reusePlaceholder: true, source });openWidget('workflow');},openWorkflowEditor: () => {@@ -137,14 +198,30 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })() =>createProjectedExternalStore({source: store,- select: (snapshot) => ({- galleryValues: getProjectWidgetValues(snapshot.activeProject, 'gallery'),- id: snapshot.activeProject.id,- isWorkflowRunning: hasPendingWorkflowQueueItem(snapshot.activeProject.queue.items),- projectGraph: snapshot.activeProject.projectGraph,- workflowValues: getProjectWidgetValues(snapshot.activeProject, 'workflow'),- }),+ select: (snapshot) => {+ const activeWorkflow = getActiveProjectWorkflow(snapshot.activeProject);++ return {+ activeWorkflow,+ activeWorkflowId: activeWorkflow.document.id,+ galleryValues: getProjectWidgetValues(snapshot.activeProject, 'gallery'),+ id: snapshot.activeProject.id,+ isWorkflowRunning: hasPendingWorkflowQueueItem(snapshot.activeProject.queue.items),+ projectGraph: activeWorkflow.document,+ workflowValues: getProjectWidgetValues(snapshot.activeProject, 'workflow'),+ workflows: snapshot.activeProject.workflows.entries,+ };+ },+ isEqual: shallowEqual,+ }),+ [store]+ );+ const persistence = useMemo(+ () =>+ createProjectedExternalStore({isEqual: shallowEqual,+ select: selectProjectPersistence,+ source: createPairedSource(store, { getSnapshot: getProjectSyncSnapshot, subscribe: subscribeProjectSync }),}),[store]);@@ -171,14 +248,27 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })() => ({capabilities,commands: {- bindLibraryWorkflow: commands.workflows.bindLibraryWorkflow,+ addWorkflow: (document, options) => commands.workflows.add(document, options),+ createWorkflow: () => commands.workflows.create(),+ duplicateWorkflow: (workflowId, copyName) => commands.workflows.duplicate(workflowId, copyName),editGraph: commands.workflows.editGraph,redo: commands.workflows.redo,- replace: commands.workflows.replace,+ removeWorkflow: (workflowId) => commands.workflows.remove(workflowId),+ renameWorkflow: (workflowId, name) => {+ commands.workflows.rename(workflowId, name);+ },+ selectWorkflow: (workflowId) => commands.workflows.select(workflowId),+ setWorkflowSource: (target, source) =>+ commands.workflows.setSource(target.projectId, target.workflowId, source),undo: commands.workflows.undo,},- getProjectGraph: () => queries.getSnapshot().activeProject.projectGraph,- nodeExecution: { get: nodeExecutionStore.get, subscribe: nodeExecutionStore.subscribe },+ getProjectGraph: () => getActiveProjectWorkflow(queries.getSnapshot().activeProject).document,+ nodeExecution: {+ get: nodeExecutionStore.get,+ getOrigin: nodeExecutionStore.getOrigin,+ subscribe: nodeExecutionStore.subscribe,+ subscribeOrigin: nodeExecutionStore.subscribeOrigin,+ },notifications: { error: notify.error, info: notify.info, success: notify.success },// Lazy-load manager filter state to preserve editor bundle boundaries; seed it before hash navigation.openAddModels: (query) => {@@ -192,6 +282,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })measure: (name, start, source, end) => measureWorkbenchPerf(name, start, source, end),time: (name, source, callback) => timeWorkbenchPerf(name, source, callback),},+ persistence,preferences,project,registerModalHotkeyLayer: registerHotkeyModalLayer,@@ -200,7 +291,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })patchValues: (widgetId, values) => commands.widgets.patchValues(widgetId, values),},}),- [capabilities, commands, notify.error, notify.info, notify.success, preferences, project, queries]+ [capabilities, commands, notify.error, notify.info, notify.success, persistence, preferences, project, queries]);return (diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.test.tsindex 129ea4eeac..598cfd8037 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/api.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.test.ts@@ -4,15 +4,7 @@ const mocks = vi.hoisted(() => ({ apiFetch: vi.fn(), apiFetchJson: vi.fn() }));vi.mock('@platform/transport/http', () => ({ apiFetch: mocks.apiFetch, apiFetchJson: mocks.apiFetchJson }));-import {- deleteLibraryWorkflowThumbnail,- getLibraryWorkflowRecord,- getAllWorkflowTags,- getWorkflowTagCounts,- listLibraryWorkflows,- setLibraryWorkflowThumbnail,- touchLibraryWorkflowLastRunAt,-} from './api';+import { getAllWorkflowTags, getLibraryWorkflowRecord, getWorkflowTagCounts, listLibraryWorkflows } from './api';describe('workflow library api', () => {beforeEach(() => {@@ -20,43 +12,6 @@ describe('workflow library api', () => {mocks.apiFetchJson.mockReset().mockResolvedValue({});});- it('touches last_run_at with a PUT to the record-scoped endpoint', async () => {- await touchLibraryWorkflowLastRunAt('abc');-- expect(mocks.apiFetch).toHaveBeenCalledWith('/api/v1/workflows/i/abc/last_run_at', {- method: 'PUT',- signal: undefined,- });- });-- it('writes a thumbnail as multipart form data under the image field', async () => {- const blob = new Blob(['fake-image-bytes'], { type: 'image/png' });-- await setLibraryWorkflowThumbnail('abc', blob);-- expect(mocks.apiFetch).toHaveBeenCalledTimes(1);- const [path, init] = mocks.apiFetch.mock.calls[0] as [string, RequestInit];-- expect(path).toBe('/api/v1/workflows/i/abc/thumbnail');- expect(init.method).toBe('PUT');- expect(init.body).toBeInstanceOf(FormData);-- const uploaded = (init.body as FormData).get('image');-- expect(uploaded).toBeInstanceOf(Blob);- expect((uploaded as Blob).size).toBe(blob.size);- expect((uploaded as Blob).type).toBe(blob.type);- });-- it('deletes a thumbnail with a DELETE to the record-scoped endpoint', async () => {- await deleteLibraryWorkflowThumbnail('abc');-- expect(mocks.apiFetch).toHaveBeenCalledWith('/api/v1/workflows/i/abc/thumbnail', {- method: 'DELETE',- signal: undefined,- });- });-it('forwards repeated tags query params when listing workflows', async () => {mocks.apiFetchJson.mockResolvedValue({ items: [], page: 1, pages: 1, total: 0 });diff --git a/invokeai/frontend/webv2/src/features/workflow/data/api.ts b/invokeai/frontend/webv2/src/features/workflow/data/api.tsindex d74afe9543..bbfc841b2f 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/api.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/api.ts@@ -1,4 +1,4 @@-import { apiFetch, apiFetchJson } from '@platform/transport/http';+import { ApiError, apiFetch, apiFetchJson } from '@platform/transport/http';/** Round-trip library WorkflowV3 payloads through workflowJson when crossing the document boundary. */@@ -9,6 +9,8 @@ export interface WorkflowLibraryListItem {name: string;description: string;category: WorkflowLibraryCategory;+ /** Monotonic content revision; every write of the template's content increments it. */+ revision: number;user_id?: string;is_public?: boolean;call_saved_workflow_compatibility?: WorkflowCallCompatibility | null;@@ -99,40 +101,131 @@ export interface WorkflowRecordDTO extends WorkflowLibraryListItem {export const getLibraryWorkflowRecord = (workflowId: string, signal?: AbortSignal): Promise<WorkflowRecordDTO> =>apiFetchJson<WorkflowRecordDTO>(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, { signal });-/** Returns the stored workflow JSON, with the record id stamped in. */-export const getLibraryWorkflow = async (- workflowId: string,- signal?: AbortSignal-): Promise<Record<string, unknown>> => {- const record = await getLibraryWorkflowRecord(workflowId, signal);+/** A write the server refused for a structured reason; other failures stay `ApiError`s. */+export class WorkflowLibraryWriteRefusedError extends Error {+ readonly reason: 'revision-conflict' | 'id-conflict' | 'bundled' | 'forbidden' | 'missing' | 'invalid';+ /** The template's revision at refusal time, when the server reported one. */+ readonly currentRevision: number | null;++ constructor(+ reason: WorkflowLibraryWriteRefusedError['reason'],+ message: string,+ currentRevision: number | null = null+ ) {+ super(message);+ this.name = 'WorkflowLibraryWriteRefusedError';+ this.reason = reason;+ this.currentRevision = currentRevision;+ }+}++const parseErrorDetail = (error: ApiError): Record<string, unknown> | string | null => {+ try {+ const parsed = JSON.parse(error.message) as { detail?: unknown };++ return typeof parsed.detail === 'string' || (typeof parsed.detail === 'object' && parsed.detail !== null)+ ? (parsed.detail as Record<string, unknown> | string)+ : null;+ } catch {+ return null;+ }+};++/** Translate the workflow endpoints' 400/403/404/409 answers; anything else is not a refusal the caller can act on. */+export const toWorkflowLibraryWriteRefusal = (error: unknown): WorkflowLibraryWriteRefusedError | null => {+ if (error instanceof WorkflowLibraryWriteRefusedError) {+ return error;+ }++ if (!(error instanceof ApiError)) {+ return null;+ }++ const detail = parseErrorDetail(error);+ const message = typeof detail === 'string' ? detail : typeof detail?.message === 'string' ? detail.message : '';++ if (error.status === 409 && typeof detail === 'object' && detail?.reason === 'revision-conflict') {+ const current = detail.current_revision;++ return new WorkflowLibraryWriteRefusedError(+ 'revision-conflict',+ message,+ typeof current === 'number' ? current : null+ );+ }++ if (error.status === 409) {+ return new WorkflowLibraryWriteRefusedError('id-conflict', message);+ }++ if (error.status === 403) {+ return new WorkflowLibraryWriteRefusedError(/bundled/i.test(message) ? 'bundled' : 'forbidden', message);+ }++ if (error.status === 404) {+ return new WorkflowLibraryWriteRefusedError('missing', message);+ }++ if (error.status === 400 || error.status === 422) {+ return new WorkflowLibraryWriteRefusedError('invalid', message);+ }++ return null;+};- return { ...record.workflow, id: record.workflow_id };+const rethrowAsRefusal = (error: unknown): never => {+ throw toWorkflowLibraryWriteRefusal(error) ?? error;};-export const createLibraryWorkflow = async (+export interface CreateLibraryWorkflowOptions {+ /** A client-reserved UUID; resending it after a lost response returns the record the first send created. */+ reservedId?: string;+ signal?: AbortSignal;+}++export const createLibraryWorkflowRecord = async (workflow: Record<string, unknown>,- signal?: AbortSignal-): Promise<string> => {+ { reservedId, signal }: CreateLibraryWorkflowOptions = {}+): Promise<WorkflowRecordDTO> => {const { id: _id, ...workflowWithoutId } = workflow;- const record = await apiFetchJson<WorkflowRecordDTO>('/api/v1/workflows/', {- body: JSON.stringify({ workflow: workflowWithoutId }),- method: 'POST',- signal,- });- return record.workflow_id;+ try {+ return await apiFetchJson<WorkflowRecordDTO>('/api/v1/workflows/', {+ body: JSON.stringify({ workflow: workflowWithoutId, ...(reservedId ? { workflow_id: reservedId } : {}) }),+ method: 'POST',+ signal,+ });+ } catch (error) {+ return rethrowAsRefusal(error);+ }};+export const createLibraryWorkflow = async (workflow: Record<string, unknown>, signal?: AbortSignal): Promise<string> =>+ (await createLibraryWorkflowRecord(workflow, { signal })).workflow_id;++export interface UpdateLibraryWorkflowOptions {+ /** The revision the caller last observed; the server refuses the write once the template moved past it. */+ expectedRevision?: number;+ signal?: AbortSignal;+}+export const updateLibraryWorkflow = async (workflowId: string,workflow: Record<string, unknown>,- signal?: AbortSignal-): Promise<void> => {- await apiFetchJson(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, {- body: JSON.stringify({ workflow: { ...workflow, id: workflowId } }),- method: 'PATCH',- signal,- });+ { expectedRevision, signal }: UpdateLibraryWorkflowOptions = {}+): Promise<WorkflowRecordDTO> => {+ try {+ return await apiFetchJson<WorkflowRecordDTO>(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}`, {+ body: JSON.stringify({+ workflow: { ...workflow, id: workflowId },+ ...(expectedRevision === undefined ? {} : { expected_revision: expectedRevision }),+ }),+ method: 'PATCH',+ signal,+ });+ } catch (error) {+ return rethrowAsRefusal(error);+ }};export const deleteLibraryWorkflow = async (workflowId: string, signal?: AbortSignal): Promise<void> => {@@ -143,25 +236,6 @@ export const touchLibraryWorkflowOpenedAt = async (workflowId: string, signal?:await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/opened_at`, { method: 'PUT', signal });};-export const touchLibraryWorkflowLastRunAt = async (workflowId: string, signal?: AbortSignal): Promise<void> => {- await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/last_run_at`, { method: 'PUT', signal });-};--export const setLibraryWorkflowThumbnail = async (- workflowId: string,- image: Blob,- signal?: AbortSignal-): Promise<void> => {- const body = new FormData();- body.append('image', image);-- await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/thumbnail`, { body, method: 'PUT', signal });-};--export const deleteLibraryWorkflowThumbnail = async (workflowId: string, signal?: AbortSignal): Promise<void> => {- await apiFetch(`/api/v1/workflows/i/${encodeURIComponent(workflowId)}/thumbnail`, { method: 'DELETE', signal });-};-export interface GetWorkflowTagCountsParams {categories?: WorkflowLibraryCategory[];hasBeenOpened?: boolean;diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.tsindex c869aa85e5..5ba6dd8441 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryBrowseStore.test.ts@@ -69,6 +69,7 @@ const buildItem = (workflowId: string, overrides: Partial<WorkflowLibraryListItecategory: 'user',description: '',name: `Workflow ${workflowId}`,+ revision: 1,tags: 'lora, upscaling',updated_at: '2026-08-18T00:00:00Z',workflow_id: workflowId,diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.tsindex d20c07f76d..8892577d1d 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.test.ts@@ -5,7 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import type * as libraryCacheModule from './libraryCache';const api = vi.hoisted(() => ({- getLibraryWorkflow: vi.fn(),+ getLibraryWorkflowRecord: vi.fn(),listLibraryWorkflows: vi.fn(),}));@@ -18,7 +18,7 @@ const params = { category: 'user' as const, page: 1, perPage: 20 };beforeEach(async () => {vi.resetModules();- api.getLibraryWorkflow.mockReset();+ api.getLibraryWorkflowRecord.mockReset();api.listLibraryWorkflows.mockReset();cache = await import('./libraryCache');account = await import('@platform/state/accountLifecycle');@@ -28,7 +28,7 @@ describe('workflow library account ownership', () => {it('clears pages and payloads synchronously on account invalidation', async () => {account.accountLifecycle.activate('user-a');api.listLibraryWorkflows.mockResolvedValue({ items: [], page: 1, pages: 1, per_page: 20, total: 0 });- api.getLibraryWorkflow.mockResolvedValue({ id: 'workflow-a' });+ api.getLibraryWorkflowRecord.mockResolvedValue({ workflow: {}, workflow_id: 'workflow-a' });await cache.listLibraryWorkflowsCached(params);await cache.getLibraryWorkflowCached('workflow-a');@@ -37,9 +37,9 @@ describe('workflow library account ownership', () => {account.accountLifecycle.invalidate();expect(cache.getCachedWorkflowPage(params)).toBeNull();- api.getLibraryWorkflow.mockResolvedValue({ id: 'after-clear' });+ api.getLibraryWorkflowRecord.mockResolvedValue({ workflow: {}, workflow_id: 'after-clear' });await cache.getLibraryWorkflowCached('workflow-a');- expect(api.getLibraryWorkflow).toHaveBeenCalledTimes(2);+ expect(api.getLibraryWorkflowRecord).toHaveBeenCalledTimes(2);});it('rejects delayed page and payload completions from the prior epoch', async () => {@@ -51,7 +51,7 @@ describe('workflow library account ownership', () => {resolvePage = resolve;}));- api.getLibraryWorkflow.mockReturnValueOnce(+ api.getLibraryWorkflowRecord.mockReturnValueOnce(new Promise((resolve) => {resolveWorkflow = resolve;})@@ -60,7 +60,7 @@ describe('workflow library account ownership', () => {const oldPage = cache.listLibraryWorkflowsCached(params);const oldWorkflow = cache.getLibraryWorkflowCached('shared-id');const pageSignal = api.listLibraryWorkflows.mock.calls[0]?.[0]?.signal as AbortSignal;- const workflowSignal = api.getLibraryWorkflow.mock.calls[0]?.[1] as AbortSignal;+ const workflowSignal = api.getLibraryWorkflowRecord.mock.calls[0]?.[1] as AbortSignal;expect(pageSignal.aborted).toBe(false);expect(workflowSignal.aborted).toBe(false);@@ -70,14 +70,14 @@ describe('workflow library account ownership', () => {expect(pageSignal.aborted).toBe(true);expect(workflowSignal.aborted).toBe(true);resolvePage?.({ items: [{ workflow_id: 'a' }], page: 1, pages: 1, per_page: 20, total: 1 });- resolveWorkflow?.({ owner: 'a' });+ resolveWorkflow?.({ workflow: { owner: 'a' }, workflow_id: 'shared-id' });await expect(oldPage).rejects.toThrow('no longer active');await expect(oldWorkflow).rejects.toThrow('no longer active');expect(cache.getCachedWorkflowPage(params)).toBeNull();- api.getLibraryWorkflow.mockResolvedValueOnce({ owner: 'b' });- await expect(cache.getLibraryWorkflowCached('shared-id')).resolves.toEqual({ owner: 'b' });+ api.getLibraryWorkflowRecord.mockResolvedValueOnce({ workflow: { owner: 'b' }, workflow_id: 'shared-id' });+ await expect(cache.getLibraryWorkflowCached('shared-id')).resolves.toEqual({ id: 'shared-id', owner: 'b' });});});diff --git a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.tsindex 26d90fe24e..53da4d2154 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/libraryCache.ts@@ -4,7 +4,13 @@ import {registerAccountOwnedResource,} from '@platform/state/accountLifecycle';-import { getLibraryWorkflow, listLibraryWorkflows, type ListWorkflowsParams, type WorkflowLibraryPage } from './api';+import {+ getLibraryWorkflowRecord,+ listLibraryWorkflows,+ type ListWorkflowsParams,+ type WorkflowLibraryPage,+ type WorkflowRecordDTO,+} from './api';/*** Serve cached library pages immediately and revalidate; local mutations invalidate ordering and pagination@@ -12,7 +18,7 @@ import { getLibraryWorkflow, listLibraryWorkflows, type ListWorkflowsParams, typ*/const pageCache = new Map<string, WorkflowLibraryPage>();-const workflowCache = new Map<string, Record<string, unknown>>();+const recordCache = new Map<string, WorkflowRecordDTO>();/** `JSON.stringify` on a sorted copy avoids delimiter collisions between tag values. */const getTagsKey = (tags: string[] | undefined): string => JSON.stringify([...(tags ?? [])].sort());@@ -36,31 +42,41 @@ export const listLibraryWorkflowsCached = async (params: ListWorkflowsParams): Preturn result;};-/** Workflow payloads are immutable per save; cache hits skip the fetch entirely. */-export const getLibraryWorkflowCached = async (+/** A record is immutable per revision; a cache hit skips the fetch until a write invalidates it. */+export const getLibraryWorkflowRecordCached = async (workflowId: string,externalSignal?: AbortSignal-): Promise<Record<string, unknown>> => {+): Promise<WorkflowRecordDTO> => {const owner = captureAccountScope();const signal = externalSignal ? AbortSignal.any([externalSignal, owner.signal]) : owner.signal;signal.throwIfAborted();- const cached = workflowCache.get(workflowId);+ const cached = recordCache.get(workflowId);if (cached) {assertAccountScopeCurrent(owner);return cached;}- const result = await getLibraryWorkflow(workflowId, signal);+ const result = await getLibraryWorkflowRecord(workflowId, signal);assertAccountScopeCurrent(owner);signal.throwIfAborted();- workflowCache.set(workflowId, result);+ recordCache.set(workflowId, result);return result;};+/** The stored workflow JSON with the record id stamped in, from the record cache. */+export const getLibraryWorkflowCached = async (+ workflowId: string,+ externalSignal?: AbortSignal+): Promise<Record<string, unknown>> => {+ const record = await getLibraryWorkflowRecordCached(workflowId, externalSignal);++ return { ...record.workflow, id: record.workflow_id };+};+type WorkflowLibraryCacheInvalidationListener = (workflowId?: string) => void;const invalidationListeners = new Set<WorkflowLibraryCacheInvalidationListener>();@@ -73,7 +89,7 @@ export const onWorkflowLibraryCacheInvalidated = (listener: WorkflowLibraryCacheexport const invalidateWorkflowLibraryCache = (workflowId?: string): void => {pageCache.clear();- workflowCache.clear();+ recordCache.clear();for (const listener of invalidationListeners) {listener(workflowId);diff --git a/invokeai/frontend/webv2/src/features/workflow/data/publication.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/publication.test.tsnew file mode 100644index 0000000000..0da4e99011--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/data/publication.test.ts@@ -0,0 +1,239 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';+import { ApiError } from '@platform/transport/http';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { WorkflowRecordDTO } from './api';++import { WorkflowLibraryWriteRefusedError } from './api';+import { createWorkflowPublicationController, isWorkflowContentEquivalent } from './publication';++const record = (overrides: Partial<WorkflowRecordDTO> = {}): WorkflowRecordDTO => ({+ category: 'user',+ description: '',+ name: 'Template',+ revision: 1,+ workflow: { name: 'Template', nodes: [] },+ workflow_id: 'lib-1',+ ...overrides,+});++const workflow = { name: 'Template', nodes: [{ id: 'n1' }] };++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ let reject!: (reason: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });++ return { promise, reject, resolve };+};++describe('workflow publication controller', () => {+ let owner: AccountScope;+ const deps = {+ createRecord: vi.fn(),+ getRecord: vi.fn(),+ invalidateCache: vi.fn(),+ reserveId: vi.fn(() => 'reserved-1'),+ updateRecord: vi.fn(),+ };++ beforeEach(() => {+ accountLifecycle.activate('user-a');+ owner = captureAccountScope();+ deps.createRecord.mockReset();+ deps.getRecord.mockReset();+ deps.invalidateCache.mockReset();+ deps.reserveId.mockReset().mockReturnValue('reserved-1');+ deps.updateRecord.mockReset();+ });++ const request = (destination: Parameters<typeof controller.publish>[0]['destination']) => ({+ destination,+ owner,+ projectId: 'project-1',+ workflow,+ workflowId: 'wf-1',+ });+ const controller = createWorkflowPublicationController(deps);++ it('creates under a reserved id, names the template, and invalidates the library', async () => {+ deps.createRecord.mockResolvedValue(record({ name: 'Named', revision: 1, workflow_id: 'reserved-1' }));++ const result = await controller.publish(request({ kind: 'create', name: 'Named' }));++ expect(result).toEqual({+ kind: 'created',+ libraryWorkflowId: 'reserved-1',+ name: 'Named',+ revision: 1,+ status: 'published',+ });+ expect(deps.createRecord).toHaveBeenCalledWith(+ { ...workflow, name: 'Named' },+ { reservedId: 'reserved-1', signal: owner.signal }+ );+ expect(deps.invalidateCache).toHaveBeenCalledWith('reserved-1');+ });++ it('refuses to overlap a publication of the same workflow and reports when it is busy', async () => {+ const first = deferred<WorkflowRecordDTO>();+ deps.createRecord.mockReturnValueOnce(first.promise);++ const inFlight = controller.publish(request({ kind: 'create', name: 'A' }));++ expect(controller.isPublishing('project-1', 'wf-1')).toBe(true);+ await expect(controller.publish(request({ kind: 'create', name: 'B' }))).resolves.toEqual({ status: 'busy' });+ expect(deps.createRecord).toHaveBeenCalledTimes(1);++ first.resolve(record({ workflow_id: 'reserved-1' }));+ await inFlight;+ expect(controller.isPublishing('project-1', 'wf-1')).toBe(false);+ });++ it('keeps the reserved id and captured content across a retry of a lost creation', async () => {+ deps.createRecord.mockRejectedValueOnce(new TypeError('Failed to fetch'));+ deps.createRecord.mockResolvedValueOnce(record({ name: 'Named', workflow_id: 'reserved-1' }));++ const failed = await controller.publish(request({ kind: 'create', name: 'Named' }));++ expect(failed.status).toBe('failed');+ if (failed.status !== 'failed') {+ throw new Error('expected a failure');+ }++ await expect(failed.retry()).resolves.toMatchObject({ libraryWorkflowId: 'reserved-1', status: 'published' });+ expect(deps.createRecord.mock.calls.map((call) => call[1].reservedId)).toEqual(['reserved-1', 'reserved-1']);+ expect(deps.reserveId).toHaveBeenCalledTimes(1);+ });++ it("updates at the expected revision under the template's own name and reports the server revision back", async () => {+ deps.getRecord.mockResolvedValue(record({ name: 'Library name', revision: 2 }));+ deps.updateRecord.mockResolvedValue(record({ name: 'Library name', revision: 3 }));++ const result = await controller.publish(+ request({ expectedRevision: 2, kind: 'update', libraryWorkflowId: 'lib-1' })+ );++ expect(result).toEqual({+ kind: 'updated',+ libraryWorkflowId: 'lib-1',+ name: 'Library name',+ revision: 3,+ status: 'published',+ });+ expect(deps.updateRecord).toHaveBeenCalledWith(+ 'lib-1',+ { ...workflow, name: 'Library name' },+ { expectedRevision: 2, signal: owner.signal }+ );+ expect(deps.invalidateCache).toHaveBeenCalledWith('lib-1');+ });++ it('reports a conflict from the record read alone, without sending', async () => {+ deps.getRecord.mockResolvedValue(record({ revision: 5 }));++ await expect(+ controller.publish(request({ expectedRevision: 2, kind: 'update', libraryWorkflowId: 'lib-1' }))+ ).resolves.toEqual({ currentRevision: 5, libraryWorkflowId: 'lib-1', status: 'conflict' });+ expect(deps.updateRecord).not.toHaveBeenCalled();+ });++ it('maps server refusals to conflict, unavailable, and invalid outcomes', async () => {+ deps.getRecord.mockResolvedValue(record({ revision: 2 }));+ deps.updateRecord.mockRejectedValueOnce(new WorkflowLibraryWriteRefusedError('revision-conflict', 'stale', 7));+ await expect(+ controller.publish(request({ expectedRevision: 2, kind: 'update', libraryWorkflowId: 'lib-1' }))+ ).resolves.toEqual({+ currentRevision: 7,+ libraryWorkflowId: 'lib-1',+ status: 'conflict',+ });++ deps.getRecord.mockRejectedValueOnce(new WorkflowLibraryWriteRefusedError('bundled', 'read-only'));+ await expect(+ controller.publish(request({ expectedRevision: 2, kind: 'update', libraryWorkflowId: 'lib-1' }))+ ).resolves.toEqual({+ libraryWorkflowId: 'lib-1',+ reason: 'bundled',+ status: 'unavailable',+ });++ deps.getRecord.mockRejectedValueOnce(new ApiError(JSON.stringify({ detail: 'nope' }), 404));+ await expect(+ controller.publish(request({ expectedRevision: 2, kind: 'update', libraryWorkflowId: 'lib-1' }))+ ).resolves.toEqual({+ libraryWorkflowId: 'lib-1',+ reason: 'missing',+ status: 'unavailable',+ });++ deps.createRecord.mockRejectedValueOnce(new WorkflowLibraryWriteRefusedError('invalid', 'bad graph'));+ await expect(controller.publish(request({ kind: 'create', name: 'X' }))).resolves.toEqual({+ message: 'bad graph',+ status: 'invalid',+ });+ });++ it('reconciles a lost update against the record before resending', async () => {+ deps.getRecord.mockResolvedValueOnce(record({ revision: 2 }));+ deps.updateRecord.mockRejectedValueOnce(new TypeError('Failed to fetch'));++ const failed = await controller.publish(+ request({ expectedRevision: 2, kind: 'update', libraryWorkflowId: 'lib-1' })+ );+ if (failed.status !== 'failed') {+ throw new Error('expected a failure');+ }++ // The write landed: the record moved exactly one revision on and holds this content.+ deps.getRecord.mockResolvedValueOnce(record({ revision: 3, workflow }));+ await expect(failed.retry()).resolves.toMatchObject({ kind: 'updated', revision: 3, status: 'published' });+ expect(deps.updateRecord).toHaveBeenCalledTimes(1);++ // The write never landed: resend at the same revision.+ deps.getRecord.mockResolvedValueOnce(record({ revision: 2 }));+ deps.updateRecord.mockResolvedValueOnce(record({ revision: 3 }));+ await expect(failed.retry()).resolves.toMatchObject({ kind: 'updated', status: 'published' });+ expect(deps.updateRecord).toHaveBeenCalledTimes(2);++ // Someone else moved it: never overwrite.+ deps.getRecord.mockResolvedValueOnce(record({ revision: 3, workflow: { name: 'Theirs', nodes: [] } }));+ await expect(failed.retry()).resolves.toEqual({+ currentRevision: 3,+ libraryWorkflowId: 'lib-1',+ status: 'conflict',+ });+ expect(deps.updateRecord).toHaveBeenCalledTimes(2);+ });++ it('reports cancellation instead of a result once the account changes', async () => {+ const pending = deferred<WorkflowRecordDTO>();+ deps.createRecord.mockReturnValueOnce(pending.promise);++ const inFlight = controller.publish(request({ kind: 'create', name: 'A' }));++ accountLifecycle.invalidate();+ accountLifecycle.activate('user-b');+ pending.resolve(record());++ await expect(inFlight).resolves.toEqual({ status: 'cancelled' });+ expect(deps.invalidateCache).not.toHaveBeenCalled();+ });+});++describe('isWorkflowContentEquivalent', () => {+ it('ignores key order and fields the server does not keep', () => {+ expect(+ isWorkflowContentEquivalent(+ { id: 'x', name: 'A', nodes: [{ b: 1, a: 2 }], meta: { version: '3.0.0', category: 'user' } },+ { name: 'A', nodes: [{ a: 2, b: 1 }], meta: { category: 'user', version: '3.0.0' }, opened_at: 'now' }+ )+ ).toBe(true);+ expect(isWorkflowContentEquivalent({ name: 'A', nodes: [] }, { name: 'B', nodes: [] })).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/data/publication.ts b/invokeai/frontend/webv2/src/features/workflow/data/publication.tsnew file mode 100644index 0000000000..ba00852a52--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/data/publication.ts@@ -0,0 +1,297 @@+import type { AccountScope } from '@platform/state/accountLifecycle';++import { createUuid } from '@platform/browser/randomUuid';+import { isAccountScopeCurrent } from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';++import type { WorkflowLibraryWriteRefusedError, WorkflowRecordDTO } from './api';++import {+ createLibraryWorkflowRecord,+ getLibraryWorkflowRecord,+ toWorkflowLibraryWriteRefusal,+ updateLibraryWorkflow,+} from './api';+import { invalidateWorkflowLibraryCache } from './libraryCache';++/**+ * The one way a project workflow reaches the library. A publication captures everything it needs up front, refuses+ * to overlap another for the same workflow, keeps its captured request and reserved id across retryable failures,+ * and reconciles an ambiguous answer against the destination record before sending again.+ */++export type WorkflowPublicationDestination =+ | { kind: 'create'; name: string }+ | { kind: 'update'; libraryWorkflowId: string; expectedRevision: number };++export interface WorkflowPublicationRequest {+ owner: AccountScope;+ projectId: string;+ workflowId: string;+ /** The serialized document as it stood when the user confirmed; later edits are not part of this publication. */+ workflow: Record<string, unknown>;+ destination: WorkflowPublicationDestination;+}++export type WorkflowPublicationResult =+ | { status: 'published'; kind: 'created' | 'updated'; libraryWorkflowId: string; revision: number; name: string }+ /** The template moved past the expected revision, or its revision was never known. */+ | { status: 'conflict'; libraryWorkflowId: string; currentRevision: number | null }+ /** The destination cannot be written: it is gone, someone else's, or bundled. Saving as new still works. */+ | { status: 'unavailable'; libraryWorkflowId: string; reason: 'missing' | 'forbidden' | 'bundled' }+ /** The server rejected the content itself. */+ | { status: 'invalid'; message: string }+ /** Nothing definitive came back; `retry` resends the same captured request under the same reserved id. */+ | { status: 'failed'; message: string; retry: () => Promise<WorkflowPublicationResult> }+ /** The account changed underneath the publication; nothing more will be reported. */+ | { status: 'cancelled' }+ /** Another publication of the same workflow is still running. */+ | { status: 'busy' };++export interface WorkflowPublicationDeps {+ createRecord: typeof createLibraryWorkflowRecord;+ getRecord: typeof getLibraryWorkflowRecord;+ invalidateCache: typeof invalidateWorkflowLibraryCache;+ reserveId: () => string;+ updateRecord: typeof updateLibraryWorkflow;+}++const PRODUCTION_DEPS: WorkflowPublicationDeps = {+ createRecord: createLibraryWorkflowRecord,+ getRecord: getLibraryWorkflowRecord,+ invalidateCache: invalidateWorkflowLibraryCache,+ reserveId: createUuid,+ updateRecord: updateLibraryWorkflow,+};++/** The fields the server keeps; anything else a payload carries is ignored on both sides. */+const CONTENT_KEYS = [+ 'author',+ 'contact',+ 'description',+ 'edges',+ 'exposedFields',+ 'form',+ 'meta',+ 'name',+ 'nodes',+ 'notes',+ 'tags',+ 'version',+] as const;++const canonicalize = (value: unknown): unknown => {+ if (Array.isArray(value)) {+ return value.map(canonicalize);+ }++ if (typeof value === 'object' && value !== null) {+ return Object.fromEntries(+ Object.keys(value)+ .sort()+ .map((key) => [key, canonicalize((value as Record<string, unknown>)[key])])+ );+ }++ return value;+};++/** Whether a stored record holds the submitted content, ignoring key order and the record's own id. */+export const isWorkflowContentEquivalent = (+ submitted: Record<string, unknown>,+ stored: Record<string, unknown>+): boolean =>+ CONTENT_KEYS.every(+ (key) => JSON.stringify(canonicalize(submitted[key] ?? null)) === JSON.stringify(canonicalize(stored[key] ?? null))+ );++const toPublished = (+ kind: 'created' | 'updated',+ record: WorkflowRecordDTO+): Extract<WorkflowPublicationResult, { status: 'published' }> => ({+ kind,+ libraryWorkflowId: record.workflow_id,+ name: record.name,+ revision: record.revision,+ status: 'published',+});++const toRefusalResult = (+ refusal: WorkflowLibraryWriteRefusedError,+ libraryWorkflowId: string+): WorkflowPublicationResult => {+ switch (refusal.reason) {+ case 'revision-conflict':+ return { currentRevision: refusal.currentRevision, libraryWorkflowId, status: 'conflict' };+ case 'missing':+ case 'forbidden':+ case 'bundled':+ return { libraryWorkflowId, reason: refusal.reason, status: 'unavailable' };+ case 'id-conflict':+ case 'invalid':+ return { message: refusal.message, status: 'invalid' };+ }+};++export interface WorkflowPublicationController {+ publish(request: WorkflowPublicationRequest): Promise<WorkflowPublicationResult>;+ /** True while a publication of that workflow is in flight. */+ isPublishing(projectId: string, workflowId: string): boolean;+ /** Advances whenever the in-flight set changes; a stable snapshot for `useSyncExternalStore`. */+ getVersion(): number;+ subscribe(listener: () => void): () => void;+}++export const createWorkflowPublicationController = (+ overrides: Partial<WorkflowPublicationDeps> = {}+): WorkflowPublicationController => {+ const deps = { ...PRODUCTION_DEPS, ...overrides };+ const inFlight = new Set<string>();+ const listeners = new Set<() => void>();+ let version = 0;+ const keyOf = (projectId: string, workflowId: string): string => `${projectId}\u0000${workflowId}`;+ const notify = (): void => {+ version += 1;+ listeners.forEach((listener) => listener());+ };++ const settle = async (+ request: WorkflowPublicationRequest,+ send: () => Promise<WorkflowPublicationResult>+ ): Promise<WorkflowPublicationResult> => {+ const key = keyOf(request.projectId, request.workflowId);++ if (inFlight.has(key)) {+ return { status: 'busy' };+ }++ inFlight.add(key);+ notify();++ try {+ if (!isAccountScopeCurrent(request.owner)) {+ return { status: 'cancelled' };+ }++ const result = await send();++ if (!isAccountScopeCurrent(request.owner)) {+ return { status: 'cancelled' };+ }++ if (result.status === 'published') {+ deps.invalidateCache(result.libraryWorkflowId);+ }++ return result;+ } finally {+ inFlight.delete(key);+ notify();+ }+ };++ /** A failure that is not a server refusal: the request may or may not have landed. */+ const toFailure = (+ error: unknown,+ request: WorkflowPublicationRequest,+ retry: () => Promise<WorkflowPublicationResult>+ ): WorkflowPublicationResult => {+ if (!isAccountScopeCurrent(request.owner)) {+ return { status: 'cancelled' };+ }++ return { message: getApiErrorMessage(error, 'The library did not answer.'), retry, status: 'failed' };+ };++ const create = (request: WorkflowPublicationRequest, name: string, reservedId: string) => {+ const attempt = (): Promise<WorkflowPublicationResult> =>+ settle(request, async () => {+ try {+ // The server matches a resend against the record the first send made, so a lost response never+ // creates a second template.+ const record = await deps.createRecord(+ { ...request.workflow, name },+ { reservedId, signal: request.owner.signal }+ );++ return toPublished('created', record);+ } catch (error) {+ const refusal = toWorkflowLibraryWriteRefusal(error);++ return refusal ? toRefusalResult(refusal, reservedId) : toFailure(error, request, attempt);+ }+ });++ return attempt();+ };++ const update = (request: WorkflowPublicationRequest, libraryWorkflowId: string, expectedRevision: number) => {+ // The template keeps its own name: an update replaces its content, and the project workflow's name stays+ // with the project. The content is fixed by the first read so a resend carries exactly what was sent before.+ let content: Record<string, unknown> | null = null;++ const send = async (record: WorkflowRecordDTO): Promise<WorkflowPublicationResult> => {+ content ??= { ...request.workflow, name: record.name };++ try {+ const updated = await deps.updateRecord(libraryWorkflowId, content, {+ expectedRevision,+ signal: request.owner.signal,+ });++ return toPublished('updated', updated);+ } catch (error) {+ const refusal = toWorkflowLibraryWriteRefusal(error);++ return refusal ? toRefusalResult(refusal, libraryWorkflowId) : toFailure(error, request, attempt);+ }+ };++ /**+ * Every attempt starts from the live record. The first read supplies the template's name; a read before a+ * resend tells whether the lost answer applied the write (the revision advanced by exactly one to this+ * content), left it untouched, or whether someone else moved the template.+ */+ const attempt = (): Promise<WorkflowPublicationResult> =>+ settle(request, async () => {+ let record: WorkflowRecordDTO;++ try {+ record = await deps.getRecord(libraryWorkflowId, request.owner.signal);+ } catch (error) {+ const refusal = toWorkflowLibraryWriteRefusal(error);++ return refusal ? toRefusalResult(refusal, libraryWorkflowId) : toFailure(error, request, attempt);+ }++ if (record.revision === expectedRevision) {+ return send(record);+ }++ if (+ content !== null &&+ record.revision === expectedRevision + 1 &&+ isWorkflowContentEquivalent(content, record.workflow)+ ) {+ return toPublished('updated', record);+ }++ return { currentRevision: record.revision, libraryWorkflowId, status: 'conflict' };+ });++ return attempt();+ };++ return {+ getVersion: () => version,+ isPublishing: (projectId, workflowId) => inFlight.has(keyOf(projectId, workflowId)),+ publish: (request) =>+ request.destination.kind === 'create'+ ? create(request, request.destination.name, deps.reserveId())+ : update(request, request.destination.libraryWorkflowId, request.destination.expectedRevision),+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+};diff --git a/invokeai/frontend/webv2/src/features/workflow/data/runCapture.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/runCapture.test.tsdeleted file mode 100644index 968527092b..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/data/runCapture.test.ts+++ /dev/null@@ -1,220 +0,0 @@-import type { QueueWorkflowRunCompletedEvent } from '@features/queue/contracts';--import { accountLifecycle } from '@platform/state/accountLifecycle';-import { describe, expect, it, vi } from 'vitest';--import type { RunCaptureDeps } from './runCapture';--import { createWorkflowRunCaptureSink } from './runCapture';--const createDeferred = <T>() => {- let resolve!: (value: T) => void;- const promise = new Promise<T>((resolvePromise) => {- resolve = resolvePromise;- });-- return { promise, resolve };-};--const createEvent = (overrides?: Partial<QueueWorkflowRunCompletedEvent>): QueueWorkflowRunCompletedEvent => ({- imageNames: ['first.png', 'last.png'],- libraryWorkflowId: 'workflow-1',- projectId: 'project-1',- queueItemId: 'queue-item-1',- ...overrides,-});--const userWorkflow = (workflowId: string) => ({ id: workflowId, meta: { category: 'user', version: '3.0.0' } });--/** The sink is fire-and-forget, so tests wait for its detached chain to settle. */-const settle = async (): Promise<void> => {- for (let tick = 0; tick < 5; tick += 1) {- await new Promise<void>((resolve) => {- setTimeout(resolve, 0);- });- }-};--/** `calls` is a parameter so a test can seed it into its own dep overrides. */-const createHarness = (overrides?: Partial<RunCaptureDeps>, calls: string[] = []) => {- const blob = new Blob(['thumbnail'], { type: 'image/png' });- const deps: RunCaptureDeps = {- fetchThumbnailBlob: vi.fn((imageName: string) => {- calls.push(`fetch:${imageName}`);- return Promise.resolve(blob);- }),- getWorkflow: vi.fn((workflowId: string) => {- calls.push(`getWorkflow:${workflowId}`);- return Promise.resolve(userWorkflow(workflowId));- }),- invalidateCache: vi.fn(() => {- calls.push('invalidate');- }),- setThumbnail: vi.fn((workflowId: string) => {- calls.push(`setThumbnail:${workflowId}`);- return Promise.resolve();- }),- touchLastRunAt: vi.fn((workflowId: string) => {- calls.push(`touchLastRunAt:${workflowId}`);- return Promise.resolve();- }),- ...overrides,- };-- return { blob, calls, deps, sink: createWorkflowRunCaptureSink(deps) };-};--describe('workflow run capture sink', () => {- it('uploads the last result thumbnail, stamps last_run_at, then invalidates the library', async () => {- const { blob, calls, deps, sink } = createHarness();-- sink.onWorkflowRunCompleted(createEvent());- await settle();-- expect(calls).toEqual([- 'getWorkflow:workflow-1',- // The run's LAST image is the workflow's cover, not an early intermediate.- 'fetch:last.png',- 'setThumbnail:workflow-1',- 'touchLastRunAt:workflow-1',- 'invalidate',- ]);- expect(deps.setThumbnail).toHaveBeenCalledWith('workflow-1', blob, expect.any(AbortSignal));- });-- it('never touches a default-category workflow, which the account does not own', async () => {- const { calls, deps, sink } = createHarness({- getWorkflow: vi.fn().mockResolvedValue({ id: 'workflow-1', meta: { category: 'default', version: '3.0.0' } }),- });-- sink.onWorkflowRunCompleted(createEvent());- await settle();-- expect(deps.getWorkflow).toHaveBeenCalledWith('workflow-1', expect.any(AbortSignal));- // Nothing after the category check ran: no download, no upload, no stamp.- expect(calls).toEqual([]);- });-- it('serializes captures per workflow and keeps only the latest queued run', async () => {- const gate = createDeferred<Blob>();- const blob = new Blob(['thumbnail'], { type: 'image/png' });- const calls: string[] = [];- let fetchCount = 0;- const { sink } = createHarness(- {- fetchThumbnailBlob: vi.fn((imageName: string) => {- calls.push(`fetch:${imageName}`);- fetchCount += 1;- // Hold the first capture open so the next two events queue behind it.- return fetchCount === 1 ? gate.promise : Promise.resolve(blob);- }),- },- calls- );-- sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-1.png'] }));- await settle();- sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-2.png'] }));- sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-3.png'] }));- await settle();-- // Nothing from the queued runs ran while the first capture was in flight.- expect(calls).toEqual(['getWorkflow:workflow-1', 'fetch:run-1.png']);-- gate.resolve(blob);- await settle();-- // run-2 was superseded by run-3 before it ever started.- expect(calls).toEqual([- 'getWorkflow:workflow-1',- 'fetch:run-1.png',- 'setThumbnail:workflow-1',- 'touchLastRunAt:workflow-1',- 'invalidate',- 'getWorkflow:workflow-1',- 'fetch:run-3.png',- 'setThumbnail:workflow-1',- 'touchLastRunAt:workflow-1',- 'invalidate',- ]);- });-- it('stops silently when the thumbnail fetch fails, leaving last_run_at untouched', async () => {- const { calls, deps, sink } = createHarness({- fetchThumbnailBlob: vi.fn().mockRejectedValue(new Error('404 thumbnail')),- });-- sink.onWorkflowRunCompleted(createEvent());- await settle();-- expect(calls).toEqual(['getWorkflow:workflow-1']);- expect(deps.setThumbnail).not.toHaveBeenCalled();- expect(deps.touchLastRunAt).not.toHaveBeenCalled();- expect(deps.invalidateCache).not.toHaveBeenCalled();- });-- it('stops silently when the thumbnail upload fails, leaving last_run_at untouched', async () => {- const { deps, sink } = createHarness({- setThumbnail: vi.fn().mockRejectedValue(new Error('413 payload too large')),- });-- sink.onWorkflowRunCompleted(createEvent());- await settle();-- expect(deps.touchLastRunAt).not.toHaveBeenCalled();- expect(deps.invalidateCache).not.toHaveBeenCalled();- });-- it('keeps draining queued runs after one of them fails', async () => {- const { deps, sink } = createHarness({- getWorkflow: vi.fn().mockRejectedValueOnce(new Error('offline')).mockResolvedValue(userWorkflow('workflow-1')),- });-- sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-1.png'] }));- sink.onWorkflowRunCompleted(createEvent({ imageNames: ['run-2.png'] }));- await settle();-- expect(deps.setThumbnail).toHaveBeenCalledTimes(1);- expect(deps.fetchThumbnailBlob).toHaveBeenCalledWith('run-2.png', expect.any(AbortSignal));- });-- it('ignores an event that carries no result images', async () => {- const { calls, sink } = createHarness();-- sink.onWorkflowRunCompleted(createEvent({ imageNames: [] }));- await settle();-- expect(calls).toEqual([]);- });-- it('captures concurrently when the runs belong to different library records', async () => {- const gate = createDeferred<Blob>();- const blob = new Blob(['thumbnail'], { type: 'image/png' });- const { deps, sink } = createHarness({- fetchThumbnailBlob: vi.fn((imageName: string) => (imageName === 'a.png' ? gate.promise : Promise.resolve(blob))),- });-- sink.onWorkflowRunCompleted(createEvent({ imageNames: ['a.png'], libraryWorkflowId: 'workflow-a' }));- sink.onWorkflowRunCompleted(createEvent({ imageNames: ['b.png'], libraryWorkflowId: 'workflow-b' }));- await settle();-- // workflow-b never waits behind workflow-a's stalled fetch.- expect(deps.setThumbnail).toHaveBeenCalledWith('workflow-b', blob, expect.any(AbortSignal));- gate.resolve(blob);- await settle();- });-- it('drops a capture whose account scope expired mid-flight', async () => {- const gate = createDeferred<Record<string, unknown>>();- const { deps, sink } = createHarness({ getWorkflow: vi.fn(() => gate.promise) });-- sink.onWorkflowRunCompleted(createEvent());- await settle();- accountLifecycle.invalidate();- gate.resolve(userWorkflow('workflow-1'));- await settle();-- expect(deps.setThumbnail).not.toHaveBeenCalled();- expect(deps.touchLastRunAt).not.toHaveBeenCalled();- });-});diff --git a/invokeai/frontend/webv2/src/features/workflow/data/runCapture.ts b/invokeai/frontend/webv2/src/features/workflow/data/runCapture.tsdeleted file mode 100644index b3c0c4421c..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/data/runCapture.ts+++ /dev/null@@ -1,133 +0,0 @@-import type { QueueWorkflowRunCompletedEvent, QueueWorkflowRunSink } from '@features/queue/contracts';-import type { AccountScope } from '@platform/state/accountLifecycle';--import { captureAccountScope, isAccountScopeCurrent } from '@platform/state/accountLifecycle';--import { setLibraryWorkflowThumbnail, touchLibraryWorkflowLastRunAt } from './api';-import { getLibraryWorkflowCached, invalidateWorkflowLibraryCache } from './libraryCache';--/**- * Best-effort capture decorates successful runs with cover/last-run metadata; failures stay silent and must not- * affect run success.- */--export interface RunCaptureDeps {- /** Downloads the gallery thumbnail bytes for one result image. */- fetchThumbnailBlob(imageName: string, signal: AbortSignal): Promise<Blob>;- getWorkflow(workflowId: string, signal?: AbortSignal): Promise<Record<string, unknown>>;- invalidateCache(): void;- setThumbnail(workflowId: string, image: Blob, signal?: AbortSignal): Promise<void>;- touchLastRunAt(workflowId: string, signal?: AbortSignal): Promise<void>;-}--/**- * Load gallery URL ownership lazily to avoid its UI dependencies in Queue bundles; fetch media with the existing- * path-scoped cookie.- */-const fetchThumbnailBlob = async (imageName: string, signal: AbortSignal): Promise<Blob> => {- const { galleryImageUrls } = await import('@features/gallery/utility');- const response = await fetch(galleryImageUrls.thumbnail(imageName), { credentials: 'same-origin', signal });-- if (!response.ok) {- throw new Error(`Thumbnail request for ${imageName} failed with status ${response.status}.`);- }-- return response.blob();-};--const PRODUCTION_DEPS: RunCaptureDeps = {- fetchThumbnailBlob,- getWorkflow: getLibraryWorkflowCached,- invalidateCache: invalidateWorkflowLibraryCache,- setThumbnail: setLibraryWorkflowThumbnail,- touchLastRunAt: touchLibraryWorkflowLastRunAt,-};--/**- * Bundled defaults ship in `meta.category: 'default'` and are read-only for the- * account, so a run of one must not write a thumbnail or a last-run stamp.- */-const isUserWorkflow = (workflow: Record<string, unknown>): boolean => {- const meta = workflow.meta;-- return typeof meta === 'object' && meta !== null && (meta as { category?: unknown }).category === 'user';-};--interface PendingCapture {- event: QueueWorkflowRunCompletedEvent;- /** The scope the run settled under; a later account owns none of its writes. */- owner: AccountScope;-}--export const createWorkflowRunCaptureSink = (overrides?: Partial<RunCaptureDeps>): QueueWorkflowRunSink => {- const deps: RunCaptureDeps = { ...PRODUCTION_DEPS, ...overrides };- // Serialize captures per library record while allowing different workflows to upload independently.- const draining = new Map<string, Promise<void>>();- // At most one queued capture per record: while one is uploading, a newer run- // supersedes any other run still waiting, because only the newest output- // should end up as the cover.- const pending = new Map<string, PendingCapture>();-- const capture = async ({ event, owner }: PendingCapture): Promise<void> => {- const { imageNames, libraryWorkflowId } = event;- const imageName = imageNames[imageNames.length - 1];-- if (!imageName || !isAccountScopeCurrent(owner)) {- return;- }-- const workflow = await deps.getWorkflow(libraryWorkflowId, owner.signal);-- if (!isAccountScopeCurrent(owner) || !isUserWorkflow(workflow)) {- return;- }-- const blob = await deps.fetchThumbnailBlob(imageName, owner.signal);-- if (!isAccountScopeCurrent(owner)) {- return;- }-- await deps.setThumbnail(libraryWorkflowId, blob, owner.signal);-- if (!isAccountScopeCurrent(owner)) {- return;- }-- // Ordered after the upload so a library row never advertises a fresh run- // against a stale cover.- await deps.touchLastRunAt(libraryWorkflowId, owner.signal);-- if (isAccountScopeCurrent(owner)) {- deps.invalidateCache();- }- };-- const drain = async (libraryWorkflowId: string): Promise<void> => {- for (let next = pending.get(libraryWorkflowId); next !== undefined; next = pending.get(libraryWorkflowId)) {- pending.delete(libraryWorkflowId);-- try {- await capture(next);- } catch {- // A failed capture must not prevent later completed runs from trying again.- }- }-- draining.delete(libraryWorkflowId);- };-- return {- onWorkflowRunCompleted: (event) => {- if (event.imageNames.length === 0) {- return;- }-- pending.set(event.libraryWorkflowId, { event, owner: captureAccountScope() });-- if (!draining.has(event.libraryWorkflowId)) {- draining.set(event.libraryWorkflowId, drain(event.libraryWorkflowId));- }- },- };-};diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.test.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.test.tsindex 0718a18f08..facf0161f9 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.test.ts@@ -16,6 +16,7 @@ const workflows = [description: 'A landscape starter',is_public: false,name: 'Alpha Workflow',+ revision: 1,tags: 'landscape,starter',workflow_id: 'workflow-a',},@@ -29,6 +30,7 @@ const workflows = [description: '',is_public: true,name: 'Beta Workflow',+ revision: 3,workflow_id: 'workflow-b',},];diff --git a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.ts b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.tsindex 7a1082e8fd..4411d8d23e 100644--- a/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.ts+++ b/invokeai/frontend/webv2/src/features/workflow/data/savedWorkflowFieldUtils.ts@@ -158,6 +158,7 @@ export const getSavedWorkflowListItemFromRecord = (record: WorkflowRecordDTO): Wis_public: record.is_public,name: record.name,opened_at: record.opened_at,+ revision: record.revision,tags: typeof record.workflow.tags === 'string' ? record.workflow.tags : record.tags,thumbnail_url: record.thumbnail_url,updated_at: record.updated_at,diff --git a/invokeai/frontend/webv2/src/features/workflow/queries.ts b/invokeai/frontend/webv2/src/features/workflow/queries.tsindex 77ac013aeb..b8fa061ed8 100644--- a/invokeai/frontend/webv2/src/features/workflow/queries.ts+++ b/invokeai/frontend/webv2/src/features/workflow/queries.ts@@ -1,4 +1,4 @@export * from './data/api';export * from './data/libraryCache';export * from './data/savedWorkflowQueries';-export { createWorkflowRunCaptureSink, type RunCaptureDeps } from './data/runCapture';+export * from './data/publication';diff --git a/invokeai/frontend/webv2/src/features/workflow/react.ts b/invokeai/frontend/webv2/src/features/workflow/react.tsindex c768921064..e1e79f93f5 100644--- a/invokeai/frontend/webv2/src/features/workflow/react.ts+++ b/invokeai/frontend/webv2/src/features/workflow/react.ts@@ -5,4 +5,9 @@ export {requestWorkflowDocumentLoad,} from './ui/workflowUiStore';export { WorkflowGraphPreviewProvider, WorkflowUiProvider } from './ui/WorkflowUiContext';-export type { WorkflowGraphPreviewPort, WorkflowReadPort, WorkflowUiAdapter } from './ui/WorkflowUiContext';+export type {+ WorkflowGraphPreviewPort,+ WorkflowProjectPersistence,+ WorkflowReadPort,+ WorkflowUiAdapter,+} from './ui/WorkflowUiContext';diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsxindex fba20eeaf5..8f38c41a7f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/PendingLibraryWorkflowLoader.tsx@@ -1,9 +1,9 @@-import { getLibraryWorkflow, touchLibraryWorkflowOpenedAt } from '@features/workflow/data/api';+import { getLibraryWorkflowRecord, touchLibraryWorkflowOpenedAt } from '@features/workflow/data/api';import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';import { requestWorkflowFitView } from '@features/workflow/ui/editor/flowInstanceStore';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';-import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';-import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';+import { useWorkflowNotifications, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { parseWorkflowJson } from '@features/workflow/utility';import { useMountEffect } from '@platform/react/useMountEffect';import {assertAccountScopeCurrent,@@ -13,16 +13,18 @@ import {import { getApiErrorMessage } from '@platform/transport/http';import { useTranslation } from 'react-i18next';-import { markLibraryGraphSynced } from './library/librarySyncBridge';+import { planLibraryWorkflowOpen } from './library/useOpenLibraryWorkflow';import { startWorkflowUiPendingLoadRuntime } from './pendingLibraryWorkflowLoadRuntime';/**- * Apply external library or embedded-workflow requests through the same parse-and-replace path as the library- * dialog.+ * Apply external library or embedded-workflow requests through the same collection commands as the library+ * dialog: a template resumes its existing copy or becomes a new one, an embedded document becomes a new workflow.+ * Without a chooser to hand to the user, a template with several copies resumes the first.*/export const PendingWorkflowLoader = () => {const { t } = useTranslation();- const { replace } = useProjectGraphCommands();+ const { addWorkflow, selectWorkflow } = useProjectGraphCommands();+ const { project } = useWorkflowUi();const notify = useWorkflowNotifications();useMountEffect(() => {const owner = captureAccountScope();@@ -31,35 +33,56 @@ export const PendingWorkflowLoader = () => {try {assertAccountScopeCurrent(owner);+ // The request is fenced to the project it arrived in.+ const projectId = project.getSnapshot().id;++ if (source.kind === 'library') {+ const plan = planLibraryWorkflowOpen(project.getSnapshot().workflows, source.workflowId);++ if (plan.kind !== 'add') {+ selectWorkflow(plan.kind === 'resume' ? plan.workflowId : plan.copies[0]!.document.id);+ return;+ }+ }+let raw: unknown = null;let label = '';+ let libraryRevision: number | null = null;if (source.kind === 'library') {- const record = await getLibraryWorkflow(source.workflowId, owner.signal);- const name = typeof record.name === 'string' && record.name.length > 0 ? record.name : 'workflow';+ const record = await getLibraryWorkflowRecord(source.workflowId, owner.signal);+ const name = record.name.length > 0 ? record.name : 'workflow';- raw = record;+ raw = { ...record.workflow, id: record.workflow_id };label = t('commandPalette.workflowLoad.loaded', { name });+ libraryRevision = record.revision;} else {raw = source.raw;label = source.label;}assertAccountScopeCurrent(owner);++ if (project.getSnapshot().id !== projectId) {+ return;+ }+const { document: parsed, warnings: parseWarnings } = parseWorkflowJson(raw);- const { document: updated, warnings: updateWarnings } = updateLoadedWorkflowNodes(parsed, t);+ const { document, warnings: updateWarnings } = updateLoadedWorkflowNodes(parsed, t);const warnings = [...parseWarnings, ...updateWarnings];- // An embedded document may still carry the id of the library record it was- // saved from; loading it must not start autosaving over that record.- const document = source.kind === 'library' ? updated : { ...updated, libraryWorkflowId: undefined };-- replace(document, label);+ addWorkflow(document, {+ label,+ reusePlaceholder: true,+ // An embedded document may carry the id of the record it was saved from; that id is provenance, never+ // a write target.+ ...(source.kind === 'library'+ ? { source: { libraryWorkflowId: source.workflowId, revision: libraryRevision } }+ : {}),+ });requestWorkflowFitView(document.nodes);if (source.kind === 'library') {- // Mark freshly loaded library graphs synced before autosave observes them as edits.- markLibraryGraphSynced(serializeWorkflowJson(document));void touchLibraryWorkflowOpenedAt(source.workflowId, owner.signal).catch(() => {// Recency bookkeeping only; loading already succeeded.});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsxdeleted file mode 100644index fa1527ef60..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowDialogHost.browser.test.tsx+++ /dev/null@@ -1,654 +0,0 @@-import type { ProjectGraphState } from '@features/workflow/core/types';--import { ChakraProvider } from '@chakra-ui/react';-import { createProjectGraph } from '@features/workflow/utility';-import { accountLifecycle } from '@platform/state/accountLifecycle';-import { QueryClient, QueryClientProvider } from '@tanstack/react-query';-import { system } from '@theme/system';-import { act, Profiler, StrictMode } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import type { WorkflowUiAdapter } from './WorkflowUiContext';--import { workflowLibrarySyncStore } from './library/workflowLibrarySyncStore';-import { WorkflowUiProvider } from './WorkflowUiContext';-import { WorkflowDialogHost } from './WorkflowWidgetChrome';--const deferred = <T,>() => {- let reject!: (reason?: unknown) => void;- let resolve!: (value: T) => void;- const promise = new Promise<T>((resolvePromise, rejectPromise) => {- resolve = resolvePromise;- reject = rejectPromise;- });-- return { promise, reject, resolve };-};--// Stub heavy dialog leaves to isolate autosave wiring.-vi.mock('./editor/AddNodeDialog', () => ({ AddNodeDialog: () => null }));-vi.mock('./library/WorkflowLibraryDialog', () => ({ WorkflowLibraryDialog: () => null }));-vi.mock('./PendingLibraryWorkflowLoader', () => ({ PendingWorkflowLoader: () => null }));--import { onWorkflowLibraryCacheInvalidated } from '@features/workflow/queries';--const { updateLibraryWorkflowMock } = vi.hoisted(() => ({ updateLibraryWorkflowMock: vi.fn() }));--vi.mock('@features/workflow/queries', async (importOriginal) => ({- ...(await importOriginal<Record<string, unknown>>()),- updateLibraryWorkflow: updateLibraryWorkflowMock,-}));--(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;--const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {- let snapshot = initialSnapshot;- const listeners = new Set<() => void>();- return {- port: {- getSnapshot: () => snapshot,- subscribe: (listener: () => void) => {- listeners.add(listener);- return () => listeners.delete(listener);- },- },- setSnapshot: (next: Snapshot) => {- snapshot = next;- for (const listener of listeners) {- listener();- }- },- };-};--const createGraphWithDuplicateWorkflowReturns = (): ProjectGraphState => ({- ...createProjectGraph('workflow-1'),- libraryWorkflowId: 'library-workflow-1',- nodes: [- { data: { type: 'workflow_return' }, id: 'return-1', position: { x: 0, y: 0 }, type: 'invocation' },- { data: { type: 'workflow_return' }, id: 'return-2', position: { x: 100, y: 0 }, type: 'invocation' },- ] as unknown as ProjectGraphState['nodes'],-});--/**- * Exercise real StrictMode cleanup/remount so autosaver creation and disposal share a lifecycle and cannot leave a- * permanently disposed instance.- */-describe('WorkflowDialogHost library autosave under StrictMode', () => {- let host: HTMLDivElement;- let root: Root;- let queryClient: QueryClient;-- beforeEach(() => {- host = document.createElement('div');- document.body.append(host);- queryClient = new QueryClient();- updateLibraryWorkflowMock.mockReset();- updateLibraryWorkflowMock.mockResolvedValue(undefined);- });-- afterEach(async () => {- await act(() => root.unmount());- queryClient.clear();- host.remove();- });-- it('still autosaves a bound workflow after a graph edit', async () => {- const cacheInvalidated = vi.fn();- const stopListening = onWorkflowLibraryCacheInvalidated(cacheInvalidated);-- const boundGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: boundGraph,- workflowValues: {},- });-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- getProjectGraph: () => project.port.getSnapshot().projectGraph,- notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },- project: project.port,- widgets: { open: vi.fn(), patchValues: vi.fn() },- } as unknown as WorkflowUiAdapter;-- root = createRoot(host);-- await act(() => {- root.render(- <StrictMode>- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <WorkflowUiProvider adapter={adapter}>- <WorkflowDialogHost />- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </StrictMode>- );- });-- expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();-- await act(() => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...boundGraph, name: 'Edited name' },- });- });-- // Past the 2s debounce.- await act(- () =>- new Promise<void>((resolve) => {- setTimeout(resolve, 2100);- })- );- // Let the autosaver's save promise settle.- await act(- () =>- new Promise<void>((resolve) => {- setTimeout(resolve, 0);- })- );-- expect(updateLibraryWorkflowMock).toHaveBeenCalledTimes(1);- expect(updateLibraryWorkflowMock).toHaveBeenCalledWith(- 'library-workflow-1',- expect.objectContaining({ name: 'Edited name' }),- expect.any(AbortSignal)- );- // The library dialog must not keep serving the pre-save payload.- expect(cacheInvalidated).toHaveBeenCalledTimes(1);- stopListening();- });-- it('rejects an autosave when the graph has duplicate workflow returns', async () => {- const boundGraph = createGraphWithDuplicateWorkflowReturns();- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: boundGraph,- workflowValues: {},- });- const notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- getProjectGraph: () => project.port.getSnapshot().projectGraph,- notifications,- project: project.port,- widgets: { open: vi.fn(), patchValues: vi.fn() },- } as unknown as WorkflowUiAdapter;-- root = createRoot(host);-- await act(() => {- root.render(- <StrictMode>- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <WorkflowUiProvider adapter={adapter}>- <WorkflowDialogHost />- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </StrictMode>- );- });-- await act(() => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...boundGraph, name: 'Invalid duplicate-return edit' },- });- });- await act(- () =>- new Promise<void>((resolve) => {- setTimeout(resolve, 2100);- })- );-- expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();- expect(notifications.error).toHaveBeenCalledTimes(1);- });-- it('does not repeat the duplicate-return autosave notification for every edit', async () => {- const boundGraph = createGraphWithDuplicateWorkflowReturns();- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: boundGraph,- workflowValues: {},- });- const notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- getProjectGraph: () => project.port.getSnapshot().projectGraph,- notifications,- project: project.port,- widgets: { open: vi.fn(), patchValues: vi.fn() },- } as unknown as WorkflowUiAdapter;-- root = createRoot(host);-- await act(() => {- root.render(- <StrictMode>- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <WorkflowUiProvider adapter={adapter}>- <WorkflowDialogHost />- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </StrictMode>- );- });-- const editAndWaitForAutosave = async (name: string) => {- await act(() => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...boundGraph, name },- });- });- await act(- () =>- new Promise<void>((resolve) => {- setTimeout(resolve, 2100);- })- );- };-- await editAndWaitForAutosave('First invalid edit');- await editAndWaitForAutosave('Second invalid edit');-- expect(notifications.error).toHaveBeenCalledTimes(1);- expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();- });-- it('does not notify when disposing a pending duplicate-return autosave', async () => {- const boundGraph = createGraphWithDuplicateWorkflowReturns();- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: boundGraph,- workflowValues: {},- });- const notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- getProjectGraph: () => project.port.getSnapshot().projectGraph,- notifications,- project: project.port,- widgets: { open: vi.fn(), patchValues: vi.fn() },- } as unknown as WorkflowUiAdapter;-- root = createRoot(host);-- await act(() => {- root.render(- <StrictMode>- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <WorkflowUiProvider adapter={adapter}>- <WorkflowDialogHost />- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </StrictMode>- );- });-- await act(() => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...boundGraph, name: 'Pending invalid edit' },- });- });- await act(() => root.render(null));-- expect(notifications.error).not.toHaveBeenCalled();- expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();- });-- it('re-arms duplicate-return notifications after valid saves and deduped reverts', async () => {- const boundGraph = createGraphWithDuplicateWorkflowReturns();- const validGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: boundGraph,- workflowValues: {},- });- const notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- getProjectGraph: () => project.port.getSnapshot().projectGraph,- notifications,- project: project.port,- widgets: { open: vi.fn(), patchValues: vi.fn() },- } as unknown as WorkflowUiAdapter;-- root = createRoot(host);-- await act(() => {- root.render(- <StrictMode>- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <WorkflowUiProvider adapter={adapter}>- <WorkflowDialogHost />- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </StrictMode>- );- });-- const waitForAutosave = async () => {- await act(- () =>- new Promise<void>((resolve) => {- setTimeout(resolve, 2100);- })- );- };-- await act(() => {- project.setSnapshot({ ...project.port.getSnapshot(), projectGraph: { ...boundGraph, name: 'Invalid edit' } });- });- await waitForAutosave();-- await act(() => {- project.setSnapshot({ ...project.port.getSnapshot(), projectGraph: validGraph });- });- await waitForAutosave();-- await act(() => {- project.setSnapshot({ ...project.port.getSnapshot(), projectGraph: { ...boundGraph, name: 'Invalid again' } });- });- await waitForAutosave();-- expect(notifications.error).toHaveBeenCalledTimes(2);-- await act(() => {- project.setSnapshot({ ...project.port.getSnapshot(), projectGraph: validGraph });- });- await waitForAutosave();-- await act(() => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...boundGraph, name: 'Invalid after revert' },- });- });- await waitForAutosave();-- expect(notifications.error).toHaveBeenCalledTimes(3);- expect(updateLibraryWorkflowMock).toHaveBeenCalledTimes(1);- });-- /** Notify autosave through the project store subscription without rerendering the dialog host on graph edits. */- it('schedules an autosave for graph edits made outside React renders', async () => {- workflowLibrarySyncStore.setSnapshot({ status: 'idle' });-- const boundGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: boundGraph,- workflowValues: {},- });-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- getProjectGraph: () => project.port.getSnapshot().projectGraph,- notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },- project: project.port,- widgets: { open: vi.fn(), patchValues: vi.fn() },- } as unknown as WorkflowUiAdapter;-- root = createRoot(host);-- let renderCount = 0;- // eslint-disable-next-line react-perf/jsx-no-new-function-as-prop -- test-only render probe, not app code- const countRender = () => {- renderCount += 1;- };-- await act(() => {- root.render(- <StrictMode>- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <WorkflowUiProvider adapter={adapter}>- <Profiler id="dialog-host" onRender={countRender}>- <WorkflowDialogHost />- </Profiler>- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </StrictMode>- );- });-- // Only the edit dispatched below is under test; the mount itself renders- // (StrictMode doubles it).- renderCount = 0;-- // Dispatch directly through the store to test imperative edits without prop-driven rerenders.- await act(() => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...boundGraph, name: 'Edited outside React' },- });- });-- expect(renderCount).toBe(0);- expect(workflowLibrarySyncStore.getSnapshot().status).toBe('dirty');- });-- /**- * Fence status callbacks across account rotation: aborted saves reject after the new account's synchronous idle- * reset.- */- it('does not park a stale save error in the sync store after an account switch', async () => {- const boundGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: boundGraph,- workflowValues: {},- });-- const request = deferred<void>();-- updateLibraryWorkflowMock.mockReturnValue(request.promise);-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- getProjectGraph: () => project.port.getSnapshot().projectGraph,- notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },- project: project.port,- widgets: { open: vi.fn(), patchValues: vi.fn() },- } as unknown as WorkflowUiAdapter;-- root = createRoot(host);-- await act(() => {- root.render(- <StrictMode>- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <WorkflowUiProvider adapter={adapter}>- <WorkflowDialogHost />- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </StrictMode>- );- });-- await act(() => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...boundGraph, name: 'Edited before switch' },- });- });-- await act(- () =>- new Promise<void>((resolve) => {- setTimeout(resolve, 2100);- })- );-- expect(updateLibraryWorkflowMock).toHaveBeenCalledTimes(1);-- try {- accountLifecycle.activate('workflow-dialog-host-test-account', ':user:workflow-dialog-host-test-account');-- expect(workflowLibrarySyncStore.getSnapshot().status).toBe('idle');-- // Resolve after rotation to exercise scope-check rejection without leaking an error status into the new- // account.- await act(async () => {- request.resolve();- await request.promise.catch(() => undefined);- // Give the save's `.then`/`.catch` continuation a turn to run.- await Promise.resolve();- await Promise.resolve();- });-- expect(workflowLibrarySyncStore.getSnapshot().status).toBe('idle');- } finally {- accountLifecycle.invalidate();- }- });-- it('does not flush a pending old-account edit after the account switches', async () => {- const boundGraph = { ...createProjectGraph('workflow-1'), libraryWorkflowId: 'library-workflow-1' };- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: boundGraph,- workflowValues: {},- });- const notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };-- accountLifecycle.activate('workflow-dialog-host-old-account', ':user:workflow-dialog-host-old-account');-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- getProjectGraph: () => project.port.getSnapshot().projectGraph,- notifications,- project: project.port,- widgets: { open: vi.fn(), patchValues: vi.fn() },- } as unknown as WorkflowUiAdapter;-- root = createRoot(host);-- try {- await act(() => {- root.render(- <StrictMode>- <ChakraProvider value={system}>- <QueryClientProvider client={queryClient}>- <WorkflowUiProvider adapter={adapter}>- <WorkflowDialogHost />- </WorkflowUiProvider>- </QueryClientProvider>- </ChakraProvider>- </StrictMode>- );- });-- await act(() => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...boundGraph, name: 'Old account edit' },- });- });-- accountLifecycle.activate('workflow-dialog-host-new-account', ':user:workflow-dialog-host-new-account');- await act(() => root.render(null));- await Promise.resolve();-- expect(updateLibraryWorkflowMock).not.toHaveBeenCalled();- } finally {- accountLifecycle.invalidate();- }- });-});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 52d74eab79..665a362ff3 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowMenuItems.browser.test.tsx@@ -1,6 +1,10 @@-import type { ProjectGraphState, WorkflowNode } from '@features/workflow/core/types';+import type { ProjectGraphState, ProjectWorkflowSource, WorkflowNode } from '@features/workflow/core/types';import type { WorkflowRuntimeApi } from '@features/workflow/ui/contracts';-import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';+import type {+ WorkflowProjectPersistence,+ WorkflowReadPort,+ WorkflowUiAdapter,+} from '@features/workflow/ui/WorkflowUiContext';import { ChakraProvider, Menu } from '@chakra-ui/react';import { createProjectGraph } from '@features/workflow/utility';@@ -10,7 +14,8 @@ import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { WorkflowUiProvider } from './WorkflowUiContext';-import { WorkflowMenuItems } from './WorkflowWidgetChrome';+import { clearWorkflowPublicationIntent, workflowUiStore } from './workflowUiStore';+import { WorkflowHeaderActions, WorkflowMenuItems } from './WorkflowWidgetChrome';const { copyWorkflowJsonMock, downloadWorkflowJsonMock } = vi.hoisted(() => ({copyWorkflowJsonMock: vi.fn(),@@ -22,26 +27,57 @@ vi.mock('./workflowTransfer', () => ({downloadWorkflowJson: downloadWorkflowJsonMock,}));+const TRANSLATIONS: Record<string, string> = {+ 'projects.exportFailed': 'Export failed',+ 'widgets.labels.workflow': 'Workflow',+ 'widgets.workflow.addNode': 'Add node',+ 'widgets.workflow.copyJson': 'Copy workflow JSON',+ 'widgets.workflow.copyJsonFailed': 'Failed to copy workflow JSON',+ 'widgets.workflow.detailsWithEllipsis': 'Workflow details…',+ 'widgets.workflow.exportJson': 'Export workflow JSON',+ 'widgets.workflow.importJsonWithEllipsis': 'Import workflow JSON…',+ 'widgets.workflow.library': 'Workflow library',+ 'widgets.workflow.libraryWithEllipsis': 'Workflow library…',+ 'widgets.workflow.newWorkflow': 'New workflow',+ 'widgets.workflow.persistenceConflict': 'Project has a sync conflict — resolve it to keep saving',+ 'widgets.workflow.persistenceError': 'Project save failed — retrying',+ 'widgets.workflow.persistencePending': 'Project changes waiting to save (recovery draft kept)',+ 'widgets.workflow.persistencePendingNoRecovery': 'Project changes waiting to save — no browser recovery available',+ 'widgets.workflow.persistenceSaved': 'Project saved to the server',+ 'widgets.workflow.persistenceSaving': 'Saving project…',+ 'widgets.workflow.saveToLibraryWithEllipsis': 'Save to library…',+ 'widgets.workflow.updateTemplateWithEllipsis': 'Update 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) =>- ({- 'projects.exportFailed': 'Export failed',- 'widgets.labels.workflow': 'Workflow',- 'widgets.workflow.copyJson': 'Copy workflow JSON',- 'widgets.workflow.copyJsonFailed': 'Failed to copy workflow JSON',- 'widgets.workflow.detailsWithEllipsis': 'Workflow details…',- 'widgets.workflow.exportJson': 'Export workflow JSON',- 'widgets.workflow.importJsonWithEllipsis': 'Import workflow JSON…',- 'widgets.workflow.newWorkflowWithEllipsis': 'New workflow…',- 'workflowLibrary.multipleWorkflowReturnNodesForTransfer':- 'The workflow must contain exactly one workflow return node before it can be exported or copied.',- })[key] ?? key,- }),+ useTranslation: () => ({ t: (key: string) => TRANSLATIONS[key] ?? key }),}));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {+ let snapshot = initialSnapshot;+ const listeners = new Set<() => void>();+ const port: WorkflowReadPort<Snapshot> = {+ getSnapshot: () => snapshot,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ return {+ port,+ setSnapshot: (next: Snapshot) => {+ snapshot = next;+ for (const listener of listeners) {+ listener();+ }+ },+ };+};+const duplicateReturnGraph = (): ProjectGraphState => ({...createProjectGraph('workflow-1'),nodes: [@@ -50,6 +86,19 @@ const duplicateReturnGraph = (): ProjectGraphState => ({] as unknown as WorkflowNode[],});+const projectSnapshot = (graph: ProjectGraphState, source?: ProjectWorkflowSource) => ({+ activeWorkflow: { document: graph, source },+ activeWorkflowId: graph.id,+ galleryValues: {},+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph: graph,+ workflowValues: {},+ workflows: [{ document: graph, source }],+});++const SAVED: WorkflowProjectPersistence = { error: null, hasLocalRecovery: true, lastSavedAt: null, status: 'saved' };+const TEST_RUNTIME: WorkflowRuntimeApi = {commands: { register: () => () => undefined },hotkeys: { register: () => () => undefined },@@ -58,10 +107,24 @@ const TEST_RUNTIME: WorkflowRuntimeApi = {typeId: 'workflow',};-describe('WorkflowMenuItems duplicate workflow-return feedback', () => {+const createCommands = () => ({+ addWorkflow: vi.fn(() => 'workflow-2'),+ createWorkflow: vi.fn(() => 'workflow-2'),+ duplicateWorkflow: vi.fn(() => null),+ editGraph: vi.fn(),+ redo: vi.fn(),+ removeWorkflow: vi.fn(),+ renameWorkflow: vi.fn(),+ selectWorkflow: vi.fn(),+ setWorkflowSource: vi.fn(),+ undo: vi.fn(),+});++describe('WorkflowMenuItems', () => {let host: HTMLDivElement;let root: Root;let notifications: WorkflowUiAdapter['notifications'];+ let commands: ReturnType<typeof createCommands>;beforeEach(() => {host = document.createElement('div');@@ -69,20 +132,25 @@ describe('WorkflowMenuItems duplicate workflow-return feedback', () => {root = createRoot(host);copyWorkflowJsonMock.mockReset();downloadWorkflowJsonMock.mockReset();+ clearWorkflowPublicationIntent();notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };+ commands = createCommands();});afterEach(async () => {await act(() => root.unmount());host.remove();+ clearWorkflowPublicationIntent();});- const renderMenu = async () => {- const graph = duplicateReturnGraph();+ const renderMenu = async (graph: ProjectGraphState, source?: ProjectWorkflowSource) => {+ const project = createMutablePort(projectSnapshot(graph, source));// eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapterconst adapter = {+ commands,getProjectGraph: () => graph,notifications,+ project: project.port,widgets: { open: vi.fn(), patchValues: vi.fn() },} as unknown as WorkflowUiAdapter;@@ -103,15 +171,14 @@ describe('WorkflowMenuItems duplicate workflow-return feedback', () => {});};- it('blocks export and copy with action-specific translated feedback', async () => {- await renderMenu();+ const menuItems = () => Array.from(host.querySelectorAll<HTMLElement>('[role="menuitem"]'));+ const menuItem = (text: string) => menuItems().find((item) => item.textContent === text);- const menuItems = () => Array.from(host.querySelectorAll<HTMLElement>('[role="menuitem"]'));- const exportItem = () => menuItems().find((item) => item.textContent === 'Export workflow JSON');- const copyItem = () => menuItems().find((item) => item.textContent === 'Copy workflow JSON');+ it('blocks export and copy with action-specific translated feedback', async () => {+ await renderMenu(duplicateReturnGraph());- await act(() => exportItem()?.click());- await act(() => copyItem()?.click());+ await act(() => menuItem('Export workflow JSON')?.click());+ await act(() => menuItem('Copy workflow JSON')?.click());expect(downloadWorkflowJsonMock).not.toHaveBeenCalled();expect(copyWorkflowJsonMock).not.toHaveBeenCalled();@@ -126,4 +193,126 @@ describe('WorkflowMenuItems duplicate workflow-return feedback', () => {'The workflow must contain exactly one workflow return node before it can be exported or copied.');});++ it('starts a new workflow beside the others without asking for confirmation', async () => {+ await renderMenu(createProjectGraph('workflow-1'));++ const item = menuItem('New workflow');+ expect(item).not.toBeUndefined();++ await act(() => item?.click());++ expect(commands.createWorkflow).toHaveBeenCalledTimes(1);+ // Nothing is replaced, so nothing stands between the click and the new workflow.+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();+ });++ it('asks the publication host to save the active workflow as a new template', async () => {+ await renderMenu(createProjectGraph('workflow-1'));++ await act(() => menuItem('Save to library…')?.click());++ expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({ kind: 'save-as-new', workflowId: 'workflow-1' });+ });++ it('offers a template update only for a workflow whose source can be written', async () => {+ await renderMenu(createProjectGraph('workflow-1'));+ expect(menuItem('Update library template…')).toBeUndefined();++ await renderMenu(createProjectGraph('workflow-1'), { libraryWorkflowId: 'default_text', revision: 1 });+ expect(menuItem('Update library template…')).toBeUndefined();++ await renderMenu(createProjectGraph('workflow-1'), { libraryWorkflowId: 'lib-1', revision: 4 });++ const item = menuItem('Update library template…');+ expect(item).not.toBeUndefined();++ await act(() => item?.click());++ expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({+ kind: 'update-source',+ workflowId: 'workflow-1',+ });+ });+});++describe('WorkflowHeaderActions', () => {+ let host: HTMLDivElement;+ let root: Root;+ let persistence: ReturnType<typeof createMutablePort<WorkflowProjectPersistence>>;++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ clearWorkflowPublicationIntent();+ persistence = createMutablePort<WorkflowProjectPersistence>(SAVED);+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ clearWorkflowPublicationIntent();+ });++ const renderHeader = async () => {+ const graph = createProjectGraph('workflow-1');+ const project = createMutablePort(projectSnapshot(graph));+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally minimal test adapter+ const adapter = {+ commands: createCommands(),+ getProjectGraph: () => graph,+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ persistence: persistence.port,+ project: project.port,+ widgets: { open: vi.fn(), patchValues: vi.fn() },+ } as unknown as WorkflowUiAdapter;++ await act(() => {+ root.render(+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <WorkflowHeaderActions region="center" runtime={TEST_RUNTIME} />+ </WorkflowUiProvider>+ </ChakraProvider>+ );+ });+ };++ const status = () => host.querySelector<HTMLElement>('[role="status"][data-persistence-status]');++ it('names the project persistence state, including a pending save with no local safety net', async () => {+ await renderHeader();++ expect(status()?.dataset.persistenceStatus).toBe('saved');+ expect(status()?.getAttribute('aria-label')).toBe('Project saved to the server');++ const expectations: Array<[WorkflowProjectPersistence['status'], boolean, string]> = [+ ['saving', true, 'Saving project…'],+ ['pending', true, 'Project changes waiting to save (recovery draft kept)'],+ ['pending', false, 'Project changes waiting to save — no browser recovery available'],+ ['error', true, 'Project save failed — retrying'],+ ['conflict', true, 'Project has a sync conflict — resolve it to keep saving'],+ // Recovery only matters while a save is still waiting.+ ['saved', false, 'Project saved to the server'],+ ];++ for (const [state, hasLocalRecovery, label] of expectations) {+ await act(() => persistence.setSnapshot({ ...SAVED, hasLocalRecovery, status: state }));++ expect(status()?.dataset.persistenceStatus).toBe(state);+ expect(status()?.getAttribute('aria-label')).toBe(label);+ }+ });++ it('asks the publication host to save the active workflow as a new template', async () => {+ await renderHeader();++ const button = host.querySelector<HTMLButtonElement>('button[aria-label="Save to library…"]');+ expect(button).not.toBeNull();++ await act(() => button?.click());++ expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({ kind: 'save-as-new', workflowId: 'workflow-1' });+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsxindex 592fd9eaae..1648009f55 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.browser.test.tsx@@ -1,6 +1,8 @@/* eslint-disable react/globals, react/immutability -- test instrumentation intentionally records render counts */+import type { ProjectGraphState } from '@features/workflow/core/types';import type { ReactNode } from 'react';+import { createProjectGraph } from '@features/workflow/utility';import { act, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -10,6 +12,7 @@ import type { WorkflowGraphPreviewPort, WorkflowReadPort, WorkflowUiAdapter } frimport {useWorkflowCapabilitiesSelector,useWorkflowGraphPreview,+ useWorkflowNodeExecutionState,useWorkflowPreferencesSelector,useWorkflowProjectSelector,useWorkflowUi,@@ -40,14 +43,26 @@ const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {};};-const projectState = (id = 'project-1') => ({+const projectState = (id = 'project-1', projectGraph: ProjectGraphState = createProjectGraph('workflow-1')) => ({+ activeWorkflow: { document: projectGraph },+ activeWorkflowId: projectGraph.id,galleryValues: {},id,isWorkflowRunning: false,- projectGraph: { edges: [], nodes: [], version: 1 as const },+ projectGraph,workflowValues: {},+ workflows: [{ document: projectGraph }],});+const NODE_STATE = {+ error: null,+ latestOutput: null,+ outputImageUrl: null,+ progress: 0.5,+ progressMessage: null,+ status: 'running' as const,+};+const preferencesState = () => ({reduceMotion: false,themeId: 'classic' as const,@@ -83,7 +98,12 @@ describe('Workflow UI read-port isolation', () => {capabilities: capabilities.port,commands: {},getProjectGraph: () => project.port.getSnapshot().projectGraph,- nodeExecution: { get: () => null, subscribe: () => vi.fn() },+ nodeExecution: {+ get: () => null,+ getOrigin: () => null,+ subscribe: () => vi.fn(),+ subscribeOrigin: () => vi.fn(),+ },notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },performance: { mark: vi.fn(), measure: vi.fn(), time: vi.fn() },preferences: preferences.port,@@ -155,7 +175,7 @@ describe('Workflow UI read-port isolation', () => {});expect(counts).toEqual({ capability: 1, graph: 1, preferences: 1, project: 1, projectEqual: 1, services: 1 });- await act(() => project.setSnapshot({ ...projectState(), projectGraph: { edges: [], nodes: [], version: 1 } }));+ await act(() => project.setSnapshot(projectState()));expect(counts).toEqual({ capability: 1, graph: 1, preferences: 1, project: 2, projectEqual: 1, services: 1 });await act(() => preferences.setSnapshot({ ...preferencesState(), workflowSnapToGrid: true }));@@ -184,4 +204,59 @@ describe('Workflow UI read-port isolation', () => {);expect(counts).toEqual({ capability: 2, graph: 3, preferences: 2, project: 2, projectEqual: 1, services: 1 });});++ it('shows node execution only while the tracked run came from the workflow this editor shows', async () => {+ const graph = createProjectGraph('workflow-1');+ const project = createMutablePort(projectState('project-1', graph));+ let origin: { projectId: string; workflowId: string } | null = null;+ const originListeners = new Set<() => void>();+ const setOrigin = (next: typeof origin) => {+ origin = next;+ originListeners.forEach((listener) => listener());+ };+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime+ const adapter = {+ capabilities: createMutablePort({ canUseCache: true }).port,+ commands: {},+ getProjectGraph: () => project.port.getSnapshot().projectGraph,+ nodeExecution: {+ get: (nodeId: string) => (nodeId === 'node-1' ? NODE_STATE : null),+ getOrigin: () => origin,+ subscribe: () => () => {},+ subscribeOrigin: (listener: () => void) => {+ originListeners.add(listener);+ return () => originListeners.delete(listener);+ },+ },+ notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ performance: { mark: vi.fn(), measure: vi.fn(), time: vi.fn() },+ preferences: createMutablePort(preferencesState()).port,+ project: project.port,+ registerModalHotkeyLayer: vi.fn(() => vi.fn()),+ widgets: {},+ } as unknown as WorkflowUiAdapter;+ const Consumer = () => <output>{useWorkflowNodeExecutionState('node-1')?.status ?? 'none'}</output>;++ await act(() => {+ root.render(+ <WorkflowUiProvider adapter={adapter}>+ <Consumer />+ </WorkflowUiProvider>+ );+ });+ expect(host.textContent).toBe('none');++ await act(() => setOrigin({ projectId: 'project-1', workflowId: 'workflow-1' }));+ expect(host.textContent).toBe('running');++ // The same project, another of its workflows: that copy's progress stays out of this editor.+ await act(() => project.setSnapshot(projectState('project-1', createProjectGraph('workflow-2'))));+ expect(host.textContent).toBe('none');++ await act(() => project.setSnapshot(projectState('project-1', graph)));+ expect(host.textContent).toBe('running');++ await act(() => setOrigin({ projectId: 'project-2', workflowId: 'workflow-1' }));+ expect(host.textContent).toBe('none');+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsxindex 34503e9826..9681d534b2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowUiContext.tsx@@ -1,5 +1,5 @@import type { ForLoopValidationReason } from '@features/workflow/core/forLoops';-import type { ProjectGraphState } from '@features/workflow/core/types';+import type { ProjectGraphState, ProjectWorkflowEntry, ProjectWorkflowSource } from '@features/workflow/core/types';import type { WorkbenchThemeId } from '@theme/themes';import type { ReactNode } from 'react';@@ -24,11 +24,26 @@ export interface WorkflowPreferences {workflowValidateConnections: boolean;}+/** How the project's own persistence stands; the editor shows it beside the library actions. */+export interface WorkflowProjectPersistence {+ status: 'pending' | 'saving' | 'saved' | 'error' | 'conflict';+ /** False when browser recovery storage is unavailable, so a pending save has no local safety net. */+ hasLocalRecovery: boolean;+ lastSavedAt: string | null;+ error: string | null;+}+export interface WorkflowProjectSnapshot {galleryValues: Record<string, unknown>;id: string;isWorkflowRunning: boolean;+ /** The active workflow's editable document. */projectGraph: ProjectGraphState;+ /** The active workflow's entry: its document plus source and run metadata. */+ activeWorkflow: ProjectWorkflowEntry;+ activeWorkflowId: string;+ /** Every workflow the project owns, in collection order; entries keep identity until edited. */+ workflows: readonly ProjectWorkflowEntry[];workflowValues: Record<string, unknown>;}@@ -48,7 +63,8 @@ export interface WorkflowGraphPreviewPort {invoke(sourceId?: WorkflowInvocationSourceId): Promise<boolean>;focusSource(sourceId?: WorkflowInvocationSourceId): void; // reveal the source's widget (provenance links)openWorkflowEditor(): void; // reveal the workflow editor widget- openDocumentInNewProject(document: ProjectGraphState, label: string): void; // fork a preview into a fresh project+ /** Forks a document into a fresh project; a library source travels with it so the copy can update its template. */+ openDocumentInNewProject(document: ProjectGraphState, label: string, source?: ProjectWorkflowSource): void;}/** This UI port preserves dependency direction: Workflow cannot import Workbench. */@@ -56,6 +72,7 @@ export interface WorkflowUiAdapter {capabilities: WorkflowReadPort<WorkflowCapabilities>;preferences: WorkflowReadPort<WorkflowPreferences>;project: WorkflowReadPort<WorkflowProjectSnapshot>;+ persistence: WorkflowReadPort<WorkflowProjectPersistence>;commands: WorkflowCommands;widgets: WorkflowWidgetCommands;getProjectGraph(): ProjectGraphState;@@ -75,6 +92,9 @@ export interface WorkflowUiAdapter {nodeExecution: {get(nodeId: string): WorkflowNodeExecutionState | null;subscribe(nodeId: string, listener: () => void): () => void;+ /** Which project workflow the tracked run came from; progress for another copy stays out of this editor. */+ getOrigin(): { projectId: string; workflowId: string } | null;+ subscribeOrigin(listener: () => void): () => void;};}@@ -144,12 +164,34 @@ export const useWorkflowNotifications = () => useWorkflowUi().notifications;export const useOpenAddModels = (): ((query: string) => void) => useWorkflowUi().openAddModels;+export const useWorkflowPersistenceSelector = <Selected,>(+ selector: (persistence: WorkflowProjectPersistence) => Selected,+ isEqual?: EqualityFn<Selected>+): Selected => {+ const { persistence } = useWorkflowUi();+ return useExternalStoreSelector(persistence.subscribe, persistence.getSnapshot, selector, isEqual);+};++/** A node's execution state, only while the tracked run originated from the workflow this editor shows. */export const useWorkflowNodeExecutionState = (nodeId: string): WorkflowNodeExecutionState | null => {- const { nodeExecution } = useWorkflowUi();+ const { nodeExecution, project } = useWorkflowUi();const subscribe = useCallback(- (listener: () => void) => nodeExecution.subscribe(nodeId, listener),- [nodeExecution, nodeId]+ (listener: () => void) => {+ const unsubscribers = [+ nodeExecution.subscribe(nodeId, listener),+ nodeExecution.subscribeOrigin(listener),+ project.subscribe(listener),+ ];+ return () => unsubscribers.forEach((unsubscribe) => unsubscribe());+ },+ [nodeExecution, nodeId, project]);- const getSnapshot = useCallback(() => nodeExecution.get(nodeId), [nodeExecution, nodeId]);+ const getSnapshot = useCallback(() => {+ const origin = nodeExecution.getOrigin();+ const snapshot = project.getSnapshot();+ return origin && origin.projectId === snapshot.id && origin.workflowId === snapshot.activeWorkflowId+ ? nodeExecution.get(nodeId)+ : null;+ }, [nodeExecution, nodeId, project]);return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsxindex cc63581b73..24f8865dc6 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/WorkflowWidgetChrome.tsx@@ -2,7 +2,6 @@ import type { InvocationTemplate, XYPosition } from '@features/workflow/contractimport { Box, HStack, Icon, Menu, Text } from '@chakra-ui/react';import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';-import { invalidateWorkflowLibraryCache, updateLibraryWorkflow } from '@features/workflow/queries';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';import {buildConnectorNode,@@ -11,7 +10,6 @@ import {buildNotesNode,CONNECTOR_INPUT_HANDLE,CONNECTOR_OUTPUT_HANDLE,- createProjectGraph,createWorkflowId,getCompatibleInputTemplate,getCompatibleOutputTemplate,@@ -20,41 +18,47 @@ import {resolveConnectorSource,shouldAddForReturnLoopLinkage,parseWorkflowJson,- serializeWorkflowJson,} from '@features/workflow/utility';-import {- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';-import { Button, IconButton, ConfirmDialog, Tooltip } from '@platform/ui';+import { useMountEffect } from '@platform/react/useMountEffect';+import { Button, IconButton, Tooltip } from '@platform/ui';import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { CloudAlertIcon, CloudCheckIcon, CloudUploadIcon, LibraryIcon, PlusIcon, RefreshCwIcon } from 'lucide-react';-import { useCallback, useEffect, useRef, type ChangeEvent } from 'react';+import {+ BookmarkIcon,+ CloudAlertIcon,+ CloudCheckIcon,+ CloudIcon,+ LibraryIcon,+ PlusIcon,+ RefreshCwIcon,+ TriangleAlertIcon,+} from 'lucide-react';+import { useCallback, useEffect, useRef, type ChangeEvent, type ElementType } from 'react';import { useTranslation } from 'react-i18next';import type { WorkflowWidgetLabelProps, WorkflowWidgetViewProps } from './contracts';+import type { WorkflowProjectPersistence } from './WorkflowUiContext';import { AddNodeDialog } from './editor/AddNodeDialog';import { CallSavedWorkflowSyncRuntime } from './editor/CallSavedWorkflowSyncRuntime';import { getWorkflowFlowInstance } from './editor/flowInstanceStore';-import { createLibraryAutosaver, type LibrarySyncStatus } from './library/libraryAutosave';-import { registerLibraryGraphSyncedHandler, releaseLibraryGraphSyncedHandler } from './library/librarySyncBridge';-import { useSaveWorkflowToLibrary } from './library/useSaveWorkflowToLibrary';+import { releaseWorkflowViewportsExcept } from './editor/workflowViewportStore';+import { isUpdatableSource } from './library/projectWorkflowEntries';import { WorkflowLibraryDialog } from './library/WorkflowLibraryDialog';-import { setWorkflowLibrarySyncStatus, workflowLibrarySyncStore } from './library/workflowLibrarySyncStore';+import { WorkflowPublicationHost } from './library/WorkflowPublicationHost';import { PendingWorkflowLoader } from './PendingLibraryWorkflowLoader';import { copyWorkflowJson, downloadWorkflowJson } from './workflowTransfer';import {useWorkflowHostCommands,useWorkflowNotifications,+ useWorkflowPersistenceSelector,useWorkflowProjectSelector,useWorkflowUi,} from './WorkflowUiContext';import {+ openWorkflowLibraryAtProjectWorkflow,requestWorkflowImport,+ requestWorkflowPublication,setAddNodeOpen,- setNewWorkflowConfirmOpen,setWorkflowLibraryOpen,workflowUiStore,} from './workflowUiStore';@@ -64,19 +68,27 @@ import {* actions, and shared menu actions.*/-/** Icon + tooltip for each library sync status, shared by the sync control's error and non-error presentations. */-const SYNC_STATUS_VIEW: Record<LibrarySyncStatus, { icon: typeof CloudCheckIcon; tooltipKey: string }> = {- dirty: { icon: RefreshCwIcon, tooltipKey: 'widgets.workflow.librarySyncSaving' },- error: { icon: CloudAlertIcon, tooltipKey: 'widgets.workflow.librarySyncError' },- idle: { icon: CloudCheckIcon, tooltipKey: 'widgets.workflow.librarySyncSaved' },- saved: { icon: CloudCheckIcon, tooltipKey: 'widgets.workflow.librarySyncSaved' },- saving: { icon: RefreshCwIcon, tooltipKey: 'widgets.workflow.librarySyncSaving' },+/** How the project's own persistence is shown beside the library actions. */+const PERSISTENCE_VIEW: Record<+ WorkflowProjectPersistence['status'],+ { color: string; icon: ElementType; labelKey: string }+> = {+ conflict: { color: 'fg.warning', icon: TriangleAlertIcon, labelKey: 'widgets.workflow.persistenceConflict' },+ error: { color: 'fg.error', icon: CloudAlertIcon, labelKey: 'widgets.workflow.persistenceError' },+ pending: { color: 'fg.subtle', icon: CloudIcon, labelKey: 'widgets.workflow.persistencePending' },+ saved: { color: 'fg.subtle', icon: CloudCheckIcon, labelKey: 'widgets.workflow.persistenceSaved' },+ saving: { color: 'fg.subtle', icon: RefreshCwIcon, labelKey: 'widgets.workflow.persistenceSaving' },};export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {const { t } = useTranslation();const workflowName = useWorkflowProjectSelector((project) => project.projectGraph.name);- const openWorkflowLibrary = useCallback(() => setWorkflowLibraryOpen(true), []);+ const projectId = useWorkflowProjectSelector((project) => project.id);+ const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);+ const openProjectWorkflows = useCallback(+ () => openWorkflowLibraryAtProjectWorkflow(projectId, activeWorkflowId),+ [activeWorkflowId, projectId]+ );if (region !== 'center') {return (@@ -86,8 +98,7 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {);}- // Center chrome already names the widget; append only the library-opening workflow name and leave renaming in- // Details.+ // 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');return (@@ -95,14 +106,17 @@ export const WorkflowWidgetLabel = ({ region }: WorkflowWidgetLabelProps) => {<Text color="fg.subtle" flexShrink={0} fontSize="xs">/</Text>- <Tooltip content={t('widgets.workflow.library')}>+ <Tooltip content={t('widgets.workflow.projectWorkflows')}><Button- aria-label={t('widgets.workflow.openLibrary', { name: displayName })}+ aria-label={t('widgets.workflow.openProjectWorkflows', { name: displayName })}+ // The button recipe refuses to shrink; the name must give way before the actions island overlaps it.+ flexShrink={1}maxW="16rem"minW="0"+ overflow="hidden"size="2xs"variant="ghost"- onClick={openWorkflowLibrary}+ onClick={openProjectWorkflows}><Icon as={LibraryIcon} boxSize="3.5" flexShrink={0} /><MiddleTruncate color={workflowName ? undefined : 'fg.subtle'} fontWeight="600" minW="0" text={displayName} />@@ -117,7 +131,11 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {const { t } = useTranslation();const { getProjectGraph } = useWorkflowUi();const { widgets } = useWorkflowHostCommands();+ const { createWorkflow } = useProjectGraphCommands();const notify = useWorkflowNotifications();+ const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);+ const source = useWorkflowProjectSelector((project) => project.activeWorkflow.source);+ const canUpdateSource = isUpdatableSource(source);const openDetailsPanel = useCallback(() => {widgets.open({ region: 'left', widgetId: 'workflow' });@@ -145,7 +163,17 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {.then(() => notify.success(t('widgets.workflow.copyJsonSuccess'))).catch(() => notify.error(t('widgets.workflow.copyJsonFailed')));}, [getProjectGraph, notify, t]);- const createNewWorkflow = useCallback(() => setNewWorkflowConfirmOpen(true), []);+ const saveToLibrary = useCallback(+ () => requestWorkflowPublication({ kind: 'save-as-new', workflowId: activeWorkflowId }),+ [activeWorkflowId]+ );+ const updateTemplate = useCallback(+ () => requestWorkflowPublication({ kind: 'update-source', workflowId: activeWorkflowId }),+ [activeWorkflowId]+ );+ const openLibrary = useCallback(() => setWorkflowLibraryOpen(true), []);+ // Nothing is replaced: a new workflow is added beside the others, so no confirmation stands in the way.+ const newWorkflow = useCallback(() => createWorkflow(), [createWorkflow]);return (<Menu.ItemGroup>@@ -155,6 +183,17 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {<Menu.Item value="details" onClick={openDetailsPanel}>{t('widgets.workflow.detailsWithEllipsis')}</Menu.Item>+ <Menu.Item value="library" onClick={openLibrary}>+ {t('widgets.workflow.libraryWithEllipsis')}+ </Menu.Item>+ <Menu.Item value="save-to-library" onClick={saveToLibrary}>+ {t('widgets.workflow.saveToLibraryWithEllipsis')}+ </Menu.Item>+ {canUpdateSource ? (+ <Menu.Item value="update-template" onClick={updateTemplate}>+ {t('widgets.workflow.updateTemplateWithEllipsis')}+ </Menu.Item>+ ) : null}<Menu.Item value="import" onClick={requestWorkflowImport}>{t('widgets.workflow.importJsonWithEllipsis')}</Menu.Item>@@ -164,21 +203,32 @@ export const WorkflowMenuItems = (_props: WorkflowWidgetViewProps) => {<Menu.Item value="copy" onClick={copyWorkflow}>{t('widgets.workflow.copyJson')}</Menu.Item>- <Menu.Item data-danger="" value="new" onClick={createNewWorkflow}>- {t('widgets.workflow.newWorkflowWithEllipsis')}+ <Menu.Item value="new" onClick={newWorkflow}>+ {t('widgets.workflow.newWorkflow')}</Menu.Item></Menu.ItemGroup>);};+const selectPersistenceView = (persistence: WorkflowProjectPersistence) => ({+ hasLocalRecovery: persistence.hasLocalRecovery,+ status: persistence.status,+});+export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {const { t } = useTranslation();- const libraryWorkflowId = useWorkflowProjectSelector((project) => project.projectGraph.libraryWorkflowId);- const syncStatus = workflowLibrarySyncStore.useSelector((snapshot) => snapshot.status);- const { saveToLibrary } = useSaveWorkflowToLibrary();+ const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);+ const { hasLocalRecovery, status } = useWorkflowPersistenceSelector(selectPersistenceView);const openAddNode = useCallback(() => setAddNodeOpen(true), []);const openWorkflowLibrary = useCallback(() => setWorkflowLibraryOpen(true), []);- const handleSaveToLibrary = useCallback(() => void saveToLibrary(), [saveToLibrary]);+ const saveToLibrary = useCallback(+ () => requestWorkflowPublication({ kind: 'save-as-new', 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 =+ status === 'pending' && !hasLocalRecovery ? t('widgets.workflow.persistencePendingNoRecovery') : t(view.labelKey);return (<HStack gap="0.5">@@ -195,7 +245,8 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {</IconButton></Tooltip>) : null}- {/* Center labels already open the library; other regions need this separate trigger. */}+ {/* Center labels already open the project's workflows; other regions need this separate trigger and leave+ publication and persistence to the editor header. */}{region === 'center' ? null : (<Tooltip content={t('widgets.workflow.library')}><IconButton@@ -209,132 +260,69 @@ export const WorkflowHeaderActions = ({ region }: WorkflowWidgetViewProps) => {</IconButton></Tooltip>)}- {libraryWorkflowId ? (- <Tooltip content={t(SYNC_STATUS_VIEW[syncStatus].tooltipKey)}>- {syncStatus === 'error' ? (+ {region === 'center' ? (+ <>+ <Tooltip content={t('widgets.workflow.saveToLibraryWithEllipsis')}><IconButton- aria-label={t('widgets.workflow.librarySyncState')}- color="fg.error"+ aria-label={t('widgets.workflow.saveToLibraryWithEllipsis')}+ color="fg.muted"size="2xs"variant="ghost"- onClick={handleSaveToLibrary}+ onClick={saveToLibrary}>- <Icon as={SYNC_STATUS_VIEW.error.icon} boxSize="3.5" />+ <Icon as={BookmarkIcon} boxSize="3.5" /></IconButton>- ) : (+ </Tooltip>+ <Tooltip content={persistenceLabel}><BoxalignItems="center"- aria-label={t(SYNC_STATUS_VIEW[syncStatus].tooltipKey)}+ aria-label={persistenceLabel}boxSize="6"- color="fg.subtle"+ color={view.color}+ data-persistence-status={status}display="flex"justifyContent="center"role="status">- <Icon as={SYNC_STATUS_VIEW[syncStatus].icon} boxSize="3.5" />+ <Icon as={view.icon} boxSize="3.5" /></Box>- )}- </Tooltip>- ) : (- <Tooltip content={t('widgets.workflow.saveToLibrary')}>- <IconButton- aria-label={t('widgets.workflow.saveToLibrary')}- color="fg.muted"- size="2xs"- variant="ghost"- onClick={handleSaveToLibrary}- >- <Icon as={CloudUploadIcon} boxSize="3.5" />- </IconButton>- </Tooltip>- )}+ </Tooltip>+ </>+ ) : null}</HStack>);};export const WorkflowDialogHost = () => {- const { editGraph, replace } = useProjectGraphCommands();+ const { addWorkflow, editGraph } = useProjectGraphCommands();const { project: projectStore } = useWorkflowUi();const notify = useWorkflowNotifications();const { t } = useTranslation();- const notifyRef = useRef(notify);- const translationRef = useRef(t);const fileInputRef = useRef<HTMLInputElement | null>(null);const addNodeConnection = workflowUiStore.useSelector((snapshot) => snapshot.addNodeConnection);const addNodePosition = workflowUiStore.useSelector((snapshot) => snapshot.addNodePosition);const importRequestCount = workflowUiStore.useSelector((snapshot) => snapshot.importRequestCount);const isAddNodeOpen = workflowUiStore.useSelector((snapshot) => snapshot.isAddNodeOpen);const isLibraryOpen = workflowUiStore.useSelector((snapshot) => snapshot.isLibraryOpen);- const isNewWorkflowConfirmOpen = workflowUiStore.useSelector((snapshot) => snapshot.isNewWorkflowConfirmOpen);const lastImportRequestRef = useRef(importRequestCount);- useEffect(() => {- notifyRef.current = notify;- translationRef.current = t;- }, [notify, t]);-- // Create/dispose autosave in one mount lifecycle for StrictMode. Subscribe/read directly from the project store;- // fence status callbacks by mount account scope to reject late-account errors.- useEffect(() => {- const hostScope = captureAccountScope();- let autosaverActive = true;- let duplicateReturnNotificationShown = false;- const autosaver = createLibraryAutosaver({- onStatus: (status) => {- if (isAccountScopeCurrent(hostScope)) {- setWorkflowLibrarySyncStatus(status);- }- },- read: () => {- const graph = projectStore.getSnapshot().projectGraph;- return { libraryWorkflowId: graph.libraryWorkflowId, serialized: serializeWorkflowJson(graph) };- },- save: async (workflowId, serialized) => {- assertAccountScopeCurrent(hostScope);- const hasDuplicateWorkflowReturns = hasMultipleWorkflowReturnNodes(projectStore.getSnapshot().projectGraph);-- if (hasDuplicateWorkflowReturns) {- if (autosaverActive && !duplicateReturnNotificationShown) {- duplicateReturnNotificationShown = true;- notifyRef.current.error(- translationRef.current('workflowLibrary.saveFailed'),- translationRef.current('workflowLibrary.multipleWorkflowReturnNodes')- );- }- throw new Error('Workflow contains multiple workflow_return nodes.');- }+ // Editor session state (viewports) is keyed by workflow; release it once its workflow leaves the project.+ useMountEffect(() => {+ let lastMembership = '';- duplicateReturnNotificationShown = false;- await updateLibraryWorkflow(workflowId, serialized, hostScope.signal);- assertAccountScopeCurrent(hostScope);- // The library dialog serves cached payloads and pages; a save changes both.- invalidateWorkflowLibraryCache(workflowId);- },- });+ return projectStore.subscribe(() => {+ const snapshot = projectStore.getSnapshot();+ const liveWorkflowIds = snapshot.workflows.map((entry) => entry.document.id);+ const membership = `${snapshot.id}\0${liveWorkflowIds.join('\0')}`;- let lastGraph = projectStore.getSnapshot().projectGraph;- const unsubscribe = projectStore.subscribe(() => {- const graph = projectStore.getSnapshot().projectGraph;- if (graph !== lastGraph) {- lastGraph = graph;- if (!hasMultipleWorkflowReturnNodes(graph)) {- duplicateReturnNotificationShown = false;- }- autosaver.notifyGraphChanged();+ if (membership === lastMembership) {+ return;}- });-- const handler = (serialized: Record<string, unknown>) => autosaver.markSynced(serialized);- registerLibraryGraphSyncedHandler(handler);-- return () => {- autosaverActive = false;- unsubscribe();- releaseLibraryGraphSyncedHandler(handler);- autosaver.dispose();- };- }, [projectStore]);+ lastMembership = membership;+ releaseWorkflowViewportsExcept(snapshot.id, liveWorkflowIds);+ });+ });useEffect(() => {if (importRequestCount > lastImportRequestRef.current) {@@ -493,6 +481,7 @@ export const WorkflowDialogHost = () => {editGraph({ node: buildCurrentImageNode(getInsertPosition()), type: 'addNode' });}, [editGraph, getInsertPosition]);+ // A file is portable: whatever id it carries names nothing this project may write to.const importFile = useCallback((file: File) => {file@@ -502,20 +491,23 @@ export const WorkflowDialogHost = () => {const { document, warnings: updateWarnings } = updateLoadedWorkflowNodes(parsed, t);const warnings = [...parseWarnings, ...updateWarnings];- replace(document, `Imported "${file.name}"`);+ addWorkflow(document, {+ label: t('widgets.workflow.importedLabel', { name: file.name }),+ reusePlaceholder: true,+ });for (const warning of warnings) {- notify.info('Workflow import warning', warning);+ notify.info(t('widgets.workflow.importWarning'), warning);}}).catch((error: unknown) => {notify.error(- 'Failed to import workflow',- error instanceof Error ? error.message : 'The file is not a valid workflow JSON.'+ t('widgets.workflow.importFailed'),+ error instanceof Error ? error.message : t('widgets.workflow.importInvalid'));});},- [notify, replace, t]+ [addWorkflow, notify, t]);const handleImportFile = useCallback((event: ChangeEvent<HTMLInputElement>) => {@@ -529,10 +521,6 @@ export const WorkflowDialogHost = () => {},[importFile]);- const closeNewWorkflowConfirm = useCallback(() => setNewWorkflowConfirmOpen(false), []);- const confirmNewWorkflow = useCallback(() => {- replace(createProjectGraph(createWorkflowId('workflow')), 'New workflow');- }, [replace]);return (<>@@ -548,15 +536,8 @@ export const WorkflowDialogHost = () => {onOpenChange={setAddNodeOpen}/><WorkflowLibraryDialog isOpen={isLibraryOpen} onOpenChange={setWorkflowLibraryOpen} />+ <WorkflowPublicationHost /><PendingWorkflowLoader />- <ConfirmDialog- body="Replace the project graph with an empty workflow? You can undo this change during this session. Save the current workflow to the library first if you need a permanent copy."- confirmLabel="New workflow"- isOpen={isNewWorkflowConfirmOpen}- title="New workflow"- onClose={closeNewWorkflowConfirm}- onConfirm={confirmNewWorkflow}- /></>);};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.tsindex 64279198dc..73f394762e 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/contracts.ts@@ -1,6 +1,6 @@import type { ProjectGraphAction } from '@features/workflow/core/document';import type { ForLoopValidationReason } from '@features/workflow/core/forLoops';-import type { ProjectGraphState, XYPosition } from '@features/workflow/core/types';+import type { ProjectGraphState, ProjectWorkflowSource, XYPosition } from '@features/workflow/core/types';import type { LogSource } from '@platform/logging/contracts';export type WorkflowRegion = 'left' | 'right' | 'bottom' | 'center' | 'dialog' | 'popover' | 'floating';@@ -40,12 +40,28 @@ export interface WorkflowWidgetLabelProps {presentation?: 'compact' | 'expanded' | 'tooltip';}+/** Where an edit or history step lands; absent means the active project's active workflow. */+export interface WorkflowTarget {+ projectId: string;+ workflowId: string;+}+export interface WorkflowCommands {- bindLibraryWorkflow(libraryWorkflowId: string): void;- editGraph(action: ProjectGraphAction): void;- replace(document: ProjectGraphState, label: string): void;- redo(): void;- undo(): void;+ /** Adds and activates a document in the active project; returns the id the project knows it by. */+ addWorkflow(+ document: ProjectGraphState,+ options: { label: string; reusePlaceholder?: boolean; source?: ProjectWorkflowSource }+ ): string;+ createWorkflow(): string;+ duplicateWorkflow(workflowId: string, copyName: string): string | null;+ editGraph(action: ProjectGraphAction, target?: WorkflowTarget): void;+ redo(target?: WorkflowTarget): void;+ removeWorkflow(workflowId: string): void;+ renameWorkflow(workflowId: string, name: string): void;+ selectWorkflow(workflowId: string): void;+ /** Records a publication target; ignored once that project or workflow no longer exists. */+ setWorkflowSource(target: WorkflowTarget, source: ProjectWorkflowSource | undefined): void;+ undo(target?: WorkflowTarget): void;}export interface WorkflowWidgetCommands {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsxindex 1ecc237377..9a3d04fa94 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/CallSavedWorkflowSyncRuntime.browser.test.tsx@@ -144,17 +144,19 @@ describe('CallSavedWorkflowSyncRuntime with an unreachable child workflow', () =let graph: ProjectGraphState = { ...createProjectGraph('parent'), nodes };const listeners = new Set<() => void>();const snapshot = () => ({+ activeWorkflow: { document: graph },+ activeWorkflowId: graph.id,galleryValues: {},id: 'project-1',isWorkflowRunning: false,projectGraph: graph,workflowValues: {},+ workflows: [{ document: graph }],});let current = snapshot();// eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetimeconst adapter = {commands: {- bindLibraryWorkflow: vi.fn(),editGraph: (action: ProjectGraphAction) => {graph = projectGraphReducer(graph, action);current = snapshot();@@ -163,7 +165,6 @@ describe('CallSavedWorkflowSyncRuntime with an unreachable child workflow', () =}},redo: vi.fn(),- replace: vi.fn(),undo: vi.fn(),},getProjectGraph: () => graph,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 b241cabf5c..3a64dcf623 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@@ -172,20 +172,47 @@ const preferencesSnapshot = {workflowSnapToGrid: false,workflowValidateConnections: true,};-const projectSnapshot = {+const PROJECT_ID = 'project-1';+const projectSnapshotFor = (graph: ProjectGraphState) => ({+ activeWorkflow: { document: graph },+ activeWorkflowId: graph.id,galleryValues: {},- id: 'project-1',+ id: PROJECT_ID,isWorkflowRunning: false,- projectGraph,+ projectGraph: graph,workflowValues: {},-};+ workflows: [{ document: graph }],+});+const projectSnapshot = projectSnapshotFor(projectGraph);++/** Execution ports report this editor's own workflow as the run's origin, so node state is shown. */+const withOrigin = (+ port: Pick<WorkflowUiAdapter['nodeExecution'], 'get' | 'subscribe'>+): WorkflowUiAdapter['nodeExecution'] => ({+ ...port,+ getOrigin: () => ({ projectId: PROJECT_ID, workflowId: projectGraph.id }),+ subscribeOrigin: () => () => {},+});-const createAdapter = (nodeExecution: WorkflowUiAdapter['nodeExecution']): WorkflowUiAdapter =>+const createAdapter = (+ nodeExecution: Pick<WorkflowUiAdapter['nodeExecution'], 'get' | 'subscribe'>+): WorkflowUiAdapter =>({capabilities: { getSnapshot: () => ({ canUseCache: true }), subscribe: () => () => {} },- commands: { bindLibraryWorkflow: vi.fn(), editGraph: vi.fn(), redo: vi.fn(), replace: vi.fn(), undo: vi.fn() },+ commands: {+ addWorkflow: vi.fn(),+ createWorkflow: vi.fn(),+ duplicateWorkflow: vi.fn(),+ editGraph: vi.fn(),+ redo: vi.fn(),+ removeWorkflow: vi.fn(),+ renameWorkflow: vi.fn(),+ selectWorkflow: vi.fn(),+ setWorkflowSource: vi.fn(),+ undo: vi.fn(),+ },getProjectGraph: () => projectGraph,- nodeExecution,+ nodeExecution: withOrigin(nodeExecution),notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },openAddModels: vi.fn(),performance: {@@ -534,18 +561,13 @@ describe('InvocationFlowNode field entry', () => {const renderEntryNode = async () => {const store = createGraphStore({ ...createProjectGraph('entry-test'), nodes: [entryNode] });+ const base = createAdapter({ get: () => null, subscribe: () => () => {} });const adapter = {- ...createAdapter({ get: () => null, subscribe: () => () => {} }),- commands: {- bindLibraryWorkflow: vi.fn(),- editGraph: store.editGraph,- redo: vi.fn(),- replace: vi.fn(),- undo: store.undo,- },+ ...base,+ commands: { ...base.commands, editGraph: store.editGraph, undo: store.undo },getProjectGraph: store.getSnapshot,project: {- getSnapshot: () => ({ ...projectSnapshot, projectGraph: store.getSnapshot() }),+ getSnapshot: () => projectSnapshotFor(store.getSnapshot()),subscribe: store.subscribe,},} as unknown as WorkflowUiAdapter;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsxindex 7256687b22..ddba7d3986 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/WorkflowEditorView.tsx@@ -242,6 +242,7 @@ export const getInitialRenderFlowModel = (model: WorkflowFlowModel, viewport: Viconst WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);const projectId = useWorkflowProjectSelector((project) => project.id);+ const workflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);const ui = useWorkflowUi();const { mark: markWorkbenchPerf, measure: measureWorkbenchPerf, time: timeWorkbenchPerf } = ui.performance;const { editGraph, redo, undo } = useProjectGraphCommands();@@ -276,8 +277,8 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {nodeCount: projectGraph.nodes.length,});const viewportKey = useMemo(- () => getWorkflowViewportKey(projectId, runtime.instanceId),- [projectId, runtime.instanceId]+ () => getWorkflowViewportKey(projectId, workflowId, runtime.instanceId),+ [projectId, runtime.instanceId, workflowId]);const perfSource = useMemo<WorkflowPerfSource>(() => ({@@ -1220,9 +1221,10 @@ const WorkflowFlow = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {};export const WorkflowEditorView = ({ runtime }: { runtime: WorkflowRuntimeApi }) => {+ // Each project workflow is its own editor mount: selection, viewport and deferred large-graph work stay with it.const flowIdentity = useWorkflowProjectSelector((project) =>- `${project.id}:${isLargeWorkflowGraph({ edgeCount: project.projectGraph.edges.length, nodeCount: project.projectGraph.nodes.length }) ? 'large' : 'standard'}`+ `${project.id}:${project.activeWorkflowId}:${isLargeWorkflowGraph({ edgeCount: project.projectGraph.edges.length, nodeCount: project.projectGraph.nodes.length }) ? 'large' : 'standard'}`);useEffect(() => {diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.test.tsindex a290ed3629..47c26ee71f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.test.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.test.ts@@ -1,10 +1,20 @@import type { Viewport } from '@xyflow/react';-import { describe, expect, it } from 'vitest';+import { beforeEach, describe, expect, it } from 'vitest';-import { getWorkflowViewport, setWorkflowViewport } from './workflowViewportStore';+import {+ clearWorkflowViewports,+ getWorkflowViewport,+ getWorkflowViewportKey,+ releaseWorkflowViewportsExcept,+ setWorkflowViewport,+} from './workflowViewportStore';describe('workflowViewportStore', () => {+ beforeEach(() => {+ clearWorkflowViewports();+ });+it('stores workflow editor viewports per widget instance for the current session', () => {const viewport: Viewport = { x: 12, y: 24, zoom: 0.75 };@@ -15,4 +25,32 @@ describe('workflowViewportStore', () => {expect(getWorkflowViewport('workflow:center')).toEqual(viewport);expect(getWorkflowViewport('workflow:bottom')).toBeNull();});++ it('keeps one viewport per project workflow so switching brings each view back', () => {+ const first = getWorkflowViewportKey('project-1', 'wf-a', 'center');+ const second = getWorkflowViewportKey('project-1', 'wf-b', 'center');++ setWorkflowViewport(first, { x: 1, y: 1, zoom: 1 });+ setWorkflowViewport(second, { x: 2, y: 2, zoom: 2 });++ expect(first).not.toBe(second);+ expect(getWorkflowViewport(first)).toEqual({ x: 1, y: 1, zoom: 1 });+ expect(getWorkflowViewport(second)).toEqual({ x: 2, y: 2, zoom: 2 });+ });++ it('releases the viewports of workflows that left a project and leaves other projects alone', () => {+ const gone = getWorkflowViewportKey('project-1', 'wf-gone', 'center');+ const kept = getWorkflowViewportKey('project-1', 'wf-kept', 'center');+ const other = getWorkflowViewportKey('project-2', 'wf-gone', 'center');++ for (const key of [gone, kept, other]) {+ setWorkflowViewport(key, { x: 0, y: 0, zoom: 1 });+ }++ releaseWorkflowViewportsExcept('project-1', ['wf-kept']);++ expect(getWorkflowViewport(gone)).toBeNull();+ expect(getWorkflowViewport(kept)).not.toBeNull();+ expect(getWorkflowViewport(other)).not.toBeNull();+ });});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.tsindex 58ae001c1c..9d039be30d 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/editor/workflowViewportStore.ts@@ -13,7 +13,22 @@ registerAccountOwnedResource({name: 'workflow-viewports',});-export const getWorkflowViewportKey = (projectId: string, instanceId: string): string => `${projectId}:${instanceId}`;+/** One viewport per project workflow per editor instance, so switching workflows brings each one's view back. */+export const getWorkflowViewportKey = (projectId: string, workflowId: string, instanceId: string): string =>+ `${projectId}\u0000${workflowId}\u0000${instanceId}`;++/** Releases the viewports of a project's workflows that no longer exist. */+export const releaseWorkflowViewportsExcept = (projectId: string, liveWorkflowIds: readonly string[]): void => {+ const live = new Set(liveWorkflowIds);++ for (const key of viewports.keys()) {+ const [keyProjectId, keyWorkflowId] = key.split('\u0000');++ if (keyProjectId === projectId && keyWorkflowId !== undefined && !live.has(keyWorkflowId)) {+ viewports.delete(key);+ }+ }+};export const getWorkflowViewport = (key: string): Viewport | null => {const viewport = viewports.get(key);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsxindex d6a9654977..514dfb1a7f 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx@@ -146,6 +146,8 @@ export interface WorkflowFieldInputProps {invalid?: boolean;/** Owning invocation node, when known — lets widgets read sibling fields (e.g. the frame scrubber's companion video). */nodeId?: string;+ /** Owning project workflow, when known — an upload that finishes after a switch still lands in this one. */+ workflowId?: string;template: FieldInputTemplate;value: unknown;onChange: (value: unknown) => void;@@ -758,7 +760,15 @@ const MediaDropMonitor = ({return null;};-const ImageCollectionInput = ({ id, invalid, nodeId, onChange, template, value }: WorkflowFieldInputProps) => {+const ImageCollectionInput = ({+ id,+ invalid,+ nodeId,+ onChange,+ template,+ value,+ workflowId,+}: WorkflowFieldInputProps) => {const { t } = useTranslation();const { project } = useWorkflowUi();const names = useMemo(() => getImageCollectionNames(value), [value]);@@ -767,7 +777,16 @@ const ImageCollectionInput = ({ id, invalid, nodeId, onChange, template, value }// to the list this render saw.const appendNames = useCallback((added: string[]) => {- const node = project.getSnapshot().projectGraph.nodes.find((candidate) => candidate.id === nodeId);+ const snapshot = project.getSnapshot();+ const document = workflowId+ ? snapshot.workflows.find((entry) => entry.document.id === workflowId)?.document+ : snapshot.projectGraph;++ if (!document) {+ return;+ }++ const node = document.nodes.find((candidate) => candidate.id === nodeId);const current = getImageCollectionNames(node && isInvocationNode(node) ? node.data.inputs[template.name]?.value : value);@@ -777,7 +796,7 @@ const ImageCollectionInput = ({ id, invalid, nodeId, onChange, template, value }onChange(next.map((image_name) => ({ image_name })));}},- [nodeId, onChange, project, template.name, value]+ [nodeId, onChange, project, template.name, value, workflowId]);const removeAt = useCallback((index: number) => onChange(names.filter((_, i) => i !== index).map((image_name) => ({ image_name }))),diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsxindex 5b54e08e5b..9856bb82b1 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewDialog.browser.test.tsx@@ -8,6 +8,7 @@ import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workimport { ChakraProvider } from '@chakra-ui/react';import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';+import { createProjectGraph } from '@features/workflow/utility';import { system } from '@theme/system';import { act, StrictMode } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -101,13 +102,14 @@ vi.mock('@features/workflow/react', async (importOriginal) => ({useInvocationTemplatesSnapshot: () => templatesSnapshotRef.current,}));-const { createLibraryWorkflowMock } = vi.hoisted(() => ({- createLibraryWorkflowMock: vi.fn(),+const { createLibraryWorkflowRecordMock } = vi.hoisted(() => ({+ createLibraryWorkflowRecordMock: vi.fn(),}));-vi.mock('@features/workflow/queries', async (importOriginal) => ({+// The publication controller reaches the transport through the API module itself, not the queries barrel.+vi.mock('@features/workflow/data/api', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),- createLibraryWorkflow: createLibraryWorkflowMock,+ createLibraryWorkflowRecord: createLibraryWorkflowRecordMock,}));// Supply rendered English strings without starting the HTTP-backed i18n client.@@ -156,6 +158,8 @@ const TRANSLATIONS: Record<string, string> = {'graphPreview.thisGraph': 'This graph','graphPreview.title': 'Graph preview','workflowLibrary.saveFailed': 'Failed to save workflow',+ 'workflowLibrary.saved': 'Workflow saved',+ 'workflowLibrary.savedCreatedBody': 'Saved "{{name}}" to the library.',};const interpolate = (template: string, options?: Record<string, unknown>): string =>@@ -283,13 +287,20 @@ const preferencesSnapshot = {};// Keep adapter snapshots stable so external-store subscribers cannot loop on fresh equivalent objects.-const createProjectSnapshot = () => ({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: { edges: [], nodes: [], version: 1 as const },- workflowValues: {},-});+const createProjectSnapshot = () => {+ const projectGraph = createProjectGraph('workflow-1');++ return {+ activeWorkflow: { document: projectGraph },+ activeWorkflowId: projectGraph.id,+ galleryValues: {},+ id: 'project-1',+ isWorkflowRunning: false,+ projectGraph,+ workflowValues: {},+ workflows: [{ document: projectGraph }],+ };+};const createWorkflowUiAdapter = (): WorkflowUiAdapter => {const projectSnapshot = createProjectSnapshot();@@ -297,14 +308,24 @@ const createWorkflowUiAdapter = (): WorkflowUiAdapter => {return {capabilities: { getSnapshot: () => ({ canUseCache: true }), subscribe: () => () => {} },commands: {- bindLibraryWorkflow: vi.fn(),+ addWorkflow: vi.fn(),+ createWorkflow: vi.fn(),+ duplicateWorkflow: vi.fn(),editGraph: vi.fn(),redo: vi.fn(),- replace: vi.fn(),+ removeWorkflow: vi.fn(),+ renameWorkflow: vi.fn(),+ selectWorkflow: vi.fn(),+ setWorkflowSource: vi.fn(),undo: vi.fn(),},- getProjectGraph: () => ({ edges: [], nodes: [], version: 1 as const }),- nodeExecution: { get: () => null, subscribe: () => () => {} },+ getProjectGraph: () => projectSnapshot.projectGraph,+ nodeExecution: {+ get: () => null,+ getOrigin: () => null,+ subscribe: () => () => {},+ subscribeOrigin: () => () => {},+ },notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },performance: {mark: vi.fn(),@@ -384,7 +405,7 @@ describe('GraphPreviewDialog', () => {workflowUiAdapter = createWorkflowUiAdapter();downloads.downloadBlob.mockReset();downloads.downloadText.mockReset();- createLibraryWorkflowMock.mockReset();+ createLibraryWorkflowRecordMock.mockReset();fitViewMock.mockClear();templatesSnapshotRef.current = TEMPLATES_SNAPSHOT;});@@ -645,16 +666,17 @@ describe('GraphPreviewDialog', () => {expect(text).not.toContain('Resolved inputs');});- it('Open as → Edit in workflow editor replaces the document, opens the editor, closes the dialog', async () => {+ it('Open as → Edit in workflow editor adds the document as a project workflow, opens the editor, closes the dialog', async () => {await renderDialog(FIXTURE_SOURCE);await openAsMenu();await clickMenuItemWithText('Edit in workflow editor');- expect(workflowUiAdapter.commands.replace).toHaveBeenCalledTimes(1);- const [document_, label] = vi.mocked(workflowUiAdapter.commands.replace).mock.calls[0] ?? [];+ expect(workflowUiAdapter.commands.addWorkflow).toHaveBeenCalledTimes(1);+ const [document_, options] = vi.mocked(workflowUiAdapter.commands.addWorkflow).mock.calls[0] ?? [];expect(document_?.nodes).toHaveLength(3);- expect(label).toBe('Opened from graph preview');+ // A blank starter workflow may be taken over; an edited one gets the preview beside it.+ expect(options).toEqual({ label: 'Opened from graph preview', reusePlaceholder: true });expect(graphPreviewPort.openWorkflowEditor).toHaveBeenCalledTimes(1);expect(onOpenChange).toHaveBeenCalledWith(false);});@@ -670,8 +692,8 @@ describe('GraphPreviewDialog', () => {expect(document_?.nodes).toHaveLength(3);expect(document_?.name).toBe('Generate');expect(label).toBe('Opened from graph preview');- // Forking must not touch the current project's workflow.- expect(workflowUiAdapter.commands.replace).not.toHaveBeenCalled();+ // Forking must not touch the current project's workflows.+ expect(workflowUiAdapter.commands.addWorkflow).not.toHaveBeenCalled();expect(onOpenChange).toHaveBeenCalledWith(false);});@@ -715,7 +737,9 @@ describe('GraphPreviewDialog', () => {});it('Open as → Save to workflow library names the document from the source label and notifies success', async () => {- createLibraryWorkflowMock.mockResolvedValue('library-workflow-1');+ createLibraryWorkflowRecordMock.mockImplementation((workflow: Record<string, unknown>) =>+ Promise.resolve({ name: workflow.name, revision: 1, workflow, workflow_id: 'library-workflow-1' })+ );await renderDialog(FIXTURE_SOURCE);@@ -723,14 +747,21 @@ describe('GraphPreviewDialog', () => {await clickMenuItemWithText('Save to workflow library');await flushAsync();- expect(createLibraryWorkflowMock).toHaveBeenCalledTimes(1);- const [serialized] = createLibraryWorkflowMock.mock.calls[0] ?? [];+ expect(createLibraryWorkflowRecordMock).toHaveBeenCalledTimes(1);+ const [serialized, options] = createLibraryWorkflowRecordMock.mock.calls[0] ?? [];expect(serialized).toMatchObject({ name: 'Generate' });- expect(workflowUiAdapter.notifications.success).toHaveBeenCalledWith('Saved to workflow library');+ // A client-reserved id makes a resend after a lost answer idempotent.+ expect(options).toMatchObject({ reservedId: expect.any(String) });+ expect(workflowUiAdapter.notifications.success).toHaveBeenCalledWith(+ 'Workflow saved',+ 'Saved "Generate" to the library.'+ );+ // A preview is not a project workflow, so nothing in the project is pointed at the new template.+ expect(workflowUiAdapter.commands.setWorkflowSource).not.toHaveBeenCalled();});- it('Open as → Save to workflow library does not notify success when the save fails', async () => {- createLibraryWorkflowMock.mockRejectedValue(new Error('network down'));+ it('Open as → Save to workflow library retries a lost answer once under the same reserved id, never claiming success', async () => {+ createLibraryWorkflowRecordMock.mockRejectedValue(new Error('network down'));await renderDialog(FIXTURE_SOURCE);@@ -738,10 +769,11 @@ describe('GraphPreviewDialog', () => {await clickMenuItemWithText('Save to workflow library');await flushAsync();- expect(createLibraryWorkflowMock).toHaveBeenCalledTimes(1);+ expect(createLibraryWorkflowRecordMock).toHaveBeenCalledTimes(2);+ const [, first] = createLibraryWorkflowRecordMock.mock.calls[0] ?? [];+ const [, second] = createLibraryWorkflowRecordMock.mock.calls[1] ?? [];+ expect((second as { reservedId: string }).reservedId).toBe((first as { reservedId: string }).reservedId);expect(workflowUiAdapter.notifications.success).not.toHaveBeenCalled();- // `useSaveWorkflowToLibrary`'s own catch path (Task 8) reports the failure.- expect(workflowUiAdapter.notifications.error).toHaveBeenCalledWith('Failed to save workflow', expect.any(String));});it('Open as → Save to workflow library bails with an error notification when the graph has no saveable nodes', async () => {@@ -752,7 +784,7 @@ describe('GraphPreviewDialog', () => {await flushAsync();// Reject conversion with no recognized nodes before backend save.- expect(createLibraryWorkflowMock).not.toHaveBeenCalled();+ expect(createLibraryWorkflowRecordMock).not.toHaveBeenCalled();expect(workflowUiAdapter.notifications.error).toHaveBeenCalledWith('No saveable nodes in this graph.');expect(workflowUiAdapter.notifications.success).not.toHaveBeenCalled();});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsxindex b76bb3b17c..ec88a083be 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/graph-preview/GraphPreviewOpenAsMenu.tsx@@ -4,7 +4,7 @@ import type { ReactNode } from 'react';import { Menu, Portal } from '@chakra-ui/react';import { previewGraphToDocument } from '@features/workflow/core/graphToDocument';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';-import { useSaveWorkflowToLibrary } from '@features/workflow/ui/library/useSaveWorkflowToLibrary';+import { useWorkflowPublication } from '@features/workflow/ui/library/useWorkflowPublication';import { MenuActionItem } from '@features/workflow/ui/MenuActionItem';import {useWorkflowGraphPreview,@@ -43,7 +43,7 @@ export const GraphPreviewOpenAsMenu = ({const { workflows } = useWorkflowHostCommands();const graphPreview = useWorkflowGraphPreview();const notifications = useWorkflowNotifications();- const { saveDocumentAsNew } = useSaveWorkflowToLibrary();+ const { saveDocumentAsNew } = useWorkflowPublication();// A hook (not `getInvocationTemplatesSnapshot()`) so the "Edit in workflow// editor" item's disabled state updates live if the menu is opened while// templates are still loading.@@ -65,8 +65,8 @@ export const GraphPreviewOpenAsMenu = ({);}- // `replace` emits its own success notification and undo entry.- workflows.replace(document, t('graphPreview.openedFromPreview'));+ // The preview becomes a workflow of its own beside the project's others (or takes over an untouched blank).+ workflows.addWorkflow(document, { label: t('graphPreview.openedFromPreview'), reusePlaceholder: true });graphPreview.openWorkflowEditor();onClose();}, [graph, templatesSnapshot, notifications, t, workflows, graphPreview, onClose]);@@ -87,10 +87,15 @@ export const GraphPreviewOpenAsMenu = ({document.name = graph.label ?? sourceLabel;- const id = await saveDocumentAsNew(document);+ // The publication reports its own outcome; a lost answer is retried by the same captured request.+ const result = await saveDocumentAsNew(document, document.name);- if (id !== null) {- notifications.success(t('graphPreview.savedToLibrary'));+ if (result.status === 'failed') {+ const retried = await result.retry();++ if (retried.status === 'failed') {+ notifications.error(t('graphPreview.saveToLibraryFailed'), retried.message);+ }}}, [graph, templatesSnapshot, sourceLabel, saveDocumentAsNew, notifications, t]);const handleSaveToLibrary = useCallback(() => void saveToLibrary(), [saveToLibrary]);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsxnew file mode 100644index 0000000000..57fad409af--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/ProjectWorkflowsView.tsx@@ -0,0 +1,506 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';++import { Badge, Box, Flex, HStack, Icon, Image, 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';+import { useOpenAddModels, useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import { requestWorkflowPublication } from '@features/workflow/ui/workflowUiStore';+import { Button, IconButton } from '@platform/ui/Button';+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';+import { MenuContent } from '@platform/ui/Menu';+import { RenameDialog } from '@platform/ui/RenameDialog';+import { Scrollable } from '@platform/ui/Scrollable';+import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';+import {+ BookmarkIcon,+ CopyIcon,+ EllipsisIcon,+ ImageOffIcon,+ PencilIcon,+ PlusIcon,+ RefreshCwIcon,+ Trash2Icon,+ WorkflowIcon,+} from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import {+ isBundledLibraryWorkflowId,+ isUpdatableSource,+ toProjectWorkflowLibraryEntries,+} from './projectWorkflowEntries';+import { formatRelativeTime } from './relativeTime';+import { getWorkflowLibraryCardId } from './WorkflowLibraryCard';+import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';+import {+ resolveEntryRequirements,+ useModelRequirementDeps,+ useWorkflowLibraryMissingCounts,+ WorkflowRequirementsList,+} from './WorkflowRequirementsList';++/**+ * The project's own workflows, presented through the library's card contract. Everything here is a local+ * collection command; the library is only consulted for the selected workflow's source, and only on request.+ */++const DETAIL_RAIL_WIDTH = '18rem';+const THUMBNAIL_ASPECT_RATIO = 3 / 2;++export interface ProjectWorkflowsViewProps {+ contextMenuPoint: { x: number; y: number } | null;+ selectedWorkflowId: string | null;+ onAddWorkflow: () => void;+ onClose: () => void;+ onContextMenu: (workflowId: string, point: { x: number; y: number }) => void;+ onContextMenuClose: () => void;+ onPreview: (entry: ProjectWorkflowEntry) => void;+ onSelect: (workflowId: string | null) => void;+}++const keepOpenForCardRightClick = (event: { detail: { originalEvent: Event }; preventDefault(): void }) => {+ const original = event.detail.originalEvent;++ if (+ original instanceof PointerEvent &&+ original.button === 2 &&+ original.target instanceof Element &&+ original.target.closest('[data-workflow-card]') !== null+ ) {+ event.preventDefault();+ }+};++export const ProjectWorkflowsView = ({+ contextMenuPoint,+ selectedWorkflowId,+ onAddWorkflow,+ onClose,+ onContextMenu,+ onContextMenuClose,+ onPreview,+ onSelect,+}: ProjectWorkflowsViewProps) => {+ const { t } = useTranslation();+ const workflows = useWorkflowProjectSelector((project) => project.workflows);+ const activeWorkflowId = useWorkflowProjectSelector((project) => project.activeWorkflowId);+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const { createWorkflow, duplicateWorkflow, removeWorkflow, renameWorkflow, selectWorkflow } =+ useProjectGraphCommands();+ const [renameTarget, setRenameTarget] = useState<string | null>(null);+ const [removeTarget, setRemoveTarget] = useState<string | null>(null);++ const entries = useMemo(+ () =>+ toProjectWorkflowLibraryEntries(+ workflows,+ templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null+ ),+ [templatesSnapshot, workflows]+ );+ const missingCounts = useWorkflowLibraryMissingCounts(entries);+ const activeSelectionId = entries.some((entry) => entry.item.workflow_id === selectedWorkflowId)+ ? selectedWorkflowId+ : activeWorkflowId;+ const selectedEntry = entries.find((entry) => entry.item.workflow_id === activeSelectionId) ?? null;++ const openWorkflow = useCallback(+ (workflowId: string) => {+ selectWorkflow(workflowId);+ onClose();+ },+ [onClose, selectWorkflow]+ );+ const handleNewWorkflow = useCallback(() => {+ onSelect(createWorkflow());+ }, [createWorkflow, onSelect]);+ const handleDuplicate = useCallback(+ (workflowId: string, name: string) => {+ const copyId = duplicateWorkflow(workflowId, t('workflowLibrary.duplicateName', { name }));++ if (copyId) {+ onSelect(copyId);+ }+ },+ [duplicateWorkflow, onSelect, t]+ );+ const confirmRemove = useCallback(() => {+ if (removeTarget) {+ removeWorkflow(removeTarget);+ onSelect(null);+ }+ }, [onSelect, removeTarget, removeWorkflow]);+ const closeRename = useCallback(() => setRenameTarget(null), []);+ const closeRemove = useCallback(() => setRemoveTarget(null), []);+ const submitRename = useCallback(+ (name: string) => {+ if (renameTarget) {+ renameWorkflow(renameTarget, name);+ }+ },+ [renameTarget, renameWorkflow]+ );++ const renameEntry = renameTarget ? workflows.find((entry) => entry.document.id === renameTarget) : undefined;+ const removeEntry = removeTarget ? workflows.find((entry) => entry.document.id === removeTarget) : undefined;++ return (+ <>+ <Stack flex="1" gap="2" minH="0" minW="0">+ <HStack gap="2" justify="space-between" minW="0">+ <Text color="fg.muted" fontSize="xs" minW="0" truncate>+ {t('workflowLibrary.projectWorkflowCount', { count: workflows.length })}+ </Text>+ <HStack flexShrink={0} gap="1">+ <Button size="xs" variant="outline" onClick={handleNewWorkflow}>+ <PlusIcon />+ {t('workflowLibrary.newWorkflow')}+ </Button>+ <Button size="xs" variant="outline" onClick={onAddWorkflow}>+ <BookmarkIcon />+ {t('workflowLibrary.addWorkflow')}+ </Button>+ </HStack>+ </HStack>+ <HStack align="stretch" flex="1" gap="3" minH="0" minW="0">+ <WorkflowLibraryGrid+ activeWorkflowId={activeWorkflowId}+ entries={entries}+ error={null}+ missingCounts={missingCounts}+ selectedWorkflowId={activeSelectionId}+ status="loaded"+ onContextMenu={onContextMenu}+ onOpen={openWorkflow}+ onSelect={onSelect}+ />+ <ProjectWorkflowDetailPanel+ contextMenuPoint={contextMenuPoint}+ entry={selectedEntry ? selectedEntry.projectWorkflow : null}+ isActive={selectedEntry?.item.workflow_id === activeWorkflowId}+ missingCount={selectedEntry ? (missingCounts.get(selectedEntry.item.workflow_id) ?? 0) : 0}+ onContextMenuClose={onContextMenuClose}+ onDuplicate={handleDuplicate}+ onOpen={openWorkflow}+ onPreview={onPreview}+ onRemove={setRemoveTarget}+ onRename={setRenameTarget}+ />+ </HStack>+ </Stack>++ <RenameDialog+ initialName={renameEntry?.document.name ?? ''}+ isOpen={renameEntry !== undefined}+ label={t('workflowLibrary.workflowName')}+ submitLabel={t('workflowLibrary.rename')}+ title={t('workflowLibrary.renameTitle')}+ onClose={closeRename}+ onSubmit={submitRename}+ />+ <ConfirmDialog+ body={t('workflowLibrary.removeConfirmBody', {+ name: removeEntry?.document.name || t('workflowLibrary.untitled'),+ })}+ confirmLabel={t('workflowLibrary.remove')}+ isOpen={removeEntry !== undefined}+ title={t('workflowLibrary.removeConfirmTitle')}+ onClose={closeRemove}+ onConfirm={confirmRemove}+ />+ </>+ );+};++interface ProjectWorkflowDetailPanelProps {+ contextMenuPoint: { x: number; y: number } | null;+ entry: ProjectWorkflowEntry | null;+ isActive: boolean;+ missingCount: number;+ onContextMenuClose: () => void;+ onDuplicate: (workflowId: string, name: string) => void;+ onOpen: (workflowId: string) => void;+ onPreview: (entry: ProjectWorkflowEntry) => void;+ onRemove: (workflowId: string) => void;+ onRename: (workflowId: string) => void;+}++const ProjectWorkflowDetailPanel = ({+ contextMenuPoint,+ entry,+ isActive,+ missingCount,+ onContextMenuClose,+ onDuplicate,+ onOpen,+ onPreview,+ onRemove,+ onRename,+}: ProjectWorkflowDetailPanelProps) => {+ const { t } = useTranslation();+ const deps = useModelRequirementDeps();+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const openAddModels = useOpenAddModels();+ const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);++ const libraryEntry = useMemo(+ () =>+ entry+ ? toProjectWorkflowLibraryEntries(+ [entry],+ templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : null+ )[0]!+ : null,+ [entry, templatesSnapshot]+ );+ const resolved = useMemo(+ () =>+ libraryEntry?.enrichment.status === 'ready' ? resolveEntryRequirements(libraryEntry.enrichment, deps) : null,+ [deps, libraryEntry]+ );++ const contextMenuPositioning = useMemo(+ () => ({+ getAnchorRect: () =>+ contextMenuPoint ? { height: 1, width: 1, x: contextMenuPoint.x, y: contextMenuPoint.y } : null,+ placement: 'bottom-start' as const,+ }),+ [contextMenuPoint]+ );+ const handleContextMenuOpenChange = useCallback(+ (event: { open: boolean }) => {+ if (!event.open) {+ onContextMenuClose();+ }+ },+ [onContextMenuClose]+ );+ const contextMenuIds = useMemo(+ () => (entry ? { trigger: getWorkflowLibraryCardId(entry.document.id) } : undefined),+ [entry]+ );+ const moreActionsIds = useTooltipTriggerIds();+ const handleThumbnailError = useCallback(+ () => setFailedThumbnailUrl(libraryEntry?.item.thumbnail_url ?? null),+ [libraryEntry]+ );+ const entryId = entry?.document.id ?? null;+ const entryName = entry?.document.name || t('workflowLibrary.untitled');+ const handleOpen = useCallback(() => entryId && onOpen(entryId), [entryId, onOpen]);+ const handleRename = useCallback(() => entryId && onRename(entryId), [entryId, onRename]);+ const handleDuplicate = useCallback(+ () => entryId && onDuplicate(entryId, entryName),+ [entryId, entryName, onDuplicate]+ );+ const handleRemove = useCallback(() => entryId && onRemove(entryId), [entryId, onRemove]);+ const handlePreview = useCallback(() => entry && onPreview(entry), [entry, onPreview]);+ const handleSaveToLibrary = useCallback(+ () => entryId && requestWorkflowPublication({ kind: 'save-as-new', workflowId: entryId }),+ [entryId]+ );+ const handleUpdateTemplate = useCallback(+ () => entryId && requestWorkflowPublication({ kind: 'update-source', workflowId: entryId }),+ [entryId]+ );++ if (!entry || !libraryEntry) {+ return (+ <Box borderColor="border.subtle" borderWidth="1px" flexShrink={0} minH="0" rounded="md" w={DETAIL_RAIL_WIDTH} />+ );+ }++ const workflowId = entry.document.id;+ const name = entryName;+ const thumbnailUrl = libraryEntry.item.thumbnail_url;+ const showThumbnail = Boolean(thumbnailUrl) && thumbnailUrl !== failedThumbnailUrl;+ const lastRun = entry.lastRun ? formatRelativeTime(entry.lastRun.completedAt, new Date()) : '';+ const source = entry.source;+ const canUpdateSource = isUpdatableSource(source);++ const actionItems = (+ <>+ <MenuActionItem+ hint={t('workflowLibrary.openProjectWorkflowHint')}+ icon={WorkflowIcon}+ label={t('workflowLibrary.open')}+ value="open"+ onSelect={handleOpen}+ />+ <MenuActionItem+ icon={PencilIcon}+ label={t('workflowLibrary.renameWithEllipsis')}+ value="rename"+ onSelect={handleRename}+ />+ <MenuActionItem+ hint={t('workflowLibrary.duplicateProjectWorkflowHint')}+ icon={CopyIcon}+ label={t('workflowLibrary.duplicate')}+ value="duplicate"+ onSelect={handleDuplicate}+ />+ <MenuActionItem+ hint={t('workflowLibrary.saveToLibraryHint')}+ icon={BookmarkIcon}+ label={t('workflowLibrary.saveToLibraryWithEllipsis')}+ value="save-to-library"+ onSelect={handleSaveToLibrary}+ />+ {canUpdateSource ? (+ <MenuActionItem+ hint={t('workflowLibrary.updateTemplateHint')}+ icon={RefreshCwIcon}+ label={t('workflowLibrary.updateTemplate')}+ value="update-template"+ onSelect={handleUpdateTemplate}+ />+ ) : null}+ <MenuActionItem+ hint={t('workflowLibrary.removeHint')}+ icon={Trash2Icon}+ label={t('workflowLibrary.removeWithEllipsis')}+ tone="danger"+ value="remove"+ onSelect={handleRemove}+ />+ </>+ );++ return (+ <Stack+ borderColor="border.subtle"+ borderWidth="1px"+ data-project-workflow-detail={workflowId}+ flexShrink={0}+ gap="0"+ minH="0"+ rounded="md"+ w={DETAIL_RAIL_WIDTH}+ >+ <Scrollable flex="1" label={name} minH="0">+ <Stack gap="2" minW="0" p="2.5">+ <Stack gap="1" minW="0">+ <Box aspectRatio={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}+ />+ ) : (+ <Flex align="center" direction="column" gap="1" h="full" justify="center" w="full">+ <Icon aria-hidden as={ImageOffIcon} boxSize="5" color="fg.subtle" opacity={0.6} />+ <Text color="fg.subtle" fontSize="2xs">+ {t('workflowLibrary.notRunYet')}+ </Text>+ </Flex>+ )}+ </Box>+ {lastRun ? (+ <Text color="fg.subtle" fontSize="2xs">+ {t('workflowLibrary.lastRun', { when: lastRun })}+ </Text>+ ) : null}+ </Stack>++ <HStack gap="1.5" minW="0">+ <Text fontSize="sm" fontWeight="600" minW="0" overflowWrap="anywhere">+ {name}+ </Text>+ {isActive ? (+ <Badge flexShrink={0} size="xs" variant="solid">+ {t('workflowLibrary.activeWorkflow')}+ </Badge>+ ) : null}+ </HStack>++ {entry.document.description ? (+ <Text color="fg.muted" fontSize="2xs" lineClamp={4}>+ {entry.document.description}+ </Text>+ ) : null}++ <Text color="fg.subtle" fontSize="2xs" data-workflow-source={source?.libraryWorkflowId ?? 'none'}>+ {source+ ? isBundledLibraryWorkflowId(source.libraryWorkflowId)+ ? t('workflowLibrary.sourceBundled')+ : source.revision === null+ ? t('workflowLibrary.sourceUnknownRevision')+ : t('workflowLibrary.sourceRevision', { revision: source.revision })+ : t('workflowLibrary.sourceNone')}+ </Text>++ {libraryEntry.tags.length > 0 ? (+ <HStack flexWrap="wrap" gap="1" minW="0">+ {libraryEntry.tags.map((tag) => (+ <Badge key={tag} size="xs" variant="subtle">+ {tag}+ </Badge>+ ))}+ </HStack>+ ) : null}++ <WorkflowRequirementsList errorMessage={null} resolved={resolved} onFindModel={openAddModels} />+ </Stack>+ </Scrollable>++ <Stack borderColor="border.subtle" borderTopWidth="1px" gap="2" p="2.5">+ <HStack gap="2" minW="0">+ <Button disabled={isActive} flex="1" minW="0" size="sm" onClick={handleOpen}>+ {isActive ? t('workflowLibrary.activeWorkflow') : t('workflowLibrary.open')}+ </Button>+ <Menu.Root ids={moreActionsIds}>+ <Tooltip content={t('workflowLibrary.moreActions')} ids={moreActionsIds}>+ <Menu.Trigger asChild>+ <IconButton aria-label={t('workflowLibrary.moreActions')} size="sm" variant="outline">+ <EllipsisIcon />+ </IconButton>+ </Menu.Trigger>+ </Tooltip>+ <Portal>+ <Menu.Positioner>+ <MenuContent minW="16rem">{actionItems}</MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </HStack>+ <Button+ disabled={libraryEntry.enrichment.status !== 'ready'}+ size="sm"+ variant="outline"+ w="full"+ onClick={handlePreview}+ >+ <WorkflowIcon />+ {t('workflowLibrary.previewGraph')}+ </Button>+ {missingCount > 0 ? (+ <Text color="fg.warning" fontSize="2xs">+ {t('workflowLibrary.installModels', { count: missingCount })}+ </Text>+ ) : null}+ </Stack>++ <Menu.Root+ ids={contextMenuIds}+ open={contextMenuPoint !== null}+ positioning={contextMenuPositioning}+ onOpenChange={handleContextMenuOpenChange}+ onPointerDownOutside={keepOpenForCardRightClick}+ >+ <Portal>+ <Menu.Positioner>+ <MenuContent data-workflow-context-menu minW="16rem">+ {actionItems}+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsxindex ff2407bc39..32fef041e2 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryCard.tsx@@ -23,6 +23,8 @@ export const getWorkflowLibraryCardId = (workflowId: string): string => `workfloexport interface WorkflowLibraryCardProps {entry: WorkflowLibraryEntry;+ /** The project's active workflow; the card says so in the header. */+ isActive?: boolean;isSelected: boolean;/** Models this workflow needs that are not installed; 0 hides the badge. */missingCount: number;@@ -33,6 +35,7 @@ export interface WorkflowLibraryCardProps {export const WorkflowLibraryCard = ({entry,+ isActive = false,isSelected,missingCount,onContextMenu,@@ -108,7 +111,14 @@ export const WorkflowLibraryCard = ({)}</Box><Stack gap="1" minW="0" p="2.5" w="full">- <MiddleTruncate fontSize="xs" fontWeight="600" minW="0" text={item.name || t('workflowLibrary.untitled')} />+ <HStack gap="1.5" minW="0">+ <MiddleTruncate fontSize="xs" fontWeight="600" minW="0" text={item.name || t('workflowLibrary.untitled')} />+ {isActive ? (+ <Badge data-active-workflow flexShrink={0} size="xs" variant="solid">+ {t('workflowLibrary.activeWorkflow')}+ </Badge>+ ) : null}+ </HStack><HStack gap="1.5" h="4" minW="0">{enrichment.status === 'pending' ? (// Show placeholders only while enriching; unreadable workflows leave facts absent.diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsxindex 02a98c9df1..5b4ca4f417 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.browser.test.tsx@@ -1,5 +1,6 @@import type { StarterModel } from '@features/models';import type { WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';import type { WorkflowLibraryEntry, WorkflowLibraryEntryEnrichment } from '@features/workflow/data/libraryBrowseStore';import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';@@ -62,6 +63,9 @@ const queries = vi.hoisted(() => ({getLibraryWorkflowCached: vi.fn((_workflowId: string, _signal?: AbortSignal) =>Promise.resolve({} as Record<string, unknown>)),+ getLibraryWorkflowRecordCached: vi.fn((_workflowId: string, _signal?: AbortSignal) =>+ Promise.resolve({} as Record<string, unknown>)+ ),invalidateWorkflowLibraryCache: vi.fn(),}));@@ -76,6 +80,9 @@ vi.mock('@platform/browser/downloadBlob', () => ({ downloadText }));const TRANSLATIONS: Record<string, string> = {'common.unknownError': 'Something went wrong',+ 'workflowLibrary.addAnotherCopy': 'Add another copy',+ 'workflowLibrary.addAnotherCopyHint': 'A second, independent copy in this project',+ 'workflowLibrary.chooseProjectCopy': 'Open which copy?','workflowLibrary.delete': 'Delete','workflowLibrary.deleteConfirmBody': 'Delete "{{name}}" from the workflow library? This cannot be undone.','workflowLibrary.deleteConfirmTitle': 'Delete workflow',@@ -99,7 +106,9 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.moreActions': 'More actions','workflowLibrary.notRunYet': 'Not run yet','workflowLibrary.open': 'Open',- 'workflowLibrary.openHint': 'Replaces the current workflow',+ 'workflowLibrary.openHint': 'Adds a copy to this project',+ 'workflowLibrary.openProjectCopy': 'Open project copy',+ 'workflowLibrary.openProjectCopyHint': 'Switches to the copy this project already has','workflowLibrary.previewGraph': 'Preview graph','workflowLibrary.requirementInstallable': 'Not installed','workflowLibrary.requirementInstalled': 'Installed',@@ -204,6 +213,7 @@ const entry = (item: {category: 'user',description: `${overrides.name} description`,+ revision: 1,thumbnail_url: null,...overrides,},@@ -244,6 +254,23 @@ const RAW_WORKFLOW: Record<string, unknown> = {meta: { category: 'default', version: '3.0.0' },};+/** The library record behind IMAGE_TO_VIDEO, at the revision a fork must carry along. */+const RAW_RECORD = {+ ...IMAGE_TO_VIDEO.item,+ revision: 7,+ workflow: RAW_WORKFLOW,+};++/** Project copies of TEXT_TO_IMAGE: what Open resumes instead of adding another. */+const projectCopy = (id: string, name: string, libraryWorkflowId = 'wf-text-to-image'): ProjectWorkflowEntry => ({+ document: { ...createProjectGraph(id), name },+ source: { libraryWorkflowId, revision: 1 },+});+const FIRST_COPY = projectCopy('copy-1', 'Text to image');+const SECOND_COPY = projectCopy('copy-2', 'Text to image, tuned');+const OTHER_TEMPLATE_COPY = projectCopy('copy-other', 'Something else', 'wf-image-to-video');+const NO_COPIES: readonly ProjectWorkflowEntry[] = [];+// #endregionconst NOTIFICATIONS = { error: vi.fn(), info: vi.fn(), success: vi.fn() };@@ -263,8 +290,9 @@ describe('WorkflowLibraryDetailPanel', () => {let onClose: () => void;let onDeleted: () => void;let onDuplicated: (workflowId: string) => void;- let onOpen: (item: WorkflowLibraryEntry['item']) => void;+ let onOpen: (item: WorkflowLibraryEntry['item'], mode: 'resume-or-add' | 'add-copy') => void;let onPreview: (selected: WorkflowLibraryEntry) => void;+ let onResume: (workflowId: string) => void;/** See `WorkflowLibraryDialog.browser.test.tsx`: keeps Chakra's observer-driven commits inside the act scope. */const settleFrame = () =>@@ -272,7 +300,10 @@ describe('WorkflowLibraryDetailPanel', () => {setTimeout(resolve, 0);});- const renderPanel = async (selected: WorkflowLibraryEntry | null) => {+ const renderPanel = async (+ selected: WorkflowLibraryEntry | null,+ projectWorkflows: readonly ProjectWorkflowEntry[] = NO_COPIES+ ) => {await act(async () => {root.render(<StrictMode>@@ -282,12 +313,14 @@ describe('WorkflowLibraryDetailPanel', () => {<WorkflowLibraryDetailPanelcontextMenuPoint={null}entry={selected}+ projectWorkflows={projectWorkflows}onClose={onClose}onContextMenuClose={NOOP}onDeleted={onDeleted}onDuplicated={onDuplicated}onOpen={onOpen}onPreview={onPreview}+ onResume={onResume}/></WorkflowGraphPreviewProvider></WorkflowUiProvider>@@ -352,6 +385,7 @@ describe('WorkflowLibraryDetailPanel', () => {onDuplicated = vi.fn((_workflowId: string) => {});onOpen = vi.fn();onPreview = vi.fn();+ onResume = vi.fn();models.activeInstallSources.current = new Set();models.installedModels.current = [INSTALLED_SDXL_MAIN, INSTALLED_WAN_VAE];@@ -366,6 +400,8 @@ describe('WorkflowLibraryDetailPanel', () => {queries.deleteLibraryWorkflow.mockResolvedValue(undefined);queries.getLibraryWorkflowCached.mockClear();queries.getLibraryWorkflowCached.mockResolvedValue(RAW_WORKFLOW);+ queries.getLibraryWorkflowRecordCached.mockClear();+ queries.getLibraryWorkflowRecordCached.mockResolvedValue(RAW_RECORD);queries.invalidateWorkflowLibraryCache.mockClear();downloadText.mockClear();@@ -404,7 +440,64 @@ describe('WorkflowLibraryDetailPanel', () => {await clickButton('Open');- expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item);+ // No project copy exists yet, so opening adds the first one.+ expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item, 'resume-or-add');+ expect(onResume).not.toHaveBeenCalled();+ });++ it('resumes the one project copy of the template instead of adding another', async () => {+ await renderPanel(TEXT_TO_IMAGE, [OTHER_TEMPLATE_COPY, FIRST_COPY]);++ expect(buttonWithText('Open')).toBeUndefined();+ expect(buttonWithText('Open project copy')).not.toBeUndefined();++ await clickButton('Open project copy');++ expect(onResume).toHaveBeenCalledWith('copy-1');+ expect(onOpen).not.toHaveBeenCalled();+ });++ it('lets the user choose which of several project copies to resume', async () => {+ await renderPanel(TEXT_TO_IMAGE, [FIRST_COPY, OTHER_TEMPLATE_COPY, SECOND_COPY]);++ await clickButton('Open project copy');++ const chooser = () => document.querySelector<HTMLElement>('[data-workflow-copy-chooser]');+ await vi.waitFor(() => expect(chooser()).not.toBeNull());++ // Only this template's copies, by name, in collection order.+ const choices = [...(chooser()?.querySelectorAll<HTMLElement>('[data-menu-item]') ?? [])];+ expect(choices.map((choice) => choice.dataset.menuItem)).toEqual(['resume:copy-1', 'resume:copy-2']);+ expect(chooser()?.textContent).toContain('Text to image, tuned');+ expect(chooser()?.textContent).not.toContain('Something else');+ expect(onResume).not.toHaveBeenCalled();++ await act(async () => {+ choices[1]?.click();+ await settleFrame();+ });++ expect(onResume).toHaveBeenCalledWith('copy-2');+ expect(onOpen).not.toHaveBeenCalled();+ });++ it('offers another independent copy only once the project already has one', async () => {+ await renderPanel(TEXT_TO_IMAGE);+ await openMenu();++ expect(menuItem('add-copy')).toBeNull();+ expect(menuItem('open')?.textContent).toContain('Open');++ await renderPanel(TEXT_TO_IMAGE, [FIRST_COPY]);+ await openMenu();++ expect(menuItem('open')?.textContent).toContain('Open project copy');+ expect(menuItem('add-copy')?.textContent).toContain('Add another copy');++ await clickMenuItem('add-copy');++ expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item, 'add-copy');+ expect(onResume).not.toHaveBeenCalled();});it('opens the workflow from the keyboard, the path the double-click-only cards do not offer', async () => {@@ -423,7 +516,7 @@ describe('WorkflowLibraryDetailPanel', () => {await settleFrame();});- expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item);+ expect(onOpen).toHaveBeenCalledWith(TEXT_TO_IMAGE.item, 'resume-or-add');});it('swaps the primary action for an install when starter models can fill the gaps', async () => {@@ -585,17 +678,24 @@ describe('WorkflowLibraryDetailPanel', () => {expect(menuItem('duplicate')?.getAttribute('aria-disabled')).toBeNull();});- it('forks the cached workflow into a fresh project', async () => {+ it('forks the cached workflow into a fresh project, carrying its library source and revision', async () => {await renderPanel(IMAGE_TO_VIDEO);await clickMenuItem('fork-into-project');+ expect(queries.getLibraryWorkflowRecordCached).toHaveBeenCalledWith('wf-image-to-video', expect.anything());expect(OPEN_DOCUMENT_IN_NEW_PROJECT).toHaveBeenCalledTimes(1);- const [document_, label] = OPEN_DOCUMENT_IN_NEW_PROJECT.mock.calls[0] as [{ name: string }, string];+ const [document_, label, source] = OPEN_DOCUMENT_IN_NEW_PROJECT.mock.calls[0] as [+ { name: string },+ string,+ unknown,+ ];expect(document_.name).toBe('Image to video');expect(label).toBe('Image to video');+ // The copy can update its template later only if it knows which revision it started from.+ expect(source).toEqual({ libraryWorkflowId: 'wf-image-to-video', revision: 7 });// The fork lands the user in a new project, so the library gets out of the way.expect(onClose).toHaveBeenCalledTimes(1);expect(queries.createLibraryWorkflow).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsxindex 64f8bbe152..fe87133d6d 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDetailPanel.tsx@@ -1,4 +1,5 @@import type { StarterInstallSource } from '@features/models';+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';import type { WorkflowLibraryListItem } from '@features/workflow/queries';@@ -8,6 +9,7 @@ import {createLibraryWorkflow,deleteLibraryWorkflow,getLibraryWorkflowCached,+ getLibraryWorkflowRecordCached,invalidateWorkflowLibraryCache,} from '@features/workflow/queries';import { MenuActionItem } from '@features/workflow/ui/MenuActionItem';@@ -24,9 +26,18 @@ import {isAccountScopeCurrent,} from '@platform/state/accountLifecycle';import { getApiErrorMessage } from '@platform/transport/http';-import { Button, ConfirmDialog, IconButton, MenuContent, Scrollable } from '@platform/ui';+import {+ Button,+ ConfirmDialog,+ IconButton,+ MenuContent,+ Scrollable,+ Tooltip,+ useTooltipTriggerIds,+} from '@platform/ui';import {CopyIcon,+ CopyPlusIcon,DownloadIcon,EllipsisIcon,GitForkIcon,@@ -37,7 +48,10 @@ import {import { useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import type { OpenLibraryWorkflowMode } from './useOpenLibraryWorkflow';+import { formatRelativeTime } from './relativeTime';+import { planLibraryWorkflowOpen } from './useOpenLibraryWorkflow';import { getWorkflowLibraryCardId } from './WorkflowLibraryCard';import {resolveEntryRequirements,@@ -61,8 +75,12 @@ export interface WorkflowLibraryDetailPanelProps {onDeleted: () => void;/** Carries the copy's id so the shell can select it once the list refreshes. */onDuplicated: (workflowId: string) => void;- onOpen: (item: WorkflowLibraryListItem) => void;+ onOpen: (item: WorkflowLibraryListItem, mode: OpenLibraryWorkflowMode) => void;onPreview: (entry: WorkflowLibraryEntry) => void;+ /** Activates a project copy the project already made from this template. */+ onResume: (workflowId: string) => void;+ /** The project's workflows, so the rail can offer the existing copies of this template. */+ projectWorkflows: readonly ProjectWorkflowEntry[];}/** A right-click on another card moves the menu there (its own handler re-anchors it) rather than dismissing it. */@@ -79,6 +97,28 @@ const isCardTarget = (target: EventTarget | null): boolean =>const toFileSlug = (name: string): string => name.trim().replaceAll(/\s+/g, '-').toLowerCase() || 'workflow';+const CHOOSER_POSITIONING = { placement: 'top-start' } as const;++const ProjectCopyItem = ({+ copy,+ onResume,+}: {+ copy: ProjectWorkflowEntry;+ onResume: (workflowId: string) => void;+}) => {+ const { t } = useTranslation();+ const handleSelect = useCallback(() => onResume(copy.document.id), [copy.document.id, onResume]);++ return (+ <MenuActionItem+ icon={WorkflowIcon}+ label={copy.document.name || t('workflowLibrary.untitled')}+ value={`resume:${copy.document.id}`}+ onSelect={handleSelect}+ />+ );+};+export const WorkflowLibraryDetailPanel = ({contextMenuPoint,entry,@@ -88,6 +128,8 @@ export const WorkflowLibraryDetailPanel = ({onDuplicated,onOpen,onPreview,+ onResume,+ projectWorkflows,}: WorkflowLibraryDetailPanelProps) => {const { t } = useTranslation();const deps = useModelRequirementDeps();@@ -112,11 +154,36 @@ export const WorkflowLibraryDetailPanel = ({);const installableCount = resolved?.filter((requirement) => requirement.status === 'installable').length ?? 0;+ const openPlan = useMemo(+ () => (entry ? planLibraryWorkflowOpen(projectWorkflows, entry.item.workflow_id) : null),+ [entry, projectWorkflows]+ );+ const [isCopyChooserOpen, setIsCopyChooserOpen] = useState(false);++ /** Open lands in the project: the first copy is added, an existing one resumed, several offered as a choice. */const handleOpen = useCallback(() => {+ if (!entry || !openPlan) {+ return;+ }++ if (openPlan.kind === 'choose') {+ setIsCopyChooserOpen(true);+ return;+ }++ if (openPlan.kind === 'resume') {+ onResume(openPlan.workflowId);+ return;+ }++ onOpen(entry.item, 'resume-or-add');+ }, [entry, onOpen, onResume, openPlan]);+ const handleAddCopy = useCallback(() => {if (entry) {- onOpen(entry.item);+ onOpen(entry.item, 'add-copy');}}, [entry, onOpen]);+ const handleCopyChooserOpenChange = useCallback((event: { open: boolean }) => setIsCopyChooserOpen(event.open), []);const handlePreview = useCallback(() => {if (entry && entry.enrichment.status === 'ready') {@@ -229,15 +296,18 @@ export const WorkflowLibraryDetailPanel = ({const owner = captureAccountScope();try {- const raw = await getLibraryWorkflowCached(entry.item.workflow_id, owner.signal);+ const record = await getLibraryWorkflowRecordCached(entry.item.workflow_id, owner.signal);assertAccountScopeCurrent(owner);- const { document } = parseWorkflowJson(raw);+ const { document } = parseWorkflowJson({ ...record.workflow, id: record.workflow_id });// The port creates and activates a fresh project first, so the project// the library was opened from is left exactly as it was.- openDocumentInNewProject(document, entry.item.name);+ openDocumentInNewProject(document, entry.item.name, {+ libraryWorkflowId: record.workflow_id,+ revision: record.revision,+ });onClose();} catch (error) {if (isAccountScopeCurrent(owner)) {@@ -290,6 +360,10 @@ export const WorkflowLibraryDetailPanel = ({() => (entry ? { trigger: getWorkflowLibraryCardId(entry.item.workflow_id) } : undefined),[entry]);+ // The chooser is anchored to the button that opened it, so closing returns focus there.+ const openButtonId = entry ? `${getWorkflowLibraryCardId(entry.item.workflow_id)}-open` : undefined;+ const chooserIds = useMemo(() => (openButtonId ? { trigger: openButtonId } : undefined), [openButtonId]);+ const moreActionsIds = useTooltipTriggerIds();const confirmDelete = useCallback(async () => {if (!entry) {@@ -327,16 +401,28 @@ export const WorkflowLibraryDetailPanel = ({? t('workflowLibrary.sampleOutput'): null;+ const hasCopies = openPlan !== null && openPlan.kind !== 'add';+ const openLabel = hasCopies ? t('workflowLibrary.openProjectCopy') : t('workflowLibrary.open');+// One item set behind both the rail's overflow button and a card's right-click.const actionItems = (<><MenuActionItem- hint={t('workflowLibrary.openHint')}+ hint={hasCopies ? t('workflowLibrary.openProjectCopyHint') : t('workflowLibrary.openHint')}icon={WorkflowIcon}- label={t('workflowLibrary.open')}+ label={openLabel}value="open"onSelect={handleOpen}/>+ {hasCopies ? (+ <MenuActionItem+ hint={t('workflowLibrary.addAnotherCopyHint')}+ icon={CopyPlusIcon}+ label={t('workflowLibrary.addAnotherCopy')}+ value="add-copy"+ onSelect={handleAddCopy}+ />+ ) : null}<MenuActionItemhint={t('workflowLibrary.duplicateHint')}icon={CopyIcon}@@ -460,16 +546,18 @@ export const WorkflowLibraryDetailPanel = ({{t('workflowLibrary.installModels', { count: installableCount })}</Button>) : (- <Button flex="1" minW="0" size="sm" onClick={handleOpen}>- {t('workflowLibrary.open')}+ <Button flex="1" id={openButtonId} minW="0" size="sm" onClick={handleOpen}>+ {openLabel}</Button>)}- <Menu.Root>- <Menu.Trigger asChild>- <IconButton aria-label={t('workflowLibrary.moreActions')} size="sm" variant="outline">- <EllipsisIcon />- </IconButton>- </Menu.Trigger>+ <Menu.Root ids={moreActionsIds}>+ <Tooltip content={t('workflowLibrary.moreActions')} ids={moreActionsIds}>+ <Menu.Trigger asChild>+ <IconButton aria-label={t('workflowLibrary.moreActions')} size="sm" variant="outline">+ <EllipsisIcon />+ </IconButton>+ </Menu.Trigger>+ </Tooltip><Portal><Menu.Positioner><MenuContent minW="16rem">{actionItems}</MenuContent>@@ -501,6 +589,31 @@ export const WorkflowLibraryDetailPanel = ({</Portal></Menu.Root>+ {/* Several copies exist: the chooser lists them by name; another copy is a separate action. */}+ <Menu.Root+ ids={chooserIds}+ open={isCopyChooserOpen && openPlan?.kind === 'choose'}+ positioning={CHOOSER_POSITIONING}+ onOpenChange={handleCopyChooserOpenChange}+ >+ <Portal>+ <Menu.Positioner>+ <MenuContent data-workflow-copy-chooser minW="16rem">+ <Menu.ItemGroup>+ <Menu.ItemGroupLabel color="fg.subtle" fontSize="2xs" textTransform="uppercase">+ {t('workflowLibrary.chooseProjectCopy')}+ </Menu.ItemGroupLabel>+ {openPlan?.kind === 'choose'+ ? openPlan.copies.map((copy) => (+ <ProjectCopyItem key={copy.document.id} copy={copy} onResume={onResume} />+ ))+ : null}+ </Menu.ItemGroup>+ </MenuContent>+ </Menu.Positioner>+ </Portal>+ </Menu.Root>+<ConfirmDialogbody={t('workflowLibrary.deleteConfirmBody', { name })}confirmLabel={t('workflowLibrary.delete')}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 6c9fc9f282..caa3b0da96 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.browser.test.tsx@@ -1,16 +1,31 @@import type { StarterModel } from '@features/models';import type { WorkflowModelRequirement } from '@features/workflow/core/modelRequirements';-import type { InvocationTemplate, InvocationTemplatesSnapshot, ProjectGraphState } from '@features/workflow/core/types';+import type {+ InvocationTemplate,+ InvocationTemplatesSnapshot,+ ProjectGraphState,+ ProjectWorkflowEntry,+} from '@features/workflow/core/types';import type {WorkflowLibraryBrowseSnapshot,WorkflowLibraryEntry,WorkflowLibraryEntryEnrichment,} from '@features/workflow/data/libraryBrowseStore';-import type { WorkflowGraphPreviewPort, WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';+import type {+ WorkflowGraphPreviewPort,+ WorkflowReadPort,+ WorkflowUiAdapter,+} from '@features/workflow/ui/WorkflowUiContext';import { ChakraProvider } from '@chakra-ui/react';import { WorkflowGraphPreviewProvider, WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';+import {+ openWorkflowLibraryAtProjectWorkflow,+ setWorkflowLibraryTab,+ workflowUiStore,+} from '@features/workflow/ui/workflowUiStore';import { buildInvocationNode, createProjectGraph, projectGraphReducer } from '@features/workflow/utility';+import { accountLifecycle } from '@platform/state/accountLifecycle';import { system } from '@theme/system';import { act, StrictMode } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -120,14 +135,16 @@ vi.mock('@features/workflow/data/libraryBrowseStore', async () => {};});-// Test loader invocation and busy-state wiring here; load sequencing has separate coverage.+// Test opener invocation and busy-state wiring here; load sequencing has separate coverage.const loader = vi.hoisted(() => ({- load: vi.fn(() => Promise.resolve()),+ open: vi.fn((_item: unknown, _mode: 'resume-or-add' | 'add-copy') => Promise.resolve()),phase: { current: 'idle' as 'applying' | 'fetching' | 'idle' },+ resume: vi.fn((_workflowId: string) => {}),}));-vi.mock('./useLoadLibraryWorkflow', () => ({- useLoadLibraryWorkflow: () => ({ load: loader.load, loadPhase: loader.phase.current }),+vi.mock('./useOpenLibraryWorkflow', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useOpenLibraryWorkflow: () => ({ loadPhase: loader.phase.current, open: loader.open, resume: loader.resume }),}));// Use fixed model-store data so missing-model badges test dialog wiring rather than live catalogs.@@ -154,12 +171,18 @@ vi.mock('@features/models', async (importOriginal) => ({// Provide English/plural strings without booting the HTTP-backed i18n client.const TRANSLATIONS: Record<string, string> = {'common.close': 'Close',+ 'workflowLibrary.activeWorkflow': 'Active',+ 'workflowLibrary.addAnotherCopy': 'Add another copy',+ 'workflowLibrary.addAnotherCopyHint': 'A second, independent copy in this project',+ 'workflowLibrary.addWorkflow': 'Add workflow',+ 'workflowLibrary.chooseProjectCopy': 'Open which copy?','workflowLibrary.allTag': 'All','workflowLibrary.applying': 'Applying workflow…','workflowLibrary.browse': 'Browse','workflowLibrary.delete': 'Delete','workflowLibrary.downloadJson': 'Download JSON','workflowLibrary.duplicate': 'Duplicate',+ 'workflowLibrary.duplicateName': '{{name}} copy','workflowLibrary.empty': 'No workflows match these filters.','workflowLibrary.fetching': 'Fetching workflow…','workflowLibrary.forkIntoProject': 'Fork into new project',@@ -168,17 +191,40 @@ const TRANSLATIONS: Record<string, string> = {'workflowLibrary.loading': 'Loading workflows…','workflowLibrary.loadingMore': 'Loading more…','workflowLibrary.moreActions': 'More actions',+ 'workflowLibrary.newWorkflow': 'New workflow','workflowLibrary.nodeCount_one': '{{count}} node','workflowLibrary.nodeCount_other': '{{count}} nodes','workflowLibrary.notRunYet': 'Not run yet','workflowLibrary.open': 'Open',+ 'workflowLibrary.openHint': 'Adds a copy to this project',+ 'workflowLibrary.openProjectCopy': 'Open project copy',+ 'workflowLibrary.openProjectCopyHint': 'Switches to the copy this project already has','workflowLibrary.previewGraph': 'Preview graph',+ 'workflowLibrary.projectWorkflowCount_one': '{{count}} workflow in this project',+ 'workflowLibrary.projectWorkflowCount_other': '{{count}} workflows in this project',+ 'workflowLibrary.remove': 'Remove',+ 'workflowLibrary.removeConfirmBody':+ 'Remove "{{name}}" from this project? Its library template, if any, is not affected.',+ 'workflowLibrary.removeConfirmTitle': 'Remove workflow',+ 'workflowLibrary.removeWithEllipsis': 'Remove…',+ 'workflowLibrary.rename': 'Rename',+ 'workflowLibrary.renameTitle': 'Rename workflow',+ 'workflowLibrary.renameWithEllipsis': 'Rename…','workflowLibrary.requirementInstallable': 'Not installed','workflowLibrary.requires': 'Requires','workflowLibrary.sampleOutput': 'Sample output',+ 'workflowLibrary.saveToLibraryWithEllipsis': 'Save to library…','workflowLibrary.searchPlaceholder': 'Search names, tags, or descriptions',+ '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.thisProjectHint':+ 'Workflows saved with this project. Edits autosave here; the library changes only when you save to it.','workflowLibrary.title': 'Workflows','workflowLibrary.untitled': 'Untitled Workflow',+ 'workflowLibrary.updateTemplate': 'Update library template',+ 'workflowLibrary.workflowName': 'Workflow name','workflowLibrary.yours': 'Yours',};@@ -228,6 +274,7 @@ const entry = (category: 'user',description: `${name} description`,name,+ revision: 1,thumbnail_url: extras.thumbnailUrl ?? null,workflow_id: workflowId,},@@ -284,8 +331,75 @@ const withSnapshot = (patch: Partial<WorkflowLibraryBrowseSnapshot>): WorkflowLi...patch,});+const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {+ let snapshot = initialSnapshot;+ const listeners = new Set<() => void>();+ const port: WorkflowReadPort<Snapshot> = {+ getSnapshot: () => snapshot,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ return {+ port,+ setSnapshot: (next: Snapshot) => {+ snapshot = next;+ for (const listener of listeners) {+ listener();+ }+ },+ };+};++const PROJECT_ID = 'project-1';++/** The project's own collection: an unlinked active workflow, a bundled copy, and a copy of a user template. */+const ALPHA: ProjectWorkflowEntry = { document: { ...createProjectGraph('wf-alpha'), name: 'Alpha' } };+const BUNDLED_COPY: ProjectWorkflowEntry = {+ document: { ...createProjectGraph('wf-bundled'), name: 'Bundled copy' },+ source: { libraryWorkflowId: 'default_text_to_image', revision: 1 },+};+const USER_COPY: ProjectWorkflowEntry = {+ document: { ...PREVIEW_DOCUMENT, id: 'wf-user', name: 'User copy' },+ source: { libraryWorkflowId: 'wf-portrait', revision: 4 },+};+const PROJECT_WORKFLOWS: readonly ProjectWorkflowEntry[] = [ALPHA, BUNDLED_COPY, USER_COPY];++const projectSnapshot = (workflows: readonly ProjectWorkflowEntry[], activeWorkflowId = 'wf-alpha') => {+ const activeWorkflow = workflows.find((entry) => entry.document.id === activeWorkflowId) ?? workflows[0]!;++ return {+ activeWorkflow,+ activeWorkflowId: activeWorkflow.document.id,+ galleryValues: {},+ id: PROJECT_ID,+ isWorkflowRunning: false,+ projectGraph: activeWorkflow.document,+ workflowValues: {},+ workflows,+ };+};++const project = createMutablePort(projectSnapshot(PROJECT_WORKFLOWS));+const COMMANDS = {+ addWorkflow: vi.fn(() => 'wf-added'),+ createWorkflow: vi.fn(() => 'wf-new'),+ duplicateWorkflow: vi.fn((_workflowId: string, _copyName: string) => 'wf-copy'),+ editGraph: vi.fn(),+ redo: vi.fn(),+ removeWorkflow: vi.fn(),+ renameWorkflow: vi.fn(),+ selectWorkflow: vi.fn(),+ setWorkflowSource: vi.fn(),+ undo: vi.fn(),+};const UI_ADAPTER = {+ commands: COMMANDS,+ getProjectGraph: () => project.port.getSnapshot().projectGraph,notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+ openAddModels: vi.fn(),+ project: project.port,} as unknown as WorkflowUiAdapter;const GRAPH_PREVIEW = { openDocumentInNewProject: vi.fn() } as unknown as WorkflowGraphPreviewPort;@@ -398,8 +512,17 @@ describe('WorkflowLibraryDialog', () => {browse.ensureWorkflowLibraryBrowseLoaded.mockClear();browse.loadNextWorkflowLibraryPage.mockClear();browse.setWorkflowLibraryBrowseFilter.mockClear();- loader.load.mockClear();+ loader.open.mockClear();+ loader.resume.mockClear();loader.phase.current = 'idle';+ for (const command of Object.values(COMMANDS)) {+ command.mockClear();+ }+ project.setSnapshot(projectSnapshot(PROJECT_WORKFLOWS));+ // 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.+ setWorkflowLibraryTab('user');});afterEach(async () => {@@ -463,6 +586,8 @@ describe('WorkflowLibraryDialog', () => {await wait(0);expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ category: 'default', tag: null });+ // The segment follows the store's category, so the tab moves with it.+ expect(workflowUiStore.getSnapshot().libraryTab).toBe('default');});it('leaves the category alone when the account already has workflows', async () => {@@ -554,8 +679,8 @@ describe('WorkflowLibraryDialog', () => {card('wf-landscape')?.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));});- expect(loader.load).toHaveBeenCalledTimes(1);- expect(loader.load).toHaveBeenCalledWith(LANDSCAPE.item);+ expect(loader.open).toHaveBeenCalledTimes(1);+ expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'resume-or-add');});it('dedupes entries that share a workflow id', async () => {@@ -630,7 +755,7 @@ describe('WorkflowLibraryDialog', () => {await vi.waitFor(() => expect(open()).not.toBeNull());await act(() => open()?.click());- expect(loader.load).toHaveBeenCalledWith(LANDSCAPE.item);+ expect(loader.open).toHaveBeenCalledWith(LANDSCAPE.item, 'resume-or-add');});it('closes the card context menu on Escape and hands focus back to the card', async () => {@@ -661,10 +786,17 @@ describe('WorkflowLibraryDialog', () => {it('opens the selected workflow from the rail, the keyboard-reachable path', async () => {await openWith(LOADED_SNAPSHOT);- // Portrait needs nothing installed, so the rail's primary action is Open.+ // Portrait needs nothing installed, but the project already holds a copy of it: Open resumes that copy.+ await clickText('Open project copy');++ expect(loader.resume).toHaveBeenCalledWith('wf-user');+ expect(loader.open).not.toHaveBeenCalled();++ // Upscale has no copy yet (and nothing to install first), so Open adds one.+ await act(() => card('wf-upscale')?.click());await clickText('Open');- expect(loader.load).toHaveBeenCalledWith(PORTRAIT.item);+ expect(loader.open).toHaveBeenCalledWith(UPSCALE.item, 'resume-or-add');});it('badges the cards with the models their workflows still need', async () => {@@ -831,3 +963,241 @@ describe('WorkflowLibraryDialog', () => {expect(document.querySelector('[aria-busy="true"]')).not.toBeNull();});});++describe('WorkflowLibraryDialog — This project', () => {+ let host: HTMLDivElement;+ let root: Root;+ let onOpenChange: (isOpen: boolean) => void;++ const settleFrame = () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });++ const renderDialog = async () => {+ await act(async () => {+ root.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={UI_ADAPTER}>+ <WorkflowGraphPreviewProvider adapter={GRAPH_PREVIEW}>+ <WorkflowLibraryDialog isOpen onOpenChange={onOpenChange} />+ </WorkflowGraphPreviewProvider>+ </WorkflowUiProvider>+ </ChakraProvider>+ </StrictMode>+ );+ await settleFrame();+ });+ };++ const cards = () => [...document.querySelectorAll<HTMLElement>('[data-workflow-card]')];+ const card = (workflowId: string) => document.querySelector<HTMLElement>(`[data-workflow-card="${workflowId}"]`);+ const rail = () => document.querySelector<HTMLElement>('[data-project-workflow-detail]');+ const buttonWithText = (text: string) =>+ [...document.querySelectorAll('button')].find((candidate) => (candidate.textContent ?? '') === text);+ const alertDialog = () => document.querySelector<HTMLElement>('[role="alertdialog"]');++ const click = async (element: HTMLElement | null | undefined) => {+ expect(element).not.toBeFalsy();++ await act(async () => {+ element?.click();+ await settleFrame();+ });+ };+ const clickText = (text: string) => click(buttonWithText(text));+ const selectCard = (workflowId: string) => click(card(workflowId));++ const menuItem = (value: string) => document.querySelector<HTMLElement>(`[data-menu-item="${value}"]`);+ const openRailMenu = async () => {+ const trigger = rail()?.querySelector<HTMLElement>('[aria-label="More actions"]');+ expect(trigger).not.toBeNull();++ if (trigger?.getAttribute('data-state') !== 'open') {+ await click(trigger);+ }+ };+ const clickRailMenuItem = async (value: string) => {+ await openRailMenu();+ await click(menuItem(value));+ };++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ onOpenChange = vi.fn((_isOpen: boolean) => {});+ browse.ensureWorkflowLibraryBrowseLoaded.mockClear();+ browse.setWorkflowLibraryBrowseFilter.mockClear();+ loader.open.mockClear();+ loader.resume.mockClear();+ loader.phase.current = 'idle';+ for (const command of Object.values(COMMANDS)) {+ command.mockClear();+ }+ project.setSnapshot(projectSnapshot(PROJECT_WORKFLOWS));+ browse.setSnapshot?.(LOADED_SNAPSHOT);+ accountLifecycle.invalidate();+ // The library opens on the project's own workflows, as it does from the workflow header.+ openWorkflowLibraryAtProjectWorkflow(PROJECT_ID, 'wf-alpha');+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('lists every project workflow as a card, badges the active one, and never fetches templates', async () => {+ await renderDialog();++ expect(document.querySelector('[data-library-tab="project"]')).not.toBeNull();+ expect(cards().map((element) => element.dataset.workflowCard)).toEqual(['wf-alpha', 'wf-bundled', 'wf-user']);+ expect(document.body.textContent).toContain('3 workflows in this project');++ const badges = [...document.querySelectorAll<HTMLElement>('[data-workflow-card] [data-active-workflow]')];+ expect(badges).toHaveLength(1);+ expect(badges[0]?.closest<HTMLElement>('[data-workflow-card]')?.dataset.workflowCard).toBe('wf-alpha');+ expect(badges[0]?.textContent).toBe('Active');++ // The project view is local; no library page is requested and no search is offered.+ expect(browse.ensureWorkflowLibraryBrowseLoaded).not.toHaveBeenCalled();+ expect(document.querySelector('input[type="search"]')).toBeNull();+ });++ it('starts a fresh workflow from the header', async () => {+ await renderDialog();++ await clickText('New workflow');++ expect(COMMANDS.createWorkflow).toHaveBeenCalledTimes(1);+ expect(onOpenChange).not.toHaveBeenCalled();+ });++ it('moves to the bundled templates when asked to add a workflow', async () => {+ await renderDialog();++ await clickText('Add workflow');++ expect(workflowUiStore.getSnapshot().libraryTab).toBe('default');+ expect(browse.setWorkflowLibraryBrowseFilter).toHaveBeenCalledWith({ category: 'default', tag: null });+ expect(document.querySelector('[data-library-tab="default"]')).not.toBeNull();+ expect(browse.ensureWorkflowLibraryBrowseLoaded).toHaveBeenCalled();+ });++ it('opens a workflow from a double-click or the rail, then closes', async () => {+ await renderDialog();++ await act(() => card('wf-user')?.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));++ expect(COMMANDS.selectWorkflow).toHaveBeenCalledWith('wf-user');+ expect(onOpenChange).toHaveBeenCalledWith(false);++ await selectCard('wf-bundled');+ expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-bundled');++ await clickText('Open');++ expect(COMMANDS.selectWorkflow).toHaveBeenLastCalledWith('wf-bundled');+ expect(onOpenChange).toHaveBeenCalledTimes(2);+ });++ it('shows the active workflow in the rail with Open disabled, since it is already open', async () => {+ await renderDialog();++ expect(rail()?.dataset.projectWorkflowDetail).toBe('wf-alpha');+ expect((buttonWithText('Active') as HTMLButtonElement | undefined)?.disabled).toBe(true);+ expect(rail()?.querySelector('[data-workflow-source]')?.textContent).toBe('Not linked to a library template');+ });++ it('renames through the dialog', async () => {+ await renderDialog();+ await selectCard('wf-bundled');++ await clickRailMenuItem('rename');++ const input = document.querySelector<HTMLInputElement>('input[name="renameValue"]');+ expect(input?.value).toBe('Bundled copy');++ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;+ await act(async () => {+ setValue?.call(input, 'Bundled, tuned');+ input?.dispatchEvent(new Event('input', { bubbles: true }));+ await Promise.resolve();+ });+ await click(input?.closest('form')?.querySelector<HTMLButtonElement>('button[type="submit"]'));++ expect(COMMANDS.renameWorkflow).toHaveBeenCalledWith('wf-bundled', 'Bundled, tuned');+ });++ it('duplicates beside the original under a copy name', async () => {+ await renderDialog();+ await selectCard('wf-bundled');++ await clickRailMenuItem('duplicate');++ expect(COMMANDS.duplicateWorkflow).toHaveBeenCalledWith('wf-bundled', 'Bundled copy copy');+ // The copy becomes the selection so the rail shows what was just made.+ expect(workflowUiStore.getSnapshot().librarySelection).toEqual({ projectId: PROJECT_ID, workflowId: 'wf-copy' });+ });++ it('removes only after the confirmation is accepted', async () => {+ await renderDialog();+ await selectCard('wf-bundled');++ await clickRailMenuItem('remove');++ expect(alertDialog()?.textContent).toContain('Remove workflow');+ expect(alertDialog()?.textContent).toContain('Remove "Bundled copy" from this project?');+ expect(COMMANDS.removeWorkflow).not.toHaveBeenCalled();++ const confirm = [...(alertDialog()?.querySelectorAll('button') ?? [])].find(+ (candidate) => (candidate.textContent ?? '').trim() === 'Remove'+ );+ await click(confirm);++ expect(COMMANDS.removeWorkflow).toHaveBeenCalledWith('wf-bundled');+ });++ it('offers a template update only for a source the account can write', async () => {+ await renderDialog();+ await selectCard('wf-bundled');+ await openRailMenu();++ expect(rail()?.querySelector('[data-workflow-source]')?.textContent).toBe('From a bundled template (read-only)');+ expect(menuItem('save-to-library')).not.toBeNull();+ expect(menuItem('update-template')).toBeNull();++ await act(async () => {+ await userEvent.keyboard('{Escape}');+ });+ await selectCard('wf-user');+ await openRailMenu();++ expect(rail()?.querySelector('[data-workflow-source]')?.textContent).toBe(+ 'Linked to library template at revision 4'+ );+ expect(menuItem('update-template')).not.toBeNull();++ await click(menuItem('update-template'));++ expect(workflowUiStore.getSnapshot().publicationIntent).toEqual({ kind: 'update-source', workflowId: 'wf-user' });+ });++ it('previews a project workflow from its own document', async () => {+ await renderDialog();+ await selectCard('wf-user');++ await clickText('Preview graph');+ await act(async () => {+ await vi.waitFor(() => expect(document.querySelector('[data-preview-dialog]')).not.toBeNull(), {+ timeout: 2000,+ });+ });++ const preview = document.querySelector('[data-preview-dialog]');+ expect(preview?.getAttribute('data-graph-id')).toBe('wf-user');+ expect(preview?.getAttribute('data-source-label')).toBe('User copy');+ expect(preview?.textContent).toContain('integer');+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsxindex 5c2ca184f4..7659c49647 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryDialog.tsx@@ -1,3 +1,4 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';import type { WorkflowLibraryBrowseSnapshot, WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';import type { WorkflowLibraryListItem } from '@features/workflow/queries';import type { ChangeEvent } from 'react';@@ -10,13 +11,25 @@ import {useWorkflowLibraryBrowseSelector,} from '@features/workflow/data/libraryBrowseStore';import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';+import {+ setWorkflowLibrarySelection,+ setWorkflowLibraryTab,+ workflowUiStore,+ type WorkflowLibraryTab,+} from '@features/workflow/ui/workflowUiStore';import { useMountEffect } from '@platform/react/useMountEffect';import { CloseButton } from '@platform/ui';import { lazy, Suspense, useCallback, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { buildLibraryGraphPreviewSource } from './libraryPreviewSource';-import { useLoadLibraryWorkflow } from './useLoadLibraryWorkflow';+import { ProjectWorkflowsView } from './ProjectWorkflowsView';+import {+ type OpenLibraryWorkflowMode,+ planLibraryWorkflowOpen,+ useOpenLibraryWorkflow,+} from './useOpenLibraryWorkflow';import { WorkflowLibraryDetailPanel } from './WorkflowLibraryDetailPanel';import { WorkflowLibraryGrid } from './WorkflowLibraryGrid';import { WorkflowLibraryTagChips } from './WorkflowLibraryTagChips';@@ -31,10 +44,11 @@ const LazyGraphPreviewDialog = lazy(() =>const SEARCH_DEBOUNCE_MS = 300;-const CATEGORY_ITEMS = [+const TAB_ITEMS: ReadonlyArray<{ labelKey: string; value: WorkflowLibraryTab }> = [+ { labelKey: 'workflowLibrary.thisProject', value: 'project' },{ labelKey: 'workflowLibrary.browse', value: 'default' },{ labelKey: 'workflowLibrary.yours', value: 'user' },-] as const;+];/** Flat and shallow-comparable, so unrelated store patches do not re-render the shell. */const selectBrowseView = (snapshot: WorkflowLibraryBrowseSnapshot) => ({@@ -46,9 +60,14 @@ const selectBrowseView = (snapshot: WorkflowLibraryBrowseSnapshot) => ({tagCounts: snapshot.tagCounts,});+const selectLibraryNavigation = (snapshot: ReturnType<typeof workflowUiStore.getSnapshot>) => ({+ selection: snapshot.librarySelection,+ tab: snapshot.libraryTab,+});+/**- * On open, load the first page and choose defaults for empty accounts only if filters have not changed during the- * probe.+ * 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 = () => {useMountEffect(() => {@@ -57,6 +76,7 @@ const WorkflowLibraryBrowseSession = () => {if (userTotal === 0 && filter.category === 'user' && !filter.search) {setWorkflowLibraryBrowseFilter({ category: 'default', tag: null });+ setWorkflowLibraryTab('default');}});});@@ -64,6 +84,11 @@ const WorkflowLibraryBrowseSession = () => {return null;};+/** A preview request from either view: a library entry's enriched document or a project workflow's own. */+type PreviewRequest =+ | { kind: 'library'; entry: WorkflowLibraryEntry }+ | { kind: 'project'; entry: ProjectWorkflowEntry };+export const WorkflowLibraryDialog = ({isOpen,onOpenChange,@@ -73,25 +98,28 @@ export const WorkflowLibraryDialog = ({}) => {const { t } = useTranslation();const { category, entries, error, status, tag, tagCounts } = useWorkflowLibraryBrowseSelector(selectBrowseView);+ const { selection, tab } = workflowUiStore.useSelector(selectLibraryNavigation);+ const projectId = useWorkflowProjectSelector((project) => project.id);+ const projectWorkflows = useWorkflowProjectSelector((project) => project.workflows);const templatesSnapshot = useInvocationTemplatesSnapshot();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// them on reopen.- const [previewEntry, setPreviewEntry] = useState<WorkflowLibraryEntry | null>(null);- // Close before clearing previewEntry so the lazy dialog remains mounted through its exit transition.+ const [previewRequest, setPreviewRequest] = useState<PreviewRequest | null>(null);+ // Close before clearing the request so the lazy dialog remains mounted through its exit transition.const [isPreviewOpen, setIsPreviewOpen] = useState(false);const [contextMenuPoint, setContextMenuPoint] = useState<{ x: number; y: number } | null>(null);const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const closeDialog = useCallback(() => {// Closing the library removes its preview immediately; the parent surface is leaving too.- setPreviewEntry(null);+ setPreviewRequest(null);setIsPreviewOpen(false);setContextMenuPoint(null);onOpenChange(false);}, [onOpenChange]);- const { load, loadPhase } = useLoadLibraryWorkflow(closeDialog);+ const { loadPhase, open, resume } = useOpenLibraryWorkflow(closeDialog);const isLoadPending = loadPhase !== 'idle';const missingCounts = useWorkflowLibraryMissingCounts(entries);@@ -100,6 +128,8 @@ export const WorkflowLibraryDialog = ({? selectedWorkflowId: (entries[0]?.item.workflow_id ?? null);const activeEntry = entries.find((entry) => entry.item.workflow_id === activeWorkflowId) ?? null;+ // The project selection belongs to the project it was made in; another project starts from its active workflow.+ const projectSelectionId = selection?.projectId === projectId ? selection.workflowId : null;const handleDialogOpenChange = useCallback((event: { open: boolean }) => {@@ -117,7 +147,11 @@ export const WorkflowLibraryDialog = ({);const handlePreviewRequest = useCallback((entry: WorkflowLibraryEntry) => {- setPreviewEntry(entry);+ setPreviewRequest({ entry, kind: 'library' });+ setIsPreviewOpen(true);+ }, []);+ const handleProjectPreviewRequest = useCallback((entry: ProjectWorkflowEntry) => {+ setPreviewRequest({ entry, kind: 'project' });setIsPreviewOpen(true);}, []);@@ -132,18 +166,31 @@ export const WorkflowLibraryDialog = ({// arrives after that must not pull the mount out from under it.const handlePreviewExitComplete = useCallback(() => {if (!isPreviewOpen) {- setPreviewEntry(null);+ setPreviewRequest(null);}}, [isPreviewOpen]);// Only ready enrichment has a document; guard stale preview entries after revalidation.const previewSource = useMemo(() => {- if (!previewEntry || previewEntry.enrichment.status !== 'ready' || templatesSnapshot.status !== 'loaded') {+ if (!previewRequest || templatesSnapshot.status !== 'loaded') {return null;}- return buildLibraryGraphPreviewSource(previewEntry.enrichment.document, templatesSnapshot.templates);- }, [previewEntry, templatesSnapshot]);+ if (previewRequest.kind === 'project') {+ return buildLibraryGraphPreviewSource(previewRequest.entry.document, templatesSnapshot.templates);+ }++ return previewRequest.entry.enrichment.status === 'ready'+ ? buildLibraryGraphPreviewSource(previewRequest.entry.enrichment.document, templatesSnapshot.templates)+ : null;+ }, [previewRequest, templatesSnapshot]);+ const previewGraphId =+ previewRequest?.kind === 'project'+ ? previewRequest.entry.document.id+ : (previewRequest?.entry.item.workflow_id ?? '');+ const previewLabel =+ (previewRequest?.kind === 'project' ? previewRequest.entry.document.name : previewRequest?.entry.item.name) ||+ t('workflowLibrary.untitled');const handleSearchChange = useCallback((event: ChangeEvent<HTMLInputElement>) => {const { value } = event.currentTarget;@@ -158,13 +205,28 @@ export const WorkflowLibraryDialog = ({searchTimerRef.current = setTimeout(() => setWorkflowLibraryBrowseFilter({ search: value }), SEARCH_DEBOUNCE_MS);}, []);- const handleCategoryChange = useCallback((event: { value: string | null }) => {- // The store applies filter patches literally, so clearing the tag when the- // category changes (its chips do not carry over) is the UI's job.- if (event.value === 'default' || event.value === 'user') {- setWorkflowLibraryBrowseFilter({ category: event.value, tag: null });- }- }, []);+ const handleTabChange = useCallback(+ (event: { value: string | null }) => {+ setContextMenuPoint(null);++ if (event.value === 'project') {+ setWorkflowLibraryTab('project');+ return;+ }++ // The store applies filter patches literally, so clearing the tag when the+ // category changes (its chips do not carry over) is the UI's job.+ if (event.value === 'default' || event.value === 'user') {+ setWorkflowLibraryTab(event.value);++ if (category !== event.value) {+ setWorkflowLibraryBrowseFilter({ category: event.value, tag: null });+ }+ }+ },+ [category]+ );+ const goToTemplates = useCallback(() => handleTabChange({ value: 'default' }), [handleTabChange]);const handleTagSelect = useCallback((nextTag: string | null) => setWorkflowLibraryBrowseFilter({ tag: nextTag }), []);@@ -174,14 +236,28 @@ export const WorkflowLibraryDialog = ({(candidate) => candidate.item.workflow_id === workflowId);- if (entry) {- void load(entry.item);+ if (!entry) {+ return;}++ const plan = planLibraryWorkflowOpen(projectWorkflows, workflowId);++ if (plan.kind === 'choose') {+ // Several copies: the project view shows them all, with the first one selected.+ setWorkflowLibrarySelection({ projectId, workflowId: plan.copies[0]!.document.id });+ setWorkflowLibraryTab('project');+ return;+ }++ void open(entry.item, 'resume-or-add');},- [load]+ [open, projectId, projectWorkflows]);- const handleOpenItem = useCallback((item: WorkflowLibraryListItem) => void load(item), [load]);+ const handleOpenItem = useCallback(+ (item: WorkflowLibraryListItem, mode: OpenLibraryWorkflowMode) => void open(item, mode),+ [open]+ );const handleDeleted = useCallback(() => {setSelectedWorkflowId(null);@@ -189,7 +265,11 @@ export const WorkflowLibraryDialog = ({}, []);const handleCardContextMenu = useCallback((workflowId: string, point: { x: number; y: number }) => {- setSelectedWorkflowId(workflowId);+ if (tab === 'project') {+ setWorkflowLibrarySelection({ projectId, workflowId });+ } else {+ setSelectedWorkflowId(workflowId);+ }// An open menu does not follow a new anchor: close it and reopen it at the// new point once that close has rendered, as a native menu relocates.@@ -200,9 +280,15 @@ export const WorkflowLibraryDialog = ({setContextMenuPoint(point);}},- [contextMenuPoint]+ [contextMenuPoint, projectId, tab]);const closeContextMenu = useCallback(() => setContextMenuPoint(null), []);+ const handleProjectSelect = useCallback(+ (workflowId: string | null) => setWorkflowLibrarySelection(workflowId ? { projectId, workflowId } : null),+ [projectId]+ );++ const isProjectTab = tab === 'project';return (<>@@ -238,19 +324,30 @@ export const WorkflowLibraryDialog = ({<Stack gap="2" minW="0" w="full"><HStack gap="3" minW="0"><Dialog.Title flexShrink={0}>{t('workflowLibrary.title')}</Dialog.Title>- <Input- aria-label={t('workflowLibrary.searchPlaceholder')}- flex="1"- minW="0"- placeholder={t('workflowLibrary.searchPlaceholder')}+ {isProjectTab ? (+ <Text color="fg.subtle" flex="1" fontSize="xs" minW="0" truncate>+ {t('workflowLibrary.thisProjectHint')}+ </Text>+ ) : (+ <Input+ aria-label={t('workflowLibrary.searchPlaceholder')}+ flex="1"+ minW="0"+ placeholder={t('workflowLibrary.searchPlaceholder')}+ size="xs"+ type="search"+ value={searchInput}+ onChange={handleSearchChange}+ />+ )}+ <SegmentGroup.Root+ flexShrink={0}size="xs"- type="search"- value={searchInput}- onChange={handleSearchChange}- />- <SegmentGroup.Root flexShrink={0} size="xs" value={category} onValueChange={handleCategoryChange}>+ value={isProjectTab ? 'project' : category}+ onValueChange={handleTabChange}+ ><SegmentGroup.Indicator />- {CATEGORY_ITEMS.map((item) => (+ {TAB_ITEMS.map((item) => (<SegmentGroup.Item key={item.value} value={item.value}><SegmentGroup.ItemHiddenInput /><SegmentGroup.ItemText>{t(item.labelKey)}</SegmentGroup.ItemText>@@ -268,50 +365,70 @@ export const WorkflowLibraryDialog = ({/></Dialog.CloseTrigger></HStack>- <WorkflowLibraryTagChips selectedTag={tag} tagCounts={tagCounts} onSelect={handleTagSelect} />+ {isProjectTab ? null : (+ <WorkflowLibraryTagChips selectedTag={tag} tagCounts={tagCounts} onSelect={handleTagSelect} />+ )}</Stack></Dialog.Header><Dialog.Body- data-pending-preview={previewEntry?.item.workflow_id}+ data-library-tab={tab}+ data-pending-preview={previewGraphId || undefined}display="flex"flex="1"gap="3"minH="0">- <WorkflowLibraryGrid- entries={entries}- error={error}- missingCounts={missingCounts}- selectedWorkflowId={activeWorkflowId}- status={status}- onContextMenu={handleCardContextMenu}- onOpen={handleOpenWorkflow}- onSelect={setSelectedWorkflowId}- />- <WorkflowLibraryDetailPanel- contextMenuPoint={contextMenuPoint}- entry={activeEntry}- onClose={closeDialog}- onContextMenuClose={closeContextMenu}- onDeleted={handleDeleted}- onDuplicated={setSelectedWorkflowId}- onOpen={handleOpenItem}- onPreview={handlePreviewRequest}- />+ {isProjectTab ? (+ <ProjectWorkflowsView+ contextMenuPoint={contextMenuPoint}+ selectedWorkflowId={projectSelectionId}+ onAddWorkflow={goToTemplates}+ onClose={closeDialog}+ onContextMenu={handleCardContextMenu}+ onContextMenuClose={closeContextMenu}+ onPreview={handleProjectPreviewRequest}+ onSelect={handleProjectSelect}+ />+ ) : (+ <>+ <WorkflowLibraryGrid+ entries={entries}+ error={error}+ missingCounts={missingCounts}+ selectedWorkflowId={activeWorkflowId}+ status={status}+ onContextMenu={handleCardContextMenu}+ onOpen={handleOpenWorkflow}+ onSelect={setSelectedWorkflowId}+ />+ <WorkflowLibraryDetailPanel+ contextMenuPoint={contextMenuPoint}+ entry={activeEntry}+ projectWorkflows={projectWorkflows}+ onClose={closeDialog}+ onContextMenuClose={closeContextMenu}+ onDeleted={handleDeleted}+ onDuplicated={setSelectedWorkflowId}+ onOpen={handleOpenItem}+ onPreview={handlePreviewRequest}+ onResume={resume}+ />+ </>+ )}</Dialog.Body>- {isOpen ? <WorkflowLibraryBrowseSession /> : null}+ {isOpen && !isProjectTab ? <WorkflowLibraryBrowseSession /> : null}</Dialog.Content></Dialog.Positioner></Portal></Dialog.Root>- {previewEntry && previewSource ? (+ {previewRequest && previewSource ? (<Suspense fallback={null}><LazyGraphPreviewDialog- graphId={previewEntry.item.workflow_id}+ graphId={previewGraphId}hideInvokeisOpen={isPreviewOpen}source={previewSource}- sourceLabel={previewEntry.item.name || t('workflowLibrary.untitled')}+ sourceLabel={previewLabel}onExitComplete={handlePreviewExitComplete}onOpenChange={handlePreviewOpenChange}/>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsxindex 63ecb2a854..4554105529 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowLibraryGrid.tsx@@ -15,6 +15,8 @@ const GRID_TEMPLATE_COLUMNS = 'repeat(3, minmax(0, 1fr))';const NO_MISSING_COUNTS: ReadonlyMap<string, number> = new Map();export interface WorkflowLibraryGridProps {+ /** The project's active workflow, marked on its card in the This-project view. */+ activeWorkflowId?: string | null;entries: readonly WorkflowLibraryEntry[];error: string | null;/** Missing-model counts by workflow id; absent ids render no badge. */@@ -46,6 +48,7 @@ const dedupeByWorkflowId = (entries: readonly WorkflowLibraryEntry[]): WorkflowL};export const WorkflowLibraryGrid = ({+ activeWorkflowId = null,entries,error,missingCounts = NO_MISSING_COUNTS,@@ -101,6 +104,7 @@ export const WorkflowLibraryGrid = ({<WorkflowLibraryCardkey={entry.item.workflow_id}entry={entry}+ isActive={entry.item.workflow_id === activeWorkflowId}isSelected={entry.item.workflow_id === selectedWorkflowId}missingCount={missingCounts.get(entry.item.workflow_id) ?? 0}onContextMenu={onContextMenu}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.tsxnew file mode 100644index 0000000000..862eb56467--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.browser.test.tsx@@ -0,0 +1,648 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';+import type { WorkflowRecordDTO } from '@features/workflow/data/api';+import type { WorkflowReadPort, WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';++import { ChakraProvider } from '@chakra-ui/react';+import { WorkflowLibraryWriteRefusedError } from '@features/workflow/data/api';+import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';+import { requestWorkflowPublication, workflowUiStore } from '@features/workflow/ui/workflowUiStore';+import { createProjectGraph, serializeWorkflowJson } from '@features/workflow/utility';+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 { WorkflowPublicationHost } from './WorkflowPublicationHost';++/**+ * The publication controller reaches the transport through the API module itself (not the queries barrel), so+ * that is where the library is stubbed; the barrel re-exports the same stubs to the host's review fetch.+ */+const api = vi.hoisted(() => ({+ createLibraryWorkflowRecord: vi.fn(),+ getLibraryWorkflowRecord: vi.fn(),+ updateLibraryWorkflow: vi.fn(),+}));++vi.mock('@features/workflow/data/api', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ ...api,+}));++vi.mock('@features/workflow/react', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ useInvocationTemplatesSnapshot: () => ({ error: null, status: 'loaded', templates: {} }),+}));++const TRANSLATIONS: Record<string, string> = {+ 'common.cancel': 'Cancel',+ 'workflowLibrary.conflictStaleBody':+ 'The library template behind "{{name}}" has changed since this copy was loaded or last saved.',+ 'workflowLibrary.conflictTitle': 'Template has changed',+ 'workflowLibrary.conflictUnknownBody':+ 'It is not known whether the library template behind "{{name}}" still matches this copy.',+ 'workflowLibrary.replaceTemplate': 'Replace template',+ 'workflowLibrary.retry': 'Retry',+ 'workflowLibrary.retryBody':+ 'Saving "{{name}}" did not get an answer from the library ({{message}}). Retry the same save?',+ 'workflowLibrary.retryDiscard': 'Discard',+ 'workflowLibrary.retryTitle': 'Library did not answer',+ 'workflowLibrary.reviewBody':+ 'This is the current library template. Replacing it writes this project workflow over it.',+ 'workflowLibrary.reviewFailed': 'The current template could not be loaded.',+ 'workflowLibrary.reviewLoading': 'Loading the current template…',+ 'workflowLibrary.reviewRevision': 'Revision {{revision}} · updated {{when}}',+ 'workflowLibrary.reviewTemplate': 'Review current template',+ 'workflowLibrary.reviewTitle': 'Current library template',+ 'workflowLibrary.saveAsNew': 'Save as new',+ 'workflowLibrary.saveFailed': 'Failed to save workflow',+ 'workflowLibrary.saveToLibraryConfirm': 'Save',+ 'workflowLibrary.saveToLibraryExplanation':+ "Creates a new library template from this workflow. Its current input values become the template's defaults.",+ 'workflowLibrary.saveToLibraryTitle': 'Save to library',+ 'workflowLibrary.saved': 'Workflow saved',+ 'workflowLibrary.savedCreatedBody': 'Saved "{{name}}" to the library.',+ 'workflowLibrary.savedUpdatedBody': 'Updated "{{name}}" in the library.',+ 'workflowLibrary.templateName': 'Template name',+ 'workflowLibrary.unavailableBundledBody':+ '"{{name}}" came from a bundled template, which cannot be changed. Save it as a new template instead.',+ 'workflowLibrary.unavailableTitle': 'Template cannot be updated',+ 'workflowLibrary.untitled': 'Untitled Workflow',+ 'workflowLibrary.updateConfirm': 'Update template',+ 'workflowLibrary.updateConfirmBody':+ 'Replace the library template with the current graph, form, and input values of "{{name}}"?',+ 'workflowLibrary.updateConfirmCallers': 'Workflows that call this template will use the new version.',+ 'workflowLibrary.updateTitle': 'Update library template',+};++const interpolate = (template: string, options?: Record<string, unknown>): string =>+ options ? template.replaceAll(/\{\{(\w+)\}\}/g, (_match, key: string) => String(options[key] ?? '')) : template;++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: Record<string, unknown>) => interpolate(TRANSLATIONS[key] ?? key, options),+ }),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {+ let snapshot = initialSnapshot;+ const listeners = new Set<() => void>();+ const port: WorkflowReadPort<Snapshot> = {+ getSnapshot: () => snapshot,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ };+ return {+ port,+ setSnapshot: (next: Snapshot) => {+ snapshot = next;+ for (const listener of listeners) {+ listener();+ }+ },+ };+};++const PROJECT_ID = 'project-1';+const WORKFLOW_ID = 'wf-1';+const LIBRARY_ID = 'lib-1';++const UNLINKED: ProjectWorkflowEntry = { document: { ...createProjectGraph(WORKFLOW_ID), name: 'Alpha' } };+const LINKED: ProjectWorkflowEntry = { ...UNLINKED, source: { libraryWorkflowId: LIBRARY_ID, revision: 3 } };+const LINKED_UNKNOWN: ProjectWorkflowEntry = { ...UNLINKED, source: { libraryWorkflowId: LIBRARY_ID, revision: null } };+const BUNDLED: ProjectWorkflowEntry = { ...UNLINKED, source: { libraryWorkflowId: 'default_alpha', revision: 1 } };+const OTHER: ProjectWorkflowEntry = { document: { ...createProjectGraph('wf-2'), name: 'Beta' } };++const projectSnapshot = (workflows: readonly ProjectWorkflowEntry[]) => ({+ activeWorkflow: workflows[0]!,+ activeWorkflowId: workflows[0]!.document.id,+ galleryValues: {},+ id: PROJECT_ID,+ isWorkflowRunning: false,+ projectGraph: workflows[0]!.document,+ workflowValues: {},+ workflows,+});++const record = (overrides: Partial<WorkflowRecordDTO> = {}): WorkflowRecordDTO => ({+ category: 'user',+ description: '',+ name: 'Alpha',+ revision: 4,+ updated_at: new Date().toISOString(),+ workflow: serializeWorkflowJson({ ...createProjectGraph('lib-doc'), name: 'Alpha' }),+ workflow_id: LIBRARY_ID,+ ...overrides,+});++const deferred = <T,>() => {+ let reject!: (reason?: unknown) => void;+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });++ return { promise, reject, resolve };+};++describe('WorkflowPublicationHost', () => {+ let host: HTMLDivElement;+ let root: Root;+ let project: ReturnType<typeof createMutablePort<ReturnType<typeof projectSnapshot>>>;+ let commands: { setWorkflowSource: ReturnType<typeof vi.fn> };+ let notifications: {+ error: ReturnType<typeof vi.fn>;+ info: ReturnType<typeof vi.fn>;+ success: ReturnType<typeof vi.fn>;+ };++ const settleFrame = () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });++ /** Lets the async publication chain and the dialogs' presence transitions settle inside act. */+ const flush = () =>+ act(async () => {+ await settleFrame();+ await settleFrame();+ });++ const renderHost = async (workflows: readonly ProjectWorkflowEntry[]) => {+ project = createMutablePort(projectSnapshot(workflows));+ // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime+ const adapter = {+ commands,+ getProjectGraph: () => project.port.getSnapshot().projectGraph,+ notifications,+ project: project.port,+ } as unknown as WorkflowUiAdapter;++ await act(async () => {+ root.render(+ <StrictMode>+ <ChakraProvider value={system}>+ <WorkflowUiProvider adapter={adapter}>+ <WorkflowPublicationHost />+ </WorkflowUiProvider>+ </ChakraProvider>+ </StrictMode>+ );+ await settleFrame();+ });+ };++ const request = async (kind: 'save-as-new' | 'update-source', workflowId = WORKFLOW_ID) => {+ await act(async () => {+ requestWorkflowPublication({ kind, workflowId });+ await settleFrame();+ });+ };++ // A closed dialog stays mounted through its exit transition; only an open one counts as shown.+ const dialogs = () => [+ ...document.querySelectorAll<HTMLElement>(+ '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]'+ ),+ ];+ const dialogTitled = (title: string) =>+ dialogs().find((dialog) => dialog.querySelector('h2')?.textContent === title) ?? null;+ const saveDialog = () => document.querySelector<HTMLElement>('[data-save-to-library-dialog][data-state="open"]');+ const reviewDialog = () => document.querySelector<HTMLElement>('[data-workflow-review-dialog][data-state="open"]');+ const choice = (value: string) => document.querySelector<HTMLButtonElement>(`[data-choice="${value}"]`);+ const buttonWithText = (scope: ParentNode | null, text: string) =>+ [...(scope?.querySelectorAll('button') ?? [])].find((candidate) => (candidate.textContent ?? '').trim() === text);++ const click = async (element: HTMLElement | null | undefined) => {+ expect(element, 'expected an element to click').not.toBeFalsy();++ await act(async () => {+ element?.click();+ await settleFrame();+ });+ await flush();+ };++ const submitSaveAsNew = async (name: string) => {+ const dialog = saveDialog();+ expect(dialog).not.toBeNull();++ const input = dialog?.querySelector<HTMLInputElement>('input[name="templateName"]');+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;++ await act(async () => {+ setValue?.call(input, name);+ input?.dispatchEvent(new Event('input', { bubbles: true }));+ await Promise.resolve();+ });+ await click(buttonWithText(dialog, 'Save'));+ };++ const confirmUpdate = async () => {+ const dialog = dialogTitled('Update library template');+ expect(dialog).not.toBeNull();+ await click(buttonWithText(dialog, 'Update template'));+ };++ beforeEach(() => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ commands = { setWorkflowSource: vi.fn() };+ notifications = { error: vi.fn(), info: vi.fn(), success: vi.fn() };+ api.createLibraryWorkflowRecord.mockReset();+ api.getLibraryWorkflowRecord.mockReset();+ api.updateLibraryWorkflow.mockReset();+ // A fresh controller and an empty intent for every test.+ accountLifecycle.invalidate();+ });++ afterEach(async () => {+ await act(() => root.unmount());+ host.remove();+ });++ it('saves the workflow as a new template under the typed name and links the copy to it', async () => {+ api.createLibraryWorkflowRecord.mockImplementation((workflow: Record<string, unknown>) =>+ Promise.resolve(record({ name: String(workflow.name), revision: 1, workflow, workflow_id: 'lib-new' }))+ );++ await renderHost([UNLINKED, OTHER]);+ await request('save-as-new');++ expect(saveDialog()?.querySelector<HTMLInputElement>('input[name="templateName"]')?.value).toBe('Alpha');+ expect(workflowUiStore.getSnapshot().publicationIntent).toBeNull();++ await submitSaveAsNew('Alpha, published');++ expect(api.createLibraryWorkflowRecord).toHaveBeenCalledTimes(1);+ const [workflow, options] = api.createLibraryWorkflowRecord.mock.calls[0] as [+ Record<string, unknown>,+ { reservedId?: string },+ ];+ expect(workflow).toMatchObject({ ...serializeWorkflowJson(UNLINKED.document), name: 'Alpha, published' });+ expect(options.reservedId).toEqual(expect.any(String));+ // The project workflow now knows which template, at which revision, it can update later.+ expect(commands.setWorkflowSource).toHaveBeenCalledWith(+ { projectId: PROJECT_ID, workflowId: WORKFLOW_ID },+ { libraryWorkflowId: 'lib-new', revision: 1 }+ );+ expect(notifications.success).toHaveBeenCalledWith('Workflow saved', 'Saved "Alpha, published" to the library.');+ expect(saveDialog()).toBeNull();+ });++ it('updates the template at the revision the copy knows, after confirmation, keeping its own name', async () => {+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ name: 'Library alpha', revision: 3 }));+ api.updateLibraryWorkflow.mockResolvedValue(record({ name: 'Library alpha', revision: 4 }));++ await renderHost([LINKED]);+ await request('update-source');++ const dialog = dialogTitled('Update library template');+ expect(dialog?.textContent).toContain('input values of "Alpha"?');+ expect(api.updateLibraryWorkflow).not.toHaveBeenCalled();++ await confirmUpdate();++ expect(api.updateLibraryWorkflow).toHaveBeenCalledTimes(1);+ const [libraryId, workflow, options] = api.updateLibraryWorkflow.mock.calls[0] as [+ string,+ Record<string, unknown>,+ { expectedRevision?: number },+ ];+ expect(libraryId).toBe(LIBRARY_ID);+ expect(workflow).toEqual({ ...serializeWorkflowJson(LINKED.document), name: 'Library alpha' });+ expect(options.expectedRevision).toBe(3);+ expect(commands.setWorkflowSource).toHaveBeenCalledWith(+ { projectId: PROJECT_ID, workflowId: WORKFLOW_ID },+ { libraryWorkflowId: LIBRARY_ID, revision: 4 }+ );+ expect(notifications.success).toHaveBeenCalledWith('Workflow saved', 'Updated "Library alpha" in the library.');+ expect(dialogTitled('Update library template')).toBeNull();+ });++ it('surfaces a revision conflict after a confirmed update instead of closing silently', async () => {+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ revision: 3 }));+ api.updateLibraryWorkflow.mockRejectedValue(new WorkflowLibraryWriteRefusedError('revision-conflict', 'stale', 5));++ await renderHost([LINKED]);+ await request('update-source');+ await confirmUpdate();++ expect(api.updateLibraryWorkflow).toHaveBeenCalledTimes(1);+ expect(commands.setWorkflowSource).not.toHaveBeenCalled();+ expect(notifications.success).not.toHaveBeenCalled();++ const conflict = dialogTitled('Template has changed');+ expect(conflict?.textContent).toContain('has changed since this copy was loaded or last saved');+ expect(choice('save-as-new')).not.toBeNull();+ expect(choice('review')).not.toBeNull();+ });++ it('asks before writing when the copy never knew its template revision, and reviews before replacing', async () => {+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ description: 'Edited elsewhere', revision: 5 }));+ api.updateLibraryWorkflow.mockResolvedValue(record({ revision: 6 }));++ await renderHost([LINKED_UNKNOWN]);+ await request('update-source');++ const conflict = dialogTitled('Template has changed');+ expect(conflict?.textContent).toContain('It is not known whether the library template behind "Alpha"');+ expect(api.updateLibraryWorkflow).not.toHaveBeenCalled();++ await click(choice('review'));++ expect(api.getLibraryWorkflowRecord).toHaveBeenCalledWith(LIBRARY_ID, expect.anything());+ expect(reviewDialog()?.textContent).toContain('Edited elsewhere');+ expect(reviewDialog()?.textContent).toContain('Revision 5');+ expect(api.updateLibraryWorkflow).not.toHaveBeenCalled();++ await click(buttonWithText(reviewDialog(), 'Replace template'));+ await confirmUpdate();++ // The write is fenced at exactly the revision that was reviewed.+ expect(api.updateLibraryWorkflow).toHaveBeenCalledTimes(1);+ expect(api.updateLibraryWorkflow.mock.calls[0]?.[2]).toMatchObject({ expectedRevision: 5 });+ expect(commands.setWorkflowSource).toHaveBeenCalledWith(+ { projectId: PROJECT_ID, workflowId: WORKFLOW_ID },+ { libraryWorkflowId: LIBRARY_ID, revision: 6 }+ );+ expect(notifications.success).toHaveBeenCalledWith('Workflow saved', 'Updated "Alpha" in the library.');+ expect(dialogs()).toHaveLength(0);+ });++ it('lets a conflict be resolved by saving as a new template instead', async () => {+ await renderHost([LINKED_UNKNOWN]);+ await request('update-source');++ await click(choice('save-as-new'));++ expect(dialogTitled('Template has changed')).toBeNull();+ expect(saveDialog()).not.toBeNull();+ expect(api.updateLibraryWorkflow).not.toHaveBeenCalled();+ });++ it('refuses to update a bundled template and offers saving as new instead', async () => {+ await renderHost([BUNDLED]);+ await request('update-source');++ expect(dialogTitled('Template cannot be updated')?.textContent).toContain('came from a bundled template');+ expect(api.updateLibraryWorkflow).not.toHaveBeenCalled();+ });++ it('offers a retry after a lost answer and resends under the same reserved id', async () => {+ api.createLibraryWorkflowRecord+ .mockRejectedValueOnce(new Error('offline'))+ .mockImplementationOnce((workflow: Record<string, unknown>) =>+ Promise.resolve(record({ name: String(workflow.name), revision: 1, workflow, workflow_id: 'lib-new' }))+ );++ await renderHost([UNLINKED]);+ await request('save-as-new');+ await submitSaveAsNew('Alpha');++ expect(dialogTitled('Library did not answer')?.textContent).toContain('(offline)');+ expect(notifications.success).not.toHaveBeenCalled();++ await click(choice('retry'));++ expect(api.createLibraryWorkflowRecord).toHaveBeenCalledTimes(2);+ const first = api.createLibraryWorkflowRecord.mock.calls[0]?.[1] as { reservedId: string };+ const second = api.createLibraryWorkflowRecord.mock.calls[1]?.[1] as { reservedId: string };+ // The server matches the resend against whatever the first send created, so nothing is saved twice.+ expect(second.reservedId).toBe(first.reservedId);+ expect(dialogs()).toHaveLength(0);+ });++ it('links the copy and reports success once a retried save lands', async () => {+ api.createLibraryWorkflowRecord+ .mockRejectedValueOnce(new Error('offline'))+ .mockImplementationOnce((workflow: Record<string, unknown>) =>+ Promise.resolve(record({ name: String(workflow.name), revision: 1, workflow, workflow_id: 'lib-new' }))+ );++ await renderHost([UNLINKED]);+ await request('save-as-new');+ await submitSaveAsNew('Alpha');+ await click(choice('retry'));++ expect(commands.setWorkflowSource).toHaveBeenCalledWith(+ { projectId: PROJECT_ID, workflowId: WORKFLOW_ID },+ { libraryWorkflowId: 'lib-new', revision: 1 }+ );+ expect(notifications.success).toHaveBeenCalledWith('Workflow saved', 'Saved "Alpha" to the library.');+ });++ it("never lets an earlier project's late answer steer a publication opened in another project", async () => {+ const pending = deferred<WorkflowRecordDTO>();+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ revision: 3 }));+ api.updateLibraryWorkflow.mockReturnValueOnce(pending.promise);++ await renderHost([LINKED]);+ await request('update-source');+ await confirmUpdate();+ expect(api.updateLibraryWorkflow).toHaveBeenCalledTimes(1);++ // A duplicate of the project shares its workflow ids but points at a different template.+ const copied: ProjectWorkflowEntry = {+ ...LINKED,+ document: { ...LINKED.document, description: 'Only project B content', name: 'Beta project copy' },+ source: { libraryWorkflowId: 'lib-B', revision: 1 },+ };+ await act(() => project.setSnapshot({ ...projectSnapshot([copied]), id: 'project-2' }));+ await request('save-as-new');+ expect(saveDialog()).not.toBeNull();++ await act(async () => {+ pending.reject(new WorkflowLibraryWriteRefusedError('revision-conflict', 'stale', 5));+ await settleFrame();+ });+ await flush();++ // The late conflict belongs to the ended operation: the save dialog stays, no conflict dialog appears.+ expect(saveDialog()).not.toBeNull();+ expect(dialogTitled('Template has changed')).toBeNull();+ expect(saveDialog()?.querySelector<HTMLButtonElement>('button[type="submit"]')?.disabled).toBe(false);++ api.createLibraryWorkflowRecord.mockResolvedValue(record({ name: 'Beta', workflow_id: 'lib-C' }));+ await submitSaveAsNew('Beta');+ expect(api.createLibraryWorkflowRecord).toHaveBeenCalledTimes(1);+ expect(api.updateLibraryWorkflow).toHaveBeenCalledTimes(1);+ expect(commands.setWorkflowSource).toHaveBeenCalledWith(+ { projectId: 'project-2', workflowId: WORKFLOW_ID },+ { libraryWorkflowId: 'lib-C', revision: expect.any(Number) }+ );+ });++ it("keeps another project's open confirmation when an earlier update settles", async () => {+ const pending = deferred<WorkflowRecordDTO>();+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ revision: 3 }));+ api.updateLibraryWorkflow.mockReturnValueOnce(pending.promise);++ await renderHost([LINKED]);+ await request('update-source');+ await confirmUpdate();++ // Project B is a duplicate: same workflow id, its own template at its own revision.+ const copied: ProjectWorkflowEntry = { ...LINKED, source: { libraryWorkflowId: 'lib-B', revision: 1 } };+ await act(() => project.setSnapshot({ ...projectSnapshot([copied]), id: 'project-2' }));+ await request('update-source');+ expect(dialogTitled('Update library template')).not.toBeNull();++ await act(async () => {+ pending.resolve(record({ revision: 4 }));+ await settleFrame();+ });+ await flush();++ // A's settled confirmation closed A's dialog only; B's confirmation is still waiting for its answer.+ expect(dialogTitled('Update library template')).not.toBeNull();+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ revision: 1, workflow_id: 'lib-B' }));+ api.updateLibraryWorkflow.mockResolvedValueOnce(record({ revision: 2, workflow_id: 'lib-B' }));+ await confirmUpdate();+ expect(api.updateLibraryWorkflow).toHaveBeenLastCalledWith(+ 'lib-B',+ expect.anything(),+ expect.objectContaining({ expectedRevision: 1 })+ );+ });++ it("keeps another project's confirmation usable while an earlier update is still pending", async () => {+ const pending = deferred<WorkflowRecordDTO>();+ api.getLibraryWorkflowRecord.mockResolvedValue(record({ revision: 3 }));+ api.updateLibraryWorkflow.mockReturnValueOnce(pending.promise);++ await renderHost([LINKED]);+ await request('update-source');+ await confirmUpdate();++ const copied: ProjectWorkflowEntry = { ...LINKED, source: { libraryWorkflowId: 'lib-B', revision: 1 } };+ await act(() => project.setSnapshot({ ...projectSnapshot([copied]), id: 'project-2' }));+ await request('update-source');++ // B's confirmation is its own dialog: nothing of A's in-flight state reaches it.+ const dialog = dialogTitled('Update library template');+ expect(buttonWithText(dialog, 'Update template')?.disabled).toBe(false);+ expect(buttonWithText(dialog, 'Cancel')?.disabled).toBe(false);++ api.getLibraryWorkflowRecord.mockResolvedValue(record({ revision: 1, workflow_id: 'lib-B' }));+ api.updateLibraryWorkflow.mockResolvedValueOnce(record({ revision: 2, workflow_id: 'lib-B' }));+ await confirmUpdate();+ expect(api.updateLibraryWorkflow).toHaveBeenLastCalledWith('lib-B', expect.anything(), expect.anything());+ expect(dialogTitled('Update library template')).toBeNull();++ await act(async () => {+ pending.resolve(record({ revision: 4 }));+ await settleFrame();+ });+ await flush();+ expect(dialogs()).toHaveLength(0);+ });++ it('offers a lost save again after switching away and back, and resends it under the same reserved id', async () => {+ api.createLibraryWorkflowRecord+ .mockRejectedValueOnce(new TypeError('Failed to fetch'))+ .mockImplementationOnce((workflow: Record<string, unknown>, options: { reservedId: string }) =>+ // The first send did land: the server answers the resend with the record it already holds.+ Promise.resolve(record({ name: String(workflow.name), revision: 1, workflow, workflow_id: options.reservedId }))+ );++ await renderHost([UNLINKED]);+ await request('save-as-new');+ await submitSaveAsNew('Alpha');+ expect(dialogTitled('Library did not answer')).not.toBeNull();++ await act(() => project.setSnapshot({ ...projectSnapshot([OTHER]), id: 'project-2' }));+ await flush();+ expect(dialogs()).toHaveLength(0);++ await act(() => project.setSnapshot(projectSnapshot([UNLINKED])));+ await flush();+ expect(dialogTitled('Library did not answer')).not.toBeNull();++ await click(choice('retry'));++ expect(api.createLibraryWorkflowRecord).toHaveBeenCalledTimes(2);+ const first = api.createLibraryWorkflowRecord.mock.calls[0]?.[1] as { reservedId: string };+ const second = api.createLibraryWorkflowRecord.mock.calls[1]?.[1] as { reservedId: string };+ expect(second.reservedId).toBe(first.reservedId);+ expect(commands.setWorkflowSource).toHaveBeenCalledWith(+ { projectId: PROJECT_ID, workflowId: WORKFLOW_ID },+ { libraryWorkflowId: first.reservedId, revision: 1 }+ );+ expect(dialogs()).toHaveLength(0);++ // Settled: coming back again offers nothing.+ await act(() => project.setSnapshot({ ...projectSnapshot([OTHER]), id: 'project-2' }));+ await act(() => project.setSnapshot(projectSnapshot([UNLINKED])));+ await flush();+ expect(dialogs()).toHaveLength(0);+ });++ it('offers a lost save once per return, and lets the user discard it to save afresh', async () => {+ api.createLibraryWorkflowRecord+ .mockRejectedValueOnce(new TypeError('Failed to fetch'))+ .mockImplementation((workflow: Record<string, unknown>, options: { reservedId: string }) =>+ Promise.resolve(record({ name: String(workflow.name), revision: 1, workflow, workflow_id: options.reservedId }))+ );++ await renderHost([UNLINKED]);+ await request('save-as-new');+ await submitSaveAsNew('Alpha');+ expect(dialogTitled('Library did not answer')).not.toBeNull();++ // Cancel defers: the handle is kept and offered once more on the next return, then stays quiet.+ await click(buttonWithText(dialogTitled('Library did not answer'), 'Cancel'));+ expect(dialogs()).toHaveLength(0);+ await act(() => project.setSnapshot({ ...projectSnapshot([OTHER]), id: 'project-2' }));+ await act(() => project.setSnapshot(projectSnapshot([UNLINKED])));+ await flush();+ expect(dialogTitled('Library did not answer')).not.toBeNull();+ await click(buttonWithText(dialogTitled('Library did not answer'), 'Cancel'));+ await act(() => project.setSnapshot({ ...projectSnapshot([OTHER]), id: 'project-2' }));+ await act(() => project.setSnapshot(projectSnapshot([UNLINKED])));+ await flush();+ expect(dialogs()).toHaveLength(0);++ // A new save for that workflow meets the unanswered one first; discarding it lets the new save proceed.+ await request('save-as-new');+ expect(dialogTitled('Library did not answer')).not.toBeNull();+ expect(saveDialog()).toBeNull();+ await click(choice('discard'));+ expect(dialogs()).toHaveLength(0);++ await request('save-as-new');+ expect(saveDialog()).not.toBeNull();+ await submitSaveAsNew('Beta');+ expect(api.createLibraryWorkflowRecord).toHaveBeenCalledTimes(2);+ const first = api.createLibraryWorkflowRecord.mock.calls[0]?.[1] as { reservedId: string };+ const second = api.createLibraryWorkflowRecord.mock.calls[1]?.[1] as { reservedId: string };+ expect(second.reservedId).not.toBe(first.reservedId);+ expect(notifications.success).toHaveBeenCalledWith('Workflow saved', 'Saved "Beta" to the library.');+ });++ it('ends the stage when its workflow leaves the project', async () => {+ const pending = deferred<WorkflowRecordDTO>();+ api.createLibraryWorkflowRecord.mockReturnValue(pending.promise);++ await renderHost([UNLINKED, OTHER]);+ await request('save-as-new');+ expect(saveDialog()).not.toBeNull();++ await act(() => project.setSnapshot(projectSnapshot([OTHER])));+ await flush();++ expect(saveDialog()).toBeNull();++ // A request for a workflow the project does not hold starts nothing.+ await request('save-as-new', WORKFLOW_ID);+ expect(saveDialog()).toBeNull();+ expect(workflowUiStore.getSnapshot().publicationIntent).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsxnew file mode 100644index 0000000000..947d2e4992--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowPublicationHost.tsx@@ -0,0 +1,744 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';+import type { WorkflowRecordDTO } from '@features/workflow/queries';+import type { FormEvent } from 'react';++import { chakra, Dialog, Input, Portal, Stack, Text } from '@chakra-ui/react';+import { getLibraryWorkflowRecord } from '@features/workflow/queries';+import { useInvocationTemplatesSnapshot } from '@features/workflow/react';+import { useWorkflowProjectSelector, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { clearWorkflowPublicationIntent, workflowUiStore } from '@features/workflow/ui/workflowUiStore';+import { parseWorkflowJson } from '@features/workflow/utility';+import { useMountEffect } from '@platform/react/useMountEffect';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';+import { Button, CloseButton } from '@platform/ui/Button';+import { ConfirmDialog } from '@platform/ui/ConfirmDialog';+import { Field } from '@platform/ui/Field';+import { lazy, Suspense, useCallback, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { buildLibraryGraphPreviewSource } from './libraryPreviewSource';+import { isUpdatableSource } from './projectWorkflowEntries';+import { formatRelativeTime } from './relativeTime';+import {+ discardUnresolvedWorkflowPublication,+ getUnresolvedWorkflowPublication,+ takeUnresolvedWorkflowPublicationOffer,+ useWorkflowPublication,+ type WorkflowPublicationFailure,+} from './useWorkflowPublication';++/** Load graph preview only on request to keep xyflow outside the publication dialogs' chunk. */+const LazyGraphPreviewDialog = lazy(() =>+ import('@features/workflow/ui/graph-preview/GraphPreviewDialog').then((module) => ({+ default: module.GraphPreviewDialog,+ }))+);++type FailedResult = WorkflowPublicationFailure;++/**+ * The publication dialogs, always mounted beside the editor so any surface (header, menu, the project view) can+ * start one for any project workflow. One stage at a time; every stage names the workflow it works on, and a+ * workflow that leaves the project ends its stage.+ */+/** Every stage names the project and workflow it belongs to and the operation that started it. */+interface StageContext {+ projectId: string;+ workflowId: string;+ operation: number;+ /** A publication is in flight for this stage; its dialogs stay open and their controls wait. */+ busy: boolean;+}++type ActiveStage = StageContext &+ (+ | { kind: 'save-as-new' }+ | { kind: 'confirm-update'; libraryWorkflowId: string; expectedRevision: number }+ | {+ kind: 'conflict';+ libraryWorkflowId: string;+ /** Null when the copy's revision was never known (a migrated project). */+ currentRevision: number | null;+ }+ | { kind: 'unavailable'; reason: 'missing' | 'forbidden' | 'bundled' }+ | {+ kind: 'review';+ libraryWorkflowId: string;+ record: WorkflowRecordDTO | null;+ error: string | null;+ isPreviewOpen: boolean;+ }+ | { kind: 'retry'; failed: FailedResult }+ );++type Stage = { kind: 'idle' } | ActiveStage;++const IDLE: Stage = { kind: 'idle' };++const contextOf = (stage: ActiveStage, busy = false): StageContext => ({+ busy,+ operation: stage.operation,+ projectId: stage.projectId,+ workflowId: stage.workflowId,+});++export const WorkflowPublicationHost = () => {+ const { t } = useTranslation();+ const { project } = useWorkflowUi();+ const workflows = useWorkflowProjectSelector((project) => project.workflows);+ const projectId = useWorkflowProjectSelector((project) => project.id);+ const templatesSnapshot = useInvocationTemplatesSnapshot();+ const publication = useWorkflowPublication();+ const [stage, setStage] = useState<Stage>(IDLE);+ const operationRef = useRef(0);++ const findEntry = useCallback(+ (workflowId: string): ProjectWorkflowEntry | undefined =>+ workflows.find((entry) => entry.document.id === workflowId),+ [workflows]+ );++ // An intent is consumed as it is posted: the stage it opens is read from the project as it stands then. Each+ // intent starts a new operation, and a project switch ends whatever stage was open, so a late answer from an+ // earlier operation can never land on a stage it did not start. A publication that never got an answer is+ // offered once more, under its own reserved id, when the user comes back to that workflow, and always meets a+ // new save for that workflow first.+ useMountEffect(() => {+ const retryStage = (failed: FailedResult, projectId: string, workflowId: string): Stage => {+ operationRef.current += 1;+ return { busy: false, failed, kind: 'retry', operation: operationRef.current, projectId, workflowId };+ };+ const consume = () => {+ const intent = workflowUiStore.getSnapshot().publicationIntent;++ if (!intent) {+ return;+ }++ clearWorkflowPublicationIntent();++ const snapshot = project.getSnapshot();+ const entry = snapshot.workflows.find((candidate) => candidate.document.id === intent.workflowId);++ if (!entry) {+ return;+ }++ // An unanswered save comes first: resending it (or discarding it knowingly) is how a duplicate is avoided.+ const unresolved = getUnresolvedWorkflowPublication(snapshot.id, intent.workflowId);++ if (unresolved) {+ setStage(retryStage(unresolved, snapshot.id, intent.workflowId));+ return;+ }++ operationRef.current += 1;+ const context: StageContext = {+ busy: false,+ operation: operationRef.current,+ projectId: snapshot.id,+ workflowId: intent.workflowId,+ };++ if (intent.kind === 'save-as-new') {+ setStage({ ...context, kind: 'save-as-new' });+ } else if (isUpdatableSource(entry.source)) {+ setStage(+ entry.source.revision === null+ ? { ...context, currentRevision: null, kind: 'conflict', libraryWorkflowId: entry.source.libraryWorkflowId }+ : {+ ...context,+ expectedRevision: entry.source.revision,+ kind: 'confirm-update',+ libraryWorkflowId: entry.source.libraryWorkflowId,+ }+ );+ } else if (entry.source) {+ setStage({ ...context, kind: 'unavailable', reason: 'bundled' });+ }+ };+ let lastActiveKey = '';+ const followActiveWorkflow = () => {+ const snapshot = project.getSnapshot();+ const activeKey = `${snapshot.id}\u0000${snapshot.activeWorkflowId}`;+ const arrived = activeKey !== lastActiveKey;++ lastActiveKey = activeKey;++ // The offer is taken on arrival, outside the updater, so it is made exactly once per return.+ const offered = arrived ? takeUnresolvedWorkflowPublicationOffer(snapshot.id, snapshot.activeWorkflowId) : null;+ const recovery = offered ? retryStage(offered, snapshot.id, snapshot.activeWorkflowId) : null;++ setStage((current) => {+ const kept = current.kind !== 'idle' && current.projectId !== snapshot.id ? IDLE : current;++ return recovery && kept.kind === 'idle' ? recovery : kept;+ });+ };++ consume();+ followActiveWorkflow();+ const unsubscribers = [workflowUiStore.subscribe(consume), project.subscribe(followActiveWorkflow)];++ return () => unsubscribers.forEach((unsubscribe) => unsubscribe());+ });++ const activeStage: Stage =+ stage.kind !== 'idle' && (stage.projectId !== projectId || !findEntry(stage.workflowId)) ? IDLE : stage;+ const isBusy = activeStage.kind !== 'idle' && activeStage.busy;+ const stageEntry = activeStage.kind === 'idle' ? undefined : findEntry(activeStage.workflowId);+ const workflowName = stageEntry?.document.name || t('workflowLibrary.untitled');++ /** Moves the stage on only while the operation that asked for the move is still the one on screen. */+ const advance = useCallback(+ (operation: number, next: (current: ActiveStage) => Stage) =>+ setStage((current) => (current.kind === 'idle' || current.operation !== operation ? current : next(current))),+ []+ );++ const close = useCallback(() => setStage(IDLE), []);++ /** Routes a settled publication to its follow-up stage; published, invalid and busy are reported by the hook. */+ const follow = useCallback(+ (operation: number, result: Awaited<ReturnType<typeof publication.saveAsNew>>) =>+ advance(operation, (current) => {+ const context = contextOf(current);++ switch (result.status) {+ case 'conflict':+ return {+ ...context,+ currentRevision: result.currentRevision,+ kind: 'conflict',+ libraryWorkflowId: result.libraryWorkflowId,+ };+ case 'unavailable':+ return { ...context, kind: 'unavailable', reason: result.reason };+ case 'failed':+ return { ...context, failed: result, kind: 'retry' };+ default:+ return IDLE;+ }+ }),+ [advance]+ );++ const beginBusy = useCallback(+ (operation: number) => advance(operation, (current) => ({ ...current, busy: true })),+ [advance]+ );++ const handleSaveAsNew = useCallback(+ async (name: string) => {+ if (activeStage.kind === 'idle') {+ return;+ }++ const { operation, workflowId } = activeStage;++ beginBusy(operation);+ follow(operation, await publication.saveAsNew({ name, workflowId }));+ },+ [activeStage, beginBusy, follow, publication]+ );++ const handleUpdate = useCallback(+ async (target: Extract<ActiveStage, { kind: 'confirm-update' }>) => {+ const { expectedRevision, libraryWorkflowId, operation, workflowId } = target;++ beginBusy(operation);+ follow(operation, await publication.updateSource({ expectedRevision, libraryWorkflowId, workflowId }));+ },+ [beginBusy, follow, publication]+ );++ const handleRetry = useCallback(async () => {+ if (activeStage.kind !== 'retry') {+ return;+ }++ const { failed, operation } = activeStage;++ beginBusy(operation);+ follow(operation, await publication.retry(failed));+ }, [activeStage, beginBusy, follow, publication]);++ const startReview = useCallback(async () => {+ if (activeStage.kind !== 'conflict') {+ return;+ }++ const { libraryWorkflowId, operation } = activeStage;+ const owner = captureAccountScope();++ advance(operation, (current) => ({+ ...contextOf(current),+ error: null,+ isPreviewOpen: false,+ kind: 'review',+ libraryWorkflowId,+ record: null,+ }));++ try {+ // Always the live record: the review is what the replacement's revision is taken from.+ const record = await getLibraryWorkflowRecord(libraryWorkflowId, owner.signal);++ assertAccountScopeCurrent(owner);+ advance(operation, (current) => (current.kind === 'review' ? { ...current, record } : current));+ } catch (error) {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ advance(operation, (current) =>+ current.kind === 'review'+ ? { ...current, error: getApiErrorMessage(error, t('workflowLibrary.reviewFailed')) }+ : current+ );+ }+ }, [activeStage, advance, t]);++ const switchToSaveAsNew = useCallback(() => {+ if (activeStage.kind !== 'idle') {+ advance(activeStage.operation, (current) => ({ ...contextOf(current), kind: 'save-as-new' }));+ }+ }, [activeStage, advance]);++ const reviewPreviewSource = useMemo(() => {+ if (activeStage.kind !== 'review' || !activeStage.record || templatesSnapshot.status !== 'loaded') {+ return null;+ }++ try {+ const { document } = parseWorkflowJson({ ...activeStage.record.workflow, id: activeStage.record.workflow_id });++ return buildLibraryGraphPreviewSource(document, templatesSnapshot.templates);+ } catch {+ return null;+ }+ }, [activeStage, templatesSnapshot]);++ const openReviewPreview = useCallback(+ () => setStage((current) => (current.kind === 'review' ? { ...current, isPreviewOpen: true } : current)),+ []+ );+ const handleReviewPreviewOpenChange = useCallback(+ (open: boolean) =>+ setStage((current) => (current.kind === 'review' && !open ? { ...current, isPreviewOpen: false } : current)),+ []+ );++ const confirmReplaceReviewed = useCallback(() => {+ if (activeStage.kind === 'review' && activeStage.record) {+ const { libraryWorkflowId, operation, record } = activeStage;++ advance(operation, (current) => ({+ ...contextOf(current),+ expectedRevision: record.revision,+ kind: 'confirm-update',+ libraryWorkflowId,+ }));+ }+ }, [activeStage, advance]);+ // The confirm dialog closes itself once its confirmation settles; that close belongs to the operation the dialog+ // was shown for, so it neither ends the update it started nor a confirmation another operation opened since.+ const confirmOperation = activeStage.kind === 'confirm-update' ? activeStage.operation : null;+ // The confirm dialog is one instance per operation: an in-flight confirmation of one operation never leaves+ // another operation's confirmation disabled. The key follows the operation from the stage's first step, so the+ // instance is already mounted when a review turns into a confirmation, and it stays put through an ordinary close.+ const stageOperation = activeStage.kind === 'idle' ? null : activeStage.operation;+ const [confirmKey, setConfirmKey] = useState(0);++ if (stageOperation !== null && stageOperation !== confirmKey) {+ setConfirmKey(stageOperation);+ }++ const closeConfirmUpdate = useCallback(() => {+ setStage((current) =>+ current.kind === 'confirm-update' && !current.busy && current.operation === confirmOperation ? IDLE : current+ );+ }, [confirmOperation]);+ const confirmUpdate = useCallback(() => {+ if (activeStage.kind === 'confirm-update') {+ return handleUpdate(activeStage);+ }++ close();+ return undefined;+ }, [activeStage, close, handleUpdate]);+ const handleDialogOpenChange = useCallback((event: { open: boolean }) => (event.open ? undefined : close()), [close]);+ const handleReview = useCallback(() => void startReview(), [startReview]);+ const handleRetryClick = useCallback(() => void handleRetry(), [handleRetry]);+ // Discarding is a knowing choice: the dialog says the template may already exist if the library did receive it.+ const handleDiscard = useCallback(() => {+ if (activeStage.kind === 'retry') {+ discardUnresolvedWorkflowPublication(activeStage.projectId, activeStage.workflowId);+ }++ close();+ }, [activeStage, close]);++ const updateConfirmBody = useMemo(+ () => (+ <Stack gap="2">+ <Text>{t('workflowLibrary.updateConfirmBody', { name: workflowName })}</Text>+ <Text color="fg.muted" fontSize="xs">+ {t('workflowLibrary.updateConfirmCallers')}+ </Text>+ </Stack>+ ),+ [t, workflowName]+ );+ const conflictOptions = useMemo(+ () => [+ { label: t('workflowLibrary.saveAsNew'), onSelect: switchToSaveAsNew, value: 'save-as-new' },+ { label: t('workflowLibrary.reviewTemplate'), onSelect: handleReview, value: 'review' },+ ],+ [handleReview, switchToSaveAsNew, t]+ );+ const saveAsNewOptions = useMemo(+ () => [{ label: t('workflowLibrary.saveAsNew'), onSelect: switchToSaveAsNew, value: 'save-as-new' }],+ [switchToSaveAsNew, t]+ );+ const retryOptions = useMemo(+ () => [+ { label: t('workflowLibrary.retryDiscard'), onSelect: handleDiscard, value: 'discard' },+ { label: t('workflowLibrary.retry'), onSelect: handleRetryClick, value: 'retry' },+ ],+ [handleDiscard, handleRetryClick, t]+ );++ return (+ <>+ <SaveToLibraryDialog+ initialName={stageEntry?.document.name ?? ''}+ isOpen={activeStage.kind === 'save-as-new'}+ isPending={isBusy}+ onClose={close}+ onSubmit={handleSaveAsNew}+ />++ <ConfirmDialog+ key={confirmKey}+ body={updateConfirmBody}+ confirmLabel={t('workflowLibrary.updateConfirm')}+ isDestructive={false}+ isOpen={activeStage.kind === 'confirm-update'}+ title={t('workflowLibrary.updateTitle')}+ onClose={closeConfirmUpdate}+ onConfirm={confirmUpdate}+ />++ <ChoiceDialog+ body={+ activeStage.kind === 'conflict' && activeStage.currentRevision === null+ ? t('workflowLibrary.conflictUnknownBody', { name: workflowName })+ : t('workflowLibrary.conflictStaleBody', { name: workflowName })+ }+ isOpen={activeStage.kind === 'conflict'}+ options={conflictOptions}+ title={t('workflowLibrary.conflictTitle')}+ onClose={close}+ />++ <ChoiceDialog+ body={+ activeStage.kind === 'unavailable'+ ? t(+ activeStage.reason === 'missing'+ ? 'workflowLibrary.unavailableMissingBody'+ : activeStage.reason === 'bundled'+ ? 'workflowLibrary.unavailableBundledBody'+ : 'workflowLibrary.unavailableForbiddenBody',+ { name: workflowName }+ )+ : ''+ }+ isOpen={activeStage.kind === 'unavailable'}+ options={saveAsNewOptions}+ title={t('workflowLibrary.unavailableTitle')}+ onClose={close}+ />++ <ChoiceDialog+ body={+ activeStage.kind === 'retry'+ ? t('workflowLibrary.retryBody', { message: activeStage.failed.message, name: workflowName })+ : ''+ }+ isBusy={isBusy}+ isOpen={activeStage.kind === 'retry'}+ options={retryOptions}+ title={t('workflowLibrary.retryTitle')}+ onClose={close}+ />++ <Dialog.Root+ lazyMount+ open={activeStage.kind === 'review'}+ size="sm"+ unmountOnExit+ onOpenChange={handleDialogOpenChange}+ >+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content data-workflow-review-dialog>+ <Dialog.Header>+ <Dialog.Title>{t('workflowLibrary.reviewTitle')}</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ {activeStage.kind === 'review' ? (+ <ReviewBody+ error={activeStage.error}+ record={activeStage.record}+ workflowName={workflowName}+ onPreview={reviewPreviewSource ? openReviewPreview : undefined}+ />+ ) : null}+ </Dialog.Body>+ <Dialog.Footer>+ <Button size="xs" variant="ghost" onClick={close}>+ {t('common.cancel')}+ </Button>+ <Button size="xs" variant="outline" onClick={switchToSaveAsNew}>+ {t('workflowLibrary.saveAsNew')}+ </Button>+ <Button+ disabled={activeStage.kind !== 'review' || !activeStage.record}+ size="xs"+ variant="solid"+ onClick={confirmReplaceReviewed}+ >+ {t('workflowLibrary.replaceTemplate')}+ </Button>+ </Dialog.Footer>+ <Dialog.CloseTrigger asChild>+ <CloseButton />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>++ {activeStage.kind === 'review' && activeStage.record && reviewPreviewSource ? (+ <Suspense fallback={null}>+ <LazyGraphPreviewDialog+ graphId={activeStage.record.workflow_id}+ hideInvoke+ isOpen={activeStage.isPreviewOpen}+ source={reviewPreviewSource}+ sourceLabel={activeStage.record.name || t('workflowLibrary.untitled')}+ onOpenChange={handleReviewPreviewOpenChange}+ />+ </Suspense>+ ) : null}+ </>+ );+};++const ReviewBody = ({+ error,+ record,+ workflowName,+ onPreview,+}: {+ error: string | null;+ record: WorkflowRecordDTO | null;+ workflowName: string;+ onPreview: (() => void) | undefined;+}) => {+ const { t } = useTranslation();++ if (error) {+ return (+ <Text color="fg.error" fontSize="sm">+ {error}+ </Text>+ );+ }++ if (!record) {+ return (+ <Text color="fg.subtle" fontSize="sm" role="status">+ {t('workflowLibrary.reviewLoading')}+ </Text>+ );+ }++ return (+ <Stack gap="2">+ <Text fontSize="sm">{t('workflowLibrary.reviewBody', { name: workflowName })}</Text>+ <Stack gap="0.5">+ <Text fontSize="sm" fontWeight="600" overflowWrap="anywhere">+ {record.name || t('workflowLibrary.untitled')}+ </Text>+ {record.description ? (+ <Text color="fg.muted" fontSize="xs" lineClamp={3}>+ {record.description}+ </Text>+ ) : null}+ <Text color="fg.subtle" fontSize="2xs">+ {t('workflowLibrary.reviewRevision', {+ revision: record.revision,+ when: record.updated_at ? formatRelativeTime(record.updated_at, new Date()) : '',+ })}+ </Text>+ </Stack>+ {onPreview ? (+ <Button alignSelf="flex-start" size="xs" variant="outline" onClick={onPreview}>+ {t('workflowLibrary.previewGraph')}+ </Button>+ ) : null}+ </Stack>+ );+};++/** A short decision with named choices; Escape and the close control cancel. */+const ChoiceDialog = ({+ body,+ isBusy = false,+ isOpen,+ options,+ title,+ onClose,+}: {+ body: string;+ isBusy?: boolean;+ isOpen: boolean;+ options: ReadonlyArray<{ label: string; onSelect: () => void; value: string }>;+ title: string;+ onClose: () => void;+}) => {+ const { t } = useTranslation();+ const handleOpenChange = useCallback((event: { open: boolean }) => (event.open ? undefined : onClose()), [onClose]);++ return (+ <Dialog.Root+ closeOnEscape={!isBusy}+ closeOnInteractOutside={!isBusy}+ lazyMount+ open={isOpen}+ size="xs"+ unmountOnExit+ onOpenChange={handleOpenChange}+ >+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content>+ <Dialog.Header>+ <Dialog.Title>{title}</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Text fontSize="sm">{body}</Text>+ </Dialog.Body>+ <Dialog.Footer>+ <Button disabled={isBusy} size="xs" variant="ghost" onClick={onClose}>+ {t('common.cancel')}+ </Button>+ {options.map((option) => (+ <ChoiceButton key={option.value} isBusy={isBusy} option={option} />+ ))}+ </Dialog.Footer>+ <Dialog.CloseTrigger asChild>+ <CloseButton disabled={isBusy} />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};++const ChoiceButton = ({+ isBusy,+ option,+}: {+ isBusy: boolean;+ option: { label: string; onSelect: () => void; value: string };+}) => (+ <Button data-choice={option.value} loading={isBusy} size="xs" variant="solid" onClick={option.onSelect}>+ {option.label}+ </Button>+);++/** Names the new template. The explanation is the contract: current input values become the template's defaults. */+export const SaveToLibraryDialog = ({+ initialName,+ isOpen,+ isPending,+ onClose,+ onSubmit,+}: {+ initialName: string;+ isOpen: boolean;+ isPending: boolean;+ onClose: () => void;+ onSubmit: (name: string) => Promise<void> | void;+}) => {+ const { t } = useTranslation();++ const handleSubmit = useCallback(+ (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ const name = new FormData(event.currentTarget).get('templateName')?.toString().trim() ?? '';++ void onSubmit(name || t('workflowLibrary.untitled'));+ },+ [onSubmit, t]+ );+ const handleOpenChange = useCallback((event: { open: boolean }) => (event.open ? undefined : onClose()), [onClose]);++ return (+ <Dialog.Root+ closeOnEscape={!isPending}+ closeOnInteractOutside={!isPending}+ lazyMount+ open={isOpen}+ size="xs"+ unmountOnExit+ onOpenChange={handleOpenChange}+ >+ <Portal>+ <Dialog.Backdrop />+ <Dialog.Positioner>+ <Dialog.Content data-save-to-library-dialog>+ <chakra.form onSubmit={handleSubmit}>+ <Dialog.Header>+ <Dialog.Title>{t('workflowLibrary.saveToLibraryTitle')}</Dialog.Title>+ </Dialog.Header>+ <Dialog.Body>+ <Stack gap="3">+ <Field label={t('workflowLibrary.templateName')}>+ <Input defaultValue={initialName} name="templateName" size="sm" />+ </Field>+ <Text color="fg.muted" fontSize="xs">+ {t('workflowLibrary.saveToLibraryExplanation')}+ </Text>+ </Stack>+ </Dialog.Body>+ <Dialog.Footer>+ <Button disabled={isPending} size="xs" type="button" variant="ghost" onClick={onClose}>+ {t('common.cancel')}+ </Button>+ <Button loading={isPending} size="xs" type="submit" variant="solid">+ {t('workflowLibrary.saveToLibraryConfirm')}+ </Button>+ </Dialog.Footer>+ </chakra.form>+ <Dialog.CloseTrigger asChild>+ <CloseButton disabled={isPending} />+ </Dialog.CloseTrigger>+ </Dialog.Content>+ </Dialog.Positioner>+ </Portal>+ </Dialog.Root>+ );+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsxindex cbb50351a7..08175220fb 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/WorkflowRequirementsList.browser.test.tsx@@ -67,7 +67,14 @@ const readyEnrichment = (): WorkflowLibraryEntryEnrichment => ({const entry = (workflowId: string, enrichment: WorkflowLibraryEntryEnrichment): WorkflowLibraryEntry => ({enrichment,- item: { category: 'user', description: '', name: workflowId, thumbnail_url: null, workflow_id: workflowId },+ item: {+ category: 'user',+ description: '',+ name: workflowId,+ revision: 1,+ thumbnail_url: null,+ workflow_id: workflowId,+ },tags: [],});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.tsdeleted file mode 100644index 27365e80c8..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.test.ts+++ /dev/null@@ -1,238 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import { createLibraryAutosaver, type LibrarySyncStatus } from './libraryAutosave';--const createManualTimers = () => {- const pending = new Map<number, () => void>();- let nextHandle = 1;- return {- fire: () => {- const jobs = [...pending.values()];- pending.clear();- for (const job of jobs) {- job();- }- },- pendingCount: () => pending.size,- timers: {- clearTimeout: (handle: number) => void pending.delete(handle),- setTimeout: (fn: () => void, _ms: number) => {- const handle = nextHandle++;- pending.set(handle, fn);- return handle;- },- },- };-};--const createHarness = (initial: { id?: string; graph?: Record<string, unknown> } = {}) => {- let current = { libraryWorkflowId: initial.id ?? 'wf-1', serialized: initial.graph ?? { nodes: [1] } };- const statuses: LibrarySyncStatus[] = [];- const save = vi.fn(() => Promise.resolve());- const manual = createManualTimers();- const autosaver = createLibraryAutosaver({- onStatus: (status) => void statuses.push(status),- read: () => current,- save,- timers: manual.timers,- });- return { autosaver, manual, save, setCurrent: (next: typeof current) => (current = next), statuses };-};--describe('createLibraryAutosaver', () => {- it('debounces a change and saves the bound workflow', async () => {- const h = createHarness();- h.autosaver.notifyGraphChanged();- expect(h.save).not.toHaveBeenCalled();- h.manual.fire();- await h.autosaver.flush();- expect(h.save).toHaveBeenCalledWith('wf-1', { nodes: [1] });- expect(h.statuses).toEqual(['dirty', 'saving', 'saved', 'saved']);- });-- it('skips saving when the serialized graph has not changed since the last save', async () => {- const h = createHarness();- h.autosaver.notifyGraphChanged();- h.manual.fire();- await h.autosaver.flush();- h.autosaver.notifyGraphChanged(); // same content- h.manual.fire();- await h.autosaver.flush();- expect(h.save).toHaveBeenCalledTimes(1);- expect(h.statuses).toEqual(['dirty', 'saving', 'saved', 'saved', 'dirty', 'saved', 'saved']);- });-- it('markSynced suppresses the echo save after a load/bind', async () => {- const h = createHarness();- h.autosaver.markSynced({ nodes: [1] });- h.autosaver.notifyGraphChanged();- h.manual.fire();- await h.autosaver.flush();- expect(h.save).not.toHaveBeenCalled();- });-- it('does nothing for an unbound workflow', () => {- const h = createHarness();- h.setCurrent({ libraryWorkflowId: undefined as unknown as string, serialized: { nodes: [1] } });- h.autosaver.notifyGraphChanged();- expect(h.manual.pendingCount()).toBe(0);- expect(h.statuses).toEqual([]);- });-- it('reports error status on a failed save and retries on the next change', async () => {- const h = createHarness();- h.save.mockRejectedValueOnce(new Error('offline'));- h.autosaver.notifyGraphChanged();- h.manual.fire();- await h.autosaver.flush();- // Error is reported, then chained retry succeeds- expect(h.statuses).toContain('error');- expect(h.statuses.at(-1)).toBe('saved');- h.setCurrent({ libraryWorkflowId: 'wf-1', serialized: { nodes: [2] } });- h.autosaver.notifyGraphChanged();- h.manual.fire();- await h.autosaver.flush();- // Called 3 times: initial (failed), chained retry, new content- expect(h.save).toHaveBeenCalledTimes(3);- expect(h.statuses.at(-1)).toBe('saved');- });-- it('flushes a pending edit on dispose instead of dropping it', () => {- const h = createHarness();- h.autosaver.notifyGraphChanged();- expect(h.save).not.toHaveBeenCalled();-- h.autosaver.dispose();-- expect(h.save).toHaveBeenCalledTimes(1);- expect(h.manual.pendingCount()).toBe(0);- });-- it('does not save on dispose when nothing is pending', () => {- const h = createHarness();- h.autosaver.dispose();- expect(h.save).not.toHaveBeenCalled();- });-- it('a second dispose() is a no-op', () => {- const h = createHarness();- h.autosaver.notifyGraphChanged();- h.autosaver.dispose();- expect(h.save).toHaveBeenCalledTimes(1);-- h.autosaver.dispose();-- expect(h.save).toHaveBeenCalledTimes(1);- expect(h.manual.pendingCount()).toBe(0);- });-- it('flush() after dispose() performs no save and resolves', async () => {- const h = createHarness();- h.autosaver.dispose();-- const result = h.autosaver.flush();-- expect(h.save).not.toHaveBeenCalled();- await expect(result).resolves.toBeUndefined();- });-- it('dispose does not emit status callbacks for the flush save', async () => {- const h = createHarness();- h.autosaver.notifyGraphChanged();- h.statuses.length = 0; // drop the 'dirty' status from notifyGraphChanged- h.autosaver.dispose();- await vi.waitFor(() => expect(h.save).toHaveBeenCalledTimes(1));- expect(h.statuses).toEqual([]);- });-- it('disposing while a save is in flight with a newer edit pending still runs the chained rerun', async () => {- const h = createHarness();- let resolveSave: () => void;- const deferred = new Promise<void>((resolve) => {- resolveSave = resolve;- });- h.save.mockReturnValueOnce(deferred);- h.autosaver.notifyGraphChanged();- h.manual.fire();- // First save is now in flight (unresolved).- h.setCurrent({ libraryWorkflowId: 'wf-1', serialized: { nodes: [2] } });- h.autosaver.notifyGraphChanged();-- h.autosaver.dispose();- expect(h.manual.pendingCount()).toBe(0);-- resolveSave!();- // Disposal allows the in-flight write and its chained newer edit to finish.- await vi.waitFor(() => expect(h.save).toHaveBeenCalledTimes(2));- expect(h.save).toHaveBeenLastCalledWith('wf-1', { nodes: [2] });- });-- it('dispose with a pending edit whose save rejects does not throw or emit status', async () => {- const h = createHarness();- h.save.mockRejectedValueOnce(new Error('offline'));- h.autosaver.notifyGraphChanged();- h.statuses.length = 0;-- h.autosaver.dispose();- await vi.waitFor(() => expect(h.save).toHaveBeenCalledTimes(1));- // Give the rejection handler's microtask a chance to run before asserting silence.- await Promise.resolve();- expect(h.statuses).toEqual([]);- });-- it('a change made during an in-flight save is saved afterward', async () => {- const h = createHarness();- let resolveSave: () => void;- const deferred = new Promise<void>((resolve) => {- resolveSave = resolve;- });- h.save.mockReturnValueOnce(deferred);- h.autosaver.notifyGraphChanged();- h.manual.fire();- // Save is now in flight, pending on deferred- h.setCurrent({ libraryWorkflowId: 'wf-1', serialized: { nodes: [2] } });- h.autosaver.notifyGraphChanged();- const flushPromise = h.autosaver.flush();- // Resolve first save, which should chain another save for the new content- resolveSave!();- h.save.mockReturnValueOnce(Promise.resolve());- await flushPromise;- expect(h.save).toHaveBeenCalledTimes(2);- expect(h.save).toHaveBeenLastCalledWith('wf-1', { nodes: [2] });- expect(h.statuses.at(-1)).toBe('saved');- });-- it('does not report saved while an edit made during the save is still unwritten', async () => {- // An old acknowledgement must not mark newer unsaved content saved.- const h = createHarness();- let resolveSave: () => void;- const deferred = new Promise<void>((resolve) => {- resolveSave = resolve;- });-- h.save.mockReturnValueOnce(deferred);- h.autosaver.notifyGraphChanged();- h.manual.fire();-- h.setCurrent({ libraryWorkflowId: 'wf-1', serialized: { nodes: [2] } });- h.autosaver.notifyGraphChanged();-- resolveSave!();- await Promise.resolve();- await Promise.resolve();-- expect(h.statuses.at(-1)).toBe('dirty');- expect(h.manual.pendingCount()).toBe(1);- });-- it('an edit that dedupes back to the saved content ends in saved, not dirty', async () => {- const h = createHarness();- h.autosaver.notifyGraphChanged();- h.manual.fire();- await h.autosaver.flush();- h.autosaver.notifyGraphChanged(); // same content- h.manual.fire();- await h.autosaver.flush();- expect(h.statuses.at(-1)).toBe('saved');- });-});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.tsdeleted file mode 100644index 9252fa90ac..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/libraryAutosave.ts+++ /dev/null@@ -1,133 +0,0 @@-/**- * Deduplicate serialized content and retry failures only on edits/flush. Report saved only without newer edits.- * Dispose flushes silently; hard tab closes can still lose debounced writes.- */--export type LibrarySyncStatus = 'idle' | 'dirty' | 'saving' | 'saved' | 'error';--export interface LibraryAutosaverDeps {- read(): { libraryWorkflowId: string | undefined; serialized: Record<string, unknown> };- save(workflowId: string, serialized: Record<string, unknown>): Promise<void>;- onStatus(status: LibrarySyncStatus): void;- /** Idle window before a save (default 2000ms). */- debounceMs?: number;- timers?: {- setTimeout(fn: () => void, ms: number): number;- clearTimeout(handle: number): void;- };-}--export const DEFAULT_LIBRARY_AUTOSAVE_DEBOUNCE_MS = 2000;--export const createLibraryAutosaver = (deps: LibraryAutosaverDeps) => {- const debounceMs = deps.debounceMs ?? DEFAULT_LIBRARY_AUTOSAVE_DEBOUNCE_MS;- const timers = deps.timers ?? {- clearTimeout: (handle: number) => globalThis.clearTimeout(handle),- setTimeout: (fn: () => void, ms: number) => globalThis.setTimeout(fn, ms),- };-- let timerHandle: number | null = null;- let inFlight: Promise<void> | null = null;- let lastSavedJson: string | null = null;- let disposed = false;- /**- * Increment revision per edit; stale successes remain dirty while failures still report error rather than- * claiming unwritten work is safe.- */- let editGeneration = 0;-- const clearTimer = (): void => {- if (timerHandle !== null) {- timers.clearTimeout(timerHandle);- timerHandle = null;- }- };-- const runSave = (): Promise<void> => {- if (inFlight) {- // Chain a rereading, deduplicating pass after active saves so mid-save edits persist without endless reruns.- return inFlight.then(() => runSave());- }-- const { libraryWorkflowId, serialized } = deps.read();-- if (!libraryWorkflowId) {- return Promise.resolve();- }-- const json = JSON.stringify(serialized);-- if (json === lastSavedJson) {- if (!disposed) {- deps.onStatus('saved');- }- return Promise.resolve();- }-- if (!disposed) {- deps.onStatus('saving');- }-- const generationAtCapture = editGeneration;-- inFlight = deps- .save(libraryWorkflowId, serialized)- .then(() => {- // `json` did reach the server, so it is still the dedupe baseline even- // when newer edits exist — the next pass compares against it and saves- // only the difference.- lastSavedJson = json;- if (!disposed) {- deps.onStatus(editGeneration === generationAtCapture ? 'saved' : 'dirty');- }- })- .catch(() => {- if (!disposed) {- deps.onStatus('error');- }- })- .finally(() => {- inFlight = null;- });-- return inFlight;- };-- return {- dispose: (): void => {- if (disposed) {- return;- }- disposed = true;- // Flush pending edits on disposal while muting status callbacks.- const hasPendingEdit = timerHandle !== null;- clearTimer();- if (hasPendingEdit) {- void runSave();- }- },- flush: (): Promise<void> => {- if (disposed) {- return Promise.resolve();- }- clearTimer();- return runSave();- },- /** Marks the last save as matching `serialized` — call after load/bind so the loaded state is not re-saved. */- markSynced: (serialized: Record<string, unknown>): void => {- lastSavedJson = JSON.stringify(serialized);- },- notifyGraphChanged: (): void => {- if (disposed || !deps.read().libraryWorkflowId) {- return;- }- editGeneration += 1;- deps.onStatus('dirty');- clearTimer();- timerHandle = timers.setTimeout(() => {- timerHandle = null;- void runSave();- }, debounceMs);- },- };-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.tsdeleted file mode 100644index 04a3f49122..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/librarySyncBridge.ts+++ /dev/null@@ -1,20 +0,0 @@-/**- * Expose the mounted autosaver's markSynced without importing chrome; load/save paths use it to prevent immediate- * echo autosaves.- */--type MarkSyncedFn = (serialized: Record<string, unknown>) => void;--let markSyncedImpl: MarkSyncedFn | null = null;--export const registerLibraryGraphSyncedHandler = (fn: MarkSyncedFn): void => {- markSyncedImpl = fn;-};--export const releaseLibraryGraphSyncedHandler = (fn: MarkSyncedFn): void => {- if (markSyncedImpl === fn) {- markSyncedImpl = null;- }-};--export const markLibraryGraphSynced: MarkSyncedFn = (serialized) => markSyncedImpl?.(serialized);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.tsnew file mode 100644index 0000000000..15f1c42996--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/projectWorkflowEntries.ts@@ -0,0 +1,80 @@+import type { InvocationTemplates, ProjectWorkflowEntry, ProjectWorkflowSource } from '@features/workflow/core/types';+import type { WorkflowLibraryEntry } from '@features/workflow/data/libraryBrowseStore';++import { galleryImageUrls } from '@features/gallery/utility';+import { parseWorkflowTags } from '@features/workflow/core/libraryTags';+import { extractWorkflowModelRequirements } from '@features/workflow/core/modelRequirements';++/**+ * A project workflow presented through the library's card and detail contracts. The mapping is cached per entry+ * identity, so editing one workflow re-derives one card and leaves every other card's props untouched.+ */++export interface ProjectWorkflowLibraryEntry extends WorkflowLibraryEntry {+ /** The project workflow the card stands for. */+ projectWorkflow: ProjectWorkflowEntry;+}++const cache = new WeakMap<+ ProjectWorkflowEntry,+ { entry: ProjectWorkflowLibraryEntry; templates: InvocationTemplates | null }+>();++/** Bundled template ids are a server invariant (`default_` prefix); they are read-only whoever asks. */+export const isBundledLibraryWorkflowId = (libraryWorkflowId: string): boolean =>+ libraryWorkflowId.startsWith('default_');++/** Whether a source can be written to at all; the server still has the final word (ownership, deletion). */+export const isUpdatableSource = (source: ProjectWorkflowSource | undefined): source is ProjectWorkflowSource =>+ source !== undefined && !isBundledLibraryWorkflowId(source.libraryWorkflowId);++export const toProjectWorkflowLibraryEntry = (+ projectWorkflow: ProjectWorkflowEntry,+ templates: InvocationTemplates | null+): ProjectWorkflowLibraryEntry => {+ const cached = cache.get(projectWorkflow);++ if (cached && cached.templates === templates) {+ return cached.entry;+ }++ const { document, lastRun } = projectWorkflow;+ const entry: ProjectWorkflowLibraryEntry = {+ enrichment: templates+ ? {+ document,+ nodeCount: document.nodes.length,+ requirements: extractWorkflowModelRequirements(document, templates),+ status: 'ready',+ }+ : { status: 'pending' },+ item: {+ category: 'user',+ description: document.description,+ last_run_at: lastRun?.completedAt ?? null,+ name: document.name,+ revision: 0,+ tags: document.tags,+ thumbnail_url: lastRun ? galleryImageUrls.thumbnail(lastRun.imageName) : null,+ updated_at: document.updatedAt,+ workflow_id: document.id,+ },+ projectWorkflow,+ tags: parseWorkflowTags(document.tags),+ };++ cache.set(projectWorkflow, { entry, templates });++ return entry;+};++export const toProjectWorkflowLibraryEntries = (+ workflows: readonly ProjectWorkflowEntry[],+ templates: InvocationTemplates | null+): ProjectWorkflowLibraryEntry[] => workflows.map((workflow) => toProjectWorkflowLibraryEntry(workflow, templates));++/** The project copies of one library template, in collection order. */+export const findProjectCopiesOf = (+ workflows: readonly ProjectWorkflowEntry[],+ libraryWorkflowId: string+): ProjectWorkflowEntry[] => workflows.filter((entry) => entry.source?.libraryWorkflowId === libraryWorkflowId);diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.tsdeleted file mode 100644index f5809064ff..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useLoadLibraryWorkflow.ts+++ /dev/null@@ -1,98 +0,0 @@-import type { WorkflowLibraryListItem } from '@features/workflow/queries';--import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';-import { getLibraryWorkflowCached, touchLibraryWorkflowOpenedAt } from '@features/workflow/queries';-import { requestWorkflowFitView } from '@features/workflow/ui/editor/flowInstanceStore';-import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';-import { useWorkflowNotifications } from '@features/workflow/ui/WorkflowUiContext';-import { parseWorkflowJson, serializeWorkflowJson } from '@features/workflow/utility';-import {- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';-import { getApiErrorMessage } from '@platform/transport/http';-import { useCallback, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { markLibraryGraphSynced } from './librarySyncBridge';--/** Drop overlapping workflow-open requests; a queued second load would silently replace the first applied graph. */--export type WorkflowLoadPhase = 'applying' | 'fetching' | 'idle';--export interface LoadLibraryWorkflow {- load: (item: WorkflowLibraryListItem) => Promise<void>;- /** Drives the caller's busy overlay; `applying` is the expensive half. */- loadPhase: WorkflowLoadPhase;-}--export const useLoadLibraryWorkflow = (onLoaded: () => void): LoadLibraryWorkflow => {- const { t } = useTranslation();- const { replace } = useProjectGraphCommands();- const notify = useWorkflowNotifications();- const [loadPhase, setLoadPhase] = useState<WorkflowLoadPhase>('idle');- const isInFlightRef = useRef(false);-- const load = useCallback(- async (item: WorkflowLibraryListItem): Promise<void> => {- const owner = captureAccountScope();-- if (isInFlightRef.current) {- return;- }- isInFlightRef.current = true;-- try {- setLoadPhase('fetching');-- const raw = await getLibraryWorkflowCached(item.workflow_id, owner.signal);-- assertAccountScopeCurrent(owner);- const { document: parsed, warnings: parseWarnings } = parseWorkflowJson(raw);- const { document, warnings: updateWarnings } = updateLoadedWorkflowNodes(parsed, t);- const warnings = [...parseWarnings, ...updateWarnings];-- assertAccountScopeCurrent(owner);- setLoadPhase('applying');- // Synchronous graph replacement can be expensive for large workflows.- // Give React a full frame to commit and paint the busy overlay first.- await new Promise<void>((resolve) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolve()));- });-- assertAccountScopeCurrent(owner);- replace(document, t('workflowLibrary.loadedLabel', { name: item.name }));- requestWorkflowFitView(document.nodes);- // Mark loaded content synced before changed graph identity can schedule an echo save.- markLibraryGraphSynced(serializeWorkflowJson(document));-- for (const warning of warnings) {- notify.info(t('workflowLibrary.loadWarning'), warning);- }-- void touchLibraryWorkflowOpenedAt(item.workflow_id, owner.signal).catch(() => {- // Recency bookkeeping only; loading already succeeded.- });- onLoaded();- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return;- }-- notify.error(- t('workflowLibrary.loadFailed'),- getApiErrorMessage(error, t('workflowLibrary.loadFailedBody', { name: item.name }))- );- } finally {- if (isAccountScopeCurrent(owner)) {- isInFlightRef.current = false;- setLoadPhase('idle');- }- }- },- [notify, onLoaded, replace, t]- );-- return { load, loadPhase };-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.test.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.test.tsnew file mode 100644index 0000000000..a56af1c84e--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.test.ts@@ -0,0 +1,23 @@+import { createProjectGraph } from '@features/workflow/utility';+import { describe, expect, it } from 'vitest';++import { planLibraryWorkflowOpen } from './useOpenLibraryWorkflow';++const entry = (id: string, libraryWorkflowId?: string) => ({+ document: createProjectGraph(id),+ ...(libraryWorkflowId ? { source: { libraryWorkflowId, revision: 1 } } : {}),+});++describe('planLibraryWorkflowOpen', () => {+ it('adds a copy when the project has none, resumes a single copy, and asks when there are several', () => {+ expect(planLibraryWorkflowOpen([entry('a'), entry('b', 'other')], 'lib')).toEqual({ kind: 'add' });+ expect(planLibraryWorkflowOpen([entry('a', 'lib'), entry('b')], 'lib')).toEqual({+ kind: 'resume',+ workflowId: 'a',+ });++ const copies = [entry('a', 'lib'), entry('b', 'lib')];++ expect(planLibraryWorkflowOpen([...copies, entry('c')], 'lib')).toEqual({ copies, kind: 'choose' });+ });+});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.tsnew file mode 100644index 0000000000..1bed5c2c48--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useOpenLibraryWorkflow.ts@@ -0,0 +1,172 @@+import type { ProjectWorkflowEntry } from '@features/workflow/core/types';+import type { WorkflowLibraryListItem } from '@features/workflow/queries';++import { updateLoadedWorkflowNodes } from '@features/workflow/data/templates';+import { getLibraryWorkflowRecordCached, touchLibraryWorkflowOpenedAt } from '@features/workflow/queries';+import { requestWorkflowFitView } from '@features/workflow/ui/editor/flowInstanceStore';+import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { useWorkflowNotifications, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { parseWorkflowJson } from '@features/workflow/utility';+import {+ assertAccountScopeCurrent,+ captureAccountScope,+ isAccountScopeCurrent,+} from '@platform/state/accountLifecycle';+import { getApiErrorMessage } from '@platform/transport/http';+import { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { findProjectCopiesOf } from './projectWorkflowEntries';++/**+ * Opening a template always lands in the project's own collection: as a new copy, or by resuming the copy the+ * project already made from it. Overlapping opens are dropped; a queued second load would add a second copy.+ */++export type WorkflowLoadPhase = 'applying' | 'fetching' | 'idle';++export type OpenLibraryWorkflowMode =+ /** Resume the one existing copy, or add the first; several copies need a choice the caller makes. */+ | 'resume-or-add'+ /** Always add a fresh, independent copy beside any existing ones. */+ | 'add-copy';++/** What opening a template would do given the project's current copies. */+export type LibraryWorkflowOpenPlan =+ | { kind: 'add' }+ | { kind: 'resume'; workflowId: string }+ | { kind: 'choose'; copies: readonly ProjectWorkflowEntry[] };++export const planLibraryWorkflowOpen = (+ workflows: readonly ProjectWorkflowEntry[],+ libraryWorkflowId: string+): LibraryWorkflowOpenPlan => {+ const copies = findProjectCopiesOf(workflows, libraryWorkflowId);++ if (copies.length === 0) {+ return { kind: 'add' };+ }++ if (copies.length === 1) {+ return { kind: 'resume', workflowId: copies[0]!.document.id };+ }++ return { copies, kind: 'choose' };+};++export interface OpenLibraryWorkflow {+ /** Fetches the template and adds a copy, or resumes the existing one; resolves once the project has it. */+ open: (item: Pick<WorkflowLibraryListItem, 'name' | 'workflow_id'>, mode: OpenLibraryWorkflowMode) => Promise<void>;+ /** Activates a copy the project already owns. */+ resume: (workflowId: string) => void;+ /** Drives the caller's busy overlay; `applying` is the expensive half. */+ loadPhase: WorkflowLoadPhase;+}++export const useOpenLibraryWorkflow = (onOpened: () => void): OpenLibraryWorkflow => {+ const { t } = useTranslation();+ const { addWorkflow, selectWorkflow } = useProjectGraphCommands();+ const { project } = useWorkflowUi();+ const notify = useWorkflowNotifications();+ const [loadPhase, setLoadPhase] = useState<WorkflowLoadPhase>('idle');+ const isInFlightRef = useRef(false);++ const resume = useCallback(+ (workflowId: string) => {+ selectWorkflow(workflowId);+ onOpened();+ },+ [onOpened, selectWorkflow]+ );++ const open = useCallback(+ async (item: Pick<WorkflowLibraryListItem, 'name' | 'workflow_id'>, mode: OpenLibraryWorkflowMode) => {+ const owner = captureAccountScope();++ if (isInFlightRef.current) {+ return;+ }++ if (mode === 'resume-or-add') {+ const plan = planLibraryWorkflowOpen(project.getSnapshot().workflows, item.workflow_id);++ if (plan.kind === 'resume') {+ resume(plan.workflowId);+ return;+ }++ if (plan.kind === 'choose') {+ // Several copies exist; the surface offering the open owns the choice.+ return;+ }+ }++ isInFlightRef.current = true;++ // The project the open started from is the project it lands in, whatever becomes active meanwhile.+ const projectId = project.getSnapshot().id;++ try {+ setLoadPhase('fetching');++ const record = await getLibraryWorkflowRecordCached(item.workflow_id, owner.signal);++ assertAccountScopeCurrent(owner);+ const { document: parsed, warnings: parseWarnings } = parseWorkflowJson({+ ...record.workflow,+ id: record.workflow_id,+ });+ const { document, warnings: updateWarnings } = updateLoadedWorkflowNodes(parsed, t);+ const warnings = [...parseWarnings, ...updateWarnings];++ assertAccountScopeCurrent(owner);+ setLoadPhase('applying');+ // Adding a large document is synchronous and expensive; give React a frame to paint the busy overlay.+ await new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });++ assertAccountScopeCurrent(owner);++ if (project.getSnapshot().id !== projectId) {+ notify.info(t('workflowLibrary.openProjectChanged', { name: item.name }));+ return;+ }++ addWorkflow(document, {+ label: t('workflowLibrary.loadedLabel', { name: item.name }),+ // The first copy may take over the blank a fresh project starts with; another copy never does.+ reusePlaceholder: mode === 'resume-or-add',+ source: { libraryWorkflowId: record.workflow_id, revision: record.revision },+ });+ requestWorkflowFitView(document.nodes);++ for (const warning of warnings) {+ notify.info(t('workflowLibrary.loadWarning'), warning);+ }++ void touchLibraryWorkflowOpenedAt(item.workflow_id, owner.signal).catch(() => {+ // Recency bookkeeping only; opening already succeeded.+ });+ onOpened();+ } catch (error) {+ if (!isAccountScopeCurrent(owner)) {+ return;+ }++ notify.error(+ t('workflowLibrary.loadFailed'),+ getApiErrorMessage(error, t('workflowLibrary.loadFailedBody', { name: item.name }))+ );+ } finally {+ if (isAccountScopeCurrent(owner)) {+ isInFlightRef.current = false;+ setLoadPhase('idle');+ }+ }+ },+ [addWorkflow, notify, onOpened, project, resume, t]+ );++ return { loadPhase, open, resume };+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsxdeleted file mode 100644index 58f09105cc..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.browser.test.tsx+++ /dev/null@@ -1,273 +0,0 @@-import type { WorkflowUiAdapter } from '@features/workflow/ui/WorkflowUiContext';--import { WorkflowUiProvider } from '@features/workflow/ui/WorkflowUiContext';-import { createProjectGraph, serializeWorkflowJson } from '@features/workflow/utility';-import { act, useEffect } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { registerLibraryGraphSyncedHandler, releaseLibraryGraphSyncedHandler } from './librarySyncBridge';-import { useSaveWorkflowToLibrary } from './useSaveWorkflowToLibrary';--const { createLibraryWorkflowMock, invalidateWorkflowLibraryCacheMock, updateLibraryWorkflowMock } = vi.hoisted(() => ({- createLibraryWorkflowMock: vi.fn(),- invalidateWorkflowLibraryCacheMock: vi.fn(),- updateLibraryWorkflowMock: vi.fn(),-}));--vi.mock('@features/workflow/queries', async (importOriginal) => ({- ...(await importOriginal<Record<string, unknown>>()),- createLibraryWorkflow: createLibraryWorkflowMock,- invalidateWorkflowLibraryCache: invalidateWorkflowLibraryCacheMock,- updateLibraryWorkflow: updateLibraryWorkflowMock,-}));--const TRANSLATIONS: Record<string, string> = {- 'common.unknownError': 'Unknown error.',- 'workflowLibrary.saveFailed': 'Failed to save workflow',- 'workflowLibrary.saved': 'Workflow saved',- 'workflowLibrary.savedCreatedBody': 'Saved "{{name}}" to the library.',- 'workflowLibrary.savedUpdatedBody': 'Updated "{{name}}" in the library.',- 'workflowLibrary.untitled': 'Untitled Workflow',-};--const interpolate = (template: string, options?: Record<string, unknown>): string =>- options ? template.replaceAll(/\{\{(\w+)\}\}/g, (_match, key: string) => String(options[key] ?? '')) : template;--vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, options?: Record<string, unknown>) => interpolate(TRANSLATIONS[key] ?? key, options),- }),-}));--(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;--const createMutablePort = <Snapshot,>(initialSnapshot: Snapshot) => {- let snapshot = initialSnapshot;- const listeners = new Set<() => void>();- return {- port: {- getSnapshot: () => snapshot,- subscribe: (listener: () => void) => {- listeners.add(listener);- return () => listeners.delete(listener);- },- },- setSnapshot: (next: Snapshot) => {- snapshot = next;- for (const listener of listeners) {- listener();- }- },- };-};--/** Baseline newly created workflows from the post-bind graph, including its ID, to prevent a redundant autosave. */-describe('useSaveWorkflowToLibrary bind-then-sync', () => {- let host: HTMLDivElement;- let root: Root;-- beforeEach(() => {- host = document.createElement('div');- document.body.append(host);- createLibraryWorkflowMock.mockReset();- createLibraryWorkflowMock.mockResolvedValue('library-workflow-99');- updateLibraryWorkflowMock.mockReset();- invalidateWorkflowLibraryCacheMock.mockReset();- root = createRoot(host);- });-- afterEach(async () => {- await act(() => root.unmount());- host.remove();- });-- it('marks the autosaver baseline with the post-bind serialized graph, matching what read() will produce', async () => {- const initialGraph = createProjectGraph('workflow-1');- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: initialGraph,- workflowValues: {},- });-- const bindLibraryWorkflow = vi.fn((libraryWorkflowId: string) => {- project.setSnapshot({- ...project.port.getSnapshot(),- projectGraph: { ...project.port.getSnapshot().projectGraph, libraryWorkflowId },- });- });-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow,- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },- project: project.port,- } as unknown as WorkflowUiAdapter;-- let saveToLibrary: (() => Promise<string | null>) | null = null;- const Harness = () => {- const hook = useSaveWorkflowToLibrary();-- useEffect(() => {- saveToLibrary = hook.saveToLibrary;- });-- return null;- };-- await act(() => {- root.render(- <WorkflowUiProvider adapter={adapter}>- <Harness />- </WorkflowUiProvider>- );- });-- const syncedCalls: Record<string, unknown>[] = [];- const handler = (serialized: Record<string, unknown>) => syncedCalls.push(serialized);-- registerLibraryGraphSyncedHandler(handler);-- try {- await act(async () => {- await saveToLibrary?.();- });-- expect(bindLibraryWorkflow).toHaveBeenCalledWith('library-workflow-99');- expect(syncedCalls).toHaveLength(1);-- // Synced baseline must match current serialization content and key order because deduplication compares JSON- // strings.- const expectedPostBindSerialized = serializeWorkflowJson(project.port.getSnapshot().projectGraph);-- expect(JSON.stringify(syncedCalls[0])).toBe(JSON.stringify(expectedPostBindSerialized));- expect(syncedCalls[0]).toMatchObject({ id: 'library-workflow-99' });- } finally {- releaseLibraryGraphSyncedHandler(handler);- }- });-});--/** Saving arbitrary preview documents must not bind or change the active project's autosave baseline. */-describe('useSaveWorkflowToLibrary saveDocumentAsNew', () => {- let host: HTMLDivElement;- let root: Root;-- beforeEach(() => {- host = document.createElement('div');- document.body.append(host);- createLibraryWorkflowMock.mockReset();- updateLibraryWorkflowMock.mockReset();- invalidateWorkflowLibraryCacheMock.mockReset();- root = createRoot(host);- });-- afterEach(async () => {- await act(() => root.unmount());- host.remove();- });-- const renderHarness = () => {- const initialGraph = createProjectGraph('workflow-1');- const project = createMutablePort({- galleryValues: {},- id: 'project-1',- isWorkflowRunning: false,- projectGraph: initialGraph,- workflowValues: {},- });-- const bindLibraryWorkflow = vi.fn();-- // eslint-disable-next-line react-perf/jsx-no-new-object-as-prop -- intentionally stable for this render lifetime- const adapter = {- commands: {- bindLibraryWorkflow,- editGraph: vi.fn(),- redo: vi.fn(),- replace: vi.fn(),- undo: vi.fn(),- },- notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },- project: project.port,- } as unknown as WorkflowUiAdapter;-- let saveDocumentAsNew: ((document: ReturnType<typeof createProjectGraph>) => Promise<string | null>) | null = null;- const Harness = () => {- const hook = useSaveWorkflowToLibrary();-- useEffect(() => {- saveDocumentAsNew = hook.saveDocumentAsNew;- });-- return null;- };-- return { adapter, bindLibraryWorkflow, getSaveDocumentAsNew: () => saveDocumentAsNew, Harness, project };- };-- it('resolves the created id, sends the serialized document, and leaves the project alone', async () => {- createLibraryWorkflowMock.mockResolvedValue('library-workflow-42');-- const { adapter, bindLibraryWorkflow, getSaveDocumentAsNew, Harness, project } = renderHarness();-- await act(() => {- root.render(- <WorkflowUiProvider adapter={adapter}>- <Harness />- </WorkflowUiProvider>- );- });-- const document = { ...createProjectGraph('preview-doc'), name: 'From preview' };-- let result: string | null = null;- await act(async () => {- result = (await getSaveDocumentAsNew()?.(document)) ?? null;- });-- expect(result).toBe('library-workflow-42');- expect(createLibraryWorkflowMock).toHaveBeenCalledTimes(1);- expect(createLibraryWorkflowMock.mock.calls[0]?.[0]).toMatchObject({ name: 'From preview' });- expect(createLibraryWorkflowMock.mock.calls[0]?.[0]).toStrictEqual(serializeWorkflowJson(document));- expect(bindLibraryWorkflow).not.toHaveBeenCalled();- expect(invalidateWorkflowLibraryCacheMock).toHaveBeenCalledTimes(1);- expect(project.port.getSnapshot().projectGraph.libraryWorkflowId).toBeUndefined();- });-- it('returns null and notifies on rejection', async () => {- createLibraryWorkflowMock.mockRejectedValue(new Error('network down'));-- const { adapter, getSaveDocumentAsNew, Harness } = renderHarness();-- await act(() => {- root.render(- <WorkflowUiProvider adapter={adapter}>- <Harness />- </WorkflowUiProvider>- );- });-- const document = { ...createProjectGraph('preview-doc'), name: 'From preview' };-- let result: string | null = 'not-null';- await act(async () => {- result = (await getSaveDocumentAsNew()?.(document)) ?? null;- });-- expect(result).toBeNull();- expect(adapter.notifications.error).toHaveBeenCalledWith(- TRANSLATIONS['workflowLibrary.saveFailed'],- expect.any(String)- );- expect(invalidateWorkflowLibraryCacheMock).not.toHaveBeenCalled();- });-});diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.tsdeleted file mode 100644index b986173eed..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/useSaveWorkflowToLibrary.ts+++ /dev/null@@ -1,120 +0,0 @@-import type { ProjectGraphState } from '@features/workflow/core/types';--import {- createLibraryWorkflow,- invalidateWorkflowLibraryCache,- updateLibraryWorkflow,-} from '@features/workflow/queries';-import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';-import {- useWorkflowNotifications,- useWorkflowProjectSelector,- useWorkflowUi,-} from '@features/workflow/ui/WorkflowUiContext';-import { hasMultipleWorkflowReturnNodes, serializeWorkflowJson } from '@features/workflow/utility';-import {- assertAccountScopeCurrent,- captureAccountScope,- isAccountScopeCurrent,-} from '@platform/state/accountLifecycle';-import { getApiErrorMessage } from '@platform/transport/http';-import { useCallback } from 'react';-import { useTranslation } from 'react-i18next';--import { markLibraryGraphSynced } from './librarySyncBridge';-import { setWorkflowLibrarySyncStatus } from './workflowLibrarySyncStore';--/**- * Save active graphs with a matching autosave baseline; arbitrary preview documents can be saved separately as new- * records.- */-export const useSaveWorkflowToLibrary = (): {- saveDocumentAsNew: (document: ProjectGraphState) => Promise<string | null>;- saveToLibrary: () => Promise<string | null>;-} => {- const projectGraph = useWorkflowProjectSelector((project) => project.projectGraph);- const { project: projectStore } = useWorkflowUi();- const { bindLibraryWorkflow } = useProjectGraphCommands();- const notify = useWorkflowNotifications();- const { t } = useTranslation();-- const saveToLibrary = useCallback(async (): Promise<string | null> => {- const owner = captureAccountScope();-- try {- if (hasMultipleWorkflowReturnNodes(projectGraph)) {- notify.error(t('workflowLibrary.saveFailed'), t('workflowLibrary.multipleWorkflowReturnNodes'));- return null;- }-- const serialized = serializeWorkflowJson(projectGraph);- let workflowId: string;- let syncedSerialized = serialized;-- const name = projectGraph.name || t('workflowLibrary.untitled');-- if (projectGraph.libraryWorkflowId) {- workflowId = projectGraph.libraryWorkflowId;- await updateLibraryWorkflow(workflowId, serialized, owner.signal);-- assertAccountScopeCurrent(owner);- notify.success(t('workflowLibrary.saved'), t('workflowLibrary.savedUpdatedBody', { name }));- } else {- workflowId = await createLibraryWorkflow(serialized, owner.signal);-- assertAccountScopeCurrent(owner);- bindLibraryWorkflow(workflowId);- notify.success(t('workflowLibrary.saved'), t('workflowLibrary.savedCreatedBody', { name }));-- // Serialize the synchronous post-bind snapshot so the baseline includes its new library ID and cannot- // trigger an echo save.- syncedSerialized = serializeWorkflowJson(projectStore.getSnapshot().projectGraph);- }-- markLibraryGraphSynced(syncedSerialized);- setWorkflowLibrarySyncStatus('saved');- invalidateWorkflowLibraryCache(workflowId);-- return workflowId;- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return null;- }-- notify.error(t('workflowLibrary.saveFailed'), getApiErrorMessage(error, t('common.unknownError')));- return null;- }- }, [bindLibraryWorkflow, notify, projectGraph, projectStore, t]);-- // Save arbitrary documents as new entries without binding the active project or updating its autosave baseline.- const saveDocumentAsNew = useCallback(- async (document: ProjectGraphState): Promise<string | null> => {- const owner = captureAccountScope();-- try {- if (hasMultipleWorkflowReturnNodes(document)) {- notify.error(t('workflowLibrary.saveFailed'), t('workflowLibrary.multipleWorkflowReturnNodes'));- return null;- }-- const serialized = serializeWorkflowJson(document);- const workflowId = await createLibraryWorkflow(serialized, owner.signal);-- assertAccountScopeCurrent(owner);- invalidateWorkflowLibraryCache(workflowId);-- return workflowId;- } catch (error) {- if (!isAccountScopeCurrent(owner)) {- return null;- }-- notify.error(t('workflowLibrary.saveFailed'), getApiErrorMessage(error, t('common.unknownError')));- return null;- }- },- [notify, t]- );-- return { saveDocumentAsNew, saveToLibrary };-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/useWorkflowPublication.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/useWorkflowPublication.tsnew file mode 100644index 0000000000..7a135ed25b--- /dev/null+++ b/invokeai/frontend/webv2/src/features/workflow/ui/library/useWorkflowPublication.ts@@ -0,0 +1,277 @@+import type { ProjectGraphState } from '@features/workflow/core/types';+import type { WorkflowPublicationController, WorkflowPublicationResult } from '@features/workflow/queries';++import { createWorkflowPublicationController } from '@features/workflow/queries';+import { useWorkflowNotifications, useWorkflowUi } from '@features/workflow/ui/WorkflowUiContext';+import { hasMultipleWorkflowReturnNodes, serializeWorkflowJson } from '@features/workflow/utility';+import { captureAccountScope, registerAccountOwnedResource } from '@platform/state/accountLifecycle';+import { useCallback, useSyncExternalStore } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * One publication controller per account: every editor save and preview save goes through it, so a workflow is+ * never published twice at once and a lost answer is reconciled before it is sent again.+ */++let controller: WorkflowPublicationController | null = null;++export const getWorkflowPublicationController = (): WorkflowPublicationController => {+ controller ??= createWorkflowPublicationController();+ return controller;+};++/**+ * Publications that got no definitive answer, by project workflow. Each keeps its captured request and reserved id+ * so a resend after a lost response cannot create a second template. They outlive the dialog that reported them:+ * a new save for that workflow meets the unanswered one first, and returning to the workflow offers it once more.+ * An entry ends when the publication settles, when the user discards it, or with the account.+ */+const unresolvedPublications = new Map<string, { failure: WorkflowPublicationFailure; offered: boolean }>();++const unresolvedKey = (projectId: string, workflowId: string): string => `${projectId}\u0000${workflowId}`;++export const getUnresolvedWorkflowPublication = (+ projectId: string,+ workflowId: string+): WorkflowPublicationFailure | null =>+ unresolvedPublications.get(unresolvedKey(projectId, workflowId))?.failure ?? null;++/** The unanswered publication, the first time the user arrives at its workflow; later arrivals stay quiet. */+export const takeUnresolvedWorkflowPublicationOffer = (+ projectId: string,+ workflowId: string+): WorkflowPublicationFailure | null => {+ const entry = unresolvedPublications.get(unresolvedKey(projectId, workflowId));++ if (!entry || entry.offered) {+ return null;+ }++ entry.offered = true;+ return entry.failure;+};++/** Forgets an unanswered publication; a later save starts afresh, under a new reserved id. */+export const discardUnresolvedWorkflowPublication = (projectId: string, workflowId: string): void => {+ unresolvedPublications.delete(unresolvedKey(projectId, workflowId));+};++registerAccountOwnedResource({+ clear: () => {+ controller = null;+ unresolvedPublications.clear();+ },+ name: 'workflow-publication',+});++/** A settled publication: like the controller's result, except a failed one retries through the same settlement. */+export type WorkflowPublicationOutcome =+ | Exclude<WorkflowPublicationResult, { status: 'failed' }>+ | { status: 'failed'; message: string; retry: () => Promise<WorkflowPublicationOutcome> }+ | { status: 'rejected'; message: string };++export type WorkflowPublicationFailure = Extract<WorkflowPublicationOutcome, { status: 'failed' }>;++export interface PublishProjectWorkflowOptions {+ workflowId: string;+ /** Names the new template; the project workflow keeps its own name. */+ name: string;+}++export interface UpdateProjectWorkflowSourceOptions {+ workflowId: string;+ libraryWorkflowId: string;+ expectedRevision: number;+}++export interface WorkflowPublication {+ /** Creates a new template from the project workflow's current content and makes it the copy's update target. */+ saveAsNew: (options: PublishProjectWorkflowOptions) => Promise<WorkflowPublicationOutcome>;+ /** Replaces the template the project workflow came from, at exactly the revision the caller reviewed. */+ updateSource: (options: UpdateProjectWorkflowSourceOptions) => Promise<WorkflowPublicationOutcome>;+ /** Creates a template from a document that is not (yet) a project workflow, such as a compiled preview. */+ saveDocumentAsNew: (document: ProjectGraphState, name: string) => Promise<WorkflowPublicationOutcome>;+ /** Resends the captured request of a failed publication. */+ retry: (result: WorkflowPublicationFailure) => Promise<WorkflowPublicationOutcome>;+ isPublishing: (workflowId: string) => boolean;+}++export const useWorkflowPublication = (): WorkflowPublication => {+ const { t } = useTranslation();+ const { commands, project } = useWorkflowUi();+ const notify = useWorkflowNotifications();+ const publicationController = getWorkflowPublicationController();++ // Re-render when the in-flight set changes so `isPublishing` answers stay current.+ useSyncExternalStore(+ publicationController.subscribe,+ publicationController.getVersion,+ publicationController.getVersion+ );++ const validate = useCallback(+ (document: ProjectGraphState): string | null =>+ hasMultipleWorkflowReturnNodes(document) ? t('workflowLibrary.multipleWorkflowReturnNodes') : null,+ [t]+ );++ /** Applies a settled publication to the originating project workflow; a later project or account never sees it. */+ const settle = useCallback(+ (+ result: WorkflowPublicationResult,+ target: { projectId: string; workflowId: string; updateSource: boolean; name: string }+ ): WorkflowPublicationOutcome => {+ if (result.status === 'published') {+ if (target.updateSource) {+ commands.setWorkflowSource(+ { projectId: target.projectId, workflowId: target.workflowId },+ { libraryWorkflowId: result.libraryWorkflowId, revision: result.revision }+ );+ }++ notify.success(+ t('workflowLibrary.saved'),+ result.kind === 'created'+ ? t('workflowLibrary.savedCreatedBody', { name: result.name })+ : t('workflowLibrary.savedUpdatedBody', { name: result.name })+ );+ } else if (result.status === 'invalid') {+ notify.error(t('workflowLibrary.saveFailed'), result.message);+ } else if (result.status === 'busy') {+ notify.info(t('workflowLibrary.saveBusy', { name: target.name }));+ }++ return result;+ },+ [commands, notify, t]+ );++ // A retry settles against the same target, so a save that lands on the second attempt still links the copy.+ const settleWithRetry = useCallback(+ function settleWithRetry(+ result: WorkflowPublicationResult,+ target: { projectId: string; workflowId: string; updateSource: boolean; name: string }+ ): WorkflowPublicationOutcome {+ const key = unresolvedKey(target.projectId, target.workflowId);++ if (result.status === 'failed') {+ const failure: WorkflowPublicationFailure = {+ ...result,+ retry: async () => settleWithRetry(await result.retry(), target),+ };++ unresolvedPublications.set(key, { failure, offered: false });+ return failure;+ }++ if (result.status !== 'busy') {+ unresolvedPublications.delete(key);+ }++ return settle(result, target);+ },+ [settle]+ );++ const saveAsNew = useCallback(+ async ({ name, workflowId }: PublishProjectWorkflowOptions): Promise<WorkflowPublicationOutcome> => {+ const snapshot = project.getSnapshot();+ const entry = snapshot.workflows.find((candidate) => candidate.document.id === workflowId);++ if (!entry) {+ return { message: t('workflowLibrary.workflowGone'), status: 'rejected' };+ }++ const rejection = validate(entry.document);++ if (rejection) {+ notify.error(t('workflowLibrary.saveFailed'), rejection);+ return { message: rejection, status: 'rejected' };+ }++ const target = { name, projectId: snapshot.id, updateSource: true, workflowId };+ const result = await publicationController.publish({+ destination: { kind: 'create', name },+ owner: captureAccountScope(),+ projectId: snapshot.id,+ workflow: serializeWorkflowJson(entry.document),+ workflowId,+ });++ return settleWithRetry(result, target);+ },+ [notify, project, publicationController, settleWithRetry, t, validate]+ );++ const updateSource = useCallback(+ async ({+ expectedRevision,+ libraryWorkflowId,+ workflowId,+ }: UpdateProjectWorkflowSourceOptions): Promise<WorkflowPublicationOutcome> => {+ const snapshot = project.getSnapshot();+ const entry = snapshot.workflows.find((candidate) => candidate.document.id === workflowId);++ if (!entry) {+ return { message: t('workflowLibrary.workflowGone'), status: 'rejected' };+ }++ const rejection = validate(entry.document);++ if (rejection) {+ notify.error(t('workflowLibrary.saveFailed'), rejection);+ return { message: rejection, status: 'rejected' };+ }++ const target = { name: entry.document.name, projectId: snapshot.id, updateSource: true, workflowId };+ const result = await publicationController.publish({+ destination: { expectedRevision, kind: 'update', libraryWorkflowId },+ owner: captureAccountScope(),+ projectId: snapshot.id,+ workflow: serializeWorkflowJson(entry.document),+ workflowId,+ });++ return settleWithRetry(result, target);+ },+ [notify, project, publicationController, settleWithRetry, t, validate]+ );++ const saveDocumentAsNew = useCallback(+ async (document: ProjectGraphState, name: string): Promise<WorkflowPublicationOutcome> => {+ const rejection = validate(document);++ if (rejection) {+ notify.error(t('workflowLibrary.saveFailed'), rejection);+ return { message: rejection, status: 'rejected' };+ }++ const projectId = project.getSnapshot().id;+ const target = { name, projectId, updateSource: false, workflowId: document.id };+ const result = await publicationController.publish({+ destination: { kind: 'create', name },+ owner: captureAccountScope(),+ projectId,+ workflow: serializeWorkflowJson(document),+ workflowId: document.id,+ });++ return settleWithRetry(result, target);+ },+ [notify, project, publicationController, settleWithRetry, t, validate]+ );++ // The failed result carries its captured request and, once settled here, its target.+ const retry = useCallback(+ (failed: WorkflowPublicationFailure): Promise<WorkflowPublicationOutcome> => failed.retry(),+ []+ );++ return {+ isPublishing: (workflowId) => publicationController.isPublishing(project.getSnapshot().id, workflowId),+ retry,+ saveAsNew,+ saveDocumentAsNew,+ updateSource,+ };+};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibrarySyncStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibrarySyncStore.tsdeleted file mode 100644index 3e07966ebd..0000000000--- a/invokeai/frontend/webv2/src/features/workflow/ui/library/workflowLibrarySyncStore.ts+++ /dev/null@@ -1,17 +0,0 @@-import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';-import { createExternalStore } from '@platform/state/externalStore';--import type { LibrarySyncStatus } from './libraryAutosave';--export const workflowLibrarySyncStore = createExternalStore<{ status: LibrarySyncStatus }>({ status: 'idle' });--registerAccountOwnedResource({- clear: () => {- workflowLibrarySyncStore.setSnapshot({ status: 'idle' });- },- name: 'workflow-library-sync',-});--export const setWorkflowLibrarySyncStatus = (status: LibrarySyncStatus): void => {- workflowLibrarySyncStore.setSnapshot({ status });-};diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsxindex 6f3f71fef7..8f5ffd0383 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeFieldControl.tsx@@ -6,6 +6,7 @@ import { getWorkflowFieldSeedMode, isSeedInputField } from '@features/workflow/gimport { useInvocationTemplatesSelector } from '@features/workflow/react';import { WorkflowFieldInput } from '@features/workflow/ui/fields/WorkflowFieldInput';import { useProjectGraphCommands } from '@features/workflow/ui/useProjectGraphCommands';+import { useWorkflowProjectSelector } from '@features/workflow/ui/WorkflowUiContext';import {cloneWorkflowFieldDefault,getEffectiveWorkflowFieldDescription,@@ -58,10 +59,14 @@ export const NodeFieldControl = ({}) => {const { t } = useTranslation();const { editGraph } = useProjectGraphCommands();+ const projectId = useWorkflowProjectSelector((project) => project.id);const { fieldName, instance, invocationNode, nodeContext, nodeId, template } = useNodeFieldBinding(element,projectGraph);+ // The form stays mounted across a workflow switch; a value that arrives later (an upload) must still land in+ // the workflow this control rendered.+ const target = useMemo(() => ({ projectId, workflowId: projectGraph.id }), [projectId, projectGraph.id]);// Seed focused label drafts from displayed text, including template fallback.const [draftLabel, setDraftLabel] = useState<string | null>(null);@@ -101,8 +106,8 @@ export const NodeFieldControl = ({);const onLabelFocus = useCallback(() => setDraftLabel(label), [label]);const onValueChange = useCallback(- (value: unknown) => editGraph({ fieldName, nodeId, type: 'setFieldValue', value }),- [editGraph, fieldName, nodeId]+ (value: unknown) => editGraph({ fieldName, nodeId, type: 'setFieldValue', value }, target),+ [editGraph, fieldName, nodeId, target]);const onSeedModeChange = useCallback((seedMode: SeedMode) => editGraph({ fieldName, nodeId, seedMode, type: 'setFieldSeedMode' }),@@ -197,6 +202,7 @@ export const NodeFieldControl = ({seedMode={getWorkflowFieldSeedMode(instance)}template={template}value={instance?.value}+ workflowId={projectGraph.id}onChange={onValueChange}onSeedModeChange={onSeedModeChange}/>diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.browser.test.tsxindex 80a8c93ff5..e2e3416186 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/NodeInspector.browser.test.tsx@@ -85,12 +85,16 @@ const node: WorkflowInvocationNode = {type: 'invocation',};const projectGraph: ProjectGraphState = { ...createProjectGraph('inspector-test'), nodes: [node] };+const PROJECT_ID = 'project-1';const projectSnapshot = {+ activeWorkflow: { document: projectGraph },+ activeWorkflowId: projectGraph.id,galleryValues: {},- id: 'project-1',+ id: PROJECT_ID,isWorkflowRunning: false,projectGraph,workflowValues: { inspectorTab: 'outputs' },+ workflows: [{ document: projectGraph }],};/** A node-execution port the test can advance between renders. */@@ -101,10 +105,13 @@ const createExecutionPort = () => {return {port: {get: (nodeId: string) => (nodeId === node.id ? state : null),+ // The run originates from this editor's own workflow; another copy's progress would be hidden.+ getOrigin: () => ({ projectId: PROJECT_ID, workflowId: projectGraph.id }),subscribe: (_nodeId: string, listener: () => void) => {listeners.add(listener);return () => listeners.delete(listener);},+ subscribeOrigin: () => () => {},},set(next: WorkflowNodeExecutionState | null) {state = next;@@ -116,7 +123,18 @@ const createExecutionPort = () => {const createAdapter = (nodeExecution: WorkflowUiAdapter['nodeExecution']): WorkflowUiAdapter =>({capabilities: { getSnapshot: () => ({ canUseCache: true }), subscribe: () => () => {} },- commands: { bindLibraryWorkflow: vi.fn(), editGraph: vi.fn(), redo: vi.fn(), replace: vi.fn(), undo: vi.fn() },+ commands: {+ addWorkflow: vi.fn(),+ createWorkflow: vi.fn(),+ duplicateWorkflow: vi.fn(),+ editGraph: vi.fn(),+ redo: vi.fn(),+ removeWorkflow: vi.fn(),+ renameWorkflow: vi.fn(),+ selectWorkflow: vi.fn(),+ setWorkflowSource: vi.fn(),+ undo: vi.fn(),+ },getProjectGraph: () => projectGraph,nodeExecution,notifications: { error: vi.fn(), info: vi.fn(), success: vi.fn() },@@ -206,7 +224,7 @@ const baseAdapter = createAdapter(createExecutionPort().port);const detailsAdapter = {...baseAdapter,project: { ...baseAdapter.project, getSnapshot: () => detailsSnapshot },-} as WorkflowUiAdapter;+} as unknown as WorkflowUiAdapter;describe('NodeInspector details tab node updates', () => {let host: HTMLDivElement;diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsxindex f9b1d4cc43..0db04cacc0 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx+++ b/invokeai/frontend/webv2/src/features/workflow/ui/linear/WorkflowLinearPanel.browser.test.tsx@@ -18,6 +18,9 @@ import { FormBuilderTab } from './FormBuilderTab';import { LinearFormView } from './LinearFormView';import { PanelModeToggle } from './WorkflowLinearPanel';+// Field controls name the project they render for; these harnesses hold one static project.+const TEST_PROJECT_PORT = { getSnapshot: () => ({ id: 'project-1' }), subscribe: () => () => undefined };+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;// Probe renders through a passthrough hook spy; compiler memoization can skip pure helper calls independently of@@ -188,13 +191,8 @@ describe('Form builder drag and drop (dnd-kit)', () => {const adapter = useMemo(() =>({- commands: {- bindLibraryWorkflow: () => undefined,- editGraph,- redo: () => undefined,- replace: () => undefined,- undo: () => undefined,- },+ commands: { editGraph, redo: () => undefined, undo: () => undefined },+ project: TEST_PROJECT_PORT,widgets: { open: () => undefined, patchValues: () => undefined },}) as unknown as WorkflowUiAdapter,[editGraph]@@ -490,7 +488,8 @@ describe('Linear form field entry', () => {const adapter = useMemo(() =>({- commands: { bindLibraryWorkflow: vi.fn(), editGraph, redo: vi.fn(), replace: vi.fn(), undo: vi.fn() },+ commands: { editGraph, redo: vi.fn(), undo: vi.fn() },+ project: TEST_PROJECT_PORT,widgets: { open: vi.fn(), patchValues: vi.fn() },}) as unknown as WorkflowUiAdapter,[editGraph]diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.tsindex f82ddfa607..9d0130818e 100644--- a/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts+++ b/invokeai/frontend/webv2/src/features/workflow/ui/workflowUiStore.ts@@ -19,6 +19,14 @@ export type AddNodeConnectionFilter =/** Bridge transient menu actions to always-mounted workflow dialogs and file input through session UI state. */+/** The library dialog's views: the project's own workflows, bundled templates, or the account's templates. */+export type WorkflowLibraryTab = 'project' | 'default' | 'user';++/** What a surface asked the publication host to do with one project workflow. */+export type WorkflowPublicationIntent =+ | { kind: 'save-as-new'; workflowId: string }+ | { kind: 'update-source'; workflowId: string };+export interface WorkflowUiSnapshot {addNodeConnection: AddNodeConnectionFilter | null;addNodePosition: XYPosition | null;@@ -26,11 +34,16 @@ export interface WorkflowUiSnapshot {collapsedPreviewNodeIds: ReadonlySet<string>;isAddNodeOpen: boolean;isLibraryOpen: boolean;- isNewWorkflowConfirmOpen: boolean;+ /** Which view the library dialog shows; remembered for the session. */+ libraryTab: WorkflowLibraryTab;+ /** The project workflow selected on the This-project view; only meaningful for the project it was made in. */+ librarySelection: { projectId: string; workflowId: string } | null;/** Bumped to ask the dialog host to open the JSON file picker. */importRequestCount: number;/** A workflow a shell surface (command palette, an image's context menu) asked to load; consumed by the widget chrome. */pendingWorkflowLoad: WorkflowLoadRequest | null;+ /** A publication the always-mounted host should start a dialog for. */+ publicationIntent: WorkflowPublicationIntent | null;}export type WorkflowLoadSource =@@ -52,8 +65,10 @@ const INITIAL_WORKFLOW_UI_SNAPSHOT: WorkflowUiSnapshot = {importRequestCount: 0,isAddNodeOpen: false,isLibraryOpen: false,- isNewWorkflowConfirmOpen: false,+ librarySelection: null,+ libraryTab: 'project',pendingWorkflowLoad: null,+ publicationIntent: null,};export const workflowUiStore = createExternalStore<WorkflowUiSnapshot>(INITIAL_WORKFLOW_UI_SNAPSHOT);@@ -69,6 +84,35 @@ export const setWorkflowLibraryOpen = (isOpen: boolean): void => {workflowUiStore.patchSnapshot({ isLibraryOpen: isOpen });};+export const setWorkflowLibraryTab = (libraryTab: WorkflowLibraryTab): void => {+ if (workflowUiStore.getSnapshot().libraryTab !== libraryTab) {+ workflowUiStore.patchSnapshot({ libraryTab });+ }+};++export const setWorkflowLibrarySelection = (selection: { projectId: string; workflowId: string } | null): void => {+ workflowUiStore.patchSnapshot({ librarySelection: selection });+};++/** Opens the library on the project's own workflows with one of them selected. */+export const openWorkflowLibraryAtProjectWorkflow = (projectId: string, workflowId: string): void => {+ workflowUiStore.patchSnapshot({+ isLibraryOpen: true,+ librarySelection: { projectId, workflowId },+ libraryTab: 'project',+ });+};++export const requestWorkflowPublication = (intent: WorkflowPublicationIntent): void => {+ workflowUiStore.patchSnapshot({ publicationIntent: intent });+};++export const clearWorkflowPublicationIntent = (): void => {+ if (workflowUiStore.getSnapshot().publicationIntent !== null) {+ workflowUiStore.patchSnapshot({ publicationIntent: null });+ }+};+export const setAddNodeOpen = (isOpen: boolean,position: XYPosition | null = null,@@ -81,10 +125,6 @@ export const setAddNodeOpen = (});};-export const setNewWorkflowConfirmOpen = (isOpen: boolean): void => {- workflowUiStore.patchSnapshot({ isNewWorkflowConfirmOpen: isOpen });-};-const requestWorkflowLoad = (source: WorkflowLoadSource): void => {nextWorkflowLoadRequestId += 1;workflowUiStore.patchSnapshot({ pendingWorkflowLoad: { requestId: nextWorkflowLoadRequestId, source } });diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 04f9bc7d49..7e7638ae21 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -102,6 +102,27 @@ const EDITOR_BOOT_SHARED_MODULES = ['/workbench/shell/topbar/ProjectSwitcher.tsx',] as const;+// The workflow core, its UI barrel and the project workflow collection are one chunk: the editor boots with all of+// them and the Launchpad palette reaches the barrel lazily, so splitting them by importer only adds requests.+const WORKFLOW_CORE_MODULES = [+ '/features/workflow/core/batch.ts',+ '/features/workflow/core/callSavedWorkflow.ts',+ '/features/workflow/core/connectors.ts',+ '/features/workflow/core/document.ts',+ '/features/workflow/core/fields.ts',+ '/features/workflow/core/forLoops.ts',+ '/features/workflow/core/graphIndex.ts',+ '/features/workflow/core/types.ts',+ '/features/workflow/core/validation.ts',+ '/features/workflow/core/workflowJson.ts',+ '/features/workflow/data/templates.ts',+ '/features/workflow/react.ts',+ '/features/workflow/ui/WorkflowUiContext.tsx',+ '/features/workflow/ui/workflowUiStore.ts',+ '/features/workflow/utility.ts',+ '/workbench/projectWorkflows.ts',+] as const;+// Keep widget metadata separate so Launchpad settings cannot import editor boot UI.const WIDGET_METADATA_MODULES = ['/features/gallery/settingsContribution.ts',@@ -284,6 +305,12 @@ export default defineConfig({priority: 30,test: (id) => matchesAnySuffix(id, EDITOR_BOOT_SHARED_MODULES),},+ {+ includeDependenciesRecursively: false,+ name: 'workflow-core',+ priority: 30,+ test: (id) => matchesAnySuffix(id, WORKFLOW_CORE_MODULES),+ },{includeDependenciesRecursively: false,name: 'widget-metadata',