@andorra-labs/code 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/THIRD_PARTY_NOTICES.md +2 -1
  2. package/dist/src/account-presentation.d.ts +11 -0
  3. package/dist/src/account-presentation.js +29 -2
  4. package/dist/src/agent-execution.js +57 -4
  5. package/dist/src/agent-mcp.d.ts +12 -0
  6. package/dist/src/agent-mcp.js +81 -2
  7. package/dist/src/app-server/protocol.d.ts +120 -1
  8. package/dist/src/app-server/protocol.js +8 -1
  9. package/dist/src/app-server/reasoning.d.ts +0 -8
  10. package/dist/src/app-server/reasoning.js +15 -28
  11. package/dist/src/app-server.d.ts +32 -0
  12. package/dist/src/app-server.js +214 -21
  13. package/dist/src/auth/AuthManager.d.ts +15 -0
  14. package/dist/src/auth/AuthManager.js +66 -7
  15. package/dist/src/auth/index.d.ts +1 -1
  16. package/dist/src/auth/index.js +1 -1
  17. package/dist/src/auth/store.d.ts +17 -1
  18. package/dist/src/auth/store.js +25 -2
  19. package/dist/src/browser-runner.js +1 -2
  20. package/dist/src/browser-server.js +10 -2
  21. package/dist/src/browser-session.js +6 -2
  22. package/dist/src/browser-stealth.d.ts +29 -0
  23. package/dist/src/browser-stealth.js +166 -0
  24. package/dist/src/browser-ui/app.js +123 -28
  25. package/dist/src/browser-ui/icons/chevron-right.svg +8 -0
  26. package/dist/src/browser-ui/index.html +8 -8
  27. package/dist/src/browser-ui/style.css +199 -171
  28. package/dist/src/browser-ui/tokens.css +198 -0
  29. package/dist/src/browser-view.d.ts +57 -9
  30. package/dist/src/browser-view.js +187 -36
  31. package/dist/src/cli.js +31 -9
  32. package/dist/src/coding-tools.js +9 -5
  33. package/dist/src/command-screens.js +4 -4
  34. package/dist/src/commands.d.ts +1 -1
  35. package/dist/src/commands.js +3 -2
  36. package/dist/src/completion-gates.d.ts +35 -0
  37. package/dist/src/completion-gates.js +25 -0
  38. package/dist/src/completion.d.ts +7 -1
  39. package/dist/src/completion.js +37 -4
  40. package/dist/src/config.d.ts +1 -1
  41. package/dist/src/config.js +2 -2
  42. package/dist/src/context-budget.d.ts +11 -0
  43. package/dist/src/context-budget.js +13 -0
  44. package/dist/src/decision/DecisionEngine.d.ts +5 -1
  45. package/dist/src/decision/DecisionManager.d.ts +1 -0
  46. package/dist/src/decision/DecisionManager.js +14 -3
  47. package/dist/src/decision/FactContinuations.d.ts +6 -0
  48. package/dist/src/decision/FactContinuations.js +9 -1
  49. package/dist/src/decision/FactServiceGate.js +1 -1
  50. package/dist/src/decision/checks.js +1 -1
  51. package/dist/src/decision/hostedSkills.d.ts +37 -0
  52. package/dist/src/decision/hostedSkills.js +64 -0
  53. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +10 -2
  54. package/dist/src/decision/providers/AndorraDecisionProvider.js +121 -10
  55. package/dist/src/default-graph.d.ts +11 -0
  56. package/dist/src/default-graph.js +20 -0
  57. package/dist/src/duration.d.ts +13 -2
  58. package/dist/src/duration.js +27 -3
  59. package/dist/src/file-diff.d.ts +105 -0
  60. package/dist/src/file-diff.js +244 -0
  61. package/dist/src/graph-manager-chat.d.ts +302 -0
  62. package/dist/src/graph-manager-chat.js +940 -0
  63. package/dist/src/graph-runner.js +6 -0
  64. package/dist/src/graph-server.d.ts +9 -0
  65. package/dist/src/graph-server.js +171 -20
  66. package/dist/src/graph-studio-features.js +2 -2
  67. package/dist/src/graph-sync.js +5 -2
  68. package/dist/src/graph-ui/app.js +369 -183
  69. package/dist/src/graph-ui/controls.css +55 -32
  70. package/dist/src/graph-ui/controls.js +85 -9
  71. package/dist/src/graph-ui/edge-router.js +114 -13
  72. package/dist/src/graph-ui/embed.js +32 -17
  73. package/dist/src/graph-ui/icons.js +1 -0
  74. package/dist/src/graph-ui/index.html +4 -4
  75. package/dist/src/graph-ui/library.css +4 -10
  76. package/dist/src/graph-ui/manager-markdown.js +155 -0
  77. package/dist/src/graph-ui/manager-state.js +191 -0
  78. package/dist/src/graph-ui/manager.css +161 -0
  79. package/dist/src/graph-ui/manager.js +700 -0
  80. package/dist/src/graph-ui/skill-picker.js +6 -6
  81. package/dist/src/graph-ui/studio-canvas.js +17 -15
  82. package/dist/src/graph-ui/studio.css +24 -23
  83. package/dist/src/graph-ui/studio.js +69 -48
  84. package/dist/src/graph-ui/style.css +128 -93
  85. package/dist/src/graph-ui/theme.js +2 -2
  86. package/dist/src/graph-ui/tokens.css +217 -151
  87. package/dist/src/graphs.d.ts +76 -2
  88. package/dist/src/graphs.js +172 -9
  89. package/dist/src/hardened-runtime.js +8 -2
  90. package/dist/src/mcp.d.ts +75 -0
  91. package/dist/src/mcp.js +240 -8
  92. package/dist/src/membership-errors.d.ts +14 -0
  93. package/dist/src/membership-errors.js +24 -1
  94. package/dist/src/membership.d.ts +20 -0
  95. package/dist/src/membership.js +45 -16
  96. package/dist/src/palette.d.ts +25 -8
  97. package/dist/src/palette.js +26 -8
  98. package/dist/src/provider-engine.d.ts +4 -4
  99. package/dist/src/provider-engine.js +39 -22
  100. package/dist/src/provider-keys.d.ts +5 -1
  101. package/dist/src/provider-keys.js +7 -3
  102. package/dist/src/provider-settings.d.ts +4 -1
  103. package/dist/src/provider-settings.js +46 -5
  104. package/dist/src/providers.d.ts +24 -0
  105. package/dist/src/providers.js +47 -2
  106. package/dist/src/qa/guidance.d.ts +26 -0
  107. package/dist/src/qa/guidance.js +46 -0
  108. package/dist/src/qa/index.d.ts +1 -8
  109. package/dist/src/qa/index.js +1 -16
  110. package/dist/src/qa/profile/QaProfile.d.ts +5 -1
  111. package/dist/src/qa/profile/QaProfile.js +6 -2
  112. package/dist/src/qa/runtime/ProcessManager.d.ts +20 -2
  113. package/dist/src/qa/runtime/ProcessManager.js +69 -13
  114. package/dist/src/qa/tools.d.ts +19 -1
  115. package/dist/src/qa/tools.js +20 -145
  116. package/dist/src/react-runtime.d.ts +11 -0
  117. package/dist/src/react-runtime.js +203 -53
  118. package/dist/src/remote/engine-pool.js +21 -6
  119. package/dist/src/run-progress.d.ts +6 -0
  120. package/dist/src/run-progress.js +7 -0
  121. package/dist/src/runtime.d.ts +8 -0
  122. package/dist/src/screen-selection.d.ts +38 -0
  123. package/dist/src/screen-selection.js +103 -0
  124. package/dist/src/session-changes.d.ts +117 -0
  125. package/dist/src/session-changes.js +796 -0
  126. package/dist/src/session-skills.d.ts +75 -0
  127. package/dist/src/session-skills.js +151 -0
  128. package/dist/src/side-panel.d.ts +1 -1
  129. package/dist/src/side-panel.js +6 -12
  130. package/dist/src/skill-commands.js +1 -1
  131. package/dist/src/skills/bundled/control-browser/SKILL.md +9 -1
  132. package/dist/src/skills/bundled/graph-manager/SKILL.md +8 -0
  133. package/dist/src/skills/bundled/provenance.json +3 -3
  134. package/dist/src/skills/bundled/web-gui-tester/SKILL.md +1 -1
  135. package/dist/src/stall-recovery.d.ts +33 -0
  136. package/dist/src/stall-recovery.js +83 -0
  137. package/dist/src/subagent-run.js +1 -2
  138. package/dist/src/telemetry/schema.d.ts +1 -1
  139. package/dist/src/telemetry/schema.js +1 -2
  140. package/dist/src/terminal-ui.d.ts +66 -22
  141. package/dist/src/terminal-ui.js +327 -92
  142. package/dist/src/tool-diff-stats.d.ts +9 -0
  143. package/dist/src/tool-diff-stats.js +20 -0
  144. package/dist/src/tool-names.d.ts +1 -1
  145. package/dist/src/tool-result-filter.js +1 -1
  146. package/dist/src/tools.js +26 -2
  147. package/dist/src/transcript.d.ts +11 -0
  148. package/dist/src/transcript.js +23 -3
  149. package/dist/src/types.d.ts +24 -4
  150. package/dist/src/usage-analytics.d.ts +7 -0
  151. package/dist/src/usage-analytics.js +55 -15
  152. package/docs/concepts/README.md +1 -1
  153. package/docs/concepts/limits.md +9 -0
  154. package/docs/guides/desktop-app.md +1 -1
  155. package/docs/guides/graph-builder.md +16 -1
  156. package/docs/guides/tui.md +9 -9
  157. package/docs/reference/slash-commands.md +2 -1
  158. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +203 -0
  159. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +79 -0
  160. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +182 -0
  161. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +156 -0
  162. package/package.json +1 -1
  163. package/tests/chat-side-panel-test-plan.md +1 -1
  164. package/dist/src/qa/api/http-runner.d.ts +0 -3
  165. package/dist/src/qa/api/http-runner.js +0 -47
  166. package/dist/src/qa/git/ChangeDetector.d.ts +0 -26
  167. package/dist/src/qa/git/ChangeDetector.js +0 -177
  168. package/dist/src/qa/git/DiffReviewer.d.ts +0 -28
  169. package/dist/src/qa/git/DiffReviewer.js +0 -115
  170. package/dist/src/qa/orchestrator/ChangeClassifier.d.ts +0 -14
  171. package/dist/src/qa/orchestrator/ChangeClassifier.js +0 -28
  172. package/dist/src/qa/orchestrator/MergeGate.d.ts +0 -14
  173. package/dist/src/qa/orchestrator/MergeGate.js +0 -40
  174. package/dist/src/qa/orchestrator/QaOrchestrator.d.ts +0 -79
  175. package/dist/src/qa/orchestrator/QaOrchestrator.js +0 -373
  176. package/dist/src/qa/runners/CommandRunner.d.ts +0 -22
  177. package/dist/src/qa/runners/CommandRunner.js +0 -96
  178. package/dist/src/qa/runners/TestRunner.d.ts +0 -21
  179. package/dist/src/qa/runners/TestRunner.js +0 -66
  180. package/dist/src/qa/runtime/RuntimeSmoke.d.ts +0 -11
  181. package/dist/src/qa/runtime/RuntimeSmoke.js +0 -78
  182. package/dist/src/qa/runtime-detect.d.ts +0 -10
  183. package/dist/src/qa/runtime-detect.js +0 -72
  184. package/dist/src/qa/security/DependencyScanner.d.ts +0 -19
  185. package/dist/src/qa/security/DependencyScanner.js +0 -167
  186. package/dist/src/qa/security/SecretScanner.d.ts +0 -3
  187. package/dist/src/qa/security/SecretScanner.js +0 -55
