@antelopejs/dms-automation 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/README.md +33 -22
  2. package/dist/cluster/bus.js +8 -6
  3. package/dist/cluster/bus.js.map +1 -1
  4. package/dist/cluster/leader.js.map +1 -1
  5. package/dist/data/procedures-query.d.ts +19 -0
  6. package/dist/data/procedures-query.js +105 -0
  7. package/dist/data/procedures-query.js.map +1 -0
  8. package/dist/data/procedures-table.d.ts +5 -20
  9. package/dist/data/procedures-table.js +10 -106
  10. package/dist/data/procedures-table.js.map +1 -1
  11. package/dist/data/runs-table.d.ts +3 -3
  12. package/dist/data/runs-table.js.map +1 -1
  13. package/dist/db/models/automation_template.model.d.ts +13 -13
  14. package/dist/db/models/automation_template.model.js +13 -14
  15. package/dist/db/models/automation_template.model.js.map +1 -1
  16. package/dist/db/models/procedure.model.d.ts +7 -5
  17. package/dist/db/models/procedure_run.model.d.ts +9 -6
  18. package/dist/db/models/procedure_run.model.js +8 -8
  19. package/dist/db/models/procedure_run.model.js.map +1 -1
  20. package/dist/db/models/stats.model.js.map +1 -1
  21. package/dist/db/models/type_switch.model.d.ts +7 -5
  22. package/dist/db/tables/procedure_run.table.d.ts +2 -1
  23. package/dist/db/tables/procedure_run.table.js.map +1 -1
  24. package/dist/implementations/dms-automation/index.d.ts +2 -2
  25. package/dist/implementations/dms-automation/index.js.map +1 -1
  26. package/dist/index.js.map +1 -1
  27. package/dist/pages/category.js.map +1 -1
  28. package/dist/pages/index.js.map +1 -1
  29. package/dist/pages/overview.js.map +1 -1
  30. package/dist/pages/procedures.js.map +1 -1
  31. package/dist/pages/runs.js.map +1 -1
  32. package/dist/pages/shared.js +1 -1
  33. package/dist/pages/shared.js.map +1 -1
  34. package/dist/realtime.d.ts +2 -1
  35. package/dist/realtime.js.map +1 -1
  36. package/dist/routes/action-types.d.ts +3 -2
  37. package/dist/routes/action-types.js.map +1 -1
  38. package/dist/routes/data-node-types.d.ts +1 -1
  39. package/dist/routes/deleteConfirm.js +4 -3
  40. package/dist/routes/deleteConfirm.js.map +1 -1
  41. package/dist/routes/graphSchema.d.ts +2 -1
  42. package/dist/routes/graphSchema.js +13 -10
  43. package/dist/routes/graphSchema.js.map +1 -1
  44. package/dist/routes/library.d.ts +12 -1
  45. package/dist/routes/library.js +38 -34
  46. package/dist/routes/library.js.map +1 -1
  47. package/dist/routes/procedureChecks.js +5 -5
  48. package/dist/routes/procedureChecks.js.map +1 -1
  49. package/dist/routes/procedureRuns.d.ts +3 -3
  50. package/dist/routes/procedureRuns.js +1 -1
  51. package/dist/routes/procedureRuns.js.map +1 -1
  52. package/dist/routes/procedureSchemas.d.ts +7 -6
  53. package/dist/routes/procedureSchemas.js +4 -2
  54. package/dist/routes/procedureSchemas.js.map +1 -1
  55. package/dist/routes/procedures.d.ts +15 -14
  56. package/dist/routes/procedures.js +2 -1
  57. package/dist/routes/procedures.js.map +1 -1
  58. package/dist/routes/requests.d.ts +12 -6
  59. package/dist/routes/requests.js +2 -1
  60. package/dist/routes/requests.js.map +1 -1
  61. package/dist/routes/runs.d.ts +9 -8
  62. package/dist/routes/runs.js +5 -3
  63. package/dist/routes/runs.js.map +1 -1
  64. package/dist/routes/stats.js.map +1 -1
  65. package/dist/routes/templates.d.ts +5 -4
  66. package/dist/routes/templates.js +2 -1
  67. package/dist/routes/templates.js.map +1 -1
  68. package/dist/routes/trigger-types.d.ts +3 -2
  69. package/dist/routes/trigger-types.js.map +1 -1
  70. package/dist/routes/typeConfigShared.d.ts +2 -1
  71. package/dist/routes/typeConfigShared.js.map +1 -1
  72. package/dist/routes/zodJson.d.ts +3 -0
  73. package/dist/routes/zodJson.js +21 -0
  74. package/dist/routes/zodJson.js.map +1 -0
  75. package/dist/runtime/armErrors.d.ts +0 -1
  76. package/dist/runtime/armErrors.js +5 -12
  77. package/dist/runtime/armErrors.js.map +1 -1
  78. package/dist/runtime/boundRunLog.d.ts +7 -5
  79. package/dist/runtime/boundRunLog.js +24 -20
  80. package/dist/runtime/boundRunLog.js.map +1 -1
  81. package/dist/runtime/builtins/actions/http.d.ts +7 -3
  82. package/dist/runtime/builtins/actions/http.js +33 -22
  83. package/dist/runtime/builtins/actions/http.js.map +1 -1
  84. package/dist/runtime/builtins/actions/log.d.ts +5 -4
  85. package/dist/runtime/builtins/actions/log.js.map +1 -1
  86. package/dist/runtime/builtins/data/boolean.d.ts +2 -1
  87. package/dist/runtime/builtins/data/boolean.js +4 -5
  88. package/dist/runtime/builtins/data/boolean.js.map +1 -1
  89. package/dist/runtime/builtins/data/compare.js +8 -10
  90. package/dist/runtime/builtins/data/compare.js.map +1 -1
  91. package/dist/runtime/builtins/data/constant.js +1 -1
  92. package/dist/runtime/builtins/data/constant.js.map +1 -1
  93. package/dist/runtime/builtins/data/json.js +4 -5
  94. package/dist/runtime/builtins/data/json.js.map +1 -1
  95. package/dist/runtime/builtins/data/math.js +4 -4
  96. package/dist/runtime/builtins/data/math.js.map +1 -1
  97. package/dist/runtime/builtins/data/object.js +27 -27
  98. package/dist/runtime/builtins/data/object.js.map +1 -1
  99. package/dist/runtime/builtins/data/string.js +13 -18
  100. package/dist/runtime/builtins/data/string.js.map +1 -1
  101. package/dist/runtime/builtins/nodes/action.js +16 -5
  102. package/dist/runtime/builtins/nodes/action.js.map +1 -1
  103. package/dist/runtime/builtins/nodes/data.js +2 -2
  104. package/dist/runtime/builtins/nodes/data.js.map +1 -1
  105. package/dist/runtime/builtins/nodes/delay.js +2 -2
  106. package/dist/runtime/builtins/nodes/delay.js.map +1 -1
  107. package/dist/runtime/builtins/nodes/forRange.js +2 -2
  108. package/dist/runtime/builtins/nodes/forRange.js.map +1 -1
  109. package/dist/runtime/builtins/nodes/foreach.js +2 -2
  110. package/dist/runtime/builtins/nodes/foreach.js.map +1 -1
  111. package/dist/runtime/builtins/nodes/groupInput.js +2 -2
  112. package/dist/runtime/builtins/nodes/groupInput.js.map +1 -1
  113. package/dist/runtime/builtins/nodes/groupOutput.js +2 -2
  114. package/dist/runtime/builtins/nodes/groupOutput.js.map +1 -1
  115. package/dist/runtime/builtins/nodes/if.js +2 -2
  116. package/dist/runtime/builtins/nodes/if.js.map +1 -1
  117. package/dist/runtime/builtins/nodes/parallel.js +2 -2
  118. package/dist/runtime/builtins/nodes/parallel.js.map +1 -1
  119. package/dist/runtime/builtins/nodes/retry.js +13 -5
  120. package/dist/runtime/builtins/nodes/retry.js.map +1 -1
  121. package/dist/runtime/builtins/nodes/setVariable.js +2 -2
  122. package/dist/runtime/builtins/nodes/setVariable.js.map +1 -1
  123. package/dist/runtime/builtins/nodes/switch.js +8 -3
  124. package/dist/runtime/builtins/nodes/switch.js.map +1 -1
  125. package/dist/runtime/builtins/nodes/trigger.js +2 -2
  126. package/dist/runtime/builtins/nodes/trigger.js.map +1 -1
  127. package/dist/runtime/builtins/nodes/tryCatch.js +2 -2
  128. package/dist/runtime/builtins/nodes/tryCatch.js.map +1 -1
  129. package/dist/runtime/builtins/triggers/cron.d.ts +4 -3
  130. package/dist/runtime/builtins/triggers/cron.js +5 -7
  131. package/dist/runtime/builtins/triggers/cron.js.map +1 -1
  132. package/dist/runtime/builtins/triggers/webhook.d.ts +11 -7
  133. package/dist/runtime/builtins/triggers/webhook.js +15 -12
  134. package/dist/runtime/builtins/triggers/webhook.js.map +1 -1
  135. package/dist/runtime/declaredProcedures.d.ts +2 -2
  136. package/dist/runtime/declaredProcedures.js +3 -2
  137. package/dist/runtime/declaredProcedures.js.map +1 -1
  138. package/dist/runtime/describe.d.ts +3 -1
  139. package/dist/runtime/describe.js +14 -13
  140. package/dist/runtime/describe.js.map +1 -1
  141. package/dist/runtime/executor.d.ts +2 -1
  142. package/dist/runtime/executor.js +18 -13
  143. package/dist/runtime/executor.js.map +1 -1
  144. package/dist/runtime/flatten.d.ts +1 -1
  145. package/dist/runtime/flatten.js +1 -1
  146. package/dist/runtime/flatten.js.map +1 -1
  147. package/dist/runtime/graphIssues.d.ts +2 -2
  148. package/dist/runtime/graphIssues.js +39 -32
  149. package/dist/runtime/graphIssues.js.map +1 -1
  150. package/dist/runtime/graphVersion.d.ts +1 -1
  151. package/dist/runtime/graphVersion.js +4 -3
  152. package/dist/runtime/graphVersion.js.map +1 -1
  153. package/dist/runtime/nodeKinds.d.ts +6 -5
  154. package/dist/runtime/nodeKinds.js.map +1 -1
  155. package/dist/runtime/reconcile.d.ts +3 -0
  156. package/dist/runtime/reconcile.js +178 -0
  157. package/dist/runtime/reconcile.js.map +1 -0
  158. package/dist/runtime/registry.d.ts +3 -3
  159. package/dist/runtime/resolveInputs.d.ts +13 -8
  160. package/dist/runtime/resolveInputs.js +18 -18
  161. package/dist/runtime/resolveInputs.js.map +1 -1
  162. package/dist/runtime/resolveSubgraph.js +4 -5
  163. package/dist/runtime/resolveSubgraph.js.map +1 -1
  164. package/dist/runtime/retention.js.map +1 -1
  165. package/dist/runtime/runProcedure.d.ts +3 -2
  166. package/dist/runtime/runProcedure.js +2 -1
  167. package/dist/runtime/runProcedure.js.map +1 -1
  168. package/dist/runtime/schedule.js +3 -0
  169. package/dist/runtime/schedule.js.map +1 -1
  170. package/dist/runtime/schemaProperties.d.ts +3 -0
  171. package/dist/runtime/schemaProperties.js +7 -0
  172. package/dist/runtime/schemaProperties.js.map +1 -0
  173. package/dist/runtime/serialQueue.d.ts +1 -1
  174. package/dist/runtime/serialQueue.js +4 -4
  175. package/dist/runtime/serialQueue.js.map +1 -1
  176. package/dist/runtime/sideEffects.d.ts +2 -2
  177. package/dist/runtime/subscriptions.d.ts +6 -4
  178. package/dist/runtime/subscriptions.js +21 -180
  179. package/dist/runtime/subscriptions.js.map +1 -1
  180. package/dist/runtime/subwalk.js.map +1 -1
  181. package/dist/runtime/templateCacheState.d.ts +6 -0
  182. package/dist/runtime/templateCacheState.js +10 -0
  183. package/dist/runtime/templateCacheState.js.map +1 -0
  184. package/dist/runtime/templateUsages.js +4 -5
  185. package/dist/runtime/templateUsages.js.map +1 -1
  186. package/dist/runtime/topo.js +2 -4
  187. package/dist/runtime/topo.js.map +1 -1
  188. package/dist/runtime/trace.d.ts +5 -2
  189. package/dist/runtime/trace.js +27 -17
  190. package/dist/runtime/trace.js.map +1 -1
  191. package/dist/runtime/triggerHandles.d.ts +4 -3
  192. package/dist/runtime/triggerHandles.js +9 -1
  193. package/dist/runtime/triggerHandles.js.map +1 -1
  194. package/dist/runtime/typeOrigin.js +12 -1
  195. package/dist/runtime/typeOrigin.js.map +1 -1
  196. package/dist/runtime/validate.js.map +1 -1
  197. package/dist/runtime/validateTemplate.js.map +1 -1
  198. package/dist/runtime/withTimeout.js.map +1 -1
  199. package/dist/runtime/wording.js +12 -8
  200. package/dist/runtime/wording.js.map +1 -1
  201. package/dist/stats/health-banner.js.map +1 -1
  202. package/dist/stats/health.js.map +1 -1
  203. package/dist/stats/kpi.js +1 -1
  204. package/dist/stats/kpi.js.map +1 -1
  205. package/dist/stats/overview.js +2 -1
  206. package/dist/stats/overview.js.map +1 -1
  207. package/dist/types/dataValue.d.ts +7 -0
  208. package/dist/types/dataValue.js +56 -0
  209. package/dist/types/dataValue.js.map +1 -0
  210. package/dist/types/graph.d.ts +19 -13
  211. package/dist/types/graph.js +8 -0
  212. package/dist/types/graph.js.map +1 -1
  213. package/dist/types/guards.d.ts +8 -0
  214. package/dist/types/guards.js +35 -0
  215. package/dist/types/guards.js.map +1 -0
  216. package/dist/types/runLog.d.ts +8 -7
  217. package/dist/types/runLog.js.map +1 -1
  218. package/frontend-vue/app/build/components/editor/EditorBanners.vue +120 -0
  219. package/frontend-vue/app/build/components/editor/EditorChoiceModal.vue +44 -0
  220. package/frontend-vue/app/build/components/editor/EditorForkModal.vue +51 -0
  221. package/frontend-vue/app/build/components/editor/EditorHeader.vue +146 -0
  222. package/frontend-vue/app/build/components/editor/EditorSaveTemplateModal.vue +105 -0
  223. package/frontend-vue/app/build/components/editor/NodeInspectorDocs.vue +28 -0
  224. package/frontend-vue/app/build/components/editor/NodeInspectorRun.vue +48 -0
  225. package/frontend-vue/app/build/composables/editor/useBuilderMount.ts +129 -0
  226. package/frontend-vue/app/build/composables/editor/useBuilderSave.ts +256 -0
  227. package/frontend-vue/app/build/composables/editor/useBuilderShortcuts.ts +270 -0
  228. package/frontend-vue/app/build/composables/editor/useDraftProblems.ts +288 -0
  229. package/frontend-vue/app/build/composables/editor/useEditorContext.ts +388 -0
  230. package/frontend-vue/app/build/composables/editor/useEditorLoad.ts +158 -0
  231. package/frontend-vue/app/build/composables/editor/useForkToLocal.ts +193 -0
  232. package/frontend-vue/app/build/composables/editor/useGraphHistory.ts +113 -0
  233. package/frontend-vue/app/build/composables/editor/useGroupEditing.ts +445 -0
  234. package/frontend-vue/app/build/composables/editor/usePalette.ts +41 -0
  235. package/frontend-vue/app/build/composables/editor/useProcedureActions.ts +96 -0
  236. package/frontend-vue/app/build/composables/editor/useRunOverlay.ts +466 -0
  237. package/frontend-vue/app/build/composables/editor/useSaveAsTemplate.ts +172 -0
  238. package/frontend-vue/app/build/composables/editor/useSavedTriggers.ts +100 -0
  239. package/frontend-vue/app/build/composables/editor/useSubgraphNavigation.ts +270 -0
  240. package/frontend-vue/app/build/composables/editor/useUnsavedGuards.ts +233 -0
  241. package/frontend-vue/app/build/composables/graphCanvas/connect.ts +273 -0
  242. package/frontend-vue/app/build/composables/graphCanvas/edgeEvents.ts +172 -0
  243. package/frontend-vue/app/build/composables/graphCanvas/edges.ts +55 -0
  244. package/frontend-vue/app/build/composables/graphCanvas/handles.ts +181 -0
  245. package/frontend-vue/app/build/composables/graphCanvas/linkMenu.ts +123 -0
  246. package/frontend-vue/app/build/composables/graphCanvas/nodeData.ts +222 -0
  247. package/frontend-vue/app/build/composables/graphCanvas/placement.ts +248 -0
  248. package/frontend-vue/app/build/composables/graphCanvas/selection.ts +150 -0
  249. package/frontend-vue/app/build/composables/graphCanvas/types.ts +188 -0
  250. package/frontend-vue/app/build/composables/graphCanvas/view.ts +230 -0
  251. package/frontend-vue/app/build/types/editor.ts +94 -0
  252. package/frontend-vue/app/build/utils/editor/apiErrors.ts +74 -0
  253. package/frontend-vue/app/build/utils/editor/graphShape.ts +68 -0
  254. package/frontend-vue/app/build/utils/editor/groupPlan.ts +322 -0
  255. package/frontend-vue/app/build/utils/editor/groupPorts.ts +210 -0
  256. package/frontend-vue/app/build/utils/editor/keyboard.ts +22 -0
  257. package/frontend-vue/app/build/utils/inspectorFields.ts +117 -0
  258. package/frontend-vue/app/build/utils/templates.ts +88 -0
  259. package/frontend-vue/app/components/AttentionList.vue +2 -6
  260. package/frontend-vue/app/components/Catalog.vue +2 -1
  261. package/frontend-vue/app/components/Editor/GraphCanvas.vue +78 -1337
  262. package/frontend-vue/app/components/Editor/NodeInspector.vue +31 -123
  263. package/frontend-vue/app/components/Editor.vue +134 -3484
  264. package/frontend-vue/app/components/Templates.vue +14 -84
  265. package/frontend-vue/build/backend-boundary.ts +122 -0
  266. package/frontend-vue/dms.frontend.build.ts +2 -0
  267. package/frontend-vue/eslint-rules/index.mjs +103 -0
  268. package/frontend-vue/eslint.config.mjs +15 -0
  269. package/frontend-vue/package.json +8 -5
  270. package/frontend-vue/pnpm-lock.yaml +168 -139
  271. package/frontend-vue/tests/api-error-presentation.test.cjs +254 -0
  272. package/frontend-vue/tests/helpers/setup.cjs +44 -0
  273. package/package.json +18 -15
  274. package/skills/dms-automation/SKILL.md +2 -2
  275. package/skills/dms-automation/cases.json +58 -0
@@ -1,25 +1,25 @@
1
1
  <script setup lang="ts">
2
- import { computed, nextTick, onBeforeUnmount, onMounted, ref, type 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'
8
- import type { BreadcrumbItem } from '@nuxt/ui'
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'
2
+ import EditorBanners from '../build/components/editor/EditorBanners.vue'
3
+ import EditorChoiceModal from '../build/components/editor/EditorChoiceModal.vue'
4
+ import EditorForkModal from '../build/components/editor/EditorForkModal.vue'
5
+ import EditorHeader from '../build/components/editor/EditorHeader.vue'
6
+ import EditorSaveTemplateModal from '../build/components/editor/EditorSaveTemplateModal.vue'
7
+ import { createEditorContext } from '../build/composables/editor/useEditorContext'
8
+ import { useBuilderMount } from '../build/composables/editor/useBuilderMount'
9
+ import { useBuilderSave } from '../build/composables/editor/useBuilderSave'
10
+ import { useBuilderShortcuts } from '../build/composables/editor/useBuilderShortcuts'
11
+ import { useDraftProblems } from '../build/composables/editor/useDraftProblems'
12
+ import { useEditorLoad } from '../build/composables/editor/useEditorLoad'
13
+ import { useForkToLocal } from '../build/composables/editor/useForkToLocal'
14
+ import { useGraphHistory } from '../build/composables/editor/useGraphHistory'
15
+ import { useGroupEditing } from '../build/composables/editor/useGroupEditing'
16
+ import { usePalette } from '../build/composables/editor/usePalette'
17
+ import { useProcedureActions } from '../build/composables/editor/useProcedureActions'
18
+ import { useRunOverlay } from '../build/composables/editor/useRunOverlay'
19
+ import { useSaveAsTemplate } from '../build/composables/editor/useSaveAsTemplate'
20
+ import { useSavedTriggers } from '../build/composables/editor/useSavedTriggers'
21
+ import { seedSubgraphPath, useSubgraphNavigation } from '../build/composables/editor/useSubgraphNavigation'
22
+ import { useUnsavedGuards } from '../build/composables/editor/useUnsavedGuards'
23
23
 
24
24
  // Editor mode.
25
25
  //
@@ -51,3160 +51,61 @@ const props = withDefaults(
51
51
  },
52
52
  )
