@andorra-labs/code 0.1.9 → 0.1.11

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 (212) hide show
  1. package/README.md +28 -208
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/dist/src/agent-execution.js +56 -0
  4. package/dist/src/app-server/protocol.d.ts +109 -1
  5. package/dist/src/app-server/protocol.js +8 -1
  6. package/dist/src/app-server.d.ts +59 -1
  7. package/dist/src/app-server.js +418 -63
  8. package/dist/src/auth/index.d.ts +1 -1
  9. package/dist/src/auth/index.js +1 -1
  10. package/dist/src/auth/store.d.ts +17 -1
  11. package/dist/src/auth/store.js +25 -2
  12. package/dist/src/automation-service.js +1 -1
  13. package/dist/src/browser-session.d.ts +8 -0
  14. package/dist/src/browser-session.js +27 -1
  15. package/dist/src/browser-ui/app.js +255 -33
  16. package/dist/src/browser-ui/index.html +9 -9
  17. package/dist/src/browser-ui/style.css +110 -65
  18. package/dist/src/browser-ui/tokens.css +27 -26
  19. package/dist/src/cli.js +10 -5
  20. package/dist/src/coding-tools.d.ts +24 -0
  21. package/dist/src/coding-tools.js +71 -8
  22. package/dist/src/command-screens.js +1 -1
  23. package/dist/src/commands.d.ts +1 -1
  24. package/dist/src/commands.js +2 -2
  25. package/dist/src/completion-gates.d.ts +42 -7
  26. package/dist/src/completion-gates.js +55 -9
  27. package/dist/src/completion.d.ts +9 -1
  28. package/dist/src/completion.js +20 -2
  29. package/dist/src/dashboard-view.js +2 -2
  30. package/dist/src/deadline.js +4 -0
  31. package/dist/src/decision/checks.js +1 -1
  32. package/dist/src/file-diff.d.ts +105 -0
  33. package/dist/src/file-diff.js +244 -0
  34. package/dist/src/graph-manager-chat.js +4 -4
  35. package/dist/src/graph-runner.js +39 -2
  36. package/dist/src/graph-sync.d.ts +8 -0
  37. package/dist/src/graph-sync.js +54 -3
  38. package/dist/src/graph-tool.js +1 -1
  39. package/dist/src/graph-ui/app.js +303 -129
  40. package/dist/src/graph-ui/controls.css +43 -22
  41. package/dist/src/graph-ui/controls.js +31 -1
  42. package/dist/src/graph-ui/embed.js +56 -7
  43. package/dist/src/graph-ui/icons.js +5 -0
  44. package/dist/src/graph-ui/index.html +3 -3
  45. package/dist/src/graph-ui/manager-state.js +2 -2
  46. package/dist/src/graph-ui/manager.css +19 -18
  47. package/dist/src/graph-ui/manager.js +5 -5
  48. package/dist/src/graph-ui/skill-picker.js +5 -5
  49. package/dist/src/graph-ui/studio-canvas.js +16 -16
  50. package/dist/src/graph-ui/studio.css +18 -15
  51. package/dist/src/graph-ui/studio.js +99 -42
  52. package/dist/src/graph-ui/style.css +125 -80
  53. package/dist/src/graph-ui/theme.js +2 -2
  54. package/dist/src/graph-ui/tokens.css +33 -29
  55. package/dist/src/graphs.d.ts +10 -3
  56. package/dist/src/graphs.js +15 -4
  57. package/dist/src/mcp.d.ts +75 -0
  58. package/dist/src/mcp.js +240 -8
  59. package/dist/src/membership-errors.d.ts +7 -1
  60. package/dist/src/membership-errors.js +9 -3
  61. package/dist/src/provider-keys.d.ts +5 -1
  62. package/dist/src/provider-keys.js +7 -3
  63. package/dist/src/provider-settings.d.ts +4 -1
  64. package/dist/src/provider-settings.js +46 -5
  65. package/dist/src/pull-requests.d.ts +42 -6
  66. package/dist/src/pull-requests.js +11 -3
  67. package/dist/src/qa/guidance.js +6 -19
  68. package/dist/src/qa/index.d.ts +0 -2
  69. package/dist/src/qa/index.js +0 -2
  70. package/dist/src/qa/profile/QaProfile.d.ts +5 -1
  71. package/dist/src/qa/profile/QaProfile.js +6 -2
  72. package/dist/src/qa/tools.d.ts +19 -1
  73. package/dist/src/qa/tools.js +20 -145
  74. package/dist/src/react-runtime.js +134 -16
  75. package/dist/src/read-document-doc.d.ts +20 -0
  76. package/dist/src/read-document-doc.js +524 -0
  77. package/dist/src/read-document-docx.d.ts +21 -0
  78. package/dist/src/read-document-docx.js +584 -0
  79. package/dist/src/read-document-text.d.ts +29 -0
  80. package/dist/src/read-document-text.js +67 -0
  81. package/dist/src/read-document-tool.d.ts +48 -0
  82. package/dist/src/read-document-tool.js +162 -0
  83. package/dist/src/read-document.d.ts +78 -0
  84. package/dist/src/read-document.js +353 -0
  85. package/dist/src/read-image.d.ts +29 -2
  86. package/dist/src/read-image.js +42 -17
  87. package/dist/src/remote/engine-pool.js +18 -6
  88. package/dist/src/runtime.d.ts +19 -0
  89. package/dist/src/runtime.js +10 -1
  90. package/dist/src/screen-selection.d.ts +38 -0
  91. package/dist/src/screen-selection.js +103 -0
  92. package/dist/src/session-changes.d.ts +122 -0
  93. package/dist/src/session-changes.js +804 -0
  94. package/dist/src/side-panel.d.ts +6 -1
  95. package/dist/src/side-panel.js +12 -10
  96. package/dist/src/skills/bundled/create-skill/SKILL.md +1 -1
  97. package/dist/src/skills/bundled/diagram/SKILL.md +1 -1
  98. package/dist/src/skills/bundled/graph-manager/SKILL.md +37 -3
  99. package/dist/src/skills/bundled/graph-manager/patterns.md +27 -0
  100. package/dist/src/skills/bundled/provenance.json +4 -4
  101. package/dist/src/skills/runtime-skills.js +3 -3
  102. package/dist/src/stall-recovery.d.ts +15 -0
  103. package/dist/src/stall-recovery.js +17 -0
  104. package/dist/src/telemetry/schema.d.ts +1 -1
  105. package/dist/src/telemetry/schema.js +1 -2
  106. package/dist/src/terminal-ui.d.ts +64 -20
  107. package/dist/src/terminal-ui.js +312 -82
  108. package/dist/src/time-limit.d.ts +53 -0
  109. package/dist/src/time-limit.js +79 -0
  110. package/dist/src/tool-diff-stats.d.ts +9 -0
  111. package/dist/src/tool-diff-stats.js +20 -0
  112. package/dist/src/tool-names.d.ts +1 -1
  113. package/dist/src/tool-result-filter.js +1 -1
  114. package/dist/src/tools.js +118 -9
  115. package/dist/src/transcript.d.ts +11 -0
  116. package/dist/src/transcript.js +15 -3
  117. package/dist/src/types.d.ts +12 -0
  118. package/dist/src/usage-analytics.d.ts +3 -1
  119. package/dist/src/usage-analytics.js +16 -2
  120. package/package.json +6 -26
  121. package/dist/src/qa/api/http-runner.d.ts +0 -3
  122. package/dist/src/qa/api/http-runner.js +0 -47
  123. package/dist/src/qa/git/ChangeDetector.d.ts +0 -26
  124. package/dist/src/qa/git/ChangeDetector.js +0 -177
  125. package/dist/src/qa/git/DiffReviewer.d.ts +0 -28
  126. package/dist/src/qa/git/DiffReviewer.js +0 -115
  127. package/dist/src/qa/orchestrator/ChangeClassifier.d.ts +0 -14
  128. package/dist/src/qa/orchestrator/ChangeClassifier.js +0 -28
  129. package/dist/src/qa/orchestrator/MergeGate.d.ts +0 -14
  130. package/dist/src/qa/orchestrator/MergeGate.js +0 -40
  131. package/dist/src/qa/orchestrator/QaOrchestrator.d.ts +0 -79
  132. package/dist/src/qa/orchestrator/QaOrchestrator.js +0 -373
  133. package/dist/src/qa/runners/CommandRunner.d.ts +0 -22
  134. package/dist/src/qa/runners/CommandRunner.js +0 -96
  135. package/dist/src/qa/runners/TestRunner.d.ts +0 -21
  136. package/dist/src/qa/runners/TestRunner.js +0 -66
  137. package/dist/src/qa/runtime/RuntimeSmoke.d.ts +0 -11
  138. package/dist/src/qa/runtime/RuntimeSmoke.js +0 -78
  139. package/dist/src/qa/runtime-detect.d.ts +0 -10
  140. package/dist/src/qa/runtime-detect.js +0 -72
  141. package/dist/src/qa/security/DependencyScanner.d.ts +0 -19
  142. package/dist/src/qa/security/DependencyScanner.js +0 -167
  143. package/dist/src/qa/security/SecretScanner.d.ts +0 -3
  144. package/dist/src/qa/security/SecretScanner.js +0 -55
  145. package/docs/README.md +0 -36
  146. package/docs/agents/README.md +0 -62
  147. package/docs/agents/install-for-agents.md +0 -56
  148. package/docs/agents/mcp-server.md +0 -212
  149. package/docs/agents/subagent-mode.md +0 -149
  150. package/docs/concepts/README.md +0 -47
  151. package/docs/concepts/jev-actionable-routing.md +0 -113
  152. package/docs/concepts/jev-decision-thresholds.md +0 -412
  153. package/docs/concepts/jev-efficiency.md +0 -217
  154. package/docs/concepts/jev-eval-2026-11-01.md +0 -78
  155. package/docs/concepts/limits.md +0 -52
  156. package/docs/concepts/memory.md +0 -10
  157. package/docs/concepts/security.md +0 -50
  158. package/docs/concepts/workspace-instructions.md +0 -29
  159. package/docs/getting-started/README.md +0 -82
  160. package/docs/getting-started/accounts.md +0 -78
  161. package/docs/getting-started/configure-providers.md +0 -132
  162. package/docs/guides/README.md +0 -13
  163. package/docs/guides/browser.md +0 -39
  164. package/docs/guides/desktop-app.md +0 -414
  165. package/docs/guides/extensions.md +0 -102
  166. package/docs/guides/graph-builder.md +0 -116
  167. package/docs/guides/headless.md +0 -46
  168. package/docs/guides/tui.md +0 -75
  169. package/docs/guides/update.md +0 -70
  170. package/docs/guides/web-search.md +0 -51
  171. package/docs/guides/windows-code-signing.md +0 -319
  172. package/docs/llms.txt +0 -45
  173. package/docs/reference/README.md +0 -7
  174. package/docs/reference/cli.md +0 -76
  175. package/docs/reference/config.md +0 -91
  176. package/docs/reference/slash-commands.md +0 -59
  177. package/docs/superpowers/plans/2026-11-01-claude-console-sign-in.md +0 -111
  178. package/docs/superpowers/plans/2026-11-01-jev-node-opt-in.md +0 -910
  179. package/docs/superpowers/plans/2026-11-02-workflow-pane.md +0 -398
  180. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +0 -125
  181. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +0 -295
  182. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +0 -203
  183. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +0 -79
  184. package/docs/superpowers/specs/2026-10-31-work-line-summary-design.md +0 -50
  185. package/docs/superpowers/specs/2026-11-01-claude-console-sign-in-design.md +0 -176
  186. package/docs/superpowers/specs/2026-11-01-jev-node-opt-in-design.md +0 -164
  187. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +0 -111
  188. package/docs/superpowers/specs/2026-11-02-workflow-pane-design.md +0 -130
  189. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +0 -206
  190. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +0 -291
  191. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +0 -182
  192. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +0 -156
  193. package/scripts/jev-efficiency-eval.mjs +0 -187
  194. package/scripts/jev-efficiency-live.mjs +0 -193
  195. package/scripts/zcode-engine-replay.mjs +0 -223
  196. package/tests/agent-centric-mcp-test-plan.md +0 -208
  197. package/tests/analytics-settings-test-plan.md +0 -165
  198. package/tests/browser-cli-smoke.mjs +0 -276
  199. package/tests/browser-test-plan.md +0 -280
  200. package/tests/chat-side-panel-test-plan.md +0 -309
  201. package/tests/decision-engine-test-plan.md +0 -163
  202. package/tests/default-active-jev-test-plan.md +0 -85
  203. package/tests/harness-extensions-test-plan.md +0 -113
  204. package/tests/jev-all-decisions-test-plan.md +0 -156
  205. package/tests/jev-efficiency/criteria.json +0 -158
  206. package/tests/jev-efficiency/workloads.mjs +0 -242
  207. package/tests/jev-efficiency-test-plan.md +0 -198
  208. package/tests/permissions-sandbox-probe.mjs +0 -74
  209. package/tests/permissions-test-plan.md +0 -191
  210. package/tests/product-telemetry-test-plan.md +0 -536
  211. package/tests/thinking-stream-preview-test-plan.md +0 -136
  212. package/tests/zcode-react-engine-test-plan.md +0 -396
