@flowdrop/flowdrop 1.15.0 → 2.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (323) hide show
  1. package/CHANGELOG.md +648 -0
  2. package/MIGRATION-2.0.md +642 -0
  3. package/README.md +28 -28
  4. package/dist/adapters/WorkflowAdapter.d.ts +1 -1
  5. package/dist/adapters/WorkflowAdapter.js +18 -13
  6. package/dist/adapters/agentspec/AgentSpecAdapter.js +10 -10
  7. package/dist/adapters/agentspec/defaultNodeTypes.js +9 -9
  8. package/dist/api/enhanced-client.js +6 -11
  9. package/dist/chat/batchFeedback.d.ts +39 -0
  10. package/dist/chat/batchFeedback.js +51 -0
  11. package/dist/commands/executor.js +66 -27
  12. package/dist/commands/storeIntegration.svelte.d.ts +4 -1
  13. package/dist/commands/storeIntegration.svelte.js +36 -21
  14. package/dist/commands/types.d.ts +2 -0
  15. package/dist/commands/types.js +5 -5
  16. package/dist/components/App.svelte +696 -565
  17. package/dist/components/App.svelte.d.ts +63 -16
  18. package/dist/components/Button.stories.svelte +65 -0
  19. package/dist/components/Button.stories.svelte.d.ts +19 -0
  20. package/dist/components/Button.svelte +62 -0
  21. package/dist/components/Button.svelte.d.ts +24 -0
  22. package/dist/components/CanvasIconButton.svelte +76 -0
  23. package/dist/components/CanvasIconButton.svelte.d.ts +18 -0
  24. package/dist/components/ConfigForm.svelte +181 -552
  25. package/dist/components/ConfigForm.svelte.d.ts +24 -7
  26. package/dist/components/ConfigModal.svelte +16 -3
  27. package/dist/components/ConfigPanel.svelte +234 -15
  28. package/dist/components/ConfigPanel.svelte.d.ts +6 -0
  29. package/dist/components/ConnectionLine.svelte +4 -2
  30. package/dist/components/EditorStatusBar.stories.svelte +44 -0
  31. package/dist/components/EditorStatusBar.stories.svelte.d.ts +27 -0
  32. package/dist/components/EditorStatusBar.svelte +99 -0
  33. package/dist/components/EditorStatusBar.svelte.d.ts +15 -0
  34. package/dist/components/IconButton.svelte +80 -0
  35. package/dist/components/IconButton.svelte.d.ts +30 -0
  36. package/dist/components/Input.svelte +74 -0
  37. package/dist/components/Input.svelte.d.ts +17 -0
  38. package/dist/components/LogoWordmark.svelte +113 -0
  39. package/dist/components/LogoWordmark.svelte.d.ts +26 -0
  40. package/dist/components/Navbar.svelte +78 -64
  41. package/dist/components/Navbar.svelte.d.ts +3 -0
  42. package/dist/components/NodeSidebar.svelte +48 -171
  43. package/dist/components/NodeStatusOverlay.svelte +94 -6
  44. package/dist/components/NodeSwapPicker.svelte +22 -38
  45. package/dist/components/PipelineStatus.svelte +22 -68
  46. package/dist/components/PipelineStatus.svelte.d.ts +3 -0
  47. package/dist/components/PortCoordinateTracker.svelte +5 -6
  48. package/dist/components/PortMappingRow.svelte +0 -2
  49. package/dist/components/SchemaForm.stories.svelte +1 -3
  50. package/dist/components/SchemaForm.svelte +22 -39
  51. package/dist/components/SchemaForm.svelte.d.ts +0 -8
  52. package/dist/components/Select.svelte +53 -0
  53. package/dist/components/Select.svelte.d.ts +15 -0
  54. package/dist/components/SettingsModal.svelte +8 -8
  55. package/dist/components/SettingsPanel.svelte +44 -10
  56. package/dist/components/SwapMappingEditor.svelte +67 -49
  57. package/dist/components/SwapMappingEditor.svelte.d.ts +0 -2
  58. package/dist/components/Textarea.svelte +39 -0
  59. package/dist/components/Textarea.svelte.d.ts +12 -0
  60. package/dist/components/ThemeToggle.svelte +15 -94
  61. package/dist/components/UniversalNode.svelte +45 -11
  62. package/dist/components/UniversalNode.svelte.d.ts +1 -1
  63. package/dist/components/WorkflowEditor.svelte +183 -162
  64. package/dist/components/WorkflowEditor.svelte.d.ts +39 -10
  65. package/dist/components/chat/AIChatPanel.svelte +99 -90
  66. package/dist/components/chat/AIChatPanel.svelte.d.ts +0 -4
  67. package/dist/components/chat/CommandPreview.svelte +2 -1
  68. package/dist/components/console/CommandConsole.svelte +7 -5
  69. package/dist/components/console/ConsoleAutocomplete.svelte +11 -12
  70. package/dist/components/console/ConsoleAutocomplete.svelte.d.ts +6 -0
  71. package/dist/components/console/ConsoleInput.svelte +18 -9
  72. package/dist/components/console/ConsoleOutput.svelte +4 -3
  73. package/dist/components/form/FormArray.svelte +42 -182
  74. package/dist/components/form/FormArray.svelte.d.ts +2 -1
  75. package/dist/components/form/FormAutocomplete.svelte +26 -21
  76. package/dist/components/form/FormCheckboxGroup.svelte +1 -5
  77. package/dist/components/form/FormCodeEditor.svelte +9 -7
  78. package/dist/components/form/FormField.svelte +22 -44
  79. package/dist/components/form/FormFieldLight.svelte +56 -50
  80. package/dist/components/form/FormFieldLight.svelte.d.ts +12 -0
  81. package/dist/components/form/FormFieldset.svelte +45 -11
  82. package/dist/components/form/FormMarkdownEditor.svelte +17 -9
  83. package/dist/components/form/FormNumberField.svelte +4 -36
  84. package/dist/components/form/FormPorts.svelte +262 -0
  85. package/dist/components/form/FormPorts.svelte.d.ts +13 -0
  86. package/dist/components/form/FormRangeField.svelte +62 -30
  87. package/dist/components/form/FormSelect.svelte +13 -75
  88. package/dist/components/form/FormTemplateEditor.svelte +17 -7
  89. package/dist/components/form/FormTextField.svelte +3 -35
  90. package/dist/components/form/FormTextarea.svelte +4 -39
  91. package/dist/components/form/FormToggle.svelte +5 -16
  92. package/dist/components/form/FormToggle.svelte.d.ts +4 -2
  93. package/dist/components/form/FormUISchemaRenderer.svelte +3 -1
  94. package/dist/components/form/resolveFieldType.d.ts +24 -0
  95. package/dist/components/form/resolveFieldType.js +55 -0
  96. package/dist/components/form/templateAutocomplete.js +1 -5
  97. package/dist/components/form/types.d.ts +1 -14
  98. package/dist/components/icons/CloseIcon.svelte +6 -0
  99. package/dist/components/icons/CloseIcon.svelte.d.ts +26 -0
  100. package/dist/components/icons/CommandLineIcon.svelte +15 -0
  101. package/dist/components/icons/CommandLineIcon.svelte.d.ts +26 -0
  102. package/dist/components/icons/MenuIcon.svelte +4 -0
  103. package/dist/components/icons/MenuIcon.svelte.d.ts +26 -0
  104. package/dist/components/icons/MenuOpenIcon.svelte +6 -0
  105. package/dist/components/icons/MenuOpenIcon.svelte.d.ts +26 -0
  106. package/dist/components/interrupt/ChoicePrompt.svelte +0 -10
  107. package/dist/components/interrupt/ConfirmationPrompt.svelte +0 -5
  108. package/dist/components/interrupt/FormPrompt.svelte +3 -2
  109. package/dist/components/interrupt/InterruptBubble.svelte +25 -27
  110. package/dist/components/interrupt/ReviewPrompt.svelte +10 -23
  111. package/dist/components/interrupt/TextInputPrompt.svelte +2 -7
  112. package/dist/components/layouts/MainLayout.svelte +24 -18
  113. package/dist/components/layouts/MainLayout.svelte.d.ts +4 -0
  114. package/dist/components/nodes/AtomNode.svelte +70 -72
  115. package/dist/components/nodes/AtomNode.svelte.d.ts +1 -1
  116. package/dist/components/nodes/GatewayNode.svelte +134 -172
  117. package/dist/components/nodes/GatewayNode.svelte.d.ts +1 -1
  118. package/dist/components/nodes/IdeaNode.svelte +79 -98
  119. package/dist/components/nodes/IdeaNode.svelte.d.ts +8 -4
  120. package/dist/components/nodes/NodeConfigButton.svelte +86 -0
  121. package/dist/components/nodes/NodeConfigButton.svelte.d.ts +15 -0
  122. package/dist/components/nodes/NotesNode.svelte +76 -85
  123. package/dist/components/nodes/NotesNode.svelte.d.ts +8 -4
  124. package/dist/components/nodes/SimpleNode.svelte +68 -137
  125. package/dist/components/nodes/SimpleNode.svelte.d.ts +4 -4
  126. package/dist/components/nodes/SquareNode.svelte +122 -169
  127. package/dist/components/nodes/SquareNode.svelte.d.ts +4 -4
  128. package/dist/components/nodes/TerminalNode.svelte +70 -127
  129. package/dist/components/nodes/TerminalNode.svelte.d.ts +4 -4
  130. package/dist/components/nodes/ToolNode.svelte +99 -104
  131. package/dist/components/nodes/ToolNode.svelte.d.ts +6 -6
  132. package/dist/components/nodes/WorkflowNode.svelte +145 -195
  133. package/dist/components/nodes/WorkflowNode.svelte.d.ts +1 -1
  134. package/dist/components/playground/ChatInput.svelte +11 -15
  135. package/dist/components/playground/ChatPanel.svelte +6 -49
  136. package/dist/components/playground/ChatPanel.svelte.d.ts +0 -14
  137. package/dist/components/playground/ControlPanel.svelte +134 -123
  138. package/dist/components/playground/ControlPanel.svelte.d.ts +3 -0
  139. package/dist/components/playground/ExecutionLogs.svelte +11 -9
  140. package/dist/components/playground/InputCollector.svelte +22 -57
  141. package/dist/components/playground/MessageStream.svelte +17 -23
  142. package/dist/components/playground/PipelineKanbanView.svelte +69 -8
  143. package/dist/components/playground/PipelineKanbanView.svelte.d.ts +2 -0
  144. package/dist/components/playground/PipelinePanel.svelte +31 -8
  145. package/dist/components/playground/PipelinePanel.svelte.d.ts +2 -0
  146. package/dist/components/playground/PipelineTableView.svelte +188 -44
  147. package/dist/components/playground/PipelineTableView.svelte.d.ts +2 -0
  148. package/dist/components/playground/Playground.svelte +154 -105
  149. package/dist/components/playground/Playground.svelte.d.ts +5 -0
  150. package/dist/components/playground/PlaygroundApp.svelte +12 -2
  151. package/dist/components/playground/PlaygroundApp.svelte.d.ts +6 -0
  152. package/dist/components/playground/PlaygroundModal.svelte +18 -3
  153. package/dist/components/playground/PlaygroundModal.svelte.d.ts +6 -0
  154. package/dist/components/playground/PlaygroundStudio.svelte +40 -37
  155. package/dist/components/playground/PlaygroundStudio.svelte.d.ts +6 -0
  156. package/dist/components/playground/SessionManager.svelte +9 -12
  157. package/dist/components/playground/pipelineViewUtils.svelte.d.ts +30 -1
  158. package/dist/components/playground/pipelineViewUtils.svelte.js +40 -3
  159. package/dist/components/surfaces/SurfaceOverlay.svelte +153 -0
  160. package/dist/components/surfaces/SurfaceOverlay.svelte.d.ts +14 -0
  161. package/dist/components/surfaces/TabbedSurface.svelte +133 -0
  162. package/dist/components/surfaces/TabbedSurface.svelte.d.ts +27 -0
  163. package/dist/config/endpoints.d.ts +23 -7
  164. package/dist/config/endpoints.js +30 -10
  165. package/dist/core/index.d.ts +6 -7
  166. package/dist/core/index.js +8 -12
  167. package/dist/display/index.d.ts +6 -3
  168. package/dist/display/index.js +7 -5
  169. package/dist/editor/index.d.ts +20 -21
  170. package/dist/editor/index.js +26 -36
  171. package/dist/form/code.d.ts +25 -15
  172. package/dist/form/code.js +44 -41
  173. package/dist/form/fieldRegistry.d.ts +17 -13
  174. package/dist/form/fieldRegistry.js +32 -12
  175. package/dist/form/full.d.ts +19 -14
  176. package/dist/form/full.js +26 -28
  177. package/dist/form/index.d.ts +3 -4
  178. package/dist/form/index.js +6 -5
  179. package/dist/form/markdown.d.ts +13 -8
  180. package/dist/form/markdown.js +22 -23
  181. package/dist/helpers/proximityConnect.d.ts +3 -2
  182. package/dist/helpers/proximityConnect.js +2 -5
  183. package/dist/helpers/workflowEditorHelper.d.ts +14 -5
  184. package/dist/helpers/workflowEditorHelper.js +32 -30
  185. package/dist/index.d.ts +28 -24
  186. package/dist/index.js +27 -50
  187. package/dist/messages/defaults.d.ts +2 -5
  188. package/dist/messages/defaults.js +3 -6
  189. package/dist/messages/index.d.ts +1 -2
  190. package/dist/messages/index.js +1 -2
  191. package/dist/mocks/app-forms.d.ts +6 -2
  192. package/dist/mocks/app-forms.js +11 -4
  193. package/dist/openapi/v1/openapi.yaml +38 -26
  194. package/dist/playground/index.d.ts +4 -5
  195. package/dist/playground/index.js +4 -32
  196. package/dist/playground/mount.d.ts +34 -5
  197. package/dist/playground/mount.js +58 -24
  198. package/dist/registry/{BaseRegistry.d.ts → BaseRegistry.svelte.d.ts} +22 -1
  199. package/dist/registry/{BaseRegistry.js → BaseRegistry.svelte.js} +37 -1
  200. package/dist/registry/builtinFormats.d.ts +9 -18
  201. package/dist/registry/builtinFormats.js +9 -39
  202. package/dist/registry/builtinNodeTypes.d.ts +53 -0
  203. package/dist/registry/builtinNodeTypes.js +67 -0
  204. package/dist/registry/builtinNodes.d.ts +2 -64
  205. package/dist/registry/builtinNodes.js +7 -103
  206. package/dist/registry/index.d.ts +3 -4
  207. package/dist/registry/index.js +4 -6
  208. package/dist/registry/nodeComponentRegistry.d.ts +184 -16
  209. package/dist/registry/nodeComponentRegistry.js +235 -17
  210. package/dist/registry/workflowFormatRegistry.d.ts +14 -9
  211. package/dist/registry/workflowFormatRegistry.js +24 -8
  212. package/dist/{schema → schemas}/index.d.ts +2 -2
  213. package/dist/{schema → schemas}/index.js +2 -2
  214. package/dist/schemas/v1/workflow.schema.json +19 -17
  215. package/dist/services/agentSpecExecutionService.d.ts +0 -2
  216. package/dist/services/agentSpecExecutionService.js +0 -3
  217. package/dist/services/apiVariableService.d.ts +2 -1
  218. package/dist/services/apiVariableService.js +16 -47
  219. package/dist/services/autoSaveService.d.ts +7 -0
  220. package/dist/services/autoSaveService.js +6 -4
  221. package/dist/services/categoriesApi.js +3 -6
  222. package/dist/services/chatService.d.ts +9 -4
  223. package/dist/services/chatService.js +23 -28
  224. package/dist/services/draftStorage.d.ts +129 -13
  225. package/dist/services/draftStorage.js +185 -37
  226. package/dist/services/dynamicSchemaService.d.ts +33 -5
  227. package/dist/services/dynamicSchemaService.js +67 -55
  228. package/dist/services/globalSave.d.ts +13 -12
  229. package/dist/services/globalSave.js +29 -51
  230. package/dist/services/historyService.d.ts +39 -11
  231. package/dist/services/historyService.js +60 -18
  232. package/dist/services/interruptService.d.ts +15 -9
  233. package/dist/services/interruptService.js +35 -37
  234. package/dist/services/nodeExecutionService.d.ts +18 -3
  235. package/dist/services/nodeExecutionService.js +71 -45
  236. package/dist/services/playgroundService.d.ts +16 -10
  237. package/dist/services/playgroundService.js +42 -43
  238. package/dist/services/portConfigApi.js +3 -6
  239. package/dist/services/settingsService.d.ts +9 -4
  240. package/dist/services/settingsService.js +23 -12
  241. package/dist/services/variableService.d.ts +2 -1
  242. package/dist/services/variableService.js +2 -2
  243. package/dist/services/workflowStorage.js +6 -6
  244. package/dist/skins/drafter.d.ts +30 -0
  245. package/dist/skins/drafter.js +198 -0
  246. package/dist/skins/index.d.ts +2 -1
  247. package/dist/skins/index.js +4 -2
  248. package/dist/stores/apiContext.d.ts +56 -0
  249. package/dist/stores/apiContext.js +80 -0
  250. package/dist/stores/categoriesStore.svelte.d.ts +28 -23
  251. package/dist/stores/categoriesStore.svelte.js +69 -64
  252. package/dist/stores/getInstance.svelte.d.ts +39 -0
  253. package/dist/stores/getInstance.svelte.js +65 -0
  254. package/dist/stores/historyStore.svelte.d.ts +89 -91
  255. package/dist/stores/historyStore.svelte.js +159 -158
  256. package/dist/stores/instanceContainer.svelte.d.ts +111 -0
  257. package/dist/stores/instanceContainer.svelte.js +119 -0
  258. package/dist/stores/interruptStore.svelte.d.ts +112 -82
  259. package/dist/stores/interruptStore.svelte.js +253 -226
  260. package/dist/stores/pipelinePanelStore.svelte.d.ts +27 -3
  261. package/dist/stores/pipelinePanelStore.svelte.js +61 -14
  262. package/dist/stores/playgroundStore.svelte.d.ts +169 -222
  263. package/dist/stores/playgroundStore.svelte.js +513 -580
  264. package/dist/stores/portCoordinateStore.svelte.d.ts +57 -51
  265. package/dist/stores/portCoordinateStore.svelte.js +109 -98
  266. package/dist/stores/settingsStore.svelte.d.ts +17 -1
  267. package/dist/stores/settingsStore.svelte.js +79 -12
  268. package/dist/stores/workflowStore.svelte.d.ts +212 -210
  269. package/dist/stores/workflowStore.svelte.js +527 -502
  270. package/dist/stories/EdgeDecorator.svelte +5 -2
  271. package/dist/stories/NodeDecorator.svelte +5 -3
  272. package/dist/styles/base.css +285 -14
  273. package/dist/styles/tokens.css +60 -2
  274. package/dist/svelte-app.d.ts +78 -11
  275. package/dist/svelte-app.js +210 -141
  276. package/dist/themes/drafter.d.ts +2 -0
  277. package/dist/themes/drafter.js +15 -0
  278. package/dist/themes/index.d.ts +2 -1
  279. package/dist/themes/index.js +8 -2
  280. package/dist/types/auth.d.ts +9 -51
  281. package/dist/types/auth.js +4 -54
  282. package/dist/types/events.d.ts +24 -3
  283. package/dist/types/events.js +2 -1
  284. package/dist/types/index.d.ts +117 -32
  285. package/dist/types/index.js +0 -1
  286. package/dist/types/navbar.d.ts +7 -0
  287. package/dist/types/playground.d.ts +18 -3
  288. package/dist/types/settings.d.ts +30 -1
  289. package/dist/types/settings.js +5 -2
  290. package/dist/types/skin.d.ts +1 -1
  291. package/dist/types/theme.d.ts +16 -2
  292. package/dist/types/uischema.d.ts +5 -0
  293. package/dist/utils/colors.d.ts +74 -21
  294. package/dist/utils/colors.js +92 -68
  295. package/dist/utils/connections.d.ts +9 -15
  296. package/dist/utils/connections.js +33 -88
  297. package/dist/utils/duration.d.ts +13 -0
  298. package/dist/utils/duration.js +45 -0
  299. package/dist/utils/edgeStyling.js +9 -5
  300. package/dist/utils/fetchWithAuth.d.ts +36 -15
  301. package/dist/utils/fetchWithAuth.js +53 -23
  302. package/dist/utils/icons.d.ts +5 -2
  303. package/dist/utils/icons.js +6 -5
  304. package/dist/utils/nodeIds.d.ts +1 -1
  305. package/dist/utils/nodeIds.js +1 -1
  306. package/dist/utils/nodeSwap.d.ts +6 -2
  307. package/dist/utils/nodeSwap.js +62 -129
  308. package/dist/utils/nodeTypes.d.ts +17 -8
  309. package/dist/utils/nodeTypes.js +27 -20
  310. package/dist/utils/performanceUtils.js +7 -0
  311. package/dist/utils/portUtils.d.ts +47 -11
  312. package/dist/utils/portUtils.js +67 -14
  313. package/dist/utils/portal.d.ts +18 -0
  314. package/dist/utils/portal.js +34 -0
  315. package/dist/utils/schemaMerge.d.ts +25 -0
  316. package/dist/utils/schemaMerge.js +61 -0
  317. package/package.json +7 -5
  318. package/dist/messages/deprecation.d.ts +0 -20
  319. package/dist/messages/deprecation.js +0 -33
  320. package/dist/registry/plugin.d.ts +0 -215
  321. package/dist/registry/plugin.js +0 -249
  322. package/dist/services/api.d.ts +0 -129
  323. package/dist/services/api.js +0 -217