53
53
 
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()
62
-
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
66
- }
67
-
68
- function queryValue(key: string): string | null {
69
- return queryString(route.query[key])
70
- }
71
-
72
- const templateQueryId = computed(() => queryValue('template'))
73
-
74
- const editorMode = computed<'procedure' | 'template'>(() => (templateQueryId.value ? 'template' : 'procedure'))
75
-
76
- const editorTemplateId = computed<string | null>(() => (editorMode.value === 'template' ? templateQueryId.value : null))
77
-
78
- interface ProcedureRecord {
79
- _id: string
80
- name: string
81
- description: string
82
- enabled: boolean
83
- graph: ProcedureGraph
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
90
- }
91
-
92
- const { $authFetch } = useAuthFetch()
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 })
102
-
103
- const procedures = ref<ProcedureRecord[]>([])
104
- const selectedId = ref<string | null>(null)
105
- const switcherOpen = ref(false)
106
- const newProcedureOpen = ref(false)
107
- const runNowOpen = ref(false)
108
- const loading = ref(false)
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)
115
- const saving = ref(false)
116
- const running = ref(false)
117
-
118
- // Template-mode state. `templatePorts` holds the OUTER-face ports of the
119
- // edited template — they're not part of the editable subgraph but they ARE
120
- // the source of truth for the root-level groupInput/groupOutput sentinels'
121
- // handle sets. We pipe them through `currentParentGroupPorts` so GraphCanvas
122
- // renders them identically to how it renders a nested group's sentinels.
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')
126
-
127
- // The palette's catalogs, read with the page. They are optional for
128
- // editing: one the server cannot answer is an empty list.
129
- const triggerTypesRead = useApiData<TriggerType[]>('/api/automation/trigger-types')
130
- const actionTypesRead = useApiData<ActionType[]>('/api/automation/action-types')
131
- const dataNodeTypesRead = useApiData<DataNodeType[]>('/api/automation/data-node-types')
132
- // Per-NodeKind UI metadata served by the backend
133
- // (`/api/automation/node-kinds`). Drives the editor's GenericNode renderer
134
- // so the frontend doesn't need to know about specific kinds.
135
- const nodeKindsRead = useAutomationNodeKinds()
136
- const triggerTypes = computed(() => triggerTypesRead.data.value ?? [])
137
- const actionTypes = computed(() => actionTypesRead.data.value ?? [])
138
- const dataNodeTypes = computed(() => dataNodeTypesRead.data.value ?? [])
139
- const nodeKinds = computed(() => nodeKindsRead.data.value ?? [])
140
-
141
- // Workspace-global templates surfaced in the canvas's node palette. Empty
142
- // list → palette section hidden (handled inside BuilderPalette).
143
- //
144
- // Only the fields the palette + template-instance creation need are kept,
145
- // and handed over with the page: the list endpoint also returns the
146
- // description, the usage count and the hydrated subgraph. Under a key of its
147
- // own, apart from the library's full rows of the same URL.
148
- const templatesRead = useApiData<TemplateSummary[]>('/api/automation/templates', {
149
- key: 'dms-automation-palette-templates',
150
- transform: (value) =>
151
- (value as { results: TemplateSummary[] }).results.map((t) => ({
152
- _id: t._id,
153
- name: t.name,
154
- icon: t.icon,
155
- ports: Array.isArray(t.ports) ? t.ports : [],
156
- })),
157
- })
158
- const templates = computed(() => templatesRead.data.value ?? [])
159
-
160
- // Hide the palette section while editing a template (self-edit). The
161
- // server's cycle check would still catch any reference cycle, but blocking
162
- // it at the UI level keeps the UX cleaner — the user can't even attempt
163
- // to drop a template (including the one currently open) into itself.
164
- const palettesTemplates = computed<TemplateSummary[] | undefined>(() =>
165
- editorMode.value === 'template' ? undefined : templates.value,
166
- )
167
-
168
- // Triggers live at the top level of a procedure: the palette offers none
169
- // inside a group or a template.
170
- const paletteTriggerTypes = computed<TriggerType[]>(() =>
171
- editorMode.value === 'template' || subgraphPath.value.length > 1 ? [] : triggerTypes.value,
172
- )
173
-
174
- // The inspector (or the template's ports): docked beside the canvas from lg
175
- // (the palette starts folded below xl, so the canvas keeps most of the
176
- // width), floating over it on narrower screens.
177
- const ASIDE_CLASS =
178
- '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'
179
-
180
- // Which graph the canvas shows (procedure or template, then the groups
181
- // entered): the canvas fits a new one into view.
182
- const canvasViewKey = computed(() => [selectedId.value ?? '', ...subgraphPath.value.slice(1).map((segment) => segment.id)].join('/'))
183
-
184
- // Back to the Library's Templates tab, on the template being edited.
185
- const libraryBackUrl = computed(() =>
186
- editorTemplateId.value && !templateNotFound.value
187
- ? `/modules/automation/library?tab=templates&template=${editorTemplateId.value}`
188
- : '/modules/automation/library?tab=templates',
189
- )
190
-
191
- const selectedNodeId = ref<string | null>(null)
192
- // Mirrors GraphCanvas's @selection-change — full set of currently selected
193
- // node ids in the canvas, sentinel-filtered. Drives the "Group selection"
194
- // toolbar button (see canGroupSelection / createGroupFromSelection).
195
- const selectedNodeIds = ref<string[]>([])
196
-
197
- function onSelectionChange(payload: { ids: string[] }) {
198
- selectedNodeIds.value = payload.ids
199
- }
200
-
201
- // Subgraph navigation stack. The first entry is always the procedure root;
202
- // each subsequent entry is a group / template segment the user has entered.
203
- // Cleared and re-seeded whenever the selected procedure changes (see the
204
- // watch on selectedId below).
205
- //
206
- // kind === 'procedure' — id is the procedure _id, name is its display name.
207
- // kind === 'group' — id is the group node's id within its parent graph.
208
- // kind === 'template' — reserved for the dedicated template editor view.
209
- // Navigation into local groups pushes as 'group';
210
- // template instances likewise push as 'group' with
211
- // the read-only signal taken from the node having a
212
- // templateId, not from the path kind.
213
- interface SubgraphPathSegment {
214
- kind: 'procedure' | 'group' | 'template'
215
- id: string
216
- name: string
217
- }
218
-
219
- const subgraphPath = ref<SubgraphPathSegment[]>([])
220
-
221
- interface ProcedureSnapshot {
222
- name: string
223
- enabled: boolean
224
- graph: ProcedureGraph
225
- // Template mode only: the template's outer ports, edited at its root.
226
- ports?: GroupPort[]
227
- }
228
-
229
- const graphHistory = ref<ProcedureGraph[]>([])
230
- const graphHistoryIndex = ref<number>(-1)
231
- const savedSnapshot = ref<ProcedureSnapshot | null>(null)
232
- const HISTORY_LIMIT = 100
233
-
234
- function cloneGraph(g: ProcedureGraph): ProcedureGraph {
235
- return JSON.parse(JSON.stringify(g))
236
- }
237
-
238
- function takeSnapshot(p: ProcedureRecord): ProcedureSnapshot {
239
- return {
240
- name: p.name,
241
- enabled: p.enabled,
242
- graph: cloneGraph(p.graph),
243
- ...(editorMode.value === 'template' ? { ports: templatePorts.value.map((port) => ({ ...port })) } : {}),
244
- }
245
- }
246
-
247
- // Strip per-node position: a drag is told apart from a structural change.
248
- function structuralKey(g: ProcedureGraph): string {
249
- return JSON.stringify({
250
- nodes: g.nodes.map(({ position: _pos, ...rest }) => rest),
251
- triggerEdges: g.triggerEdges,
252
- dataEdges: g.dataEdges,
253
- })
254
- }
255
-
256
- /**
257
- * What a change does, when it is one a burst of changes repeats: the same
258
- * nodes moved ("move:a,b"), or the same settings of one node edited
259
- * ("edit:a:url"), at any depth of groups. `null` for anything else.
260
- */
261
- function repeatableChangeKey(before: ProcedureGraph, after: ProcedureGraph): string | null {
262
- if (JSON.stringify([before.triggerEdges, before.dataEdges]) !== JSON.stringify([after.triggerEdges, after.dataEdges])) return null
263
- if (before.nodes.length !== after.nodes.length) return null
264
- const moved: string[] = []
265
- let edited: string | null = null
266
- for (let i = 0; i < after.nodes.length; i++) {
267
- const a = before.nodes[i]! as GraphNode & Record<string, unknown>
268
- const b = after.nodes[i]! as GraphNode & Record<string, unknown>
269
- if (a.id !== b.id) return null
270
- const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])].filter((k) => JSON.stringify(a[k]) !== JSON.stringify(b[k]))
271
- if (keys.length === 0) continue
272
- if (keys.length === 1 && keys[0] === 'position') {
273
- moved.push(a.id)
274
- continue
275
- }
276
- if (edited) return null
277
- if (keys.length === 1 && keys[0] === 'subgraph' && a.subgraph && b.subgraph) {
278
- const inner = repeatableChangeKey(a.subgraph, b.subgraph)
279
- if (!inner) return null
280
- edited = `${a.id}/${inner}`
281
- continue
282
- }
283
- if (!keys.every((k) => k === 'config' || k === 'label')) return null
284
- const fields = Object.keys({ ...a.config, ...b.config }).filter((k) => JSON.stringify(a.config?.[k]) !== JSON.stringify(b.config?.[k]))
285
- edited = `${a.id}:${[...fields, ...(keys.includes('label') ? ['label'] : [])].join(',')}`
286
- }
287
- if (edited) return moved.length ? null : `edit:${edited}`
288
- return moved.length ? `move:${moved.join(',')}` : null
289
- }
290
-
291
- // A drag emits a graph per frame and a text field one per keystroke: the
292
- // changes of one burst make one undo step (the last one is replaced while
293
- // the same nodes move, or the same field is typed in, without a pause).
294
- const HISTORY_MERGE_MS = 1000
295
- let lastChange: { key: string | null; at: number } = { key: null, at: 0 }
296
-
297
- function pushHistory(g: ProcedureGraph, merge = false) {
298
- const current = graphHistory.value[graphHistoryIndex.value]
299
- if (current && JSON.stringify(current) === JSON.stringify(g)) return
300
- const key = merge && current ? repeatableChangeKey(current, g) : null
301
- const now = Date.now()
302
- const sameBurst = key !== null && key === lastChange.key && now - lastChange.at < HISTORY_MERGE_MS
303
- lastChange = { key, at: now }
304
- // A new action, a drag included, drops what Redo could bring back.
305
- graphHistory.value = graphHistory.value.slice(0, graphHistoryIndex.value + 1)
306
- if (sameBurst) {
307
- graphHistory.value[graphHistoryIndex.value] = cloneGraph(g)
308
- return
309
- }
310
- graphHistory.value.push(cloneGraph(g))
311
- graphHistoryIndex.value = graphHistory.value.length - 1
312
- if (graphHistory.value.length > HISTORY_LIMIT) {
313
- graphHistory.value.shift()
314
- graphHistoryIndex.value--
315
- }
316
- }
317
-
318
- function initHistoryAndSaved() {
319
- lastChange = { key: null, at: 0 }
320
- if (selected.value) {
321
- graphHistory.value = [cloneGraph(selected.value.graph)]
322
- graphHistoryIndex.value = 0
323
- savedSnapshot.value = takeSnapshot(selected.value)
324
- } else {
325
- graphHistory.value = []
326
- graphHistoryIndex.value = -1
327
- savedSnapshot.value = null
328
- }
329
- }
330
-
331
- const PROCEDURES_PAGE_SIZE = 200
332
-
333
- // What the builder opens, read with the page: every procedure, or the
334
- // template `?template=` names. The editor works on its own copy of what they
335
- // answered (`procedures`), which its drafts change.
336
- const procedureListRead = useApiData<ProcedureRecord[]>(
337
- () => (editorMode.value === 'procedure' ? 'dms-automation-builder-procedures' : null),
338
- async ({ $authFetch, signal }) => {
339
- // The API serves pages of PROCEDURES_PAGE_SIZE at most: read them all.
340
- const list: ProcedureRecord[] = []
341
- for (let page = 0; ; page++) {
342
- const { results } = await $authFetch<{ results: ProcedureRecord[] }>(
343
- `/api/automation/procedures?limit=${PROCEDURES_PAGE_SIZE}&page=${page}`,
344
- { signal },
345
- )
346
- list.push(...results)
347
- if (results.length < PROCEDURES_PAGE_SIZE) break
348
- }
349
- return list
350
- },
351
- )
352
-
353
- interface AutomationTemplateApi {
354
- _id: string
355
- name: string
356
- description?: string
357
- icon?: string
358
- ports: GroupPort[]
359
- subgraph: ProcedureGraph
360
- }
361
-
362
- const templateRead = useApiData<AutomationTemplateApi>(() =>
363
- editorTemplateId.value ? `/api/automation/templates/${editorTemplateId.value}` : null,
364
- )
365
-
366
- /** Opens what the procedure list answered: `?selected=`, else the procedure open, else the first. */
367
- function openList() {
368
- const error = procedureListRead.error.value
369
- if (error) {
370
- loadError.value = describeApiError(error)
371
- return
372
- }
373
- loadError.value = null
374
- // Copies: a draft changes the editor's records, not the read's.
375
- procedures.value = (procedureListRead.data.value ?? []).map((p) => ({ ...p }))
376
- if (
377
- selectedId.value &&
378
- !procedures.value.some((p) => p._id === selectedId.value)
379
- ) {
380
- selectedId.value = null
381
- }
382
- const requested = queryValue('selected')
383
- if (requested && procedures.value.some((p) => p._id === requested)) {
384
- selectedId.value = requested
385
- } else if (requested && !selectedId.value) {
386
- // A link to a deleted procedure opens none: the builder says so
387
- // and offers the switcher (see onMounted).
388
- missingProcedureId.value = requested
389
- return
390
- }
391
- if (!selectedId.value && procedures.value.length > 0) {
392
- const first = procedures.value[0]
393
- selectedId.value = first ? first._id : null
394
- }
395
- }
396
-
397
- /** Reads the procedure list again (one was created) and opens it. */
398
- async function loadList() {
399
- loading.value = true
400
- await procedureListRead.refresh()
401
- loading.value = false
402
- openList()
403
- }
404
-
405
- /** Opens what the template read answered, or says why there is none. */
406
- function openTemplate() {
407
- const id = editorTemplateId.value
408
- if (!id) {
409
- templateNotFound.value = true
410
- loadError.value = t('dms_automation.editor.templateNotFound')
411
- return
412
- }
413
- const error = templateRead.error.value
414
- const tpl = templateRead.data.value
415
- if (error || !tpl) {
416
- // Worded for users, the same on the server and in the browser (the
417
- // raw fetch error names an internal URL that differs between them).
418
- templateNotFound.value = apiErrorStatus(error) === 404
419
- loadError.value = templateNotFound.value ? t('dms_automation.editor.templateNotFound') : describeApiError(error)
420
- procedures.value = []
421
- selectedId.value = null
422
- templatePorts.value = []
423
- return
424
- }
425
- templateNotFound.value = false
426
- loadError.value = null
427
- // Adapt the template into the ProcedureRecord shape so the rest of
428
- // the editor (history, dirty-tracking, sentinel sync, group toolbar)
429
- // keeps working unchanged. `enabled` is meaningless for templates;
430
- // pin it to true so the "disabled" warning banner never appears.
431
- const adapted: ProcedureRecord = {
432
- _id: tpl._id,
433
- name: tpl.name,
434
- description: tpl.description ?? '',
435
- enabled: true,
436
- graph: tpl.subgraph,
437
- }
438
- procedures.value = [adapted]
439
- selectedId.value = adapted._id
440
- templateIcon.value = tpl.icon || 'i-ph-package'
441
- templatePorts.value = Array.isArray(tpl.ports)
442
- ? tpl.ports.map((p) => ({ ...p }))
443
- : []
444
- }
54
+ const ctx = createEditorContext(props)
55
+ const graphHistory = useGraphHistory(ctx)
56
+ const load = useEditorLoad(ctx)
445
57
 
446
58
  // What the builder opens is awaited: the server renders it, and the browser
447
59
  // opens the same from the data handed over. The catalogs, the templates and
448
60
  // the bar's figures are read meanwhile, in parallel.
449
- await Promise.all([procedureListRead, templateRead])
450
- if (editorMode.value === 'template') openTemplate()
451
- else openList()
452
-
453
- const selected = computed<ProcedureRecord | null>(
454
- () => procedures.value.find((p) => p._id === selectedId.value) ?? null,
455
- )
61
+ await Promise.all([load.procedureListRead, load.templateRead])
62
+ if (ctx.editorMode.value === 'template') load.openTemplate()
63
+ else load.openList()
456
64
 
457
65
  // `watch(selectedId, …)` (declared below) doesn't fire for the value
458
66
  // assigned during the awaits above, so seed history + savedSnapshot once
459
67
  // for the auto-selected procedure. Must come after `selected` is declared
460
68
  // — initHistoryAndSaved() reads selected.value.