@@ -17,14 +17,15 @@ const themeColor = (token, fallback) => {
17
17
  // its outcome: an outcome is not a failure, and colouring "blocked" or "pass" made a resting graph
18
18
  // read as a status board. The one red on the canvas is a run route into a node that failed
19
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.
20
+ // canvas ground, so a crossing stays legible. Each fallback is the dark token's own value
21
+ // (desktop/src/styles/tokens.css), for a page that has not loaded the stylesheet.
21
22
  const connectionPalette = () => ({
22
- line: themeColor('--text-3', '#9a9aa4'),
23
- active: themeColor('--accent', '#dedee3'),
24
- halo: themeColor('--canvas-bg', '#1b1b1e'),
25
- pill: themeColor('--bg-input', '#202024'),
26
- pillEdge: themeColor('--border', '#2a2a30'),
27
- pillInk: themeColor('--text-2', '#b4b4bc'),
23
+ line: themeColor('--text-3', 'rgba(245,245,245,.60)'),
24
+ active: themeColor('--accent', '#ececec'),
25
+ halo: themeColor('--canvas-bg', '#191919'),
26
+ pill: themeColor('--bg-input', '#1f1f1f'),
27
+ pillEdge: themeColor('--border', 'rgba(245,245,245,.08)'),
28
+ pillInk: themeColor('--text-2', 'rgba(245,245,245,.74)'),
28
29
  });
29
30
  /** The connection's stroke at rest and while it is traced (hovered, focused or selected). */
30
31
  const EDGE_WIDTH = '1.5', EDGE_ACTIVE_WIDTH = '2';
@@ -53,19 +54,29 @@ function closeDialog(dialog) {
53
54
  const controls = globalThis.AndorraControls;
54
55
  if (typeof controls?.closeDialog === 'function') controls.closeDialog(dialog); else dialog.close();
55
56
  }
56
- 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' };
57
+ const DISCARD_QUESTION = { title: 'Discard unsaved changes?', message: 'Edits to this graph since its last version are lost. Recoverable drafts stay in draft history.', confirmLabel: 'Discard', tone: 'danger' };
57
58
  function status(message, error = false) { $('status').textContent = message; $('status').parentElement.classList.toggle('error', error); }
58
59
  // The free tier keeps one custom graph of up to three nodes (Done does not count) and leaves the
59
60
  // Orchestrator to Premium. The server enforces the same rules on save; these keep the editor honest
60
61
  // about them before the user builds something it cannot save.
61
62
  const FREE_CREATE_TIP = 'Free tier includes 1 custom graph. Upgrade to Premium for more graphs.';
62
- const FREE_ORCHESTRATOR_TIP = 'The Orchestrator is a Premium feature. Free tier graphs can use the other agent nodes.';
63
+ const FREE_ORCHESTRATOR_TIP = 'The Orchestrator is a Premium feature. Free tier graphs can use the other agents.';
63
64
  function freeTier() { return state.plan?.paid === false; }
64
- function freeNodeTip() { return `Free tier graphs can have up to ${state.plan.nodeLimit} nodes, not counting Done. Upgrade to Premium for larger graphs.`; }
65
+ function freeNodeTip() { return `Free tier graphs can have up to ${state.plan.nodeLimit} steps, not counting Done. Upgrade to Premium for larger graphs.`; }
65
66
  function countedNodes(graph) { return Object.values(graph.nodes).filter(node => node.type !== 'end').length; }
66
67
  function canCreateGraph() { return !freeTier() || state.graphs.filter(graph => graph.id !== 'default').length < state.plan.customGraphLimit; }
67
68
  /** Whether a free account may save this graph: its kept graph, or a new one while it has none. */
68
69
  function freeGraphEditable(graph) { return !freeTier() || (graph.revision ? graph.id === (state.plan.freeGraphId ?? state.graphs.find(item => item.id !== 'default')?.id) : canCreateGraph()); }
70
+ const FREE_LOCKED_TIP = 'On the free tier only your first custom graph is available. Upgrade to Premium to open this graph.';
71
+ /**
72
+ * Whether a free account's saved workflow is outside its allowance: neither the preset nor the one it
73
+ * keeps. The server refuses to run or save it, so the list shows it locked and the editor never opens it.
74
+ */
75
+ function graphLocked(id) {
76
+ if (!freeTier() || id === 'default') return false;
77
+ const graph = state.graphs.find(item => item.id === id);
78
+ return Boolean(graph?.revision) && !freeGraphEditable(graph);
79
+ }
69
80
  /** Why adding these nodes would leave the free allowance, or undefined. */
70
81
  function freeNodeRefusal(added) {
71
82
  if (!freeTier() || !state.graph) return undefined;
@@ -76,11 +87,90 @@ function freeNodeRefusal(added) {
76
87
  async function api(path, body, options = {}) {
77
88
  const response = await fetch(path, { method: options.method || (body ? 'POST' : 'GET'), headers: { Authorization: `Bearer ${token || ''}`, ...(body ? { 'Content-Type': 'application/json' } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}), ...(options.signal ? { signal: options.signal } : {}), ...(options.keepalive ? { keepalive: true } : {}) });
78
89
  const data = await response.json();
79
- if (!response.ok) throw new Error(typeof data.error === 'string' ? data.error : JSON.stringify(data.error || data));
90
+ if (!response.ok) {
91
+ const message = typeof data.error === 'string' ? data.error : JSON.stringify(data.error || data);
92
+ // A graph the engine refused is explained in the editor's words, naming the step it is about.
93
+ const graph = body?.graph && typeof body.graph === 'object' ? body.graph : body?.nodes ? body : state.graph;
94
+ const plain = plainGraphError(message, graph);
95
+ throw Object.assign(new Error(plain.message), plain.nodeId ? { nodeId: plain.nodeId } : {});
96
+ }
80
97
  return data;
81
98
  }
99
+ // The engine's validation says "Invalid graph: node fixer: required outcome fail has no route; connect
100
+ // its output port": its own identifiers and words (node, entry, edge, limits.maxNodeVisits), meant for
101
+ // the CLI and the agents that read them. The editor says the same thing in the words its own controls
102
+ // use (ADR 0022 D13: a step, a connection, the starting step, Maximum visits per step) and names the
103
+ // step by its name. The messages the editor's controls can produce are written out; any other keeps
104
+ // the engine's sentence with those words swapped. Engine text that is not a validation passes through.
105
+ function plainGraphError(message, graph) {
106
+ const match = /^Invalid graph: ([\s\S]*)$/.exec(String(message));
107
+ if (!match) return { message: String(message), nodeId: null };
108
+ const nodes = graph && typeof graph.nodes === 'object' && graph.nodes ? graph.nodes : {};
109
+ const name = id => (typeof nodes[id]?.name === 'string' && nodes[id].name.trim()) || id;
110
+ const quoted = id => `“${name(id)}”`;
111
+ const words = text => text
112
+ .replace(/\bgraph limits\.maxNodeVisits\b/g, 'Maximum visits per step').replace(/\blimits\.maxNodeVisits\b/g, 'Maximum visits per step')
113
+ .replace(/\bthe (graph )?entry\b/g, 'the starting step').replace(/\bgraph entry\b/g, 'starting step')
114
+ .replace(/\bnodes\b/g, 'steps').replace(/\bnode\b/g, 'step').replace(/\bNodes\b/g, 'Steps').replace(/\bNode\b/g, 'Step')
115
+ .replace(/\bedges\b/g, 'connections').replace(/\bedge\b/g, 'connection').replace(/\boutput port\b/g, 'outcome');
116
+ const sentence = text => { const value = text.trim(); return value ? value.charAt(0).toUpperCase() + value.slice(1) + (/[.!?]$/.test(value) ? '' : '.') : value; };
117
+ const detail = match[1];
118
+ let found;
119
+ if (/^all nodes must be reachable from the entry/.test(detail)) {
120
+ // Which steps no connection reaches from the starting step: the engine does not say, the editor can.
121
+ const reached = new Set(), queue = graph?.entry && nodes[graph.entry] ? [graph.entry] : [];
122
+ while (queue.length) { const id = queue.shift(); if (reached.has(id)) continue; reached.add(id); for (const edge of graph?.edges || []) if (edge?.source === id && nodes[edge.target]) queue.push(edge.target); }
123
+ const lost = Object.keys(nodes).filter(id => !reached.has(id));
124
+ if (lost.length === 1) return { message: `Step ${quoted(lost[0])} is not connected. Connect it or remove it.`, nodeId: lost[0] };
125
+ if (lost.length > 1) return { message: `${lost.length} steps are not connected: ${lost.map(quoted).join(', ')}. Connect them or remove them.`, nodeId: lost[0] };
126
+ return { message: 'Every step must be reachable from the starting step. Connect or remove the steps that are not.', nodeId: null };
127
+ }
128
+ if (/^include an End node$/.test(detail)) return { message: 'Add an End step, so the graph has somewhere to finish.', nodeId: null };
129
+ if (/^include between 2 and 100 nodes/.test(detail)) return { message: 'A graph has between 2 and 100 steps, plus the Orchestrator.', nodeId: null };
130
+ if (/^entry must reference an existing node$/.test(detail)) return { message: 'Choose a starting step in Graph settings.', nodeId: null };
131
+ if (/^every edge must connect existing nodes$/.test(detail)) return { message: 'A connection leads to a step that no longer exists. Remove it.', nodeId: null };
132
+ if (/^unlimited graph cycle/.test(detail)) return { message: 'This graph can loop back forever. Set Maximum visits per step or a run time limit in Graph settings.', nodeId: null };
133
+ if ((found = /^node (\S+): required outcome (\S+) has no route/.exec(detail))) return { message: `${name(found[1])}: the “${found[2]}” outcome is not connected. Connect it to a step.`, nodeId: found[1] };
134
+ if ((found = /^edge \S+: nonexistent outcome (\S+)/.exec(detail))) return { message: `A connection starts from the outcome “${found[1]}”, which its step no longer has. Remove it or pick another outcome.`, nodeId: null };
135
+ if (/^duplicate edge /.test(detail)) return { message: 'Two connections join the same outcome to the same step. Remove one of them.', nodeId: null };
136
+ if ((found = /^Join (\S+) needs an incoming branch$/.exec(detail))) return { message: `${name(found[1])}: connect at least one step into this Join.`, nodeId: found[1] };
137
+ // A message about one step: "node <id>: …", "node <id> must …", or "Join <id>: …", "Agent <id>: …".
138
+ if ((found = /^(?:node|Join|Condition|Loop|Agent) (\S+?)(:\s*| )([\s\S]*)$/.exec(detail)) && nodes[found[1]]) {
139
+ return { message: `${name(found[1])}: ${sentence(words(found[3]))}`, nodeId: found[1] };
140
+ }
141
+ return { message: sentence(words(detail)), nodeId: null };
142
+ }
82
143
  function checkpoint() { state.undo.push(copy(state.graph)); if (state.undo.length > 80) state.undo.shift(); state.redo = []; }
83
- function changed() { scheduleValidation(); state.dirty = true; renderCanvas(); renderHeading(); renderValidation(); status('Unsaved changes'); syncImportRequirementsMarker(); queueDraft(); }
144
+ // The comparison form of a graph: keys sorted at every depth, so an edit that is undone by hand
145
+ // (a field cleared and typed back) compares equal even when its key moved in the object, and
146
+ // without the draft-only provider marker, which is editor state rather than graph content.
147
+ function graphKey(graph) {
148
+ const sorted = value => Array.isArray(value) ? value.map(sorted)
149
+ : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, sorted(value[key])]))
150
+ : value;
151
+ const { pendingProviderNodes, ...content } = graph;
152
+ return JSON.stringify(sorted(content));
153
+ }
154
+ // Remember the open graph as the saved state. `null` marks a graph with no saved form to return to
155
+ // (new, duplicated, recovered from a draft, migrated, or replaced by an import), which stays
156
+ // unsaved until it is saved.
157
+ function markSaved(graph) { state.savedKey = graph ? graphKey(graph) : null; }
158
+ // Unsaved means the open graph differs from the saved state, not that some edit happened: edits
159
+ // that are undone, or reverted by hand, leave nothing to save. Back at the saved state, an
160
+ // autosave still waiting would record an edit that no longer exists, so it is cancelled.
161
+ function refreshDirty() {
162
+ state.dirty = !!state.graph && (state.savedKey == null || graphKey(state.graph) !== state.savedKey);
163
+ if (!state.dirty && pendingDraft && pendingDraft.id === state.graph?.id) { pendingDraft = null; clearTimeout(draftTimer); }
164
+ }
165
+ function changed() { scheduleValidation(); refreshDirty(); renderCanvas(); renderHeading(); renderValidation(); status(state.dirty ? 'Unsaved changes' : 'No unsaved changes'); syncImportRequirementsMarker(); queueDraft(); }
166
+ // The save stamps metadata only the server writes; edits kept across a save take those stamps, so
167
+ // reverting the kept edits returns the graph to exactly the version just saved.
168
+ function adoptServerStamps(saved) {
169
+ for (const key of ['updatedAt', 'createdAt']) {
170
+ if (saved.metadata?.[key] !== undefined) state.graph.metadata = { ...state.graph.metadata, [key]: saved.metadata[key] };
171
+ else if (state.graph.metadata) delete state.graph.metadata[key];
172
+ }
173
+ }
84
174
  let draftTimer, pendingDraft, draftWrite;
