@open-mercato/core 0.7.1-develop.7193.1.910a5b0a1e → 0.7.1-develop.7194.1.ab4fc81f82

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 (1238) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/AGENTS.md +4 -3
  3. package/agentic/standalone-guide.md +1 -1
  4. package/build.mjs +16 -0
  5. package/dist/generated/entities/action_log/index.js +2 -0
  6. package/dist/generated/entities/action_log/index.js.map +2 -2
  7. package/dist/generated/entities/user/index.js +2 -0
  8. package/dist/generated/entities/user/index.js.map +2 -2
  9. package/dist/generated/entities/user_task/index.js +14 -0
  10. package/dist/generated/entities/user_task/index.js.map +2 -2
  11. package/dist/generated/entities/workflow_definition/index.js +6 -0
  12. package/dist/generated/entities/workflow_definition/index.js.map +2 -2
  13. package/dist/generated/entities/workflow_definition_draft/index.js +25 -0
  14. package/dist/generated/entities/workflow_definition_draft/index.js.map +7 -0
  15. package/dist/generated/entities/workflow_definition_metric_rollup/index.js +23 -0
  16. package/dist/generated/entities/workflow_definition_metric_rollup/index.js.map +7 -0
  17. package/dist/generated/entities/workflow_instance/index.js +4 -0
  18. package/dist/generated/entities/workflow_instance/index.js.map +2 -2
  19. package/dist/generated/entities.ids.generated.js +4 -1
  20. package/dist/generated/entities.ids.generated.js.map +2 -2
  21. package/dist/generated/entity-fields-registry.js +39 -0
  22. package/dist/generated/entity-fields-registry.js.map +2 -2
  23. package/dist/helpers/integration/workflowsFixtures.js +477 -2
  24. package/dist/helpers/integration/workflowsFixtures.js.map +2 -2
  25. package/dist/helpers/integration/workflowsUi.js +148 -0
  26. package/dist/helpers/integration/workflowsUi.js.map +7 -0
  27. package/dist/modules/attachments/lib/createFromBuffer.js +79 -0
  28. package/dist/modules/attachments/lib/createFromBuffer.js.map +7 -0
  29. package/dist/modules/audit_logs/data/entities.js +5 -0
  30. package/dist/modules/audit_logs/data/entities.js.map +2 -2
  31. package/dist/modules/audit_logs/data/validators.js +1 -0
  32. package/dist/modules/audit_logs/data/validators.js.map +2 -2
  33. package/dist/modules/audit_logs/lib/projections.js +2 -1
  34. package/dist/modules/audit_logs/lib/projections.js.map +2 -2
  35. package/dist/modules/audit_logs/migrations/Migration20260625120000.js +15 -0
  36. package/dist/modules/audit_logs/migrations/Migration20260625120000.js.map +7 -0
  37. package/dist/modules/audit_logs/services/actionLogService.js +3 -0
  38. package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
  39. package/dist/modules/auth/data/entities.js +6 -0
  40. package/dist/modules/auth/data/entities.js.map +2 -2
  41. package/dist/modules/auth/lib/executionPrincipal.js +140 -0
  42. package/dist/modules/auth/lib/executionPrincipal.js.map +7 -0
  43. package/dist/modules/auth/migrations/Migration20260625050000.js +13 -0
  44. package/dist/modules/auth/migrations/Migration20260625050000.js.map +7 -0
  45. package/dist/modules/business_rules/components/InlineRuleEditor.js +154 -0
  46. package/dist/modules/business_rules/components/InlineRuleEditor.js.map +7 -0
  47. package/dist/modules/business_rules/data/validators.js +6 -0
  48. package/dist/modules/business_rules/data/validators.js.map +2 -2
  49. package/dist/modules/business_rules/lib/rule-engine.js +5 -3
  50. package/dist/modules/business_rules/lib/rule-engine.js.map +2 -2
  51. package/dist/modules/catalog/commands/products.js +5 -0
  52. package/dist/modules/catalog/commands/products.js.map +2 -2
  53. package/dist/modules/catalog/workflows.js +19 -0
  54. package/dist/modules/catalog/workflows.js.map +7 -0
  55. package/dist/modules/customer_accounts/backend/customer_accounts/roles/[id]/page.js +3 -1
  56. package/dist/modules/customer_accounts/backend/customer_accounts/roles/[id]/page.js.map +2 -2
  57. package/dist/modules/customer_accounts/cli.js +80 -0
  58. package/dist/modules/customer_accounts/cli.js.map +7 -0
  59. package/dist/modules/customer_accounts/lib/customerRoleAclSync.js +59 -0
  60. package/dist/modules/customer_accounts/lib/customerRoleAclSync.js.map +7 -0
  61. package/dist/modules/customer_accounts/setup.js +4 -2
  62. package/dist/modules/customer_accounts/setup.js.map +2 -2
  63. package/dist/modules/customers/commands/deals.js +4 -0
  64. package/dist/modules/customers/commands/deals.js.map +2 -2
  65. package/dist/modules/customers/components/detail/ChangelogEntryRow.js +1 -1
  66. package/dist/modules/customers/components/detail/ChangelogEntryRow.js.map +2 -2
  67. package/dist/modules/customers/components/detail/utils.js +2 -0
  68. package/dist/modules/customers/components/detail/utils.js.map +2 -2
  69. package/dist/modules/customers/events.js +13 -2
  70. package/dist/modules/customers/events.js.map +2 -2
  71. package/dist/modules/customers/lib/link-workflow-task-handler.js +64 -0
  72. package/dist/modules/customers/lib/link-workflow-task-handler.js.map +7 -0
  73. package/dist/modules/customers/lib/todoCompatibility.js +1 -1
  74. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  75. package/dist/modules/customers/lib/workflowTaskLink.js +9 -0
  76. package/dist/modules/customers/lib/workflowTaskLink.js.map +7 -0
  77. package/dist/modules/customers/subscribers/link-workflow-task.js +12 -0
  78. package/dist/modules/customers/subscribers/link-workflow-task.js.map +7 -0
  79. package/dist/modules/customers/workflows.js +29 -0
  80. package/dist/modules/customers/workflows.js.map +7 -0
  81. package/dist/modules/entities/api/records.js +13 -33
  82. package/dist/modules/entities/api/records.js.map +3 -3
  83. package/dist/modules/entities/lib/entityClassification.js +60 -0
  84. package/dist/modules/entities/lib/entityClassification.js.map +7 -0
  85. package/dist/modules/sales/commands/documents.js +31 -0
  86. package/dist/modules/sales/commands/documents.js.map +2 -2
  87. package/dist/modules/sales/events.js +12 -1
  88. package/dist/modules/sales/events.js.map +2 -2
  89. package/dist/modules/sales/workflows.js +12 -1
  90. package/dist/modules/sales/workflows.js.map +2 -2
  91. package/dist/modules/seeds/cli.js +199 -0
  92. package/dist/modules/seeds/cli.js.map +7 -0
  93. package/dist/modules/seeds/examples/sample-seed.json +26 -0
  94. package/dist/modules/seeds/index.js +12 -0
  95. package/dist/modules/seeds/index.js.map +7 -0
  96. package/dist/modules/workflows/acl.js +96 -0
  97. package/dist/modules/workflows/acl.js.map +2 -2
  98. package/dist/modules/workflows/ai-agents.js +50 -0
  99. package/dist/modules/workflows/ai-agents.js.map +7 -0
  100. package/dist/modules/workflows/ai-tools/authoring-pack.js +582 -0
  101. package/dist/modules/workflows/ai-tools/authoring-pack.js.map +7 -0
  102. package/dist/modules/workflows/ai-tools/types.js +43 -0
  103. package/dist/modules/workflows/ai-tools/types.js.map +7 -0
  104. package/dist/modules/workflows/ai-tools.js +10 -0
  105. package/dist/modules/workflows/ai-tools.js.map +7 -0
  106. package/dist/modules/workflows/api/command-settings/route.js +137 -0
  107. package/dist/modules/workflows/api/command-settings/route.js.map +7 -0
  108. package/dist/modules/workflows/api/commands/route.js +72 -0
  109. package/dist/modules/workflows/api/commands/route.js.map +7 -0
  110. package/dist/modules/workflows/api/definitions/[id]/callers/route.js +76 -0
  111. package/dist/modules/workflows/api/definitions/[id]/callers/route.js.map +7 -0
  112. package/dist/modules/workflows/api/definitions/[id]/context-schema/route.js +134 -0
  113. package/dist/modules/workflows/api/definitions/[id]/context-schema/route.js.map +7 -0
  114. package/dist/modules/workflows/api/definitions/[id]/customize/route.js +5 -1
  115. package/dist/modules/workflows/api/definitions/[id]/customize/route.js.map +2 -2
  116. package/dist/modules/workflows/api/definitions/[id]/draft/route.js +286 -0
  117. package/dist/modules/workflows/api/definitions/[id]/draft/route.js.map +7 -0
  118. package/dist/modules/workflows/api/definitions/[id]/publish/route.js +207 -0
  119. package/dist/modules/workflows/api/definitions/[id]/publish/route.js.map +7 -0
  120. package/dist/modules/workflows/api/definitions/[id]/reset-to-code/route.js +5 -0
  121. package/dist/modules/workflows/api/definitions/[id]/reset-to-code/route.js.map +2 -2
  122. package/dist/modules/workflows/api/definitions/[id]/route.js +93 -9
  123. package/dist/modules/workflows/api/definitions/[id]/route.js.map +3 -3
  124. package/dist/modules/workflows/api/definitions/[id]/test-step/route.js +210 -0
  125. package/dist/modules/workflows/api/definitions/[id]/test-step/route.js.map +7 -0
  126. package/dist/modules/workflows/api/definitions/generate/route.js +233 -0
  127. package/dist/modules/workflows/api/definitions/generate/route.js.map +7 -0
  128. package/dist/modules/workflows/api/definitions/route.js +61 -113
  129. package/dist/modules/workflows/api/definitions/route.js.map +2 -2
  130. package/dist/modules/workflows/api/definitions/serialize.js +9 -0
  131. package/dist/modules/workflows/api/definitions/serialize.js.map +2 -2
  132. package/dist/modules/workflows/api/endpoints/route.js +69 -0
  133. package/dist/modules/workflows/api/endpoints/route.js.map +7 -0
  134. package/dist/modules/workflows/api/functions/route.js +73 -0
  135. package/dist/modules/workflows/api/functions/route.js.map +7 -0
  136. package/dist/modules/workflows/api/grantable-features/route.js +75 -0
  137. package/dist/modules/workflows/api/grantable-features/route.js.map +7 -0
  138. package/dist/modules/workflows/api/instances/[id]/context/route.js +180 -0
  139. package/dist/modules/workflows/api/instances/[id]/context/route.js.map +7 -0
  140. package/dist/modules/workflows/api/instances/[id]/rerun-step/route.js +184 -0
  141. package/dist/modules/workflows/api/instances/[id]/rerun-step/route.js.map +7 -0
  142. package/dist/modules/workflows/api/instances/[id]/retry/route.js +12 -2
  143. package/dist/modules/workflows/api/instances/[id]/retry/route.js.map +2 -2
  144. package/dist/modules/workflows/api/instances/[id]/step-through/route.js +148 -0
  145. package/dist/modules/workflows/api/instances/[id]/step-through/route.js.map +7 -0
  146. package/dist/modules/workflows/api/instances/[id]/steps/route.js +123 -0
  147. package/dist/modules/workflows/api/instances/[id]/steps/route.js.map +7 -0
  148. package/dist/modules/workflows/api/instances/[id]/would-do/route.js +172 -0
  149. package/dist/modules/workflows/api/instances/[id]/would-do/route.js.map +7 -0
  150. package/dist/modules/workflows/api/instances/bulk-replay/route.js +117 -0
  151. package/dist/modules/workflows/api/instances/bulk-replay/route.js.map +7 -0
  152. package/dist/modules/workflows/api/instances/failure-queue/route.js +165 -0
  153. package/dist/modules/workflows/api/instances/failure-queue/route.js.map +7 -0
  154. package/dist/modules/workflows/api/instances/route.js +94 -3
  155. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  156. package/dist/modules/workflows/api/metrics/definitions/route.js +188 -0
  157. package/dist/modules/workflows/api/metrics/definitions/route.js.map +7 -0
  158. package/dist/modules/workflows/api/openapi.js +415 -4
  159. package/dist/modules/workflows/api/openapi.js.map +2 -2
  160. package/dist/modules/workflows/api/portal/tasks/[id]/complete/route.js +132 -0
  161. package/dist/modules/workflows/api/portal/tasks/[id]/complete/route.js.map +7 -0
  162. package/dist/modules/workflows/api/portal/tasks/[id]/route.js +97 -0
  163. package/dist/modules/workflows/api/portal/tasks/[id]/route.js.map +7 -0
  164. package/dist/modules/workflows/api/portal/tasks/route.js +126 -0
  165. package/dist/modules/workflows/api/portal/tasks/route.js.map +7 -0
  166. package/dist/modules/workflows/api/rule-usage/route.js +80 -0
  167. package/dist/modules/workflows/api/rule-usage/route.js.map +7 -0
  168. package/dist/modules/workflows/api/task-settings/route.js +107 -0
  169. package/dist/modules/workflows/api/task-settings/route.js.map +7 -0
  170. package/dist/modules/workflows/api/tasks/[id]/claim/route.js +27 -16
  171. package/dist/modules/workflows/api/tasks/[id]/claim/route.js.map +2 -2
  172. package/dist/modules/workflows/api/tasks/[id]/complete/route.js +40 -16
  173. package/dist/modules/workflows/api/tasks/[id]/complete/route.js.map +2 -2
  174. package/dist/modules/workflows/api/tasks/[id]/reassign/route.js +150 -0
  175. package/dist/modules/workflows/api/tasks/[id]/reassign/route.js.map +7 -0
  176. package/dist/modules/workflows/api/tasks/[id]/route.js +39 -6
  177. package/dist/modules/workflows/api/tasks/[id]/route.js.map +2 -2
  178. package/dist/modules/workflows/api/tasks/[id]/unclaim/route.js +100 -0
  179. package/dist/modules/workflows/api/tasks/[id]/unclaim/route.js.map +7 -0
  180. package/dist/modules/workflows/api/tasks/route.js +37 -6
  181. package/dist/modules/workflows/api/tasks/route.js.map +2 -2
  182. package/dist/modules/workflows/api/tasks/serialize.js +83 -0
  183. package/dist/modules/workflows/api/tasks/serialize.js.map +7 -0
  184. package/dist/modules/workflows/api/templates/route.js +69 -0
  185. package/dist/modules/workflows/api/templates/route.js.map +7 -0
  186. package/dist/modules/workflows/api/work-inbox/next/route.js +129 -0
  187. package/dist/modules/workflows/api/work-inbox/next/route.js.map +7 -0
  188. package/dist/modules/workflows/api/work-inbox/route.js +119 -0
  189. package/dist/modules/workflows/api/work-inbox/route.js.map +7 -0
  190. package/dist/modules/workflows/backend/config/workflows/page.js +10 -0
  191. package/dist/modules/workflows/backend/config/workflows/page.js.map +7 -0
  192. package/dist/modules/workflows/backend/config/workflows/page.meta.js +35 -0
  193. package/dist/modules/workflows/backend/config/workflows/page.meta.js.map +7 -0
  194. package/dist/modules/workflows/backend/definitions/[id]/page.js +6 -271
  195. package/dist/modules/workflows/backend/definitions/[id]/page.js.map +3 -3
  196. package/dist/modules/workflows/backend/definitions/create/page.js +7 -56
  197. package/dist/modules/workflows/backend/definitions/create/page.js.map +2 -2
  198. package/dist/modules/workflows/backend/definitions/create/page.meta.js +1 -1
  199. package/dist/modules/workflows/backend/definitions/create/page.meta.js.map +2 -2
  200. package/dist/modules/workflows/backend/definitions/page.js +131 -51
  201. package/dist/modules/workflows/backend/definitions/page.js.map +2 -2
  202. package/dist/modules/workflows/backend/definitions/visual-editor/page.js +2606 -677
  203. package/dist/modules/workflows/backend/definitions/visual-editor/page.js.map +3 -3
  204. package/dist/modules/workflows/backend/instances/[id]/page.js +532 -421
  205. package/dist/modules/workflows/backend/instances/[id]/page.js.map +2 -2
  206. package/dist/modules/workflows/backend/instances/[id]/page.meta.js +1 -1
  207. package/dist/modules/workflows/backend/instances/[id]/page.meta.js.map +1 -1
  208. package/dist/modules/workflows/backend/instances/failure-queue/page.js +211 -0
  209. package/dist/modules/workflows/backend/instances/failure-queue/page.js.map +7 -0
  210. package/dist/modules/workflows/backend/instances/failure-queue/page.meta.js +20 -0
  211. package/dist/modules/workflows/backend/instances/failure-queue/page.meta.js.map +7 -0
  212. package/dist/modules/workflows/backend/instances/page.js +159 -22
  213. package/dist/modules/workflows/backend/instances/page.js.map +2 -2
  214. package/dist/modules/workflows/backend/instances/page.meta.js +1 -1
  215. package/dist/modules/workflows/backend/instances/page.meta.js.map +1 -1
  216. package/dist/modules/workflows/backend/tasks/[id]/page.js +553 -392
  217. package/dist/modules/workflows/backend/tasks/[id]/page.js.map +3 -3
  218. package/dist/modules/workflows/backend/tasks/page.js +8 -250
  219. package/dist/modules/workflows/backend/tasks/page.js.map +2 -2
  220. package/dist/modules/workflows/backend/tasks/page.meta.js +1 -0
  221. package/dist/modules/workflows/backend/tasks/page.meta.js.map +2 -2
  222. package/dist/modules/workflows/backend/work-inbox/page.js +399 -0
  223. package/dist/modules/workflows/backend/work-inbox/page.js.map +7 -0
  224. package/dist/modules/workflows/backend/work-inbox/page.meta.js +19 -0
  225. package/dist/modules/workflows/backend/work-inbox/page.meta.js.map +7 -0
  226. package/dist/modules/workflows/cli.js +1 -1
  227. package/dist/modules/workflows/cli.js.map +2 -2
  228. package/dist/modules/workflows/commands/tasks.js +81 -0
  229. package/dist/modules/workflows/commands/tasks.js.map +7 -0
  230. package/dist/modules/workflows/components/ActivitiesEditor.js +281 -287
  231. package/dist/modules/workflows/components/ActivitiesEditor.js.map +2 -2
  232. package/dist/modules/workflows/components/ActivityEditDialog.js +220 -0
  233. package/dist/modules/workflows/components/ActivityEditDialog.js.map +7 -0
  234. package/dist/modules/workflows/components/AgentSelector.js +115 -0
  235. package/dist/modules/workflows/components/AgentSelector.js.map +7 -0
  236. package/dist/modules/workflows/components/AnnotationEditDialog.js +110 -0
  237. package/dist/modules/workflows/components/AnnotationEditDialog.js.map +7 -0
  238. package/dist/modules/workflows/components/BusinessRuleUsagePanel.js +71 -0
  239. package/dist/modules/workflows/components/BusinessRuleUsagePanel.js.map +7 -0
  240. package/dist/modules/workflows/components/BusinessRulesSelector.js +151 -93
  241. package/dist/modules/workflows/components/BusinessRulesSelector.js.map +2 -2
  242. package/dist/modules/workflows/components/ConfigJsonTextarea.js +85 -0
  243. package/dist/modules/workflows/components/ConfigJsonTextarea.js.map +7 -0
  244. package/dist/modules/workflows/components/ContextSchemaEditor.js +150 -0
  245. package/dist/modules/workflows/components/ContextSchemaEditor.js.map +7 -0
  246. package/dist/modules/workflows/components/DefinitionErrorHandlerField.js +102 -0
  247. package/dist/modules/workflows/components/DefinitionErrorHandlerField.js.map +7 -0
  248. package/dist/modules/workflows/components/DefinitionMetadataDrawer.js +377 -0
  249. package/dist/modules/workflows/components/DefinitionMetadataDrawer.js.map +7 -0
  250. package/dist/modules/workflows/components/DefinitionMetricsCells.js +132 -0
  251. package/dist/modules/workflows/components/DefinitionMetricsCells.js.map +7 -0
  252. package/dist/modules/workflows/components/DefinitionTriggersEditor.js +307 -216
  253. package/dist/modules/workflows/components/DefinitionTriggersEditor.js.map +2 -2
  254. package/dist/modules/workflows/components/EdgeEditDialog.js +11 -18
  255. package/dist/modules/workflows/components/EdgeEditDialog.js.map +2 -2
  256. package/dist/modules/workflows/components/EdgeEditDialogCrudForm.js +112 -72
  257. package/dist/modules/workflows/components/EdgeEditDialogCrudForm.js.map +2 -2
  258. package/dist/modules/workflows/components/InputDataPanel.js +128 -0
  259. package/dist/modules/workflows/components/InputDataPanel.js.map +7 -0
  260. package/dist/modules/workflows/components/InspectorPanel.js +161 -0
  261. package/dist/modules/workflows/components/InspectorPanel.js.map +7 -0
  262. package/dist/modules/workflows/components/NodeEditDialog.js +363 -41
  263. package/dist/modules/workflows/components/NodeEditDialog.js.map +2 -2
  264. package/dist/modules/workflows/components/NodeEditDialogCrudForm.js +714 -159
  265. package/dist/modules/workflows/components/NodeEditDialogCrudForm.js.map +2 -2
  266. package/dist/modules/workflows/components/StepsEditor.js.map +2 -2
  267. package/dist/modules/workflows/components/TemplateGalleryDialog.js +148 -0
  268. package/dist/modules/workflows/components/TemplateGalleryDialog.js.map +7 -0
  269. package/dist/modules/workflows/components/TransitionsEditor.js +80 -74
  270. package/dist/modules/workflows/components/TransitionsEditor.js.map +2 -2
  271. package/dist/modules/workflows/components/TriggersDialog.js +53 -0
  272. package/dist/modules/workflows/components/TriggersDialog.js.map +7 -0
  273. package/dist/modules/workflows/components/TriggersEditor.js +331 -0
  274. package/dist/modules/workflows/components/TriggersEditor.js.map +7 -0
  275. package/dist/modules/workflows/components/WorkflowAiDraftDialog.js +278 -0
  276. package/dist/modules/workflows/components/WorkflowAiDraftDialog.js.map +7 -0
  277. package/dist/modules/workflows/components/WorkflowCodeView.js +173 -0
  278. package/dist/modules/workflows/components/WorkflowCodeView.js.map +7 -0
  279. package/dist/modules/workflows/components/WorkflowCommandPalette.js +62 -0
  280. package/dist/modules/workflows/components/WorkflowCommandPalette.js.map +7 -0
  281. package/dist/modules/workflows/components/WorkflowCompensationGhostEdge.js +70 -0
  282. package/dist/modules/workflows/components/WorkflowCompensationGhostEdge.js.map +7 -0
  283. package/dist/modules/workflows/components/WorkflowDataMappingEdge.js +36 -0
  284. package/dist/modules/workflows/components/WorkflowDataMappingEdge.js.map +7 -0
  285. package/dist/modules/workflows/components/WorkflowGraph.js +4 -2
  286. package/dist/modules/workflows/components/WorkflowGraph.js.map +2 -2
  287. package/dist/modules/workflows/components/WorkflowGraphImpl.js +324 -86
  288. package/dist/modules/workflows/components/WorkflowGraphImpl.js.map +3 -3
  289. package/dist/modules/workflows/components/WorkflowIconPicker.js +109 -0
  290. package/dist/modules/workflows/components/WorkflowIconPicker.js.map +7 -0
  291. package/dist/modules/workflows/components/WorkflowLegend.js +45 -29
  292. package/dist/modules/workflows/components/WorkflowLegend.js.map +2 -2
  293. package/dist/modules/workflows/components/WorkflowNodeCard.js +221 -22
  294. package/dist/modules/workflows/components/WorkflowNodeCard.js.map +2 -2
  295. package/dist/modules/workflows/components/WorkflowRouteChips.js +111 -0
  296. package/dist/modules/workflows/components/WorkflowRouteChips.js.map +7 -0
  297. package/dist/modules/workflows/components/WorkflowSelector.js +108 -88
  298. package/dist/modules/workflows/components/WorkflowSelector.js.map +2 -2
  299. package/dist/modules/workflows/components/WorkflowTransitionEdge.js +61 -11
  300. package/dist/modules/workflows/components/WorkflowTransitionEdge.js.map +2 -2
  301. package/dist/modules/workflows/components/WorkflowTransitionLabel.js +15 -5
  302. package/dist/modules/workflows/components/WorkflowTransitionLabel.js.map +2 -2
  303. package/dist/modules/workflows/components/fields/ActivityArrayEditor.js +88 -21
  304. package/dist/modules/workflows/components/fields/ActivityArrayEditor.js.map +2 -2
  305. package/dist/modules/workflows/components/fields/ActivityConfigFields.js +615 -0
  306. package/dist/modules/workflows/components/fields/ActivityConfigFields.js.map +7 -0
  307. package/dist/modules/workflows/components/fields/ActivityTestPanel.js +191 -0
  308. package/dist/modules/workflows/components/fields/ActivityTestPanel.js.map +7 -0
  309. package/dist/modules/workflows/components/fields/AgentInvokeConfigField.js +488 -0
  310. package/dist/modules/workflows/components/fields/AgentInvokeConfigField.js.map +7 -0
  311. package/dist/modules/workflows/components/fields/AgentReviewOnBreachField.js +61 -0
  312. package/dist/modules/workflows/components/fields/AgentReviewOnBreachField.js.map +7 -0
  313. package/dist/modules/workflows/components/fields/BranchingRoutesEditor.js +227 -0
  314. package/dist/modules/workflows/components/fields/BranchingRoutesEditor.js.map +7 -0
  315. package/dist/modules/workflows/components/fields/BusinessRuleConditionsEditor.js +37 -4
  316. package/dist/modules/workflows/components/fields/BusinessRuleConditionsEditor.js.map +2 -2
  317. package/dist/modules/workflows/components/fields/CommandPicker.js +111 -0
  318. package/dist/modules/workflows/components/fields/CommandPicker.js.map +7 -0
  319. package/dist/modules/workflows/components/fields/EndpointPicker.js +235 -0
  320. package/dist/modules/workflows/components/fields/EndpointPicker.js.map +7 -0
  321. package/dist/modules/workflows/components/fields/FormFieldArrayEditor.js +2 -2
  322. package/dist/modules/workflows/components/fields/FormFieldArrayEditor.js.map +2 -2
  323. package/dist/modules/workflows/components/fields/FunctionPicker.js +55 -0
  324. package/dist/modules/workflows/components/fields/FunctionPicker.js.map +7 -0
  325. package/dist/modules/workflows/components/fields/MappingArrayEditor.js +38 -15
  326. package/dist/modules/workflows/components/fields/MappingArrayEditor.js.map +2 -2
  327. package/dist/modules/workflows/components/fields/PortFieldArrayEditor.js +206 -0
  328. package/dist/modules/workflows/components/fields/PortFieldArrayEditor.js.map +7 -0
  329. package/dist/modules/workflows/components/fields/RolesMultiSelect.js +53 -0
  330. package/dist/modules/workflows/components/fields/RolesMultiSelect.js.map +7 -0
  331. package/dist/modules/workflows/components/fields/RouteOrderEditor.js +130 -0
  332. package/dist/modules/workflows/components/fields/RouteOrderEditor.js.map +7 -0
  333. package/dist/modules/workflows/components/fields/SchemaBuilderDialog.js +104 -0
  334. package/dist/modules/workflows/components/fields/SchemaBuilderDialog.js.map +7 -0
  335. package/dist/modules/workflows/components/fields/StartPreConditionsEditor.js +2 -2
  336. package/dist/modules/workflows/components/fields/StartPreConditionsEditor.js.map +2 -2
  337. package/dist/modules/workflows/components/fields/TaskAssignmentField.js +210 -0
  338. package/dist/modules/workflows/components/fields/TaskAssignmentField.js.map +7 -0
  339. package/dist/modules/workflows/components/fields/TaskDeadlineFields.js +126 -0
  340. package/dist/modules/workflows/components/fields/TaskDeadlineFields.js.map +7 -0
  341. package/dist/modules/workflows/components/fields/TaskDecisionsField.js +218 -0
  342. package/dist/modules/workflows/components/fields/TaskDecisionsField.js.map +7 -0
  343. package/dist/modules/workflows/components/fields/TaskEntityBindingsField.js +114 -0
  344. package/dist/modules/workflows/components/fields/TaskEntityBindingsField.js.map +7 -0
  345. package/dist/modules/workflows/components/fields/TemplateTextControl.js +64 -0
  346. package/dist/modules/workflows/components/fields/TemplateTextControl.js.map +7 -0
  347. package/dist/modules/workflows/components/fields/VariablePickerButton.js +121 -0
  348. package/dist/modules/workflows/components/fields/VariablePickerButton.js.map +7 -0
  349. package/dist/modules/workflows/components/fields/ledgerDropTarget.js +35 -0
  350. package/dist/modules/workflows/components/fields/ledgerDropTarget.js.map +7 -0
  351. package/dist/modules/workflows/components/fields/useActivityTypeOptions.js +16 -0
  352. package/dist/modules/workflows/components/fields/useActivityTypeOptions.js.map +7 -0
  353. package/dist/modules/workflows/components/formConfig.js +39 -10
  354. package/dist/modules/workflows/components/formConfig.js.map +2 -2
  355. package/dist/modules/workflows/components/mobile/MobileDefinitionDetail.js.map +2 -2
  356. package/dist/modules/workflows/components/mobile/MobileMetadataSheet.js.map +2 -2
  357. package/dist/modules/workflows/components/mobile/MobileTaskForm.js +29 -2
  358. package/dist/modules/workflows/components/mobile/MobileTaskForm.js.map +2 -2
  359. package/dist/modules/workflows/components/mobile/MobileVisualEditor.js +64 -65
  360. package/dist/modules/workflows/components/mobile/MobileVisualEditor.js.map +2 -2
  361. package/dist/modules/workflows/components/nodes/AnnotationGroupNode.js +64 -0
  362. package/dist/modules/workflows/components/nodes/AnnotationGroupNode.js.map +7 -0
  363. package/dist/modules/workflows/components/nodes/AutomatedNode.js +24 -16
  364. package/dist/modules/workflows/components/nodes/AutomatedNode.js.map +2 -2
  365. package/dist/modules/workflows/components/nodes/EndNode.js +13 -12
  366. package/dist/modules/workflows/components/nodes/EndNode.js.map +2 -2
  367. package/dist/modules/workflows/components/nodes/ErrorOutputHandle.js +29 -0
  368. package/dist/modules/workflows/components/nodes/ErrorOutputHandle.js.map +7 -0
  369. package/dist/modules/workflows/components/nodes/IfElseNode.js +51 -0
  370. package/dist/modules/workflows/components/nodes/IfElseNode.js.map +7 -0
  371. package/dist/modules/workflows/components/nodes/InvokeAgentNode.js +122 -0
  372. package/dist/modules/workflows/components/nodes/InvokeAgentNode.js.map +7 -0
  373. package/dist/modules/workflows/components/nodes/NodeOutcomeRows.js +100 -0
  374. package/dist/modules/workflows/components/nodes/NodeOutcomeRows.js.map +7 -0
  375. package/dist/modules/workflows/components/nodes/ParallelForkNode.js +18 -14
  376. package/dist/modules/workflows/components/nodes/ParallelForkNode.js.map +2 -2
  377. package/dist/modules/workflows/components/nodes/ParallelJoinNode.js +18 -14
  378. package/dist/modules/workflows/components/nodes/ParallelJoinNode.js.map +2 -2
  379. package/dist/modules/workflows/components/nodes/StartNode.js +66 -15
  380. package/dist/modules/workflows/components/nodes/StartNode.js.map +2 -2
  381. package/dist/modules/workflows/components/nodes/StickyNoteNode.js +54 -0
  382. package/dist/modules/workflows/components/nodes/StickyNoteNode.js.map +7 -0
  383. package/dist/modules/workflows/components/nodes/SubWorkflowNode.js +107 -41
  384. package/dist/modules/workflows/components/nodes/SubWorkflowNode.js.map +2 -2
  385. package/dist/modules/workflows/components/nodes/SwitchNode.js +51 -0
  386. package/dist/modules/workflows/components/nodes/SwitchNode.js.map +7 -0
  387. package/dist/modules/workflows/components/nodes/TriggerCap.js +65 -0
  388. package/dist/modules/workflows/components/nodes/TriggerCap.js.map +7 -0
  389. package/dist/modules/workflows/components/nodes/TriggerNode.js +111 -0
  390. package/dist/modules/workflows/components/nodes/TriggerNode.js.map +7 -0
  391. package/dist/modules/workflows/components/nodes/UserTaskNode.js +43 -17
  392. package/dist/modules/workflows/components/nodes/UserTaskNode.js.map +2 -2
  393. package/dist/modules/workflows/components/nodes/WaitForConditionNode.js +53 -0
  394. package/dist/modules/workflows/components/nodes/WaitForConditionNode.js.map +7 -0
  395. package/dist/modules/workflows/components/nodes/WaitForSignalNode.js +21 -15
  396. package/dist/modules/workflows/components/nodes/WaitForSignalNode.js.map +2 -2
  397. package/dist/modules/workflows/components/nodes/WaitForTimerNode.js +21 -15
  398. package/dist/modules/workflows/components/nodes/WaitForTimerNode.js.map +2 -2
  399. package/dist/modules/workflows/components/nodes/index.js +14 -0
  400. package/dist/modules/workflows/components/nodes/index.js.map +2 -2
  401. package/dist/modules/workflows/components/portal/PortalTaskForm.js +196 -0
  402. package/dist/modules/workflows/components/portal/PortalTaskForm.js.map +7 -0
  403. package/dist/modules/workflows/components/run/AgentActivityPanel.js +22 -0
  404. package/dist/modules/workflows/components/run/AgentActivityPanel.js.map +7 -0
  405. package/dist/modules/workflows/components/run/RerunStepDialog.js +106 -0
  406. package/dist/modules/workflows/components/run/RerunStepDialog.js.map +7 -0
  407. package/dist/modules/workflows/components/run/RunEventBadge.js +30 -0
  408. package/dist/modules/workflows/components/run/RunEventBadge.js.map +7 -0
  409. package/dist/modules/workflows/components/run/RunGantt.js +130 -0
  410. package/dist/modules/workflows/components/run/RunGantt.js.map +7 -0
  411. package/dist/modules/workflows/components/run/RunStatusBadge.js +82 -0
  412. package/dist/modules/workflows/components/run/RunStatusBadge.js.map +7 -0
  413. package/dist/modules/workflows/components/run/RunStepInspector.js +116 -0
  414. package/dist/modules/workflows/components/run/RunStepInspector.js.map +7 -0
  415. package/dist/modules/workflows/components/run/WouldDoReport.js +52 -0
  416. package/dist/modules/workflows/components/run/WouldDoReport.js.map +7 -0
  417. package/dist/modules/workflows/components/run/useAgentLabels.js +28 -0
  418. package/dist/modules/workflows/components/run/useAgentLabels.js.map +7 -0
  419. package/dist/modules/workflows/components/run/useLastRunOverlay.js +89 -0
  420. package/dist/modules/workflows/components/run/useLastRunOverlay.js.map +7 -0
  421. package/dist/modules/workflows/components/run/useLiveAgentActions.js +41 -0
  422. package/dist/modules/workflows/components/run/useLiveAgentActions.js.map +7 -0
  423. package/dist/modules/workflows/components/run/useLiveRunUpdates.js +57 -0
  424. package/dist/modules/workflows/components/run/useLiveRunUpdates.js.map +7 -0
  425. package/dist/modules/workflows/components/settings/CommandSettingsPageClient.js +156 -0
  426. package/dist/modules/workflows/components/settings/CommandSettingsPageClient.js.map +7 -0
  427. package/dist/modules/workflows/components/work-inbox/EntityContextPanel.js +72 -0
  428. package/dist/modules/workflows/components/work-inbox/EntityContextPanel.js.map +7 -0
  429. package/dist/modules/workflows/components/work-inbox/ReassignTaskDialog.js +156 -0
  430. package/dist/modules/workflows/components/work-inbox/ReassignTaskDialog.js.map +7 -0
  431. package/dist/modules/workflows/components/work-inbox/StatusChip.js +46 -0
  432. package/dist/modules/workflows/components/work-inbox/StatusChip.js.map +7 -0
  433. package/dist/modules/workflows/components/work-inbox/TaskActionNotice.js +53 -0
  434. package/dist/modules/workflows/components/work-inbox/TaskActionNotice.js.map +7 -0
  435. package/dist/modules/workflows/components/work-inbox/TaskFormFields.js +261 -0
  436. package/dist/modules/workflows/components/work-inbox/TaskFormFields.js.map +7 -0
  437. package/dist/modules/workflows/components/work-inbox/WorkInboxEmptyState.js +27 -0
  438. package/dist/modules/workflows/components/work-inbox/WorkInboxEmptyState.js.map +7 -0
  439. package/dist/modules/workflows/data/activity-config-schemas.js +191 -0
  440. package/dist/modules/workflows/data/activity-config-schemas.js.map +7 -0
  441. package/dist/modules/workflows/data/activity-config-warnings.js +42 -0
  442. package/dist/modules/workflows/data/activity-config-warnings.js.map +7 -0
  443. package/dist/modules/workflows/data/branching-route-warnings.js +65 -0
  444. package/dist/modules/workflows/data/branching-route-warnings.js.map +7 -0
  445. package/dist/modules/workflows/data/entities.js +144 -4
  446. package/dist/modules/workflows/data/entities.js.map +2 -2
  447. package/dist/modules/workflows/data/metrics-validators.js +35 -0
  448. package/dist/modules/workflows/data/metrics-validators.js.map +7 -0
  449. package/dist/modules/workflows/data/task-primitives.js +14 -0
  450. package/dist/modules/workflows/data/task-primitives.js.map +7 -0
  451. package/dist/modules/workflows/data/validators.js +504 -61
  452. package/dist/modules/workflows/data/validators.js.map +3 -3
  453. package/dist/modules/workflows/di.js +16 -1
  454. package/dist/modules/workflows/di.js.map +2 -2
  455. package/dist/modules/workflows/events.js +66 -8
  456. package/dist/modules/workflows/events.js.map +2 -2
  457. package/dist/modules/workflows/examples/oze-residential-install-60-nodes.json +1545 -0
  458. package/dist/modules/workflows/examples/sales-pipeline-definition.json +35 -35
  459. package/dist/modules/workflows/examples/templates/lead-to-install.json +160 -0
  460. package/dist/modules/workflows/examples/templates/order-approval.json +230 -0
  461. package/dist/modules/workflows/examples/templates/task-escalation.json +110 -0
  462. package/dist/modules/workflows/examples/templates/webhook-integration.json +113 -0
  463. package/dist/modules/workflows/extension-points.js +1 -1
  464. package/dist/modules/workflows/extension-points.js.map +2 -2
  465. package/dist/modules/workflows/frontend/[orgSlug]/portal/tasks/[id]/page.js +144 -0
  466. package/dist/modules/workflows/frontend/[orgSlug]/portal/tasks/[id]/page.js.map +7 -0
  467. package/dist/modules/workflows/frontend/[orgSlug]/portal/tasks/[id]/page.meta.js +12 -0
  468. package/dist/modules/workflows/frontend/[orgSlug]/portal/tasks/[id]/page.meta.js.map +7 -0
  469. package/dist/modules/workflows/frontend/[orgSlug]/portal/tasks/page.js +114 -0
  470. package/dist/modules/workflows/frontend/[orgSlug]/portal/tasks/page.js.map +7 -0
  471. package/dist/modules/workflows/frontend/[orgSlug]/portal/tasks/page.meta.js +18 -0
  472. package/dist/modules/workflows/frontend/[orgSlug]/portal/tasks/page.meta.js.map +7 -0
  473. package/dist/modules/workflows/lib/activity-executor.js +505 -137
  474. package/dist/modules/workflows/lib/activity-executor.js.map +3 -3
  475. package/dist/modules/workflows/lib/activity-queue-types.js +3 -1
  476. package/dist/modules/workflows/lib/activity-queue-types.js.map +2 -2
  477. package/dist/modules/workflows/lib/activity-registry-bootstrap.js +2 -0
  478. package/dist/modules/workflows/lib/activity-registry-bootstrap.js.map +7 -0
  479. package/dist/modules/workflows/lib/activity-registry.js +27 -0
  480. package/dist/modules/workflows/lib/activity-registry.js.map +7 -0
  481. package/dist/modules/workflows/lib/activity-types.js +291 -0
  482. package/dist/modules/workflows/lib/activity-types.js.map +7 -0
  483. package/dist/modules/workflows/lib/activity-worker-handler.js +456 -32
  484. package/dist/modules/workflows/lib/activity-worker-handler.js.map +3 -3
  485. package/dist/modules/workflows/lib/advanced-config.js +31 -0
  486. package/dist/modules/workflows/lib/advanced-config.js.map +7 -0
  487. package/dist/modules/workflows/lib/agent-disposition-task.js +198 -0
  488. package/dist/modules/workflows/lib/agent-disposition-task.js.map +7 -0
  489. package/dist/modules/workflows/lib/agent-outcome-paths.js +82 -0
  490. package/dist/modules/workflows/lib/agent-outcome-paths.js.map +7 -0
  491. package/dist/modules/workflows/lib/agent-result-mapping.js +54 -0
  492. package/dist/modules/workflows/lib/agent-result-mapping.js.map +7 -0
  493. package/dist/modules/workflows/lib/agent-review-inspector.js +61 -0
  494. package/dist/modules/workflows/lib/agent-review-inspector.js.map +7 -0
  495. package/dist/modules/workflows/lib/agent-review.js +66 -0
  496. package/dist/modules/workflows/lib/agent-review.js.map +7 -0
  497. package/dist/modules/workflows/lib/ai-authoring.js +155 -0
  498. package/dist/modules/workflows/lib/ai-authoring.js.map +7 -0
  499. package/dist/modules/workflows/lib/ai-draft-runner.js +43 -0
  500. package/dist/modules/workflows/lib/ai-draft-runner.js.map +7 -0
  501. package/dist/modules/workflows/lib/annotation-events.js +10 -0
  502. package/dist/modules/workflows/lib/annotation-events.js.map +7 -0
  503. package/dist/modules/workflows/lib/branching-routes.js +182 -0
  504. package/dist/modules/workflows/lib/branching-routes.js.map +7 -0
  505. package/dist/modules/workflows/lib/breach-routing.js +50 -0
  506. package/dist/modules/workflows/lib/breach-routing.js.map +7 -0
  507. package/dist/modules/workflows/lib/bulk-replay.js +101 -0
  508. package/dist/modules/workflows/lib/bulk-replay.js.map +7 -0
  509. package/dist/modules/workflows/lib/business-rule-usage.js +91 -0
  510. package/dist/modules/workflows/lib/business-rule-usage.js.map +7 -0
  511. package/dist/modules/workflows/lib/caller-graph.js +53 -0
  512. package/dist/modules/workflows/lib/caller-graph.js.map +7 -0
  513. package/dist/modules/workflows/lib/code-view-apply.js +86 -0
  514. package/dist/modules/workflows/lib/code-view-apply.js.map +7 -0
  515. package/dist/modules/workflows/lib/collect-validation-issues.js +164 -0
  516. package/dist/modules/workflows/lib/collect-validation-issues.js.map +7 -0
  517. package/dist/modules/workflows/lib/compensation-ghosts.js +72 -0
  518. package/dist/modules/workflows/lib/compensation-ghosts.js.map +7 -0
  519. package/dist/modules/workflows/lib/component-guard.js +7 -0
  520. package/dist/modules/workflows/lib/component-guard.js.map +7 -0
  521. package/dist/modules/workflows/lib/condition-handler.js +443 -0
  522. package/dist/modules/workflows/lib/condition-handler.js.map +7 -0
  523. package/dist/modules/workflows/lib/context-ledger.js +448 -0
  524. package/dist/modules/workflows/lib/context-ledger.js.map +7 -0
  525. package/dist/modules/workflows/lib/crud-form-dialogs-flag.js +8 -0
  526. package/dist/modules/workflows/lib/crud-form-dialogs-flag.js.map +7 -0
  527. package/dist/modules/workflows/lib/data-edge-mapping.js +63 -0
  528. package/dist/modules/workflows/lib/data-edge-mapping.js.map +7 -0
  529. package/dist/modules/workflows/lib/definition-context-schema.js +56 -0
  530. package/dist/modules/workflows/lib/definition-context-schema.js.map +7 -0
  531. package/dist/modules/workflows/lib/definition-edit-safety.js +123 -0
  532. package/dist/modules/workflows/lib/definition-edit-safety.js.map +7 -0
  533. package/dist/modules/workflows/lib/definition-error-body.js +33 -0
  534. package/dist/modules/workflows/lib/definition-error-body.js.map +7 -0
  535. package/dist/modules/workflows/lib/definition-evaluation.js +79 -0
  536. package/dist/modules/workflows/lib/definition-evaluation.js.map +7 -0
  537. package/dist/modules/workflows/lib/definition-grant.js +90 -0
  538. package/dist/modules/workflows/lib/definition-grant.js.map +7 -0
  539. package/dist/modules/workflows/lib/definition-json-locations.js +139 -0
  540. package/dist/modules/workflows/lib/definition-json-locations.js.map +7 -0
  541. package/dist/modules/workflows/lib/definition-payload.js +31 -0
  542. package/dist/modules/workflows/lib/definition-payload.js.map +7 -0
  543. package/dist/modules/workflows/lib/draft-restore.js +49 -0
  544. package/dist/modules/workflows/lib/draft-restore.js.map +7 -0
  545. package/dist/modules/workflows/lib/dry-run.js +106 -0
  546. package/dist/modules/workflows/lib/dry-run.js.map +7 -0
  547. package/dist/modules/workflows/lib/duration.js +66 -17
  548. package/dist/modules/workflows/lib/duration.js.map +2 -2
  549. package/dist/modules/workflows/lib/edge-reattachment.js +79 -0
  550. package/dist/modules/workflows/lib/edge-reattachment.js.map +7 -0
  551. package/dist/modules/workflows/lib/edgeFormTransforms.js +7 -11
  552. package/dist/modules/workflows/lib/edgeFormTransforms.js.map +2 -2
  553. package/dist/modules/workflows/lib/editor-annotations.js +195 -0
  554. package/dist/modules/workflows/lib/editor-annotations.js.map +7 -0
  555. package/dist/modules/workflows/lib/editor-commands.js +103 -0
  556. package/dist/modules/workflows/lib/editor-commands.js.map +7 -0
  557. package/dist/modules/workflows/lib/editor-history.js +51 -0
  558. package/dist/modules/workflows/lib/editor-history.js.map +7 -0
  559. package/dist/modules/workflows/lib/endpoint-catalog.js +181 -0
  560. package/dist/modules/workflows/lib/endpoint-catalog.js.map +7 -0
  561. package/dist/modules/workflows/lib/endpoint-path.js +90 -0
  562. package/dist/modules/workflows/lib/endpoint-path.js.map +7 -0
  563. package/dist/modules/workflows/lib/engine-version.js +42 -0
  564. package/dist/modules/workflows/lib/engine-version.js.map +7 -0
  565. package/dist/modules/workflows/lib/error-handler.js +132 -0
  566. package/dist/modules/workflows/lib/error-handler.js.map +7 -0
  567. package/dist/modules/workflows/lib/error-routing.js +104 -0
  568. package/dist/modules/workflows/lib/error-routing.js.map +7 -0
  569. package/dist/modules/workflows/lib/event-logger.js +23 -0
  570. package/dist/modules/workflows/lib/event-logger.js.map +2 -2
  571. package/dist/modules/workflows/lib/expression-refs.js +168 -0
  572. package/dist/modules/workflows/lib/expression-refs.js.map +7 -0
  573. package/dist/modules/workflows/lib/failure-grouping.js +62 -0
  574. package/dist/modules/workflows/lib/failure-grouping.js.map +7 -0
  575. package/dist/modules/workflows/lib/find-definition.js +1 -0
  576. package/dist/modules/workflows/lib/find-definition.js.map +2 -2
  577. package/dist/modules/workflows/lib/flow-logic-warnings.js +338 -0
  578. package/dist/modules/workflows/lib/flow-logic-warnings.js.map +7 -0
  579. package/dist/modules/workflows/lib/graph-utils.js +328 -77
  580. package/dist/modules/workflows/lib/graph-utils.js.map +2 -2
  581. package/dist/modules/workflows/lib/icon-search.js +32 -0
  582. package/dist/modules/workflows/lib/icon-search.js.map +7 -0
  583. package/dist/modules/workflows/lib/insert-at-cursor.js +26 -0
  584. package/dist/modules/workflows/lib/insert-at-cursor.js.map +7 -0
  585. package/dist/modules/workflows/lib/instance-date-filter.js +28 -0
  586. package/dist/modules/workflows/lib/instance-date-filter.js.map +7 -0
  587. package/dist/modules/workflows/lib/interpolation-pipeline.js +271 -0
  588. package/dist/modules/workflows/lib/interpolation-pipeline.js.map +7 -0
  589. package/dist/modules/workflows/lib/ledger-drag.js +28 -0
  590. package/dist/modules/workflows/lib/ledger-drag.js.map +7 -0
  591. package/dist/modules/workflows/lib/ledger-entry-display.js +66 -0
  592. package/dist/modules/workflows/lib/ledger-entry-display.js.map +7 -0
  593. package/dist/modules/workflows/lib/ledger-schema-flatten.js +82 -0
  594. package/dist/modules/workflows/lib/ledger-schema-flatten.js.map +7 -0
  595. package/dist/modules/workflows/lib/metrics/definition-metrics.js +110 -0
  596. package/dist/modules/workflows/lib/metrics/definition-metrics.js.map +7 -0
  597. package/dist/modules/workflows/lib/metrics/metrics-display.js +26 -0
  598. package/dist/modules/workflows/lib/metrics/metrics-display.js.map +7 -0
  599. package/dist/modules/workflows/lib/metrics/rollup-schedule.js +7 -0
  600. package/dist/modules/workflows/lib/metrics/rollup-schedule.js.map +7 -0
  601. package/dist/modules/workflows/lib/metrics/rollup-service.js +160 -0
  602. package/dist/modules/workflows/lib/metrics/rollup-service.js.map +7 -0
  603. package/dist/modules/workflows/lib/node-config-summary.js +128 -0
  604. package/dist/modules/workflows/lib/node-config-summary.js.map +7 -0
  605. package/dist/modules/workflows/lib/node-geometry.js +53 -0
  606. package/dist/modules/workflows/lib/node-geometry.js.map +7 -0
  607. package/dist/modules/workflows/lib/node-nudge.js +44 -0
  608. package/dist/modules/workflows/lib/node-nudge.js.map +7 -0
  609. package/dist/modules/workflows/lib/node-outcome-rows.js +88 -0
  610. package/dist/modules/workflows/lib/node-outcome-rows.js.map +7 -0
  611. package/dist/modules/workflows/lib/node-placement.js +55 -0
  612. package/dist/modules/workflows/lib/node-placement.js.map +7 -0
  613. package/dist/modules/workflows/lib/node-type-icons.js +54 -13
  614. package/dist/modules/workflows/lib/node-type-icons.js.map +2 -2
  615. package/dist/modules/workflows/lib/nodeFormTransforms.js +329 -19
  616. package/dist/modules/workflows/lib/nodeFormTransforms.js.map +2 -2
  617. package/dist/modules/workflows/lib/outcome-routing.js +158 -0
  618. package/dist/modules/workflows/lib/outcome-routing.js.map +7 -0
  619. package/dist/modules/workflows/lib/owned-definition.js +107 -0
  620. package/dist/modules/workflows/lib/owned-definition.js.map +7 -0
  621. package/dist/modules/workflows/lib/owned-node-changes.js +10 -0
  622. package/dist/modules/workflows/lib/owned-node-changes.js.map +7 -0
  623. package/dist/modules/workflows/lib/palette-drag.js +36 -0
  624. package/dist/modules/workflows/lib/palette-drag.js.map +7 -0
  625. package/dist/modules/workflows/lib/palette-drop.js +45 -0
  626. package/dist/modules/workflows/lib/palette-drop.js.map +7 -0
  627. package/dist/modules/workflows/lib/parallel-handler.js +57 -2
  628. package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
  629. package/dist/modules/workflows/lib/port-contract.js +54 -0
  630. package/dist/modules/workflows/lib/port-contract.js.map +7 -0
  631. package/dist/modules/workflows/lib/portal-task-access.js +89 -0
  632. package/dist/modules/workflows/lib/portal-task-access.js.map +7 -0
  633. package/dist/modules/workflows/lib/rerun-from-step.js +65 -0
  634. package/dist/modules/workflows/lib/rerun-from-step.js.map +7 -0
  635. package/dist/modules/workflows/lib/route-chip-events.js +23 -0
  636. package/dist/modules/workflows/lib/route-chip-events.js.map +7 -0
  637. package/dist/modules/workflows/lib/route-chips.js +91 -0
  638. package/dist/modules/workflows/lib/route-chips.js.map +7 -0
  639. package/dist/modules/workflows/lib/route-edge.js +17 -0
  640. package/dist/modules/workflows/lib/route-edge.js.map +7 -0
  641. package/dist/modules/workflows/lib/route-kinds.js +67 -0
  642. package/dist/modules/workflows/lib/route-kinds.js.map +7 -0
  643. package/dist/modules/workflows/lib/route-priority.js +104 -0
  644. package/dist/modules/workflows/lib/route-priority.js.map +7 -0
  645. package/dist/modules/workflows/lib/run-duration.js +44 -0
  646. package/dist/modules/workflows/lib/run-duration.js.map +7 -0
  647. package/dist/modules/workflows/lib/run-event-tone.js +25 -0
  648. package/dist/modules/workflows/lib/run-event-tone.js.map +7 -0
  649. package/dist/modules/workflows/lib/run-execution.js +305 -0
  650. package/dist/modules/workflows/lib/run-execution.js.map +7 -0
  651. package/dist/modules/workflows/lib/run-gantt.js +180 -0
  652. package/dist/modules/workflows/lib/run-gantt.js.map +7 -0
  653. package/dist/modules/workflows/lib/run-outcome-evidence.js +33 -0
  654. package/dist/modules/workflows/lib/run-outcome-evidence.js.map +7 -0
  655. package/dist/modules/workflows/lib/run-outcome.js +48 -0
  656. package/dist/modules/workflows/lib/run-outcome.js.map +7 -0
  657. package/dist/modules/workflows/lib/sample-resolver.js +71 -0
  658. package/dist/modules/workflows/lib/sample-resolver.js.map +7 -0
  659. package/dist/modules/workflows/lib/seeds.js +1 -1
  660. package/dist/modules/workflows/lib/seeds.js.map +2 -2
  661. package/dist/modules/workflows/lib/server-output-contract.js +65 -0
  662. package/dist/modules/workflows/lib/server-output-contract.js.map +7 -0
  663. package/dist/modules/workflows/lib/set-variable.js +47 -0
  664. package/dist/modules/workflows/lib/set-variable.js.map +7 -0
  665. package/dist/modules/workflows/lib/signal-handler.js +63 -4
  666. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  667. package/dist/modules/workflows/lib/start-fixtures.js +42 -0
  668. package/dist/modules/workflows/lib/start-fixtures.js.map +7 -0
  669. package/dist/modules/workflows/lib/status-colors.js +153 -22
  670. package/dist/modules/workflows/lib/status-colors.js.map +2 -2
  671. package/dist/modules/workflows/lib/step-handler.js +529 -53
  672. package/dist/modules/workflows/lib/step-handler.js.map +3 -3
  673. package/dist/modules/workflows/lib/step-presentation.js +147 -0
  674. package/dist/modules/workflows/lib/step-presentation.js.map +7 -0
  675. package/dist/modules/workflows/lib/step-through.js +26 -0
  676. package/dist/modules/workflows/lib/step-through.js.map +7 -0
  677. package/dist/modules/workflows/lib/step-type-conversion.js +167 -0
  678. package/dist/modules/workflows/lib/step-type-conversion.js.map +7 -0
  679. package/dist/modules/workflows/lib/subgraph-clipboard.js +114 -0
  680. package/dist/modules/workflows/lib/subgraph-clipboard.js.map +7 -0
  681. package/dist/modules/workflows/lib/task-decision-context.js +38 -0
  682. package/dist/modules/workflows/lib/task-decision-context.js.map +7 -0
  683. package/dist/modules/workflows/lib/task-decisions.js +49 -0
  684. package/dist/modules/workflows/lib/task-decisions.js.map +7 -0
  685. package/dist/modules/workflows/lib/task-entity-access.js +62 -0
  686. package/dist/modules/workflows/lib/task-entity-access.js.map +7 -0
  687. package/dist/modules/workflows/lib/task-entity-aliases.js +39 -0
  688. package/dist/modules/workflows/lib/task-entity-aliases.js.map +7 -0
  689. package/dist/modules/workflows/lib/task-entity-types.js +36 -0
  690. package/dist/modules/workflows/lib/task-entity-types.js.map +7 -0
  691. package/dist/modules/workflows/lib/task-form-registry.js +33 -0
  692. package/dist/modules/workflows/lib/task-form-registry.js.map +7 -0
  693. package/dist/modules/workflows/lib/task-form-schema.js +75 -0
  694. package/dist/modules/workflows/lib/task-form-schema.js.map +7 -0
  695. package/dist/modules/workflows/lib/task-handler.js +251 -32
  696. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  697. package/dist/modules/workflows/lib/task-inspector-config.js +182 -0
  698. package/dist/modules/workflows/lib/task-inspector-config.js.map +7 -0
  699. package/dist/modules/workflows/lib/task-list-query.js +19 -0
  700. package/dist/modules/workflows/lib/task-list-query.js.map +7 -0
  701. package/dist/modules/workflows/lib/task-notifications.js +119 -0
  702. package/dist/modules/workflows/lib/task-notifications.js.map +7 -0
  703. package/dist/modules/workflows/lib/task-permission-settings.js +43 -0
  704. package/dist/modules/workflows/lib/task-permission-settings.js.map +7 -0
  705. package/dist/modules/workflows/lib/task-presets.js +35 -0
  706. package/dist/modules/workflows/lib/task-presets.js.map +7 -0
  707. package/dist/modules/workflows/lib/task-quick-action.js +45 -0
  708. package/dist/modules/workflows/lib/task-quick-action.js.map +7 -0
  709. package/dist/modules/workflows/lib/task-resolution.js +120 -0
  710. package/dist/modules/workflows/lib/task-resolution.js.map +7 -0
  711. package/dist/modules/workflows/lib/task-sla.js +357 -0
  712. package/dist/modules/workflows/lib/task-sla.js.map +7 -0
  713. package/dist/modules/workflows/lib/task-visibility-request.js +266 -0
  714. package/dist/modules/workflows/lib/task-visibility-request.js.map +7 -0
  715. package/dist/modules/workflows/lib/task-visibility.js +194 -0
  716. package/dist/modules/workflows/lib/task-visibility.js.map +7 -0
  717. package/dist/modules/workflows/lib/timer-handler.js +3 -1
  718. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  719. package/dist/modules/workflows/lib/transition-handler.js +148 -20
  720. package/dist/modules/workflows/lib/transition-handler.js.map +2 -2
  721. package/dist/modules/workflows/lib/trigger-node.js +121 -0
  722. package/dist/modules/workflows/lib/trigger-node.js.map +7 -0
  723. package/dist/modules/workflows/lib/visual-editor-navigation.js +14 -0
  724. package/dist/modules/workflows/lib/visual-editor-navigation.js.map +7 -0
  725. package/dist/modules/workflows/lib/work-inbox/empty-state.js +52 -0
  726. package/dist/modules/workflows/lib/work-inbox/empty-state.js.map +7 -0
  727. package/dist/modules/workflows/lib/work-inbox/entity-links.js +63 -0
  728. package/dist/modules/workflows/lib/work-inbox/entity-links.js.map +7 -0
  729. package/dist/modules/workflows/lib/work-inbox/navigation.js +11 -0
  730. package/dist/modules/workflows/lib/work-inbox/navigation.js.map +7 -0
  731. package/dist/modules/workflows/lib/work-inbox/presentation.js +90 -0
  732. package/dist/modules/workflows/lib/work-inbox/presentation.js.map +7 -0
  733. package/dist/modules/workflows/lib/work-inbox/provider.js +118 -0
  734. package/dist/modules/workflows/lib/work-inbox/provider.js.map +7 -0
  735. package/dist/modules/workflows/lib/work-inbox/query.js +70 -0
  736. package/dist/modules/workflows/lib/work-inbox/query.js.map +7 -0
  737. package/dist/modules/workflows/lib/work-inbox/service.js +56 -0
  738. package/dist/modules/workflows/lib/work-inbox/service.js.map +7 -0
  739. package/dist/modules/workflows/lib/work-inbox/user-task-source.js +149 -0
  740. package/dist/modules/workflows/lib/work-inbox/user-task-source.js.map +7 -0
  741. package/dist/modules/workflows/lib/workflow-command-enablement.js +57 -0
  742. package/dist/modules/workflows/lib/workflow-command-enablement.js.map +7 -0
  743. package/dist/modules/workflows/lib/workflow-command-settings.js +54 -0
  744. package/dist/modules/workflows/lib/workflow-command-settings.js.map +7 -0
  745. package/dist/modules/workflows/lib/workflow-executor.js +658 -6
  746. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  747. package/dist/modules/workflows/lib/workflow-function-registry.js +40 -0
  748. package/dist/modules/workflows/lib/workflow-function-registry.js.map +7 -0
  749. package/dist/modules/workflows/lib/workflow-safe-commands.js +11 -1
  750. package/dist/modules/workflows/lib/workflow-safe-commands.js.map +2 -2
  751. package/dist/modules/workflows/lib/workflow-templates.js +69 -0
  752. package/dist/modules/workflows/lib/workflow-templates.js.map +7 -0
  753. package/dist/modules/workflows/migrations/Migration20260626214855_workflows.js +15 -0
  754. package/dist/modules/workflows/migrations/Migration20260626214855_workflows.js.map +7 -0
  755. package/dist/modules/workflows/migrations/Migration20260626222424_workflows.js +17 -0
  756. package/dist/modules/workflows/migrations/Migration20260626222424_workflows.js.map +7 -0
  757. package/dist/modules/workflows/migrations/Migration20260727074335_workflows.js +15 -0
  758. package/dist/modules/workflows/migrations/Migration20260727074335_workflows.js.map +7 -0
  759. package/dist/modules/workflows/migrations/Migration20260728104038_workflows.js +13 -0
  760. package/dist/modules/workflows/migrations/Migration20260728104038_workflows.js.map +7 -0
  761. package/dist/modules/workflows/migrations/Migration20260728163001_workflows.js +15 -0
  762. package/dist/modules/workflows/migrations/Migration20260728163001_workflows.js.map +7 -0
  763. package/dist/modules/workflows/migrations/Migration20260729061736_workflows.js +13 -0
  764. package/dist/modules/workflows/migrations/Migration20260729061736_workflows.js.map +7 -0
  765. package/dist/modules/workflows/migrations/Migration20260729192652_workflows.js +12 -0
  766. package/dist/modules/workflows/migrations/Migration20260729192652_workflows.js.map +7 -0
  767. package/dist/modules/workflows/migrations/Migration20260730085000_workflows.js +13 -0
  768. package/dist/modules/workflows/migrations/Migration20260730085000_workflows.js.map +7 -0
  769. package/dist/modules/workflows/migrations/Migration20260730092706_workflows.js +13 -0
  770. package/dist/modules/workflows/migrations/Migration20260730092706_workflows.js.map +7 -0
  771. package/dist/modules/workflows/notifications.js +38 -10
  772. package/dist/modules/workflows/notifications.js.map +2 -2
  773. package/dist/modules/workflows/setup.js +81 -1
  774. package/dist/modules/workflows/setup.js.map +2 -2
  775. package/dist/modules/workflows/subscribers/task-assigned-notification.js +19 -27
  776. package/dist/modules/workflows/subscribers/task-assigned-notification.js.map +2 -2
  777. package/dist/modules/workflows/subscribers/task-deadline-breached-notification.js +24 -0
  778. package/dist/modules/workflows/subscribers/task-deadline-breached-notification.js.map +7 -0
  779. package/dist/modules/workflows/subscribers/task-reminder-notification.js +24 -0
  780. package/dist/modules/workflows/subscribers/task-reminder-notification.js.map +7 -0
  781. package/dist/modules/workflows/widgets/injection/pending-work/widget.client.js +73 -0
  782. package/dist/modules/workflows/widgets/injection/pending-work/widget.client.js.map +7 -0
  783. package/dist/modules/workflows/widgets/injection/pending-work/widget.js +17 -0
  784. package/dist/modules/workflows/widgets/injection/pending-work/widget.js.map +7 -0
  785. package/dist/modules/workflows/widgets/injection-table.js +26 -0
  786. package/dist/modules/workflows/widgets/injection-table.js.map +2 -2
  787. package/dist/modules/workflows/workers/workflow-activities.worker.js +61 -39
  788. package/dist/modules/workflows/workers/workflow-activities.worker.js.map +2 -2
  789. package/dist/modules/workflows/workers/workflow-definition-metric-rollup.worker.js +40 -0
  790. package/dist/modules/workflows/workers/workflow-definition-metric-rollup.worker.js.map +7 -0
  791. package/dist/modules/workflows/workers/workflow-instance-bulk-replay.js +43 -0
  792. package/dist/modules/workflows/workers/workflow-instance-bulk-replay.js.map +7 -0
  793. package/dist/modules/workflows/workers/workflow-invoke-agent.worker.js +30 -0
  794. package/dist/modules/workflows/workers/workflow-invoke-agent.worker.js.map +7 -0
  795. package/generated/entities/action_log/index.ts +1 -0
  796. package/generated/entities/user/index.ts +1 -0
  797. package/generated/entities/user_task/index.ts +7 -0
  798. package/generated/entities/workflow_definition/index.ts +3 -0
  799. package/generated/entities/workflow_definition_draft/index.ts +11 -0
  800. package/generated/entities/workflow_definition_metric_rollup/index.ts +10 -0
  801. package/generated/entities/workflow_instance/index.ts +2 -0
  802. package/generated/entities.ids.generated.ts +4 -1
  803. package/generated/entity-fields-registry.ts +39 -0
  804. package/jest.setup.ts +13 -0
  805. package/package.json +8 -7
  806. package/src/helpers/integration/workflowsFixtures.ts +765 -5
  807. package/src/helpers/integration/workflowsUi.ts +318 -0
  808. package/src/modules/attachments/lib/createFromBuffer.ts +120 -0
  809. package/src/modules/audit_logs/data/entities.ts +12 -0
  810. package/src/modules/audit_logs/data/validators.ts +1 -0
  811. package/src/modules/audit_logs/lib/projections.ts +5 -1
  812. package/src/modules/audit_logs/migrations/.snapshot-open-mercato.json +26 -0
  813. package/src/modules/audit_logs/migrations/Migration20260625120000.ts +15 -0
  814. package/src/modules/audit_logs/services/actionLogService.ts +3 -0
  815. package/src/modules/auth/data/entities.ts +21 -0
  816. package/src/modules/auth/i18n/de.json +31 -0
  817. package/src/modules/auth/i18n/en.json +31 -0
  818. package/src/modules/auth/i18n/es.json +31 -0
  819. package/src/modules/auth/i18n/ko.json +31 -0
  820. package/src/modules/auth/i18n/pl.json +31 -0
  821. package/src/modules/auth/lib/executionPrincipal.ts +235 -0
  822. package/src/modules/auth/migrations/.snapshot-open-mercato.json +16 -0
  823. package/src/modules/auth/migrations/Migration20260625050000.ts +21 -0
  824. package/src/modules/business_rules/components/InlineRuleEditor.tsx +231 -0
  825. package/src/modules/business_rules/data/validators.ts +6 -0
  826. package/src/modules/business_rules/i18n/de.json +4 -0
  827. package/src/modules/business_rules/i18n/en.json +4 -0
  828. package/src/modules/business_rules/i18n/es.json +4 -0
  829. package/src/modules/business_rules/i18n/ko.json +4 -0
  830. package/src/modules/business_rules/i18n/pl.json +4 -0
  831. package/src/modules/business_rules/lib/rule-engine.ts +15 -1
  832. package/src/modules/catalog/commands/products.ts +12 -0
  833. package/src/modules/catalog/i18n/de.json +1 -0
  834. package/src/modules/catalog/i18n/en.json +1 -0
  835. package/src/modules/catalog/i18n/es.json +1 -0
  836. package/src/modules/catalog/i18n/ko.json +1 -0
  837. package/src/modules/catalog/i18n/pl.json +1 -0
  838. package/src/modules/catalog/workflows.ts +35 -0
  839. package/src/modules/customer_accounts/AGENTS.md +11 -0
  840. package/src/modules/customer_accounts/backend/customer_accounts/roles/[id]/page.tsx +2 -0
  841. package/src/modules/customer_accounts/cli.ts +96 -0
  842. package/src/modules/customer_accounts/i18n/de.json +5 -0
  843. package/src/modules/customer_accounts/i18n/en.json +5 -0
  844. package/src/modules/customer_accounts/i18n/es.json +5 -0
  845. package/src/modules/customer_accounts/i18n/ko.json +5 -0
  846. package/src/modules/customer_accounts/i18n/pl.json +5 -0
  847. package/src/modules/customer_accounts/lib/customerRoleAclSync.ts +92 -0
  848. package/src/modules/customer_accounts/setup.ts +15 -3
  849. package/src/modules/customers/commands/deals.ts +5 -0
  850. package/src/modules/customers/components/detail/ChangelogEntryRow.tsx +4 -2
  851. package/src/modules/customers/components/detail/utils.ts +2 -0
  852. package/src/modules/customers/events.ts +21 -3
  853. package/src/modules/customers/i18n/de.json +4 -0
  854. package/src/modules/customers/i18n/en.json +4 -0
  855. package/src/modules/customers/i18n/es.json +4 -0
  856. package/src/modules/customers/i18n/ko.json +4 -0
  857. package/src/modules/customers/i18n/pl.json +4 -0
  858. package/src/modules/customers/lib/link-workflow-task-handler.ts +136 -0
  859. package/src/modules/customers/lib/todoCompatibility.ts +4 -1
  860. package/src/modules/customers/lib/workflowTaskLink.ts +23 -0
  861. package/src/modules/customers/subscribers/link-workflow-task.ts +19 -0
  862. package/src/modules/customers/workflows.ts +57 -0
  863. package/src/modules/entities/api/records.ts +18 -62
  864. package/src/modules/entities/lib/entityClassification.ts +102 -0
  865. package/src/modules/sales/commands/documents.ts +46 -0
  866. package/src/modules/sales/events.ts +20 -2
  867. package/src/modules/sales/i18n/de.json +2 -1
  868. package/src/modules/sales/i18n/en.json +2 -1
  869. package/src/modules/sales/i18n/es.json +2 -1
  870. package/src/modules/sales/i18n/ko.json +2 -1
  871. package/src/modules/sales/i18n/pl.json +2 -1
  872. package/src/modules/sales/workflows.ts +12 -1
  873. package/src/modules/seeds/README.md +86 -0
  874. package/src/modules/seeds/cli.ts +220 -0
  875. package/src/modules/seeds/examples/sample-seed.json +26 -0
  876. package/src/modules/seeds/index.ts +11 -0
  877. package/src/modules/workflows/AGENTS.md +851 -10
  878. package/src/modules/workflows/acl.ts +96 -0
  879. package/src/modules/workflows/ai-agents.ts +80 -0
  880. package/src/modules/workflows/ai-tools/authoring-pack.ts +798 -0
  881. package/src/modules/workflows/ai-tools/types.ts +117 -0
  882. package/src/modules/workflows/ai-tools.ts +20 -0
  883. package/src/modules/workflows/api/command-settings/route.ts +171 -0
  884. package/src/modules/workflows/api/commands/route.ts +109 -0
  885. package/src/modules/workflows/api/definitions/[id]/callers/route.ts +95 -0
  886. package/src/modules/workflows/api/definitions/[id]/context-schema/route.ts +187 -0
  887. package/src/modules/workflows/api/definitions/[id]/customize/route.ts +6 -1
  888. package/src/modules/workflows/api/definitions/[id]/draft/route.ts +395 -0
  889. package/src/modules/workflows/api/definitions/[id]/publish/route.ts +250 -0
  890. package/src/modules/workflows/api/definitions/[id]/reset-to-code/route.ts +5 -0
  891. package/src/modules/workflows/api/definitions/[id]/route.ts +107 -7
  892. package/src/modules/workflows/api/definitions/[id]/test-step/route.ts +288 -0
  893. package/src/modules/workflows/api/definitions/generate/route.ts +335 -0
  894. package/src/modules/workflows/api/definitions/route.ts +88 -113
  895. package/src/modules/workflows/api/definitions/serialize.ts +9 -0
  896. package/src/modules/workflows/api/endpoints/route.ts +88 -0
  897. package/src/modules/workflows/api/functions/route.ts +91 -0
  898. package/src/modules/workflows/api/grantable-features/route.ts +102 -0
  899. package/src/modules/workflows/api/instances/[id]/context/route.ts +214 -0
  900. package/src/modules/workflows/api/instances/[id]/rerun-step/route.ts +226 -0
  901. package/src/modules/workflows/api/instances/[id]/retry/route.ts +18 -2
  902. package/src/modules/workflows/api/instances/[id]/step-through/route.ts +195 -0
  903. package/src/modules/workflows/api/instances/[id]/steps/route.ts +160 -0
  904. package/src/modules/workflows/api/instances/[id]/would-do/route.ts +216 -0
  905. package/src/modules/workflows/api/instances/bulk-replay/route.ts +141 -0
  906. package/src/modules/workflows/api/instances/failure-queue/route.ts +197 -0
  907. package/src/modules/workflows/api/instances/route.ts +135 -3
  908. package/src/modules/workflows/api/metrics/definitions/route.ts +262 -0
  909. package/src/modules/workflows/api/openapi.ts +549 -2
  910. package/src/modules/workflows/api/portal/tasks/[id]/complete/route.ts +160 -0
  911. package/src/modules/workflows/api/portal/tasks/[id]/route.ts +124 -0
  912. package/src/modules/workflows/api/portal/tasks/route.ts +157 -0
  913. package/src/modules/workflows/api/rule-usage/route.ts +94 -0
  914. package/src/modules/workflows/api/task-settings/route.ts +138 -0
  915. package/src/modules/workflows/api/tasks/[id]/claim/route.ts +42 -17
  916. package/src/modules/workflows/api/tasks/[id]/complete/route.ts +47 -15
  917. package/src/modules/workflows/api/tasks/[id]/reassign/route.ts +197 -0
  918. package/src/modules/workflows/api/tasks/[id]/route.ts +57 -6
  919. package/src/modules/workflows/api/tasks/[id]/unclaim/route.ts +132 -0
  920. package/src/modules/workflows/api/tasks/route.ts +60 -5
  921. package/src/modules/workflows/api/tasks/serialize.ts +119 -0
  922. package/src/modules/workflows/api/templates/route.ts +87 -0
  923. package/src/modules/workflows/api/work-inbox/next/route.ts +170 -0
  924. package/src/modules/workflows/api/work-inbox/route.ts +153 -0
  925. package/src/modules/workflows/backend/config/workflows/page.meta.ts +33 -0
  926. package/src/modules/workflows/backend/config/workflows/page.tsx +12 -0
  927. package/src/modules/workflows/backend/definitions/[id]/page.tsx +19 -343
  928. package/src/modules/workflows/backend/definitions/create/page.meta.ts +1 -1
  929. package/src/modules/workflows/backend/definitions/create/page.tsx +19 -59
  930. package/src/modules/workflows/backend/definitions/page.tsx +156 -76
  931. package/src/modules/workflows/backend/definitions/visual-editor/page.tsx +3129 -584
  932. package/src/modules/workflows/backend/instances/[id]/page.meta.ts +1 -1
  933. package/src/modules/workflows/backend/instances/[id]/page.tsx +711 -539
  934. package/src/modules/workflows/backend/instances/failure-queue/page.meta.ts +16 -0
  935. package/src/modules/workflows/backend/instances/failure-queue/page.tsx +311 -0
  936. package/src/modules/workflows/backend/instances/page.meta.ts +1 -1
  937. package/src/modules/workflows/backend/instances/page.tsx +218 -38
  938. package/src/modules/workflows/backend/tasks/[id]/page.tsx +639 -400
  939. package/src/modules/workflows/backend/tasks/page.meta.ts +7 -0
  940. package/src/modules/workflows/backend/tasks/page.tsx +20 -333
  941. package/src/modules/workflows/backend/work-inbox/page.meta.ts +15 -0
  942. package/src/modules/workflows/backend/work-inbox/page.tsx +506 -0
  943. package/src/modules/workflows/cli.ts +1 -1
  944. package/src/modules/workflows/commands/tasks.ts +146 -0
  945. package/src/modules/workflows/components/ActivitiesEditor.tsx +91 -114
  946. package/src/modules/workflows/components/ActivityEditDialog.tsx +244 -0
  947. package/src/modules/workflows/components/AgentSelector.tsx +200 -0
  948. package/src/modules/workflows/components/AnnotationEditDialog.tsx +157 -0
  949. package/src/modules/workflows/components/BusinessRuleUsagePanel.tsx +106 -0
  950. package/src/modules/workflows/components/BusinessRulesSelector.tsx +71 -17
  951. package/src/modules/workflows/components/ConfigJsonTextarea.tsx +111 -0
  952. package/src/modules/workflows/components/ContextSchemaEditor.tsx +165 -0
  953. package/src/modules/workflows/components/DefinitionErrorHandlerField.tsx +133 -0
  954. package/src/modules/workflows/components/DefinitionMetadataDrawer.tsx +456 -0
  955. package/src/modules/workflows/components/DefinitionMetricsCells.tsx +212 -0
  956. package/src/modules/workflows/components/DefinitionTriggersEditor.tsx +196 -95
  957. package/src/modules/workflows/components/EdgeEditDialog.tsx +15 -16
  958. package/src/modules/workflows/components/EdgeEditDialogCrudForm.tsx +130 -80
  959. package/src/modules/workflows/components/InputDataPanel.tsx +177 -0
  960. package/src/modules/workflows/components/InspectorPanel.tsx +250 -0
  961. package/src/modules/workflows/components/NodeEditDialog.tsx +444 -38
  962. package/src/modules/workflows/components/NodeEditDialogCrudForm.tsx +848 -178
  963. package/src/modules/workflows/components/StepsEditor.tsx +9 -2
  964. package/src/modules/workflows/components/TemplateGalleryDialog.tsx +205 -0
  965. package/src/modules/workflows/components/TransitionsEditor.tsx +98 -89
  966. package/src/modules/workflows/components/TriggersDialog.tsx +83 -0
  967. package/src/modules/workflows/components/TriggersEditor.tsx +363 -0
  968. package/src/modules/workflows/components/WorkflowAiDraftDialog.tsx +383 -0
  969. package/src/modules/workflows/components/WorkflowCodeView.tsx +257 -0
  970. package/src/modules/workflows/components/WorkflowCommandPalette.tsx +82 -0
  971. package/src/modules/workflows/components/WorkflowCompensationGhostEdge.tsx +78 -0
  972. package/src/modules/workflows/components/WorkflowDataMappingEdge.tsx +46 -0
  973. package/src/modules/workflows/components/WorkflowGraph.tsx +54 -1
  974. package/src/modules/workflows/components/WorkflowGraphImpl.tsx +463 -37
  975. package/src/modules/workflows/components/WorkflowIconPicker.tsx +144 -0
  976. package/src/modules/workflows/components/WorkflowLegend.tsx +59 -33
  977. package/src/modules/workflows/components/WorkflowNodeCard.tsx +355 -28
  978. package/src/modules/workflows/components/WorkflowRouteChips.tsx +145 -0
  979. package/src/modules/workflows/components/WorkflowSelector.tsx +33 -14
  980. package/src/modules/workflows/components/WorkflowTransitionEdge.tsx +83 -10
  981. package/src/modules/workflows/components/WorkflowTransitionLabel.tsx +13 -2
  982. package/src/modules/workflows/components/fields/ActivityArrayEditor.tsx +120 -30
  983. package/src/modules/workflows/components/fields/ActivityConfigFields.tsx +675 -0
  984. package/src/modules/workflows/components/fields/ActivityTestPanel.tsx +250 -0
  985. package/src/modules/workflows/components/fields/AgentInvokeConfigField.tsx +580 -0
  986. package/src/modules/workflows/components/fields/AgentReviewOnBreachField.tsx +88 -0
  987. package/src/modules/workflows/components/fields/BranchingRoutesEditor.tsx +323 -0
  988. package/src/modules/workflows/components/fields/BusinessRuleConditionsEditor.tsx +36 -4
  989. package/src/modules/workflows/components/fields/CommandPicker.tsx +158 -0
  990. package/src/modules/workflows/components/fields/EndpointPicker.tsx +330 -0
  991. package/src/modules/workflows/components/fields/FormFieldArrayEditor.tsx +2 -2
  992. package/src/modules/workflows/components/fields/FunctionPicker.tsx +68 -0
  993. package/src/modules/workflows/components/fields/MappingArrayEditor.tsx +46 -12
  994. package/src/modules/workflows/components/fields/PortFieldArrayEditor.tsx +255 -0
  995. package/src/modules/workflows/components/fields/RolesMultiSelect.tsx +68 -0
  996. package/src/modules/workflows/components/fields/RouteOrderEditor.tsx +169 -0
  997. package/src/modules/workflows/components/fields/SchemaBuilderDialog.tsx +139 -0
  998. package/src/modules/workflows/components/fields/StartPreConditionsEditor.tsx +2 -2
  999. package/src/modules/workflows/components/fields/TaskAssignmentField.tsx +355 -0
  1000. package/src/modules/workflows/components/fields/TaskDeadlineFields.tsx +172 -0
  1001. package/src/modules/workflows/components/fields/TaskDecisionsField.tsx +294 -0
  1002. package/src/modules/workflows/components/fields/TaskEntityBindingsField.tsx +156 -0
  1003. package/src/modules/workflows/components/fields/TemplateTextControl.tsx +85 -0
  1004. package/src/modules/workflows/components/fields/VariablePickerButton.tsx +177 -0
  1005. package/src/modules/workflows/components/fields/ledgerDropTarget.ts +55 -0
  1006. package/src/modules/workflows/components/fields/useActivityTypeOptions.ts +19 -0
  1007. package/src/modules/workflows/components/formConfig.tsx +84 -10
  1008. package/src/modules/workflows/components/mobile/MobileDefinitionDetail.tsx +5 -0
  1009. package/src/modules/workflows/components/mobile/MobileMetadataSheet.tsx +10 -0
  1010. package/src/modules/workflows/components/mobile/MobileTaskForm.tsx +55 -19
  1011. package/src/modules/workflows/components/mobile/MobileVisualEditor.tsx +49 -40
  1012. package/src/modules/workflows/components/nodes/AnnotationGroupNode.tsx +81 -0
  1013. package/src/modules/workflows/components/nodes/AutomatedNode.tsx +34 -17
  1014. package/src/modules/workflows/components/nodes/EndNode.tsx +15 -14
  1015. package/src/modules/workflows/components/nodes/ErrorOutputHandle.tsx +32 -0
  1016. package/src/modules/workflows/components/nodes/IfElseNode.tsx +64 -0
  1017. package/src/modules/workflows/components/nodes/InvokeAgentNode.tsx +180 -0
  1018. package/src/modules/workflows/components/nodes/NodeOutcomeRows.tsx +143 -0
  1019. package/src/modules/workflows/components/nodes/ParallelForkNode.tsx +28 -15
  1020. package/src/modules/workflows/components/nodes/ParallelJoinNode.tsx +28 -15
  1021. package/src/modules/workflows/components/nodes/StartNode.tsx +78 -18
  1022. package/src/modules/workflows/components/nodes/StickyNoteNode.tsx +65 -0
  1023. package/src/modules/workflows/components/nodes/SubWorkflowNode.tsx +124 -23
  1024. package/src/modules/workflows/components/nodes/SwitchNode.tsx +64 -0
  1025. package/src/modules/workflows/components/nodes/TriggerCap.tsx +103 -0
  1026. package/src/modules/workflows/components/nodes/TriggerNode.tsx +151 -0
  1027. package/src/modules/workflows/components/nodes/UserTaskNode.tsx +67 -22
  1028. package/src/modules/workflows/components/nodes/WaitForConditionNode.tsx +74 -0
  1029. package/src/modules/workflows/components/nodes/WaitForSignalNode.tsx +31 -17
  1030. package/src/modules/workflows/components/nodes/WaitForTimerNode.tsx +31 -16
  1031. package/src/modules/workflows/components/nodes/index.ts +17 -0
  1032. package/src/modules/workflows/components/portal/PortalTaskForm.tsx +280 -0
  1033. package/src/modules/workflows/components/run/AgentActivityPanel.tsx +48 -0
  1034. package/src/modules/workflows/components/run/RerunStepDialog.tsx +133 -0
  1035. package/src/modules/workflows/components/run/RunEventBadge.tsx +37 -0
  1036. package/src/modules/workflows/components/run/RunGantt.tsx +180 -0
  1037. package/src/modules/workflows/components/run/RunStatusBadge.tsx +112 -0
  1038. package/src/modules/workflows/components/run/RunStepInspector.tsx +176 -0
  1039. package/src/modules/workflows/components/run/WouldDoReport.tsx +93 -0
  1040. package/src/modules/workflows/components/run/useAgentLabels.ts +42 -0
  1041. package/src/modules/workflows/components/run/useLastRunOverlay.ts +150 -0
  1042. package/src/modules/workflows/components/run/useLiveAgentActions.ts +70 -0
  1043. package/src/modules/workflows/components/run/useLiveRunUpdates.ts +89 -0
  1044. package/src/modules/workflows/components/settings/CommandSettingsPageClient.tsx +228 -0
  1045. package/src/modules/workflows/components/work-inbox/EntityContextPanel.tsx +179 -0
  1046. package/src/modules/workflows/components/work-inbox/ReassignTaskDialog.tsx +203 -0
  1047. package/src/modules/workflows/components/work-inbox/StatusChip.tsx +61 -0
  1048. package/src/modules/workflows/components/work-inbox/TaskActionNotice.tsx +77 -0
  1049. package/src/modules/workflows/components/work-inbox/TaskFormFields.tsx +322 -0
  1050. package/src/modules/workflows/components/work-inbox/WorkInboxEmptyState.tsx +43 -0
  1051. package/src/modules/workflows/data/activity-config-schemas.ts +249 -0
  1052. package/src/modules/workflows/data/activity-config-warnings.ts +71 -0
  1053. package/src/modules/workflows/data/branching-route-warnings.ts +129 -0
  1054. package/src/modules/workflows/data/entities.ts +397 -4
  1055. package/src/modules/workflows/data/metrics-validators.ts +51 -0
  1056. package/src/modules/workflows/data/task-primitives.ts +36 -0
  1057. package/src/modules/workflows/data/types.ts +81 -2
  1058. package/src/modules/workflows/data/validators.ts +729 -60
  1059. package/src/modules/workflows/di.ts +22 -0
  1060. package/src/modules/workflows/events.ts +68 -8
  1061. package/src/modules/workflows/examples/oze-residential-install-60-nodes.json +1545 -0
  1062. package/src/modules/workflows/examples/sales-pipeline-definition.json +35 -35
  1063. package/src/modules/workflows/examples/templates/lead-to-install.json +160 -0
  1064. package/src/modules/workflows/examples/templates/order-approval.json +230 -0
  1065. package/src/modules/workflows/examples/templates/task-escalation.json +110 -0
  1066. package/src/modules/workflows/examples/templates/webhook-integration.json +113 -0
  1067. package/src/modules/workflows/extension-points.ts +1 -1
  1068. package/src/modules/workflows/frontend/[orgSlug]/portal/tasks/[id]/page.meta.ts +21 -0
  1069. package/src/modules/workflows/frontend/[orgSlug]/portal/tasks/[id]/page.tsx +212 -0
  1070. package/src/modules/workflows/frontend/[orgSlug]/portal/tasks/page.meta.ts +25 -0
  1071. package/src/modules/workflows/frontend/[orgSlug]/portal/tasks/page.tsx +185 -0
  1072. package/src/modules/workflows/i18n/de.json +1083 -24
  1073. package/src/modules/workflows/i18n/en.json +1081 -22
  1074. package/src/modules/workflows/i18n/es.json +1083 -24
  1075. package/src/modules/workflows/i18n/ko.json +1072 -13
  1076. package/src/modules/workflows/i18n/pl.json +1082 -23
  1077. package/src/modules/workflows/lib/activity-executor.ts +855 -186
  1078. package/src/modules/workflows/lib/activity-queue-types.ts +120 -1
  1079. package/src/modules/workflows/lib/activity-registry-bootstrap.ts +7 -0
  1080. package/src/modules/workflows/lib/activity-registry.ts +89 -0
  1081. package/src/modules/workflows/lib/activity-types.ts +415 -0
  1082. package/src/modules/workflows/lib/activity-worker-handler.ts +744 -35
  1083. package/src/modules/workflows/lib/advanced-config.ts +41 -0
  1084. package/src/modules/workflows/lib/agent-disposition-task.ts +343 -0
  1085. package/src/modules/workflows/lib/agent-outcome-paths.ts +153 -0
  1086. package/src/modules/workflows/lib/agent-result-mapping.ts +88 -0
  1087. package/src/modules/workflows/lib/agent-review-inspector.ts +125 -0
  1088. package/src/modules/workflows/lib/agent-review.ts +171 -0
  1089. package/src/modules/workflows/lib/ai-authoring.ts +402 -0
  1090. package/src/modules/workflows/lib/ai-draft-runner.ts +105 -0
  1091. package/src/modules/workflows/lib/annotation-events.ts +15 -0
  1092. package/src/modules/workflows/lib/branching-routes.ts +280 -0
  1093. package/src/modules/workflows/lib/breach-routing.ts +142 -0
  1094. package/src/modules/workflows/lib/bulk-replay.ts +185 -0
  1095. package/src/modules/workflows/lib/business-rule-usage.ts +154 -0
  1096. package/src/modules/workflows/lib/caller-graph.ts +104 -0
  1097. package/src/modules/workflows/lib/code-view-apply.ts +178 -0
  1098. package/src/modules/workflows/lib/collect-validation-issues.ts +239 -0
  1099. package/src/modules/workflows/lib/compensation-ghosts.ts +134 -0
  1100. package/src/modules/workflows/lib/component-guard.ts +13 -0
  1101. package/src/modules/workflows/lib/condition-handler.ts +658 -0
  1102. package/src/modules/workflows/lib/context-ledger.ts +814 -0
  1103. package/src/modules/workflows/lib/crud-form-dialogs-flag.ts +5 -0
  1104. package/src/modules/workflows/lib/data-edge-mapping.ts +112 -0
  1105. package/src/modules/workflows/lib/definition-context-schema.ts +103 -0
  1106. package/src/modules/workflows/lib/definition-edit-safety.ts +228 -0
  1107. package/src/modules/workflows/lib/definition-error-body.ts +43 -0
  1108. package/src/modules/workflows/lib/definition-evaluation.ts +156 -0
  1109. package/src/modules/workflows/lib/definition-grant.ts +211 -0
  1110. package/src/modules/workflows/lib/definition-json-locations.ts +226 -0
  1111. package/src/modules/workflows/lib/definition-payload.ts +81 -0
  1112. package/src/modules/workflows/lib/draft-restore.ts +72 -0
  1113. package/src/modules/workflows/lib/dry-run.ts +203 -0
  1114. package/src/modules/workflows/lib/duration.ts +138 -24
  1115. package/src/modules/workflows/lib/edge-reattachment.ts +186 -0
  1116. package/src/modules/workflows/lib/edgeFormTransforms.ts +15 -14
  1117. package/src/modules/workflows/lib/editor-annotations.ts +301 -0
  1118. package/src/modules/workflows/lib/editor-commands.ts +205 -0
  1119. package/src/modules/workflows/lib/editor-history.ts +151 -0
  1120. package/src/modules/workflows/lib/endpoint-catalog.ts +283 -0
  1121. package/src/modules/workflows/lib/endpoint-path.ts +134 -0
  1122. package/src/modules/workflows/lib/engine-version.ts +67 -0
  1123. package/src/modules/workflows/lib/error-handler.ts +192 -0
  1124. package/src/modules/workflows/lib/error-routing.ts +236 -0
  1125. package/src/modules/workflows/lib/event-logger.ts +27 -0
  1126. package/src/modules/workflows/lib/expression-refs.ts +291 -0
  1127. package/src/modules/workflows/lib/failure-grouping.ts +134 -0
  1128. package/src/modules/workflows/lib/find-definition.ts +4 -0
  1129. package/src/modules/workflows/lib/flow-logic-warnings.ts +591 -0
  1130. package/src/modules/workflows/lib/graph-utils.ts +620 -110
  1131. package/src/modules/workflows/lib/icon-search.ts +65 -0
  1132. package/src/modules/workflows/lib/insert-at-cursor.ts +53 -0
  1133. package/src/modules/workflows/lib/instance-date-filter.ts +56 -0
  1134. package/src/modules/workflows/lib/interpolation-pipeline.ts +351 -0
  1135. package/src/modules/workflows/lib/ledger-drag.ts +61 -0
  1136. package/src/modules/workflows/lib/ledger-entry-display.ts +89 -0
  1137. package/src/modules/workflows/lib/ledger-schema-flatten.ts +137 -0
  1138. package/src/modules/workflows/lib/metrics/definition-metrics.ts +268 -0
  1139. package/src/modules/workflows/lib/metrics/metrics-display.ts +57 -0
  1140. package/src/modules/workflows/lib/metrics/rollup-schedule.ts +26 -0
  1141. package/src/modules/workflows/lib/metrics/rollup-service.ts +292 -0
  1142. package/src/modules/workflows/lib/node-config-summary.ts +235 -0
  1143. package/src/modules/workflows/lib/node-geometry.ts +168 -0
  1144. package/src/modules/workflows/lib/node-nudge.ts +63 -0
  1145. package/src/modules/workflows/lib/node-outcome-rows.ts +195 -0
  1146. package/src/modules/workflows/lib/node-placement.ts +104 -0
  1147. package/src/modules/workflows/lib/node-type-icons.ts +71 -10
  1148. package/src/modules/workflows/lib/nodeFormTransforms.ts +519 -28
  1149. package/src/modules/workflows/lib/outcome-routing.ts +346 -0
  1150. package/src/modules/workflows/lib/owned-definition.ts +188 -0
  1151. package/src/modules/workflows/lib/owned-node-changes.ts +29 -0
  1152. package/src/modules/workflows/lib/palette-drag.ts +68 -0
  1153. package/src/modules/workflows/lib/palette-drop.ts +114 -0
  1154. package/src/modules/workflows/lib/parallel-handler.ts +79 -2
  1155. package/src/modules/workflows/lib/port-contract.ts +107 -0
  1156. package/src/modules/workflows/lib/portal-task-access.ts +220 -0
  1157. package/src/modules/workflows/lib/rerun-from-step.ts +140 -0
  1158. package/src/modules/workflows/lib/route-chip-events.ts +45 -0
  1159. package/src/modules/workflows/lib/route-chips.ts +177 -0
  1160. package/src/modules/workflows/lib/route-edge.ts +57 -0
  1161. package/src/modules/workflows/lib/route-kinds.ts +166 -0
  1162. package/src/modules/workflows/lib/route-priority.ts +197 -0
  1163. package/src/modules/workflows/lib/run-duration.ts +70 -0
  1164. package/src/modules/workflows/lib/run-event-tone.ts +46 -0
  1165. package/src/modules/workflows/lib/run-execution.ts +598 -0
  1166. package/src/modules/workflows/lib/run-gantt.ts +311 -0
  1167. package/src/modules/workflows/lib/run-outcome-evidence.ts +60 -0
  1168. package/src/modules/workflows/lib/run-outcome.ts +142 -0
  1169. package/src/modules/workflows/lib/sample-resolver.ts +113 -0
  1170. package/src/modules/workflows/lib/seeds.ts +3 -1
  1171. package/src/modules/workflows/lib/server-output-contract.ts +120 -0
  1172. package/src/modules/workflows/lib/set-variable.ts +94 -0
  1173. package/src/modules/workflows/lib/signal-handler.ts +134 -4
  1174. package/src/modules/workflows/lib/start-fixtures.ts +93 -0
  1175. package/src/modules/workflows/lib/status-colors.ts +220 -21
  1176. package/src/modules/workflows/lib/step-handler.ts +744 -68
  1177. package/src/modules/workflows/lib/step-presentation.ts +295 -0
  1178. package/src/modules/workflows/lib/step-through.ts +71 -0
  1179. package/src/modules/workflows/lib/step-type-conversion.ts +263 -0
  1180. package/src/modules/workflows/lib/subgraph-clipboard.ts +214 -0
  1181. package/src/modules/workflows/lib/task-decision-context.ts +76 -0
  1182. package/src/modules/workflows/lib/task-decisions.ts +117 -0
  1183. package/src/modules/workflows/lib/task-entity-access.ts +181 -0
  1184. package/src/modules/workflows/lib/task-entity-aliases.ts +77 -0
  1185. package/src/modules/workflows/lib/task-entity-types.ts +66 -0
  1186. package/src/modules/workflows/lib/task-form-registry.ts +123 -0
  1187. package/src/modules/workflows/lib/task-form-schema.ts +129 -0
  1188. package/src/modules/workflows/lib/task-handler.ts +492 -51
  1189. package/src/modules/workflows/lib/task-inspector-config.ts +348 -0
  1190. package/src/modules/workflows/lib/task-list-query.ts +46 -0
  1191. package/src/modules/workflows/lib/task-notifications.ts +218 -0
  1192. package/src/modules/workflows/lib/task-permission-settings.ts +117 -0
  1193. package/src/modules/workflows/lib/task-presets.ts +95 -0
  1194. package/src/modules/workflows/lib/task-quick-action.ts +111 -0
  1195. package/src/modules/workflows/lib/task-resolution.ts +270 -0
  1196. package/src/modules/workflows/lib/task-sla.ts +628 -0
  1197. package/src/modules/workflows/lib/task-visibility-request.ts +668 -0
  1198. package/src/modules/workflows/lib/task-visibility.ts +627 -0
  1199. package/src/modules/workflows/lib/timer-handler.ts +8 -1
  1200. package/src/modules/workflows/lib/transition-handler.ts +228 -20
  1201. package/src/modules/workflows/lib/trigger-node.ts +272 -0
  1202. package/src/modules/workflows/lib/visual-editor-navigation.ts +29 -0
  1203. package/src/modules/workflows/lib/work-inbox/empty-state.ts +150 -0
  1204. package/src/modules/workflows/lib/work-inbox/entity-links.ts +99 -0
  1205. package/src/modules/workflows/lib/work-inbox/navigation.ts +28 -0
  1206. package/src/modules/workflows/lib/work-inbox/presentation.ts +163 -0
  1207. package/src/modules/workflows/lib/work-inbox/provider.ts +390 -0
  1208. package/src/modules/workflows/lib/work-inbox/query.ts +103 -0
  1209. package/src/modules/workflows/lib/work-inbox/service.ts +122 -0
  1210. package/src/modules/workflows/lib/work-inbox/user-task-source.ts +240 -0
  1211. package/src/modules/workflows/lib/workflow-command-enablement.ts +188 -0
  1212. package/src/modules/workflows/lib/workflow-command-settings.ts +124 -0
  1213. package/src/modules/workflows/lib/workflow-executor.ts +1036 -10
  1214. package/src/modules/workflows/lib/workflow-function-registry.ts +44 -0
  1215. package/src/modules/workflows/lib/workflow-safe-commands.ts +42 -1
  1216. package/src/modules/workflows/lib/workflow-templates.ts +91 -0
  1217. package/src/modules/workflows/migrations/.snapshot-open-mercato.json +2321 -698
  1218. package/src/modules/workflows/migrations/Migration20260626214855_workflows.ts +15 -0
  1219. package/src/modules/workflows/migrations/Migration20260626222424_workflows.ts +17 -0
  1220. package/src/modules/workflows/migrations/Migration20260727074335_workflows.ts +15 -0
  1221. package/src/modules/workflows/migrations/Migration20260728104038_workflows.ts +13 -0
  1222. package/src/modules/workflows/migrations/Migration20260728163001_workflows.ts +36 -0
  1223. package/src/modules/workflows/migrations/Migration20260729061736_workflows.ts +13 -0
  1224. package/src/modules/workflows/migrations/Migration20260729192652_workflows.ts +11 -0
  1225. package/src/modules/workflows/migrations/Migration20260730085000_workflows.ts +13 -0
  1226. package/src/modules/workflows/migrations/Migration20260730092706_workflows.ts +13 -0
  1227. package/src/modules/workflows/notifications.ts +40 -10
  1228. package/src/modules/workflows/setup.ts +128 -0
  1229. package/src/modules/workflows/subscribers/task-assigned-notification.ts +36 -45
  1230. package/src/modules/workflows/subscribers/task-deadline-breached-notification.ts +31 -0
  1231. package/src/modules/workflows/subscribers/task-reminder-notification.ts +31 -0
  1232. package/src/modules/workflows/widgets/injection/pending-work/widget.client.tsx +119 -0
  1233. package/src/modules/workflows/widgets/injection/pending-work/widget.ts +27 -0
  1234. package/src/modules/workflows/widgets/injection-table.ts +52 -2
  1235. package/src/modules/workflows/workers/workflow-activities.worker.ts +95 -42
  1236. package/src/modules/workflows/workers/workflow-definition-metric-rollup.worker.ts +71 -0
  1237. package/src/modules/workflows/workers/workflow-instance-bulk-replay.ts +51 -0
  1238. package/src/modules/workflows/workers/workflow-invoke-agent.worker.ts +72 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/workflows/backend/definitions/visual-editor/page.tsx"],
4
- "sourcesContent": ["'use client'\n\nimport { WorkflowGraph } from '../../../components/WorkflowGraph'\n// Conditional imports based on feature flag\nimport { NodeEditDialog } from '../../../components/NodeEditDialog'\nimport { EdgeEditDialog } from '../../../components/EdgeEditDialog'\nimport { NodeEditDialogCrudForm } from '../../../components/NodeEditDialogCrudForm'\nimport { EdgeEditDialogCrudForm } from '../../../components/EdgeEditDialogCrudForm'\nimport type { Node, Edge, Connection } from '@xyflow/react'\nimport { useState, useCallback, useEffect } from 'react'\nimport { useRouter, useSearchParams, usePathname } from 'next/navigation'\nimport { graphToDefinition, definitionToGraph, validateWorkflowGraph, generateStepId, generateTransitionId, appendWorkflowEdge, ValidationError } from '../../../lib/graph-utils'\nimport { performDeleteEdgeFlow, performDeleteNodeFlow } from '../../../lib/visual-editor-delete-flow'\nimport { humanizeDefinitionIssuePath } from '../../../lib/format-validation-error'\nimport { workflowDefinitionDataSchema } from '../../../data/validators'\nimport { Page } from '@open-mercato/ui/backend/Page'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Switch } from '@open-mercato/ui/primitives/switch'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { TagsInput } from '@open-mercato/ui/backend/inputs/TagsInput'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { Alert, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { FormHeader } from '@open-mercato/ui/backend/forms'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from '@open-mercato/ui/backend/injection/recordContext'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { CircleQuestionMark, PanelTopClose, PanelTopOpen, Play, Save, Trash2 } from 'lucide-react'\nimport { NODE_TYPE_ICONS, NODE_TYPE_COLORS, NODE_TYPE_LABELS } from '../../../lib/node-type-icons'\nimport { DefinitionTriggersEditor } from '../../../components/DefinitionTriggersEditor'\nimport { MobileVisualEditor } from '../../../components/mobile/MobileVisualEditor'\nimport { useIsMobile } from '@open-mercato/ui/hooks/useIsMobile'\nimport type { WorkflowDefinitionTrigger } from '../../../data/entities'\nimport type { WorkflowMetadataState, WorkflowMetadataHandlers } from '../../../data/types'\nimport * as React from 'react'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\n/**\n * VisualEditorPage - Visual workflow definition editor\n *\n * Layout:\n * - Page Header: Title, description, and action buttons (Save, Validate, Test)\n * - Workflow Metadata: Collapsible form for workflow details\n * - Page Body:\n * - Left sidebar: Step palette (click to add)\n * - Main canvas: ReactFlow graph editor\n * - Flash Messages: Top-right positioned validation messages\n * - Edit Dialogs: Modal dialogs for editing steps and transitions\n */\nexport default function VisualEditorPage() {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const pathname = usePathname()\n const definitionId = searchParams.get('id')\n const isMobile = useIsMobile()\n\n const { confirm, ConfirmDialogElement } = useConfirmDialog()\n\n const [isLoading, setIsLoading] = useState(!!definitionId)\n const [isSaving, setIsSaving] = useState(false)\n const [nodes, setNodes] = useState<Node[]>([])\n const [edges, setEdges] = useState<Edge[]>([])\n const [selectedNode, setSelectedNode] = useState<Node | null>(null)\n const [selectedEdge, setSelectedEdge] = useState<Edge | null>(null)\n const [showMetadata, setShowMetadata] = useState(true)\n const [isCompactViewport, setIsCompactViewport] = useState(false)\n\n // Auto-collapse metadata on compact viewports after hydration\n useEffect(() => {\n if (typeof window === 'undefined') return\n const mediaQuery = window.matchMedia('(max-width: 1279px)')\n const applyViewportMode = () => {\n const compact = mediaQuery.matches\n setIsCompactViewport(compact)\n setShowMetadata(!compact)\n }\n\n applyViewportMode()\n mediaQuery.addEventListener('change', applyViewportMode)\n\n return () => {\n mediaQuery.removeEventListener('change', applyViewportMode)\n }\n }, [])\n const [showNodeDialog, setShowNodeDialog] = useState(false)\n const [showEdgeDialog, setShowEdgeDialog] = useState(false)\n const [showClearConfirm, setShowClearConfirm] = useState(false)\n\n // Workflow metadata state\n const [workflowId, setWorkflowId] = useState('')\n const [workflowName, setWorkflowName] = useState('')\n const [description, setDescription] = useState('')\n const [version, setVersion] = useState(1)\n const [enabled, setEnabled] = useState(true)\n const [category, setCategory] = useState('')\n const [tags, setTags] = useState<string[]>([])\n const [icon, setIcon] = useState('')\n const [effectiveFrom, setEffectiveFrom] = useState('')\n const [effectiveTo, setEffectiveTo] = useState('')\n const [triggers, setTriggers] = useState<WorkflowDefinitionTrigger[]>([])\n const [source, setSource] = useState<'code' | 'code_override' | 'user' | null>(null)\n const [updatedAt, setUpdatedAt] = useState<string | null>(null)\n\n const isCodeOnly = source === 'code'\n const isCodeOverride = source === 'code_override'\n\n // Load existing definition if ID is provided\n useEffect(() => {\n const loadDefinition = async () => {\n if (!definitionId) {\n setIsLoading(false)\n return\n }\n\n try {\n const result = await apiCall<{ data: any; error?: string }>(`/api/workflows/definitions/${definitionId}`)\n\n if (!result.ok) {\n flash(`Failed to load workflow: ${result.result?.error || 'Unknown error'}`, 'error')\n setIsLoading(false)\n return\n }\n\n const definition = result.result?.data\n\n // Populate metadata\n setWorkflowId(definition.workflowId)\n setWorkflowName(definition.workflowName || definition.definition.workflowName || '')\n setDescription(definition.description || definition.definition.description || '')\n setVersion(definition.version)\n setEnabled(definition.enabled)\n setCategory(definition.metadata?.category || '')\n setTags(definition.metadata?.tags || [])\n setIcon(definition.metadata?.icon || '')\n setEffectiveFrom(definition.effectiveFrom || '')\n setEffectiveTo(definition.effectiveTo || '')\n\n // Convert definition to graph\n const graph = definitionToGraph(definition.definition)\n setNodes(graph.nodes)\n setEdges(graph.edges)\n\n // Load embedded triggers from definition\n setTriggers(definition.definition?.triggers || [])\n\n // Track source so the editor mirrors the non-visual edit page UX:\n // code \u2192 read-only with Customize button; code_override \u2192 editable\n // with Reset to code; user \u2192 editable, no banner.\n setSource((definition.source as 'code' | 'code_override' | 'user') ?? null)\n setUpdatedAt(typeof definition.updatedAt === 'string' ? definition.updatedAt : null)\n } catch (error) {\n logger.error('Error loading workflow definition', { err: error })\n flash('Failed to load workflow definition', 'error')\n } finally {\n setIsLoading(false)\n }\n }\n\n loadDefinition()\n }, [definitionId])\n\n // Handle node changes from ReactFlow. The lazy graph applies React Flow's\n // change reducers internally (#3169) and hands back the resolved nodes, so\n // this page never imports the @xyflow/react runtime.\n const handleNodesChange = useCallback((nextNodes: Node[]) => {\n if (isCodeOnly) return\n setNodes(nextNodes)\n }, [isCodeOnly])\n\n // Handle edge changes from ReactFlow (resolved edges from the lazy graph).\n const handleEdgesChange = useCallback((nextEdges: Edge[]) => {\n if (isCodeOnly) return\n setEdges(nextEdges)\n }, [isCodeOnly])\n\n // Handle adding new node from palette\n const handleAddNode = useCallback((nodeType: string) => {\n if (isCodeOnly) return\n const newNode: Node = {\n id: generateStepId(nodeType),\n type: nodeType,\n position: {\n x: 250 + nodes.length * 50,\n y: 100 + nodes.length * 150,\n },\n data: {\n label: getDefaultLabel(nodeType),\n description: '',\n badge: getDefaultBadge(nodeType),\n status: 'pending',\n },\n }\n\n setNodes((nds) => [...nds, newNode])\n }, [nodes.length, isCodeOnly])\n\n // Handle node selection - open edit dialog (suppressed in read-only mode\n // so users can't open the node editor on a code-defined workflow).\n const handleNodeClick = useCallback((_event: React.MouseEvent, node: Node) => {\n if (isCodeOnly) return\n setSelectedNode(node)\n setSelectedEdge(null)\n setShowNodeDialog(true)\n }, [isCodeOnly])\n\n // Handle edge selection - open edit dialog\n const handleEdgeClick = useCallback((_event: React.MouseEvent, edge: Edge) => {\n if (isCodeOnly) return\n setSelectedEdge(edge)\n setSelectedNode(null)\n setShowEdgeDialog(true)\n }, [isCodeOnly])\n\n // Save node updates\n const handleSaveNode = useCallback((nodeId: string, updates: Partial<Node['data']>) => {\n setNodes((nds) =>\n nds.map((node) =>\n node.id === nodeId\n ? { ...node, data: { ...node.data, ...updates } }\n : node\n )\n )\n flash('Node updated successfully', 'success')\n }, [])\n\n // Save edge updates\n const handleSaveEdge = useCallback((edgeId: string, updates: Partial<Edge['data']>) => {\n setEdges((eds) =>\n eds.map((edge) =>\n edge.id === edgeId\n ? { ...edge, data: { ...edge.data, ...updates } }\n : edge\n )\n )\n flash('Transition updated successfully', 'success')\n }, [])\n\n // Delete edge\n const handleDeleteEdge = useCallback(async (edgeId: string) => {\n await performDeleteEdgeFlow(edgeId, {\n confirm,\n t,\n setShowEdgeDialog,\n setSelectedEdge,\n setEdges,\n notifyDeleted: () => flash('Transition deleted successfully', 'success'),\n })\n }, [confirm, t])\n\n // Delete node\n const handleDeleteNode = useCallback(async (nodeId: string) => {\n await performDeleteNodeFlow(nodeId, {\n nodes,\n confirm,\n t,\n setShowNodeDialog,\n setSelectedNode,\n setNodes,\n setEdges,\n notifyDeleted: () => flash('Step deleted successfully', 'success'),\n })\n }, [confirm, nodes, t])\n\n // Handle new connections\n const handleConnect = useCallback((connection: Connection) => {\n const newEdge: Edge = {\n id: generateTransitionId(connection.source!, connection.target!),\n source: connection.source!,\n target: connection.target!,\n type: 'smoothstep',\n data: {\n trigger: 'auto',\n preConditions: [],\n postConditions: [],\n activities: [],\n label: '',\n },\n }\n\n setEdges((eds) => appendWorkflowEdge(eds, newEdge))\n }, [])\n\n // Validate workflow\n const handleValidate = useCallback(() => {\n const graphErrors = validateWorkflowGraph(nodes, edges)\n const allErrors: ValidationError[] = [...graphErrors]\n\n // Run Zod schema validation\n try {\n const definitionData = graphToDefinition(nodes, edges, { includePositions: true })\n const result = workflowDefinitionDataSchema.safeParse(definitionData)\n\n if (!result.success) {\n // Convert Zod errors to validation errors\n result.error.issues.forEach((issue) => {\n allErrors.push({\n type: 'error',\n message: `Schema validation: ${issue.path.join('.')} - ${issue.message}`,\n })\n })\n }\n } catch (error) {\n allErrors.push({\n type: 'error',\n message: `Schema validation failed: ${error instanceof Error ? error.message : 'Unknown error'}`,\n })\n }\n\n if (allErrors.length === 0) {\n flash('Validation passed! Your workflow is valid and ready to save.', 'success')\n } else {\n // Show first error/warning message\n const firstError = allErrors[0]\n const errorCount = allErrors.length\n const message = errorCount > 1\n ? `${firstError.message} (and ${errorCount - 1} more ${errorCount === 2 ? 'issue' : 'issues'})`\n : firstError.message\n flash(message, firstError.type === 'error' ? 'error' : 'warning')\n }\n }, [nodes, edges])\n\n // Save workflow definition\n const handleSave = useCallback(async () => {\n // Validate required fields\n if (!workflowId || !workflowName) {\n flash('Workflow ID and Name are required fields', 'error')\n return\n }\n\n // Validate workflow structure\n const errors = validateWorkflowGraph(nodes, edges)\n const criticalErrors = errors.filter(e => e.type === 'error')\n if (criticalErrors.length > 0) {\n flash(`Cannot save: ${criticalErrors.length} validation error(s) found. Please fix them first.`, 'error')\n return\n }\n\n // Generate definition data and include triggers\n const graphDefinition = graphToDefinition(nodes, edges, { includePositions: true })\n const definitionData = {\n ...graphDefinition,\n triggers: triggers.length > 0 ? triggers : undefined,\n }\n\n // Run Zod schema validation before saving. Report every issue, not just the\n // first: a save rejected for one missing activity field used to look like\n // \"nothing happened\" once the operator fixed that field and hit a second\n // one (#4232). Paths are humanized (steps.2.activities.0.config.endpoint \u2192\n // step 3 \u203A activity 1 \u203A endpoint) so the message points at the node to open.\n const schemaResult = workflowDefinitionDataSchema.safeParse(definitionData)\n if (!schemaResult.success) {\n const issues = schemaResult.error.issues\n const described = issues\n .slice(0, 3)\n .map((issue) => `${humanizeDefinitionIssuePath(issue.path)}: ${issue.message}`)\n const suffix = issues.length > described.length ? ` (+${issues.length - described.length} more)` : ''\n flash(`Cannot save \u2014 ${described.join('; ')}${suffix}`, 'error')\n return\n }\n\n setIsSaving(true)\n\n try {\n\n const metadata: any = {}\n if (category) metadata.category = category\n if (tags.length > 0) metadata.tags = tags\n if (icon) metadata.icon = icon\n\n // Determine if creating new or updating existing\n const isUpdate = !!definitionId\n\n let result\n if (isUpdate) {\n // Update existing definition \u2014 send the full editable payload so metadata\n // edits (name, description, version, category, tags, icon, effective\n // dates) actually persist. Previously only `definition` + `enabled`\n // were sent, silently dropping every other field.\n result = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(updatedAt),\n () => apiCall<{ data: any; error?: string }>(`/api/workflows/definitions/${definitionId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n workflowName,\n description: description || null,\n version,\n definition: definitionData,\n metadata: Object.keys(metadata).length > 0 ? metadata : null,\n enabled,\n effectiveFrom: effectiveFrom || null,\n effectiveTo: effectiveTo || null,\n }),\n }),\n )\n } else {\n // Create new definition\n result = await apiCall<{ data: any; error?: string }>('/api/workflows/definitions', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n workflowId,\n workflowName,\n description: description || null,\n version,\n definition: definitionData,\n metadata: Object.keys(metadata).length > 0 ? metadata : null,\n enabled,\n effectiveFrom: effectiveFrom || null,\n effectiveTo: effectiveTo || null,\n }),\n })\n }\n\n if (!result.ok) {\n const conflictError = Object.assign(new Error(t('workflows.messages.saveFailed', 'Failed to save')), {\n status: result.status,\n ...(result.result && typeof result.result === 'object' ? result.result : {}),\n })\n if (!surfaceRecordConflict(conflictError, t)) {\n flash(`Failed to save: ${result.result?.error || 'Unknown error'}`, 'error')\n }\n return\n }\n\n const savedDefinition = result.result?.data\n\n flash(`Workflow ${isUpdate ? 'updated' : 'created'} successfully!`, 'success')\n\n // Redirect to definition detail page after short delay\n setTimeout(() => {\n router.push(`/backend/definitions/${savedDefinition.id}`)\n }, 1500)\n\n } catch (error) {\n logger.error('Error saving workflow definition', { err: error })\n flash('Failed to save workflow definition. Please try again.', 'error')\n } finally {\n setIsSaving(false)\n }\n }, [nodes, edges, workflowId, workflowName, description, version, enabled, category, tags, icon, effectiveFrom, effectiveTo, triggers, definitionId, updatedAt, router])\n\n // Customize a code-defined workflow \u2192 creates an override and reloads the\n // editor pointed at the new UUID. Mirrors the non-visual edit page button.\n const handleCustomize = useCallback(async () => {\n if (!definitionId) return\n setIsSaving(true)\n try {\n const result = await apiCall<{ data?: { id?: string }; error?: string }>(\n `/api/workflows/definitions/${definitionId}/customize`,\n { method: 'POST' },\n )\n if (!result.ok) {\n flash(result.result?.error || 'Failed to customize workflow', 'error')\n return\n }\n const newId = result.result?.data?.id\n if (!newId) return\n router.push(`/backend/definitions/visual-editor?id=${encodeURIComponent(newId)}`)\n router.refresh()\n } finally {\n setIsSaving(false)\n }\n }, [definitionId, router])\n\n // Reset a code-override back to its code definition. Mirrors the\n // non-visual edit page action, with the same confirm dialog.\n const handleResetToCode = useCallback(async () => {\n if (!definitionId) return\n const confirmed = await confirm({\n title: t('workflows.actions.resetToCode'),\n description: t('workflows.actions.resetConfirm'),\n confirmText: t('workflows.actions.resetToCode'),\n variant: 'destructive',\n })\n if (!confirmed) return\n\n setIsSaving(true)\n try {\n const result = await apiCall<{ data?: { id?: string }; error?: string }>(\n `/api/workflows/definitions/${definitionId}/reset-to-code`,\n { method: 'POST' },\n )\n if (!result.ok) {\n flash(result.result?.error || 'Failed to reset workflow', 'error')\n return\n }\n const codeId = result.result?.data?.id || (workflowId ? `code:${workflowId}` : null)\n if (!codeId) return\n router.push(`/backend/definitions/visual-editor?id=${encodeURIComponent(codeId)}`)\n router.refresh()\n } finally {\n setIsSaving(false)\n }\n }, [definitionId, workflowId, router, confirm, t])\n\n // Test workflow\n const handleTest = useCallback(() => {\n // First validate\n const errors = validateWorkflowGraph(nodes, edges)\n const criticalErrors = errors.filter((e) => e.type === 'error')\n if (criticalErrors.length > 0) {\n flash(`Cannot test: ${criticalErrors.length} validation error(s) found. Please fix them first.`, 'error')\n return\n }\n\n // TODO: Implement test logic (create instance, run first step)\n flash('Test functionality will be implemented next', 'info')\n }, [nodes, edges])\n\n // Load example workflow\n const handleLoadExample = useCallback(() => {\n // Set example metadata\n setWorkflowId('approval_workflow')\n setWorkflowName('Simple Approval Workflow')\n setDescription('A basic approval workflow for reviewing and approving requests')\n setVersion(1)\n setEnabled(true)\n setCategory('Approvals')\n setTags(['approval', 'review'])\n\n const exampleNodes: Node[] = [\n {\n id: 'start',\n type: 'start',\n position: { x: 250, y: 50 },\n data: {\n label: 'Start',\n description: 'Workflow begins',\n status: 'pending',\n badge: 'Start',\n },\n },\n {\n id: 'step1',\n type: 'userTask',\n position: { x: 250, y: 250 },\n data: {\n label: 'Review Request',\n description: 'User reviews the incoming request',\n status: 'pending',\n stepNumber: 1,\n badge: 'User Task',\n assignedToRoles: ['Reviewer'],\n },\n },\n {\n id: 'end',\n type: 'end',\n position: { x: 250, y: 450 },\n data: {\n label: 'Complete',\n description: 'Workflow ends',\n status: 'pending',\n badge: 'End',\n },\n },\n ]\n\n const exampleEdges: Edge[] = [\n {\n id: 'e-start-step1',\n source: 'start',\n target: 'step1',\n type: 'smoothstep',\n data: {\n trigger: 'auto',\n preConditions: [],\n postConditions: [],\n activities: [],\n },\n },\n {\n id: 'e-step1-end',\n source: 'step1',\n target: 'end',\n type: 'smoothstep',\n data: {\n trigger: 'auto',\n preConditions: [],\n postConditions: [],\n activities: [],\n },\n },\n ]\n\n setNodes(exampleNodes)\n setEdges(exampleEdges)\n flash('Example workflow loaded', 'success')\n }, [])\n\n // Clear canvas\n const handleClear = useCallback(() => {\n if (nodes.length > 0 || edges.length > 0 || workflowId || workflowName) {\n setShowClearConfirm(true)\n }\n }, [nodes.length, edges.length, workflowId, workflowName])\n\n // Confirm clear action\n const confirmClear = useCallback(() => {\n setNodes([])\n setEdges([])\n setWorkflowId('')\n setWorkflowName('')\n setDescription('')\n setVersion(1)\n setEnabled(true)\n setCategory('')\n setTags([])\n setIcon('')\n setEffectiveFrom('')\n setEffectiveTo('')\n setTriggers([])\n setShowClearConfirm(false)\n flash('Canvas cleared', 'success')\n }, [])\n\n // Publish page-load record context to the AppShell-owned `backend:record:current`\n // mount so the enterprise record_locks widget resolves `workflows.definition` + id\n // explicitly. This is the highest-value record_locks target (long-lived visual\n // edits): presence holds the lock while the graph is open, and the raw `apiCall`\n // save already routes its 409 through `surfaceRecordConflict`. Cleared on create\n // (no `definitionId`) and on unmount. Mirrors the form edit page's resourceKind so\n // a lock held in either editor surfaces in the other.\n useSetCurrentRecordInjectionContext(\n buildRecordInjectionContext({\n resourceKind: 'workflows.definition',\n resourceId: definitionId,\n updatedAt,\n path: pathname,\n }),\n )\n\n // Show loading spinner while loading definition\n if (isLoading) {\n return (\n <Page className=\"flex items-center justify-center min-h-[50vh]\">\n <LoadingMessage label=\"Loading workflow definition...\" />\n </Page>\n )\n }\n\n const metadata: WorkflowMetadataState = {\n workflowId, workflowName, description, version,\n enabled, category, tags, icon,\n effectiveFrom, effectiveTo, triggers,\n }\n\n const metadataHandlers: WorkflowMetadataHandlers = {\n setWorkflowId, setWorkflowName, setDescription, setVersion,\n setEnabled, setCategory, setTags, setIcon,\n setEffectiveFrom, setEffectiveTo, setTriggers,\n }\n\n const sharedDialogs = (\n <>\n {process.env.NEXT_PUBLIC_WORKFLOW_CRUDFORM_ENABLED === 'true' ? (\n <NodeEditDialogCrudForm node={selectedNode} isOpen={showNodeDialog} onClose={() => setShowNodeDialog(false)} onSave={handleSaveNode} onDelete={handleDeleteNode} />\n ) : (\n <NodeEditDialog node={selectedNode} isOpen={showNodeDialog} onClose={() => setShowNodeDialog(false)} onSave={handleSaveNode} onDelete={handleDeleteNode} />\n )}\n {process.env.NEXT_PUBLIC_WORKFLOW_CRUDFORM_ENABLED === 'true' ? (\n <EdgeEditDialogCrudForm edge={selectedEdge} isOpen={showEdgeDialog} onClose={() => setShowEdgeDialog(false)} onSave={handleSaveEdge} onDelete={handleDeleteEdge} />\n ) : (\n <EdgeEditDialog edge={selectedEdge} isOpen={showEdgeDialog} onClose={() => setShowEdgeDialog(false)} onSave={handleSaveEdge} onDelete={handleDeleteEdge} />\n )}\n <Dialog open={showClearConfirm} onOpenChange={setShowClearConfirm}>\n <DialogContent className=\"sm:max-w-md\">\n <DialogHeader>\n <DialogTitle>{t('workflows.visualEditor.clearTitle')}</DialogTitle>\n <DialogDescription>{t('workflows.visualEditor.clearDescription')}</DialogDescription>\n </DialogHeader>\n <DialogFooter>\n <Button variant=\"outline\" onClick={() => setShowClearConfirm(false)}>{t('common.cancel', 'Cancel')}</Button>\n <Button variant=\"destructive-solid\" onClick={confirmClear}>{t('common.clear', 'Clear')}</Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </>\n )\n\n if (isMobile) {\n return (\n <Page className=\"flex h-[100svh] flex-col space-y-0 overflow-hidden\">\n <MobileVisualEditor\n definitionId={definitionId}\n isSaving={isSaving}\n nodes={nodes}\n edges={edges}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onNodeClick={handleNodeClick}\n onEdgeClick={handleEdgeClick}\n onConnect={handleConnect}\n onAddNode={handleAddNode}\n onSave={handleSave}\n onValidate={handleValidate}\n onTest={handleTest}\n onLoadExample={handleLoadExample}\n onClear={handleClear}\n metadata={metadata}\n metadataHandlers={metadataHandlers}\n />\n {sharedDialogs}\n {ConfirmDialogElement}\n </Page>\n )\n }\n\n return (\n <Page className=\"space-y-0 overflow-x-hidden\">\n {/* Page Header */}\n <div className=\"shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3\">\n <FormHeader\n mode=\"detail\"\n backHref=\"/backend/definitions\"\n backLabel={t('workflows.definitions.backToList', 'Back to definitions')}\n title={definitionId ? (workflowName || t('workflows.definitions.singular')) : t('workflows.backend.definitions.visual_editor.title')}\n subtitle={definitionId\n ? t('workflows.definitions.detail.summary', 'Editing workflow definition')\n : t('workflows.definitions.create.summary', 'Create and edit workflow definitions visually with a drag-and-drop interface')\n }\n actionsContent={\n <div className=\"flex flex-wrap items-center justify-end gap-1 md:gap-2\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setShowMetadata(!showMetadata)}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs\"\n aria-label={showMetadata ? t('workflows.visualEditor.hideMetadata') : t('workflows.visualEditor.showMetadata')}\n >\n {showMetadata ? <PanelTopClose className=\"mr-1.5 h-4 w-4\" /> : <PanelTopOpen className=\"mr-1.5 h-4 w-4\" />}\n {showMetadata ? t('workflows.visualEditor.hideMetadata') : t('workflows.visualEditor.showMetadata')}\n </Button>\n {!isCodeOnly && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleLoadExample}\n disabled={isSaving}\n className=\"h-8 text-xs\"\n >\n {t('workflows.visualEditor.loadExample')}\n </Button>\n )}\n {!isCodeOnly && (\n <Button\n variant=\"destructive\"\n size=\"sm\"\n onClick={handleClear}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs\"\n aria-label={t('workflows.visualEditor.clear')}\n >\n <Trash2 className=\"mr-1.5 h-4 w-4\" />\n {t('workflows.visualEditor.clear')}\n </Button>\n )}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleValidate}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs\"\n aria-label={t('workflows.visualEditor.validate')}\n >\n <CircleQuestionMark className=\"mr-1.5 h-4 w-4\" />\n {t('workflows.visualEditor.validate')}\n </Button>\n {!isCodeOnly && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleTest}\n disabled={isSaving}\n className=\"h-8 text-xs\"\n >\n <Play className=\"mr-1.5 h-4 w-4\" />\n {t('workflows.visualEditor.runTest')}\n </Button>\n )}\n {isCodeOverride && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleResetToCode}\n disabled={isSaving}\n className=\"h-8 text-xs\"\n >\n {t('workflows.actions.resetToCode')}\n </Button>\n )}\n {isCodeOnly ? (\n <Button\n size=\"sm\"\n onClick={handleCustomize}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs md:px-3\"\n >\n {t('workflows.actions.customize')}\n </Button>\n ) : (\n <Button\n size=\"sm\"\n onClick={handleSave}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs md:px-3\"\n aria-label={isSaving ? t('workflows.mobile.saving') : definitionId ? t('workflows.common.update') : t('workflows.common.save')}\n >\n <Save className=\"mr-1.5 h-4 w-4\" />\n {isSaving ? t('workflows.mobile.saving') : definitionId ? t('workflows.common.update') : t('workflows.common.save')}\n </Button>\n )}\n </div>\n }\n />\n </div>\n\n {/* Source banner (code-defined / customized) */}\n {(isCodeOnly || isCodeOverride) && (\n <div className=\"shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3\">\n {isCodeOnly && (\n <Alert status=\"information\">\n <AlertTitle>{t('workflows.source.code.readonlyBanner')}</AlertTitle>\n </Alert>\n )}\n {isCodeOverride && (\n <Alert status=\"warning\">\n <AlertTitle>{t('workflows.source.code_override.banner')}</AlertTitle>\n </Alert>\n )}\n </div>\n )}\n\n {/* Workflow Metadata Form */}\n {showMetadata && (\n <div className={isCompactViewport\n ? 'shrink-0 border-b border-border bg-background px-3 py-2 max-h-[60svh] overflow-y-auto overscroll-contain md:px-6 md:py-3'\n : 'shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3'\n }>\n <fieldset disabled={isCodeOnly} className=\"rounded-lg border bg-card p-3 disabled:opacity-70 md:p-4\">\n <h2 className=\"mb-3 text-xs font-semibold uppercase text-muted-foreground\">{t('workflows.visualEditor.workflowMetadata')}</h2>\n <div className=\"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 md:gap-4\">\n {/* Workflow ID */}\n <div className=\"min-w-0 space-y-1\">\n <Label htmlFor=\"workflowId\" className=\"text-xs\">{t('workflows.form.workflowId')} *</Label>\n <Input\n id=\"workflowId\"\n value={workflowId}\n onChange={(e) => setWorkflowId(e.target.value)}\n placeholder=\"checkout_workflow\"\n disabled={!!definitionId}\n className=\"h-8 text-sm\"\n />\n {definitionId && <p className=\"text-overline text-muted-foreground\">{t('workflows.visualEditor.readOnly')}</p>}\n </div>\n\n {/* Workflow Name */}\n <div className=\"min-w-0 space-y-1\">\n <Label htmlFor=\"workflowName\" className=\"text-xs\">{t('workflows.form.workflowName')} *</Label>\n <Input\n id=\"workflowName\"\n value={workflowName}\n onChange={(e) => setWorkflowName(e.target.value)}\n placeholder=\"Checkout Process\"\n className=\"h-8 text-sm\"\n />\n </div>\n\n {/* Category */}\n <div className=\"min-w-0 space-y-1\">\n <Label htmlFor=\"category\" className=\"text-xs\">{t('workflows.form.category')}</Label>\n <Input\n id=\"category\"\n value={category}\n onChange={(e) => setCategory(e.target.value)}\n placeholder=\"E-Commerce\"\n className=\"h-8 text-sm\"\n />\n </div>\n\n {/* Description */}\n <div className=\"min-w-0 space-y-1 sm:col-span-2 lg:col-span-3\">\n <Label htmlFor=\"description\" className=\"text-xs\">{t('workflows.form.description')}</Label>\n <Textarea\n id=\"description\"\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n placeholder={t('workflows.form.placeholders.description')}\n rows={2}\n className=\"min-h-[60px] text-sm\"\n />\n </div>\n\n {/* Version */}\n <div className=\"min-w-0 space-y-1\">\n <Label htmlFor=\"version\" className=\"text-xs\">{t('workflows.form.version')} *</Label>\n <Input\n id=\"version\"\n type=\"number\"\n value={version}\n onChange={(e) => setVersion(parseInt(e.target.value) || 1)}\n min={1}\n disabled={!!definitionId}\n className=\"h-8 text-sm\"\n />\n </div>\n\n {/* Enabled */}\n <div className=\"min-w-0 space-y-1\">\n <Label className=\"text-xs\">{t('common.enabled', 'Enabled')}</Label>\n <div className=\"flex h-8 items-center gap-2\">\n <Switch\n id=\"enabled\"\n checked={enabled}\n onCheckedChange={setEnabled}\n />\n <Label htmlFor=\"enabled\" className=\"cursor-pointer text-xs font-normal\">\n {enabled ? t('common.on', 'On') : t('common.off', 'Off')}\n </Label>\n </div>\n </div>\n\n {/* Tags */}\n <div className=\"min-w-0 space-y-1\">\n <Label className=\"text-xs\">{t('workflows.form.tags')}</Label>\n <TagsInput\n value={tags}\n onChange={setTags}\n placeholder={t('workflows.form.placeholders.tags')}\n />\n </div>\n\n {/* Icon */}\n <div className=\"min-w-0 space-y-1\">\n <Label htmlFor=\"icon\" className=\"text-xs\">{t('workflows.form.icon')}</Label>\n <Input\n id=\"icon\"\n value={icon}\n onChange={(e) => setIcon(e.target.value)}\n placeholder=\"ShoppingCart\"\n className=\"h-8 text-sm\"\n />\n </div>\n\n <div className=\"min-w-0 space-y-1\">\n <Label htmlFor=\"effectiveFrom\" className=\"text-xs\">{t('workflows.form.effectiveFrom')}</Label>\n <Input\n id=\"effectiveFrom\"\n type=\"date\"\n value={effectiveFrom}\n onChange={(e) => setEffectiveFrom(e.target.value)}\n className=\"h-8 text-sm\"\n />\n </div>\n\n <div className=\"min-w-0 space-y-1\">\n <Label htmlFor=\"effectiveTo\" className=\"text-xs\">{t('workflows.form.effectiveTo')}</Label>\n <Input\n id=\"effectiveTo\"\n type=\"date\"\n value={effectiveTo}\n onChange={(e) => setEffectiveTo(e.target.value)}\n className=\"h-8 text-sm\"\n />\n </div>\n </div>\n </fieldset>\n\n {/* Event Triggers \u2014 also locked when the workflow is code-defined */}\n <fieldset disabled={isCodeOnly} className=\"mt-3 disabled:opacity-70\">\n <DefinitionTriggersEditor\n value={triggers}\n onChange={setTriggers}\n />\n </fieldset>\n </div>\n )}\n\n {/* Main Content */}\n {isCompactViewport ? (\n <div className=\"px-3 py-3 md:px-6 md:py-4\">\n <div className=\"relative min-w-0\">\n <div className=\"h-[64svh] min-h-[360px] rounded-lg border bg-card\">\n <WorkflowGraph\n initialNodes={nodes}\n initialEdges={edges}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onNodeClick={handleNodeClick}\n onEdgeClick={handleEdgeClick}\n onConnect={handleConnect}\n editable={!isCodeOnly}\n height=\"100%\"\n />\n </div>\n\n {nodes.length === 0 && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center px-4\">\n <div className=\"text-center\">\n <h2 className=\"mb-2 text-lg font-semibold text-foreground\">{t('workflows.visualEditor.startBuilding')}</h2>\n <p className=\"mb-4 text-sm text-muted-foreground\">{t('workflows.visualEditor.tapToAddBelow')}</p>\n <button\n onClick={handleLoadExample}\n className=\"pointer-events-auto text-sm text-primary hover:underline\"\n >\n {t('workflows.visualEditor.loadExampleWorkflow')}\n </button>\n </div>\n </div>\n )}\n </div>\n\n {!isCodeOnly && (\n <div className=\"mt-3 rounded-lg border bg-card p-3\">\n <h2 className=\"mb-2 text-xs font-semibold uppercase text-muted-foreground\">{t('workflows.visualEditor.stepPalette')}</h2>\n <p className=\"mb-3 text-xs text-muted-foreground\">{t('workflows.visualEditor.tapToAdd')}</p>\n\n <div className=\"flex gap-2 overflow-x-auto pb-1\">\n {(['start', 'userTask', 'automated', 'waitForSignal', 'waitForTimer', 'subWorkflow', 'end'] as const).map((nodeType) => {\n const Icon = NODE_TYPE_ICONS[nodeType]\n return (\n <button\n key={nodeType}\n onClick={() => handleAddNode(nodeType)}\n className=\"flex shrink-0 items-center gap-1 rounded-md border bg-background px-2 py-1 text-xs hover:bg-muted active:bg-muted/50\"\n >\n <Icon className=\"h-3.5 w-3.5\" />\n <span>{NODE_TYPE_LABELS[nodeType].title}</span>\n </button>\n )\n })}\n </div>\n </div>\n )}\n </div>\n ) : (\n <div className=\"flex min-h-[72svh] min-w-0 flex-1 border-t border-border\">\n {/* Left Sidebar - Step Palette (hidden in read-only mode) */}\n {!isCodeOnly && (\n <div className=\"w-[24rem] shrink-0 overflow-y-auto border-r border-border bg-background p-6\">\n <div className=\"rounded-lg border bg-card p-4\">\n <h2 className=\"mb-2 text-sm font-semibold uppercase text-muted-foreground\">{t('workflows.visualEditor.stepPalette')}</h2>\n <p className=\"mb-4 text-xs text-muted-foreground\">\n {t('workflows.visualEditor.clickToAdd')}\n </p>\n\n <div className=\"space-y-3\">\n {/* START Step */}\n <button\n onClick={() => handleAddNode('start')}\n className=\"group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md\"\n >\n <div className={`absolute right-2 top-2 ${NODE_TYPE_COLORS.start} opacity-60 transition-opacity group-hover:opacity-100`}>\n {(() => {\n const Icon = NODE_TYPE_ICONS.start\n return <Icon className=\"h-4 w-4\" />\n })()}\n </div>\n <div className=\"text-sm font-semibold text-foreground\">{NODE_TYPE_LABELS.start.title}</div>\n <div className=\"mt-0.5 text-xs text-muted-foreground\">{NODE_TYPE_LABELS.start.description}</div>\n </button>\n\n {/* USER_TASK Step */}\n <button\n onClick={() => handleAddNode('userTask')}\n className=\"group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md\"\n >\n <div className={`absolute right-2 top-2 ${NODE_TYPE_COLORS.userTask} opacity-60 transition-opacity group-hover:opacity-100`}>\n {(() => {\n const Icon = NODE_TYPE_ICONS.userTask\n return <Icon className=\"h-4 w-4\" />\n })()}\n </div>\n <div className=\"text-sm font-semibold text-foreground\">{NODE_TYPE_LABELS.userTask.title}</div>\n <div className=\"mt-0.5 text-xs text-muted-foreground\">{NODE_TYPE_LABELS.userTask.description}</div>\n </button>\n\n {/* AUTOMATED Step */}\n <button\n onClick={() => handleAddNode('automated')}\n className=\"group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md\"\n >\n <div className={`absolute right-2 top-2 ${NODE_TYPE_COLORS.automated} opacity-60 transition-opacity group-hover:opacity-100`}>\n {(() => {\n const Icon = NODE_TYPE_ICONS.automated\n return <Icon className=\"h-4 w-4\" />\n })()}\n </div>\n <div className=\"text-sm font-semibold text-foreground\">{NODE_TYPE_LABELS.automated.title}</div>\n <div className=\"mt-0.5 text-xs text-muted-foreground\">{NODE_TYPE_LABELS.automated.description}</div>\n </button>\n\n {/* WAIT_FOR_SIGNAL Step */}\n <button\n onClick={() => handleAddNode('waitForSignal')}\n className=\"group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md\"\n >\n <div className={`absolute right-2 top-2 ${NODE_TYPE_COLORS.waitForSignal} opacity-60 transition-opacity group-hover:opacity-100`}>\n {(() => {\n const Icon = NODE_TYPE_ICONS.waitForSignal\n return <Icon className=\"h-4 w-4\" />\n })()}\n </div>\n <div className=\"text-sm font-semibold text-foreground\">{NODE_TYPE_LABELS.waitForSignal.title}</div>\n <div className=\"mt-0.5 text-xs text-muted-foreground\">{NODE_TYPE_LABELS.waitForSignal.description}</div>\n </button>\n\n {/* WAIT_FOR_TIMER Step */}\n <button\n onClick={() => handleAddNode('waitForTimer')}\n className=\"group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md\"\n >\n <div className={`absolute right-2 top-2 ${NODE_TYPE_COLORS.waitForTimer} opacity-60 transition-opacity group-hover:opacity-100`}>\n {(() => {\n const Icon = NODE_TYPE_ICONS.waitForTimer\n return <Icon className=\"h-4 w-4\" />\n })()}\n </div>\n <div className=\"text-sm font-semibold text-foreground\">{NODE_TYPE_LABELS.waitForTimer.title}</div>\n <div className=\"mt-0.5 text-xs text-muted-foreground\">{NODE_TYPE_LABELS.waitForTimer.description}</div>\n </button>\n\n {/* SUB_WORKFLOW Step */}\n <button\n onClick={() => handleAddNode('subWorkflow')}\n className=\"group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md\"\n >\n <div className={`absolute right-2 top-2 ${NODE_TYPE_COLORS.subWorkflow} opacity-60 transition-opacity group-hover:opacity-100`}>\n {(() => {\n const Icon = NODE_TYPE_ICONS.subWorkflow\n return <Icon className=\"h-4 w-4\" />\n })()}\n </div>\n <div className=\"text-sm font-semibold text-foreground\">{NODE_TYPE_LABELS.subWorkflow.title}</div>\n <div className=\"mt-0.5 text-xs text-muted-foreground\">{NODE_TYPE_LABELS.subWorkflow.description}</div>\n </button>\n\n {/* END Step */}\n <button\n onClick={() => handleAddNode('end')}\n className=\"group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md\"\n >\n <div className={`absolute right-2 top-2 ${NODE_TYPE_COLORS.end} opacity-60 transition-opacity group-hover:opacity-100`}>\n {(() => {\n const Icon = NODE_TYPE_ICONS.end\n return <Icon className=\"h-4 w-4\" />\n })()}\n </div>\n <div className=\"text-sm font-semibold text-foreground\">{NODE_TYPE_LABELS.end.title}</div>\n <div className=\"mt-0.5 text-xs text-muted-foreground\">{NODE_TYPE_LABELS.end.description}</div>\n </button>\n </div>\n\n {/* Instructions */}\n <Alert status=\"information\" className=\"mt-6\">\n <AlertTitle className=\"text-xs\">{t('workflows.visualEditor.howToUse', 'How to use:')}</AlertTitle>\n <div className=\"mt-2\">\n <ul className=\"list-inside list-disc space-y-1 text-xs\">\n <li>{t('workflows.visualEditor.hint.addSteps', 'Click step types to add them')}</li>\n <li>{t('workflows.visualEditor.hint.dragSteps', 'Drag steps to position them')}</li>\n <li>{t('workflows.visualEditor.hint.connectSteps', 'Connect steps by dragging from handles')}</li>\n <li>{t('workflows.visualEditor.hint.editSteps', 'Click steps and transitions to edit them')}</li>\n <li>{t('workflows.visualEditor.hint.validate', 'Validate before saving')}</li>\n </ul>\n </div>\n </Alert>\n </div>\n </div>\n )}\n\n {/* Main Canvas */}\n <div className=\"min-w-0 flex-1 p-6\">\n <div className=\"relative h-[72svh] min-h-[640px]\">\n <div className=\"h-full rounded-lg border bg-card\">\n <WorkflowGraph\n initialNodes={nodes}\n initialEdges={edges}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onNodeClick={handleNodeClick}\n onEdgeClick={handleEdgeClick}\n onConnect={handleConnect}\n editable={!isCodeOnly}\n height=\"100%\"\n />\n </div>\n\n {/* Empty State */}\n {nodes.length === 0 && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center px-4\">\n <div className=\"text-center\">\n <h2 className=\"mb-2 text-xl font-semibold text-foreground\">\n {t('workflows.visualEditor.startBuilding')}\n </h2>\n <p className=\"mb-4 text-muted-foreground\">\n {t('workflows.visualEditor.clickToAddFromPalette')}\n </p>\n <button\n onClick={handleLoadExample}\n className=\"pointer-events-auto text-sm text-primary hover:underline\"\n >\n {t('workflows.visualEditor.loadExampleWorkflow')}\n </button>\n </div>\n </div>\n )}\n </div>\n </div>\n </div>\n )}\n {sharedDialogs}\n {ConfirmDialogElement}\n </Page>\n )\n}\n\n// Helper functions\nfunction getDefaultLabel(nodeType: string): string {\n const labels: Record<string, string> = {\n start: 'Start',\n end: 'End',\n userTask: 'New User Task',\n automated: 'New Automated Task',\n decision: 'Decision Point',\n waitForSignal: 'Wait for Signal',\n waitForTimer: 'Wait for Timer',\n }\n return labels[nodeType] || 'New Step'\n}\n\nfunction getDefaultBadge(nodeType: string): string {\n const badges: Record<string, string> = {\n start: 'Start',\n end: 'End',\n userTask: 'User Task',\n automated: 'Automated',\n decision: 'Decision',\n waitForSignal: 'Wait for Signal',\n waitForTimer: 'Wait for Timer',\n }\n return badges[nodeType] || 'Task'\n}\n\n"],
5
- "mappings": ";AA6oBQ,SAkBJ,UAlBI,KA+BE,YA/BF;AA3oBR,SAAS,qBAAqB;AAE9B,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,SAAS,8BAA8B;AACvC,SAAS,8BAA8B;AAEvC,SAAS,UAAU,aAAa,iBAAiB;AACjD,SAAS,WAAW,iBAAiB,mBAAmB;AACxD,SAAS,mBAAmB,mBAAmB,uBAAuB,gBAAgB,sBAAsB,0BAA2C;AACvJ,SAAS,uBAAuB,6BAA6B;AAC7D,SAAS,mCAAmC;AAC5C,SAAS,oCAAoC;AAC7C,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,aAAa;AACtB,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB;AAC1B,SAAS,sBAAsB;AAC/B,SAAS,OAAO,kBAAkB;AAClC,SAAS,wBAAwB;AACjC,SAAS,YAAY;AACrB,SAAS,kBAAkB;AAC3B,SAAS,SAAS,mCAAmC;AACrD,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,6BAA6B,2CAA2C;AACjF,SAAS,aAAa;AACtB,SAAS,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b,+BAAC,SAAI,WAAU,eACb;AAAA,8BAAC,QAAG,WAAU,8CACX,YAAE,sCAAsC,GAC3C;AAAA,UACA,oBAAC,OAAE,WAAU,8BACV,YAAE,8CAA8C,GACnD;AAAA,UACA;AAAA,YAAC;AAAA;AAAA,cACC,SAAS;AAAA,cACT,WAAU;AAAA,cAET,YAAE,4CAA4C;AAAA;AAAA,UACjD;AAAA,WACF,GACF;AAAA,SAEJ,GACF;AAAA,OACF;AAAA,IAED;AAAA,IACA;AAAA,KACH;AAEJ;AAGA,SAAS,gBAAgB,UAA0B;AACjD,QAAM,SAAiC;AAAA,IACrC,OAAO;AAAA,IACP,KAAK;AAAA,IACL,UAAU;AAAA,IACV,WAAW;AAAA,IACX,UAAU;AAAA,IACV,eAAe;AAAA,IACf,cAAc;AAAA,EAChB;AACA,SAAO,OAAO,QAAQ,KAAK;AAC7B;AAEA,SAAS,gBAAgB,UAA0B;AACjD,QAAM,SAAiC;AAAA,IACrC,OAAO;AAAA,IACP,KAAK;AAAA,IACL,UAAU;AAAA,IACV,WAAW;AAAA,IACX,UAAU;AAAA,IACV,eAAe;AAAA,IACf,cAAc;AAAA,EAChB;AACA,SAAO,OAAO,QAAQ,KAAK;AAC7B;",
6
- "names": ["metadata"]
4
+ "sourcesContent": ["'use client'\n\nimport { WorkflowGraph } from '../../../components/WorkflowGraph'\nimport { useLastRunOverlay } from '../../../components/run/useLastRunOverlay'\n// Conditional imports based on feature flag\nimport { NodeEditDialog } from '../../../components/NodeEditDialog'\nimport { EdgeEditDialog } from '../../../components/EdgeEditDialog'\nimport { NodeEditDialogCrudForm } from '../../../components/NodeEditDialogCrudForm'\nimport { EdgeEditDialogCrudForm } from '../../../components/EdgeEditDialogCrudForm'\nimport type { Node, Edge, Connection } from '@xyflow/react'\nimport { useState, useCallback, useEffect, useMemo, useRef } from 'react'\nimport { useRouter, useSearchParams, usePathname } from 'next/navigation'\nimport { graphToDefinition, definitionToGraph, applyAutoLayout, validateWorkflowGraph, generateStepId, generateTransitionId, appendWorkflowEdge, getBadgeForNodeType, ValidationError } from '../../../lib/graph-utils'\nimport { convertStepType, type ConvertibleStepType } from '../../../lib/step-type-conversion'\nimport { collectValidationIssues, countIssuesBySeverity, type WorkflowIssueTranslator, type WorkflowValidationIssue, type ZodIssueLike } from '../../../lib/collect-validation-issues'\nimport { formatWorkflowValidationError } from '../../../lib/format-validation-error'\nimport type { WorkflowGraphDropEvent, WorkflowGraphFocusTarget, WorkflowGraphNodesChangeMeta } from '../../../components/WorkflowGraph'\nimport { resolveNewNodePlacement } from '../../../lib/node-placement'\nimport {\n commitEditorHistory,\n createEditorHistory,\n redoEditorHistory,\n undoEditorHistory,\n type EditorHistoryState,\n type WorkflowEditorDocument,\n type WorkflowEditorPanelState,\n} from '../../../lib/editor-history'\nimport {\n parseWorkflowSubgraph,\n pasteWorkflowSubgraph,\n serializeWorkflowSubgraph,\n stringifyWorkflowSubgraph,\n type SubgraphClipboardParseFailure,\n type WorkflowSubgraphClipboard,\n} from '../../../lib/subgraph-clipboard'\nimport {\n annotationsFromNodes,\n annotationsToNodes,\n createGroupNode,\n createNoteNode,\n isAnnotationNode,\n readEditorAnnotations,\n removeAnnotationNode,\n updateAnnotationNode,\n type WorkflowGroupNodeData,\n type WorkflowNoteNodeData,\n} from '../../../lib/editor-annotations'\nimport { WORKFLOW_GROUP_TOGGLE_EVENT } from '../../../lib/annotation-events'\nimport { AnnotationEditDialog } from '../../../components/AnnotationEditDialog'\nimport { WorkflowCodeView } from '../../../components/WorkflowCodeView'\nimport { DefinitionMetadataDrawer, type DefinitionMetadataSection } from '../../../components/DefinitionMetadataDrawer'\nimport { TriggersDialog } from '../../../components/TriggersDialog'\nimport { describeCodeViewDraft, evaluateCodeViewDraft } from '../../../lib/code-view-apply'\nimport {\n WorkflowAiDraftDialog,\n type WorkflowAiDraftApplyRefusal,\n} from '../../../components/WorkflowAiDraftDialog'\nimport { buildAiCheckpointLabel } from '../../../lib/ai-authoring'\nimport {\n locateDefinitionJsonEntities,\n locateIssues,\n severityByLine,\n} from '../../../lib/definition-json-locations'\nimport { WorkflowCommandPalette } from '../../../components/WorkflowCommandPalette'\nimport { buildWorkflowEditorCommands, type WorkflowEditorCommand } from '../../../lib/editor-commands'\nimport { NUDGE_COMMIT_DELAY_MS, nudgeOffset, nudgeSelectedNodes, resolveNudgeDirection, selectedNodeIds } from '../../../lib/node-nudge'\nimport { canRedoEditorHistory, canUndoEditorHistory } from '../../../lib/editor-history'\nimport { readPaletteDragItem, writePaletteDragPayload } from '../../../lib/palette-drag'\nimport { appendActivityToRoute, insertStepOnRoute, type PaletteDropRejectionCode } from '../../../lib/palette-drop'\nimport { useActivityTypeOptions } from '../../../components/fields/useActivityTypeOptions'\nimport { resolveActivityIcon } from '../../../components/WorkflowRouteChips'\nimport { performDeleteEdgeFlow, performDeleteNodeFlow } from '../../../lib/visual-editor-delete-flow'\nimport { resolveCrudFormDialogsEnabled } from '../../../lib/crud-form-dialogs-flag'\nimport { decideDraftRestore, isServerDraftEligible, stableSerializeDefinition } from '../../../lib/draft-restore'\nimport { buildDefinitionPayload, buildMetadataPayload } from '../../../lib/definition-payload'\nimport { resolveDefinitionInterpolationMode, type WorkflowInterpolationMode } from '../../../lib/interpolation-pipeline'\nimport { findRouteKindDescriptorForHandle } from '../../../lib/route-kinds'\nimport { buildWorkflowRouteEdge } from '../../../lib/route-edge'\nimport { isDecisionSourceHandle, type DecisionRowLike } from '../../../lib/node-outcome-rows'\nimport { STRUCTURAL_EDIT_CONFLICT_CODE } from '../../../lib/definition-edit-safety'\nimport type { WorkflowErrorHandlerConfig } from '../../../data/validators'\nimport { WORKFLOW_NODE_DELETE_EVENT } from '../../../components/WorkflowNodeCard'\nimport { WORKFLOW_ROUTE_CHIP_EVENT, WORKFLOW_ROUTE_ACTIVITY_EVENT, type RouteChipEventDetail, type RouteActivityEventDetail } from '../../../lib/route-chip-events'\nimport { ActivityEditDialog } from '../../../components/ActivityEditDialog'\nimport type { Activity } from '../../../components/fields/ActivityArrayEditor'\nimport { applyRouteOrder, canNormalizeRoutePriorities, normalizeRoutePriorities, readRouteOrder, type RouteOrderEntry } from '../../../lib/route-priority'\nimport { classifyConnection, applyInputMappingToNodes, buildDataMappingEdge } from '../../../lib/data-edge-mapping'\nimport { reattachWorkflowEdge, type EdgeReattachRejection } from '../../../lib/edge-reattachment'\nimport { workflowDefinitionDataSchema, type WorkflowIoContract } from '../../../data/validators'\nimport { collectActivityConfigWarnings } from '../../../data/activity-config-warnings'\nimport {\n applyIfElseRoutes,\n applySwitchRoutes,\n isBranchingNodeType,\n readBranchingRoutes,\n readSwitchField,\n type SwitchRoutesValue,\n} from '../../../lib/branching-routes'\nimport {\n buildTriggerPayloadContracts,\n computeContextLedger,\n type LedgerContract,\n type LedgerWorkflowDefinition,\n} from '../../../lib/context-ledger'\nimport { useAvailableEvents } from '@open-mercato/ui/backend/inputs/EventSelect'\nimport { toUnresolvedContextRefIssues } from '../../../lib/definition-evaluation'\nimport type { PinnedSampleEnvelope } from '../../../lib/sample-resolver'\nimport { Page } from '@open-mercato/ui/backend/Page'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Switch } from '@open-mercato/ui/primitives/switch'\nimport {\n Drawer,\n DrawerBody,\n DrawerContent,\n DrawerDescription,\n DrawerFooter,\n DrawerHeader,\n DrawerTitle,\n} from '@open-mercato/ui/primitives/drawer'\nimport { LoadingMessage } from '@open-mercato/ui/backend/detail'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport { ConfirmDialog, useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { formatRelativeTime } from '@open-mercato/shared/lib/time'\nimport { FormHeader, ActionsDropdown, type ActionMenuEntry } from '@open-mercato/ui/backend/forms'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { apiFetch } from '@open-mercato/ui/backend/utils/api'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from '@open-mercato/ui/backend/injection/recordContext'\nimport { readJsonSafe } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport {\n listStartFixtures,\n removeStartFixture,\n upsertStartFixture,\n type WorkflowStartFixtures,\n} from '../../../lib/start-fixtures'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { ChevronDown, ChevronRight, CircleAlert, CircleQuestionMark, Code, Command, Group, History, Maximize2, Minimize2, Network, PanelLeftClose, PanelLeftOpen, PanelRightOpen, Play, Save, ShieldMinus, Sparkles, StickyNote, Trash2, TriangleAlert, X } from 'lucide-react'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { usePersistedBooleanFlag } from '@open-mercato/ui/backend/crud/usePersistedBooleanFlag'\nimport { useSidebarCollapse } from '@open-mercato/ui/backend/AppShell'\nimport { NODE_TYPE_ICONS, NODE_TYPE_COLORS, NODE_TYPE_LABELS } from '../../../lib/node-type-icons'\nimport { TemplateGalleryDialog, type WorkflowTemplateGalleryItem } from '../../../components/TemplateGalleryDialog'\nimport { MobileVisualEditor } from '../../../components/mobile/MobileVisualEditor'\nimport { useIsMobile } from '@open-mercato/ui/hooks/useIsMobile'\nimport type { WorkflowContextSchema, WorkflowDefinitionData, WorkflowDefinitionTrigger } from '../../../data/entities'\nimport type { WorkflowMetadataState, WorkflowMetadataHandlers } from '../../../data/types'\nimport * as React from 'react'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\ntype WorkflowDefinitionDraftPayload = {\n definition: Record<string, unknown>\n metadata?: Record<string, unknown> | null\n baseUpdatedAt: string | null\n updatedAt: string | null\n}\n\nconst DRAFT_AUTOSAVE_DEBOUNCE_MS = 2000\nconst DRAFT_SAVED_LABEL_REFRESH_MS = 30000\n\n/**\n * Ledger-checked context-reference warnings for the Problems panel (spec\n * section 3.5). The editor validates UNSAVED state, so the ledger is computed\n * CLIENT-side with `resolveOutputContract` pinned to 'unknown' instead of\n * fetching the server ledger from the context-schema API: the client ledger is\n * type-poorer (activity outputs stay single `unknown` nodes rather than typed\n * contract entries) but structurally identical, and since `unknown` entries\n * resolve every sub-path in the checker, the degradation can only suppress\n * warnings, never fabricate them. Warnings merge into the same ZodIssueLike\n * channel as activity-config warnings, so `collectValidationIssues` maps them\n * to nodes/edges and they never block saves.\n */\nfunction computeClientContextLedger(\n definitionData: WorkflowDefinitionData,\n triggerPayloadContracts?: Record<string, LedgerContract>,\n) {\n return computeContextLedger(definitionData as unknown as LedgerWorkflowDefinition, {\n resolveOutputContract: () => 'unknown',\n triggerPayloadContracts,\n })\n}\n\nfunction collectContextRefWarnings(\n definitionData: WorkflowDefinitionData,\n translate: ReturnType<typeof useT>,\n triggerPayloadContracts?: Record<string, LedgerContract>,\n): ZodIssueLike[] {\n const ledger = computeClientContextLedger(definitionData, triggerPayloadContracts)\n return toUnresolvedContextRefIssues(definitionData, ledger, translate)\n}\n\n/**\n * VisualEditorPage - Visual workflow definition editor\n *\n * Layout:\n * - Page Header: Title, description, and action buttons (Save, Validate, Test)\n * - Workflow Metadata: Collapsible form for workflow details\n * - Page Body:\n * - Left sidebar: Step palette (click to add)\n * - Main canvas: ReactFlow graph editor\n * - Flash Messages: Top-right positioned validation messages\n * - Edit Dialogs: Modal dialogs for editing steps and transitions\n */\n/**\n * Resolve the declared IO port contracts of every sub-workflow referenced by a\n * definition, keyed by `subWorkflowId`, so SUB_WORKFLOW nodes can render the\n * child's IN/OUT ports. Fail-open: any lookup error leaves that child without a\n * contract and its node simply renders without ports.\n */\nasync function loadSubWorkflowContracts(\n definition: { steps?: Array<{ stepType?: string; config?: { subWorkflowId?: string } }> } | null | undefined,\n): Promise<Map<string, WorkflowIoContract>> {\n const contracts = new Map<string, WorkflowIoContract>()\n const subWorkflowIds = Array.from(\n new Set(\n (definition?.steps || [])\n .filter((step) => step?.stepType === 'SUB_WORKFLOW' && step?.config?.subWorkflowId)\n .map((step) => step.config!.subWorkflowId as string),\n ),\n )\n await Promise.all(\n subWorkflowIds.map(async (workflowId) => {\n try {\n const res = await apiCall<{ data?: Array<{ definition?: { io?: WorkflowIoContract } }> }>(\n `/api/workflows/definitions?workflowId=${encodeURIComponent(workflowId)}&limit=1`,\n )\n const io = res.ok ? res.result?.data?.[0]?.definition?.io : undefined\n if (io) contracts.set(workflowId, io)\n } catch {\n // fail-open\n }\n }),\n )\n return contracts\n}\n\nconst PALETTE_NODE_TYPES = ['start', 'userTask', 'automated', 'invokeAgent', 'ifElse', 'switch', 'waitForSignal', 'waitForTimer', 'waitForCondition', 'subWorkflow', 'end'] as const\n\n/** Body of a definition update \u2014 shared by explicit Save and the quiet autosave. */\ntype DefinitionUpdateBody = {\n workflowName: string\n description: string | null\n version: number\n definition: ReturnType<typeof buildDefinitionPayload>\n metadata: ReturnType<typeof buildMetadataPayload>\n enabled: boolean\n effectiveFrom: string | null\n effectiveTo: string | null\n}\n\n/**\n * Edit-safety rule (spec 4.1): the definition PUT refuses a topology change\n * while instances are still executing this version. The refusal is a dead end\n * without its remedy, so the rejected payload rides along and is re-applied to\n * the freshly minted version.\n */\ntype StructuralEditConflict = {\n activeInstanceCount: number\n payload: DefinitionUpdateBody\n}\n\nfunction readStructuralEditConflictCount(status: number, body: unknown): number | null {\n if (status !== 409) return null\n const record = body && typeof body === 'object' ? (body as Record<string, unknown>) : null\n if (!record || record.code !== STRUCTURAL_EDIT_CONFLICT_CODE) return null\n return typeof record.activeInstanceCount === 'number' ? record.activeInstanceCount : 0\n}\n\nexport default function VisualEditorPage() {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const pathname = usePathname()\n const definitionId = searchParams.get('id')\n const templateId = searchParams.get('template')\n const isMobile = useIsMobile()\n\n const { confirm, ConfirmDialogElement } = useConfirmDialog()\n\n const [isLoading, setIsLoading] = useState(!!definitionId)\n const [isSaving, setIsSaving] = useState(false)\n const [nodes, setNodes] = useState<Node[]>([])\n const [edges, setEdges] = useState<Edge[]>([])\n const [selectedNode, setSelectedNode] = useState<Node | null>(null)\n const [selectedEdge, setSelectedEdge] = useState<Edge | null>(null)\n const [edgeDialogFocusFieldId, setEdgeDialogFocusFieldId] = useState<string | null>(null)\n // Latest edges, readable from window-event handlers without re-subscribing on\n // every graph change (route chips resolve their edge through this).\n const edgesRef = React.useRef<Edge[]>([])\n edgesRef.current = edges\n const nodesRef = React.useRef<Node[]>([])\n nodesRef.current = nodes\n // Definition metadata lives in a right-side Drawer, so it costs the canvas\n // nothing and never needs hiding. It starts closed \u2014 the canvas is what the\n // page is for \u2014 and `handleSave` opens it when the required id/name are\n // still missing, which is the moment the author needs it.\n const [metadataOpen, setMetadataOpen] = useState(false)\n // Which section the drawer lands on. Only the canvas trigger pill sets it\n // (fidelity gap #5) \u2014 every other way in wants the top of the form \u2014 so it is\n // cleared whenever the drawer is opened by anything else.\n const [metadataFocusSection, setMetadataFocusSection] = useState<DefinitionMetadataSection | null>(null)\n const [triggersDialogOpen, setTriggersDialogOpen] = useState(false)\n // The route activity chip's target: which edge + activity the focused\n // single-activity modal is editing (fidelity gap #6 follow-up).\n const [activityEdit, setActivityEdit] = useState<{ edgeId: string; activityId: string } | null>(null)\n // The START node's trigger cap opens a focused Triggers modal (Direction A),\n // NOT the five-section definition drawer \u2014 the author clicked \"what starts\n // this\", so the affordance opens exactly that.\n const handleOpenTriggers = useCallback(() => {\n setTriggersDialogOpen(true)\n }, [])\n // The focus target is one-shot: every other way into the drawer wants the top\n // of the form, so closing it clears the request.\n const handleMetadataOpenChange = useCallback((open: boolean) => {\n if (!open) setMetadataFocusSection(null)\n setMetadataOpen(open)\n }, [])\n const [isCompactViewport, setIsCompactViewport] = useState(false)\n const [autosaveState, setAutosaveState] = useState<'idle' | 'saving' | 'saved'>('idle')\n const [structuralConflict, setStructuralConflict] = useState<StructuralEditConflict | null>(null)\n const [isCreatingVersion, setIsCreatingVersion] = useState(false)\n // Debounced autosave-on-drag plumbing. `performAutosaveRef` is reassigned each\n // render so the debounced timer always runs the latest closure (no stale nodes).\n const autosaveTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n const performAutosaveRef = React.useRef<() => Promise<void>>(async () => {})\n // Last payload the quiet autosave actually persisted, so an unchanged graph\n // never issues a redundant PUT (#4248). Cleared on failure so the next change\n // retries the write.\n const lastAutosavedBodyRef = React.useRef<string | null>(null)\n const { value: paletteCollapsed, toggle: togglePaletteCollapsed, setValue: setPaletteCollapsed } = usePersistedBooleanFlag('om:wf-editor-palette', false)\n const [showPaletteHowTo, setShowPaletteHowTo] = useState(false)\n const { value: focusMode, setValue: setFocusMode, toggle: toggleFocus } = usePersistedBooleanFlag('om:wf-editor-focus', false)\n // Compensation ghosts (spec \u00A74.4) are OFF by default and remembered per\n // author: they are a read-only overlay, never part of the document.\n const { value: showCompensation, toggle: toggleCompensation } = usePersistedBooleanFlag('om:wf-editor-compensation', false)\n // \"Show last run\" (spec \u00A78.3). OFF by default and remembered per author, and\n // it fetches nothing until it is on \u2014 an author editing a definition should\n // not pay for three requests they never asked for.\n const { value: showLastRun, toggle: toggleLastRun } = usePersistedBooleanFlag('om:wf-editor-last-run', false)\n const { requestCollapse, releaseRequest } = useSidebarCollapse()\n // Remember the palette state from before Focus mode took over so we can\n // restore exactly what the author had when they exit.\n const priorPaletteCollapsedRef = React.useRef<boolean | null>(null)\n\n // Focus mode orchestrator: collapse the app sidebar + palette when entering\n // and restore the author's prior palette state when leaving. Runs on mount\n // too, so a persisted `focusMode === true` applies the collapses immediately.\n // The metadata Drawer is not touched: it overlays rather than displaces the\n // canvas, so hiding it would buy Focus mode nothing and would only make the\n // palette's \"Toggle the workflow details panel\" command a silent no-op.\n useEffect(() => {\n if (focusMode) {\n if (priorPaletteCollapsedRef.current === null) priorPaletteCollapsedRef.current = paletteCollapsed\n requestCollapse(true)\n setPaletteCollapsed(true)\n } else {\n releaseRequest()\n if (priorPaletteCollapsedRef.current !== null) {\n setPaletteCollapsed(priorPaletteCollapsedRef.current)\n priorPaletteCollapsedRef.current = null\n }\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [focusMode])\n\n // Always release the app-sidebar request when the editor unmounts so the\n // user's prior sidebar state is restored when they navigate away.\n useEffect(() => () => releaseRequest(), [releaseRequest])\n\n // Track the compact (<1280px) layout after hydration\n useEffect(() => {\n if (typeof window === 'undefined') return\n const mediaQuery = window.matchMedia('(max-width: 1279px)')\n const applyViewportMode = () => {\n setIsCompactViewport(mediaQuery.matches)\n }\n\n applyViewportMode()\n mediaQuery.addEventListener('change', applyViewportMode)\n\n return () => {\n mediaQuery.removeEventListener('change', applyViewportMode)\n }\n }, [])\n const [showNodeDialog, setShowNodeDialog] = useState(false)\n const [showEdgeDialog, setShowEdgeDialog] = useState(false)\n\n const crudFormDialogsEnabled = resolveCrudFormDialogsEnabled(process.env.NEXT_PUBLIC_WORKFLOW_CRUDFORM_ENABLED)\n\n // Where the inspectors are MOUNTED. Both of them now open as the wide overlay\n // Drawer (#4708 for the step form, its follow-up for the route form): the\n // 384px rail could not hold either dense form. What survives of the rail\n // decision is the mount point \u2014 on a roomy viewport the panels live inside the\n // editor layout row, below it they ride the shared dialog stack \u2014 plus the\n // shortcut ownership that keys off it. The legacy dialogs keep their own modal\n // chrome; they are deprecated and are not being redesigned.\n const inspectorsDocked = crudFormDialogsEnabled && !isMobile && !isCompactViewport\n\n // Sticky notes and groups (spec 4.5) are canvas nodes with their own tiny\n // inspector \u2014 they carry no step configuration, so they never open the step\n // dialog.\n const [selectedAnnotation, setSelectedAnnotation] = useState<Node | null>(null)\n const [showAnnotationDialog, setShowAnnotationDialog] = useState(false)\n // Cmd+K command palette (spec 4.6). Together with the inspector and the\n // Problems panel it is the complete non-pointer authoring path, so every\n // mutating action the toolbar offers is reachable through it.\n const [showCommandPalette, setShowCommandPalette] = useState(false)\n // Code view, stage 1 (spec \u00A72.2): the assembled definition JSON read-only,\n // beside the same structured issue list the Problems panel renders.\n const [showCodeView, setShowCodeView] = useState(false)\n const [showClearConfirm, setShowClearConfirm] = useState(false)\n const [showTemplateGallery, setShowTemplateGallery] = useState(false)\n const [problems, setProblems] = useState<WorkflowValidationIssue[]>([])\n const [showProblems, setShowProblems] = useState(false)\n const [problemsCollapsed, setProblemsCollapsed] = useState(false)\n const [focusTarget, setFocusTarget] = useState<WorkflowGraphFocusTarget | null>(null)\n const focusRequestRef = React.useRef(0)\n\n // Error-severity issue counts per node id \u2014 drives the per-node error badges\n // on the canvas; clearing the problems list clears every badge.\n const nodeErrorCounts = React.useMemo(() => {\n const counts: Record<string, number> = {}\n for (const issue of problems) {\n if (issue.severity !== 'error' || !issue.nodeId) continue\n counts[issue.nodeId] = (counts[issue.nodeId] ?? 0) + 1\n }\n return counts\n }, [problems])\n\n // Workflow metadata state\n const [workflowId, setWorkflowId] = useState('')\n const lastRunOverlay = useLastRunOverlay({ workflowId, enabled: showLastRun && !!definitionId })\n const [workflowName, setWorkflowName] = useState('')\n const [description, setDescription] = useState('')\n const [version, setVersion] = useState(1)\n const [enabled, setEnabled] = useState(true)\n const [category, setCategory] = useState('')\n const [tags, setTags] = useState<string[]>([])\n const [icon, setIcon] = useState('')\n const [effectiveFrom, setEffectiveFrom] = useState('')\n const [effectiveTo, setEffectiveTo] = useState('')\n const [triggers, setTriggers] = useState<WorkflowDefinitionTrigger[]>([])\n const [contextSchema, setContextSchema] = useState<WorkflowContextSchema | undefined>(undefined)\n // The sub-workflow io port contract is not edited on this page, but it must\n // survive the graph \u2192 definition rebuild on save/draft, so it is carried as\n // pass-through state exactly like contextSchema.\n const [definitionIo, setDefinitionIo] = useState<WorkflowIoContract | undefined>(undefined)\n // Interpolation mode (spec \u00A73.6): new definitions start strict (matching the\n // POST create default); loaded definitions keep their stored value, and\n // ABSENT stays absent through save round-trips so existing lenient\n // definitions are never flipped by an unrelated edit.\n const [interpolation, setInterpolation] = useState<WorkflowInterpolationMode | undefined>(undefined)\n // Definition-level catch-all error handler (spec section 5.9). Pass-through\n // state like contextSchema/io: absent stays absent through save round-trips.\n const [errorHandler, setErrorHandler] = useState<WorkflowErrorHandlerConfig | undefined>(undefined)\n const [loadedMetadata, setLoadedMetadata] = useState<Record<string, unknown> | null>(null)\n const [source, setSource] = useState<'code' | 'code_override' | 'user' | null>(null)\n const [updatedAt, setUpdatedAt] = useState<string | null>(null)\n\n // Start-instance dialog state (mirrors the non-visual edit page UX)\n const [startOpen, setStartOpen] = useState(false)\n const [startContext, setStartContext] = useState('{}')\n const [starting, setStarting] = useState(false)\n // Spec section 8.2 test-run modes. Independent by design: a real run can be\n // stepped through, and a dry run can be let loose end to end.\n const [startDryRun, setStartDryRun] = useState(false)\n const [startStepThrough, setStartStepThrough] = useState(false)\n const [fixtureName, setFixtureName] = useState('')\n\n // Undo/redo (spec \u00A74.5). One stack over the whole editor document, so an\n // inspector save undoes exactly like a deleted route. Snapshots are cheap\n // because every mutating path already replaces the node/edge arrays instead\n // of mutating them, so an entry only holds references.\n const [history, setHistory] = useState<EditorHistoryState<WorkflowEditorDocument>>(createEditorHistory)\n const historyRef = React.useRef(history)\n historyRef.current = history\n const loadedMetadataRef = React.useRef<Record<string, unknown> | null>(null)\n loadedMetadataRef.current = loadedMetadata\n\n const historyLabels = useMemo(() => ({\n addStep: t('workflows.visualEditor.history.addStep', 'Add step'),\n editStep: t('workflows.visualEditor.history.editStep', 'Edit step'),\n editRoute: t('workflows.visualEditor.history.editRoute', 'Edit route'),\n deleteStep: t('workflows.visualEditor.history.deleteStep', 'Delete step'),\n deleteRoute: t('workflows.visualEditor.history.deleteRoute', 'Delete route'),\n connect: t('workflows.visualEditor.history.connect', 'Connect steps'),\n reattach: t('workflows.visualEditor.history.reattach', 'Re-target route'),\n move: t('workflows.visualEditor.history.move', 'Move steps'),\n convert: t('workflows.visualEditor.history.convert', 'Change step type'),\n branchRoutes: t('workflows.visualEditor.history.branchRoutes', 'Edit branch routes'),\n routeOrder: t('workflows.visualEditor.history.routeOrder', 'Reorder routes'),\n pinSample: t('workflows.visualEditor.history.pinSample', 'Pin sample'),\n unpinSample: t('workflows.visualEditor.history.unpinSample', 'Unpin sample'),\n tidy: t('workflows.visualEditor.history.tidy', 'Tidy layout'),\n paste: t('workflows.visualEditor.history.paste', 'Paste'),\n duplicate: t('workflows.visualEditor.history.duplicate', 'Duplicate'),\n insertOnRoute: t('workflows.visualEditor.history.insertOnRoute', 'Insert step on route'),\n addActivity: t('workflows.visualEditor.history.addActivity', 'Add action to route'),\n addNote: t('workflows.visualEditor.history.addNote', 'Add note'),\n addGroup: t('workflows.visualEditor.history.addGroup', 'Add group'),\n editAnnotation: t('workflows.visualEditor.history.editAnnotation', 'Edit annotation'),\n deleteAnnotation: t('workflows.visualEditor.history.deleteAnnotation', 'Delete annotation'),\n toggleGroup: t('workflows.visualEditor.history.toggleGroup', 'Collapse group'),\n saveFixture: t('workflows.visualEditor.history.saveFixture', 'Save start fixture'),\n deleteFixture: t('workflows.visualEditor.history.deleteFixture', 'Delete start fixture'),\n applyCode: t('workflows.visualEditor.history.applyCode', 'Apply JSON from Code view'),\n }), [t])\n\n // The definition-panel fields ride ALONG with the document so the Code view's\n // Apply \u2014 which replaces the whole definition, panel fields included \u2014 is one\n // fully reversible action. Every other entry captures them too, which costs\n // five references and makes an undo restore the state it claims to.\n const panelStateRef = React.useRef<WorkflowEditorPanelState>({\n triggers: [],\n contextSchema: undefined,\n io: undefined,\n interpolation: undefined,\n errorHandler: undefined,\n })\n useEffect(() => {\n panelStateRef.current = {\n triggers,\n contextSchema,\n io: definitionIo,\n interpolation,\n errorHandler,\n }\n }, [triggers, contextSchema, definitionIo, interpolation, errorHandler])\n\n const captureDocument = useCallback((): WorkflowEditorDocument => ({\n nodes: nodesRef.current,\n edges: edgesRef.current,\n metadata: loadedMetadataRef.current,\n panel: panelStateRef.current,\n }), [])\n\n const commitCapturedDocument = useCallback((document: WorkflowEditorDocument, label: string) => {\n setHistory((current) => commitEditorHistory(current, document, label))\n }, [])\n\n const commitHistory = useCallback((label: string) => {\n commitCapturedDocument(captureDocument(), label)\n }, [captureDocument, commitCapturedDocument])\n\n // A whole-document replacement (draft restore, template load, clear) starts a\n // fresh stack: those paths also rewrite the definition-panel fields, which the\n // document deliberately does not version, so undoing into them would restore\n // half a workflow.\n const resetHistory = useCallback(() => {\n setHistory(createEditorHistory<WorkflowEditorDocument>())\n }, [])\n\n const mutationContextId = `workflows.definitions.visual-editor:${definitionId ?? 'unknown'}`\n const { runMutation, retryLastMutation } = useGuardedMutation<Record<string, unknown>>({\n contextId: mutationContextId,\n })\n\n const isCodeOnly = source === 'code'\n const isCodeOverride = source === 'code_override'\n\n // Per-user draft layer (spec \u00A74.7): drafts persist server-side only for\n // SAVED definitions (uuid ids). Unsaved/new definitions and code-defined\n // workflows keep their state client-side only \u2014 no persistence at all.\n // Draft saves deliberately never participate in the definition's optimistic\n // lock; only the explicit Save PUT sends the lock header.\n const draftEligible = isServerDraftEligible(definitionId) && !isCodeOnly\n const [pendingDraft, setPendingDraft] = useState<{ draft: WorkflowDefinitionDraftPayload; baseMismatch: boolean } | null>(null)\n const [draftAutosaveReady, setDraftAutosaveReady] = useState(false)\n const [draftSavedAt, setDraftSavedAt] = useState<string | null>(null)\n const [draftSaveFailed, setDraftSaveFailed] = useState(false)\n const [draftClock, setDraftClock] = useState(0)\n const lastPersistedDraftRef = useRef<string | null>(null)\n const draftSuspendedRef = useRef(false)\n\n // Load existing definition if ID is provided\n useEffect(() => {\n const loadDefinition = async () => {\n if (!definitionId) {\n setInterpolation('strict')\n setIsLoading(false)\n return\n }\n\n try {\n const result = await apiCall<{ data: any; error?: string }>(`/api/workflows/definitions/${definitionId}`)\n\n if (!result.ok) {\n flash(`Failed to load workflow: ${result.result?.error || 'Unknown error'}`, 'error')\n setIsLoading(false)\n return\n }\n\n const definition = result.result?.data\n\n // Populate metadata\n setWorkflowId(definition.workflowId)\n setWorkflowName(definition.workflowName || definition.definition.workflowName || '')\n setDescription(definition.description || definition.definition.description || '')\n setVersion(definition.version)\n setEnabled(definition.enabled)\n setCategory(definition.metadata?.category || '')\n setTags(definition.metadata?.tags || [])\n setIcon(definition.metadata?.icon || '')\n setEffectiveFrom(definition.effectiveFrom || '')\n setEffectiveTo(definition.effectiveTo || '')\n\n // Resolve referenced sub-workflow port contracts so SUB_WORKFLOW nodes\n // render IN/OUT ports without opening the child (fail-open).\n const childContracts = await loadSubWorkflowContracts(definition.definition)\n\n // Convert definition to graph. Annotations ride alongside the steps as\n // canvas nodes so a note drags, undoes and autosaves like everything\n // else \u2014 they are filtered back out on the way to `definition.steps`.\n const graph = definitionToGraph(definition.definition, { childContracts })\n const loadedMetadataBag = definition.metadata && typeof definition.metadata === 'object'\n ? (definition.metadata as Record<string, unknown>)\n : null\n const annotationNodes = annotationsToNodes(readEditorAnnotations(loadedMetadataBag))\n setNodes([...graph.nodes, ...annotationNodes])\n setEdges(graph.edges)\n\n // Load embedded triggers from definition\n const loadedTriggers = definition.definition?.triggers || []\n setTriggers(loadedTriggers)\n\n // Carry the declared context schema and the FULL metadata object so\n // save/draft rebuilds cannot silently strip keys the editor does not\n // edit (contextSchema, future metadata.editor.* keys).\n const loadedContextSchema = (definition.definition?.contextSchema ?? undefined) as WorkflowContextSchema | undefined\n setContextSchema(loadedContextSchema)\n const loadedIo = (definition.definition?.io ?? undefined) as WorkflowIoContract | undefined\n setDefinitionIo(loadedIo)\n const loadedInterpolation = resolveDefinitionInterpolationMode(definition.definition)\n setInterpolation(loadedInterpolation)\n const loadedErrorHandler = (definition.definition?.errorHandler ?? undefined) as WorkflowErrorHandlerConfig | undefined\n setErrorHandler(loadedErrorHandler)\n const loadedMetadataObject = loadedMetadataBag ? { ...loadedMetadataBag } : null\n setLoadedMetadata(loadedMetadataObject)\n\n // Track source so the editor mirrors the non-visual edit page UX:\n // code \u2192 read-only with Customize button; code_override \u2192 editable\n // with Reset to code; user \u2192 editable, no banner.\n const loadedSource = (definition.source as 'code' | 'code_override' | 'user') ?? null\n setSource(loadedSource)\n const loadedUpdatedAt = typeof definition.updatedAt === 'string' ? definition.updatedAt : null\n setUpdatedAt(loadedUpdatedAt)\n\n // Draft layer: compare against the ROUND-TRIPPED definition (graph \u2192\n // definition with the same normalization the autosave uses) so a mere\n // load/serialize drift never looks like an unsaved draft.\n const comparableDefinition = buildDefinitionPayload({\n graphDefinition: graphToDefinition(graph.nodes, graph.edges, { includePositions: true }),\n triggers: loadedTriggers,\n contextSchema: loadedContextSchema,\n io: loadedIo,\n interpolation: loadedInterpolation,\n errorHandler: loadedErrorHandler,\n })\n const loadedDraftMetadata = buildMetadataPayload({\n loadedMetadata: loadedMetadataObject,\n category: definition.metadata?.category || '',\n tags: definition.metadata?.tags || [],\n icon: definition.metadata?.icon || '',\n annotations: annotationsFromNodes(annotationNodes),\n })\n lastPersistedDraftRef.current = stableSerializeDefinition({\n definition: comparableDefinition,\n metadata: loadedDraftMetadata,\n })\n\n if (loadedSource !== 'code' && isServerDraftEligible(definitionId)) {\n const draftResult = await apiCall<{ data?: WorkflowDefinitionDraftPayload; error?: string }>(\n `/api/workflows/definitions/${definitionId}/draft`,\n )\n const draft = draftResult.ok ? draftResult.result?.data : undefined\n const decision = draft\n ? decideDraftRestore({\n draftDefinition: draft.definition,\n draftBaseUpdatedAt: draft.baseUpdatedAt,\n loadedDefinition: comparableDefinition,\n definitionUpdatedAt: loadedUpdatedAt,\n })\n : { offerRestore: false as const }\n if (draft && decision.offerRestore) {\n // Hold autosave until the user restores or discards, so editing\n // with the banner open can never silently overwrite the draft.\n setPendingDraft({ draft, baseMismatch: decision.baseMismatch })\n } else {\n setDraftAutosaveReady(true)\n }\n }\n } catch (error) {\n logger.error('Error loading workflow definition', { err: error })\n flash('Failed to load workflow definition', 'error')\n } finally {\n setIsLoading(false)\n }\n }\n\n loadDefinition()\n }, [definitionId])\n\n // The canvas owns the annotations, so every persistence path derives them back\n // out of the node array rather than tracking a second copy that could drift.\n const annotations = useMemo(() => annotationsFromNodes(nodes), [nodes])\n\n const draftMetadata = useMemo(\n () => buildMetadataPayload({ loadedMetadata, tags, category, icon, annotations }),\n [loadedMetadata, tags, category, icon, annotations],\n )\n\n // Debounced autosave-to-draft (~2s): watches the same editor-state dep set\n // the save handler uses and PUTs the per-user draft. Never fires for\n // unsaved/new or code-defined definitions, and failures stay quiet \u2014 the\n // small indicator flips to \"draft not saved\" and the next change retries.\n useEffect(() => {\n if (!draftAutosaveReady || !draftEligible || !definitionId) return\n if (draftSuspendedRef.current) return\n let payload: { definition: ReturnType<typeof buildDefinitionPayload>; metadata: Record<string, unknown> | null; baseUpdatedAt: string | null }\n try {\n payload = {\n definition: buildDefinitionPayload({\n graphDefinition: graphToDefinition(nodes, edges, { includePositions: true }),\n triggers,\n contextSchema,\n io: definitionIo,\n interpolation,\n errorHandler,\n }),\n metadata: draftMetadata,\n baseUpdatedAt: updatedAt,\n }\n } catch {\n return\n }\n const serialized = stableSerializeDefinition({ definition: payload.definition, metadata: payload.metadata })\n if (serialized === lastPersistedDraftRef.current) return\n const timer = window.setTimeout(async () => {\n if (draftSuspendedRef.current) return\n try {\n const result = await apiCall<{ data?: WorkflowDefinitionDraftPayload; error?: string }>(\n `/api/workflows/definitions/${definitionId}/draft`,\n {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n },\n )\n if (result.ok) {\n lastPersistedDraftRef.current = serialized\n setDraftSavedAt(new Date().toISOString())\n setDraftSaveFailed(false)\n } else {\n setDraftSaveFailed(true)\n }\n } catch {\n setDraftSaveFailed(true)\n }\n }, DRAFT_AUTOSAVE_DEBOUNCE_MS)\n return () => window.clearTimeout(timer)\n }, [draftAutosaveReady, draftEligible, definitionId, nodes, edges, triggers, contextSchema, definitionIo, interpolation, errorHandler, draftMetadata, updatedAt, workflowName, description, version, enabled, effectiveFrom, effectiveTo])\n\n // Keep the \"Draft saved Xs ago\" label fresh without re-rendering per second.\n useEffect(() => {\n if (!draftSavedAt) return\n const interval = window.setInterval(() => setDraftClock((tick) => tick + 1), DRAFT_SAVED_LABEL_REFRESH_MS)\n return () => window.clearInterval(interval)\n }, [draftSavedAt])\n\n const draftSavedLabel = useMemo(() => {\n if (!draftSavedAt) return null\n return formatRelativeTime(draftSavedAt, { translate: t })\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [draftSavedAt, draftClock, t])\n\n const handleRestoreDraft = useCallback(() => {\n if (!pendingDraft) return\n try {\n const draftDefinition = pendingDraft.draft.definition as unknown as Parameters<typeof definitionToGraph>[0]\n const graph = definitionToGraph(draftDefinition)\n setNodes([...graph.nodes, ...annotationsToNodes(readEditorAnnotations(pendingDraft.draft.metadata ?? null))])\n setEdges(graph.edges)\n const draftTriggers = pendingDraft.draft.definition.triggers\n setTriggers(Array.isArray(draftTriggers) ? (draftTriggers as WorkflowDefinitionTrigger[]) : [])\n const draftContextSchema = pendingDraft.draft.definition.contextSchema\n setContextSchema(draftContextSchema ? (draftContextSchema as WorkflowContextSchema) : undefined)\n const draftIo = (pendingDraft.draft.definition as { io?: WorkflowIoContract }).io\n setDefinitionIo(draftIo ?? undefined)\n setInterpolation(resolveDefinitionInterpolationMode(pendingDraft.draft.definition))\n const draftErrorHandler = (pendingDraft.draft.definition as { errorHandler?: WorkflowErrorHandlerConfig }).errorHandler\n setErrorHandler(draftErrorHandler ?? undefined)\n const restoredMetadata = pendingDraft.draft.metadata ?? null\n setLoadedMetadata(restoredMetadata)\n if (restoredMetadata) {\n setCategory(typeof restoredMetadata.category === 'string' ? restoredMetadata.category : '')\n setTags(Array.isArray(restoredMetadata.tags) ? restoredMetadata.tags.filter((tag): tag is string => typeof tag === 'string') : [])\n setIcon(typeof restoredMetadata.icon === 'string' ? restoredMetadata.icon : '')\n }\n lastPersistedDraftRef.current = stableSerializeDefinition({\n definition: pendingDraft.draft.definition,\n metadata: pendingDraft.draft.metadata ?? null,\n })\n resetHistory()\n flash(t('workflows.visualEditor.draft.restored', 'Draft restored'), 'success')\n } catch (error) {\n logger.error('Error restoring workflow definition draft', { err: error })\n flash(t('workflows.visualEditor.draft.restoreFailed', 'Failed to restore draft'), 'error')\n } finally {\n setPendingDraft(null)\n setDraftAutosaveReady(true)\n }\n }, [pendingDraft, resetHistory, t])\n\n const handleDiscardDraft = useCallback(async () => {\n setPendingDraft(null)\n setDraftAutosaveReady(true)\n if (!definitionId) return\n try {\n await apiCall(`/api/workflows/definitions/${definitionId}/draft`, { method: 'DELETE' })\n } catch (error) {\n logger.error('Error discarding workflow definition draft', { err: error })\n }\n }, [definitionId])\n\n // Schedule a quiet debounced autosave (~900ms). Only for already-saved,\n // editable definitions; new unsaved drafts fall back to an explicit Save.\n const scheduleAutosave = useCallback(() => {\n if (!definitionId || isCodeOnly) return\n if (autosaveTimerRef.current) clearTimeout(autosaveTimerRef.current)\n autosaveTimerRef.current = setTimeout(() => {\n autosaveTimerRef.current = null\n void performAutosaveRef.current()\n }, 900)\n }, [definitionId, isCodeOnly])\n\n // Clear any pending autosave timer on unmount.\n useEffect(() => () => {\n if (autosaveTimerRef.current) clearTimeout(autosaveTimerRef.current)\n }, [])\n\n const applyHistoryDocument = useCallback((document: WorkflowEditorDocument) => {\n setNodes(document.nodes)\n setEdges(document.edges)\n setLoadedMetadata(document.metadata)\n // Entries captured before the panel fields were versioned carry none; then\n // the panel is left exactly as it is, which is the previous behaviour.\n if (document.panel) {\n setTriggers(document.panel.triggers as WorkflowDefinitionTrigger[])\n setContextSchema(document.panel.contextSchema as WorkflowContextSchema | undefined)\n setDefinitionIo(document.panel.io as WorkflowIoContract | undefined)\n setInterpolation(document.panel.interpolation as WorkflowInterpolationMode | undefined)\n setErrorHandler(document.panel.errorHandler as WorkflowErrorHandlerConfig | undefined)\n }\n scheduleAutosave()\n }, [scheduleAutosave])\n\n const handleUndo = useCallback(() => {\n if (isCodeOnly) return\n const step = undoEditorHistory(historyRef.current, captureDocument())\n if (!step) {\n flash(t('workflows.visualEditor.history.nothingToUndo', 'Nothing to undo'), 'info')\n return\n }\n setHistory(step.state)\n applyHistoryDocument(step.document)\n flash(t('workflows.visualEditor.history.undone', 'Undone: {label}', { label: step.label }), 'success')\n }, [isCodeOnly, captureDocument, applyHistoryDocument, t])\n\n const handleRedo = useCallback(() => {\n if (isCodeOnly) return\n const step = redoEditorHistory(historyRef.current, captureDocument())\n if (!step) {\n flash(t('workflows.visualEditor.history.nothingToRedo', 'Nothing to redo'), 'info')\n return\n }\n setHistory(step.state)\n applyHistoryDocument(step.document)\n flash(t('workflows.visualEditor.history.redone', 'Redone: {label}', { label: step.label }), 'success')\n }, [isCodeOnly, captureDocument, applyHistoryDocument, t])\n\n // Copy / paste / duplicate of a selected subgraph (spec \u00A74.5). The payload on\n // the system clipboard is portable JSON in the DEFINITION vocabulary, so it\n // travels to another workflow and to the Code view. When the browser denies\n // clipboard access (insecure context, no permission) the editor falls back to\n // an in-page buffer and says so, rather than failing silently.\n const localClipboardRef = React.useRef<string | null>(null)\n\n const selectedSubgraph = useCallback(() => {\n const selectedIds = nodesRef.current.filter((node) => node.selected).map((node) => node.id)\n return serializeWorkflowSubgraph(nodesRef.current, edgesRef.current, selectedIds)\n }, [])\n\n const handleCopySelection = useCallback(async () => {\n const payload = selectedSubgraph()\n if (!payload) {\n flash(t('workflows.visualEditor.clipboard.nothingSelected', 'Select one or more steps first'), 'info')\n return\n }\n const serialized = stringifyWorkflowSubgraph(payload)\n localClipboardRef.current = serialized\n try {\n await navigator.clipboard.writeText(serialized)\n flash(\n t('workflows.visualEditor.clipboard.copied', 'Copied {count} step(s)', { count: String(payload.steps.length) }),\n 'success',\n )\n } catch (error) {\n logger.warn('Workflow subgraph copy fell back to the in-page buffer', { err: error })\n flash(\n t(\n 'workflows.visualEditor.clipboard.copyUnavailable',\n 'The browser blocked clipboard access, so the selection was kept in this editor only \u2014 pasting into another tab will not work.',\n ),\n 'warning',\n )\n }\n }, [selectedSubgraph, t])\n\n const describeClipboardFailure = useCallback((code: SubgraphClipboardParseFailure['code']) => {\n switch (code) {\n case 'invalidJson':\n return t('workflows.visualEditor.clipboard.invalidJson', 'The clipboard does not contain valid JSON.')\n case 'empty':\n return t('workflows.visualEditor.clipboard.empty', 'The copied selection contains no steps.')\n default:\n return t('workflows.visualEditor.clipboard.unsupportedFormat', 'The clipboard does not contain a copied workflow selection.')\n }\n }, [t])\n\n const spliceSubgraph = useCallback((payload: WorkflowSubgraphClipboard, label: string) => {\n const result = pasteWorkflowSubgraph(nodesRef.current, edgesRef.current, payload)\n commitHistory(label)\n setNodes(result.nodes)\n setEdges(result.edges)\n scheduleAutosave()\n flash(\n t('workflows.visualEditor.clipboard.pasted', 'Pasted {count} step(s)', { count: String(result.pastedNodeIds.length) }),\n 'success',\n )\n }, [commitHistory, scheduleAutosave, t])\n\n const handlePaste = useCallback(async () => {\n if (isCodeOnly) return\n let text: string | null = null\n try {\n text = await navigator.clipboard.readText()\n } catch (error) {\n logger.warn('Workflow subgraph paste fell back to the in-page buffer', { err: error })\n text = localClipboardRef.current\n if (!text) {\n flash(\n t(\n 'workflows.visualEditor.clipboard.pasteUnavailable',\n 'The browser blocked clipboard access, so there is nothing to paste. Copy a selection in this editor first.',\n ),\n 'error',\n )\n return\n }\n }\n const parsed = parseWorkflowSubgraph(text ?? '')\n if (!parsed.ok) {\n flash(describeClipboardFailure(parsed.code), 'error')\n return\n }\n spliceSubgraph(parsed.payload, historyLabels.paste)\n }, [isCodeOnly, describeClipboardFailure, spliceSubgraph, historyLabels.paste, t])\n\n const handleDuplicateSelection = useCallback(() => {\n if (isCodeOnly) return\n const payload = selectedSubgraph()\n if (!payload) {\n flash(t('workflows.visualEditor.clipboard.nothingSelected', 'Select one or more steps first'), 'info')\n return\n }\n spliceSubgraph(payload, historyLabels.duplicate)\n }, [isCodeOnly, selectedSubgraph, spliceSubgraph, historyLabels.duplicate, t])\n\n // Handle node changes from ReactFlow. The lazy graph applies React Flow's\n // change reducers internally (#3169) and hands back the resolved nodes plus a\n // note on what the batch meant, so this page never imports the @xyflow/react\n // runtime. A drag persists once, on drag end (#4248); selecting or measuring\n // a node changes nothing worth saving and must not touch the stored row.\n // A drag reports one change batch per frame, so the undoable \"before\" state is\n // the arrangement captured when the drag STARTED \u2014 not the previous frame.\n const dragBaselineRef = React.useRef<WorkflowEditorDocument | null>(null)\n\n const handleNodesChange = useCallback((nextNodes: Node[], meta?: WorkflowGraphNodesChangeMeta) => {\n if (isCodeOnly) return\n if ((meta?.dragging || meta?.resizing) && !dragBaselineRef.current) dragBaselineRef.current = captureDocument()\n const baseline = dragBaselineRef.current ?? captureDocument()\n setNodes(nextNodes)\n if (meta && !meta.persistable) return\n dragBaselineRef.current = null\n commitCapturedDocument(baseline, historyLabels.move)\n scheduleAutosave()\n }, [isCodeOnly, captureDocument, commitCapturedDocument, historyLabels.move, scheduleAutosave])\n\n // Auto-arrange / Tidy: the single intentional full re-layout. Re-runs dagre\n // (LR) over the current graph, overwrites positions, and persists via autosave.\n const handleAutoArrange = useCallback(() => {\n if (isCodeOnly) return\n commitHistory(historyLabels.tidy)\n setNodes((nds) => applyAutoLayout(nds, edges))\n scheduleAutosave()\n }, [isCodeOnly, edges, commitHistory, historyLabels.tidy, scheduleAutosave])\n\n // Handle edge changes from ReactFlow (resolved edges from the lazy graph).\n const handleEdgesChange = useCallback((nextEdges: Edge[]) => {\n if (isCodeOnly) return\n setEdges(nextEdges)\n }, [isCodeOnly])\n\n const buildPaletteNode = useCallback((nodeType: string, dropPosition?: { x: number; y: number } | null): Node => ({\n id: generateStepId(nodeType),\n type: nodeType,\n position: resolveNewNodePlacement(nodesRef.current, { dropPosition }),\n data: {\n label: getDefaultLabel(nodeType),\n description: '',\n badge: getDefaultBadge(nodeType),\n status: 'pending',\n },\n }), [])\n\n // Handle adding new node from palette. A drop position (drag-from-palette)\n // places the card under the cursor; the click-append path lands after the\n // right-most card. Both are nudged clear of existing cards (#4248) and both\n // count as a manual arrangement, so the placement is persisted like a drag.\n const handleAddNode = useCallback((nodeType: string, dropPosition?: { x: number; y: number } | null) => {\n if (isCodeOnly) return\n const newNode = buildPaletteNode(nodeType, dropPosition)\n commitHistory(historyLabels.addStep)\n setNodes((nds) => [...nds, newNode])\n scheduleAutosave()\n }, [isCodeOnly, buildPaletteNode, commitHistory, historyLabels.addStep, scheduleAutosave])\n\n // Notes and groups are added from the palette exactly like steps: a click\n // appends one at a free spot and opens its inspector, so the keyboard path is\n // the same path.\n const handleAddAnnotation = useCallback((kind: 'note' | 'group') => {\n if (isCodeOnly) return\n const position = resolveNewNodePlacement(nodesRef.current, {})\n const node = kind === 'note'\n ? createNoteNode(position, '')\n : createGroupNode(position, t('workflows.annotations.group.untitled', 'Untitled group'))\n commitHistory(kind === 'note' ? historyLabels.addNote : historyLabels.addGroup)\n setNodes((nds) => [...nds, node])\n setSelectedAnnotation(node)\n setShowAnnotationDialog(true)\n scheduleAutosave()\n }, [isCodeOnly, commitHistory, historyLabels.addNote, historyLabels.addGroup, scheduleAutosave, t])\n\n const activityTypeOptions = useActivityTypeOptions()\n\n const describePaletteDropRejection = useCallback((code: PaletteDropRejectionCode) => {\n switch (code) {\n case 'dataMappingRoute':\n return t('workflows.visualEditor.palette.rejected.dataMappingRoute', 'Data mapping links are edited in the step configuration, not on the canvas.')\n default:\n return t('workflows.visualEditor.palette.rejected.unknownRoute', 'That route no longer exists.')\n }\n }, [t])\n\n // Drag-from-palette (spec \u00A74.2). Dropping on empty canvas places the step at\n // the cursor; dropping on a route splices it between that route's endpoints;\n // dropping an action on a route appends it to the route's activities. The\n // graph resolved the flow-space position and the route under the cursor \u2014 the\n // effect itself is pure (`lib/palette-drop.ts`).\n const handleCanvasDrop = useCallback((event: WorkflowGraphDropEvent) => {\n if (isCodeOnly) return\n const item = readPaletteDragItem(event.dataTransfer)\n if (!item) return\n\n if (item.kind === 'step') {\n if (!event.edgeId) {\n handleAddNode(item.nodeType, event.position)\n return\n }\n const result = insertStepOnRoute(\n nodesRef.current,\n edgesRef.current,\n event.edgeId,\n buildPaletteNode(item.nodeType, event.position),\n )\n if (!result.ok) {\n flash(describePaletteDropRejection(result.code), 'error')\n return\n }\n commitHistory(historyLabels.insertOnRoute)\n setNodes(result.nodes)\n setEdges(result.edges)\n scheduleAutosave()\n flash(t('workflows.visualEditor.palette.insertedOnRoute', 'Step inserted on the route'), 'success')\n return\n }\n\n if (!event.edgeId) {\n flash(t('workflows.visualEditor.palette.dragActionHint', 'Drop an action onto a route to add it there'), 'info')\n return\n }\n const activityLabel = activityTypeOptions.find((option) => option.value === item.activityType)?.label ?? item.activityType\n const result = appendActivityToRoute(edgesRef.current, event.edgeId, {\n activityId: `activity_${Date.now()}`,\n activityName: activityLabel,\n activityType: item.activityType,\n config: {},\n })\n if (!result.ok) {\n flash(describePaletteDropRejection(result.code), 'error')\n return\n }\n commitHistory(historyLabels.addActivity)\n setEdges(result.edges)\n scheduleAutosave()\n flash(t('workflows.visualEditor.palette.activityAdded', '{activity} added to the route', { activity: activityLabel }), 'success')\n }, [\n isCodeOnly,\n handleAddNode,\n buildPaletteNode,\n activityTypeOptions,\n describePaletteDropRejection,\n commitHistory,\n historyLabels.insertOnRoute,\n historyLabels.addActivity,\n scheduleAutosave,\n t,\n ])\n\n const handlePaletteStepDragStart = useCallback((event: React.DragEvent<HTMLButtonElement>, nodeType: string) => {\n writePaletteDragPayload(event.dataTransfer, { kind: 'step', nodeType }, NODE_TYPE_LABELS[nodeType as keyof typeof NODE_TYPE_LABELS]?.title ?? nodeType)\n }, [])\n\n const handlePaletteActivityDragStart = useCallback((event: React.DragEvent<HTMLButtonElement>, activityType: string, label: string) => {\n writePaletteDragPayload(event.dataTransfer, { kind: 'activity', activityType }, label)\n }, [])\n\n // Handle node selection - open edit dialog (suppressed in read-only mode\n // so users can't open the node editor on a code-defined workflow).\n const handleNodeClick = useCallback((_event: React.MouseEvent, node: Node) => {\n if (isCodeOnly) return\n if (isAnnotationNode(node)) {\n setSelectedAnnotation(node)\n setSelectedNode(null)\n setSelectedEdge(null)\n setShowAnnotationDialog(true)\n return\n }\n setSelectedNode(node)\n setSelectedEdge(null)\n // With a docked rail the canvas stays clickable, so a step click can arrive\n // while the ROUTE inspector is open. Closing the other one keeps a single\n // rail; the modal variant could never reach this state.\n setShowEdgeDialog(false)\n setShowNodeDialog(true)\n }, [isCodeOnly])\n\n // Handle edge selection - open edit dialog\n const handleEdgeClick = useCallback((_event: React.MouseEvent, edge: Edge) => {\n if (isCodeOnly) return\n setSelectedEdge(edge)\n setSelectedNode(null)\n setEdgeDialogFocusFieldId(null)\n setShowNodeDialog(false)\n setShowEdgeDialog(true)\n }, [isCodeOnly])\n\n // Route chips (#4244) open the edge dialog on the section behind the chip.\n // Chips render inside React Flow's label portal, so they announce on `window`\n // instead of bubbling to `onEdgeClick` \u2014 same bridge as the node delete button.\n const handleRouteChipOpen = useCallback((edgeId: string, section: RouteChipEventDetail['section']) => {\n if (isCodeOnly) return\n const edge = edgesRef.current.find((candidate) => candidate.id === edgeId)\n if (!edge) return\n setSelectedEdge(edge)\n setSelectedNode(null)\n setEdgeDialogFocusFieldId(section === 'condition' ? 'condition' : 'activities')\n setShowEdgeDialog(true)\n }, [isCodeOnly])\n\n // Save node updates\n const handleSaveNode = useCallback((nodeId: string, updates: Partial<Node['data']>) => {\n commitHistory(historyLabels.editStep)\n if (Object.prototype.hasOwnProperty.call(updates, 'decisions')) {\n const previousNode = nodesRef.current.find((node) => node.id === nodeId)\n const previousDecisions = previousNode?.data.decisions as DecisionRowLike[] | undefined\n const nextDecisions = updates.decisions as DecisionRowLike[] | undefined\n const previousIds = new Set(\n (previousDecisions ?? []).flatMap((decision) =>\n typeof decision.transitionId === 'string' ? [decision.transitionId] : []\n ),\n )\n const nextIds = new Set(\n (nextDecisions ?? []).flatMap((decision) =>\n typeof decision.transitionId === 'string' ? [decision.transitionId] : []\n ),\n )\n setEdges((currentEdges) =>\n currentEdges.map((edge) => {\n if (edge.source !== nodeId) return edge\n if (nextIds.has(edge.id)) return { ...edge, sourceHandle: edge.id }\n if (previousIds.has(edge.id) && edge.sourceHandle === edge.id) {\n const { sourceHandle: _removed, ...remainingEdge } = edge\n return remainingEdge\n }\n return edge\n }),\n )\n }\n setNodes((nds) =>\n nds.map((node) =>\n node.id === nodeId\n ? { ...node, data: { ...node.data, ...updates } }\n : node\n )\n )\n flash('Node updated successfully', 'success')\n }, [commitHistory, historyLabels.editStep])\n\n // Branching (IF_ELSE / SWITCH) routes are read from and written back to the\n // node's outgoing edges \u2014 the inspector never introduces a bespoke shape.\n const branchingRoutesValue = useMemo<SwitchRoutesValue | undefined>(() => {\n if (!selectedNode || !isBranchingNodeType(selectedNode.type)) return undefined\n return {\n field: readSwitchField(edges, selectedNode.id),\n routes: readBranchingRoutes(edges, selectedNode.id),\n }\n }, [selectedNode, edges])\n\n const handleSaveBranchingRoutes = useCallback((nodeId: string, value: SwitchRoutesValue) => {\n const nodeType = nodes.find((node) => node.id === nodeId)?.type\n commitHistory(historyLabels.branchRoutes)\n setEdges((eds) => (nodeType === 'switch' ? applySwitchRoutes(eds, nodeId, value) : applyIfElseRoutes(eds, nodeId, value.routes)))\n scheduleAutosave()\n }, [nodes, commitHistory, historyLabels.branchRoutes, scheduleAutosave])\n\n // Route order (spec 4.4): a non-branching step's outgoing routes are ordered\n // in the inspector and the priority number is derived from that order.\n const routeOrderValue = useMemo<RouteOrderEntry[] | undefined>(() => {\n if (!selectedNode || isBranchingNodeType(selectedNode.type)) return undefined\n return readRouteOrder(edges, selectedNode.id)\n }, [selectedNode, edges])\n\n // Nodes whose legacy priorities have already been rewritten this session. The\n // normalization pass runs on the FIRST edit of a node's routes and is\n // idempotent afterwards.\n const normalizedRouteNodesRef = React.useRef<Set<string>>(new Set())\n\n // A `source: 'code'` definition is read-only in the editor, so normalization\n // simply cannot run for it. Customize mints an editable override (source\n // becomes 'code_override') and the pass runs there on the first route edit \u2014\n // which is exactly the spec's \"only on Customize\".\n const normalizeRoutesOnFirstEdit = useCallback((nodeId: string) => {\n if (!canNormalizeRoutePriorities(source)) return\n if (normalizedRouteNodesRef.current.has(nodeId)) return\n normalizedRouteNodesRef.current.add(nodeId)\n setEdges((eds) => normalizeRoutePriorities(eds, nodeId))\n }, [source])\n\n const handleSaveRouteOrder = useCallback((nodeId: string, entries: RouteOrderEntry[]) => {\n if (isCodeOnly) return\n commitHistory(historyLabels.routeOrder)\n normalizeRoutesOnFirstEdit(nodeId)\n setEdges((eds) => applyRouteOrder(eds, nodeId, entries))\n scheduleAutosave()\n }, [isCodeOnly, normalizeRoutesOnFirstEdit, commitHistory, historyLabels.routeOrder, scheduleAutosave])\n\n // Save edge updates\n const handleSaveEdge = useCallback((edgeId: string, updates: Partial<Edge['data']>) => {\n commitHistory(historyLabels.editRoute)\n setEdges((eds) =>\n eds.map((edge) =>\n edge.id === edgeId\n ? { ...edge, data: { ...edge.data, ...updates } }\n : edge\n )\n )\n flash('Transition updated successfully', 'success')\n }, [commitHistory, historyLabels.editRoute])\n\n // Delete edge. The undo snapshot is taken before the confirmation and only\n // committed once the delete actually lands, so a cancelled confirm leaves no\n // entry on the stack.\n const handleDeleteEdge = useCallback(async (edgeId: string) => {\n const before = captureDocument()\n const deleted = await performDeleteEdgeFlow(edgeId, {\n confirm,\n t,\n setShowEdgeDialog,\n setSelectedEdge,\n setEdges,\n notifyDeleted: () => flash('Transition deleted successfully', 'success'),\n })\n if (deleted) commitCapturedDocument(before, historyLabels.deleteRoute)\n }, [confirm, t, captureDocument, commitCapturedDocument, historyLabels.deleteRoute])\n\n // Annotation inspector (spec 4.5). Notes and groups edit a single field each\n // and commit one undo entry, exactly like a step inspector save.\n const handleSaveAnnotation = useCallback((nodeId: string, updates: Partial<WorkflowNoteNodeData & WorkflowGroupNodeData>) => {\n if (isCodeOnly) return\n commitHistory(historyLabels.editAnnotation)\n setNodes((nds) => updateAnnotationNode(nds, nodeId, updates))\n scheduleAutosave()\n }, [isCodeOnly, commitHistory, historyLabels.editAnnotation, scheduleAutosave])\n\n const handleDeleteAnnotation = useCallback(async (nodeId: string) => {\n if (isCodeOnly) return\n const before = captureDocument()\n setShowAnnotationDialog(false)\n setSelectedAnnotation(null)\n const confirmed = await confirm({\n title: t('workflows.annotations.confirmDeleteTitle', 'Delete annotation?'),\n text: t('workflows.annotations.confirmDeleteText', 'The note or group is removed from the canvas. Nothing the workflow executes changes.'),\n variant: 'destructive',\n })\n if (!confirmed) return\n commitCapturedDocument(before, historyLabels.deleteAnnotation)\n setNodes((nds) => removeAnnotationNode(nds, nodeId))\n scheduleAutosave()\n }, [isCodeOnly, captureDocument, commitCapturedDocument, historyLabels.deleteAnnotation, confirm, scheduleAutosave, t])\n\n const handleToggleGroupCollapsed = useCallback((nodeId: string) => {\n if (isCodeOnly) return\n const node = nodesRef.current.find((candidate) => candidate.id === nodeId)\n if (!node) return\n const collapsed = (node.data as Partial<WorkflowGroupNodeData> | undefined)?.collapsed === true\n commitHistory(historyLabels.toggleGroup)\n setNodes((nds) => updateAnnotationNode(nds, nodeId, { collapsed: !collapsed }))\n scheduleAutosave()\n }, [isCodeOnly, commitHistory, historyLabels.toggleGroup, scheduleAutosave])\n\n useEffect(() => {\n const onToggle = (event: Event) => {\n const nodeId = (event as CustomEvent<{ nodeId?: string }>).detail?.nodeId\n if (typeof nodeId === 'string') handleToggleGroupCollapsed(nodeId)\n }\n window.addEventListener(WORKFLOW_GROUP_TOGGLE_EVENT, onToggle)\n return () => window.removeEventListener(WORKFLOW_GROUP_TOGGLE_EVENT, onToggle)\n }, [handleToggleGroupCollapsed])\n\n // Delete node\n const handleDeleteNode = useCallback(async (nodeId: string) => {\n const annotation = nodesRef.current.find((candidate) => candidate.id === nodeId && isAnnotationNode(candidate))\n if (annotation) {\n await handleDeleteAnnotation(nodeId)\n return\n }\n const before = captureDocument()\n const deleted = await performDeleteNodeFlow(nodeId, {\n nodes,\n confirm,\n t,\n setShowNodeDialog,\n setSelectedNode,\n setNodes,\n setEdges,\n notifyDeleted: () => flash('Step deleted successfully', 'success'),\n })\n if (deleted) commitCapturedDocument(before, historyLabels.deleteStep)\n }, [confirm, nodes, t, captureDocument, commitCapturedDocument, historyLabels.deleteStep, handleDeleteAnnotation])\n\n // In-place step type conversion (spec 4.5, #4237). The step keeps its id,\n // name, position and every incoming/outgoing route; config the new type\n // cannot execute is quarantined by `convertStepType` and stays visible in the\n // inspector. The dialog closes before the confirm so only one modal is on\n // screen (same reason as the delete flow).\n const handleConvertNodeType = useCallback(async (nodeId: string, targetType: ConvertibleStepType) => {\n if (isCodeOnly) return\n const node = nodesRef.current.find((candidate) => candidate.id === nodeId)\n if (!node) return\n\n const before = captureDocument()\n const result = convertStepType({ type: node.type, data: node.data as Record<string, unknown> }, targetType)\n if (!result.ok) {\n flash(t('workflows.stepConversion.unavailable', 'This step type cannot be changed.'), 'error')\n return\n }\n\n setShowNodeDialog(false)\n setSelectedNode(null)\n const confirmed = await confirm({\n title: t('workflows.stepConversion.confirmTitle', 'Change step type?'),\n text: result.quarantined.length > 0\n ? t(\n 'workflows.stepConversion.confirmWithQuarantine',\n 'The step keeps its name, position and routes. {count} setting(s) the new type cannot execute move to Unmapped configuration: {keys}',\n { count: String(result.quarantined.length), keys: result.quarantined.join(', ') },\n )\n : t('workflows.stepConversion.confirm', 'The step keeps its name, position and routes.'),\n })\n if (!confirmed) return\n\n commitCapturedDocument(before, historyLabels.convert)\n setNodes((nds) =>\n nds.map((candidate) =>\n candidate.id === nodeId\n ? { ...candidate, type: result.type, data: { ...result.data, badge: getBadgeForNodeType(result.type) } }\n : candidate,\n ),\n )\n scheduleAutosave()\n flash(\n result.quarantined.length > 0\n ? t('workflows.stepConversion.convertedWithQuarantine', 'Step type changed; {count} setting(s) parked as unmapped configuration', { count: String(result.quarantined.length) })\n : t('workflows.stepConversion.converted', 'Step type changed'),\n result.quarantined.length > 0 ? 'warning' : 'success',\n )\n }, [isCodeOnly, confirm, captureDocument, commitCapturedDocument, historyLabels.convert, scheduleAutosave, t])\n\n // Inline node delete: a node's trash button dispatches WORKFLOW_NODE_DELETE_EVENT\n // (decoupled from the node component); route it through the same confirm +\n // edge-cleanup flow as the edit dialog's delete. No-op in read-only mode.\n useEffect(() => {\n if (isCodeOnly) return\n const onNodeDelete = (event: Event) => {\n const nodeId = (event as CustomEvent<{ nodeId?: string }>).detail?.nodeId\n if (typeof nodeId === 'string') void handleDeleteNode(nodeId)\n }\n window.addEventListener(WORKFLOW_NODE_DELETE_EVENT, onNodeDelete)\n return () => window.removeEventListener(WORKFLOW_NODE_DELETE_EVENT, onNodeDelete)\n }, [isCodeOnly, handleDeleteNode])\n\n useEffect(() => {\n const onChipOpen = (event: Event) => {\n const detail = (event as CustomEvent<RouteChipEventDetail>).detail\n if (detail?.edgeId) handleRouteChipOpen(detail.edgeId, detail.section)\n }\n window.addEventListener(WORKFLOW_ROUTE_CHIP_EVENT, onChipOpen)\n return () => window.removeEventListener(WORKFLOW_ROUTE_CHIP_EVENT, onChipOpen)\n }, [handleRouteChipOpen])\n\n useEffect(() => {\n const onActivityOpen = (event: Event) => {\n if (isCodeOnly) return\n const detail = (event as CustomEvent<RouteActivityEventDetail>).detail\n if (detail?.edgeId && detail?.activityId) {\n setActivityEdit({ edgeId: detail.edgeId, activityId: detail.activityId })\n }\n }\n window.addEventListener(WORKFLOW_ROUTE_ACTIVITY_EVENT, onActivityOpen)\n return () => window.removeEventListener(WORKFLOW_ROUTE_ACTIVITY_EVENT, onActivityOpen)\n }, [isCodeOnly])\n\n // Handle new connections. A drop onto a sub-workflow IN port authors a field\n // mapping (written to the target step's config.inputMapping + a distinct data\n // edge); a plain handle-to-handle connection stays a control-flow transition.\n const handleConnect = useCallback((connection: Connection) => {\n const classification = classifyConnection(connection)\n\n if (classification.kind === 'data-ignored') {\n return\n }\n\n if (classification.kind === 'data-mapping') {\n const { targetNodeId, childPortKey, parentPath } = classification\n commitHistory(historyLabels.connect)\n setNodes((nds) => applyInputMappingToNodes(nds, targetNodeId, childPortKey, parentPath))\n const dataEdge = buildDataMappingEdge(connection, childPortKey)\n setEdges((eds) => appendWorkflowEdge(eds.filter((e) => e.id !== dataEdge.id), dataEdge))\n return\n }\n\n // A connection drawn from one of a node's kinded output handles authors that\n // kind of route (spec 5.9 error routes, SLA-breach routes, \u2026): normal\n // routing never selects one, the engine follows it only down its own path.\n const routeKind = findRouteKindDescriptorForHandle(connection.sourceHandle)\n const sourceNode = nodesRef.current.find((node) => node.id === connection.source)\n const decisions = sourceNode?.data.decisions as DecisionRowLike[] | undefined\n const decisionTransitionId = isDecisionSourceHandle(decisions, connection.sourceHandle)\n ? connection.sourceHandle\n : null\n if (\n decisionTransitionId &&\n edgesRef.current.some(\n (edge) =>\n edge.source === connection.source &&\n (edge.id === decisionTransitionId || edge.sourceHandle === decisionTransitionId),\n )\n ) {\n return\n }\n\n const routeData = routeKind\n ? {\n kind: routeKind.kind,\n ...routeKind.discriminatorFields({\n sourceHandle: connection.sourceHandle,\n }),\n }\n : {}\n\n // A drawn route is the same object a saved one loads as, so it takes the\n // workflow edge renderer (a curve) immediately rather than on the next\n // reload \u2014 see `lib/route-edge.ts`.\n const newEdge: Edge = buildWorkflowRouteEdge({\n id: decisionTransitionId ?? generateTransitionId(),\n source: connection.source!,\n target: connection.target!,\n sourceHandle: routeKind ? connection.sourceHandle : decisionTransitionId,\n data: {\n trigger: 'auto',\n preConditions: [],\n postConditions: [],\n activities: [],\n label: '',\n ...routeData,\n },\n })\n\n commitHistory(historyLabels.connect)\n setEdges((eds) => appendWorkflowEdge(eds, newEdge))\n }, [commitHistory, historyLabels.connect])\n\n // Route reattachment (#4233): dropping an existing route endpoint on another\n // node re-targets it. The route keeps its durable transitionId, so its label,\n // condition, activities and priority travel with it. A refused target leaves\n // the edge list untouched, which is what snaps the endpoint back \u2014 the reason\n // is surfaced instead of silently reverting.\n const describeReattachRejection = useCallback((rejection: EdgeReattachRejection) => {\n switch (rejection.code) {\n case 'selfLoop':\n return t('workflows.reattach.rejected.selfLoop', 'A route cannot start and end on the same step.')\n case 'duplicateRoute':\n return t('workflows.reattach.rejected.duplicateRoute', 'A route already connects those two steps.')\n case 'dataMappingRoute':\n return t('workflows.reattach.rejected.dataMappingRoute', 'Data mapping links are edited in the step configuration, not on the canvas.')\n case 'errorHandleUnsupported':\n return t('workflows.reattach.rejected.errorHandleUnsupported', 'An error route can only start at a step that can fail.')\n case 'kindHandleUnsupported':\n return t('workflows.reattach.rejected.kindHandleUnsupported', 'This route cannot start at that type of step.')\n case 'graphInvalid':\n return t('workflows.reattach.rejected.graphInvalid', 'That target would break the workflow: {reason}', { reason: rejection.detail ?? '' })\n case 'forkJoinInvalid':\n return t('workflows.reattach.rejected.forkJoinInvalid', 'That target would break the parallel branch structure: {reason}', { reason: rejection.detail ?? '' })\n default:\n return t('workflows.reattach.rejected.unsupported', 'That route cannot be re-targeted.')\n }\n }, [t])\n\n const handleReconnect = useCallback((oldEdge: Edge, connection: Connection) => {\n if (isCodeOnly) return\n const result = reattachWorkflowEdge(nodesRef.current, edgesRef.current, oldEdge.id, connection)\n if (!result.ok) {\n flash(describeReattachRejection(result), 'error')\n return\n }\n commitHistory(historyLabels.reattach)\n setEdges(result.edges)\n scheduleAutosave()\n flash(t('workflows.reattach.retargeted', 'Route re-targeted'), 'success')\n }, [isCodeOnly, describeReattachRejection, commitHistory, historyLabels.reattach, scheduleAutosave, t])\n\n // Typed trigger contextMapping targets (spec section 3.1, step 1.9): the\n // ledger stays pure, so trigger event payload contracts are pre-resolved\n // here from the already-fetched declared-events list (which carries\n // payloadSchema since step 1.7) and passed in as plain data. Schema-less or\n // wildcard triggers get no contract and their mapping targets stay unknown.\n // Handler-step candidates for the definition-level error handler: every step\n // that can actually receive the run (START/END are not recovery targets).\n const errorHandlerStepOptions = useMemo(\n () =>\n nodes\n .filter((node) => node.type !== 'start' && node.type !== 'end')\n .map((node) => ({\n stepId: node.id,\n label: typeof node.data?.label === 'string' && node.data.label ? node.data.label : node.id,\n })),\n [nodes],\n )\n\n const { events: availableEvents } = useAvailableEvents()\n const triggerPayloadContracts = useMemo(\n () => buildTriggerPayloadContracts(triggers, availableEvents),\n [triggers, availableEvents],\n )\n\n // Ledger entries for the variable picker in the open edit dialog (spec\n // section 3.5, step 3.2). Computed lazily \u2014 only while a dialog is open \u2014\n // with the same client-side 'unknown'-contract ledger the Problems warnings\n // use, so the picker never offers a path the ref checker would then flag.\n // Node dialogs get the edited step's incoming view; edge dialogs get the\n // TARGET step's incoming view, matching the transition scope rule in\n // lib/expression-refs.ts.\n const dialogLedger = useMemo(() => {\n if (!showNodeDialog && !showEdgeDialog) return null\n try {\n const definitionData = buildDefinitionPayload({\n graphDefinition: graphToDefinition(nodes, edges),\n triggers,\n contextSchema,\n io: definitionIo,\n })\n return computeClientContextLedger(definitionData, triggerPayloadContracts)\n } catch {\n return null\n }\n }, [showNodeDialog, showEdgeDialog, nodes, edges, triggers, contextSchema, definitionIo, triggerPayloadContracts])\n\n // A step nobody has wired yet has no incoming route, so the fixpoint leaves\n // its ledger empty and the Input data panel opened on nothing at all (issue\n // #5988). What such a step will receive once it is wired is exactly what the\n // run starts with \u2014 the START step's ledger IS that initial context, since it\n // has no incoming transitions either \u2014 so an unwired step borrows it rather\n // than showing the author an empty picker.\n const nodeDialogLedgerEntries = useMemo(() => {\n if (!dialogLedger || !selectedNode) return undefined\n const stepEntries = dialogLedger.steps[selectedNode.id]?.entries\n if (stepEntries && stepEntries.length > 0) return stepEntries\n const startNode = nodes.find((candidate) => candidate.type === 'start')\n const startEntries = startNode ? dialogLedger.steps[startNode.id]?.entries : undefined\n return startEntries && startEntries.length > 0 ? startEntries : stepEntries\n }, [dialogLedger, nodes, selectedNode])\n\n // Pinned per-step samples carried inside metadata.editor.samples (spec\n // section 3.6, step 4.4). The page owns the metadata object, so pin/unpin\n // write through setLoadedMetadata and the explicit Save (and draft\n // autosave) persist them via buildMetadataPayload's spread.\n const editorSamples = useMemo(() => {\n const editorValue = loadedMetadata?.editor\n if (!editorValue || typeof editorValue !== 'object' || Array.isArray(editorValue)) return undefined\n const samplesValue = (editorValue as Record<string, unknown>).samples\n if (!samplesValue || typeof samplesValue !== 'object' || Array.isArray(samplesValue)) return undefined\n return samplesValue as Record<string, PinnedSampleEnvelope>\n }, [loadedMetadata])\n\n const handlePinSample = useCallback((stepId: string, data: unknown) => {\n commitHistory(historyLabels.pinSample)\n setLoadedMetadata((previous) => {\n const base: Record<string, unknown> = { ...(previous ?? {}) }\n const editorValue = base.editor\n const editor: Record<string, unknown> =\n editorValue && typeof editorValue === 'object' && !Array.isArray(editorValue)\n ? { ...(editorValue as Record<string, unknown>) }\n : {}\n const samplesValue = editor.samples\n const samples: Record<string, unknown> =\n samplesValue && typeof samplesValue === 'object' && !Array.isArray(samplesValue)\n ? { ...(samplesValue as Record<string, unknown>) }\n : {}\n samples[stepId] = { pinnedAt: new Date().toISOString(), source: 'test', data }\n editor.samples = samples\n base.editor = editor\n return base\n })\n flash(t('workflows.testStep.pinnedFlash', 'Sample pinned \u2014 it is stored with the definition on save'), 'success')\n }, [commitHistory, historyLabels.pinSample, t])\n\n const handleUnpinSample = useCallback((stepId: string) => {\n commitHistory(historyLabels.unpinSample)\n setLoadedMetadata((previous) => {\n if (!previous) return previous\n const editorValue = previous.editor\n if (!editorValue || typeof editorValue !== 'object' || Array.isArray(editorValue)) return previous\n const editor = { ...(editorValue as Record<string, unknown>) }\n const samplesValue = editor.samples\n if (!samplesValue || typeof samplesValue !== 'object' || Array.isArray(samplesValue)) return previous\n const samples = { ...(samplesValue as Record<string, unknown>) }\n if (!(stepId in samples)) return previous\n delete samples[stepId]\n if (Object.keys(samples).length > 0) editor.samples = samples\n else delete editor.samples\n const base = { ...previous }\n if (Object.keys(editor).length > 0) base.editor = editor\n else delete base.editor\n return Object.keys(base).length > 0 ? base : null\n })\n }, [commitHistory, historyLabels.unpinSample])\n\n // Named START contexts (spec section 8.1). They live beside samples in\n // metadata.editor, but they are a DIFFERENT thing \u2014 a whole start context,\n // not per-step data \u2014 so they get their own key and their own cap.\n const startFixtures = useMemo(() => {\n const editorValue = loadedMetadata?.editor\n if (!editorValue || typeof editorValue !== 'object' || Array.isArray(editorValue)) return undefined\n const fixturesValue = (editorValue as Record<string, unknown>).fixtures\n if (!fixturesValue || typeof fixturesValue !== 'object' || Array.isArray(fixturesValue)) return undefined\n return fixturesValue as WorkflowStartFixtures\n }, [loadedMetadata])\n\n const startFixtureList = useMemo(() => listStartFixtures(startFixtures), [startFixtures])\n\n const handleSaveFixture = useCallback(() => {\n let context: Record<string, unknown>\n try {\n const parsed = startContext.trim() ? JSON.parse(startContext) : {}\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('[internal] context must be a JSON object')\n }\n context = parsed as Record<string, unknown>\n } catch {\n flash(t('workflows.startInstance.invalidJson'), 'error')\n return\n }\n\n const result = upsertStartFixture(startFixtures, fixtureName, context, new Date().toISOString())\n if (!result.ok) {\n flash(t(`workflows.fixtures.errors.${result.reason}`), 'error')\n return\n }\n\n commitHistory(historyLabels.saveFixture)\n setLoadedMetadata((previous) => {\n const base: Record<string, unknown> = { ...(previous ?? {}) }\n const editorValue = base.editor\n const editor: Record<string, unknown> =\n editorValue && typeof editorValue === 'object' && !Array.isArray(editorValue)\n ? { ...(editorValue as Record<string, unknown>) }\n : {}\n editor.fixtures = result.fixtures\n base.editor = editor\n return base\n })\n setFixtureName('')\n flash(t('workflows.fixtures.saved'), 'success')\n }, [startContext, startFixtures, fixtureName, commitHistory, historyLabels.saveFixture, t])\n\n const handleApplyFixture = useCallback((name: string) => {\n const fixture = startFixtures?.[name]\n if (!fixture) return\n setStartContext(JSON.stringify(fixture.context, null, 2))\n setFixtureName(fixture.name)\n }, [startFixtures])\n\n const handleDeleteFixture = useCallback((name: string) => {\n commitHistory(historyLabels.deleteFixture)\n setLoadedMetadata((previous) => {\n if (!previous) return previous\n const editorValue = previous.editor\n if (!editorValue || typeof editorValue !== 'object' || Array.isArray(editorValue)) return previous\n const editor = { ...(editorValue as Record<string, unknown>) }\n const next = removeStartFixture(editor.fixtures as WorkflowStartFixtures | undefined, name)\n if (Object.keys(next).length > 0) editor.fixtures = next\n else delete editor.fixtures\n const base = { ...previous }\n if (Object.keys(editor).length > 0) base.editor = editor\n else delete base.editor\n return Object.keys(base).length > 0 ? base : null\n })\n }, [commitHistory, historyLabels.deleteFixture])\n\n const edgeDialogLedgerEntries = useMemo(\n () => (dialogLedger && selectedEdge ? dialogLedger.steps[selectedEdge.target]?.entries : undefined),\n [dialogLedger, selectedEdge],\n )\n\n // Bridge the pure issue collector to the page's i18n. `t` already accepts a\n // fallback plus params, so the flow-logic messages stay translatable without\n // the collector depending on React.\n const translateIssue = useCallback<WorkflowIssueTranslator>(\n (key, fallback, params) => t(key, fallback, params),\n [t],\n )\n\n // Collect every graph and schema issue for the current document. Shared by the\n // explicit Validate action and the Code view's JSON-schema validation display\n // (spec \u00A72.2), so both surfaces can never disagree about what is wrong.\n const evaluateWorkflowIssues = useCallback((): WorkflowValidationIssue[] => {\n const graphErrors = validateWorkflowGraph(nodes, edges)\n let zodIssues: ZodIssueLike[] = []\n let configWarnings: ZodIssueLike[] = []\n let schemaFailureMessage: string | null = null\n let flowLogicDefinition: WorkflowDefinitionData | null = null\n let flowLogicLedger: ReturnType<typeof computeClientContextLedger> | undefined\n\n try {\n const definitionData = graphToDefinition(nodes, edges, { includePositions: true })\n const result = workflowDefinitionDataSchema.safeParse(definitionData)\n if (!result.success) {\n zodIssues = result.error.issues\n }\n const ledgerDefinition = buildDefinitionPayload({ graphDefinition: definitionData, triggers, contextSchema, io: definitionIo, interpolation, errorHandler })\n flowLogicDefinition = ledgerDefinition\n flowLogicLedger = computeClientContextLedger(ledgerDefinition, triggerPayloadContracts)\n configWarnings = [\n ...collectActivityConfigWarnings(definitionData),\n ...collectContextRefWarnings(ledgerDefinition, t, triggerPayloadContracts),\n ]\n } catch (error) {\n schemaFailureMessage = error instanceof Error ? error.message : String(error)\n }\n\n const issues = collectValidationIssues({\n graphErrors,\n zodIssues,\n configWarnings,\n nodes,\n edges,\n definition: flowLogicDefinition,\n ledger: flowLogicLedger,\n translate: translateIssue,\n })\n if (schemaFailureMessage) {\n issues.unshift({\n id: 'schema-exception',\n severity: 'error',\n message: t('workflows.visualEditor.problems.schemaValidationFailed', 'Schema validation failed: {message}', { message: schemaFailureMessage }),\n })\n }\n return issues\n }, [nodes, edges, triggers, contextSchema, definitionIo, interpolation, errorHandler, triggerPayloadContracts, translateIssue, t])\n\n // Validate workflow \u2014 collect every graph and schema issue into the problems\n // panel. Shared by the explicit Validate action and by the \"Problems pass\n // already run\" an applied AI draft owes the author (spec \u00A79).\n const runProblemsPass = useCallback(() => {\n const issues = evaluateWorkflowIssues()\n setProblems(issues)\n\n if (issues.length === 0) {\n setShowProblems(false)\n flash(t('workflows.visualEditor.problems.validationPassed', 'Validation passed! Your workflow is valid and ready to save.'), 'success')\n } else {\n setShowProblems(true)\n setProblemsCollapsed(false)\n const { errors, warnings } = countIssuesBySeverity(issues)\n flash(\n t('workflows.visualEditor.problems.summary', 'Validation found {errors} error(s) and {warnings} warning(s).', { errors, warnings }),\n errors > 0 ? 'error' : 'warning',\n )\n }\n }, [evaluateWorkflowIssues, t])\n\n const handleValidate = runProblemsPass\n\n // Code view, stage 1 (spec \u00A72.2). The JSON is assembled through the same\n // builders Save uses, so what an author reads is exactly what is persisted;\n // it is only computed while the panel is open.\n const codeViewJson = useMemo(() => {\n if (!showCodeView) return ''\n try {\n const definitionData = buildDefinitionPayload({\n graphDefinition: graphToDefinition(nodes, edges, { includePositions: true }),\n triggers,\n contextSchema,\n io: definitionIo,\n interpolation,\n errorHandler,\n })\n return JSON.stringify(definitionData, null, 2)\n } catch (error) {\n return t(\n 'workflows.visualEditor.codeView.assemblyFailed',\n 'The definition could not be assembled: {message}',\n { message: error instanceof Error ? error.message : String(error) },\n )\n }\n }, [showCodeView, nodes, edges, triggers, contextSchema, definitionIo, interpolation, errorHandler, t])\n\n const codeViewIssues = useMemo(\n () => (showCodeView ? evaluateWorkflowIssues() : []),\n [showCodeView, evaluateWorkflowIssues],\n )\n\n // Code view stage 2 (spec \u00A72.2). Safety model, stated once:\n // canvas \u2192 code is LIVE (the panel re-renders from the canvas whenever the\n // author has not started editing); code \u2192 canvas needs an explicit Apply.\n // Parsing, validation and the gutter markers stay live as you type, so the\n // feedback loop is immediate even though the commit is not \u2014 mutating the\n // canvas per keystroke would delete every node the moment \"steps\" is\n // mid-rename, and push one undo entry per character.\n const [codeDraft, setCodeDraft] = useState<string | null>(null)\n const codeDraftText = codeDraft ?? codeViewJson\n\n // The ONE gate a whole definition passes before it may replace the document.\n // Extracted so the Code view's Apply and the AI draft's Apply (spec \u00A79) share\n // it verbatim \u2014 an AI-authored graph has earned exactly as much trust as a\n // pasted one, which is to say none.\n const definitionApplyGate = useMemo(() => ({\n parseDefinition: (parsed: unknown) => {\n const result = workflowDefinitionDataSchema.safeParse(parsed)\n if (result.success) return { ok: true as const, definition: result.data as WorkflowDefinitionData }\n return {\n ok: false as const,\n messages: result.error.issues.map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`),\n }\n },\n // Warnings never block, exactly as they never block a Save; only graph\n // ERRORS do, because a canvas holding a graph the engine rejects is worse\n // than no apply \u2014 the author has lost the text they typed.\n // `autoLayout: false` on purpose: whether a definition is VALID cannot\n // depend on running a layout engine over it, and skipping dagre keeps this\n // memo cheap enough to run on every keystroke.\n validateGraph: (definition: WorkflowDefinitionData) => {\n const graph = definitionToGraph(definition, { autoLayout: false })\n return validateWorkflowGraph(graph.nodes, graph.edges)\n .filter((issue) => issue.type === 'error')\n .map((issue) => issue.message)\n },\n }), [])\n\n const codeApplyDecision = useMemo(\n () => evaluateCodeViewDraft<WorkflowDefinitionData>({\n draftText: codeDraftText,\n canvasText: codeViewJson,\n ...definitionApplyGate,\n }),\n [codeDraftText, codeViewJson, definitionApplyGate],\n )\n\n const codeDraftStatus = useMemo(() => describeCodeViewDraft(codeApplyDecision), [codeApplyDecision])\n\n const codeIssueLocations = useMemo(() => {\n if (!showCodeView) return { severityByLine: new Map<number, 'error' | 'warning'>(), lineByIssueId: new Map<string, number>() }\n let parsed: unknown\n try {\n parsed = JSON.parse(codeDraftText)\n } catch {\n // Unparseable text has no entity positions to point at; the parse-error\n // line is marked on its own by `codeDraftStatus`.\n return { severityByLine: new Map<number, 'error' | 'warning'>(), lineByIssueId: new Map<string, number>() }\n }\n const locations = locateDefinitionJsonEntities(codeDraftText, parsed)\n const located = locateIssues(codeViewIssues, locations)\n return {\n severityByLine: severityByLine(located),\n lineByIssueId: new Map(located.map((issue) => [issue.issueId, issue.line])),\n }\n }, [showCodeView, codeDraftText, codeViewIssues])\n\n // Replace the whole editor document from a validated definition, as ONE undo\n // entry named `label`. Shared by the Code view's Apply and the AI draft's\n // Apply so a twenty-node generation is exactly as reversible as a paste.\n const applyDefinitionDocument = useCallback((definition: WorkflowDefinitionData, label: string) => {\n // Committed BEFORE the replacement, so undo restores the graph AND the\n // panel fields the applied definition also carried.\n commitHistory(label)\n const graph = definitionToGraph(definition, { autoLayout: true })\n setNodes(graph.nodes)\n setEdges(graph.edges)\n setTriggers(definition.triggers ?? [])\n // The zod-parsed shapes leave the optional field flags optional; the editor\n // state types have them resolved. The same narrowing the draft-restore path\n // uses applies here.\n setContextSchema(definition.contextSchema as WorkflowContextSchema | undefined)\n setDefinitionIo(definition.io as WorkflowIoContract | undefined)\n setInterpolation(definition.interpolation)\n setErrorHandler(definition.errorHandler)\n scheduleAutosave()\n }, [commitHistory, scheduleAutosave])\n\n const handleApplyCodeDraft = useCallback(() => {\n if (!codeApplyDecision.ok) return\n applyDefinitionDocument(codeApplyDecision.definition, historyLabels.applyCode)\n setCodeDraft(null)\n flash(t('workflows.visualEditor.codeView.applied'), 'success')\n }, [codeApplyDecision, applyDefinitionDocument, historyLabels.applyCode, t])\n\n // ---------------------------------------------------------------------\n // Prompt-to-draft (spec \u00A79)\n //\n // The generated definition NEVER reaches the canvas by a path of its own: it\n // goes through `evaluateCodeViewDraft`, the same gate a pasted definition\n // passes, and lands through `applyDefinitionDocument`, the same replacement\n // the Code view's Apply performs. So a refused draft leaves the canvas\n // byte-identical, and an applied one \u2014 however many nodes it minted \u2014 is ONE\n // named entry on the existing undo stack.\n //\n // Nothing here writes to the server. The route that generated the draft\n // persisted nothing either; Save and Enable stay exactly where they were.\n // ---------------------------------------------------------------------\n const [showAiDraft, setShowAiDraft] = useState(false)\n const [problemsPassToken, setProblemsPassToken] = useState(0)\n\n // The pass has to observe the APPLIED graph, and `evaluateWorkflowIssues`\n // closes over the node/edge state, so it runs on the commit after the apply\n // rather than inside it. The ref keeps it the page's ONE evaluator.\n const runProblemsPassRef = React.useRef(runProblemsPass)\n runProblemsPassRef.current = runProblemsPass\n useEffect(() => {\n if (problemsPassToken === 0) return\n runProblemsPassRef.current()\n }, [problemsPassToken])\n\n const handleApplyAiDraft = useCallback((input: {\n definition: Record<string, unknown>\n prompt: string\n }): WorkflowAiDraftApplyRefusal | null => {\n const decision = evaluateCodeViewDraft<WorkflowDefinitionData>({\n // Serialized so the AI path and the Code view path are literally the same\n // call. It also proves the draft survives the JSON round trip the Code\n // view and every save will put it through.\n draftText: JSON.stringify(input.definition, null, 2),\n ...definitionApplyGate,\n })\n\n if (!decision.ok) {\n switch (decision.reason) {\n case 'parseError':\n return { reason: 'parseError', messages: [decision.message] }\n case 'schemaError':\n case 'graphError':\n return { reason: decision.reason, messages: decision.messages }\n default:\n // `unchanged` cannot occur \u2014 no `canvasText` is supplied \u2014 but a\n // refusal must never fall through into a silent apply.\n return {\n reason: 'schemaError',\n messages: [t('workflows.aiDraft.refusedUnknown', 'The generated definition was refused.')],\n }\n }\n }\n\n applyDefinitionDocument(\n decision.definition,\n buildAiCheckpointLabel(input.prompt, {\n prefix: t('workflows.visualEditor.history.aiDraft', 'AI draft'),\n }),\n )\n setProblemsPassToken((token) => token + 1)\n flash(\n t('workflows.aiDraft.applied', 'AI draft applied. Review the problems, then save when you are happy with it.'),\n 'success',\n )\n return null\n }, [definitionApplyGate, applyDefinitionDocument, t])\n\n const handleRevertCodeDraft = useCallback(() => {\n setCodeDraft(null)\n }, [])\n\n // Closing the panel discards an unapplied draft: keeping it would let the\n // author reopen the view onto text that no longer describes the canvas, with\n // no signal that the two had diverged.\n const handleCloseCodeView = useCallback(() => {\n setCodeDraft(null)\n setShowCodeView(false)\n }, [])\n\n const handleCopyDefinitionJson = useCallback(async () => {\n try {\n await navigator.clipboard.writeText(codeViewJson)\n flash(t('workflows.visualEditor.codeView.copied', 'Definition JSON copied'), 'success')\n } catch (error) {\n logger.warn('Workflow definition JSON copy was blocked by the browser', { err: error })\n flash(\n t(\n 'workflows.visualEditor.codeView.copyUnavailable',\n 'The browser blocked clipboard access, so nothing was copied \u2014 select the JSON and copy it manually.',\n ),\n 'warning',\n )\n }\n }, [codeViewJson, t])\n\n // Focus the offending node or edge on the canvas when a problem row is clicked\n const handleProblemClick = useCallback((issue: WorkflowValidationIssue) => {\n if (!issue.nodeId && !issue.edgeId) return\n focusRequestRef.current += 1\n setFocusTarget({\n ...(issue.nodeId ? { nodeId: issue.nodeId } : { edgeId: issue.edgeId }),\n requestId: focusRequestRef.current,\n })\n }, [])\n\n // Save workflow definition\n const handleSave = useCallback(async () => {\n // Validate required fields. They live in the details drawer, so open it \u2014\n // an error toast pointing at fields the author cannot see is a dead end.\n if (!workflowId || !workflowName) {\n setMetadataOpen(true)\n flash(t('workflows.visualEditor.metadata.requiredFields', 'Workflow ID and name are required.'), 'error')\n return\n }\n\n // Validate workflow structure and schema, surfacing every issue in the problems panel\n const graphErrors = validateWorkflowGraph(nodes, edges)\n\n // Generate definition data and re-attach triggers, contextSchema, io, and\n // the interpolation mode\n const definitionData = buildDefinitionPayload({\n graphDefinition: graphToDefinition(nodes, edges, { includePositions: true }),\n triggers,\n contextSchema,\n io: definitionIo,\n interpolation,\n errorHandler,\n })\n\n const schemaResult = workflowDefinitionDataSchema.safeParse(definitionData)\n const issues = collectValidationIssues({\n graphErrors,\n zodIssues: schemaResult.success ? [] : schemaResult.error.issues,\n configWarnings: [\n ...collectActivityConfigWarnings(definitionData),\n ...collectContextRefWarnings(definitionData, t, triggerPayloadContracts),\n ],\n nodes,\n edges,\n definition: definitionData,\n ledger: computeClientContextLedger(definitionData, triggerPayloadContracts),\n translate: translateIssue,\n })\n setProblems(issues)\n const { errors } = countIssuesBySeverity(issues)\n if (errors > 0) {\n setShowProblems(true)\n setProblemsCollapsed(false)\n flash(t('workflows.visualEditor.problems.saveBlocked', 'Cannot save: {count} validation error(s) found. Please fix them first.', { count: errors }), 'error')\n return\n }\n\n setIsSaving(true)\n\n try {\n\n const metadataPayload = buildMetadataPayload({ loadedMetadata, tags, category, icon, definition: definitionData, annotations })\n\n // Determine if creating new or updating existing\n const isUpdate = !!definitionId\n\n let result\n let updateBody: DefinitionUpdateBody | null = null\n if (isUpdate) {\n // Update existing definition \u2014 send the full editable payload so metadata\n // edits (name, description, version, category, tags, icon, effective\n // dates) actually persist. Previously only `definition` + `enabled`\n // were sent, silently dropping every other field.\n updateBody = {\n workflowName,\n description: description || null,\n version,\n definition: definitionData,\n metadata: metadataPayload,\n enabled,\n effectiveFrom: effectiveFrom || null,\n effectiveTo: effectiveTo || null,\n }\n result = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(updatedAt),\n () => apiCall<{ data: any; error?: string }>(`/api/workflows/definitions/${definitionId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(updateBody),\n }),\n )\n } else {\n // Create new definition\n result = await apiCall<{ data: any; error?: string }>('/api/workflows/definitions', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n workflowId,\n workflowName,\n description: description || null,\n version,\n definition: definitionData,\n metadata: metadataPayload,\n enabled,\n effectiveFrom: effectiveFrom || null,\n effectiveTo: effectiveTo || null,\n }),\n })\n }\n\n if (!result.ok) {\n const activeInstanceCount = readStructuralEditConflictCount(result.status, result.result)\n if (activeInstanceCount !== null && updateBody) {\n setStructuralConflict({ activeInstanceCount, payload: updateBody })\n return\n }\n const conflictError = Object.assign(new Error(t('workflows.messages.saveFailed', 'Failed to save')), {\n status: result.status,\n ...(result.result && typeof result.result === 'object' ? result.result : {}),\n })\n if (!surfaceRecordConflict(conflictError, t)) {\n flash(formatWorkflowValidationError(result.result, t('workflows.messages.saveFailed', 'Failed to save')), 'error')\n }\n return\n }\n\n setStructuralConflict(null)\n if (updateBody) lastAutosavedBodyRef.current = stableSerializeDefinition(updateBody)\n\n const savedDefinition = result.result?.data\n\n // Explicit Save promoted the working copy: drop the per-user draft\n // (fire-and-forget) and suspend autosave so a pending debounce can't\n // recreate it before the redirect.\n draftSuspendedRef.current = true\n setPendingDraft(null)\n setDraftSavedAt(null)\n setDraftSaveFailed(false)\n if (isUpdate && isServerDraftEligible(definitionId)) {\n void apiCall(`/api/workflows/definitions/${definitionId}/draft`, { method: 'DELETE' }).catch(() => undefined)\n }\n\n flash(\n isUpdate\n ? t('workflows.messages.workflowUpdated', 'Workflow updated successfully')\n : t('workflows.messages.workflowCreated', 'Workflow created successfully'),\n 'success',\n )\n\n // Stay on the visual editor after saving. On update, refresh the local\n // optimistic-lock token so the next save keeps working. On create, switch\n // the editor into edit mode by pointing the URL at the new id \u2014 the load\n // effect then re-syncs from the persisted definition without leaving the\n // canvas.\n if (isUpdate) {\n if (typeof savedDefinition?.updatedAt === 'string') {\n setUpdatedAt(savedDefinition.updatedAt)\n }\n } else if (savedDefinition?.id) {\n router.replace(`/backend/definitions/visual-editor?id=${encodeURIComponent(savedDefinition.id)}`)\n }\n\n } catch (error) {\n logger.error('Error saving workflow definition', { err: error })\n flash(t('workflows.messages.saveFailed', 'Failed to save'), 'error')\n } finally {\n setIsSaving(false)\n }\n }, [nodes, edges, workflowId, workflowName, description, version, enabled, category, tags, icon, effectiveFrom, effectiveTo, triggers, contextSchema, definitionIo, interpolation, errorHandler, loadedMetadata, annotations, definitionId, updatedAt, router, t])\n\n // \u2500\u2500 Non-pointer authoring path (spec \u00A74.6) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Every canvas operation is reachable from the keyboard: the command palette\n // reaches all of them, and the direct bindings below cover the ones an author\n // performs constantly (open, delete, nudge).\n\n const focusNode = useCallback((nodeId: string) => {\n focusRequestRef.current += 1\n setFocusTarget({ nodeId, requestId: focusRequestRef.current })\n }, [])\n\n const openSelectedInspector = useCallback(() => {\n const selected = nodesRef.current.find((node) => node.selected)\n if (!selected) {\n const selectedEdgeNode = edgesRef.current.find((edge) => edge.selected)\n if (!selectedEdgeNode || isCodeOnly) return\n setSelectedEdge(selectedEdgeNode)\n setSelectedNode(null)\n setEdgeDialogFocusFieldId(null)\n setShowEdgeDialog(true)\n return\n }\n handleNodeClick({} as React.MouseEvent, selected)\n }, [isCodeOnly, handleNodeClick])\n\n // Del removes whatever is selected. Each removal runs its own confirm +\n // cleanup flow, so a multi-selection deletes exactly as clicking each trash\n // button would \u2014 and each one is undoable.\n const handleDeleteSelection = useCallback(async () => {\n if (isCodeOnly) return\n const nodeIds = selectedNodeIds(nodesRef.current)\n const edgeIds = edgesRef.current.filter((edge) => edge.selected).map((edge) => edge.id)\n if (nodeIds.length === 0 && edgeIds.length === 0) {\n flash(t('workflows.visualEditor.keyboard.nothingSelected', 'Select a step or a route first'), 'info')\n return\n }\n for (const edgeId of edgeIds) await handleDeleteEdge(edgeId)\n for (const nodeId of nodeIds) await handleDeleteNode(nodeId)\n }, [isCodeOnly, handleDeleteEdge, handleDeleteNode, t])\n\n // Arrow-key nudging follows the drag rule (#4248): a burst of keystrokes is\n // ONE arrangement, so the baseline is captured on the first press and the undo\n // entry plus the autosave land once the burst settles.\n const nudgeBaselineRef = React.useRef<WorkflowEditorDocument | null>(null)\n const nudgeCommitTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n\n const handleNudge = useCallback((key: string, coarse: boolean) => {\n if (isCodeOnly) return false\n const direction = resolveNudgeDirection(key)\n if (!direction) return false\n if (selectedNodeIds(nodesRef.current).length === 0) return false\n if (!nudgeBaselineRef.current) nudgeBaselineRef.current = captureDocument()\n setNodes((nds) => nudgeSelectedNodes(nds, nudgeOffset(direction, coarse)))\n if (nudgeCommitTimerRef.current) clearTimeout(nudgeCommitTimerRef.current)\n nudgeCommitTimerRef.current = setTimeout(() => {\n nudgeCommitTimerRef.current = null\n const baseline = nudgeBaselineRef.current\n nudgeBaselineRef.current = null\n if (baseline) commitCapturedDocument(baseline, historyLabels.move)\n scheduleAutosave()\n }, NUDGE_COMMIT_DELAY_MS)\n return true\n }, [isCodeOnly, captureDocument, commitCapturedDocument, historyLabels.move, scheduleAutosave])\n\n useEffect(() => () => {\n if (nudgeCommitTimerRef.current) clearTimeout(nudgeCommitTimerRef.current)\n }, [])\n\n const commandPaletteCommands = useMemo<WorkflowEditorCommand[]>(() => buildWorkflowEditorCommands({\n readOnly: isCodeOnly,\n canUndo: canUndoEditorHistory(history),\n canRedo: canRedoEditorHistory(history),\n hasNodes: nodes.length > 0,\n hasSelection: nodes.some((node) => node.selected) || edges.some((edge) => edge.selected),\n canRunTest: !!definitionId,\n stepTypes: PALETTE_NODE_TYPES.map((nodeType) => ({\n nodeType,\n typeLabel: NODE_TYPE_LABELS[nodeType]?.title ?? nodeType,\n })),\n steps: nodes\n .filter((node) => !isAnnotationNode(node))\n .map((node) => ({\n id: node.id,\n label: typeof node.data?.label === 'string' && node.data.label ? node.data.label : node.id,\n typeLabel: NODE_TYPE_LABELS[(node.type ?? '') as keyof typeof NODE_TYPE_LABELS]?.title ?? node.type ?? '',\n })),\n labels: {\n undo: t('workflows.commandPalette.undo', 'Undo'),\n redo: t('workflows.commandPalette.redo', 'Redo'),\n deleteSelection: t('workflows.commandPalette.delete', 'Delete selection'),\n copy: t('workflows.commandPalette.copy', 'Copy selection'),\n paste: t('workflows.commandPalette.paste', 'Paste'),\n duplicate: t('workflows.commandPalette.duplicate', 'Duplicate selection'),\n addStep: (typeLabel: string) => t('workflows.commandPalette.addStep', 'Add step: {type}', { type: typeLabel }),\n addNote: t('workflows.commandPalette.addNote', 'Add note'),\n addGroup: t('workflows.commandPalette.addGroup', 'Add group'),\n goToStep: t('workflows.commandPalette.goToStep', 'Go to step'),\n tidy: t('workflows.visualEditor.autoArrange'),\n togglePalette: t('workflows.commandPalette.togglePalette', 'Toggle the step palette'),\n toggleMetadata: t('workflows.commandPalette.toggleMetadata', 'Toggle the workflow details panel'),\n toggleFocus: t('workflows.commandPalette.toggleFocus', 'Toggle focus mode'),\n toggleProblems: t('workflows.commandPalette.toggleProblems', 'Toggle the Problems panel'),\n toggleCodeView: t('workflows.commandPalette.toggleCodeView', 'Toggle the Code view'),\n toggleCompensation: t('workflows.commandPalette.toggleCompensation', 'Toggle compensation paths'),\n validate: t('workflows.visualEditor.validate'),\n runTest: t('workflows.actions.startInstance'),\n save: t('workflows.common.save'),\n aiDraft: t('workflows.aiDraft.open', 'Draft this workflow with AI'),\n },\n actions: {\n undo: handleUndo,\n redo: handleRedo,\n deleteSelection: () => { void handleDeleteSelection() },\n copy: () => { void handleCopySelection() },\n paste: () => { void handlePaste() },\n duplicate: handleDuplicateSelection,\n addStep: (nodeType: string) => handleAddNode(nodeType),\n addNote: () => handleAddAnnotation('note'),\n addGroup: () => handleAddAnnotation('group'),\n goToStep: focusNode,\n tidy: handleAutoArrange,\n togglePalette: togglePaletteCollapsed,\n toggleMetadata: () => setMetadataOpen((open) => !open),\n toggleFocus,\n toggleProblems: () => setShowProblems((visible) => !visible),\n toggleCodeView: () => setShowCodeView((visible) => !visible),\n toggleCompensation,\n validate: handleValidate,\n runTest: () => setStartOpen(true),\n save: () => { void handleSave() },\n aiDraft: () => setShowAiDraft(true),\n },\n }), [\n isCodeOnly, history, nodes, edges, definitionId, t,\n handleUndo, handleRedo, handleDeleteSelection, handleCopySelection, handlePaste, handleDuplicateSelection,\n handleAddNode, handleAddAnnotation, focusNode, handleAutoArrange, togglePaletteCollapsed, toggleFocus,\n toggleCompensation, handleValidate, handleSave,\n ])\n\n // Keyboard shortcuts: Cmd/Ctrl+K opens the command palette, Cmd/Ctrl+Z undoes,\n // Cmd/Ctrl+Shift+Z redoes, Cmd/Ctrl+C, +V and +D copy, paste and duplicate the\n // selected subgraph, Enter opens the inspector for the selection, Del removes\n // it, the arrows nudge it, `F` toggles Focus mode and `Esc` exits it.\n //\n // Everything except the palette is suppressed while the user is typing in a\n // field (a text input keeps its own native undo, copy/paste and caret keys) or\n // while a dialog is open, so a shortcut never hijacks form input or the\n // dialog's own Escape-to-close. Cmd+K is deliberately exempt from the typing\n // guard: it is the way out of any focus, which is the whole point of a palette.\n useEffect(() => {\n if (isMobile) return\n const onKeyDown = (event: KeyboardEvent) => {\n const active = document.activeElement as HTMLElement | null\n const tag = (active?.tagName || '').toLowerCase()\n const isEditing = tag === 'input' || tag === 'textarea' || tag === 'select' || !!active?.isContentEditable\n // Docking is a SPATIAL change, not a keyboard one: an open inspector\n // still owns the shortcuts, because it holds a form with unsaved values\n // and every canvas binding here either mutates the document under it\n // (undo, delete, paste) or would save a graph that omits the edit sitting\n // in the rail. What docking buys is that the canvas stays visible and\n // clickable \u2014 re-targeting is a click, and Escape closes the rail.\n const isInspectorOpen = showNodeDialog || showEdgeDialog\n const isDialogOpen = isInspectorOpen || showAnnotationDialog || showClearConfirm || startOpen || showCodeView\n // The details drawer is a modal overlay, so the canvas bindings must not\n // fire behind it. Cmd+S is the deliberate exception: the drawer has no\n // submit of its own to protect \u2014 saving the workflow IS its primary\n // action \u2014 so the shortcut keeps working while it is open.\n const isOverlayOpen = isDialogOpen || metadataOpen || showAiDraft\n const isCommandKey = (event.metaKey || event.ctrlKey) && !event.altKey\n\n if (isCommandKey && (event.key === 'k' || event.key === 'K')) {\n if (isOverlayOpen) return\n event.preventDefault()\n setShowCommandPalette((open) => !open)\n return\n }\n if (isCommandKey && !event.shiftKey && (event.key === 's' || event.key === 'S')) {\n if (isDialogOpen || isCodeOnly) return\n event.preventDefault()\n void handleSave()\n return\n }\n if (isEditing || showCommandPalette) return\n\n if (isCommandKey && (event.key === 'z' || event.key === 'Z')) {\n if (isOverlayOpen) return\n event.preventDefault()\n if (event.shiftKey) handleRedo()\n else handleUndo()\n return\n }\n if (isCommandKey && !event.shiftKey && !isOverlayOpen) {\n if (event.key === 'c' || event.key === 'C') {\n event.preventDefault()\n void handleCopySelection()\n return\n }\n if (event.key === 'v' || event.key === 'V') {\n event.preventDefault()\n void handlePaste()\n return\n }\n if (event.key === 'd' || event.key === 'D') {\n event.preventDefault()\n handleDuplicateSelection()\n return\n }\n }\n if (event.metaKey || event.ctrlKey || event.altKey) return\n if (event.key === 'Escape') {\n // Escape raised inside the rail is claimed by the rail itself. Reaching\n // here means focus is on the canvas, where Escape should still close the\n // inspector before it falls through to leaving Focus mode.\n if (inspectorsDocked && isInspectorOpen) {\n event.preventDefault()\n setShowNodeDialog(false)\n setShowEdgeDialog(false)\n return\n }\n if (focusMode && !isOverlayOpen) {\n event.preventDefault()\n setFocusMode(false)\n }\n return\n }\n if (isOverlayOpen) return\n if (event.key === 'Enter') {\n event.preventDefault()\n openSelectedInspector()\n return\n }\n if (event.key === 'Delete' || event.key === 'Backspace') {\n event.preventDefault()\n void handleDeleteSelection()\n return\n }\n if (resolveNudgeDirection(event.key)) {\n if (handleNudge(event.key, event.shiftKey)) event.preventDefault()\n return\n }\n if (event.key === 'f' || event.key === 'F') {\n event.preventDefault()\n toggleFocus()\n }\n }\n window.addEventListener('keydown', onKeyDown)\n return () => window.removeEventListener('keydown', onKeyDown)\n }, [\n isMobile, focusMode, inspectorsDocked, showNodeDialog, showEdgeDialog, showAnnotationDialog, showClearConfirm, startOpen,\n showCodeView, metadataOpen, showAiDraft, showCommandPalette, toggleFocus, setFocusMode, handleUndo, handleRedo, handleCopySelection, handlePaste,\n handleDuplicateSelection, openSelectedInspector, handleDeleteSelection, handleNudge,\n handleSave, isCodeOnly,\n ])\n\n // Quiet autosave routine (no redirect, no success flash). Mirrors the update\n // branch of `handleSave` exactly \u2014 same payload and the same optimistic-lock\n // header \u2014 so dragged positions persist without an explicit Save. Reassigned\n // every render and invoked through `performAutosaveRef` by the debounced timer\n // so it always sees the latest nodes/edges/metadata.\n performAutosaveRef.current = async () => {\n if (!definitionId || isCodeOnly) return\n if (!workflowId || !workflowName) return\n\n const criticalErrors = validateWorkflowGraph(nodes, edges).filter((e) => e.type === 'error')\n if (criticalErrors.length > 0) return\n\n // Same payload builders as the explicit Save: the quiet autosave must not\n // strip contextSchema, io, interpolation, or unedited metadata keys\n // (editor samples).\n const definitionData = buildDefinitionPayload({\n graphDefinition: graphToDefinition(nodes, edges, { includePositions: true }),\n triggers,\n contextSchema,\n io: definitionIo,\n interpolation,\n errorHandler,\n })\n if (!workflowDefinitionDataSchema.safeParse(definitionData).success) return\n\n const metadataPayload = buildMetadataPayload({ loadedMetadata, tags, category, icon, definition: definitionData, annotations })\n\n const updateBody: DefinitionUpdateBody = {\n workflowName,\n description: description || null,\n version,\n definition: definitionData,\n metadata: metadataPayload,\n enabled,\n effectiveFrom: effectiveFrom || null,\n effectiveTo: effectiveTo || null,\n }\n\n // Autosave only when the payload actually differs from what the row already\n // holds. Without this a selection or a re-render would PUT an identical body\n // and bump the optimistic-lock token for nothing.\n const serializedBody = stableSerializeDefinition(updateBody)\n if (serializedBody === lastAutosavedBodyRef.current) return\n lastAutosavedBodyRef.current = serializedBody\n\n setAutosaveState('saving')\n try {\n const result = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(updatedAt),\n () => apiCall<{ data: any; error?: string }>(`/api/workflows/definitions/${definitionId}`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(updateBody),\n }),\n )\n\n if (!result.ok) {\n setAutosaveState('idle')\n lastAutosavedBodyRef.current = null\n // A quiet autosave carrying a structural change hits the same edit-safety\n // rule as Save. Surfacing the banner here keeps the author from watching\n // \"Saved\" never appear with no explanation.\n const activeInstanceCount = readStructuralEditConflictCount(result.status, result.result)\n if (activeInstanceCount !== null) {\n setStructuralConflict({ activeInstanceCount, payload: updateBody })\n return\n }\n const conflictError = Object.assign(new Error('[internal] workflow autosave failed'), {\n status: result.status,\n ...(result.result && typeof result.result === 'object' ? result.result : {}),\n })\n surfaceRecordConflict(conflictError, t)\n return\n }\n\n setStructuralConflict(null)\n\n const savedDefinition = result.result?.data\n if (typeof savedDefinition?.updatedAt === 'string') {\n setUpdatedAt(savedDefinition.updatedAt)\n }\n setAutosaveState('saved')\n } catch (error) {\n logger.error('workflow autosave failed', {\n error: error instanceof Error ? error.message : String(error),\n })\n lastAutosavedBodyRef.current = null\n setAutosaveState('idle')\n }\n }\n\n // Fade the \"Saved\" affordance back to idle shortly after a successful autosave.\n useEffect(() => {\n if (autosaveState !== 'saved') return\n const timer = setTimeout(() => setAutosaveState('idle'), 2000)\n return () => clearTimeout(timer)\n }, [autosaveState])\n\n // Remedy for the edit-safety rule: mint the next version from the stored\n // definition (the same machinery Publish uses), apply the rejected edit to\n // that fresh row, and continue editing it. Instances that pinned the previous\n // row keep executing the definition they started on.\n const handleCreateVersion = useCallback(async () => {\n if (!definitionId || !structuralConflict) return\n setIsCreatingVersion(true)\n try {\n const publishResult = await apiCall<{ data?: { id?: string; version?: number; updatedAt?: string }; error?: string }>(\n `/api/workflows/definitions/${definitionId}/publish`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({}) },\n )\n const mintedVersion = publishResult.result?.data\n if (!publishResult.ok || !mintedVersion?.id) {\n flash(\n publishResult.result?.error\n || t('workflows.visualEditor.editSafety.createVersionFailed', 'Could not create a new version.'),\n 'error',\n )\n return\n }\n\n const nextVersion = mintedVersion.version ?? version\n const saveResult = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(mintedVersion.updatedAt ?? null),\n () => apiCall<{ data?: { updatedAt?: string }; error?: string }>(\n `/api/workflows/definitions/${mintedVersion.id}`,\n {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ ...structuralConflict.payload, version: nextVersion }),\n },\n ),\n )\n if (!saveResult.ok) {\n flash(\n formatWorkflowValidationError(\n saveResult.result,\n t('workflows.visualEditor.editSafety.createVersionFailed', 'Could not create a new version.'),\n ),\n 'error',\n )\n return\n }\n\n setStructuralConflict(null)\n setVersion(nextVersion)\n setUpdatedAt(saveResult.result?.data?.updatedAt ?? null)\n flash(\n t('workflows.visualEditor.editSafety.createVersionSucceeded', 'Version {version} created. Your changes were saved there.', {\n version: String(nextVersion),\n }),\n 'success',\n )\n router.replace(`/backend/definitions/visual-editor?id=${encodeURIComponent(mintedVersion.id)}`)\n } finally {\n setIsCreatingVersion(false)\n }\n }, [definitionId, structuralConflict, version, router, t])\n\n // Customize a code-defined workflow \u2192 creates an override and reloads the\n // editor pointed at the new UUID. Mirrors the non-visual edit page button.\n const handleCustomize = useCallback(async () => {\n if (!definitionId) return\n setIsSaving(true)\n try {\n const result = await apiCall<{ data?: { id?: string }; error?: string }>(\n `/api/workflows/definitions/${definitionId}/customize`,\n { method: 'POST' },\n )\n if (!result.ok) {\n flash(result.result?.error || 'Failed to customize workflow', 'error')\n return\n }\n const newId = result.result?.data?.id\n if (!newId) return\n router.push(`/backend/definitions/visual-editor?id=${encodeURIComponent(newId)}`)\n router.refresh()\n } finally {\n setIsSaving(false)\n }\n }, [definitionId, router])\n\n // Reset a code-override back to its code definition. Mirrors the\n // non-visual edit page action, with the same confirm dialog.\n const handleResetToCode = useCallback(async () => {\n if (!definitionId) return\n const confirmed = await confirm({\n title: t('workflows.actions.resetToCode'),\n description: t('workflows.actions.resetConfirm'),\n confirmText: t('workflows.actions.resetToCode'),\n variant: 'destructive',\n })\n if (!confirmed) return\n\n setIsSaving(true)\n try {\n const result = await apiCall<{ data?: { id?: string }; error?: string }>(\n `/api/workflows/definitions/${definitionId}/reset-to-code`,\n { method: 'POST' },\n )\n if (!result.ok) {\n flash(result.result?.error || 'Failed to reset workflow', 'error')\n return\n }\n const codeId = result.result?.data?.id || (workflowId ? `code:${workflowId}` : null)\n if (!codeId) return\n router.push(`/backend/definitions/visual-editor?id=${encodeURIComponent(codeId)}`)\n router.refresh()\n } finally {\n setIsSaving(false)\n }\n }, [definitionId, workflowId, router, confirm, t])\n\n // Start a workflow instance with an initial JSON context, mirroring the\n // non-visual edit page. Requires a persisted definition (the executor\n // resolves the definition by workflowId + version).\n const handleStartInstance = useCallback(async () => {\n let initialContext: Record<string, unknown>\n try {\n const parsed = startContext.trim() ? JSON.parse(startContext) : {}\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new Error('[internal] context must be a JSON object')\n }\n initialContext = parsed as Record<string, unknown>\n } catch {\n flash(t('workflows.startInstance.invalidJson'), 'error')\n return\n }\n setStarting(true)\n try {\n const result = await runMutation({\n operation: async () => {\n const response = await apiFetch('/api/workflows/instances', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n workflowId,\n version,\n initialContext,\n ...(startDryRun ? { dryRun: true } : {}),\n ...(startStepThrough ? { stepThrough: true } : {}),\n }),\n })\n if (!response.ok) {\n const errorBody = await readJsonSafe<{ error?: string }>(response, null)\n throw new Error(errorBody?.error || t('workflows.startInstance.failed'))\n }\n return readJsonSafe<{ data?: { instance?: { id?: string } } }>(response, null)\n },\n mutationPayload: { resourceId: definitionId, operation: 'start-instance' },\n context: {\n formId: mutationContextId,\n resourceKind: 'workflows.instance',\n resourceId: definitionId,\n operation: 'start-instance',\n retryLastMutation,\n },\n })\n flash(t('workflows.startInstance.started'), 'success')\n setStartOpen(false)\n const instanceId = result?.data?.instance?.id\n if (instanceId) {\n router.push(`/backend/instances/${instanceId}`)\n router.refresh()\n }\n } catch (error) {\n flash(error instanceof Error ? error.message : t('workflows.startInstance.failed'), 'error')\n } finally {\n setStarting(false)\n }\n }, [startContext, startDryRun, startStepThrough, workflowId, version, definitionId, mutationContextId, retryLastMutation, router, t])\n\n // Apply a gallery template to the canvas: populate metadata from the\n // template's i18n keys and convert its definition into graph nodes/edges.\n const applyTemplate = useCallback((template: WorkflowTemplateGalleryItem) => {\n setWorkflowId(template.id.replace(/-/g, '_'))\n setWorkflowName(t(template.nameKey))\n setDescription(t(template.descriptionKey))\n setVersion(1)\n setEnabled(true)\n setCategory(template.category)\n setTags([])\n setIcon(template.icon)\n\n const graph = definitionToGraph(template.definition)\n setNodes(graph.nodes)\n setEdges(graph.edges)\n setTriggers(template.definition.triggers || [])\n setContextSchema(template.definition.contextSchema ?? undefined)\n setDefinitionIo((template.definition.io ?? undefined) as WorkflowIoContract | undefined)\n setInterpolation(resolveDefinitionInterpolationMode(template.definition) ?? 'strict')\n setErrorHandler((template.definition as { errorHandler?: WorkflowErrorHandlerConfig }).errorHandler ?? undefined)\n setLoadedMetadata(null)\n resetHistory()\n flash(t('workflows.visualEditor.templateLoaded', 'Template loaded'), 'success')\n }, [resetHistory, t])\n\n // Open the template gallery (replaces the old hardcoded inline example).\n const handleOpenTemplateGallery = useCallback(() => {\n setShowTemplateGallery(true)\n }, [])\n\n const handleTemplateSelect = useCallback((template: WorkflowTemplateGalleryItem | null) => {\n if (template) applyTemplate(template)\n }, [applyTemplate])\n\n // Populate the canvas from ?template=<id> when creating a new workflow.\n useEffect(() => {\n if (definitionId || !templateId) return\n let cancelled = false\n const loadTemplate = async () => {\n const result = await apiCall<{ items?: WorkflowTemplateGalleryItem[]; error?: string }>('/api/workflows/templates')\n if (cancelled) return\n const template = result.ok\n ? (result.result?.items || []).find((item) => item.id === templateId)\n : undefined\n if (template) {\n applyTemplate(template)\n } else {\n flash(t('workflows.templates.gallery.notFound', 'Template not found'), 'error')\n }\n }\n void loadTemplate()\n return () => {\n cancelled = true\n }\n }, [definitionId, templateId, applyTemplate, t])\n\n // Clear canvas\n const handleClear = useCallback(() => {\n if (nodes.length > 0 || edges.length > 0 || workflowId || workflowName) {\n setShowClearConfirm(true)\n }\n }, [nodes.length, edges.length, workflowId, workflowName])\n\n // Confirm clear action\n const confirmClear = useCallback(() => {\n setNodes([])\n setEdges([])\n setWorkflowId('')\n setWorkflowName('')\n setDescription('')\n setVersion(1)\n setEnabled(true)\n setCategory('')\n setTags([])\n setIcon('')\n setEffectiveFrom('')\n setEffectiveTo('')\n setTriggers([])\n setContextSchema(undefined)\n setDefinitionIo(undefined)\n setLoadedMetadata(null)\n setShowClearConfirm(false)\n resetHistory()\n flash('Canvas cleared', 'success')\n }, [resetHistory])\n\n // Publish page-load record context to the AppShell-owned `backend:record:current`\n // mount so the enterprise record_locks widget resolves `workflows.definition` + id\n // explicitly. This is the highest-value record_locks target (long-lived visual\n // edits): presence holds the lock while the graph is open, and the raw `apiCall`\n // save already routes its 409 through `surfaceRecordConflict`. Cleared on create\n // (no `definitionId`) and on unmount. Mirrors the form edit page's resourceKind so\n // a lock held in either editor surfaces in the other.\n useSetCurrentRecordInjectionContext(\n buildRecordInjectionContext({\n resourceKind: 'workflows.definition',\n resourceId: definitionId,\n updatedAt,\n path: pathname,\n }),\n )\n\n // Show loading spinner while loading definition\n if (isLoading) {\n return (\n <Page className=\"flex items-center justify-center min-h-[50vh]\">\n <LoadingMessage label=\"Loading workflow definition...\" />\n </Page>\n )\n }\n\n const metadata: WorkflowMetadataState = {\n workflowId, workflowName, description, version,\n enabled, category, tags, icon,\n effectiveFrom, effectiveTo, triggers,\n contextSchema, interpolation, errorHandler,\n }\n\n const metadataHandlers: WorkflowMetadataHandlers = {\n setWorkflowId, setWorkflowName, setDescription, setVersion,\n setEnabled, setCategory, setTags, setIcon,\n setEffectiveFrom, setEffectiveTo, setTriggers,\n setContextSchema,\n setInterpolation,\n setErrorHandler: (next) => setErrorHandler(next ?? undefined),\n }\n\n // The required identity fields now live behind the details drawer, so the\n // toolbar has to say when they are still blank.\n const metadataIncomplete = !isCodeOnly && (!workflowId || !workflowName)\n\n const inspectorPanels = (\n <>\n {crudFormDialogsEnabled ? (\n // Both forms are dense (Invoke-Agent, timeout, sub-editors on the step;\n // condition, mapping and activities on the route) and the 384px docked\n // rail made them unusable, so each opens as the wide overlay Drawer that\n // mirrors the definition metadata drawer, with its ledger in a sticky\n // side column.\n <NodeEditDialogCrudForm node={selectedNode} isOpen={showNodeDialog} onClose={() => setShowNodeDialog(false)} onSave={handleSaveNode} onDelete={handleDeleteNode} ledgerEntries={nodeDialogLedgerEntries} definitionId={definitionId} samples={editorSamples} onPinSample={handlePinSample} onUnpinSample={handleUnpinSample} branchingRoutes={branchingRoutesValue} onSaveBranchingRoutes={handleSaveBranchingRoutes} routeOrder={routeOrderValue} onSaveRouteOrder={handleSaveRouteOrder} onConvertType={handleConvertNodeType} variant=\"overlay\" wide />\n ) : (\n <NodeEditDialog node={selectedNode} isOpen={showNodeDialog} onClose={() => setShowNodeDialog(false)} onSave={handleSaveNode} onDelete={handleDeleteNode} />\n )}\n {crudFormDialogsEnabled ? (\n <EdgeEditDialogCrudForm edge={selectedEdge} isOpen={showEdgeDialog} onClose={() => setShowEdgeDialog(false)} onSave={handleSaveEdge} onDelete={handleDeleteEdge} ledgerEntries={edgeDialogLedgerEntries} focusFieldId={edgeDialogFocusFieldId} variant=\"overlay\" wide />\n ) : (\n <EdgeEditDialog edge={selectedEdge} isOpen={showEdgeDialog} onClose={() => setShowEdgeDialog(false)} onSave={handleSaveEdge} onDelete={handleDeleteEdge} />\n )}\n </>\n )\n\n const sharedDialogs = (\n <>\n {/* Docked inspectors render inside the editor's layout row instead, so\n they shrink the canvas rather than covering it. */}\n {inspectorsDocked ? null : inspectorPanels}\n <WorkflowCommandPalette\n open={showCommandPalette}\n onOpenChange={setShowCommandPalette}\n commands={commandPaletteCommands}\n />\n <DefinitionMetadataDrawer\n open={metadataOpen}\n onOpenChange={handleMetadataOpenChange}\n focusSection={metadataFocusSection}\n definitionId={definitionId}\n readOnly={isCodeOnly}\n metadata={metadata}\n handlers={metadataHandlers}\n errorHandlerStepOptions={errorHandlerStepOptions}\n onSave={() => { void handleSave() }}\n isSaving={isSaving}\n />\n <TriggersDialog\n open={triggersDialogOpen}\n onOpenChange={setTriggersDialogOpen}\n triggers={triggers}\n onSave={setTriggers}\n />\n {(() => {\n const edge = activityEdit ? edges.find((candidate) => candidate.id === activityEdit.edgeId) ?? null : null\n const activities = (edge?.data?.activities as Activity[] | undefined) ?? []\n const activity = activityEdit ? activities.find((item) => item.activityId === activityEdit.activityId) ?? null : null\n const labelFor = (nodeId: string) =>\n (nodes.find((node) => node.id === nodeId)?.data?.label as string | undefined) ?? nodeId\n const routeLabel = edge ? `${labelFor(edge.source)} \u2192 ${labelFor(edge.target)}` : undefined\n return (\n <ActivityEditDialog\n open={!!activity}\n onOpenChange={(open) => { if (!open) setActivityEdit(null) }}\n activity={activity}\n routeLabel={routeLabel}\n onSave={(updated) => {\n if (!activityEdit) return\n handleSaveEdge(activityEdit.edgeId, {\n activities: activities.map((item) => (item.activityId === updated.activityId ? updated : item)),\n })\n }}\n onRemove={() => {\n if (!activityEdit) return\n handleSaveEdge(activityEdit.edgeId, {\n activities: activities.filter((item) => item.activityId !== activityEdit.activityId),\n })\n }}\n onOpenFullTransition={() => {\n if (activityEdit) handleRouteChipOpen(activityEdit.edgeId, 'activities')\n }}\n />\n )\n })()}\n <WorkflowCodeView\n isOpen={showCodeView}\n onClose={handleCloseCodeView}\n definitionJson={codeViewJson}\n issues={codeViewIssues}\n onCopy={() => { void handleCopyDefinitionJson() }}\n onPasteSubgraph={() => { void handlePaste() }}\n canPaste={!isCodeOnly}\n onIssueClick={handleProblemClick}\n draftText={codeDraftText}\n onDraftChange={setCodeDraft}\n onApply={handleApplyCodeDraft}\n onRevert={handleRevertCodeDraft}\n draftStatus={codeDraftStatus}\n severityByLine={codeIssueLocations.severityByLine}\n lineByIssueId={codeIssueLocations.lineByIssueId}\n />\n <WorkflowAiDraftDialog\n open={showAiDraft}\n onOpenChange={setShowAiDraft}\n onApply={handleApplyAiDraft}\n canvasHasContent={nodes.length > 0}\n />\n <AnnotationEditDialog\n node={selectedAnnotation}\n isOpen={showAnnotationDialog}\n onClose={() => setShowAnnotationDialog(false)}\n onSave={handleSaveAnnotation}\n onDelete={handleDeleteAnnotation}\n />\n <TemplateGalleryDialog\n open={showTemplateGallery}\n onOpenChange={setShowTemplateGallery}\n onSelect={handleTemplateSelect}\n />\n {/* Clearing the canvas is a yes/no interruption that must block \u2014 a rail\n would make an irreversible action easy to miss. */}\n <ConfirmDialog\n open={showClearConfirm}\n onOpenChange={setShowClearConfirm}\n title={t('workflows.visualEditor.clearTitle')}\n text={t('workflows.visualEditor.clearDescription')}\n confirmText={t('common.clear', 'Clear')}\n cancelText={t('common.cancel', 'Cancel')}\n variant=\"destructive\"\n onConfirm={confirmClear}\n />\n {/* Starting a run is a FORM \u2014 a context payload, saved fixtures and two\n run-mode switches \u2014 authored against the canvas it will execute, so it\n is a rail rather than a modal that hides the graph. */}\n <Drawer open={startOpen} onOpenChange={setStartOpen}>\n <DrawerContent\n data-testid=\"workflow-start-instance-drawer\"\n closeAriaLabel={t('workflows.startInstance.close')}\n onKeyDown={(event) => {\n if (!(event.metaKey || event.ctrlKey) || event.key !== 'Enter') return\n event.preventDefault()\n event.stopPropagation()\n if (starting) return\n void handleStartInstance()\n }}\n >\n <DrawerHeader>\n <DrawerTitle>{t('workflows.startInstance.title')}</DrawerTitle>\n <DrawerDescription>{t('workflows.startInstance.description')}</DrawerDescription>\n </DrawerHeader>\n <DrawerBody className=\"space-y-3 py-2\">\n\n {startFixtureList.length > 0 ? (\n <div className=\"space-y-1\">\n <span className=\"text-overline text-muted-foreground\">{t('workflows.fixtures.label')}</span>\n <div className=\"flex flex-wrap gap-1\">\n {startFixtureList.map((fixture) => (\n <span key={fixture.name} className=\"inline-flex items-center gap-1 rounded-md border border-border bg-muted px-2 py-1\">\n <button\n type=\"button\"\n className=\"text-xs font-medium hover:underline\"\n onClick={() => handleApplyFixture(fixture.name)}\n >\n {fixture.name}\n </button>\n <button\n type=\"button\"\n className=\"text-xs text-muted-foreground hover:text-foreground\"\n aria-label={t('workflows.fixtures.delete', { name: fixture.name })}\n onClick={() => handleDeleteFixture(fixture.name)}\n >\n &times;\n </button>\n </span>\n ))}\n </div>\n </div>\n ) : null}\n\n <label className=\"text-sm font-medium\" htmlFor=\"workflow-start-context\">\n {t('workflows.startInstance.contextLabel')}\n </label>\n <Textarea\n id=\"workflow-start-context\"\n value={startContext}\n onChange={(e) => setStartContext(e.target.value)}\n rows={9}\n spellCheck={false}\n className=\"font-mono text-sm\"\n />\n\n <div className=\"flex items-end gap-2\">\n <div className=\"flex-1 space-y-1\">\n <Label htmlFor=\"workflow-fixture-name\" className=\"text-xs\">\n {t('workflows.fixtures.nameLabel')}\n </Label>\n <Input\n id=\"workflow-fixture-name\"\n value={fixtureName}\n onChange={(e) => setFixtureName(e.target.value)}\n placeholder={t('workflows.fixtures.namePlaceholder')}\n />\n </div>\n <Button variant=\"outline\" onClick={handleSaveFixture} disabled={!fixtureName.trim()}>\n {t('workflows.fixtures.save')}\n </Button>\n </div>\n <p className=\"text-xs text-muted-foreground\">{t('workflows.fixtures.storageWarning')}</p>\n\n <div className=\"space-y-2 rounded-md border border-border p-2\">\n <div className=\"flex items-center justify-between gap-2\">\n <Label htmlFor=\"workflow-start-dry-run\" className=\"text-sm font-medium\">\n {t('workflows.startInstance.dryRunLabel')}\n </Label>\n <Switch\n id=\"workflow-start-dry-run\"\n checked={startDryRun}\n onCheckedChange={(checked) => setStartDryRun(checked === true)}\n />\n </div>\n <p className=\"text-xs text-muted-foreground\">{t('workflows.startInstance.dryRunHint')}</p>\n <div className=\"flex items-center justify-between gap-2\">\n <Label htmlFor=\"workflow-start-step-through\" className=\"text-sm font-medium\">\n {t('workflows.startInstance.stepThroughLabel')}\n </Label>\n <Switch\n id=\"workflow-start-step-through\"\n checked={startStepThrough}\n onCheckedChange={(checked) => setStartStepThrough(checked === true)}\n />\n </div>\n <p className=\"text-xs text-muted-foreground\">{t('workflows.startInstance.stepThroughHint')}</p>\n </div>\n </DrawerBody>\n <DrawerFooter>\n <Button variant=\"outline\" onClick={() => setStartOpen(false)} disabled={starting}>\n {t('workflows.startInstance.cancel')}\n </Button>\n <Button onClick={() => void handleStartInstance()} disabled={starting}>\n {starting ? <Spinner className=\"h-4 w-4\" /> : t('workflows.startInstance.start')}\n </Button>\n </DrawerFooter>\n </DrawerContent>\n </Drawer>\n </>\n )\n\n const structuralConflictBanner = structuralConflict ? (\n <div className=\"shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3\">\n <Alert variant=\"warning\">\n <AlertTitle>\n {t('workflows.visualEditor.editSafety.bannerTitle', 'This change needs a new version')}\n </AlertTitle>\n <AlertDescription>\n {t(\n 'workflows.visualEditor.editSafety.bannerDescription',\n '{count} instance(s) are still running on this version. Changing the steps or routes would re-point them mid-flight, so the change is saved to a new version instead.',\n { count: String(structuralConflict.activeInstanceCount) },\n )}\n </AlertDescription>\n <div className=\"mt-2 flex flex-wrap gap-2\">\n <Button size=\"sm\" onClick={handleCreateVersion} disabled={isCreatingVersion} className=\"h-8 text-xs\">\n {t('workflows.visualEditor.editSafety.createVersion', 'Create version')}\n </Button>\n <Button\n size=\"sm\"\n variant=\"outline\"\n onClick={() => setStructuralConflict(null)}\n disabled={isCreatingVersion}\n className=\"h-8 text-xs\"\n >\n {t('workflows.visualEditor.editSafety.keepEditing', 'Keep editing')}\n </Button>\n </div>\n </Alert>\n </div>\n ) : null\n\n const draftRestoreBanner = pendingDraft ? (\n <div className=\"shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3\">\n <Alert variant=\"info\">\n <AlertTitle>\n {t('workflows.visualEditor.draft.bannerTitle', 'You have an unsaved draft from {time}', {\n time: formatRelativeTime(pendingDraft.draft.updatedAt, { translate: t }) ?? '',\n })}\n </AlertTitle>\n {pendingDraft.baseMismatch && (\n <AlertDescription>\n {t('workflows.visualEditor.draft.bannerConflict', 'The workflow definition has changed since this draft was made. Restoring will apply your draft over the newer version.')}\n </AlertDescription>\n )}\n <div className=\"mt-2 flex flex-wrap gap-2\">\n <Button size=\"sm\" onClick={handleRestoreDraft} className=\"h-8 text-xs\">\n {t('workflows.visualEditor.draft.restore', 'Restore draft')}\n </Button>\n <Button size=\"sm\" variant=\"outline\" onClick={handleDiscardDraft} className=\"h-8 text-xs\">\n {t('workflows.visualEditor.draft.discard', 'Discard')}\n </Button>\n </div>\n </Alert>\n </div>\n ) : null\n\n const { errors: problemErrorCount, warnings: problemWarningCount } = countIssuesBySeverity(problems)\n\n const problemsPanel = showProblems && problems.length > 0 ? (\n <div className=\"shrink-0 border-t border-border bg-background px-3 py-2 md:px-6 md:py-3\">\n <div className={`rounded-lg border bg-card ${problemErrorCount > 0 ? 'border-status-error-border' : 'border-status-warning-border'}`}>\n <div className=\"flex items-center justify-between gap-2 px-3 py-2\">\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => setProblemsCollapsed((collapsed) => !collapsed)}\n aria-expanded={!problemsCollapsed}\n className=\"h-auto gap-2 p-0 text-sm font-semibold text-foreground hover:bg-transparent\"\n >\n {problemsCollapsed ? <ChevronRight className=\"h-4 w-4\" aria-hidden=\"true\" /> : <ChevronDown className=\"h-4 w-4\" aria-hidden=\"true\" />}\n {t('workflows.visualEditor.problems.title', 'Problems')}\n <span className=\"text-xs font-normal text-muted-foreground\">\n {t('workflows.visualEditor.problems.counts', '{errors} error(s) \u00B7 {warnings} warning(s)', { errors: problemErrorCount, warnings: problemWarningCount })}\n </span>\n </Button>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => setShowProblems(false)}\n aria-label={t('workflows.visualEditor.problems.dismiss', 'Dismiss problems')}\n className=\"h-7 w-7 p-0\"\n >\n <X className=\"h-4 w-4\" aria-hidden=\"true\" />\n </Button>\n </div>\n {!problemsCollapsed && (\n <ul className=\"max-h-56 overflow-y-auto border-t border-border\">\n {problems.map((issue) => {\n const isNavigable = Boolean(issue.nodeId || issue.edgeId)\n return (\n <li key={issue.id}>\n <Button\n variant=\"ghost\"\n onClick={() => handleProblemClick(issue)}\n disabled={!isNavigable}\n className={`flex h-auto w-full items-start justify-start gap-2 rounded-none px-3 py-1.5 text-left text-sm font-normal ${isNavigable ? 'hover:bg-muted' : 'cursor-default hover:bg-transparent'}`}\n >\n {issue.severity === 'error' ? (\n <CircleAlert className=\"mt-0.5 h-4 w-4 shrink-0 text-status-error-text\" aria-hidden=\"true\" />\n ) : (\n <TriangleAlert className=\"mt-0.5 h-4 w-4 shrink-0 text-status-warning-text\" aria-hidden=\"true\" />\n )}\n <span className=\"min-w-0 flex-1 text-foreground\">{issue.message}</span>\n {issue.nodeLabel && (\n <span className=\"shrink-0 text-xs text-muted-foreground\">{issue.nodeLabel}</span>\n )}\n </Button>\n </li>\n )\n })}\n </ul>\n )}\n </div>\n </div>\n ) : null\n\n if (isMobile) {\n return (\n <Page className=\"flex h-[100svh] flex-col space-y-0 overflow-hidden\">\n {structuralConflictBanner}\n {draftRestoreBanner}\n <MobileVisualEditor\n definitionId={definitionId}\n isSaving={isSaving}\n nodes={nodes}\n edges={edges}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onNodeClick={handleNodeClick}\n onEdgeClick={handleEdgeClick}\n onConnect={handleConnect}\n onReconnect={handleReconnect}\n onAddNode={handleAddNode}\n onSave={handleSave}\n onValidate={handleValidate}\n onStartInstance={() => setStartOpen(true)}\n onLoadExample={handleOpenTemplateGallery}\n onClear={handleClear}\n metadata={metadata}\n onMetadataOpenChange={handleMetadataOpenChange}\n />\n {sharedDialogs}\n {ConfirmDialogElement}\n </Page>\n )\n }\n\n // Break the editor out of `main`'s centered `max-w-screen-2xl` so the canvas\n // uses the full content column on wide screens (the side gutters the author\n // saw). Width = the content column (viewport minus the sidebar offset exposed\n // by AppShell); the negative margins cancel `main`'s auto-centering\n // (`max(0, (col-1536)/2)`) and its `lg:p-6` padding (24px). Desktop-only \u2014 the\n // compact (<1280px) layout keeps the normal centered container.\n const fullBleedSideMargin =\n 'calc(-1 * (max(0px, (100vw - var(--app-content-offset, 0px) - 1536px) / 2) + 24px))'\n const fullBleedStyle: React.CSSProperties = !isCompactViewport\n ? {\n width: 'calc(100vw - var(--app-content-offset, 0px))',\n marginLeft: fullBleedSideMargin,\n marginRight: fullBleedSideMargin,\n }\n : {}\n\n return (\n <Page\n className=\"flex min-h-[calc(100svh-7rem)] flex-col space-y-0 overflow-x-hidden\"\n style={fullBleedStyle}\n >\n {/* Page Header */}\n <div className={`shrink-0 border-b border-border bg-background ${focusMode ? 'px-3 py-1.5 md:px-4' : 'px-3 py-2 md:px-6 md:py-3'}`}>\n <FormHeader\n mode=\"detail\"\n backHref=\"/backend/definitions\"\n backLabel={t('workflows.definitions.backToList', 'Back to definitions')}\n title={definitionId ? (workflowName || t('workflows.definitions.singular')) : t('workflows.backend.definitions.visual_editor.title')}\n subtitle={focusMode\n ? undefined\n : definitionId\n ? t('workflows.definitions.detail.summary', 'Editing workflow definition')\n : t('workflows.definitions.create.summary', 'Create and edit workflow definitions visually with a drag-and-drop interface')\n }\n actionsContent={\n <div className=\"flex flex-wrap items-center justify-end gap-1 md:gap-2\">\n {draftEligible && (draftSaveFailed || draftSavedLabel) && (\n <span role=\"status\" className=\"text-xs text-muted-foreground\">\n {draftSaveFailed\n ? t('workflows.visualEditor.draft.saveFailed', 'Draft not saved')\n : t('workflows.visualEditor.draft.saved', 'Draft saved {time}', { time: draftSavedLabel ?? '' })}\n </span>\n )}\n {!isCodeOnly && definitionId && autosaveState !== 'idle' && (\n <span className=\"mr-1 text-xs text-muted-foreground\" aria-live=\"polite\">\n {autosaveState === 'saving' ? t('workflows.visualEditor.autosaving') : t('workflows.visualEditor.autosaved')}\n </span>\n )}\n {focusMode ? (\n // Focus mode collapses the toolbar to the essentials; the toggle\n // stays reachable so the author can leave, and Cmd+K still opens\n // every command.\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={toggleFocus}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs\"\n aria-label={t('workflows.visualEditor.exitFocusMode')}\n >\n <Minimize2 className=\"mr-1.5 h-4 w-4\" />\n {t('workflows.visualEditor.exitFocusMode')}\n </Button>\n ) : (\n <>\n {/* Validate \u2014 surfaces the last Problems pass's error count so the\n author sees \"3 errors\" without opening the panel; icon + count,\n never colour alone (spec \u00A74.6). */}\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={handleValidate}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs\"\n aria-label={problemErrorCount > 0\n ? t('workflows.visualEditor.validateWithErrors', '{count} validation errors', { count: problemErrorCount })\n : t('workflows.visualEditor.validate')}\n >\n {problemErrorCount > 0 ? (\n <CircleAlert className=\"mr-1.5 h-4 w-4 text-destructive\" aria-hidden=\"true\" />\n ) : (\n <CircleQuestionMark className=\"mr-1.5 h-4 w-4\" aria-hidden=\"true\" />\n )}\n {t('workflows.visualEditor.validate')}\n {problemErrorCount > 0 && (\n <span className=\"ml-1.5 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-xs font-semibold text-white\">\n {problemErrorCount}\n </span>\n )}\n </Button>\n {/* One grouped overflow keeps only the essentials \u2014 Validate,\n Start instance, Update \u2014 in the row. The metadata-incomplete\n warning rides the trigger (attention dot) and the Settings\n item, so hiding Settings here never buries it. */}\n {(() => {\n const moreActions: ActionMenuEntry[] = []\n moreActions.push({ id: 'group-tools', header: t('workflows.visualEditor.menuGroups.tools', 'Tools') })\n moreActions.push({ id: 'commands', label: t('workflows.commandPalette.buttonLabel', 'Commands'), icon: Command, onSelect: () => setShowCommandPalette(true) })\n if (!isCodeOnly) moreActions.push({ id: 'ai-draft', label: t('workflows.aiDraft.toggleShort', 'AI draft'), icon: Sparkles, onSelect: () => setShowAiDraft(true) })\n moreActions.push({ id: 'group-view', header: t('workflows.visualEditor.menuGroups.view', 'View') })\n moreActions.push({ id: 'focus', label: t('workflows.visualEditor.enterFocusMode'), icon: Maximize2, onSelect: toggleFocus, disabled: isSaving })\n moreActions.push({ id: 'settings', label: t('workflows.visualEditor.metadata.buttonLabel', 'Settings'), icon: metadataIncomplete ? TriangleAlert : PanelRightOpen, onSelect: () => setMetadataOpen(true), disabled: isSaving })\n moreActions.push({ id: 'code', label: t('workflows.visualEditor.codeView.title', 'Code'), icon: Code, onSelect: () => setShowCodeView(true) })\n moreActions.push({ id: 'group-canvas', header: t('workflows.visualEditor.menuGroups.canvas', 'Canvas') })\n if (!isCodeOnly) moreActions.push({ id: 'load-example', label: t('workflows.visualEditor.loadExample'), onSelect: handleOpenTemplateGallery, disabled: isSaving })\n if (!isCodeOnly) moreActions.push({ id: 'auto-arrange', label: t('workflows.visualEditor.autoArrange'), icon: Network, onSelect: handleAutoArrange, disabled: isSaving || nodes.length === 0 })\n moreActions.push({ id: 'compensation', label: t('workflows.compensation.toggleShort', 'Compensation'), icon: ShieldMinus, onSelect: toggleCompensation })\n if (isCodeOverride) moreActions.push({ id: 'reset-to-code', label: t('workflows.actions.resetToCode'), onSelect: handleResetToCode, disabled: isSaving })\n if (!isCodeOnly) {\n moreActions.push({ separator: true, id: 'sep-destructive' })\n moreActions.push({ id: 'clear', label: t('workflows.visualEditor.clear'), icon: Trash2, onSelect: handleClear, disabled: isSaving, destructive: true })\n }\n return (\n <ActionsDropdown\n items={moreActions}\n label={t('workflows.visualEditor.more', 'More')}\n ariaLabel={t('workflows.visualEditor.more', 'More')}\n triggerClassName=\"h-8 px-2 text-xs\"\n triggerIcon={false}\n attention={metadataIncomplete}\n />\n )\n })()}\n {/* Execution overlay (spec \u00A78.3): \"Show last run\" paints node\n states with DS status tokens and the taken path. It stays a\n toolbar button rather than joining the More menu because it\n is a STATEFUL toggle with something to report: a menu entry\n can neither announce `aria-pressed` nor keep the \"(never\n run)\" caption visible once the menu closes, and \u00A78.3 requires\n a definition that has never run to say so. Read-only \u2014\n derived at render time, never part of the document. */}\n {definitionId && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={toggleLastRun}\n aria-pressed={showLastRun}\n className=\"h-8 px-2 text-xs\"\n aria-label={t('workflows.lastRun.toggle', 'Show the last run on the canvas')}\n >\n <History className=\"mr-1.5 h-4 w-4\" aria-hidden=\"true\" />\n {t('workflows.lastRun.toggleShort', 'Last run')}\n {showLastRun && lastRunOverlay.isUnavailable ? (\n <span className=\"ml-1.5 text-muted-foreground\">\n {t('workflows.lastRun.never', '(never run)')}\n </span>\n ) : null}\n </Button>\n )}\n {definitionId && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setStartOpen(true)}\n disabled={isSaving}\n className=\"h-8 text-xs\"\n >\n <Play className=\"mr-1.5 h-4 w-4\" />\n {t('workflows.actions.startInstance')}\n </Button>\n )}\n </>\n )}\n {isCodeOnly ? (\n <Button\n size=\"sm\"\n onClick={handleCustomize}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs md:px-3\"\n >\n {t('workflows.actions.customize')}\n </Button>\n ) : (\n <Button\n size=\"sm\"\n onClick={handleSave}\n disabled={isSaving}\n className=\"h-8 px-2 text-xs md:px-3\"\n aria-label={isSaving ? t('workflows.mobile.saving') : definitionId ? t('workflows.common.update') : t('workflows.common.save')}\n >\n <Save className=\"mr-1.5 h-4 w-4\" />\n {isSaving ? t('workflows.mobile.saving') : definitionId ? t('workflows.common.update') : t('workflows.common.save')}\n </Button>\n )}\n </div>\n }\n />\n </div>\n\n {/* Source banner (code-defined / customized) */}\n {(isCodeOnly || isCodeOverride) && (\n <div className=\"shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3\">\n {isCodeOnly && (\n <Alert status=\"information\">\n <AlertTitle>{t('workflows.source.code.readonlyBanner')}</AlertTitle>\n </Alert>\n )}\n {isCodeOverride && (\n <Alert status=\"warning\">\n <AlertTitle>{t('workflows.source.code_override.banner')}</AlertTitle>\n </Alert>\n )}\n </div>\n )}\n\n {/* Edit-safety rule: structural change refused while instances run (spec \u00A74.1) */}\n {structuralConflictBanner}\n\n {/* Per-user draft restore banner (spec \u00A74.7) */}\n {draftRestoreBanner}\n\n {/* Main Content */}\n {isCompactViewport ? (\n <div className=\"px-3 py-3 md:px-6 md:py-4\">\n <div className=\"relative min-w-0\">\n <div className=\"h-[64svh] min-h-[360px] rounded-lg border bg-card\">\n <WorkflowGraph\n initialNodes={nodes}\n initialEdges={edges}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onNodeClick={handleNodeClick}\n onEdgeClick={handleEdgeClick}\n onConnect={handleConnect}\n onReconnect={handleReconnect}\n onCanvasDrop={handleCanvasDrop}\n editable={!isCodeOnly}\n height=\"100%\"\n focusTarget={focusTarget}\n nodeErrorCounts={nodeErrorCounts}\n showCompensation={showCompensation}\n runOverlay={lastRunOverlay.execution}\n runAgentLabels={lastRunOverlay.agentLabels}\n triggers={triggers}\n definitionEnabled={enabled}\n onOpenTriggers={handleOpenTriggers}\n />\n </div>\n\n {nodes.length === 0 && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center px-4\">\n <div className=\"text-center\">\n <h2 className=\"mb-2 text-lg font-semibold text-foreground\">{t('workflows.visualEditor.startBuilding')}</h2>\n <p className=\"mb-4 text-sm text-muted-foreground\">{t('workflows.visualEditor.tapToAddBelow')}</p>\n <button\n onClick={handleOpenTemplateGallery}\n className=\"pointer-events-auto text-sm text-primary hover:underline\"\n >\n {t('workflows.visualEditor.loadExampleWorkflow')}\n </button>\n </div>\n </div>\n )}\n </div>\n\n {!isCodeOnly && (\n <div className=\"mt-3 rounded-lg border bg-card p-3\">\n <h2 className=\"mb-2 text-xs font-semibold uppercase text-muted-foreground\">{t('workflows.visualEditor.stepPalette')}</h2>\n <p className=\"mb-3 text-xs text-muted-foreground\">{t('workflows.visualEditor.tapToAdd')}</p>\n\n <div className=\"flex gap-2 overflow-x-auto pb-1\">\n {(['start', 'userTask', 'automated', 'invokeAgent', 'waitForSignal', 'waitForTimer', 'subWorkflow', 'end'] as const).map((nodeType) => {\n const Icon = NODE_TYPE_ICONS[nodeType]\n return (\n <button\n key={nodeType}\n draggable\n onDragStart={(event) => handlePaletteStepDragStart(event, nodeType)}\n onClick={() => handleAddNode(nodeType)}\n className=\"flex shrink-0 items-center gap-1 rounded-md border bg-background px-2 py-1 text-xs hover:bg-muted active:bg-muted/50\"\n >\n <Icon className=\"h-3.5 w-3.5\" />\n <span>{NODE_TYPE_LABELS[nodeType].title}</span>\n </button>\n )\n })}\n </div>\n </div>\n )}\n </div>\n ) : (\n <div data-testid=\"workflow-editor-row\" className=\"flex min-h-0 min-w-0 flex-1 border-t border-border pl-3 md:pl-6\">\n {/* Left Sidebar - Step Palette rail (hidden in read-only mode) */}\n {!isCodeOnly && (\n <div className={`${paletteCollapsed ? 'w-14' : 'w-48'} shrink-0 overflow-y-auto border-r border-border bg-background p-2`}>\n <div className={`mb-2 flex items-center ${paletteCollapsed ? 'justify-center' : 'justify-between'}`}>\n {!paletteCollapsed && (\n <h2 className=\"px-1 text-xs font-semibold uppercase text-muted-foreground\">{t('workflows.visualEditor.stepPalette')}</h2>\n )}\n <IconButton\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n onClick={togglePaletteCollapsed}\n title={paletteCollapsed ? t('workflows.visualEditor.expandPalette') : t('workflows.visualEditor.collapsePalette')}\n aria-label={paletteCollapsed ? t('workflows.visualEditor.expandPalette') : t('workflows.visualEditor.collapsePalette')}\n >\n {paletteCollapsed ? <PanelLeftOpen className=\"h-4 w-4\" /> : <PanelLeftClose className=\"h-4 w-4\" />}\n </IconButton>\n </div>\n\n {!paletteCollapsed && (\n <p className=\"mb-2 px-1 text-xs text-muted-foreground\">{t('workflows.visualEditor.clickToAdd')}</p>\n )}\n\n <div className={`flex flex-col gap-1 ${paletteCollapsed ? 'items-center' : ''}`}>\n {PALETTE_NODE_TYPES.map((nodeType) => {\n const Icon = NODE_TYPE_ICONS[nodeType]\n const label = NODE_TYPE_LABELS[nodeType]\n const tooltip = `${label.title} \u2014 ${label.description}`\n if (paletteCollapsed) {\n return (\n <button\n key={nodeType}\n type=\"button\"\n draggable\n onDragStart={(event) => handlePaletteStepDragStart(event, nodeType)}\n onClick={() => handleAddNode(nodeType)}\n title={tooltip}\n aria-label={tooltip}\n className=\"flex h-9 w-9 items-center justify-center rounded-md border hover:bg-muted\"\n >\n <Icon className={`h-4 w-4 ${NODE_TYPE_COLORS[nodeType]}`} />\n </button>\n )\n }\n return (\n <button\n key={nodeType}\n type=\"button\"\n draggable\n onDragStart={(event) => handlePaletteStepDragStart(event, nodeType)}\n onClick={() => handleAddNode(nodeType)}\n title={label.description}\n className=\"flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left text-xs hover:bg-muted\"\n >\n <Icon className={`h-4 w-4 shrink-0 ${NODE_TYPE_COLORS[nodeType]}`} />\n <span className=\"truncate font-medium text-foreground\">{label.title}</span>\n </button>\n )\n })}\n </div>\n\n {/* Actions (spec \u00A74.4): drag one onto a route to append it to that\n route's activities \u2014 the chips (#4244) then render it. Clicking\n explains where the keyboard path is, so the entry is never dead. */}\n {!paletteCollapsed && (\n <div className=\"mt-4\">\n <h2 className=\"mb-1 px-1 text-xs font-semibold uppercase text-muted-foreground\">\n {t('workflows.visualEditor.palette.actionsTitle', 'Actions')}\n </h2>\n <p className=\"mb-2 px-1 text-xs text-muted-foreground\">\n {t('workflows.visualEditor.palette.dragActionHint', 'Drop an action onto a route to add it there')}\n </p>\n <div className=\"flex flex-col gap-1\">\n {activityTypeOptions.map((option) => {\n const ActionIcon = resolveActivityIcon(option.value)\n return (\n <button\n key={option.value}\n type=\"button\"\n draggable\n onDragStart={(event) => handlePaletteActivityDragStart(event, option.value, option.label)}\n onClick={() => flash(t('workflows.visualEditor.palette.dragActionHint', 'Drop an action onto a route to add it there'), 'info')}\n title={t('workflows.visualEditor.palette.dragActionHint', 'Drop an action onto a route to add it there')}\n className=\"flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left text-xs hover:bg-muted\"\n >\n <ActionIcon className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n <span className=\"truncate font-medium text-foreground\">{option.label}</span>\n </button>\n )\n })}\n </div>\n </div>\n )}\n\n {/* Annotations (spec \u00A74.5): documentation only \u2014 filtered out of the\n saved definition, so they can never change what the engine runs. */}\n {!paletteCollapsed && (\n <div className=\"mt-4\">\n <h2 className=\"mb-1 px-1 text-xs font-semibold uppercase text-muted-foreground\">\n {t('workflows.annotations.paletteTitle', 'Annotations')}\n </h2>\n <p className=\"mb-2 px-1 text-xs text-muted-foreground\">\n {t('workflows.annotations.paletteHint', 'Documentation only \u2014 never executed')}\n </p>\n <div className=\"flex flex-col gap-1\">\n <button\n type=\"button\"\n onClick={() => handleAddAnnotation('note')}\n title={t('workflows.annotations.note.addHint', 'Add a markdown sticky note to the canvas')}\n className=\"flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left text-xs hover:bg-muted\"\n >\n <StickyNote className=\"h-4 w-4 shrink-0 text-status-warning-text\" aria-hidden=\"true\" />\n <span className=\"truncate font-medium text-foreground\">{t('workflows.annotations.note.add', 'Note')}</span>\n </button>\n <button\n type=\"button\"\n onClick={() => handleAddAnnotation('group')}\n title={t('workflows.annotations.group.addHint', 'Add a named region around part of the canvas')}\n className=\"flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left text-xs hover:bg-muted\"\n >\n <Group className=\"h-4 w-4 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n <span className=\"truncate font-medium text-foreground\">{t('workflows.annotations.group.add', 'Group')}</span>\n </button>\n </div>\n </div>\n )}\n\n {!paletteCollapsed && (\n <div className=\"mt-3\">\n <button\n type=\"button\"\n onClick={() => setShowPaletteHowTo((prev) => !prev)}\n aria-expanded={showPaletteHowTo}\n className=\"flex w-full items-center gap-1.5 rounded-md px-1 py-1 text-xs text-muted-foreground hover:text-foreground\"\n >\n <CircleQuestionMark className=\"h-3.5 w-3.5\" />\n <span>{t('workflows.visualEditor.howToUse', 'How to use:')}</span>\n </button>\n {showPaletteHowTo && (\n <Alert variant=\"info\" className=\"mt-2\">\n <AlertTitle className=\"text-xs\">{t('workflows.visualEditor.howToUse', 'How to use:')}</AlertTitle>\n <div className=\"mt-2\">\n <ul className=\"list-inside list-disc space-y-1 text-xs\">\n <li>{t('workflows.visualEditor.hint.addSteps', 'Click step types to add them')}</li>\n <li>{t('workflows.visualEditor.hint.dragFromPalette', 'Drag a step onto the canvas, or onto a route to insert it there')}</li>\n <li>{t('workflows.visualEditor.hint.dragSteps', 'Drag steps to position them')}</li>\n <li>{t('workflows.visualEditor.hint.connectSteps', 'Connect steps by dragging from handles')}</li>\n <li>{t('workflows.visualEditor.hint.editSteps', 'Click steps and transitions to edit them')}</li>\n <li>{t('workflows.visualEditor.hint.copyPaste', 'Select steps and copy, paste or duplicate them with Cmd/Ctrl+C, +V and +D')}</li>\n <li>{t('workflows.visualEditor.hint.commandPalette', 'Press Cmd/Ctrl+K for every command without the mouse')}</li>\n <li>{t('workflows.visualEditor.hint.keyboardCanvas', 'With a step selected: Enter opens it, Del removes it, arrows nudge it (hold Shift for bigger steps)')}</li>\n <li>{t('workflows.visualEditor.hint.validate', 'Validate before saving')}</li>\n </ul>\n </div>\n </Alert>\n )}\n </div>\n )}\n </div>\n )}\n\n {/* Main Canvas \u2014 the header already carries the Focus toggle, so no\n separate in-canvas Exit-focus button (avoids two identical controls). */}\n <div className=\"min-w-0 flex-1 p-6\">\n <div className=\"relative h-full min-h-[480px]\">\n <div className=\"h-full rounded-lg border bg-card\">\n <WorkflowGraph\n initialNodes={nodes}\n initialEdges={edges}\n onNodesChange={handleNodesChange}\n onEdgesChange={handleEdgesChange}\n onNodeClick={handleNodeClick}\n onEdgeClick={handleEdgeClick}\n onConnect={handleConnect}\n onReconnect={handleReconnect}\n onCanvasDrop={handleCanvasDrop}\n editable={!isCodeOnly}\n height=\"100%\"\n focusTarget={focusTarget}\n nodeErrorCounts={nodeErrorCounts}\n showCompensation={showCompensation}\n runOverlay={lastRunOverlay.execution}\n runAgentLabels={lastRunOverlay.agentLabels}\n triggers={triggers}\n definitionEnabled={enabled}\n onOpenTriggers={handleOpenTriggers}\n />\n </div>\n\n {/* Empty State */}\n {nodes.length === 0 && (\n <div className=\"pointer-events-none absolute inset-0 flex items-center justify-center px-4\">\n <div className=\"text-center\">\n <h2 className=\"mb-2 text-xl font-semibold text-foreground\">\n {t('workflows.visualEditor.startBuilding')}\n </h2>\n <p className=\"mb-4 text-muted-foreground\">\n {t('workflows.visualEditor.clickToAddFromPalette')}\n </p>\n <button\n onClick={handleOpenTemplateGallery}\n className=\"pointer-events-auto text-sm text-primary hover:underline\"\n >\n {t('workflows.visualEditor.loadExampleWorkflow')}\n </button>\n </div>\n </div>\n )}\n </div>\n </div>\n\n {/* Docked step / route inspector (spec \u00A74.1). It is a sibling of the\n canvas, not an overlay on it, so opening it narrows the graph and\n leaves it visible and clickable. */}\n {inspectorsDocked ? inspectorPanels : null}\n </div>\n )}\n {problemsPanel}\n {sharedDialogs}\n {ConfirmDialogElement}\n </Page>\n )\n}\n\n// Helper functions\nfunction getDefaultLabel(nodeType: string): string {\n const labels: Record<string, string> = {\n start: 'Start',\n end: 'End',\n userTask: 'New User Task',\n automated: 'New Automated Task',\n decision: 'Decision Point',\n waitForSignal: 'Wait for Signal',\n waitForTimer: 'Wait for Timer',\n waitForCondition: 'Wait for Condition',\n invokeAgent: 'Invoke Agent',\n ifElse: 'If / Else',\n switch: 'Switch',\n }\n return labels[nodeType] || 'New Step'\n}\n\nfunction getDefaultBadge(nodeType: string): string {\n const badges: Record<string, string> = {\n start: 'Start',\n end: 'End',\n userTask: 'User Task',\n automated: 'Automated',\n decision: 'Decision',\n waitForSignal: 'Wait for Signal',\n waitForTimer: 'Wait for Timer',\n waitForCondition: 'Wait for Condition',\n invokeAgent: 'Invoke Agent',\n ifElse: 'If / Else',\n switch: 'Switch',\n }\n return badges[nodeType] || 'Task'\n}\n"],
5
+ "mappings": ";AAoyFQ,SA0BJ,UA1BI,KA0BJ,YA1BI;AAlyFR,S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