@antelopejs/dms-automation 0.2.7 → 0.3.1

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 (312) hide show
  1. package/README.md +46 -2
  2. package/dist/data/procedures-table.d.ts +38 -4
  3. package/dist/data/procedures-table.js +264 -82
  4. package/dist/data/procedures-table.js.map +1 -1
  5. package/dist/data/runs-table.d.ts +19 -3
  6. package/dist/data/runs-table.js +254 -19
  7. package/dist/data/runs-table.js.map +1 -1
  8. package/dist/db/index.d.ts +1 -2
  9. package/dist/db/index.js +1 -2
  10. package/dist/db/index.js.map +1 -1
  11. package/dist/db/models/automation_template.model.d.ts +16 -1
  12. package/dist/db/models/automation_template.model.js +31 -11
  13. package/dist/db/models/automation_template.model.js.map +1 -1
  14. package/dist/db/models/index.d.ts +1 -1
  15. package/dist/db/models/index.js +1 -1
  16. package/dist/db/models/procedure.model.d.ts +1 -0
  17. package/dist/db/models/procedure.model.js +7 -0
  18. package/dist/db/models/procedure.model.js.map +1 -1
  19. package/dist/db/models/procedure_run.model.d.ts +16 -9
  20. package/dist/db/models/procedure_run.model.js +96 -17
  21. package/dist/db/models/procedure_run.model.js.map +1 -1
  22. package/dist/db/models/stats.model.d.ts +60 -61
  23. package/dist/db/models/stats.model.js +189 -236
  24. package/dist/db/models/stats.model.js.map +1 -1
  25. package/dist/db/models/type_switch.model.d.ts +25 -0
  26. package/dist/db/models/type_switch.model.js +25 -0
  27. package/dist/db/models/type_switch.model.js.map +1 -0
  28. package/dist/db/tables/index.d.ts +1 -2
  29. package/dist/db/tables/index.js +1 -2
  30. package/dist/db/tables/index.js.map +1 -1
  31. package/dist/db/tables/procedure.table.d.ts +6 -0
  32. package/dist/db/tables/procedure.table.js +24 -0
  33. package/dist/db/tables/procedure.table.js.map +1 -1
  34. package/dist/db/tables/procedure_run.table.d.ts +15 -1
  35. package/dist/db/tables/procedure_run.table.js +54 -0
  36. package/dist/db/tables/procedure_run.table.js.map +1 -1
  37. package/dist/db/tables/type_switch.table.d.ts +8 -0
  38. package/dist/db/tables/{trigger_type_config.table.js → type_switch.table.js} +16 -15
  39. package/dist/db/tables/type_switch.table.js.map +1 -0
  40. package/dist/displays/index.d.ts +14 -0
  41. package/dist/displays/index.js +23 -0
  42. package/dist/displays/index.js.map +1 -0
  43. package/dist/index.d.ts +7 -0
  44. package/dist/index.js +8 -0
  45. package/dist/index.js.map +1 -1
  46. package/dist/pages/builder.d.ts +1 -1
  47. package/dist/pages/builder.js +10 -3
  48. package/dist/pages/builder.js.map +1 -1
  49. package/dist/pages/index.d.ts +2 -1
  50. package/dist/pages/index.js +2 -1
  51. package/dist/pages/index.js.map +1 -1
  52. package/dist/pages/library.d.ts +2 -1
  53. package/dist/pages/library.js +54 -4
  54. package/dist/pages/library.js.map +1 -1
  55. package/dist/pages/overview.d.ts +6 -1
  56. package/dist/pages/overview.js +121 -2
  57. package/dist/pages/overview.js.map +1 -1
  58. package/dist/pages/procedures.js +111 -16
  59. package/dist/pages/procedures.js.map +1 -1
  60. package/dist/pages/runs.d.ts +4 -1
  61. package/dist/pages/runs.js +109 -13
  62. package/dist/pages/runs.js.map +1 -1
  63. package/dist/pages/shared.d.ts +18 -0
  64. package/dist/pages/shared.js +238 -0
  65. package/dist/pages/shared.js.map +1 -0
  66. package/dist/pages/trace.d.ts +10 -0
  67. package/dist/pages/trace.js +41 -0
  68. package/dist/pages/trace.js.map +1 -0
  69. package/dist/realtime.d.ts +3 -0
  70. package/dist/realtime.js +14 -0
  71. package/dist/realtime.js.map +1 -0
  72. package/dist/routes/action-types.d.ts +2 -14
  73. package/dist/routes/action-types.js +2 -32
  74. package/dist/routes/action-types.js.map +1 -1
  75. package/dist/routes/deleteConfirm.d.ts +3 -0
  76. package/dist/routes/deleteConfirm.js +64 -0
  77. package/dist/routes/deleteConfirm.js.map +1 -0
  78. package/dist/routes/graphSchema.d.ts +3 -90
  79. package/dist/routes/graphSchema.js +36 -9
  80. package/dist/routes/graphSchema.js.map +1 -1
  81. package/dist/routes/index.d.ts +1 -0
  82. package/dist/routes/index.js +1 -0
  83. package/dist/routes/index.js.map +1 -1
  84. package/dist/routes/library.d.ts +40 -0
  85. package/dist/routes/library.js +147 -0
  86. package/dist/routes/library.js.map +1 -0
  87. package/dist/routes/procedureChecks.d.ts +16 -0
  88. package/dist/routes/procedureChecks.js +72 -0
  89. package/dist/routes/procedureChecks.js.map +1 -0
  90. package/dist/routes/procedureRuns.d.ts +21 -0
  91. package/dist/routes/procedureRuns.js +45 -0
  92. package/dist/routes/procedureRuns.js.map +1 -0
  93. package/dist/routes/procedureSchemas.d.ts +107 -0
  94. package/dist/routes/procedureSchemas.js +61 -0
  95. package/dist/routes/procedureSchemas.js.map +1 -0
  96. package/dist/routes/procedures.d.ts +125 -7
  97. package/dist/routes/procedures.js +363 -67
  98. package/dist/routes/procedures.js.map +1 -1
  99. package/dist/routes/requests.d.ts +15 -0
  100. package/dist/routes/requests.js +35 -0
  101. package/dist/routes/requests.js.map +1 -0
  102. package/dist/routes/runs.d.ts +107 -2
  103. package/dist/routes/runs.js +340 -37
  104. package/dist/routes/runs.js.map +1 -1
  105. package/dist/routes/stats.d.ts +19 -1
  106. package/dist/routes/stats.js +160 -4
  107. package/dist/routes/stats.js.map +1 -1
  108. package/dist/routes/templates.d.ts +6 -2
  109. package/dist/routes/templates.js +106 -36
  110. package/dist/routes/templates.js.map +1 -1
  111. package/dist/routes/trigger-types.d.ts +2 -15
  112. package/dist/routes/trigger-types.js +2 -32
  113. package/dist/routes/trigger-types.js.map +1 -1
  114. package/dist/routes/typeConfigShared.d.ts +7 -11
  115. package/dist/routes/typeConfigShared.js +25 -15
  116. package/dist/routes/typeConfigShared.js.map +1 -1
  117. package/dist/runtime/armErrors.d.ts +16 -0
  118. package/dist/runtime/armErrors.js +69 -0
  119. package/dist/runtime/armErrors.js.map +1 -0
  120. package/dist/runtime/boundRunLog.d.ts +24 -0
  121. package/dist/runtime/boundRunLog.js +202 -10
  122. package/dist/runtime/boundRunLog.js.map +1 -1
  123. package/dist/runtime/builtins/actions/http.d.ts +10 -1
  124. package/dist/runtime/builtins/actions/http.js +306 -19
  125. package/dist/runtime/builtins/actions/http.js.map +1 -1
  126. package/dist/runtime/builtins/actions/log.js +2 -2
  127. package/dist/runtime/builtins/actions/log.js.map +1 -1
  128. package/dist/runtime/builtins/data/boolean.d.ts +1 -0
  129. package/dist/runtime/builtins/data/boolean.js +18 -10
  130. package/dist/runtime/builtins/data/boolean.js.map +1 -1
  131. package/dist/runtime/builtins/data/compare.js +60 -11
  132. package/dist/runtime/builtins/data/compare.js.map +1 -1
  133. package/dist/runtime/builtins/data/constant.js +9 -12
  134. package/dist/runtime/builtins/data/constant.js.map +1 -1
  135. package/dist/runtime/builtins/data/json.js +4 -4
  136. package/dist/runtime/builtins/data/json.js.map +1 -1
  137. package/dist/runtime/builtins/data/math.js +44 -24
  138. package/dist/runtime/builtins/data/math.js.map +1 -1
  139. package/dist/runtime/builtins/data/object.js +10 -10
  140. package/dist/runtime/builtins/data/object.js.map +1 -1
  141. package/dist/runtime/builtins/data/string.js +31 -20
  142. package/dist/runtime/builtins/data/string.js.map +1 -1
  143. package/dist/runtime/builtins/nodes/action.js +4 -0
  144. package/dist/runtime/builtins/nodes/action.js.map +1 -1
  145. package/dist/runtime/builtins/nodes/delay.js +1 -1
  146. package/dist/runtime/builtins/nodes/delay.js.map +1 -1
  147. package/dist/runtime/builtins/nodes/forRange.d.ts +1 -1
  148. package/dist/runtime/builtins/nodes/forRange.js +10 -4
  149. package/dist/runtime/builtins/nodes/forRange.js.map +1 -1
  150. package/dist/runtime/builtins/nodes/if.js +2 -1
  151. package/dist/runtime/builtins/nodes/if.js.map +1 -1
  152. package/dist/runtime/builtins/nodes/parallel.js +9 -2
  153. package/dist/runtime/builtins/nodes/parallel.js.map +1 -1
  154. package/dist/runtime/builtins/nodes/retry.js +1 -1
  155. package/dist/runtime/builtins/nodes/retry.js.map +1 -1
  156. package/dist/runtime/builtins/nodes/setVariable.js +1 -3
  157. package/dist/runtime/builtins/nodes/setVariable.js.map +1 -1
  158. package/dist/runtime/builtins/triggers/cron.d.ts +3 -0
  159. package/dist/runtime/builtins/triggers/cron.js +21 -7
  160. package/dist/runtime/builtins/triggers/cron.js.map +1 -1
  161. package/dist/runtime/builtins/triggers/manual.js +2 -2
  162. package/dist/runtime/builtins/triggers/manual.js.map +1 -1
  163. package/dist/runtime/builtins/triggers/webhook.d.ts +14 -1
  164. package/dist/runtime/builtins/triggers/webhook.js +116 -30
  165. package/dist/runtime/builtins/triggers/webhook.js.map +1 -1
  166. package/dist/runtime/describe.d.ts +23 -0
  167. package/dist/runtime/describe.js +114 -0
  168. package/dist/runtime/describe.js.map +1 -0
  169. package/dist/runtime/executionResult.d.ts +1 -0
  170. package/dist/runtime/executor.js +82 -5
  171. package/dist/runtime/executor.js.map +1 -1
  172. package/dist/runtime/graphIssues.d.ts +20 -0
  173. package/dist/runtime/graphIssues.js +290 -0
  174. package/dist/runtime/graphIssues.js.map +1 -0
  175. package/dist/runtime/graphVersion.d.ts +2 -0
  176. package/dist/runtime/graphVersion.js +43 -0
  177. package/dist/runtime/graphVersion.js.map +1 -0
  178. package/dist/runtime/nodeKinds.d.ts +4 -4
  179. package/dist/runtime/nodeKinds.js +1 -2
  180. package/dist/runtime/nodeKinds.js.map +1 -1
  181. package/dist/runtime/registry.d.ts +2 -1
  182. package/dist/runtime/registry.js +1 -2
  183. package/dist/runtime/registry.js.map +1 -1
  184. package/dist/runtime/resolveInputs.d.ts +3 -1
  185. package/dist/runtime/resolveInputs.js +12 -2
  186. package/dist/runtime/resolveInputs.js.map +1 -1
  187. package/dist/runtime/resolveSubgraph.d.ts +12 -1
  188. package/dist/runtime/resolveSubgraph.js +36 -0
  189. package/dist/runtime/resolveSubgraph.js.map +1 -1
  190. package/dist/runtime/retention.d.ts +6 -0
  191. package/dist/runtime/retention.js +54 -0
  192. package/dist/runtime/retention.js.map +1 -0
  193. package/dist/runtime/runProcedure.d.ts +12 -0
  194. package/dist/runtime/runProcedure.js +130 -0
  195. package/dist/runtime/runProcedure.js.map +1 -0
  196. package/dist/runtime/schedule.d.ts +2 -0
  197. package/dist/runtime/schedule.js +139 -0
  198. package/dist/runtime/schedule.js.map +1 -0
  199. package/dist/runtime/subscriptions.d.ts +11 -1
  200. package/dist/runtime/subscriptions.js +91 -125
  201. package/dist/runtime/subscriptions.js.map +1 -1
  202. package/dist/runtime/subwalk.js +2 -3
  203. package/dist/runtime/subwalk.js.map +1 -1
  204. package/dist/runtime/templateUsages.d.ts +4 -0
  205. package/dist/runtime/templateUsages.js +102 -0
  206. package/dist/runtime/templateUsages.js.map +1 -0
  207. package/dist/runtime/topo.d.ts +1 -0
  208. package/dist/runtime/topo.js +23 -0
  209. package/dist/runtime/topo.js.map +1 -1
  210. package/dist/runtime/trace.d.ts +44 -0
  211. package/dist/runtime/trace.js +240 -0
  212. package/dist/runtime/trace.js.map +1 -0
  213. package/dist/runtime/typeSwitches.d.ts +3 -0
  214. package/dist/runtime/typeSwitches.js +27 -0
  215. package/dist/runtime/typeSwitches.js.map +1 -0
  216. package/dist/runtime/validate.d.ts +11 -0
  217. package/dist/runtime/validate.js +118 -61
  218. package/dist/runtime/validate.js.map +1 -1
  219. package/dist/runtime/webhookRoutes.d.ts +4 -0
  220. package/dist/runtime/webhookRoutes.js +68 -0
  221. package/dist/runtime/webhookRoutes.js.map +1 -0
  222. package/dist/runtime/withTimeout.d.ts +1 -0
  223. package/dist/runtime/withTimeout.js +17 -0
  224. package/dist/runtime/withTimeout.js.map +1 -0
  225. package/dist/runtime/wording.d.ts +10 -0
  226. package/dist/runtime/wording.js +118 -0
  227. package/dist/runtime/wording.js.map +1 -0
  228. package/dist/stats/health-banner.d.ts +13 -0
  229. package/dist/stats/health-banner.js +149 -0
  230. package/dist/stats/health-banner.js.map +1 -0
  231. package/dist/stats/health.d.ts +49 -0
  232. package/dist/stats/health.js +130 -0
  233. package/dist/stats/health.js.map +1 -0
  234. package/dist/stats/kpi.d.ts +21 -0
  235. package/dist/stats/kpi.js +101 -0
  236. package/dist/stats/kpi.js.map +1 -0
  237. package/dist/stats/overview.d.ts +94 -0
  238. package/dist/stats/overview.js +244 -0
  239. package/dist/stats/overview.js.map +1 -0
  240. package/dist/types/constants.d.ts +0 -1
  241. package/dist/types/constants.js +1 -2
  242. package/dist/types/constants.js.map +1 -1
  243. package/dist/types/runLog.d.ts +2 -0
  244. package/dist/types/runLog.js +4 -0
  245. package/dist/types/runLog.js.map +1 -1
  246. package/frontend-vue/app/components/AttentionList.vue +276 -0
  247. package/frontend-vue/app/components/Catalog/SchemaTable.vue +127 -0
  248. package/frontend-vue/app/components/Catalog.vue +457 -0
  249. package/frontend-vue/app/components/Editor/BottomDock.vue +188 -0
  250. package/frontend-vue/app/components/Editor/BuilderPalette.vue +101 -45
  251. package/frontend-vue/app/components/Editor/GraphCanvas.vue +818 -206
  252. package/frontend-vue/app/components/Editor/GroupPortEditor.vue +29 -18
  253. package/frontend-vue/app/components/Editor/JsonField.vue +3 -3
  254. package/frontend-vue/app/components/Editor/NewProcedureDialog.vue +108 -0
  255. package/frontend-vue/app/components/Editor/NodeInspector.vue +373 -101
  256. package/frontend-vue/app/components/Editor/ProcedureSwitcher.vue +147 -0
  257. package/frontend-vue/app/components/Editor/RunNowDialog.vue +145 -0
  258. package/frontend-vue/app/components/Editor/WiredField.vue +3 -3
  259. package/frontend-vue/app/components/Editor/nodes/GenericNode.vue +97 -91
  260. package/frontend-vue/app/components/Editor/nodes/GroupNode.vue +5 -6
  261. package/frontend-vue/app/components/Editor/nodes/GroupSentinel.vue +3 -2
  262. package/frontend-vue/app/components/Editor/nodes/styles.ts +14 -18
  263. package/frontend-vue/app/components/Editor.vue +1894 -705
  264. package/frontend-vue/app/components/IconPicker.vue +122 -0
  265. package/frontend-vue/app/components/LiveTopics.vue +20 -0
  266. package/frontend-vue/app/components/Run/RunCompare.vue +115 -0
  267. package/frontend-vue/app/components/Run/RunFailure.vue +54 -0
  268. package/frontend-vue/app/components/Run/RunLogList.vue +167 -0
  269. package/frontend-vue/app/components/Run/RunPathTaken.vue +139 -0
  270. package/frontend-vue/app/components/Run/RunPayload.vue +85 -0
  271. package/frontend-vue/app/components/Run/RunWaterfall.vue +374 -0
  272. package/frontend-vue/app/components/RunPeek.vue +132 -0
  273. package/frontend-vue/app/components/RunTrace.vue +462 -0
  274. package/frontend-vue/app/components/Templates.vue +382 -537
  275. package/frontend-vue/app/components/WebhookEndpoint.vue +81 -0
  276. package/frontend-vue/app/composables/useAutomationNodeKinds.ts +23 -6
  277. package/frontend-vue/app/composables/useAutomationRuns.ts +160 -25
  278. package/frontend-vue/app/composables/useGraphConnect.ts +103 -51
  279. package/frontend-vue/app/composables/useRunActions.ts +60 -0
  280. package/frontend-vue/app/plugins/cell-displays.ts +169 -0
  281. package/frontend-vue/app/utils/automation.ts +4 -36
  282. package/frontend-vue/app/utils/describe.ts +252 -0
  283. package/frontend-vue/app/utils/redactedHeaders.ts +31 -0
  284. package/frontend-vue/dms.frontend.build.ts +7 -0
  285. package/frontend-vue/dms.frontend.ts +7 -4
  286. package/frontend-vue/i18n/locales/dms-automation-en-GB.json +1149 -309
  287. package/frontend-vue/i18n/locales/dms-automation-fr-FR.json +1154 -314
  288. package/frontend-vue/package.json +1 -1
  289. package/package.json +8 -6
  290. package/dist/db/models/type_config.model.d.ts +0 -47
  291. package/dist/db/models/type_config.model.js +0 -51
  292. package/dist/db/models/type_config.model.js.map +0 -1
  293. package/dist/db/tables/action_type_config.table.d.ts +0 -7
  294. package/dist/db/tables/action_type_config.table.js +0 -35
  295. package/dist/db/tables/action_type_config.table.js.map +0 -1
  296. package/dist/db/tables/trigger_type_config.table.d.ts +0 -7
  297. package/dist/db/tables/trigger_type_config.table.js.map +0 -1
  298. package/frontend-vue/app/components/Actions.vue +0 -151
  299. package/frontend-vue/app/components/Catalog/TypeConfigForm.vue +0 -170
  300. package/frontend-vue/app/components/Catalog/TypeList.vue +0 -203
  301. package/frontend-vue/app/components/DataNodes.vue +0 -275
  302. package/frontend-vue/app/components/Editor/ProcedureList.vue +0 -156
  303. package/frontend-vue/app/components/Editor/RunsDrawer.vue +0 -312
  304. package/frontend-vue/app/components/Library.vue +0 -69
  305. package/frontend-vue/app/components/Overview.vue +0 -503
  306. package/frontend-vue/app/components/RunDetailDrawer.vue +0 -165
  307. package/frontend-vue/app/components/RunFireTree.vue +0 -170
  308. package/frontend-vue/app/components/RunTraceDrawer.vue +0 -59
  309. package/frontend-vue/app/components/RunsStats.vue +0 -126
  310. package/frontend-vue/app/components/RunsTimelineDisplay.vue +0 -287
  311. package/frontend-vue/app/components/Triggers.vue +0 -147
  312. package/frontend-vue/app/plugins/runs-timeline-display.client.ts +0 -16