461
- initHistoryAndSaved()
462
- seedSubgraphPath()
463
-
464
- function seedSubgraphPath() {
465
- const p = selected.value
466
- if (!p) {
467
- subgraphPath.value = []
468
- return
469
- }
470
- // In template mode the root segment is the template itself (we reuse the
471
- // 'template' kind already declared on SubgraphPathSegment). The breadcrumb
472
- // renders it with the i-ph-link icon, which is exactly what we want for
473
- // "Templates ▸ <name>".
474
- if (editorMode.value === 'template') {
475
- subgraphPath.value = [
476
- { kind: 'template', id: p._id, name: p.name || 'Template' },
477
- ]
478
- return
479
- }
480
- subgraphPath.value = [
481
- { kind: 'procedure', id: p._id, name: p.name || 'Procedure' },
482
- ]
483
- }
484
-
485
- // Walk the procedure graph following subgraphPath. Returns the full chain
486
- // of (segment, containerGraph, groupNode|null) so currentGraph and
487
- // currentParentGroupPorts can be derived from one traversal without
488
- // re-walking.
489
- //
490
- // If a path segment can't be resolved (e.g. the group node was deleted in
491
- // the outer graph), traversal stops at the last valid level — the caller
492
- // is expected to also watch the stale path and trim it (see the watch on
493
- // `selected.graph`).
494
- interface SubgraphFrame {
495
- segment: SubgraphPathSegment
496
- graph: ProcedureGraph
497
- // The group node that owns `graph` (i.e. graph === groupNode.subgraph).
498
- // Null for the procedure root.
499
- groupNode: GraphNode | null
500
- }
501
-
502
- const subgraphFrames = computed<SubgraphFrame[]>(() => {
503
- const p = selected.value
504
- if (!p) return []
505
- const path = subgraphPath.value
506
- if (path.length === 0) return []
507
- const frames: SubgraphFrame[] = [
508
- { segment: path[0]!, graph: p.graph, groupNode: null },
509
- ]
510
- for (let i = 1; i < path.length; i++) {
511
- const seg = path[i]!
512
- const parent = frames[i - 1]!
513
- const node = parent.graph.nodes.find(
514
- (n) => n.id === seg.id && n.kind === 'group',
515
- )
516
- if (!node) break
517
- // Local group → inline subgraph. Template instance → no inline
518
- // subgraph on the client, so we can't navigate in. The
519
- // double-click handler guards against pushing a template-instance
520
- // segment in the first place; this is a safety net.
521
- const sub = node.subgraph
522
- if (!sub) break
523
- frames.push({ segment: seg, graph: sub, groupNode: node })
524
- }
525
- return frames
526
- })
527
-
528
- const currentGraph = computed<ProcedureGraph | null>(() => {
529
- const frames = subgraphFrames.value
530
- if (frames.length === 0) return null
531
- return frames[frames.length - 1]!.graph
532
- })
533
-
534
- // The parent group node whose subgraph we're currently viewing — null at
535
- // the procedure root.
536
- const currentParentGroup = computed<GraphNode | null>(() => {
537
- const frames = subgraphFrames.value
538
- if (frames.length <= 1) return null
539
- return frames[frames.length - 1]!.groupNode
540
- })
541
-
542
- const currentParentGroupPorts = computed<GroupPort[] | undefined>(() => {
543
- const g = currentParentGroup.value
544
- if (g) return Array.isArray(g.ports) ? g.ports : []
545
- // Root level in template mode: the template's own `ports` are the
546
- // outer-face of the edited subgraph. Inject them so the root-level
547
- // groupInput / groupOutput sentinels render the right handles.
548
- if (editorMode.value === 'template') return templatePorts.value
549
- return undefined
550
- })
551
-
552
- // Read-only mode kicks in when viewing the inner subgraph of a template
553
- // instance (a group node carrying `templateId`). The fork action lets
554
- // the user promote it to a local group; until then we just show a
555
- // banner and disable mutations.
556
- const isCurrentGraphReadOnly = computed<boolean>(() => {
557
- const g = currentParentGroup.value
558
- if (!g) return false
559
- return Boolean(g.templateId)
560
- })
561
-
562
- const breadcrumbItems = computed<BreadcrumbItem[]>(() =>
563
- subgraphPath.value.map((seg, idx) => ({
564
- label: seg.name,
565
- icon:
566
- seg.kind === 'procedure'
567
- ? 'i-ph-flow-arrow'
568
- : seg.kind === 'template'
569
- ? 'i-ph-link'
570
- : 'i-ph-package',
571
- // onSelect fires for clicks; popping the path to `idx + 1` keeps
572
- // the clicked segment and discards everything deeper.
573
- onSelect: (ev: Event) => {
574
- ev.preventDefault()
575
- if (idx < subgraphPath.value.length - 1) {
576
- subgraphPath.value = subgraphPath.value.slice(0, idx + 1)
577
- // Clear node selection — the old selected node id may not
578
- // exist in the new current graph.
579
- selectedNodeId.value = null
580
- }
581
- },
582
- })),
583
- )
584
-
585
- // If the user deletes a group node from an outer graph while their path
586
- // points into its subgraph, prune the path back to the deepest valid
587
- // frame. Cheap because subgraphFrames already does the traversal.
588
- watch(
589
- () => subgraphFrames.value.length,
590
- (framesLen) => {
591
- if (framesLen > 0 && framesLen < subgraphPath.value.length) {
592
- subgraphPath.value = subgraphPath.value.slice(0, framesLen)
593
- selectedNodeId.value = null
594
- }
595
- },
596
- )
597
-
598
- // Keep the procedure-root breadcrumb label in sync with renames.
599
- watch(
600
- () => selected.value?.name,
601
- (name) => {
602
- const first = subgraphPath.value[0]
603
- if (first && first.kind === 'procedure' && name) first.name = name
604
- },
605
- )
606
-
607
- function exitSubgraph() {
608
- subgraphPath.value = subgraphPath.value.slice(0, -1)
609
- selectedNodeId.value = null
610
- }
611
-
612
- function onGraphUpdate(g: ProcedureGraph) {
613
- if (!selected.value) return
614
- const path = subgraphPath.value
615
- if (path.length <= 1) {
616
- // At procedure root — write straight through, same as before
617
- // subgraph navigation existed.
618
- selected.value.graph = g
619
- pushHistory(g, true)
620
- return
621
- }
622
- // At a deeper level — `g` is the subgraph of the deepest group node.
623
- // Walk the path from the outer procedure graph down, cloning the
624
- // chain so Vue's reactivity sees a fresh top-level graph (history
625
- // keys structuralKey() off node identity at every level).
626
- const rootGraph = cloneGraph(selected.value.graph)
627
- let containerNodes = rootGraph.nodes
628
- for (let i = 1; i < path.length; i++) {
629
- const seg = path[i]!
630
- const idx = containerNodes.findIndex(
631
- (n) => n.id === seg.id && n.kind === 'group',
632
- )
633
- if (idx === -1) {
634
- // Path was stale — bail out without mutating; the watch on
635
- // subgraphFrames.length will prune the path.
636
- return
637
- }
638
- // Replace the node at idx with a shallow clone so we can mutate
639
- // its `subgraph` without aliasing back into the original (the
640
- // outer graph already came from cloneGraph above, so its node
641
- // objects are fresh too — but the inner subgraph reference
642
- // chain needs explicit substitution).
643
- const cloned: GraphNode = { ...containerNodes[idx]! }
644
- containerNodes[idx] = cloned
645
- if (i === path.length - 1) {
646
- cloned.subgraph = g
647
- } else {
648
- // Mid-chain — keep walking, ensuring each intermediate
649
- // subgraph is also a fresh object for the next iteration's
650
- // nodes array.
651
- if (!cloned.subgraph) return
652
- cloned.subgraph = {
653
- ...cloned.subgraph,
654
- nodes: [...cloned.subgraph.nodes],
655
- }
656
- containerNodes = cloned.subgraph.nodes
657
- }
658
- }
659
- selected.value.graph = rootGraph
660
- pushHistory(rootGraph, true)
661
- }
662
-
663
- const canUndo = computed<boolean>(
664
- () => graphHistoryIndex.value > 0,
665
- )
666
- const canRedo = computed<boolean>(
667
- () => graphHistoryIndex.value < graphHistory.value.length - 1,
668
- )
669
- const isDirty = computed<boolean>(() => {
670
- if (!selected.value || !savedSnapshot.value) return false
671
- return (
672
- JSON.stringify(takeSnapshot(selected.value)) !==
673
- JSON.stringify(savedSnapshot.value)
674
- )
675
- })
676
-
677
- function onUndo() {
678
- if (!canUndo.value || !selected.value) return
679
- lastChange = { key: null, at: 0 }
680
- graphHistoryIndex.value--
681
- const g = graphHistory.value[graphHistoryIndex.value]
682
- if (g) selected.value.graph = cloneGraph(g)
683
- }
684
-
685
- function onRedo() {
686
- if (!canRedo.value || !selected.value) return
687
- lastChange = { key: null, at: 0 }
688
- graphHistoryIndex.value++
689
- const g = graphHistory.value[graphHistoryIndex.value]
690
- if (g) selected.value.graph = cloneGraph(g)
691
- }
692
-
693
- function onCancel() {
694
- if (!selected.value || !savedSnapshot.value) return
695
- const snap = savedSnapshot.value
696
- selected.value.name = snap.name
697
- selected.value.enabled = snap.enabled
698
- selected.value.graph = cloneGraph(snap.graph)
699
- if (snap.ports) templatePorts.value = snap.ports.map((port) => ({ ...port }))
700
- pushHistory(selected.value.graph)
701
- // A refused save is answered by the draft it refused: discarding it
702
- // clears the banner, and the name, outside the graph, is checked again.
703
- saveBlocked.value = false
704
- void validateDraft()
705
- }
706
-
707
- const selectedNode = computed<GraphNode | null>(() => {
708
- const id = selectedNodeId.value
709
- if (!id) return null
710
- // Lookup is scoped to whichever graph the canvas is currently
711
- // bound to, not always the procedure root — otherwise selecting a
712
- // node inside a subgraph would resolve to null.
713
- const g = currentGraph.value
714
- if (!g) return null
715
- return g.nodes.find((n) => n.id === id) ?? null
716
- })
717
-
718
- const selectedNodeTriggerType = computed<TriggerType | null>(() => {
719
- const n = selectedNode.value
720
- if (!n || n.kind !== 'trigger') return null
721
- return triggerTypes.value.find((t) => t.id === n.typeId) ?? null
722
- })
723
-
724
- const selectedNodeActionType = computed<ActionType | null>(() => {
725
- const n = selectedNode.value
726
- if (!n || n.kind !== 'action') return null
727
- return actionTypes.value.find((a) => a.id === n.typeId) ?? null
728
- })
729
-
730
- function onSelectNode(id: string | null) {
731
- selectedNodeId.value = id
732
- }
733
-
734
- // The node palette lives in the left BuilderPalette sidebar; its add events are
735
- // forwarded to the canvas' exposed helpers via this template ref.
736
- const graphCanvasRef = ref<{
737
- addNode: (kind: string, typeId?: string) => void
738
- addTemplateInstance: (template: { _id: string; name: string; icon?: string; ports: GroupPort[] }) => void
739
- } | null>(null)
740
-
741
- function onPaletteAddNode(payload: { kind: string; typeId?: string }) {
742
- graphCanvasRef.value?.addNode(payload.kind, payload.typeId)
743
- }
744
- function onPaletteAddTemplate(template: { _id: string; name: string; icon?: string; ports: GroupPort[] }) {
745
- graphCanvasRef.value?.addTemplateInstance(template)
746
- }
747
-
748
- watch(selectedId, () => {
749
- selectedNodeId.value = null
750
- initHistoryAndSaved()
751
- seedSubgraphPath()
752
- })
753
-
754
- // `?template=<id>` changed while the editor stayed mounted (Editor is
755
- // mounted once per route navigation, so this is mostly a guard for in-place
756
- // query updates, e.g. catalog "Edit" buttons using router.push): the template
757
- // read follows the URL, and the editor opens what it answers.
758
- watch(
759
- () => templateRead.status.value,
760
- (status) => {
761
- if (editorMode.value === 'template' && (status === 'success' || status === 'error')) openTemplate()
762
- },
763
- )
764
-
765
- /** A group's name: its step name, else the name it was created with. */
766
- function groupName(node: GraphNode): string {
767
- return node.label || (node.config?.name as string | undefined) || t('dms_automation.editor.groupDefaultName')
768
- }
769
-
770
- function onGroupEnter(payload: { id: string }) {
771
- const g = currentGraph.value
772
- if (!g) return
773
- const node = g.nodes.find((n) => n.id === payload.id && n.kind === 'group')
774
- if (!node) return
775
- // Template instances have no inline subgraph — the frame walker would
776
- // stop at this segment and the watcher would prune it back. Bail early so
777
- // the path doesn't briefly include a doomed segment.
778
- if (node.templateId && !node.subgraph) return
779
- const name = groupName(node)
780
- subgraphPath.value = [
781
- ...subgraphPath.value,
782
- { kind: 'group', id: node.id, name },
783
- ]
784
- selectedNodeId.value = null
785
- }
786
-
787
- // "Enter group" affordance — true iff the currently selected node is a group
788
- // (local, or a template instance with a resolved subgraph). Read-only state
789
- // is not consulted: entering a group from a read-only view is allowed.
790
- // Drives the toolbar button, the inspector button, and the Tab keybinding.
791
- const canEnterGroup = computed<boolean>(() => {
792
- const n = selectedNode.value
793
- if (!n || n.kind !== 'group') return false
794
- // Template instances need a resolved subgraph to navigate into; without
795
- // one we can't render the inner view.
796
- if (n.templateId && !n.subgraph) return false
797
- return true
798
- })
799
-
800
- function enterSelectedGroup() {
801
- const n = selectedNode.value
802
- if (!n || n.kind !== 'group') return
803
- onGroupEnter({ id: n.id })
804
- }
805
-
806
- function onUpdateNode(updated: GraphNode) {
807
- const g = currentGraph.value
808
- if (!g) return
809
- const nextGraph: ProcedureGraph = {
810
- ...g,
811
- nodes: g.nodes.map((n) => (n.id === updated.id ? updated : n)),
812
- }
813
- onGraphUpdate(nextGraph)
814
- }
815
-
816
- // Detect port renames between two port arrays of the same group node.
817
- //
818
- // Two-pass matching, scoped per (kind, direction):
819
- // 1. Ports present in BOTH arrays under the same (kind, direction, name) are
820
- // considered identical — no rename.
821
- // 2. Of the remaining old/new ports, pair them positionally within each
822
- // (kind, direction) bucket. Each pair is a rename (old.name → new.name).
823
- // Unpaired old-only ports are true deletions; unpaired new-only ports are
824
- // true additions.
825
- //
826
- // This is heuristic but the GroupPortEditor emits one mutation per UX action,
827
- // so each ports:update typically carries a single delta and the positional
828
- // pairing is unambiguous.
829
- interface PortRename {
830
- kind: 'data' | 'trigger'
831
- direction: 'in' | 'out'
832
- oldName: string
833
- newName: string
834
- }
835
-
836
- function detectPortRenames(
837
- oldPorts: GroupPort[],
838
- newPorts: GroupPort[],
839
- ): PortRename[] {
840
- const renames: PortRename[] = []
841
- const buckets: Array<{ kind: 'data' | 'trigger'; direction: 'in' | 'out' }> = [
842
- { kind: 'data', direction: 'in' },
843
- { kind: 'data', direction: 'out' },
844
- { kind: 'trigger', direction: 'in' },
845
- { kind: 'trigger', direction: 'out' },
846
- ]
847
- for (const b of buckets) {
848
- const oldInBucket = oldPorts.filter(
849
- (p) => p.kind === b.kind && p.direction === b.direction,
850
- )
851
- const newInBucket = newPorts.filter(
852
- (p) => p.kind === b.kind && p.direction === b.direction,
853
- )
854
- const newNames = new Set(newInBucket.map((p) => p.name))
855
- const oldNames = new Set(oldInBucket.map((p) => p.name))
856
- // Ports that exist in both arrays with the same name didn't change.
857
- const oldOnly = oldInBucket.filter((p) => !newNames.has(p.name))
858
- const newOnly = newInBucket.filter((p) => !oldNames.has(p.name))
859
- const pairCount = Math.min(oldOnly.length, newOnly.length)
860
- for (let i = 0; i < pairCount; i++) {
861
- renames.push({
862
- kind: b.kind,
863
- direction: b.direction,
864
- oldName: oldOnly[i]!.name,
865
- newName: newOnly[i]!.name,
866
- })
867
- }
868
- }
869
- return renames
870
- }
871
-
872
- // Rewrite edge endpoints that referenced the renamed port names. Mutates the
873
- // provided edge arrays in place.
874
- //
875
- // `nodeId` is the node owning the renamed ports — either the outer group node
876
- // (for the outer graph's edges) or a sentinel node id inside the subgraph (for
877
- // the inner edges). The direction of the rename determines which edge end is
878
- // affected:
879
- // • data/in → edge.to.field when edge.to.node === nodeId
880
- // • data/out → edge.from.port when edge.from.node === nodeId
881
- // • trigger/in → edge.to.branch when edge.to.node === nodeId
882
- // • trigger/out → edge.from.branch when edge.from.node === nodeId
883
- //
884
- // For the inner subgraph, the sentinels invert the direction (an inbound port
885
- // on the group is an OUTBOUND handle on the groupInput sentinel and vice
886
- // versa). Callers pass `invertDirection: true` so a group-level "in" rename is
887
- // applied to the sentinel's "out" handles, etc.
888
- function applyPortRenamesToEdges(
889
- triggerEdges: TriggerEdge[],
890
- dataEdges: DataEdge[],
891
- nodeId: string,
892
- renames: PortRename[],
893
- invertDirection: boolean,
894
- ): void {
895
- for (const r of renames) {
896
- const effectiveDirection = invertDirection
897
- ? r.direction === 'in'
898
- ? 'out'
899
- : 'in'
900
- : r.direction
901
- if (r.kind === 'data') {
902
- if (effectiveDirection === 'out') {
903
- for (const e of dataEdges) {
904
- if (e.from.node === nodeId && e.from.port === r.oldName) {
905
- e.from.port = r.newName
906
- }
907
- }
908
- } else {
909
- for (const e of dataEdges) {
910
- if (e.to.node === nodeId && e.to.field === r.oldName) {
911
- e.to.field = r.newName
912
- }
913
- }
914
- }
915
- } else {
916
- if (effectiveDirection === 'out') {
917
- for (const e of triggerEdges) {
918
- if (e.from.node === nodeId && e.from.branch === r.oldName) {
919
- e.from.branch = r.newName
920
- }
921
- }
922
- } else {
923
- for (const e of triggerEdges) {
924
- if (e.to.node === nodeId && e.to.branch === r.oldName) {
925
- e.to.branch = r.newName
926
- }
927
- }
928
- }
929
- }
930
- }
931
- }
932
-
933
- // Make sure the group node's local subgraph has the sentinels and that no
934
- // inner edge references a port that was just removed. The sentinels are
935
- // auto-managed (the user never creates them by hand); their handle set is
936
- // derived at render time from the parent group's `ports` array (see
937
- // GraphCanvas.vue `parent-group-ports` prop plumbing), so this
938
- // function only owns four responsibilities:
939
- // 1. Ensure a single groupInput and a single groupOutput exist.
940
- // 2. Drop data edges whose source/target port no longer exists.
941
- // 3. Drop trigger edges whose source branch (originating at groupInput)
942
- // no longer exists.
943
- // 4. Drop trigger edges into groupOutput whose target port (`to.branch`)
944
- // no longer exists.
945
- function syncSentinels(group: GraphNode): void {
946
- if (!group.subgraph) return
947
-
948
- let gi = group.subgraph.nodes.find((n) => n.kind === 'groupInput')
949
- let go = group.subgraph.nodes.find((n) => n.kind === 'groupOutput')
950
-
951
- if (!gi) {
952
- gi = {
953
- id: newId(),
954
- kind: 'groupInput',
955
- config: {},
956
- position: { x: 0, y: 0 },
957
- }
958
- group.subgraph.nodes.push(gi)
959
- }
960
- if (!go) {
961
- go = {
962
- id: newId(),
963
- kind: 'groupOutput',
964
- config: {},
965
- position: { x: 600, y: 0 },
966
- }
967
- group.subgraph.nodes.push(go)
968
- }
969
-
970
- const ports = Array.isArray(group.ports) ? group.ports : []
971
- const validDataIn = new Set(
972
- ports
973
- .filter((p) => p.kind === 'data' && p.direction === 'in')
974
- .map((p) => p.name),
975
- )
976
- const validDataOut = new Set(
977
- ports
978
- .filter((p) => p.kind === 'data' && p.direction === 'out')
979
- .map((p) => p.name),
980
- )
981
- const validTriggerIn = new Set(
982
- ports
983
- .filter((p) => p.kind === 'trigger' && p.direction === 'in')
984
- .map((p) => p.name),
985
- )
986
- const validTriggerOut = new Set(
987
- ports
988
- .filter((p) => p.kind === 'trigger' && p.direction === 'out')
989
- .map((p) => p.name),
990
- )
991
-
992
- const giId = gi.id
993
- const goId = go.id
994
-
995
- group.subgraph.dataEdges = group.subgraph.dataEdges.filter((e) => {
996
- if (e.from.node === giId && !validDataIn.has(e.from.port)) return false
997
- if (e.to.node === goId && !validDataOut.has(e.to.field)) return false
998
- return true
999
- })
1000
-
1001
- group.subgraph.triggerEdges = group.subgraph.triggerEdges.filter((e) => {
1002
- // trigger edges OUT OF groupInput carry the port name as `from.branch`
1003
- // (the same convention if/switch use for named branches).
1004
- if (e.from.node === giId) {
1005
- const branch = e.from.branch ?? 'main'
1006
- if (!validTriggerIn.has(branch)) return false
1007
- }
1008
- // trigger edges INTO groupOutput carry the target port name on
1009
- // `to.branch`. If the port has been removed from the group's
1010
- // declarations, drop the edge.
1011
- if (e.to.node === goId && e.to.branch !== undefined) {
1012
- if (!validTriggerOut.has(e.to.branch)) return false
1013
- }
1014
- return true
1015
- })
1016
- }
1017
-
1018
- function onPortsUpdate(payload: { nodeId: string; ports: GroupPort[] }) {
1019
- const g = currentGraph.value
1020
- if (!g) return
1021
- const idx = g.nodes.findIndex(
1022
- (n) => n.id === payload.nodeId && n.kind === 'group',
1023
- )
1024
- if (idx === -1) return
1025
- const existing = g.nodes[idx]!
1026
- // Template instances don't own a local subgraph — their `ports` come from
1027
- // the template definition and are read-only on the instance. Defensive:
1028
- // silently no-op if someone managed to invoke the editor on one.
1029
- if (existing.templateId) return
1030
-
1031
- // Detect renames against the PREVIOUS ports array BEFORE we replace it.
1032
- // Pure additions and pure deletions yield no renames; syncSentinels still
1033
- // handles deletions by dropping orphaned inner edges, and the outer graph
1034
- // has no edges for added ports yet, so neither needs port-name rewrites.
1035
- const oldPorts = Array.isArray(existing.ports) ? existing.ports : []
1036
- const renames = detectPortRenames(oldPorts, payload.ports)
1037
-
1038
- // Build a deep-cloned group node so syncSentinels can mutate its subgraph
1039
- // freely without aliasing into the current graph's state. The outer
1040
- // onUpdateNode/onGraphUpdate path expects a fresh node reference.
1041
- const clonedGroup: GraphNode = {
1042
- ...existing,
1043
- ports: payload.ports.map((p) => ({ ...p })),
1044
- subgraph: existing.subgraph
1045
- ? (JSON.parse(JSON.stringify(existing.subgraph)) as ProcedureGraph)
1046
- : undefined,
1047
- }
1048
-
1049
- // Cascade renames into the INNER subgraph before syncSentinels runs — if
1050
- // we waited until after, syncSentinels would treat the old port names
1051
- // still on inner edges as references to deleted ports and drop them.
1052
- if (renames.length > 0 && clonedGroup.subgraph) {
1053
- const gi = clonedGroup.subgraph.nodes.find((n) => n.kind === 'groupInput')
1054
- const go = clonedGroup.subgraph.nodes.find((n) => n.kind === 'groupOutput')
1055
- // Group-level "in" ports surface as groupInput's OUT handles, and
1056
- // group-level "out" ports surface as groupOutput's IN handles. We pass
1057
- // invertDirection=true and target the right sentinel per direction.
1058
- const inRenames = renames.filter((r) => r.direction === 'in')
1059
- const outRenames = renames.filter((r) => r.direction === 'out')
1060
- if (gi && inRenames.length > 0) {
1061
- applyPortRenamesToEdges(
1062
- clonedGroup.subgraph.triggerEdges,
1063
- clonedGroup.subgraph.dataEdges,
1064
- gi.id,
1065
- inRenames,
1066
- true,
1067
- )
1068
- }
1069
- if (go && outRenames.length > 0) {
1070
- applyPortRenamesToEdges(
1071
- clonedGroup.subgraph.triggerEdges,
1072
- clonedGroup.subgraph.dataEdges,
1073
- go.id,
1074
- outRenames,
1075
- true,
1076
- )
1077
- }
1078
- }
1079
-
1080
- syncSentinels(clonedGroup)
1081
-
1082
- // Cascade renames into the OUTER graph's edges (where this group node is
1083
- // an endpoint). We do this by walking the current graph, cloning the
1084
- // triggerEdges / dataEdges arrays, applying the renames, then going
1085
- // through onGraphUpdate so history + dirty tracking pick it up. We can't
1086
- // rely on onUpdateNode for outer-edge changes because it only replaces
1087
- // the node, not the edges.
1088
- if (renames.length > 0) {
1089
- const nextOuter: ProcedureGraph = {
1090
- ...g,
1091
- nodes: g.nodes.map((n, i) => (i === idx ? clonedGroup : n)),
1092
- triggerEdges: g.triggerEdges.map((e) => ({
1093
- ...e,
1094
- from: { ...e.from },
1095
- to: { ...e.to },
1096
- })),
1097
- dataEdges: g.dataEdges.map((e) => ({
1098
- ...e,
1099
- from: { ...e.from },
1100
- to: { ...e.to },
1101
- })),
1102
- }
1103
- applyPortRenamesToEdges(
1104
- nextOuter.triggerEdges,
1105
- nextOuter.dataEdges,
1106
- payload.nodeId,
1107
- renames,
1108
- false,
1109
- )
1110
- onGraphUpdate(nextOuter)
1111
- return
1112
- }
1113
-
1114
- onUpdateNode(clonedGroup)
1115
- }
1116
-
1117
- function onUnwireField(payload: { field: string }) {
1118
- const g = currentGraph.value
1119
- if (!g || !selectedNode.value) return
1120
- const nodeId = selectedNode.value.id
1121
- const nextGraph: ProcedureGraph = {
1122
- ...g,
1123
- dataEdges: g.dataEdges.filter(
1124
- (e) => !(e.to.node === nodeId && e.to.field === payload.field),
1125
- ),
1126
- }
1127
- onGraphUpdate(nextGraph)
1128
- }
1129
-
1130
- // Inspector "Delete node" button — same outcome as pressing Delete/Backspace
1131
- // on the canvas: drop the node plus every trigger/data edge that touches it.
1132
- function onDeleteNode(payload: { id: string }) {
1133
- const g = currentGraph.value
1134
- if (!g || isCurrentGraphReadOnly.value) return
1135
- const id = payload.id
1136
- const nextGraph: ProcedureGraph = {
1137
- ...g,
1138
- nodes: g.nodes.filter((n) => n.id !== id),
1139
- triggerEdges: g.triggerEdges.filter(
1140
- (e) => e.from.node !== id && e.to.node !== id,
1141
- ),
1142
- dataEdges: g.dataEdges.filter(
1143
- (e) => e.from.node !== id && e.to.node !== id,
1144
- ),
1145
- }
1146
- if (selectedNodeId.value === id) selectedNodeId.value = null
1147
- onGraphUpdate(nextGraph)
1148
- }
1149
-
1150
- // ---------------------------------------------------------------------------
1151
- // Create-group-from-selection
1152
- // ---------------------------------------------------------------------------
1153
- // Visible when the user has selected one or more eligible nodes in the
1154
- // current canvas. "Eligible" rules out kinds that can't legally live inside
1155
- // a group's subgraph in v1:
1156
- // • `trigger` — triggers must live at the top level of a procedure.
1157
- // • `groupInput` / `groupOutput` — sentinels are auto-managed and only
1158
- // valid inside their owning group.
1159
- // Selection containing multiple groups IS allowed: nesting an existing
1160
- // group inside a new one is just a regular subgraph node move; the v1
1161
- // validator doesn't forbid it, and the executor's depth cap catches
1162
- // runaway recursion.
1163
- //
1164
- // Also gated on:
1165
- // • An editable graph (not the read-only template-instance view).
1166
- // • A real procedure being open (selected.value).
1167
- const canGroupSelection = computed<boolean>(() => {
1168
- if (!selected.value) return false
1169
- if (isCurrentGraphReadOnly.value) return false
1170
- const ids = selectedNodeIds.value
1171
- if (ids.length === 0) return false
1172
- const g = currentGraph.value
1173
- if (!g) return false
1174
- const idSet = new Set(ids)
1175
- for (const n of g.nodes) {
1176
- if (!idSet.has(n.id)) continue
1177
- if (n.kind === 'trigger') return false
1178
- if (n.kind === 'groupInput' || n.kind === 'groupOutput') return false
1179
- }
1180
- return true
1181
- })
1182
-
1183
- // Friendly default port names. Each cut edge maps to a desired name based on
1184
- // the user-facing label on the cut side; if two edges land on the same name
1185
- // (e.g. two inside actions both have an `input` field), we suffix `-2`, `-3`
1186
- // per (kind, direction). The user can rename later in the GroupPortEditor.
1187
- //
1188
- // Port name picks:
1189
- // data-in → target node's input field name
1190
- // data-out → source node's output port name
1191
- // trigger-in → source branch label if present, else 'main'
1192
- // trigger-out → source branch label if present, else 'main'
1193
- //
1194
- // The "main" default for non-branching trigger cuts is intentional: the
1195
- // GroupNode / sentinel renderers place a trigger port named "main" on the
1196
- // title bar (mirroring ordinary trigger/action nodes), so a typical group
1197
- // wrapping linear flow looks just like a single action — title-bar in/out.
1198
- // Branch-labeled ports (if.then, switch.<case>, …) render in the body.
1199
- function desiredPortNameForTrigger(branch: string | undefined): string {
1200
- return branch && branch.length > 0 ? branch : 'main'
1201
- }
1202
-
1203
- // Dedup against an already-declared set scoped to (kind, direction). The set
1204
- // is mutated as new names are reserved.
1205
- function uniqueName(desired: string, taken: Set<string>): string {
1206
- if (!taken.has(desired)) {
1207
- taken.add(desired)
1208
- return desired
1209
- }
1210
- let i = 2
1211
- while (taken.has(`${desired}-${i}`)) i++
1212
- const final = `${desired}-${i}`
1213
- taken.add(final)
1214
- return final
1215
- }
1216
-
1217
- interface NewGroupPlan {
1218
- groupId: string
1219
- groupPorts: GroupPort[]
1220
- // Sentinel node ids — the planner generates them up front so its inner
1221
- // edges reference real ids; the caller installs the sentinel nodes
1222
- // under these ids.
1223
- groupInputId: string
1224
- groupOutputId: string
1225
- // Edges to add to the outer graph (replacements for cut edges).
1226
- outerTriggerEdges: TriggerEdge[]
1227
- outerDataEdges: DataEdge[]
1228
- // Edges to add inside the new subgraph (connecting sentinels to the
1229
- // inner endpoints of the cut edges).
1230
- innerTriggerEdges: TriggerEdge[]
1231
- innerDataEdges: DataEdge[]
1232
- }
1233
-
1234
- // Build a JsonSchema property bag from a kind's declared static port
1235
- // list — used as the fallback when no type-registry schema applies.
1236
- function staticPortsToSchema(
1237
- ports: ReadonlyArray<{ name: string; type?: string }>,
1238
- ): JsonSchema {
1239
- const properties: Record<string, JsonSchemaProperty> = {}
1240
- for (const p of ports) {
1241
- properties[p.name] = p.type ? { type: p.type } : {}
1242
- }
1243
- return { properties }
1244
- }
1245
-
1246
- function findSchemaForDataSourcePort(nodeId: string, port: string): JsonSchema | undefined {
1247
- const g = currentGraph.value
1248
- if (!g) return undefined
1249
- const node = g.nodes.find((n) => n.id === nodeId)
1250
- if (!node) return undefined
1251
- // `group` carries its ports on the node itself, not in the kind registry.
1252
- if (node.kind === 'group') {
1253
- const p = (node.ports ?? []).find(
1254
- (pp) => pp.kind === 'data' && pp.direction === 'out' && pp.name === port,
1255
- )
1256
- return p?.schema as JsonSchema | undefined
1257
- }
1258
- const ui = nodeKinds.value.find((k) => k.kind === node.kind)?.meta.ui
1259
- if (!ui) return undefined
1260
- let outputSchema: JsonSchema | undefined
1261
- if (ui.typeRegistry && ui.dataOutsFromTypeSchema) {
1262
- const key = ui.dataOutsFromTypeSchema
1263
- if (ui.typeRegistry === 'triggers') {
1264
- const t = triggerTypes.value.find((tt) => tt.id === node.typeId) as
1265
- | Record<string, JsonSchema | undefined>
1266
- | undefined
1267
- outputSchema = t?.[key]
1268
- } else if (ui.typeRegistry === 'actions') {
1269
- const a = actionTypes.value.find((aa) => aa.id === node.typeId) as
1270
- | Record<string, JsonSchema | undefined>
1271
- | undefined
1272
- outputSchema = a?.[key]
1273
- } else {
1274
- const d = dataNodeTypes.value.find((dd) => dd.id === node.typeId) as
1275
- | Record<string, JsonSchema | undefined>
1276
- | undefined
1277
- outputSchema = d?.[key]
1278
- }
1279
- }
1280
- if (!outputSchema && ui.staticDataOuts.length > 0) {
1281
- outputSchema = staticPortsToSchema(ui.staticDataOuts)
1282
- }
1283
- const prop = outputSchema?.properties?.[port]
1284
- if (!prop) return undefined
1285
- return prop as JsonSchema
1286
- }
1287
-
1288
- function findSchemaForDataTargetField(nodeId: string, field: string): JsonSchema | undefined {
1289
- const g = currentGraph.value
1290
- if (!g) return undefined
1291
- const node = g.nodes.find((n) => n.id === nodeId)
1292
- if (!node) return undefined
1293
- if (node.kind === 'group') {
1294
- const p = (node.ports ?? []).find(
1295
- (pp) => pp.kind === 'data' && pp.direction === 'in' && pp.name === field,
1296
- )
1297
- return p?.schema as JsonSchema | undefined
1298
- }
1299
- const ui = nodeKinds.value.find((k) => k.kind === node.kind)?.meta.ui
1300
- if (!ui) return undefined
1301
- let inputSchema: JsonSchema | undefined
1302
- if (ui.typeRegistry && ui.dataInsFromTypeSchema) {
1303
- const key = ui.dataInsFromTypeSchema
1304
- if (ui.typeRegistry === 'actions') {
1305
- const a = actionTypes.value.find((aa) => aa.id === node.typeId) as
1306
- | Record<string, JsonSchema | undefined>
1307
- | undefined
1308
- inputSchema = a?.[key]
1309
- } else if (ui.typeRegistry === 'dataNodes') {
1310
- const d = dataNodeTypes.value.find((dd) => dd.id === node.typeId) as
1311
- | Record<string, JsonSchema | undefined>
1312
- | undefined
1313
- inputSchema = d?.[key]
1314
- } else {
1315
- const t = triggerTypes.value.find((tt) => tt.id === node.typeId) as
1316
- | Record<string, JsonSchema | undefined>
1317
- | undefined
1318
- inputSchema = t?.[key]
1319
- }
1320
- }
1321
- if (!inputSchema && ui.staticDataIns.length > 0) {
1322
- inputSchema = staticPortsToSchema(ui.staticDataIns)
1323
- }
1324
- const prop = inputSchema?.properties?.[field]
1325
- if (!prop) return undefined
1326
- return prop as JsonSchema
1327
- }
1328
-
1329
- function planNewGroup(
1330
- g: ProcedureGraph,
1331
- selection: Set<string>,
1332
- groupId: string,
1333
- ): NewGroupPlan {
1334
- const ports: GroupPort[] = []
1335
- const outerTriggerEdges: TriggerEdge[] = []
1336
- const outerDataEdges: DataEdge[] = []
1337
- const innerTriggerEdges: TriggerEdge[] = []
1338
- const innerDataEdges: DataEdge[] = []
1339
-
1340
- // Per (kind, direction) name reservations — keeps dedup scoped so a
1341
- // data-in "input" and a data-out "output" can coexist even if a
1342
- // hypothetical trigger-in shared the same desired label.
1343
- const takenDataIn = new Set<string>()
1344
- const takenDataOut = new Set<string>()
1345
- const takenTriggerIn = new Set<string>()
1346
- const takenTriggerOut = new Set<string>()
1347
-
1348
- // We need sentinel ids that match the ones syncSentinels will (re)use.
1349
- // Generate them up front so the inner edges below can reference them;
1350
- // then we splat them into the subgraph and let syncSentinels see them
1351
- // already in place.
1352
- const groupInputId = newId()
1353
- const groupOutputId = newId()
1354
-
1355
- for (const e of g.triggerEdges) {
1356
- const fromIn = selection.has(e.from.node)
1357
- const toIn = selection.has(e.to.node)
1358
- if (fromIn === toIn) continue // both inside or both outside → not cut
1359
- if (fromIn && !toIn) {
1360
- // Cut: source inside, target outside → declare trigger-out port.
1361
- const name = uniqueName(
1362
- desiredPortNameForTrigger(e.from.branch),
1363
- takenTriggerOut,
1364
- )
1365
- ports.push({ kind: 'trigger', direction: 'out', name })
1366
- // Outer: new edge from the OUTER group node's trigger-out handle
1367
- // to the original target node. `from.branch` IS the port name —
1368
- // matches how connect parses `group-trigger-out-<port>`.
1369
- outerTriggerEdges.push({
1370
- id: newId(),
1371
- from: { node: groupId, branch: name },
1372
- to: { node: e.to.node },
1373
- })
1374
- // Inner: original source node fires into groupOutput. Source-side
1375
- // branch is preserved verbatim (for if/switch routing); target
1376
- // port name lives on `to.branch` so the renderer can pick the
1377
- // right `groupOutput-trigger-in-<port>` handle.
1378
- innerTriggerEdges.push({
1379
- id: newId(),
1380
- from: { node: e.from.node, branch: e.from.branch },
1381
- to: { node: groupOutputId, branch: name },
1382
- })
1383
- } else {
1384
- // Cut: source outside, target inside → declare trigger-in port.
1385
- const name = uniqueName(
1386
- desiredPortNameForTrigger(e.from.branch),
1387
- takenTriggerIn,
1388
- )
1389
- ports.push({ kind: 'trigger', direction: 'in', name })
1390
- // Outer: original source node fires into OUTER group node's
1391
- // trigger-in handle. Port name lives on `to.branch` (rendered as
1392
- // `group-trigger-in-<port>` via the renderer).
1393
- outerTriggerEdges.push({
1394
- id: newId(),
1395
- from: { node: e.from.node, branch: e.from.branch },
1396
- to: { node: groupId, branch: name },
1397
- })
1398
- // Inner: groupInput fires into original target. Port name lives
1399
- // on `from.branch` — matches the syncSentinels filter for
1400
- // trigger edges out of groupInput.
1401
- innerTriggerEdges.push({
1402
- id: newId(),
1403
- from: { node: groupInputId, branch: name },
1404
- to: { node: e.to.node },
1405
- })
1406
- }
1407
- }
1408
-
1409
- for (const e of g.dataEdges) {
1410
- const fromIn = selection.has(e.from.node)
1411
- const toIn = selection.has(e.to.node)
1412
- if (fromIn === toIn) continue
1413
- if (fromIn && !toIn) {
1414
- // Cut: source inside, target outside → declare data-out port.
1415
- const name = uniqueName(e.from.port, takenDataOut)
1416
- ports.push({
1417
- kind: 'data',
1418
- direction: 'out',
1419
- name,
1420
- schema: findSchemaForDataSourcePort(e.from.node, e.from.port),
1421
- })
1422
- // Outer: group node's data-out → original target field.
1423
- outerDataEdges.push({
1424
- id: newId(),
1425
- from: { node: groupId, port: name },
1426
- to: { node: e.to.node, field: e.to.field },
1427
- })
1428
- // Inner: original source → groupOutput's data-in port (name).
1429
- innerDataEdges.push({
1430
- id: newId(),
1431
- from: { node: e.from.node, port: e.from.port },
1432
- to: { node: groupOutputId, field: name },
1433
- })
1434
- } else {
1435
- // Cut: source outside, target inside → declare data-in port.
1436
- const name = uniqueName(e.to.field, takenDataIn)
1437
- ports.push({
1438
- kind: 'data',
1439
- direction: 'in',
1440
- name,
1441
- schema: findSchemaForDataTargetField(e.to.node, e.to.field),
1442
- })
1443
- // Outer: original source → group node's data-in port.
1444
- outerDataEdges.push({
1445
- id: newId(),
1446
- from: { node: e.from.node, port: e.from.port },
1447
- to: { node: groupId, field: name },
1448
- })
1449
- // Inner: groupInput's data-out → original target field.
1450
- innerDataEdges.push({
1451
- id: newId(),
1452
- from: { node: groupInputId, port: name },
1453
- to: { node: e.to.node, field: e.to.field },
1454
- })
1455
- }
1456
- }
1457
-
1458
- return {
1459
- groupId,
1460
- groupPorts: ports,
1461
- groupInputId,
1462
- groupOutputId,
1463
- outerTriggerEdges,
1464
- outerDataEdges,
1465
- innerTriggerEdges,
1466
- innerDataEdges,
1467
- }
1468
- }
1469
-
1470
- function createGroupFromSelection() {
1471
- if (!canGroupSelection.value) return
1472
- const g = currentGraph.value
1473
- if (!g) return
1474
- const ids = selectedNodeIds.value.slice()
1475
- if (ids.length === 0) return
1476
-
1477
- // The group gets a default name, then the inspector opens on it with its
1478
- // name field focused: renaming is one keystroke away, nothing blocks.
1479
- const inputName = t('dms_automation.editor.groupDefaultName')
1480
-
1481
- const selection = new Set(ids)
1482
- const groupId = newId()
1483
-
1484
- const plan = planNewGroup(g, selection, groupId)
1485
-
1486
- // Position the new group at the centroid of the selection. We also
1487
- // shift the selected nodes' positions into the subgraph's coordinate
1488
- // space: subtract the selection min, then add a left-margin so the
1489
- // groupInput sentinel can sit at x ≈ 0.
1490
- const SUBGRAPH_LEFT_MARGIN = 220 // groupInput sits at x = 0 with room
1491
- const SUBGRAPH_RIGHT_MARGIN = 220
1492
- const selectedNodes = g.nodes.filter((n) => selection.has(n.id))
1493
- const xs = selectedNodes.map((n) => n.position.x)
1494
- const ys = selectedNodes.map((n) => n.position.y)
1495
- const minX = xs.length ? Math.min(...xs) : 0
1496
- const maxX = xs.length ? Math.max(...xs) : 0
1497
- const minY = ys.length ? Math.min(...ys) : 0
1498
- const maxY = ys.length ? Math.max(...ys) : 0
1499
- const centerX = xs.length ? (minX + maxX) / 2 : 200
1500
- const centerY = ys.length ? (minY + maxY) / 2 : 200
1501
-
1502
- const innerNodes: GraphNode[] = selectedNodes.map((n) => ({
1503
- ...JSON.parse(JSON.stringify(n)),
1504
- position: {
1505
- x: n.position.x - minX + SUBGRAPH_LEFT_MARGIN,
1506
- y: n.position.y - minY,
1507
- },
1508
- }))
1509
-
1510
- const innerHeight = Math.max(maxY - minY, 0)
1511
- const innerWidth = Math.max(maxX - minX, 0)
1512
-
1513
- const groupInputNode: GraphNode = {
1514
- id: plan.groupInputId,
1515
- kind: 'groupInput',
1516
- config: {},
1517
- position: { x: 0, y: innerHeight / 2 },
1518
- }
1519
- const groupOutputNode: GraphNode = {
1520
- id: plan.groupOutputId,
1521
- kind: 'groupOutput',
1522
- config: {},
1523
- position: {
1524
- x: innerWidth + SUBGRAPH_LEFT_MARGIN + SUBGRAPH_RIGHT_MARGIN,
1525
- y: innerHeight / 2,
1526
- },
1527
- }
1528
-
1529
- // Inner edges fully inside the selection — keep them verbatim (re-id
1530
- // not required since we keep node ids stable; ids only need to be
1531
- // unique within their containing graph and these are all from the
1532
- // outer graph we just stripped them from).
1533
- const innerOriginalTriggerEdges = g.triggerEdges.filter(
1534
- (e) => selection.has(e.from.node) && selection.has(e.to.node),
1535
- )
1536
- const innerOriginalDataEdges = g.dataEdges.filter(
1537
- (e) => selection.has(e.from.node) && selection.has(e.to.node),
1538
- )
1539
-
1540
- const newGroupNode: GraphNode = {
1541
- id: groupId,
1542
- kind: 'group',
1543
- config: { name: inputName },
1544
- position: { x: centerX, y: centerY },
1545
- ports: plan.groupPorts,
1546
- subgraph: {
1547
- nodes: [...innerNodes, groupInputNode, groupOutputNode],
1548
- triggerEdges: [...innerOriginalTriggerEdges, ...plan.innerTriggerEdges],
1549
- dataEdges: [...innerOriginalDataEdges, ...plan.innerDataEdges],
1550
- },
1551
- }
1552
-
1553
- // Build the new outer graph: drop the selected nodes + every edge that
1554
- // touches them (cut OR fully-inside), then add the new group + the
1555
- // replacement outer edges.
1556
- const remainingOuterNodes = g.nodes.filter((n) => !selection.has(n.id))
1557
- const remainingOuterTriggerEdges = g.triggerEdges.filter(
1558
- (e) => !selection.has(e.from.node) && !selection.has(e.to.node),
1559
- )
1560
- const remainingOuterDataEdges = g.dataEdges.filter(
1561
- (e) => !selection.has(e.from.node) && !selection.has(e.to.node),
1562
- )
1563
-
1564
- const nextGraph: ProcedureGraph = {
1565
- nodes: [...remainingOuterNodes, newGroupNode],
1566
- triggerEdges: [...remainingOuterTriggerEdges, ...plan.outerTriggerEdges],
1567
- dataEdges: [...remainingOuterDataEdges, ...plan.outerDataEdges],
1568
- }
1569
-
1570
- // Clear stale selection — the original ids no longer exist in the
1571
- // outer graph. Select the newly-created group.
1572
- selectedNodeIds.value = []
1573
- selectedNodeId.value = groupId
1574
-
1575
- onGraphUpdate(nextGraph)
1576
- void focusInspectorName()
1577
- }
1578
-
1579
- const inspectorRef = ref<HTMLElement | null>(null)
1580
-
1581
- /** Focuses the inspector's first field, the step name, and selects its text. */
1582
- async function focusInspectorName() {
1583
- await nextTick()
1584
- const input = inspectorRef.value?.querySelector('input')
1585
- input?.focus()
1586
- input?.select()
1587
- }
1588
-
1589
- const procedureName = computed<string>({
1590
- get: () => selected.value?.name ?? '',
1591
- set: (v: string) => {
1592
- if (selected.value) selected.value.name = v
1593
- },
1594
- })
1595
-
1596
- // Titles and toasts about what is stored name it as stored, not as the
1597
- // draft spells it (possibly blank) at that moment.
1598
- const savedName = computed<string>(() => savedSnapshot.value?.name || selected.value?.name || '')
1599
-
1600
- // The name is the one field outside the graph a save checks: a blank one is
1601
- // said under the name, and Save waits for it.
1602
- const NAME_INPUT_ID = 'builder-procedure-name'
1603
- const nameMissing = computed<boolean>(() => !!selected.value && !selected.value.name.trim())
1604
-
1605
- const procedureEnabled = computed<boolean>({
1606
- get: () => selected.value?.enabled ?? false,
1607
- set: (v: boolean) => {
1608
- if (selected.value) selected.value.enabled = v
1609
- },
1610
- })
1611
-
1612
- // ---------------------------------------------------------------------------
1613
- // The builder's bar: state, saving, problems (AU-03, AU-04, AU-16)
1614
- // ---------------------------------------------------------------------------
1615
-
1616
- // Each procedure's state, for the bar's badge and the switcher (procedure
1617
- // mode only).
1618
- const summariesRead = useApiData<ProcedureSummaryRow[]>(() =>
1619
- editorMode.value === 'procedure' ? `${props.apiUrl}/procedures/summary` : null,
1620
- )
1621
- const summaries = computed(() => summariesRead.data.value ?? [])
1622
-
1623
- const currentSummary = computed(() => summaries.value.find((s) => s.procedureId === selectedId.value) ?? null)
1624
-
1625
- const STATE_TONES = {
1626
- failing: 'error',
1627
- degraded: 'warning',
1628
- healthy: 'success',
1629
- paused: 'neutral',
1630
- draft: 'info',
1631
- } as const
1632
-
1633
- /** How many things changed since the last save, for "2 unsaved changes". */
1634
- const changeCount = computed<number>(() => {
1635
- const current = selected.value
1636
- const saved = savedSnapshot.value
1637
- if (!current || !saved) return 0
1638
- let count = 0
1639
- if (current.name !== saved.name) count++
1640
- if (current.enabled !== saved.enabled) count++
1641
- if (saved.ports && JSON.stringify(saved.ports) !== JSON.stringify(templatePorts.value)) count++
1642
- const before = new Map(saved.graph.nodes.map((n) => [n.id, JSON.stringify(n)]))
1643
- const after = new Map(current.graph.nodes.map((n) => [n.id, JSON.stringify(n)]))
1644
- for (const [id, value] of after) if (before.get(id) !== value) count++
1645
- for (const id of before.keys()) if (!after.has(id)) count++
1646
- const edges = (g: ProcedureGraph) => JSON.stringify([g.triggerEdges, g.dataEdges])
1647
- if (edges(current.graph) !== edges(saved.graph)) count++
1648
- return count
1649
- })
1650
-
1651
- // Problems of the draft, asked of the server (the same validator a save
1652
- // runs) a moment after each change.
1653
- // Each issue carries a `code` (and its `params`) the locale words; its English
1654
- // `message` is the fallback for a code the locale does not know.
1655
- interface GraphIssue {
1656
- severity: 'error' | 'warning'
1657
- message: string
1658
- code?: string
1659
- params?: Record<string, unknown>
1660
- nodeId?: string
1661
- }
1662
- const issues = ref<GraphIssue[]>([])
1663
- // The draft's triggers, worded by the server with its problems: the canvas
1664
- // and the test dock name them.
1665
- const draftTriggers = ref<WordedTrigger[]>([])
1666
- let validateTimer: ReturnType<typeof setTimeout> | undefined
1667
- const VALIDATE_DELAY_MS = 500
1668
-
1669
- async function validateDraft() {
1670
- const current = selected.value
1671
- if (!current || editorMode.value !== 'procedure') {
1672
- issues.value = []
1673
- draftTriggers.value = []
1674
- return
1675
- }
1676
- try {
1677
- const res = await $authFetch<{ issues: typeof issues.value; triggers?: WordedTrigger[] }>(`${props.apiUrl}/procedures/validate`, {
1678
- method: 'POST',
1679
- // With the procedure and its name, the server also checks what other
1680
- // procedures hold (a webhook path, a name).
1681
- body: { graph: current.graph, enabled: current.enabled, procedureId: current._id, name: current.name },
1682
- })
1683
- issues.value = res.issues ?? []
1684
- draftTriggers.value = res.triggers ?? []
1685
- } catch {
1686
- // A graph the schema refuses is reported on save.
1687
- }
1688
- }
1689
-
1690
- function scheduleValidation() {
1691
- clearTimeout(validateTimer)
1692
- validateTimer = setTimeout(() => void validateDraft(), VALIDATE_DELAY_MS)
1693
- }
1694
- watch(
1695
- () => (selected.value ? [structuralKey(selected.value.graph), selected.value.name, selected.value.enabled].join('|') : ''),
1696
- scheduleValidation,
1697
- )
1698
- // The draft as opened is checked in the browser: a server render has no
1699
- // draft to check, and its timer would outlive the render.
1700
- onMounted(scheduleValidation)
1701
- onBeforeUnmount(() => clearTimeout(validateTimer))
1702
-
1703
- const blockingIssues = computed(() => issues.value.filter((i) => i.severity === 'error'))
1704
-
1705
- /** How the builder names a node: its label, else its type's name. */
1706
- function nodeDisplayName(id: string): string {
1707
- const node = walkAll(selected.value?.graph).find((n) => n.id === id)
1708
- if (!node) return id
1709
- if (node.kind === 'group') return groupName(node)
1710
- if (node.label) return node.label
1711
- const typeName =
1712
- node.kind === 'trigger'
1713
- ? triggerTypes.value.find((x) => x.id === node.typeId)?.name
1714
- : node.kind === 'action'
1715
- ? actionTypes.value.find((x) => x.id === node.typeId)?.name
1716
- : node.kind === 'data'
1717
- ? dataNodeTypes.value.find((x) => x.id === node.typeId)?.name
1718
- : nodeKinds.value.find((k) => k.kind === node.kind)?.meta.ui?.label
1719
- return typeName ? processI18n(typeName) : (node.config?.name as string | undefined) ?? node.kind
1720
- }
1721
-
1722
- function walkAll(graph: ProcedureGraph | undefined): GraphNode[] {
1723
- if (!graph) return []
1724
- return graph.nodes.flatMap((n) => [n, ...walkAll(n.subgraph)])
1725
- }
1726
-
1727
- /** An issue in the user's language. */
1728
- function issueText(issue: GraphIssue): string {
1729
- const key = `dms_automation.editor.problems.codes.${issue.code}`
1730
- return issue.code && te(key) ? t(key, issue.params ?? {}) : issue.message
1731
- }
1732
-
1733
- const dockIssues = computed<DockIssue[]>(() =>
1734
- issues.value.map((issue) => ({
1735
- ...issue,
1736
- message: issueText(issue),
1737
- nodeName: issue.nodeId ? nodeDisplayName(issue.nodeId) : undefined,
1738
- })),
1739
- )
1740
-
1741
- // Code and params travel along: the inspector names a setting as its form does.
1742
- const issuesByNode = computed<Record<string, Omit<GraphIssue, 'nodeId'>>>(() => {
1743
- const out: Record<string, Omit<GraphIssue, 'nodeId'>> = {}
1744
- for (const issue of issues.value) {
1745
- if (!issue.nodeId) continue
1746
- if (!out[issue.nodeId] || issue.severity === 'error')
1747
- out[issue.nodeId] = { severity: issue.severity, message: issueText(issue), code: issue.code, params: issue.params }
1748
- }
1749
- return out
1750
- })
1751
-
1752
- const dockTab = ref<DockTab>('problems')
1753
- // The dock stays out of the canvas's way until it has something to say: it
1754
- // opens on its own for a problem that blocks enabling (a warning only counts
1755
- // on its tab), and closes again once that is fixed, unless the user has
1756
- // taken it over in between.
1757
- const dockCollapsed = ref(true)
1758
- let dockOpenedForProblems = false
1759
- watch(
1760
- () => blockingIssues.value.length,
1761
- (count, before) => {
1762
- if (count > 0 && !before) {
1763
- dockTab.value = 'problems'
1764
- dockCollapsed.value = false
1765
- dockOpenedForProblems = true
1766
- } else if (count === 0 && dockOpenedForProblems && dockTab.value === 'problems') {
1767
- dockCollapsed.value = true
1768
- }
1769
- },
1770
- )
1771
- watch([dockTab, dockCollapsed], () => {
1772
- if (dockCollapsed.value || dockTab.value !== 'problems') dockOpenedForProblems = false
1773
- })
1774
-
1775
- function selectNode(id: string) {
1776
- // A node inside a group is named by its top-level group in the issues.
1777
- subgraphPath.value = subgraphPath.value.slice(0, 1)
1778
- selectedNodeId.value = id
1779
- }
1780
-
1781
- interface ProcedureTriggers {
1782
- triggers: Array<WordedTrigger & { nextAt: string | null }>
1783
- }
1784
-
1785
- /**
1786
- * A URL of the procedure open, for the reads that follow it: none in
1787
- * template mode or while no procedure is open.
1788
- */
1789
- function selectedProcedureUrl(path: string): () => string | null {
1790
- return () => (selectedId.value && editorMode.value === 'procedure' ? `${props.apiUrl}/procedures/${selectedId.value}/${path}` : null)
1791
- }
1792
-
1793
- /**
1794
- * Data of the procedure open, or nothing while another one's is still on
1795
- * screen or once its read failed.
1796
- */
1797
- function ofSelected<T>(read: { data: Ref<T | null>; placeholder: Readonly<Ref<boolean>>; error: Ref<unknown> }): T | null {
1798
- return read.placeholder.value || read.error.value ? null : read.data.value
1799
- }
1800
-
1801
- // The saved triggers: what a paused procedure will not fire, and what Run
1802
- // now offers.
1803
- const savedTriggersRead = useApiData<ProcedureTriggers>(selectedProcedureUrl('triggers'))
1804
- const savedTriggers = computed(() => ofSelected(savedTriggersRead)?.triggers ?? [])
1805
-
1806
- /** The banner of a disabled procedure names what will not fire (AU-16). */
1807
- const pausedBanner = computed(() => {
1808
- const current = selected.value
1809
- if (!current || current.enabled || editorMode.value !== 'procedure') return null
1810
- const triggers = savedTriggers.value.filter((tr) => tr.typeId !== 'manual')
1811
- if (triggers.length === 0) return null
1812
- const first = triggers[0]!
1813
- const what = processText(first.text)
1814
- const isDraft = currentSummary.value?.status === 'draft'
1815
- return {
1816
- title: t(isDraft ? 'dms_automation.editor.paused.draftTitle' : 'dms_automation.editor.paused.title', { name: savedName.value }),
1817
- description: first.nextAt
1818
- ? t('dms_automation.editor.paused.schedule', {
1819
- what,
1820
- next: describeDateTime(first.nextAt, dateTimeFormat, first.timeZone),
1821
- })
1822
- : t('dms_automation.editor.paused.other', { what }),
1823
- }
1824
- })
1825
-
1826
- async function enableNow() {
1827
- if (!selected.value) return
1828
- selected.value.enabled = true
1829
- await onSave()
1830
- }
1831
-
1832
- const saveState = computed(() => {
1833
- if (saving.value) return t('dms_automation.editor.saving')
1834
- if (changeCount.value > 0) return t('dms_automation.editor.unsaved', { count: changeCount.value })
1835
- return t('dms_automation.editor.saved')
1836
- })
1837
-
1838
- // ---------------------------------------------------------------------------
1839
- // Create, delete, export
1840
- // ---------------------------------------------------------------------------
1841
-
1842
- async function onCreated(id: string) {
1843
- await Promise.all([loadList(), summariesRead.refresh()])
1844
- selectedId.value = id
1845
- void router.replace(`${builderPath()}?selected=${id}`)
1846
- }
1847
-
1848
- async function onCreate() {
1849
- if (!(await confirmDiscard())) return
1850
- newProcedureOpen.value = true
1851
- }
1852
-
1853
- async function onDelete() {
1854
- const current = selected.value
1855
- if (!current) return
1856
- const name = savedName.value
1857
- // The server words the dialog, as the procedures table's delete does.
1858
- await confirmFrom(`${props.apiUrl}/procedures/{{row.id}}/delete-confirm`, {
1859
- params: { id: current._id },
1860
- onConfirm: async () => {
1861
- await $authFetch(`${props.apiUrl}/procedures/${current._id}`, { method: 'DELETE' })
1862
- procedures.value = procedures.value.filter((p) => p._id !== current._id)
1863
- selectedId.value = procedures.value[0]?._id ?? null
1864
- void router.replace(selectedId.value ? `${builderPath()}?selected=${selectedId.value}` : builderPath())
1865
- toast.add({ title: t('dms_automation.editor.deleted', { name }), color: 'success', icon: 'i-ph-check-circle' })
1866
- void summariesRead.refresh()
1867
- },
1868
- })
1869
- }
1870
-
1871
- async function onExport() {
1872
- const current = selected.value
1873
- if (!current) return
1874
- const data = await $authFetch<unknown>(`${props.apiUrl}/procedures/${current._id}/export`)
1875
- const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
1876
- const url = URL.createObjectURL(blob)
1877
- const link = document.createElement('a')
1878
- link.href = url
1879
- link.download = `${current.name.replace(/[^\w-]+/g, '-').toLowerCase() || 'procedure'}.json`
1880
- link.click()
1881
- URL.revokeObjectURL(url)
1882
- }
1883
-
1884
- // ---------------------------------------------------------------------------
1885
- // Questions with more than a yes and a no: switching procedure with unsaved
1886
- // changes (AU-04), running the saved version, a save refused for a newer one
1887
- // ---------------------------------------------------------------------------
1888
-
1889
- interface Choice<C extends string> {
1890
- value: C
1891
- label: string
1892
- color?: 'primary' | 'neutral' | 'error' | 'warning'
1893
- variant?: 'solid' | 'outline' | 'ghost' | 'soft'
1894
- }
1895
-
1896
- interface ChoiceQuestion<C extends string> {
1897
- title: string
1898
- description: string
1899
- choices: Choice<C>[]
1900
- /** The answer of a dialog closed without choosing (Escape, ✕, a click outside). */
1901
- dismiss: C
1902
- }
1903
-
1904
- const choiceDialog = ref<ChoiceQuestion<string> & { open: boolean; resolve?: (choice: string) => void }>({
1905
- open: false,
1906
- title: '',
1907
- description: '',
1908
- choices: [],
1909
- dismiss: '',
1910
- })
1911
-
1912
- function askChoice<C extends string>(question: ChoiceQuestion<C>): Promise<C> {
1913
- return new Promise((resolve) => {
1914
- choiceDialog.value = { ...question, open: true, resolve: resolve as (choice: string) => void }
1915
- })
1916
- }
1917
-
1918
- /** The dialog opens on its safe answer: Enter keeps the draft, runs nothing. */
1919
- function focusSafeChoice(event: Event) {
1920
- event.preventDefault()
1921
- void nextTick(() => document.querySelector<HTMLElement>('[data-safe-choice]')?.focus())
1922
- }
1923
-
1924
- /** Escape, ✕ or a click outside answers the question's `dismiss`. */
1925
- function onChoiceDialogOpen(open: boolean) {
1926
- if (!open && choiceDialog.value.open) answerChoice(choiceDialog.value.dismiss)
1927
- }
1928
-
1929
- function answerChoice(choice: string) {
1930
- const resolve = choiceDialog.value.resolve
1931
- choiceDialog.value = { ...choiceDialog.value, open: false, resolve: undefined }
1932
- resolve?.(choice)
1933
- }
1934
-
1935
- /** Resolves `true` when the draft may be left: saved, discarded or clean. */
1936
- async function confirmDiscard(): Promise<boolean> {
1937
- if (!isDirty.value) return true
1938
- const choice = await askChoice({
1939
- title: t('dms_automation.editor.leave.title', { name: savedName.value }),
1940
- description: t('dms_automation.editor.leave.description', { count: changeCount.value }),
1941
- choices: [
1942
- { value: 'discard', label: t('dms_automation.editor.discard'), color: 'error', variant: 'ghost' },
1943
- { value: 'stay', label: t('dms_automation.editor.leave.keep'), color: 'neutral', variant: 'outline' },
1944
- { value: 'save', label: t('dms_automation.editor.leave.save'), color: 'primary' },
1945
- ],
1946
- dismiss: 'stay',
1947
- })
1948
- if (choice === 'stay') return false
1949
- if (choice === 'save') return await onSave()
1950
- onCancel()
1951
- return true
1952
- }
1953
-
1954
- async function onPickProcedure(id: string) {
1955
- if (!(await confirmDiscard())) return
1956
- selectedId.value = id
1957
- void router.replace(`${builderPath()}?selected=${id}`)
1958
- }
1959
-
1960
- // The template editor guards its draft like the procedure editor.
1961
- watch(isDirty, (dirty) => (unsavedDraft.value = dirty), { immediate: true })
1962
-
1963
- // The DMS leave guard only holds a visit to another path. A visit to the
1964
- // builder itself that remounts it (the sidebar's "Builder", a link with
1965
- // another ?selected=), or that keeps it mounted but opens another procedure,
1966
- // loses the draft just the same: it is held here and run again once the
1967
- // draft is saved or discarded. The builder's own URL updates go through.
1968
- interface PendingVisit {
1969
- url?: URL
1970
- method?: string
1971
- prefetch?: boolean
1972
- preserveState?: unknown
1973
- replace?: boolean
1974
- }
1975
-
1976
- function onInertiaBefore(event: Event) {
1977
- const visit = (event as CustomEvent<{ visit?: PendingVisit }>).detail?.visit
1978
- if (!visit?.url || visit.prefetch) return
1979
- if (visit.method && visit.method.toLowerCase() !== 'get') return
1980
- if (visit.url.pathname !== builderPath() || !isDirty.value) return
1981
- const keepsPage = visit.preserveState === true
1982
- if (keepsPage && !opensAnotherProcedure(visit.url.searchParams.get('selected'))) return
1983
- event.preventDefault()
1984
- const href = `${visit.url.pathname}${visit.url.search}${visit.url.hash}`
1985
- void confirmDiscard().then((leave) => {
1986
- if (leave) void navigateDms(href, { preserveState: keepsPage, replace: visit.replace })
1987
- })
1988
- }
1989
-
1990
- function opensAnotherProcedure(id: string | null): id is string {
1991
- return editorMode.value === 'procedure' && !!id && id !== selectedId.value
1992
- }
1993
-
1994
- // Back and Forward between two addresses of the builder: the DMS guard lets
1995
- // them through (same path). Where the browser announces them before they
1996
- // happen (Navigation API), the draft is asked about first and the step is
1997
- // taken again once it is saved or discarded. A browser without it remounts
1998
- // the page on the step: the DMS guard has the same gap.
1999
- interface TraverseEvent extends Event {
2000
- navigationType?: string
2001
- destination?: { url: string; key: string; sameDocument: boolean }
2002
- }
2003
-
2004
- interface NavigationLike extends EventTarget {
2005
- traverseTo: (key: string) => unknown
2006
- }
2007
-
2008
- function browserNavigation(): NavigationLike | undefined {
2009
- return typeof window === 'undefined' ? undefined : (window as unknown as { navigation?: NavigationLike }).navigation
2010
- }
2011
-
2012
- // Set while the history step the user chose to take is taken again.
2013
- let traverseAllowed = false
2014
-
2015
- function onNavigate(event: Event) {
2016
- const { navigationType, destination } = event as TraverseEvent
2017
- if (navigationType !== 'traverse' || !destination) return
2018
- if (traverseAllowed) {
2019
- traverseAllowed = false
2020
- return
2021
- }
2022
- if (!destination.sameDocument || !event.cancelable || !isDirty.value) return
2023
- if (new URL(destination.url).pathname !== builderPath()) return
2024
- event.preventDefault()
2025
- void confirmDiscard().then((leave) => {
2026
- if (!leave) return
2027
- traverseAllowed = true
2028
- void browserNavigation()?.traverseTo(destination.key)
2029
- })
2030
- }
2031
-
2032
- // ?selected= changed while the page stayed mounted (a visit that keeps it,
2033
- // such as a link to the builder from the builder): the builder opens that
2034
- // procedure. A draft is asked about first; keeping it puts the address back.
2035
- watch(
2036
- () => queryValue('selected'),
2037
- async (id) => {
2038
- if (!opensAnotherProcedure(id)) return
2039
- if (!(await confirmDiscard())) {
2040
- void router.replace(`${builderPath()}?selected=${selectedId.value}`)
2041
- return
2042
- }
2043
- if (procedures.value.some((p) => p._id === id)) {
2044
- selectedId.value = id
2045
- return
2046
- }
2047
- missingProcedureId.value = id
2048
- selectedId.value = null
2049
- switcherOpen.value = true
2050
- },
2051
- )
2052
-
2053
- // ---------------------------------------------------------------------------
2054
- // Save
2055
- // ---------------------------------------------------------------------------
2056
-
2057
- interface SaveRefusal {
2058
- data?: {
2059
- issues?: Array<
2060
- | { severity?: string; message?: string; code?: string; params?: Record<string, unknown>; nodeId?: string; path?: unknown[] }
2061
- | string
2062
- >
2063
- }
2064
- }
2065
-
2066
- function issuesOf(error: unknown): GraphIssue[] | null {
2067
- const raw = (error as SaveRefusal)?.data?.issues
2068
- if (!Array.isArray(raw)) return null
2069
- // A field of the body other than the graph (zod issues carry its path) is
2070
- // not a problem of the graph.
2071
- if (raw.some((issue) => typeof issue === 'object' && Array.isArray(issue.path) && issue.path[0] !== 'graph')) return null
2072
- return raw.map((issue) =>
2073
- typeof issue === 'string'
2074
- ? { severity: 'error' as const, message: issue }
2075
- : {
2076
- severity: issue.severity === 'warning' ? 'warning' : 'error',
2077
- message: issue.message ?? '',
2078
- code: issue.code,
2079
- params: issue.params,
2080
- nodeId: issue.nodeId,
2081
- },
2082
- )
2083
- }
2084
-
2085
- /** Save the open procedure (or template). Resolves whether it was saved. */
2086
- async function onSave(): Promise<boolean> {
2087
- if (!selected.value) return false
2088
- if (nameMissing.value) {
2089
- document.getElementById(NAME_INPUT_ID)?.focus()
2090
- return false
2091
- }
2092
- saving.value = true
2093
- const current = selected.value
2094
- // What is sent is what counts as saved: a change made while the request
2095
- // runs stays an unsaved change.
2096
- const sent = takeSnapshot(current)
2097
- try {
2098
- if (editorMode.value === 'template') {
2099
- await $authFetch(`${props.apiUrl}/templates/${current._id}`, {
2100
- method: 'PUT',
2101
- body: {
2102
- name: sent.name,
2103
- description: current.description,
2104
- icon: templateIcon.value,
2105
- ports: sent.ports ?? [],
2106
- subgraph: sent.graph,
2107
- },
2108
- })
2109
- savedSnapshot.value = sent
2110
- toast.add({ title: t('dms_automation.templates.saved', { name: sent.name }), color: 'success', icon: 'i-ph-check-circle' })
2111
- return true
2112
- }
2113
- const res = await $authFetch<{ version: number; revision: number; issues?: GraphIssue[] }>(`${props.apiUrl}/procedures/${current._id}`, {
2114
- method: 'PUT',
2115
- body: {
2116
- name: sent.name,
2117
- description: current.description,
2118
- enabled: sent.enabled,
2119
- graph: sent.graph,
2120
- expectedRevision: current.revision,
2121
- },
2122
- })
2123
- current.version = res.version
2124
- current.revision = res.revision
2125
- savedSnapshot.value = sent
2126
- if (res.issues) issues.value = res.issues
2127
- toast.add({
2128
- title: t('dms_automation.editor.savedToast', { name: sent.name }),
2129
- description: res.issues?.length ? t('dms_automation.editor.savedWithProblems', { count: res.issues.length }) : undefined,
2130
- color: 'success',
2131
- icon: 'i-ph-check-circle',
2132
- actions: [{ label: t('dms_automation.editor.testRun'), onClick: () => void onTestRun() }],
2133
- })
2134
- void summariesRead.refresh()
2135
- void savedTriggersRead.refresh()
2136
- return true
2137
- } catch (e) {
2138
- if (editorMode.value === 'procedure' && apiErrorStatus(e) === 409) return await resolveStale(current, e)
2139
- const refused = issuesOf(e)
2140
- if (refused) {
2141
- issues.value = refused
2142
- saveBlocked.value = true
2143
- dockTab.value = 'problems'
2144
- dockCollapsed.value = false
2145
- } else {
2146
- toast.add({
2147
- title: editorMode.value === 'template' ? t('dms_automation.templates.saveError') : t('dms_automation.editor.saveError'),
2148
- description: describeApiError(e),
2149
- color: 'error',
2150
- icon: 'i-ph-warning',
2151
- })
2152
- }
2153
- return false
2154
- } finally {
2155
- saving.value = false
2156
- }
2157
- }
2158
-
2159
- /**
2160
- * The procedure was saved elsewhere (another tab, a pause from the list)
2161
- * since this draft was loaded, and the server refused to overwrite it:
2162
- * reload what is saved now, or overwrite it with the draft.
2163
- */
2164
- async function resolveStale(current: ProcedureRecord, error: unknown): Promise<boolean> {
2165
- saving.value = false
2166
- let latest = (error as { data: { revision: number } }).data.revision
2167
- const choice = await askChoice({
2168
- title: t('dms_automation.editor.stale.title', { name: savedName.value }),
2169
- description: t('dms_automation.editor.stale.description'),
2170
- choices: [
2171
- { value: 'stay', label: t('dms_automation.editor.stale.keep'), color: 'neutral', variant: 'ghost' },
2172
- { value: 'reload', label: t('dms_automation.editor.stale.reload'), color: 'neutral', variant: 'outline' },
2173
- { value: 'overwrite', label: t('dms_automation.editor.stale.overwrite'), color: 'warning' },
2174
- ],
2175
- dismiss: 'stay',
2176
- })
2177
- if (choice === 'overwrite') {
2178
- // Overwriting puts the draft's edits over what was saved elsewhere, not
2179
- // its on/off state over a pause or a resume made elsewhere: unless the
2180
- // switch was flipped in this draft, the procedure stays as it is now.
2181
- if (current.enabled === savedSnapshot.value?.enabled) {
2182
- try {
2183
- const saved = await $authFetch<{ enabled: boolean; revision: number }>(`${props.apiUrl}/procedures/${current._id}`)
2184
- current.enabled = saved.enabled
2185
- latest = saved.revision
2186
- } catch {
2187
- // Unreadable: the draft's state is saved, as before.
2188
- }
2189
- }
2190
- current.revision = latest
2191
- return await onSave()
2192
- }
2193
- if (choice === 'reload') await reloadSelected()
2194
- return false
2195
- }
2196
-
2197
- /** Replaces the draft with the procedure as it is saved now. */
2198
- async function reloadSelected() {
2199
- const current = selected.value
2200
- if (!current) return
2201
- try {
2202
- const fresh = await $authFetch<ProcedureRecord>(`${props.apiUrl}/procedures/${current._id}`)
2203
- procedures.value = procedures.value.map((p) => (p._id === fresh._id ? fresh : p))
2204
- selectedNodeId.value = null
2205
- initHistoryAndSaved()
2206
- seedSubgraphPath()
2207
- saveBlocked.value = false
2208
- void summariesRead.refresh()
2209
- void savedTriggersRead.refresh()
2210
- } catch (e) {
2211
- toast.add({ title: t('dms_automation.editor.loadProceduresError'), description: describeApiError(e), color: 'error', icon: 'i-ph-warning' })
2212
- }
2213
- }
2214
-
2215
- /** Set when a save was refused for problems: the banner offers the way out. */
2216
- const saveBlocked = ref(false)
2217
- watch(blockingIssues, (list) => {
2218
- if (list.length === 0) saveBlocked.value = false
2219
- })
2220
-
2221
- async function saveAsDraft() {
2222
- if (!selected.value) return
2223
- selected.value.enabled = false
2224
- if (await onSave()) saveBlocked.value = false
2225
- }
2226
-
2227
- function goToFirstProblem() {
2228
- const first = blockingIssues.value.find((i) => i.nodeId) ?? issues.value.find((i) => i.nodeId)
2229
- if (first?.nodeId) selectNode(first.nodeId)
2230
- }
2231
-
2232
-
2233
- // ---------------------------------------------------------------------------
2234
- // Save-as-template
2235
- // ---------------------------------------------------------------------------
2236
- // Visible when the user has selected a single local group (kind === 'group',
2237
- // no templateId). On submit:
2238
- // 1. POST /api/automation/templates with { name, description, icon, ports,
2239
- // subgraph } from the local group.
2240
- // 2. On success: mutate the in-graph node — set templateId = res._id, drop
2241
- // subgraph. The save flow (onGraphUpdate → onSave by user) propagates.
2242
- // 3. On failure (Zod or template cycle): render the error body inline in
2243
- // the modal; the graph is NOT touched.
2244
- const selectedLocalGroupNode = computed<GraphNode | null>(() => {
2245
- const n = selectedNode.value
2246
- if (!n || n.kind !== 'group') return null
2247
- if (n.templateId) return null
2248
- return n
2249
- })
2250
-
2251
- const canSaveAsTemplate = computed<boolean>(() => {
2252
- if (!selected.value) return false
2253
- if (isCurrentGraphReadOnly.value) return false
2254
- return selectedLocalGroupNode.value !== null
2255
- })
2256
-
2257
- const saveAsTemplateOpen = ref<boolean>(false)
2258
- const saveAsTemplateName = ref<string>('')
2259
- const saveAsTemplateDescription = ref<string>('')
2260
- const saveAsTemplateIcon = ref<string>('i-ph-package')
2261
- const saveAsTemplateSubmitting = ref<boolean>(false)
2262
- const saveAsTemplateError = ref<string | null>(null)
2263
- const TEMPLATE_NAME_ID = 'save-template-name'
2264
- const TEMPLATE_ROW = { layout: 'form', spacing: 'list', inset: false } as const
2265
- // A missing name shows under its field; what the server refuses (issues, a
2266
- // reference cycle) stays in the banner above the buttons.
2267
- const templateFieldErrors = useFieldErrors({ fields: { name: TEMPLATE_NAME_ID } })
2268
- watch(saveAsTemplateName, () => templateFieldErrors.clear('name'))
2269
-
2270
- function openSaveAsTemplate() {
2271
- const n = selectedLocalGroupNode.value
2272
- if (!n) return
2273
- saveAsTemplateName.value = groupName(n)
2274
- saveAsTemplateDescription.value = ''
2275
- saveAsTemplateIcon.value = 'i-ph-package'
2276
- saveAsTemplateError.value = null
2277
- templateFieldErrors.clear()
2278
- saveAsTemplateSubmitting.value = false
2279
- saveAsTemplateOpen.value = true
2280
- }
2281
-
2282
- // Render the 400 body from src/routes/templates.ts:
2283
- // - Zod failure → { error: 'invalid body', issues: ZodIssue[] }
2284
- // - validateGraph failure → { error: 'invalid graph', issues: string[] }
2285
- // - cycle → { error: 'template reference cycle', cycle: string[] }
2286
- // Other errors (network, 401, 500) fall back to the message string.
2287
- function formatTemplateError(err: unknown): string {
2288
- const data = (err as { data?: unknown; message?: string } | undefined)?.data as
2289
- | {
2290
- error?: string
2291
- issues?: Array<{ path?: Array<string | number>; message?: string } | string>
2292
- cycle?: string[]
2293
- }
2294
- | undefined
2295
- if (data && typeof data === 'object') {
2296
- const head = data.error ?? 'Request failed'
2297
- if (Array.isArray(data.issues) && data.issues.length > 0) {
2298
- const lines = data.issues.map((iss) => {
2299
- if (typeof iss === 'string') return iss
2300
- const path = Array.isArray(iss.path) ? iss.path.join('.') : ''
2301
- const msg = iss.message ?? 'invalid'
2302
- return path ? `${path}: ${msg}` : msg
2303
- })
2304
- return `${head}\n${lines.join('\n')}`
2305
- }
2306
- if (Array.isArray(data.cycle) && data.cycle.length > 0) {
2307
- return `${head}: ${data.cycle.join(' → ')}`
2308
- }
2309
- return head
2310
- }
2311
- return describeApiError(err)
2312
- }
2313
-
2314
- function convertLocalGroupToTemplateInstance(
2315
- nodeId: string,
2316
- templateId: string,
2317
- ): void {
2318
- const g = currentGraph.value
2319
- if (!g) return
2320
- const existing = g.nodes.find((n) => n.id === nodeId && n.kind === 'group')
2321
- if (!existing) return
2322
- const updated: GraphNode = { ...existing, templateId }
2323
- delete updated.subgraph
2324
- onUpdateNode(updated)
2325
- }
2326
-
2327
- async function submitSaveAsTemplate() {
2328
- const n = selectedLocalGroupNode.value
2329
- if (!n) return
2330
- const name = saveAsTemplateName.value.trim()
2331
- if (!name) {
2332
- await templateFieldErrors.setError('name', t('dms_automation.editor.saveTemplateModal.nameRequired'))
2333
- return
2334
- }
2335
- if (!n.subgraph) {
2336
- saveAsTemplateError.value = t('dms_automation.editor.saveTemplateModal.noSubgraph')
2337
- return
2338
- }
2339
- saveAsTemplateSubmitting.value = true
2340
- saveAsTemplateError.value = null
2341
- try {
2342
- const body = {
2343
- name,
2344
- description: saveAsTemplateDescription.value.trim(),
2345
- icon: saveAsTemplateIcon.value.trim() || 'i-ph-package',
2346
- ports: Array.isArray(n.ports) ? n.ports : [],
2347
- subgraph: n.subgraph,
2348
- }
2349
- const created = await $authFetch<{ _id: string }>(
2350
- '/api/automation/templates',
2351
- { method: 'POST', body },
2352
- )
2353
- // The template exists now: the procedure links to it once saved. A
2354
- // draft with nothing else unsaved is saved at once; one with other
2355
- // changes is left to the user, who is told.
2356
- const linkOnly = !isDirty.value
2357
- convertLocalGroupToTemplateInstance(n.id, created._id)
2358
- saveAsTemplateOpen.value = false
2359
- void templatesRead.refresh()
2360
- toast.add({
2361
- title: t('dms_automation.templates.saved', { name }),
2362
- description: linkOnly ? undefined : t('dms_automation.editor.saveTemplateModal.saveToLink'),
2363
- color: 'success',
2364
- icon: 'i-ph-check-circle',
2365
- })
2366
- if (linkOnly) await onSave()
2367
- } catch (e) {
2368
- saveAsTemplateError.value = formatTemplateError(e)
2369
- } finally {
2370
- saveAsTemplateSubmitting.value = false
2371
- }
2372
- }
2373
-
2374
- // ---------------------------------------------------------------------------
2375
- // Fork-to-local-group
2376
- // ---------------------------------------------------------------------------
2377
- // Visible when a template-instance group node is selected — i.e. kind === 'group'
2378
- // AND templateId is set. The fork is the escape hatch from the live-link
2379
- // model: it converts the instance back to a local group by deep-cloning the
2380
- // template's current subgraph into the node and dropping templateId.
2381
- //
2382
- // Selection rules:
2383
- // • Allowed even from the read-only inner-subgraph view of a template
2384
- // instance — this is the "Fork to edit" CTA flow. The action mutates
2385
- // the OUTER graph (the procedure root or whichever container holds
2386
- // the template instance), not the inner subgraph being viewed.
2387
- // • To make that work, the selection target for the fork is the deepest
2388
- // currentParentGroup when we're inside a template-instance subgraph,
2389
- // OR the selectedNode otherwise.
2390
- //
2391
- // The deep-clone uses a JSON parse/stringify round-trip: structuredClone
2392
- // throws on Vue's reactive proxies (see the inline note at the clone site).
2393
- //
2394
- // Edge case: if the template was deleted between selection and confirm,
2395
- // GET /:id returns 404 → we surface that as an error in the modal so the
2396
- // user can dismiss and stop trying.
2397
- interface ForkTarget {
2398
- // The group node to convert (the template instance).
2399
- node: GraphNode
2400
- // The graph in which that node lives. May be the procedure root or any
2401
- // outer subgraph (when the user is viewing the inner read-only graph of
2402
- // an instance, the instance node lives one frame up).
2403
- containerGraph: ProcedureGraph
2404
- }
2405
-
2406
- const forkTarget = computed<ForkTarget | null>(() => {
2407
- if (!selected.value) return null
2408
- const frames = subgraphFrames.value
2409
- // Case A: user is INSIDE a template-instance subgraph (read-only view).
2410
- // The instance node is the parent group; its container is the previous
2411
- // frame's graph.
2412
- if (isCurrentGraphReadOnly.value && frames.length >= 2) {
2413
- const parent = frames[frames.length - 1]!.groupNode
2414
- const container = frames[frames.length - 2]!.graph
2415
- if (parent && parent.kind === 'group' && parent.templateId) {
2416
- return { node: parent, containerGraph: container }
2417
- }
2418
- }
2419
- // Case B: user has a template-instance node selected in the current
2420
- // (editable) graph.
2421
- const sel = selectedNode.value
2422
- const g = currentGraph.value
2423
- if (sel && g && sel.kind === 'group' && sel.templateId) {
2424
- return { node: sel, containerGraph: g }
2425
- }
2426
- return null
2427
- })
2428
-
2429
- const canForkToLocal = computed<boolean>(() => forkTarget.value !== null)
2430
-
2431
- const forkOpen = ref<boolean>(false)
2432
- const forkSubmitting = ref<boolean>(false)
2433
- const forkError = ref<string | null>(null)
2434
-
2435
- function openFork() {
2436
- if (!canForkToLocal.value) return
2437
- forkError.value = null
2438
- forkSubmitting.value = false
2439
- forkOpen.value = true
2440
- }
2441
-
2442
- interface FetchedTemplate {
2443
- _id: string
2444
- name: string
2445
- description: string
2446
- icon: string
2447
- ports: GroupPort[]
2448
- subgraph: ProcedureGraph
2449
- }
2450
-
2451
- // Replace the template instance node with a forked local copy. Mirrors the
2452
- // shape of convertLocalGroupToTemplateInstance but in reverse: drops
2453
- // templateId, installs subgraph from the fetched template, and writes back
2454
- // through onUpdateNode / onGraphUpdate (so history + dirty-snapshot stay
2455
- // consistent). The replacement uses a fresh node object so Vue reactivity
2456
- // sees a real change.
2457
- function convertTemplateInstanceToLocal(
2458
- target: ForkTarget,
2459
- template: FetchedTemplate,
2460
- ): void {
2461
- const { node, containerGraph } = target
2462
- const idx = containerGraph.nodes.findIndex(
2463
- (n) => n.id === node.id && n.kind === 'group',
2464
- )
2465
- if (idx === -1) return
2466
- const updated: GraphNode = {
2467
- ...node,
2468
- // Deep-clone the template's subgraph so subsequent edits to the
2469
- // template (or to this fork) don't alias each other. JSON round-trip
2470
- // strips Vue's reactive proxy — structuredClone throws on proxies.
2471
- subgraph: JSON.parse(JSON.stringify(template.subgraph)) as ProcedureGraph,
2472
- // Preserve the local ports if the instance carries them (it should
2473
- // — palette drops clone template.ports onto the instance); fall back
2474
- // to the template's port list otherwise.
2475
- ports: Array.isArray(node.ports) && node.ports.length > 0
2476
- ? node.ports.map((p) => ({ ...p }))
2477
- : template.ports.map((p) => ({ ...p })),
2478
- }
2479
- delete updated.templateId
2480
-
2481
- // If the user was inside the template instance's subgraph (Case A in
2482
- // forkTarget), pop the read-only path segment first so the canvas
2483
- // re-binds to the (now editable) outer graph. The user can re-enter
2484
- // the local subgraph fresh via dblclick if they want.
2485
- if (isCurrentGraphReadOnly.value && subgraphPath.value.length > 1) {
2486
- subgraphPath.value = subgraphPath.value.slice(0, -1)
2487
- selectedNodeId.value = updated.id
2488
- }
2489
-
2490
- // Use onUpdateNode — it walks subgraphPath and rewrites the correct
2491
- // container graph (root or any depth). Because we just popped above
2492
- // when needed, currentGraph now points at containerGraph.
2493
- onUpdateNode(updated)
2494
- }
2495
-
2496
- function formatForkError(err: unknown): string {
2497
- const status = (err as { statusCode?: number; status?: number } | undefined)
2498
- const code = status?.statusCode ?? status?.status
2499
- if (code === 404) {
2500
- return 'This template no longer exists. It may have been deleted by another user.'
2501
- }
2502
- const data = (err as { data?: { error?: string } } | undefined)?.data
2503
- if (data?.error) return data.error
2504
- return describeApiError(err)
2505
- }
2506
-
2507
- async function submitFork() {
2508
- const target = forkTarget.value
2509
- if (!target) return
2510
- const templateId = target.node.templateId
2511
- if (!templateId) return
2512
- forkSubmitting.value = true
2513
- forkError.value = null
2514
- try {
2515
- const tpl = await $authFetch<FetchedTemplate>(
2516
- `/api/automation/templates/${templateId}`,
2517
- )
2518
- convertTemplateInstanceToLocal(target, tpl)
2519
- forkOpen.value = false
2520
- toast.add({
2521
- title: t('dms_automation.editor.forked', {
2522
- name: target.node.label || (target.node.config?.name as string | undefined) || tpl.name,
2523
- }),
2524
- color: 'success',
2525
- icon: 'i-ph-check-circle',
2526
- })
2527
- } catch (e) {
2528
- forkError.value = formatForkError(e)
2529
- } finally {
2530
- forkSubmitting.value = false
2531
- }
2532
- }
2533
-
2534
- // Keyboard. With Ctrl (⌘ on macOS): S saves, Enter runs a test, P opens the
2535
- // switcher, Z / Shift+Z / Y undo and redo, D duplicates the selected step, C
2536
- // and V copy and paste the selection. Enter enters the selected group, Escape
2537
- // leaves the debug view, then the group, then the selection. Tab is left to
2538
- // the focus. Keys typed in a field, or while a dialog or a menu is open,
2539
- // belong to them.
2540
- function isEditableTarget(target: EventTarget | null): boolean {
2541
- if (!(target instanceof HTMLElement)) return false
2542
- const tag = target.tagName
2543
- if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true
2544
- if (target.isContentEditable) return true
2545
- return false
2546
- }
2547
-
2548
- // Open overlays only: a closing dialog stays in the page while it animates
2549
- // out, and a non-modal card (the DMS star prompt) has no state at all.
2550
- const OVERLAY_SELECTOR = ':is([role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"])[data-state="open"]'
2551
-
2552
- function isOverlayOpen(): boolean {
2553
- return (
2554
- saveAsTemplateOpen.value ||
2555
- forkOpen.value ||
2556
- switcherOpen.value ||
2557
- runNowOpen.value ||
2558
- newProcedureOpen.value ||
2559
- choiceDialog.value.open ||
2560
- document.querySelector(OVERLAY_SELECTOR) !== null
2561
- )
2562
- }
2563
-
2564
- /**
2565
- * Blurs the focused field so it commits what is typed in it (a JSON setting
2566
- * or the step name only do on blur), and returns it to focus again after.
2567
- */
2568
- async function commitFocusedField(): Promise<HTMLElement | null> {
2569
- const field = document.activeElement
2570
- if (!(field instanceof HTMLElement) || !isEditableTarget(field)) return null
2571
- field.blur()
2572
- await nextTick()
2573
- return field
2574
- }
2575
-
2576
- async function saveFromKeyboard() {
2577
- const field = await commitFocusedField()
2578
- if (isDirty.value) await onSave()
2579
- field?.focus()
2580
- }
2581
-
2582
- async function testRunFromKeyboard() {
2583
- const field = await commitFocusedField()
2584
- await onTestRun()
2585
- field?.focus()
2586
- }
2587
-
2588
- // Ctrl+C / Ctrl+V: the selected steps and the wires between them, pasted as
2589
- // new steps beside the originals, in this graph or another one.
2590
- let clipboard: ProcedureGraph | null = null
2591
-
2592
- function copySelection(): boolean {
2593
- const g = currentGraph.value
2594
- const ids = new Set(selectedNodeIds.value.length > 0 ? selectedNodeIds.value : selectedNodeId.value ? [selectedNodeId.value] : [])
2595
- if (!g || ids.size === 0) return false
2596
- const nodes = g.nodes.filter((n) => ids.has(n.id) && n.kind !== 'groupInput' && n.kind !== 'groupOutput')
2597
- if (nodes.length === 0) return false
2598
- const kept = new Set(nodes.map((n) => n.id))
2599
- clipboard = cloneGraph({
2600
- nodes,
2601
- triggerEdges: g.triggerEdges.filter((e) => kept.has(e.from.node) && kept.has(e.to.node)),
2602
- dataEdges: g.dataEdges.filter((e) => kept.has(e.from.node) && kept.has(e.to.node)),
2603
- })
2604
- return true
2605
- }
2606
-
2607
- function pasteClipboard(): boolean {
2608
- const g = currentGraph.value
2609
- if (!g || !clipboard || isCurrentGraphReadOnly.value) return false
2610
- // Triggers only live at the top level of a procedure.
2611
- const triggersAllowed = editorMode.value === 'procedure' && subgraphPath.value.length <= 1
2612
- // Each paste lands one step further, like Duplicate.
2613
- clipboard.nodes = clipboard.nodes.map((n) => ({ ...n, position: { x: n.position.x + 40, y: n.position.y + 60 } }))
2614
- const source = cloneGraph(clipboard)
2615
- const nodes = source.nodes.filter((n) => triggersAllowed || n.kind !== 'trigger')
2616
- if (nodes.length === 0) return false
2617
- const ids = new Map(nodes.map((n) => [n.id, newId()]))
2618
- const idOf = (id: string) => ids.get(id)!
2619
- const pasted = nodes.map((n) => ({ ...n, id: idOf(n.id) }))
2620
- const triggerEdges = source.triggerEdges
2621
- .filter((e) => ids.has(e.from.node) && ids.has(e.to.node))
2622
- .map((e) => ({ ...e, id: newId(), from: { ...e.from, node: idOf(e.from.node) }, to: { ...e.to, node: idOf(e.to.node) } }))
2623
- const dataEdges = source.dataEdges
2624
- .filter((e) => ids.has(e.from.node) && ids.has(e.to.node))
2625
- .map((e) => ({ ...e, id: newId(), from: { ...e.from, node: idOf(e.from.node) }, to: { ...e.to, node: idOf(e.to.node) } }))
2626
- onGraphUpdate({
2627
- ...g,
2628
- nodes: [...g.nodes, ...pasted],
2629
- triggerEdges: [...g.triggerEdges, ...triggerEdges],
2630
- dataEdges: [...g.dataEdges, ...dataEdges],
2631
- })
2632
- selectedNodeId.value = pasted.at(-1)!.id
2633
- return true
2634
- }
2635
-
2636
- /** The editing shortcuts, on the canvas: whatever is not typed in a field. */
2637
- function onEditShortcut(ev: KeyboardEvent, key: string): boolean {
2638
- if (isEditableTarget(ev.target)) return false
2639
- if (key === 'z' || key === 'y') {
2640
- if (key === 'y' || ev.shiftKey) onRedo()
2641
- else onUndo()
2642
- return true
2643
- }
2644
- if (key === 'd') {
2645
- const node = selectedNode.value
2646
- if (node && node.kind !== 'groupInput' && node.kind !== 'groupOutput') onDuplicateNode({ id: node.id })
2647
- return true
2648
- }
2649
- // A text selected on the page is copied as text.
2650
- if (key === 'c') return !window.getSelection()?.toString() && copySelection()
2651
- if (key === 'v') return pasteClipboard()
2652
- return false
2653
- }
2654
-
2655
- // Listened to in the capture phase, so a focused field (a select opens on
2656
- // Enter) never sees a shortcut meant for the builder.
2657
- function onShortcut(ev: KeyboardEvent): boolean {
2658
- if (!(ev.metaKey || ev.ctrlKey) || ev.altKey) return false
2659
- const key = ev.key.toLowerCase()
2660
- // The browser's "Save page" is never what Ctrl+S means here.
2661
- if (key === 's') ev.preventDefault()
2662
- if (isOverlayOpen()) return false
2663
- if (['s', 'enter', 'p'].includes(key)) ev.stopPropagation()
2664
- if (key === 's') {
2665
- void saveFromKeyboard()
2666
- return true
2667
- }
2668
- if (key === 'enter' && editorMode.value === 'procedure') {
2669
- ev.preventDefault()
2670
- void testRunFromKeyboard()
2671
- return true
2672
- }
2673
- if (key === 'p' && editorMode.value === 'procedure') {
2674
- ev.preventDefault()
2675
- switcherOpen.value = true
2676
- return true
2677
- }
2678
- if (onEditShortcut(ev, key)) {
2679
- ev.preventDefault()
2680
- ev.stopPropagation()
2681
- return true
2682
- }
2683
- return false
2684
- }
2685
-
2686
- /** Enter belongs to a focused button or link; elsewhere it enters a group. */
2687
- function isActivatable(target: EventTarget | null): boolean {
2688
- return target instanceof Element && target.closest('button, a[href], [role="button"], [role="tab"], [role="menuitem"], [role="option"]') !== null
2689
- }
2690
-
2691
- function onKeyDown(ev: KeyboardEvent) {
2692
- if (onShortcut(ev)) return
2693
- if (isEditableTarget(ev.target) || isOverlayOpen()) return
2694
- if (ev.key === 'Enter' && !ev.shiftKey && !ev.ctrlKey && !ev.metaKey && !ev.altKey) {
2695
- if (!canEnterGroup.value || isActivatable(ev.target)) return
2696
- ev.preventDefault()
2697
- enterSelectedGroup()
2698
- return
2699
- }
2700
- if (ev.key !== 'Escape') return
2701
- if (overlayRun.value && subgraphPath.value.length <= 1) {
2702
- ev.preventDefault()
2703
- exitDebug()
2704
- } else if (subgraphPath.value.length > 1) {
2705
- ev.preventDefault()
2706
- exitSubgraph()
2707
- } else if (selectedNodeId.value) {
2708
- ev.preventDefault()
2709
- selectedNodeId.value = null
2710
- }
2711
- }
2712
-
2713
- onMounted(() => {
2714
- if (typeof window === 'undefined') return
2715
- window.addEventListener('keydown', onKeyDown, { capture: true })
2716
- document.addEventListener('inertia:before', onInertiaBefore)
2717
- browserNavigation()?.addEventListener('navigate', onNavigate)
2718
- })
2719
- onBeforeUnmount(() => {
2720
- if (typeof window === 'undefined') return
2721
- window.removeEventListener('keydown', onKeyDown, { capture: true })
2722
- document.removeEventListener('inertia:before', onInertiaBefore)
2723
- browserNavigation()?.removeEventListener('navigate', onNavigate)
2724
- })
2725
-
2726
- // ---------------------------------------------------------------------------
2727
- // Runs over the canvas: Test run of the draft, debugging a stored run (AU-05)
2728
- // ---------------------------------------------------------------------------
2729
-
2730
- // The dock's last runs: its tab counts the failed ones, folded too.
2731
- const RECENT_RUNS = 8
2732
- const recentRunsRead = useApiData<DockRun[]>(selectedProcedureUrl('runs'), { query: { limit: RECENT_RUNS } })
2733
- const recentRuns = computed(() => {
2734
- const list = ofSelected(recentRunsRead)
2735
- return Array.isArray(list) ? list.slice(0, RECENT_RUNS) : []
2736
- })
2737
-
2738
- /** The run shown over the canvas, and whether it is a test of the draft. */
2739
- const overlayRun = ref<RunDetail | null>(null)
2740
- const overlayIsTest = ref(false)
2741
- const testing = ref(false)
2742
- const testPayload = ref('{}')
2743
- const testPayloadSource = ref<string | null>(null)
2744
- // The trigger a Test run starts from, chosen in the dock (see the watch on
2745
- // the draft's triggers at the end).
2746
- const testTriggerNodeId = ref<string | undefined>(undefined)
2747
-
2748
- // The last real payload of the trigger a Test run starts from, which fills
2749
- // the test payload the user then edits. Left to the browser: it is shown
2750
- // only once the dock's payload tab is opened, and may be large.
2751
- const lastPayloadRead = useApiData<{ last: { runId: string; payload: unknown } | null }>(selectedProcedureUrl('last-payload'), {
2752
- query: () => (testTriggerNodeId.value ? { triggerNodeId: testTriggerNodeId.value } : {}),
2753
- server: false,
2754
- // Copied into an editable field: the page's refreshes leave the draft alone.
2755
- refreshOnPageRefresh: false,
2756
- })
2757
- // Each answer (or failure) of another procedure or trigger replaces the
2758
- // payload; the previous procedure's, still on screen meanwhile, does not.
2759
- watch([() => lastPayloadRead.data.value, () => lastPayloadRead.error.value], ([answer, error]) => {
2760
- if (!error && lastPayloadRead.placeholder.value) return
2761
- const last = error ? null : answer?.last
2762
- testPayload.value = JSON.stringify(last?.payload ?? {}, null, 2)
2763
- testPayloadSource.value = last?.runId ?? null
2764
- })
2765
-
2766
- const runStates = computed<Record<string, NodeRunState> | undefined>(() => {
2767
- const run = overlayRun.value
2768
- if (!run || subgraphPath.value.length > 1) return undefined
2769
- const out: Record<string, NodeRunState> = {}
2770
- for (const step of run.trace.steps) {
2771
- const id = step.nodeId.split('__')[0]!
2772
- const previous = out[id]
2773
- const status = step.status === 'failed' ? 'failed' : 'ok'
2774
- if (!previous || status === 'failed') {
2775
- out[id] = { status, durationMs: (previous?.durationMs ?? 0) + (step.durationMs ?? 0) }
2776
- }
2777
- }
2778
- for (const skipped of run.trace.skipped) out[skipped.nodeId] = { status: 'skipped' }
2779
- return out
2780
- })
2781
-
2782
- const overlaySteps = computed<TraceStep[] | null>(() => (overlayIsTest.value ? (overlayRun.value?.trace.steps ?? null) : null))
2783
-
2784
- // The dock's "Test run" tab only exists while a test run is on screen.
2785
- watch(overlaySteps, (steps) => {
2786
- if (!steps && dockTab.value === 'test') dockTab.value = 'problems'
2787
- })
2788
-
2789
- /** The step of the selected node in the run on screen, for the inspector. */
2790
- const selectedRunStep = computed<TraceStep | null>(() => {
2791
- const id = selectedNodeId.value
2792
- const steps = overlayRun.value?.trace.steps ?? []
2793
- if (!id) return null
2794
- const own = steps.filter((s) => s.nodeId === id || s.nodeId.startsWith(`${id}__`))
2795
- return own.find((s) => s.status === 'failed') ?? own.at(-1) ?? null
2796
- })
2797
-
2798
- const overlayLabel = computed(() => {
2799
- const run = overlayRun.value
2800
- if (!run) return ''
2801
- const when = describeTime(run.startedAt, dateTimeFormat)
2802
- return overlayIsTest.value
2803
- ? t('dms_automation.editor.debug.testLabel', { when })
2804
- : t('dms_automation.editor.debug.runLabel', { run: run._id.slice(-6), when })
2805
- })
2806
-
2807
- /** A real run of an older version than the one open says so. */
2808
- const overlayDescription = computed(() => {
2809
- const run = overlayRun.value
2810
- const version = selected.value?.version
2811
- if (!run || overlayIsTest.value || !run.procedureVersion || !version || run.procedureVersion === version) return overlayLabel.value
2812
- return `${overlayLabel.value} · ${t('dms_automation.editor.debug.olderVersion', { run: run.procedureVersion, current: version })}`
2813
- })
2814
-
2815
- const overlaySummary = computed(() => {
2816
- const run = overlayRun.value
2817
- if (!run) return ''
2818
- const duration = describeDuration(run.durationMs, locale.value)
2819
- if (run.status === 'failed') {
2820
- const step = stepTitle(run.failedStep, processI18n)
2821
- return step
2822
- ? t('dms_automation.editor.debug.failedAt', { step, duration })
2823
- : t('dms_automation.editor.debug.failed', { duration })
2824
- }
2825
- return t('dms_automation.editor.debug.passed', { duration })
2826
- })
2827
-
2828
- /** The overlay banner's tone and icon, by how the run ended. */
2829
- const overlayLook = computed(() => {
2830
- const status = overlayRun.value?.status
2831
- if (status === 'failed') return { tone: 'error', icon: 'i-ph-bug' } as const
2832
- return { tone: 'success', icon: 'i-ph-check-circle' } as const
2833
- })
2834
-
2835
- /** Shows a stored run over the canvas; a test run is told by its kind. */
2836
- function displayRun(run: RunDetail) {
2837
- overlayRun.value = run
2838
- overlayIsTest.value = run.kind === 'test'
2839
- if (run.failedNodeId) selectNode(run.failedNodeId.split('__')[0]!)
2840
- }
2841
-
2842
- async function showRun(runId: string): Promise<RunDetail> {
2843
- const run = await runsApi.getRun(runId)
2844
- displayRun(run)
2845
- return run
2846
- }
2847
-
2848
- /**
2849
- * `?run=`: the run is shown over the procedure it ran, which the builder
2850
- * opens if another one is asked; a run that no longer exists is said.
2851
- */
2852
- async function openRunFromUrl(runId: string) {
2853
- const notFound = () => {
2854
- toast.add({ title: t('dms_automation.editor.debug.runNotFound'), color: 'warning', icon: 'i-ph-warning' })
2855
- exitDebug()
2856
- }
2857
- let run: RunDetail
2858
- try {
2859
- run = await runsApi.getRun(runId)
2860
- } catch {
2861
- notFound()
2862
- return
2863
- }
2864
- if (run.procedureId !== selectedId.value) {
2865
- if (!procedures.value.some((p) => p._id === run.procedureId)) {
2866
- notFound()
2867
- return
2868
- }
2869
- selectedId.value = run.procedureId
2870
- // Switching clears the run on screen: show this one after it.
2871
- await nextTick()
2872
- }
2873
- displayRun(run)
2874
- }
2875
-
2876
- function exitDebug() {
2877
- overlayRun.value = null
2878
- overlayIsTest.value = false
2879
- if (queryValue('run')) void router.replace(`${builderPath()}?selected=${selectedId.value}`)
2880
- }
2881
-
2882
- /** A step a test runs for real, as `POST /procedures/:id/test-effects` lists it. */
2883
- interface RealEffectStep {
2884
- nodeId: string
2885
- typeId: string
2886
- typeName: string
2887
- label?: string
2888
- }
2889
-
2890
- /**
2891
- * Asks before a test that acts for real: the steps that would (actions that
2892
- * cannot simulate) are listed. Resolves `true` at once when there are none.
2893
- */
2894
- async function confirmRealEffects(procedureId: string, graph: unknown): Promise<boolean> {
2895
- const { realEffects } = await $authFetch<{ realEffects: RealEffectStep[] }>(`${props.apiUrl}/procedures/${procedureId}/test-effects`, {
2896
- method: 'POST',
2897
- body: { graph },
2898
- })
2899
- if (realEffects.length === 0) return true
2900
- return await confirm({
2901
- title: t('dms_automation.editor.testEffects.title'),
2902
- description: t('dms_automation.editor.testEffects.description', { count: realEffects.length }),
2903
- color: 'warning',
2904
- icon: 'i-ph-flask',
2905
- confirmLabel: t('dms_automation.editor.testEffects.confirm'),
2906
- initialFocus: 'cancel',
2907
- impact: realEffects.map((step) => ({
2908
- icon: 'i-ph-lightning',
2909
- label: processI18n(step.typeName),
2910
- ...(step.label ? { count: step.label } : {}),
2911
- })),
2912
- })
2913
- }
2914
-
2915
- async function onTestRun() {
2916
- const current = selected.value
2917
- // One test at a time: Ctrl+Enter pressed again waits for it.
2918
- if (!current || editorMode.value !== 'procedure' || testing.value) return
2919
- let payload: unknown
2920
- try {
2921
- payload = JSON.parse(testPayload.value || 'null')
2922
- } catch {
2923
- dockTab.value = 'payload'
2924
- dockCollapsed.value = false
2925
- toast.add({ title: t('dms_automation.editor.dock.invalidJson'), color: 'error', icon: 'i-ph-warning' })
2926
- return
2927
- }
2928
- testing.value = true
2929
- try {
2930
- // Steps that act for real (an e-mail sent, a record written) are named
2931
- // before the test runs, never after: closing the question runs nothing.
2932
- if (!(await confirmRealEffects(current._id, current.graph))) return
2933
- // The previous result leaves the canvas while this test runs.
2934
- overlayRun.value = null
2935
- overlayIsTest.value = false
2936
- const res = await $authFetch<{ runId: string }>(`${props.apiUrl}/procedures/${current._id}/test`, {
2937
- method: 'POST',
2938
- body: { graph: current.graph, payload, triggerNodeId: testTriggerNodeId.value, confirmRealEffects: true },
2939
- })
2940
- await showRun(res.runId)
2941
- dockTab.value = 'test'
2942
- dockCollapsed.value = false
2943
- void recentRunsRead.refresh()
2944
- } catch (e) {
2945
- const refused = issuesOf(e)
2946
- if (refused) {
2947
- issues.value = refused
2948
- dockTab.value = 'problems'
2949
- dockCollapsed.value = false
2950
- }
2951
- toast.add({ title: t('dms_automation.editor.testRunError'), description: describeApiError(e), color: 'error', icon: 'i-ph-warning' })
2952
- } finally {
2953
- testing.value = false
2954
- }
2955
- }
2956
-
2957
- /** Run now runs the saved graph: with unsaved changes, say so first. */
2958
- async function openRunNow() {
2959
- if (!selected.value) return
2960
- if (isDirty.value) {
2961
- // Closing the question (Escape, ✕, a click outside) runs nothing.
2962
- const choice = await askChoice({
2963
- title: t('dms_automation.editor.runSaved.title'),
2964
- description: t('dms_automation.editor.runSaved.description', { count: changeCount.value }),
2965
- choices: [
2966
- { value: 'cancel', label: t('dms_automation.common.cancel'), color: 'neutral', variant: 'ghost' },
2967
- { value: 'test', label: t('dms_automation.editor.runSaved.testDraft'), color: 'neutral', variant: 'outline' },
2968
- { value: 'saved', label: t('dms_automation.editor.runSaved.runSaved'), color: 'warning' },
2969
- ],
2970
- dismiss: 'cancel',
2971
- })
2972
- if (choice === 'cancel') return
2973
- if (choice === 'test') {
2974
- await onTestRun()
2975
- return
2976
- }
2977
- }
2978
- runNowOpen.value = true
2979
- }
2980
-
2981
- /** A run of the saved version ended: show it, and say how it went. */
2982
- async function onRunStarted(runId: string) {
2983
- const name = savedName.value
2984
- const trace = { label: t('dms_automation.runs.trace'), onClick: () => void router.push(`${props.traceUrl}?run=${runId}`) }
2985
- void recentRunsRead.refresh()
2986
- void summariesRead.refresh()
2987
- let run: RunDetail
2988
- try {
2989
- run = await showRun(runId)
2990
- } catch {
2991
- toast.add({ title: t('dms_automation.editor.runStarted', { name }), color: 'neutral', icon: 'i-ph-play-circle', actions: [trace] })
2992
- return
2993
- }
2994
- const step = stepTitle(run.failedStep, processI18n)
2995
- const failed = run.status === 'failed'
2996
- toast.add({
2997
- title: failed
2998
- ? step
2999
- ? t('dms_automation.editor.runFailedAt', { name, step })
3000
- : t('dms_automation.editor.runFailed', { name })
3001
- : t('dms_automation.editor.runSucceeded', { name }),
3002
- color: failed ? 'error' : 'success',
3003
- icon: failed ? 'i-ph-x-circle' : 'i-ph-check-circle',
3004
- actions: [trace],
3005
- })
3006
- }
3007
-
3008
- /**
3009
- * Debugging a real run: once the fix is saved, run it again with the payload
3010
- * it received, on the saved version, and show the new run in its place.
3011
- */
3012
- async function rerunOverlay() {
3013
- const run = overlayRun.value
3014
- if (!run || overlayIsTest.value) return
3015
- let newRunId: string | null = null
3016
- const confirmed = await confirm({
3017
- title: t('dms_automation.runs.rerunConfirmTitle'),
3018
- description: t('dms_automation.runs.rerunConfirmDescription'),
3019
- color: 'warning',
3020
- icon: 'i-ph-arrow-clockwise',
3021
- confirmLabel: t('dms_automation.runs.rerun'),
3022
- onConfirm: async () => {
3023
- newRunId = (await runsApi.rerun(run._id)).runId
3024
- },
3025
- })
3026
- if (!confirmed || !newRunId) return
3027
- await onRunStarted(newRunId)
3028
- if (queryValue('run')) void router.replace(`${builderPath()}?selected=${selectedId.value}&run=${newRunId}`)
3029
- }
3030
-
3031
- function openTrace(runId: string) {
3032
- void router.push(`${props.traceUrl}?run=${runId}`)
3033
- }
3034
-
3035
- // ---------------------------------------------------------------------------
3036
- // Node actions from the inspector
3037
- // ---------------------------------------------------------------------------
3038
-
3039
- function onDuplicateNode(payload: { id: string }) {
3040
- const g = currentGraph.value
3041
- if (!g || isCurrentGraphReadOnly.value) return
3042
- const node = g.nodes.find((n) => n.id === payload.id)
3043
- if (!node) return
3044
- const copy: GraphNode = {
3045
- ...cloneGraph({ nodes: [node], triggerEdges: [], dataEdges: [] }).nodes[0]!,
3046
- id: newId(),
3047
- position: { x: node.position.x + 40, y: node.position.y + 60 },
3048
- }
3049
- onGraphUpdate({ ...g, nodes: [...g.nodes, copy] })
3050
- selectedNodeId.value = copy.id
3051
- }
3052
-
3053
- /** Put a Retry in front of a step: it now runs inside the Retry's body. */
3054
- function onWrapInRetry(payload: { id: string }) {
3055
- const g = currentGraph.value
3056
- if (!g || isCurrentGraphReadOnly.value) return
3057
- const node = g.nodes.find((n) => n.id === payload.id)
3058
- if (!node) return
3059
- const retry: GraphNode = {
3060
- id: newId(),
3061
- kind: 'retry',
3062
- config: { maxAttempts: 3 },
3063
- position: { x: node.position.x - 40, y: node.position.y - 140 },
3064
- }
3065
- const triggerEdges = g.triggerEdges.map((e) => {
3066
- if (e.to.node === node.id) return { ...e, to: { ...e.to, node: retry.id } }
3067
- if (e.from.node === node.id && (!e.from.branch || e.from.branch === 'main')) {
3068
- return { ...e, from: { node: retry.id, branch: 'main' } }
3069
- }
3070
- return e
3071
- })
3072
- triggerEdges.push({ id: newId(), from: { node: retry.id, branch: 'body' }, to: { node: node.id } })
3073
- onGraphUpdate({ ...g, nodes: [...g.nodes, retry], triggerEdges })
3074
- selectedNodeId.value = retry.id
3075
- }
3076
-
3077
- // ---------------------------------------------------------------------------
3078
- // Loading what the bar and the dock show, per procedure
3079
- // ---------------------------------------------------------------------------
3080
-
3081
- // Another procedure opened: what the bar and the dock show follows it
3082
- // through their reads' URLs.
3083
- watch(selectedId, (id) => {
3084
- if (id) missingProcedureId.value = null
3085
- overlayRun.value = null
3086
- })
3087
-
3088
- /** `?path=g1,g2`: the groups to enter, outermost first, before `?node=`. */
3089
- function enterPathFromUrl(): boolean {
3090
- const ids = (queryValue('path') ?? '').split(',').filter(Boolean)
3091
- for (const id of ids) {
3092
- const depth = subgraphPath.value.length
3093
- onGroupEnter({ id })
3094
- if (subgraphPath.value.length === depth) break
3095
- }
3096
- return subgraphPath.value.length > 1
3097
- }
3098
-
3099
- onMounted(async () => {
3100
- if (missingProcedureId.value) switcherOpen.value = true
3101
- const runId = queryValue('run')
3102
- if (runId) await openRunFromUrl(runId)
3103
- const nodeId = queryValue('node')
3104
- if (nodeId) {
3105
- if (enterPathFromUrl()) selectedNodeId.value = nodeId
3106
- else selectNode(nodeId)
3107
- }
3108
- // The URL names the procedure on screen, to share or reload it.
3109
- if (editorMode.value === 'procedure' && selectedId.value && queryValue('selected') !== selectedId.value) {
3110
- void router.replace({ path: builderPath(), query: { ...route.query, selected: selectedId.value } })
3111
- }
3112
- })
3113
-
3114
- const selectedTriggerSummaries = computed<TriggerSummary[]>(() =>
3115
- (selected.value?.graph.nodes ?? [])
3116
- .filter((n) => n.kind === 'trigger' && n.typeId)
3117
- .map((n) => ({
3118
- nodeId: n.id,
3119
- typeId: n.typeId!,
3120
- typeName: triggerTypes.value.find((x) => x.id === n.typeId)?.name ?? n.typeId!,
3121
- path: typeof n.config?.path === 'string' ? n.config.path : undefined,
3122
- method: typeof n.config?.method === 'string' ? n.config.method : undefined,
3123
- cron: typeof n.config?.cron === 'string' ? n.config.cron : undefined,
3124
- })),
3125
- )
3126
-
3127
- // A draft trigger as the server words it, its type's name until it has.
3128
- function triggerLabel(trigger: TriggerSummary): string {
3129
- const worded = draftTriggers.value.find((tr) => tr.nodeId === trigger.nodeId)
3130
- return worded ? processText(worded.text) : processI18n(trigger.typeName)
3131
- }
3132
-
3133
- // Test run starts from the trigger picked in the dock: the manual one, else
3134
- // the first, until the user picks another; its last real payload prefills
3135
- // the test payload.
3136
- const testTriggerItems = computed(() =>
3137
- selectedTriggerSummaries.value.map((trigger) => ({ label: triggerLabel(trigger), value: trigger.nodeId ?? '' })),
3138
- )
3139
- watch(
3140
- selectedTriggerSummaries,
3141
- (triggers) => {
3142
- if (triggers.some((trigger) => trigger.nodeId === testTriggerNodeId.value)) return
3143
- testTriggerNodeId.value = triggers.find((trigger) => trigger.typeId === 'manual')?.nodeId ?? triggers[0]?.nodeId
3144
- },
3145
- { immediate: true },
3146
- )
3147
-
3148
- // Below xl the inspector floats over the canvas instead of narrowing it; the
3149
- // palette can be put away. Remembered per browser.
3150
- const PALETTE_HIDDEN_KEY = 'dms-automation:builder-palette-hidden'
3151
- const PALETTE_FOLDED_BELOW_PX = 1280
3152
- const paletteHidden = ref(false)
3153
- onMounted(() => {
3154
- // Folded by default below xl, where it would leave the canvas too little.
3155
- let stored: string | null = null
3156
- try {
3157
- stored = window.localStorage.getItem(PALETTE_HIDDEN_KEY)
3158
- } catch {
3159
- // Storage blocked: the default for the width applies.
3160
- }
3161
- paletteHidden.value = stored === null ? window.innerWidth < PALETTE_FOLDED_BELOW_PX : stored === '1'
3162
- })
3163
- function togglePalette() {
3164
- paletteHidden.value = !paletteHidden.value
3165
- try {
3166
- window.localStorage.setItem(PALETTE_HIDDEN_KEY, paletteHidden.value ? '1' : '0')
3167
- } catch {
3168
- // Storage blocked: the choice lasts until the page is left.
3169
- }
3170
- }
3171
-
3172
- // Template mode: the template's own ports are edited at its root, where its
3173
- // Group input / Group output steps show them. Shown when no step, or
3174
- // one of those two, is selected.
3175
- const showTemplatePorts = computed<boolean>(
3176
- () =>
3177
- editorMode.value === 'template' &&
3178
- subgraphPath.value.length <= 1 &&
3179
- (!selectedNode.value || selectedNode.value.kind === 'groupInput' || selectedNode.value.kind === 'groupOutput'),
3180
- )
3181
-
3182
- function onTemplatePortsUpdate(next: GroupPort[]) {
3183
- const root = selected.value?.graph
3184
- if (!root) return
3185
- // The root graph is the template's subgraph: renames and removals go
3186
- // through the same path as a group's ports.
3187
- const template: GraphNode = {
3188
- id: '',
3189
- kind: 'group',
3190
- config: {},
3191
- position: { x: 0, y: 0 },
3192
- ports: next.map((p) => ({ ...p })),
3193
- subgraph: cloneGraph(root),
3194
- }
3195
- const renames = detectPortRenames(templatePorts.value, next)
3196
- const gi = template.subgraph!.nodes.find((n) => n.kind === 'groupInput')
3197
- const go = template.subgraph!.nodes.find((n) => n.kind === 'groupOutput')
3198
- const inRenames = renames.filter((r) => r.direction === 'in')
3199
- const outRenames = renames.filter((r) => r.direction === 'out')
3200
- if (gi && inRenames.length > 0) applyPortRenamesToEdges(template.subgraph!.triggerEdges, template.subgraph!.dataEdges, gi.id, inRenames, true)
3201
- if (go && outRenames.length > 0) applyPortRenamesToEdges(template.subgraph!.triggerEdges, template.subgraph!.dataEdges, go.id, outRenames, true)
3202
- syncSentinels(template)
3203
- templatePorts.value = template.ports!
3204
- onGraphUpdate(template.subgraph!)
3205
- }
69
+ graphHistory.initHistoryAndSaved()
70
+ seedSubgraphPath(ctx)
71
+
72
+ const nav = useSubgraphNavigation(ctx, graphHistory, load)
73
+ const groups = useGroupEditing(ctx, nav)
74
+ const problems = useDraftProblems(ctx, graphHistory, nav)
75
+ const triggers = useSavedTriggers(ctx, problems)
76
+ const guards = useUnsavedGuards(ctx, graphHistory, problems, { onSave: () => save.onSave() })
77
+ const actions = useProcedureActions(ctx, load, problems, guards)
78
+ const save = useBuilderSave(ctx, graphHistory, problems, triggers, guards, { onTestRun: () => runs.onTestRun() })
79
+ const saveTpl = useSaveAsTemplate(ctx, graphHistory, nav, save)
80
+ const fork = useForkToLocal(ctx, nav)
81
+ useBuilderShortcuts(ctx, graphHistory, nav, groups, guards, save, saveTpl, fork, {
82
+ onTestRun: () => runs.onTestRun(),
83
+ exitDebug: () => runs.exitDebug(),
84
+ })
85
+ const runs = useRunOverlay(ctx, graphHistory, problems, triggers, guards)
86
+ const mount = useBuilderMount(ctx, nav, problems, runs)
87
+ const palette = usePalette()
3206
88
 
