@flowdrop/flowdrop 2.10.1 → 2.12.0

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 (571) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/dist/adapters/agentspec/autoLayout.d.ts +18 -36
  3. package/dist/adapters/agentspec/autoLayout.js +75 -93
  4. package/dist/chat/activity.d.ts +49 -0
  5. package/dist/chat/activity.js +65 -0
  6. package/dist/chat/commandClassifier.js +2 -1
  7. package/dist/commands/executor.js +186 -27
  8. package/dist/commands/index.d.ts +2 -1
  9. package/dist/commands/index.js +2 -0
  10. package/dist/commands/parser.js +43 -3
  11. package/dist/commands/session.d.ts +60 -0
  12. package/dist/commands/session.js +332 -0
  13. package/dist/commands/storeIntegration.svelte.js +18 -1
  14. package/dist/commands/types.d.ts +77 -4
  15. package/dist/components/App.svelte +1030 -207
  16. package/dist/components/App.svelte.d.ts +26 -2
  17. package/dist/components/BindablePortListbox.svelte +68 -369
  18. package/dist/components/Button.svelte +17 -14
  19. package/dist/components/Button.svelte.d.ts +2 -2
  20. package/dist/components/CanvasContextMenu.svelte +31 -10
  21. package/dist/components/CanvasController.svelte +146 -3
  22. package/dist/components/CanvasController.svelte.d.ts +25 -33
  23. package/dist/components/CanvasIconButton.svelte +6 -6
  24. package/dist/components/CanvasToolbar.svelte +103 -0
  25. package/dist/components/CanvasToolbar.svelte.d.ts +23 -0
  26. package/dist/components/CanvasZoomControls.svelte +122 -0
  27. package/dist/components/CanvasZoomControls.svelte.d.ts +15 -0
  28. package/dist/components/ConfigForm.svelte +163 -125
  29. package/dist/components/ConfigModal.svelte +13 -56
  30. package/dist/components/ConfigModal.svelte.d.ts +1 -1
  31. package/dist/components/ConfigPanel.svelte +98 -228
  32. package/dist/components/ConfigPanel.svelte.d.ts +2 -2
  33. package/dist/components/ConnectPortPicker.svelte +153 -0
  34. package/dist/components/ConnectPortPicker.svelte.d.ts +22 -0
  35. package/dist/components/ConnectionLine.svelte +1 -1
  36. package/dist/components/DoctorMenu.svelte +422 -0
  37. package/dist/components/DoctorMenu.svelte.d.ts +7 -0
  38. package/dist/components/ExternalLinkRow.svelte +82 -0
  39. package/dist/components/ExternalLinkRow.svelte.d.ts +14 -0
  40. package/dist/components/FlowDropEdge.svelte +52 -2
  41. package/dist/components/FlowDropEdge.svelte.d.ts +5 -1
  42. package/dist/components/InterfaceNameInput.svelte +103 -0
  43. package/dist/components/InterfaceNameInput.svelte.d.ts +13 -0
  44. package/dist/components/InterfaceTag.svelte +215 -0
  45. package/dist/components/InterfaceTag.svelte.d.ts +20 -0
  46. package/dist/components/InterfaceTagAnchor.svelte +103 -0
  47. package/dist/components/InterfaceTagAnchor.svelte.d.ts +12 -0
  48. package/dist/components/InterfaceTagLayer.svelte +314 -0
  49. package/dist/components/InterfaceTagLayer.svelte.d.ts +28 -0
  50. package/dist/components/LogsSidebar.svelte +58 -55
  51. package/dist/components/LoopbackLanes.svelte +54 -0
  52. package/dist/components/LoopbackLanes.svelte.d.ts +8 -0
  53. package/dist/components/MarkdownDisplay.svelte +1 -1
  54. package/dist/components/Navbar.svelte +539 -169
  55. package/dist/components/Navbar.svelte.d.ts +20 -1
  56. package/dist/components/NodeInspector.svelte +153 -0
  57. package/dist/components/NodeInspector.svelte.d.ts +19 -0
  58. package/dist/components/NodeLastRun.svelte +212 -0
  59. package/dist/components/NodeLastRun.svelte.d.ts +13 -0
  60. package/dist/components/NodeSidebar.svelte +279 -23
  61. package/dist/components/NodeSidebar.svelte.d.ts +11 -0
  62. package/dist/components/NodeStatusOverlay.svelte +144 -353
  63. package/dist/components/NodeStatusOverlay.svelte.d.ts +4 -1
  64. package/dist/components/PipelineStatus.svelte +5 -18
  65. package/dist/components/PortMappingRow.svelte +28 -44
  66. package/dist/components/PortPickerListbox.svelte +475 -0
  67. package/dist/components/PortPickerListbox.svelte.d.ts +73 -0
  68. package/dist/components/ReadOnlyDetails.svelte +52 -89
  69. package/dist/components/RunBar.svelte +222 -0
  70. package/dist/components/RunBar.svelte.d.ts +20 -0
  71. package/dist/components/RunsMenu.svelte +649 -0
  72. package/dist/components/RunsMenu.svelte.d.ts +14 -0
  73. package/dist/components/SchemaForm.svelte +1 -1
  74. package/dist/components/SettingsModal.svelte +28 -60
  75. package/dist/components/SettingsPanel.svelte +516 -242
  76. package/dist/components/StraightGuides.svelte +46 -0
  77. package/dist/components/StraightGuides.svelte.d.ts +7 -0
  78. package/dist/components/ThemeToggle.svelte +14 -4
  79. package/dist/components/UniversalNode.svelte +152 -51
  80. package/dist/components/WebMCPBridgeMenu.svelte +336 -0
  81. package/dist/components/WebMCPBridgeMenu.svelte.d.ts +3 -0
  82. package/dist/components/WorkflowEditor.svelte +821 -142
  83. package/dist/components/WorkflowEditor.svelte.d.ts +43 -1
  84. package/dist/components/WorkflowInterfaceEditor.svelte +106 -100
  85. package/dist/components/WorkflowInterfaceEditor.svelte.d.ts +12 -1
  86. package/dist/components/WorkflowInterfaceEntryCard.svelte +496 -494
  87. package/dist/components/WorkflowInterfaceEntryCard.svelte.d.ts +14 -1
  88. package/dist/components/WorkflowInterfaceEntryComposer.svelte +23 -67
  89. package/dist/components/WorkflowPlaygroundSettings.svelte +514 -0
  90. package/dist/components/WorkflowPlaygroundSettings.svelte.d.ts +20 -0
  91. package/dist/components/WorkflowSettingsPanel.svelte +311 -0
  92. package/dist/components/WorkflowSettingsPanel.svelte.d.ts +20 -0
  93. package/dist/components/ZoomTier.svelte +56 -0
  94. package/dist/components/ZoomTier.svelte.d.ts +4 -0
  95. package/dist/components/chat/AIChatPanel.svelte +464 -313
  96. package/dist/components/chat/ActivityList.svelte +130 -0
  97. package/dist/components/chat/ActivityList.svelte.d.ts +11 -0
  98. package/dist/components/chat/ActivityRow.svelte +179 -0
  99. package/dist/components/chat/ActivityRow.svelte.d.ts +16 -0
  100. package/dist/components/chat/CommandPreview.svelte +42 -64
  101. package/dist/components/console/CommandConsole.svelte +106 -41
  102. package/dist/components/console/CommandConsole.svelte.d.ts +2 -0
  103. package/dist/components/console/ConsoleAutocomplete.svelte +14 -13
  104. package/dist/components/console/ConsoleInput.svelte +60 -27
  105. package/dist/components/console/ConsoleOutput.svelte +86 -24
  106. package/dist/components/console/ConsoleStrip.svelte +80 -0
  107. package/dist/components/console/ConsoleStrip.svelte.d.ts +13 -0
  108. package/dist/components/form/FieldFactory.svelte +30 -4
  109. package/dist/components/form/FormArray.svelte +306 -339
  110. package/dist/components/form/FormArray.svelte.d.ts +10 -0
  111. package/dist/components/form/FormArrayRows.svelte +443 -0
  112. package/dist/components/form/FormArrayRows.svelte.d.ts +18 -0
  113. package/dist/components/form/FormAutocomplete.svelte +2 -2
  114. package/dist/components/form/FormCheckboxGroup.svelte +10 -85
  115. package/dist/components/form/FormCodeEditor.svelte +3 -3
  116. package/dist/components/form/FormFieldWrapper.svelte +98 -18
  117. package/dist/components/form/FormFieldWrapper.svelte.d.ts +10 -0
  118. package/dist/components/form/FormFieldset.svelte +44 -28
  119. package/dist/components/form/FormMarkdownEditor.svelte +6 -6
  120. package/dist/components/form/FormPorts.svelte +437 -141
  121. package/dist/components/form/FormSelect.svelte +1 -1
  122. package/dist/components/form/FormTemplateEditor.svelte +22 -26
  123. package/dist/components/form/FormToggle.svelte +15 -106
  124. package/dist/components/form/FormToggle.svelte.d.ts +3 -2
  125. package/dist/components/form/FormUISchemaRenderer.svelte +38 -3
  126. package/dist/components/form/humanizeKey.d.ts +7 -0
  127. package/dist/components/form/humanizeKey.js +21 -0
  128. package/dist/components/form/index.d.ts +2 -2
  129. package/dist/components/form/index.js +2 -2
  130. package/dist/components/form/types.d.ts +6 -0
  131. package/dist/components/icons/MenuOpenIcon.svelte +8 -1
  132. package/dist/components/interrupt/ChoicePrompt.svelte +51 -152
  133. package/dist/components/interrupt/ChoicePrompt.svelte.d.ts +0 -2
  134. package/dist/components/interrupt/ConfirmationPrompt.svelte +18 -201
  135. package/dist/components/interrupt/ConfirmationPrompt.svelte.d.ts +0 -4
  136. package/dist/components/interrupt/FormPrompt.svelte +22 -147
  137. package/dist/components/interrupt/FormPrompt.svelte.d.ts +0 -4
  138. package/dist/components/interrupt/InterruptBubble.svelte +198 -355
  139. package/dist/components/interrupt/InterruptBubble.svelte.d.ts +0 -2
  140. package/dist/components/interrupt/ReviewPrompt.svelte +0 -10
  141. package/dist/components/interrupt/TextInputPrompt.svelte +23 -120
  142. package/dist/components/interrupt/TextInputPrompt.svelte.d.ts +0 -2
  143. package/dist/components/layouts/MainLayout.svelte +110 -75
  144. package/dist/components/layouts/MainLayout.svelte.d.ts +17 -0
  145. package/dist/components/nodes/CaptionNode.svelte +7 -0
  146. package/dist/components/nodes/GatewayNode.svelte +66 -431
  147. package/dist/components/nodes/IdeaNode.svelte +6 -5
  148. package/dist/components/nodes/NodeCard.svelte +1051 -0
  149. package/dist/components/nodes/NodeCard.svelte.d.ts +30 -0
  150. package/dist/components/nodes/NodeConfigButton.svelte +28 -9
  151. package/dist/components/nodes/NodeProblemMark.svelte +113 -0
  152. package/dist/components/nodes/NodeProblemMark.svelte.d.ts +8 -0
  153. package/dist/components/nodes/NodeTip.svelte +104 -0
  154. package/dist/components/nodes/NodeTip.svelte.d.ts +15 -0
  155. package/dist/components/nodes/NotesNode.svelte +183 -150
  156. package/dist/components/nodes/SimpleNode.svelte +176 -44
  157. package/dist/components/nodes/SquareNode.svelte +127 -34
  158. package/dist/components/nodes/TerminalNode.svelte +232 -88
  159. package/dist/components/nodes/ToolNode.svelte +49 -381
  160. package/dist/components/nodes/WorkflowNode.svelte +40 -399
  161. package/dist/components/playground/ChatBubble.svelte +248 -62
  162. package/dist/components/playground/ChatInput.svelte +134 -297
  163. package/dist/components/playground/ChatInput.svelte.d.ts +17 -0
  164. package/dist/components/playground/ControlPanel.svelte +318 -188
  165. package/dist/components/playground/ControlPanel.svelte.d.ts +13 -0
  166. package/dist/components/playground/DockedPlayground.svelte +75 -0
  167. package/dist/components/playground/DockedPlayground.svelte.d.ts +24 -0
  168. package/dist/components/playground/ExecutionConsole.svelte +54 -36
  169. package/dist/components/playground/ExecutionConsole.svelte.d.ts +12 -0
  170. package/dist/components/playground/ExecutionLogs.svelte +4 -0
  171. package/dist/components/playground/HeaderMenu.svelte +170 -0
  172. package/dist/components/playground/HeaderMenu.svelte.d.ts +22 -0
  173. package/dist/components/playground/InputCollector.svelte +8 -32
  174. package/dist/components/playground/InputFields.svelte +246 -0
  175. package/dist/components/playground/InputFields.svelte.d.ts +16 -0
  176. package/dist/components/playground/InterfaceInputForm.svelte +285 -30
  177. package/dist/components/playground/InterfaceInputForm.svelte.d.ts +20 -0
  178. package/dist/components/playground/InterfaceJsonInput.svelte +92 -0
  179. package/dist/components/playground/InterfaceJsonInput.svelte.d.ts +10 -0
  180. package/dist/components/playground/LogRow.svelte +12 -12
  181. package/dist/components/playground/MessageMarkdown.svelte +11 -11
  182. package/dist/components/playground/MessageStream.svelte +154 -182
  183. package/dist/components/playground/Playground.svelte +17 -1087
  184. package/dist/components/playground/PlaygroundApp.svelte +12 -2
  185. package/dist/components/playground/PlaygroundApp.svelte.d.ts +2 -1
  186. package/dist/components/playground/PlaygroundHeader.svelte +309 -0
  187. package/dist/components/playground/PlaygroundHeader.svelte.d.ts +22 -0
  188. package/dist/components/playground/PlaygroundModal.svelte +7 -1
  189. package/dist/components/playground/PlaygroundStudio.svelte +31 -33
  190. package/dist/components/playground/PlaygroundSurface.svelte +648 -0
  191. package/dist/components/playground/PlaygroundSurface.svelte.d.ts +79 -0
  192. package/dist/components/playground/StepsSummary.svelte +312 -0
  193. package/dist/components/playground/StepsSummary.svelte.d.ts +11 -0
  194. package/dist/components/playground/messageDisplay.d.ts +9 -0
  195. package/dist/components/playground/messageDisplay.js +24 -2
  196. package/dist/components/playground/stepSummary.d.ts +71 -0
  197. package/dist/components/playground/stepSummary.js +152 -0
  198. package/dist/components/ports/PortTypeBadge.svelte +13 -1
  199. package/dist/components/primitives/Button.svelte +226 -0
  200. package/dist/components/primitives/Button.svelte.d.ts +31 -0
  201. package/dist/components/primitives/Card.svelte +110 -0
  202. package/dist/components/primitives/Card.svelte.d.ts +20 -0
  203. package/dist/components/primitives/Checkbox.svelte +126 -0
  204. package/dist/components/primitives/Checkbox.svelte.d.ts +15 -0
  205. package/dist/components/primitives/Chip.svelte +143 -0
  206. package/dist/components/primitives/Chip.svelte.d.ts +22 -0
  207. package/dist/components/primitives/Combobox.svelte +444 -0
  208. package/dist/components/primitives/Combobox.svelte.d.ts +22 -0
  209. package/dist/components/primitives/Composer.svelte +293 -0
  210. package/dist/components/primitives/Composer.svelte.d.ts +47 -0
  211. package/dist/components/primitives/EmptyState.svelte +113 -0
  212. package/dist/components/primitives/EmptyState.svelte.d.ts +18 -0
  213. package/dist/components/primitives/Field.svelte +178 -0
  214. package/dist/components/primitives/Field.svelte.d.ts +30 -0
  215. package/dist/components/primitives/IconButton.svelte +156 -0
  216. package/dist/components/primitives/IconButton.svelte.d.ts +27 -0
  217. package/dist/components/primitives/Menu.svelte +435 -0
  218. package/dist/components/primitives/Menu.svelte.d.ts +61 -0
  219. package/dist/components/primitives/Notice.svelte +161 -0
  220. package/dist/components/primitives/Notice.svelte.d.ts +22 -0
  221. package/dist/components/primitives/PanelHeader.svelte +134 -0
  222. package/dist/components/primitives/PanelHeader.svelte.d.ts +23 -0
  223. package/dist/components/primitives/Segmented.svelte +198 -0
  224. package/dist/components/primitives/Segmented.svelte.d.ts +32 -0
  225. package/dist/components/primitives/Select.svelte +130 -0
  226. package/dist/components/primitives/Select.svelte.d.ts +26 -0
  227. package/dist/components/primitives/StatusPill.svelte +218 -0
  228. package/dist/components/primitives/StatusPill.svelte.d.ts +24 -0
  229. package/dist/components/primitives/Switch.svelte +113 -0
  230. package/dist/components/primitives/Switch.svelte.d.ts +14 -0
  231. package/dist/components/primitives/Tabs.svelte +209 -0
  232. package/dist/components/primitives/Tabs.svelte.d.ts +32 -0
  233. package/dist/components/primitives/Toolbar.svelte +94 -0
  234. package/dist/components/primitives/Toolbar.svelte.d.ts +14 -0
  235. package/dist/components/primitives/ToolbarSeparator.svelte +40 -0
  236. package/dist/components/primitives/ToolbarSeparator.svelte.d.ts +7 -0
  237. package/dist/components/surfaces/SurfaceOverlay.svelte +10 -40
  238. package/dist/components/surfaces/TabbedSurface.svelte +49 -39
  239. package/dist/components/surfaces/TabbedSurface.svelte.d.ts +8 -0
  240. package/dist/components/toast/DismissibleToast.svelte +94 -32
  241. package/dist/components/toast/DismissibleToast.svelte.d.ts +17 -7
  242. package/dist/config/endpoints.d.ts +43 -1
  243. package/dist/config/endpoints.js +21 -3
  244. package/dist/core/index.d.ts +9 -6
  245. package/dist/core/index.js +1 -1
  246. package/dist/editor/connectCandidates.d.ts +56 -0
  247. package/dist/editor/connectCandidates.js +131 -0
  248. package/dist/editor/contextMenu.d.ts +31 -2
  249. package/dist/editor/contextMenu.js +96 -9
  250. package/dist/editor/index.d.ts +3 -1
  251. package/dist/editor/index.js +1 -0
  252. package/dist/editor/interfaceMenu.d.ts +35 -0
  253. package/dist/editor/interfaceMenu.js +47 -0
  254. package/dist/editor/portMenu.d.ts +23 -0
  255. package/dist/editor/portMenu.js +34 -0
  256. package/dist/editor/tidy.d.ts +30 -0
  257. package/dist/editor/tidy.js +66 -0
  258. package/dist/helpers/workflowEditorHelper.d.ts +15 -0
  259. package/dist/helpers/workflowEditorHelper.js +39 -3
  260. package/dist/layout/fromWorkflow.d.ts +42 -0
  261. package/dist/layout/fromWorkflow.js +135 -0
  262. package/dist/layout/geometry.d.ts +102 -0
  263. package/dist/layout/geometry.js +317 -0
  264. package/dist/layout/index.d.ts +21 -0
  265. package/dist/layout/index.js +14 -0
  266. package/dist/layout/inspect.d.ts +18 -0
  267. package/dist/layout/inspect.js +81 -0
  268. package/dist/layout/lanePath.d.ts +23 -0
  269. package/dist/layout/lanePath.js +47 -0
  270. package/dist/layout/measure.d.ts +141 -0
  271. package/dist/layout/measure.js +477 -0
  272. package/dist/layout/primitives.d.ts +124 -0
  273. package/dist/layout/primitives.js +461 -0
  274. package/dist/layout/sweep.d.ts +59 -0
  275. package/dist/layout/sweep.js +257 -0
  276. package/dist/layout/toWorkflow.d.ts +43 -0
  277. package/dist/layout/toWorkflow.js +131 -0
  278. package/dist/layout/types.d.ts +93 -0
  279. package/dist/layout/types.js +35 -0
  280. package/dist/messages/defaults.d.ts +694 -26
  281. package/dist/messages/defaults.js +626 -27
  282. package/dist/messages/types.d.ts +21 -1
  283. package/dist/openapi/v1/openapi.yaml +222 -5
  284. package/dist/playground/index.d.ts +31 -2
  285. package/dist/playground/index.js +31 -1
  286. package/dist/playground/mount.d.ts +34 -12
  287. package/dist/playground/mount.js +80 -35
  288. package/dist/playground/runAction.d.ts +29 -0
  289. package/dist/playground/runAction.js +38 -0
  290. package/dist/schemas/index.js +1 -1
  291. package/dist/schemas/v1/workflow.schema.json +140 -2
  292. package/dist/services/doctorService.d.ts +52 -0
  293. package/dist/services/doctorService.js +113 -0
  294. package/dist/services/globalSave.js +17 -24
  295. package/dist/services/nodeExecutionService.d.ts +12 -1
  296. package/dist/services/nodeExecutionService.js +58 -58
  297. package/dist/services/playgroundService.d.ts +23 -3
  298. package/dist/services/playgroundService.js +53 -5
  299. package/dist/services/runsService.d.ts +42 -0
  300. package/dist/services/runsService.js +87 -0
  301. package/dist/services/toastQueue.d.ts +33 -0
  302. package/dist/services/toastQueue.js +38 -0
  303. package/dist/services/toastService.d.ts +30 -9
  304. package/dist/services/toastService.js +81 -46
  305. package/dist/settings/index.d.ts +1 -0
  306. package/dist/skins/default.d.ts +1 -1
  307. package/dist/skins/drafter.d.ts +1 -1
  308. package/dist/skins/graphite.d.ts +26 -0
  309. package/dist/skins/graphite.js +473 -0
  310. package/dist/skins/index.d.ts +6 -5
  311. package/dist/skins/index.js +7 -5
  312. package/dist/skins/slate.d.ts +1 -1
  313. package/dist/skins/slate.js +4 -4
  314. package/dist/stores/attachedRunStore.svelte.d.ts +35 -0
  315. package/dist/stores/attachedRunStore.svelte.js +47 -0
  316. package/dist/stores/connectDragStore.svelte.d.ts +39 -0
  317. package/dist/stores/connectDragStore.svelte.js +42 -0
  318. package/dist/stores/doctorStore.svelte.d.ts +79 -0
  319. package/dist/stores/doctorStore.svelte.js +244 -0
  320. package/dist/stores/editedNodesStore.svelte.d.ts +42 -0
  321. package/dist/stores/editedNodesStore.svelte.js +84 -0
  322. package/dist/stores/editorModeStore.svelte.d.ts +34 -0
  323. package/dist/stores/editorModeStore.svelte.js +55 -0
  324. package/dist/stores/instanceContainer.svelte.d.ts +68 -0
  325. package/dist/stores/instanceContainer.svelte.js +49 -2
  326. package/dist/stores/loopbackLanesStore.svelte.d.ts +18 -0
  327. package/dist/stores/loopbackLanesStore.svelte.js +25 -0
  328. package/dist/stores/nodeHighlightStore.svelte.d.ts +34 -0
  329. package/dist/stores/nodeHighlightStore.svelte.js +56 -0
  330. package/dist/stores/playgroundStore.svelte.d.ts +74 -2
  331. package/dist/stores/playgroundStore.svelte.js +182 -6
  332. package/dist/stores/runController.svelte.d.ts +382 -0
  333. package/dist/stores/runController.svelte.js +1217 -0
  334. package/dist/stores/settingsStore.svelte.d.ts +80 -18
  335. package/dist/stores/settingsStore.svelte.js +180 -62
  336. package/dist/stores/workflowStore.svelte.d.ts +18 -1
  337. package/dist/stores/workflowStore.svelte.js +29 -1
  338. package/dist/styles/base.css +300 -28
  339. package/dist/styles/fonts/Inter-LICENSE.txt +93 -0
  340. package/dist/styles/fonts/inter-latin-wght-normal.woff2 +0 -0
  341. package/dist/styles/fonts/inter.css +19 -0
  342. package/dist/styles/toast.css +100 -20
  343. package/dist/styles/tokenAliases.d.ts +13 -0
  344. package/dist/styles/tokenAliases.js +206 -0
  345. package/dist/styles/tokens.css +586 -14
  346. package/dist/svelte-app.d.ts +38 -5
  347. package/dist/svelte-app.js +14 -3
  348. package/dist/themes/graphite.d.ts +2 -0
  349. package/dist/themes/graphite.js +15 -0
  350. package/dist/themes/index.d.ts +2 -1
  351. package/dist/themes/index.js +22 -3
  352. package/dist/themes/minimal.js +10 -0
  353. package/dist/themes/scopedSkinCss.d.ts +47 -0
  354. package/dist/themes/scopedSkinCss.js +220 -0
  355. package/dist/types/chat.d.ts +6 -0
  356. package/dist/types/doctor.d.ts +82 -0
  357. package/dist/types/doctor.js +11 -0
  358. package/dist/types/events.d.ts +35 -0
  359. package/dist/types/events.js +4 -1
  360. package/dist/types/index.d.ts +103 -6
  361. package/dist/types/index.js +15 -3
  362. package/dist/types/navbar.d.ts +36 -0
  363. package/dist/types/playground.d.ts +66 -0
  364. package/dist/types/settings.d.ts +120 -7
  365. package/dist/types/settings.js +35 -3
  366. package/dist/types/skin.d.ts +23 -10
  367. package/dist/types/theme.d.ts +40 -2
  368. package/dist/utils/appearance.d.ts +19 -0
  369. package/dist/utils/appearance.js +13 -0
  370. package/dist/utils/canvasFit.d.ts +41 -0
  371. package/dist/utils/canvasFit.js +44 -0
  372. package/dist/utils/chipTitles.d.ts +9 -0
  373. package/dist/utils/chipTitles.js +19 -0
  374. package/dist/utils/connections.js +8 -0
  375. package/dist/utils/consoleHighlight.d.ts +28 -0
  376. package/dist/utils/consoleHighlight.js +269 -0
  377. package/dist/utils/deprecation.d.ts +17 -0
  378. package/dist/utils/deprecation.js +29 -0
  379. package/dist/utils/doctorOperations.d.ts +40 -0
  380. package/dist/utils/doctorOperations.js +237 -0
  381. package/dist/utils/duration.d.ts +13 -0
  382. package/dist/utils/duration.js +40 -0
  383. package/dist/utils/inspectorContext.d.ts +19 -0
  384. package/dist/utils/inspectorContext.js +12 -0
  385. package/dist/utils/inspectorSections.d.ts +20 -0
  386. package/dist/utils/inspectorSections.js +44 -0
  387. package/dist/utils/inspectorSurface.d.ts +46 -0
  388. package/dist/utils/inspectorSurface.js +51 -0
  389. package/dist/utils/interfaceTags.d.ts +102 -0
  390. package/dist/utils/interfaceTags.js +211 -0
  391. package/dist/utils/itemRef.d.ts +86 -0
  392. package/dist/utils/itemRef.js +106 -0
  393. package/dist/utils/lastRun.d.ts +35 -0
  394. package/dist/utils/lastRun.js +73 -0
  395. package/dist/utils/messageNodeLink.d.ts +17 -0
  396. package/dist/utils/messageNodeLink.js +16 -0
  397. package/dist/utils/minimapVisibility.d.ts +28 -0
  398. package/dist/utils/minimapVisibility.js +34 -0
  399. package/dist/utils/nodeAriaLabel.d.ts +12 -0
  400. package/dist/utils/nodeAriaLabel.js +17 -0
  401. package/dist/utils/nodeFingerprint.d.ts +27 -0
  402. package/dist/utils/nodeFingerprint.js +66 -0
  403. package/dist/utils/nodeFormSchema.d.ts +10 -0
  404. package/dist/utils/nodeFormSchema.js +2 -2
  405. package/dist/utils/nodeGeometry.d.ts +168 -0
  406. package/dist/utils/nodeGeometry.js +204 -0
  407. package/dist/utils/nodeProblem.d.ts +19 -0
  408. package/dist/utils/nodeProblem.js +9 -0
  409. package/dist/utils/nodeStatus.d.ts +38 -3
  410. package/dist/utils/nodeStatus.js +67 -39
  411. package/dist/utils/nodeSwap.js +9 -1
  412. package/dist/utils/nodeWrapper.d.ts +1 -0
  413. package/dist/utils/playgroundChat.d.ts +121 -0
  414. package/dist/utils/playgroundChat.js +275 -0
  415. package/dist/utils/playgroundHistory.d.ts +48 -0
  416. package/dist/utils/playgroundHistory.js +38 -0
  417. package/dist/utils/playgroundInputRuns.d.ts +26 -0
  418. package/dist/utils/playgroundInputRuns.js +50 -0
  419. package/dist/utils/portExposure.d.ts +49 -0
  420. package/dist/utils/portExposure.js +122 -0
  421. package/dist/utils/portUtils.d.ts +16 -0
  422. package/dist/utils/portUtils.js +37 -0
  423. package/dist/utils/portal.d.ts +3 -14
  424. package/dist/utils/portal.js +22 -0
  425. package/dist/utils/reservedPorts.d.ts +59 -0
  426. package/dist/utils/reservedPorts.js +60 -0
  427. package/dist/utils/runEdges.d.ts +24 -0
  428. package/dist/utils/runEdges.js +35 -0
  429. package/dist/utils/runsList.d.ts +69 -0
  430. package/dist/utils/runsList.js +134 -0
  431. package/dist/utils/selectOptions.d.ts +62 -0
  432. package/dist/utils/selectOptions.js +137 -0
  433. package/dist/utils/sessionRuns.d.ts +62 -0
  434. package/dist/utils/sessionRuns.js +123 -0
  435. package/dist/utils/sheetWidths.d.ts +29 -0
  436. package/dist/utils/sheetWidths.js +41 -0
  437. package/dist/utils/sidebarWidths.d.ts +34 -0
  438. package/dist/utils/sidebarWidths.js +47 -0
  439. package/dist/utils/straightWires.d.ts +73 -0
  440. package/dist/utils/straightWires.js +99 -0
  441. package/dist/utils/themeScope.svelte.d.ts +10 -0
  442. package/dist/utils/themeScope.svelte.js +80 -0
  443. package/dist/utils/wiredHandles.d.ts +10 -0
  444. package/dist/utils/wiredHandles.js +14 -0
  445. package/dist/utils/workflowDraft.d.ts +9 -0
  446. package/dist/utils/workflowDraft.js +39 -0
  447. package/dist/utils/workflowInterface.d.ts +128 -27
  448. package/dist/utils/workflowInterface.js +244 -33
  449. package/dist/utils/zoomTier.d.ts +43 -0
  450. package/dist/utils/zoomTier.js +107 -0
  451. package/dist/utils/zoomTierRows.d.ts +41 -0
  452. package/dist/utils/zoomTierRows.js +103 -0
  453. package/dist/webmcp/WebMCPConfirm.svelte +68 -18
  454. package/dist/webmcp/bridge.d.ts +5 -0
  455. package/dist/webmcp/bridge.js +8 -0
  456. package/dist/webmcp/bridgeController.svelte.d.ts +84 -0
  457. package/dist/webmcp/bridgeController.svelte.js +224 -0
  458. package/dist/webmcp/descriptors.d.ts +1 -1
  459. package/dist/webmcp/descriptors.js +66 -5
  460. package/dist/webmcp/fakeWidget.d.ts +34 -0
  461. package/dist/webmcp/fakeWidget.js +75 -0
  462. package/dist/webmcp/gate.d.ts +6 -0
  463. package/dist/webmcp/gate.js +8 -0
  464. package/dist/webmcp/index.d.ts +2 -0
  465. package/dist/webmcp/index.js +1 -0
  466. package/dist/webmcp/runtime.js +6 -2
  467. package/dist/webmcp/types.d.ts +2 -0
  468. package/dist/webmcp/validate.js +5 -1
  469. package/package.json +14 -7
  470. package/dist/components/Button.stories.svelte +0 -65
  471. package/dist/components/Button.stories.svelte.d.ts +0 -19
  472. package/dist/components/CanvasBanner.stories.svelte +0 -30
  473. package/dist/components/CanvasBanner.stories.svelte.d.ts +0 -27
  474. package/dist/components/CanvasContextMenu.stories.svelte +0 -63
  475. package/dist/components/CanvasContextMenu.stories.svelte.d.ts +0 -19
  476. package/dist/components/ConfigPanel.stories.svelte +0 -47
  477. package/dist/components/ConfigPanel.stories.svelte.d.ts +0 -27
  478. package/dist/components/EditorStatusBar.stories.svelte +0 -44
  479. package/dist/components/EditorStatusBar.stories.svelte.d.ts +0 -27
  480. package/dist/components/FlowDropEdge.stories.svelte +0 -197
  481. package/dist/components/FlowDropEdge.stories.svelte.d.ts +0 -26
  482. package/dist/components/LoadingSpinner.stories.svelte +0 -30
  483. package/dist/components/LoadingSpinner.stories.svelte.d.ts +0 -27
  484. package/dist/components/Logo.stories.svelte +0 -22
  485. package/dist/components/Logo.stories.svelte.d.ts +0 -27
  486. package/dist/components/MarkdownDisplay.stories.svelte +0 -38
  487. package/dist/components/MarkdownDisplay.stories.svelte.d.ts +0 -27
  488. package/dist/components/Navbar.stories.svelte +0 -58
  489. package/dist/components/Navbar.stories.svelte.d.ts +0 -27
  490. package/dist/components/NodeStatusOverlay.stories.svelte +0 -85
  491. package/dist/components/NodeStatusOverlay.stories.svelte.d.ts +0 -27
  492. package/dist/components/SchemaForm.stories.svelte +0 -122
  493. package/dist/components/SchemaForm.stories.svelte.d.ts +0 -27
  494. package/dist/components/Select.svelte +0 -53
  495. package/dist/components/Select.svelte.d.ts +0 -15
  496. package/dist/components/StatusIcon.stories.svelte +0 -60
  497. package/dist/components/StatusIcon.stories.svelte.d.ts +0 -27
  498. package/dist/components/StatusLabel.stories.svelte +0 -17
  499. package/dist/components/StatusLabel.stories.svelte.d.ts +0 -27
  500. package/dist/components/ThemeToggle.stories.svelte +0 -25
  501. package/dist/components/ThemeToggle.stories.svelte.d.ts +0 -27
  502. package/dist/components/console/CommandConsole.stories.svelte +0 -111
  503. package/dist/components/console/CommandConsole.stories.svelte.d.ts +0 -27
  504. package/dist/components/form/FormCheckboxGroup.stories.svelte +0 -28
  505. package/dist/components/form/FormCheckboxGroup.stories.svelte.d.ts +0 -27
  506. package/dist/components/form/FormFieldWrapper.stories.svelte +0 -53
  507. package/dist/components/form/FormFieldWrapper.stories.svelte.d.ts +0 -27
  508. package/dist/components/form/FormNumberField.stories.svelte +0 -36
  509. package/dist/components/form/FormNumberField.stories.svelte.d.ts +0 -27
  510. package/dist/components/form/FormRangeField.stories.svelte +0 -31
  511. package/dist/components/form/FormRangeField.stories.svelte.d.ts +0 -27
  512. package/dist/components/form/FormSelect.stories.svelte +0 -50
  513. package/dist/components/form/FormSelect.stories.svelte.d.ts +0 -27
  514. package/dist/components/form/FormTextField.stories.svelte +0 -30
  515. package/dist/components/form/FormTextField.stories.svelte.d.ts +0 -27
  516. package/dist/components/form/FormTextarea.stories.svelte +0 -34
  517. package/dist/components/form/FormTextarea.stories.svelte.d.ts +0 -27
  518. package/dist/components/form/FormToggle.stories.svelte +0 -30
  519. package/dist/components/form/FormToggle.stories.svelte.d.ts +0 -27
  520. package/dist/components/icons/CommandLineIcon.svelte +0 -15
  521. package/dist/components/icons/CommandLineIcon.svelte.d.ts +0 -26
  522. package/dist/components/interrupt/ChoicePrompt.stories.svelte +0 -68
  523. package/dist/components/interrupt/ChoicePrompt.stories.svelte.d.ts +0 -27
  524. package/dist/components/interrupt/ConfirmationPrompt.stories.svelte +0 -71
  525. package/dist/components/interrupt/ConfirmationPrompt.stories.svelte.d.ts +0 -27
  526. package/dist/components/interrupt/ReviewPrompt.stories.svelte +0 -77
  527. package/dist/components/interrupt/ReviewPrompt.stories.svelte.d.ts +0 -27
  528. package/dist/components/interrupt/TextInputPrompt.stories.svelte +0 -51
  529. package/dist/components/interrupt/TextInputPrompt.stories.svelte.d.ts +0 -27
  530. package/dist/components/nodes/CaptionNode.stories.svelte +0 -65
  531. package/dist/components/nodes/CaptionNode.stories.svelte.d.ts +0 -18
  532. package/dist/components/nodes/GatewayNode.stories.svelte +0 -108
  533. package/dist/components/nodes/GatewayNode.stories.svelte.d.ts +0 -26
  534. package/dist/components/nodes/IdeaNode.stories.svelte +0 -52
  535. package/dist/components/nodes/IdeaNode.stories.svelte.d.ts +0 -26
  536. package/dist/components/nodes/NotesNode.stories.svelte +0 -76
  537. package/dist/components/nodes/NotesNode.stories.svelte.d.ts +0 -26
  538. package/dist/components/nodes/SimpleNode.stories.svelte +0 -223
  539. package/dist/components/nodes/SimpleNode.stories.svelte.d.ts +0 -26
  540. package/dist/components/nodes/SquareNode.stories.svelte +0 -127
  541. package/dist/components/nodes/SquareNode.stories.svelte.d.ts +0 -26
  542. package/dist/components/nodes/TerminalNode.stories.svelte +0 -25
  543. package/dist/components/nodes/TerminalNode.stories.svelte.d.ts +0 -26
  544. package/dist/components/nodes/ToolNode.stories.svelte +0 -189
  545. package/dist/components/nodes/ToolNode.stories.svelte.d.ts +0 -26
  546. package/dist/components/nodes/WorkflowNode.stories.svelte +0 -188
  547. package/dist/components/nodes/WorkflowNode.stories.svelte.d.ts +0 -26
  548. package/dist/components/playground/MessageBubble.stories.svelte +0 -151
  549. package/dist/components/playground/MessageBubble.stories.svelte.d.ts +0 -27
  550. package/dist/components/toast/WarningIcon.svelte +0 -28
  551. package/dist/components/toast/WarningIcon.svelte.d.ts +0 -26
  552. package/dist/mocks/app-environment.d.ts +0 -8
  553. package/dist/mocks/app-environment.js +0 -16
  554. package/dist/mocks/app-forms.d.ts +0 -6
  555. package/dist/mocks/app-forms.js +0 -29
  556. package/dist/mocks/app-navigation.d.ts +0 -5
  557. package/dist/mocks/app-navigation.js +0 -36
  558. package/dist/mocks/app-stores.d.ts +0 -14
  559. package/dist/mocks/app-stores.js +0 -26
  560. package/dist/stories/CanvasDecorator.svelte +0 -49
  561. package/dist/stories/CanvasDecorator.svelte.d.ts +0 -8
  562. package/dist/stories/EdgeDecorator.svelte +0 -125
  563. package/dist/stories/EdgeDecorator.svelte.d.ts +0 -17
  564. package/dist/stories/NodeDecorator.svelte +0 -75
  565. package/dist/stories/NodeDecorator.svelte.d.ts +0 -8
  566. package/dist/stories/WebMCPFakeAgent.svelte +0 -229
  567. package/dist/stories/WebMCPFakeAgent.svelte.d.ts +0 -10
  568. package/dist/stories/utils.d.ts +0 -93
  569. package/dist/stories/utils.js +0 -156
  570. package/dist/webmcp/WebMCP.stories.svelte +0 -101
  571. package/dist/webmcp/WebMCP.stories.svelte.d.ts +0 -18