@@ -1,9 +1,25 @@
1
1
  <script setup lang="ts">
2
- import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
2
+ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
3
+ import { type RunDetail, type TraceStep, useAutomationRuns } from '../composables/useAutomationRuns'
4
+ import type { NodeRunState } from './Editor/nodes/GenericNode.vue'
5
+ import type { DockIssue, DockRun, DockTab } from './Editor/BottomDock.vue'
6
+ import type { ProcedureSummaryRow } from './Editor/ProcedureSwitcher.vue'
7
+ import { describeDateTime, describeDuration, describeTime, stepTitle, type TriggerSummary, type WordedTrigger } from '../utils/describe'
3
8
  import type { BreadcrumbItem } from '@nuxt/ui'
4
- import type { NodeKindEntry } from '../composables/useAutomationNodeKinds'
5
- import { type ListEnvelope, newId, unwrapList } from '../utils/automation'
6
- import type { GroupPort } from '../composables/useGraphConnect'
9
+ import type { NodeKindEntry, TemplateSummary } from '../composables/useAutomationNodeKinds'
10
+ import { newId, queryString } from '../utils/automation'
11
+ import type {
12
+ ActionType,
13
+ DataEdge,
14
+ DataNodeType,
15
+ GraphNode,
16
+ GroupPort,
17
+ JsonSchema,
18
+ JsonSchemaProperty,
19
+ ProcedureGraph,
20
+ TriggerEdge,
21
+ TriggerType,
22
+ } from '../composables/useGraphConnect'
7
23
 
8
24
  // Editor mode.
9
25
  //
@@ -17,74 +33,47 @@ import type { GroupPort } from '../composables/useGraphConnect'
17
33
  // PUT /api/automation/templates/:id. Run, procedure list, and enabled toggle
18
34
  // are hidden.
19
35
  //
20
- // Mode is resolved from props first (so a host page can hard-wire it) and
21
- // otherwise from the route query: `?template=<id>` switches into template mode.
36
+ // Mode is resolved from the route query: `?template=<id>` switches into
37
+ // template mode.
22
38
  // This keeps the route wiring trivial (the Templates catalog navigates
23
39
  // to `/modules/automation/builder?template=<id>`) without needing a
24
40
  // dedicated page.
25
41
  const props = withDefaults(
26
42
  defineProps<{
27
- mode?: 'procedure' | 'template'
28
- entityId?: string
43
+ apiUrl?: string
44
+ runsUrl?: string
45
+ traceUrl?: string
29
46
  }>(),
30
- { mode: undefined, entityId: undefined },
47
+ {
48
+ apiUrl: '/api/automation',
49
+ runsUrl: '/modules/automation/runs',
50
+ traceUrl: '/modules/automation/trace',
51
+ },
31
52
  )
32
53
 
33
54
  const route = useDmsRoute()
55
+ const router = useDmsRouter()
56
+ const { t, te, locale } = useI18n()
57
+ const { dateTimeFormat } = useRegionalFormat()
58
+ const { processI18n } = useTranslation()
59
+ const { processText } = useComposedText()
60
+ // Shortcut hints print ⌘ on macOS and Ctrl elsewhere, like the rest of the DMS.
61
+ const { formatShortcut } = useKeyboardPlatform()
34
62
 