85
175
  // How long editing must pause before a draft is written. Every draft is a snapshot the account
86
176
  // keeps, so a pause shorter than this would store one per keystroke burst.
@@ -135,9 +225,11 @@ function restoreImportRequirements(graph) {
135
225
  if (owed.size) graph.pendingProviderNodes = [...owed]; else delete graph.pendingProviderNodes;
136
226
  return owed.size ? owed : null;
137
227
  }
138
- async function openDraft(snapshot) {
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 node, then save.' : 'Recovered draft. Save a revision when valid, or duplicate if its base revision changed.'); graphOpened('open'); }
228
+ /** Open a draft snapshot; `graphId` names the saved workflow it belongs to, refused when that one is locked. */
229
+ async function openDraft(snapshot, graphId) {
230
+ if (graphLocked(graphId)) { status(FREE_LOCKED_TIP, true); return; }
231
+ if (state.dirty && !await askConfirm({ title: 'Open the saved draft?', message: 'Current edits are retained in draft history.', confirmLabel: 'Open Draft' })) return;
232
+ try { const graph = foldGraphSubagentCaps(await api(`/api/drafts/${snapshot}`)); const owed = restoreImportRequirements(graph); state.graph = graph; markSaved(null); 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'); }
141
233
  catch (error) { status(error.message, true); }
142
234
  }
143
235
  function mutate(action, inspector = false) { if (!state.graph) return; checkpoint(); action(); changed(); if (inspector) renderInspector(); }
@@ -268,36 +360,36 @@ function selectNode(node, event = {}) {
268
360
  } else state.selectedIds = [node.id];
269
361
  state.selected = state.selectedIds.at(-1) || null; state.selectedEdge = null; state.bulkOutcome = null;
270
362
  renderCanvas(); renderInspector(); showInspector();
271
- if (mixed) status('Selection restarted. Use Ctrl/Cmd-click to select nodes of the same type.');
363
+ if (mixed) status('Selection restarted. Use Ctrl/Cmd-click to select steps of the same type.');
272
364
  }
273
365
  function routeSelectionTo(targetId) {
274
366
  const pick = state.routePick, target = state.graph?.nodes[targetId];
275
367
  if (!pick || !target) return;
276
368
  if (pick.sources.includes(targetId) || target.agentRole === 'orchestrator') { status('Choose a destination outside the selection. The Orchestrator cannot have incoming connections.', true); return; }
277
369
  const sources = pick.sources.map(id => state.graph.nodes[id]);
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 nodes and choose an outcome again.',true); return; }
370
+ 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; }
279
371
  mutate(() => {
280
372
  const existing = state.graph.edges;
281
373
  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});
282
374
  state.graph.edges = [...existing.filter(edge => !pick.sources.includes(edge.source) || edgeOutcome(edge) !== pick.outcome),...replacements];
283
375
  state.routePick = null;
284
376
  },true);
285
- status(`Routed ${sources.length} nodes to ${target.name}. Existing matching handoffs were kept; configure and validate new input mappings below.`);
377
+ status(`Routed ${sources.length} steps to ${target.name}. Existing matching connections were kept; set the inputs of new ones below.`);
286
378
  }
287
379
  function renderBulkInspector(parent, nodes) {
288
- $('inspector-title').textContent = `${nodes.length} nodes selected`;
380
+ $('inspector-title').textContent = `${nodes.length} steps selected`;
289
381
  parent.append(el('p',nodes.map(node=>node.name).join(', '),'help'));
290
- const group = section(parent,'Output Node');
382
+ const group = section(parent,'Output step');
291
383
  const shared = outcomes(nodes[0]).filter(outcome => nodes.every(node => outcomes(node).includes(outcome)));
292
- if (!shared.length) {group.append(el('p','These nodes have no shared outcome. Give them a matching completion outcome before routing together.','help'));return;}
384
+ if (!shared.length) {group.append(el('p','These steps have no shared outcome. Give them a matching completion outcome before routing together.','help'));return;}
293
385
  if (!shared.includes(state.bulkOutcome)) state.bulkOutcome=shared[0];
294
386
  const selector=choice(group,'Shared outcome',state.bulkOutcome,shared,()=>{});selector.onchange=()=>{state.bulkOutcome=selector.value;state.routePick=null;renderCanvas();renderInspector();};
295
- 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'));
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 node. Press Escape to cancel.');};group.append(route);
298
- if(state.routePick){const cancel=el('button','Cancel destination selection');cancel.onclick=cancelRoutePick;group.append(cancel);}
299
- const connections=section(group,'Handoff mappings');
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);}
387
+ 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'));
388
+ const route=el('button',state.routePick?'Click a destination on the canvas':`Route all ${nodes.length} to…`,'primary');
389
+ 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);
390
+ if(state.routePick){const cancel=el('button','Cancel Selection');cancel.onclick=cancelRoutePick;group.append(cancel);}
391
+ const connections=section(group,'Connection inputs');
392
+ 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);}
301
393
  }
302
394
  function cancelRoutePick() { state.routePick=null;renderCanvas();renderInspector();status('Destination selection cancelled. No connections changed.'); }