@@ -1,23 +1,26 @@
1
1
  /**
2
2
  * Workflow Store for FlowDrop (Svelte 5 Runes)
3
3
  *
4
- * Provides global state management for workflows with dirty state tracking
5
- * and undo/redo history integration.
4
+ * Provides per-instance state management for workflows with dirty state
5
+ * tracking and undo/redo history integration.
6
6
  *
7
- * **Important: Single-instance only.** This store uses module-level singletons.
8
- * Only one FlowDrop editor instance per page is supported. Mounting multiple
9
- * FlowDrop editors on the same page will cause them to share workflow state.
7
+ * The reactive state lives in the {@link WorkflowStore} class — one per
8
+ * FlowDrop instance, created by `createFlowDropInstance()` and resolved in
9
+ * components via `getInstance().workflow`.
10
10
  *
11
11
  * @module stores/workflowStore
12
12
  */
13
13
  import { DEFAULT_WORKFLOW_FORMAT } from '../types/index.js';
14
- import { historyService } from '../services/historyService.js';
14
+ import { WORKFLOW_SCHEMA_VERSION } from '../schemas/index.js';
15
15
  /**
16
16
  * Safely build updated workflow metadata, providing defaults for required fields.
17
+ *
18
+ * Accepts loosely-typed legacy metadata so it can absorb 1.x documents (where
19
+ * the schema-version field was named `version`) during load-time healing.
17
20
  */