35
- const templateQueryId = computed<string | null>(() => {
36
- const q = route.query.template
37
- if (typeof q === 'string' && q.length > 0) return q
38
- if (Array.isArray(q) && typeof q[0] === 'string' && q[0]!.length > 0) return q[0]!
39
- return null
40
- })
41
-
42
- const editorMode = computed<'procedure' | 'template'>(() => {
43
- if (props.mode) return props.mode
44
- if (templateQueryId.value) return 'template'
45
- return 'procedure'
46
- })
47
-
48
- const editorTemplateId = computed<string | null>(() => {
49
- if (editorMode.value !== 'template') return null
50
- return props.entityId ?? templateQueryId.value
51
- })
52
-
53
- interface GraphNode {
54
- id: string
55
- // Node kind is a free-form string keyed off the backend kind registry
56
- // (`/api/automation/node-kinds`); the few kinds with bespoke Vue
57
- // components (group / groupInput / groupOutput) are compared as
58
- // literals where needed.
59
- kind: string
60
- typeId?: string
61
- config: Record<string, unknown>
62
- position: { x: number; y: number }
63
- // Group-only extras — present iff kind === 'group'.
64
- ports?: GroupPort[]
65
- templateId?: string
66
- subgraph?: ProcedureGraph
63
+ /** The builder's own path, without the query its URL may carry. */
64
+ function builderPath(): string {
65
+ return route.path.split('?')[0] ?? route.path
67
66
  }
68
67
 
69
- interface TriggerEdge {
70
- id: string
71
- from: { node: string; branch?: string }
72
- // `to.branch` carries the target's trigger-in port name when the target is
73
- // a group node or groupOutput sentinel — see src/types/graph.ts.
74
- to: { node: string; branch?: string }
68
+ function queryValue(key: string): string | null {
69
+ return queryString(route.query[key])
75
70
  }
76
71
 
77
- interface DataEdge {
78
- id: string
79
- from: { node: string; port: string }
80
- to: { node: string; field: string }
81
- }
72
+ const templateQueryId = computed(() => queryValue('template'))
82
73
 
83
- interface ProcedureGraph {
84
- nodes: GraphNode[]
85
- triggerEdges: TriggerEdge[]
86
- dataEdges: DataEdge[]
87
- }
74
+ const editorMode = computed<'procedure' | 'template'>(() => (templateQueryId.value ? 'template' : 'procedure'))
75
+
76
+ const editorTemplateId = computed<string | null>(() => (editorMode.value === 'template' ? templateQueryId.value : null))
88
77
 
89
78
  interface ProcedureRecord {
90
79
  _id: string
@@ -92,65 +81,37 @@ interface ProcedureRecord {
92
81
  description: string
93
82
  enabled: boolean
94
83
  graph: ProcedureGraph
95
- }
96
-
97
- interface ProcedureApiRecord {
98
- _id: string
99
- name: string
100
- description?: string
101
- enabled: boolean
102
- graph: string | ProcedureGraph
103
- }
104
-
105
- interface JsonSchemaProperty {
106
- type?: string
107
- [key: string]: unknown
108
- }
109
-
110
- interface JsonSchema {
111
- type?: string
112
- properties?: Record<string, JsonSchemaProperty>
113
- [key: string]: unknown
114
- }
115
-
116
- interface TriggerType {
117
- id: string
118
- name: string
119
- description?: string
120
- icon?: string
121
- configSchema?: JsonSchema
122
- outputSchema?: JsonSchema
123
- }
124
-
125
- interface ActionType {
126
- id: string
127
- name: string
128
- description?: string
129
- icon?: string
130
- inputSchema?: JsonSchema
131
- outputSchema?: JsonSchema
132
- }
133
-
134
- interface DataNodeType {
135
- id: string
136
- category: string
137
- name: string
138
- description: string
139
- icon: string
140
- inputSchema: JsonSchema
141
- outputSchema: JsonSchema
142
- // Kept in sync with the canonical DataNodeType (useGraphConnect.ts).
143
- configSchema?: JsonSchema
84
+ // The graph's version (it moves with the graph only), and the revision
85
+ // (it moves with every write: a save, a pause from the list). A save sends
86
+ // the revision it started from back, so the server refuses to overwrite
87
+ // what was written elsewhere in the meantime.
88
+ version?: number
89
+ revision?: number
144
90
  }
145
91
 
146
92
  const { $authFetch } = useAuthFetch()
147
93
  const toast = useToast()
94
+ // Composables are called before the first `await` of this setup: after it,
95
+ // the component instance they inject from is gone.
96
+ const { confirm } = useConfirm()
97
+ const { confirmFrom } = useConfirmFrom()
98
+ const runsApi = useAutomationRuns(props.apiUrl)
99
+ // Leaving the page with unsaved changes goes through the DMS leave guard.
100
+ const unsavedDraft = ref(false)
101
+ useUnsavedChanges({ dirty: unsavedDraft })
148
102
 
149
103
  const procedures = ref<ProcedureRecord[]>([])
150
104
  const selectedId = ref<string | null>(null)
151
- const showProcedures = ref(false)
105
+ const switcherOpen = ref(false)
106
+ const newProcedureOpen = ref(false)
107
+ const runNowOpen = ref(false)
152
108
  const loading = ref(false)
153
109
  const loadError = ref<string | null>(null)
110
+ // The `?selected=` of a procedure that no longer exists: the builder says so
111
+ // instead of opening another one.
112
+ const missingProcedureId = ref<string | null>(null)
113
+ // `?template=` names a template that no longer exists.
114
+ const templateNotFound = ref(false)
154
115
  const saving = ref(false)
155
116
  const running = ref(false)
156
117
 
@@ -160,6 +121,8 @@ const running = ref(false)
160
121
  // handle sets. We pipe them through `currentParentGroupPorts` so GraphCanvas
161
122
  // renders them identically to how it renders a nested group's sentinels.
162
123
  const templatePorts = ref<GroupPort[]>([])
124
+ // Kept as loaded: saving the template from the editor must not reset its icon.
125
+ const templateIcon = ref<string>('i-ph-package')
163
126
  const templateLoadKey = ref<string | null>(null)
164
127
 
165
128
  const triggerTypes = ref<TriggerType[]>([])
@@ -178,26 +141,13 @@ const nodeKinds = ref<NodeKindEntry[]>([])
178
141
  // the client (id, name, icon, ports). The list endpoint still returns full
179
142
  // rows (description, usageCount, hydrated subgraph); the `.map()` below
180
143
  // simply discards the extra fields after the fetch.
181
- interface TemplatePaletteRow {
182
- _id: string
183
- name: string
184
- icon?: string
185
- ports: GroupPort[]
186
- }
187
- interface TemplateListResponse {
188
- results?: TemplatePaletteRow[]
189
- items?: TemplatePaletteRow[]
190
- }
191
- const templates = ref<TemplatePaletteRow[]>([])
144
+ const templates = ref<TemplateSummary[]>([])
192
145
  const templatesLoadError = ref<string | null>(null)
193
146
 
194
147
  async function loadTemplates() {
195
148
  try {
196
- const data = await $authFetch<
197
- TemplatePaletteRow[] | TemplateListResponse
198
- >('/api/automation/templates')
199
- const list = unwrapList<TemplatePaletteRow>(data)
200
- templates.value = list.map((t) => ({
149
+ const { results } = await $authFetch<{ results: TemplateSummary[] }>('/api/automation/templates')
150
+ templates.value = results.map((t) => ({
201
151
  _id: t._id,
202
152
  name: t.name,
203
153
  icon: t.icon,
@@ -205,7 +155,7 @@ async function loadTemplates() {
205
155
  }))
206
156
  templatesLoadError.value = null
207
157
  } catch (e) {
208
- templatesLoadError.value = (e as Error).message ?? 'Failed to load templates'
158
+ templatesLoadError.value = describeApiError(e)
209
159
  templates.value = []
210
160
  }
211
161
  }
@@ -214,10 +164,33 @@ async function loadTemplates() {
214
164
  // server's cycle check would still catch any reference cycle, but blocking
215
165
  // it at the UI level keeps the UX cleaner — the user can't even attempt
216
166
  // to drop a template (including the one currently open) into itself.
217
- const palettesTemplates = computed<TemplatePaletteRow[] | undefined>(() =>
167
+ const palettesTemplates = computed<TemplateSummary[] | undefined>(() =>
218
168
  editorMode.value === 'template' ? undefined : templates.value,
219
169
  )
220
170
 
171
+ // Triggers live at the top level of a procedure: the palette offers none
172
+ // inside a group or a template.
173
+ const paletteTriggerTypes = computed<TriggerType[]>(() =>
174
+ editorMode.value === 'template' || subgraphPath.value.length > 1 ? [] : triggerTypes.value,
175
+ )
176
+
177
+ // The inspector (or the template's ports): docked beside the canvas from lg
178
+ // (the palette starts folded below xl, so the canvas keeps most of the
179
+ // width), floating over it on narrower screens.
180
+ const ASIDE_CLASS =
181
+ 'absolute inset-y-0 right-0 z-10 flex w-80 max-w-full flex-col border-l border-default bg-default shadow-lg lg:relative lg:z-auto lg:shrink-0 lg:shadow-none'
182
+
183
+ // Which graph the canvas shows (procedure or template, then the groups
184
+ // entered): the canvas fits a new one into view.
185
+ const canvasViewKey = computed(() => [selectedId.value ?? '', ...subgraphPath.value.slice(1).map((segment) => segment.id)].join('/'))
186
+
187
+ // Back to the Library's Templates tab, on the template being edited.
188
+ const libraryBackUrl = computed(() =>
189
+ editorTemplateId.value && !templateNotFound.value
190
+ ? `/modules/automation/library?tab=templates&template=${editorTemplateId.value}`
191
+ : '/modules/automation/library?tab=templates',
192
+ )
193
+
221
194
  const selectedNodeId = ref<string | null>(null)
222
195
  // Mirrors GraphCanvas's @selection-change — full set of currently selected
223
196
  // node ids in the canvas, sentinel-filtered. Drives the "Group selection"
@@ -252,6 +225,8 @@ interface ProcedureSnapshot {
252
225
  name: string
253
226
  enabled: boolean
254
227
  graph: ProcedureGraph
228
+ // Template mode only: the template's outer ports, edited at its root.
229
+ ports?: GroupPort[]
255
230
  }
256
231
 
257
232
  const graphHistory = ref<ProcedureGraph[]>([])
@@ -264,12 +239,15 @@ function cloneGraph(g: ProcedureGraph): ProcedureGraph {
264
239
  }
265
240
 
266
241
  function takeSnapshot(p: ProcedureRecord): ProcedureSnapshot {
267
- return { name: p.name, enabled: p.enabled, graph: cloneGraph(p.graph) }
242
+ return {
243
+ name: p.name,
244
+ enabled: p.enabled,
245
+ graph: cloneGraph(p.graph),
246
+ ...(editorMode.value === 'template' ? { ports: templatePorts.value.map((port) => ({ ...port })) } : {}),
247
+ }
268
248
  }
269
249
 
270
- // Strip per-node position so pure drag-to-reposition doesn't add an undo
271
- // step on every pixel. The drag's final position still gets saved by Apply
272
- // and reverted by Cancel because savedSnapshot keeps the full graph.
250
+ // Strip per-node position: a drag is told apart from a structural change.
273
251
  function structuralKey(g: ProcedureGraph): string {
274
252
  return JSON.stringify({
275
253
  nodes: g.nodes.map(({ position: _pos, ...rest }) => rest),
@@ -278,10 +256,60 @@ function structuralKey(g: ProcedureGraph): string {
278
256
  })
279
257
  }
280
258
 
281
- function pushHistory(g: ProcedureGraph) {
259
+ /**
260
+ * What a change does, when it is one a burst of changes repeats: the same
261
+ * nodes moved ("move:a,b"), or the same settings of one node edited
262
+ * ("edit:a:url"), at any depth of groups. `null` for anything else.
263
+ */
264
+ function repeatableChangeKey(before: ProcedureGraph, after: ProcedureGraph): string | null {
265
+ if (JSON.stringify([before.triggerEdges, before.dataEdges]) !== JSON.stringify([after.triggerEdges, after.dataEdges])) return null
266
+ if (before.nodes.length !== after.nodes.length) return null
267
+ const moved: string[] = []
268
+ let edited: string | null = null
269
+ for (let i = 0; i < after.nodes.length; i++) {
270
+ const a = before.nodes[i]! as GraphNode & Record<string, unknown>
271
+ const b = after.nodes[i]! as GraphNode & Record<string, unknown>
272
+ if (a.id !== b.id) return null
273
+ const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])].filter((k) => JSON.stringify(a[k]) !== JSON.stringify(b[k]))
274
+ if (keys.length === 0) continue
275
+ if (keys.length === 1 && keys[0] === 'position') {
276
+ moved.push(a.id)
277
+ continue
278
+ }
279
+ if (edited) return null
280
+ if (keys.length === 1 && keys[0] === 'subgraph' && a.subgraph && b.subgraph) {
281
+ const inner = repeatableChangeKey(a.subgraph, b.subgraph)
282
+ if (!inner) return null
283
+ edited = `${a.id}/${inner}`
284
+ continue
285
+ }
286
+ if (!keys.every((k) => k === 'config' || k === 'label')) return null
287
+ const fields = Object.keys({ ...a.config, ...b.config }).filter((k) => JSON.stringify(a.config?.[k]) !== JSON.stringify(b.config?.[k]))
288
+ edited = `${a.id}:${[...fields, ...(keys.includes('label') ? ['label'] : [])].join(',')}`
289
+ }
290
+ if (edited) return moved.length ? null : `edit:${edited}`
291
+ return moved.length ? `move:${moved.join(',')}` : null
292
+ }
293
+
294
+ // A drag emits a graph per frame and a text field one per keystroke: the
295
+ // changes of one burst make one undo step (the last one is replaced while
296
+ // the same nodes move, or the same field is typed in, without a pause).
297
+ const HISTORY_MERGE_MS = 1000
298
+ let lastChange: { key: string | null; at: number } = { key: null, at: 0 }
299
+
300
+ function pushHistory(g: ProcedureGraph, merge = false) {
282
301
  const current = graphHistory.value[graphHistoryIndex.value]
283
- if (current && structuralKey(current) === structuralKey(g)) return
302
+ if (current && JSON.stringify(current) === JSON.stringify(g)) return
303
+ const key = merge && current ? repeatableChangeKey(current, g) : null
304
+ const now = Date.now()
305
+ const sameBurst = key !== null && key === lastChange.key && now - lastChange.at < HISTORY_MERGE_MS
306
+ lastChange = { key, at: now }
307
+ // A new action, a drag included, drops what Redo could bring back.
284
308
  graphHistory.value = graphHistory.value.slice(0, graphHistoryIndex.value + 1)
309
+ if (sameBurst) {
310
+ graphHistory.value[graphHistoryIndex.value] = cloneGraph(g)
311
+ return
312
+ }
285
313
  graphHistory.value.push(cloneGraph(g))
286
314
  graphHistoryIndex.value = graphHistory.value.length - 1
287
315
  if (graphHistory.value.length > HISTORY_LIMIT) {
@@ -291,6 +319,7 @@ function pushHistory(g: ProcedureGraph) {
291
319
  }
292
320
 
293
321
  function initHistoryAndSaved() {
322
+ lastChange = { key: null, at: 0 }
294
323
  if (selected.value) {
295
324
  graphHistory.value = [cloneGraph(selected.value.graph)]
296
325
  graphHistoryIndex.value = 0
@@ -302,66 +331,43 @@ function initHistoryAndSaved() {
302
331
  }
303
332
  }
304
333
 
305
- function emptyGraph(): ProcedureGraph {
306
- return {
307
- nodes: [
308
- {
309
- id: 'trigger-1',
310
- kind: 'trigger',
311
- typeId: 'manual',
312
- config: {},
313
- position: { x: 100, y: 100 },
314
- },
315
- ],
316
- triggerEdges: [],
317
- dataEdges: [],
318
- }
319
- }
320
-
321
- function parseGraph(g: string | ProcedureGraph | undefined | null): ProcedureGraph {
322
- if (!g) return emptyGraph()
323
- if (typeof g === 'string') {
324
- try {
325
- const parsed = JSON.parse(g) as ProcedureGraph
326
- return parsed && Array.isArray(parsed.nodes) ? parsed : emptyGraph()
327
- } catch {
328
- return emptyGraph()
329
- }
330
- }
331
- return g
332
- }
333
-
334
- function normalize(r: ProcedureApiRecord): ProcedureRecord {
335
- return {
336
- _id: r._id,
337
- name: r.name,
338
- description: r.description ?? '',
339
- enabled: !!r.enabled,
340
- graph: parseGraph(r.graph),
341
- }
342
- }
334
+ const PROCEDURES_PAGE_SIZE = 200
343
335
 
344
336
  async function loadList() {
345
337
  loading.value = true
346
338
  loadError.value = null
347
339
  try {
348
- const data = await $authFetch<
349
- ProcedureApiRecord[] | ListEnvelope<ProcedureApiRecord>
350
- >('/api/automation/procedures')
351
- const list = unwrapList<ProcedureApiRecord>(data)
352
- procedures.value = list.map(normalize)
340
+ // The API serves pages of PROCEDURES_PAGE_SIZE at most: read them all.
341
+ const list: ProcedureRecord[] = []
342
+ for (let page = 0; ; page++) {
343
+ const { results } = await $authFetch<{ results: ProcedureRecord[] }>(
344
+ `/api/automation/procedures?limit=${PROCEDURES_PAGE_SIZE}&page=${page}`,
345
+ )
346
+ list.push(...results)
347
+ if (results.length < PROCEDURES_PAGE_SIZE) break
348
+ }
349
+ procedures.value = list
353
350
  if (
354
351
  selectedId.value &&
355
352
  !procedures.value.some((p) => p._id === selectedId.value)
356
353
  ) {
357
354
  selectedId.value = null
358
355
  }
356
+ const requested = queryValue('selected')
357
+ if (requested && procedures.value.some((p) => p._id === requested)) {
358
+ selectedId.value = requested
359
+ } else if (requested && !selectedId.value) {
360
+ // A link to a deleted procedure opens none: the builder says so
361
+ // and offers the switcher (see onMounted).
362
+ missingProcedureId.value = requested
363
+ return
364
+ }
359
365
  if (!selectedId.value && procedures.value.length > 0) {
360
366
  const first = procedures.value[0]
361
367
  selectedId.value = first ? first._id : null
362
368
  }
363
369
  } catch (e) {
364
- loadError.value = (e as Error).message ?? 'Failed to load procedures'
370
+ loadError.value = describeApiError(e)
365
371
  } finally {
366
372
  loading.value = false
367
373
  }
@@ -369,21 +375,9 @@ async function loadList() {
369
375
 
370
376
  async function loadTypeCatalogs() {
371
377
  try {
372
- triggerTypes.value = unwrapList<TriggerType>(
373
- await $authFetch<TriggerType[] | ListEnvelope<TriggerType>>(
374
- '/api/automation/trigger-types',
375
- ),
376
- )
377
- actionTypes.value = unwrapList<ActionType>(
378
- await $authFetch<ActionType[] | ListEnvelope<ActionType>>(
379
- '/api/automation/action-types',
380
- ),
381
- )
382
- dataNodeTypes.value = unwrapList<DataNodeType>(
383
- await $authFetch<DataNodeType[] | ListEnvelope<DataNodeType>>(
384
- '/api/automation/data-node-types',
385
- ),
386
- )
378
+ triggerTypes.value = await $authFetch<TriggerType[]>('/api/automation/trigger-types')
379
+ actionTypes.value = await $authFetch<ActionType[]>('/api/automation/action-types')
380
+ dataNodeTypes.value = await $authFetch<DataNodeType[]>('/api/automation/data-node-types')
387
381
  nodeKinds.value = await useAutomationNodeKinds().list()
388
382
  } catch {
389
383
  // Catalogs are optional for editing — silently ignore.
@@ -395,18 +389,18 @@ interface AutomationTemplateApi {
395
389
  name: string
396
390
  description?: string
397
391
  icon?: string
398
- ports?: GroupPort[]
399
- subgraph?: string | ProcedureGraph
392
+ ports: GroupPort[]
393
+ subgraph: ProcedureGraph
400
394
  }
401
395
 
402
396
  async function loadTemplate(id: string) {
403
397
  loading.value = true
404
398
  loadError.value = null
405
399
  try {
400
+ templateNotFound.value = false
406
401
  const tpl = await $authFetch<AutomationTemplateApi>(
407
402
  `/api/automation/templates/${id}`,
408
403
  )
409
- const subgraph = parseGraph(tpl.subgraph)
410
404
  // Adapt the template into the ProcedureRecord shape so the rest of
411
405
  // the editor (history, dirty-tracking, sentinel sync, group toolbar)
412
406
  // keeps working unchanged. `enabled` is meaningless for templates;
@@ -416,16 +410,20 @@ async function loadTemplate(id: string) {
416
410
  name: tpl.name,
417
411
  description: tpl.description ?? '',
418
412
  enabled: true,
419
- graph: subgraph,
413
+ graph: tpl.subgraph,
420
414
  }
421
415
  procedures.value = [adapted]
422
416
  selectedId.value = adapted._id
417
+ templateIcon.value = tpl.icon || 'i-ph-package'
423
418
  templatePorts.value = Array.isArray(tpl.ports)
424
419
  ? tpl.ports.map((p) => ({ ...p }))
425
420
  : []
426
421
  templateLoadKey.value = id
427
422
  } catch (e) {
428
- loadError.value = (e as Error).message ?? 'Failed to load template'
423
+ // Worded for users, the same on the server and in the browser (the
424
+ // raw fetch error names an internal URL that differs between them).
425
+ templateNotFound.value = apiErrorStatus(e) === 404
426
+ loadError.value = templateNotFound.value ? t('dms_automation.editor.templateNotFound') : describeApiError(e)
429
427
  procedures.value = []
430
428
  selectedId.value = null
431
429
  templatePorts.value = []
@@ -439,7 +437,8 @@ if (editorMode.value === 'template') {
439
437
  if (id) {
440
438
  await loadTemplate(id)
441
439
  } else {
442
- loadError.value = 'No template id provided'
440
+ templateNotFound.value = true
441
+ loadError.value = t('dms_automation.editor.templateNotFound')
443
442
  }
444
443
  } else {
445
444
  await loadList()
@@ -613,7 +612,7 @@ function onGraphUpdate(g: ProcedureGraph) {
613
612
  // At procedure root — write straight through, same as before
614
613
  // subgraph navigation existed.
615
614
  selected.value.graph = g
616
- pushHistory(g)
615
+ pushHistory(g, true)
617
616
  return
618
617
  }
619
618
  // At a deeper level — `g` is the subgraph of the deepest group node.
@@ -654,7 +653,7 @@ function onGraphUpdate(g: ProcedureGraph) {
654
653
  }
655
654
  }
656
655
  selected.value.graph = rootGraph
657
- pushHistory(rootGraph)
656
+ pushHistory(rootGraph, true)
658
657
  }
659
658
 
660
659
  const canUndo = computed<boolean>(
@@ -673,6 +672,7 @@ const isDirty = computed<boolean>(() => {
673
672
 
674
673
  function onUndo() {
675
674
  if (!canUndo.value || !selected.value) return
675
+ lastChange = { key: null, at: 0 }
676
676
  graphHistoryIndex.value--
677
677
  const g = graphHistory.value[graphHistoryIndex.value]
678
678
  if (g) selected.value.graph = cloneGraph(g)
@@ -680,6 +680,7 @@ function onUndo() {
680
680
 
681
681
  function onRedo() {
682
682
  if (!canRedo.value || !selected.value) return
683
+ lastChange = { key: null, at: 0 }
683
684
  graphHistoryIndex.value++
684
685
  const g = graphHistory.value[graphHistoryIndex.value]
685
686
  if (g) selected.value.graph = cloneGraph(g)
@@ -691,7 +692,12 @@ function onCancel() {
691
692
  selected.value.name = snap.name
692
693
  selected.value.enabled = snap.enabled
693
694
  selected.value.graph = cloneGraph(snap.graph)
695
+ if (snap.ports) templatePorts.value = snap.ports.map((port) => ({ ...port }))
694
696
  pushHistory(selected.value.graph)
697
+ // A refused save is answered by the draft it refused: discarding it
698
+ // clears the banner, and the name, outside the graph, is checked again.
699
+ saveBlocked.value = false
700
+ void validateDraft()
695
701
  }
696
702
 
697
703
  const selectedNode = computed<GraphNode | null>(() => {
@@ -728,10 +734,6 @@ const graphCanvasRef = ref<{
728
734
  addTemplateInstance: (template: { _id: string; name: string; icon?: string; ports: GroupPort[] }) => void
729
735
  } | null>(null)
730
736
 
731
- // Runs panel (toolbar button + right slideover). Kept so onRun can refresh the
732
- // list and its trigger badge once a run has been queued.
733
- const runsDrawerRef = ref<{ reload: () => void } | null>(null)
734
-
735
737
  function onPaletteAddNode(payload: { kind: string; typeId?: string }) {
736
738
  graphCanvasRef.value?.addNode(payload.kind, payload.typeId)
737
739
  }
@@ -739,11 +741,6 @@ function onPaletteAddTemplate(template: { _id: string; name: string; icon?: stri
739
741
  graphCanvasRef.value?.addTemplateInstance(template)
740
742
  }
741
743
 
742
- function onProcedurePicked(id: string | null) {
743
- selectedId.value = id
744
- if (id) showProcedures.value = false
745
- }
746
-
747
744
  watch(selectedId, () => {
748
745
  selectedNodeId.value = null
749
746
  initHistoryAndSaved()
@@ -760,6 +757,11 @@ watch(templateQueryId, async (id) => {
760
757
  await loadTemplate(id)
761
758
  })
762
759
 
760
+ /** A group's name: its step name, else the name it was created with. */
761
+ function groupName(node: GraphNode): string {
762
+ return node.label || (node.config?.name as string | undefined) || t('dms_automation.editor.groupDefaultName')
763
+ }
764
+
763
765
  function onGroupEnter(payload: { id: string }) {
764
766
  const g = currentGraph.value
765
767
  if (!g) return
@@ -769,8 +771,7 @@ function onGroupEnter(payload: { id: string }) {
769
771
  // stop at this segment and the watcher would prune it back. Bail early so
770
772
  // the path doesn't briefly include a doomed segment.
771
773
  if (node.templateId && !node.subgraph) return
772
- const name =
773
- (node.config?.name as string | undefined) ?? 'Group'
774
+ const name = groupName(node)
774
775
  subgraphPath.value = [
775
776
  ...subgraphPath.value,
776
777
  { kind: 'group', id: node.id, name },
@@ -1468,12 +1469,9 @@ function createGroupFromSelection() {
1468
1469
  const ids = selectedNodeIds.value.slice()
1469
1470
  if (ids.length === 0) return
1470
1471
 
1471
- // Default name; window.prompt is intentionally lo-fi for v1. A modal
1472
- // could replace this later, but it keeps the change scope tight.
1473
- const inputName =
1474
- typeof window !== 'undefined'
1475
- ? (window.prompt('Group name', 'Group') ?? '').trim() || 'Group'
1476
- : 'Group'
1472
+ // The group gets a default name, then the inspector opens on it with its
1473
+ // name field focused: renaming is one keystroke away, nothing blocks.
1474
+ const inputName = t('dms_automation.editor.groupDefaultName')
1477
1475
 
1478
1476
  const selection = new Set(ids)
1479
1477
  const groupId = newId()
@@ -1570,15 +1568,18 @@ function createGroupFromSelection() {
1570
1568
  selectedNodeId.value = groupId
1571
1569
 
1572
1570
  onGraphUpdate(nextGraph)
1571
+ void focusInspectorName()
1573
1572
  }
1574
1573
 
1575
- const canRun = computed<boolean>(() => {
1576
- const g = selected.value?.graph
1577
- if (!g) return false
1578
- return g.nodes.some(
1579
- (n) => n.kind === 'trigger' && n.typeId === 'manual',
1580
- )
1581
- })
1574
+ const inspectorRef = ref<HTMLElement | null>(null)
1575
+
1576
+ /** Focuses the inspector's first field, the step name, and selects its text. */
1577
+ async function focusInspectorName() {
1578
+ await nextTick()
1579
+ const input = inspectorRef.value?.querySelector('input')
1580
+ input?.focus()
1581
+ input?.select()
1582
+ }
1582
1583
 
1583
1584
  const procedureName = computed<string>({
1584
1585
  get: () => selected.value?.name ?? '',
@@ -1587,6 +1588,15 @@ const procedureName = computed<string>({
1587
1588
  },
1588
1589
  })
1589
1590
 
1591
+ // Titles and toasts about what is stored name it as stored, not as the
1592
+ // draft spells it (possibly blank) at that moment.
1593
+ const savedName = computed<string>(() => savedSnapshot.value?.name || selected.value?.name || '')
1594
+
1595
+ // The name is the one field outside the graph a save checks: a blank one is
1596
+ // said under the name, and Save waits for it.
1597
+ const NAME_INPUT_ID = 'builder-procedure-name'
1598
+ const nameMissing = computed<boolean>(() => !!selected.value && !selected.value.name.trim())
1599
+
1590
1600
  const procedureEnabled = computed<boolean>({
1591
1601
  get: () => selected.value?.enabled ?? false,
1592
1602
  set: (v: boolean) => {
@@ -1594,188 +1604,671 @@ const procedureEnabled = computed<boolean>({
1594
1604
  },
1595
1605
  })
1596
1606
 
1597
- // Triggers other than `manual` only fire when the procedure is enabled and
1598
- // saved (reconcile activates them); manual still works via Run-now regardless.
1599
- const hasInactiveTriggers = computed<boolean>(() => {
1600
- const g = selected.value?.graph
1601
- if (!g || selected.value?.enabled) return false
1602
- return g.nodes.some(
1603
- (n) => n.kind === 'trigger' && n.typeId && n.typeId !== 'manual',
1604
- )
1605
- })
1607
+ // ---------------------------------------------------------------------------
1608
+ // The builder's bar: state, saving, problems (AU-03, AU-04, AU-16)
1609
+ // ---------------------------------------------------------------------------
1606
1610
 
1607
- async function onCreate() {
1611
+ const summaries = ref<ProcedureSummaryRow[]>([])
1612
+
1613
+ async function loadSummaries() {
1608
1614
  try {
1609
- const body = {
1610
- name: 'New procedure',
1611
- description: '',
1612
- enabled: false,
1613
- graph: emptyGraph(),
1614
- }
1615
- const res = await $authFetch<{ _id: string }>(
1616
- '/api/automation/procedures',
1617
- { method: 'POST', body },
1618
- )
1619
- const created: ProcedureRecord = {
1620
- _id: res._id,
1621
- name: body.name,
1622
- description: body.description,
1623
- enabled: body.enabled,
1624
- graph: body.graph,
1625
- }
1626
- procedures.value = [created, ...procedures.value]
1627
- selectedId.value = created._id
1628
- toast.add({
1629
- title: 'Procedure created',
1630
- color: 'success',
1631
- icon: 'i-ph-check-circle',
1632
- })
1633
- } catch (e) {
1634
- toast.add({
1635
- title: 'Failed to create procedure',
1636
- description: (e as Error).message,
1637
- color: 'error',
1638
- icon: 'i-ph-warning',
1639
- })
1615
+ summaries.value = await $authFetch<ProcedureSummaryRow[]>(`${props.apiUrl}/procedures/summary`)
1616
+ } catch {
1617
+ summaries.value = []
1640
1618
  }
1641
1619
  }
1642
1620
 
1643
- async function onDelete(id: string) {
1621
+ const currentSummary = computed(() => summaries.value.find((s) => s.procedureId === selectedId.value) ?? null)
1622
+
1623
+ const STATE_TONES = {
1624
+ failing: 'error',
1625
+ degraded: 'warning',
1626
+ healthy: 'success',
1627
+ paused: 'neutral',
1628
+ draft: 'info',
1629
+ } as const
1630
+
1631
+ /** How many things changed since the last save, for "2 unsaved changes". */
1632
+ const changeCount = computed<number>(() => {
1633
+ const current = selected.value
1634
+ const saved = savedSnapshot.value
1635
+ if (!current || !saved) return 0
1636
+ let count = 0
1637
+ if (current.name !== saved.name) count++
1638
+ if (current.enabled !== saved.enabled) count++
1639
+ if (saved.ports && JSON.stringify(saved.ports) !== JSON.stringify(templatePorts.value)) count++
1640
+ const before = new Map(saved.graph.nodes.map((n) => [n.id, JSON.stringify(n)]))
1641
+ const after = new Map(current.graph.nodes.map((n) => [n.id, JSON.stringify(n)]))
1642
+ for (const [id, value] of after) if (before.get(id) !== value) count++
1643
+ for (const id of before.keys()) if (!after.has(id)) count++
1644
+ const edges = (g: ProcedureGraph) => JSON.stringify([g.triggerEdges, g.dataEdges])
1645
+ if (edges(current.graph) !== edges(saved.graph)) count++
1646
+ return count
1647
+ })
1648
+
1649
+ // Problems of the draft, asked of the server (the same validator a save
1650
+ // runs) a moment after each change.
1651
+ // Each issue carries a `code` (and its `params`) the locale words; its English
1652
+ // `message` is the fallback for a code the locale does not know.
1653
+ interface GraphIssue {
1654
+ severity: 'error' | 'warning'
1655
+ message: string
1656
+ code?: string
1657
+ params?: Record<string, unknown>
1658
+ nodeId?: string
1659
+ }
1660
+ const issues = ref<GraphIssue[]>([])
1661
+ // The draft's triggers, worded by the server with its problems: the canvas
1662
+ // and the test dock name them.
1663
+ const draftTriggers = ref<WordedTrigger[]>([])
1664
+ let validateTimer: ReturnType<typeof setTimeout> | undefined
1665
+ const VALIDATE_DELAY_MS = 500
1666
+
1667
+ async function validateDraft() {
1668
+ const current = selected.value
1669
+ if (!current || editorMode.value !== 'procedure') {
1670
+ issues.value = []
1671
+ draftTriggers.value = []
1672
+ return
1673
+ }
1644
1674
  try {
1645
- await $authFetch(`/api/automation/procedures/${id}`, {
1646
- method: 'DELETE',
1675
+ const res = await $authFetch<{ issues: typeof issues.value; triggers?: WordedTrigger[] }>(`${props.apiUrl}/procedures/validate`, {
1676
+ method: 'POST',
1677
+ // With the procedure and its name, the server also checks what other
1678
+ // procedures hold (a webhook path, a name).
1679
+ body: { graph: current.graph, enabled: current.enabled, procedureId: current._id, name: current.name },
1647
1680
  })
1648
- procedures.value = procedures.value.filter((p) => p._id !== id)
1649
- if (selectedId.value === id) {
1650
- const first = procedures.value[0]
1651
- selectedId.value = first ? first._id : null
1681
+ issues.value = res.issues ?? []
1682
+ draftTriggers.value = res.triggers ?? []
1683
+ } catch {
1684
+ // A graph the schema refuses is reported on save.
1685
+ }
1686
+ }
1687
+
1688
+ watch(
1689
+ () => (selected.value ? [structuralKey(selected.value.graph), selected.value.name, selected.value.enabled].join('|') : ''),
1690
+ () => {
1691
+ clearTimeout(validateTimer)
1692
+ validateTimer = setTimeout(() => void validateDraft(), VALIDATE_DELAY_MS)
1693
+ },
1694
+ { immediate: true },
1695
+ )
1696
+
1697
+ const blockingIssues = computed(() => issues.value.filter((i) => i.severity === 'error'))
1698
+
1699
+ /** How the builder names a node: its label, else its type's name. */
1700
+ function nodeDisplayName(id: string): string {
1701
+ const node = walkAll(selected.value?.graph).find((n) => n.id === id)
1702
+ if (!node) return id
1703
+ if (node.kind === 'group') return groupName(node)
1704
+ if (node.label) return node.label
1705
+ const typeName =
1706
+ node.kind === 'trigger'
1707
+ ? triggerTypes.value.find((x) => x.id === node.typeId)?.name
1708
+ : node.kind === 'action'
1709
+ ? actionTypes.value.find((x) => x.id === node.typeId)?.name
1710
+ : node.kind === 'data'
1711
+ ? dataNodeTypes.value.find((x) => x.id === node.typeId)?.name
1712
+ : nodeKinds.value.find((k) => k.kind === node.kind)?.meta.ui?.label
1713
+ return typeName ? processI18n(typeName) : (node.config?.name as string | undefined) ?? node.kind
1714
+ }
1715
+
1716
+ function walkAll(graph: ProcedureGraph | undefined): GraphNode[] {
1717
+ if (!graph) return []
1718
+ return graph.nodes.flatMap((n) => [n, ...walkAll(n.subgraph)])
1719
+ }
1720
+
1721
+ /** An issue in the user's language. */
1722
+ function issueText(issue: GraphIssue): string {
1723
+ const key = `dms_automation.editor.problems.codes.${issue.code}`
1724
+ return issue.code && te(key) ? t(key, issue.params ?? {}) : issue.message
1725
+ }
1726
+
1727
+ const dockIssues = computed<DockIssue[]>(() =>
1728
+ issues.value.map((issue) => ({
1729
+ ...issue,
1730
+ message: issueText(issue),
1731
+ nodeName: issue.nodeId ? nodeDisplayName(issue.nodeId) : undefined,
1732
+ })),
1733
+ )
1734
+
1735
+ // Code and params travel along: the inspector names a setting as its form does.
1736
+ const issuesByNode = computed<Record<string, Omit<GraphIssue, 'nodeId'>>>(() => {
1737
+ const out: Record<string, Omit<GraphIssue, 'nodeId'>> = {}
1738
+ for (const issue of issues.value) {
1739
+ if (!issue.nodeId) continue
1740
+ if (!out[issue.nodeId] || issue.severity === 'error')
1741
+ out[issue.nodeId] = { severity: issue.severity, message: issueText(issue), code: issue.code, params: issue.params }
1742
+ }
1743
+ return out
1744
+ })
1745
+
1746
+ const dockTab = ref<DockTab>('problems')
1747
+ // The dock stays out of the canvas's way until it has something to say: it
1748
+ // opens on its own for a problem that blocks enabling (a warning only counts
1749
+ // on its tab), and closes again once that is fixed, unless the user has
1750
+ // taken it over in between.
1751
+ const dockCollapsed = ref(true)
1752
+ let dockOpenedForProblems = false
1753
+ watch(
1754
+ () => blockingIssues.value.length,
1755
+ (count, before) => {
1756
+ if (count > 0 && !before) {
1757
+ dockTab.value = 'problems'
1758
+ dockCollapsed.value = false
1759
+ dockOpenedForProblems = true
1760
+ } else if (count === 0 && dockOpenedForProblems && dockTab.value === 'problems') {
1761
+ dockCollapsed.value = true
1652
1762
  }
1653
- toast.add({
1654
- title: 'Procedure deleted',
1655
- color: 'success',
1656
- icon: 'i-ph-check-circle',
1657
- })
1658
- } catch (e) {
1659
- toast.add({
1660
- title: 'Failed to delete procedure',
1661
- description: (e as Error).message,
1662
- color: 'error',
1663
- icon: 'i-ph-warning',
1664
- })
1763
+ },
1764
+ )
1765
+ watch([dockTab, dockCollapsed], () => {
1766
+ if (dockCollapsed.value || dockTab.value !== 'problems') dockOpenedForProblems = false
1767
+ })
1768
+
1769
+ function selectNode(id: string) {
1770
+ // A node inside a group is named by its top-level group in the issues.
1771
+ subgraphPath.value = subgraphPath.value.slice(0, 1)
1772
+ selectedNodeId.value = id
1773
+ }
1774
+
1775
+ interface ProcedureTriggers {
1776
+ triggers: Array<WordedTrigger & { nextAt: string | null }>
1777
+ }
1778
+ const savedTriggers = ref<ProcedureTriggers['triggers']>([])
1779
+
1780
+ async function loadSavedTriggers() {
1781
+ if (!selectedId.value || editorMode.value !== 'procedure') return
1782
+ try {
1783
+ const res = await $authFetch<ProcedureTriggers>(`${props.apiUrl}/procedures/${selectedId.value}/triggers`)
1784
+ savedTriggers.value = res.triggers
1785
+ } catch {
1786
+ savedTriggers.value = []
1665
1787
  }
1666
1788
  }
1667
1789
 
1668
- async function onSave() {
1669
- if (!selected.value) return
1670
- saving.value = true
1790
+ /** The banner of a disabled procedure names what will not fire (AU-16). */
1791
+ const pausedBanner = computed(() => {
1671
1792
  const current = selected.value
1672
- try {
1673
- if (editorMode.value === 'template') {
1674
- // Template save — the PUT route's Zod requires name + ports +
1675
- // subgraph and re-runs validateGraph + cycle detection. We send
1676
- // the in-memory state verbatim; description/icon are not edited
1677
- // from the procedure-style editor chrome yet (catalog page owns
1678
- // metadata edits) so we preserve whatever was loaded.
1679
- const body = {
1680
- name: current.name,
1681
- description: current.description,
1682
- icon: 'i-ph-package',
1683
- ports: templatePorts.value.map((p) => ({ ...p })),
1684
- subgraph: current.graph,
1685
- }
1686
- await $authFetch(`/api/automation/templates/${current._id}`, {
1687
- method: 'PUT',
1688
- body,
1689
- })
1690
- savedSnapshot.value = takeSnapshot(current)
1691
- toast.add({
1692
- title: 'Template saved',
1693
- description: current.name,
1694
- color: 'success',
1695
- icon: 'i-ph-check-circle',
1696
- })
1697
- return
1698
- }
1699
- const body = {
1700
- name: current.name,
1701
- description: current.description,
1702
- enabled: current.enabled,
1703
- graph: current.graph,
1704
- }
1705
- await $authFetch(`/api/automation/procedures/${current._id}`, {
1706
- method: 'PUT',
1707
- body,
1708
- })
1709
- savedSnapshot.value = takeSnapshot(current)
1710
- toast.add({
1711
- title: 'Procedure saved',
1712
- description: current.name,
1713
- color: 'success',
1714
- icon: 'i-ph-check-circle',
1715
- })
1716
- } catch (e) {
1717
- toast.add({
1718
- title:
1719
- editorMode.value === 'template'
1720
- ? 'Failed to save template'
1721
- : 'Failed to save procedure',
1722
- description: (e as Error).message,
1723
- color: 'error',
1724
- icon: 'i-ph-warning',
1725
- })
1726
- } finally {
1727
- saving.value = false
1793
+ if (!current || current.enabled || editorMode.value !== 'procedure') return null
1794
+ const triggers = savedTriggers.value.filter((tr) => tr.typeId !== 'manual')
1795
+ if (triggers.length === 0) return null
1796
+ const first = triggers[0]!
1797
+ const what = processText(first.text)
1798
+ const isDraft = currentSummary.value?.status === 'draft'
1799
+ return {
1800
+ title: t(isDraft ? 'dms_automation.editor.paused.draftTitle' : 'dms_automation.editor.paused.title', { name: savedName.value }),
1801
+ description: first.nextAt
1802
+ ? t('dms_automation.editor.paused.schedule', {
1803
+ what,
1804
+ next: describeDateTime(first.nextAt, dateTimeFormat, first.timeZone),
1805
+ })
1806
+ : t('dms_automation.editor.paused.other', { what }),
1728
1807
  }
1808
+ })
1809
+
1810
+ async function enableNow() {
1811
+ if (!selected.value) return
1812
+ selected.value.enabled = true
1813
+ await onSave()
1814
+ }
1815
+
1816
+ const saveState = computed(() => {
1817
+ if (saving.value) return t('dms_automation.editor.saving')
1818
+ if (changeCount.value > 0) return t('dms_automation.editor.unsaved', { count: changeCount.value })
1819
+ return t('dms_automation.editor.saved')
1820
+ })
1821
+
1822
+ // ---------------------------------------------------------------------------
1823
+ // Create, delete, export
1824
+ // ---------------------------------------------------------------------------
1825
+
1826
+ async function onCreated(id: string) {
1827
+ await loadList()
1828
+ await loadSummaries()
1829
+ selectedId.value = id
1830
+ void router.replace(`${builderPath()}?selected=${id}`)
1831
+ }
1832
+
1833
+ async function onCreate() {
1834
+ if (!(await confirmDiscard())) return
1835
+ newProcedureOpen.value = true
1836
+ }
1837
+
1838
+ async function onDelete() {
1839
+ const current = selected.value
1840
+ if (!current) return
1841
+ const name = savedName.value
1842
+ // The server words the dialog, as the procedures table's delete does.
1843
+ await confirmFrom(`${props.apiUrl}/procedures/{id}/delete-confirm`, {
1844
+ params: { id: current._id },
1845
+ onConfirm: async () => {
1846
+ await $authFetch(`${props.apiUrl}/procedures/${current._id}`, { method: 'DELETE' })
1847
+ procedures.value = procedures.value.filter((p) => p._id !== current._id)
1848
+ selectedId.value = procedures.value[0]?._id ?? null
1849
+ void router.replace(selectedId.value ? `${builderPath()}?selected=${selectedId.value}` : builderPath())
1850
+ toast.add({ title: t('dms_automation.editor.deleted', { name }), color: 'success', icon: 'i-ph-check-circle' })
1851
+ void loadSummaries()
1852
+ },
1853
+ })
1854
+ }
1855
+
1856
+ async function onExport() {
1857
+ const current = selected.value
1858
+ if (!current) return
1859
+ const data = await $authFetch<unknown>(`${props.apiUrl}/procedures/${current._id}/export`)
1860
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
1861
+ const url = URL.createObjectURL(blob)
1862
+ const link = document.createElement('a')
1863
+ link.href = url
1864
+ link.download = `${current.name.replace(/[^\w-]+/g, '-').toLowerCase() || 'procedure'}.json`
1865
+ link.click()
1866
+ URL.revokeObjectURL(url)
1729
1867
  }
1730
1868
 
1731
1869
  // ---------------------------------------------------------------------------
1732
- // Save-as-template
1870
+ // Questions with more than a yes and a no: switching procedure with unsaved
1871
+ // changes (AU-04), running the saved version, a save refused for a newer one
1733
1872
  // ---------------------------------------------------------------------------
1734
- // Visible when the user has selected a single local group (kind === 'group',
1735
- // no templateId). On submit:
1736
- // 1. POST /api/automation/templates with { name, description, icon, ports,
1737
- // subgraph } from the local group.
1738
- // 2. On success: mutate the in-graph node — set templateId = res._id, drop
1739
- // subgraph. The save flow (onGraphUpdate → onSave by user) propagates.
1740
- // 3. On failure (Zod or template cycle): render the error body inline in
1741
- // the modal; the graph is NOT touched.
1742
- const selectedLocalGroupNode = computed<GraphNode | null>(() => {
1743
- const n = selectedNode.value
1744
- if (!n || n.kind !== 'group') return null
1745
- if (n.templateId) return null
1746
- return n
1747
- })
1748
1873
 
1749
- const canSaveAsTemplate = computed<boolean>(() => {
1750
- if (!selected.value) return false
1751
- if (isCurrentGraphReadOnly.value) return false
1752
- return selectedLocalGroupNode.value !== null
1874
+ interface Choice<C extends string> {
1875
+ value: C
1876
+ label: string
1877
+ color?: 'primary' | 'neutral' | 'error' | 'warning'
1878
+ variant?: 'solid' | 'outline' | 'ghost' | 'soft'
1879
+ }
1880
+
1881
+ interface ChoiceQuestion<C extends string> {
1882
+ title: string
1883
+ description: string
1884
+ choices: Choice<C>[]
1885
+ /** The answer of a dialog closed without choosing (Escape, ✕, a click outside). */
1886
+ dismiss: C
1887
+ }
1888
+
1889
+ const choiceDialog = ref<ChoiceQuestion<string> & { open: boolean; resolve?: (choice: string) => void }>({
1890
+ open: false,
1891
+ title: '',
1892
+ description: '',
1893
+ choices: [],
1894
+ dismiss: '',
1753
1895
  })
1754
1896
 
1755
- const saveAsTemplateOpen = ref<boolean>(false)
1756
- const saveAsTemplateName = ref<string>('')
1757
- const saveAsTemplateDescription = ref<string>('')
1758
- const saveAsTemplateIcon = ref<string>('i-ph-package')
1759
- const saveAsTemplateSubmitting = ref<boolean>(false)
1760
- const saveAsTemplateError = ref<string | null>(null)
1897
+ function askChoice<C extends string>(question: ChoiceQuestion<C>): Promise<C> {
1898
+ return new Promise((resolve) => {
1899
+ choiceDialog.value = { ...question, open: true, resolve: resolve as (choice: string) => void }
1900
+ })
1901
+ }
1761
1902
 
1762
- function openSaveAsTemplate() {
1763
- const n = selectedLocalGroupNode.value
1764
- if (!n) return
1765
- saveAsTemplateName.value =
1766
- (n.config?.name as string | undefined) ?? 'Template'
1767
- saveAsTemplateDescription.value = ''
1768
- saveAsTemplateIcon.value = 'i-ph-package'
1769
- saveAsTemplateError.value = null
1770
- saveAsTemplateSubmitting.value = false
1771
- saveAsTemplateOpen.value = true
1903
+ /** The dialog opens on its safe answer: Enter keeps the draft, runs nothing. */
1904
+ function focusSafeChoice(event: Event) {
1905
+ event.preventDefault()
1906
+ void nextTick(() => document.querySelector<HTMLElement>('[data-safe-choice]')?.focus())
1772
1907
  }
1773
1908
 
1774
- // Render the 400 body from src/routes/templates.ts:
1775
- // - Zod failure → { error: 'invalid body', issues: ZodIssue[] }
1776
- // - validateGraph failure → { error: 'invalid graph', issues: string[] }
1777
- // - cycle → { error: 'template reference cycle', cycle: string[] }
1778
- // Other errors (network, 401, 500) fall back to the message string.
1909
+ /** Escape, ✕ or a click outside answers the question's `dismiss`. */
1910
+ function onChoiceDialogOpen(open: boolean) {
1911
+ if (!open && choiceDialog.value.open) answerChoice(choiceDialog.value.dismiss)
1912
+ }
1913
+
1914
+ function answerChoice(choice: string) {
1915
+ const resolve = choiceDialog.value.resolve
1916
+ choiceDialog.value = { ...choiceDialog.value, open: false, resolve: undefined }
1917
+ resolve?.(choice)
1918
+ }
1919
+
1920
+ /** Resolves `true` when the draft may be left: saved, discarded or clean. */
1921
+ async function confirmDiscard(): Promise<boolean> {
1922
+ if (!isDirty.value) return true
1923
+ const choice = await askChoice({
1924
+ title: t('dms_automation.editor.leave.title', { name: savedName.value }),
1925
+ description: t('dms_automation.editor.leave.description', { count: changeCount.value }),
1926
+ choices: [
1927
+ { value: 'discard', label: t('dms_automation.editor.discard'), color: 'error', variant: 'ghost' },
1928
+ { value: 'stay', label: t('dms_automation.editor.leave.keep'), color: 'neutral', variant: 'outline' },
1929
+ { value: 'save', label: t('dms_automation.editor.leave.save'), color: 'primary' },
1930
+ ],
1931
+ dismiss: 'stay',
1932
+ })
1933
+ if (choice === 'stay') return false
1934
+ if (choice === 'save') return await onSave()
1935
+ onCancel()
1936
+ return true
1937
+ }
1938
+
1939
+ async function onPickProcedure(id: string) {
1940
+ if (!(await confirmDiscard())) return
1941
+ selectedId.value = id
1942
+ void router.replace(`${builderPath()}?selected=${id}`)
1943
+ }
1944
+
1945
+ // The template editor guards its draft like the procedure editor.
1946
+ watch(isDirty, (dirty) => (unsavedDraft.value = dirty), { immediate: true })
1947
+
1948
+ // The DMS leave guard only holds a visit to another path. A visit to the
1949
+ // builder itself that remounts it (the sidebar's "Builder", a link with
1950
+ // another ?selected=), or that keeps it mounted but opens another procedure,
1951
+ // loses the draft just the same: it is held here and run again once the
1952
+ // draft is saved or discarded. The builder's own URL updates go through.
1953
+ interface PendingVisit {
1954
+ url?: URL
1955
+ method?: string
1956
+ prefetch?: boolean
1957
+ preserveState?: unknown
1958
+ replace?: boolean
1959
+ }
1960
+
1961
+ function onInertiaBefore(event: Event) {
1962
+ const visit = (event as CustomEvent<{ visit?: PendingVisit }>).detail?.visit
1963
+ if (!visit?.url || visit.prefetch) return
1964
+ if (visit.method && visit.method.toLowerCase() !== 'get') return
1965
+ if (visit.url.pathname !== builderPath() || !isDirty.value) return
1966
+ const keepsPage = visit.preserveState === true
1967
+ if (keepsPage && !opensAnotherProcedure(visit.url.searchParams.get('selected'))) return
1968
+ event.preventDefault()
1969
+ const href = `${visit.url.pathname}${visit.url.search}${visit.url.hash}`
1970
+ void confirmDiscard().then((leave) => {
1971
+ if (leave) void navigateDms(href, { preserveState: keepsPage, replace: visit.replace })
1972
+ })
1973
+ }
1974
+
1975
+ function opensAnotherProcedure(id: string | null): id is string {
1976
+ return editorMode.value === 'procedure' && !!id && id !== selectedId.value
1977
+ }
1978
+
1979
+ // Back and Forward between two addresses of the builder: the DMS guard lets
1980
+ // them through (same path). Where the browser announces them before they
1981
+ // happen (Navigation API), the draft is asked about first and the step is
1982
+ // taken again once it is saved or discarded. A browser without it remounts
1983
+ // the page on the step: the DMS guard has the same gap.
1984
+ interface TraverseEvent extends Event {
1985
+ navigationType?: string
1986
+ destination?: { url: string; key: string; sameDocument: boolean }
1987
+ }
1988
+
1989
+ interface NavigationLike extends EventTarget {
1990
+ traverseTo: (key: string) => unknown
1991
+ }
1992
+
1993
+ function browserNavigation(): NavigationLike | undefined {
1994
+ return typeof window === 'undefined' ? undefined : (window as unknown as { navigation?: NavigationLike }).navigation
1995
+ }
1996
+
1997
+ // Set while the history step the user chose to take is taken again.
1998
+ let traverseAllowed = false
1999
+
2000
+ function onNavigate(event: Event) {
2001
+ const { navigationType, destination } = event as TraverseEvent
2002
+ if (navigationType !== 'traverse' || !destination) return
2003
+ if (traverseAllowed) {
2004
+ traverseAllowed = false
2005
+ return
2006
+ }
2007
+ if (!destination.sameDocument || !event.cancelable || !isDirty.value) return
2008
+ if (new URL(destination.url).pathname !== builderPath()) return
2009
+ event.preventDefault()
2010
+ void confirmDiscard().then((leave) => {
2011
+ if (!leave) return
2012
+ traverseAllowed = true
2013
+ void browserNavigation()?.traverseTo(destination.key)
2014
+ })
2015
+ }
2016
+
2017
+ // ?selected= changed while the page stayed mounted (a visit that keeps it,
2018
+ // such as a link to the builder from the builder): the builder opens that
2019
+ // procedure. A draft is asked about first; keeping it puts the address back.
2020
+ watch(
2021
+ () => queryValue('selected'),
2022
+ async (id) => {
2023
+ if (!opensAnotherProcedure(id)) return
2024
+ if (!(await confirmDiscard())) {
2025
+ void router.replace(`${builderPath()}?selected=${selectedId.value}`)
2026
+ return
2027
+ }
2028
+ if (procedures.value.some((p) => p._id === id)) {
2029
+ selectedId.value = id
2030
+ return
2031
+ }
2032
+ missingProcedureId.value = id
2033
+ selectedId.value = null
2034
+ switcherOpen.value = true
2035
+ },
2036
+ )
2037
+
2038
+ // ---------------------------------------------------------------------------
2039
+ // Save
2040
+ // ---------------------------------------------------------------------------
2041
+
2042
+ interface SaveRefusal {
2043
+ data?: {
2044
+ issues?: Array<
2045
+ | { severity?: string; message?: string; code?: string; params?: Record<string, unknown>; nodeId?: string; path?: unknown[] }
2046
+ | string
2047
+ >
2048
+ }
2049
+ }
2050
+
2051
+ function issuesOf(error: unknown): GraphIssue[] | null {
2052
+ const raw = (error as SaveRefusal)?.data?.issues
2053
+ if (!Array.isArray(raw)) return null
2054
+ // A field of the body other than the graph (zod issues carry its path) is
2055
+ // not a problem of the graph.
2056
+ if (raw.some((issue) => typeof issue === 'object' && Array.isArray(issue.path) && issue.path[0] !== 'graph')) return null
2057
+ return raw.map((issue) =>
2058
+ typeof issue === 'string'
2059
+ ? { severity: 'error' as const, message: issue }
2060
+ : {
2061
+ severity: issue.severity === 'warning' ? 'warning' : 'error',
2062
+ message: issue.message ?? '',
2063
+ code: issue.code,
2064
+ params: issue.params,
2065
+ nodeId: issue.nodeId,
2066
+ },
2067
+ )
2068
+ }
2069
+
2070
+ /** Save the open procedure (or template). Resolves whether it was saved. */
2071
+ async function onSave(): Promise<boolean> {
2072
+ if (!selected.value) return false
2073
+ if (nameMissing.value) {
2074
+ document.getElementById(NAME_INPUT_ID)?.focus()
2075
+ return false
2076
+ }
2077
+ saving.value = true
2078
+ const current = selected.value
2079
+ // What is sent is what counts as saved: a change made while the request
2080
+ // runs stays an unsaved change.
2081
+ const sent = takeSnapshot(current)
2082
+ try {
2083
+ if (editorMode.value === 'template') {
2084
+ await $authFetch(`${props.apiUrl}/templates/${current._id}`, {
2085
+ method: 'PUT',
2086
+ body: {
2087
+ name: sent.name,
2088
+ description: current.description,
2089
+ icon: templateIcon.value,
2090
+ ports: sent.ports ?? [],
2091
+ subgraph: sent.graph,
2092
+ },
2093
+ })
2094
+ savedSnapshot.value = sent
2095
+ toast.add({ title: t('dms_automation.templates.saved', { name: sent.name }), color: 'success', icon: 'i-ph-check-circle' })
2096
+ return true
2097
+ }
2098
+ const res = await $authFetch<{ version: number; revision: number; issues?: GraphIssue[] }>(`${props.apiUrl}/procedures/${current._id}`, {
2099
+ method: 'PUT',
2100
+ body: {
2101
+ name: sent.name,
2102
+ description: current.description,
2103
+ enabled: sent.enabled,
2104
+ graph: sent.graph,
2105
+ expectedRevision: current.revision,
2106
+ },
2107
+ })
2108
+ current.version = res.version
2109
+ current.revision = res.revision
2110
+ savedSnapshot.value = sent
2111
+ if (res.issues) issues.value = res.issues
2112
+ toast.add({
2113
+ title: t('dms_automation.editor.savedToast', { name: sent.name }),
2114
+ description: res.issues?.length ? t('dms_automation.editor.savedWithProblems', { count: res.issues.length }) : undefined,
2115
+ color: 'success',
2116
+ icon: 'i-ph-check-circle',
2117
+ actions: [{ label: t('dms_automation.editor.testRun'), onClick: () => void onTestRun() }],
2118
+ })
2119
+ void loadSummaries()
2120
+ void loadSavedTriggers()
2121
+ return true
2122
+ } catch (e) {
2123
+ if (editorMode.value === 'procedure' && apiErrorStatus(e) === 409) return await resolveStale(current, e)
2124
+ const refused = issuesOf(e)
2125
+ if (refused) {
2126
+ issues.value = refused
2127
+ saveBlocked.value = true
2128
+ dockTab.value = 'problems'
2129
+ dockCollapsed.value = false
2130
+ } else {
2131
+ toast.add({
2132
+ title: editorMode.value === 'template' ? t('dms_automation.templates.saveError') : t('dms_automation.editor.saveError'),
2133
+ description: describeApiError(e),
2134
+ color: 'error',
2135
+ icon: 'i-ph-warning',
2136
+ })
2137
+ }
2138
+ return false
2139
+ } finally {
2140
+ saving.value = false
2141
+ }
2142
+ }
2143
+
2144
+ /**
2145
+ * The procedure was saved elsewhere (another tab, a pause from the list)
2146
+ * since this draft was loaded, and the server refused to overwrite it:
2147
+ * reload what is saved now, or overwrite it with the draft.
2148
+ */
2149
+ async function resolveStale(current: ProcedureRecord, error: unknown): Promise<boolean> {
2150
+ saving.value = false
2151
+ let latest = (error as { data: { revision: number } }).data.revision
2152
+ const choice = await askChoice({
2153
+ title: t('dms_automation.editor.stale.title', { name: savedName.value }),
2154
+ description: t('dms_automation.editor.stale.description'),
2155
+ choices: [
2156
+ { value: 'stay', label: t('dms_automation.editor.stale.keep'), color: 'neutral', variant: 'ghost' },
2157
+ { value: 'reload', label: t('dms_automation.editor.stale.reload'), color: 'neutral', variant: 'outline' },
2158
+ { value: 'overwrite', label: t('dms_automation.editor.stale.overwrite'), color: 'warning' },
2159
+ ],
2160
+ dismiss: 'stay',
2161
+ })
2162
+ if (choice === 'overwrite') {
2163
+ // Overwriting puts the draft's edits over what was saved elsewhere, not
2164
+ // its on/off state over a pause or a resume made elsewhere: unless the
2165
+ // switch was flipped in this draft, the procedure stays as it is now.
2166
+ if (current.enabled === savedSnapshot.value?.enabled) {
2167
+ try {
2168
+ const saved = await $authFetch<{ enabled: boolean; revision: number }>(`${props.apiUrl}/procedures/${current._id}`)
2169
+ current.enabled = saved.enabled
2170
+ latest = saved.revision
2171
+ } catch {
2172
+ // Unreadable: the draft's state is saved, as before.
2173
+ }
2174
+ }
2175
+ current.revision = latest
2176
+ return await onSave()
2177
+ }
2178
+ if (choice === 'reload') await reloadSelected()
2179
+ return false
2180
+ }
2181
+
2182
+ /** Replaces the draft with the procedure as it is saved now. */
2183
+ async function reloadSelected() {
2184
+ const current = selected.value
2185
+ if (!current) return
2186
+ try {
2187
+ const fresh = await $authFetch<ProcedureRecord>(`${props.apiUrl}/procedures/${current._id}`)
2188
+ procedures.value = procedures.value.map((p) => (p._id === fresh._id ? fresh : p))
2189
+ selectedNodeId.value = null
2190
+ initHistoryAndSaved()
2191
+ seedSubgraphPath()
2192
+ saveBlocked.value = false
2193
+ void loadSummaries()
2194
+ void loadSavedTriggers()
2195
+ } catch (e) {
2196
+ toast.add({ title: t('dms_automation.editor.loadProceduresError'), description: describeApiError(e), color: 'error', icon: 'i-ph-warning' })
2197
+ }
2198
+ }
2199
+
2200
+ /** Set when a save was refused for problems: the banner offers the way out. */
2201
+ const saveBlocked = ref(false)
2202
+ watch(blockingIssues, (list) => {
2203
+ if (list.length === 0) saveBlocked.value = false
2204
+ })
2205
+
2206
+ async function saveAsDraft() {
2207
+ if (!selected.value) return
2208
+ selected.value.enabled = false
2209
+ if (await onSave()) saveBlocked.value = false
2210
+ }
2211
+
2212
+ function goToFirstProblem() {
2213
+ const first = blockingIssues.value.find((i) => i.nodeId) ?? issues.value.find((i) => i.nodeId)
2214
+ if (first?.nodeId) selectNode(first.nodeId)
2215
+ }
2216
+
2217
+
2218
+ // ---------------------------------------------------------------------------
2219
+ // Save-as-template
2220
+ // ---------------------------------------------------------------------------
2221
+ // Visible when the user has selected a single local group (kind === 'group',
2222
+ // no templateId). On submit:
2223
+ // 1. POST /api/automation/templates with { name, description, icon, ports,
2224
+ // subgraph } from the local group.
2225
+ // 2. On success: mutate the in-graph node — set templateId = res._id, drop
2226
+ // subgraph. The save flow (onGraphUpdate → onSave by user) propagates.
2227
+ // 3. On failure (Zod or template cycle): render the error body inline in
2228
+ // the modal; the graph is NOT touched.
2229
+ const selectedLocalGroupNode = computed<GraphNode | null>(() => {
2230
+ const n = selectedNode.value
2231
+ if (!n || n.kind !== 'group') return null
2232
+ if (n.templateId) return null
2233
+ return n
2234
+ })
2235
+
2236
+ const canSaveAsTemplate = computed<boolean>(() => {
2237
+ if (!selected.value) return false
2238
+ if (isCurrentGraphReadOnly.value) return false
2239
+ return selectedLocalGroupNode.value !== null
2240
+ })
2241
+
2242
+ const saveAsTemplateOpen = ref<boolean>(false)
2243
+ const saveAsTemplateName = ref<string>('')
2244
+ const saveAsTemplateDescription = ref<string>('')
2245
+ const saveAsTemplateIcon = ref<string>('i-ph-package')
2246
+ const saveAsTemplateSubmitting = ref<boolean>(false)
2247
+ const saveAsTemplateError = ref<string | null>(null)
2248
+ const TEMPLATE_NAME_ID = 'save-template-name'
2249
+ const TEMPLATE_ROW = { layout: 'form', spacing: 'list', inset: false } as const
2250
+ // A missing name shows under its field; what the server refuses (issues, a
2251
+ // reference cycle) stays in the banner above the buttons.
2252
+ const templateFieldErrors = useFieldErrors({ fields: { name: TEMPLATE_NAME_ID } })
2253
+ watch(saveAsTemplateName, () => templateFieldErrors.clear('name'))
2254
+
2255
+ function openSaveAsTemplate() {
2256
+ const n = selectedLocalGroupNode.value
2257
+ if (!n) return
2258
+ saveAsTemplateName.value = groupName(n)
2259
+ saveAsTemplateDescription.value = ''
2260
+ saveAsTemplateIcon.value = 'i-ph-package'
2261
+ saveAsTemplateError.value = null
2262
+ templateFieldErrors.clear()
2263
+ saveAsTemplateSubmitting.value = false
2264
+ saveAsTemplateOpen.value = true
2265
+ }
2266
+
2267
+ // Render the 400 body from src/routes/templates.ts:
2268
+ // - Zod failure → { error: 'invalid body', issues: ZodIssue[] }
2269
+ // - validateGraph failure → { error: 'invalid graph', issues: string[] }
2270
+ // - cycle → { error: 'template reference cycle', cycle: string[] }
2271
+ // Other errors (network, 401, 500) fall back to the message string.
1779
2272
  function formatTemplateError(err: unknown): string {
1780
2273
  const data = (err as { data?: unknown; message?: string } | undefined)?.data as
1781
2274
  | {
@@ -1800,7 +2293,7 @@ function formatTemplateError(err: unknown): string {
1800
2293
  }
1801
2294
  return head
1802
2295
  }
1803
- return (err as Error).message ?? 'Failed to save template'
2296
+ return describeApiError(err)
1804
2297
  }
1805
2298
 
1806
2299
  function convertLocalGroupToTemplateInstance(
@@ -1821,11 +2314,11 @@ async function submitSaveAsTemplate() {
1821
2314
  if (!n) return
1822
2315
  const name = saveAsTemplateName.value.trim()
1823
2316
  if (!name) {
1824
- saveAsTemplateError.value = 'Name is required'
2317
+ await templateFieldErrors.setError('name', t('dms_automation.editor.saveTemplateModal.nameRequired'))
1825
2318
  return
1826
2319
  }
1827
2320
  if (!n.subgraph) {
1828
- saveAsTemplateError.value = 'Group has no subgraph to save'
2321
+ saveAsTemplateError.value = t('dms_automation.editor.saveTemplateModal.noSubgraph')
1829
2322
  return
1830
2323
  }
1831
2324
  saveAsTemplateSubmitting.value = true
@@ -1842,14 +2335,20 @@ async function submitSaveAsTemplate() {
1842
2335
  '/api/automation/templates',
1843
2336
  { method: 'POST', body },
1844
2337
  )
2338
+ // The template exists now: the procedure links to it once saved. A
2339
+ // draft with nothing else unsaved is saved at once; one with other
2340
+ // changes is left to the user, who is told.
2341
+ const linkOnly = !isDirty.value
1845
2342
  convertLocalGroupToTemplateInstance(n.id, created._id)
1846
2343
  saveAsTemplateOpen.value = false
2344
+ void loadTemplates()
1847
2345
  toast.add({
1848
- title: 'Template saved',
1849
- description: name,
2346
+ title: t('dms_automation.templates.saved', { name }),
2347
+ description: linkOnly ? undefined : t('dms_automation.editor.saveTemplateModal.saveToLink'),
1850
2348
  color: 'success',
1851
2349
  icon: 'i-ph-check-circle',
1852
2350
  })
2351
+ if (linkOnly) await onSave()
1853
2352
  } catch (e) {
1854
2353
  saveAsTemplateError.value = formatTemplateError(e)
1855
2354
  } finally {
@@ -1987,7 +2486,7 @@ function formatForkError(err: unknown): string {
1987
2486
  }
1988
2487
  const data = (err as { data?: { error?: string } } | undefined)?.data
1989
2488
  if (data?.error) return data.error
1990
- return (err as Error).message ?? 'Failed to fork template instance'
2489
+ return describeApiError(err)
1991
2490
  }
1992
2491
 
1993
2492
  async function submitFork() {
@@ -2004,9 +2503,9 @@ async function submitFork() {
2004
2503
  convertTemplateInstanceToLocal(target, tpl)
2005
2504
  forkOpen.value = false
2006
2505
  toast.add({
2007
- title: 'Forked to local group',
2008
- description:
2009
- (target.node.config?.name as string | undefined) ?? tpl.name,
2506
+ title: t('dms_automation.editor.forked', {
2507
+ name: target.node.label || (target.node.config?.name as string | undefined) || tpl.name,
2508
+ }),
2010
2509
  color: 'success',
2011
2510
  icon: 'i-ph-check-circle',
2012
2511
  })
@@ -2017,11 +2516,12 @@ async function submitFork() {
2017
2516
  }
2018
2517
  }
2019
2518
 
2020
- // Tab / Shift+Tab / Escape keybindings for subgraph navigation. Tab enters
2021
- // the selected group (if eligible); Shift+Tab and Escape pop one level out.
2022
- // We ignore the key when focus is in an editable field (input, textarea,
2023
- // contenteditable, USelect popovers) so typing a literal Tab in the
2024
- // inspector still works.
2519
+ // Keyboard. With Ctrl (⌘ on macOS): S saves, Enter runs a test, P opens the
2520
+ // switcher, Z / Shift+Z / Y undo and redo, D duplicates the selected step, C
2521
+ // and V copy and paste the selection. Enter enters the selected group, Escape
2522
+ // leaves the debug view, then the group, then the selection. Tab is left to
2523
+ // the focus. Keys typed in a field, or while a dialog or a menu is open,
2524
+ // belong to them.
2025
2525
  function isEditableTarget(target: EventTarget | null): boolean {
2026
2526
  if (!(target instanceof HTMLElement)) return false
2027
2527
  const tag = target.tagName
@@ -2030,344 +2530,1017 @@ function isEditableTarget(target: EventTarget | null): boolean {
2030
2530
  return false
2031
2531
  }
2032
2532
 
2533
+ // Open overlays only: a closing dialog stays in the page while it animates
2534
+ // out, and a non-modal card (the DMS star prompt) has no state at all.
2535
+ const OVERLAY_SELECTOR = ':is([role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"])[data-state="open"]'
2536
+
2537
+ function isOverlayOpen(): boolean {
2538
+ return (
2539
+ saveAsTemplateOpen.value ||
2540
+ forkOpen.value ||
2541
+ switcherOpen.value ||
2542
+ runNowOpen.value ||
2543
+ newProcedureOpen.value ||
2544
+ choiceDialog.value.open ||
2545
+ document.querySelector(OVERLAY_SELECTOR) !== null
2546
+ )
2547
+ }
2548
+
2549
+ /**
2550
+ * Blurs the focused field so it commits what is typed in it (a JSON setting
2551
+ * or the step name only do on blur), and returns it to focus again after.
2552
+ */
2553
+ async function commitFocusedField(): Promise<HTMLElement | null> {
2554
+ const field = document.activeElement
2555
+ if (!(field instanceof HTMLElement) || !isEditableTarget(field)) return null
2556
+ field.blur()
2557
+ await nextTick()
2558
+ return field
2559
+ }
2560
+
2561
+ async function saveFromKeyboard() {
2562
+ const field = await commitFocusedField()
2563
+ if (isDirty.value) await onSave()
2564
+ field?.focus()
2565
+ }
2566
+
2567
+ async function testRunFromKeyboard() {
2568
+ const field = await commitFocusedField()
2569
+ await onTestRun()
2570
+ field?.focus()
2571
+ }
2572
+
2573
+ // Ctrl+C / Ctrl+V: the selected steps and the wires between them, pasted as
2574
+ // new steps beside the originals, in this graph or another one.
2575
+ let clipboard: ProcedureGraph | null = null
2576
+
2577
+ function copySelection(): boolean {
2578
+ const g = currentGraph.value
2579
+ const ids = new Set(selectedNodeIds.value.length > 0 ? selectedNodeIds.value : selectedNodeId.value ? [selectedNodeId.value] : [])
2580
+ if (!g || ids.size === 0) return false
2581
+ const nodes = g.nodes.filter((n) => ids.has(n.id) && n.kind !== 'groupInput' && n.kind !== 'groupOutput')
2582
+ if (nodes.length === 0) return false
2583
+ const kept = new Set(nodes.map((n) => n.id))
2584
+ clipboard = cloneGraph({
2585
+ nodes,
2586
+ triggerEdges: g.triggerEdges.filter((e) => kept.has(e.from.node) && kept.has(e.to.node)),
2587
+ dataEdges: g.dataEdges.filter((e) => kept.has(e.from.node) && kept.has(e.to.node)),
2588
+ })
2589
+ return true
2590
+ }
2591
+
2592
+ function pasteClipboard(): boolean {
2593
+ const g = currentGraph.value
2594
+ if (!g || !clipboard || isCurrentGraphReadOnly.value) return false
2595
+ // Triggers only live at the top level of a procedure.
2596
+ const triggersAllowed = editorMode.value === 'procedure' && subgraphPath.value.length <= 1
2597
+ // Each paste lands one step further, like Duplicate.
2598
+ clipboard.nodes = clipboard.nodes.map((n) => ({ ...n, position: { x: n.position.x + 40, y: n.position.y + 60 } }))
2599
+ const source = cloneGraph(clipboard)
2600
+ const nodes = source.nodes.filter((n) => triggersAllowed || n.kind !== 'trigger')
2601
+ if (nodes.length === 0) return false
2602
+ const ids = new Map(nodes.map((n) => [n.id, newId()]))
2603
+ const idOf = (id: string) => ids.get(id)!
2604
+ const pasted = nodes.map((n) => ({ ...n, id: idOf(n.id) }))
2605
+ const triggerEdges = source.triggerEdges
2606
+ .filter((e) => ids.has(e.from.node) && ids.has(e.to.node))
2607
+ .map((e) => ({ ...e, id: newId(), from: { ...e.from, node: idOf(e.from.node) }, to: { ...e.to, node: idOf(e.to.node) } }))
2608
+ const dataEdges = source.dataEdges
2609
+ .filter((e) => ids.has(e.from.node) && ids.has(e.to.node))
2610
+ .map((e) => ({ ...e, id: newId(), from: { ...e.from, node: idOf(e.from.node) }, to: { ...e.to, node: idOf(e.to.node) } }))
2611
+ onGraphUpdate({
2612
+ ...g,
2613
+ nodes: [...g.nodes, ...pasted],
2614
+ triggerEdges: [...g.triggerEdges, ...triggerEdges],
2615
+ dataEdges: [...g.dataEdges, ...dataEdges],
2616
+ })
2617
+ selectedNodeId.value = pasted.at(-1)!.id
2618
+ return true
2619
+ }
2620
+
2621
+ /** The editing shortcuts, on the canvas: whatever is not typed in a field. */
2622
+ function onEditShortcut(ev: KeyboardEvent, key: string): boolean {
2623
+ if (isEditableTarget(ev.target)) return false
2624
+ if (key === 'z' || key === 'y') {
2625
+ if (key === 'y' || ev.shiftKey) onRedo()
2626
+ else onUndo()
2627
+ return true
2628
+ }
2629
+ if (key === 'd') {
2630
+ const node = selectedNode.value
2631
+ if (node && node.kind !== 'groupInput' && node.kind !== 'groupOutput') onDuplicateNode({ id: node.id })
2632
+ return true
2633
+ }
2634
+ // A text selected on the page is copied as text.
2635
+ if (key === 'c') return !window.getSelection()?.toString() && copySelection()
2636
+ if (key === 'v') return pasteClipboard()
2637
+ return false
2638
+ }
2639
+
2640
+ // Listened to in the capture phase, so a focused field (a select opens on
2641
+ // Enter) never sees a shortcut meant for the builder.
2642
+ function onShortcut(ev: KeyboardEvent): boolean {
2643
+ if (!(ev.metaKey || ev.ctrlKey) || ev.altKey) return false
2644
+ const key = ev.key.toLowerCase()
2645
+ // The browser's "Save page" is never what Ctrl+S means here.
2646
+ if (key === 's') ev.preventDefault()
2647
+ if (isOverlayOpen()) return false
2648
+ if (['s', 'enter', 'p'].includes(key)) ev.stopPropagation()
2649
+ if (key === 's') {
2650
+ void saveFromKeyboard()
2651
+ return true
2652
+ }
2653
+ if (key === 'enter' && editorMode.value === 'procedure') {
2654
+ ev.preventDefault()
2655
+ void testRunFromKeyboard()
2656
+ return true
2657
+ }
2658
+ if (key === 'p' && editorMode.value === 'procedure') {
2659
+ ev.preventDefault()
2660
+ switcherOpen.value = true
2661
+ return true
2662
+ }
2663
+ if (onEditShortcut(ev, key)) {
2664
+ ev.preventDefault()
2665
+ ev.stopPropagation()
2666
+ return true
2667
+ }
2668
+ return false
2669
+ }
2670
+
2671
+ /** Enter belongs to a focused button or link; elsewhere it enters a group. */
2672
+ function isActivatable(target: EventTarget | null): boolean {
2673
+ return target instanceof Element && target.closest('button, a[href], [role="button"], [role="tab"], [role="menuitem"], [role="option"]') !== null
2674
+ }
2675
+
2033
2676
  function onKeyDown(ev: KeyboardEvent) {
2034
- if (isEditableTarget(ev.target)) return
2035
- // Modal / drawer open → don't hijack keys.
2036
- if (saveAsTemplateOpen.value || forkOpen.value || showProcedures.value) return
2037
- if (ev.key === 'Tab' && !ev.shiftKey) {
2038
- if (!canEnterGroup.value) return
2677
+ if (onShortcut(ev)) return
2678
+ if (isEditableTarget(ev.target) || isOverlayOpen()) return
2679
+ if (ev.key === 'Enter' && !ev.shiftKey && !ev.ctrlKey && !ev.metaKey && !ev.altKey) {
2680
+ if (!canEnterGroup.value || isActivatable(ev.target)) return
2039
2681
  ev.preventDefault()
2040
2682
  enterSelectedGroup()
2041
2683
  return
2042
2684
  }
2043
- if ((ev.key === 'Tab' && ev.shiftKey) || ev.key === 'Escape') {
2044
- if (subgraphPath.value.length <= 1) return
2685
+ if (ev.key !== 'Escape') return
2686
+ if (overlayRun.value && subgraphPath.value.length <= 1) {
2687
+ ev.preventDefault()
2688
+ exitDebug()
2689
+ } else if (subgraphPath.value.length > 1) {
2045
2690
  ev.preventDefault()
2046
2691
  exitSubgraph()
2692
+ } else if (selectedNodeId.value) {
2693
+ ev.preventDefault()
2694
+ selectedNodeId.value = null
2047
2695
  }
2048
2696
  }
2049
2697
 
2050
2698
  onMounted(() => {
2051
2699
  if (typeof window === 'undefined') return
2052
- window.addEventListener('keydown', onKeyDown)
2700
+ window.addEventListener('keydown', onKeyDown, { capture: true })
2701
+ document.addEventListener('inertia:before', onInertiaBefore)
2702
+ browserNavigation()?.addEventListener('navigate', onNavigate)
2053
2703
  })
2054
2704
  onBeforeUnmount(() => {
2055
2705
  if (typeof window === 'undefined') return
2056
- window.removeEventListener('keydown', onKeyDown)
2706
+ window.removeEventListener('keydown', onKeyDown, { capture: true })
2707
+ document.removeEventListener('inertia:before', onInertiaBefore)
2708
+ browserNavigation()?.removeEventListener('navigate', onNavigate)
2057
2709
  })
2058
2710
 
2059
- async function onRun() {
2060
- if (!selected.value) return
2061
- running.value = true
2062
- const id = selected.value._id
2711
+ // ---------------------------------------------------------------------------
2712
+ // Runs over the canvas: Test run of the draft, debugging a stored run (AU-05)
2713
+ // ---------------------------------------------------------------------------
2714
+
2715
+ const recentRuns = ref<DockRun[]>([])
2716
+
2717
+ async function loadRecentRuns() {
2718
+ if (!selectedId.value || editorMode.value !== 'procedure') return
2719
+ try {
2720
+ const list = await $authFetch<DockRun[]>(`${props.apiUrl}/procedures/${selectedId.value}/runs?limit=8`)
2721
+ recentRuns.value = Array.isArray(list) ? list.slice(0, 8) : []
2722
+ } catch {
2723
+ recentRuns.value = []
2724
+ }
2725
+ }
2726
+
2727
+ /** The run shown over the canvas, and whether it is a test of the draft. */
2728
+ const overlayRun = ref<RunDetail | null>(null)
2729
+ const overlayIsTest = ref(false)
2730
+ const testing = ref(false)
2731
+ const testPayload = ref('{}')
2732
+ const testPayloadSource = ref<string | null>(null)
2733
+ // The trigger a Test run starts from, chosen in the dock (see the watch on
2734
+ // the draft's triggers at the end).
2735
+ const testTriggerNodeId = ref<string | undefined>(undefined)
2736
+
2737
+ async function loadTestPayload() {
2738
+ if (!selectedId.value || editorMode.value !== 'procedure') return
2739
+ const query = testTriggerNodeId.value ? `?triggerNodeId=${encodeURIComponent(testTriggerNodeId.value)}` : ''
2063
2740
  try {
2064
- const res = await $authFetch<{ runId: string }>(
2065
- `/api/automation/procedures/${id}/run`,
2066
- { method: 'POST', body: {} },
2741
+ const res = await $authFetch<{ last: { runId: string; payload: unknown } | null }>(
2742
+ `${props.apiUrl}/procedures/${selectedId.value}/last-payload${query}`,
2067
2743
  )
2068
- toast.add({
2069
- title: 'Run started',
2070
- description: res.runId ? `runId: ${res.runId}` : id,
2071
- color: 'success',
2072
- icon: 'i-ph-play-circle',
2744
+ testPayload.value = JSON.stringify(res.last?.payload ?? {}, null, 2)
2745
+ testPayloadSource.value = res.last?.runId ?? null
2746
+ } catch {
2747
+ testPayload.value = '{}'
2748
+ testPayloadSource.value = null
2749
+ }
2750
+ }
2751
+
2752
+ const runStates = computed<Record<string, NodeRunState> | undefined>(() => {
2753
+ const run = overlayRun.value
2754
+ if (!run || subgraphPath.value.length > 1) return undefined
2755
+ const out: Record<string, NodeRunState> = {}
2756
+ for (const step of run.trace.steps) {
2757
+ const id = step.nodeId.split('__')[0]!
2758
+ const previous = out[id]
2759
+ const status = step.status === 'failed' ? 'failed' : 'ok'
2760
+ if (!previous || status === 'failed') {
2761
+ out[id] = { status, durationMs: (previous?.durationMs ?? 0) + (step.durationMs ?? 0) }
2762
+ }
2763
+ }
2764
+ for (const skipped of run.trace.skipped) out[skipped.nodeId] = { status: 'skipped' }
2765
+ return out
2766
+ })
2767
+
2768
+ const overlaySteps = computed<TraceStep[] | null>(() => (overlayIsTest.value ? (overlayRun.value?.trace.steps ?? null) : null))
2769
+
2770
+ // The dock's "Test run" tab only exists while a test run is on screen.
2771
+ watch(overlaySteps, (steps) => {
2772
+ if (!steps && dockTab.value === 'test') dockTab.value = 'problems'
2773
+ })
2774
+
2775
+ /** The step of the selected node in the run on screen, for the inspector. */
2776
+ const selectedRunStep = computed<TraceStep | null>(() => {
2777
+ const id = selectedNodeId.value
2778
+ const steps = overlayRun.value?.trace.steps ?? []
2779
+ if (!id) return null
2780
+ const own = steps.filter((s) => s.nodeId === id || s.nodeId.startsWith(`${id}__`))
2781
+ return own.find((s) => s.status === 'failed') ?? own.at(-1) ?? null
2782
+ })
2783
+
2784
+ const overlayLabel = computed(() => {
2785
+ const run = overlayRun.value
2786
+ if (!run) return ''
2787
+ const when = describeTime(run.startedAt, dateTimeFormat)
2788
+ return overlayIsTest.value
2789
+ ? t('dms_automation.editor.debug.testLabel', { when })
2790
+ : t('dms_automation.editor.debug.runLabel', { run: run._id.slice(-6), when })
2791
+ })
2792
+
2793
+ /** A real run of an older version than the one open says so. */
2794
+ const overlayDescription = computed(() => {
2795
+ const run = overlayRun.value
2796
+ const version = selected.value?.version
2797
+ if (!run || overlayIsTest.value || !run.procedureVersion || !version || run.procedureVersion === version) return overlayLabel.value
2798
+ return `${overlayLabel.value} · ${t('dms_automation.editor.debug.olderVersion', { run: run.procedureVersion, current: version })}`
2799
+ })
2800
+
2801
+ const overlaySummary = computed(() => {
2802
+ const run = overlayRun.value
2803
+ if (!run) return ''
2804
+ const duration = describeDuration(run.durationMs, locale.value)
2805
+ if (run.status === 'failed') {
2806
+ const step = stepTitle(run.failedStep, processI18n)
2807
+ return step
2808
+ ? t('dms_automation.editor.debug.failedAt', { step, duration })
2809
+ : t('dms_automation.editor.debug.failed', { duration })
2810
+ }
2811
+ return t('dms_automation.editor.debug.passed', { duration })
2812
+ })
2813
+
2814
+ /** Shows a stored run over the canvas; a test run is told by its kind. */
2815
+ function displayRun(run: RunDetail) {
2816
+ overlayRun.value = run
2817
+ overlayIsTest.value = run.kind === 'test'
2818
+ if (run.failedNodeId) selectNode(run.failedNodeId.split('__')[0]!)
2819
+ }
2820
+
2821
+ async function showRun(runId: string): Promise<RunDetail> {
2822
+ const run = await runsApi.getRun(runId)
2823
+ displayRun(run)
2824
+ return run
2825
+ }
2826
+
2827
+ /**
2828
+ * `?run=`: the run is shown over the procedure it ran, which the builder
2829
+ * opens if another one is asked; a run that no longer exists is said.
2830
+ */
2831
+ async function openRunFromUrl(runId: string) {
2832
+ const notFound = () => {
2833
+ toast.add({ title: t('dms_automation.editor.debug.runNotFound'), color: 'warning', icon: 'i-ph-warning' })
2834
+ exitDebug()
2835
+ }
2836
+ let run: RunDetail
2837
+ try {
2838
+ run = await runsApi.getRun(runId)
2839
+ } catch {
2840
+ notFound()
2841
+ return
2842
+ }
2843
+ if (run.procedureId !== selectedId.value) {
2844
+ if (!procedures.value.some((p) => p._id === run.procedureId)) {
2845
+ notFound()
2846
+ return
2847
+ }
2848
+ selectedId.value = run.procedureId
2849
+ // Switching clears the run on screen: show this one after it.
2850
+ await nextTick()
2851
+ }
2852
+ displayRun(run)
2853
+ }
2854
+
2855
+ function exitDebug() {
2856
+ overlayRun.value = null
2857
+ overlayIsTest.value = false
2858
+ if (queryValue('run')) void router.replace(`${builderPath()}?selected=${selectedId.value}`)
2859
+ }
2860
+
2861
+ async function onTestRun() {
2862
+ const current = selected.value
2863
+ // One test at a time: Ctrl+Enter pressed again waits for it.
2864
+ if (!current || editorMode.value !== 'procedure' || testing.value) return
2865
+ let payload: unknown
2866
+ try {
2867
+ payload = JSON.parse(testPayload.value || 'null')
2868
+ } catch {
2869
+ dockTab.value = 'payload'
2870
+ dockCollapsed.value = false
2871
+ toast.add({ title: t('dms_automation.editor.dock.invalidJson'), color: 'error', icon: 'i-ph-warning' })
2872
+ return
2873
+ }
2874
+ testing.value = true
2875
+ // The previous result leaves the canvas while this test runs.
2876
+ overlayRun.value = null
2877
+ overlayIsTest.value = false
2878
+ try {
2879
+ const res = await $authFetch<{ runId: string }>(`${props.apiUrl}/procedures/${current._id}/test`, {
2880
+ method: 'POST',
2881
+ body: { graph: current.graph, payload, triggerNodeId: testTriggerNodeId.value },
2073
2882
  })
2074
- // Reflect the freshly-queued run in the runs panel and its trigger badge.
2075
- runsDrawerRef.value?.reload()
2883
+ await showRun(res.runId)
2884
+ dockTab.value = 'test'
2885
+ dockCollapsed.value = false
2886
+ void loadRecentRuns()
2076
2887
  } catch (e) {
2077
- toast.add({
2078
- title: 'Failed to start run',
2079
- description: (e as Error).message,
2080
- color: 'error',
2081
- icon: 'i-ph-warning',
2082
- })
2888
+ const refused = issuesOf(e)
2889
+ if (refused) {
2890
+ issues.value = refused
2891
+ dockTab.value = 'problems'
2892
+ dockCollapsed.value = false
2893
+ }
2894
+ toast.add({ title: t('dms_automation.editor.testRunError'), description: describeApiError(e), color: 'error', icon: 'i-ph-warning' })
2083
2895
  } finally {
2084
- running.value = false
2896
+ testing.value = false
2897
+ }
2898
+ }
2899
+
2900
+ /** Run now runs the saved graph: with unsaved changes, say so first. */
2901
+ async function openRunNow() {
2902
+ if (!selected.value) return
2903
+ if (isDirty.value) {
2904
+ // Closing the question (Escape, ✕, a click outside) runs nothing.
2905
+ const choice = await askChoice({
2906
+ title: t('dms_automation.editor.runSaved.title'),
2907
+ description: t('dms_automation.editor.runSaved.description', { count: changeCount.value }),
2908
+ choices: [
2909
+ { value: 'cancel', label: t('dms_automation.common.cancel'), color: 'neutral', variant: 'ghost' },
2910
+ { value: 'test', label: t('dms_automation.editor.runSaved.testDraft'), color: 'neutral', variant: 'outline' },
2911
+ { value: 'saved', label: t('dms_automation.editor.runSaved.runSaved'), color: 'warning' },
2912
+ ],
2913
+ dismiss: 'cancel',
2914
+ })
2915
+ if (choice === 'cancel') return
2916
+ if (choice === 'test') {
2917
+ await onTestRun()
2918
+ return
2919
+ }
2920
+ }
2921
+ runNowOpen.value = true
2922
+ }
2923
+
2924
+ /** A run of the saved version ended: show it, and say how it went. */
2925
+ async function onRunStarted(runId: string) {
2926
+ const name = savedName.value
2927
+ const trace = { label: t('dms_automation.runs.trace'), onClick: () => void router.push(`${props.traceUrl}?run=${runId}`) }
2928
+ void loadRecentRuns()
2929
+ void loadSummaries()
2930
+ let run: RunDetail
2931
+ try {
2932
+ run = await showRun(runId)
2933
+ } catch {
2934
+ toast.add({ title: t('dms_automation.editor.runStarted', { name }), color: 'neutral', icon: 'i-ph-play-circle', actions: [trace] })
2935
+ return
2936
+ }
2937
+ const step = stepTitle(run.failedStep, processI18n)
2938
+ const failed = run.status === 'failed'
2939
+ toast.add({
2940
+ title: failed
2941
+ ? step
2942
+ ? t('dms_automation.editor.runFailedAt', { name, step })
2943
+ : t('dms_automation.editor.runFailed', { name })
2944
+ : t('dms_automation.editor.runSucceeded', { name }),
2945
+ color: failed ? 'error' : 'success',
2946
+ icon: failed ? 'i-ph-x-circle' : 'i-ph-check-circle',
2947
+ actions: [trace],
2948
+ })
2949
+ }
2950
+
2951
+ /**
2952
+ * Debugging a real run: once the fix is saved, run it again with the payload
2953
+ * it received, on the saved version, and show the new run in its place.
2954
+ */
2955
+ async function rerunOverlay() {
2956
+ const run = overlayRun.value
2957
+ if (!run || overlayIsTest.value) return
2958
+ let newRunId: string | null = null
2959
+ const confirmed = await confirm({
2960
+ title: t('dms_automation.runs.rerunConfirmTitle'),
2961
+ description: t('dms_automation.runs.rerunConfirmDescription'),
2962
+ color: 'warning',
2963
+ icon: 'i-ph-arrow-clockwise',
2964
+ confirmLabel: t('dms_automation.runs.rerun'),
2965
+ onConfirm: async () => {
2966
+ newRunId = (await runsApi.rerun(run._id)).runId
2967
+ },
2968
+ })
2969
+ if (!confirmed || !newRunId) return
2970
+ await onRunStarted(newRunId)
2971
+ if (queryValue('run')) void router.replace(`${builderPath()}?selected=${selectedId.value}&run=${newRunId}`)
2972
+ }
2973
+
2974
+ function openTrace(runId: string) {
2975
+ void router.push(`${props.traceUrl}?run=${runId}`)
2976
+ }
2977
+
2978
+ // ---------------------------------------------------------------------------
2979
+ // Node actions from the inspector
2980
+ // ---------------------------------------------------------------------------
2981
+
2982
+ function onDuplicateNode(payload: { id: string }) {
2983
+ const g = currentGraph.value
2984
+ if (!g || isCurrentGraphReadOnly.value) return
2985
+ const node = g.nodes.find((n) => n.id === payload.id)
2986
+ if (!node) return
2987
+ const copy: GraphNode = {
2988
+ ...cloneGraph({ nodes: [node], triggerEdges: [], dataEdges: [] }).nodes[0]!,
2989
+ id: newId(),
2990
+ position: { x: node.position.x + 40, y: node.position.y + 60 },
2991
+ }
2992
+ onGraphUpdate({ ...g, nodes: [...g.nodes, copy] })
2993
+ selectedNodeId.value = copy.id
2994
+ }
2995
+
2996
+ /** Put a Retry in front of a step: it now runs inside the Retry's body. */
2997
+ function onWrapInRetry(payload: { id: string }) {
2998
+ const g = currentGraph.value
2999
+ if (!g || isCurrentGraphReadOnly.value) return
3000
+ const node = g.nodes.find((n) => n.id === payload.id)
3001
+ if (!node) return
3002
+ const retry: GraphNode = {
3003
+ id: newId(),
3004
+ kind: 'retry',
3005
+ config: { maxAttempts: 3 },
3006
+ position: { x: node.position.x - 40, y: node.position.y - 140 },
3007
+ }
3008
+ const triggerEdges = g.triggerEdges.map((e) => {
3009
+ if (e.to.node === node.id) return { ...e, to: { ...e.to, node: retry.id } }
3010
+ if (e.from.node === node.id && (!e.from.branch || e.from.branch === 'main')) {
3011
+ return { ...e, from: { node: retry.id, branch: 'main' } }
3012
+ }
3013
+ return e
3014
+ })
3015
+ triggerEdges.push({ id: newId(), from: { node: retry.id, branch: 'body' }, to: { node: node.id } })
3016
+ onGraphUpdate({ ...g, nodes: [...g.nodes, retry], triggerEdges })
3017
+ selectedNodeId.value = retry.id
3018
+ }
3019
+
3020
+ // ---------------------------------------------------------------------------
3021
+ // Loading what the bar and the dock show, per procedure
3022
+ // ---------------------------------------------------------------------------
3023
+
3024
+ watch(
3025
+ selectedId,
3026
+ (id) => {
3027
+ if (id) missingProcedureId.value = null
3028
+ overlayRun.value = null
3029
+ void loadSavedTriggers()
3030
+ void loadRecentRuns()
3031
+ void loadTestPayload()
3032
+ },
3033
+ { immediate: true },
3034
+ )
3035
+
3036
+ /** `?path=g1,g2`: the groups to enter, outermost first, before `?node=`. */
3037
+ function enterPathFromUrl(): boolean {
3038
+ const ids = (queryValue('path') ?? '').split(',').filter(Boolean)
3039
+ for (const id of ids) {
3040
+ const depth = subgraphPath.value.length
3041
+ onGroupEnter({ id })
3042
+ if (subgraphPath.value.length === depth) break
3043
+ }
3044
+ return subgraphPath.value.length > 1
3045
+ }
3046
+
3047
+ onMounted(async () => {
3048
+ await loadSummaries()
3049
+ if (missingProcedureId.value) switcherOpen.value = true
3050
+ const runId = queryValue('run')
3051
+ if (runId) await openRunFromUrl(runId)
3052
+ const nodeId = queryValue('node')
3053
+ if (nodeId) {
3054
+ if (enterPathFromUrl()) selectedNodeId.value = nodeId
3055
+ else selectNode(nodeId)
3056
+ }
3057
+ // The URL names the procedure on screen, to share or reload it.
3058
+ if (editorMode.value === 'procedure' && selectedId.value && queryValue('selected') !== selectedId.value) {
3059
+ void router.replace({ path: builderPath(), query: { ...route.query, selected: selectedId.value } })
3060
+ }
3061
+ })
3062
+
3063
+ const selectedTriggerSummaries = computed<TriggerSummary[]>(() =>
3064
+ (selected.value?.graph.nodes ?? [])
3065
+ .filter((n) => n.kind === 'trigger' && n.typeId)
3066
+ .map((n) => ({
3067
+ nodeId: n.id,
3068
+ typeId: n.typeId!,
3069
+ typeName: triggerTypes.value.find((x) => x.id === n.typeId)?.name ?? n.typeId!,
3070
+ path: typeof n.config?.path === 'string' ? n.config.path : undefined,
3071
+ method: typeof n.config?.method === 'string' ? n.config.method : undefined,
3072
+ cron: typeof n.config?.cron === 'string' ? n.config.cron : undefined,
3073
+ })),
3074
+ )
3075
+
3076
+ // A draft trigger as the server words it, its type's name until it has.
3077
+ function triggerLabel(trigger: TriggerSummary): string {
3078
+ const worded = draftTriggers.value.find((tr) => tr.nodeId === trigger.nodeId)
3079
+ return worded ? processText(worded.text) : processI18n(trigger.typeName)
3080
+ }
3081
+
3082
+ // Test run starts from the trigger picked in the dock: the manual one, else
3083
+ // the first, until the user picks another; its last real payload prefills
3084
+ // the test payload.
3085
+ const testTriggerItems = computed(() =>
3086
+ selectedTriggerSummaries.value.map((trigger) => ({ label: triggerLabel(trigger), value: trigger.nodeId ?? '' })),
3087
+ )
3088
+ watch(
3089
+ selectedTriggerSummaries,
3090
+ (triggers) => {
3091
+ if (triggers.some((trigger) => trigger.nodeId === testTriggerNodeId.value)) return
3092
+ testTriggerNodeId.value = triggers.find((trigger) => trigger.typeId === 'manual')?.nodeId ?? triggers[0]?.nodeId
3093
+ },
3094
+ { immediate: true },
3095
+ )
3096
+ watch(testTriggerNodeId, () => void loadTestPayload())
3097
+
3098
+ // Below xl the inspector floats over the canvas instead of narrowing it; the
3099
+ // palette can be put away. Remembered per browser.
3100
+ const PALETTE_HIDDEN_KEY = 'dms-automation:builder-palette-hidden'
3101
+ const PALETTE_FOLDED_BELOW_PX = 1280
3102
+ const paletteHidden = ref(false)
3103
+ onMounted(() => {
3104
+ // Folded by default below xl, where it would leave the canvas too little.
3105
+ let stored: string | null = null
3106
+ try {
3107
+ stored = window.localStorage.getItem(PALETTE_HIDDEN_KEY)
3108
+ } catch {
3109
+ // Storage blocked: the default for the width applies.
3110
+ }
3111
+ paletteHidden.value = stored === null ? window.innerWidth < PALETTE_FOLDED_BELOW_PX : stored === '1'
3112
+ })
3113
+ function togglePalette() {
3114
+ paletteHidden.value = !paletteHidden.value
3115
+ try {
3116
+ window.localStorage.setItem(PALETTE_HIDDEN_KEY, paletteHidden.value ? '1' : '0')
3117
+ } catch {
3118
+ // Storage blocked: the choice lasts until the page is left.
3119
+ }
3120
+ }
3121
+
3122
+ // Template mode: the template's own ports are edited at its root, where its
3123
+ // Group input / Group output steps show them. Shown when no step, or
3124
+ // one of those two, is selected.
3125
+ const showTemplatePorts = computed<boolean>(
3126
+ () =>
3127
+ editorMode.value === 'template' &&
3128
+ subgraphPath.value.length <= 1 &&
3129
+ (!selectedNode.value || selectedNode.value.kind === 'groupInput' || selectedNode.value.kind === 'groupOutput'),
3130
+ )
3131
+
3132
+ function onTemplatePortsUpdate(next: GroupPort[]) {
3133
+ const root = selected.value?.graph
3134
+ if (!root) return
3135
+ // The root graph is the template's subgraph: renames and removals go
3136
+ // through the same path as a group's ports.
3137
+ const template: GraphNode = {
3138
+ id: '',
3139
+ kind: 'group',
3140
+ config: {},
3141
+ position: { x: 0, y: 0 },
3142
+ ports: next.map((p) => ({ ...p })),
3143
+ subgraph: cloneGraph(root),
2085
3144
  }
3145
+ const renames = detectPortRenames(templatePorts.value, next)
3146
+ const gi = template.subgraph!.nodes.find((n) => n.kind === 'groupInput')
3147
+ const go = template.subgraph!.nodes.find((n) => n.kind === 'groupOutput')
3148
+ const inRenames = renames.filter((r) => r.direction === 'in')
3149
+ const outRenames = renames.filter((r) => r.direction === 'out')
3150
+ if (gi && inRenames.length > 0) applyPortRenamesToEdges(template.subgraph!.triggerEdges, template.subgraph!.dataEdges, gi.id, inRenames, true)
3151
+ if (go && outRenames.length > 0) applyPortRenamesToEdges(template.subgraph!.triggerEdges, template.subgraph!.dataEdges, go.id, outRenames, true)
3152
+ syncSentinels(template)
3153
+ templatePorts.value = template.ports!
3154
+ onGraphUpdate(template.subgraph!)
2086
3155
  }
3156
+
3157
+
2087
3158
  </script>
2088
3159
 
2089
3160
  <template>
2090
3161
  <!--
2091
- The page (src/pages/builder.ts) renders the native dms header
2092
- (icon / title / description), so the editor doesn't repeat one here.
2093
- The page fills the panel (`fillHeight`): the editor takes the height
2094
- left under that header, and the `min-h-0` / `flex-1` chain below passes
2095
- it down to the canvas, which pans inside it instead of growing.
3162
+ The builder is one tool: the page hides its header (src/pages/builder.ts)
3163
+ and the editor fills the panel. One bar holds the procedure's identity,
3164
+ state and actions; the palette, the canvas and the inspector share the
3165
+ height; the dock under them lists problems, runs and the test payload.
2096
3166
  -->
2097
- <div class="flex min-h-0 flex-1 flex-col gap-4">
2098
- <UAlert
2099
- v-if="loadError"
2100
- color="error"
2101
- variant="subtle"
2102
- icon="i-ph-warning"
2103
- :title="
2104
- editorMode === 'template'
2105
- ? $t('dms_automation.editor.loadTemplateError')
2106
- : $t('dms_automation.editor.loadProceduresError')
2107
- "
2108
- :description="loadError"
2109
- />
2110
-
2111
- <DmsCard :padded="false">
2112
- <div class="flex flex-wrap items-center gap-3 px-4 py-3 sm:px-5">
3167
+ <div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-default bg-default">
3168
+ <header class="flex min-h-13 flex-wrap items-center gap-2 border-b border-default px-3 py-2">
3169
+ <template v-if="editorMode === 'procedure'">
3170
+ <UTooltip :text="$t('dms_automation.editor.switcher.title')" :kbds="['meta', 'p']">
3171
+ <UButton
3172
+ icon="i-ph-flow-arrow"
3173
+ variant="ghost"
3174
+ color="neutral"
3175
+ :aria-label="$t('dms_automation.editor.switcher.title')"
3176
+ @click="switcherOpen = true"
3177
+ />
3178
+ </UTooltip>
3179
+ </template>
3180
+ <template v-else>
3181
+ <UButton icon="i-ph-arrow-left" variant="ghost" color="neutral" :to="libraryBackUrl">
3182
+ {{ $t('dms_automation.library.title') }}
3183
+ </UButton>
3184
+ <UBadge color="info" variant="subtle">{{ $t('dms_automation.editor.templateBadge') }}</UBadge>
3185
+ </template>
3186
+ <UTooltip v-if="selected && currentGraph && !isCurrentGraphReadOnly" :text="paletteHidden ? $t('dms_automation.editor.showBlocks') : $t('dms_automation.editor.hideBlocks')">
2113
3187
  <UButton
2114
- v-if="editorMode === 'procedure'"
2115
- icon="i-ph-list-bullets"
2116
- variant="outline"
3188
+ :icon="paletteHidden ? 'i-ph-sidebar-simple' : 'i-ph-sidebar-simple-fill'"
3189
+ variant="ghost"
2117
3190
  color="neutral"
2118
- @click="showProcedures = true"
2119
- >
2120
- {{ $t('dms_automation.editor.procedures') }}
2121
- </UButton>
2122
- <UInput
2123
- v-if="selected"
2124
- v-model="procedureName"
2125
- :placeholder="
2126
- editorMode === 'template'
2127
- ? $t('dms_automation.editor.templateName')
2128
- : $t('dms_automation.editor.procedureName')
2129
- "
2130
- class="min-w-[200px] flex-1"
3191
+ :aria-label="paletteHidden ? $t('dms_automation.editor.showBlocks') : $t('dms_automation.editor.hideBlocks')"
3192
+ :aria-pressed="!paletteHidden"
3193
+ @click="togglePalette"
2131
3194
  />
2132
- <div
2133
- v-if="selected && editorMode === 'procedure'"
2134
- class="flex items-center gap-2"
2135
- >
2136
- <span class="text-sm text-muted">{{ $t('dms_automation.editor.enabled') }}</span>
2137
- <USwitch v-model="procedureEnabled" />
2138
- </div>
3195
+ </UTooltip>
3196
+ <UInput
3197
+ v-if="selected"
3198
+ :id="NAME_INPUT_ID"
3199
+ v-model="procedureName"
3200
+ variant="ghost"
3201
+ :color="nameMissing ? 'error' : undefined"
3202
+ :highlight="nameMissing"
3203
+ :placeholder="editorMode === 'template' ? $t('dms_automation.editor.templateName') : $t('dms_automation.editor.procedureName')"
3204
+ :aria-label="editorMode === 'template' ? $t('dms_automation.editor.templateName') : $t('dms_automation.editor.procedureName')"
3205
+ :aria-invalid="nameMissing || undefined"
3206
+ :aria-describedby="nameMissing ? `${NAME_INPUT_ID}-error` : undefined"
3207
+ class="min-w-[12rem] max-w-sm flex-1 font-medium"
3208
+ />
3209
+ <DmsFieldError v-if="nameMissing" :id="`${NAME_INPUT_ID}-error`" :message="$t('dms_automation.editor.nameRequired')" />
3210
+ <DmsStatusPill
3211
+ v-if="currentSummary && editorMode === 'procedure'"
3212
+ :tone="STATE_TONES[currentSummary.status]"
3213
+ :label="$t(`dms_automation.procedures.status.${currentSummary.status}`)"
3214
+ size="sm"
3215
+ />
3216
+ <label v-if="selected && editorMode === 'procedure'" class="flex items-center gap-2 text-sm text-muted">
3217
+ <USwitch v-model="procedureEnabled" size="sm" />
3218
+ {{ procedureEnabled ? $t('dms_automation.editor.enabled') : $t('dms_automation.editor.disabled') }}
3219
+ </label>
3220
+ <span v-if="selected" class="ml-1 inline-flex items-center gap-1 whitespace-nowrap text-xs" :class="changeCount > 0 ? 'text-warning' : 'text-dimmed'">
3221
+ <UIcon :name="changeCount > 0 ? 'i-ph-circle-fill' : 'i-ph-check'" class="size-2.5 shrink-0" />
3222
+ {{ saveState }}
3223
+ </span>
3224
+ <div class="ml-auto flex flex-wrap items-center gap-2">
2139
3225
  <UButton
2140
- v-if="selected && editorMode === 'procedure'"
2141
- color="success"
2142
- icon="i-ph-play"
2143
- variant="solid"
2144
- :disabled="!canRun"
2145
- :loading="running"
2146
- @click="onRun"
3226
+ v-if="selected"
3227
+ variant="ghost"
3228
+ color="neutral"
3229
+ :disabled="!isDirty || saving"
3230
+ @click="onCancel"
2147
3231
  >
2148
- {{ $t('dms_automation.editor.runNow') }}
3232
+ {{ $t('dms_automation.editor.discard') }}
2149
3233
  </UButton>
2150
- <DmsAutomationRunsDrawer
3234
+ <template v-if="selected && editorMode === 'procedure'">
3235
+ <UButton variant="outline" color="neutral" icon="i-ph-play" @click="openRunNow">
3236
+ {{ $t('dms_automation.editor.runNowButton') }}
3237
+ </UButton>
3238
+ <UButton variant="outline" color="neutral" icon="i-ph-flask" :loading="testing" @click="onTestRun">
3239
+ {{ $t('dms_automation.editor.testRun') }}
3240
+ <UKbd :value="formatShortcut(['meta', '↵'])" size="sm" class="ml-1" />
3241
+ </UButton>
3242
+ </template>
3243
+ <UButton v-if="selected" color="primary" icon="i-ph-floppy-disk" :disabled="!isDirty || nameMissing" :loading="saving" @click="onSave">
3244
+ {{ $t('dms_automation.common.save') }}
3245
+ <UKbd :value="formatShortcut(['meta', 's'])" size="sm" class="ml-1" />
3246
+ </UButton>
3247
+ <UDropdownMenu
2151
3248
  v-if="selected && editorMode === 'procedure'"
2152
- ref="runsDrawerRef"
2153
- :procedure-id="selectedId"
2154
- :procedure-name="procedureName"
2155
- />
2156
- <div
2157
- v-if="!selected && editorMode === 'procedure'"
2158
- class="text-sm text-dimmed"
2159
- >
2160
- {{ $t('dms_automation.editor.noProcedure') }}
2161
- </div>
2162
- <div
2163
- v-if="!selected && editorMode === 'template'"
2164
- class="text-sm text-dimmed"
2165
- >
2166
- {{ $t('dms_automation.editor.templateNotLoaded') }}
2167
- </div>
2168
- <UButton
2169
- class="ml-auto"
2170
- color="neutral"
2171
- variant="outline"
2172
- icon="i-ph-arrows-clockwise"
2173
- :loading="loading"
2174
- @click="
2175
- editorMode === 'template' && editorTemplateId
2176
- ? loadTemplate(editorTemplateId)
2177
- : loadList()
2178
- "
3249
+ :items="[
3250
+ [
3251
+ { label: $t('dms_automation.newProcedure.title'), icon: 'i-ph-plus', onSelect: onCreate },
3252
+ { label: $t('dms_automation.editor.exportJson'), icon: 'i-ph-download-simple', onSelect: onExport },
3253
+ { label: $t('dms_automation.editor.viewRuns'), icon: 'i-ph-list-bullets', to: `${runsUrl}?procedure=${selectedId}` },
3254
+ ],
3255
+ [{ label: $t('dms_automation.editor.delete'), icon: 'i-ph-trash', color: 'error', onSelect: onDelete }],
3256
+ ]"
2179
3257
  >
2180
- {{ $t('dms_automation.common.refresh') }}
2181
- </UButton>
3258
+ <UButton icon="i-ph-dots-three" variant="ghost" color="neutral" :aria-label="$t('dms_automation.editor.more')" />
3259
+ </UDropdownMenu>
2182
3260
  </div>
2183
- </DmsCard>
3261
+ </header>
2184
3262
 
2185
- <div v-if="selected" class="flex min-h-0 flex-1 flex-col gap-4">
2186
- <UAlert
2187
- v-if="hasInactiveTriggers && editorMode === 'procedure'"
2188
- color="warning"
2189
- variant="subtle"
3263
+ <div class="flex flex-col gap-2 empty:hidden" :class="loadError || saveBlocked || pausedBanner || overlayRun || testing || isCurrentGraphReadOnly ? 'border-b border-default p-2' : ''">
3264
+ <DmsBanner
3265
+ v-if="loadError"
3266
+ size="sm"
3267
+ tone="error"
2190
3268
  icon="i-ph-warning"
2191
- :title="$t('dms_automation.editor.disabledTitle')"
2192
- :description="$t('dms_automation.editor.disabledDescription')"
2193
- :actions="[
2194
- {
2195
- label: $t('dms_automation.editor.enableAndSave'),
2196
- color: 'warning',
2197
- variant: 'solid',
2198
- loading: saving,
2199
- onClick: () => {
2200
- procedureEnabled = true
2201
- onSave()
2202
- },
2203
- },
2204
- ]"
3269
+ :title="editorMode === 'template' ? $t('dms_automation.editor.loadTemplateError') : $t('dms_automation.editor.loadProceduresError')"
3270
+ :description="loadError"
3271
+ >
3272
+ <template v-if="templateNotFound" #actions>
3273
+ <UButton size="xs" color="error" variant="soft" icon="i-ph-arrow-left" :to="libraryBackUrl">{{ $t('dms_automation.editor.backToTemplates') }}</UButton>
3274
+ </template>
3275
+ </DmsBanner>
3276
+ <DmsBanner
3277
+ v-if="saveBlocked && blockingIssues.length"
3278
+ size="sm"
3279
+ tone="error"
3280
+ icon="i-ph-warning-octagon"
3281
+ :title="$t('dms_automation.editor.problems.title', { count: blockingIssues.length })"
3282
+ :description="$t('dms_automation.editor.problems.description')"
3283
+ >
3284
+ <template #actions>
3285
+ <UButton size="xs" color="error" variant="soft" @click="goToFirstProblem">{{ $t('dms_automation.editor.problems.first') }}</UButton>
3286
+ <UButton size="xs" color="neutral" variant="outline" :loading="saving" @click="saveAsDraft">{{ $t('dms_automation.editor.problems.saveDraft') }}</UButton>
3287
+ </template>
3288
+ </DmsBanner>
3289
+ <DmsBanner v-if="pausedBanner && !saveBlocked" size="sm" tone="warning" icon="i-ph-pause-circle" :title="pausedBanner.title" :description="pausedBanner.description">
3290
+ <template #actions>
3291
+ <UButton size="xs" color="warning" variant="soft" :loading="saving" :disabled="blockingIssues.length > 0" @click="enableNow">
3292
+ {{ $t('dms_automation.editor.paused.enable') }}
3293
+ </UButton>
3294
+ </template>
3295
+ </DmsBanner>
3296
+ <DmsBanner
3297
+ v-if="testing"
3298
+ size="sm"
3299
+ tone="info"
3300
+ icon="i-ph-flask"
3301
+ :title="$t('dms_automation.editor.debug.testing')"
3302
+ :description="$t('dms_automation.editor.debug.testingHint')"
2205
3303
  />
2206
- <div
2207
- v-if="subgraphPath.length > 1"
2208
- class="flex items-center justify-between gap-3 rounded-lg border border-default bg-elevated px-3 py-2"
3304
+ <DmsBanner
3305
+ v-if="overlayRun && !testing"
3306
+ size="sm"
3307
+ :tone="overlayRun.status === 'failed' ? 'error' : 'success'"
3308
+ :icon="overlayRun.status === 'failed' ? 'i-ph-bug' : 'i-ph-check-circle'"
3309
+ :title="overlaySummary"
3310
+ :description="overlayDescription"
2209
3311
  >
2210
- <UBreadcrumb
2211
- :items="breadcrumbItems"
2212
- :ui="{ linkLabel: 'first-letter:uppercase' }"
2213
- />
2214
- <UButton
2215
- v-if="subgraphPath.length > 1"
2216
- size="xs"
2217
- variant="ghost"
2218
- color="neutral"
2219
- icon="i-ph-arrow-up-left"
2220
- @click="exitSubgraph"
2221
- >
2222
- {{ $t('dms_automation.editor.exitSubgraph') }}
2223
- </UButton>
2224
- </div>
2225
- <UAlert
3312
+ <template #actions>
3313
+ <UTooltip v-if="!overlayIsTest" :text="isDirty ? $t('dms_automation.editor.debug.rerunSaveFirst') : $t('dms_automation.editor.debug.rerunHint')">
3314
+ <UButton size="xs" variant="soft" color="neutral" icon="i-ph-arrow-clockwise" :disabled="isDirty" @click="rerunOverlay">
3315
+ {{ $t('dms_automation.runs.rerunWithPayload') }}
3316
+ </UButton>
3317
+ </UTooltip>
3318
+ <UButton v-if="overlayIsTest" size="xs" variant="soft" color="neutral" icon="i-ph-arrow-clockwise" :loading="testing" @click="onTestRun">
3319
+ {{ $t('dms_automation.editor.debug.again') }}
3320
+ </UButton>
3321
+ <UButton size="xs" variant="ghost" color="neutral" icon="i-ph-path" @click="openTrace(overlayRun._id)">
3322
+ {{ $t('dms_automation.runs.trace') }}
3323
+ </UButton>
3324
+ <UButton size="xs" variant="ghost" color="neutral" @click="exitDebug">
3325
+ {{ $t('dms_automation.editor.debug.exit') }}
3326
+ <UKbd value="Esc" size="sm" class="ml-1" />
3327
+ </UButton>
3328
+ </template>
3329
+ </DmsBanner>
3330
+ <DmsBanner
2226
3331
  v-if="isCurrentGraphReadOnly"
2227
- color="info"
2228
- variant="subtle"
3332
+ size="sm"
3333
+ tone="info"
2229
3334
  icon="i-ph-link"
2230
3335
  :title="$t('dms_automation.editor.linkedTitle')"
2231
3336
  :description="$t('dms_automation.editor.linkedDescription')"
2232
- :actions="canForkToLocal ? [
2233
- {
2234
- label: $t('dms_automation.editor.forkToEdit'),
2235
- color: 'info',
2236
- variant: 'solid',
2237
- icon: 'i-ph-git-fork',
2238
- onClick: openFork,
2239
- },
2240
- ] : []"
3337
+ >
3338
+ <template v-if="canForkToLocal" #actions>
3339
+ <UButton size="xs" color="info" variant="soft" icon="i-ph-git-fork" @click="openFork">
3340
+ {{ $t('dms_automation.editor.forkToEdit') }}
3341
+ </UButton>
3342
+ </template>
3343
+ </DmsBanner>
3344
+ </div>
3345
+
3346
+ <DmsEmptyState
3347
+ v-if="!selected && !loading && editorMode === 'procedure' && missingProcedureId"
3348
+ class="m-auto"
3349
+ size="lg"
3350
+ icon="i-ph-question"
3351
+ :title="$t('dms_automation.editor.missingTitle')"
3352
+ :description="$t('dms_automation.editor.missingDescription')"
3353
+ :actions="[
3354
+ { label: $t('dms_automation.editor.missingPick'), icon: 'i-ph-flow-arrow', onClick: () => (switcherOpen = true) },
3355
+ { label: $t('dms_automation.newProcedure.title'), icon: 'i-ph-plus', variant: 'outline', onClick: () => (newProcedureOpen = true) },
3356
+ ]"
3357
+ />
3358
+ <DmsEmptyState
3359
+ v-else-if="!selected && !loading && editorMode === 'procedure'"
3360
+ class="m-auto"
3361
+ size="lg"
3362
+ icon="i-ph-flow-arrow"
3363
+ :title="$t('dms_automation.editor.noProcedureTitle')"
3364
+ :description="$t('dms_automation.editor.noProcedure')"
3365
+ :actions="[{ label: $t('dms_automation.newProcedure.title'), icon: 'i-ph-plus', onClick: () => (newProcedureOpen = true) }]"
3366
+ />
3367
+
3368
+ <div v-if="selected" class="relative flex min-h-0 flex-1">
3369
+ <DmsAutomationBuilderPalette
3370
+ v-if="currentGraph && !isCurrentGraphReadOnly && !paletteHidden"
3371
+ :node-kinds="nodeKinds"
3372
+ :trigger-types="paletteTriggerTypes"
3373
+ :action-types="actionTypes"
3374
+ :data-node-types="dataNodeTypes"
3375
+ :templates="palettesTemplates"
3376
+ class="w-60 shrink-0 border-r border-default"
3377
+ @add-node="onPaletteAddNode"
3378
+ @add-template="onPaletteAddTemplate"
2241
3379
  />
2242
- <div class="flex min-h-0 flex-1 gap-4">
2243
- <DmsAutomationBuilderPalette
2244
- v-if="currentGraph && !isCurrentGraphReadOnly"
2245
- :node-kinds="nodeKinds"
2246
- :trigger-types="triggerTypes"
2247
- :action-types="actionTypes"
2248
- :data-node-types="dataNodeTypes"
2249
- :templates="palettesTemplates"
2250
- class="w-60 shrink-0"
2251
- @add-node="onPaletteAddNode"
2252
- @add-template="onPaletteAddTemplate"
2253
- />
2254
- <div class="h-full min-w-0 flex-1">
2255
- <DmsClientOnly>
2256
- <DmsAutomationGraphCanvas
2257
- v-if="currentGraph"
2258
- ref="graphCanvasRef"
2259
- :graph="currentGraph"
2260
- :trigger-types="triggerTypes"
2261
- :action-types="actionTypes"
2262
- :data-node-types="dataNodeTypes"
2263
- :node-kinds="nodeKinds"
2264
- :can-undo="canUndo"
2265
- :can-redo="canRedo"
2266
- :is-dirty="isDirty"
2267
- :applying="saving"
2268
- :parent-group-ports="currentParentGroupPorts"
2269
- :read-only="isCurrentGraphReadOnly"
2270
- @update:graph="onGraphUpdate"
2271
- @select:node="onSelectNode"
2272
- @selection-change="onSelectionChange"
2273
- @undo="onUndo"
2274
- @redo="onRedo"
2275
- @cancel="onCancel"
2276
- @apply="onSave"
2277
- @group:enter="onGroupEnter"
2278
- >
2279
- <template
2280
- v-if="canGroupSelection || canSaveAsTemplate || canForkToLocal || canEnterGroup"
2281
- #groupActions
3380
+ <div class="h-full min-w-0 flex-1">
3381
+ <DmsClientOnly>
3382
+ <DmsAutomationGraphCanvas
3383
+ v-if="currentGraph"
3384
+ ref="graphCanvasRef"
3385
+ :graph="currentGraph"
3386
+ :trigger-types="triggerTypes"
3387
+ :action-types="actionTypes"
3388
+ :data-node-types="dataNodeTypes"
3389
+ :node-kinds="nodeKinds"
3390
+ :can-undo="canUndo"
3391
+ :can-redo="canRedo"
3392
+ :parent-group-ports="currentParentGroupPorts"
3393
+ :read-only="isCurrentGraphReadOnly"
3394
+ :run-states="runStates"
3395
+ :issues="subgraphPath.length <= 1 ? issuesByNode : undefined"
3396
+ :selected-node-id="selectedNodeId"
3397
+ :view-key="canvasViewKey"
3398
+ :covered-by="inspectorRef"
3399
+ :triggers="draftTriggers"
3400
+ class="[&_.graph-canvas-wrap]:rounded-none [&_.graph-canvas-wrap]:border-0"
3401
+ @update:graph="onGraphUpdate"
3402
+ @select:node="onSelectNode"
3403
+ @selection-change="onSelectionChange"
3404
+ @undo="onUndo"
3405
+ @redo="onRedo"
3406
+ @group:enter="onGroupEnter"
2282
3407
  >
2283
- <UButton
2284
- v-if="canEnterGroup"
2285
- size="sm"
2286
- color="primary"
2287
- icon="i-ph-arrow-square-in"
2288
- variant="ghost"
2289
- @click="enterSelectedGroup"
2290
- >
2291
- {{ $t('dms_automation.editor.enterGroup') }}
2292
- </UButton>
2293
- <UButton
2294
- v-if="canGroupSelection"
2295
- size="sm"
2296
- color="primary"
2297
- icon="i-ph-package"
2298
- variant="ghost"
2299
- @click="createGroupFromSelection"
3408
+ <template #breadcrumb>
3409
+ <div class="flex items-center gap-2 rounded-lg border border-default bg-elevated/90 px-2 py-1 shadow-sm">
3410
+ <UBreadcrumb :items="breadcrumbItems" />
3411
+ <UButton
3412
+ v-if="subgraphPath.length > 1"
3413
+ size="xs"
3414
+ variant="ghost"
3415
+ color="neutral"
3416
+ icon="i-ph-arrow-up-left"
3417
+ @click="exitSubgraph"
3418
+ >
3419
+ {{ $t('dms_automation.editor.exitSubgraph') }}
3420
+ </UButton>
3421
+ </div>
3422
+ </template>
3423
+ <template
3424
+ v-if="canGroupSelection || canSaveAsTemplate || canForkToLocal || canEnterGroup"
3425
+ #groupActions
2300
3426
  >
2301
- {{ $t('dms_automation.editor.groupSelection', { n: selectedNodeIds.length }) }}
2302
- </UButton>
2303
- <UButton
2304
- v-if="canSaveAsTemplate"
2305
- size="sm"
2306
- color="primary"
2307
- icon="i-ph-floppy-disk"
2308
- variant="ghost"
2309
- @click="openSaveAsTemplate"
2310
- >
2311
- {{ $t('dms_automation.editor.saveAsTemplate') }}
2312
- </UButton>
2313
- <UButton
2314
- v-if="canForkToLocal"
2315
- size="sm"
2316
- color="primary"
2317
- icon="i-ph-git-fork"
2318
- variant="ghost"
2319
- @click="openFork"
2320
- >
2321
- {{ $t('dms_automation.editor.forkToLocal') }}
2322
- </UButton>
2323
- </template>
2324
- <template v-if="selectedNode" #inspector>
2325
- <DmsAutomationNodeInspector
2326
- :node="selectedNode"
2327
- :data-edges="selected.graph.dataEdges"
2328
- :trigger-type="selectedNodeTriggerType"
2329
- :action-type="selectedNodeActionType"
2330
- :trigger-types="triggerTypes"
2331
- :action-types="actionTypes"
2332
- :data-node-types="dataNodeTypes"
2333
- :node-kinds="nodeKinds"
2334
- :read-only="isCurrentGraphReadOnly"
2335
- @update:node="onUpdateNode"
2336
- @unwire="onUnwireField"
2337
- @ports:update="onPortsUpdate"
2338
- @group:enter="onGroupEnter"
2339
- @delete:node="onDeleteNode"
2340
- />
3427
+ <span v-if="selectedNodeIds.length > 1" class="px-1 text-xs text-muted">
3428
+ {{ $t('dms_automation.editor.selected', { count: selectedNodeIds.length }) }}
3429
+ </span>
3430
+ <UButton v-if="canEnterGroup" size="sm" color="primary" icon="i-ph-arrow-square-in" variant="ghost" @click="enterSelectedGroup">
3431
+ {{ $t('dms_automation.editor.enterGroup') }}
3432
+ </UButton>
3433
+ <UButton v-if="canGroupSelection" size="sm" color="primary" icon="i-ph-stack" variant="ghost" @click="createGroupFromSelection">
3434
+ {{ $t('dms_automation.editor.groupSelection', { n: selectedNodeIds.length }) }}
3435
+ </UButton>
3436
+ <UButton v-if="canSaveAsTemplate" size="sm" color="primary" icon="i-ph-floppy-disk" variant="ghost" @click="openSaveAsTemplate">
3437
+ {{ $t('dms_automation.editor.saveAsTemplate') }}
3438
+ </UButton>
3439
+ <UButton v-if="canForkToLocal" size="sm" color="primary" icon="i-ph-git-fork" variant="ghost" @click="openFork">
3440
+ {{ $t('dms_automation.editor.forkToLocal') }}
3441
+ </UButton>
3442
+ </template>
3443
+ </DmsAutomationGraphCanvas>
3444
+ <template #fallback>
3445
+ <div class="flex h-full items-center justify-center text-sm text-dimmed">
3446
+ {{ $t('dms_automation.editor.loading') }}
3447
+ </div>
2341
3448
  </template>
2342
- </DmsAutomationGraphCanvas>
2343
- <template #fallback>
2344
- <div
2345
- class="flex h-full items-center justify-center rounded-lg border border-default text-sm text-dimmed"
2346
- >
2347
- {{ $t('dms_automation.editor.loading') }}
2348
- </div>
2349
- </template>
2350
3449
  </DmsClientOnly>
2351
- </div>
2352
3450
  </div>
3451
+ <aside v-if="showTemplatePorts" ref="inspectorRef" :class="ASIDE_CLASS">
3452
+ <div class="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto p-4">
3453
+ <p class="text-xs text-muted">{{ $t('dms_automation.editor.templatePortsHint') }}</p>
3454
+ <DmsAutomationGroupPortEditor :ports="templatePorts" @ports:update="onTemplatePortsUpdate" />
3455
+ </div>
3456
+ </aside>
3457
+ <aside v-else-if="selectedNode" ref="inspectorRef" :class="ASIDE_CLASS">
3458
+ <DmsAutomationNodeInspector
3459
+ :node="selectedNode"
3460
+ :data-edges="currentGraph?.dataEdges ?? []"
3461
+ :trigger-type="selectedNodeTriggerType"
3462
+ :action-type="selectedNodeActionType"
3463
+ :data-node-types="dataNodeTypes"
3464
+ :node-kinds="nodeKinds"
3465
+ :read-only="isCurrentGraphReadOnly"
3466
+ :run-step="subgraphPath.length <= 1 ? selectedRunStep : null"
3467
+ :run-label="overlayLabel"
3468
+ :run-trace-url="overlayRun ? `${traceUrl}?run=${overlayRun._id}` : undefined"
3469
+ :issue="issuesByNode[selectedNode.id] ?? null"
3470
+ :node-name="nodeDisplayName"
3471
+ :saved-triggers="savedTriggers"
3472
+ @update:node="onUpdateNode"
3473
+ @unwire="onUnwireField"
3474
+ @ports:update="onPortsUpdate"
3475
+ @group:enter="onGroupEnter"
3476
+ @delete:node="onDeleteNode"
3477
+ @duplicate:node="onDuplicateNode"
3478
+ @wrap:retry="onWrapInRetry"
3479
+ @close="selectedNodeId = null"
3480
+ />
3481
+ </aside>
2353
3482
  </div>
2354
3483
 
2355
- <USlideover
3484
+ <DmsAutomationBottomDock
3485
+ v-if="selected && editorMode === 'procedure'"
3486
+ v-model:tab="dockTab"
3487
+ v-model:payload="testPayload"
3488
+ v-model:collapsed="dockCollapsed"
3489
+ :issues="dockIssues"
3490
+ :runs="recentRuns"
3491
+ :test-steps="overlaySteps"
3492
+ :payload-source="testPayloadSource"
3493
+ :triggers="testTriggerItems"
3494
+ v-model:trigger="testTriggerNodeId"
3495
+ :runs-url="`${runsUrl}?procedure=${selectedId}`"
3496
+ @select-node="selectNode"
3497
+ @open-trace="openTrace"
3498
+ />
3499
+
3500
+ <DmsAutomationProcedureSwitcher
2356
3501
  v-if="editorMode === 'procedure'"
2357
- v-model:open="showProcedures"
2358
- side="left"
2359
- :title="$t('dms_automation.editor.procedures')"
3502
+ v-model:open="switcherOpen"
3503
+ :procedures="summaries"
3504
+ :current-id="selectedId"
3505
+ proceduresUrl="/modules/automation/procedures"
3506
+ @pick="onPickProcedure"
3507
+ @create="onCreate"
3508
+ />
3509
+ <DmsAutomationNewProcedureDialog v-model:open="newProcedureOpen" :api-url="apiUrl" @created="onCreated" />
3510
+ <DmsAutomationRunNowDialog
3511
+ v-if="selected && editorMode === 'procedure'"
3512
+ v-model:open="runNowOpen"
3513
+ :api-url="apiUrl"
3514
+ :procedure-id="selected._id"
3515
+ :procedure-name="savedName"
3516
+ :triggers="savedTriggers"
3517
+ @started="onRunStarted"
3518
+ />
3519
+
3520
+ <UModal
3521
+ :open="choiceDialog.open"
3522
+ :title="choiceDialog.title"
3523
+ :content="{ onOpenAutoFocus: focusSafeChoice }"
3524
+ @update:open="onChoiceDialogOpen"
2360
3525
  >
2361
3526
  <template #body>
2362
- <DmsAutomationProcedureList
2363
- :procedures="procedures"
2364
- :model-value="selectedId"
2365
- @update:model-value="onProcedurePicked"
2366
- @create="onCreate"
2367
- @delete="onDelete"
2368
- />
3527
+ <p class="text-sm text-toned">{{ choiceDialog.description }}</p>
3528
+ </template>
3529
+ <template #footer>
3530
+ <div class="flex w-full justify-end gap-2">
3531
+ <UButton
3532
+ v-for="choice in choiceDialog.choices"
3533
+ :key="choice.value"
3534
+ :color="choice.color ?? 'neutral'"
3535
+ :variant="choice.variant ?? 'solid'"
3536
+ :data-safe-choice="choice.value === choiceDialog.dismiss || undefined"
3537
+ @click="answerChoice(choice.value)"
3538
+ >
3539
+ {{ choice.label }}
3540
+ </UButton>
3541
+ </div>
2369
3542
  </template>
2370
- </USlideover>
3543
+ </UModal>
2371
3544
 
2372
3545
  <UModal
2373
3546
  v-model:open="saveAsTemplateOpen"
@@ -2375,47 +3548,64 @@ async function onRun() {
2375
3548
  >
2376
3549
  <template #body>
2377
3550
  <div class="flex flex-col gap-3">
2378
- <UFormField
3551
+ <DmsFieldRow
3552
+ v-bind="TEMPLATE_ROW"
2379
3553
  :label="$t('dms_automation.editor.saveTemplateModal.name')"
3554
+ :label-for="TEMPLATE_NAME_ID"
2380
3555
  required
2381
3556
  >
2382
- <UInput
2383
- v-model="saveAsTemplateName"
2384
- :placeholder="$t('dms_automation.editor.saveTemplateModal.namePlaceholder')"
2385
- class="w-full"
2386
- :disabled="saveAsTemplateSubmitting"
2387
- />
2388
- </UFormField>
2389
- <UFormField
3557
+ <div class="grid gap-1.5">
3558
+ <DmsInputText
3559
+ :id="TEMPLATE_NAME_ID"
3560
+ v-model="saveAsTemplateName"
3561
+ :placeholder="$t('dms_automation.editor.saveTemplateModal.namePlaceholder')"
3562
+ class="w-full"
3563
+ :disabled="saveAsTemplateSubmitting"
3564
+ v-bind="templateFieldErrors.aria('name')"
3565
+ />
3566
+ <DmsFieldError :id="templateFieldErrors.errorId('name')" :message="templateFieldErrors.errors.name" />
3567
+ </div>
3568
+ </DmsFieldRow>
3569
+ <DmsFieldRow
3570
+ v-bind="TEMPLATE_ROW"
2390
3571
  :label="$t('dms_automation.editor.saveTemplateModal.description')"
3572
+ label-for="save-template-description"
2391
3573
  >
2392
- <UTextarea
3574
+ <DmsTextarea
3575
+ id="save-template-description"
2393
3576
  v-model="saveAsTemplateDescription"
2394
3577
  :placeholder="$t('dms_automation.editor.saveTemplateModal.descriptionPlaceholder')"
2395
3578
  class="w-full"
2396
3579
  :rows="3"
2397
3580
  :disabled="saveAsTemplateSubmitting"
2398
3581
  />
2399
- </UFormField>
2400
- <UFormField
2401
- :label="$t('dms_automation.editor.saveTemplateModal.icon')"
2402
- :help="$t('dms_automation.editor.saveTemplateModal.iconHelp')"
2403
- >
2404
- <UInput
2405
- v-model="saveAsTemplateIcon"
2406
- placeholder="i-ph-package"
2407
- class="w-full"
2408
- :disabled="saveAsTemplateSubmitting"
2409
- />
2410
- </UFormField>
2411
- <UAlert
3582
+ </DmsFieldRow>
3583
+ <DmsFieldRow v-bind="TEMPLATE_ROW" :label="$t('dms_automation.editor.saveTemplateModal.icon')">
3584
+ <DmsAutomationIconPicker v-model="saveAsTemplateIcon" />
3585
+ </DmsFieldRow>
3586
+ <div v-if="selectedLocalGroupNode?.ports?.length" class="flex flex-col gap-1">
3587
+ <span class="text-xs font-medium text-highlighted">{{ $t('dms_automation.editor.saveTemplateModal.ports') }}</span>
3588
+ <div class="overflow-hidden rounded-md border border-default">
3589
+ <div
3590
+ v-for="port in selectedLocalGroupNode.ports"
3591
+ :key="`${port.direction}-${port.kind}-${port.name}`"
3592
+ class="flex items-center gap-2 border-b border-default px-2 py-1 font-mono text-xs last:border-0"
3593
+ >
3594
+ <UBadge size="sm" variant="subtle" :color="port.kind === 'trigger' ? 'info' : 'success'">{{ $t(`dms_automation.templates.ports.kind.${port.kind}`) }}</UBadge>
3595
+ <span class="text-muted">{{ $t(`dms_automation.templates.ports.direction.${port.direction}`) }}</span>
3596
+ <span class="text-highlighted">{{ port.name }}</span>
3597
+ <span v-if="port.schema?.type" class="ml-auto text-dimmed">{{ port.schema.type }}</span>
3598
+ </div>
3599
+ </div>
3600
+ </div>
3601
+ <DmsBanner
2412
3602
  v-if="saveAsTemplateError"
2413
- color="error"
2414
- variant="subtle"
2415
- icon="i-ph-warning"
3603
+ size="sm"
3604
+ tone="error"
2416
3605
  :title="$t('dms_automation.editor.saveTemplateModal.error')"
2417
3606
  :description="saveAsTemplateError"
2418
3607
  />
3608
+ <DmsFormRequiredLegend />
2419
3609
  </div>
2420
3610
  </template>
2421
3611
  <template #footer>
@@ -2446,11 +3636,10 @@ async function onRun() {
2446
3636
  <p class="text-sm text-toned">
2447
3637
  {{ $t('dms_automation.editor.forkModal.body') }}
2448
3638
  </p>
2449
- <UAlert
3639
+ <DmsBanner
2450
3640
  v-if="forkError"
2451
- color="error"
2452
- variant="subtle"
2453
- icon="i-ph-warning"
3641
+ size="sm"
3642
+ tone="error"
2454
3643
  :title="$t('dms_automation.editor.forkModal.error')"
2455
3644
  :description="forkError"
2456
3645
  />