303
395
  /** One validation problem: the message shown to the reader, and the node it blames. Errors that
@@ -305,13 +397,13 @@ function cancelRoutePick() { state.routePick=null;renderCanvas();renderInspector
305
397
  function issues() {
306
398
  const graph = state.graph; if (!graph) return [];
307
399
  const result = [], nodes = Object.values(graph.nodes);
308
- if (nodes.length < 2 || nodes.length > nodeLimit(graph)) result.push({ message: `Use between 2 and ${nodeLimit(graph)} nodes; remove extra nodes before saving.` });
400
+ if (nodes.length < 2 || nodes.length > nodeLimit(graph)) result.push({ message: `Use between 2 and ${nodeLimit(graph)} steps; remove extra steps before saving.` });
309
401
  if (freeTier()) {
310
402
  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 });
311
403
  if (nodes.some(node => node.agentRole === 'orchestrator')) result.push({ message: FREE_ORCHESTRATOR_TIP });
312
404
  if (countedNodes(graph) > state.plan.nodeLimit) result.push({ message: freeNodeTip() });
313
405
  }
314
- if (new TextEncoder().encode(JSON.stringify(graph)).byteLength > 512 * 1024) result.push({ message: 'Graph exceeds 512 KiB; shorten instructions or remove nodes before saving.' });
406
+ if (new TextEncoder().encode(JSON.stringify(graph)).byteLength > 512 * 1024) result.push({ message: 'Graph exceeds 512 KiB; shorten instructions or remove steps before saving.' });
315
407
  if (!graph.name.trim()) result.push({ message: 'Give this graph a name.' });
316
408
  if (graph.name.length > 200) result.push({ message: 'Keep the graph name to 200 characters or fewer.' });
317
409
  if (graph.metadata?.description?.length > 2000) result.push({ message: 'Keep the description to 2000 characters or fewer.' });
@@ -324,18 +416,18 @@ function issues() {
324
416
  if (widgetIds.has(widget.id)) result.push({ message: `${label}: duplicate widget id; remove and re-add this widget.` });
325
417
  widgetIds.add(widget.id);
326
418
  }
327
- if (!graph.nodes[graph.entry]) result.push({ message: 'Choose an existing entry node.' });
419
+ if (!graph.nodes[graph.entry]) result.push({ message: 'Choose an existing entry step.' });
328
420
  for (const node of nodes) {
329
421
  const blame = message => result.push({ message, nodeId: node.id });
330
- if (node.jevEnabled !== undefined && (node.type !== 'agent' || typeof node.jevEnabled !== 'boolean')) blame(`${node.name}: Jev decisions must be a boolean on an Agent node.`);
422
+ if (node.jevEnabled !== undefined && (node.type !== 'agent' || typeof node.jevEnabled !== 'boolean')) blame(`${node.name}: Jev decisions must be a boolean on an Agent step.`);
331
423
  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__.`);
332
424
  if (!node.name.trim()) blame(`${node.id}: Add a name.`);
333
- if (node.name.length > 200) blame(`${node.id}: Keep the node name to 200 characters or fewer.`);
425
+ if (node.name.length > 200) blame(`${node.id}: Keep the step name to 200 characters or fewer.`);
334
426
  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.`);
335
427
  if (node.type === 'agent') {
336
428
  // An imported graph must not drift onto the machine default provider unnoticed: nodes
337
429
  // that arrived without a usable provider stay pinned to this list until one is chosen.
338
- if (state.pendingProviderNodes?.has(node.id) && !node.provider) blame(`${node.name}: choose a model profile for this imported node before saving.`);
430
+ if (state.pendingProviderNodes?.has(node.id) && !node.provider) blame(`${node.name}: choose a model profile for this imported step before saving.`);
339
431
  // Missing provider profiles remain editable; the inspector labels them unavailable.
340
432
  // Run-time preflight, not graph storage, enforces local provider availability.
341
433
  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.`);
@@ -353,12 +445,49 @@ function scheduleValidation() {
353
445
  const snapshot = JSON.stringify(state.graph);
354
446
  state.validationTimer = setTimeout(async () => {
355
447
  try { await api('/api/validate', { graph: JSON.parse(snapshot) }); if (JSON.stringify(state.graph) === snapshot) { state.validated = true; state.validationErrors = []; renderValidation(); renderCanvas(); } }
356
- catch (error) { if (JSON.stringify(state.graph) === snapshot) { state.validated = true; state.validationErrors = [error.message]; renderValidation(); renderCanvas(); } }
448
+ catch (error) { if (JSON.stringify(state.graph) === snapshot) { state.validated = true; state.validationErrors = [error.nodeId ? { message: error.message, nodeId: error.nodeId } : error.message]; renderValidation(); renderCanvas(); } }
357
449
  }, 350);
358
450
  }
451
+ // The workflow on the canvas, kept for this tab in session storage, so a reload of the editor — the
452
+ // desktop's Reload Editor, or the browser's — opens it again rather than the first in the list. An
453
+ // unsaved one is reopened from the draft the reload kept of it.
454
+ const OPEN_KEY = 'andorra-graph-open';
455
+ let rememberedOpen;
456
+ function rememberOpenGraph() {
457
+ // Before boot has opened anything there is nothing to remember, and the last value must survive
458
+ // until boot has read it.
459
+ if (!state.graph) return;
460
+ const value = JSON.stringify({ id: state.graph.id, unsaved: !!state.dirty });
461
+ if (value === rememberedOpen) return;
462
+ rememberedOpen = value;
463
+ try { sessionStorage.setItem(OPEN_KEY, value); } catch { /* Storage is unavailable; boot opens the first workflow. */ }
464
+ }
465
+ function rememberedGraph() {
466
+ try {
467
+ const value = JSON.parse(sessionStorage.getItem(OPEN_KEY) || 'null');
468
+ return value && typeof value.id === 'string' ? { id: value.id, unsaved: value.unsaved === true } : null;
469
+ } catch { return null; }
470
+ }
471
+ // Reopen what the tab had open before it reloaded: the newest draft of it when it held unsaved work
472
+ // (the reload kept that work as a draft first), else its saved version. False when there is nothing
473
+ // to reopen, and boot opens the first workflow as before.
474
+ async function reopenRemembered() {
475
+ const remembered = rememberedGraph();
476
+ if (!remembered || graphLocked(remembered.id)) return false;
477
+ const saved = state.graphs.some(graph => graph.id === remembered.id);
478
+ if (remembered.unsaved || !saved) {
479
+ try {
480
+ state.drafts = await api('/api/drafts');
481
+ const draft = state.drafts.find(item => item.graphId === remembered.id);
482
+ if (draft) { await openDraft(draft.snapshot, draft.graphId); return state.graph?.id === remembered.id; }
483
+ } catch { /* Fall back to the saved version. */ }
484
+ }
485
+ return saved && await openGraph(remembered.id);
486
+ }
359
487
  function renderHeading() {
360
- $('graph-title').textContent = state.graph?.name || 'Graph studio';
361
- $('revision').textContent = state.graph ? `${state.graph.revision ? `Revision ${state.graph.revision}` : 'New graph'}${state.dirty ? ' · Unsaved' : ''}` : '';
488
+ rememberOpenGraph();
489
+ $('graph-title').textContent = state.graph?.name || 'Graph Editor';
490
+ $('revision').textContent = state.graph ? `${state.graph.revision ? `Version ${state.graph.revision}` : 'New graph'}${state.dirty ? ' · Unsaved' : ''}` : '';
362
491
  $('save').disabled = state.saving || !state.graph || !state.dirty || state.graph.id === 'default';
363
492
  $('save').title = state.graph?.id === 'default' ? 'Duplicate the preset to save your customization' : '';
364
493
  $('undo').disabled = !state.undo.length; $('redo').disabled = !state.redo.length;
@@ -376,11 +505,25 @@ function renderList() {
376
505
  $('new-graph').title = canCreateGraph() ? 'Create graph' : FREE_CREATE_TIP;
377
506
  $('duplicate').disabled = state.saving || !state.graph || !canCreateGraph();
378
507
  $('duplicate').title = canCreateGraph() ? '' : FREE_CREATE_TIP;
508
+ $('empty-create').disabled = state.saving || !canCreateGraph();
509
+ $('empty-create').title = canCreateGraph() ? '' : FREE_CREATE_TIP;
379
510
  $('graphs').replaceChildren();
380
- for (const graph of state.graphs.filter(graph => graph.name.toLowerCase().includes($('search').value.toLowerCase()))) {
381
- const button = el('button', undefined, `graph-row${state.graph?.id === graph.id ? ' active' : ''}`);
511
+ const query = $('search').value.toLowerCase();
512
+ const listed = state.graphs.filter(graph => graph.name.toLowerCase().includes(query));
513
+ for (const graph of listed) {
514
+ const locked = graphLocked(graph.id);
515
+ const button = el('button', undefined, `graph-row${state.graph?.id === graph.id ? ' active' : ''}${locked ? ' locked' : ''}`);
382
516
  button.disabled = state.saving;
383
- button.append(el('span', graph.name), el('small', graph.id === 'default' ? 'Preset' : `r${graph.revision}`));
517
+ const tag = el('small', graph.id === 'default' ? 'Preset' : `v${graph.revision}`);
518
+ button.append(el('span', graph.name), tag);
519
+ // A locked row stays focusable so its tooltip and context menu (Export, Delete) still reach it;
520
+ // aria-disabled says it cannot be opened, and a click explains why instead.
521
+ if (locked) {
522
+ button.setAttribute('aria-disabled', 'true');
523
+ button.title = FREE_LOCKED_TIP;
524
+ const glyph = globalThis.AndorraIcons?.icon?.('lock', 12);
525
+ if (glyph) tag.prepend(glyph);
526
+ }
384
527
  button.onclick = () => openGraph(graph.id);
385
528
  button.oncontextmenu = event => { event.preventDefault(); showGraphMenu(graph, event.clientX, event.clientY); };
386
529
  $('graphs').append(button);
@@ -400,23 +543,44 @@ function renderList() {
400
543
  head.append(clear); $('graphs').append(head);
401
544
  }
402
545
  for (const draft of shown) {
403
- const button = el('button', undefined, 'graph-row draft-row'); button.disabled = state.saving;
546
+ const locked = graphLocked(draft.graphId);
547
+ const button = el('button', undefined, `graph-row draft-row${locked ? ' locked' : ''}`); button.disabled = state.saving;
404
548
  const saved = draft.updatedAt ? new Date(draft.updatedAt).toLocaleString() : '(date unknown)';
405
549
  const when = el('small', globalThis.AndorraDrafts?.age(draft.updatedAt) || 'Draft');
406
- button.title = `${draft.name} — draft saved ${saved}`;
550
+ button.title = locked ? FREE_LOCKED_TIP : `${draft.name} — draft saved ${saved}`;
551
+ if (locked) { button.setAttribute('aria-disabled', 'true'); const glyph = globalThis.AndorraIcons?.icon?.('lock', 12); if (glyph) when.prepend(glyph); }
407
552
  button.append(el('span', draft.name), when);
408
- button.onclick = () => openDraft(draft.snapshot);
553
+ button.onclick = () => openDraft(draft.snapshot, draft.graphId);
409
554
  button.oncontextmenu = event => { event.preventDefault(); showMenuAt(event.clientX, event.clientY, `Actions for the draft of ${draft.name}`, [
410
- { label: 'Open Draft', icon: 'history', run: () => openDraft(draft.snapshot) },
555
+ ...(locked ? [] : [{ label: 'Open Draft', icon: 'history', run: () => openDraft(draft.snapshot, draft.graphId) }]),
411
556
  { label: 'Clear Draft', icon: 'trash', danger: true, run: () => clearDrafts([draft]) },
412
557
  ]); };
413
558
  $('graphs').append(button);
414
559
  }
415
560
  if (state.showDraftHistory || matching.length > current.length) {
416
- const history = el('button', state.showDraftHistory ? 'Show latest drafts' : `Show draft history (${matching.length})`, 'graph-drafts-toggle');
561
+ // A disclosure, as the desktop's Disclosure is: the chevron turns, the words stay (D13).
562
+ const history = el('button', undefined, 'graph-drafts-toggle');
417
563
  history.type = 'button';
564
+ history.setAttribute('aria-expanded', String(Boolean(state.showDraftHistory)));
565
+ const chevron = globalThis.AndorraIcons?.icon?.('chevron-right', 12);
566
+ if (chevron) history.append(chevron);
567
+ history.append(el('span', state.showDraftHistory ? 'Draft history' : `Draft history (${matching.length})`));
418
568
  history.onclick = () => { state.showDraftHistory = !state.showDraftHistory; renderList(); }; $('graphs').append(history);
419
569
  }
570
+ // A filter that matches nothing says so, in the EmptyState's anatomy, rather than leaving a gap.
571
+ if (query && !listed.length && !matching.length) $('graphs').append(emptyState('search', 'No graphs match', 'Try another name, or clear the filter.'));
572
+ }
573
+ // The desktop's EmptyState (components/ui.tsx): a 16px mark, a 13/500 title, a 12px muted line and at
574
+ // most one button. In the rail's lists it is the compact kind.
575
+ function emptyState(icon, title, line, action) {
576
+ const box = el('div', undefined, 'empty-state empty-state-compact');
577
+ box.setAttribute('role', 'status');
578
+ const glyph = globalThis.AndorraIcons?.icon?.(icon);
579
+ if (glyph) { const mark = el('span', undefined, 'empty-state-icon'); mark.append(glyph); box.append(mark); }
580
+ box.append(el('p', title, 'empty-state-title'));
581
+ if (line) box.append(el('p', line, 'empty-state-line'));
582
+ if (action) { const row = el('div', undefined, 'empty-state-action'); row.append(action); box.append(row); }
583
+ return box;
420
584
  }
421
585
  // Clearing takes a graph's drafts off the list; saved graphs and their revisions are untouched.
422
586
  // The open graph's edits are not lost: its next autosave is a new draft.
@@ -424,7 +588,7 @@ async function clearDrafts(drafts, all = false) {
424
588
  const graphIds = [...new Set(drafts.map(draft => draft.graphId))];
425
589
  if (!graphIds.length) return;
426
590
  const one = graphIds.length === 1 && !all;
427
- 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;
591
+ 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 versions are not affected.', confirmLabel: 'Clear', tone: 'danger' })) return;
428
592
  try { state.drafts = await api('/api/drafts/clear', { graphIds }); if (!state.drafts.length) state.showDraftHistory = false; renderList(); status(one ? 'Draft cleared' : 'Drafts cleared'); }
429
593
  catch (error) { status('Drafts not cleared: ' + error.message, true); }
430
594
  }
@@ -442,10 +606,12 @@ function showMenuAt(x, y, ariaLabel, items) {
442
606
  menu.setAttribute('role', 'menu'); menu.setAttribute('aria-label', ariaLabel);
443
607
  const buttons = [];
444
608
  for (const item of items) {
445
- const button = el('button', item.label, item.danger ? 'danger' : undefined);
609
+ // A destructive item is a neutral row below a divider (C7); its confirmation names the loss.
610
+ if (item.danger && buttons.length) { const rule = el('hr'); rule.setAttribute('role', 'separator'); menu.append(rule); }
611
+ const button = el('button', item.label);
446
612
  button.type = 'button'; button.setAttribute('role', 'menuitem');
447
613
  if (item.icon) button.setAttribute('data-icon', item.icon);
448
- if (item.danger) button.className = 'danger';
614
+ if (item.danger) button.setAttribute('data-destructive', 'true');
449
615
  button.onclick = () => { closeGraphMenu(); item.run(); };
450
616
  menu.append(button); buttons.push(button);
451
617
  }
@@ -466,15 +632,15 @@ function showMenuAt(x, y, ariaLabel, items) {
466
632
  };
467
633
  const outside = event => { if (!menu.contains(event.target)) close(); };
468
634
  // The toolbar overflow's menu-button pattern: the opening takes focus, arrows move between
469
- // items, Escape closes and hands focus back to the row, Tab closes without restoring.
635
+ // items, Escape and Tab close it and hand focus back to where it was, so focus never falls to the
636
+ // page as the menu leaves.
470
637
  menu.onkeydown = event => {
471
638
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
472
639
  event.preventDefault();
473
640
  const index = buttons.indexOf(document.activeElement);
474
641
  buttons[(index + (event.key === 'ArrowDown' ? 1 : -1) + buttons.length) % buttons.length]?.focus();
475
642
  }
476
- else if (event.key === 'Escape') { event.preventDefault(); close(true); }
477
- else if (event.key === 'Tab') close();
643
+ else if (event.key === 'Escape' || event.key === 'Tab') { event.preventDefault(); close(true); }
478
644
  };
479
645
  window.addEventListener?.('pointerdown', outside, true);
480
646
  closeGraphMenuHandlers = close;
@@ -482,7 +648,8 @@ function showMenuAt(x, y, ariaLabel, items) {
482
648
  }
483
649
  function showGraphMenu(graph, x, y) {
484
650
  const items = [
485
- { label: 'Duplicate', icon: 'copy', run: () => duplicateGraph(graph) },
651
+ // A locked workflow cannot seed a copy: the copy would be a second custom workflow.
652
+ ...(graphLocked(graph.id) ? [] : [{ label: 'Duplicate', icon: 'copy', run: () => duplicateGraph(graph) }]),
486
653
  { label: 'Export JSON', icon: 'download', run: () => { exportGraph(graph).catch(error => status(error.message, true)); } },
487
654
  ];
488
655
  // The preset is bundled with the CLI: it has no storage to remove, and hiding it would only
@@ -536,13 +703,13 @@ async function duplicateGraph(source) {
536
703
  if (!created) return;
537
704
  if (state.dirty) { status(`Created "${created.name}". Open it from the list to rename it.`); return; }
538
705
  await openGraph(created.id, { reason: 'duplicate' });
539
- if (state.graph?.id === created.id) status(`Duplicated "${source.name}" - Rename it in Graph settings.`);
706
+ if (state.graph?.id === created.id) status(`Duplicated "${source.name}". Rename it in Graph settings.`);
540
707
  }
541
708
  // Deleting removes the graph, its revisions and its draft history from this machine, and for a
542
709
  // signed-in account the cloud copies stop restoring it. The confirm names that loss: there is no undo.
543
710
  async function deleteGraph(graph) {
544
711
  if (state.saving) { status('Wait for the current save before deleting a graph.'); return; }
545
- if (!confirm(`Delete "${graph.name}"? Its revisions and drafts are removed from this machine.`)) return;
712
+ if (!await askConfirm({ title: `Delete “${graph.name}”?`, message: 'Its versions and drafts are removed from this machine.', confirmLabel: 'Delete', tone: 'danger' })) return;
546
713
  state.saving = true; renderHeading(); renderList();
547
714
  // The confirm accepted the loss of unsaved edits of the deleted graph, so no draft of it may
548
715
  // outlive it: stop its queued write, and let an in-flight one land before the deletion's
@@ -631,7 +798,7 @@ function nodeSubtitle(node) {
631
798
  const nodeIconElement = node => globalThis.AndorraIcons?.icon?.(globalThis.AndorraIcons.nodeIcon(node));
632
799
  function renderCanvas() {
633
800
  $('nodes').replaceChildren(); $('edges').replaceChildren(); $('canvas').classList.toggle('picking-destination',!!state.routePick);
634
- const hintText = state.routePick ? 'Click a destination node · Escape cancels' : 'Ctrl/Cmd-click same-type nodes to select together · Drag or scroll to pan · Pinch or Ctrl/Cmd+scroll to zoom';
801
+ 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';
635
802
  $('canvas-hint-text').textContent = hintText; $('canvas-hint').hidden = !state.routePick && canvasHintDismissed(); $('canvas-hint-close').hidden = !!state.routePick;
636
803
  $('empty').hidden = !!state.graph;
637
804
  if (!state.graph) return;
@@ -649,7 +816,7 @@ function renderCanvas() {
649
816
  button.append(title);
650
817
  const subtitle = nodeSubtitle(node);
651
818
  if (subtitle) { const line = el('small', subtitle); line.title = subtitle; button.append(line); }
652
- 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); }
819
+ 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); }
653
820
  button.onkeydown = event => { if ((event.key === 'Enter' || event.key === ' ') && event.target === button) {event.preventDefault(); selectNode(node,event);} };
654
821
  button.onclick = event => selectNode(node,event);
655
822
  button.onpointerdown = event => {
@@ -770,7 +937,7 @@ function renderEdges() {
770
937
  element.classList.toggle('edge-target',Boolean(active && id===active.target));
771
938
  }
772
939
  const item=rendered.find(item=>item.edge===active);
773
- caption.textContent=item?`${edgeOutcome(item.edge)} -> ${state.graph.nodes[item.edge.target].name}`:'';
940
+ caption.textContent=item?`${edgeOutcome(item.edge)} → ${state.graph.nodes[item.edge.target].name}`:'';
774
941
  if(item){caption.setAttribute('x',String(item.from.x));caption.setAttribute('y',String(item.from.y-14));caption.setAttribute('fill',palette.active);}
775
942
  };
776
943
  // Draw a selected connection last so crossings cannot obscure its direction.
@@ -784,11 +951,11 @@ function renderEdges() {
784
951
  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);
785
952
  halo.setAttribute('d',d);halo.setAttribute('stroke',palette.halo);halo.setAttribute('stroke-width','6');halo.setAttribute('fill','none');halo.style.pointerEvents='none';
786
953
  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';
787
- 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}`);
954
+ 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}`);
788
955
  hit.onclick=event=>{event.stopPropagation();clearSelection();state.selectedEdge=edge;renderInspector();renderCanvas();showInspector();};
789
956
  hit.onkeydown=event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();hit.onclick(event);}};
