@andorra-labs/code 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/THIRD_PARTY_NOTICES.md +2 -1
  2. package/dist/src/account-presentation.d.ts +11 -0
  3. package/dist/src/account-presentation.js +29 -2
  4. package/dist/src/agent-execution.js +57 -4
  5. package/dist/src/agent-mcp.d.ts +12 -0
  6. package/dist/src/agent-mcp.js +81 -2
  7. package/dist/src/app-server/protocol.d.ts +120 -1
  8. package/dist/src/app-server/protocol.js +8 -1
  9. package/dist/src/app-server/reasoning.d.ts +0 -8
  10. package/dist/src/app-server/reasoning.js +15 -28
  11. package/dist/src/app-server.d.ts +32 -0
  12. package/dist/src/app-server.js +214 -21
  13. package/dist/src/auth/AuthManager.d.ts +15 -0
  14. package/dist/src/auth/AuthManager.js +66 -7
  15. package/dist/src/auth/index.d.ts +1 -1
  16. package/dist/src/auth/index.js +1 -1
  17. package/dist/src/auth/store.d.ts +17 -1
  18. package/dist/src/auth/store.js +25 -2
  19. package/dist/src/browser-runner.js +1 -2
  20. package/dist/src/browser-server.js +10 -2
  21. package/dist/src/browser-session.js +6 -2
  22. package/dist/src/browser-stealth.d.ts +29 -0
  23. package/dist/src/browser-stealth.js +166 -0
  24. package/dist/src/browser-ui/app.js +123 -28
  25. package/dist/src/browser-ui/icons/chevron-right.svg +8 -0
  26. package/dist/src/browser-ui/index.html +8 -8
  27. package/dist/src/browser-ui/style.css +199 -171
  28. package/dist/src/browser-ui/tokens.css +198 -0
  29. package/dist/src/browser-view.d.ts +57 -9
  30. package/dist/src/browser-view.js +187 -36
  31. package/dist/src/cli.js +31 -9
  32. package/dist/src/coding-tools.js +9 -5
  33. package/dist/src/command-screens.js +4 -4
  34. package/dist/src/commands.d.ts +1 -1
  35. package/dist/src/commands.js +3 -2
  36. package/dist/src/completion-gates.d.ts +35 -0
  37. package/dist/src/completion-gates.js +25 -0
  38. package/dist/src/completion.d.ts +7 -1
  39. package/dist/src/completion.js +37 -4
  40. package/dist/src/config.d.ts +1 -1
  41. package/dist/src/config.js +2 -2
  42. package/dist/src/context-budget.d.ts +11 -0
  43. package/dist/src/context-budget.js +13 -0
  44. package/dist/src/decision/DecisionEngine.d.ts +5 -1
  45. package/dist/src/decision/DecisionManager.d.ts +1 -0
  46. package/dist/src/decision/DecisionManager.js +14 -3
  47. package/dist/src/decision/FactContinuations.d.ts +6 -0
  48. package/dist/src/decision/FactContinuations.js +9 -1
  49. package/dist/src/decision/FactServiceGate.js +1 -1
  50. package/dist/src/decision/checks.js +1 -1
  51. package/dist/src/decision/hostedSkills.d.ts +37 -0
  52. package/dist/src/decision/hostedSkills.js +64 -0
  53. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +10 -2
  54. package/dist/src/decision/providers/AndorraDecisionProvider.js +121 -10
  55. package/dist/src/default-graph.d.ts +11 -0
  56. package/dist/src/default-graph.js +20 -0
  57. package/dist/src/duration.d.ts +13 -2
  58. package/dist/src/duration.js +27 -3
  59. package/dist/src/file-diff.d.ts +105 -0
  60. package/dist/src/file-diff.js +244 -0
  61. package/dist/src/graph-manager-chat.d.ts +302 -0
  62. package/dist/src/graph-manager-chat.js +940 -0
  63. package/dist/src/graph-runner.js +6 -0
  64. package/dist/src/graph-server.d.ts +9 -0
  65. package/dist/src/graph-server.js +171 -20
  66. package/dist/src/graph-studio-features.js +2 -2
  67. package/dist/src/graph-sync.js +5 -2
  68. package/dist/src/graph-ui/app.js +369 -183
  69. package/dist/src/graph-ui/controls.css +55 -32
  70. package/dist/src/graph-ui/controls.js +85 -9
  71. package/dist/src/graph-ui/edge-router.js +114 -13
  72. package/dist/src/graph-ui/embed.js +32 -17
  73. package/dist/src/graph-ui/icons.js +1 -0
  74. package/dist/src/graph-ui/index.html +4 -4
  75. package/dist/src/graph-ui/library.css +4 -10
  76. package/dist/src/graph-ui/manager-markdown.js +155 -0
  77. package/dist/src/graph-ui/manager-state.js +191 -0
  78. package/dist/src/graph-ui/manager.css +161 -0
  79. package/dist/src/graph-ui/manager.js +700 -0
  80. package/dist/src/graph-ui/skill-picker.js +6 -6
  81. package/dist/src/graph-ui/studio-canvas.js +17 -15
  82. package/dist/src/graph-ui/studio.css +24 -23
  83. package/dist/src/graph-ui/studio.js +69 -48
  84. package/dist/src/graph-ui/style.css +128 -93
  85. package/dist/src/graph-ui/theme.js +2 -2
  86. package/dist/src/graph-ui/tokens.css +217 -151
  87. package/dist/src/graphs.d.ts +76 -2
  88. package/dist/src/graphs.js +172 -9
  89. package/dist/src/hardened-runtime.js +8 -2
  90. package/dist/src/mcp.d.ts +75 -0
  91. package/dist/src/mcp.js +240 -8
  92. package/dist/src/membership-errors.d.ts +14 -0
  93. package/dist/src/membership-errors.js +24 -1
  94. package/dist/src/membership.d.ts +20 -0
  95. package/dist/src/membership.js +45 -16
  96. package/dist/src/palette.d.ts +25 -8
  97. package/dist/src/palette.js +26 -8
  98. package/dist/src/provider-engine.d.ts +4 -4
  99. package/dist/src/provider-engine.js +39 -22
  100. package/dist/src/provider-keys.d.ts +5 -1
  101. package/dist/src/provider-keys.js +7 -3
  102. package/dist/src/provider-settings.d.ts +4 -1
  103. package/dist/src/provider-settings.js +46 -5
  104. package/dist/src/providers.d.ts +24 -0
  105. package/dist/src/providers.js +47 -2
  106. package/dist/src/qa/guidance.d.ts +26 -0
  107. package/dist/src/qa/guidance.js +46 -0
  108. package/dist/src/qa/index.d.ts +1 -8
  109. package/dist/src/qa/index.js +1 -16
  110. package/dist/src/qa/profile/QaProfile.d.ts +5 -1
  111. package/dist/src/qa/profile/QaProfile.js +6 -2
  112. package/dist/src/qa/runtime/ProcessManager.d.ts +20 -2
  113. package/dist/src/qa/runtime/ProcessManager.js +69 -13
  114. package/dist/src/qa/tools.d.ts +19 -1
  115. package/dist/src/qa/tools.js +20 -145
  116. package/dist/src/react-runtime.d.ts +11 -0
  117. package/dist/src/react-runtime.js +203 -53
  118. package/dist/src/remote/engine-pool.js +21 -6
  119. package/dist/src/run-progress.d.ts +6 -0
  120. package/dist/src/run-progress.js +7 -0
  121. package/dist/src/runtime.d.ts +8 -0
  122. package/dist/src/screen-selection.d.ts +38 -0
  123. package/dist/src/screen-selection.js +103 -0
  124. package/dist/src/session-changes.d.ts +117 -0
  125. package/dist/src/session-changes.js +796 -0
  126. package/dist/src/session-skills.d.ts +75 -0
  127. package/dist/src/session-skills.js +151 -0
  128. package/dist/src/side-panel.d.ts +1 -1
  129. package/dist/src/side-panel.js +6 -12
  130. package/dist/src/skill-commands.js +1 -1
  131. package/dist/src/skills/bundled/control-browser/SKILL.md +9 -1
  132. package/dist/src/skills/bundled/graph-manager/SKILL.md +8 -0
  133. package/dist/src/skills/bundled/provenance.json +3 -3
  134. package/dist/src/skills/bundled/web-gui-tester/SKILL.md +1 -1
  135. package/dist/src/stall-recovery.d.ts +33 -0
  136. package/dist/src/stall-recovery.js +83 -0
  137. package/dist/src/subagent-run.js +1 -2
  138. package/dist/src/telemetry/schema.d.ts +1 -1
  139. package/dist/src/telemetry/schema.js +1 -2
  140. package/dist/src/terminal-ui.d.ts +66 -22
  141. package/dist/src/terminal-ui.js +327 -92
  142. package/dist/src/tool-diff-stats.d.ts +9 -0
  143. package/dist/src/tool-diff-stats.js +20 -0
  144. package/dist/src/tool-names.d.ts +1 -1
  145. package/dist/src/tool-result-filter.js +1 -1
  146. package/dist/src/tools.js +26 -2
  147. package/dist/src/transcript.d.ts +11 -0
  148. package/dist/src/transcript.js +23 -3
  149. package/dist/src/types.d.ts +24 -4
  150. package/dist/src/usage-analytics.d.ts +7 -0
  151. package/dist/src/usage-analytics.js +55 -15
  152. package/docs/concepts/README.md +1 -1
  153. package/docs/concepts/limits.md +9 -0
  154. package/docs/guides/desktop-app.md +1 -1
  155. package/docs/guides/graph-builder.md +16 -1
  156. package/docs/guides/tui.md +9 -9
  157. package/docs/reference/slash-commands.md +2 -1
  158. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +203 -0
  159. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +79 -0
  160. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +182 -0
  161. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +156 -0
  162. package/package.json +1 -1
  163. package/tests/chat-side-panel-test-plan.md +1 -1
  164. package/dist/src/qa/api/http-runner.d.ts +0 -3
  165. package/dist/src/qa/api/http-runner.js +0 -47
  166. package/dist/src/qa/git/ChangeDetector.d.ts +0 -26
  167. package/dist/src/qa/git/ChangeDetector.js +0 -177
  168. package/dist/src/qa/git/DiffReviewer.d.ts +0 -28
  169. package/dist/src/qa/git/DiffReviewer.js +0 -115
  170. package/dist/src/qa/orchestrator/ChangeClassifier.d.ts +0 -14
  171. package/dist/src/qa/orchestrator/ChangeClassifier.js +0 -28
  172. package/dist/src/qa/orchestrator/MergeGate.d.ts +0 -14
  173. package/dist/src/qa/orchestrator/MergeGate.js +0 -40
  174. package/dist/src/qa/orchestrator/QaOrchestrator.d.ts +0 -79
  175. package/dist/src/qa/orchestrator/QaOrchestrator.js +0 -373
  176. package/dist/src/qa/runners/CommandRunner.d.ts +0 -22
  177. package/dist/src/qa/runners/CommandRunner.js +0 -96
  178. package/dist/src/qa/runners/TestRunner.d.ts +0 -21
  179. package/dist/src/qa/runners/TestRunner.js +0 -66
  180. package/dist/src/qa/runtime/RuntimeSmoke.d.ts +0 -11
  181. package/dist/src/qa/runtime/RuntimeSmoke.js +0 -78
  182. package/dist/src/qa/runtime-detect.d.ts +0 -10
  183. package/dist/src/qa/runtime-detect.js +0 -72
  184. package/dist/src/qa/security/DependencyScanner.d.ts +0 -19
  185. package/dist/src/qa/security/DependencyScanner.js +0 -167
  186. package/dist/src/qa/security/SecretScanner.d.ts +0 -3
  187. package/dist/src/qa/security/SecretScanner.js +0 -55
@@ -13,16 +13,21 @@ const themeColor = (token, fallback) => {
13
13
  } catch { /* A partial DOM falls through to the literal below. */ }
14
14
  return fallback;
15
15
  };
16
- // The connection colours, read once per paint. An outcome is a status, and status is the only
17
- // colour the chrome carries; the halo is the canvas ground, so a crossing stays legible.
16
+ // The connection colours, read once per paint. Every connection is the same neutral line, whatever
17
+ // its outcome: an outcome is not a failure, and colouring "blocked" or "pass" made a resting graph
18
+ // read as a status board. The one red on the canvas is a run route into a node that failed
19
+ // (studio.css). The outcome's pill is outlined in the hairline with muted ink; the halo is the
20
+ // canvas ground, so a crossing stays legible. Each fallback is the dark token's own value.
18
21
  const connectionPalette = () => ({
19
- fail: themeColor('--err', '#d64545'),
20
- pass: themeColor('--ok', '#2f9e6a'),
21
- blocked: themeColor('--warn', '#d99a2b'),
22
- plain: themeColor('--text-3', '#85858f'),
22
+ line: themeColor('--text-3', '#9a9aa4'),
23
+ active: themeColor('--accent', '#dedee3'),
23
24
  halo: themeColor('--canvas-bg', '#1b1b1e'),
24
25
  pill: themeColor('--bg-input', '#202024'),
26
+ pillEdge: themeColor('--border', '#2a2a30'),
27
+ pillInk: themeColor('--text-2', '#b4b4bc'),
25
28
  });
29
+ /** The connection's stroke at rest and while it is traced (hovered, focused or selected). */
30
+ const EDGE_WIDTH = '1.5', EDGE_ACTIVE_WIDTH = '2';
26
31
  const fragmentToken = new URLSearchParams(location.hash.slice(1)).get('token');
27
32
  const token = fragmentToken || sessionStorage.getItem('andorra-graph-token');
28
33
  if (fragmentToken) sessionStorage.setItem('andorra-graph-token', fragmentToken);
@@ -37,15 +42,26 @@ function askConfirm(options) {
37
42
  if (typeof controls?.confirm === 'function') return controls.confirm(options);
38
43
  return Promise.resolve(confirm([options.title, options.message].filter(Boolean).join('\n\n')));
39
44
  }
40
- const DISCARD_QUESTION = { title: 'Discard unsaved changes?', message: 'Edits to this graph since its last revision are lost. Recoverable drafts stay in draft history.', confirmLabel: 'Discard', tone: 'danger' };
45
+ // Menus and dialogs leave the way they came (controls.js). A page without that layer — the test
46
+ // harness — removes or closes them at once.
47
+ function leaveLayer(layer, done) {
48
+ const controls = globalThis.AndorraControls;
49
+ if (typeof controls?.leave === 'function') return controls.leave(layer, done);
50
+ done(); return () => {};
51
+ }
52
+ function closeDialog(dialog) {
53
+ const controls = globalThis.AndorraControls;
54
+ if (typeof controls?.closeDialog === 'function') controls.closeDialog(dialog); else dialog.close();
55
+ }
56
+ const DISCARD_QUESTION = { title: 'Discard unsaved changes?', message: 'Edits to this workflow since its last version are lost. Recoverable drafts stay in draft history.', confirmLabel: 'Discard', tone: 'danger' };
41
57
  function status(message, error = false) { $('status').textContent = message; $('status').parentElement.classList.toggle('error', error); }
42
58
  // The free tier keeps one custom graph of up to three nodes (Done does not count) and leaves the
43
59
  // Orchestrator to Premium. The server enforces the same rules on save; these keep the editor honest
44
60
  // about them before the user builds something it cannot save.
45
- const FREE_CREATE_TIP = 'Free tier includes 1 custom graph. Upgrade to Premium for more graphs.';
46
- const FREE_ORCHESTRATOR_TIP = 'The Orchestrator is a Premium feature. Free tier graphs can use the other agent nodes.';
61
+ const FREE_CREATE_TIP = 'Free tier includes 1 custom workflow. Upgrade to Premium for more workflows.';
62
+ const FREE_ORCHESTRATOR_TIP = 'The Orchestrator is a Premium feature. Free tier workflows can use the other agents.';
47
63
  function freeTier() { return state.plan?.paid === false; }
48
- function freeNodeTip() { return `Free tier graphs can have up to ${state.plan.nodeLimit} nodes, not counting Done. Upgrade to Premium for larger graphs.`; }
64
+ function freeNodeTip() { return `Free tier workflows can have up to ${state.plan.nodeLimit} steps, not counting Done. Upgrade to Premium for larger workflows.`; }
49
65
  function countedNodes(graph) { return Object.values(graph.nodes).filter(node => node.type !== 'end').length; }
50
66
  function canCreateGraph() { return !freeTier() || state.graphs.filter(graph => graph.id !== 'default').length < state.plan.customGraphLimit; }
51
67
  /** Whether a free account may save this graph: its kept graph, or a new one while it has none. */
@@ -120,8 +136,8 @@ function restoreImportRequirements(graph) {
120
136
  return owed.size ? owed : null;
121
137
  }
122
138
  async function openDraft(snapshot) {
123
- if (state.dirty && !await askConfirm({ title: 'Open the saved draft?', message: 'Current edits are retained in draft history.', confirmLabel: 'Open draft' })) return;
124
- try { const graph = foldGraphSubagentCaps(await api(`/api/drafts/${snapshot}`)); const owed = restoreImportRequirements(graph); state.graph = graph; state.dirty = true; clearSelection(); state.undo = []; state.redo = []; state.pendingProviderNodes = owed; render(); fit(); status(owed ? 'Recovered imported draft. Assign a model profile to every outlined node, then save.' : 'Recovered draft. Save a revision when valid, or duplicate if its base revision changed.'); }
139
+ if (state.dirty && !await askConfirm({ title: 'Open the saved draft?', message: 'Current edits are retained in draft history.', confirmLabel: 'Open Draft' })) return;
140
+ try { const graph = foldGraphSubagentCaps(await api(`/api/drafts/${snapshot}`)); const owed = restoreImportRequirements(graph); state.graph = graph; state.dirty = true; clearSelection(); state.undo = []; state.redo = []; state.pendingProviderNodes = owed; render(); fit(); status(owed ? 'Recovered imported draft. Assign a model profile to every outlined step, then save.' : 'Recovered draft. Save when valid, or duplicate if its base version changed.'); graphOpened('open'); }
125
141
  catch (error) { status(error.message, true); }
126
142
  }
127
143
  function mutate(action, inspector = false) { if (!state.graph) return; checkpoint(); action(); changed(); if (inspector) renderInspector(); }
@@ -252,36 +268,36 @@ function selectNode(node, event = {}) {
252
268
  } else state.selectedIds = [node.id];
253
269
  state.selected = state.selectedIds.at(-1) || null; state.selectedEdge = null; state.bulkOutcome = null;