18
21
  function buildMetadata(existing, updates) {
19
22
  return {
20
- version: existing?.version ?? '1.0',
23
+ schemaVersion: existing?.schemaVersion ?? existing?.version ?? WORKFLOW_SCHEMA_VERSION,
21
24
  createdAt: existing?.createdAt ?? new Date().toISOString(),
22
25
  updatedAt: new Date().toISOString(),
23
26
  author: existing?.author,
@@ -28,336 +31,30 @@ function buildMetadata(existing, updates) {
28
31
  ...updates
29
32
  };
30
33
  }
31
- // =========================================================================
32
- // Core Workflow State (Svelte 5 Runes)
33
- // =========================================================================
34
- /** Global workflow state */
35
- let workflowState = $state(null);
36
- // =========================================================================
37
- // Dirty State Tracking (Version Counter)
38
- // =========================================================================
39
- /**
40
- * Monotonic edit version — bumps on every mutation action.
41
- *
42
- * Used for two purposes:
43
- * 1. O(1) dirty detection: isDirty = _editVersion !== _savedVersion
44
- * 2. Save verification protocol: include the version in the save request,
45
- * backend echoes it back. If the echoed version doesn't match, the save
46
- * didn't persist the version the client submitted.
47
- */
48
- let _editVersion = $state(0);
49
- /**
50
- * Edit version captured at the last successful save.
51
- * When _editVersion === _savedVersion, the workflow is clean.
52
- */
53
- let _savedVersion = $state(0);
54
- /**
55
- * Callback for dirty state changes
56
- *
57
- * Set by the App component to notify parent application.
58
- */
59
- let onDirtyStateChangeCallback = null;
60
- /**
61
- * Callback for workflow changes
62
- *
63
- * Set by the App component to notify parent application.
64
- */
65
- let onWorkflowChangeCallback = null;
66
- /**
67
- * Flag to track if we're currently restoring from history (undo/redo)
68
- *
69
- * When true, prevents pushing to history to avoid recursive loops.
70
- */
71
- let isRestoringFromHistory = false;
72
- /**
73
- * Flag to track if history recording is enabled
74
- *
75
- * Can be disabled for bulk operations or when history is not needed.
76
- */
77
- let historyEnabled = true;
78
- // =========================================================================
79
- // Getter Functions (Reactive State Access)
80
- // =========================================================================
81
- /**
82
- * Get the current workflow store value reactively
83
- *
84
- * @returns The current workflow or null
85
- */
86
- export function getWorkflowStore() {
87
- return workflowState;
88
- }
89
- /**
90
- * Get the current dirty state reactively
91
- *
92
- * Reads both _editVersion and _savedVersion, so Svelte tracks them
93
- * as reactive dependencies — any component using this will re-render
94
- * when dirty state changes.
95
- *
96
- * @returns true if there are unsaved changes
97
- */
98
- export function getIsDirty() {
99
- return _editVersion !== _savedVersion;
100
- }
101
- /**
102
- * Get the workflow ID reactively
103
- *
104
- * @returns The workflow ID or null
105
- */
106
- export function getWorkflowId() {
107
- return workflowState?.id ?? null;
108
- }
109
- /**
110
- * Get the workflow name reactively
111
- *
112
- * @returns The workflow name or 'Untitled Workflow'
113
- */
114
- export function getWorkflowName() {
115
- return workflowState?.name ?? 'Untitled Workflow';
116
- }
117
- /**
118
- * Get the workflow nodes reactively
119
- *
120
- * @returns Array of workflow nodes
121
- */
122
- export function getWorkflowNodes() {
123
- return workflowState?.nodes ?? [];
124
- }
125
- /**
126
- * Get the workflow edges reactively
127
- *
128
- * @returns Array of workflow edges
129
- */
130
- export function getWorkflowEdges() {
131
- return workflowState?.edges ?? [];
132
- }
133
- /**
134
- * Get the workflow metadata reactively
135
- *
136
- * @returns The workflow metadata with defaults
137
- */
138
- export function getWorkflowMetadata() {
139
- return (workflowState?.metadata ?? {
140
- version: '1.0.0',
141
- createdAt: new Date().toISOString(),
142
- updatedAt: new Date().toISOString(),
143
- versionId: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
144
- updateNumber: 0
145
- });
146
- }
147
- /**
148
- * Get the current workflow format reactively
149
- *
150
- * @returns The workflow format string
151
- */
152
- export function getWorkflowFormat() {
153
- return workflowState?.metadata?.format ?? DEFAULT_WORKFLOW_FORMAT;
154
- }
155
- /**
156
- * Get workflow change summary reactively (useful for triggering saves)
157
- *
158
- * @returns Object with nodes, edges, and name
159
- */
160
- export function getWorkflowChanged() {
161
- return {
162
- nodes: getWorkflowNodes(),
163
- edges: getWorkflowEdges(),
164
- name: getWorkflowName()
165
- };
166
- }
167
- /**
168
- * Get workflow validation state reactively
169
- *
170
- * @returns Validation info object
171
- */
172
- export function getWorkflowValidation() {
173
- const nodes = getWorkflowNodes();
174
- const edges = getWorkflowEdges();
175
- return {
176
- hasNodes: nodes.length > 0,
177
- hasEdges: edges.length > 0,
178
- nodeCount: nodes.length,
179
- edgeCount: edges.length,
180
- isValid: nodes.length > 0 && edges.length >= 0
181
- };
182
- }
183
- /**
184
- * Get workflow metadata change summary reactively
185
- *
186
- * @returns Metadata change info
187
- */
188
- export function getWorkflowMetadataChanged() {
189
- const metadata = getWorkflowMetadata();
190
- return {
191
- createdAt: metadata.createdAt,
192
- updatedAt: metadata.updatedAt,
193
- version: metadata.version ?? '1.0.0'
194
- };
195
- }
196
- /**
197
- * Get connected handles reactively
198
- *
199
- * Provides a Set of all handle IDs that are currently connected to edges.
200
- * Used by node components to implement hideUnconnectedHandles functionality.
201
- *
202
- * @example
203
- * ```typescript
204
- * import { getConnectedHandles } from './workflowStore.svelte.js';
205
- *
206
- * // Check if a specific handle is connected
207
- * const isConnected = getConnectedHandles().has('node-1-input-data');
208
- * ```
209
- */
210
- export function getConnectedHandles() {
211
- const edges = getWorkflowEdges();
212
- const handles = new Set();
213
- edges.forEach((edge) => {
214
- // Add source handle (output port)
215
- if (edge.sourceHandle) {
216
- handles.add(edge.sourceHandle);
217
- }
218
- // Add target handle (input port)
219
- if (edge.targetHandle) {
220
- handles.add(edge.targetHandle);
221
- }
222
- });
223
- return handles;
224
- }
225
- // =========================================================================
226
- // Callback Setters
227
- // =========================================================================
228
- /**
229
- * Set the dirty state change callback
230
- *
231
- * @param callback - Function to call when dirty state changes
232
- */
233
- export function setOnDirtyStateChange(callback) {
234
- onDirtyStateChangeCallback = callback;
235
- }
236
- /**
237
- * Set the workflow change callback
238
- *
239
- * @param callback - Function to call when workflow changes
240
- */
241
- export function setOnWorkflowChange(callback) {
242
- onWorkflowChangeCallback = callback;
243
- }
244
- // =========================================================================
245
- // Internal Helpers
246
- // =========================================================================
247
- /**
248
- * Bump the edit version and notify dirty state change if needed.
249
- * Called by every mutation action.
250
- */
251
- function bumpVersion() {
252
- _editVersion++;
253
- // Dirty state just flipped from clean → dirty
254
- if (_editVersion - 1 === _savedVersion) {
255
- if (onDirtyStateChangeCallback) {
256
- onDirtyStateChangeCallback(true);
257
- }
258
- }
259
- }
260
- /**
261
- * Notify external listeners of a workflow change.
262
- * Does NOT bump the version — callers that mutate must call bumpVersion() explicitly.
263
- *
264
- * @param changeType - The type of change that occurred
265
- */
266
- function notifyWorkflowChange(changeType) {
267
- if (workflowState && onWorkflowChangeCallback) {
268
- onWorkflowChangeCallback(workflowState, changeType);
269
- }
270
- }
271
- /**
272
- * Mark the current workflow state as saved.
273
- *
274
- * Captures the current edit version so isDirty becomes false.
275
- * Call this after a successful backend save.
276
- */
277
- export function markAsSaved() {
278
- const wasDirty = _editVersion !== _savedVersion;
279
- _savedVersion = _editVersion;
280
- if (wasDirty && onDirtyStateChangeCallback) {
281
- onDirtyStateChangeCallback(false);
282
- }
283
- }
284
- /**
285
- * Check if there are unsaved changes (non-reactive version for plain TS)
286
- *
287
- * @returns true if there are unsaved changes
288
- */
289
- export function isDirty() {
290
- return _editVersion !== _savedVersion;
291
- }
292
- /**
293
- * Get the current edit version.
294
- *
295
- * Use this for the save verification protocol:
296
- * 1. Before save: `const v = getEditVersion()`
297
- * 2. Include `v` in the save request payload
298
- * 3. Backend echoes `v` in the response
299
- * 4. If echoed version matches: `markAsSaved()`
300
- * 5. If not: the save didn't persist the version you submitted — reset from backend response
301
- *
302
- * @returns The current monotonic edit version
303
- */
304
- export function getEditVersion() {
305
- return _editVersion;
306
- }
307
- /**
308
- * Enable or disable history recording
309
- *
310
- * Useful for bulk operations where you don't want individual history entries.
311
- *
312
- * @param enabled - Whether history should be recorded
313
- */
314
- export function setHistoryEnabled(enabled) {
315
- historyEnabled = enabled;
316
- }
317
34
  /**
318
- * Check if history recording is enabled
35
+ * Normalize workflow metadata at load time (the only back-compat path we keep,
36
+ * mirroring the storage-key migration in commit 8fab9157).
319
37
  *
320
- * @returns true if history is being recorded
321
- */
322
- export function isHistoryEnabled() {
323
- return historyEnabled;
324
- }
325
- /**
326
- * Set the restoring from history flag
327
- *
328
- * Used internally by the history store when performing undo/redo.
329
- *
330
- * @param restoring - Whether we're currently restoring from history
331
- */
332
- export function setRestoringFromHistory(restoring) {
333
- isRestoringFromHistory = restoring;
334
- }
335
- /**
336
- * Push current state to history before making changes
38
+ * Rules:
39
+ * - missing `metadata` → `buildMetadata(undefined)` (fresh required defaults)
40
+ * - legacy `version` key present → copied to `schemaVersion` when absent, then
41
+ * the legacy key is dropped
337
42
  *
338
- * @param description - Description of the change about to be made
339
- * @param workflow - Optional workflow to push (uses store if not provided)
43
+ * Idempotent: re-running on an already-healed workflow returns equivalent
44
+ * metadata (round-trip stable).
340
45
  */
341
- function pushToHistory(description, workflow) {
342
- if (!historyEnabled || isRestoringFromHistory) {
343
- return;
46
+ export function normalizeWorkflowMetadata(workflow) {
47
+ const raw = workflow.metadata;
48
+ if (!raw) {
49
+ return { ...workflow, metadata: buildMetadata(undefined) };
344
50
  }
345
- const workflowToPush = workflow ?? workflowState;
346
- if (workflowToPush) {
347
- historyService.push(workflowToPush, { description });
348
- }
349
- }
350
- /**
351
- * Get the current workflow (non-reactive version for plain TS)
352
- *
353
- * @returns The current workflow or null
354
- */
355
- export function getWorkflow() {
356
- return workflowState;
51
+ const { version: legacyVersion, ...rest } = raw;
52
+ const healed = {
53
+ ...rest,
54
+ schemaVersion: rest.schemaVersion ?? legacyVersion ?? WORKFLOW_SCHEMA_VERSION
55
+ };
56
+ return { ...workflow, metadata: healed };
357
57
  }
358
- // =========================================================================
359
- // Helper Functions
360
- // =========================================================================
361
58
  /**
362
59
  * Check if workflow data has actually changed
363
60
  *
@@ -398,234 +95,560 @@ function hasWorkflowDataChanged(currentWorkflow, newNodes, newEdges) {
398
95
  return false;
399
96
  }
400
97
  // =========================================================================
401
- // Workflow Actions
98
+ // WorkflowStore (per-instance reactive state)
402
99
  // =========================================================================
403
100
  /**
404
- * Actions for updating the workflow
101
+ * Per-instance workflow state with dirty tracking and history integration.
405
102
  *
406
- * All actions that modify the workflow will trigger dirty state updates
407
- * and emit change events.
103
+ * All reads go through getters backed by `$state`, so reading them inside a
104
+ * component template or `$derived` tracks reactively, exactly like the
105
+ * legacy module-level functions did.
408
106
  */
409
- export const workflowActions = {
107
+ export class WorkflowStore {
108
+ /** Current workflow */
109
+ #workflow = $state(null);
410
110
  /**
411
- * Initialize workflow (from load or new)
111
+ * Monotonic edit version — bumps on every mutation action.
112
+ *
113
+ * Used for two purposes:
114
+ * 1. O(1) dirty detection: isDirty = #editVersion !== #savedVersion
115
+ * 2. Save verification protocol: include the version in the save request,
116
+ * backend echoes it back. If the echoed version doesn't match, the save
117
+ * didn't persist the version the client submitted.
118
+ */
119
+ #editVersion = $state(0);
120
+ /**
121
+ * Edit version captured at the last successful save.
122
+ * When #editVersion === #savedVersion, the workflow is clean.
123
+ */
124
+ #savedVersion = $state(0);
125
+ /** Callback for dirty state changes — set by the App component. */
126
+ #onDirtyStateChange = null;
127
+ /** Callback for workflow changes — set by the App component. */
128
+ #onWorkflowChange = null;
129
+ /**
130
+ * Whether we're currently restoring from history (undo/redo).
131
+ * When true, prevents pushing to history to avoid recursive loops.
132
+ */
133
+ #restoringFromHistory = false;
134
+ /** Whether history recording is enabled (disable for bulk operations). */
135
+ #historyEnabled = true;
136
+ /**
137
+ * Identifies the config-edit session currently in progress, as
138
+ * `${nodeId}::${fieldKey}`, or null when no field is being edited.
139
+ *
140
+ * Config fields commit live on every change (see {@link updateNodeConfig}),
141
+ * but a whole field-editing session — however many keystrokes — should be a
142
+ * single undo step and fire the external change event only once. The session
143
+ * is a history transaction: opened lazily on the first change, coalescing all
144
+ * live edits, and closed by {@link finalizeNodeConfig}. A change to a
145
+ * different node/field auto-finalizes the previous session first, giving
146
+ * one-undo-step-per-field granularity.
147
+ */
148
+ #configEditKey = null;
149
+ /** Undo/redo engine for this instance (constructor-injected). */
150
+ #history;
151
+ /** Bound mutation facade — see {@link WorkflowStoreActions}. */
152
+ actions;
153
+ constructor(history) {
154
+ this.#history = history;
155
+ this.actions = Object.freeze({
156
+ initialize: this.initialize.bind(this),
157
+ updateWorkflow: this.updateWorkflow.bind(this),
158
+ restoreFromHistory: this.restoreFromHistory.bind(this),
159
+ updateNodes: this.updateNodes.bind(this),
160
+ updateEdges: this.updateEdges.bind(this),
161
+ updateName: this.updateName.bind(this),
162
+ addNode: this.addNode.bind(this),
163
+ removeNode: this.removeNode.bind(this),
164
+ addEdge: this.addEdge.bind(this),
165
+ removeEdge: this.removeEdge.bind(this),
166
+ updateNode: this.updateNode.bind(this),
167
+ updateNodeConfig: this.updateNodeConfig.bind(this),
168
+ finalizeNodeConfig: this.finalizeNodeConfig.bind(this),
169
+ clear: this.clear.bind(this),
170
+ updateMetadata: this.updateMetadata.bind(this),
171
+ batchUpdate: this.batchUpdate.bind(this),
172
+ swapNode: this.swapNode.bind(this),
173
+ pushHistory: this.pushHistory.bind(this)
174
+ });
175
+ }
176
+ // -----------------------------------------------------------------------
177
+ // Reactive getters
178
+ // -----------------------------------------------------------------------
179
+ /** The current workflow, or null when none is loaded. */
180
+ get current() {
181
+ return this.#workflow;
182
+ }
183
+ /**
184
+ * Whether there are unsaved changes.
185
+ *
186
+ * Reads both #editVersion and #savedVersion, so Svelte tracks them as
187
+ * reactive dependencies — any component using this re-renders when dirty
188
+ * state changes.
189
+ */
190
+ get isDirty() {
191
+ return this.#editVersion !== this.#savedVersion;
192
+ }
193
+ /** The workflow ID, or null. */
194
+ get id() {
195
+ return this.#workflow?.id ?? null;
196
+ }
197
+ /** The workflow name, or 'Untitled Workflow'. */
198
+ get name() {
199
+ return this.#workflow?.name ?? 'Untitled Workflow';
200
+ }
201
+ /** The workflow nodes. */
202
+ get nodes() {
203
+ return this.#workflow?.nodes ?? [];
204
+ }
205
+ /** The workflow edges. */
206
+ get edges() {
207
+ return this.#workflow?.edges ?? [];
208
+ }
209
+ /** The workflow metadata, with defaults. */
210
+ get metadata() {
211
+ return (this.#workflow?.metadata ?? {
212
+ schemaVersion: WORKFLOW_SCHEMA_VERSION,
213
+ createdAt: new Date().toISOString(),
214
+ updatedAt: new Date().toISOString(),
215
+ versionId: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
216
+ updateNumber: 0
217
+ });
218
+ }
219
+ /** The workflow format string. */
220
+ get format() {
221
+ return this.#workflow?.metadata?.format ?? DEFAULT_WORKFLOW_FORMAT;
222
+ }
223
+ /** Workflow change summary (useful for triggering saves). */
224
+ get changeSummary() {
225
+ return {
226
+ nodes: this.nodes,
227
+ edges: this.edges,
228
+ name: this.name
229
+ };
230
+ }
231
+ /** Workflow validation state. */
232
+ get validation() {
233
+ const nodes = this.nodes;
234
+ const edges = this.edges;
235
+ return {
236
+ hasNodes: nodes.length > 0,
237
+ hasEdges: edges.length > 0,
238
+ nodeCount: nodes.length,
239
+ edgeCount: edges.length,
240
+ isValid: nodes.length > 0 && edges.length >= 0
241
+ };
242
+ }
243
+ /** Workflow metadata change summary. */
244
+ get metadataChangeSummary() {
245
+ const metadata = this.metadata;
246
+ return {
247
+ createdAt: metadata.createdAt,
248
+ updatedAt: metadata.updatedAt,
249
+ schemaVersion: metadata.schemaVersion ?? WORKFLOW_SCHEMA_VERSION
250
+ };
251
+ }
252
+ /**
253
+ * Set of all handle IDs currently connected to edges.
254
+ *
255
+ * Handle IDs are formatted `{nodeId}-{direction}-{portId}`.
256
+ */
257
+ get connectedHandles() {
258
+ const handles = new Set();
259
+ this.edges.forEach((edge) => {
260
+ // Add source handle (output port)
261
+ if (edge.sourceHandle) {
262
+ handles.add(edge.sourceHandle);
263
+ }
264
+ // Add target handle (input port)
265
+ if (edge.targetHandle) {
266
+ handles.add(edge.targetHandle);
267
+ }
268
+ });
269
+ return handles;
270
+ }
271
+ /**
272
+ * The current monotonic edit version.
273
+ *
274
+ * Use this for the save verification protocol:
275
+ * 1. Before save: `const v = store.editVersion`
276
+ * 2. Include `v` in the save request payload
277
+ * 3. Backend echoes `v` in the response
278
+ * 4. If echoed version matches: `store.markAsSaved()`
279
+ * 5. If not: the save didn't persist the version you submitted — reset from backend response
280
+ */
281
+ get editVersion() {
282
+ return this.#editVersion;
283
+ }
284
+ /** Whether history recording is enabled. */
285
+ get historyEnabled() {
286
+ return this.#historyEnabled;
287
+ }
288
+ /** Enable or disable history recording (e.g. for bulk operations). */
289
+ set historyEnabled(enabled) {
290
+ this.#historyEnabled = enabled;
291
+ }
292
+ // -----------------------------------------------------------------------
293
+ // Callback setters & save protocol
294
+ // -----------------------------------------------------------------------
295
+ /** Set the dirty state change callback. */
296
+ setOnDirtyStateChange(callback) {
297
+ this.#onDirtyStateChange = callback;
298
+ }
299
+ /** Set the workflow change callback. */
300
+ setOnWorkflowChange(callback) {
301
+ this.#onWorkflowChange = callback;
302
+ }
303
+ /**
304
+ * Mark the current workflow state as saved.
305
+ *
306
+ * Captures the current edit version so isDirty becomes false.
307
+ * Call this after a successful backend save.
308
+ */
309
+ markAsSaved() {
310
+ const wasDirty = this.#editVersion !== this.#savedVersion;
311
+ this.#savedVersion = this.#editVersion;
312
+ if (wasDirty && this.#onDirtyStateChange) {
313
+ this.#onDirtyStateChange(false);
314
+ }
315
+ }
316
+ /**
317
+ * Set the restoring from history flag.
318
+ *
319
+ * Used internally by the history store when performing undo/redo.
320
+ */
321
+ setRestoringFromHistory(restoring) {
322
+ this.#restoringFromHistory = restoring;
323
+ }
324
+ // -----------------------------------------------------------------------
325
+ // Internal helpers
326
+ // -----------------------------------------------------------------------
327
+ /**
328
+ * Bump the edit version and notify dirty state change if needed.
329
+ * Called by every mutation action.
330
+ */
331
+ #bumpVersion() {
332
+ this.#editVersion++;
333
+ // Dirty state just flipped from clean → dirty
334
+ if (this.#editVersion - 1 === this.#savedVersion) {
335
+ if (this.#onDirtyStateChange) {
336
+ this.#onDirtyStateChange(true);
337
+ }
338
+ }
339
+ }
340
+ /**
341
+ * Notify external listeners of a workflow change.
342
+ * Does NOT bump the version — callers that mutate must call #bumpVersion() explicitly.
343
+ */
344
+ #notifyWorkflowChange(changeType) {
345
+ if (this.#workflow && this.#onWorkflowChange) {
346
+ this.#onWorkflowChange(this.#workflow, changeType);
347
+ }
348
+ }
349
+ /**
350
+ * Record the current (post-change) state to history.
351
+ *
352
+ * Call this AFTER mutating `#workflow` so the entry captures the new committed
353
+ * state — the history stack's top is the live state, making one undo == one
354
+ * change (see issue #39). Passing the pre-change state instead makes a single
355
+ * undo skip a step once there are two or more sequential edits.
356
+ *
357
+ * @param description - Description of the change that was just made
358
+ * @param workflow - Optional workflow to push (uses store state if not provided)
359
+ */
360
+ #pushToHistory(description, workflow) {
361
+ if (!this.#historyEnabled || this.#restoringFromHistory) {
362
+ return;
363
+ }
364
+ const workflowToPush = workflow ?? this.#workflow;
365
+ if (workflowToPush) {
366
+ this.#history.push(workflowToPush, { description });
367
+ }
368
+ }
369
+ // -----------------------------------------------------------------------
370
+ // Mutation actions
371
+ // -----------------------------------------------------------------------
372
+ /**
373
+ * Initialize workflow (from load or new).
412
374
  *
413
375
  * This sets the initial saved snapshot, clears dirty state, and initializes history.
414
376
  */
415
- initialize: (workflow) => {
416
- workflowState = workflow;
377
+ initialize(workflow) {
378
+ this.#configEditKey = null;
379
+ workflow = normalizeWorkflowMetadata(workflow);
380
+ this.#workflow = workflow;
417
381
  // Reset version counters — workflow is "clean" after initialization
418
- _editVersion = 0;
419
- _savedVersion = 0;
420
- if (onDirtyStateChangeCallback) {
421
- onDirtyStateChangeCallback(false);
382
+ this.#editVersion = 0;
383
+ this.#savedVersion = 0;
384
+ if (this.#onDirtyStateChange) {
385
+ this.#onDirtyStateChange(false);
422
386
  }
423
387
  // Initialize history with the loaded workflow
424
- historyService.initialize(workflow);
425
- },
388
+ this.#history.initialize(workflow);
389
+ }
426
390
  /**
427
- * Update the entire workflow
391
+ * Update the entire workflow.
428
392
  *
429
393
  * Note: This is typically called from SvelteFlow sync and should not push to history
430
394
  * for every small change. History is pushed by specific actions or drag handlers.
431
395
  */
432
- updateWorkflow: (workflow) => {
433
- workflowState = workflow;
434
- bumpVersion();
435
- notifyWorkflowChange('metadata');
436
- },
396
+ updateWorkflow(workflow) {
397
+ this.#workflow = workflow;
398
+ this.#bumpVersion();
399
+ this.#notifyWorkflowChange('metadata');
400
+ }
437
401
  /**
438
- * Restore workflow from history (undo/redo)
402
+ * Restore workflow from history (undo/redo).
439
403
  *
440
404
  * This bypasses history recording to prevent recursive loops.
441
405
  */
442
- restoreFromHistory: (workflow) => {
443
- isRestoringFromHistory = true;
444
- workflowState = workflow;
445
- bumpVersion();
446
- notifyWorkflowChange('metadata');
447
- isRestoringFromHistory = false;
448
- },
449
- /**
450
- * Update nodes
451
- */
452
- updateNodes: (nodes) => {
453
- if (!workflowState)
406
+ restoreFromHistory(workflow) {
407
+ // Undo/redo supersedes any in-progress config edit; drop the session marker
408
+ // (the history service already closed the transaction).
409
+ this.#configEditKey = null;
410
+ this.#restoringFromHistory = true;
411
+ workflow = normalizeWorkflowMetadata(workflow);
412
+ this.#workflow = workflow;
413
+ this.#bumpVersion();
414
+ this.#notifyWorkflowChange('metadata');
415
+ this.#restoringFromHistory = false;
416
+ }
417
+ /** Update nodes. */
418
+ updateNodes(nodes) {
419
+ if (!this.#workflow)
454
420
  return;
455
421
  // Check if nodes have actually changed to prevent infinite loops
456
- if (!hasWorkflowDataChanged(workflowState, nodes, workflowState.edges)) {
422
+ if (!hasWorkflowDataChanged(this.#workflow, nodes, this.#workflow.edges)) {
457
423
  return;
458
424
  }
459
425
  // Generate unique version identifier
460
426
  const versionId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
461
- workflowState = {
462
- ...workflowState,
427
+ this.#workflow = {
428
+ ...this.#workflow,
463
429
  nodes,
464
- metadata: buildMetadata(workflowState.metadata, {
430
+ metadata: buildMetadata(this.#workflow.metadata, {
465
431
  versionId,
466
- updateNumber: (workflowState.metadata?.updateNumber ?? 0) + 1
432
+ updateNumber: (this.#workflow.metadata?.updateNumber ?? 0) + 1
467
433
  })
468
434
  };
469
- bumpVersion();
470
- notifyWorkflowChange('node_move');
471
- },
472
- /**
473
- * Update edges
474
- */
475
- updateEdges: (edges) => {
476
- if (!workflowState)
435
+ this.#bumpVersion();
436
+ this.#notifyWorkflowChange('node_move');
437
+ }
438
+ /** Update edges. */
439
+ updateEdges(edges) {
440
+ if (!this.#workflow)
477
441
  return;
478
442
  // Check if edges have actually changed to prevent infinite loops
479
- if (!hasWorkflowDataChanged(workflowState, workflowState.nodes, edges)) {
443
+ if (!hasWorkflowDataChanged(this.#workflow, this.#workflow.nodes, edges)) {
480
444
  return;
481
445
  }
482
446
  // Generate unique version identifier
483
447
  const versionId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
484
- workflowState = {
485
- ...workflowState,
448
+ this.#workflow = {
449
+ ...this.#workflow,
486
450
  edges,
487
- metadata: buildMetadata(workflowState.metadata, {
451
+ metadata: buildMetadata(this.#workflow.metadata, {
488
452
  versionId,
489
- updateNumber: (workflowState.metadata?.updateNumber ?? 0) + 1
453
+ updateNumber: (this.#workflow.metadata?.updateNumber ?? 0) + 1
490
454
  })
491
455
  };
492
- bumpVersion();
493
- notifyWorkflowChange('edge_add');
494
- },
495
- /**
496
- * Update workflow name
497
- */
498
- updateName: (name) => {
499
- if (!workflowState)
456
+ this.#bumpVersion();
457
+ this.#notifyWorkflowChange('edge_add');
458
+ }
459
+ /** Update workflow name. */
460
+ updateName(name) {
461
+ if (!this.#workflow)
500
462
  return;
501
- workflowState = {
502
- ...workflowState,
463
+ this.#workflow = {
464
+ ...this.#workflow,
503
465
  name,
504
- metadata: buildMetadata(workflowState.metadata)
466
+ metadata: buildMetadata(this.#workflow.metadata)
505
467
  };
506
- bumpVersion();
507
- notifyWorkflowChange('name');
508
- },
509
- /**
510
- * Add a node
511
- */
512
- addNode: (node) => {
513
- pushToHistory('Add node');
514
- if (!workflowState)
468
+ this.#bumpVersion();
469
+ this.#notifyWorkflowChange('name');
470
+ }
471
+ /** Add a node. */
472
+ addNode(node) {
473
+ if (!this.#workflow)
515
474
  return;
516
- workflowState = {
517
- ...workflowState,
518
- nodes: [...workflowState.nodes, node],
519
- metadata: buildMetadata(workflowState.metadata)
475
+ this.#workflow = {
476
+ ...this.#workflow,
477
+ nodes: [...this.#workflow.nodes, node],
478
+ metadata: buildMetadata(this.#workflow.metadata)
520
479
  };
521
- bumpVersion();
522
- notifyWorkflowChange('node_add');
523
- },
480
+ this.#pushToHistory('Add node');
481
+ this.#bumpVersion();
482
+ this.#notifyWorkflowChange('node_add');
483
+ }
524
484
  /**
525
- * Remove a node
485
+ * Remove a node.
526
486
  *
527
487
  * This is an atomic operation that also removes connected edges.
528
488
  * A single undo will restore both the node and its edges.
529
489
  */
530
- removeNode: (nodeId) => {
531
- pushToHistory('Delete node');
532
- if (!workflowState)
490
+ removeNode(nodeId) {
491
+ if (!this.#workflow)
533
492
  return;
534
- workflowState = {
535
- ...workflowState,
536
- nodes: workflowState.nodes.filter((node) => node.id !== nodeId),
537
- edges: workflowState.edges.filter((edge) => edge.source !== nodeId && edge.target !== nodeId),
538
- metadata: buildMetadata(workflowState.metadata)
493
+ this.#workflow = {
494
+ ...this.#workflow,
495
+ nodes: this.#workflow.nodes.filter((node) => node.id !== nodeId),
496
+ edges: this.#workflow.edges.filter((edge) => edge.source !== nodeId && edge.target !== nodeId),
497
+ metadata: buildMetadata(this.#workflow.metadata)
539
498
  };
540
- bumpVersion();
541
- notifyWorkflowChange('node_remove');
542
- },
543
- /**
544
- * Add an edge
545
- */
546
- addEdge: (edge) => {
547
- pushToHistory('Add connection');
548
- if (!workflowState)
499
+ this.#pushToHistory('Delete node');
500
+ this.#bumpVersion();
501
+ this.#notifyWorkflowChange('node_remove');
502
+ }
503
+ /** Add an edge. */
504
+ addEdge(edge) {
505
+ if (!this.#workflow)
506
+ return;
507
+ // Never append an edge whose id already exists — SvelteFlow keys edges by id
508
+ // and a duplicate throws `each_key_duplicate`, taking down the canvas. Guard
509
+ // before touching history so a no-op stays a no-op.
510
+ if (this.#workflow.edges.some((e) => e.id === edge.id))
511
+ return;
512
+ this.#workflow = {
513
+ ...this.#workflow,
514
+ edges: [...this.#workflow.edges, edge],
515
+ metadata: buildMetadata(this.#workflow.metadata)
516
+ };
517
+ this.#pushToHistory('Add connection');
518
+ this.#bumpVersion();
519
+ this.#notifyWorkflowChange('edge_add');
520
+ }
521
+ /** Remove an edge. */
522
+ removeEdge(edgeId) {
523
+ if (!this.#workflow)
549
524
  return;
550
- workflowState = {
551
- ...workflowState,
552
- edges: [...workflowState.edges, edge],
553
- metadata: buildMetadata(workflowState.metadata)
525
+ this.#workflow = {
526
+ ...this.#workflow,
527
+ edges: this.#workflow.edges.filter((edge) => edge.id !== edgeId),
528
+ metadata: buildMetadata(this.#workflow.metadata)
554
529
  };
555
- bumpVersion();
556
- notifyWorkflowChange('edge_add');
557
- },
530
+ this.#pushToHistory('Delete connection');
531
+ this.#bumpVersion();
532
+ this.#notifyWorkflowChange('edge_remove');
533
+ }
558
534
  /**
559
- * Remove an edge
535
+ * Update a specific node.
536
+ *
537
+ * Used for config changes. Pushes to history for undo support.
560
538
  */
561
- removeEdge: (edgeId) => {
562
- pushToHistory('Delete connection');
563
- if (!workflowState)
539
+ updateNode(nodeId, updates) {
540
+ if (!this.#workflow)
564
541
  return;
565
- workflowState = {
566
- ...workflowState,
567
- edges: workflowState.edges.filter((edge) => edge.id !== edgeId),
568
- metadata: buildMetadata(workflowState.metadata)
542
+ this.#workflow = {
543
+ ...this.#workflow,
544
+ nodes: this.#workflow.nodes.map((node) => node.id === nodeId ? { ...node, ...updates } : node),
545
+ metadata: buildMetadata(this.#workflow.metadata)
569
546
  };
570
- bumpVersion();
571
- notifyWorkflowChange('edge_remove');
572
- },
547
+ this.#pushToHistory('Update node config');
548
+ this.#bumpVersion();
549
+ this.#notifyWorkflowChange('node_config');
550
+ }
573
551
  /**
574
- * Update a specific node
552
+ * Apply a live config edit to a node.
575
553
  *
576
- * Used for config changes. Pushes to history for undo support.
554
+ * Unlike {@link updateNode}, this is cheap enough to call on every keystroke:
555
+ * it does NOT snapshot the workflow to history and does NOT fire the external
556
+ * change event per call. Instead it opens (lazily) a single history
557
+ * transaction for the field-editing session and defers the change event to
558
+ * {@link finalizeNodeConfig}. Editing a different node or field first
559
+ * finalizes the previous session, so undo granularity is one step per field.
560
+ *
561
+ * The store always reflects the latest value immediately (the mutation and
562
+ * version bump happen here), so a save mid-session persists the current
563
+ * value even if the session hasn't been finalized yet.
564
+ *
565
+ * @param nodeId - Node whose config is being edited
566
+ * @param updates - Partial node updates (typically `{ data }`)
567
+ * @param opts.fieldKey - The config field being edited; drives per-field
568
+ * session boundaries. Omit to treat the whole node as one session.
577
569
  */
578
- updateNode: (nodeId, updates) => {
579
- pushToHistory('Update node config');
580
- if (!workflowState)
570
+ updateNodeConfig(nodeId, updates, opts) {
571
+ if (!this.#workflow)
581
572
  return;
582
- workflowState = {
583
- ...workflowState,
584
- nodes: workflowState.nodes.map((node) => node.id === nodeId ? { ...node, ...updates } : node),
585
- metadata: buildMetadata(workflowState.metadata)
573
+ const sessionKey = `${nodeId}::${opts?.fieldKey ?? ''}`;
574
+ // Moving to a different field/node closes the previous field's session.
575
+ if (this.#configEditKey !== null && this.#configEditKey !== sessionKey) {
576
+ this.finalizeNodeConfig();
577
+ }
578
+ // Open a transaction for this session on first touch. `push()` calls are
579
+ // no-ops until it commits, so the per-keystroke edits below never clone.
580
+ if (this.#configEditKey === null) {
581
+ if (this.#historyEnabled && !this.#restoringFromHistory) {
582
+ this.#history.startTransaction(this.#workflow, 'Update node config');
583
+ }
584
+ this.#configEditKey = sessionKey;
585
+ }
586
+ this.#workflow = {
587
+ ...this.#workflow,
588
+ nodes: this.#workflow.nodes.map((node) => node.id === nodeId ? { ...node, ...updates } : node),
589
+ metadata: buildMetadata(this.#workflow.metadata)
586
590
  };
587
- bumpVersion();
588
- notifyWorkflowChange('node_config');
589
- },
591
+ this.#bumpVersion();
592
+ // Deliberately no #pushToHistory (coalesced into the transaction) and no
593
+ // #notifyWorkflowChange (deferred to finalize) — that is the whole point.
594
+ }
590
595
  /**
591
- * Clear the workflow
596
+ * Finalize the in-progress config-edit session, if any.
592
597
  *
593
- * Resets the workflow and clears history.
598
+ * Commits the session's history transaction (one undo step for the whole
599
+ * session) and fires the external change event once. Idempotent: a no-op
600
+ * when no session is open. Call on blur, panel close, node switch, and before
601
+ * save. Undo/redo call this first (via the history facade / command dispatch)
602
+ * so a session becomes a committed step before it is undone.
594
603
  */
595
- clear: () => {
596
- workflowState = null;
597
- _editVersion = 0;
598
- _savedVersion = 0;
599
- historyService.clear();
600
- if (onDirtyStateChangeCallback) {
601
- onDirtyStateChangeCallback(false);
604
+ finalizeNodeConfig(changeType = 'node_config') {
605
+ if (this.#configEditKey === null)
606
+ return;
607
+ this.#configEditKey = null;
608
+ // A session can only be open when a workflow is loaded, so #workflow is
609
+ // non-null here; commit its final (post-change) state as one undo step.
610
+ if (this.#historyEnabled && this.#workflow) {
611
+ this.#history.commitTransaction(this.#workflow);
602
612
  }
603
- },
613
+ this.#notifyWorkflowChange(changeType);
614
+ }
604
615
  /**
605
- * Update workflow metadata
616
+ * Clear the workflow.
617
+ *
618
+ * Resets the workflow and clears history.
606
619
  */
607
- updateMetadata: (metadata) => {
608
- if (!workflowState)
620
+ clear() {
621
+ this.#configEditKey = null;
622
+ this.#workflow = null;
623
+ this.#editVersion = 0;
624
+ this.#savedVersion = 0;
625
+ this.#history.clear();
626
+ if (this.#onDirtyStateChange) {
627
+ this.#onDirtyStateChange(false);
628
+ }
629
+ }
630
+ /** Update workflow metadata. */
631
+ updateMetadata(metadata) {
632
+ if (!this.#workflow)
609
633
  return;
610
- workflowState = {
611
- ...workflowState,
612
- metadata: buildMetadata(workflowState.metadata, metadata)
634
+ this.#workflow = {
635
+ ...this.#workflow,
636
+ metadata: buildMetadata(this.#workflow.metadata, metadata)
613
637
  };
614
- bumpVersion();
615
- notifyWorkflowChange('metadata');
616
- },
638
+ this.#bumpVersion();
639
+ this.#notifyWorkflowChange('metadata');
640
+ }
617
641
  /**
618
- * Batch update nodes and edges
642
+ * Batch update nodes and edges.
619
643
  *
620
644
  * Useful for complex operations that update multiple things at once.
621
645
  * Creates a single history entry for the entire batch.
622
646
  */
623
- batchUpdate: (updates) => {
624
- pushToHistory('Batch update');
625
- if (!workflowState)
647
+ batchUpdate(updates) {
648
+ if (!this.#workflow)
626
649
  return;
627
- workflowState = {
628
- ...workflowState,
650
+ this.#workflow = {
651
+ ...this.#workflow,
629
652
  ...(updates.nodes && { nodes: updates.nodes }),
630
653
  ...(updates.edges && { edges: updates.edges }),
631
654
  ...(updates.name && { name: updates.name }),
@@ -633,40 +656,42 @@ export const workflowActions = {
633
656
  description: updates.description
634
657
  }),
635
658
  ...(updates.config !== undefined && { config: updates.config }),
636
- metadata: buildMetadata(workflowState.metadata, updates.metadata ?? undefined)
659
+ metadata: buildMetadata(this.#workflow.metadata, updates.metadata ?? undefined)
637
660
  };
638
- bumpVersion();
639
- notifyWorkflowChange('metadata');
640
- },
661
+ this.#pushToHistory('Batch update');
662
+ this.#bumpVersion();
663
+ this.#notifyWorkflowChange('metadata');
664
+ }
641
665
  /**
642
666
  * Swap a node — atomically replaces nodes and edges with a descriptive history entry.
643
667
  *
644
668
  * Unlike batchUpdate, this uses `"node_swap"` as the change type and
645
669
  * records a meaningful description for the undo history.
646
670
  */
647
- swapNode: (updates) => {
648
- pushToHistory(updates.description ?? 'Swap node');
649
- if (!workflowState)
671
+ swapNode(updates) {
672
+ if (!this.#workflow)
650
673
  return;
651
- workflowState = {
652
- ...workflowState,
674
+ this.#workflow = {
675
+ ...this.#workflow,
653
676
  nodes: updates.nodes,
654
677
  edges: updates.edges,
655
- metadata: buildMetadata(workflowState.metadata)
678
+ metadata: buildMetadata(this.#workflow.metadata)
656
679
  };
657
- bumpVersion();
658
- notifyWorkflowChange('node_swap');
659
- },
680
+ this.#pushToHistory(updates.description ?? 'Swap node');
681
+ this.#bumpVersion();
682
+ this.#notifyWorkflowChange('node_swap');
683
+ }
660
684
  /**
661
- * Push current state to history manually
685
+ * Push the current (post-change) state to history manually.
662
686
  *
663
- * Use this before operations that modify the workflow through other means
664
- * (e.g., drag operations handled by SvelteFlow directly).
687
+ * Use this AFTER operations that modify the workflow through other means
688
+ * (e.g., drag operations handled by SvelteFlow directly), passing the
689
+ * resulting state so undo returns to the state before the operation.
665
690
  *
666
- * @param description - Description of the upcoming change
691
+ * @param description - Description of the change that was just made
667
692
  * @param workflow - Optional workflow to push (uses store state if not provided)
668
693
  */
669
- pushHistory: (description, workflow) => {
670
- pushToHistory(description, workflow);
694
+ pushHistory(description, workflow) {
695
+ this.#pushToHistory(description, workflow);
671
696
  }
672
- };
697
+ }