89
+ // The inspector (or the template's ports): docked beside the canvas from lg
90
+ // (the palette starts folded below xl, so the canvas keeps most of the
91
+ // width), floating over it on narrower screens.
92
+ const ASIDE_CLASS =
93
+ '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'
3207
94
 
95
+ const { actionTypes, canvasViewKey, currentGraph, currentParentGroupPorts, dataNodeTypes, dockCollapsed, dockTab, draftTriggers, editorMode, formatShortcut, graphCanvasRef, inspectorRef, isCurrentGraphReadOnly, libraryBackUrl, loadError, loading, missingProcedureId, newProcedureOpen, nodeKinds, onSelectionChange, overlayIsTest, overlayRun, paletteTriggerTypes, palettesTemplates, runNowOpen, saveBlocked, saving, selected, selectedId, selectedNode, selectedNodeActionType, selectedNodeId, selectedNodeIds, selectedNodeTriggerType, subgraphPath, switcherOpen, templateNotFound, templatePorts, testPayload, testPayloadSource, testTriggerNodeId, testing, triggerTypes } = ctx
96
+ const { canRedo, canUndo, isDirty, onRedo, onUndo } = graphHistory
97
+ const { breadcrumbItems, canEnterGroup, enterSelectedGroup, exitSubgraph, onGraphUpdate, onGroupEnter, onPaletteAddNode, onPaletteAddTemplate, onSelectNode, onUpdateNode } = nav
98
+ const { canGroupSelection, createGroupFromSelection, onDeleteNode, onDuplicateNode, onPortsUpdate, onTemplatePortsUpdate, onUnwireField, onWrapInRetry, showTemplatePorts } = groups
99
+ const { NAME_INPUT_ID, blockingIssues, changeCount, currentSummary, dockIssues, issuesByNode, nameMissing, nodeDisplayName, onCancel, procedureEnabled, procedureName, savedName, selectNode, summaries } = problems
100
+ const { pausedBanner, saveState, savedTriggers } = triggers
101
+ const { answerChoice, choiceDialog, onChoiceDialogOpen, onPickProcedure } = guards
102
+ const { onCreate, onCreated, onDelete, onExport } = actions
103
+ const { enableNow, goToFirstProblem, onSave, saveAsDraft } = save
104
+ const { canSaveAsTemplate, openSaveAsTemplate, saveAsTemplateDescription, saveAsTemplateError, saveAsTemplateIcon, saveAsTemplateName, saveAsTemplateOpen, saveAsTemplateSubmitting, selectedLocalGroupNode, submitSaveAsTemplate, templateFieldErrors } = saveTpl
105
+ const { canForkToLocal, forkError, forkOpen, forkSubmitting, openFork, submitFork } = fork
106
+ const { exitDebug, onRunStarted, onTestRun, openRunNow, openTrace, overlayDescription, overlayLabel, overlayLook, overlaySteps, overlaySummary, recentRuns, rerunOverlay, runStates, selectedRunStep } = runs
107
+ const { testTriggerItems } = mount
108
+ const { paletteHidden, togglePalette } = palette
3208
109
  </script>