254
270
  renderCanvas(); renderInspector(); showInspector();
255
- if (mixed) status('Selection restarted. Use Ctrl/Cmd-click to select nodes of the same type.');
271
+ if (mixed) status('Selection restarted. Use Ctrl/Cmd-click to select steps of the same type.');
256
272
  }
257
273
  function routeSelectionTo(targetId) {
258
274
  const pick = state.routePick, target = state.graph?.nodes[targetId];
259
275
  if (!pick || !target) return;
260
276
  if (pick.sources.includes(targetId) || target.agentRole === 'orchestrator') { status('Choose a destination outside the selection. The Orchestrator cannot have incoming connections.', true); return; }
261
277
  const sources = pick.sources.map(id => state.graph.nodes[id]);
262
- if (sources.some(node => !node || !outcomes(node).includes(pick.outcome)) || sources.some(node => selectionType(node) !== selectionType(sources[0]))) { state.routePick=null; renderInspector(); status('The selection changed. Select matching nodes and choose an outcome again.',true); return; }
278
+ if (sources.some(node => !node || !outcomes(node).includes(pick.outcome)) || sources.some(node => selectionType(node) !== selectionType(sources[0]))) { state.routePick=null; renderInspector(); status('The selection changed. Select matching steps and choose an outcome again.',true); return; }
263
279
  mutate(() => {
264
280
  const existing = state.graph.edges;
265
281
  const replacements = sources.map(node => existing.find(edge => edge.source === node.id && edgeOutcome(edge) === pick.outcome && edge.target === targetId) || {id:`edge-${crypto.randomUUID().slice(0,8)}`,source:node.id,target:targetId,outcome:pick.outcome});
266
282
  state.graph.edges = [...existing.filter(edge => !pick.sources.includes(edge.source) || edgeOutcome(edge) !== pick.outcome),...replacements];
267
283
  state.routePick = null;
268
284
  },true);
269
- status(`Routed ${sources.length} nodes to ${target.name}. Existing matching handoffs were kept; configure and validate new input mappings below.`);
285
+ status(`Routed ${sources.length} steps to ${target.name}. Existing matching connections were kept; set the inputs of new ones below.`);
270
286
  }
271
287
  function renderBulkInspector(parent, nodes) {
272
- $('inspector-title').textContent = `${nodes.length} nodes selected`;
288
+ $('inspector-title').textContent = `${nodes.length} steps selected`;
273
289
  parent.append(el('p',nodes.map(node=>node.name).join(', '),'help'));
274
- const group = section(parent,'Output Node');
290
+ const group = section(parent,'Output step');
275
291
  const shared = outcomes(nodes[0]).filter(outcome => nodes.every(node => outcomes(node).includes(outcome)));
276
- if (!shared.length) {group.append(el('p','These nodes have no shared outcome. Give them a matching completion outcome before routing together.','help'));return;}
292
+ if (!shared.length) {group.append(el('p','These steps have no shared outcome. Give them a matching completion outcome before routing together.','help'));return;}
277
293
  if (!shared.includes(state.bulkOutcome)) state.bulkOutcome=shared[0];
278
294
  const selector=choice(group,'Shared outcome',state.bulkOutcome,shared,()=>{});selector.onchange=()=>{state.bulkOutcome=selector.value;state.routePick=null;renderCanvas();renderInspector();};
279
- group.append(el('p','This replaces only the chosen outcome routes. Other outcomes stay connected. Existing handoffs to the chosen destination are retained; new destinations start without mappings.','help'));
280
- const route=el('button',state.routePick?'Click a destination on the canvas':`Route all ${nodes.length} to...`,'primary');
281
- route.onclick=()=>{state.routePick={sources:nodes.map(node=>node.id),outcome:state.bulkOutcome};renderCanvas();renderInspector();status('Click the destination node. Press Escape to cancel.');};group.append(route);
282
- if(state.routePick){const cancel=el('button','Cancel destination selection');cancel.onclick=cancelRoutePick;group.append(cancel);}
283
- const connections=section(group,'Handoff mappings');
284
- for(const node of nodes) for(const edge of state.graph.edges.filter(edge=>edge.source===node.id&&edgeOutcome(edge)===state.bulkOutcome)) {const edit=el('button',`${node.name} -> ${state.graph.nodes[edge.target]?.name} (${Object.keys(edge.inputMapping||{}).length} mappings)`,'graph-row');edit.onclick=()=>{clearSelection();state.selectedEdge=edge;renderCanvas();renderInspector();};connections.append(edit);}
295
+ group.append(el('p','This replaces only the chosen outcome routes. Other outcomes stay connected. Existing connections to the chosen destination are kept; new destinations start without inputs.','help'));
296
+ const route=el('button',state.routePick?'Click a destination on the canvas':`Route all ${nodes.length} to…`,'primary');
297
+ route.onclick=()=>{state.routePick={sources:nodes.map(node=>node.id),outcome:state.bulkOutcome};renderCanvas();renderInspector();status('Click the destination step. Press Escape to cancel.');};group.append(route);
298
+ if(state.routePick){const cancel=el('button','Cancel Selection');cancel.onclick=cancelRoutePick;group.append(cancel);}
299
+ const connections=section(group,'Connection inputs');
300
+ for(const node of nodes) for(const edge of state.graph.edges.filter(edge=>edge.source===node.id&&edgeOutcome(edge)===state.bulkOutcome)) {const edit=el('button',`${node.name} → ${state.graph.nodes[edge.target]?.name} (${Object.keys(edge.inputMapping||{}).length} mappings)`,'graph-row');edit.onclick=()=>{clearSelection();state.selectedEdge=edge;renderCanvas();renderInspector();};connections.append(edit);}
285
301
  }
286
302
  function cancelRoutePick() { state.routePick=null;renderCanvas();renderInspector();status('Destination selection cancelled. No connections changed.'); }