790
957
  // The connection's hint is the app's tooltip (an SVG title would be the platform's).
791
- hit.setAttribute('data-tip',`${state.graph.nodes[edge.source].name}: ${outcome} -> ${state.graph.nodes[edge.target].name}`);
958
+ hit.setAttribute('data-tip',`${state.graph.nodes[edge.source].name}: ${outcome} → ${state.graph.nodes[edge.target].name}`);
792
959
  hit.onpointerenter=hit.onfocus=()=>emphasize(edge);
793
960
  hit.onpointerleave=hit.onblur=()=>emphasize(state.selectedEdge);
794
961
  const entry={edge,path,halo,arrow,from,pill:null};rendered.push(entry);
@@ -821,7 +988,7 @@ function renderEdges() {
821
988
  function removeNodes(ids) {
822
989
  const graph = state.graph;
823
990
  const remaining = Object.keys(graph.nodes).filter(id => !ids.has(id));
824
- if (!remaining.length) { status('Keep at least one node as the graph start. Add a replacement before deleting all nodes.', true); return; }
991
+ if (!remaining.length) { status('Keep at least one step as the graph start. Add a replacement before deleting all steps.', true); return; }
825
992
  const nextEntry = ids.has(graph.entry)
826
993
  ? graph.edges.find(edge => edge.source === graph.entry && !ids.has(edge.target) && graph.nodes[edge.target])?.target ?? remaining[0]
827
994
  : graph.entry;
@@ -834,7 +1001,7 @@ function removeNodes(ids) {
834
1001
  graph.schemaVersion = 3;
835
1002
  clearSelection();
836
1003
  }, true);
837
- status(`Deleted ${ids.size} node${ids.size === 1 ? '' : 's'} and their connections. Start: ${graph.nodes[nextEntry].name}. Undo restores them.`);
1004
+ status(`Deleted ${ids.size} step${ids.size === 1 ? '' : 's'} and their connections. Start: ${graph.nodes[nextEntry].name}. Undo restores them.`);
838
1005
  }
839
1006
  function deleteSelection() {
840
1007
  if(!state.graph)return;
@@ -873,7 +1040,7 @@ function nodeErrorIds() {
873
1040
  function renderValidation() {
874
1041
  const container=$('validation');if(!container)return;container.replaceChildren();const errors=[...issues(),...state.validationErrors].map(errorEntry);
875
1042
  if(!errors.length)container.append(el('p',state.validated?'Validated · Ready to save':'Checking graph…',state.validated?'valid ok':'valid'));
876
- 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);}
1043
+ 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);}
877
1044
  }
878
1045
  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; }
879
1046
  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; }
@@ -1001,7 +1168,7 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1001
1168
  // model made the provider list read as the whole model list.
1002
1169
  const providers = state.providers.map(p => ({value: idFor(p), label: titleFor(p)}));
1003
1170
  if (target.provider && !providers.some(p => p.value === target.provider)) providers.push({value: target.provider, label: target.provider + ' (unavailable)'});
1004
- const defaultProviderLabel = inheritedProvider ? `Same as parent node (${inheritedProvider})` : state.defaultProvider ? `Use configured default (${state.defaultProvider})` : 'Use configured default';
1171
+ const defaultProviderLabel = inheritedProvider ? `Same as parent agent (${inheritedProvider})` : state.defaultProvider ? `Use configured default (${state.defaultProvider})` : 'Use configured default';
1005
1172
  choice(parent, 'Provider', target.provider || '', [{value:'', label: defaultProviderLabel}, ...providers], value => update({ ...target, provider: value || undefined, model: undefined }));
1006
1173
  if (target.provider && !state.providers.some(p => idFor(p) === target.provider)) providerWarning(parent, target.provider);
1007
1174
  // A providerless subagent child inherits the parent node's provider at execution
@@ -1094,7 +1261,7 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1094
1261
  parent.append(el('p', `This selection follows "${originalId}"'s current model, ${exact.model}.`, 'help'));
1095
1262
  }
1096
1263
  }
1097
- const info = el('p', 'Context window: detecting from model...', 'help model-context'); parent.append(info);
1264
+ const info = el('p', 'Context window: detecting from model…', 'help model-context'); parent.append(info);
1098
1265
  const key = JSON.stringify([target.provider || '', target.model || '', provider?.model || '']);
1099
1266
  // Capture the registry generation before any discovery request starts: a callback resolving
1100
1267
  // after a registry change describes the previous endpoint and must discard itself.
@@ -1243,7 +1410,7 @@ function modelFields(parent, target, update, parentModel, inheritedProvider, fal
1243
1410
  function renderCompletion(parent, node) {
1244
1411
  const graph = state.graph, routing = node.agentRole === 'orchestrator';
1245
1412
  const behavior = choice(parent, routing ? 'Routing behavior' : 'Completion behavior', node.completion?.mode || 'single', [
1246
- {value:'single',label:routing ? 'Continue to connected nodes' : 'Continue when complete'},
1413
+ {value:'single',label:routing ? 'Continue to connected steps' : 'Continue when complete'},
1247
1414
  {value:'outcomes',label:'Choose outcome using written criteria'},
1248
1415
  ], mode => {
1249
1416
  node.completion = mode === 'single' ? {mode,outcome:'completed'} : {mode,outcomes:routing ? ['frontend','backend','devops'] : ['pass','fail','blocked']};
@@ -1252,7 +1419,7 @@ function renderCompletion(parent, node) {
1252
1419
  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.');
1253
1420
  // The server refuses written criteria on a delegating Orchestrator, so the option is withheld
1254
1421
  // rather than offered and then rejected on save.
1255
- 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')); }
1422
+ 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')); }
1256
1423
  if (node.completion?.mode === 'outcomes') {
1257
1424
  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'));
1258
1425
  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'));
@@ -1292,7 +1459,7 @@ function renderCompletion(parent, node) {
1292
1459
  }, true);
1293
1460
  row.append(remove);
1294
1461
  });
1295
- const add = el('button', 'Add outcome');
1462
+ const add = el('button', 'Add Outcome');
1296
1463
  add.disabled = completion.outcomes.length >= 20;
1297
1464
  add.title = 'Up to 20 outcomes per agent';
1298
1465
  add.onclick = () => mutate(() => {
@@ -1323,14 +1490,14 @@ function routes(parent, node) {
1323
1490
  for (const destination of Object.values(state.graph.nodes).filter(n => n.id !== node.id && n.agentRole !== 'orchestrator')) {
1324
1491
  const edge = state.graph.edges.find(e => e.source === node.id && edgeOutcome(e) === outcome && e.target === destination.id);
1325
1492
  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); });
1326
- if (edge) { const edit = el('button', 'Configure handoff', 'link-button'); edit.onclick = () => { state.selectedEdge = edge; state.selected = null; renderInspector(); renderCanvas(); }; row.append(edit); }
1493
+ if (edge) { const edit = el('button', 'Edit Connection', 'link-button'); edit.onclick = () => { state.selectedEdge = edge; state.selected = null; renderInspector(); renderCanvas(); }; row.append(edit); }
1327
1494
  }
1328
1495
  }
1329
1496
  }
1330
1497
  function renderEdgeInspector(parent, edge) {
1331
- $('inspector-title').textContent = 'Connection handoff';
1498
+ $('inspector-title').textContent = 'Connection';
1332
1499
  parent.append(el('h3', `${state.graph.nodes[edge.source]?.name} - ${edgeOutcome(edge)}`), el('p', `To: ${state.graph.nodes[edge.target]?.name}`, 'help'));
1333
- 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'));
1500
+ if (edge.bootstrap) parent.append(el('p', 'Initial connection: starts this updated graph at its original Join. Later loop iterations wait for the other incoming branches. Removing this connection removes that initial-start behavior.', 'help'));
1334
1501
  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'));
1335
1502
  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'));
1336
1503
  for (const [key, value] of Object.entries(edge.inputMapping || {})) {
@@ -1341,11 +1508,11 @@ function renderEdgeInspector(parent, edge) {
1341
1508
  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));
1342
1509
  if (kind === 'constant') jsonField(row, 'Constant value', value.constant, next => set({constant:next}));
1343
1510
  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); } }