@@ -0,0 +1,1217 @@
1
+ /**
2
+ * Run Controller
3
+ *
4
+ * The session and run executors of one FlowDrop instance: load, create,
5
+ * select, delete and reset sessions, take a turn, launch a run, signal a
6
+ * pipeline, stop, poll, refresh. They used to live inside `Playground.svelte`;
7
+ * moving them here lets any surface of the instance drive the same code path
8
+ * (the Playground, the editor's Command Console, and later a canvas Test mode)
9
+ * instead of each growing a second, subtly different copy.
10
+ *
11
+ * Constructor injection only: the controller is handed the instance's
12
+ * `PlaygroundStore`, `PlaygroundService`, `ApiContext` and `WorkflowStore`.
13
+ * It never reads Svelte context (`getContext` throws outside component
14
+ * initialisation); whoever configures it supplies a messages getter instead.
15
+ *
16
+ * @module stores/runController
17
+ */
18
+ import { SvelteSet } from 'svelte/reactivity';
19
+ import { nodeExecutionService } from '../services/nodeExecutionService.js';
20
+ import { readRunStatus } from '../services/runsService.js';
21
+ import { pipelineSignalService } from '../services/pipelineSignalService.js';
22
+ import { workflowLaunchService } from '../services/workflowLaunchService.js';
23
+ import { describeLaunchResult } from '../playground/commands/index.js';
24
+ import { resolveRunAction } from '../playground/runAction.js';
25
+ import { defaultMessages } from '../messages/defaults.js';
26
+ import { logger } from '../utils/logger.js';
27
+ import { playgroundSessionsOf, versionDividersFromRuns, isRunStale } from '../utils/sessionRuns.js';
28
+ /**
29
+ * API base URLs whose server sent a workflow without `playground` (before
30
+ * FlowDrop 2.7.0). Such a server sends none for any workflow, so once one
31
+ * load has said so, a caller that passes the interface needs no further
32
+ * load. Keyed by base URL, not by client: mounting with `endpointConfig`
33
+ * rebuilds the client every time. Lasts for the page; an upgraded server
34
+ * is seen on the next page load.
35
+ */
36
+ const serversWithoutPlaygroundSettings = new Set();
37
+ /**
38
+ * API base URLs whose server has no session runs endpoint (it answered 404,
39
+ * or the instance has no `sessions` group). Asked once per page, like
40
+ * {@link serversWithoutPlaygroundSettings}: such a server shows no version
41
+ * dividers and is not asked again.
42
+ */
43
+ const serversWithoutSessionRuns = new Set();
44
+ /** Statuses a run does not leave. */
45
+ export const TERMINAL_RUN_STATUSES = ['failed', 'done', 'stopped'];
46
+ function sessionRunStatus(status, stopped) {
47
+ switch (status) {
48
+ case 'running':
49
+ return 'running';
50
+ case 'awaiting_input':
51
+ return 'waiting';
52
+ case 'failed':
53
+ return 'failed';
54
+ case 'completed':
55
+ return 'done';
56
+ default:
57
+ // idle: the poller's resting state. A stop lands here; so does a run that
58
+ // finished while nobody was looking.
59
+ return stopped ? 'stopped' : 'done';
60
+ }
61
+ }
62
+ /** A host's run status vocabulary ({@link import('../webmcp/types.js').RunStatus}) in the bar's. */
63
+ function hostRunStatus(status) {
64
+ switch (status) {
65
+ case 'paused':
66
+ case 'interrupted':
67
+ return 'waiting';
68
+ case 'completed':
69
+ return 'done';
70
+ case 'failed':
71
+ return 'failed';
72
+ case 'cancelled':
73
+ return 'stopped';
74
+ default:
75
+ return 'running';
76
+ }
77
+ }
78
+ /**
79
+ * Per-instance run controller, `fd.runs`.
80
+ *
81
+ * This is the controller Test mode builds on: every way of starting, stopping
82
+ * and following a run in an instance goes through it.
83
+ */
84
+ export class RunController {
85
+ #playground;
86
+ #service;
87
+ #api;
88
+ #workflow;
89
+ #options = $state.raw({});
90
+ // Monotonic token so a slow session load can't overwrite a newer one when
91
+ // the user switches sessions faster than the network responds (last-load
92
+ // wins).
93
+ #loadToken = 0;
94
+ // Same idea as #loadToken, for node status loads.
95
+ #statusToken = 0;
96
+ // requestNodeStatuses(): one load in flight, and whether another was asked for meanwhile.
97
+ #statusLoading = false;
98
+ #statusAgain = false;
99
+ #pendingSignal = $state(null);
100
+ // The run the instance shows (see ActiveRun). Replaced, never mutated.
101
+ #tracked = $state.raw(null);
102
+ #endedAt = $state(null);
103
+ /**
104
+ * Runs the server's runs list calls failed. A session whose pipeline failed
105
+ * still reads `completed` (the turn finished; its run did not), so the
106
+ * session status alone would show such a run as done.
107
+ */
108
+ #failedRunIds = new SvelteSet();
109
+ #unsubscribeSessionStatus = null;
110
+ #hostStatusHook;
111
+ #hostPoll = null;
112
+ // Bumped by stopHostPolling()/dispose(): a host status read already in
113
+ // flight compares it after its await and drops out instead of rescheduling.
114
+ #hostPollEpoch = 0;
115
+ #openedId = $state(null);
116
+ /**
117
+ * Milliseconds between status reads of a host run (`onRunStatus`). A public
118
+ * field, like a timeout in a client: tests and slow backends set it.
119
+ */
120
+ hostPollInterval = 2000;
121
+ #isRefreshing = $state(false);
122
+ constructor(deps) {
123
+ this.#playground = deps.playground;
124
+ this.#service = deps.service;
125
+ this.#api = deps.api;
126
+ this.#workflow = deps.workflow;
127
+ // The moment a run ends is the one thing the session status cannot say on
128
+ // its own; note it as the status moves. Synchronous, so two changes in one
129
+ // flush are both seen and the time is the transition's, not the flush's.
130
+ this.#unsubscribeSessionStatus = this.#playground.onSessionStatusChange((status) => {
131
+ this.clearPendingSignal();
132
+ const tracked = this.#tracked;
133
+ if (tracked?.origin !== 'session')
134
+ return;
135
+ const next = sessionRunStatus(status, tracked.stopped);
136
+ this.#endedAt = TERMINAL_RUN_STATUSES.includes(next) ? Date.now() : null;
137
+ if (next === 'done' && tracked.sessionId)
138
+ void this.#noteRunFailure(tracked.sessionId);
139
+ });
140
+ }
141
+ // -----------------------------------------------------------------------
142
+ // Configuration
143
+ // -----------------------------------------------------------------------
144
+ /**
145
+ * Replace the options. Called at init and again whenever the caller's
146
+ * props change; it replaces, it does not merge, so a key left out falls
147
+ * back to its default.
148
+ */
149
+ configure(options) {
150
+ this.#options = options;
151
+ }
152
+ /**
153
+ * A signal accepted but not yet observed as effective.
154
+ *
155
+ * Backends refuse a second signal on the same pipeline, so we hold this to
156
+ * disable rather than fire a request guaranteed to be rejected. Cleared when
157
+ * the session status changes — see {@link clearPendingSignal}.
158
+ */
159
+ get pendingSignal() {
160
+ return this.#pendingSignal;
161
+ }
162
+ /** Whether a status refresh is in flight. */
163
+ get isRefreshing() {
164
+ return this.#isRefreshing;
165
+ }
166
+ /** The instance's playground store, for surfaces that read what a run produced. */
167
+ get playground() {
168
+ return this.#playground;
169
+ }
170
+ /** The instance's workflow store: the editor's workflow and its dirty state. */
171
+ get editor() {
172
+ return this.#workflow;
173
+ }
174
+ /** Whether the instance has a backend to talk to. */
175
+ get isConfigured() {
176
+ return this.#api.isConfigured();
177
+ }
178
+ /** Whether the backend can launch a run without a chat message. */
179
+ get canLaunch() {
180
+ return workflowLaunchService.isSupported(this.#api.config);
181
+ }
182
+ /** A launch result as feedback text, in the configured messages. */
183
+ describeLaunch(result) {
184
+ return describeLaunchResult(result, this.#messages.playground.commands);
185
+ }
186
+ /** The configured messages, falling back to the English defaults. */
187
+ get #messages() {
188
+ return (this.#options.messages ?? (() => defaultMessages))();
189
+ }
190
+ get #messagePageSize() {
191
+ return this.#options.messagePageSize ?? 50;
192
+ }
193
+ /** Whether a surface told us which workflow to drive. */
194
+ get #hasConfiguredWorkflow() {
195
+ return this.#options.workflowId !== undefined;
196
+ }
197
+ /**
198
+ * The workflow id in effect: the configured one, else the editor's current
199
+ * workflow (the Console has no Playground mounted), else `null` — an
200
+ * unsaved new workflow.
201
+ */
202
+ get workflowId() {
203
+ return this.#options.workflowId ?? this.#workflow.current?.id ?? null;
204
+ }
205
+ #requireWorkflowId() {
206
+ const id = this.workflowId;
207
+ if (!id)
208
+ throw new Error(this.#messages.playground.saveFirst);
209
+ return id;
210
+ }
211
+ // -----------------------------------------------------------------------
212
+ // Editor fallback
213
+ // -----------------------------------------------------------------------
214
+ /**
215
+ * Make the playground store reflect the editor's workflow, for a surface
216
+ * with no Playground mounted. A no-op when a surface configured a workflow
217
+ * id (the Playground sets its own workflow) or the editor has none.
218
+ *
219
+ * The same workflow is re-adopted when the editor holds a newer copy, so a
220
+ * binding edited since the last turn is the one the next turn uses. When the
221
+ * store holds a different workflow, its sessions belong to that one and are
222
+ * dropped, so a turn from the Console never lands in another workflow's
223
+ * session.
224
+ */
225
+ adoptEditorWorkflow() {
226
+ if (this.#hasConfiguredWorkflow)
227
+ return;
228
+ const editorWorkflow = this.#workflow.current;
229
+ if (!editorWorkflow)
230
+ return;
231
+ const held = this.#playground.currentWorkflow;
232
+ if (held === editorWorkflow)
233
+ return;
234
+ if (held && held.id !== editorWorkflow.id) {
235
+ this.#service.stopPolling();
236
+ this.#playground.setSessions([]);
237
+ this.#playground.setCurrentSession(null);
238
+ this.#playground.clearMessages();
239
+ }
240
+ this.#playground.setWorkflow(editorWorkflow);
241
+ }
242
+ // -----------------------------------------------------------------------
243
+ // Interface
244
+ // -----------------------------------------------------------------------
245
+ /**
246
+ * Make sure the playground knows the workflow's interface and chat binding.
247
+ *
248
+ * The mode (chat box, form, Run) is read from the workflow's Playground
249
+ * settings, else from its interface's deprecated turn ports. A workflow
250
+ * passed in with both an `interface` and a `playground` key is used as is;
251
+ * when either is missing, the workflow is loaded through the workflows API
252
+ * (`workflows.get`) and only the missing keys are taken from there: a key
253
+ * the caller passed is its live copy (the editor's, unsaved edits and all)
254
+ * and never gives way to the saved one. Any failure
255
+ * leaves the playground in `legacy` mode, which is the behaviour it had
256
+ * before turn ports.
257
+ */
258
+ async ensureWorkflowInterface() {
259
+ if (!this.#api.config)
260
+ return;
261
+ const workflow = this.#options.workflow;
262
+ const workflowId = this.#requireWorkflowId();
263
+ const server = this.#api.config.baseUrl;
264
+ if (workflow?.interface !== undefined &&
265
+ (workflow.playground !== undefined || serversWithoutPlaygroundSettings.has(server))) {
266
+ return;
267
+ }
268
+ try {
269
+ const loaded = await this.#api.client.loadWorkflow(workflowId);
270
+ if (loaded.playground === undefined)
271
+ serversWithoutPlaygroundSettings.add(server);
272
+ if (!workflow) {
273
+ if (loaded.interface !== undefined || loaded.playground !== undefined) {
274
+ this.#playground.setWorkflow(loaded);
275
+ }
276
+ return;
277
+ }
278
+ const missingInterface = workflow.interface === undefined && loaded.interface !== undefined;
279
+ const missingPlayground = workflow.playground === undefined && loaded.playground !== undefined;
280
+ if (!missingInterface && !missingPlayground)
281
+ return;
282
+ this.#playground.setWorkflow({
283
+ ...workflow,
284
+ ...(missingInterface && { interface: loaded.interface }),
285
+ ...(missingPlayground && { playground: loaded.playground })
286
+ });
287
+ }
288
+ catch (err) {
289
+ logger.debug('[Playground] Workflow interface unavailable, keeping legacy input:', err);
290
+ }
291
+ }
292
+ // -----------------------------------------------------------------------
293
+ // Sessions
294
+ // -----------------------------------------------------------------------
295
+ async loadSessions() {
296
+ this.#playground.setLoading(true);
297
+ this.#playground.setError(null);
298
+ try {
299
+ const sessionList = await this.#service.listSessions(this.#api.config, this.#requireWorkflowId(), undefined, this.#api.authProvider);
300
+ this.#playground.setSessions(this.#options.playgroundSessionsOnly ? playgroundSessionsOf(sessionList) : sessionList);
301
+ }
302
+ catch (err) {
303
+ const errorMessage = err instanceof Error ? err.message : 'Failed to load sessions';
304
+ this.#playground.setError(errorMessage);
305
+ logger.error('Failed to load sessions:', err);
306
+ }
307
+ finally {
308
+ this.#playground.setLoading(false);
309
+ }
310
+ }
311
+ async loadSession(sessionId) {
312
+ this.#playground.setLoading(true);
313
+ this.#playground.setError(null);
314
+ const token = ++this.#loadToken;
315
+ try {
316
+ const session = await this.#service.getSession(this.#api.config, sessionId, this.#api.authProvider);
317
+ if (token !== this.#loadToken)
318
+ return; // a newer session load superseded us
319
+ this.#playground.setCurrentSession(session);
320
+ // Load only the most recent page; older messages load on demand when the
321
+ // user scrolls up (loadOlderMessages). Clear right before applying the
322
+ // fresh page — not before the await — so switching sessions doesn't blank
323
+ // the view for the duration of the fetch.
324
+ const response = await this.#service.getMessages(this.#api.config, sessionId, {
325
+ latest: true,
326
+ limit: this.#messagePageSize
327
+ }, this.#api.authProvider);
328
+ if (token !== this.#loadToken)
329
+ return;
330
+ this.#playground.clearMessages();
331
+ this.#playground.applyServerResponse(response, sessionId);
332
+ this.#playground.setHasOlder(this.deriveHasOlder(response));
333
+ if (session.status !== 'idle') {
334
+ // Seed polling from the newest loaded message so it tails live updates
335
+ // instead of crawling forward from the start of the conversation.
336
+ this.startPolling(sessionId, true);
337
+ }
338
+ // The version dividers of a conversation loaded from the server (the
339
+ // editor's Playground shows them). Not awaited: the feed is usable now
340
+ // and the dividers appear when known.
341
+ if (this.#options.saveWorkflow !== undefined) {
342
+ void this.loadSessionRuns(sessionId, { rebuildDividers: true });
343
+ }
344
+ }
345
+ catch (err) {
346
+ if (token !== this.#loadToken)
347
+ return; // don't surface a superseded load's error
348
+ const errorMessage = err instanceof Error ? err.message : 'Failed to load session';
349
+ this.#playground.setError(errorMessage);
350
+ logger.error('Failed to load session:', err);
351
+ }
352
+ finally {
353
+ if (token === this.#loadToken)
354
+ this.#playground.setLoading(false);
355
+ }
356
+ }
357
+ /**
358
+ * Load the page of messages immediately older than the oldest one currently
359
+ * shown. Triggered by scroll-up in MessageStream, which serializes calls and
360
+ * owns the in-flight/anchoring state. Bypasses applyServerResponse so a
361
+ * historical fetch never disturbs the live polling cursor or pipeline view.
362
+ */
363
+ async loadOlderMessages() {
364
+ const sessionId = this.#playground.currentSession?.id;
365
+ const before = this.#playground.oldestSequenceNumber;
366
+ if (!sessionId || before === null)
367
+ return;
368
+ try {
369
+ const response = await this.#service.getMessages(this.#api.config, sessionId, {
370
+ before,
371
+ limit: this.#messagePageSize
372
+ }, this.#api.authProvider);
373
+ // The session may have changed while the fetch was in flight — don't
374
+ // splice an old session's page into the new session's store.
375
+ if (this.#playground.currentSession?.id !== sessionId)
376
+ return;
377
+ if (response.data && response.data.length > 0) {
378
+ this.#playground.addMessages(response.data);
379
+ }
380
+ this.#playground.setHasOlder(this.deriveHasOlder(response));
381
+ }
382
+ catch (err) {
383
+ logger.error('[Playground] Failed to load older messages:', err);
384
+ }
385
+ }
386
+ /**
387
+ * Whether older messages remain after a backward-pagination response. Prefer
388
+ * the server's explicit `hasOlder` flag; fall back to inferring from page
389
+ * fullness for backends that haven't adopted the field yet.
390
+ */
391
+ deriveHasOlder(response) {
392
+ if (typeof response.hasOlder === 'boolean')
393
+ return response.hasOlder;
394
+ return (response.data?.length ?? 0) >= this.#messagePageSize;
395
+ }
396
+ async createSession() {
397
+ this.#playground.setLoading(true);
398
+ this.#playground.setError(null);
399
+ try {
400
+ // A list that is not the whole story (the editor lists only the
401
+ // Playground's sessions; the Console never loaded one) cannot number
402
+ // the next session without repeating a name, so the server names it.
403
+ // The standalone Playground lists every session and keeps counting.
404
+ const sessionName = this.#hasConfiguredWorkflow && !this.#options.playgroundSessionsOnly
405
+ ? `Session ${this.#playground.sessions.length + 1}`
406
+ : undefined;
407
+ const session = await this.#service.createSession(this.#api.config, this.#requireWorkflowId(), sessionName, undefined, this.#api.authProvider);
408
+ // Stop polling the previous (possibly running) session before switching,
409
+ // mirroring selectSession. Otherwise its next poll keeps the old
410
+ // 'running' status alive and the new session's chat input stays disabled.
411
+ this.#service.stopPolling();
412
+ if (this.#options.onSessionNavigate) {
413
+ this.#options.onSessionNavigate(session.id);
414
+ return;
415
+ }
416
+ this.#playground.addSession(session);
417
+ this.#playground.setCurrentSession(session);
418
+ this.#playground.clearMessages();
419
+ }
420
+ catch (err) {
421
+ const errorMessage = err instanceof Error ? err.message : 'Failed to create session';
422
+ this.#playground.setError(errorMessage);
423
+ logger.error('Failed to create session:', err);
424
+ }
425
+ finally {
426
+ this.#playground.setLoading(false);
427
+ }
428
+ }
429
+ // -----------------------------------------------------------------------
430
+ // Save and versions
431
+ // -----------------------------------------------------------------------
432
+ /**
433
+ * Whether a send must save the workflow first: the surface can save and the
434
+ * editor's workflow has unsaved edits (its Playground settings count, they
435
+ * are part of the workflow).
436
+ */
437
+ get needsSave() {
438
+ return (this.#options.saveWorkflow !== undefined &&
439
+ this.#workflow.current !== null &&
440
+ this.#workflow.isDirty);
441
+ }
442
+ /**
443
+ * Save the workflow if it has unsaved edits, so the run that follows is on
444
+ * what the person sees. Resolves `true` when there is nothing to save or the
445
+ * save was written. A failed or cancelled save resolves `false` and shows why
446
+ * in the Playground: the caller sends nothing.
447
+ */
448
+ async saveFirst() {
449
+ if (!this.needsSave)
450
+ return true;
451
+ const messages = this.#messages.playground;
452
+ try {
453
+ const saved = await this.#options.saveWorkflow?.();
454
+ if (saved === false) {
455
+ this.#playground.setError(messages.saveNotDone);
456
+ return false;
457
+ }
458
+ return true;
459
+ }
460
+ catch (err) {
461
+ const reason = err instanceof Error ? err.message : '';
462
+ this.#playground.setError(messages.saveFailed({ message: reason }));
463
+ return false;
464
+ }
465
+ }
466
+ /**
467
+ * Load the current session's runs from the runs endpoint into
468
+ * `playground.sessionRuns`, optionally rebuilding the conversation's version
469
+ * dividers from them. Resolves `null` (and changes nothing) on a server
470
+ * without the endpoint, which is asked only once per page, and when the
471
+ * request fails: version information is an extra, never an error.
472
+ */
473
+ async loadSessionRuns(sessionId, options = {}) {
474
+ const id = sessionId ?? this.#playground.currentSession?.id;
475
+ const server = this.#api.config?.baseUrl;
476
+ if (!id ||
477
+ !this.#api.config ||
478
+ (server !== undefined && serversWithoutSessionRuns.has(server))) {
479
+ return null;
480
+ }
481
+ try {
482
+ const result = await this.#service.getSessionRuns(this.#api.config, id, undefined, this.#api.authProvider);
483
+ if (result === null) {
484
+ if (server !== undefined)
485
+ serversWithoutSessionRuns.add(server);
486
+ this.#playground.setSessionRuns(id, null);
487
+ this.#playground.setVersionDividers(id, []);
488
+ return null;
489
+ }
490
+ // A newer session may have been loaded meanwhile: its runs are not these.
491
+ if (this.#playground.currentSession?.id !== id)
492
+ return result;
493
+ this.#playground.setSessionRuns(id, result);
494
+ if (options.rebuildDividers) {
495
+ this.#playground.setVersionDividers(id, versionDividersFromRuns(result));
496
+ }
497
+ return result;
498
+ }
499
+ catch (err) {
500
+ logger.debug('[Playground] Session runs unavailable:', err);
501
+ return null;
502
+ }
503
+ }
504
+ /**
505
+ * The workflow was just saved. When a conversation is open, put a "Saved,
506
+ * new version" divider below its last message, so the feed reads in the
507
+ * order things happened. No divider without a conversation, on a server
508
+ * without the runs endpoint, or when the save did not change the version
509
+ * the last run ran on (a node dragged to another place, say).
510
+ */
511
+ async noteWorkflowSaved() {
512
+ const playground = this.#playground;
513
+ const session = playground.currentSession;
514
+ const last = playground.messages.at(-1);
515
+ if (!session || !last)
516
+ return;
517
+ // A conversation retained from another workflow is not this save's.
518
+ const editorId = this.#workflow.current?.id;
519
+ if (editorId !== undefined && playground.currentWorkflow?.id !== editorId)
520
+ return;
521
+ const sessionId = session.id;
522
+ // The divider goes where the conversation ends now, not where it ends when
523
+ // the runs answer below arrives (`last` is read before the first await).
524
+ const result = await this.loadSessionRuns(sessionId);
525
+ if (result === null)
526
+ return;
527
+ const lastVersion = result.runs.findLast((run) => run.workflowVersion != null)?.workflowVersion;
528
+ if (lastVersion != null &&
529
+ result.workflowVersion != null &&
530
+ !isRunStale(lastVersion, result.workflowVersion)) {
531
+ return;
532
+ }
533
+ playground.addVersionDivider(sessionId, {
534
+ id: `save:${last.id}`,
535
+ anchor: { kind: 'after-message', messageId: last.id }
536
+ });
537
+ }
538
+ async selectSession(sessionId) {
539
+ this.#playground.pinExecution(null);
540
+ const currentSessionId = this.#playground.currentSession?.id;
541
+ if (currentSessionId === sessionId)
542
+ return;
543
+ this.#service.stopPolling();
544
+ this.#playground.updateSessionStatus('idle');
545
+ await this.loadSession(sessionId);
546
+ }
547
+ async deleteSession(sessionId) {
548
+ try {
549
+ await this.#service.deleteSession(this.#api.config, sessionId, this.#api.authProvider);
550
+ this.#playground.removeSession(sessionId);
551
+ if (this.#playground.currentSession?.id === sessionId) {
552
+ this.#service.stopPolling();
553
+ }
554
+ }
555
+ catch (err) {
556
+ const errorMessage = err instanceof Error ? err.message : 'Failed to delete session';
557
+ this.#playground.setError(errorMessage);
558
+ logger.error('Failed to delete session:', err);
559
+ }
560
+ }
561
+ /**
562
+ * Reset a stuck session to idle.
563
+ *
564
+ * Mirrors stopExecution: tear down polling and force the local status
565
+ * back to idle even on failure, since the point of reset is to escape a state
566
+ * the client and server disagree about.
567
+ */
568
+ async resetSession() {
569
+ const sessionId = this.#playground.currentSession?.id;
570
+ if (!sessionId)
571
+ return;
572
+ try {
573
+ await this.#service.resetSession(this.#api.config, sessionId, this.#api.authProvider);
574
+ this.#service.stopPolling();
575
+ this.#playground.updateSessionStatus('idle');
576
+ this.#playground.setError(null);
577
+ }
578
+ catch (err) {
579
+ this.#service.stopPolling();
580
+ this.#playground.updateSessionStatus('idle');
581
+ logger.error('Failed to reset session:', err);
582
+ throw err;
583
+ }
584
+ }
585
+ // -----------------------------------------------------------------------
586
+ // Runs and turns
587
+ // -----------------------------------------------------------------------
588
+ /**
589
+ * Launch a run with named inputs and no chat message.
590
+ *
591
+ * Creates a session first when there is none, so the run has a conversation
592
+ * to report into — the launch endpoint accepts a session id precisely so its
593
+ * messages land somewhere the user is looking.
594
+ */
595
+ async launchWorkflow(inputs) {
596
+ this.adoptEditorWorkflow();
597
+ if (!this.#playground.currentSession) {
598
+ await this.createSession();
599
+ }
600
+ const sessionId = this.#playground.currentSession?.id;
601
+ const result = await workflowLaunchService.launch(this.#api.config, this.#requireWorkflowId(), { inputs, sessionId }, this.#api.authProvider);
602
+ // Switched to another session while launching: leave it alone.
603
+ if (this.#playground.currentSession?.id !== sessionId)
604
+ return result;
605
+ if (result.status === 'launched' && sessionId) {
606
+ // Mirror a turn: reflect the run optimistically and tail it.
607
+ this.#playground.updateSessionStatus('running');
608
+ this.#playground.pinExecution(null);
609
+ this.#playground.setError(null);
610
+ if (!this.#service.isPolling()) {
611
+ this.startPolling(sessionId, true);
612
+ }
613
+ this.#beginSessionRun(sessionId);
614
+ }
615
+ return result;
616
+ }
617
+ /**
618
+ * Start a run from a button or auto-run, without posting a chat message.
619
+ *
620
+ * Falls back to sending `predefinedMessage` only where the backend has no
621
+ * launch verb — there a message is genuinely the only way to start a run, so
622
+ * the fabricated turn is the lesser evil. Everywhere else this is what stops
623
+ * "Run workflow" appearing in the conversation as though a user typed it.
624
+ *
625
+ * @returns Feedback for a refused launch, for the caller to show; `null`
626
+ * when nothing needs reporting.
627
+ */
628
+ async startRun() {
629
+ this.adoptEditorWorkflow();
630
+ const inputMode = this.#playground.inputMode;
631
+ // A workflow that declares turn ports but no message port runs as a turn
632
+ // on its inputs: no fabricated message, which its server would refuse.
633
+ if (inputMode === 'form' || inputMode === 'run') {
634
+ await this.takeTurn({}, { launch: true });
635
+ return null;
636
+ }
637
+ const action = resolveRunAction({
638
+ canLaunch: workflowLaunchService.isSupported(this.#api.config),
639
+ predefinedMessage: this.#options.predefinedMessage,
640
+ defaultMessage: this.#messages.playground.chat.predefinedRun
641
+ });
642
+ if (action.kind === 'message') {
643
+ logger.debug('[Playground] Starting run by message:', action.content);
644
+ await this.sendMessage(action.content);
645
+ return null;
646
+ }
647
+ const result = await this.launchWorkflow({});
648
+ // Only failures need reporting: a successful launch is evident from the run
649
+ // itself appearing in the console.
650
+ if (result.status !== 'launched') {
651
+ // A refused launch never sends the `enableRun` message that would
652
+ // otherwise bring Run back.
653
+ this.#playground.releaseRunLock();
654
+ return this.describeLaunch(result);
655
+ }
656
+ return null;
657
+ }
658
+ /**
659
+ * Send a chat message as a turn. Slash commands are not handled here; the
660
+ * Playground intercepts them before calling this.
661
+ */
662
+ sendMessage(content) {
663
+ return this.takeTurn({ content });
664
+ }
665
+ /**
666
+ * Send an operator signal to a specific pipeline.
667
+ *
668
+ * Records the signal as pending on acceptance so a second one is refused
669
+ * client-side rather than by the backend.
670
+ */
671
+ async sendSignal(signal, pipelineId, reason) {
672
+ const result = await pipelineSignalService[signal](this.#api.config, pipelineId, { reason }, this.#api.authProvider);
673
+ if (result.status === 'accepted') {
674
+ this.#pendingSignal = { pipelineId, signal };
675
+ }
676
+ return result;
677
+ }
678
+ /**
679
+ * Clear a pending signal once the session status moves.
680
+ *
681
+ * The status transition is the observable consequence of the signal landing
682
+ * — or of the run ending by itself, which equally means the signal is moot.
683
+ */
684
+ clearPendingSignal() {
685
+ if (this.#pendingSignal)
686
+ this.#pendingSignal = null;
687
+ }
688
+ /**
689
+ * Take one turn: post the request to the session's turn door and tail the
690
+ * session. The interface form's values ride along as `inputs` (none in
691
+ * legacy mode). A refusal (a 400 naming the fix, a 409, …) is shown with the
692
+ * server's own message and leaves the session idle.
693
+ *
694
+ * @param options.launch The turn is a Run click: a refusal is shown under
695
+ * the Run button (`launchError`) rather than in the banner.
696
+ * @returns Whether the turn was accepted
697
+ */
698
+ async takeTurn(request, options = {}) {
699
+ const playground = this.#playground;
700
+ this.adoptEditorWorkflow();
701
+ // Not `canRun`: a Run click has already taken the run lock by now.
702
+ if (playground.isExecuting || playground.turnPending) {
703
+ playground.releaseRunLock();
704
+ return false;
705
+ }
706
+ playground.setTurnPending(true);
707
+ const report = (message) => options.launch ? playground.setLaunchError(message) : playground.setError(message);
708
+ playground.setLaunchError(null);
709
+ try {
710
+ // In legacy mode there are no interface form entries, so `inputs` is
711
+ // `{}` — exactly what the legacy door was always sent.
712
+ const turnInputs = playground.turnInputs;
713
+ if (!turnInputs.ok) {
714
+ const { inputForm } = this.#messages.playground;
715
+ const names = (entries) => entries.map((entry) => entry.name ?? entry.id).join(', ');
716
+ report([
717
+ turnInputs.missing.length > 0
718
+ ? inputForm.missingRequired({ names: names(turnInputs.missing) })
719
+ : null,
720
+ turnInputs.invalid.length > 0
721
+ ? inputForm.invalidJson({ names: names(turnInputs.invalid) })
722
+ : null
723
+ ]
724
+ .filter((line) => line !== null)
725
+ .join('. '));
726
+ playground.releaseRunLock();
727
+ return false;
728
+ }
729
+ const body = { ...request, inputs: turnInputs.inputs };
730
+ if (!playground.currentSession) {
731
+ await this.createSession();
732
+ }
733
+ const sessionId = playground.currentSession?.id;
734
+ if (!sessionId) {
735
+ playground.releaseRunLock();
736
+ return false;
737
+ }
738
+ playground.updateSessionStatus('running');
739
+ playground.pinExecution(null);
740
+ playground.setError(null);
741
+ try {
742
+ const response = await this.#service.sendTurn(this.#api.config, sessionId, body, this.#api.authProvider);
743
+ // The user may have switched sessions while the turn was in flight:
744
+ // its result and its poll belong to the session it was sent on.
745
+ if (playground.currentSession?.id !== sessionId)
746
+ return true;
747
+ // The legacy door answers with the user's row; the turn door with a
748
+ // turn result, and the row arrives with the poll started below.
749
+ if (response.kind === 'turn') {
750
+ playground.setLastTurn(response.result);
751
+ }
752
+ else {
753
+ playground.addMessage(response.message);
754
+ playground.setLastTurn(null);
755
+ }
756
+ // Only start polling if not already active — avoids resetting the cursor
757
+ // mid-session and re-fetching messages that are already in the store.
758
+ // Seed from the newest loaded message so polling tails live updates
759
+ // rather than crawling forward from the start of the conversation.
760
+ if (!this.#service.isPolling()) {
761
+ this.startPolling(sessionId, true);
762
+ }
763
+ this.#beginSessionRun(sessionId);
764
+ return true;
765
+ }
766
+ catch (err) {
767
+ const errorMessage = err instanceof Error ? err.message : 'Failed to send message';
768
+ report(errorMessage);
769
+ playground.updateSessionStatus('idle');
770
+ playground.releaseRunLock();
771
+ logger.error('Failed to send message:', err);
772
+ return false;
773
+ }
774
+ }
775
+ finally {
776
+ playground.setTurnPending(false);
777
+ }
778
+ }
779
+ async stopExecution() {
780
+ const sessionId = this.#playground.currentSession?.id;
781
+ if (!sessionId)
782
+ return;
783
+ // Whoever stops (the bar, the Playground, `session stop`), the run reads
784
+ // as stopped, not as done, once the session goes idle.
785
+ const tracked = this.#tracked;
786
+ if (tracked?.origin === 'session' && tracked.sessionId === sessionId) {
787
+ this.#tracked = { ...tracked, stopped: true };
788
+ }
789
+ try {
790
+ // A 200 means the server ended the run; a 409 means there was nothing
791
+ // left to stop. Either way the session is idle: say so, then read the
792
+ // server's side of it instead of trusting a local guess.
793
+ await this.#service.stopExecution(this.#api.config, sessionId, this.#api.authProvider);
794
+ this.#service.stopPolling();
795
+ this.#playground.updateSessionStatus('idle');
796
+ await this.refresh();
797
+ }
798
+ catch (err) {
799
+ // A real failure (network, 5xx, 403): the run may still be going, so
800
+ // do not pretend it stopped. Show the error and let the server decide.
801
+ if (tracked?.origin === 'session' && tracked.sessionId === sessionId) {
802
+ this.#tracked = { ...tracked, stopped: false };
803
+ }
804
+ this.#playground.setError(err instanceof Error ? err.message : 'Failed to stop execution');
805
+ logger.error('Failed to stop execution:', err);
806
+ await this.refresh();
807
+ }
808
+ }
809
+ // -----------------------------------------------------------------------
810
+ // Following a run
811
+ // -----------------------------------------------------------------------
812
+ startPolling(sessionId, seedSequence = false, overrideShouldStopPolling) {
813
+ const pollingInterval = this.#options.pollingInterval ?? 1500;
814
+ const initialSequenceNumber = seedSequence ? this.#playground.latestSequenceNumber : null;
815
+ this.#service.startPolling(this.#api.config, sessionId, (response) => this.#playground.applyServerResponse(response, sessionId), pollingInterval, overrideShouldStopPolling ?? this.#options.shouldStopPolling, initialSequenceNumber, this.#api.authProvider);
816
+ }
817
+ /** Stop this instance's poller. */
818
+ stopPolling() {
819
+ this.#service.stopPolling();
820
+ }
821
+ /**
822
+ * Load one run's per-node status into `fd.playground` (`nodeStatuses`).
823
+ *
824
+ * The node status overlay draws from that store, so the result survives
825
+ * edits to the graph. Without arguments it follows the session's active run
826
+ * and the editor's workflow. A newer call, or {@link clearNodeStatuses},
827
+ * discards the result of one still in flight. Without a run or a saved
828
+ * workflow it clears instead. A read that fails keeps the last good result
829
+ * of the same run.
830
+ */
831
+ async loadNodeStatuses(pipelineId, workflow) {
832
+ const runId = pipelineId ?? this.#playground.activeExecutionId;
833
+ const target = workflow ?? this.#workflow.current;
834
+ const token = ++this.#statusToken;
835
+ if (!runId || !target?.id) {
836
+ this.#playground.clearNodeStatuses();
837
+ return;
838
+ }
839
+ try {
840
+ const statuses = await nodeExecutionService.fetchMultipleNodeExecutionInfo(this.#api.config, target.nodes.map((node) => node.id), runId);
841
+ if (token !== this.#statusToken)
842
+ return;
843
+ this.#playground.setNodeStatuses(statuses, { workflowId: target.id, pipelineId: runId });
844
+ }
845
+ catch (error) {
846
+ if (token === this.#statusToken) {
847
+ logger.error('Failed to load node execution info:', error);
848
+ // A failed read keeps the last good map of this run (the next poll
849
+ // tick retries). Statuses of another run or workflow are not kept.
850
+ const shown = this.#playground.nodeStatusScope;
851
+ if (shown && (shown.pipelineId !== runId || shown.workflowId !== target.id)) {
852
+ this.#playground.clearNodeStatuses();
853
+ }
854
+ }
855
+ }
856
+ }
857
+ /**
858
+ * Ask for the shown run's node statuses to be (re)loaded, for a caller that
859
+ * asks on every poll tick: one load runs at a time, and any number of asks
860
+ * made while it runs coalesce into one more load afterwards. The request
861
+ * rate therefore follows the network, not the poll interval, and the last
862
+ * state is always the one loaded.
863
+ */
864
+ requestNodeStatuses() {
865
+ if (this.#statusLoading) {
866
+ this.#statusAgain = true;
867
+ return;
868
+ }
869
+ this.#statusLoading = true;
870
+ void (async () => {
871
+ try {
872
+ do {
873
+ this.#statusAgain = false;
874
+ // A host run has no session execution id: name the run being shown.
875
+ await this.loadNodeStatuses(this.activeRun?.runId);
876
+ } while (this.#statusAgain);
877
+ }
878
+ finally {
879
+ this.#statusLoading = false;
880
+ }
881
+ })();
882
+ }
883
+ /** Drop the node statuses and any load still in flight. */
884
+ clearNodeStatuses() {
885
+ this.#statusToken++;
886
+ this.#statusAgain = false;
887
+ this.#playground.clearNodeStatuses();
888
+ }
889
+ /**
890
+ * Whether a run is going or waiting for someone: the shown run
891
+ * ({@link activeRun}, session or host) is running or waiting, or the
892
+ * current session is running or awaiting input (a Playground turn that no
893
+ * bar tracks). The one fact "a run needs watching" is read from here: the
894
+ * dot on the Test switch, and the badges that follow a run in Edit mode.
895
+ * For a tracked session run it agrees with the run bar by construction,
896
+ * since the bar's status is derived from the session's.
897
+ */
898
+ get isLive() {
899
+ const status = this.activeRun?.status;
900
+ if (status === 'running' || status === 'waiting')
901
+ return true;
902
+ const session = this.#playground.sessionStatus;
903
+ return session === 'running' || session === 'awaiting_input';
904
+ }
905
+ /** Fetch what is new for the current session and tail it when it is running. */
906
+ async refresh() {
907
+ const sessionId = this.#playground.currentSession?.id;
908
+ if (!sessionId || this.#isRefreshing)
909
+ return;
910
+ this.#isRefreshing = true;
911
+ try {
912
+ const response = await this.#service.getMessages(this.#api.config, sessionId, {
913
+ since: this.#service.getLastSequenceNumber() ?? undefined
914
+ }, this.#api.authProvider);
915
+ this.#playground.applyServerResponse(response, sessionId);
916
+ if (response.sessionStatus === 'running' && !this.#service.isPolling()) {
917
+ this.startPolling(sessionId, true);
918
+ }
919
+ }
920
+ catch (err) {
921
+ logger.error('[Playground] Status refresh failed:', err);
922
+ }
923
+ finally {
924
+ this.#isRefreshing = false;
925
+ }
926
+ }
927
+ /**
928
+ * Catch up immediately rather than waiting for the next poll interval, using
929
+ * the service's sequence cursor so only new messages are fetched. Shared by
930
+ * the interrupt-resolved handler (which also restarts polling, as
931
+ * `restartPolling`) and the tab-visible catch-up (which only fetches).
932
+ */
933
+ async catchUp(options = {}) {
934
+ const sessionId = this.#playground.currentSession?.id;
935
+ if (!sessionId)
936
+ return;
937
+ try {
938
+ const response = await this.#service.getMessages(this.#api.config, sessionId, {
939
+ since: this.#service.getLastSequenceNumber() ?? undefined
940
+ }, this.#api.authProvider);
941
+ this.#playground.applyServerResponse(response, sessionId);
942
+ }
943
+ catch (err) {
944
+ logger.error(options.restartPolling
945
+ ? '[Playground] Failed to refresh after interrupt:'
946
+ : '[Playground] Visibility catchup failed:', err);
947
+ }
948
+ // Polling continues through awaiting_input now, but restart defensively
949
+ // in case it stopped for any reason (e.g. component re-mount).
950
+ if (options.restartPolling && !this.#service.isPolling()) {
951
+ this.startPolling(sessionId, true);
952
+ }
953
+ }
954
+ /** Whether this instance's service is polling a session. */
955
+ get isPolling() {
956
+ return this.#service.isPolling();
957
+ }
958
+ // -----------------------------------------------------------------------
959
+ // The run being shown
960
+ // -----------------------------------------------------------------------
961
+ /**
962
+ * The run the instance is showing, or `null`. Reactive. A session run's
963
+ * status follows the session; a host run's follows `onRunStatus`.
964
+ */
965
+ get activeRun() {
966
+ return this.#activeRun;
967
+ }
968
+ /** Memoised: the same object until something it reads changes. */
969
+ #activeRun = $derived.by(() => {
970
+ const tracked = this.#tracked;
971
+ if (!tracked)
972
+ return null;
973
+ let status;
974
+ let runId = tracked.runId;
975
+ if (tracked.origin === 'session') {
976
+ // Another conversation took over: that run is not the one we followed.
977
+ if (this.#playground.currentSession?.id !== tracked.sessionId)
978
+ return null;
979
+ status = sessionRunStatus(this.#playground.sessionStatus, tracked.stopped);
980
+ runId = this.#playground.activeExecutionId;
981
+ if (status === 'done' && runId && this.#failedRunIds.has(runId))
982
+ status = 'failed';
983
+ }
984
+ else {
985
+ status = tracked.hostStatus;
986
+ }
987
+ return {
988
+ origin: tracked.origin,
989
+ runId,
990
+ status,
991
+ startedAt: tracked.startedAt,
992
+ endedAt: TERMINAL_RUN_STATUSES.includes(status) ? (this.#endedAt ?? tracked.startedAt) : null
993
+ };
994
+ });
995
+ /**
996
+ * Stop the run being shown: the session's stop for a session run, a cancel
997
+ * signal on the pipeline for a host run (the next status read reports it).
998
+ */
999
+ async stopRun() {
1000
+ const tracked = this.#tracked;
1001
+ if (!tracked)
1002
+ return;
1003
+ if (tracked.origin === 'session') {
1004
+ await this.stopExecution();
1005
+ return;
1006
+ }
1007
+ if (!tracked.runId)
1008
+ return;
1009
+ const result = await this.sendSignal('cancel', tracked.runId);
1010
+ if (result.status === 'accepted')
1011
+ this.#scheduleHostPoll(tracked.runId, 0);
1012
+ }
1013
+ /**
1014
+ * Forget the shown run and its node statuses. The run bar calls it when it
1015
+ * fades; the statuses go with it so the Edit canvas is back to normal.
1016
+ */
1017
+ dismissRun() {
1018
+ this.#openedId = null;
1019
+ this.#clearHostPoll();
1020
+ this.#tracked = null;
1021
+ this.#endedAt = null;
1022
+ this.clearNodeStatuses();
1023
+ }
1024
+ /**
1025
+ * The host's `onRun` / `onRunStatus` routed through this controller: runs
1026
+ * they start become the shown run, and the status they report moves it.
1027
+ * Hands back hooks that behave exactly as the given ones (same arguments,
1028
+ * same envelopes, same rejections); use them wherever the originals went.
1029
+ * A run is followed only when the host also supplies `onRunStatus`: without
1030
+ * it there is no way to know the run ended.
1031
+ */
1032
+ wrapHostHooks(hooks) {
1033
+ const { onRun, onRunStatus } = hooks;
1034
+ const out = { ...hooks };
1035
+ if (onRunStatus) {
1036
+ this.#hostStatusHook = onRunStatus;
1037
+ out.onRunStatus = async (runId) => {
1038
+ const envelope = await onRunStatus(runId);
1039
+ this.#applyHostStatus(runId, envelope.ok ? envelope.data?.status : undefined);
1040
+ return envelope;
1041
+ };
1042
+ }
1043
+ if (onRun) {
1044
+ out.onRun = async (inputs) => {
1045
+ const envelope = await onRun(inputs);
1046
+ if (envelope.ok && envelope.data?.runId) {
1047
+ this.#beginHostRun(envelope.data.runId, envelope.data.status);
1048
+ }
1049
+ return envelope;
1050
+ };
1051
+ }
1052
+ return out;
1053
+ }
1054
+ /**
1055
+ * Show a run from the Runs list: it becomes the shown run (node badges, run
1056
+ * pill), whatever started it. A run that has not finished is followed until
1057
+ * it does, through the pipelines status endpoint (or the host's
1058
+ * `onRunStatus` when it gave one).
1059
+ */
1060
+ openRun(runId, status) {
1061
+ this.#openedId = runId;
1062
+ const hostStatus = hostRunStatus(status);
1063
+ this.#clearHostPoll();
1064
+ this.#tracked = {
1065
+ origin: 'host',
1066
+ runId,
1067
+ sessionId: null,
1068
+ startedAt: Date.now(),
1069
+ stopped: false,
1070
+ hostStatus
1071
+ };
1072
+ const terminal = TERMINAL_RUN_STATUSES.includes(hostStatus);
1073
+ this.#endedAt = terminal ? Date.now() : null;
1074
+ if (!terminal)
1075
+ this.#scheduleHostPoll(runId, this.hostPollInterval);
1076
+ }
1077
+ /**
1078
+ * The run opened from the Runs list and still shown, or `null` (nothing
1079
+ * opened, or a live run has taken its place). Reactive.
1080
+ */
1081
+ get openedRunId() {
1082
+ const tracked = this.#tracked;
1083
+ return this.#openedId !== null && tracked?.origin === 'host' && tracked.runId === this.#openedId
1084
+ ? this.#openedId
1085
+ : null;
1086
+ }
1087
+ /** Stop the timers and subscriptions this controller started. */
1088
+ dispose() {
1089
+ this.stopHostPolling();
1090
+ this.#unsubscribeSessionStatus?.();
1091
+ this.#unsubscribeSessionStatus = null;
1092
+ }
1093
+ /**
1094
+ * Stop reading the status of a host run and forget it. Also drops a read
1095
+ * already in flight. The controller stays usable: a later host run polls again.
1096
+ */
1097
+ stopHostPolling() {
1098
+ this.#hostPollEpoch++;
1099
+ this.#clearHostPoll();
1100
+ if (this.#tracked?.origin === 'host') {
1101
+ this.#tracked = null;
1102
+ this.#endedAt = null;
1103
+ }
1104
+ }
1105
+ #beginSessionRun(sessionId) {
1106
+ this.#clearHostPoll();
1107
+ this.#tracked = {
1108
+ origin: 'session',
1109
+ runId: null,
1110
+ sessionId,
1111
+ startedAt: Date.now(),
1112
+ stopped: false,
1113
+ hostStatus: 'running'
1114
+ };
1115
+ this.#endedAt = null;
1116
+ }
1117
+ /** A finished session run may have failed: ask the runs list, once, when it ends. */
1118
+ async #noteRunFailure(sessionId) {
1119
+ const result = await this.loadSessionRuns(sessionId);
1120
+ const runId = this.#playground.activeExecutionId;
1121
+ const run = result?.runs.find((r) => r.id === runId);
1122
+ if (run?.status === 'failed')
1123
+ this.#failedRunIds.add(run.id);
1124
+ }
1125
+ #beginHostRun(runId, status) {
1126
+ if (!this.#hostStatusHook)
1127
+ return;
1128
+ const hostStatus = hostRunStatus(status);
1129
+ this.#clearHostPoll();
1130
+ this.#tracked = {
1131
+ origin: 'host',
1132
+ runId,
1133
+ sessionId: null,
1134
+ startedAt: Date.now(),
1135
+ stopped: false,
1136
+ hostStatus
1137
+ };
1138
+ this.#endedAt = TERMINAL_RUN_STATUSES.includes(hostStatus) ? Date.now() : null;
1139
+ if (!TERMINAL_RUN_STATUSES.includes(hostStatus)) {
1140
+ this.#scheduleHostPoll(runId, this.hostPollInterval);
1141
+ }
1142
+ }
1143
+ #applyHostStatus(runId, status) {
1144
+ const tracked = this.#tracked;
1145
+ if (tracked?.origin !== 'host' || tracked.runId !== runId || status === undefined)
1146
+ return;
1147
+ const next = hostRunStatus(status);
1148
+ if (next === tracked.hostStatus)
1149
+ return;
1150
+ this.#tracked = { ...tracked, hostStatus: next };
1151
+ if (TERMINAL_RUN_STATUSES.includes(next)) {
1152
+ this.#endedAt = Date.now();
1153
+ this.#clearHostPoll();
1154
+ }
1155
+ else {
1156
+ this.#endedAt = null;
1157
+ }
1158
+ }
1159
+ #scheduleHostPoll(runId, delay) {
1160
+ this.#clearHostPoll();
1161
+ this.#hostPoll = setTimeout(() => {
1162
+ this.#hostPoll = null;
1163
+ void this.#pollHost(runId);
1164
+ }, delay);
1165
+ }
1166
+ async #pollHost(runId) {
1167
+ const tracked = this.#tracked;
1168
+ const hook = this.#hostStatusHook ?? this.#readStatusFromApi;
1169
+ if (tracked?.origin !== 'host' || tracked.runId !== runId)
1170
+ return;
1171
+ const epoch = this.#hostPollEpoch;
1172
+ try {
1173
+ const envelope = await hook(runId);
1174
+ if (epoch !== this.#hostPollEpoch)
1175
+ return;
1176
+ this.#applyHostStatus(runId, envelope.ok ? envelope.data?.status : undefined);
1177
+ }
1178
+ catch (err) {
1179
+ logger.error('Failed to read host run status:', err);
1180
+ }
1181
+ if (epoch !== this.#hostPollEpoch)
1182
+ return;
1183
+ const now = this.#tracked;
1184
+ if (now?.origin === 'host' &&
1185
+ now.runId === runId &&
1186
+ !TERMINAL_RUN_STATUSES.includes(now.hostStatus)) {
1187
+ this.#scheduleHostPoll(runId, this.hostPollInterval);
1188
+ }
1189
+ }
1190
+ /** The status read of a run opened from the Runs list when the host gave no `onRunStatus`. */
1191
+ #readStatusFromApi = async (runId) => {
1192
+ const config = this.#api.config;
1193
+ if (!config)
1194
+ return { ok: false };
1195
+ const status = await readRunStatus(config, runId, this.#api.authProvider);
1196
+ return status === undefined ? { ok: false } : { ok: true, data: { status } };
1197
+ };
1198
+ #clearHostPoll() {
1199
+ if (this.#hostPoll !== null)
1200
+ clearTimeout(this.#hostPoll);
1201
+ this.#hostPoll = null;
1202
+ }
1203
+ // -----------------------------------------------------------------------
1204
+ // Slash-command adapter
1205
+ // -----------------------------------------------------------------------
1206
+ /** The adapter for `playground/commands/dispatch.ts`. */
1207
+ commandHandlers() {
1208
+ return {
1209
+ createSession: () => this.createSession(),
1210
+ deleteSession: (sessionId) => this.deleteSession(sessionId),
1211
+ stopExecution: () => this.stopExecution(),
1212
+ resetSession: () => this.resetSession(),
1213
+ sendSignal: (signal, pipelineId, reason) => this.sendSignal(signal, pipelineId, reason),
1214
+ launchWorkflow: (inputs) => this.launchWorkflow(inputs)
1215
+ };
1216
+ }
1217
+ }