287
303
  /** One validation problem: the message shown to the reader, and the node it blames. Errors that
@@ -289,15 +305,15 @@ function cancelRoutePick() { state.routePick=null;renderCanvas();renderInspector
289
305
  function issues() {
290
306
  const graph = state.graph; if (!graph) return [];
291
307
  const result = [], nodes = Object.values(graph.nodes);
292
- if (nodes.length < 2 || nodes.length > nodeLimit(graph)) result.push({ message: `Use between 2 and ${nodeLimit(graph)} nodes; remove extra nodes before saving.` });
308
+ if (nodes.length < 2 || nodes.length > nodeLimit(graph)) result.push({ message: `Use between 2 and ${nodeLimit(graph)} steps; remove extra steps before saving.` });
293
309
  if (freeTier()) {
294
- if (!freeGraphEditable(graph)) result.push({ message: graph.revision ? 'On the free tier only your first custom graph can be changed. Upgrade to Premium to edit this graph.' : FREE_CREATE_TIP });
310
+ if (!freeGraphEditable(graph)) result.push({ message: graph.revision ? 'On the free tier only your first custom workflow can be changed. Upgrade to Premium to edit this workflow.' : FREE_CREATE_TIP });
295
311
  if (nodes.some(node => node.agentRole === 'orchestrator')) result.push({ message: FREE_ORCHESTRATOR_TIP });
296
312
  if (countedNodes(graph) > state.plan.nodeLimit) result.push({ message: freeNodeTip() });
297
313
  }
298
- if (new TextEncoder().encode(JSON.stringify(graph)).byteLength > 512 * 1024) result.push({ message: 'Graph exceeds 512 KiB; shorten instructions or remove nodes before saving.' });
299
- if (!graph.name.trim()) result.push({ message: 'Give this graph a name.' });
300
- if (graph.name.length > 200) result.push({ message: 'Keep the graph name to 200 characters or fewer.' });
314
+ if (new TextEncoder().encode(JSON.stringify(graph)).byteLength > 512 * 1024) result.push({ message: 'Workflow exceeds 512 KiB; shorten instructions or remove steps before saving.' });
315
+ if (!graph.name.trim()) result.push({ message: 'Give this workflow a name.' });
316
+ if (graph.name.length > 200) result.push({ message: 'Keep the workflow name to 200 characters or fewer.' });
301
317
  if (graph.metadata?.description?.length > 2000) result.push({ message: 'Keep the description to 2000 characters or fewer.' });
302
318
  if (Array.isArray(graph.widgets) && graph.widgets.length > 5) result.push({ message: 'Use at most 5 widgets.' });
303
319
  const widgetIds = new Set();
@@ -308,18 +324,18 @@ function issues() {
308
324
  if (widgetIds.has(widget.id)) result.push({ message: `${label}: duplicate widget id; remove and re-add this widget.` });
309
325
  widgetIds.add(widget.id);
310
326
  }
311
- if (!graph.nodes[graph.entry]) result.push({ message: 'Choose an existing entry node.' });
327
+ if (!graph.nodes[graph.entry]) result.push({ message: 'Choose an existing entry step.' });
312
328
  for (const node of nodes) {
313
329
  const blame = message => result.push({ message, nodeId: node.id });
314
- if (node.jevEnabled !== undefined && (node.type !== 'agent' || typeof node.jevEnabled !== 'boolean')) blame(`${node.name}: Jev decisions must be a boolean on an Agent node.`);
330
+ if (node.jevEnabled !== undefined && (node.type !== 'agent' || typeof node.jevEnabled !== 'boolean')) blame(`${node.name}: Jev decisions must be a boolean on an Agent step.`);
315
331
  for (const outcome of outcomes(node)) if (typeof outcome !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_ -]{0,79}$/.test(outcome) || outcome.endsWith(' ') || outcome.includes(' ') || ['constructor', 'prototype', '__proto__'].includes(outcome)) blame(`${node.name}: Use outcome names of 1-80 characters starting with a letter or number and containing only letters, numbers, single spaces, underscores or hyphens. Avoid reserved names constructor, prototype and __proto__.`);
316
332
  if (!node.name.trim()) blame(`${node.id}: Add a name.`);
317
- if (node.name.length > 200) blame(`${node.id}: Keep the node name to 200 characters or fewer.`);
333
+ if (node.name.length > 200) blame(`${node.id}: Keep the step name to 200 characters or fewer.`);
318
334
  if (node.position !== undefined && (!Number.isFinite(node.position?.x) || !Number.isFinite(node.position?.y) || Math.abs(node.position.x) > 100000 || Math.abs(node.position.y) > 100000)) blame(`${node.name}: Set finite X and Y coordinates between -100000 and 100000.`);
319
335
  if (node.type === 'agent') {
320
336
  // An imported graph must not drift onto the machine default provider unnoticed: nodes
321
337
  // that arrived without a usable provider stay pinned to this list until one is chosen.
322
- if (state.pendingProviderNodes?.has(node.id) && !node.provider) blame(`${node.name}: choose a model profile for this imported node before saving.`);
338
+ if (state.pendingProviderNodes?.has(node.id) && !node.provider) blame(`${node.name}: choose a model profile for this imported step before saving.`);
323
339
  // Missing provider profiles remain editable; the inspector labels them unavailable.
324
340
  // Run-time preflight, not graph storage, enforces local provider availability.
325
341
  for (const key of ['instruction', 'systemPrompt']) if (node[key] !== undefined && (typeof node[key] !== 'string' || node[key].length > 100000)) blame(`${node.name}: Keep ${key} to 100000 characters or fewer.`);
@@ -341,8 +357,8 @@ function scheduleValidation() {
341
357
  }, 350);
342
358
  }
343
359
  function renderHeading() {
344
- $('graph-title').textContent = state.graph?.name || 'Graph studio';
345
- $('revision').textContent = state.graph ? `${state.graph.revision ? `Revision ${state.graph.revision}` : 'New graph'}${state.dirty ? ' · Unsaved' : ''}` : '';
360
+ $('graph-title').textContent = state.graph?.name || 'Workflow Editor';
361
+ $('revision').textContent = state.graph ? `${state.graph.revision ? `Version ${state.graph.revision}` : 'New workflow'}${state.dirty ? ' · Unsaved' : ''}` : '';
346
362
  $('save').disabled = state.saving || !state.graph || !state.dirty || state.graph.id === 'default';
347
363
  $('save').title = state.graph?.id === 'default' ? 'Duplicate the preset to save your customization' : '';
348
364
  $('undo').disabled = !state.undo.length; $('redo').disabled = !state.redo.length;
@@ -350,10 +366,14 @@ function renderHeading() {
350
366
  $('duplicate').disabled = state.saving || !state.graph || !canCreateGraph();
351
367
  renderLibrary();
352
368
  window.AndorraStudio?.heading?.();
369
+ globalThis.AndorraManager?.heading?.();
353
370
  }
371
+ // How the open graph arrived ('new', 'duplicate', 'import' or 'open'). Graph Manager's first-run tip
372
+ // belongs to New graph alone, and the reason is kept for a panel script that loads after the graph.
373
+ function graphOpened(reason) { state.openReason = reason; globalThis.AndorraManager?.graphOpened(reason); }
354
374
  function renderList() {
355
375
  $('new-graph').disabled = state.saving || !canCreateGraph();
356
- $('new-graph').title = canCreateGraph() ? 'Create graph' : FREE_CREATE_TIP;
376
+ $('new-graph').title = canCreateGraph() ? 'Create workflow' : FREE_CREATE_TIP;
357
377
  $('duplicate').disabled = state.saving || !state.graph || !canCreateGraph();
358
378
  $('duplicate').title = canCreateGraph() ? '' : FREE_CREATE_TIP;
359
379
  $('graphs').replaceChildren();
@@ -387,14 +407,19 @@ function renderList() {
387
407
  button.append(el('span', draft.name), when);
388
408
  button.onclick = () => openDraft(draft.snapshot);
389
409
  button.oncontextmenu = event => { event.preventDefault(); showMenuAt(event.clientX, event.clientY, `Actions for the draft of ${draft.name}`, [
390
- { label: 'Open draft', icon: 'history', run: () => openDraft(draft.snapshot) },
391
- { label: 'Clear draft', icon: 'trash', danger: true, run: () => clearDrafts([draft]) },
410
+ { label: 'Open Draft', icon: 'history', run: () => openDraft(draft.snapshot) },
411
+ { label: 'Clear Draft', icon: 'trash', danger: true, run: () => clearDrafts([draft]) },
392
412
  ]); };
393
413
  $('graphs').append(button);
394
414
  }
395
415
  if (state.showDraftHistory || matching.length > current.length) {
396
- const history = el('button', state.showDraftHistory ? 'Show latest drafts' : `Show draft history (${matching.length})`, 'graph-drafts-toggle');
416
+ // A disclosure, as the desktop's Disclosure is: the chevron turns, the words stay (D13).
417
+ const history = el('button', undefined, 'graph-drafts-toggle');
397
418
  history.type = 'button';
419
+ history.setAttribute('aria-expanded', String(Boolean(state.showDraftHistory)));
420
+ const chevron = globalThis.AndorraIcons?.icon?.('chevron-right', 12);
421
+ if (chevron) history.append(chevron);
422
+ history.append(el('span', state.showDraftHistory ? 'Draft history' : `Draft history (${matching.length})`));
398
423
  history.onclick = () => { state.showDraftHistory = !state.showDraftHistory; renderList(); }; $('graphs').append(history);
399
424
  }
400
425
  }
@@ -404,7 +429,7 @@ async function clearDrafts(drafts, all = false) {
404
429
  const graphIds = [...new Set(drafts.map(draft => draft.graphId))];
405
430
  if (!graphIds.length) return;
406
431
  const one = graphIds.length === 1 && !all;
407
- if (!await askConfirm({ title: one ? `Clear the draft of "${drafts[0].name}"?` : $('search').value ? 'Clear the matching drafts?' : 'Clear all drafts?', message: 'Cleared drafts leave this list, with their history. Saved graphs and their revisions are not affected.', confirmLabel: 'Clear', tone: 'danger' })) return;
432
+ if (!await askConfirm({ title: one ? `Clear the draft of "${drafts[0].name}"?` : $('search').value ? 'Clear the matching drafts?' : 'Clear all drafts?', message: 'Cleared drafts leave this list, with their history. Saved workflows and their versions are not affected.', confirmLabel: 'Clear', tone: 'danger' })) return;
408
433
  try { state.drafts = await api('/api/drafts/clear', { graphIds }); if (!state.drafts.length) state.showDraftHistory = false; renderList(); status(one ? 'Draft cleared' : 'Drafts cleared'); }
409
434
  catch (error) { status('Drafts not cleared: ' + error.message, true); }
410
435
  }
@@ -439,7 +464,9 @@ function showMenuAt(x, y, ariaLabel, items) {
439
464
  const close = (restoreFocus = false) => {
440
465
  closeGraphMenuHandlers = undefined;
441
466
  window.removeEventListener?.('pointerdown', outside, true);
442
- menu.remove();
467
+ // The menu leaves the way it came (controls.js); a menu opened at once is a new element.
468
+ menu.removeAttribute?.('id'); menu.setAttribute('aria-hidden', 'true');
469
+ leaveLayer(menu, () => menu.remove());
443
470
  if (restoreFocus) invoker?.focus?.();
444
471
  };
445
472
  const outside = event => { if (!menu.contains(event.target)) close(); };
@@ -469,9 +496,9 @@ function showGraphMenu(graph, x, y) {
469
496
  showMenuAt(x, y, `${graph.name} actions`, items);
470
497
  }
471
498
  function showNewGraphMenu(x, y) {
472
- showMenuAt(x, y, 'Create a graph', [
473
- { label: 'New graph', icon: 'plus', run: () => newGraph() },
474
- { label: 'Import graph', icon: 'upload', run: () => { if (window.AndorraStudio?.openImport) window.AndorraStudio.openImport(); else status('The import dialog is still loading. Try again in a moment.', true); } },
499
+ showMenuAt(x, y, 'Create a workflow', [
500
+ { label: 'New Workflow', icon: 'plus', run: () => newGraph() },
501
+ { label: 'Import Workflow', icon: 'upload', run: () => { if (window.AndorraStudio?.openImport) window.AndorraStudio.openImport(); else status('The import dialog is still loading. Try again in a moment.', true); } },
475
502
  ]);
476
503
  }
477
504
  // The saved revision a row names is what a friend receives: the open draft's unsaved edits are
@@ -479,7 +506,7 @@ function showNewGraphMenu(x, y) {
479
506
  // the file itself; a plain browser downloads the fetched revision directly.
480
507
  async function exportGraph(graph) {
481
508
  if (window.AndorraEmbed?.hostChrome?.() && window.AndorraEmbed.exportGraph) { window.AndorraEmbed.exportGraph(graph.id); return; }
482
- if (state.saving) { status('Wait for the current save before exporting a graph.'); return; }
509
+ if (state.saving) { status('Wait for the current save before exporting a workflow.'); return; }
483
510
  downloadGraph(dropLegacyTokenFields(await api(`/api/graphs/${encodeURIComponent(graph.id)}`)));
484
511
  }
485
512
  function exportFileName(graph) {
@@ -493,14 +520,14 @@ function downloadJson(value, stem) {
493
520
  setTimeout(() => URL.revokeObjectURL(url), 1000);
494
521
  }
495
522
  async function duplicateGraph(source) {
496
- if (state.saving) { status('Wait for the current save before duplicating a graph.'); return; }
523
+ if (state.saving) { status('Wait for the current save before duplicating a workflow.'); return; }
497
524
  state.saving = true; renderHeading(); renderList();
498
525
  let created;
499
526
  try {
500
527
  const saved = dropLegacyTokenFields(await api(`/api/graphs/${encodeURIComponent(source.id)}`));
501
528
  // validateGraph caps names at 200 characters, so a near-limit source name must make room
502
529
  // for the suffix or the save would be rejected with no way to rename the invisible copy.
503
- const suffix = ' (Copy)', base = saved.name || 'Untitled graph';
530
+ const suffix = ' (Copy)', base = saved.name || 'Untitled workflow';
504
531
  const name = base.length + suffix.length > 200 ? base.slice(0, 200 - suffix.length).trimEnd() + suffix : base + suffix;
505
532
  const duplicate = { ...saved, id: newId(), name, revision: 0 };
506
533
  const stored = await api('/api/graphs', duplicate);
@@ -513,14 +540,14 @@ async function duplicateGraph(source) {
513
540
  state.saving = false; renderHeading(); renderList();
514
541
  if (!created) return;
515
542
  if (state.dirty) { status(`Created "${created.name}". Open it from the list to rename it.`); return; }
516
- await openGraph(created.id);
517
- if (state.graph?.id === created.id) status(`Duplicated "${source.name}" - Rename it in Graph settings.`);
543
+ await openGraph(created.id, { reason: 'duplicate' });
544
+ if (state.graph?.id === created.id) status(`Duplicated "${source.name}". Rename it in Workflow settings.`);
518
545
  }
519
546
  // Deleting removes the graph, its revisions and its draft history from this machine, and for a
520
547
  // signed-in account the cloud copies stop restoring it. The confirm names that loss: there is no undo.
521
548
  async function deleteGraph(graph) {
522
- if (state.saving) { status('Wait for the current save before deleting a graph.'); return; }
523
- if (!confirm(`Delete "${graph.name}"? Its revisions and drafts are removed from this machine.`)) return;
549
+ if (state.saving) { status('Wait for the current save before deleting a workflow.'); return; }
550
+ if (!confirm(`Delete "${graph.name}"? Its versions and drafts are removed from this machine.`)) return;
524
551
  state.saving = true; renderHeading(); renderList();
525
552
  // The confirm accepted the loss of unsaved edits of the deleted graph, so no draft of it may
526
553
  // outlive it: stop its queued write, and let an in-flight one land before the deletion's
@@ -557,7 +584,25 @@ async function deleteGraph(graph) {
557
584
  if (state.graph?.id !== graph.id) status(`Deleted "${graph.name}".`);
558
585
  }
559
586
  function position(node, index) { return node.position || { x: index * 290, y: 0 }; }
560
- function transform() { $('scene').style.transform = `translate(${state.x}px,${state.y}px) scale(${state.zoom})`; $('zoom').textContent = `${Math.round(state.zoom * 100)}%`; window.AndorraStudio?.viewport?.(); }
587
+ // The snap lattice, in canvas units: a dragged card lands on it when Snap to grid is on, and the
588
+ // canvas draws one dot on each of its points.
589
+ const GRID_STEP = 20;
590
+ // Below this many screen pixels between dots the grid doubles its step, so at a low zoom it stays a
591
+ // grid rather than a haze; every dot drawn is still a snap point.
592
+ const GRID_MIN_PX = 10;
593
+ function transform() {
594
+ $('scene').style.transform = `translate(${state.x}px,${state.y}px) scale(${state.zoom})`;
595
+ // The dot grid lives in canvas space, so it moves and scales with the cards. A dot is drawn at the
596
+ // centre of its tile, so the tile starts half a step before the lattice point it marks.
597
+ let step = GRID_STEP * state.zoom;
598
+ while (step < GRID_MIN_PX) step *= 2;
599
+ const canvas = $('canvas');
600
+ if (canvas?.style) { canvas.style.backgroundSize = `${step}px ${step}px`; canvas.style.backgroundPosition = `${state.x - step / 2}px ${state.y - step / 2}px`; }
601
+ $('zoom').textContent = `${Math.round(state.zoom * 100)}%`; window.AndorraStudio?.viewport?.();
602
+ }
603
+ // Pan and pinch arrive many times a frame; the view is written once per frame.
604
+ let transformFrame = 0;
605
+ function requestTransform() { transformFrame ||= nextFrame(() => { transformFrame = 0; transform(); }); }
561
606
  // The canvas tips show until the reader dismisses them once. The choice is a per-browser
562
607
  // convenience, so unavailable storage simply shows the tips again next time.
563
608
  const HINT_KEY = 'andorra-graph-canvas-hint-dismissed';
@@ -584,14 +629,14 @@ function nodeSubtitle(node) {
584
629
  const model = nodeModelLabel(node);
585
630
  return node.agentRole === 'orchestrator' ? `Orchestrator${model ? ' · ' + model : ''}` : model;
586
631
  }
587
- if (node.type === 'end') return 'Graph complete';
632
+ if (node.type === 'end') return 'Workflow complete';
588
633
  if (node.type === 'action') return node.action?.kind === 'tests' ? 'Run tests' : node.action?.kind === 'git' ? 'Git operation' : 'Run command';
589
634
  return { join: 'Wait for branches', loop: 'Bounded repetition', condition: 'Branch on run state', parallel: 'Fan out', approval: 'Human approval' }[node.type] || 'Flow control';
590
635
  }
591
636
  const nodeIconElement = node => globalThis.AndorraIcons?.icon?.(globalThis.AndorraIcons.nodeIcon(node));
592
637
  function renderCanvas() {
593
638
  $('nodes').replaceChildren(); $('edges').replaceChildren(); $('canvas').classList.toggle('picking-destination',!!state.routePick);
594
- const hintText = state.routePick ? 'Click a destination node · Escape cancels' : 'Ctrl/Cmd-click same-type nodes to select together · Drag to pan · Scroll to zoom';
639
+ const hintText = state.routePick ? 'Click a destination step · Escape cancels' : 'Ctrl/Cmd-click same-type steps to select together · Drag or scroll to pan · Pinch or Ctrl/Cmd+scroll to zoom';
595
640
  $('canvas-hint-text').textContent = hintText; $('canvas-hint').hidden = !state.routePick && canvasHintDismissed(); $('canvas-hint-close').hidden = !!state.routePick;
596
641
  $('empty').hidden = !!state.graph;
597
642
  if (!state.graph) return;
@@ -609,40 +654,120 @@ function renderCanvas() {
609
654
  button.append(title);
610
655
  const subtitle = nodeSubtitle(node);
611
656
  if (subtitle) { const line = el('small', subtitle); line.title = subtitle; button.append(line); }
612
- for (const outcome of outcomes(node)) { const port = el('button', outcome, 'output-port'); port.setAttribute('aria-label', `Connect ${node.name}: ${outcome}`); port.title = `${outcome} - drag to a node to connect`; if (connected.has(JSON.stringify([node.id, outcome]))) port.setAttribute('data-connected', 'true'); port.onpointerdown = event => event.stopPropagation(); port.onclick = event => { event.stopPropagation(); if(state.routePick || event.ctrlKey || event.metaKey) {selectNode(node,event);return;} clearSelection(); state.selectedIds=[node.id]; state.selected = node.id; state.inspectorTab = 'behavior'; renderCanvas(); renderInspector(); $('inspector').classList.remove('hidden'); $('toggle-inspector').setAttribute('aria-expanded','true'); document.getElementById(`route-${outcome}`)?.scrollIntoView({block: 'nearest'}); }; button.append(port); }
657
+ for (const outcome of outcomes(node)) { const port = el('button', outcome, 'output-port'); port.setAttribute('aria-label', `Connect ${node.name}: ${outcome}`); port.title = `${outcome} · drag to a step to connect`; if (connected.has(JSON.stringify([node.id, outcome]))) port.setAttribute('data-connected', 'true'); port.onpointerdown = event => event.stopPropagation(); port.onclick = event => { event.stopPropagation(); if(state.routePick || event.ctrlKey || event.metaKey) {selectNode(node,event);return;} clearSelection(); state.selectedIds=[node.id]; state.selected = node.id; state.inspectorTab = 'behavior'; renderCanvas(); renderInspector(); $('inspector').classList.remove('hidden'); $('toggle-inspector').setAttribute('aria-expanded','true'); document.getElementById(`route-${outcome}`)?.scrollIntoView({block: 'nearest'}); }; button.append(port); }
613
658
  button.onkeydown = event => { if ((event.key === 'Enter' || event.key === ' ') && event.target === button) {event.preventDefault(); selectNode(node,event);} };
614
659
  button.onclick = event => selectNode(node,event);
615
660
  button.onpointerdown = event => {
616
661
  if (event.button !== 0) return; event.stopPropagation(); if(event.ctrlKey || event.metaKey || state.routePick) return; state.suppressClick=null; const start = { x: event.clientX, y: event.clientY }, origin = position(node, index); let moved = false;
617
- const move = e => { if (!moved && Math.hypot(e.clientX - start.x, e.clientY - start.y) < 3) return; if (!moved) { checkpoint(); moved = true; } const grid = state.studioSnap ? 20 : 1; node.position = { x: Math.round((origin.x + (e.clientX - start.x) / state.zoom) / grid) * grid, y: Math.round((origin.y + (e.clientY - start.y) / state.zoom) / grid) * grid }; changed(); };
618
- const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); if (moved) {state.suppressClick=node.id; setTimeout(()=>{if(state.suppressClick===node.id)state.suppressClick=null;},0); renderInspector();} };
619
- window.addEventListener('pointermove', move); window.addEventListener('pointerup', up, { once: true });
662
+ // A drag moves this one card and re-routes only its own connections, once per frame
663
+ // (dragFrame). The full paint — every route, validation, the status line, the draft — runs
664
+ // once, on release; before, every pointer move rebuilt the whole canvas.
665
+ let boxes = null, latest = null, frame = 0;
666
+ const paint = () => { frame = 0; if (!latest) return; node.position = latest; dragFrame(node, boxes); };
667
+ const move = e => {
668
+ if (!moved && Math.hypot(e.clientX - start.x, e.clientY - start.y) < 3) return;
669
+ if (!moved) { checkpoint(); moved = true; boxes = measureBoxes(); button.classList.add('dragging'); }
670
+ const grid = state.studioSnap ? GRID_STEP : 1;
671
+ latest = { x: Math.round((origin.x + (e.clientX - start.x) / state.zoom) / grid) * grid, y: Math.round((origin.y + (e.clientY - start.y) / state.zoom) / grid) * grid };
672
+ frame ||= nextFrame(paint);
673
+ };
674
+ const up = () => {
675
+ window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); window.removeEventListener('pointercancel', up);
676
+ if (frame) { cancelFrame(frame); paint(); }
677
+ if (moved) { button.classList.remove('dragging'); changed(); state.suppressClick=node.id; setTimeout(()=>{if(state.suppressClick===node.id)state.suppressClick=null;},0); renderInspector(); }
678
+ };
679
+ window.addEventListener('pointermove', move); window.addEventListener('pointerup', up, { once: true }); window.addEventListener('pointercancel', up, { once: true });
620
680
  };
621
681
  $('nodes').append(button);
622
682
  }); transform(); renderEdges(); window.AndorraStudio?.canvas?.();
623
683
  }
624
- let routedGeometry = '', routedPaths = new Map();
684
+ // One animation frame, or at once where there are no frames (a harness without a renderer).
685
+ const nextFrame = callback => (typeof requestAnimationFrame === 'function' ? requestAnimationFrame(callback) : (callback(), 0));
686
+ const cancelFrame = frame => { if (frame && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(frame); };
687
+ // Every connection's route, computed together in edge-list order (AndorraEdgeRouter.routeEdges) and
688
+ // kept until the cards or the connections change. The corner points are kept as well, so a drag can
689
+ // re-route the connections it moves while keeping them off the others.
690
+ let routedKey = '', routedPaths = [], routedPoints = [];
691
+ // The drawn parts of each connection, by its index in the edge list: what a drag frame updates.
692
+ let drawnEdges = [];
693
+ /** Each card's box in canvas units and the centre of each of its outcome ports, measured once. */
694
+ function measureBoxes() {
695
+ const boxes = new Map(), elements = new Map(Array.from($('nodes').children).map(item => [item.getAttribute('data-node-id'), item]));
696
+ Object.values(state.graph.nodes).forEach((node, index) => {
697
+ const element = elements.get(node.id), p = position(node, index);
698
+ if (!element) return;
699
+ const offsets = Array.from(element.querySelectorAll('.output-port')).map(port => port.offsetTop + port.offsetHeight / 2);
700
+ boxes.set(node.id, { ...p, width: element.offsetWidth, height: element.offsetHeight, offsets, ports: offsets.map(offset => ({ x: p.x + element.offsetWidth, y: p.y + offset })) });
701
+ });
702
+ return boxes;
703
+ }
704
+ /** Where a connection leaves its source's outcome port and where it enters its target. */
705
+ function routeInput(edge, boxes) {
706
+ const from = boxes.get(edge.source), to = boxes.get(edge.target); if (!from || !to) return null;
707
+ const source = from.ports[Math.max(0, outcomes(state.graph.nodes[edge.source]).indexOf(edgeOutcome(edge)))];
708
+ return source ? { source, target: { x: to.x, y: to.y + 48 } } : null;
709
+ }
710
+ // Elbows are drawn rounded; a router without the helper keeps its square corners.
711
+ const drawnRoute = points => points && { d: (AndorraEdgeRouter.roundedPath || AndorraEdgeRouter.path)(points), label: AndorraEdgeRouter.labelPoint?.(points) };
712
+ /**
713
+ * One frame of a node drag. The card moves by its transform alone, and only the connections that
714
+ * touch it are routed again — each kept off the routes the last full paint laid out — and written
715
+ * into the paths already drawn. No element is created or removed.
716
+ */
717
+ function dragFrame(node, boxes) {
718
+ const element = Array.from($('nodes').children).find(item => item.getAttribute('data-node-id') === node.id), box = boxes?.get(node.id), p = node.position;
719
+ if (!element || !box) return;
720
+ // Measured from where the card was last painted, so a repaint mid-drag cannot double the offset.
721
+ element.style.transform = `translate(${p.x - parseFloat(element.style.left)}px, ${p.y - parseFloat(element.style.top)}px)`;
722
+ box.x = p.x; box.y = p.y; box.ports = box.offsets.map(offset => ({ x: p.x + box.width, y: p.y + offset }));
723
+ const edges = state.graph.edges, moving = edges.map((edge, index) => (edge.source === node.id || edge.target === node.id ? index : -1)).filter(index => index >= 0);
724
+ const occupied = routedPoints.filter((points, index) => points && !moving.includes(index)), rectangles = [...boxes.values()];
725
+ for (const index of moving) {
726
+ const input = routeInput(edges[index], boxes), drawn = drawnEdges[index];
727
+ if (!input || !drawn) continue;
728
+ const points = AndorraEdgeRouter.routeEdge(input.source, input.target, rectangles, index, undefined, occupied);
729
+ if (!points) continue;
730
+ occupied.push(points);
731
+ const route = drawnRoute(points);
732
+ for (const part of [drawn.halo, drawn.path, drawn.hit]) part.setAttribute('d', route.d);
733
+ if (drawn.pill && route.label) placePill(drawn.pill, route.label);
734
+ }
735
+ window.AndorraStudio?.dragged?.();
736
+ }
737
+ /** Put an outcome pill on its route's label point. */
738
+ function placePill(pill, at) {
739
+ pill.rect.setAttribute('x', String(Math.round(at.x - pill.width / 2))); pill.rect.setAttribute('y', String(at.y - PILL_HEIGHT / 2));
740
+ pill.text.setAttribute('x', String(Math.round(at.x))); pill.text.setAttribute('y', String(at.y + 4));
741
+ }
742
+ const PILL_HEIGHT = 18;
625
743
  function renderEdges() {
626
- $('edges').replaceChildren();
744
+ $('edges').replaceChildren(); drawnEdges = [];
627
745
  if (!state.graph) return;
628
746
  const svg = tag => document.createElementNS('http://www.w3.org/2000/svg', tag);
629
747
  const defs=svg('defs'); $('edges').append(defs);
630
- const boxes=new Map();
631
- Object.values(state.graph.nodes).forEach((node,index)=>{
632
- const element=Array.from($('nodes').children).find(item=>item.getAttribute('data-node-id')===node.id), p=position(node,index);
633
- const ports=Array.from(element.querySelectorAll('.output-port'));
634
- boxes.set(node.id,{...p,width:element.offsetWidth,height:element.offsetHeight,ports:ports.map(port=>({x:p.x+element.offsetWidth,y:p.y+port.offsetTop+port.offsetHeight/2}))});
635
- });
636
- const geometry=JSON.stringify([...boxes]);
637
- if(geometry!==routedGeometry){routedGeometry=geometry;routedPaths.clear();}
748
+ const boxes=measureBoxes();
638
749
  const rectangles=[...boxes.values()], rendered=[], pills=[], palette=connectionPalette();
750
+ // Routes are laid out in the edge list's order, never the drawing order below, so selecting a
751
+ // connection does not move any line. Each route keeps clear of those laid out before it.
752
+ const routeInputs=state.graph.edges.map(edge=>routeInput(edge,boxes));
753
+ const routesKey=JSON.stringify([[...boxes].map(([id,box])=>[id,box.x,box.y,box.width,box.height,box.ports]),routeInputs]);
754
+ if(routesKey!==routedKey){
755
+ routedKey=routesKey;
756
+ routedPoints=AndorraEdgeRouter.routeEdges?AndorraEdgeRouter.routeEdges(routeInputs,rectangles):routeInputs.map((input,index)=>input&&AndorraEdgeRouter.routeEdge(input.source,input.target,rectangles,index));
757
+ routedPaths=routedPoints.map(drawnRoute);
758
+ }
639
759
  const caption=svg('text'); caption.setAttribute('class','edge-caption'); caption.style.pointerEvents='none';
760
+ // A traced connection (hovered, focused or selected) is drawn in the accent ink, a little heavier,
761
+ // and the others step back; nothing else about a connection changes its colour.
640
762
  const emphasize = active => {
641
763
  for (const item of rendered) {
642
- item.path.setAttribute('stroke-width',item.edge===active?'3':'1.7');
643
- item.path.setAttribute('opacity',active && item.edge!==active?'0.25':'1');
644
- item.halo.setAttribute('opacity',active && item.edge!==active?'0.25':'1');
645
- item.pill?.setAttribute('opacity',active && item.edge!==active?'0.25':'1');
764
+ const on=item.edge===active;
765
+ item.path.setAttribute('stroke',on?palette.active:palette.line);
766
+ item.arrow.setAttribute('fill',on?palette.active:palette.line);
767
+ item.path.setAttribute('stroke-width',on?EDGE_ACTIVE_WIDTH:EDGE_WIDTH);
768
+ item.path.setAttribute('opacity',active && !on?'0.25':'1');
769
+ item.halo.setAttribute('opacity',active && !on?'0.25':'1');
770
+ item.pill?.setAttribute('opacity',active && !on?'0.25':'1');
646
771
  }
647
772
  for (const element of Array.from($('nodes').children)) {
648
773
  const id=element.getAttribute('data-node-id');
@@ -650,56 +775,58 @@ function renderEdges() {
650
775
  element.classList.toggle('edge-target',Boolean(active && id===active.target));
651
776
  }
652
777
  const item=rendered.find(item=>item.edge===active);
653
- caption.textContent=item?`${edgeOutcome(item.edge)} -> ${state.graph.nodes[item.edge.target].name}`:'';
654
- if(item){caption.setAttribute('x',String(item.from.x));caption.setAttribute('y',String(item.from.y-14));caption.setAttribute('fill',item.color);}
778
+ caption.textContent=item?`${edgeOutcome(item.edge)} → ${state.graph.nodes[item.edge.target].name}`:'';
779
+ if(item){caption.setAttribute('x',String(item.from.x));caption.setAttribute('y',String(item.from.y-14));caption.setAttribute('fill',palette.active);}
655
780
  };
656
781
  // Draw a selected connection last so crossings cannot obscure its direction.
657
782
  const ordered=state.graph.edges.map((edge,index)=>({edge,index})).sort((a,b)=>Number(a.edge===state.selectedEdge)-Number(b.edge===state.selectedEdge));
658
783
  ordered.forEach(({edge,index})=>{
659
- const from=boxes.get(edge.source),to=boxes.get(edge.target);if(!from||!to)return;
660
- const source=from.ports[Math.max(0,outcomes(state.graph.nodes[edge.source]).indexOf(edgeOutcome(edge)))];if(!source)return;
661
- const routeKey=JSON.stringify([source,to.x,to.y+48,index]);
662
- if(!routedPaths.has(routeKey)){
663
- const points=AndorraEdgeRouter.routeEdge(source,{x:to.x,y:to.y+48},rectangles,index);
664
- // Elbows are drawn rounded; a router without the helper keeps its square corners.
665
- routedPaths.set(routeKey,{d:(AndorraEdgeRouter.roundedPath||AndorraEdgeRouter.path)(points),label:AndorraEdgeRouter.labelPoint?.(points)});
666
- }
667
- const route=routedPaths.get(routeKey), d=route.d, path=svg('path'), hit=svg('path'), halo=svg('path');
668
- const outcome=edgeOutcome(edge), color=outcome==='fail'||outcome==='rejected'?palette.fail:outcome==='pass'||outcome==='approved'?palette.pass:outcome==='blocked'?palette.blocked:palette.plain;
784
+ const from=boxes.get(edge.source),route=routedPaths[index];if(!from||!route)return;
785
+ const d=route.d, path=svg('path'), hit=svg('path'), halo=svg('path');
786
+ const outcome=edgeOutcome(edge);
669
787
  const marker=svg('marker'), arrow=svg('path');
670
788
  for(const [name,value] of Object.entries({id:`edge-arrow-${index}`,viewBox:'0 0 10 10',refX:'9',refY:'5',markerWidth:'7',markerHeight:'7',orient:'auto-start-reverse'}))marker.setAttribute(name,value);
671
- arrow.setAttribute('d','M 0 0 L 10 5 L 0 10 z');arrow.setAttribute('fill',color);arrow.style.pointerEvents='none';marker.append(arrow);defs.append(marker);
789
+ arrow.setAttribute('d','M 0 0 L 10 5 L 0 10 z');arrow.setAttribute('fill',palette.line);arrow.style.pointerEvents='none';marker.append(arrow);defs.append(marker);
672
790
  halo.setAttribute('d',d);halo.setAttribute('stroke',palette.halo);halo.setAttribute('stroke-width','6');halo.setAttribute('fill','none');halo.style.pointerEvents='none';
673
- path.setAttribute('d',d);path.setAttribute('data-route',JSON.stringify([edge.source,edgeOutcome(edge),edge.target]));path.setAttribute('stroke',color);path.setAttribute('fill','none');path.setAttribute('stroke-linejoin','round');path.setAttribute('marker-end',`url(#edge-arrow-${index})`);path.style.pointerEvents='none';
674
- hit.setAttribute('d',d);hit.setAttribute('stroke','transparent');hit.setAttribute('stroke-width','14');hit.setAttribute('fill','none');hit.style.pointerEvents='stroke';hit.style.cursor='pointer';hit.setAttribute('tabindex','0');hit.setAttribute('role','button');hit.setAttribute('aria-label',`Configure handoff from ${state.graph.nodes[edge.source].name}, ${edgeOutcome(edge)}, to ${state.graph.nodes[edge.target].name}`);
791
+ path.setAttribute('d',d);path.setAttribute('data-route',JSON.stringify([edge.source,edgeOutcome(edge),edge.target]));path.setAttribute('stroke',palette.line);path.setAttribute('stroke-width',EDGE_WIDTH);path.setAttribute('fill','none');path.setAttribute('stroke-linejoin','round');path.setAttribute('marker-end',`url(#edge-arrow-${index})`);path.style.pointerEvents='none';
792
+ hit.setAttribute('d',d);hit.setAttribute('stroke','transparent');hit.setAttribute('stroke-width','14');hit.setAttribute('fill','none');hit.style.pointerEvents='stroke';hit.style.cursor='pointer';hit.setAttribute('tabindex','0');hit.setAttribute('role','button');hit.setAttribute('aria-label',`Edit connection from ${state.graph.nodes[edge.source].name}, ${edgeOutcome(edge)}, to ${state.graph.nodes[edge.target].name}`);
675
793
  hit.onclick=event=>{event.stopPropagation();clearSelection();state.selectedEdge=edge;renderInspector();renderCanvas();showInspector();};
676
794
  hit.onkeydown=event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();hit.onclick(event);}};
677
795
  // The connection's hint is the app's tooltip (an SVG title would be the platform's).
678
- hit.setAttribute('data-tip',`${state.graph.nodes[edge.source].name}: ${outcome} -> ${state.graph.nodes[edge.target].name}`);
796
+ hit.setAttribute('data-tip',`${state.graph.nodes[edge.source].name}: ${outcome} → ${state.graph.nodes[edge.target].name}`);
679
797
  hit.onpointerenter=hit.onfocus=()=>emphasize(edge);
680
798
  hit.onpointerleave=hit.onblur=()=>emphasize(state.selectedEdge);
681
- const entry={edge,path,halo,from,color,pill:null};rendered.push(entry);
799
+ const entry={edge,path,halo,arrow,from,pill:null};rendered.push(entry);
800
+ drawnEdges[index]={path,halo,hit,pill:null};
682
801
  $('edges').append(halo,path,hit);
683
802
  // The outcome rides its line as a pill. A node's only, default outcome needs no name.
684
803
  const single=outcomes(state.graph.nodes[edge.source]).length===1&&outcome==='completed';
685
- if(route.label&&!single)pills.push({entry,outcome,color,at:route.label});
804
+ if(route.label&&!single)pills.push({entry,index,outcome,at:route.label});
686
805
  });