@@ -0,0 +1,700 @@
1
+ /* The Graph Manager button, its first-graph tip and the side chat panel. The decisions live in manager-state.js; this file draws them and talks to the graph server's /api/manager routes. */
2
+ 'use strict';
3
+ globalThis.AndorraManager = (() => {
4
+ const logic = globalThis.AndorraManagerState;
5
+ const markdown = globalThis.AndorraManagerMarkdown;
6
+ const byId = id => document.getElementById(id);
7
+ const button = byId('graph-manager'), tip = byId('manager-tip'), panel = byId('manager-panel');
8
+ if (!logic || !button || !tip || !panel) return undefined;
9
+ const providerSelect = byId('manager-provider'), modelSelect = byId('manager-model');
10
+ const notices = byId('manager-notices'), log = byId('manager-transcript'), input = byId('manager-input');
11
+ const sendButton = byId('manager-send'), stopButton = byId('manager-stop'), runLabel = byId('manager-run-state');
12
+
13
+ /** Reading the storage property can itself throw (a sandboxed frame, blocked site data); the helpers treat a missing store as empty. */
14
+ function storage() {
15
+ try { return window.localStorage; } catch { return undefined; }
16
+ }
17
+
18
+ const RUN_LABELS = { starting: 'Starting…', working: 'Working…', awaiting: 'Waiting for you' };
19
+ const MIN_WIDTH = 300, MAX_WIDTH = 640;
20
+
21
+ let open = false;
22
+ let transcript = [];
23
+ /** The engine's run state, read from `state` events and each snapshot; the transcript does not keep it. */
24
+ let runState = 'idle';
25
+ let source = null, retryTimer = null, retryMs = 1000, connected = false;
26
+ /** The canvas of the latest message the chat took, as JSON; what the agent's save is compared against. */
27
+ let sentCanvas = null;
28
+ /** The graph the conversation is about, once it has a message. */
29
+ let chatGraphId = null;
30
+ /** Messages posted and not yet echoed by the stream, oldest first: { text, canvas, graphId }. */
31
+ let posted = [];
32
+ /** What `sentCanvas` and `chatGraphId` were before the latest echoed message, until that message can no longer be refused. */
33
+ let beforeLastMessage = null;
34
+ /** A message sent into a working run changed the canvas: the agent's next save may predate it, so it is offered. */
35
+ let unsureCanvas = false;
36
+ let shownGraphId = null;
37
+ let choice;
38
+ let providersSeen = '';
39
+ /** A revision the agent saved that was not loaded because the canvas holds other edits. */
40
+ let offeredRevision = null;
41
+ /** A graph the agent created beside the bundled preset, which it cannot change: { id, label }. Opened only on click. */
42
+ let createdOffer = null;
43
+ /** The graph the user moved to while a conversation about another one is open. */
44
+ let switchOffer = null;
45
+ let localError = '';
46
+ /** What this panel answered each approval with, to label the closed card. */
47
+ const decisions = new Map();
48
+ /** Cards whose answer is on its way; their controls stay disabled until the stream settles them. */
49
+ const answering = new Set();
50
+ /** What each drawn block showed: `{ block, pending, element }`. */
51
+ let rendered = [];
52
+
53
+ const node = (tag, text, className) => {
54
+ const item = document.createElement(tag);
55
+ if (text !== undefined) item.textContent = text;
56
+ if (className) item.className = className;
57
+ return item;
58
+ };
59
+ const control = (label, run, className) => {
60
+ const item = node('button', label, className || 'btn-small');
61
+ item.type = 'button'; item.onclick = run;
62
+ return item;
63
+ };
64
+
65
+ // ------------------------------------------------------------------ Button and tip
66
+
67
+ function hideTip() { tip.hidden = true; }
68
+ function dismissTip() { logic.dismissTip(storage()); hideTip(); }
69
+
70
+ /** Follows the editor's heading: the button exists only beside an open graph, and a different graph is noticed here whichever way it arrived. */
71
+ function heading() {
72
+ const graph = state.graph;
73
+ button.hidden = button.parentElement.hidden = !graph;
74
+ if (!graph) { hideTip(); if (open) setOpen(false); shownGraphId = null; return; }
75
+ if (graph.id !== shownGraphId) {
76
+ shownGraphId = graph.id;
77
+ hideTip();
78
+ offeredRevision = null;
79
+ createdOffer = null;
80
+ switchOffer = chatGraphId && chatGraphId !== graph.id && transcript.length ? graph.id : null;
81
+ renderNotices();
82
+ }
83
+ if (open) fillModels();
84
+ }
85
+
86
+ function graphOpened(reason) {
87
+ heading();
88
+ if (!open && state.graph && logic.shouldShowTip(storage(), reason)) tip.hidden = false;
89
+ }
90
+
91
+ // ------------------------------------------------------------------ Panel
92
+
93
+ function setOpen(next) {
94
+ if (open === next) return;
95
+ open = next;
96
+ panel.hidden = !open;
97
+ panel.parentElement?.classList.toggle('manager-open', open);
98
+ button.setAttribute('aria-expanded', String(open));
99
+ if (open) {
100
+ dismissTip();
101
+ fillModels();
102
+ connect();
103
+ render();
104
+ input.focus();
105
+ } else {
106
+ disconnect();
107
+ }
108
+ // The canvas changed width, so its controls and minimap take their places again.
109
+ window.dispatchEvent(new Event('resize'));
110
+ }
111
+
112
+ function setWidth(width) {
113
+ document.documentElement.style.setProperty('--manager-panel', `${Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, Math.round(width)))}px`);
114
+ }
115
+
116
+ // ------------------------------------------------------------------ Model
117
+
118
+ const modelsOf = provider => [...new Set([provider.model, ...(provider.models || [])].filter(Boolean))];
119
+ const providerOf = id => state.providers.find(entry => entry.id === id);
120
+
121
+ function option(value, label) { const item = node('option', label); item.value = value; return item; }
122
+
123
+ /** Fills both selects from the editor's provider registry, keeping the choice while it is still offered. */
124
+ function fillModels() {
125
+ const signature = JSON.stringify(state.providers);
126
+ if (signature === providersSeen && choice) return;
127
+ providersSeen = signature;
128
+ const kept = choice && modelsOf(providerOf(choice.provider) || {}).includes(choice.model);
129
+ if (!kept) choice = logic.initialModel(storage(), state.graph, state.providers);
130
+ providerSelect.replaceChildren(...state.providers.map(provider => option(provider.id, titleFor(provider))));
131
+ providerSelect.disabled = modelSelect.disabled = !choice;
132
+ if (choice) providerSelect.value = choice.provider;
133
+ fillModelOptions();
134
+ renderNotices();
135
+ }
136
+ function fillModelOptions() {
137
+ modelSelect.replaceChildren(...(choice ? modelsOf(providerOf(choice.provider) || {}) : []).map(model => option(model, model)));
138
+ if (choice) modelSelect.value = choice.model;
139
+ for (const select of [providerSelect, modelSelect]) globalThis.AndorraControls?.refreshSelect?.(select);
140
+ }
141
+ providerSelect.onchange = () => {
142
+ const provider = providerOf(providerSelect.value);
143
+ const model = provider && modelsOf(provider)[0];
144
+ if (!model) return;
145
+ choice = { provider: provider.id, model };
146
+ logic.rememberModel(storage(), choice);
147
+ fillModelOptions();
148
+ };
149
+ modelSelect.onchange = () => {
150
+ if (!choice || !modelSelect.value) return;
151
+ choice = { provider: choice.provider, model: modelSelect.value };
152
+ logic.rememberModel(storage(), choice);
153
+ };
154
+
155
+ // ------------------------------------------------------------------ Stream
156
+
157
+ function connect() {
158
+ if (source || !open || !token || typeof EventSource !== 'function') return;
159
+ clearTimeout(retryTimer);
160
+ // EventSource cannot send an Authorization header, so the stream takes the session token in its query.
161
+ const stream = source = new EventSource(`/api/manager/stream?token=${encodeURIComponent(token)}`);
162
+ stream.onopen = () => { if (source !== stream) return; connected = true; retryMs = 1000; renderRunState(); };
163
+ stream.onmessage = message => {
164
+ if (source !== stream) return;
165
+ let event;
166
+ try { event = JSON.parse(message.data); } catch { return; }
167
+ receive(event);
168
+ };
169
+ stream.onerror = () => {
170
+ if (source !== stream) return;
171
+ connected = false; renderRunState();
172
+ // The browser retries a dropped stream on its own and the server opens each one with a
173
+ // snapshot. A stream it has given up on (the server refused it) is reopened here, more slowly.
174
+ if (stream.readyState !== 2) return;
175
+ stream.close(); source = null;
176
+ retryTimer = setTimeout(connect, retryMs);
177
+ retryMs = Math.min(retryMs * 2, 30_000);
178
+ };
179
+ }
180
+ function disconnect() {
181
+ clearTimeout(retryTimer);
182
+ source?.close();
183
+ source = null; connected = false;
184
+ }
185
+
186
+ function receive(event) {
187
+ if (!event || typeof event.type !== 'string') return;
188
+ transcript = logic.reduce(transcript, event);
189
+ if (event.type === 'snapshot') {
190
+ runState = typeof event.state === 'string' ? event.state : 'idle';
191
+ answering.clear();
192
+ // What happened while this panel was not listening is unknown: another window may have sent
193
+ // since, from another canvas. The baseline survives only as the canvas of this panel's own
194
+ // message, when that message is the conversation's latest and started its run.
195
+ const latest = transcript.filter(entry => entry.type === 'user').pop();
196
+ const own = latest && posted.find(entry => entry.text === latest.text && entry.whileIdle);
197
+ sentCanvas = own ? own.canvas : null;
198
+ if (own) chatGraphId = own.graphId;
199
+ posted = []; beforeLastMessage = null; unsureCanvas = false;
200
+ if (!transcript.length) { chatGraphId = null; switchOffer = null; createdOffer = null; decisions.clear(); }
201
+ // A conversation found already under way (a reload, another window) is taken to be about the open graph.
202
+ else if (!chatGraphId) chatGraphId = state.graph?.id ?? null;
203
+ // A graph deleted while this panel was not listening leaves the list all the same, and
204
+ // nothing of it is offered: its latest revision is the deletion.
205
+ const deleted = logic.deletedGraphs(transcript);
206
+ if (state.graphs.some(entry => deleted.has(entry.id))) { state.graphs = state.graphs.filter(entry => !deleted.has(entry.id)); renderList(); }
207
+ if (deleted.has(state.graph?.id)) offeredRevision = null;
208
+ if (createdOffer && deleted.has(createdOffer.id)) createdOffer = null;
209
+ // A save that happened while this panel was not listening is offered, never applied: nothing
210
+ // here knows which canvas it was made from.
211
+ const missed = transcript.filter(entry => entry.type === 'graph.saved' && entry.graphId === state.graph?.id).pop();
212
+ if (missed && !deleted.has(missed.graphId) && missed.revision > (state.graph.revision || 0)) offeredRevision = missed.revision;
213
+ // Likewise a graph created while nobody was listening: its latest save is the one offered.
214
+ const created = transcript.map(entry => logic.createdGraph(state.graph?.id, entry)).filter(Boolean).pop();
215
+ if (created && !deleted.has(created.id)) createdOffer = created;
216
+ } else if (event.type === 'user') {
217
+ accepted(event.text);
218
+ } else if (event.type === 'error') {
219
+ refused();
220
+ } else if (event.type === 'state') {
221
+ runState = event.state;
222
+ // The run is over: its message was read or no longer matters, and no save follows without a new one.
223
+ if (runState === 'idle') { beforeLastMessage = null; unsureCanvas = false; }
224
+ } else if (event.type === 'resolved') {
225
+ answering.delete(event.id);
226
+ } else if (event.type === 'graph.saved') {
227
+ void graphSaved(event);
228
+ } else if (event.type === 'graph.deleted') {
229
+ graphDeleted(event);
230
+ }
231
+ render();
232
+ }
233
+
234
+ /**
235
+ * The chat echoed a message. Only now does its canvas count as sent: a request the server refused
236
+ * is never echoed. The echo comes before delivery to the engine, so what it replaces is kept until
237
+ * the message can no longer be refused.
238
+ */
239
+ function accepted(text) {
240
+ const index = posted.findIndex(entry => entry.text === text);
241
+ if (index < 0) {
242
+ // Another window's message (or one of this panel's whose echo arrived after a reconnect): the
243
+ // agent now works from a canvas this panel never saw, so nothing here is known to be what it
244
+ // has. A save that follows is offered, never loaded over what is on this canvas.
245
+ sentCanvas = null; beforeLastMessage = null;
246
+ return;
247
+ }
248
+ const [message] = posted.splice(index, 1);
249
+ if (runState !== 'idle') {
250
+ // Nothing on the stream says whether a working run read this message before its next save.
251
+ if (message.canvas !== sentCanvas) unsureCanvas = true;
252
+ chatGraphId = message.graphId;
253
+ return;
254
+ }
255
+ beforeLastMessage = { sentCanvas, chatGraphId };
256
+ sentCanvas = message.canvas; chatGraphId = message.graphId;
257
+ }
258
+ /** The chat reported an error: a message still open to refusal is taken as refused, which only ever makes a save an offer. */
259
+ function refused() {
260
+ if (beforeLastMessage) ({ sentCanvas, chatGraphId } = beforeLastMessage);
261
+ beforeLastMessage = null; unsureCanvas = false;
262
+ }
263
+
264
+ /**
265
+ * The editor's fields put their text into the graph only when they are left, so while one is
266
+ * focused the canvas can equal the one sent and still hold words the user is typing. A load redraws
267
+ * the inspector over them. A focused text field anywhere outside this panel therefore counts as an
268
+ * edit: the save is offered, and the half-typed text is neither lost nor committed for the user.
269
+ * Selects and checkboxes commit at once and hold nothing back.
270
+ */
271
+ function typingInEditor() {
272
+ const active = document.activeElement;
273
+ if (!active || active === document.body || panel.contains(active)) return false;
274
+ if (active.isContentEditable || active.tagName === 'TEXTAREA') return true;
275
+ return active.tagName === 'INPUT' && !['checkbox', 'radio', 'button', 'submit', 'reset', 'range', 'color', 'file', 'image'].includes(active.type);
276
+ }
277
+
278
+ /**
279
+ * The agent saved a graph. Only the open one concerns the canvas: its new revision opens at once
280
+ * when that discards nothing, and is otherwise offered, so no edit is ever replaced unasked.
281
+ */
282
+ async function graphSaved(event) {
283
+ const graph = state.graph;
284
+ const created = logic.createdGraph(graph?.id, event);
285
+ if (created) {
286
+ // The preset cannot be saved, so the agent's work is a new graph. It joins the list and is offered.
287
+ const known = state.graphs.find(entry => entry.id === created.id);
288
+ if (known) known.revision = event.revision; else state.graphs.push({ id: created.id, name: created.label, revision: event.revision });
289
+ renderList();
290
+ createdOffer = created;
291
+ renderNotices();
292
+ return;
293
+ }
294
+ if (!graph || event.graphId !== graph.id) return;
295
+ const listedGraph = state.graphs.find(entry => entry.id === graph.id);
296
+ if (listedGraph) listedGraph.revision = event.revision; else state.graphs.push({ id: graph.id, name: graph.name, revision: event.revision });
297
+ renderList();
298
+ const mayLoad = () => !unsureCanvas && !typingInEditor() && !logic.deletedGraphs(transcript).has(graph.id)
299
+ && logic.applyDecision({ sentCanvas, currentCanvas: JSON.stringify(state.graph), untouched: state.untouched ?? null }) === 'load';
300
+ if (mayLoad()) {
301
+ // The revision takes a request to arrive, and the canvas is the user's all that while. It is
302
+ // fetched first and applied only if the canvas is still the one the decision was made on;
303
+ // nothing awaits between that check and the replacement.
304
+ const canvas = JSON.stringify(state.graph);
305
+ const fetched = await api(`/api/graphs/${encodeURIComponent(graph.id)}`).catch(() => undefined);
306
+ // The user moved to another graph meanwhile: this save has nothing to replace or offer there.
307
+ if (state.graph?.id !== graph.id) return;
308
+ // A later save of the same run already put this revision, or a newer one, on the canvas.
309
+ if ((state.graph.revision || 0) >= event.revision) return;
310
+ if (fetched && JSON.stringify(state.graph) === canvas && mayLoad() && await loadRevision(graph.id, fetched)) return;
311
+ }
312
+ offeredRevision = event.revision;
313
+ renderNotices();
314
+ }
315
+ /**
316
+ * The agent deleted a graph, which publishes a revision marked as deleted. It leaves the list. When
317
+ * it is the open graph that revision is never loaded or offered: the canvas stays as it is, still
318
+ * the user's to copy or keep, and the status line says what happened.
319
+ */
320
+ function graphDeleted(event) {
321
+ if (state.graphs.some(entry => entry.id === event.graphId)) {
322
+ state.graphs = state.graphs.filter(entry => entry.id !== event.graphId);
323
+ renderList();
324
+ }
325
+ if (createdOffer?.id === event.graphId) createdOffer = null;
326
+ if (state.graph?.id !== event.graphId) return;
327
+ offeredRevision = null;
328
+ status('Workflow Manager deleted this workflow.');
329
+ }
330
+ /** Opens the graph the agent created. Unsaved edits on the canvas are asked about first, as for any other graph. */
331
+ async function openCreated(offer) {
332
+ const before = chatGraphId;
333
+ // The conversation is about the graph it created from here on, so opening it offers no new chat.
334
+ if (transcript.length) chatGraphId = offer.id;
335
+ if (!await openGraph(offer.id) || state.graph?.id !== offer.id) { chatGraphId = before; renderNotices(); return; }
336
+ // The canvas is the agent's own save: a further save in the same run replaces it freely.
337
+ sentCanvas = JSON.stringify(state.graph);
338
+ beforeLastMessage = null; unsureCanvas = false;
339
+ createdOffer = null;
340
+ renderNotices();
341
+ }
342
+ /** Replaces the canvas with the graph's latest revision: `fetched` when the caller already holds it, else requested now. */
343
+ async function loadRevision(id, fetched) {
344
+ if (!await openGraph(id, { discard: true, ...(fetched ? { fetched } : {}) }) || state.graph?.id !== id) return false;
345
+ // The canvas is now the agent's own save: a further save in the same run replaces it as freely.
346
+ sentCanvas = JSON.stringify(state.graph);
347
+ beforeLastMessage = null; unsureCanvas = false;
348
+ offeredRevision = null;
349
+ status(`Workflow Manager saved version ${state.graph.revision}`);
350
+ renderNotices();
351
+ return true;
352
+ }
353
+
354
+ // ------------------------------------------------------------------ Requests
355
+
356
+ async function post(path, body) {
357
+ try { await api(path, body || {}); localError = ''; return true; }
358
+ catch (error) { localError = error?.message || String(error); return false; }
359
+ finally { renderNotices(); }
360
+ }
361
+
362
+ async function send() {
363
+ const text = input.value.trim();
364
+ if (!text || !state.graph) return;
365
+ if (!choice) { localError = 'Add a model provider to use Workflow Manager.'; renderNotices(); return; }
366
+ const revision = Number.isInteger(state.graph.revision) ? state.graph.revision : 0;
367
+ // The canvas is recorded with the message and becomes the comparison baseline only when the
368
+ // stream echoes that message; a refused request puts the words back and leaves the baseline alone.
369
+ const message = { text, canvas: JSON.stringify(state.graph), graphId: state.graph.id };
370
+ // A message sent while idle starts its own run; a snapshot may stand in for its echo.
371
+ message.whileIdle = runState === 'idle';
372
+ posted.push(message);
373
+ switchOffer = null;
374
+ input.value = '';
375
+ const sent = await post('/api/manager/message', { provider: choice.provider, model: choice.model, text, graph: JSON.parse(message.canvas), saved: revision > 0, revision });
376
+ if (sent) return;
377
+ posted = posted.filter(entry => entry !== message);
378
+ if (!input.value) input.value = text;
379
+ }
380
+
381
+ async function settle(entry, path, body, label) {
382
+ if (answering.has(entry.id)) return;
383
+ answering.add(entry.id);
384
+ if (label) decisions.set(entry.id, label);
385
+ render();
386
+ if (await post(path, body)) return;
387
+ answering.delete(entry.id); decisions.delete(entry.id);
388
+ render();
389
+ }
390
+
391
+ async function newChat() {
392
+ switchOffer = null;
393
+ await post('/api/manager/reset');
394
+ }
395
+
396
+ // ------------------------------------------------------------------ Drawing
397
+
398
+ /** Rows the reader opened or closed, by key, so a redraw keeps each one as they left it. */
399
+ const openRows = new Map();
400
+ const span = (text, className) => node('span', text, className);
401
+ const lastLine = text => String(text || '').trimEnd().split('\n').pop().trim();
402
+ /** A live figure: the seconds since `startedAt`, kept current by the ticker below. */
403
+ function since(startedAt) {
404
+ const item = span(logic.seconds(Date.now() - startedAt), 'manager-row-duration');
405
+ item.dataset.since = String(startedAt);
406
+ return item;
407
+ }
408
+ function glyph(text, label) {
409
+ const item = span(text, 'manager-status-glyph');
410
+ item.setAttribute('aria-hidden', 'true');
411
+ return label ? [item, span(label, 'sr-only')] : [item];
412
+ }
413
+
414
+ /**
415
+ * One fold the way the app draws it: a flat line that opens to its body. A row with no body is the
416
+ * line alone, with no control to press.
417
+ */
418
+ function fold(key, className, status, head, body, defaultOpen) {
419
+ const wrap = node('div', undefined, `manager-fold ${className}`);
420
+ if (status) wrap.dataset.status = status;
421
+ if (!body) {
422
+ const line = node('div', undefined, 'manager-fold-head manager-fold-static');
423
+ line.append(...head.filter(Boolean));
424
+ wrap.append(line);
425
+ return wrap;
426
+ }
427
+ const open = openRows.has(key) ? openRows.get(key) : !!defaultOpen;
428
+ const button = node('button', undefined, 'manager-fold-head');
429
+ button.type = 'button';
430
+ button.setAttribute('aria-expanded', String(open));
431
+ button.append(...head.filter(Boolean));
432
+ const panelBody = node('div', undefined, 'manager-fold-body');
433
+ panelBody.append(...[body].flat().filter(Boolean));
434
+ panelBody.hidden = !open;
435
+ wrap.dataset.open = String(open);
436
+ button.onclick = () => {
437
+ const next = wrap.dataset.open !== 'true';
438
+ openRows.set(key, next);
439
+ wrap.dataset.open = String(next);
440
+ button.setAttribute('aria-expanded', String(next));
441
+ panelBody.hidden = !next;
442
+ if (next) followThought(panelBody);
443
+ };
444
+ wrap.append(button, panelBody);
445
+ return wrap;
446
+ }
447
+ /** An open live thought shows its newest words, as the app's does. */
448
+ function followThought(scope) {
449
+ for (const text of scope.querySelectorAll('.manager-fold[data-status="thinking"] .manager-activity-text')) text.scrollTop = text.scrollHeight;
450
+ }
451
+
452
+ /** One model call's reasoning: `Thinking` with its newest words while it streams, `Thought for 4s` once it settles. */
453
+ function thoughtRow(entry) {
454
+ const live = entry.status === 'thinking';
455
+ const preview = live ? lastLine(entry.text) : '';
456
+ const tail = preview ? span(undefined, 'manager-activity-preview manager-preview-tail') : null;
457
+ if (tail) tail.append(span(preview));
458
+ const head = live
459
+ ? [...glyph('◐', 'Thinking: '), span('Thinking', 'manager-activity-name'), tail, since(entry.startedAt)]
460
+ : [span(logic.thoughtLabel(entry.durationMs), 'manager-activity-name')];
461
+ const text = node('div', entry.text || (live ? 'Still thinking; nothing has streamed yet.' : 'No reasoning text was streamed for this call.'), 'manager-activity-text');
462
+ text.tabIndex = 0;
463
+ const note = entry.truncated ? node('div', 'Showing the first part of this call\'s reasoning; the rest exceeded the display limit.', 'manager-activity-note') : null;
464
+ return fold(`thought:${entry.id}`, 'manager-activity', live ? 'thinking' : 'done', head, [text, note]);
465
+ }
466
+
467
+ const TOOL_GLYPHS = { running: ['◐', 'Running: '], failed: ['✕', 'Failed: '], stopped: ['○', 'Stopped: '] };
468
+ /** One tool call: what it did and to what, its figure once it settles, and why it failed when it did. */
469
+ function toolRow(entry) {
470
+ const status = entry.status || 'done';
471
+ const mark = TOOL_GLYPHS[status];
472
+ const verb = entry.verb || entry.text || 'Tool';
473
+ const head = [
474
+ ...(mark ? glyph(mark[0], mark[1]) : []),
475
+ span(verb, 'manager-activity-verb'),
476
+ entry.target ? span(entry.target, 'manager-activity-target') : null,
477
+ status === 'running' ? since(entry.startedAt)
478
+ : typeof entry.endedAt === 'number' && typeof entry.startedAt === 'number' ? span(logic.seconds(entry.endedAt - entry.startedAt), 'manager-row-duration') : null,
479
+ ];
480
+ const details = [];
481
+ if (entry.text && entry.text !== [verb, entry.target].filter(Boolean).join(' ')) details.push(node('div', entry.text, 'manager-activity-command'));
482
+ if (entry.reason) details.push(node('div', entry.reason, 'manager-activity-reason'));
483
+ if (status === 'stopped') details.push(node('div', 'The run ended before this call reported back.', 'manager-activity-note'));
484
+ const row = fold(`tool:${entry.id}`, 'manager-activity', status, head, details.length ? details : null);
485
+ row.title = entry.text || verb;
486
+ return row;
487
+ }
488
+ const workRow = entry => entry.type === 'thought' ? thoughtRow(entry) : toolRow(entry);
489
+
490
+ /**
491
+ * A stretch of thinking and calls between messages. While it runs every row shows; once it
492
+ * settles it condenses to the one line the app's turn shows (`Thought for 8s, made 4 edits`), with
493
+ * its wall time at the edge, and opens back to the same rows.
494
+ */
495
+ function workBlock(block) {
496
+ if (!block.settled) {
497
+ const live = node('div', undefined, 'manager-work-live');
498
+ live.append(...block.entries.map(workRow));
499
+ return live;
500
+ }
501
+ const failed = block.entries.filter(entry => entry.type === 'tool' && entry.status === 'failed').length;
502
+ const label = logic.workLabel(block.entries);
503
+ const duration = logic.workDuration(block.entries);
504
+ const labelSpan = span(label, 'manager-work-label');
505
+ labelSpan.title = label;
506
+ const head = [labelSpan, failed ? span(`${failed} failed`, 'manager-work-failed') : null, duration === undefined ? null : span(logic.seconds(duration), 'manager-row-duration')];
507
+ return fold(block.key, 'manager-work', failed ? 'failed' : 'done', head, block.entries.map(workRow));
508
+ }
509
+
510
+ /** Engine and model text is set as text or built as Markdown nodes, never parsed as markup. */
511
+ function row(entry) {
512
+ if (entry.type === 'user') {
513
+ const item = node('div', undefined, 'manager-row manager-user');
514
+ item.append(node('div', entry.text, 'manager-user-body'));
515
+ return item;
516
+ }
517
+ if (entry.type === 'assistant') {
518
+ const item = node('div', undefined, 'manager-row manager-assistant');
519
+ if (markdown) item.append(markdown.render(entry.text)); else item.textContent = entry.text;
520
+ return item;
521
+ }
522
+ if (entry.type === 'thought' || entry.type === 'tool') return workRow(entry);
523
+ if (entry.type === 'error') { const item = node('div', entry.message, 'manager-row manager-error'); item.setAttribute('role', 'alert'); return item; }
524
+ if (entry.type === 'graph.saved') {
525
+ // A save of another graph than the conversation's own names it.
526
+ const other = entry.graphId !== chatGraphId && entry.graphId !== state.graph?.id;
527
+ return node('div', other ? `Saved ${entry.name || entry.graphId}, version ${entry.revision}` : `Saved version ${entry.revision}`, 'manager-row manager-saved');
528
+ }
529
+ if (entry.type === 'graph.deleted') {
530
+ const other = entry.graphId !== chatGraphId && entry.graphId !== state.graph?.id;
531
+ return node('div', other ? `Deleted ${entry.graphId}` : 'Deleted this workflow', 'manager-row manager-saved');
532
+ }
533
+ if (entry.type === 'approval') return approvalCard(entry);
534
+ if (entry.type === 'question') return questionCard(entry);
535
+ return null;
536
+ }
537
+
538
+ function card(entry, title, text) {
539
+ const item = node('div', undefined, 'manager-row manager-card');
540
+ item.dataset.id = entry.id;
541
+ item.append(node('strong', title), node('p', text));
542
+ return item;
543
+ }
544
+ /** A settled card keeps its text and loses its controls. */
545
+ function closed(item, entry, fallback) {
546
+ item.classList.add('answered');
547
+ item.append(node('span', decisions.get(entry.id) || fallback, 'manager-card-result'));
548
+ return item;
549
+ }
550
+ function actions(item, entry, controls) {
551
+ const bar = node('div', undefined, 'manager-card-actions');
552
+ for (const each of controls) { each.disabled = answering.has(entry.id); bar.append(each); }
553
+ item.append(bar);
554
+ return item;
555
+ }
556
+ function approvalCard(entry) {
557
+ const item = card(entry, 'Workflow Manager asks to', entry.text);
558
+ if (entry.answered) return closed(item, entry, 'Answered');
559
+ return actions(item, entry, [
560
+ control('Approve', () => settle(entry, '/api/manager/approve', { id: entry.id, approved: true }, 'Approved'), 'btn-small primary'),
561
+ control('Deny', () => settle(entry, '/api/manager/approve', { id: entry.id, approved: false }, 'Denied')),
562
+ ]);
563
+ }
564
+ function questionCard(entry) {
565
+ const item = card(entry, 'Workflow Manager asks', entry.question);
566
+ if (entry.answered) return closed(item, entry, 'Answered');
567
+ const answer = value => settle(entry, '/api/manager/answer', { id: entry.id, value }, `Answered: ${value}`);
568
+ if (Array.isArray(entry.choices) && entry.choices.length) {
569
+ return actions(item, entry, entry.choices.map(value => control(String(value), () => answer(String(value)))));
570
+ }
571
+ const field = node('input');
572
+ field.type = 'text'; field.setAttribute('aria-label', 'Your answer');
573
+ const submit = () => { if (field.value.trim()) void answer(field.value.trim()); };
574
+ field.onkeydown = event => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } };
575
+ return actions(item, entry, [field, control('Answer', submit, 'btn-small primary')]);
576
+ }
577
+
578
+ /** Two blocks draw the same while every entry they show is the same object and nothing they depend on moved. */
579
+ function sameBlock(before, block, pending) {
580
+ if (!before || before.block.kind !== block.kind || before.pending !== pending) return false;
581
+ if (block.kind === 'entry') return before.block.entry === block.entry;
582
+ return before.block.key === block.key && before.block.settled === block.settled
583
+ && before.block.entries.length === block.entries.length && before.block.entries.every((entry, at) => entry === block.entries[at]);
584
+ }
585
+
586
+ /** Redraws only the blocks whose entries or pending state changed, so a half-typed answer survives the next event. */
587
+ function renderTranscript() {
588
+ const atEnd = log.scrollHeight - log.scrollTop - log.clientHeight < 40;
589
+ const next = [];
590
+ if (!transcript.length) {
591
+ log.replaceChildren(node('p', 'Ask Workflow Manager to build or change this workflow. It sees the canvas as it is now, unsaved edits included, and asks before it saves anything.', 'help manager-empty'));
592
+ rendered = [];
593
+ return;
594
+ }
595
+ if (!rendered.length) log.replaceChildren();
596
+ logic.blocks(transcript, runState !== 'idle').forEach((block, index) => {
597
+ const before = rendered[index], pending = block.kind === 'entry' && answering.has(block.entry.id);
598
+ if (sameBlock(before, block, pending)) { next.push(before); return; }
599
+ const element = block.kind === 'work' ? workBlock(block) : row(block.entry);
600
+ if (before?.element && element) before.element.replaceWith(element);
601
+ else { before?.element?.remove(); if (element) log.append(element); }
602
+ if (element) followThought(element);
603
+ next.push({ block, pending, element });
604
+ });
605
+ for (const stale of rendered.slice(next.length)) stale.element?.remove();
606
+ rendered = next;
607
+ if (atEnd) log.scrollTop = log.scrollHeight;
608
+ }
609
+
610
+ /** Live figures count up between events; the ticker runs only while one is on screen. */
611
+ let ticker = null;
612
+ function tick() {
613
+ const live = log.querySelectorAll('[data-since]');
614
+ if (!live.length || !open) { clearInterval(ticker); ticker = null; return; }
615
+ for (const item of live) item.textContent = logic.seconds(Date.now() - Number(item.dataset.since));
616
+ }
617
+ function startTicker() {
618
+ if (!ticker && open && log.querySelector('[data-since]')) ticker = setInterval(tick, 100);
619
+ }
620
+
621
+ function notice(className, text, controls) {
622
+ const bar = node('div', undefined, `manager-notice ${className}`);
623
+ bar.append(node('span', text));
624
+ const buttons = node('span', undefined, 'manager-notice-actions');
625
+ buttons.append(...controls);
626
+ bar.append(buttons);
627
+ return bar;
628
+ }
629
+ function renderNotices() {
630
+ const bars = [];
631
+ if (!state.providers.length) bars.push(notice('manager-warning', 'Add a model provider to use Workflow Manager.', []));
632
+ if (switchOffer && state.graph?.id === switchOffer) {
633
+ bars.push(notice('manager-switch', `Start a new chat about ${state.graph.name || 'this workflow'}?`, [
634
+ control('New chat', () => { void newChat(); }, 'btn-small primary'),
635
+ control('Keep this chat', () => { switchOffer = null; renderNotices(); }),
636
+ ]));
637
+ }
638
+ if (offeredRevision !== null && state.graph) {
639
+ const id = state.graph.id;
640
+ bars.push(notice('manager-load', `Workflow Manager saved version ${offeredRevision}. Load it?`, [
641
+ control('Load', () => { void loadRevision(id); }, 'btn-small primary'),
642
+ control('Not now', () => { offeredRevision = null; renderNotices(); }),
643
+ ]));
644
+ }
645
+ if (createdOffer && state.graph?.id === 'default') {
646
+ const offer = createdOffer;
647
+ bars.push(notice('manager-created', `Workflow Manager created ${offer.label}. Open it?`, [
648
+ control('Open', () => { void openCreated(offer); }, 'btn-small primary'),
649
+ control('Not now', () => { createdOffer = null; renderNotices(); }),
650
+ ]));
651
+ }
652
+ if (localError) {
653
+ const bar = notice('manager-error', localError, [control('Dismiss', () => { localError = ''; renderNotices(); })]);
654
+ bar.setAttribute('role', 'alert');
655
+ bars.push(bar);
656
+ }
657
+ notices.replaceChildren(...bars);
658
+ }
659
+ function renderRunState() {
660
+ runLabel.textContent = RUN_LABELS[runState] || (open && source && !connected ? 'Connecting…' : '');
661
+ stopButton.hidden = runState === 'idle';
662
+ }
663
+ function render() { renderTranscript(); renderNotices(); renderRunState(); startTicker(); }
664
+
665
+ // ------------------------------------------------------------------ Wiring
666
+
667
+ button.onclick = () => setOpen(!open);
668
+ byId('manager-tip-close').onclick = dismissTip;
669
+ byId('manager-close').onclick = () => { setOpen(false); button.focus(); };
670
+ byId('manager-new-chat').onclick = () => { void newChat(); };
671
+ sendButton.onclick = () => { void send(); };
672
+ stopButton.onclick = () => { void post('/api/manager/cancel'); };
673
+ input.onkeydown = event => {
674
+ if (event.key !== 'Enter' || event.shiftKey || event.isComposing) return;
675
+ event.preventDefault();
676
+ void send();
677
+ };
678
+ const grip = byId('manager-resize');
679
+ if (grip) {
680
+ grip.onpointerdown = event => {
681
+ grip.setPointerCapture(event.pointerId);
682
+ const right = panel.getBoundingClientRect().right;
683
+ grip.onpointermove = move => setWidth(right - move.clientX);
684
+ grip.onpointerup = () => { grip.onpointermove = null; };
685
+ };
686
+ grip.onkeydown = event => {
687
+ if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
688
+ event.preventDefault();
689
+ setWidth(panel.getBoundingClientRect().width + (event.key === 'ArrowLeft' ? 20 : -20));
690
+ };
691
+ }
692
+ // A page kept for Back/Forward comes back without its stream.
693
+ window.addEventListener('pagehide', disconnect);
694
+ window.addEventListener('pageshow', () => { if (open) connect(); });
695
+
696
+ // The graph can be open before this script runs; app.js keeps how it arrived.
697
+ if (state.graph) graphOpened(state.openReason || 'open'); else heading();
698
+
699
+ return { graphOpened, heading };
700
+ })();