3209
110
 
3210
111
  <template>
@@ -3215,183 +116,64 @@ function onTemplatePortsUpdate(next: GroupPort[]) {
3215
116
  height; the dock under them lists problems, runs and the test payload.
3216
117
  -->
3217
118
  <div class="flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-default bg-default">
3218
- <header class="flex min-h-13 flex-wrap items-center gap-2 border-b border-default px-3 py-2">
3219
- <template v-if="editorMode === 'procedure'">
3220
- <UTooltip :text="$t('dms_automation.editor.switcher.title')" :kbds="['meta', 'p']">
3221
- <UButton
3222
- icon="i-ph-flow-arrow"
3223
- variant="ghost"
3224
- color="neutral"
3225
- :aria-label="$t('dms_automation.editor.switcher.title')"
3226
- @click="switcherOpen = true"
3227
- />
3228
- </UTooltip>
3229
- </template>
3230
- <template v-else>
3231
- <UButton icon="i-ph-arrow-left" variant="ghost" color="neutral" :to="libraryBackUrl">
3232
- {{ $t('dms_automation.library.title') }}
3233
- </UButton>
3234
- <UBadge color="info" variant="subtle">{{ $t('dms_automation.editor.templateBadge') }}</UBadge>
3235
- </template>
3236
- <UTooltip v-if="selected && currentGraph && !isCurrentGraphReadOnly" :text="paletteHidden ? $t('dms_automation.editor.showBlocks') : $t('dms_automation.editor.hideBlocks')">
3237
- <UButton
3238
- :icon="paletteHidden ? 'i-ph-sidebar-simple' : 'i-ph-sidebar-simple-fill'"
3239
- variant="ghost"
3240
- color="neutral"
3241
- :aria-label="paletteHidden ? $t('dms_automation.editor.showBlocks') : $t('dms_automation.editor.hideBlocks')"
3242
- :aria-pressed="!paletteHidden"
3243
- @click="togglePalette"
3244
- />
3245
- </UTooltip>
3246
- <UInput
3247
- v-if="selected"
3248
- :id="NAME_INPUT_ID"
3249
- v-model="procedureName"
3250
- variant="ghost"
3251
- :color="nameMissing ? 'error' : undefined"
3252
- :highlight="nameMissing"
3253
- :placeholder="editorMode === 'template' ? $t('dms_automation.editor.templateName') : $t('dms_automation.editor.procedureName')"
3254
- :aria-label="editorMode === 'template' ? $t('dms_automation.editor.templateName') : $t('dms_automation.editor.procedureName')"
3255
- :aria-invalid="nameMissing || undefined"
3256
- :aria-describedby="nameMissing ? `${NAME_INPUT_ID}-error` : undefined"
3257
- class="min-w-[12rem] max-w-sm flex-1 font-medium"
3258
- />
3259
- <DmsFieldError v-if="nameMissing" :id="`${NAME_INPUT_ID}-error`" :message="$t('dms_automation.editor.nameRequired')" />
3260
- <DmsStatusPill
3261
- v-if="currentSummary && editorMode === 'procedure'"
3262
- :tone="STATE_TONES[currentSummary.status]"
3263
- :label="$t(`dms_automation.procedures.status.${currentSummary.status}`)"
3264
- size="sm"
3265
- />
3266
- <label v-if="selected && editorMode === 'procedure'" class="flex items-center gap-2 text-sm text-muted">
3267
- <USwitch v-model="procedureEnabled" size="sm" />
3268
- {{ procedureEnabled ? $t('dms_automation.editor.enabled') : $t('dms_automation.editor.disabled') }}
3269
- </label>
3270
- <span v-if="selected" class="ml-1 inline-flex items-center gap-1 whitespace-nowrap text-xs" :class="changeCount > 0 ? 'text-warning' : 'text-dimmed'">
3271
- <UIcon :name="changeCount > 0 ? 'i-ph-circle-fill' : 'i-ph-check'" class="size-2.5 shrink-0" />
3272
- {{ saveState }}
3273
- </span>
3274
- <div class="ml-auto flex flex-wrap items-center gap-2">
3275
- <UButton
3276
- v-if="selected"
3277
- variant="ghost"
3278
- color="neutral"
3279
- :disabled="!isDirty || saving"
3280
- @click="onCancel"
3281
- >
3282
- {{ $t('dms_automation.editor.discard') }}
3283
- </UButton>
3284
- <template v-if="selected && editorMode === 'procedure'">
3285
- <UButton variant="outline" color="neutral" icon="i-ph-play" @click="openRunNow">
3286
- {{ $t('dms_automation.editor.runNowButton') }}
3287
- </UButton>
3288
- <UButton variant="outline" color="neutral" icon="i-ph-flask" :loading="testing" @click="onTestRun">
3289
- {{ $t('dms_automation.editor.testRun') }}
3290
- <UKbd :value="formatShortcut(['meta', '↵'])" size="sm" class="ml-1" />
3291
- </UButton>
3292
- </template>
3293
- <UButton v-if="selected" color="primary" icon="i-ph-floppy-disk" :disabled="!isDirty || nameMissing" :loading="saving" @click="onSave">
3294
- {{ $t('dms_automation.common.save') }}
3295
- <UKbd :value="formatShortcut(['meta', 's'])" size="sm" class="ml-1" />
3296
- </UButton>
3297
- <UDropdownMenu
3298
- v-if="selected && editorMode === 'procedure'"
3299
- :items="[
3300
- [
3301
- { label: $t('dms_automation.newProcedure.title'), icon: 'i-ph-plus', onSelect: onCreate },
3302
- { label: $t('dms_automation.editor.exportJson'), icon: 'i-ph-download-simple', onSelect: onExport },
3303
- { label: $t('dms_automation.editor.viewRuns'), icon: 'i-ph-list-bullets', to: `${runsUrl}?procedure=${selectedId}` },
3304
- ],
3305
- [{ label: $t('dms_automation.editor.delete'), icon: 'i-ph-trash', color: 'error', onSelect: onDelete }],
3306
- ]"
3307
- >
3308
- <UButton icon="i-ph-dots-three" variant="ghost" color="neutral" :aria-label="$t('dms_automation.editor.more')" />
3309
- </UDropdownMenu>
3310
- </div>
3311
- </header>
119
+ <EditorHeader
120
+ v-model:name="procedureName"
121
+ v-model:enabled="procedureEnabled"
122
+ :editor-mode="editorMode"
123
+ :library-back-url="libraryBackUrl"
124
+ :selected="selected"
125
+ :selected-id="selectedId"
126
+ :current-graph="currentGraph"
127
+ :is-current-graph-read-only="isCurrentGraphReadOnly"
128
+ :palette-hidden="paletteHidden"
129
+ :name-input-id="NAME_INPUT_ID"
130
+ :name-missing="nameMissing"
131
+ :current-summary="currentSummary"
132
+ :change-count="changeCount"
133
+ :save-state="saveState"
134
+ :is-dirty="isDirty"
135
+ :saving="saving"
136
+ :testing="testing"
137
+ :runs-url="runsUrl"
138
+ :format-shortcut="formatShortcut"
139
+ @open-switcher="switcherOpen = true"
140
+ @toggle-palette="togglePalette"
141
+ @discard="onCancel"
142
+ @run-now="openRunNow"
143
+ @test-run="onTestRun"
144
+ @save="onSave"
145
+ @create="onCreate"
146
+ @export="onExport"
147
+ @delete="onDelete"
148
+ />
3312
149
 