687
806
  const pillLayer=svg('g');pillLayer.setAttribute('class','edge-pills');pillLayer.setAttribute('aria-hidden','true');
688
- for(const {entry,outcome,color,at} of pills){const edge=entry.edge;
807
+ const drawnPills=[];
808
+ for(const {entry,index,outcome,at} of pills){const edge=entry.edge;
689
809
  const group=svg('g'),rect=svg('rect'),text=svg('text');
690
- const width=Math.max(28,Math.round(outcome.length*6.6+16)),height=18;
691
810
  group.setAttribute('class','edge-pill');group.setAttribute('data-route',JSON.stringify([edge.source,outcome,edge.target]));
692
- for(const [name,value] of Object.entries({x:String(Math.round(at.x-width/2)),y:String(at.y-height/2),width:String(width),height:String(height),rx:String(height/2),fill:palette.pill,stroke:color,'stroke-width':'1'}))rect.setAttribute(name,value);
693
- for(const [name,value] of Object.entries({x:String(Math.round(at.x)),y:String(at.y+4),'text-anchor':'middle',fill:color}))text.setAttribute(name,value);
811
+ for(const [name,value] of Object.entries({height:String(PILL_HEIGHT),rx:String(PILL_HEIGHT/2),fill:palette.pill,stroke:palette.pillEdge,'stroke-width':'1'}))rect.setAttribute(name,value);
812
+ for(const [name,value] of Object.entries({'text-anchor':'middle',fill:palette.pillInk}))text.setAttribute(name,value);
694
813
  text.textContent=outcome;group.append(rect,text);pillLayer.append(group);
695
- entry.pill=group;
814
+ const pill={rect,text,width:Math.max(28,Math.round(outcome.length*6.6+16))};
815
+ entry.pill=group;drawnEdges[index].pill=pill;drawnPills.push({pill,at});
816
+ }
817
+ $('edges').append(pillLayer,caption);
818
+ // A pill fits its word as the face sets it; the estimate stands in where nothing is rendered.
819
+ for(const {pill,at} of drawnPills){
820
+ const measured=typeof pill.text.getComputedTextLength==='function'?pill.text.getComputedTextLength():0;
821
+ if(measured>0)pill.width=Math.max(28,Math.ceil(measured+16));
822
+ pill.rect.setAttribute('width',String(pill.width));placePill(pill,at);
696
823
  }
697
- $('edges').append(pillLayer,caption); emphasize(state.selectedEdge);
824
+ emphasize(state.selectedEdge);
698
825
  }
699
826
  function removeNodes(ids) {
700
827
  const graph = state.graph;
701
828
  const remaining = Object.keys(graph.nodes).filter(id => !ids.has(id));
702
- if (!remaining.length) { status('Keep at least one node as the graph start. Add a replacement before deleting all nodes.', true); return; }
829
+ if (!remaining.length) { status('Keep at least one step as the workflow start. Add a replacement before deleting all steps.', true); return; }
703
830
  const nextEntry = ids.has(graph.entry)
704
831
  ? graph.edges.find(edge => edge.source === graph.entry && !ids.has(edge.target) && graph.nodes[edge.target])?.target ?? remaining[0]
705
832
  : graph.entry;
@@ -712,7 +839,7 @@ function removeNodes(ids) {
712
839
  graph.schemaVersion = 3;
713
840
  clearSelection();
714
841
  }, true);
715
- status(`Deleted ${ids.size} node${ids.size === 1 ? '' : 's'} and their connections. Start: ${graph.nodes[nextEntry].name}. Undo restores them.`);
842
+ status(`Deleted ${ids.size} step${ids.size === 1 ? '' : 's'} and their connections. Start: ${graph.nodes[nextEntry].name}. Undo restores them.`);
716
843
  }
717
844
  function deleteSelection() {
718
845
  if(!state.graph)return;
@@ -750,8 +877,8 @@ function nodeErrorIds() {
750
877
  }
751
878
  function renderValidation() {
752
879
  const container=$('validation');if(!container)return;container.replaceChildren();const errors=[...issues(),...state.validationErrors].map(errorEntry);
753
- if(!errors.length)container.append(el('p',state.validated?'Validated · Ready to save':'Checking graph…',state.validated?'valid ok':'valid'));
754
- else {const list=el('ul',undefined,'validation');errors.forEach(({message,nodeId})=>{ const row=el('li',message); row.tabIndex=0; row.title='Click to focus the affected node'; row.onclick=()=>{if(nodeId){clearSelection();state.selected=nodeId;state.selectedIds=[nodeId];renderCanvas();renderInspector();}};row.onkeydown=e=>{if(e.key==='Enter'||e.key===' ')row.click();};list.append(row);});container.append(list);}
880
+ if(!errors.length)container.append(el('p',state.validated?'Validated · Ready to save':'Checking workflow…',state.validated?'valid ok':'valid'));
881
+ else {const list=el('ul',undefined,'validation');errors.forEach(({message,nodeId})=>{ const row=el('li',message); row.tabIndex=0; row.title='Click to focus the affected step'; row.onclick=()=>{if(nodeId){clearSelection();state.selected=nodeId;state.selectedIds=[nodeId];renderCanvas();renderInspector();}};row.onkeydown=e=>{if(e.key==='Enter'||e.key===' ')row.click();};list.append(row);});container.append(list);}
755
882
  }
756
883
  function disclosure(parent, title, open = false) { const item = el('details', undefined, 'section disclosure'); const key = `${state.selectedEdge?.id || state.selected || 'graph'}:${title}`; item.open = state.disclosures[key] ?? open; item.ontoggle = () => {state.disclosures[key] = item.open;}; item.append(el('summary', title)); const body = el('div'); item.append(body); parent.append(item); return body; }
757
884
  function check(parent, label, value, update) { const wrapper = el('label', undefined, 'tool-label'), input = el('input'); input.type = 'checkbox'; input.checked = value; input.onchange = () => mutate(() => update(input.checked), true); wrapper.append(input, el('span', label)); parent.append(wrapper); return input; }
@@ -879,7 +1006,7 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
879
1006
  // model made the provider list read as the whole model list.
880
1007
  const providers = state.providers.map(p => ({value: idFor(p), label: titleFor(p)}));
881
1008
  if (target.provider && !providers.some(p => p.value === target.provider)) providers.push({value: target.provider, label: target.provider + ' (unavailable)'});
882
- const defaultProviderLabel = inheritedProvider ? `Same as parent node (${inheritedProvider})` : state.defaultProvider ? `Use configured default (${state.defaultProvider})` : 'Use configured default';
1009
+ const defaultProviderLabel = inheritedProvider ? `Same as parent agent (${inheritedProvider})` : state.defaultProvider ? `Use configured default (${state.defaultProvider})` : 'Use configured default';
883
1010
  choice(parent, 'Provider', target.provider || '', [{value:'', label: defaultProviderLabel}, ...providers], value => update({ ...target, provider: value || undefined, model: undefined }));
884
1011
  if (target.provider && !state.providers.some(p => idFor(p) === target.provider)) providerWarning(parent, target.provider);
885
1012
  // A providerless subagent child inherits the parent node's provider at execution
@@ -958,21 +1085,21 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
958
1085
  const typeMismatch = claimed && !!recorded?.type && claimedProvider.type !== recorded.type;
959
1086
  const matches = !claimed && recorded?.type === 'codex' ? state.providers.filter(p => p.type === 'codex' && offers(p, requiredModels)) : [];
960
1087
  const refusalHint = typeMismatch
961
- ? `Provider "${originalId}" is configured locally with type "${claimedProvider.type}", but this graph was published with type "${recorded.type}". Execution will refuse this graph; reconnect a provider of the recorded type.`
962
- : `Provider "${originalId}" is configured locally but does not offer ${requiredModels.join(', ')}. Execution will refuse this graph until that provider is configured with the model; another profile is never used as a substitute.`;
1088
+ ? `Provider "${originalId}" is configured locally with type "${claimedProvider.type}", but this workflow was published with type "${recorded.type}". Execution will refuse this workflow; reconnect a provider of the recorded type.`
1089
+ : `Provider "${originalId}" is configured locally but does not offer ${requiredModels.join(', ')}. Execution will refuse this workflow until that provider is configured with the model; another profile is never used as a substitute.`;
963
1090
  const hint = matches.length === 1
964
1091
  ? `Will use local Codex OAuth profile "${idFor(matches[0])}" (${requiredModels.join(', ') || 'all referenced models'}). The OAuth connection is verified before execution.`
965
1092
  : matches.length > 1
966
- ? `Multiple local Codex OAuth profiles (${matches.map(idFor).join(', ')}) each satisfy this graph's requirements for "${originalId}". Execution needs exactly one; configure the original provider ID or keep a single compatible profile.`
1093
+ ? `Multiple local Codex OAuth profiles (${matches.map(idFor).join(', ')}) each satisfy this workflow's requirements for "${originalId}". Execution needs exactly one; configure the original provider ID or keep a single compatible profile.`
967
1094
  : claimed
968
1095
  ? refusalHint
969
- : `Provider "${originalId}"${requiredModels.length ? ` / ${requiredModels.join(', ')}` : ''} is not configured on this machine. This graph can be saved, but execution requires a compatible provider.`;
1096
+ : `Provider "${originalId}"${requiredModels.length ? ` / ${requiredModels.join(', ')}` : ''} is not configured on this machine. This workflow can be saved, but execution requires a compatible provider.`;
970
1097
  parent.append(el('p', hint, 'help'));
971
1098
  } else if (followsProvider && recorded?.model && recorded.model !== exact.model) {
972
1099
  parent.append(el('p', `This selection follows "${originalId}"'s current model, ${exact.model}.`, 'help'));
973
1100
  }
974
1101
  }
975
- const info = el('p', 'Context window: detecting from model...', 'help model-context'); parent.append(info);
1102
+ const info = el('p', 'Context window: detecting from model…', 'help model-context'); parent.append(info);
976
1103
  const key = JSON.stringify([target.provider || '', target.model || '', provider?.model || '']);
977
1104
  // Capture the registry generation before any discovery request starts: a callback resolving
978
1105
  // after a registry change describes the previous endpoint and must discard itself.