1344
- const remove = el('button', 'Remove mapping'); remove.onclick = () => mutate(() => { delete edge.inputMapping[key]; }, true); row.append(remove);
1511
+ const remove = el('button', 'Remove Mapping'); remove.onclick = () => mutate(() => { delete edge.inputMapping[key]; }, true); row.append(remove);
1345
1512
  }
1346
- 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);
1347
- 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);
1348
- 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);
1513
+ 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);
1514
+ 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);
1515
+ 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);
1349
1516
  }
1350
1517
  function effectiveCaps(node = {}) { return node.capabilities || {filesystem:'read-write',shell:'allowed',git:'write',github:'none',browser:'playwright',deployment:'none'}; }
1351
1518
  // Browser copy of src/tool-names.ts. The server treats these spellings as aliases of the canonical
@@ -1370,7 +1537,7 @@ function canonicalToolName(name) { const d = displayToolName(name); return SHELL
1370
1537
  // Browser copy of permitsBuiltInTool in src/graphs.ts for a delegated worktree child, the one
1371
1538
  // kind of subagent that runs commands. The server validates a writing role's tools with that rule,
1372
1539
  // so a tool offered here that it refuses could be ticked and then fail validation.
1373
- const QA_TOOL_NAMES = ['qa.inspect_project', 'qa.status', 'qa.fast', 'qa.deep', 'qa.test', 'qa.terminal', 'qa.security', 'qa.browser'];
1540
+ const QA_TOOL_NAMES = ['qa.terminal', 'qa.browser'];
1374
1541
  function delegatedRolePermits(caps, name) {
1375
1542
  const display = displayToolName(name);
1376
1543
  // Mirrors canRunCommands in src/graphs.ts: the shell setting alone grants commands.
@@ -1415,7 +1582,7 @@ function renderSubagents(parent, node) {
1415
1582
  // The server refuses writing roles on an Orchestrator outside separate worktrees, so the
1416
1583
  // editor moves the policy there as soon as a role may write.
1417
1584
  const requireWorktree = () => { if (node.agentRole === 'orchestrator' && (policy.roles || []).some(isWritingRole)) set({workspace:'worktree'}); };
1418
- 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});
1585
+ 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});
1419
1586
  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}));
1420
1587
  // Mirrors bindPortableGraphProviders: enabled retry attempts may spawn providerless children on
1421
1588
  // the fallback provider, so a discovered child pick must be recorded there as well.
@@ -1447,20 +1614,20 @@ function renderSubagents(parent, node) {
1447
1614
  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';});
1448
1615
  }
1449
1616
  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;});
1450
- const remove=el('button','Remove role');remove.onclick=()=>mutate(()=>{set({roles:policy.roles.filter(r=>r!==role)});pruneRoutes(node);},true);body.append(remove);
1617
+ const remove=el('button','Remove Role');remove.onclick=()=>mutate(()=>{set({roles:policy.roles.filter(r=>r!==role)});pruneRoutes(node);},true);body.append(remove);
1451
1618
  }
1452
- 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);
1619
+ 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);
1453
1620
  }
1454
1621
  function renderControlInspector(parent,node) {
1455
1622
  if(node.type==='join')choice(parent,'Wait for branches',node.join?.mode||'all',['all','any'],value=>{node.join={mode:value};});
1456
1623
  if(node.type==='loop')field(parent,'Maximum loop iterations',node.loop?.maxIterations??3,value=>{node.loop={maxIterations:value};},{type:'number',min:1});
1457
1624
  if(node.type==='condition') {
1458
- 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};});
1625
+ 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};});
1459
1626
  field(parent,'Output field path',node.condition?.path||'',value=>{node.condition={source:'',equals:true,...node.condition,path:value};});
1460
1627
  jsonField(parent,'Equals',node.condition?.equals??true,value=>{node.condition={source:'',path:'',...node.condition,equals:value};});
1461
1628
  }
1462
1629
  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});}
1463
- if(node.type==='parallel')parent.append(el('p','All completed connections become ready. A Parallel node is optional for ordinary outcome fan-out.', 'help'));
1630
+ if(node.type==='parallel')parent.append(el('p','All completed connections become ready. A Parallel step is optional for ordinary outcome fan-out.', 'help'));
1464
1631
  if(node.type==='approval')parent.append(el('p','The CLI asks for approval. Route approved and rejected separately.', 'help'));
1465
1632
  }
1466
1633
  function setAgentModifier(node, kind, value) {
@@ -1490,7 +1657,7 @@ function scalarField(parent, label, value, update) {
1490
1657
  function renderModifiers(parent, node) {
1491
1658
  if (node.agentRole === 'orchestrator') return;
1492
1659
  const group = disclosure(parent, 'Modifiers', Boolean(node.modifiers && Object.keys(node.modifiers).length));
1493
- group.append(el('p','Add behavior to this agent without extra control nodes.','help'));
1660
+ group.append(el('p','Add behavior to this agent without extra control steps.','help'));
1494
1661
  check(group, 'Condition modifier', Boolean(node.modifiers?.condition), enabled => setAgentModifier(node,'condition',enabled ? {path:'approved',equals:true} : undefined));
1495
1662
  if (node.modifiers?.condition) {
1496
1663
  const config = node.modifiers.condition;
@@ -1501,11 +1668,11 @@ function renderModifiers(parent, node) {
1501
1668
  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));
1502
1669
  if (node.modifiers?.loop) {
1503
1670
  const config = node.modifiers.loop;
1504
- field(group,'Maximum attempts',config.maxIterations,value=>{config.maxIterations=value;},{type:'number',min:1,max:100});
1671
+ field(group,'Maximum tries',config.maxIterations,value=>{config.maxIterations=value;},{type:'number',min:1,max:100});
1505
1672
  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}});});
1506
1673
  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}});});
1507
1674
  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;}); }
1508
- 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'));
1675
+ 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'));
1509
1676
  }
1510
1677
  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}:{})}));
1511
1678
  if (node.modifiers?.parallel) {
@@ -1529,10 +1696,10 @@ function hasRetryCycle(graph) {
1529
1696
  function retryLimitHelp(parent, graph) {
1530
1697
  if (!hasRetryCycle(graph) || graph.limits?.maxNodeVisits || graph.limits?.wallTimeMs) return;
1531
1698
  const box = el('div', undefined, 'cycle-help');
1532
- 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.'));
1533
- const fix = el('button', 'Limit each node to 3 visits');
1699
+ 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 step, or give the run a wall clock. Without one the cycle never ends.'));
1700
+ const fix = el('button', 'Limit Each Step to 3 Visits');
1534
1701
  fix.onclick = () => mutate(() => { graph.limits = {...graph.limits, maxNodeVisits:3}; }, true);
1535
- const clock = el('button', 'Give the run 30 minutes');
1702
+ const clock = el('button', 'Give the Run 30 Minutes');
1536
1703
  clock.onclick = () => mutate(() => { graph.limits = {...graph.limits, wallTimeMs:30 * 60_000}; }, true);
1537
1704
  box.append(fix, clock); parent.append(box);
1538
1705
  }
@@ -1541,7 +1708,7 @@ function renderInspector() {
1541
1708
  document.body?.classList?.remove?.('prompt-fullscreen'); for (const backdrop of document.querySelectorAll?.('.prompt-backdrop') ?? []) backdrop.remove();
1542
1709
  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; }
1543
1710
  if (state.selectedEdge && !graph.edges.includes(state.selectedEdge)) state.selectedEdge = null;
1544
- const node = graph.nodes[state.selected]; $('inspector-title').textContent = node ? 'Node settings' : 'Graph settings';
1711
+ const node = graph.nodes[state.selected]; $('inspector-title').textContent = node ? 'Step settings' : 'Graph settings';
1545
1712
  $('graph-settings').hidden = !node && !state.selectedEdge && selectedNodes().length <= 1;
1546
1713
  retryLimitHelp(parent, graph);
1547
1714
  if (state.selectedEdge) renderEdgeInspector(parent, state.selectedEdge);
@@ -1549,9 +1716,9 @@ function renderInspector() {
1549
1716
  else if (!node) {
1550
1717
  const panels = inspectorTabs(parent, ['general', 'behavior', 'advanced']); const general = panels.general;
1551
1718
  field(general, 'Graph name', graph.name, value => { graph.name = value; renderList(); }, {maxLength:200});
1552
- const meta = el('p', `${graph.id} · Revision ${graph.revision}`, 'mono graph-meta'); meta.title = graph.id; general.append(meta);
1719
+ const meta = el('p', `${graph.id} · Version ${graph.revision}`, 'mono graph-meta'); meta.title = graph.id; general.append(meta);
1553
1720
  if (graph.id === 'default') general.append(el('p', 'Duplicate this bundled preset to save your customization.', 'help'));
1554
- 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.');
1721
+ 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.');
1555
1722
  field(general, 'Description', graph.metadata?.description, value => {graph.metadata={...graph.metadata,description:value};}, {multiline:true,maxLength:2000});
1556
1723
  const widgetGroup = disclosure(panels.behavior, 'Widgets', true);
1557
1724
  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'));
@@ -1559,18 +1726,18 @@ function renderInspector() {
1559
1726
  const label = `Widget ${index + 1} name`;
1560
1727
  field(widgetGroup, label, widget.name, value => { widget.name = value; }, {maxLength:80,refresh:true});
1561
1728
  field(widgetGroup, `Widget ${index + 1} description`, widget.description, value => { widget.description = value; }, {multiline:true,maxLength:1000});
1562
- const remove = el('button','Remove widget','danger');
1729
+ const remove = el('button','Remove Widget','danger');
1563
1730
  remove.onclick = () => mutate(() => { graph.widgets = (graph.widgets ?? []).filter(item => item !== widget); if (!graph.widgets.length) delete graph.widgets; }, true);
1564
1731
  widgetGroup.append(remove);
1565
1732
  }
1566
1733
  if ((graph.widgets ?? []).length < 5) {
1567
- const add = el('button','Add widget');
1734
+ const add = el('button','Add Widget');
1568
1735
  add.onclick = () => mutate(() => { graph.widgets = [...(graph.widgets ?? []), { id: `widget-${crypto.randomUUID().slice(0,8)}`, name: '', description: '' }]; }, true);
1569
1736
  widgetGroup.append(add);
1570
1737
  widgetGroup.append(el('p','Up to 5 widgets per graph. Names and descriptions are required before saving.','help'));
1571
1738
  } else widgetGroup.append(el('p','Widget limit reached (5).','help'));
1572
- 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});
1573
- 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.');
1739
+ 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});
1740
+ explain(visits,'0 means unlimited, which is the default. A return connection repeats a step, so a graph with one needs a ceiling: a visit limit, or a wall clock. An agent Loop modifier has its own try limit.');
1574
1741
  // Per-graph desktop settings render here; a browser-launched studio has no host bridge and skips them.