3313
- <div class="flex flex-col gap-2 empty:hidden" :class="loadError || saveBlocked || pausedBanner || overlayRun || testing || isCurrentGraphReadOnly ? 'border-b border-default p-2' : ''">
3314
- <DmsBanner
3315
- v-if="loadError"
3316
- size="sm"
3317
- tone="error"
3318
- icon="i-ph-warning"
3319
- :title="editorMode === 'template' ? $t('dms_automation.editor.loadTemplateError') : $t('dms_automation.editor.loadProceduresError')"
3320
- :description="loadError"
3321
- >
3322
- <template v-if="templateNotFound" #actions>
3323
- <UButton size="xs" color="error" variant="soft" icon="i-ph-arrow-left" :to="libraryBackUrl">{{ $t('dms_automation.editor.backToTemplates') }}</UButton>
3324
- </template>
3325
- </DmsBanner>
3326
- <DmsBanner
3327
- v-if="saveBlocked && blockingIssues.length"
3328
- size="sm"
3329
- tone="error"
3330
- icon="i-ph-warning-octagon"
3331
- :title="$t('dms_automation.editor.problems.title', { count: blockingIssues.length })"
3332
- :description="$t('dms_automation.editor.problems.description')"
3333
- >
3334
- <template #actions>
3335
- <UButton size="xs" color="error" variant="soft" @click="goToFirstProblem">{{ $t('dms_automation.editor.problems.first') }}</UButton>
3336
- <UButton size="xs" color="neutral" variant="outline" :loading="saving" @click="saveAsDraft">{{ $t('dms_automation.editor.problems.saveDraft') }}</UButton>
3337
- </template>
3338
- </DmsBanner>
3339
- <DmsBanner v-if="pausedBanner && !saveBlocked" size="sm" tone="warning" icon="i-ph-pause-circle" :title="pausedBanner.title" :description="pausedBanner.description">
3340
- <template #actions>
3341
- <UButton size="xs" color="warning" variant="soft" :loading="saving" :disabled="blockingIssues.length > 0" @click="enableNow">
3342
- {{ $t('dms_automation.editor.paused.enable') }}
3343
- </UButton>
3344
- </template>
3345
- </DmsBanner>
3346
- <DmsBanner
3347
- v-if="testing"
3348
- size="sm"
3349
- tone="info"
3350
- icon="i-ph-flask"
3351
- :title="$t('dms_automation.editor.debug.testing')"
3352
- :description="$t('dms_automation.editor.debug.testingHint')"
3353
- />
3354
- <DmsBanner
3355
- v-if="overlayRun && !testing"
3356
- size="sm"
3357
- :tone="overlayLook.tone"
3358
- :icon="overlayLook.icon"
3359
- :title="overlaySummary"
3360
- :description="overlayDescription"
3361
- >
3362
- <template #actions>
3363
- <UTooltip v-if="!overlayIsTest" :text="isDirty ? $t('dms_automation.editor.debug.rerunSaveFirst') : $t('dms_automation.editor.debug.rerunHint')">
3364
- <UButton size="xs" variant="soft" color="neutral" icon="i-ph-arrow-clockwise" :disabled="isDirty" @click="rerunOverlay">
3365
- {{ $t('dms_automation.runs.rerunWithPayload') }}
3366
- </UButton>
3367
- </UTooltip>
3368
- <UButton v-if="overlayIsTest" size="xs" variant="soft" color="neutral" icon="i-ph-arrow-clockwise" :loading="testing" @click="onTestRun">
3369
- {{ $t('dms_automation.editor.debug.again') }}
3370
- </UButton>
3371
- <UButton size="xs" variant="ghost" color="neutral" icon="i-ph-path" @click="openTrace(overlayRun._id)">
3372
- {{ $t('dms_automation.runs.trace') }}
3373
- </UButton>
3374
- <UButton size="xs" variant="ghost" color="neutral" @click="exitDebug">
3375
- {{ $t('dms_automation.editor.debug.exit') }}
3376
- <UKbd value="Esc" size="sm" class="ml-1" />
3377
- </UButton>
3378
- </template>
3379
- </DmsBanner>
3380
- <DmsBanner
3381
- v-if="isCurrentGraphReadOnly"
3382
- size="sm"
3383
- tone="info"
3384
- icon="i-ph-link"
3385
- :title="$t('dms_automation.editor.linkedTitle')"
3386
- :description="$t('dms_automation.editor.linkedDescription')"
3387
- >
3388
- <template v-if="canForkToLocal" #actions>
3389
- <UButton size="xs" color="info" variant="soft" icon="i-ph-git-fork" @click="openFork">
3390
- {{ $t('dms_automation.editor.forkToEdit') }}
3391
- </UButton>
3392
- </template>
3393
- </DmsBanner>
3394
- </div>
150
+ <EditorBanners
151
+ :load-error="loadError"
152
+ :template-not-found="templateNotFound"
153
+ :editor-mode="editorMode"
154
+ :library-back-url="libraryBackUrl"
155
+ :save-blocked="saveBlocked"
156
+ :blocking-issues="blockingIssues"
157
+ :paused-banner="pausedBanner"
158
+ :saving="saving"
159
+ :testing="testing"
160
+ :overlay-run="overlayRun"
161
+ :overlay-is-test="overlayIsTest"
162
+ :overlay-look="overlayLook"
163
+ :overlay-summary="overlaySummary"
164
+ :overlay-description="overlayDescription"
165
+ :is-dirty="isDirty"
166
+ :is-current-graph-read-only="isCurrentGraphReadOnly"
167
+ :can-fork-to-local="canForkToLocal"
168
+ @go-to-first-problem="goToFirstProblem"
169
+ @save-as-draft="saveAsDraft"
170
+ @enable-now="enableNow"
171
+ @rerun="rerunOverlay"
172
+ @test-run="onTestRun"
173
+ @open-trace="openTrace"
174
+ @exit-debug="exitDebug"
175
+ @open-fork="openFork"
176
+ />
3395
177
 