@@ -1121,7 +1248,7 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1121
1248
  function renderCompletion(parent, node) {
1122
1249
  const graph = state.graph, routing = node.agentRole === 'orchestrator';
1123
1250
  const behavior = choice(parent, routing ? 'Routing behavior' : 'Completion behavior', node.completion?.mode || 'single', [
1124
- {value:'single',label:routing ? 'Continue to connected nodes' : 'Continue when complete'},
1251
+ {value:'single',label:routing ? 'Continue to connected steps' : 'Continue when complete'},
1125
1252
  {value:'outcomes',label:'Choose outcome using written criteria'},
1126
1253
  ], mode => {
1127
1254
  node.completion = mode === 'single' ? {mode,outcome:'completed'} : {mode,outcomes:routing ? ['frontend','backend','devops'] : ['pass','fail','blocked']};
@@ -1130,7 +1257,7 @@ function renderCompletion(parent, node) {
1130
1257
  explain(behavior, 'Outcome names are short phrases such as DONE, PASS, FAILED TESTING or BLOCKED. Describe when the agent should choose each one; for a single outcome, describe when the work is considered achieved, for example "This is considered DONE when xyz is finished". The agent evaluates these written criteria using its evidence; they are not automatic checks. Connect outcomes to destinations under Connections.');
1131
1258
  // The server refuses written criteria on a delegating Orchestrator, so the option is withheld
1132
1259
  // rather than offered and then rejected on save.
1133
- if (delegatesWriting(node) && node.completion?.mode !== 'outcomes') { for (const option of behavior.options) option.disabled = option.value === 'outcomes'; parent.append(el('p', 'An Orchestrator with a writing role keeps a single outcome: it completes with a handoff, or delivers landed changes through its delivered port.', 'help')); }
1260
+ if (delegatesWriting(node) && node.completion?.mode !== 'outcomes') { for (const option of behavior.options) option.disabled = option.value === 'outcomes'; parent.append(el('p', 'An Orchestrator with a writing role keeps a single outcome: it completes by passing work on, or delivers landed changes through its delivered port.', 'help')); }
1134
1261
  if (node.completion?.mode === 'outcomes') {
1135
1262
  parent.append(el('p', 'Criteria are optional; blank rows use the agent prompt. Removing or renaming an outcome removes its old routes. Undo restores routes and criteria.', 'help'));
1136
1263
  if (node.modifiers?.condition || node.modifiers?.loop?.until.outcome !== undefined) parent.append(el('p', 'Modifiers control the final connections: a Condition routes to true/false; an outcome Loop exposes its exit outcome.', 'help'));
@@ -1170,7 +1297,7 @@ function renderCompletion(parent, node) {
1170
1297
  }, true);
1171
1298
  row.append(remove);
1172
1299
  });
1173
- const add = el('button', 'Add outcome');
1300
+ const add = el('button', 'Add Outcome');
1174
1301
  add.disabled = completion.outcomes.length >= 20;
1175
1302
  add.title = 'Up to 20 outcomes per agent';
1176
1303
  add.onclick = () => mutate(() => {
@@ -1201,14 +1328,14 @@ function routes(parent, node) {
1201
1328
  for (const destination of Object.values(state.graph.nodes).filter(n => n.id !== node.id && n.agentRole !== 'orchestrator')) {
1202
1329
  const edge = state.graph.edges.find(e => e.source === node.id && edgeOutcome(e) === outcome && e.target === destination.id);
1203
1330
  check(row, destination.name, !!edge, enabled => { if (enabled) state.graph.edges.push({id: `edge-${crypto.randomUUID().slice(0,8)}`, source: node.id, target: destination.id, outcome}); else state.graph.edges = state.graph.edges.filter(e => e !== edge); });
1204
- if (edge) { const edit = el('button', 'Configure handoff', 'link-button'); edit.onclick = () => { state.selectedEdge = edge; state.selected = null; renderInspector(); renderCanvas(); }; row.append(edit); }
1331
+ if (edge) { const edit = el('button', 'Edit Connection', 'link-button'); edit.onclick = () => { state.selectedEdge = edge; state.selected = null; renderInspector(); renderCanvas(); }; row.append(edit); }
1205
1332
  }
1206
1333
  }
1207
1334
  }
1208
1335
  function renderEdgeInspector(parent, edge) {
1209
- $('inspector-title').textContent = 'Connection handoff';
1336
+ $('inspector-title').textContent = 'Connection';
1210
1337
  parent.append(el('h3', `${state.graph.nodes[edge.source]?.name} - ${edgeOutcome(edge)}`), el('p', `To: ${state.graph.nodes[edge.target]?.name}`, 'help'));
1211
- if (edge.bootstrap) parent.append(el('p', 'Initial handoff: starts this upgraded graph at its original Join. Later loop iterations wait for the other incoming branches. Removing this connection removes that initial-start behavior.', 'help'));
1338
+ if (edge.bootstrap) parent.append(el('p', 'Initial connection: starts this updated workflow at its original Join. Later loop iterations wait for the other incoming branches. Removing this connection removes that initial-start behavior.', 'help'));
1212
1339
  const mappings = section(parent, 'Input mapping'); mappings.append(el('p', 'Map validated outputs or run context into the destination named inputs. Constants must be valid JSON.', 'help'));
1213
1340
  const targetSchema=state.graph.nodes[edge.target]?.inputSchema, sourceSchema=state.graph.nodes[edge.source]?.modifiers?.parallel?.mode === 'copies' ? {properties:{results:{type:'array'}}} : state.graph.nodes[edge.source]?.outputSchema; const targetKeys = Object.keys(targetSchema?.properties || {}), sourceKeys = Object.keys(sourceSchema?.properties || {}); if(targetKeys.length)mappings.append(el('p',`Destination inputs: ${targetKeys.map(key=>key+(targetSchema.required?.includes(key)?' (required)':'')).join(', ')}`,'help'));if(sourceKeys.length)mappings.append(el('p',`Available source outputs: ${sourceKeys.join(', ')}`,'help'));
1214
1341
  for (const [key, value] of Object.entries(edge.inputMapping || {})) {
@@ -1219,11 +1346,11 @@ function renderEdgeInspector(parent, edge) {
1219
1346
  choice(row, 'Source', kind, [{value:'$source.output', label:'Source output field'}, {value:'$run.input', label:'Run input field'}, {value:'$run.state', label:'Run state field'}, {value:'$run.loop.iteration', label:'Loop iteration'}, {value:'$source.artifacts', label:'Source artifacts'}, {value:'constant', label:'Constant'}], next => set(next === 'constant' ? {constant: ''} : ['$source.output','$run.input','$run.state'].includes(next) ? `${next}.${next === '$source.output' ? sourceKeys[0] || 'result' : 'task'}` : next));
1220
1347
  if (kind === 'constant') jsonField(row, 'Constant value', value.constant, next => set({constant:next}));
1221
1348
  else if (['$source.output','$run.input','$run.state'].includes(kind)) { const input = field(row, 'Field / path', value.slice(kind.length + 1), next => set(`${kind}.${next}`)); const availableKeys = kind === '$source.output' ? sourceKeys : Object.keys((kind === '$run.input' ? state.graph.inputSchema : state.graph.stateSchema)?.properties || {}); if (availableKeys.length) { const list = el('datalist'); list.id = `mapping-${crypto.randomUUID()}`; availableKeys.forEach(key => { const option = el('option'); option.value = key; list.append(option); }); input.setAttribute('list', list.id); row.append(list); } }
1222
- const remove = el('button', 'Remove mapping'); remove.onclick = () => mutate(() => { delete edge.inputMapping[key]; }, true); row.append(remove);
1349
+ const remove = el('button', 'Remove Mapping'); remove.onclick = () => mutate(() => { delete edge.inputMapping[key]; }, true); row.append(remove);
1223
1350
  }
1224
- const add = el('button', 'Add mapping'); add.onclick = () => mutate(() => { edge.inputMapping ||= {}; let key = targetKeys.find(k => !Object.hasOwn(edge.inputMapping,k)) || 'input'; while (Object.hasOwn(edge.inputMapping,key)) key += '_'; edge.inputMapping[key] = {constant:''}; }, true);
1225
- const suggest = el('button', 'Suggest matching fields'); suggest.onclick = () => mutate(() => { edge.inputMapping ||= {}; for (const key of targetKeys.filter(k => sourceKeys.includes(k))) if (!Object.hasOwn(edge.inputMapping,key)) edge.inputMapping[key] = `$source.output.${key}`; }, true); mappings.append(add, suggest);
1226
- const remove = el('button', 'Remove connection', 'danger'); remove.onclick = () => mutate(() => { state.graph.edges = state.graph.edges.filter(e => e !== edge); state.selectedEdge = null; }, true); parent.append(remove);
1351
+ const add = el('button', 'Add Mapping'); add.onclick = () => mutate(() => { edge.inputMapping ||= {}; let key = targetKeys.find(k => !Object.hasOwn(edge.inputMapping,k)) || 'input'; while (Object.hasOwn(edge.inputMapping,key)) key += '_'; edge.inputMapping[key] = {constant:''}; }, true);
1352
+ const suggest = el('button', 'Suggest Matching Fields'); suggest.onclick = () => mutate(() => { edge.inputMapping ||= {}; for (const key of targetKeys.filter(k => sourceKeys.includes(k))) if (!Object.hasOwn(edge.inputMapping,key)) edge.inputMapping[key] = `$source.output.${key}`; }, true); mappings.append(add, suggest);
1353
+ const remove = el('button', 'Remove Connection', 'danger'); remove.onclick = () => mutate(() => { state.graph.edges = state.graph.edges.filter(e => e !== edge); state.selectedEdge = null; }, true); parent.append(remove);
1227
1354
  }
1228
1355
  function effectiveCaps(node = {}) { return node.capabilities || {filesystem:'read-write',shell:'allowed',git:'write',github:'none',browser:'playwright',deployment:'none'}; }
1229
1356
  // Browser copy of src/tool-names.ts. The server treats these spellings as aliases of the canonical
@@ -1248,10 +1375,11 @@ function canonicalToolName(name) { const d = displayToolName(name); return SHELL
1248
1375
  // Browser copy of permitsBuiltInTool in src/graphs.ts for a delegated worktree child, the one
1249
1376
  // kind of subagent that runs commands. The server validates a writing role's tools with that rule,
1250
1377
  // so a tool offered here that it refuses could be ticked and then fail validation.
1251
- const QA_TOOL_NAMES = ['qa.inspect_project', 'qa.status', 'qa.fast', 'qa.deep', 'qa.test', 'qa.terminal', 'qa.security', 'qa.browser'];
1378
+ const QA_TOOL_NAMES = ['qa.terminal', 'qa.browser'];
1252
1379
  function delegatedRolePermits(caps, name) {
1253
1380
  const display = displayToolName(name);
1254
- const commands = caps.shell === 'allowed' && caps.filesystem === 'read-write' && caps.git === 'write';
1381
+ // Mirrors canRunCommands in src/graphs.ts: the shell setting alone grants commands.
1382
+ const commands = caps.shell === 'allowed';
1255
1383
  if (name === 'qa.browser_session' || name === 'browser.solve_captcha' || name === 'web_search') return caps.browser === 'playwright';
1256
1384
  if (['Read', 'Glob', 'Grep', 'repo_explore', 'read_skill_resource'].includes(display)) return caps.filesystem !== 'none';
1257
1385
  if (['Write', 'Edit'].includes(display)) return caps.filesystem === 'read-write';
@@ -1274,7 +1402,7 @@ function roleToolOptions(node, role, policy) {
1274
1402
  const parent = effectiveCaps(node);
1275
1403
  const child = role.capabilities || {...parent,...((policy.workspace || 'shared-read-only') === 'shared-read-only' ? {filesystem:parent.filesystem === 'none' ? 'none' : 'read',git:parent.git === 'none' ? 'none' : 'read',shell:'disabled'} : {})};
1276
1404
  const canonical = canonicalToolName;
1277
- const permits = (caps, name) => name === 'qa.browser_session' ? caps.browser === 'playwright' : ['Read','Glob','Grep','repo_explore','read_skill_resource'].includes(canonical(name)) ? caps.filesystem !== 'none' : ['Write','Edit'].includes(canonical(name)) ? caps.filesystem === 'read-write' : canonical(name) === 'shell' ? caps.shell === 'allowed' && caps.filesystem === 'read-write' && caps.git === 'write' : name === 'git_read' ? caps.git !== 'none' : ['read_artifact','write_artifact'].includes(name);
1405
+ const permits = (caps, name) => name === 'qa.browser_session' ? caps.browser === 'playwright' : ['Read','Glob','Grep','repo_explore','read_skill_resource'].includes(canonical(name)) ? caps.filesystem !== 'none' : ['Write','Edit'].includes(canonical(name)) ? caps.filesystem === 'read-write' : canonical(name) === 'shell' ? false /* an ordinary subagent never runs commands (validateGraph refuses it) */ : name === 'git_read' ? caps.git !== 'none' : ['read_artifact','write_artifact'].includes(name);
1278
1406
  const configured = node.tools?.map(displayToolName);
1279
1407
  const available = (configured || state.tools.map(t=>displayToolName(typeof t === 'string' ? t : t.name || t.id))).filter((name,index,array)=>array.indexOf(name)===index).filter(name=>permits(parent,name)&&permits(child,name));
1280
1408
  const defaults = policy.toolInheritance === 'inherit' ? available : available.filter(name=>['Read','Glob','Grep','git_read','qa.browser_session','read_skill_resource'].includes(canonical(name)));
@@ -1287,12 +1415,12 @@ function renderSubagents(parent, node) {
1287
1415
  const delegating = delegatesWriting(node);
1288
1416
  explain(check(parent,'Allow subagents',policy.enabled,value=>{set({enabled:value});pruneRoutes(node);}), delegating
1289
1417
  ? 'Writing roles of an Orchestrator run in their own Git worktree with a shell. The shell is not sandboxed and follows your permission mode. The Orchestrator reviews each change and lands the ones it accepts into your working folder; it never writes code itself.'
1290
- : 'Internal delegation returns observations to this Agent. Only this parent chooses its graph outcome. Active children finish or cancel before the parent can complete. Subagents of ordinary agents never receive the unsandboxed host shell. Read-only roles use filesystem tools and supported Git read operations.');
1418
+ : 'Internal delegation returns observations to this Agent. Only this parent chooses its workflow outcome. Active children finish or cancel before the parent can complete. Subagents of ordinary agents never receive the unsandboxed host shell. Read-only roles use filesystem tools and supported Git read operations.');
1291
1419
  if (!policy.enabled) return;
1292
1420
  // The server refuses writing roles on an Orchestrator outside separate worktrees, so the
1293
1421
  // editor moves the policy there as soon as a role may write.
1294
1422
  const requireWorktree = () => { if (node.agentRole === 'orchestrator' && (policy.roles || []).some(isWritingRole)) set({workspace:'worktree'}); };
1295
- for (const [key,label,fallback] of [['maxConcurrent','Max concurrent',3],['maxTotal','Max total per node run',8],['maxDepth','Max nesting depth',1]]) field(parent,label,policy[key]??fallback,value=>set({[key]:value}),{type:'number',min:1,max:key==='maxDepth'?3:key==='maxConcurrent'?16:1000});
1423
+ for (const [key,label,fallback] of [['maxConcurrent','Max concurrent',3],['maxTotal','Max total per agent run',8],['maxDepth','Max nesting depth',1]]) field(parent,label,policy[key]??fallback,value=>set({[key]:value}),{type:'number',min:1,max:key==='maxDepth'?3:key==='maxConcurrent'?16:1000});
1296
1424
  choice(parent,'Model policy',policy.modelPolicy||'inherit',[{value:'inherit',label:'Inherit parent model'},{value:'specific',label:'Use specific model'},{value:'per-role',label:'Per-role model'}],value=>set({modelPolicy:value}));
1297
1425
  // Mirrors bindPortableGraphProviders: enabled retry attempts may spawn providerless children on
1298
1426
  // the fallback provider, so a discovered child pick must be recorded there as well.
@@ -1324,20 +1452,20 @@ function renderSubagents(parent, node) {
1324
1452
  check(allowedTools,available?name:`${name} (unavailable — remove to repair)`,toolOptions.selected.includes(name),enabled=>{role.tools=enabled?[...new Set([...toolOptions.selected,name])]:toolOptions.selected.filter(t=>t!==name);if(!toolOptions.delegated)policy.toolInheritance='restricted';});
1325
1453
  }
1326
1454
  const contracts=disclosure(body,'Role contracts');jsonField(contracts,'Input schema',role.inputSchema,value=>{role.inputSchema=value;});jsonField(contracts,'Output schema',role.outputSchema,value=>{role.outputSchema=value;});
1327
- const remove=el('button','Remove role');remove.onclick=()=>mutate(()=>{set({roles:policy.roles.filter(r=>r!==role)});pruneRoutes(node);},true);body.append(remove);
1455
+ const remove=el('button','Remove Role');remove.onclick=()=>mutate(()=>{set({roles:policy.roles.filter(r=>r!==role)});pruneRoutes(node);},true);body.append(remove);
1328
1456
  }
1329
- const add=el('button','Add role');add.onclick=()=>mutate(()=>{set({roles:[...(policy.roles||[]),{id:`role-${crypto.randomUUID().slice(0,8)}`,name:'Repository Researcher',instruction:'Research the bounded task and return findings.',capabilities:{...effectiveCaps(node),filesystem:effectiveCaps(node).filesystem==='none'?'none':'read',shell:effectiveCaps(node).shell==='disabled'?'disabled':'read-only',git:effectiveCaps(node).git==='none'?'none':'read'}}]});requireWorktree();},true);roles.append(add);
1457
+ const add=el('button','Add Role');add.onclick=()=>mutate(()=>{set({roles:[...(policy.roles||[]),{id:`role-${crypto.randomUUID().slice(0,8)}`,name:'Repository Researcher',instruction:'Research the bounded task and return findings.',capabilities:{...effectiveCaps(node),filesystem:effectiveCaps(node).filesystem==='none'?'none':'read',shell:effectiveCaps(node).shell==='disabled'?'disabled':'read-only',git:effectiveCaps(node).git==='none'?'none':'read'}}]});requireWorktree();},true);roles.append(add);
1330
1458
  }
1331
1459
  function renderControlInspector(parent,node) {
1332
1460
  if(node.type==='join')choice(parent,'Wait for branches',node.join?.mode||'all',['all','any'],value=>{node.join={mode:value};});
1333
1461
  if(node.type==='loop')field(parent,'Maximum loop iterations',node.loop?.maxIterations??3,value=>{node.loop={maxIterations:value};},{type:'number',min:1});
1334
1462
  if(node.type==='condition') {
1335
- choice(parent,'Source node',node.condition?.source||'', [{value:'',label:'Choose a predecessor'},...Object.values(state.graph.nodes).filter(n=>n.id!==node.id).map(n=>({value:n.id,label:n.name}))],value=>{node.condition={path:'',equals:true,...node.condition,source:value};});
1463
+ choice(parent,'Source step',node.condition?.source||'', [{value:'',label:'Choose a predecessor'},...Object.values(state.graph.nodes).filter(n=>n.id!==node.id).map(n=>({value:n.id,label:n.name}))],value=>{node.condition={path:'',equals:true,...node.condition,source:value};});
1336
1464
  field(parent,'Output field path',node.condition?.path||'',value=>{node.condition={source:'',equals:true,...node.condition,path:value};});
1337
1465
  jsonField(parent,'Equals',node.condition?.equals??true,value=>{node.condition={source:'',path:'',...node.condition,equals:value};});
1338
1466
  }
1339
1467
  if(node.type==='action') {choice(parent,'Action',node.action?.kind||'command',['command','tests','git'],value=>{node.action={command:'',...node.action,kind:value};});field(parent,'Command',node.action?.command||'',value=>{node.action={kind:'command',...node.action,command:value};},{multiline:true,maxLength:100000});}
1340
- if(node.type==='parallel')parent.append(el('p','All completed connections become ready. A Parallel node is optional for ordinary outcome fan-out.', 'help'));
1468
+ if(node.type==='parallel')parent.append(el('p','All completed connections become ready. A Parallel step is optional for ordinary outcome fan-out.', 'help'));
1341
1469
  if(node.type==='approval')parent.append(el('p','The CLI asks for approval. Route approved and rejected separately.', 'help'));
1342
1470
  }
1343
1471
  function setAgentModifier(node, kind, value) {
@@ -1367,7 +1495,7 @@ function scalarField(parent, label, value, update) {
1367
1495
  function renderModifiers(parent, node) {
1368
1496
  if (node.agentRole === 'orchestrator') return;
1369
1497
  const group = disclosure(parent, 'Modifiers', Boolean(node.modifiers && Object.keys(node.modifiers).length));
1370
- group.append(el('p','Add behavior to this agent without extra control nodes.','help'));
1498
+ group.append(el('p','Add behavior to this agent without extra control steps.','help'));
1371
1499
  check(group, 'Condition modifier', Boolean(node.modifiers?.condition), enabled => setAgentModifier(node,'condition',enabled ? {path:'approved',equals:true} : undefined));
1372
1500
  if (node.modifiers?.condition) {
1373
1501
  const config = node.modifiers.condition;
@@ -1378,11 +1506,11 @@ function renderModifiers(parent, node) {
1378
1506
  check(group, 'Loop modifier', Boolean(node.modifiers?.loop), enabled => setAgentModifier(node,'loop',enabled ? {maxIterations:3,until:{outcome:node.completion?.mode==='outcomes' ? node.completion.outcomes[0] : node.completion?.outcome || 'completed'}} : undefined));
1379
1507
  if (node.modifiers?.loop) {
1380
1508
  const config = node.modifiers.loop;
1381
- field(group,'Maximum attempts',config.maxIterations,value=>{config.maxIterations=value;},{type:'number',min:1,max:100});
1509
+ field(group,'Maximum tries',config.maxIterations,value=>{config.maxIterations=value;},{type:'number',min:1,max:100});
1382
1510
  choice(group,'Exit when',config.until.outcome!==undefined?'outcome':'output',[{value:'outcome',label:'Agent returns an outcome'},{value:'output',label:'Output field matches a value'}],value=>{setAgentModifier(node,'loop',{...config,until:value==='outcome'?{outcome:node.completion?.mode==='outcomes'?node.completion.outcomes[0]:node.completion?.outcome||'completed'}:{path:'finished',equals:true}});});
1383
1511
  if (config.until.outcome !== undefined) choice(group,'Exit outcome',config.until.outcome,node.completion?.mode==='outcomes'?node.completion.outcomes:[node.completion?.outcome||'completed'],value=>{setAgentModifier(node,'loop',{...config,until:{outcome:value}});});
1384
1512
  else { field(group,'Exit output field',config.until.path,value=>{config.until.path=value.trim();}); scalarField(group,'Exit value (JSON)',config.until.equals,value=>{config.until.equals=value;}); }
1385
- group.append(el('p','Repeat this agent until the exit condition matches. If the attempt limit is reached, stop with an exhausted result instead of continuing as if successful.','help'));
1513
+ group.append(el('p','Repeat this agent until the exit condition matches. If the try limit is reached, stop with an exhausted result instead of continuing as if successful.','help'));
1386
1514
  }
1387
1515
  choice(group,'Parallel modifier',node.modifiers?.parallel?.mode||'off',[{value:'off',label:'Off'},{value:'branches',label:'Connected downstream agents'},{value:'copies',label:'Copies of this agent'}],mode=>setAgentModifier(node,'parallel',mode==='off'?undefined:{mode,maxConcurrent:2,...(mode==='copies'?{copies:2}:{})}));
1388
1516
  if (node.modifiers?.parallel) {
@@ -1406,29 +1534,29 @@ function hasRetryCycle(graph) {
1406
1534
  function retryLimitHelp(parent, graph) {
1407
1535
  if (!hasRetryCycle(graph) || graph.limits?.maxNodeVisits || graph.limits?.wallTimeMs) return;
1408
1536
  const box = el('div', undefined, 'cycle-help');
1409
- box.append(el('strong', 'This graph includes a retry cycle'), el('p', 'A return connection can run the same agents repeatedly, so the run needs a ceiling: set a maximum number of visits per node, or give the run a wall clock. Without one the cycle never ends.'));
1410
- const fix = el('button', 'Limit each node to 3 visits');
1537
+ box.append(el('strong', 'This workflow includes a retry cycle'), el('p', 'A return connection can run the same agents repeatedly, so the run needs a ceiling: set a maximum number of visits per step, or give the run a wall clock. Without one the cycle never ends.'));
1538
+ const fix = el('button', 'Limit Each Step to 3 Visits');
1411
1539
  fix.onclick = () => mutate(() => { graph.limits = {...graph.limits, maxNodeVisits:3}; }, true);
1412
- const clock = el('button', 'Give the run 30 minutes');
1540
+ const clock = el('button', 'Give the Run 30 Minutes');
1413
1541
  clock.onclick = () => mutate(() => { graph.limits = {...graph.limits, wallTimeMs:30 * 60_000}; }, true);
1414
1542
  box.append(fix, clock); parent.append(box);
1415
1543
  }
1416
1544
  function renderInspector() {
1417
1545
  // A redraw replaces a full-screen prompt editor, so its backdrop goes with it.
1418
1546
  document.body?.classList?.remove?.('prompt-fullscreen'); for (const backdrop of document.querySelectorAll?.('.prompt-backdrop') ?? []) backdrop.remove();
1419
- const parent = $('inspector-body'); parent.replaceChildren(); const graph = state.graph; if (!graph) { parent.append(el('p', 'Create a graph or choose a preset.', 'help')); return; }
1547
+ const parent = $('inspector-body'); parent.replaceChildren(); const graph = state.graph; if (!graph) { parent.append(el('p', 'Create a workflow or choose a preset.', 'help')); return; }
1420
1548
  if (state.selectedEdge && !graph.edges.includes(state.selectedEdge)) state.selectedEdge = null;
1421
- const node = graph.nodes[state.selected]; $('inspector-title').textContent = node ? 'Node settings' : 'Graph settings';
1549
+ const node = graph.nodes[state.selected]; $('inspector-title').textContent = node ? 'Step settings' : 'Workflow settings';
1422
1550
  $('graph-settings').hidden = !node && !state.selectedEdge && selectedNodes().length <= 1;
1423
1551
  retryLimitHelp(parent, graph);
1424
1552
  if (state.selectedEdge) renderEdgeInspector(parent, state.selectedEdge);
1425
1553
  else if (selectedNodes().length > 1) renderBulkInspector(parent,selectedNodes());
1426
1554
  else if (!node) {
1427
1555
  const panels = inspectorTabs(parent, ['general', 'behavior', 'advanced']); const general = panels.general;
1428
- field(general, 'Graph name', graph.name, value => { graph.name = value; renderList(); }, {maxLength:200});
1429
- const meta = el('p', `${graph.id} · Revision ${graph.revision}`, 'mono graph-meta'); meta.title = graph.id; general.append(meta);
1556
+ field(general, 'Workflow name', graph.name, value => { graph.name = value; renderList(); }, {maxLength:200});
1557
+ const meta = el('p', `${graph.id} · Version ${graph.revision}`, 'mono graph-meta'); meta.title = graph.id; general.append(meta);
1430
1558
  if (graph.id === 'default') general.append(el('p', 'Duplicate this bundled preset to save your customization.', 'help'));
1431
- const start = field(general,'Starting node',graph.nodes[graph.entry]?.name || '',()=>{}); start.disabled=true; explain(start,'The Orchestrator is optional. Deleting the starting node promotes its first remaining connected successor, or the first remaining node if none is connected.');
1559
+ const start = field(general,'Starting step',graph.nodes[graph.entry]?.name || '',()=>{}); start.disabled=true; explain(start,'The Orchestrator is optional. Deleting the starting step promotes its first remaining connected successor, or the first remaining step if none is connected.');
1432
1560
  field(general, 'Description', graph.metadata?.description, value => {graph.metadata={...graph.metadata,description:value};}, {multiline:true,maxLength:2000});
1433
1561
  const widgetGroup = disclosure(panels.behavior, 'Widgets', true);
1434
1562
  widgetGroup.append(el('p','Widgets appear as sections beside the run plan. Each description tells the agents what belongs in the widget; during runs the agents keep its value current.','help'));
@@ -1436,18 +1564,18 @@ function renderInspector() {
1436
1564
  const label = `Widget ${index + 1} name`;
1437
1565
  field(widgetGroup, label, widget.name, value => { widget.name = value; }, {maxLength:80,refresh:true});
1438
1566
  field(widgetGroup, `Widget ${index + 1} description`, widget.description, value => { widget.description = value; }, {multiline:true,maxLength:1000});
1439
- const remove = el('button','Remove widget','danger');
1567
+ const remove = el('button','Remove Widget','danger');
1440
1568
  remove.onclick = () => mutate(() => { graph.widgets = (graph.widgets ?? []).filter(item => item !== widget); if (!graph.widgets.length) delete graph.widgets; }, true);
1441
1569
  widgetGroup.append(remove);
1442
1570
  }
1443
1571
  if ((graph.widgets ?? []).length < 5) {
1444
- const add = el('button','Add widget');
1572
+ const add = el('button','Add Widget');
1445
1573
  add.onclick = () => mutate(() => { graph.widgets = [...(graph.widgets ?? []), { id: `widget-${crypto.randomUUID().slice(0,8)}`, name: '', description: '' }]; }, true);
1446
1574
  widgetGroup.append(add);
1447
- widgetGroup.append(el('p','Up to 5 widgets per graph. Names and descriptions are required before saving.','help'));
1575
+ widgetGroup.append(el('p','Up to 5 widgets per workflow. Names and descriptions are required before saving.','help'));
1448
1576
  } else widgetGroup.append(el('p','Widget limit reached (5).','help'));
1449
- const visits = field(panels.behavior, 'Maximum visits per node', graph.limits?.maxNodeVisits ?? 0, value => {graph.limits={...graph.limits}; if(value===undefined || value===0) delete graph.limits.maxNodeVisits; else graph.limits.maxNodeVisits=value;}, {type:'number',optional:true,min:0,max:100,refresh:true});
1450
- explain(visits,'0 means unlimited, which is the default. A return connection repeats a node, so a graph with one needs a ceiling: a visit limit, or a wall clock. An agent Loop modifier has its own attempt limit.');
1577
+ const visits = field(panels.behavior, 'Maximum visits per step', graph.limits?.maxNodeVisits ?? 0, value => {graph.limits={...graph.limits}; if(value===undefined || value===0) delete graph.limits.maxNodeVisits; else graph.limits.maxNodeVisits=value;}, {type:'number',optional:true,min:0,max:100,refresh:true});
1578
+ explain(visits,'0 means unlimited, which is the default. A return connection repeats a step, so a workflow with one needs a ceiling: a visit limit, or a wall clock. An agent Loop modifier has its own try limit.');
1451
1579
  // Per-graph desktop settings render here; a browser-launched studio has no host bridge and skips them.
1452
1580
  window.AndorraEmbed?.inspector?.(general);
1453
1581
  const advanced = panels.advanced; jsonField(advanced, 'Run limits', graph.limits, value => {graph.limits=value;}); jsonField(advanced,'Run input schema',graph.inputSchema,value=>{graph.inputSchema=value;}); jsonField(advanced,'Run state schema',graph.stateSchema,value=>{graph.stateSchema=value;});
@@ -1455,24 +1583,24 @@ function renderInspector() {
1455
1583
  const panels = inspectorTabs(parent, node.type === 'agent' ? ['general', 'model', 'behavior', 'advanced'] : outcomes(node).length ? ['general', 'behavior', 'advanced'] : ['general', 'advanced']);
1456
1584
  const general = panels.general; field(general, 'Name', node.name, value => {node.name=value;}, {maxLength:200});
1457
1585
  if (node.type === 'agent') {
1458
- if(node.agentRole==='orchestrator'){general.append(el('p','Orchestrator - optional starting Agent for research, clarification and handoff. Remove it to start directly at the next node.','help'));}
1586
+ if(node.agentRole==='orchestrator'){general.append(el('p','Orchestrator: optional starting Agent for research, clarification and handing work on. Remove it to start directly at the next step.','help'));}
1459
1587
  const prompt = promptField(general, 'Prompt', node.instruction ?? node.prompt ?? '', value => {node.instruction=value; delete node.prompt;}, { placeholder: 'Type / to add a skill' });
1460
- explain(prompt, 'Edit the instructions for this agent. Save the graph to use this prompt in future runs. This replaces this node\'s instructions; project guidance, advanced system instructions and runtime permissions still apply. Type / to add a skill: the node loads every /skill its prompt names when it runs. A skill this machine does not have is flagged here and skipped at run time; it never stops the graph.');
1588
+ explain(prompt, 'Edit the instructions for this agent. Save the workflow to use this prompt in future runs. This replaces this step\'s instructions; project guidance, advanced system instructions and runtime permissions still apply. Type / to add a skill: the step loads every /skill its prompt names when it runs. A skill this machine does not have is flagged here and skipped at run time; it never stops the workflow.');
1461
1589
  explain(check(general, 'Jev decisions', node.jevEnabled === true, value => { if (value) node.jevEnabled = true; else delete node.jevEnabled; }), 'Off unless ticked. When Jev is on, it assists this agent with routing decisions. The coding model still implements the task; sign-in, quota and runtime permissions apply.');
1462
1590
  const model = panels.model;
1463
1591
  modelFields(model, node, value => {node.provider=value.provider; node.model=value.model;});
1464
1592
  const conversation = choice(model, 'Conversation', node.contextPolicy?.conversation ?? 'reuse', [{value:'reuse',label:'Reuse with the same provider and model'}, {value:'isolate',label:'Start an isolated conversation'}], value => {node.contextPolicy={...node.contextPolicy,conversation:value};});
1465
- explain(conversation, 'Reuse continues from the preceding Agent with this node\'s instructions and permissions. Different providers or models start fresh. Branches receive separate copies of their shared history. Provider caching and token savings depend on the model service.');
1593
+ explain(conversation, 'Reuse continues from the preceding Agent with this step\'s instructions and permissions. Different providers or models start fresh. Branches receive separate copies of their shared history. Provider caching and token savings depend on the model service.');
1466
1594
  const skills = choice(model, 'Skill inheritance', node.contextPolicy?.skillInheritance ?? 'inherit', [{value:'inherit',label:'Inherit active workflow skills'}, {value:'none',label:'Do not inherit skills'}], value => {node.contextPolicy={...node.contextPolicy,skillInheritance:value};});
1467
- explain(skills, 'Inherits skills activated earlier in this graph, even when the conversation is isolated or the model changes. Each Agent loads the skill for its own role. Opting out also isolates predecessor conversation text to avoid leaking loaded skills; it never changes tool or approval permissions.');
1595
+ explain(skills, 'Inherits skills activated earlier in this workflow, even when the conversation is isolated or the model changes. Each Agent loads the skill for its own role. Opting out also isolates predecessor conversation text to avoid leaking loaded skills; it never changes tool or approval permissions.');
1468
1596
  renderCompletion(section(panels.behavior, node.agentRole === 'orchestrator' ? 'Routing' : 'Outcomes and conditions'), node);
1469
1597
  renderModifiers(panels.behavior, node);
1470
1598
  const advanced = panels.advanced;
1471
- const caps = disclosure(advanced, 'Permissions'); capabilities(caps,node.capabilities,value=>{node.capabilities=value;}); caps.append(el('p', 'Restricted filesystem or Git policies disable the unsandboxed host shell. Read-only Agents use filesystem tools and supported Git read operations. Browser and deployment access require compatible runtime tools; configuration does not supply credentials.', 'help'));
1599
+ const caps = disclosure(advanced, 'Permissions'); capabilities(caps,node.capabilities,value=>{node.capabilities=value;}); caps.append(el('p', 'Shell grants the unsandboxed host shell on its own; Filesystem and Git govern the file-writing and Git tools. Commands still follow the permission mode of the run. Browser and deployment access require compatible runtime tools; configuration does not supply credentials.', 'help'));
1472
1600
  const context = disclosure(advanced, 'Context sharing'); check(context,'Include previous task summaries',node.contextPolicy?.history??false,value=>{node.contextPolicy={...node.contextPolicy,history:value};}); choice(context,'Visible predecessor state',node.contextPolicy?.predecessors||'none',['none','direct','all'],value=>{node.contextPolicy={...node.contextPolicy,predecessors:value};}); field(context,'Maximum context characters',node.contextPolicy?.maxChars??32000,value=>{node.contextPolicy={...node.contextPolicy,maxChars:value};},{type:'number',min:1}); jsonField(context, 'Input mapping', node.inputs, value=>{node.inputs=value;});
1473
1601
  renderSubagents(disclosure(advanced,'Subagents'),node);
1474
1602
  const limits = disclosure(advanced,'Execution limits');
1475
- for (const [key,label,defaultValue] of [['maxContextChars','Context characters',120000],['maxCompletionRepairs','Completion repair attempts',2]]) field(limits,label,node.limits?.[key] ?? defaultValue,value=>{node.limits={...node.limits,[key]:value}; delete node.limits.maxTokens;},{type:'number',min:key==='maxCompletionRepairs'?0:1});
1603
+ for (const [key,label,defaultValue] of [['maxContextChars','Context characters',120000],['maxCompletionRepairs','Completion repair tries',2]]) field(limits,label,node.limits?.[key] ?? defaultValue,value=>{node.limits={...node.limits,[key]:value}; delete node.limits.maxTokens;},{type:'number',min:key==='maxCompletionRepairs'?0:1});
1476
1604
  // Iterations and wall time default to blank, and blank means unlimited. The editor must
1477
1605
  // not invent a bound the author never chose: a task that legitimately runs for hours
1478
1606
  // should not be cut short, and a person answering a question is never on the clock.
@@ -1483,28 +1611,32 @@ function renderInspector() {
1483
1611
  // Tool calls default to blank, and blank means unlimited: an absent limit is only
1484
1612
  // written when the field is cleared, so a node keeps its ceiling once one is set.
1485
1613
  field(limits,'Tool calls (blank = unlimited)',node.limits?.maxToolCalls,value=>{node.limits={...node.limits,maxToolCalls:value}; if(value===undefined)delete node.limits.maxToolCalls;},{type:'number',min:0,optional:true,placeholder:'Unlimited'});
1486
- skillPrompt(field(advanced,'System prompt',node.systemPrompt ?? node.prompt,value=>{node.systemPrompt=value; delete node.prompt;},{multiline:true,maxLength:100000})); jsonField(advanced,'Input schema (JSON Schema)',node.inputSchema,value=>{node.inputSchema=value;}); jsonField(advanced,'Output schema (JSON Schema)',node.outputSchema,value=>{node.outputSchema=value;}); field(advanced,'Retry attempts',node.retry?.maxAttempts??1,value=>{node.retry={...node.retry,maxAttempts:value};},{type:'number',min:1}); const fallback=disclosure(advanced,'Fallback model'); modelFields(fallback,node.retry?.fallback||{},value=>{node.retry={maxAttempts:1,...node.retry,fallback:value.provider?{provider:value.provider,model:value.model}:undefined};});
1614
+ skillPrompt(field(advanced,'System prompt',node.systemPrompt ?? node.prompt,value=>{node.systemPrompt=value; delete node.prompt;},{multiline:true,maxLength:100000})); jsonField(advanced,'Input schema (JSON Schema)',node.inputSchema,value=>{node.inputSchema=value;}); jsonField(advanced,'Output schema (JSON Schema)',node.outputSchema,value=>{node.outputSchema=value;}); field(advanced,'Retries',node.retry?.maxAttempts??1,value=>{node.retry={...node.retry,maxAttempts:value};},{type:'number',min:1}); const fallback=disclosure(advanced,'Fallback model'); modelFields(fallback,node.retry?.fallback||{},value=>{node.retry={maxAttempts:1,...node.retry,fallback:value.provider?{provider:value.provider,model:value.model}:undefined};});
1487
1615
  field(advanced,'Executor','react-basic',()=>{}).disabled=true;
1488
1616
  const tools = disclosure(advanced,'Tool allowlist');
1489
1617
  for (const name of [...new Set([...state.tools.map(t=>typeof t==='string'?t:t.name||t.id),...(node.tools||[])])]) check(tools,name,node.tools===undefined||node.tools.includes(name),enabled=>{const all=state.tools.map(t=>typeof t==='string'?t:t.name||t.id); node.tools=enabled?[...new Set([...(node.tools??all),name])]:(node.tools??all).filter(t=>t!==name);});
1490
- const saveDefinition = el('button','Save agent variant'); saveDefinition.onclick=()=>saveAgentVariant(node); general.append(saveDefinition);
1491
- } else { general.append(el('p', 'This control node does not call a model and has no agent prompt.', 'help')); renderControlInspector(general,node); }
1618
+ const saveDefinition = el('button','Save to Library'); saveDefinition.onclick=()=>saveAgentVariant(node); general.append(saveDefinition);
1619
+ } else { general.append(el('p', 'This control step does not call a model and has no agent prompt.', 'help')); renderControlInspector(general,node); }
1492
1620
  if (panels.behavior) routes(panels.behavior,node);
1493
1621
  const layout = disclosure(panels.advanced,'Position'); const p=position(node,Object.keys(graph.nodes).indexOf(node.id)); field(layout,'X',p.x,value=>{node.position={...p,x:value};},{type:'number',min:-100000,max:100000,refresh:true});field(layout,'Y',p.y,value=>{node.position={...p,y:value};},{type:'number',min:-100000,max:100000,refresh:true});
1494
- const remove=el('button','Remove node','danger');remove.disabled=Object.keys(graph.nodes).length===1;remove.onclick=()=>{void askConfirm({title:`Remove ${node.name}?`,message:'The node and its connections are removed from this graph. Undo brings them back.',confirmLabel:'Remove node',tone:'danger'}).then(confirmed=>{if(confirmed&&state.graph?.nodes?.[node.id])removeNodes(new Set([node.id]));});};panels.advanced.append(remove);
1622
+ const remove=el('button','Remove Step','danger');remove.disabled=Object.keys(graph.nodes).length===1;remove.onclick=()=>{void askConfirm({title:`Remove ${node.name}?`,message:'The step and its connections are removed from this workflow. Undo brings them back.',confirmLabel:'Remove Step',tone:'danger'}).then(confirmed=>{if(confirmed&&state.graph?.nodes?.[node.id])removeNodes(new Set([node.id]));});};panels.advanced.append(remove);
1495
1623
  }
1496
1624
  const validation=section(parent,'Validation');validation.id='validation';renderValidation();
1497
1625
  window.AndorraStudio?.inspector?.(parent, node);
1498
1626
  }
1499
1627
  function render() { renderHeading(); renderList(); renderLibrary(); renderCanvas(); renderInspector(); scheduleValidation(); queueDraft(); }
1500
- async function openGraph(id) {
1501
- if (state.saving) { status('Wait for the current save before opening another graph.'); return; }
1502
- if (state.dirty && !await askConfirm(DISCARD_QUESTION)) return;
1503
- try { const opened = await api(`/api/graphs/${encodeURIComponent(id)}`); const capMoved = hasSubagentCap(opened); state.graph = dropLegacyTokenFields(opened); const migrated = state.graph.editorMigration === true; state.dirty = migrated || capMoved; delete state.graph.editorMigration; clearSelection(); state.undo = []; state.redo = []; state.pendingProviderNodes = null; render(); fit(); status(migrated ? 'Legacy graph upgraded in editor - Save to persist a new revision' : capMoved ? 'Orchestrator Max subagents moved to Advanced > Subagents - Save to persist a new revision' : 'Graph loaded'); } catch (error) { status(error.message, true); }
1628
+ // `options.discard` skips the question about unsaved edits: Graph Manager passes it once it has
1629
+ // established that loading loses nothing, or the user has asked for the load. Resolves to whether
1630
+ // the graph was opened.
1631
+ async function openGraph(id, options = {}) {
1632
+ if (state.saving) { status('Wait for the current save before opening another workflow.'); return false; }
1633
+ if (state.dirty && !options.discard && !await askConfirm(DISCARD_QUESTION)) return false;
1634
+ // A caller that already holds the graph (`options.fetched`) is applied without a request, so nothing can change the canvas between its own checks and this replacement.
1635
+ try { const opened = options.fetched === undefined ? await api(`/api/graphs/${encodeURIComponent(id)}`) : options.fetched; const capMoved = hasSubagentCap(opened); state.graph = dropLegacyTokenFields(opened); const migrated = state.graph.editorMigration === true; state.dirty = migrated || capMoved; delete state.graph.editorMigration; clearSelection(); state.undo = []; state.redo = []; state.pendingProviderNodes = null; render(); fit(); status(migrated ? 'This workflow was updated to the current format. Save to keep it.' : capMoved ? 'Orchestrator Max subagents moved to Advanced > Subagents. Save to keep it.' : 'Workflow loaded'); graphOpened(options.reason || 'open'); return true; } catch (error) { status(error.message, true); return false; }
1504
1636
  }
1505
1637
  function newId() { return `graph-${crypto.randomUUID()}`; }
1506
1638
  function newGraph(duplicate = false, discarded = false) {
1507
- if (state.saving) { status('Wait for the current save before creating another graph.'); return; }
1639
+ if (state.saving) { status('Wait for the current save before creating another workflow.'); return; }
1508
1640
  if (!canCreateGraph()) { status(FREE_CREATE_TIP, true); return; }
1509
1641
  // Unsaved edits are asked about first; a clean graph is replaced at once.
1510
1642
  if (state.dirty && !discarded) { void askConfirm(DISCARD_QUESTION).then(discard => { if (discard) newGraph(duplicate, true); }); return; }
@@ -1512,25 +1644,26 @@ function newGraph(duplicate = false, discarded = false) {
1512
1644
  else if (freeTier()) {
1513
1645
  // A free graph starts from the Software Engineer alone: the Orchestrator is a Premium node.
1514
1646
  const engineerPreset=state.definitions.find(definition=>definition.id==='software-engineer')?.node;
1515
- if(!engineerPreset){status('Starting presets are unavailable. Reload the Graph Builder and try again.',true);return;}
1516
- state.graph={schemaVersion:3,id:newId(),name:'Untitled graph',revision:0,entry:'engineer',nodes:{engineer:{...copy(engineerPreset),id:'engineer',position:{x:0,y:0}},done:{id:'done',name:'Done',type:'end',position:{x:320,y:0}}},edges:[{id:'engineer-done',source:'engineer',target:'done',outcome:'completed'}]};
1647
+ if(!engineerPreset){status('Starting presets are unavailable. Reload the Workflow Editor and try again.',true);return;}
1648
+ state.graph={schemaVersion:3,id:newId(),name:'Untitled workflow',revision:0,entry:'engineer',nodes:{engineer:{...copy(engineerPreset),id:'engineer',position:{x:0,y:0}},done:{id:'done',name:'Done',type:'end',position:{x:320,y:0}}},edges:[{id:'engineer-done',source:'engineer',target:'done',outcome:'completed'}]};
1517
1649
  }
1518
1650
  else {
1519
1651
  const orchestratorPreset=state.definitions.find(definition=>definition.node.agentRole==='orchestrator')?.node;
1520
1652
  const engineerPreset=state.definitions.find(definition=>definition.id==='software-engineer')?.node;
1521
- if(!orchestratorPreset || !engineerPreset){status('Starting presets are unavailable. Reload the Graph Builder and try again.',true);return;}
1653
+ if(!orchestratorPreset || !engineerPreset){status('Starting presets are unavailable. Reload the Workflow Editor and try again.',true);return;}
1522
1654
  const orchestrator={...copy(orchestratorPreset),id:'orchestrator',position:{x:0,y:0}};
1523
1655
  const engineer={...copy(engineerPreset),id:'engineer',position:{x:320,y:0}};
1524
1656
  const inputMapping={originalTask:'$run.input.task'};
1525
1657
  for(const key of ['taskInstruction','requirements','acceptanceCriteria','designConsiderations','codebaseFindings']) inputMapping[key]=`$source.output.${key}`;
1526
- state.graph={schemaVersion:3,id:newId(),name:'Untitled graph',revision:0,entry:'orchestrator',nodes:{orchestrator,engineer,done:{id:'done',name:'Done',type:'end',position:{x:640,y:0}}},edges:[{id:'orchestrator-engineer',source:'orchestrator',target:'engineer',outcome:'completed',inputMapping},{id:'engineer-done',source:'engineer',target:'done',outcome:'completed'}]};
1658
+ state.graph={schemaVersion:3,id:newId(),name:'Untitled workflow',revision:0,entry:'orchestrator',nodes:{orchestrator,engineer,done:{id:'done',name:'Done',type:'end',position:{x:640,y:0}}},edges:[{id:'orchestrator-engineer',source:'orchestrator',target:'engineer',outcome:'completed',inputMapping},{id:'engineer-done',source:'engineer',target:'done',outcome:'completed'}]};
1527
1659
  }
1528
1660
  // A duplicate copies the open graph, providerless nodes included, so its unmet provider
1529
1661
  // requirements travel with it; an unrelated new graph starts without any.
1530
1662
  state.dirty = true; clearSelection(); state.undo = []; state.redo = [];
1531
1663
  state.untouched = JSON.stringify(state.graph);
1532
1664
  state.pendingProviderNodes = duplicate ? new Set(state.pendingProviderNodes ?? []) : null;
1533
- render(); fit(); status('New graph - Customize your agent and save your first revision');
1665
+ render(); fit(); status('New workflow · Customize your agent, then save');
1666
+ graphOpened(duplicate ? 'duplicate' : 'new');
1534
1667
  }
1535
1668
  // The settings a new Agent starts from, whether it is dropped on the canvas or added to the list.
1536
1669
  function blankAgentSettings() {
@@ -1549,7 +1682,7 @@ function addNode(type, definition, dropPosition) {
1549
1682
  const canResearch = definition.capabilities?.filesystem !== 'none' &&
1550
1683
  (definition.tools === undefined || ['Read','Glob','Grep','repo_explore'].some(tool => researchTools.includes(tool)));
1551
1684
  if (!canResearch) {
1552
- status('Cannot apply this Orchestrator variant: enable filesystem read access and at least one research tool (Read, Glob, Grep, or repo_explore), then save the variant again. Choose another Orchestrator variant to continue.', true);
1685
+ status('Cannot apply this saved Orchestrator: enable filesystem read access and at least one research tool (Read, Glob, Grep, or repo_explore), then save it again. Choose another saved Orchestrator to continue.', true);
1553
1686
  return;
1554
1687
  }
1555
1688
  // Saved definitions can predate intake's required research and clarification.
@@ -1575,7 +1708,7 @@ function addNode(type, definition, dropPosition) {
1575
1708
  clearSelection(); state.selected = existing.id; state.selectedIds = [existing.id];
1576
1709
  }, true);
1577
1710
  showInspector();
1578
- status('Starting Orchestrator definition applied. Matching routes and handoffs were kept; validate mappings before saving. Undo restores the previous definition.');
1711
+ status('Saved Orchestrator applied. Matching routes and connections were kept; check their inputs before saving. Undo restores the previous definition.');
1579
1712
  return;
1580
1713
  }
1581
1714
  }
@@ -1623,9 +1756,9 @@ function libraryDialog(title, fields, submit, submitLabel = 'Save') {
1623
1756
  form.append(el('h3', title));
1624
1757
  for (const [label, input] of fields) { const row = el('label', label); row.append(input); form.append(row); }
1625
1758
  const error = el('p', '', 'help'), actions = el('div', undefined, 'library-dialog-actions');
1626
- const cancel = el('button', 'Cancel'); cancel.type = 'button'; cancel.onclick = () => dialog.close();
1627
- const save = el('button', submitLabel); save.type = 'submit'; actions.append(cancel, save); form.append(error, actions);
1628
- form.onsubmit = async event => { event.preventDefault(); save.disabled = true; try { await submit(); dialog.close(); } catch (failure) { error.textContent = failure.message; } finally { save.disabled = false; } };
1759
+ const cancel = el('button', 'Cancel'); cancel.type = 'button'; cancel.onclick = () => closeDialog(dialog);
1760
+ const save = el('button', submitLabel, 'primary'); save.type = 'submit'; actions.append(cancel, save); form.append(error, actions);
1761
+ form.onsubmit = async event => { event.preventDefault(); save.disabled = true; try { await submit(); closeDialog(dialog); } catch (failure) { error.textContent = failure.message; } finally { save.disabled = false; } };
1629
1762
  dialog.onclose = () => dialog.remove(); dialog.append(form); document.body.append(dialog); dialog.showModal(); fields[0]?.[1].focus();
1630
1763
  }
1631
1764
  // The browser's `required` accepts whitespace, so a name that only trims to nothing is
@@ -1638,9 +1771,9 @@ function requireAgentName(input) {
1638
1771
  function saveAgentVariant(node) {
1639
1772
  const name = el('input'); name.value = node.name; name.required = true; name.maxLength = 200;
1640
1773
  const snapshot = copy(node), id = `definition-${crypto.randomUUID()}`;
1641
- libraryDialog('Save Agent variant', [['Variant name', name]], async () => {
1774
+ libraryDialog('Save agent to library', [['Name', name]], async () => {
1642
1775
  const agentName = requireAgentName(name);
1643
- await writeDefinition({schemaVersion:2, id, name:agentName, description:'', revision:0, node:{...snapshot,name:agentName}}, 'Agent variant saved');
1776
+ await writeDefinition({schemaVersion:2, id, name:agentName, description:'', revision:0, node:{...snapshot,name:agentName}}, 'Saved to library');
1644
1777
  });
1645
1778
  }
1646
1779
  // Truncation counts the field's own unit (UTF-16 code units) but must not cut between the two
@@ -1726,7 +1859,7 @@ async function shareAgent(definition) {
1726
1859
  // Built-in Agents have no Delete. Graphs that already use a deleted Agent keep their own copy.
1727
1860
  async function deleteAgent(definition) {
1728
1861
  if (definition.preset) return;
1729
- if (!confirm(`Delete the Agent "${definition.name}"? Graphs that already use it keep their own copy. This cannot be undone.`)) return;
1862
+ if (!confirm(`Delete the Agent "${definition.name}"? Workflows that already use it keep their own copy. This cannot be undone.`)) return;
1730
1863
  try { await api(`/api/definitions/${encodeURIComponent(definition.id)}`, undefined, { method: 'DELETE' }); }
1731
1864
  catch (error) {
1732
1865
  // A lost response can still have deleted it, so the refreshed list decides what is reported.
@@ -1770,7 +1903,7 @@ async function writeDefinition(payload, saved) {
1770
1903
  function renderLibrary() {
1771
1904
  const container = $('node-library'); container.replaceChildren();
1772
1905
  const query = $('node-search').value.toLowerCase();
1773
- const definitionItem = d => ({name:d.name,type:'agent',description:d.preset ? 'Editable Agent preset' : `Saved variant - r${d.revision}`,node:d.node,definition:d});
1906
+ const definitionItem = d => ({name:d.name,type:'agent',description:d.preset ? 'Editable Agent preset' : `Saved agent · version ${d.revision}`,node:d.node,definition:d});
1774
1907
  const addItem = (parent, item) => {
1775
1908
  // A library item drags onto the canvas; a click, Enter or Space adds it, so the library stays
1776
1909
  // usable without a pointer. The type icon is placed first by the stylesheet's grid.
@@ -1793,7 +1926,7 @@ function renderLibrary() {
1793
1926
  const freeRefusal = freeNodeRefusal([{ type: item.type, agentRole: item.node?.agentRole }]);
1794
1927
  if (freeRefusal) button.title = freeRefusal;
1795
1928
  button.disabled = cannotAdd && !item.definition; button.draggable = !button.disabled && !freeRefusal;
1796
- button.onclick = () => { if (cannotAdd) { status(state.graph ? 'Graph node limit reached.' : 'Open a graph to add this Agent.', true); return; } addNode(item.type, item.node); };
1929
+ button.onclick = () => { if (cannotAdd) { status(state.graph ? 'Workflow step limit reached.' : 'Open a workflow to add this Agent.', true); return; } addNode(item.type, item.node); };
1797
1930
  button.ondragstart = event => { event.dataTransfer.setData('application/andorra-node', JSON.stringify({name:item.name,type:item.type,node:item.node})); event.dataTransfer.effectAllowed = 'copy'; };
1798
1931
  row.append(button);
1799
1932
  // An Agent's actions are secondary, so they open from a right-click on the row (which the
@@ -1836,15 +1969,52 @@ function renderLibrary() {
1836
1969
  if (agents) agents.append(el('p','Select an Agent to configure Condition, Loop, and Parallel modifiers.','help'));
1837
1970
  section(container,'control','Control',['join'].map(type=>({name:type.charAt(0).toUpperCase()+type.slice(1),type,description:{condition:'Branch on run state',loop:'Bounded repetition',parallel:'Explicit fan-out',join:'Wait for all or any branches'}[type]})));
1838
1971
  section(container,'actions','Actions',[{name:'Run command',type:'action',node:{name:'Run command',action:{kind:'command',command:''}},description:'Execute a shell command'},{name:'Run tests',type:'action',node:{name:'Run tests',action:{kind:'tests',command:'npm test'}},description:'Execute project tests'},{name:'Git operation',type:'action',node:{name:'Git operation',action:{kind:'git',command:'git status'}},description:'Run a Git operation'}]);
1839
- section(container,'flow','Flow',[{name:'Human approval',type:'approval',description:'Pause for a decision'},{name:'End',type:'end',description:'Finish this graph path'}]);
1972
+ section(container,'flow','Flow',[{name:'Human approval',type:'approval',description:'Pause for a decision'},{name:'End',type:'end',description:'Finish this workflow path'}]);
1973
+ }
1974
+ // Fit, Arrange and the zoom buttons ease the view to where it is going, over --dur-3 on an ease-in-out
1975
+ // with no overshoot, so the eye can follow the cards. A gesture (pan, pinch, wheel) stops the ease and
1976
+ // takes over at once. Reduced motion, and a page that draws no frames, jump straight there.
1977
+ let viewAnimation = 0, viewTarget = null;
1978
+ function stopViewAnimation() { cancelFrame(viewAnimation); viewAnimation = 0; viewTarget = null; }
1979
+ const easeInOut = t => (t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
1980
+ function viewDuration() { return Math.min(240, parseFloat(themeColor('--dur-3', '200ms')) || 200); }
1981
+ function reducedMotion() { try { return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; } catch { return false; } }
1982
+ /** Ease the view to `target` ({x, y, zoom}); with an `anchor`, that screen point stays still. */
1983
+ function animateView(target, anchor) {
1984
+ stopViewAnimation();
1985
+ if (reducedMotion() || typeof requestAnimationFrame !== 'function' || typeof performance === 'undefined') { Object.assign(state, target); transform(); return; }
1986
+ const from = { x: state.x, y: state.y, zoom: state.zoom }, begin = performance.now(), duration = viewDuration();
1987
+ viewTarget = target;
1988
+ const step = now => {
1989
+ const t = Math.min(1, Math.max(0, (now - begin) / duration)), k = easeInOut(t);
1990
+ // The zoom moves geometrically, so each frame scales by the same ratio.
1991
+ state.zoom = from.zoom * Math.pow(target.zoom / from.zoom, k);
1992
+ if (anchor) { state.x = anchor.x - (anchor.x - from.x) * state.zoom / from.zoom; state.y = anchor.y - (anchor.y - from.y) * state.zoom / from.zoom; }
1993
+ else { state.x = from.x + (target.x - from.x) * k; state.y = from.y + (target.y - from.y) * k; }
1994
+ if (t >= 1) { Object.assign(state, target); viewAnimation = 0; viewTarget = null; } else viewAnimation = requestAnimationFrame(step);
1995
+ transform();
1996
+ };
1997
+ viewAnimation = requestAnimationFrame(step);
1840
1998
  }
1841
- function fit() {
1999
+ function fit(animate = false) {
1842
2000
  if (!state.graph) return; const nodes = Object.values(state.graph.nodes); if (!nodes.length) return;
1843
2001
  const positions = nodes.map(position), minX = Math.min(...positions.map(p => p.x)), minY = Math.min(...positions.map(p => p.y)), maxX = Math.max(...positions.map(p => p.x)) + 210, maxY = Math.max(...positions.map(p => p.y)) + Math.max(...nodes.map(n => 94 + outcomes(n).length * 25));
1844
- state.zoom = Math.min(1, Math.max(.2, Math.min(($('canvas').clientWidth - 90) / (maxX - minX), ($('canvas').clientHeight - 170) / (maxY - minY))));
1845
- state.x = ($('canvas').clientWidth - (maxX - minX) * state.zoom) / 2 - minX * state.zoom; state.y = ($('canvas').clientHeight - (maxY - minY) * state.zoom) / 2 - minY * state.zoom; transform();
2002
+ const zoomed = Math.min(1, Math.max(.2, Math.min(($('canvas').clientWidth - 90) / (maxX - minX), ($('canvas').clientHeight - 170) / (maxY - minY))));
2003
+ const target = { zoom: zoomed, x: ($('canvas').clientWidth - (maxX - minX) * zoomed) / 2 - minX * zoomed, y: ($('canvas').clientHeight - (maxY - minY) * zoomed) / 2 - minY * zoomed };
2004
+ if (animate) { animateView(target); return; }
2005
+ stopViewAnimation(); Object.assign(state, target); transform();
2006
+ }
2007
+ const ZOOM_MIN = .2, ZOOM_MAX = 2;
2008
+ /** Zoom at once about a screen point: the pinch and Ctrl/Cmd+wheel gesture. */
2009
+ function zoom(factor, x = $('canvas').clientWidth / 2, y = $('canvas').clientHeight / 2) { stopViewAnimation(); const next = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, state.zoom * factor)); state.x = x - (x - state.x) * next / state.zoom; state.y = y - (y - state.y) * next / state.zoom; state.zoom = next; requestTransform(); }
2010
+ /** The zoom buttons: ease about the canvas centre. A press during an ease builds on where it was going. */
2011
+ function zoomBy(factor) {
2012
+ const x = $('canvas').clientWidth / 2, y = $('canvas').clientHeight / 2, base = viewTarget ?? state;
2013
+ const next = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, base.zoom * factor));
2014
+ const target = { zoom: next, x: x - (x - base.x) * next / base.zoom, y: y - (y - base.y) * next / base.zoom };
2015
+ if (viewTarget) { animateView(target); return; }
2016
+ animateView(target, { x, y });
1846
2017
  }
1847
- function zoom(factor, x = $('canvas').clientWidth / 2, y = $('canvas').clientHeight / 2) { const next = Math.max(.2, Math.min(2, state.zoom * factor)); state.x = x - (x - state.x) * next / state.zoom; state.y = y - (y - state.y) * next / state.zoom; state.zoom = next; transform(); }
1848
2018
  // A keyboard-activated click carries no pointer coordinates, so the menu falls back to the
1849
2019
  // window corner rather than refusing to open.
1850
2020
  $('new-graph').onclick = event => showNewGraphMenu(event?.clientX ?? 0, event?.clientY ?? 0); $('duplicate').onclick = () => newGraph(true); $('search').oninput = renderList;
@@ -1879,16 +2049,32 @@ $('save').onclick = async () => {
1879
2049
  try { const submitted = dropLegacyTokenFields(copy(state.graph)); const graph = await api('/api/graphs', submitted); if (state.graph.id === submitted.id) {
1880
2050
  // The draft marker is editor state, not graph content, so a difference in it alone is not an edit.
1881
2051
  const liveView = { ...state.graph }; delete liveView.pendingProviderNodes;
1882
- const edited = JSON.stringify(liveView) !== JSON.stringify(submitted); if (edited) { state.graph.revision = graph.revision; state.undo = []; state.redo = []; } else { state.graph = graph; state.dirty = false; state.undo = []; state.redo = []; } retireSatisfiedProviderRequirements(); } const index = state.graphs.findIndex(g => g.id === graph.id); const summary = { id: graph.id, name: graph.name, revision: graph.revision }; if (index >= 0) state.graphs[index] = summary; else state.graphs.push(summary); render(); status(`Saved revision ${graph.revision}${state.dirty ? ' - You have newer unsaved changes' : ''}`); } catch (error) { status(error.message, true); } finally { state.saving = false; renderHeading(); renderList(); }
2052
+ const edited = JSON.stringify(liveView) !== JSON.stringify(submitted); if (edited) { state.graph.revision = graph.revision; state.undo = []; state.redo = []; } else { state.graph = graph; state.dirty = false; state.undo = []; state.redo = []; } retireSatisfiedProviderRequirements(); } const index = state.graphs.findIndex(g => g.id === graph.id); const summary = { id: graph.id, name: graph.name, revision: graph.revision }; if (index >= 0) state.graphs[index] = summary; else state.graphs.push(summary); render(); status(`Saved version ${graph.revision}${state.dirty ? ' · You have newer unsaved changes' : ''}`); } catch (error) { status(error.message, true); } finally { state.saving = false; renderHeading(); renderList(); }
1883
2053
  };
1884
2054
  $('canvas-hint-close').onclick = dismissCanvasHint;
1885
- $('fit').onclick = fit; $('zoom-in').onclick = () => zoom(1.2); $('zoom-out').onclick = () => zoom(1 / 1.2);
2055
+ $('fit').onclick = () => fit(true); $('zoom-in').onclick = () => zoomBy(1.2); $('zoom-out').onclick = () => zoomBy(1 / 1.2);
1886
2056
  $('layout').onclick = () => mutate(() => {
1887
2057
  const levels = new Map([[state.graph.entry, 0]]), queue = [state.graph.entry];
1888
2058
  while (queue.length) { const id = queue.shift(); for (const edge of state.graph.edges.filter(e => e.source === id)) if (!levels.has(edge.target)) { levels.set(edge.target, levels.get(id) + 1); queue.push(edge.target); } }
1889
- const rows = new Map(); for (const node of Object.values(state.graph.nodes)) { const level = levels.get(node.id) ?? 0, row = rows.get(level) || 0; node.position = { x: level * 300, y: row * 220 }; rows.set(level, row + 1); } fit();
2059
+ const rows = new Map(); for (const node of Object.values(state.graph.nodes)) { const level = levels.get(node.id) ?? 0, row = rows.get(level) || 0; node.position = { x: level * 300, y: row * 220 }; rows.set(level, row + 1); } fit(true);
1890
2060
  }, true);
1891
- $('canvas').addEventListener('wheel', event => { if (event.target.closest('button, .node, path')) return; event.preventDefault(); dismissCanvasHint(); const bounds = $('canvas').getBoundingClientRect(); zoom(Math.exp(-event.deltaY * .001), event.clientX - bounds.left, event.clientY - bounds.top); }, { passive: false });
2061
+ // Two-finger scroll pans, as on every canvas a trackpad drives; a pinch (which the browser reports as
2062
+ // a wheel with Ctrl held) or Ctrl/Cmd with a mouse wheel zooms about the pointer. A mouse wheel with
2063
+ // Shift pans sideways. Only the floating controls keep the wheel to themselves.
2064
+ const WHEEL_LINE_PX = 16, WHEEL_ZOOM_CAP = 50, WHEEL_ZOOM_RATE = 150;
2065
+ $('canvas').addEventListener('wheel', event => {
2066
+ if (event.target.closest('.canvas-toolbar, .canvas-hint, #studio-minimap')) return;
2067
+ event.preventDefault(); dismissCanvasHint();
2068
+ const unit = event.deltaMode === 1 ? WHEEL_LINE_PX : event.deltaMode === 2 ? $('canvas').clientHeight : 1;
2069
+ if (event.ctrlKey || event.metaKey) {
2070
+ const bounds = $('canvas').getBoundingClientRect(), delta = Math.max(-WHEEL_ZOOM_CAP, Math.min(WHEEL_ZOOM_CAP, event.deltaY * unit));
2071
+ zoom(Math.pow(2, -delta / WHEEL_ZOOM_RATE), event.clientX - bounds.left, event.clientY - bounds.top);
2072
+ return;
2073
+ }
2074
+ let dx = event.deltaX * unit, dy = event.deltaY * unit;
2075
+ if (event.shiftKey && !dx) { dx = dy; dy = 0; }
2076
+ stopViewAnimation(); state.x -= dx; state.y -= dy; requestTransform();
2077
+ }, { passive: false });
1892
2078
  $('canvas').ondragover = event => {
1893
2079
  const types = Array.from(event.dataTransfer?.types || []);
1894
2080
  if ((state.graph && !state.saving && types.includes('application/andorra-node')) || types.includes('Files')) {event.preventDefault();event.dataTransfer.dropEffect='copy';}
@@ -1905,7 +2091,7 @@ $('canvas').ondrop = event => {
1905
2091
  const file = Array.from(event.dataTransfer?.files || []).find(item => /\.json$/i.test(item.name) || item.type === 'application/json');
1906
2092
  if (file) { event.preventDefault(); void window.AndorraStudio?.importGraphFile?.(file)?.catch(error => status(error.message, true)); }
1907
2093
  };
1908
- $('canvas').onpointerdown = event => { if (event.button !== 0 || event.target.closest('button, .node, path, .canvas-hint')) return; dismissCanvasHint(); const start = { x: event.clientX - state.x, y: event.clientY - state.y }; $('canvas').setPointerCapture(event.pointerId); $('canvas').onpointermove = e => { state.x = e.clientX - start.x; state.y = e.clientY - start.y; transform(); }; $('canvas').onpointerup = () => { $('canvas').onpointermove = null; }; };
2094
+ $('canvas').onpointerdown = event => { if (event.button !== 0 || event.target.closest('button, .node, path, .canvas-hint')) return; dismissCanvasHint(); stopViewAnimation(); const start = { x: event.clientX - state.x, y: event.clientY - state.y }; $('canvas').setPointerCapture(event.pointerId); $('canvas').onpointermove = e => { state.x = e.clientX - start.x; state.y = e.clientY - start.y; requestTransform(); }; $('canvas').onpointerup = () => { $('canvas').onpointermove = null; }; };
1909
2095
  $('resize').onpointerdown = event => { $('resize').setPointerCapture(event.pointerId); $('resize').onpointermove = e => { document.documentElement.style.setProperty('--panel', `${Math.max(360, Math.min(720, innerWidth - e.clientX))}px`); }; $('resize').onpointerup = () => { $('resize').onpointermove = null; }; };
1910
2096
  $('resize').onkeydown = event => { if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return; event.preventDefault(); const width = $('inspector').getBoundingClientRect().width + (event.key === 'ArrowLeft' ? 20 : -20); document.documentElement.style.setProperty('--panel', `${Math.max(360, Math.min(720, width))}px`); };
1911
2097
  $('export').onclick = () => { if (!state.graph) return; downloadGraph(state.graph); };
@@ -1937,7 +2123,7 @@ if (token) setTimeout(refreshCloudState, 1000);
1937
2123
  entry point is feature-detected because this module also loads into partial-DOM harnesses.
1938
2124
  The idle favicon is the published Andorra Labs logo; the two busy states are status markers
1939
2125
  rather than the brand, so they keep their own artwork. */
1940
- const baseTitle = document.title || 'Graph studio - Andorra Code';
2126
+ const baseTitle = document.title || 'Workflow Editor · Andorra Code';
1941
2127
  const faviconHref = svg => 'data:image/svg+xml,' + encodeURIComponent(svg);
1942
2128
  const FAVICONS = {
1943
2129
  idle: '/andorra-logo.png',
@@ -2022,4 +2208,4 @@ setFavicon('idle');
2022
2208
  if (token) watchActivity();
2023
2209
  try { if ((!window.parent || window.parent === window) && typeof Notification === 'function' && Notification.permission === 'default') { window.addEventListener('pointerdown', requestActivityNotifications); window.addEventListener('keydown', requestActivityNotifications); } } catch { /* Partial DOM. */ }
2024
2210
 
2025
- (async () => { renderHeading(); if (!token) { status('Session token missing. Open this app using andorra graph.', true); return; } try { const data = await api('/api/bootstrap'); state.plan = data.plan; state.graphs = data.graphs; applyProviderRegistry(data); state.tools = data.tools || []; state.definitions = foldDefinitionCaps(data.definitions); renderLibrary(); renderList(); const wantsNew = new URLSearchParams(location.search).get('new') === '1'; if (wantsNew && canCreateGraph()) newGraph(); else if (state.graphs.length) { await openGraph((freeTier() && state.plan.freeGraphId) || state.graphs[0].id); if (wantsNew) status(FREE_CREATE_TIP, true); } else { render(); status('Create your first graph'); } window.AndorraEmbed?.ready?.(); if (data.graphMigrationErrors?.length) status('Some saved graphs could not be opened: ' + data.graphMigrationErrors.map(item => item.name + ' (' + item.id + '): ' + item.error).join('; ') + '. Their saved revisions are unchanged.', true); } catch (error) { status(error.message, true); } })();
2211
+ (async () => { renderHeading(); if (!token) { status('The sign-in token is missing. Open this app with the andorra graph command.', true); return; } try { const data = await api('/api/bootstrap'); state.plan = data.plan; state.graphs = data.graphs; applyProviderRegistry(data); state.tools = data.tools || []; state.definitions = foldDefinitionCaps(data.definitions); renderLibrary(); renderList(); const wantsNew = new URLSearchParams(location.search).get('new') === '1'; if (wantsNew && canCreateGraph()) newGraph(); else if (state.graphs.length) { await openGraph((freeTier() && state.plan.freeGraphId) || state.graphs[0].id); if (wantsNew) status(FREE_CREATE_TIP, true); } else { render(); status('Create your first workflow'); } window.AndorraEmbed?.ready?.(); if (data.graphMigrationErrors?.length) status('Some saved workflows could not be opened: ' + data.graphMigrationErrors.map(item => item.name + ' (' + item.id + '): ' + item.error).join('; ') + '. Their saved versions are unchanged.', true); } catch (error) { status(error.message, true); } })();