1575
1742
  window.AndorraEmbed?.inspector?.(general);
1576
1743
  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;});
@@ -1578,15 +1745,15 @@ function renderInspector() {
1578
1745
  const panels = inspectorTabs(parent, node.type === 'agent' ? ['general', 'model', 'behavior', 'advanced'] : outcomes(node).length ? ['general', 'behavior', 'advanced'] : ['general', 'advanced']);
1579
1746
  const general = panels.general; field(general, 'Name', node.name, value => {node.name=value;}, {maxLength:200});
1580
1747
  if (node.type === 'agent') {
1581
- 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'));}
1748
+ 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'));}
1582
1749
  const prompt = promptField(general, 'Prompt', node.instruction ?? node.prompt ?? '', value => {node.instruction=value; delete node.prompt;}, { placeholder: 'Type / to add a skill' });
1583
- 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.');
1750
+ explain(prompt, 'Edit the instructions for this agent. Save the graph 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 graph.');
1584
1751
  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.');
1585
1752
  const model = panels.model;
1586
1753
  modelFields(model, node, value => {node.provider=value.provider; node.model=value.model;});
1587
1754
  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};});
1588
- 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.');
1589
- 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};});
1755
+ 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.');
1756
+ const skills = choice(model, 'Skill inheritance', node.contextPolicy?.skillInheritance ?? 'inherit', [{value:'inherit',label:'Inherit active graph skills'}, {value:'none',label:'Do not inherit skills'}], value => {node.contextPolicy={...node.contextPolicy,skillInheritance:value};});
1590
1757
  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.');
1591
1758
  renderCompletion(section(panels.behavior, node.agentRole === 'orchestrator' ? 'Routing' : 'Outcomes and conditions'), node);
1592
1759
  renderModifiers(panels.behavior, node);
@@ -1595,7 +1762,7 @@ function renderInspector() {
1595
1762
  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;});
1596
1763
  renderSubagents(disclosure(advanced,'Subagents'),node);
1597
1764
  const limits = disclosure(advanced,'Execution limits');
1598
- 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});
1765
+ 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});
1599
1766
  // Iterations and wall time default to blank, and blank means unlimited. The editor must
1600
1767
  // not invent a bound the author never chose: a task that legitimately runs for hours
1601
1768
  // should not be cut short, and a person answering a question is never on the clock.
@@ -1606,15 +1773,15 @@ function renderInspector() {
1606
1773
  // Tool calls default to blank, and blank means unlimited: an absent limit is only
1607
1774
  // written when the field is cleared, so a node keeps its ceiling once one is set.
1608
1775
  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'});
1609
- 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};});
1776
+ 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};});
1610
1777
  field(advanced,'Executor','react-basic',()=>{}).disabled=true;
1611
1778
  const tools = disclosure(advanced,'Tool allowlist');
1612
1779
  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);});
1613
- const saveDefinition = el('button','Save agent variant'); saveDefinition.onclick=()=>saveAgentVariant(node); general.append(saveDefinition);
1614
- } else { general.append(el('p', 'This control node does not call a model and has no agent prompt.', 'help')); renderControlInspector(general,node); }
1780
+ const saveDefinition = el('button','Save to Library'); saveDefinition.onclick=()=>saveAgentVariant(node); general.append(saveDefinition);
1781
+ } else { general.append(el('p', 'This control step does not call a model and has no agent prompt.', 'help')); renderControlInspector(general,node); }
1615
1782
  if (panels.behavior) routes(panels.behavior,node);
1616
1783
  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});
1617
- 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);
1784
+ 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 graph. 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);
1618
1785
  }
1619
1786
  const validation=section(parent,'Validation');validation.id='validation';renderValidation();
1620
1787
  window.AndorraStudio?.inspector?.(parent, node);
@@ -1625,9 +1792,10 @@ function render() { renderHeading(); renderList(); renderLibrary(); renderCanvas
1625
1792
  // the graph was opened.
1626
1793
  async function openGraph(id, options = {}) {
1627
1794
  if (state.saving) { status('Wait for the current save before opening another graph.'); return false; }
1795
+ if (graphLocked(id)) { status(FREE_LOCKED_TIP, true); return false; }
1628
1796
  if (state.dirty && !options.discard && !await askConfirm(DISCARD_QUESTION)) return false;
1629
1797
  // 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.
1630
- 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 ? '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'); graphOpened(options.reason || 'open'); return true; } catch (error) { status(error.message, true); return false; }
1798
+ 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; markSaved(state.dirty ? null : state.graph); clearSelection(); state.undo = []; state.redo = []; state.pendingProviderNodes = null; render(); fit(); status(migrated ? 'This graph was updated to the current format. Save to keep it.' : capMoved ? 'Orchestrator Max subagents moved to Advanced > Subagents. Save to keep it.' : 'Graph loaded'); graphOpened(options.reason || 'open'); return true; } catch (error) { status(error.message, true); return false; }
1631
1799
  }
1632
1800
  function newId() { return `graph-${crypto.randomUUID()}`; }
1633
1801
  function newGraph(duplicate = false, discarded = false) {
@@ -1639,13 +1807,13 @@ function newGraph(duplicate = false, discarded = false) {
1639
1807
  else if (freeTier()) {
1640
1808
  // A free graph starts from the Software Engineer alone: the Orchestrator is a Premium node.
1641
1809
  const engineerPreset=state.definitions.find(definition=>definition.id==='software-engineer')?.node;
1642
- if(!engineerPreset){status('Starting presets are unavailable. Reload the Graph Builder and try again.',true);return;}
1810
+ if(!engineerPreset){status('Starting presets are unavailable. Reload the Graph Editor and try again.',true);return;}
1643
1811
  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'}]};
1644
1812
  }
1645
1813
  else {
1646
1814
  const orchestratorPreset=state.definitions.find(definition=>definition.node.agentRole==='orchestrator')?.node;
1647
1815
  const engineerPreset=state.definitions.find(definition=>definition.id==='software-engineer')?.node;
1648
- if(!orchestratorPreset || !engineerPreset){status('Starting presets are unavailable. Reload the Graph Builder and try again.',true);return;}
1816
+ if(!orchestratorPreset || !engineerPreset){status('Starting presets are unavailable. Reload the Graph Editor and try again.',true);return;}
1649
1817
  const orchestrator={...copy(orchestratorPreset),id:'orchestrator',position:{x:0,y:0}};
1650
1818
  const engineer={...copy(engineerPreset),id:'engineer',position:{x:320,y:0}};
1651
1819
  const inputMapping={originalTask:'$run.input.task'};
@@ -1654,10 +1822,10 @@ function newGraph(duplicate = false, discarded = false) {
1654
1822
  }
1655
1823
  // A duplicate copies the open graph, providerless nodes included, so its unmet provider
1656
1824
  // requirements travel with it; an unrelated new graph starts without any.
1657
- state.dirty = true; clearSelection(); state.undo = []; state.redo = [];
1825
+ markSaved(null); state.dirty = true; clearSelection(); state.undo = []; state.redo = [];
1658
1826
  state.untouched = JSON.stringify(state.graph);
1659
1827
  state.pendingProviderNodes = duplicate ? new Set(state.pendingProviderNodes ?? []) : null;
1660
- render(); fit(); status('New graph - Customize your agent and save your first revision');
1828
+ render(); fit(); status('New graph · Customize your agent, then save');
1661
1829
  graphOpened(duplicate ? 'duplicate' : 'new');
1662
1830
  }
1663
1831
  // The settings a new Agent starts from, whether it is dropped on the canvas or added to the list.
@@ -1677,7 +1845,7 @@ function addNode(type, definition, dropPosition) {
1677
1845
  const canResearch = definition.capabilities?.filesystem !== 'none' &&
1678
1846
  (definition.tools === undefined || ['Read','Glob','Grep','repo_explore'].some(tool => researchTools.includes(tool)));
1679
1847
  if (!canResearch) {
1680
- 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);
1848
+ 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);
1681
1849
  return;
1682
1850
  }
1683
1851
  // Saved definitions can predate intake's required research and clarification.
@@ -1703,7 +1871,7 @@ function addNode(type, definition, dropPosition) {
1703
1871
  clearSelection(); state.selected = existing.id; state.selectedIds = [existing.id];
1704
1872
  }, true);
1705
1873
  showInspector();
1706
- status('Starting Orchestrator definition applied. Matching routes and handoffs were kept; validate mappings before saving. Undo restores the previous definition.');
1874
+ status('Saved Orchestrator applied. Matching routes and connections were kept; check their inputs before saving. Undo restores the previous definition.');
1707
1875
  return;
1708
1876
  }
1709
1877
  }