3396
178
  <DmsEmptyState
3397
179
  v-if="!selected && !loading && editorMode === 'procedure' && missingProcedureId"
@@ -3567,152 +349,20 @@ function onTemplatePortsUpdate(next: GroupPort[]) {
3567
349
  @started="onRunStarted"
3568
350
  />
3569
351
 
3570
- <UModal
3571
- :open="choiceDialog.open"
3572
- :title="choiceDialog.title"
3573
- :content="{ onOpenAutoFocus: focusSafeChoice }"
3574
- @update:open="onChoiceDialogOpen"
3575
- >
3576
- <template #body>
3577
- <p class="text-sm text-toned">{{ choiceDialog.description }}</p>
3578
- </template>
3579
- <template #footer>
3580
- <div class="flex w-full justify-end gap-2">
3581
- <UButton
3582
- v-for="choice in choiceDialog.choices"
3583
- :key="choice.value"
3584
- :color="choice.color ?? 'neutral'"
3585
- :variant="choice.variant ?? 'solid'"
3586
- :data-safe-choice="choice.value === choiceDialog.dismiss || undefined"
3587
- @click="answerChoice(choice.value)"
3588
- >
3589
- {{ choice.label }}
3590
- </UButton>
3591
- </div>
3592
- </template>
3593
- </UModal>
352
+ <EditorChoiceModal :dialog="choiceDialog" @update:open="onChoiceDialogOpen" @answer="answerChoice" />
3594
353
 
3595
- <UModal
354
+ <EditorSaveTemplateModal
3596
355
  v-model:open="saveAsTemplateOpen"
3597
- :title="$t('dms_automation.editor.saveTemplateModal.title')"
3598
- >
3599
- <template #body>
3600
- <div class="flex flex-col gap-3">
3601
- <DmsFieldRow
3602
- v-bind="TEMPLATE_ROW"
3603
- :label="$t('dms_automation.editor.saveTemplateModal.name')"
3604
- :label-for="TEMPLATE_NAME_ID"
3605
- required
3606
- >
3607
- <div class="grid gap-1.5">
3608
- <DmsInputText
3609
- :id="TEMPLATE_NAME_ID"
3610
- v-model="saveAsTemplateName"
3611
- :placeholder="$t('dms_automation.editor.saveTemplateModal.namePlaceholder')"
3612
- class="w-full"
3613
- :disabled="saveAsTemplateSubmitting"
3614
- v-bind="templateFieldErrors.aria('name')"
3615
- />
3616
- <DmsFieldError :id="templateFieldErrors.errorId('name')" :message="templateFieldErrors.errors.name" />
3617
- </div>
3618
- </DmsFieldRow>
3619
- <DmsFieldRow
3620
- v-bind="TEMPLATE_ROW"
3621
- :label="$t('dms_automation.editor.saveTemplateModal.description')"
3622
- label-for="save-template-description"
3623
- >
3624
- <DmsTextarea
3625
- id="save-template-description"
3626
- v-model="saveAsTemplateDescription"
3627
- :placeholder="$t('dms_automation.editor.saveTemplateModal.descriptionPlaceholder')"
3628
- class="w-full"
3629
- :rows="3"
3630
- :disabled="saveAsTemplateSubmitting"
3631
- />
3632
- </DmsFieldRow>
3633
- <DmsFieldRow v-bind="TEMPLATE_ROW" :label="$t('dms_automation.editor.saveTemplateModal.icon')">
3634
- <DmsAutomationIconPicker v-model="saveAsTemplateIcon" />
3635
- </DmsFieldRow>
3636
- <div v-if="selectedLocalGroupNode?.ports?.length" class="flex flex-col gap-1">
3637
- <span class="text-xs font-medium text-highlighted">{{ $t('dms_automation.editor.saveTemplateModal.ports') }}</span>
3638
- <div class="overflow-hidden rounded-md border border-default">
3639
- <div
3640
- v-for="port in selectedLocalGroupNode.ports"
3641
- :key="`${port.direction}-${port.kind}-${port.name}`"
3642
- class="flex items-center gap-2 border-b border-default px-2 py-1 font-mono text-xs last:border-0"
3643
- >
3644
- <UBadge size="sm" variant="subtle" :color="port.kind === 'trigger' ? 'info' : 'success'">{{ $t(`dms_automation.templates.ports.kind.${port.kind}`) }}</UBadge>
3645
- <span class="text-muted">{{ $t(`dms_automation.templates.ports.direction.${port.direction}`) }}</span>
3646
- <span class="text-highlighted">{{ port.name }}</span>
3647
- <span v-if="port.schema?.type" class="ml-auto text-dimmed">{{ port.schema.type }}</span>
3648
- </div>
3649
- </div>
3650
- </div>
3651
- <DmsBanner
3652
- v-if="saveAsTemplateError"
3653
- size="sm"
3654
- tone="error"
3655
- :title="$t('dms_automation.editor.saveTemplateModal.error')"
3656
- :description="saveAsTemplateError"
3657
- />
3658
- <DmsFormRequiredLegend />
3659
- </div>
3660
- </template>
3661
- <template #footer>
3662
- <div class="flex w-full justify-end gap-2">
3663
- <UButton
3664
- :label="$t('dms_automation.editor.saveTemplateModal.cancel')"
3665
- variant="outline"
3666
- color="neutral"
3667
- :disabled="saveAsTemplateSubmitting"
3668
- @click="saveAsTemplateOpen = false"
3669
- />
3670
- <UButton
3671
- :label="$t('dms_automation.editor.saveTemplateModal.submit')"
3672
- color="primary"
3673
- :loading="saveAsTemplateSubmitting"
3674
- @click="submitSaveAsTemplate"
3675
- />
3676
- </div>
3677
- </template>
3678
- </UModal>
356
+ v-model:name="saveAsTemplateName"
357
+ v-model:description="saveAsTemplateDescription"
358
+ v-model:icon="saveAsTemplateIcon"
359
+ :group="selectedLocalGroupNode"
360
+ :submitting="saveAsTemplateSubmitting"
361
+ :error="saveAsTemplateError"
362
+ :field-errors="templateFieldErrors"
363
+ @submit="submitSaveAsTemplate"
364
+ />
3679
365
 
3680
- <UModal
3681
- v-model:open="forkOpen"
3682
- :title="$t('dms_automation.editor.forkModal.title')"
3683
- >
3684
- <template #body>
3685
- <div class="flex flex-col gap-3">
3686
- <p class="text-sm text-toned">
3687
- {{ $t('dms_automation.editor.forkModal.body') }}
3688
- </p>
3689
- <DmsBanner
3690
- v-if="forkError"
3691
- size="sm"
3692
- tone="error"
3693
- :title="$t('dms_automation.editor.forkModal.error')"
3694
- :description="forkError"
3695
- />
3696
- </div>
3697
- </template>
3698
- <template #footer>
3699
- <div class="flex w-full justify-end gap-2">
3700
- <UButton
3701
- :label="$t('dms_automation.editor.forkModal.cancel')"
3702
- variant="outline"
3703
- color="neutral"
3704
- :disabled="forkSubmitting"
3705
- @click="forkOpen = false"
3706
- />
3707
- <UButton
3708
- :label="$t('dms_automation.editor.forkModal.submit')"
3709
- color="primary"
3710
- icon="i-ph-git-fork"
3711
- :loading="forkSubmitting"
3712
- @click="submitFork"
3713
- />
3714
- </div>
3715
- </template>
3716
- </UModal>
366
+ <EditorForkModal v-model:open="forkOpen" :submitting="forkSubmitting" :error="forkError" @submit="submitFork" />
3717
367
  </div>
3718
368
  </template>