@@ -1766,9 +1934,9 @@ function requireAgentName(input) {
1766
1934
  function saveAgentVariant(node) {
1767
1935
  const name = el('input'); name.value = node.name; name.required = true; name.maxLength = 200;
1768
1936
  const snapshot = copy(node), id = `definition-${crypto.randomUUID()}`;
1769
- libraryDialog('Save Agent variant', [['Variant name', name]], async () => {
1937
+ libraryDialog('Save agent to library', [['Name', name]], async () => {
1770
1938
  const agentName = requireAgentName(name);
1771
- await writeDefinition({schemaVersion:2, id, name:agentName, description:'', revision:0, node:{...snapshot,name:agentName}}, 'Agent variant saved');
1939
+ await writeDefinition({schemaVersion:2, id, name:agentName, description:'', revision:0, node:{...snapshot,name:agentName}}, 'Saved to library');
1772
1940
  });
1773
1941
  }
1774
1942
  // Truncation counts the field's own unit (UTF-16 code units) but must not cut between the two
@@ -1804,7 +1972,7 @@ function addAgent() {
1804
1972
  libraryDialog('Add agent', [['Agent name', name], ['Description', description], ['Instructions', instruction]], async () => {
1805
1973
  const agentName = requireAgentName(name);
1806
1974
  await writeDefinition({schemaVersion:2, id, name:agentName, description:description.value.trim(), revision:0, node:{id:'agent', type:'agent', name:agentName, ...blankAgentSettings(), instruction:instruction.value.trim()}}, `Agent ${agentName} added`);
1807
- }, 'Add agent');
1975
+ }, 'Add Agent');
1808
1976
  skillPrompt(instruction);
1809
1977
  }
1810
1978
  // The server's 512 KiB limit applies to the import request, not the file: Share pretty-prints its
@@ -1854,7 +2022,7 @@ async function shareAgent(definition) {
1854
2022
  // Built-in Agents have no Delete. Graphs that already use a deleted Agent keep their own copy.
1855
2023
  async function deleteAgent(definition) {
1856
2024
  if (definition.preset) return;
1857
- if (!confirm(`Delete the Agent "${definition.name}"? Graphs that already use it keep their own copy. This cannot be undone.`)) return;
2025
+ if (!await askConfirm({ title: `Delete the Agent “${definition.name}”?`, message: 'Graphs that already use it keep their own copy. This cannot be undone.', confirmLabel: 'Delete', tone: 'danger' })) return;
1858
2026
  try { await api(`/api/definitions/${encodeURIComponent(definition.id)}`, undefined, { method: 'DELETE' }); }
1859
2027
  catch (error) {
1860
2028
  // A lost response can still have deleted it, so the refreshed list decides what is reported.
@@ -1898,7 +2066,7 @@ async function writeDefinition(payload, saved) {
1898
2066
  function renderLibrary() {
1899
2067
  const container = $('node-library'); container.replaceChildren();
1900
2068
  const query = $('node-search').value.toLowerCase();
1901
- const definitionItem = d => ({name:d.name,type:'agent',description:d.preset ? 'Editable Agent preset' : `Saved variant - r${d.revision}`,node:d.node,definition:d});
2069
+ const definitionItem = d => ({name:d.name,type:'agent',description:d.preset ? 'Editable Agent preset' : `Saved agent · version ${d.revision}`,node:d.node,definition:d});
1902
2070
  const addItem = (parent, item) => {
1903
2071
  // A library item drags onto the canvas; a click, Enter or Space adds it, so the library stays
1904
2072
  // usable without a pointer. The type icon is placed first by the stylesheet's grid.
@@ -1921,7 +2089,7 @@ function renderLibrary() {
1921
2089
  const freeRefusal = freeNodeRefusal([{ type: item.type, agentRole: item.node?.agentRole }]);
1922
2090
  if (freeRefusal) button.title = freeRefusal;
1923
2091
  button.disabled = cannotAdd && !item.definition; button.draggable = !button.disabled && !freeRefusal;
1924
- 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); };
2092
+ button.onclick = () => { if (cannotAdd) { status(state.graph ? 'Graph step limit reached.' : 'Open a graph to add this Agent.', true); return; } addNode(item.type, item.node); };
1925
2093
  button.ondragstart = event => { event.dataTransfer.setData('application/andorra-node', JSON.stringify({name:item.name,type:item.type,node:item.node})); event.dataTransfer.effectAllowed = 'copy'; };
1926
2094
  row.append(button);
1927
2095
  // An Agent's actions are secondary, so they open from a right-click on the row (which the
@@ -1956,8 +2124,8 @@ function renderLibrary() {
1956
2124
  parent.append(group); return group;
1957
2125
  };
1958
2126
  const agents = section(container, 'agents', 'Agents', [
1959
- {id:'add', name:'Add agent', description:'Create a new Agent in this list', icon:'plus', title:'Create a new Agent and add it to this list', action:addAgent},
1960
- {id:'import', name:'Import agent', description:'Add an Agent from a shared JSON file', icon:'upload', title:'Import an Agent shared from Andorra Code', action:importAgent, last:true},
2127
+ {id:'add', name:'Add Agent', description:'Create a new Agent in this list', icon:'plus', title:'Create a new Agent and add it to this list', action:addAgent},
2128
+ {id:'import', name:'Import Agent', description:'Add an Agent from a shared JSON file', icon:'upload', title:'Import an Agent shared from Andorra Code', action:importAgent, last:true},
1961
2129
  ...state.definitions.filter(d=>d.preset).map(definitionItem),
1962
2130
  ...state.definitions.filter(d=>!d.preset).map(definitionItem),
1963
2131
  ]);
@@ -1965,6 +2133,7 @@ function renderLibrary() {
1965
2133
  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]})));
1966
2134
  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'}]);
1967
2135
  section(container,'flow','Flow',[{name:'Human approval',type:'approval',description:'Pause for a decision'},{name:'End',type:'end',description:'Finish this graph path'}]);
2136
+ if (query && !container.children.length) container.append(emptyState('search', 'No steps match', 'Try another name, or clear the search.'));
1968
2137
  }
1969
2138
  // Fit, Arrange and the zoom buttons ease the view to where it is going, over --dur-3 on an ease-in-out
1970
2139
  // with no overshoot, so the eye can follow the cards. A gesture (pan, pinch, wheel) stops the ease and
@@ -2012,12 +2181,12 @@ function zoomBy(factor) {
2012
2181
  }
2013
2182
  // A keyboard-activated click carries no pointer coordinates, so the menu falls back to the
2014
2183
  // window corner rather than refusing to open.
2015
- $('new-graph').onclick = event => showNewGraphMenu(event?.clientX ?? 0, event?.clientY ?? 0); $('duplicate').onclick = () => newGraph(true); $('search').oninput = renderList;
2184
+ $('new-graph').onclick = event => showNewGraphMenu(event?.clientX ?? 0, event?.clientY ?? 0); $('empty-create').onclick = () => newGraph(); $('duplicate').onclick = () => newGraph(true); $('search').oninput = renderList;
2016
2185
  $('node-search').oninput = renderLibrary;
2017
2186
  $('graph-settings').onclick = () => { clearSelection(); renderCanvas(); renderInspector(); };
2018
2187
  $('toggle-inspector').onclick = () => { const hidden = $('inspector').classList.toggle('hidden'); $('toggle-inspector').setAttribute('aria-expanded', String(!hidden)); };
2019
- $('undo').onclick = () => { if (!state.undo.length) return; state.redo.push(copy(state.graph)); state.graph = state.undo.pop(); clearSelection(); state.dirty = true; render(); status('Change undone'); };
2020
- $('redo').onclick = () => { if (!state.redo.length) return; state.undo.push(copy(state.graph)); state.graph = state.redo.pop(); clearSelection(); state.dirty = true; render(); status('Change restored'); };
2188
+ $('undo').onclick = () => { if (!state.undo.length) return; state.redo.push(copy(state.graph)); state.graph = state.undo.pop(); clearSelection(); refreshDirty(); render(); status(state.dirty ? 'Change undone' : 'Change undone · No unsaved changes'); };
2189
+ $('redo').onclick = () => { if (!state.redo.length) return; state.undo.push(copy(state.graph)); state.graph = state.redo.pop(); clearSelection(); refreshDirty(); render(); status('Change restored'); };
2021
2190
  // A refused Save briefly pulses the outlined nodes, so the eye finds the cards it must fix
2022
2191
  // before the run can be saved. No re-render happens on that early return, so the class lives.
2023
2192
  function pulseErrorNodes() {
@@ -2044,7 +2213,7 @@ $('save').onclick = async () => {
2044
2213
  try { const submitted = dropLegacyTokenFields(copy(state.graph)); const graph = await api('/api/graphs', submitted); if (state.graph.id === submitted.id) {
2045
2214
  // The draft marker is editor state, not graph content, so a difference in it alone is not an edit.
2046
2215
  const liveView = { ...state.graph }; delete liveView.pendingProviderNodes;
2047
- 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(); }
2216
+ const edited = JSON.stringify(liveView) !== JSON.stringify(submitted); markSaved(graph); if (edited) { state.graph.revision = graph.revision; adoptServerStamps(graph); state.undo = []; state.redo = []; refreshDirty(); } 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(); }
2048
2217
  };
2049
2218
  $('canvas-hint-close').onclick = dismissCanvasHint;
2050
2219
  $('fit').onclick = () => fit(true); $('zoom-in').onclick = () => zoomBy(1.2); $('zoom-out').onclick = () => zoomBy(1 / 1.2);
@@ -2117,13 +2286,16 @@ if (token) setTimeout(refreshCloudState, 1000);
2117
2286
  system notification (a Windows toast) fire when the CLI waits on the user. Every browser
2118
2287
  entry point is feature-detected because this module also loads into partial-DOM harnesses.
2119
2288
  The idle favicon is the published Andorra Labs logo; the two busy states are status markers
2120
- rather than the brand, so they keep their own artwork. */
2121
- const baseTitle = document.title || 'Graph studio - Andorra Code';
2289
+ rather than the brand, so they keep their own artwork, drawn in the theme's neutral inks when they
2290
+ are set: both stand on the neutral accent's tile, with the turning ring or the wait's mark in the
2291
+ ink that sits on it, so either reads on a light or a dark tab strip. The chrome keeps no amber
2292
+ (P-LNT-16). Each fallback is the dark token's own value, for a page without the stylesheet. */
2293
+ const baseTitle = document.title || 'Graph Editor · Andorra Code';
2122
2294
  const faviconHref = svg => 'data:image/svg+xml,' + encodeURIComponent(svg);
2123
2295
  const FAVICONS = {
2124
- idle: '/andorra-logo.png',
2125
- running: faviconHref('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="11" fill="none" stroke="#8d8d96" stroke-width="4" opacity="0.45"/><g><path d="M16 5a11 11 0 0 1 11 11" fill="none" stroke="#5b5b63" stroke-width="4" stroke-linecap="round"/><animateTransform attributeName="transform" attributeType="XML" type="rotate" from="0 16 16" to="360 16 16" dur="0.9s" repeatCount="indefinite"/></g></svg>'),
2126
- 'awaiting-input': faviconHref('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#D97706"/><rect x="14" y="7" width="4" height="13" rx="2" fill="#fff"/><circle cx="16" cy="24.5" r="2.4" fill="#fff"/></svg>'),
2296
+ idle: () => '/andorra-logo.png',
2297
+ running: () => faviconHref(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="${themeColor('--accent', '#ececec')}"/><circle cx="16" cy="16" r="9" fill="none" stroke="${themeColor('--on-accent', '#141414')}" stroke-width="3.5" opacity="0.36"/><g><path d="M16 7a9 9 0 0 1 9 9" fill="none" stroke="${themeColor('--on-accent', '#141414')}" stroke-width="3.5" stroke-linecap="round"/><animateTransform attributeName="transform" attributeType="XML" type="rotate" from="0 16 16" to="360 16 16" dur="${themeColor('--loop-spin', '1s')}" repeatCount="indefinite"/></g></svg>`),
2298
+ 'awaiting-input': () => faviconHref(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="${themeColor('--accent', '#ececec')}"/><rect x="14" y="7" width="4" height="13" rx="2" fill="${themeColor('--on-accent', '#141414')}"/><circle cx="16" cy="24.5" r="2.4" fill="${themeColor('--on-accent', '#141414')}"/></svg>`),
2127
2299
  };
2128
2300
  function setFavicon(activity) {
2129
2301
  try {
@@ -2133,7 +2305,7 @@ function setFavicon(activity) {
2133
2305
  link.setAttribute('rel', 'icon');
2134
2306
  (document.head || document.body).append(link);
2135
2307
  }
2136
- const href = FAVICONS[activity] || FAVICONS.idle;
2308
+ const href = (FAVICONS[activity] || FAVICONS.idle)();
2137
2309
  link.setAttribute('type', href.startsWith('data:') ? 'image/svg+xml' : 'image/png');
2138
2310
  link.setAttribute('href', href);
2139
2311
  } catch { /* A partial DOM cannot host a favicon. */ }
@@ -2146,14 +2318,16 @@ function applyActivity(value) {
2146
2318
  if (typeof applyProviderRegistry === 'function') applyProviderRegistry(value);
2147
2319
  if (!Object.hasOwn(FAVICONS, value.state)) return;
2148
2320
  setFavicon(value.state);
2149
- document.title = value.state === 'running' ? `Running · ${baseTitle}` : value.state === 'awaiting-input' ? `Input needed · ${baseTitle}` : baseTitle;
2321
+ // One phrase for a run waiting on the person, the desktop's (P-ATN-07): "Needs your input".
2322
+ document.title = value.state === 'running' ? `Running · ${baseTitle}` : value.state === 'awaiting-input' ? `Needs your input · ${baseTitle}` : baseTitle;
2150
2323
  const activityKey = JSON.stringify([value.state, value.runId, value.updatedAt, value.kind, value.detail]);
2151
2324
  // Native-app notifications are requested by the top-level Tauri window. Browsers
2152
2325
  // deny permission requests from cross-origin iframes, so relay only safe status.
2153
2326
  window.AndorraEmbed?.activity?.(value);
2154
2327
  if ((!window.parent || window.parent === window) && value.state === 'awaiting-input' &&
2155
2328
  lastActivityKey !== activityKey && typeof Notification === 'function' && Notification.permission === 'granted') {
2156
- try { new Notification('Andorra Code needs your input', { body: value.detail || 'Open the terminal to answer.', tag: 'andorra-activity' }); } catch { /* The favicon and title still changed. */ }
2329
+ // The desktop's own notice for the same state (desktop/src/engine/taskNotifications.ts).
2330
+ try { new Notification('Needs your input', { body: value.detail || 'A graph run is waiting for your answer in its terminal.', tag: 'andorra-activity' }); } catch { /* The favicon and title still changed. */ }
2157
2331
  }
2158
2332
  lastActivityKey = activityKey;
2159
2333
  }
@@ -2203,4 +2377,4 @@ setFavicon('idle');
2203
2377
  if (token) watchActivity();
2204
2378
  try { if ((!window.parent || window.parent === window) && typeof Notification === 'function' && Notification.permission === 'default') { window.addEventListener('pointerdown', requestActivityNotifications); window.addEventListener('keydown', requestActivityNotifications); } } catch { /* Partial DOM. */ }
2205
2379
 
2206
- (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); } })();
2380
+ (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 (!wantsNew && await reopenRemembered()) { /* The graph this tab had open before it reloaded. */ } 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 versions are unchanged.', true); } catch (error) { status(error.message, true); } })();