@hncode/hncode 0.8.6 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +30 -0
  2. package/README_CN.md +27 -0
  3. package/package.json +1 -1
  4. package/src/agent.js +172 -43
  5. package/src/bootstrap.js +63 -56
  6. package/src/ci.js +247 -247
  7. package/src/colors.js +5 -1
  8. package/src/commands.js +121 -0
  9. package/src/composer.js +31 -1
  10. package/src/config.js +177 -45
  11. package/src/context.js +29 -0
  12. package/src/files.js +32 -0
  13. package/src/fx.js +19 -2
  14. package/src/i18n.js +180 -131
  15. package/src/index.js +558 -77
  16. package/src/permission-gate.js +103 -0
  17. package/src/plugin.js +221 -2
  18. package/src/prompt-presets.js +36 -0
  19. package/src/protocol.js +184 -0
  20. package/src/registry-browser.js +14 -3
  21. package/src/remote.js +117 -5
  22. package/src/schedule.js +148 -11
  23. package/src/serve.js +613 -0
  24. package/src/session-client.js +148 -0
  25. package/src/session-host.js +52 -0
  26. package/src/session.js +26 -3
  27. package/src/settings-schema.js +2 -2
  28. package/src/status-line.js +48 -0
  29. package/src/toml.js +18 -4
  30. package/src/tool-status.js +45 -0
  31. package/src/tools/bash.js +43 -24
  32. package/src/tools/edit.js +10 -5
  33. package/src/tools/web-search.js +8 -5
  34. package/src/tools/write.js +28 -3
  35. package/src/tui.js +448 -1380
  36. package/src/ws.js +248 -0
  37. package/src/session-hub.js +0 -445
  38. package/src/web-auth.js +0 -98
  39. package/src/web-daemon-cli.js +0 -63
  40. package/src/web-daemon-client.js +0 -203
  41. package/src/web-daemon.js +0 -894
  42. package/src/web-live.js +0 -250
  43. package/src/web-public/app.css +0 -1524
  44. package/src/web-public/app.js +0 -2969
  45. package/src/web-public/complete.js +0 -154
  46. package/src/web-public/fonts/JetBrainsMono-Bold.woff2 +0 -0
  47. package/src/web-public/fonts/JetBrainsMono-Regular.woff2 +0 -0
  48. package/src/web-public/fonts/noto-sans-sc-100-400-normal.woff2 +0 -0
  49. package/src/web-public/fonts/noto-sans-sc-101-400-normal.woff2 +0 -0
  50. package/src/web-public/fonts/noto-sans-sc-102-400-normal.woff2 +0 -0
  51. package/src/web-public/fonts/noto-sans-sc-103-400-normal.woff2 +0 -0
  52. package/src/web-public/fonts/noto-sans-sc-104-400-normal.woff2 +0 -0
  53. package/src/web-public/fonts/noto-sans-sc-105-400-normal.woff2 +0 -0
  54. package/src/web-public/fonts/noto-sans-sc-106-400-normal.woff2 +0 -0
  55. package/src/web-public/fonts/noto-sans-sc-107-400-normal.woff2 +0 -0
  56. package/src/web-public/fonts/noto-sans-sc-108-400-normal.woff2 +0 -0
  57. package/src/web-public/fonts/noto-sans-sc-109-400-normal.woff2 +0 -0
  58. package/src/web-public/fonts/noto-sans-sc-110-400-normal.woff2 +0 -0
  59. package/src/web-public/fonts/noto-sans-sc-111-400-normal.woff2 +0 -0
  60. package/src/web-public/fonts/noto-sans-sc-112-400-normal.woff2 +0 -0
  61. package/src/web-public/fonts/noto-sans-sc-113-400-normal.woff2 +0 -0
  62. package/src/web-public/fonts/noto-sans-sc-114-400-normal.woff2 +0 -0
  63. package/src/web-public/fonts/noto-sans-sc-115-400-normal.woff2 +0 -0
  64. package/src/web-public/fonts/noto-sans-sc-116-400-normal.woff2 +0 -0
  65. package/src/web-public/fonts/noto-sans-sc-117-400-normal.woff2 +0 -0
  66. package/src/web-public/fonts/noto-sans-sc-118-400-normal.woff2 +0 -0
  67. package/src/web-public/fonts/noto-sans-sc-119-400-normal.woff2 +0 -0
  68. package/src/web-public/fonts/noto-sans-sc-21-400-normal.woff2 +0 -0
  69. package/src/web-public/fonts/noto-sans-sc-22-400-normal.woff2 +0 -0
  70. package/src/web-public/fonts/noto-sans-sc-23-400-normal.woff2 +0 -0
  71. package/src/web-public/fonts/noto-sans-sc-24-400-normal.woff2 +0 -0
  72. package/src/web-public/fonts/noto-sans-sc-25-400-normal.woff2 +0 -0
  73. package/src/web-public/fonts/noto-sans-sc-26-400-normal.woff2 +0 -0
  74. package/src/web-public/fonts/noto-sans-sc-27-400-normal.woff2 +0 -0
  75. package/src/web-public/fonts/noto-sans-sc-28-400-normal.woff2 +0 -0
  76. package/src/web-public/fonts/noto-sans-sc-29-400-normal.woff2 +0 -0
  77. package/src/web-public/fonts/noto-sans-sc-30-400-normal.woff2 +0 -0
  78. package/src/web-public/fonts/noto-sans-sc-31-400-normal.woff2 +0 -0
  79. package/src/web-public/fonts/noto-sans-sc-32-400-normal.woff2 +0 -0
  80. package/src/web-public/fonts/noto-sans-sc-33-400-normal.woff2 +0 -0
  81. package/src/web-public/fonts/noto-sans-sc-34-400-normal.woff2 +0 -0
  82. package/src/web-public/fonts/noto-sans-sc-35-400-normal.woff2 +0 -0
  83. package/src/web-public/fonts/noto-sans-sc-36-400-normal.woff2 +0 -0
  84. package/src/web-public/fonts/noto-sans-sc-37-400-normal.woff2 +0 -0
  85. package/src/web-public/fonts/noto-sans-sc-38-400-normal.woff2 +0 -0
  86. package/src/web-public/fonts/noto-sans-sc-39-400-normal.woff2 +0 -0
  87. package/src/web-public/fonts/noto-sans-sc-4-400-normal.woff2 +0 -0
  88. package/src/web-public/fonts/noto-sans-sc-40-400-normal.woff2 +0 -0
  89. package/src/web-public/fonts/noto-sans-sc-41-400-normal.woff2 +0 -0
  90. package/src/web-public/fonts/noto-sans-sc-42-400-normal.woff2 +0 -0
  91. package/src/web-public/fonts/noto-sans-sc-43-400-normal.woff2 +0 -0
  92. package/src/web-public/fonts/noto-sans-sc-44-400-normal.woff2 +0 -0
  93. package/src/web-public/fonts/noto-sans-sc-45-400-normal.woff2 +0 -0
  94. package/src/web-public/fonts/noto-sans-sc-46-400-normal.woff2 +0 -0
  95. package/src/web-public/fonts/noto-sans-sc-47-400-normal.woff2 +0 -0
  96. package/src/web-public/fonts/noto-sans-sc-48-400-normal.woff2 +0 -0
  97. package/src/web-public/fonts/noto-sans-sc-49-400-normal.woff2 +0 -0
  98. package/src/web-public/fonts/noto-sans-sc-5-400-normal.woff2 +0 -0
  99. package/src/web-public/fonts/noto-sans-sc-50-400-normal.woff2 +0 -0
  100. package/src/web-public/fonts/noto-sans-sc-51-400-normal.woff2 +0 -0
  101. package/src/web-public/fonts/noto-sans-sc-52-400-normal.woff2 +0 -0
  102. package/src/web-public/fonts/noto-sans-sc-53-400-normal.woff2 +0 -0
  103. package/src/web-public/fonts/noto-sans-sc-54-400-normal.woff2 +0 -0
  104. package/src/web-public/fonts/noto-sans-sc-55-400-normal.woff2 +0 -0
  105. package/src/web-public/fonts/noto-sans-sc-56-400-normal.woff2 +0 -0
  106. package/src/web-public/fonts/noto-sans-sc-57-400-normal.woff2 +0 -0
  107. package/src/web-public/fonts/noto-sans-sc-58-400-normal.woff2 +0 -0
  108. package/src/web-public/fonts/noto-sans-sc-59-400-normal.woff2 +0 -0
  109. package/src/web-public/fonts/noto-sans-sc-6-400-normal.woff2 +0 -0
  110. package/src/web-public/fonts/noto-sans-sc-60-400-normal.woff2 +0 -0
  111. package/src/web-public/fonts/noto-sans-sc-61-400-normal.woff2 +0 -0
  112. package/src/web-public/fonts/noto-sans-sc-62-400-normal.woff2 +0 -0
  113. package/src/web-public/fonts/noto-sans-sc-63-400-normal.woff2 +0 -0
  114. package/src/web-public/fonts/noto-sans-sc-64-400-normal.woff2 +0 -0
  115. package/src/web-public/fonts/noto-sans-sc-65-400-normal.woff2 +0 -0
  116. package/src/web-public/fonts/noto-sans-sc-66-400-normal.woff2 +0 -0
  117. package/src/web-public/fonts/noto-sans-sc-67-400-normal.woff2 +0 -0
  118. package/src/web-public/fonts/noto-sans-sc-68-400-normal.woff2 +0 -0
  119. package/src/web-public/fonts/noto-sans-sc-69-400-normal.woff2 +0 -0
  120. package/src/web-public/fonts/noto-sans-sc-70-400-normal.woff2 +0 -0
  121. package/src/web-public/fonts/noto-sans-sc-71-400-normal.woff2 +0 -0
  122. package/src/web-public/fonts/noto-sans-sc-72-400-normal.woff2 +0 -0
  123. package/src/web-public/fonts/noto-sans-sc-73-400-normal.woff2 +0 -0
  124. package/src/web-public/fonts/noto-sans-sc-74-400-normal.woff2 +0 -0
  125. package/src/web-public/fonts/noto-sans-sc-75-400-normal.woff2 +0 -0
  126. package/src/web-public/fonts/noto-sans-sc-76-400-normal.woff2 +0 -0
  127. package/src/web-public/fonts/noto-sans-sc-77-400-normal.woff2 +0 -0
  128. package/src/web-public/fonts/noto-sans-sc-78-400-normal.woff2 +0 -0
  129. package/src/web-public/fonts/noto-sans-sc-79-400-normal.woff2 +0 -0
  130. package/src/web-public/fonts/noto-sans-sc-80-400-normal.woff2 +0 -0
  131. package/src/web-public/fonts/noto-sans-sc-81-400-normal.woff2 +0 -0
  132. package/src/web-public/fonts/noto-sans-sc-82-400-normal.woff2 +0 -0
  133. package/src/web-public/fonts/noto-sans-sc-83-400-normal.woff2 +0 -0
  134. package/src/web-public/fonts/noto-sans-sc-84-400-normal.woff2 +0 -0
  135. package/src/web-public/fonts/noto-sans-sc-85-400-normal.woff2 +0 -0
  136. package/src/web-public/fonts/noto-sans-sc-86-400-normal.woff2 +0 -0
  137. package/src/web-public/fonts/noto-sans-sc-87-400-normal.woff2 +0 -0
  138. package/src/web-public/fonts/noto-sans-sc-88-400-normal.woff2 +0 -0
  139. package/src/web-public/fonts/noto-sans-sc-89-400-normal.woff2 +0 -0
  140. package/src/web-public/fonts/noto-sans-sc-90-400-normal.woff2 +0 -0
  141. package/src/web-public/fonts/noto-sans-sc-91-400-normal.woff2 +0 -0
  142. package/src/web-public/fonts/noto-sans-sc-97-400-normal.woff2 +0 -0
  143. package/src/web-public/fonts/noto-sans-sc-98-400-normal.woff2 +0 -0
  144. package/src/web-public/fonts/noto-sans-sc-99-400-normal.woff2 +0 -0
  145. package/src/web-public/fonts/noto-sans-sc.css +0 -775
  146. package/src/web-public/fonts.css +0 -31
  147. package/src/web-public/home.css +0 -222
  148. package/src/web-public/home.html +0 -33
  149. package/src/web-public/home.js +0 -160
  150. package/src/web-public/i18n.js +0 -983
  151. package/src/web-public/index.html +0 -196
  152. package/src/web-public/login.css +0 -123
  153. package/src/web-public/login.html +0 -25
  154. package/src/web-public/login.js +0 -46
  155. package/src/web-public/settings.js +0 -290
  156. package/src/web-ws.js +0 -226
  157. package/src/web.js +0 -430
@@ -1,2969 +0,0 @@
1
- import { t, catalog, LANGUAGES, DEFAULT_LANG } from './i18n.js';
2
- import { Completer } from './complete.js';
3
- import { SettingsPanel, attachSettings } from './settings.js';
4
-
5
-
6
- const $ = (id) => document.getElementById(id);
7
- const stream = $('stream');
8
- const input = $('input');
9
-
10
- let LANG = DEFAULT_LANG;
11
- try {
12
- const saved = localStorage.getItem('hncode.lang');
13
- if (saved && LANGUAGES.some((l) => l.id === saved)) LANG = saved;
14
- } catch {}
15
-
16
- let T = catalog(LANG);
17
-
18
- const tr = (key, vars) => {
19
- let s = T[key] || key;
20
- if (vars) {
21
- for (const k of Object.keys(vars)) s = s.split('{' + k + '}').join(String(vars[k]));
22
- }
23
- return s;
24
- };
25
-
26
- // Strip ANSI escape codes from a string. Rows the TUI sends for WIN-PLATFORM
27
- // (role 'rich', some system lines) carry terminal styling (\x1b[97m etc.); the
28
- // browser has no terminal, so those must become plain text or the literal
29
- // "[97m" leak shows up in the transcript. Applied once at paintRow so every
30
- // role — simple text, markdown, tool rows — is clean.
31
- const ANSI_RE = /\u001b\[[0-9;:<=>?]*[ -/]*[@-~]/g;
32
- function stripAnsi(s) { return String(s == null ? '' : s).replace(ANSI_RE, ''); }
33
-
34
- let status = {};
35
- let completer = null;
36
- let settingsPanel = null;
37
-
38
- function applyStatic() {
39
- document.documentElement.lang = LANG === 'zh' ? 'zh-CN' : 'en';
40
- for (const node of document.querySelectorAll('[data-i18n]')) {
41
- node.textContent = tr(node.getAttribute('data-i18n'));
42
- }
43
- for (const node of document.querySelectorAll('[data-i18n-title]')) {
44
- node.title = tr(node.getAttribute('data-i18n-title'));
45
- }
46
- for (const node of document.querySelectorAll('[data-i18n-placeholder]')) {
47
- node.placeholder = tr(node.getAttribute('data-i18n-placeholder'));
48
- }
49
- for (const node of document.querySelectorAll('[data-i18n-aria-label]')) {
50
- node.setAttribute('aria-label', tr(node.getAttribute('data-i18n-aria-label')));
51
- }
52
- rerenderRows();
53
- renderStatus();
54
- setPmode();
55
- }
56
-
57
- function buildLangSwitch() {
58
- const box = $('lang-switch');
59
- box.replaceChildren();
60
- box.title = tr('nav.language');
61
- for (const l of LANGUAGES) {
62
- const b = document.createElement('button');
63
- b.type = 'button';
64
- b.textContent = l.label;
65
- b.className = l.id === LANG ? 'is-on' : '';
66
- b.addEventListener('click', () => {
67
- if (l.id === LANG) return;
68
- LANG = l.id;
69
- T = catalog(LANG);
70
- try { localStorage.setItem('hncode.lang', LANG); } catch {}
71
- buildLangSwitch();
72
- applyStatic();
73
- });
74
- box.appendChild(b);
75
- }
76
- }
77
-
78
- function rerenderRows() {
79
- for (const [i, node] of win.els) {
80
- const row = rowItems[i];
81
- if (row && node._rec) paintRow(node._rec);
82
- }
83
- }
84
-
85
- let es = null;
86
- let retry = 0;
87
- let retryTimer = null;
88
- let readOnly = false;
89
- let readOnlyChecked = false;
90
-
91
- function setConn(kind, text) {
92
- $('conn').className = 'dot dot-' + kind;
93
- $('conn-text').textContent = text;
94
- }
95
-
96
- // Live updates arrive over WebSocket, not EventSource. The server (web.js) runs a
97
- // zero-dependency RFC 6455 endpoint at /api/ws: on connect it sends a `snapshot`
98
- // of the current view, then every hub event as a JSON text frame. A dropped
99
- // connection is retried with backoff, like EventSource auto-reconnect did for
100
- // SSE.
101
- function connect() {
102
- if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; }
103
- if (es) { try { es.close(); } catch { /* already gone */ } }
104
-
105
- setConn('wait', tr('nav.connecting'));
106
- // Relative URL, exactly like the old `new EventSource('api/events')`: the
107
- // browser resolves it against the current document path, so behind the daemon
108
- // (page at /s/<id>/) the handshake reaches /s/<id>/api/ws, and a standalone
109
- // /web reaches /api/ws. Building `location.host + '/api/ws'` instead dropped
110
- // the /s/<id> prefix and made the daemon drop every handshake.
111
- const src = new WebSocket('api/ws');
112
- es = src;
113
-
114
- src.onopen = () => {
115
- if (src !== es) return;
116
- retry = 0;
117
- setConn('on', tr('nav.connected'));
118
- };
119
-
120
- src.onmessage = (ev) => {
121
- let msg;
122
- try { msg = JSON.parse(ev.data); } catch { return; }
123
- handle(msg);
124
- };
125
-
126
- src.onclose = (ev) => {
127
- // TEMP diag: record every close so a "reloads every few seconds" bug can be
128
- // tied to who dropped the socket. Remove after diagnosing.
129
- if (!window.__wsCloseLog) window.__wsCloseLog = [];
130
- window.__wsCloseLog.push({ t: Date.now(), code: ev && ev.code, wasClean: ev && ev.wasClean, reason: ev && ev.reason });
131
- console.log('WS-close', ev && ev.code, ev && ev.wasClean);
132
- if (src !== es) return;
133
- if (es === src) es = null;
134
- // A WebSocket that never opened usually means the session has EXITED: the
135
- // daemon destroys the handshake for read-only sessions (there is no live
136
- // server to proxy). Fall back to a one-shot `api/state` fetch so the
137
- // finished transcript still renders, instead of spinning on reconnect.
138
- if (!readOnly && !readOnlyChecked && retry === 0) {
139
- readOnlyChecked = true;
140
- loadReadOnlySnapshot();
141
- return;
142
- }
143
- setConn('off', tr('nav.disconnected'));
144
- retry = Math.min(retry + 1, 6);
145
- retryTimer = setTimeout(connect, 400 * retry);
146
- };
147
-
148
- src.onerror = () => { /* onclose follows and does the retry */ };
149
- }
150
-
151
- // The session has EXITED (read-only): load its snapshot over HTTP and freeze
152
- // the UI. api/state on the daemon answer for a saved session; standalone web.js
153
- // does too. Disable the composer so a read-only page cannot pretend it can act.
154
- async function loadReadOnlySnapshot() {
155
- if (readOnly) return;
156
- let res;
157
- try { res = await fetch('api/state', { headers: { accept: 'application/json' } }); }
158
- catch { /* network error — fall through to normal retry */ }
159
- if (!res || !res.ok) {
160
- // Not a read-only case; resume normal reconnect.
161
- if (res) setConn('off', tr('nav.disconnected'));
162
- retry = Math.min(retry + 1, 6);
163
- retryTimer = setTimeout(connect, 400 * retry);
164
- return;
165
- }
166
- let data;
167
- try { data = await res.json(); } catch { /* ignore */ return; }
168
- readOnly = true;
169
- applySnapshot({ rows: (data && data.rows) || [], status: (data && data.status) || {} });
170
- setConn('off', tr('nav.disconnected'));
171
- // Freeze the composer: no WS to send on, and the session is read-only anyway.
172
- const inputEl = $('input');
173
- if (inputEl) inputEl.disabled = true;
174
- setPanelVisible('send', false);
175
- setPanelVisible('btn-interrupt', false);
176
- setPanelVisible('working', false);
177
- const readonlyBadge = $('readonly-badge');
178
- if (readonlyBadge) readonlyBadge.hidden = false;
179
- }
180
-
181
- async function act(name, args) {
182
- // The ONLY transport is the WebSocket. Sending is fire-and-forget (the UI
183
- // updates optimistically; the real result rides the status/row stream back),
184
- // and there is deliberately NO HTTP fallback: if the socket is down the server
185
- // is unreachable, so a POST would not reach it either — it would just hang the
186
- // caller. Tell the user the link is down and let the reconnect loop restore it.
187
- var ws = es;
188
- if (ws && ws.readyState === 1) {
189
- try {
190
- ws.send(JSON.stringify({ action: name, args: args || [] }));
191
- return { ok: true };
192
- } catch (e) { /* fall through to down-report */ }
193
- }
194
- // Connection lost. If the socket is simply reconnecting (readyState 0), wait
195
- // for it; if it is closed, tell the user and ensure connect() is running.
196
- if (ws && ws.readyState === 0) {
197
- return { ok: false, error: tr('err.unreachable') };
198
- }
199
- toast(tr('nav.disconnected'));
200
- connect();
201
- return { ok: false, error: tr('err.unreachable') };
202
- }
203
-
204
- async function actReturning(name, args) {
205
- const body = await act(name, args);
206
- if (!body || body.ok !== true) throw new Error((body && body.error) || tr('err.actionFailed'));
207
- return body;
208
- }
209
-
210
- let toastTimer = null;
211
-
212
- function toast(text) {
213
- const node = $('notice');
214
- node.textContent = text;
215
- node.hidden = false;
216
- clearTimeout(toastTimer);
217
- toastTimer = setTimeout(() => { node.hidden = true; }, 4000);
218
- }
219
-
220
- function handle(msg) {
221
- switch (msg.type) {
222
- case 'snapshot': applySnapshot(msg); break;
223
- case 'row': addRow(msg.row); break;
224
- case 'row_patch': patchRow(msg.id, msg.patch); break;
225
- case 'rows_reset': applySnapshot({ rows: msg.rows, status }); break;
226
- case 'status': applyStatus(msg.status); break;
227
- // Granular events (claude-code style): update just one panel, not the whole
228
- // status DOM. The server pushes these when a single field changes.
229
- case 'queued': {
230
- const q = Array.isArray(msg.queued) ? msg.queued : [];
231
- if (!status) status = {};
232
- status.queued = q;
233
- setPanelVisible('queue-panel', q.length > 0);
234
- renderQueuePanel(q, !!(status && status.busy));
235
- break;
236
- }
237
- case 'todos': {
238
- const t = Array.isArray(msg.todos) ? msg.todos : [];
239
- if (!status) status = {};
240
- status.todos = t;
241
- setPanelVisible('todo-panel', t.length > 0);
242
- renderTodoPanel(t);
243
- break;
244
- }
245
- case 'tasks': {
246
- const t = Array.isArray(msg.tasks) ? msg.tasks : [];
247
- if (status) status.tasks = t;
248
- if (!isViewHidden('tasks')) renderTasks(t);
249
- renderTabCounts(status || {});
250
- break;
251
- }
252
- default: break;
253
- }
254
- }
255
-
256
- /**
257
- * Animation-only fields, matching the server's exclusion list (session-hub.js).
258
- * They drive the Working pulse, which the browser draws for itself; a change in
259
- * just these must NOT trigger a full status re-render, or a long turn would
260
- * rebuild every card pane every frame — exactly the churn that froze the tab.
261
- */
262
- const ANIMATION_FIELDS = new Set(['spin', 'workMsg', 'pulseStart']);
263
-
264
- function samePlain(a, b) {
265
- if (a === b) return true; // identical ref or primitive
266
- if (Array.isArray(a) && Array.isArray(b)) {
267
- if (a.length !== b.length) return false; // cheap length gate first
268
- }
269
- return JSON.stringify(a) === JSON.stringify(b); // deep: last resort only
270
- }
271
-
272
- function stableStatusChanged(next) {
273
- for (const k of Object.keys(next)) {
274
- if (ANIMATION_FIELDS.has(k)) continue;
275
- if (!samePlain(next[k], status[k])) return true;
276
- }
277
- for (const k of Object.keys(status)) {
278
- if (ANIMATION_FIELDS.has(k)) continue;
279
- if (!(k in next)) return true;
280
- }
281
- return false;
282
- }
283
-
284
- function applyStatus(s) {
285
- const next = s || {};
286
- // The WORKING row's word / pulse phase is drawn by drawPulse() off its own
287
- // clock, so a broadcast that only moved `spin` should not touch the panels.
288
- const stableChanged = !status || stableStatusChanged(next);
289
- const wasBusy = !!(status && status.busy);
290
- status = next;
291
- // Always animate the Working row off the latest state; only re-render the
292
- // whole status DOM when a stable field actually changed.
293
- if (status.busy) drawPulse(); else clearPulse();
294
- if (stableChanged) renderStatus();
295
- else if (status.busy !== wasBusy) renderBusyButton();
296
- }
297
-
298
- let rowItems = [];
299
-
300
- const rowIndex = new Map();
301
- let expandedRows = new Set();
302
-
303
- /**
304
- * Set scrollTop as a PROGRAMMATIC move and remember the target, so the async
305
- * `scroll` event it fires is recognized as ours and not mistaken for a user
306
- * scroll. The old `pinning` flag alone was unreliable: the scroll event is
307
- * dispatched a frame later, by which time the microtask that cleared `pinning`
308
- * had already run — so a programmatic "snap to bottom" was read back as the user
309
- * scrolling to the bottom, which re-pinned the view and fought a user who had
310
- * just scrolled up.
311
- */
312
- function setScrollTop(v) {
313
- stream.scrollTop = v;
314
- // Remember the CLAMPED position the browser actually landed on (scrollTop is
315
- // capped to the scrollable range), so the async scroll event compares equal and
316
- // is correctly ignored rather than misread as a user scroll.
317
- win._progTop = stream.scrollTop;
318
- }
319
-
320
- // Flow virtualisation: rows live in NORMAL document flow; the browser computes
321
- // every real height, so two rows can never overlap. Only rows inside the
322
- // window have DOM; the ranges above/below it are reserved by two padding divs,
323
- // sized from measured heights (PLACEHOLDER_H until a row is first mounted).
324
- //
325
- // The overscan is measured in PIXELS, not rows. A row-count overscan is unusable
326
- // here because row heights differ by an order of magnitude — a folded tool result is
327
- // ~180px, a plain system line ~20px — so "8 rows" could be 160px of slack in one
328
- // stretch of the transcript and 1400px in another. In the thin stretch a row was
329
- // unmounted while it was still on screen (the reported "gone before it left the
330
- // viewport"), because the padding divs then took its place and the content jumped.
331
- // Keeping one extra viewport above and below makes the window independent of how
332
- // tall the rows happen to be.
333
- const WIN_OVERSCAN_PX = 800;
334
- // The row-count floor that goes with it (see renderWindow): whichever reaches further
335
- // wins. Estimates cannot be trusted, so this is what actually guarantees a row is not
336
- // unmounted while it is still visible.
337
- const WIN_OVERSCAN_ROWS = 12;
338
- const NEAR_END_PX = 24;
339
- // TanStack Virtual's rule for estimateSize: "estimate the LARGEST possible
340
- // size (within comfort)". An underestimate makes the scroll range too short,
341
- // so unmeasured history is skipped past and rows pop/jump as they mount. A
342
- // generous overestimate only makes the scrollbar slightly long, which the
343
- // measurement cache shrinks as rows mount. Tool rows dominate this transcript,
344
- // and a folded result is ~8 lines + chrome, so ~180px is a safe floor.
345
- const PLACEHOLDER_H = 180;
346
-
347
- const win = {
348
- spacer: null,
349
- topPad: null,
350
- bottomPad: null,
351
- heights: [], // REAL heights, measured per mounted row (0 = never seen)
352
- start: 0,
353
- end: 0,
354
- els: new Map(),
355
- raf: null,
356
- pinned: true,
357
- _lastStart: -1,
358
- _lastEnd: -1,
359
- _progTop: null, // last programmatic scrollTop, to ignore our own scroll event
360
- };
361
-
362
- function knownHeight(i) {
363
- const h = win.heights[i];
364
- return h > 0 ? h : PLACEHOLDER_H;
365
- }
366
-
367
- function heightAbove(i) {
368
- let sum = 0;
369
- for (let k = 0; k < i && k < rowItems.length; k++) sum += knownHeight(k);
370
- return sum;
371
- }
372
-
373
- function heightBelow(i) {
374
- let sum = 0;
375
- for (let k = i; k < rowItems.length; k++) sum += knownHeight(k);
376
- return sum;
377
- }
378
-
379
- function scheduleWindow() {
380
- if (win.raf !== null) return;
381
- win.raf = requestAnimationFrame(renderWindow);
382
- }
383
-
384
- function ensureSpacer() {
385
- if (win.spacer && win.spacer.isConnected) return win.spacer;
386
- stream.replaceChildren();
387
- win.spacer = document.createElement("div");
388
- win.spacer.className = "win-spacer";
389
- win.topPad = document.createElement("div");
390
- win.bottomPad = document.createElement("div");
391
- win.topPad.className = "win-pad";
392
- win.bottomPad.className = "win-pad";
393
- win.spacer.append(win.topPad, win.bottomPad);
394
- stream.appendChild(win.spacer);
395
- win.els.clear();
396
- return win.spacer;
397
- }
398
-
399
- function mountRow(i, el) {
400
- // Insert at the row's DOCUMENT position, not blindly at the end. Scrolling
401
- // UP mounts top rows while later rows are already in the spacer; appending
402
- // them at the end put a row that belongs ABOVE below rows that belong BELOW
403
- // — document order broke and the transcript rendered scrambled/overlapping.
404
- let before = win.bottomPad;
405
- for (let k = i + 1; k < win.end; k++) {
406
- const next = win.els.get(k);
407
- if (next) { before = next; break; }
408
- }
409
- win.spacer.insertBefore(el, before);
410
- win.els.set(i, el);
411
- const rec = el._rec;
412
- if (rec) rec.index = i;
413
- }
414
-
415
- function unmountRow(i) {
416
- const el = win.els.get(i);
417
- if (!el) return;
418
- const rec = el._rec;
419
- if (rec) {
420
- const h = el.getBoundingClientRect().height;
421
- if (h > 0 && win.heights[rec.index] !== h) { win.heights[rec.index] = h; win._lastStart = -1; }
422
- if (rec.ro) rec.ro.unobserve(el);
423
- }
424
- el.remove();
425
- win.els.delete(i);
426
- }
427
-
428
- function clearAllRows() {
429
- for (const i of [...win.els.keys()]) unmountRow(i);
430
- win._lastStart = -1;
431
- win._lastEnd = -1;
432
- }
433
-
434
- function renderWindow() {
435
- win.raf = null;
436
- if (!win.spacer || !win.spacer.isConnected) return;
437
- if (!rowItems.length) {
438
- win.topPad.style.height = "0px";
439
- win.bottomPad.style.height = "0px";
440
- clearAllRows();
441
- win.start = win.end = 0;
442
- return;
443
- }
444
- const viewH = stream.clientHeight || 608;
445
- // Overscan is expressed in BOTH pixels and rows, and whichever reaches FURTHER
446
- // wins. Row heights differ by an order of magnitude (a folded tool result ~180px,
447
- // a plain line ~20px), so a row count alone left almost no margin in a thin
448
- // stretch and unmounted rows that were still on screen. A pixel budget alone is not
449
- // enough either: an UNMEASURED row is priced at PLACEHOLDER_H, so walking 800px of
450
- // estimates can cover far less than 800px of real content and the last rows fall
451
- // outside the window. The row floor is the guarantee; the pixel budget trims the
452
- // overshoot on tall rows.
453
- const over = Math.max(WIN_OVERSCAN_PX, viewH);
454
- const MIN_MARGIN_ROWS = WIN_OVERSCAN_ROWS;
455
- if (win.pinned) {
456
- // Pinned to the tail: grow upward until BOTH budgets are satisfied.
457
- win.end = rowItems.length;
458
- let used = 0;
459
- let start = win.end;
460
- while (start > 0 && (used < viewH + over || win.end - start < MIN_MARGIN_ROWS)) {
461
- start--;
462
- used += knownHeight(start);
463
- }
464
- win.start = start;
465
- } else {
466
- // Walk from the top accumulating heights until the scroll position is reached.
467
- let acc = 0;
468
- let first = rowItems.length - 1;
469
- for (let i = 0; i < rowItems.length; i++) {
470
- if (acc + knownHeight(i) > stream.scrollTop) { first = i; break; }
471
- acc += knownHeight(i);
472
- }
473
- // Above the viewport: the pixel budget OR the row floor, whichever is further.
474
- let start = first;
475
- let above = 0;
476
- while (start > 0 && (above < over || first - start < MIN_MARGIN_ROWS)) {
477
- start--;
478
- above += knownHeight(start);
479
- }
480
- // Below the viewport: same rule.
481
- let end = first + 1;
482
- let used = knownHeight(first);
483
- while (end < rowItems.length && (used < viewH + over || end - first < MIN_MARGIN_ROWS)) {
484
- used += knownHeight(end);
485
- end++;
486
- }
487
- win.start = start;
488
- win.end = Math.min(rowItems.length, end);
489
- }
490
- const sameRange = win.start === win._lastStart && win.end === win._lastEnd;
491
- win._lastStart = win.start;
492
- win._lastEnd = win.end;
493
- // A height change does NOT need a different window — only different paddings. The
494
- // pad sizes are recomputed below on every pass, so returning early here is safe.
495
- // It used to be gated on `same` (start+end), which is why `_lastStart = -1` on
496
- // every height change tore the whole window down and rebuilt it: each tool call
497
- // changes a row's height, so the unmount/remount cycle re-created every visible
498
- // row's DOM and the tool NAMES visibly flashed — not just the call that finished.
499
- if (sameRange) {
500
- win.topPad.style.height = heightAbove(win.start) + "px";
501
- win.bottomPad.style.height = heightBelow(win.end) + "px";
502
- if (win.pinned) setScrollTop(stream.scrollHeight);
503
- return;
504
- }
505
- for (const k of [...win.els.keys()]) {
506
- if (k < win.start || k >= win.end) unmountRow(k);
507
- }
508
- for (let k = win.start; k < win.end; k++) {
509
- if (!win.els.has(k)) mountRow(k, buildRow(rowItems[k]));
510
- }
511
- win.topPad.style.height = heightAbove(win.start) + "px";
512
- win.bottomPad.style.height = heightBelow(win.end) + "px";
513
- if (win.pinned) setScrollTop(stream.scrollHeight);
514
- }
515
-
516
- var sharedRO = typeof ResizeObserver === "function" ? new ResizeObserver(function (entries) {
517
- let delta = 0;
518
- for (const en of entries) {
519
- const rec = en.target._rec;
520
- if (!rec || rec.index < 0) continue;
521
- const h = en.target.getBoundingClientRect().height;
522
- const prev = win.heights[rec.index] > 0 ? win.heights[rec.index] : PLACEHOLDER_H;
523
- if (h <= 0 || prev === h) continue;
524
- win.heights[rec.index] = h;
525
- delta += h - prev;
526
- }
527
- if (delta !== 0) {
528
- win._lastStart = -1; // heights changed: paddings must be recomputed
529
- scheduleWindow();
530
- // TanStack semantics (shouldAdjustScrollPositionOnItemSizeChange): correct
531
- // the scroll offset only when the change is ABOVE the viewport AND the user
532
- // is not scrolling backward — that combination is the classic "rows jump
533
- // while scrolling up" jank. End-pinned views still re-anchor to the bottom.
534
- if (win.pinned) {
535
- setScrollTop(stream.scrollHeight);
536
- } else if (delta > 0) {
537
- // A row above the viewport got TALLER: keep the text under the reader
538
- // stationary by shifting the offset by the same amount.
539
- setScrollTop(stream.scrollTop + delta);
540
- }
541
- // delta < 0 while unpinned: content above shrank; no correction needed,
542
- // the browser keeps the viewport anchored to the same content.
543
- }
544
- }) : null;
545
-
546
- function observeRow(el) {
547
- if (sharedRO) sharedRO.observe(el);
548
- return sharedRO;
549
- }
550
-
551
- function onScroll() {
552
- // Ignore the scroll event our OWN setScrollTop just fired (same position),
553
- // so a programmatic snap-to-bottom is never mistaken for a user scroll.
554
- if (win._progTop != null && Math.abs(stream.scrollTop - win._progTop) <= 1) {
555
- return;
556
- }
557
- win._progTop = null;
558
- const dist = stream.scrollHeight - stream.scrollTop - stream.clientHeight;
559
- // Any scroll AWAY from the bottom is a deliberate move by the user, so the
560
- // tail-follow ends IMMEDIATELY — no matter how small. The old rule kept
561
- // `pinned` true until the user had scrolled more than a full viewport, so a
562
- // small upward scroll left the view pinned and the next render yanked it back
563
- // to the bottom: the "fighting the scroll" jank. Re-pin only when the user
564
- // returns to (or near) the bottom.
565
- win.pinned = dist <= NEAR_END_PX * 3;
566
- scheduleWindow();
567
- }
568
-
569
- // Patch any height-affecting repaint into the measurement cycle.
570
- const patchQueue = new Set();
571
- let patchFlushQueued = false;
572
-
573
- /**
574
- * A streaming patch repaints the row's content, which almost always changes its
575
- * height — and a changed height invalidates every offset below it. So the reflow
576
- * is forced here instead of waiting for the row's resize observer: the observer
577
- * fires a frame LATER, and until it does the rows underneath sit at their old
578
- * positions with the new, taller row drawn over them. That gap is the overlap
579
- * that showed up while text streamed in.
580
- */
581
- function queueRowPatch(rec, patch) {
582
- for (const k of Object.keys(patch)) rec.row[k] = patch[k];
583
- if (patch.append !== undefined) {
584
- const cut = typeof patch.textTo === 'number' ? patch.textTo : 0;
585
- rec.row.text = String(rec.row.text || '').slice(0, cut) + patch.append;
586
- }
587
- patchQueue.add(rec);
588
- if (patchFlushQueued) return;
589
- patchFlushQueued = true;
590
- requestAnimationFrame(() => {
591
- patchFlushQueued = false;
592
- let heightsChanged = false;
593
- for (const r of patchQueue) {
594
- paintRow(r);
595
- const h = r.el.getBoundingClientRect().height;
596
- if (h > 0 && r.index >= 0 && win.heights[r.index] !== h) { win.heights[r.index] = h; heightsChanged = true; }
597
- }
598
- if (heightsChanged) win._lastStart = -1;
599
- patchQueue.clear();
600
- scheduleWindow();
601
- });
602
- }
603
-
604
- function resetView(rows, nextStatus) {
605
- rowIndex.clear();
606
- rowItems = (rows || []).map((r) => ({ ...r }));
607
- for (let i = 0; i < rowItems.length; i++) {
608
- const r = rowItems[i];
609
- if (r && r.id != null) rowIndex.set(r.id, i);
610
- }
611
- status = nextStatus || {};
612
- renderStatus();
613
-
614
- expandedRows = new Set();
615
- win.heights = new Array(rowItems.length).fill(0); // 0 = unmeasured placeholder
616
- win.start = win.end = 0;
617
- win.pinned = true;
618
- clearAllRows();
619
- win.spacer = null;
620
- ensureSpacer();
621
- renderWindow();
622
- }
623
-
624
- function applySnapshot(s) {
625
- resetView(s.rows, s.status);
626
- }
627
-
628
- /**
629
- * The browser's transcript is capped at the same number the server keeps
630
- * (`MAX_ROWS` in session-hub.js). Without a cap the two grow apart in the way
631
- * that only shows up on the long sessions this UI exists for: the server trims
632
- * its ring while the tab keeps every row it was ever sent, so the page holds a
633
- * transcript the server no longer has — and every structure derived from it
634
- * (the id index, the heights array, the expanded set) grows with it.
635
- */
636
- const MAX_ROWS = 4000;
637
-
638
- /** Drop the oldest rows until the list is back under the cap, moving every
639
- derived structure with them. */
640
- function trimRows() {
641
- const over = rowItems.length - MAX_ROWS;
642
- if (over <= 0) return;
643
-
644
- rowItems.splice(0, over);
645
- win.heights.splice(0, over);
646
-
647
- // Every remaining row moved up by `over`, so the id index is rebuilt rather
648
- // than patched — an incremental fix-up here is exactly where an off-by-`over`
649
- // bug would hide.
650
- rowIndex.clear();
651
- for (let i = 0; i < rowItems.length; i++) {
652
- const r = rowItems[i];
653
- if (r && r.id != null) rowIndex.set(r.id, i);
654
- }
655
-
656
- // Mounted elements are keyed by index, so they are now wrong too; dropping
657
- // them costs one re-render and removes any chance of a stale element painting
658
- // a row that has moved.
659
- clearAllRows();
660
- win.start = win.end = 0;
661
- }
662
-
663
- function addRow(row) {
664
- if (!row) return;
665
- if (row.id != null && rowIndex.has(row.id)) { patchRow(row.id, row); return; }
666
- const item = { ...row };
667
- rowItems.push(item);
668
- // Pre-estimate the row's height so a long message is sized correctly even
669
- // before it scrolls into view; the resize observer replaces this once mounted.
670
- win.heights.push(0); // unmeasured until first mount
671
- if (item.id != null) rowIndex.set(item.id, rowItems.length - 1);
672
- // Results start FOLDED — the "more" button adds the id to expandedRows.
673
- // (Every row used to start expanded, which defeated the fold caps entirely
674
- // and made a giant tool result overlap everything around it.)
675
- trimRows();
676
- scheduleWindow();
677
- }
678
-
679
- function patchRow(id, patch) {
680
- const i = rowIndex.get(id);
681
- if (i === undefined) return;
682
- const prev = rowItems[i];
683
- const next = { ...prev, ...patch };
684
- if (patch.append !== undefined) {
685
- const cut = typeof patch.textTo === 'number' ? patch.textTo : 0;
686
- next.text = String(prev.text || '').slice(0, cut) + patch.append;
687
- delete next.append;
688
- delete next.textTo;
689
- }
690
- rowItems[i] = next;
691
- const el = win.els.get(i);
692
- if (el && el._rec) {
693
- queueRowPatch(el._rec, patch);
694
- } else if (win.heights[i] !== undefined) {
695
- // Not on screen: keep the pre-estimate in step with the growing text, or the
696
- // scrollbar lags a long streaming message by a whole viewport.
697
- win.heights[i] = 0; // re-measure on next mount
698
- scheduleWindow();
699
- }
700
- }
701
-
702
-
703
- function repaintRow(id) {
704
- const i = rowIndex.get(id);
705
- if (i === undefined) return;
706
- const el = win.els.get(i);
707
- if (!el || !el._rec) return;
708
- paintRow(el._rec);
709
- const h = el.getBoundingClientRect().height;
710
- if (h > 0) win.heights[i] = h;
711
- scheduleWindow();
712
- }
713
-
714
-
715
-
716
- /**
717
- * MARKERS — the `❯` / `●` / `↳` the terminal prints at the start of a line.
718
- *
719
- * The terminal has NO gutter column: `messageLines()` builds each row as a text
720
- * prefix (`'❯ '`, `'● '`, `'↳ '`, or a two-space continuation) concatenated to
721
- * the body, and `rowToLine()` emits `ind + body` verbatim. The marker's two
722
- * columns ARE the layout, so a wrapped paragraph hangs under the marker for
723
- * free. The browser reproduces that with a CSS `::before` on the body box — a
724
- * real grid column would have to centre the glyph and would not hang right.
725
- */
726
- const MARK_KEY = {
727
- user: 'mark.user',
728
- queued: 'mark.queued',
729
- steer: 'mark.steer',
730
- bash: 'mark.bash',
731
- warn: 'mark.warn',
732
- };
733
-
734
- const BOX_ROLES = new Set(['user', 'queued', 'bash']);
735
- const SIMPLE_ROLES = new Set(['user', 'queued', 'steer', 'bash', 'system', 'warn', 'error', 'aborted']);
736
-
737
- function markFor(role, row) {
738
- if (role === 'tool') return tr(row.failed ? 'mark.toolFailed' : 'mark.tool');
739
- if (role === 'tool_result') return tr('mark.result');
740
- if (role === 'thinking') return tr('mark.thinking');
741
- if (role === 'compaction') return tr('mark.tool');
742
- if (role === 'bg_task') {
743
- return tr(row.card && row.card.phase === 'failed' ? 'mark.bgTaskFailed' : 'mark.bgTask');
744
- }
745
- const key = MARK_KEY[role];
746
- return key ? tr(key) : '';
747
- }
748
-
749
- function rowClassFor(role) {
750
- if (role === 'tool') return 'msg-tool';
751
- if (role === 'tool_result') return 'msg-result';
752
- if (role === 'bg_task') return 'msg-bgtask';
753
- return 'msg-' + role;
754
- }
755
-
756
- // A single assistant row past this many characters renders as PLAIN TEXT even
757
- // if it contains markdown: block-parsing a 200KB reply into thousands of nodes
758
- // in one row stalled the tab. Plain text is one node and reads fine; the row
759
- // content itself is what the model sent.
760
- const MD_CHAR_BUDGET = 60000;
761
-
762
- function buildRow(row) {
763
- const el = document.createElement('div');
764
- el.className = 'win-row';
765
- const rec = { el, row: row || {}, role: '', body: null, ro: null, simple: false, index: -1, mark: null };
766
- el._rec = rec;
767
- rec.ro = observeRow(el);
768
- paintRow(rec);
769
- return el;
770
- }
771
-
772
- function paintRow(rec) {
773
- const r = rec.row || {};
774
- const role = String(r.role || 'system');
775
- const text = stripAnsi(String(r.text == null ? '' : r.text));
776
-
777
- // STREAMING: a pending assistant row ALWAYS renders as one text node. The
778
- // markdown parser is O(text) per repaint, so running it on every streamed
779
- // patch of a growing reply is quadratic and froze the tab. When the turn
780
- // finishes (pending -> false) the row is re-classified once and the full
781
- // markdown render happens exactly once, like the terminal finishing a block.
782
- const streamPending = role === 'assistant' && r.pending === true;
783
- const tooBigForMd = role === 'assistant' && text.length > MD_CHAR_BUDGET;
784
- const simple = SIMPLE_ROLES.has(role) || (role === 'assistant' && (streamPending || tooBigForMd || !hasMarkup(text)));
785
- if (rec.role !== role || rec.simple !== simple) {
786
- rec.el.className = 'win-row ' + rowClassFor(role);
787
- rec.body = document.createElement('div');
788
- rec.body.className = BOX_ROLES.has(role) ? 'msg-box' : 'msg-body';
789
- rec.el.replaceChildren(rec.body);
790
- rec.role = role;
791
- rec.simple = simple;
792
- }
793
-
794
- rec.el.classList.toggle('is-failed', r.failed === true);
795
- rec.el.classList.toggle('is-running', role === 'tool' && !!r.pending && !r.failed);
796
- rec.el.classList.toggle('is-done', role === 'tool' && !r.pending && !r.failed);
797
- if (role === 'compaction') {
798
- rec.el.classList.toggle('is-done', r.phase === 'done');
799
- rec.el.classList.toggle('is-cancelled', r.phase === 'cancelled');
800
- rec.el.classList.toggle('is-running', r.phase !== 'done' && r.phase !== 'cancelled');
801
- }
802
- if (role === 'bg_task' && r.card) {
803
- rec.el.classList.toggle('is-started', r.card.phase === 'started');
804
- rec.el.classList.toggle('is-completed', r.card.phase === 'completed');
805
- rec.el.classList.toggle('is-failed', r.card.phase === 'failed');
806
- }
807
-
808
- const mark = markFor(role, r);
809
- if (rec.mark !== mark) {
810
- rec.mark = mark;
811
- if (mark) rec.el.setAttribute('data-mark', mark);
812
- else rec.el.removeAttribute('data-mark');
813
- }
814
-
815
- if (rec.simple) {
816
- if (rec.body.textContent !== text) rec.body.textContent = text;
817
- return;
818
- }
819
- paintBody(rec, r, role, text);
820
- }
821
-
822
-
823
- /** True when the text needs block rendering. A plain reply keeps ONE text node
824
- for its whole life, so a streamed patch is a single assignment instead of a
825
- rebuilt subtree on every frame. */
826
- function hasMarkup(text) {
827
- return text.indexOf('```') >= 0 || text.indexOf('#') >= 0
828
- || text.indexOf('`') >= 0 || text.indexOf('**') >= 0 || text.indexOf('](') >= 0;
829
- }
830
-
831
- const RESULT_MAX_LINES = 12;
832
- const DIFF_MAX_ROWS = 16;
833
- const THINK_PREVIEW = 1; // collapsed thinking shows a single live/one-line preview
834
-
835
- function paintBody(rec, r, role, text) {
836
- const body = rec.body;
837
- body.replaceChildren();
838
-
839
- if (role === 'tool') { paintToolRow(body, r, rec); return; }
840
- if (role === 'tool_result') { paintResultRow(body, r); return; }
841
- if (role === 'compaction') { paintCompactionRow(body, r); return; }
842
- if (role === 'bg_task') { paintBgTaskRow(body, r); return; }
843
- if (role === 'thinking') { paintThinkingRow(body, r, text); return; }
844
- appendMarkdown(body, text);
845
- }
846
-
847
- function el(cls, text) {
848
- const n = document.createElement('span');
849
- if (cls) n.className = cls;
850
- if (text != null) n.textContent = text;
851
- return n;
852
- }
853
-
854
- /**
855
- * Which argument identifies a call, mirroring the terminal's `KEY_ARG`: a tool
856
- * line must read `Using Read (src/tui.js)`, so the field is chosen per tool
857
- * rather than being "the first string that happens to be non-empty".
858
- */
859
- const KEY_ARG = {
860
- Bash: ['command'],
861
- Read: ['path', 'file_path'],
862
- Write: ['path', 'file_path'],
863
- Edit: ['path', 'file_path'],
864
- Grep: ['pattern'],
865
- Glob: ['pattern'],
866
- FileLines: ['path', 'file_path'],
867
- FetchURL: ['url'],
868
- WebSearch: ['query'],
869
- Agent: ['description', 'prompt'],
870
- TaskOutput: ['task_id'],
871
- TaskStop: ['task_id'],
872
- };
873
-
874
- const MAX_ARG = 60;
875
-
876
- /** Terminal `keyArgument`: first line only, workspace-relative for paths,
877
- truncated to MAX_ARG with the ellipsis on the side that keeps a path's
878
- basename readable. */
879
- function keyArgument(name, args, workspace) {
880
- if (!args || typeof args !== 'object') return '';
881
- const keys = KEY_ARG[name] || Object.keys(args);
882
- for (const k of keys) {
883
- const v = args[k];
884
- if (typeof v !== 'string' || !v.length) continue;
885
- let text = v.split('\n')[0];
886
- const isPath = k === 'path' || k === 'file_path';
887
- if (isPath && workspace && text.startsWith(workspace)) {
888
- const rel = text.slice(workspace.length).replace(/^[/\\]+/, '');
889
- if (rel) text = rel;
890
- }
891
- if (text.length > MAX_ARG) {
892
- text = isPath ? '\u2026' + text.slice(text.length - (MAX_ARG - 1))
893
- : text.slice(0, MAX_ARG - 1) + '\u2026';
894
- }
895
- if (isPath) text = text.replace(/\\/g, '/');
896
- return text;
897
- }
898
- return '';
899
- }
900
-
901
- /**
902
- * The tool NAME's sweep while a call is running — the terminal's own animation,
903
- * ported rather than approximated.
904
- *
905
- * A 2s loop in two 1s colour pairs: base cyan → pale cyan, back, then base cyan
906
- * → cyan-blue, back. Each character fades across a band ~2-4 characters wide, so
907
- * the crest moves as a gradient instead of a hard edge. The phase is measured
908
- * from the tick the pulse STARTED (`pulseStart`), not the raw spinner tick: the
909
- * spinner has been running since the turn began, so using it directly drops the
910
- * pulse into a mid-cycle colour the instant the animation hands over.
911
- */
912
- const SWEEP = 6;
913
- const SWEEP_HALF = SWEEP + SWEEP;
914
- const SWEEP_CYCLE = SWEEP_HALF * 2;
915
- const CYAN_RGB = [0, 215, 255];
916
- const PALE_CYAN_RGB = [150, 255, 255];
917
- const CYAN_BLUE_RGB = [0, 150, 255];
918
-
919
- function mixRgb(from, to, k) {
920
- const t = Math.max(0, Math.min(1, k));
921
- return 'rgb('
922
- + Math.round(from[0] + (to[0] - from[0]) * t) + ','
923
- + Math.round(from[1] + (to[1] - from[1]) * t) + ','
924
- + Math.round(from[2] + (to[2] - from[2]) * t) + ')';
925
- }
926
-
927
- function paintToolName(rec, name, pending, tick) {
928
- const box = rec.nameEl;
929
- if (!box || !box.isConnected) return;
930
-
931
- if (!pending) {
932
- unregisterSweep(rec);
933
- // Leave the DOM alone when it already shows the plain name. `paintBody` rebuilds
934
- // a row's children on every patch, so this node is normally FRESH (empty) and the
935
- // branch below is what fills it; but when the name is unchanged the existing
936
- // content is already correct, and rewriting it makes the name flicker on rows
937
- // that finished long ago — the flash reported for "every tool name", not just the
938
- // call that just ran.
939
- if (rec.namePending === false && box.textContent === name) return;
940
- box.replaceChildren(document.createTextNode(name));
941
- rec.namePending = false;
942
- rec.nameText = name;
943
- return;
944
- }
945
-
946
- // The tick comes from a LOCAL clock (see sweepFrame), not from `status.spin`.
947
- // The server stopped broadcasting every spin frame (ANIMATION_FIELDS in
948
- // session-hub.js), so a sweep driven by it only moved when some OTHER field
949
- // happened to change — it froze for long stretches and then jumped. Worse,
950
- // pushing per-character gradient values over the wire for every frame is exactly
951
- // the cost the browser should be paying instead.
952
- const start = rec.sweepStart == null ? (rec.sweepStart = tick) : rec.sweepStart;
953
- if (rec.namePending === true && rec.nameTick === tick && rec.nameText === name) return;
954
- rec.namePending = true;
955
- rec.nameTick = tick;
956
- rec.nameText = name;
957
-
958
- const inCycle = (((tick - start) % SWEEP_CYCLE) + SWEEP_CYCLE) % SWEEP_CYCLE;
959
- const inHalf = inCycle % SWEEP_HALF;
960
- const target = inCycle < SWEEP_HALF ? PALE_CYAN_RGB : CYAN_BLUE_RGB;
961
- const n = name.length || 1;
962
- const band = Math.max(2, Math.min(4, n / 3)) / n;
963
-
964
- const frag = document.createDocumentFragment();
965
- for (let i = 0; i < name.length; i++) {
966
- const at = i / n;
967
- const t = inHalf < SWEEP
968
- ? ((inHalf + 1) / SWEEP - at) / band
969
- : 1 - ((inHalf - SWEEP + 1) / SWEEP - at) / band;
970
- const s = document.createElement('span');
971
- s.style.color = mixRgb(CYAN_RGB, target, t);
972
- s.textContent = name[i];
973
- frag.appendChild(s);
974
- }
975
- box.replaceChildren(frag);
976
- }
977
-
978
- /* ---- pending tool-name sweeps, on their own clock -------------------------
979
- Every pending tool row registers here; ONE rAF loop repaints them all at the
980
- terminal's 80ms tick (not 60fps: rebuilding per-character spans faster buys
981
- nothing visible and burns CPU). A row unregisters the moment it stops pending,
982
- so an idle page runs no loop at all. */
983
- const sweeps = new Set();
984
- let sweepRaf = null;
985
- let sweepLastTick = -1;
986
-
987
- function registerSweep(rec) {
988
- sweeps.add(rec);
989
- if (sweepRaf === null) sweepRaf = requestAnimationFrame(sweepFrame);
990
- }
991
-
992
- function unregisterSweep(rec) {
993
- rec.sweepStart = null;
994
- if (!sweeps.delete(rec)) return;
995
- if (!sweeps.size) stopSweeps();
996
- }
997
-
998
- function stopSweeps() {
999
- if (sweepRaf !== null) { cancelAnimationFrame(sweepRaf); sweepRaf = null; }
1000
- sweepLastTick = -1;
1001
- sweeps.clear();
1002
- }
1003
-
1004
- const SWEEP_TICK_MS = 80;
1005
-
1006
- function sweepFrame() {
1007
- sweepRaf = null;
1008
- // Drop anything detached (its row was removed or re-rendered).
1009
- for (const rec of [...sweeps]) if (!rec.nameEl || !rec.nameEl.isConnected) sweeps.delete(rec);
1010
- if (!sweeps.size) { sweepLastTick = -1; return; }
1011
- const now = performance.now();
1012
- const tick = Math.floor(now / SWEEP_TICK_MS);
1013
- if (tick !== sweepLastTick) {
1014
- sweepLastTick = tick;
1015
- for (const rec of sweeps) paintToolName(rec, rec.nameText, true, tick);
1016
- }
1017
- sweepRaf = requestAnimationFrame(sweepFrame);
1018
- }
1019
-
1020
- function paintToolRow(body, r, rec) {
1021
- const name = r.toolName || r.name || 'tool';
1022
- // The verb IS the state: `Using` while running, `Used` once finished. It is
1023
- // the one thing that tells a reader at a glance whether a call is in flight.
1024
- body.appendChild(el('tool-verb', tr(r.pending ? 'tool.using' : 'tool.used')));
1025
- body.append(' ');
1026
-
1027
- // The name gets its own node so the sweep can repaint just its glyphs. The
1028
- // record lives on the NODE, never on the row: the row object is serialized to
1029
- // the server and copied on every patch, so putting DOM references on it would
1030
- // keep the old tree alive after every repaint.
1031
- const nameEl = document.createElement('span');
1032
- nameEl.className = 'tool-name';
1033
- body.appendChild(nameEl);
1034
- // The sweep record lives on the ROW record (`rec`), which survives a repaint; only
1035
- // its `nameEl` is refreshed here. `paintBody` calls `replaceChildren()` before
1036
- // rebuilding, so this node is a NEW element on every patch — keying the state on
1037
- // the node reset the cycle on each frame and left detached records in the set.
1038
- if (!rec._sweep) rec._sweep = { nameEl, namePending: null, nameTick: -1, nameText: '', sweepStart: null };
1039
- rec._sweep.nameEl = nameEl;
1040
- // A pending row joins the local sweep loop; a finished one paints once and leaves
1041
- // it. `sweepStart` is stamped on the first frame, so the cycle begins when the
1042
- // call started rather than at an arbitrary phase.
1043
- if (r.pending) {
1044
- registerSweep(rec._sweep);
1045
- paintToolName(rec._sweep, name, true, Math.floor(performance.now() / SWEEP_TICK_MS));
1046
- } else {
1047
- paintToolName(rec._sweep, name, false, 0);
1048
- }
1049
-
1050
-
1051
- const arg = keyArgument(name, r.toolArgs, status.cwd);
1052
- if (arg) body.appendChild(el('tool-arg', ' (' + arg + ')'));
1053
-
1054
- if (name === 'Write' && typeof r.streamContent === 'string' && r.streamContent.length) {
1055
- const bytes = r.streamContent.length;
1056
- const size = bytes >= 1048576 ? (bytes / 1048576).toFixed(1) + 'MB'
1057
- : bytes >= 1024 ? (bytes / 1024).toFixed(1) + 'KB'
1058
- : bytes + 'B';
1059
- body.appendChild(el('tool-size', ' ' + size));
1060
- }
1061
-
1062
- // The counts ride the tool line; the diff BODY belongs to the result row. The
1063
- // terminal shows them in exactly that split, never the diff twice.
1064
- if (name === 'Edit' && !r.pending) {
1065
- const d = Array.isArray(r.diff) && r.diff.length ? r.diff : r._diffCounts;
1066
- if (Array.isArray(d) && d.length) {
1067
- const adds = d.filter((x) => x.type === 'add').length;
1068
- const dels = d.filter((x) => x.type === 'del').length;
1069
- if (adds) body.appendChild(el('tool-add', ' +' + adds));
1070
- if (dels) body.appendChild(el('tool-del', ' \u2212' + dels));
1071
- }
1072
- }
1073
-
1074
- // Live output of a still-running command, where the terminal puts it: under the
1075
- // `Using …` row, tail-capped, so a chatty command cannot flood the row.
1076
- if (r.pending && typeof r.liveOutput === 'string' && r.liveOutput.length) {
1077
- const raw = r.liveOutput.replace(/\r\n/g, '\n').split('\n');
1078
- const cap = expandedRows.has(r.id) ? Infinity : 8;
1079
- body.appendChild(el('tool-live', '\n' + raw.slice(-cap).map((l) => ' ' + l).join('\n')));
1080
- }
1081
- }
1082
-
1083
-
1084
-
1085
- /**
1086
- * Tool output. The terminal's shape is the whole point of the row:
1087
- *
1088
- * ● Used Edit (a.js) +1 -1 <- tool line, counts only
1089
- * ↳ 179 - old line <- ONE `↳` on the FIRST body row
1090
- * 179 + new line
1091
- * Edited a.js: replaced 1 occurrence(s). <- receipt LAST
1092
- *
1093
- * An Edit's DIFF is the body and carries the marker, with the receipt moved to
1094
- * the bottom; every other tool's output IS the body and carries the marker on
1095
- * its first line.
1096
- */
1097
- function paintResultRow(body, r) {
1098
- const failed = r.failed === true;
1099
- const text = String(r.text == null ? '' : r.text);
1100
- const diff = Array.isArray(r.diff) ? r.diff.filter((d) => d.type !== 'ctx') : [];
1101
-
1102
- if (diff.length) {
1103
- // Same shape as the folded result below: show the first diff rows with the `↳`
1104
- // on the first, and let the fold hint trail the block. The old form drew `↳` on
1105
- // a line by itself with the hint on the NEXT line and no diff content at all.
1106
- const rows = expandedRows.has(r.id) ? diff : diff.slice(0, DIFF_MAX_ROWS);
1107
- const width = Math.max(1, ...rows.map((d) => String(d.no || 0).length));
1108
- rows.forEach((d, i) => {
1109
- const no = String(d.no || 0).padStart(width);
1110
- const mark = d.type === 'add' ? '+' : '-';
1111
- const prefix = i === 0 ? tr('mark.result') + ' ' : ' ';
1112
- body.appendChild(el(d.type === 'add' ? 'diff-add' : 'diff-del',
1113
- prefix + no + ' ' + mark + ' ' + String(d.text) + '\n'));
1114
- });
1115
- const hiddenDiff = diff.length - rows.length;
1116
- if (hiddenDiff > 0) body.appendChild(moreButton(r.id, hiddenDiff));
1117
- const receipt = text.trim()
1118
- .split('\n').filter((ln) => !/^\[exit code:/.test(ln.trim())).join('\n')
1119
- .trim();
1120
- if (receipt) body.appendChild(el(failed ? 'diff-del' : 'res-more', receipt));
1121
- if (expandedRows.has(r.id) && diff.length > DIFF_MAX_ROWS) body.appendChild(collapseButton(r.id));
1122
- return;
1123
- }
1124
- // A finished result is FOLDED (like the terminal's ctrl+o): a whole-file Read is
1125
- // thousands of DOM nodes in ONE row, which stutters scrolling. The preview keeps
1126
- // the FIRST lines visible with the `↳` marker on the first one, and the fold hint
1127
- // rides the END of the block — the terminal's shape:
1128
- // ↳ 1 first line of the output
1129
- // 2 second line
1130
- // … (N more lines, expand)
1131
- // It used to render `↳` alone on one line and the hint on the NEXT, so a folded
1132
- // row showed a dangling marker and no output at all, and the hint read as a
1133
- // separate paragraph rather than as "there is more of THIS".
1134
- // `[exit code: N]` is bookkeeping for the model, never shown to the user.
1135
- const lines = text.replace(/\r\n/g, '\n').split('\n')
1136
- .filter((ln) => !/^\[exit code:/.test(ln.trim()));
1137
- while (lines.length && lines[0].trim() === '') lines.shift();
1138
- while (lines.length && lines[lines.length - 1].trim() === '') lines.pop();
1139
- if (!lines.length) return;
1140
-
1141
- const folded = !expandedRows.has(r.id);
1142
- const shown = folded ? lines.slice(0, RESULT_MAX_LINES) : lines;
1143
- shown.forEach((ln, i) => {
1144
- const isErr = /^\[error:/.test(ln.trim());
1145
- const prefix = i === 0 ? tr('mark.result') + ' ' : ' ';
1146
- body.appendChild(el(isErr || failed ? 'diff-del' : '', prefix + ln + '\n'));
1147
- });
1148
- const hidden = lines.length - shown.length;
1149
- if (hidden > 0) body.appendChild(moreButton(r.id, hidden));
1150
- if (expandedRows.has(r.id) && lines.length > RESULT_MAX_LINES) body.appendChild(collapseButton(r.id));
1151
- }
1152
-
1153
-
1154
- function moreButton(id, n) {
1155
- const b = document.createElement('button');
1156
- b.type = 'button';
1157
- b.className = 'msg-more';
1158
- b.textContent = tr('tool.moreLines', { n });
1159
- b.addEventListener('click', () => { expandedRows.add(id); repaintRow(id); });
1160
- return b;
1161
- }
1162
-
1163
- /** A "collapse" control shown once a foldable row is expanded, so a long
1164
- thinking / result block can be folded back without a reload. */
1165
- function collapseButton(id) {
1166
- const b = document.createElement('button');
1167
- b.type = 'button';
1168
- b.className = 'msg-more';
1169
- b.textContent = tr('tool.collapse');
1170
- b.addEventListener('click', () => { expandedRows.delete(id); repaintRow(id); });
1171
- return b;
1172
- }
1173
-
1174
- /** Compaction, matching the terminal: `● Compacting context…` / `● Compaction
1175
- complete (X → Y tokens)` / `● Compaction cancelled`. The marker carries the
1176
- phase colour, so it is part of the line rather than a separate column. */
1177
- function paintCompactionRow(body, r) {
1178
- const done = r.phase === 'done';
1179
- const cancelled = r.phase === 'cancelled';
1180
- const label = done ? tr('tool.compacted')
1181
- : cancelled ? tr('tool.compactCancelled')
1182
- : tr('tool.compacting');
1183
- let line = tr('mark.tool') + ' ' + label;
1184
- if (done && r.tokensBefore != null && r.tokensAfter != null) {
1185
- line += ' (' + fmtNum(r.tokensBefore) + ' \u2192 ' + fmtNum(r.tokensAfter) + ' tokens)';
1186
- }
1187
- body.appendChild(document.createTextNode(line));
1188
- if (r.instruction) body.appendChild(document.createTextNode('\n ' + String(r.instruction)));
1189
- }
1190
-
1191
- /** Background-task lifecycle card: `● agent task completed in background`, the
1192
- conclusion indented underneath and capped like a tool result so one chatty
1193
- subagent cannot flood the transcript. */
1194
- function paintBgTaskRow(body, r) {
1195
- const card = r.card || { phase: 'completed', headline: '' };
1196
- body.appendChild(document.createTextNode(
1197
- tr(card.phase === 'failed' ? 'mark.bgTaskFailed' : 'mark.bgTask') + ' ' + (card.headline || '')));
1198
- if (card.detail) body.appendChild(el('res-more', ' (' + card.detail + ')'));
1199
- const t = String(r.text || '').trim();
1200
- if (!t) return;
1201
- const lines = t.split('\n');
1202
- const cap = expandedRows.has(r.id) ? 200 : 6;
1203
- body.appendChild(document.createTextNode('\n ' + lines.slice(0, cap).join('\n ')));
1204
- if (lines.length > cap) body.appendChild(el('res-more', '\n \u2026 ' + (lines.length - cap)));
1205
- }
1206
-
1207
-
1208
- /**
1209
- * Reasoning block, matching the terminal:
1210
- * live -> "<spinner> thinking…" then the LAST 2 content lines, indented
1211
- * finalized -> `●` inline on the first line, up to 2 preview lines, then a
1212
- * "… (N more lines)" hint
1213
- * All of it dim, body italic. The marker is part of the text (prefix `● `,
1214
- * continuations indented two), exactly as `messageLines` builds it.
1215
- */
1216
- function paintThinkingRow(body, r, text) {
1217
- const lines = text ? text.replace(/\r\n/g, '\n').split('\n') : [];
1218
- // An EMPTY reasoning block renders NOTHING, matching `messageLines` in the
1219
- // terminal. A model may emit a `think` event with no text, and a block finalised by
1220
- // a tool call can be left empty; drawing a bare `●` (or a lone spinner) for those
1221
- // reads as a rendering bug. The row stays in the model, so a block that later
1222
- // receives text appears in full — only the paint is skipped.
1223
- if (!lines.some((l) => l.trim() !== '')) return;
1224
- const cap = expandedRows.has(r.id) ? Infinity : THINK_PREVIEW;
1225
-
1226
- if (r.pending) {
1227
- // The live form shows a spinner label instead of the `●`, and previews the
1228
- // TAIL of the reasoning rather than its head.
1229
- const label = document.createElement('div');
1230
- label.className = 'think-live';
1231
- label.textContent = tr('chat.thinking');
1232
- body.appendChild(label);
1233
- // Live: show the newest lines (up to THINK_PREVIEW), replaced in place as the
1234
- // model's reasoning grows — matching the terminal's `contentLines.slice(-PREVIEW)`.
1235
- const tail = lines.slice(-THINK_PREVIEW);
1236
- for (const ln of tail) body.appendChild(document.createTextNode(' ' + ln + '\n'));
1237
- return;
1238
- }
1239
-
1240
- const shown = lines.slice(0, cap);
1241
- shown.forEach((ln, i) => {
1242
- body.appendChild(document.createTextNode(
1243
- (i === 0 ? tr('mark.thinking') + ' ' : ' ') + ln + '\n'));
1244
- });
1245
- const hidden = lines.length - shown.length;
1246
- if (hidden > 0) body.appendChild(moreButton(r.id, hidden));
1247
- else if (expandedRows.has(r.id) && lines.length > 1) body.appendChild(collapseButton(r.id));
1248
- }
1249
-
1250
-
1251
-
1252
- const FENCE_RE = /^[ \t]*```+\s*(\S*)/;
1253
- const INLINE_RE = /(`[^`]+`|\*\*[^*]+\*\*|\*[^*\s][^*]*?\*|~~[^~]+~~|\[[^\]]+\]\([^)\s]+\)|(^|\s)https?:\/\/[^\s]+)/g;
1254
-
1255
- /** Markdown as the terminal renders it: a fenced block becomes its own box with
1256
- the language on a rule, `#` lines are emphasised, and inline `code` / **bold**
1257
- / [links](url) keep their form. Everything else stays verbatim — a tool
1258
- result or a shell line must never be reinterpreted as prose. */
1259
- function appendMarkdown(wrap, text) {
1260
- const lines = String(text == null ? '' : text).split('\n');
1261
- let plain = [];
1262
- let code = null;
1263
- let lang = '';
1264
-
1265
- const flushPlain = () => {
1266
- if (!plain.length) return;
1267
- const chunk = plain;
1268
- plain = [];
1269
- // Split the buffered lines into block groups: lists, tables, quotes, hr,
1270
- // headings, and paragraphs. Each is appended as its own container.
1271
- let i = 0;
1272
- const isTableSep = (l) => /^\s*\|?\s*:?-{2,}.*\|/.test(l) || /^\s*\|[-: ]+\|/.test(l);
1273
- while (i < chunk.length) {
1274
- const raw = chunk[i];
1275
- const t = raw.replace(/\s+$/, '');
1276
- // table: header line, then a separator line
1277
- if (t.includes('|') && i + 1 < chunk.length && isTableSep(chunk[i + 1])) {
1278
- const header = t.split('|').map((c) => c.trim()).filter((c, j, a) => !(c === '' && (j === 0 || j === a.length - 1)));
1279
- const body = [];
1280
- i += 2;
1281
- while (i < chunk.length && chunk[i].trim().includes('|') && !isTableSep(chunk[i])) {
1282
- const cells = chunk[i].split('|').map((c) => c.trim()).filter((c, j, a) => !(c === '' && (j === 0 || j === a.length - 1)));
1283
- body.push(cells);
1284
- i++;
1285
- }
1286
- wrap.appendChild(buildTable(header, body));
1287
- continue;
1288
- }
1289
- // hr
1290
- if (/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(t)) { wrap.appendChild(el('md-hr', '')); i++; continue; }
1291
- // quote: one or more consecutive `>` lines
1292
- if (/^\s*>\s?/.test(t)) {
1293
- const q = [];
1294
- while (i < chunk.length && /^\s*>\s?/.test(chunk[i])) {
1295
- q.push(chunk[i].replace(/^\s*>\s?/, ''));
1296
- i++;
1297
- }
1298
- const box = document.createElement('div');
1299
- box.className = 'md-quote';
1300
- q.forEach((ql, j) => { if (j) box.appendChild(document.createTextNode('\n')); box.appendChild(inlineParts(ql)); });
1301
- wrap.appendChild(box);
1302
- continue;
1303
- }
1304
- // task checkbox
1305
- const task = /^(\s*)([-*+]\s+)?\[( |x|X)\]\s+(.*)$/.exec(t);
1306
- if (task) {
1307
- const row = document.createElement('div');
1308
- row.className = 'md-task';
1309
- const box = el('md-check', task[3] !== ' ' ? '\u2713' : '\u25cb');
1310
- row.appendChild(box);
1311
- row.appendChild(inlineParts(task[4]));
1312
- wrap.appendChild(row);
1313
- i++;
1314
- continue;
1315
- }
1316
- // list item, ordered or unordered
1317
- const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(t);
1318
- if (li) {
1319
- const list = document.createElement('div');
1320
- list.className = /^\d/.test(li[2]) ? 'md-list-ol' : 'md-list-ul';
1321
- while (i < chunk.length) {
1322
- const m = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(chunk[i].replace(/\s+$/, ''));
1323
- if (!m || (/^\d/.test(m[2]))) {
1324
- if (!m) break;
1325
- }
1326
- const isO = /^\d/.test(m[2]);
1327
- if (isO !== /^\d/.test(li[2])) break;
1328
- const item = document.createElement('div');
1329
- item.className = 'md-li';
1330
- const bullet = isO ? m[2] : '\u2022';
1331
- item.appendChild(el('md-bullet', bullet));
1332
- item.appendChild(inlineParts(m[3]));
1333
- list.appendChild(item);
1334
- i++;
1335
- }
1336
- wrap.appendChild(list);
1337
- continue;
1338
- }
1339
- // heading
1340
- const head = /^\s*#{1,6}\s+(.*)$/.exec(t);
1341
- if (head) { wrap.appendChild(el('md-h', head[1])); i++; continue; }
1342
- // paragraph / plain
1343
- const paraNode = document.createElement('div');
1344
- paraNode.className = 'md-p';
1345
- paraNode.appendChild(inlineParts(t));
1346
- wrap.appendChild(paraNode);
1347
- i++;
1348
- }
1349
- };
1350
-
1351
- const flushCode = () => {
1352
- const box = document.createElement('div');
1353
- box.className = 'code-block';
1354
- if (lang) {
1355
- const bar = document.createElement('div');
1356
- bar.className = 'code-bar';
1357
- bar.textContent = lang;
1358
- box.appendChild(bar);
1359
- }
1360
- const pre = document.createElement('pre');
1361
- pre.className = 'code-body';
1362
- pre.textContent = code.join('\n');
1363
- box.appendChild(pre);
1364
- wrap.appendChild(box);
1365
- code = null;
1366
- lang = '';
1367
- };
1368
-
1369
- for (const line of lines) {
1370
- const fence = FENCE_RE.exec(line);
1371
- if (fence) {
1372
- if (code === null) { flushPlain(); code = []; lang = fence[1] || ''; }
1373
- else flushCode();
1374
- continue;
1375
- }
1376
- if (code === null) plain.push(line);
1377
- else code.push(line);
1378
- }
1379
- flushPlain();
1380
- if (code !== null && code.length) flushCode();
1381
- }
1382
-
1383
- /** Render a Markdown table as a grid. Header is the first row (bold). */
1384
- function buildTable(header, body) {
1385
- const table = document.createElement('div');
1386
- table.className = 'md-table';
1387
- const h = document.createElement('div');
1388
- h.className = 'md-tr';
1389
- for (const c of header) { const cell = el('md-th', c); h.appendChild(cell); }
1390
- table.appendChild(h);
1391
- for (const row of body) {
1392
- const r = document.createElement('div');
1393
- r.className = 'md-tr';
1394
- for (const c of row) r.appendChild(el('md-td', c));
1395
- table.appendChild(r);
1396
- }
1397
- return table;
1398
- }
1399
-
1400
- function inlineParts(line) {
1401
- if (!line) return document.createTextNode('');
1402
- const frag = document.createDocumentFragment();
1403
- let at = 0;
1404
- for (const m of line.matchAll(INLINE_RE)) {
1405
- if (m.index > at) frag.appendChild(document.createTextNode(line.slice(at, m.index)));
1406
- const tok = m[0];
1407
- if (tok[0] === '`') frag.appendChild(el('md-code', tok.slice(1, -1)));
1408
- else if (tok.startsWith('**')) frag.appendChild(el('md-b', tok.slice(2, -2)));
1409
- else if (tok.startsWith('~~')) frag.appendChild(el('md-s', tok.slice(2, -2)));
1410
- else if (tok.startsWith('*')) frag.appendChild(el('md-i', tok.slice(1, -1)));
1411
- else if (tok.startsWith('[')) {
1412
- const label = tok.slice(1, tok.indexOf(']'));
1413
- const href = tok.slice(tok.indexOf('(') + 1, -1);
1414
- const a = document.createElement('a');
1415
- a.className = 'md-link';
1416
- a.href = href;
1417
- a.target = '_blank';
1418
- a.rel = 'noreferrer noopener';
1419
- a.textContent = label;
1420
- frag.appendChild(a);
1421
- } else {
1422
- // Bare URL, possibly left-trimmed to the leading whitespace captured.
1423
- const url = tok.trim();
1424
- const a = document.createElement('a');
1425
- a.className = 'md-link';
1426
- a.href = url;
1427
- a.target = '_blank';
1428
- a.rel = 'noreferrer noopener';
1429
- a.textContent = url;
1430
- if (tok[0].match(/\s/)) frag.appendChild(document.createTextNode(' '));
1431
- frag.appendChild(a);
1432
- }
1433
- at = m.index + tok.length;
1434
- }
1435
- if (at < line.length) frag.appendChild(document.createTextNode(line.slice(at)));
1436
- return frag;
1437
- }
1438
-
1439
- function summarizeArgs(args) {
1440
- if (!args || typeof args !== 'object') return '';
1441
- const keys = ['command', 'cmd', 'path', 'file_path', 'pattern', 'query', 'url', 'description', 'task_id'];
1442
- for (const k of keys) {
1443
- const v = args[k];
1444
- if (typeof v === 'string' && v) return v.split('\n')[0].slice(0, 160);
1445
- }
1446
- return '';
1447
- }
1448
-
1449
- function fmtNum(n) {
1450
- n = Number(n) || 0;
1451
- const trim = (v) => {
1452
- const s = v.toFixed(1);
1453
- return s.endsWith('.0') ? s.slice(0, -2) : s;
1454
- };
1455
- if (n >= 1048576) return trim(n / 1048576) + 'M';
1456
- if (n >= 1024) return (n >= 102400 ? Math.round(n / 1024) : trim(n / 1024)) + 'k';
1457
- return String(n);
1458
- }
1459
-
1460
- // ------------------------------------------------------- status and panels
1461
-
1462
- // A hidden tab pane is skipped by renderStatus; VIEW_IDS tracks which one is
1463
- // visible so switching a tab back on rebuilds it once from the latest status.
1464
- const dirtyViews = new Set();
1465
- function isViewHidden(name) {
1466
- const sec = document.getElementById("view-" + name);
1467
- if (!sec) return false;
1468
- if (!sec.hidden) return false;
1469
- dirtyViews.add(name);
1470
- return true;
1471
- }
1472
-
1473
- function renderStatus() {
1474
- const s = status || {};
1475
-
1476
- $('sess-title').textContent = s.title || tr('chat.untitled');
1477
- const sessId = String(s.session || '');
1478
- const idEl = $('sess-id');
1479
- idEl.textContent = sessId;
1480
- const oldCopy = $('sess-id-copy');
1481
- if (oldCopy) oldCopy.remove();
1482
- if (sessId) {
1483
- const cb = copyButton(sessId, tr('copy.copy'));
1484
- cb.id = 'sess-id-copy';
1485
- idEl.after(cb);
1486
- }
1487
-
1488
- // Send and Interrupt share one edge of the composer: while a turn runs, the
1489
- // only useful action there is to stop it, so Send yields to Stop instead of
1490
- // sitting beside a button that would just queue another message.
1491
- setPanelVisible('btn-interrupt', !!s.busy);
1492
- setPanelVisible('send', !s.busy);
1493
-
1494
-
1495
- setPanelVisible('todo-panel', (s.todos || []).length > 0);
1496
- setPanelVisible('queue-panel', (s.queued || []).length > 0);
1497
- setPanelVisible('working', !!s.busy);
1498
-
1499
- renderTodoPanel(s.todos || []);
1500
- renderQueuePanel(s.queued || [], !!s.busy);
1501
- // Hidden tabs keep stale DOM — their pane is display:none, nobody sees it,
1502
- // and rebuilding hundreds of cards per status broadcast was pure waste.
1503
- // setupViews() marks a pane "dirty" when its view becomes visible.
1504
- if (!isViewHidden("tasks")) renderTasks(s.tasks || []);
1505
- if (!isViewHidden("files")) renderFiles(s.files || []);
1506
- if (!isViewHidden("tools")) renderTools(s.tools || []);
1507
- if (!isViewHidden("commands")) renderCommands(s.commands || []);
1508
- renderTabCounts(s);
1509
- applyModal(s);
1510
- renderStatusLine(s);
1511
- }
1512
-
1513
- /** Flip only the composer's Send/Stop state when `busy` changed — called from
1514
- applyStatus on an animation-only broadcast, so a run that never changes a
1515
- stable field still swaps the button without touching the panes. */
1516
- function renderBusyButton() {
1517
- const busy = !!(status && status.busy);
1518
- setPanelVisible('btn-interrupt', busy);
1519
- setPanelVisible('send', !busy);
1520
- setPanelVisible('working', busy);
1521
- }
1522
-
1523
- function setPanelVisible(id, on) {
1524
- const node = $(id);
1525
- if (node) node.hidden = !on;
1526
- }
1527
-
1528
- /**
1529
- * One row, grouped the way the terminal's footer groups it: which mode I am in,
1530
- * which model, where I am, what git says, and the usage readout pinned right.
1531
- * Every part is a fact about the running session — nothing here is decoration.
1532
- */
1533
- function renderStatusLine(s) {
1534
- const line = $('statusline');
1535
- line.replaceChildren();
1536
- const o = s.options || {};
1537
-
1538
- line.appendChild(popoverButton('sl-mode', modeLabel(s.mode), 'side.mode', () => modeItems(o)));
1539
- // One badge, one accent — Plan/Focus/Swarm are mutually exclusive, so exactly one
1540
- // of these is shown. The class carries the colour (see .sl-badge-* in app.css); the
1541
- // three must NOT share it, or the statusline cannot say which mode is on.
1542
- // PTC FIRST: it narrows the toolset harder than any of the others — only the sandbox tool is offered — so a
1543
- // session in that mode must say so from the status line alone.
1544
- const badge = s.ptcMode ? { text: 'PTC', cls: 'sl-badge-ptc' }
1545
- : s.plan ? { text: 'Plan', cls: 'sl-badge-plan' }
1546
- : s.focus ? { text: 'Focus', cls: 'sl-badge-focus' }
1547
- : s.swarm ? { text: 'Swarm', cls: 'sl-badge-swarm' }
1548
- : null;
1549
- if (badge) line.appendChild(el('sl-badge ' + badge.cls, badge.text));
1550
-
1551
- if (s.model) {
1552
- const label = s.model + (s.reasoning
1553
- ? (s.effort && s.effort !== 'on' ? ' thinking: ' + s.effort : ' thinking')
1554
- : '');
1555
- line.appendChild(popoverButton('sl-model', label, 'side.model', () => modelItems(o)));
1556
- }
1557
-
1558
- const running = (s.tasks || []).filter((t) => t.status === 'running');
1559
- const bash = running.filter((t) => t.kind !== 'agent').length;
1560
- const agents = running.filter((t) => t.kind === 'agent').length;
1561
- if (bash) line.appendChild(el('sl-tasks-bash', tr('status.tasksBash', { n: bash })));
1562
- if (agents) line.appendChild(el('sl-tasks-agent', tr('status.tasksAgent', { n: agents })));
1563
-
1564
- if (s.cwd) line.appendChild(el('sl-cwd', s.cwd));
1565
-
1566
- const gi = s.git;
1567
- if (gi && gi.branch) {
1568
- line.appendChild(el('sl-branch', gi.branch));
1569
- if (gi.insertions) line.appendChild(el('sl-add', '+' + gi.insertions));
1570
- if (gi.deletions) line.appendChild(el('sl-del', '\u2212' + gi.deletions));
1571
- }
1572
-
1573
- line.appendChild(el('sl-spacer', ''));
1574
-
1575
- // The usage readout is the terminal's own string (`3 turns | 7 steps | 42
1576
- // tok/s`), and the terminal does not translate it. Neither does this: one
1577
- // person reading both screens must not see two different sentences.
1578
- line.appendChild(el('sl-usage', tr('status.usage', {
1579
- turns: Number(s.rounds || 0),
1580
- steps: Number(s.steps || 0),
1581
- rate: Math.round(Number(s.tokRate || 0)),
1582
- })));
1583
- line.appendChild(el('sl-ctx', tr('status.context', {
1584
- pct: Number(s.ctxPercent || 0),
1585
- used: fmtNum(s.ctxTokens || 0),
1586
- max: fmtNum(s.ctxMax || 1),
1587
- })));
1588
- }
1589
-
1590
-
1591
- function popoverButton(cls, label, titleKey, buildItems) {
1592
- const b = document.createElement('button');
1593
- b.type = 'button';
1594
- b.className = cls;
1595
- b.textContent = label;
1596
- b.title = tr('popover.click');
1597
- b.addEventListener('click', (ev) => {
1598
- ev.preventDefault();
1599
- openPopover(b, tr(titleKey), buildItems(), cls);
1600
- });
1601
- return b;
1602
- }
1603
-
1604
- function modelItems(o) {
1605
- const items = [];
1606
- for (const m of (o.model && o.model.items) || []) {
1607
- items.push({
1608
- label: m.label || m.value,
1609
- sub: m.sub || '',
1610
- on: m.value === (o.model && o.model.value),
1611
- cmd: '/model',
1612
- arg: m.value,
1613
- // Each model's own thinking levels, sent by the server. Null when the
1614
- // model has no Thinking control. The effort popover renders these on the
1615
- // right of the "Thinking Effort" row when the pointer sits on it.
1616
- efforts: (m.efforts && m.efforts.map((e) => ({
1617
- label: e.label || e.value,
1618
- on: e.value === (o.effort && o.effort.value),
1619
- cmd: '/effort',
1620
- arg: e.value,
1621
- }))) || null,
1622
- });
1623
- }
1624
- return items;
1625
- }
1626
-
1627
- function modeItems(o) {
1628
- return ((o.mode && o.mode.items) || []).map((m) => ({
1629
- label: m.label || m.value,
1630
- sub: m.sub || '',
1631
- on: m.value === (o.mode && o.mode.value),
1632
- cmd: '/permission',
1633
- arg: m.value,
1634
- }));
1635
- }
1636
-
1637
- function modeLabel(mode) {
1638
- const m = String(mode || '').toLowerCase();
1639
- if (m === 'auto') return 'Auto';
1640
- if (m === 'yolo') return 'Yolo';
1641
- if (m === 'ask') return 'Ask';
1642
- return mode ? String(mode) : '\u2014';
1643
- }
1644
-
1645
- let popoverOpen = null;
1646
-
1647
- function openPopover(anchor, title, items, kind) {
1648
- const box = $('popover');
1649
- const list = $('popover-list');
1650
- if (!box || !list) return;
1651
- $('popover-title').textContent = title;
1652
- list.replaceChildren();
1653
-
1654
- if (!items.length) {
1655
- list.appendChild(el('popover-item', tr('side.none')));
1656
- box.hidden = false; positionPopover(anchor, box);
1657
- return;
1658
- }
1659
-
1660
- // A model popover is two stacked sections, exactly as the user asked:
1661
- // Model A
1662
- // Model B <- pick a model (its own levels follow)
1663
- // Model C
1664
- // ──────────────
1665
- // Thinking Effort > on <- hover the row to reveal its level list
1666
- const isModelPopover = kind === 'sl-model';
1667
- box.dataset.modelPopover = isModelPopover ? 'yes' : 'no';
1668
- if (isModelPopover) {
1669
- renderModelPopover(list, items);
1670
- } else {
1671
- for (const it of items) list.appendChild(buildPopoverItem(it));
1672
- }
1673
-
1674
- box.hidden = false;
1675
- positionPopover(anchor, box);
1676
- popoverOpen = kind;
1677
-
1678
- // The listener is registered on the NEXT frame's task, not in a microtask: the
1679
- // click that opened the popover is still propagating up to `document`, so a
1680
- // listener added synchronously here would receive that same click, see a target
1681
- // outside the popover, and close it again — the menu appeared and vanished in
1682
- // one gesture, which is why the buttons looked dead.
1683
- setTimeout(() => {
1684
- document.addEventListener('mousedown', onDocDown);
1685
- document.addEventListener('keydown', onDocKey);
1686
- }, 0);
1687
- }
1688
-
1689
- /**
1690
- * Position the popover ABOVE the anchor — the status line sits at the bottom of
1691
- * the screen, so a menu that appears below the button runs into the floor.
1692
- * `gap` is kept small (a few px) so the menu reads as attached to what it opens.
1693
- */
1694
- function positionPopover(anchor, box) {
1695
- const r = anchor.getBoundingClientRect();
1696
- box.style.left = Math.max(8, Math.min(r.left, window.innerWidth - box.offsetWidth - 8)) + 'px';
1697
- box.style.top = Math.max(8, r.top - box.offsetHeight - 8) + 'px';
1698
- }
1699
-
1700
- /** Position the floating level list just to the RIGHT of the effort row, flush
1701
- with its top. */
1702
- function positionFlyout(flyout, anchor) {
1703
- const r = anchor.getBoundingClientRect();
1704
- flyout.style.left = Math.max(4, r.right + 4) + 'px';
1705
- flyout.style.top = Math.max(4, r.top - 2) + 'px';
1706
- }
1707
-
1708
- function buildPopoverItem(it) {
1709
- const b = document.createElement('button');
1710
- b.type = 'button';
1711
- b.className = 'popover-item' + (it.on ? ' is-on' : '');
1712
- b.appendChild(el('', it.label));
1713
- if (it.sub) b.appendChild(el('sub', it.sub));
1714
- b.addEventListener('click', () => {
1715
- closePopover();
1716
- void act('dispatch', [it.cmd, it.arg]);
1717
- });
1718
- return b;
1719
- }
1720
-
1721
- /** Model + effort popover, three stacked blocks:
1722
- 1. the model list (its own scroll)
1723
- 2. a hairline divider
1724
- 3. a "Thinking Effort" row showing the current level
1725
- Hovering the effort row floats the level list out to its RIGHT, as a separate
1726
- panel — it does not push the main layout. Hovering a model on top shows that
1727
- model's levels instead. */
1728
- function renderModelPopover(list, items) {
1729
- const currentEff = items.find((m) => m.on) || items[0];
1730
- const currentEfforts = (currentEff && currentEff.efforts) || null;
1731
-
1732
- // 1) model list.
1733
- const modelBox = document.createElement('div');
1734
- modelBox.className = 'popover-section';
1735
- for (const m of items) {
1736
- const it = document.createElement('button');
1737
- it.type = 'button';
1738
- it.className = 'popover-item' + (m.on ? ' is-on' : '');
1739
- it.appendChild(el('', m.label));
1740
- if (m.sub) it.appendChild(el('sub', m.sub));
1741
- it.addEventListener('click', () => {
1742
- closePopover();
1743
- void act('dispatch', [m.cmd, m.arg]);
1744
- });
1745
- it._efforts = m.efforts;
1746
- it._isCurrent = !!m.on;
1747
- modelBox.appendChild(it);
1748
- }
1749
- list.appendChild(modelBox);
1750
-
1751
- // 2) divider.
1752
- list.appendChild(el('popover-rule', ''));
1753
-
1754
- // 3) effort row.
1755
- const effRow = document.createElement('div');
1756
- effRow.className = 'popover-effort';
1757
- effRow.appendChild(el('', tr('popover.effortLabel')));
1758
- const effValue = document.createElement('span');
1759
- effValue.className = 'popover-effort-val' + (currentEfforts ? ' has-levels' : '');
1760
- const curLevel = currentEfforts && currentEfforts.filter((e) => e.on).map((e) => e.label)[0];
1761
- effValue.textContent = curLevel || (currentEfforts ? tr('popover.off') : tr('popover.unknown'));
1762
- effRow.appendChild(effValue);
1763
- list.appendChild(effRow);
1764
-
1765
- if (!currentEfforts) return;
1766
-
1767
- // The floating level list, positioned to the RIGHT of the effort row. It is a
1768
- // sibling of the main popover so it can break out beside it rather than
1769
- // reflowing the stack.
1770
- const effHost = $('popover');
1771
- const flyout = document.createElement('div');
1772
- flyout.className = 'popover-flyout';
1773
- flyout.hidden = true;
1774
- document.body.appendChild(flyout);
1775
-
1776
- const setLevels = (efforts, isCurrent) => {
1777
- flyout.replaceChildren();
1778
- if (!efforts || !efforts.length) {
1779
- flyout.appendChild(el('popover-item', tr('popover.unknown')));
1780
- return;
1781
- }
1782
- for (const e of efforts) flyout.appendChild(buildPopoverItem({ ...e, on: e.on && isCurrent }));
1783
- positionFlyout(flyout, effRow);
1784
- flyout.hidden = false;
1785
- };
1786
-
1787
- const hideFlyout = () => { flyout.hidden = true; };
1788
-
1789
- const clearHover = () => {
1790
- for (const o of list.querySelectorAll('.popover-item.is-hover')) o.classList.remove('is-hover');
1791
- };
1792
-
1793
- // hovering a model row hides any open effort flyout — the flyout belongs to the
1794
- // Thinking Effort row, so moving to the model list dismisses it.
1795
- for (const it of modelBox.children) {
1796
- it.addEventListener('mouseenter', () => {
1797
- clearHover();
1798
- it.classList.add('is-hover');
1799
- hideFlyout();
1800
- });
1801
- it.addEventListener('mouseleave', () => { it.classList.remove('is-hover'); });
1802
- }
1803
-
1804
- // hovering the effort row floats the CURRENT model's levels.
1805
- effRow.addEventListener('mouseenter', () => {
1806
- clearHover();
1807
- setLevels(currentEfforts, true);
1808
- });
1809
- effRow.addEventListener('mouseleave', () => { /* keep flyout until mouse leaves it */ });
1810
-
1811
- // Keep the flyout visible only while the pointer is over it or the popover.
1812
- // (flyoutWatcher, registered once below, does that.)
1813
- }
1814
-
1815
- /** Last pointer position, used by flyoutWatcher. */
1816
- let flyoutX = -1, flyoutY = -1;
1817
-
1818
- /** Hide the effort flyout whenever the pointer leaves both the popover and the
1819
- flyout itself. Runs for every mousemove; the check is cheap. */
1820
- function flyoutWatcher(ev) {
1821
- flyoutX = ev.clientX;
1822
- flyoutY = ev.clientY;
1823
- const f = document.querySelector('.popover-flyout');
1824
- if (!f || f.hidden) return;
1825
- const box = document.getElementById('popover');
1826
- const inBox = box && !box.hidden && insideRect(box, flyoutX, flyoutY);
1827
- const inFly = insideRect(f, flyoutX, flyoutY);
1828
- if (!inBox && !inFly) f.hidden = true;
1829
- }
1830
-
1831
- /** True when (x, y) lies within the element's box. */
1832
- function insideRect(el, x, y) {
1833
- const r = el.getBoundingClientRect();
1834
- return x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;
1835
- }
1836
-
1837
- // Registered ONCE (module scope), not per popover open — the flyout is looked up
1838
- // each move, so one listener serves every open/close cycle.
1839
- if (typeof document !== 'undefined') document.addEventListener('mousemove', flyoutWatcher);
1840
-
1841
- function onDocDown(ev) {
1842
- const box = $('popover');
1843
- if (box && box.contains(ev.target)) return;
1844
- closePopover();
1845
- }
1846
-
1847
- function onDocKey(ev) {
1848
- if (ev.key === 'Escape') closePopover();
1849
- }
1850
-
1851
- function closePopover() {
1852
- const box = $('popover');
1853
- if (box) box.hidden = true;
1854
- popoverOpen = null;
1855
- // The floating level list is appended to <body>, so it must be removed here or
1856
- // it would linger after the popover closes.
1857
- for (const f of document.querySelectorAll('.popover-flyout')) f.remove();
1858
- document.removeEventListener('mousedown', onDocDown);
1859
- document.removeEventListener('keydown', onDocKey);
1860
- }
1861
-
1862
- const SPINNER = ['\u280b', '\u2819', '\u2839', '\u2838', '\u283c', '\u2834', '\u2826', '\u2827', '\u2807', '\u280f'];
1863
- const ORANGE_RGB = [255, 140, 0];
1864
- const WORK_YELLOW_RGB = [255, 240, 120];
1865
- const WORK_RED_RGB = [255, 0, 0];
1866
- /** Animation clock and phrase for the Working pulse. Kept at module scope so the
1867
- rAF loop can stop itself and so `applyStatus` can restart it without a fresh
1868
- capture each time. */
1869
- let pulseRaf = null;
1870
- let pulseMsg = '';
1871
-
1872
- /**
1873
- * The Working row's pulse, driven by its OWN rAF loop, not by the server's `spin`
1874
- * counter. The server no longer broadcasts every spin frame (see
1875
- * ANIMATION_FIELDS in session-hub.js); even when it does, redrawing the row from
1876
- * a remote tick lets the two drift. The sweep keeps the terminal's orange→yellow→
1877
- * red cycle, advanced by elapsed TIME so it stays smooth.
1878
- */
1879
- function drawPulse() {
1880
- pulseMsg = String((status && status.workMsg) || '');
1881
- if (pulseRaf === null) pulseRaf = requestAnimationFrame(pulseFrame);
1882
- }
1883
-
1884
- /* The pulse advances at the TERMINAL's tick — 80ms per spinner frame — not at
1885
- display refresh rate: rebuilding the row's per-character spans at 60fps buys
1886
- nothing the eye can see and burns real CPU. */
1887
- const PULSE_TICK_MS = 80;
1888
- let pulseLastTick = -1;
1889
-
1890
- function pulseFrame() {
1891
- pulseRaf = null;
1892
- if (!status || !status.busy) { stopPulse(); return; }
1893
- const box = $('working-text');
1894
- const now = performance.now();
1895
- if (box && box.isConnected) {
1896
- const tick = Math.floor(now / PULSE_TICK_MS);
1897
- if (tick !== pulseLastTick) { paintPulseFrame(box, now); pulseLastTick = tick; }
1898
- }
1899
- pulseRaf = requestAnimationFrame(pulseFrame);
1900
- }
1901
-
1902
- function clearPulse() {
1903
- stopPulse();
1904
- const box = $('working-text');
1905
- if (box) box.replaceChildren();
1906
- }
1907
-
1908
- function stopPulse() {
1909
- if (pulseRaf !== null) { cancelAnimationFrame(pulseRaf); pulseRaf = null; }
1910
- pulseMsg = '';
1911
- pulseLastTick = -1;
1912
- }
1913
-
1914
- function paintPulseFrame(box, now) {
1915
- const msg = pulseMsg;
1916
- if (!msg) { box.replaceChildren(); return; }
1917
- // The sweep advances on time: 6 ticks ≈ 0.5s, so a 24-tick cycle is ~2s.
1918
- const tick = Math.floor(now / 80);
1919
- const inCycle = tick % SWEEP_CYCLE;
1920
- const inHalf = inCycle % SWEEP_HALF;
1921
- const target = inCycle < SWEEP_HALF ? WORK_YELLOW_RGB : WORK_RED_RGB;
1922
- const n = msg.length;
1923
- const band = Math.max(2, Math.min(4, n / 3)) / n;
1924
-
1925
- const frag = document.createDocumentFragment();
1926
- const spin = document.createElement('span');
1927
- spin.className = 'spin';
1928
- spin.textContent = SPINNER[tick % SPINNER.length];
1929
- frag.appendChild(spin);
1930
-
1931
- for (let i = 0; i < n; i++) {
1932
- const at = i / n;
1933
- const t = inHalf < SWEEP
1934
- ? ((inHalf + 1) / SWEEP - at) / band
1935
- : 1 - ((inHalf - SWEEP + 1) / SWEEP - at) / band;
1936
- const s = document.createElement('span');
1937
- s.style.color = mixRgb(ORANGE_RGB, target, t);
1938
- s.textContent = msg[i];
1939
- frag.appendChild(s);
1940
- }
1941
- box.replaceChildren(frag);
1942
- }
1943
-
1944
-
1945
- /**
1946
- * Drag-to-resize for the todo and queue panels, ported from the terminal.
1947
- *
1948
- * The terminal marks each panel's top rule as a resize hitbox, and dragging
1949
- * works in ROWS with `up = more rows`: the delta is taken against the row the
1950
- * drag started on, so the panel grows as the pointer rises and shrinks as it
1951
- * falls. The result is clamped to `[1, total]` — at least one row, never more
1952
- * than exist. `null` means "no manual size", i.e. the automatic heuristic.
1953
- */
1954
- const QUEUE_MAX_VISIBLE = 5;
1955
- const panelRows = { todo: null, queue: null };
1956
- const resizeDrag = { kind: null, startY: 0, startRows: 0 };
1957
-
1958
-
1959
- /** Row count a panel shows: the manual drag value when set, else the automatic
1960
- one. Always clamped to [1, total], and 0 when there is nothing to show. */
1961
- function panelRowCount(kind, total) {
1962
- if (!total) return 0;
1963
- const rows = panelRows[kind];
1964
- if (typeof rows === 'number' && Number.isFinite(rows)) {
1965
- return Math.max(1, Math.min(total, Math.round(rows)));
1966
- }
1967
- return kind === 'todo'
1968
- ? (todosExpanded ? total : selectVisibleTodos(status.todos || []).rows.length)
1969
- : Math.min(total, QUEUE_MAX_VISIBLE);
1970
- }
1971
-
1972
- function setResizeHover(el, on) {
1973
- el.classList.toggle('is-hover', on);
1974
- }
1975
-
1976
- function setupPanelResize() {
1977
- for (const rule of document.querySelectorAll('.stack-rule')) {
1978
- const kind = rule.getAttribute('data-resize');
1979
-
1980
- rule.addEventListener('mouseenter', () => setResizeHover(rule, true));
1981
- rule.addEventListener('mouseleave', () => {
1982
- if (resizeDrag.kind !== kind) setResizeHover(rule, false);
1983
- });
1984
-
1985
- rule.addEventListener('pointerdown', (ev) => {
1986
- // Capturing keeps the drag alive once the pointer leaves the 6px rule,
1987
- // which it immediately does — a resize handle you have to stay on top of
1988
- // is unusable.
1989
- ev.preventDefault();
1990
- rule.setPointerCapture(ev.pointerId);
1991
- rule.classList.add('is-dragging');
1992
- const total = kind === 'todo'
1993
- ? (status.todos || []).length
1994
- : (status.queued || []).length;
1995
- resizeDrag.kind = kind;
1996
- resizeDrag.startY = ev.clientY;
1997
- resizeDrag.startRows = panelRowCount(kind, total);
1998
- setResizeHover(rule, true);
1999
- });
2000
-
2001
- rule.addEventListener('pointermove', (ev) => {
2002
- if (resizeDrag.kind !== kind) return;
2003
- const total = kind === 'todo'
2004
- ? (status.todos || []).length
2005
- : (status.queued || []).length;
2006
- if (!total) return;
2007
- // Rows are a line-height tall; converting the pixel delta into rows is what
2008
- // makes the drag track the pointer instead of jumping a row per pixel.
2009
- const rowPx = kind === 'todo' ? TODO_ROW_PX : QUEUE_ROW_PX;
2010
- const delta = Math.round((resizeDrag.startY - ev.clientY) / rowPx);
2011
- const want = Math.max(1, Math.min(total, resizeDrag.startRows + delta));
2012
- if (panelRows[kind] === want) return;
2013
- panelRows[kind] = want;
2014
- if (kind === 'todo') renderTodoPanel(status.todos || []);
2015
- else renderQueuePanel(status.queued || [], !!status.busy);
2016
- });
2017
-
2018
- const end = (ev) => {
2019
- if (resizeDrag.kind !== kind) return;
2020
- rule.classList.remove('is-dragging');
2021
- try { rule.releasePointerCapture(ev.pointerId); } catch { /* already gone */ }
2022
- resizeDrag.kind = null;
2023
- setResizeHover(rule, false);
2024
- };
2025
- rule.addEventListener('pointerup', end);
2026
- rule.addEventListener('pointercancel', end);
2027
- }
2028
- }
2029
-
2030
- // -------------------------------------------------------------- todo panel
2031
-
2032
- const TODO_MAX_VISIBLE = 5;
2033
- const TODO_MARK = { in_progress: '\u25cf', done: '\u2713', pending: '\u25cb' };
2034
- /** One rendered todo row, in CSS pixels — the pointer-delta to row conversion. */
2035
- const TODO_ROW_PX = 21;
2036
- const QUEUE_ROW_PX = 21;
2037
-
2038
- let todosExpanded = false;
2039
-
2040
-
2041
- function selectVisibleTodos(todos) {
2042
- if (todos.length <= TODO_MAX_VISIBLE) return { rows: todos, hidden: 0, counts: null };
2043
- const inProgress = [], pending = [], done = [];
2044
- todos.forEach((t, i) => {
2045
- if (t.status === 'in_progress') inProgress.push(i);
2046
- else if (t.status === 'pending') pending.push(i);
2047
- else done.push(i);
2048
- });
2049
- const picked = new Set(inProgress.slice(0, TODO_MAX_VISIBLE));
2050
- if (picked.size < TODO_MAX_VISIBLE) {
2051
- const doneC = done.slice().reverse();
2052
- const remaining = TODO_MAX_VISIBLE - picked.size;
2053
- let doneCount, pendCount;
2054
- if (!doneC.length) { doneCount = 0; pendCount = Math.min(remaining, pending.length); }
2055
- else if (!pending.length) { pendCount = 0; doneCount = Math.min(remaining, doneC.length); }
2056
- else {
2057
- doneCount = 1;
2058
- pendCount = Math.min(remaining - 1, pending.length);
2059
- if (pendCount < remaining - 1) doneCount = Math.min(doneC.length, remaining - pendCount);
2060
- }
2061
- for (let i = 0; i < doneCount; i++) picked.add(doneC[i]);
2062
- for (let i = 0; i < pendCount; i++) picked.add(pending[i]);
2063
- }
2064
- const idx = [...picked].sort((a, b) => a - b);
2065
- const counts = { done: 0, in_progress: 0, pending: 0 };
2066
- todos.forEach((t, i) => { if (!picked.has(i)) counts[t.status] = (counts[t.status] || 0) + 1; });
2067
- return { rows: idx.map((i) => todos[i]), hidden: todos.length - idx.length, counts };
2068
- }
2069
-
2070
- function todoMoreButton(label, title, onClick) {
2071
- const b = document.createElement('button');
2072
- b.type = 'button';
2073
- b.className = 'msg-more';
2074
- b.style.margin = '0';
2075
- b.textContent = label;
2076
- if (title) b.title = title;
2077
- b.addEventListener('click', onClick);
2078
- return b;
2079
- }
2080
-
2081
- function renderTodoPanel(todos) {
2082
- const ul = $('st-todos');
2083
- if (!ul) return;
2084
- ul.replaceChildren();
2085
- if (!todos.length) return;
2086
-
2087
- // The visible set is the automatic pick topped up to the panel's row count, so
2088
- // dragging the rule taller ADDS rows rather than reordering them — the
2089
- // in-progress item keeps its priority while more of the list appears under it.
2090
- const want = panelRowCount('todo', todos.length);
2091
- const auto = selectVisibleTodos(todos);
2092
- const rows = auto.rows.slice();
2093
- if (rows.length < want) {
2094
- const seen = new Set(rows);
2095
- for (const t of todos) {
2096
- if (rows.length >= want) break;
2097
- if (!seen.has(t)) { rows.push(t); seen.add(t); }
2098
- }
2099
- }
2100
- const shown = rows.slice(0, want);
2101
-
2102
- for (const t of shown) {
2103
- const li = document.createElement('li');
2104
- li.className = t.status === 'done' ? 'done' : t.status === 'in_progress' ? 'now' : '';
2105
- li.appendChild(el('mark', TODO_MARK[t.status] || TODO_MARK.pending));
2106
- li.appendChild(el('t', String(t.title == null ? '' : t.title)));
2107
- ul.appendChild(li);
2108
- }
2109
-
2110
- const hidden = todos.length - shown.length;
2111
- if (hidden > 0) {
2112
- const counts = { done: 0, in_progress: 0, pending: 0 };
2113
- for (const t of todos) if (!shown.includes(t)) counts[t.status] = (counts[t.status] || 0) + 1;
2114
- const dist = [['done', 'done'], ['in_progress', 'in progress'], ['pending', 'pending']]
2115
- .filter(([k]) => counts[k] > 0)
2116
- .map(([k, label]) => counts[k] + ' ' + label)
2117
- .join(', ');
2118
- const li = document.createElement('li');
2119
- li.className = 'more';
2120
- li.appendChild(todoMoreButton(
2121
- '\u2026 +' + hidden + (dist ? ' (' + dist + ')' : ''),
2122
- tr('status.expandTodos'),
2123
- () => { todosExpanded = true; panelRows.todo = todos.length; renderTodoPanel(todos); },
2124
- ));
2125
- ul.appendChild(li);
2126
- } else if (todosExpanded && todos.length > TODO_MAX_VISIBLE) {
2127
- const li = document.createElement('li');
2128
- li.className = 'more';
2129
- li.appendChild(todoMoreButton(tr('tool.collapse'), '', () => {
2130
-
2131
- todosExpanded = false;
2132
- panelRows.todo = null;
2133
- renderTodoPanel(todos);
2134
- }));
2135
- ul.appendChild(li);
2136
- }
2137
- }
2138
-
2139
-
2140
- // ------------------------------------------------------------- queue panel
2141
-
2142
- function renderQueuePanel(queued, busy) {
2143
- const ul = $('st-queue');
2144
- if (!ul) return;
2145
- ul.replaceChildren();
2146
- if (!queued.length) return;
2147
-
2148
- // Same rule as the todo panel: the drag count wins, clamped to what exists.
2149
- const rows = queued.slice(0, panelRowCount('queue', queued.length));
2150
-
2151
- rows.forEach((raw) => {
2152
- const text = String(raw == null ? '' : raw);
2153
- const single = text.replace(/\s+/g, ' ').trim();
2154
- const li = document.createElement('li');
2155
- li.appendChild(el('mark', tr('mark.queued')));
2156
- const tx = el('t', single);
2157
- tx.title = single;
2158
- li.appendChild(tx);
2159
-
2160
- if (busy) {
2161
- const b = document.createElement('button');
2162
- b.type = 'button';
2163
- b.className = 'steer-btn';
2164
- b.textContent = tr('queue.steer');
2165
- b.title = tr('queue.steerHint');
2166
- b.addEventListener('click', (ev) => {
2167
- ev.preventDefault();
2168
- // The payload is the item's OWN text, captured here. Indexing into the
2169
- // `queued` array read a list that status rebuilds from scratch on every
2170
- // frame, so a click after any change steered the wrong message — or
2171
- // nothing. A successful steer removes the item, so the row disappears on
2172
- // the next status frame.
2173
- void steerQueued(b, text);
2174
- });
2175
- li.appendChild(b);
2176
- }
2177
-
2178
- // Edit: pull the message back out of the queue and load it into the composer,
2179
- // mirroring the terminal's ↑-to-recall. Available whether or not a turn is
2180
- // running — a queued message is editable at any time.
2181
- const eb = document.createElement('button');
2182
- eb.type = 'button';
2183
- eb.className = 'steer-btn edit-btn';
2184
- eb.textContent = tr('queue.edit');
2185
- eb.title = tr('queue.editHint');
2186
- eb.addEventListener('click', (ev) => {
2187
- ev.preventDefault();
2188
- void editQueued(eb, text);
2189
- });
2190
- li.appendChild(eb);
2191
-
2192
- // Drop: remove it from the queue without editing.
2193
- const db = document.createElement('button');
2194
- db.type = 'button';
2195
- db.className = 'steer-btn drop-btn';
2196
- db.textContent = tr('queue.drop');
2197
- db.title = tr('queue.dropHint');
2198
- db.addEventListener('click', (ev) => {
2199
- ev.preventDefault();
2200
- void dropQueued(db, text);
2201
- });
2202
- li.appendChild(db);
2203
- ul.appendChild(li);
2204
- });
2205
-
2206
- const li = document.createElement('li');
2207
- li.className = 'more';
2208
- const hidden = queued.length - rows.length;
2209
- li.textContent = hidden > 0
2210
- ? tr('queue.moreHint', { n: hidden })
2211
- : tr(busy ? 'queue.hintRunning' : 'queue.hintIdle');
2212
- ul.appendChild(li);
2213
- }
2214
-
2215
- /** Steer one queued message into the running turn. The button reports its own
2216
- progress, because a send that silently does nothing is indistinguishable
2217
- from a broken button. */
2218
- async function steerQueued(btn, text) {
2219
- btn.disabled = true;
2220
- btn.textContent = tr('queue.steering');
2221
- const body = await act('steer', [text]);
2222
- if (!body || body.ok !== true) {
2223
- btn.disabled = false;
2224
- btn.textContent = tr('queue.steer');
2225
- }
2226
- }
2227
-
2228
- /** Recall a queued message into the composer for editing, like the terminal's ↑.
2229
- The server removes it from the queue and returns its text; we put that text in
2230
- the input so the user can change and re-send it. */
2231
- async function editQueued(btn, text) {
2232
- btn.disabled = true;
2233
- const body = await act('editQueued', [text]);
2234
- btn.disabled = false;
2235
- if (!body || body.ok !== true) return;
2236
- input.value = String(body.text == null ? text : body.text);
2237
- input.focus();
2238
- input.setSelectionRange(input.value.length, input.value.length);
2239
- autoGrow();
2240
- setPmode();
2241
- }
2242
-
2243
- /** Remove a queued message without editing it. */
2244
- async function dropQueued(btn, text) {
2245
- btn.disabled = true;
2246
- const body = await act('dropQueued', [text]);
2247
- btn.disabled = false;
2248
- if (!body || body.ok !== true) btn.disabled = false;
2249
- }
2250
-
2251
-
2252
- // ------------------------------------------------------------- side tabs
2253
-
2254
- function card() {
2255
- const n = document.createElement('div');
2256
- n.className = 'card';
2257
- return n;
2258
- }
2259
-
2260
- function cardHead(...nodes) {
2261
- const h = document.createElement('div');
2262
- h.className = 'card-head';
2263
- h.append(...nodes);
2264
- return h;
2265
- }
2266
-
2267
- function cardFields() {
2268
- const g = document.createElement('div');
2269
- g.className = 'card-fields';
2270
- return g;
2271
- }
2272
-
2273
- function rightMeta(text) {
2274
- const s = document.createElement('span');
2275
- s.className = 'right';
2276
- s.textContent = text;
2277
- return s;
2278
- }
2279
-
2280
- function field(label, value) {
2281
- const row = document.createElement('div');
2282
- row.className = 'field';
2283
- row.appendChild(el('field-label', label));
2284
- const v = el('field-value', '');
2285
- if (value == null || value === '') {
2286
- v.className = 'field-value dim';
2287
- v.textContent = tr('unit.none');
2288
- } else if (value instanceof Node) {
2289
- v.appendChild(value);
2290
- } else {
2291
- v.textContent = String(value);
2292
- }
2293
- row.appendChild(v);
2294
- return row;
2295
- }
2296
-
2297
- function pill(text, tone) {
2298
- return el('pill' + (tone ? ' pill-' + tone : ''), text);
2299
- }
2300
-
2301
- function emptyNote(text) {
2302
- return el('cards-empty', text);
2303
- }
2304
-
2305
- function renderTasks(list) {
2306
- const wrap = $('tasks');
2307
- wrap.replaceChildren();
2308
- if (!list.length) { wrap.appendChild(emptyNote(tr('tasks.empty'))); return; }
2309
- for (const task of list) {
2310
- const c = card();
2311
- const tone = task.status === 'running' ? 'info'
2312
- : task.status === 'failed' ? 'danger'
2313
- : task.status === 'done' || task.status === 'completed' ? 'ok'
2314
- : 'soft';
2315
- const head = cardHead(
2316
- pill(task.kind || 'bash', 'soft'),
2317
- pill(task.status || '', tone),
2318
- pill(task.id || '', 'sub'),
2319
- );
2320
- if (task.status === 'running') {
2321
- const b = document.createElement('button');
2322
- b.className = 'steer-btn';
2323
- b.textContent = tr('tasks.stop');
2324
- b.addEventListener('click', () => act('stopTask', [task.id]));
2325
- head.appendChild(b);
2326
- }
2327
- c.appendChild(head);
2328
- c.appendChild(rightMeta(task.startedAt ? ago(task.startedAt) : ''));
2329
-
2330
- const fields = cardFields();
2331
- fields.appendChild(field(tr('tasks.colSummary'), String(task.summary || task.prompt || '')));
2332
- if (task.agentId) fields.appendChild(field('agent', task.agentId));
2333
- c.appendChild(fields);
2334
- wrap.appendChild(c);
2335
- }
2336
- }
2337
-
2338
- function renderFiles(files) {
2339
- const wrap = $('files');
2340
- wrap.replaceChildren();
2341
- if (!files.length) { wrap.appendChild(emptyNote(tr('files.empty'))); return; }
2342
- for (const f of files) {
2343
- const c = card();
2344
- c.appendChild(cardHead(pill(f.ops || '', 'soft')));
2345
- c.appendChild(rightMeta(String(f.count || 0)));
2346
- const fields = cardFields();
2347
- fields.appendChild(field(tr('files.colPath'), f.path));
2348
- c.appendChild(fields);
2349
- wrap.appendChild(c);
2350
- }
2351
- }
2352
-
2353
- function renderTools(list) {
2354
- const wrap = $('tools');
2355
- wrap.replaceChildren();
2356
- if (!list.length) { wrap.appendChild(emptyNote(tr('side.none'))); return; }
2357
- for (const x of list) {
2358
- const c = card();
2359
- c.appendChild(cardHead(pill(x.name || '', 'soft')));
2360
- const fields = cardFields();
2361
- fields.appendChild(field('description', String(x.description || '').split('\n')[0]));
2362
- c.appendChild(fields);
2363
- wrap.appendChild(c);
2364
- }
2365
- }
2366
-
2367
- function renderCommands(list) {
2368
- const wrap = $('commands');
2369
- wrap.replaceChildren();
2370
- if (!list.length) { wrap.appendChild(emptyNote(tr('side.none'))); return; }
2371
- for (const cmd of list) {
2372
- const c = card();
2373
- c.classList.add('cmd-card'); // enables the hover affordance
2374
- c.appendChild(cardHead(pill('/' + (cmd.name || ''), 'solid'), pill(cmd.argumentHint || '', 'soft')));
2375
- const fields = cardFields();
2376
- fields.appendChild(field('description', cmd.desc || ''));
2377
- c.appendChild(fields);
2378
- // Clicking a command card acts on it, the way accepting a completion does in
2379
- // the terminal:
2380
- // * a command that takes NO argument runs immediately,
2381
- // * a command that needs one (its argumentHint is shown on the card head) is
2382
- // PREPARED in the composer, with the leading slash and trailing space in
2383
- // place, so the user fills in the value and presses Enter — sending it
2384
- // empty would just bounce the usage/error back.
2385
- const nm = String(cmd.name || '');
2386
- const needsArg = !!(cmd && cmd.argumentHint);
2387
- c.addEventListener('click', () => {
2388
- if (needsArg) {
2389
- const box = $('composer');
2390
- if (box) box.focus();
2391
- input.value = '/' + nm + ' ';
2392
- input.setSelectionRange(input.value.length, input.value.length);
2393
- if (typeof autoGrow === 'function') autoGrow();
2394
- if (typeof setPmode === 'function') setPmode();
2395
- } else {
2396
- void send('/' + nm);
2397
- }
2398
- });
2399
- wrap.appendChild(c);
2400
- }
2401
- }
2402
-
2403
-
2404
- function renderTabCounts(s) {
2405
- const counts = {
2406
- tasks: (s.tasks || []).length,
2407
- files: (s.files || []).length,
2408
- logs: ($('logs') || { childElementCount: 0 }).childElementCount,
2409
- tools: (s.tools || []).length,
2410
- commands: (s.commands || []).length,
2411
- };
2412
- for (const b of document.querySelectorAll('.tab')) {
2413
- const n = counts[b.getAttribute('data-view')];
2414
- const old = b.querySelector('.tab-count');
2415
- if (!n) { if (old) old.remove(); continue; }
2416
- if (old) { old.textContent = String(n); continue; }
2417
- b.appendChild(el('tab-count', String(n)));
2418
- }
2419
- }
2420
-
2421
- const MAX_LOG = 600;
2422
-
2423
- function addLog(e) {
2424
- const box = $('logs');
2425
- const line = document.createElement('div');
2426
- line.className = 'log-line';
2427
- line.append(
2428
- el('log-t', new Date(e.at || Date.now()).toTimeString().slice(0, 8)),
2429
- el('log-k', String(e.kind || e.type || '')),
2430
- el('log-d', String(e.text || '')),
2431
- );
2432
- box.appendChild(line);
2433
- while (box.children.length > MAX_LOG) box.removeChild(box.firstChild);
2434
- if (!$('view-logs').hidden) box.scrollTop = box.scrollHeight;
2435
- }
2436
-
2437
- // ----------------------------------------------------------------- modal
2438
-
2439
- let modalKey = '';
2440
-
2441
- function applyModal(s) {
2442
- const box = $('modal');
2443
- const pending = s.pending;
2444
- if (!pending) { box.hidden = true; modalKey = ''; return; }
2445
- const key = JSON.stringify(pending);
2446
- if (key === modalKey && !box.hidden) return;
2447
- modalKey = key;
2448
-
2449
- $('modal-box').className = 'modal-box '
2450
- + (pending.kind === 'approval' ? 'is-approval' : 'is-question');
2451
- $('modal-title').textContent = pending.kind === 'approval' ? tr('modal.approve') : tr('modal.question');
2452
- $('modal-body').textContent = pending.detail || pending.question || '';
2453
- const actions = $('modal-actions');
2454
- actions.replaceChildren();
2455
-
2456
- const mkBtn = (label, fn, primary) => {
2457
- const b = document.createElement('button');
2458
- b.className = primary ? 'btn' : 'btn-quiet';
2459
- b.textContent = label;
2460
- b.addEventListener('click', fn);
2461
- actions.appendChild(b);
2462
- };
2463
-
2464
- if (pending.kind === 'approval') {
2465
- mkBtn(tr('modal.allow'), () => act('approve', [pending.id, true]), true);
2466
- mkBtn(tr('modal.deny'), () => act('approve', [pending.id, false]), false);
2467
- } else {
2468
- const body = $('modal-body');
2469
- const multi = !!pending.multiSelect;
2470
- const picked = new Set();
2471
- // Declared before the option handlers below reference it (single-select
2472
- // submits immediately and must be able to read the note if it is present).
2473
- let noteEl = null;
2474
- // Progress line: "Question n/total" + optional header.
2475
- const total = Number(pending.total || 1);
2476
- const idx = Number(pending.index || 0);
2477
- if (total > 1) {
2478
- const prog = document.createElement('div');
2479
- prog.className = 'modal-progress';
2480
- prog.textContent = tr('modal.progress', { n: idx + 1, total })
2481
- + (pending.header ? ' ' + pending.header : '');
2482
- body.appendChild(prog);
2483
- }
2484
- // Option rows (the model's real options).
2485
- const list = document.createElement('div');
2486
- list.className = 'modal-options';
2487
- for (const o of pending.options || []) {
2488
- const label = (o && typeof o === 'object') ? o.label : String(o);
2489
- const desc = (o && typeof o === 'object') ? (o.description || '') : '';
2490
- const b = document.createElement('button');
2491
- b.type = 'button';
2492
- b.className = 'modal-opt';
2493
- b.dataset.label = label;
2494
- const t = document.createElement('span');
2495
- t.className = 'modal-opt-label';
2496
- t.textContent = label;
2497
- b.appendChild(t);
2498
- if (desc) {
2499
- const d = document.createElement('span');
2500
- d.className = 'modal-opt-desc';
2501
- d.textContent = desc;
2502
- b.appendChild(d);
2503
- }
2504
- if (multi) {
2505
- const box = document.createElement('span');
2506
- box.className = 'modal-check';
2507
- box.textContent = '\u25cb';
2508
- b.prepend(box);
2509
- b.addEventListener('click', () => {
2510
- if (picked.has(label)) picked.delete(label); else picked.add(label);
2511
- b.classList.toggle('is-on', picked.has(label));
2512
- box.textContent = picked.has(label) ? '\u2713' : '\u25cb';
2513
- });
2514
- } else {
2515
- // Single-select: choosing an option answers immediately, like the terminal.
2516
- b.addEventListener('click', () => {
2517
- void act('answerQuestion', [pending.id, [label], '', noteEl ? noteEl.value : '', true]);
2518
- });
2519
- }
2520
- list.appendChild(b);
2521
- }
2522
- body.appendChild(list);
2523
- // Per-question "Other": a free-text answer of the user's own.
2524
- const otherWrap = document.createElement('div');
2525
- otherWrap.className = 'modal-other';
2526
- const otherBtn = document.createElement('button');
2527
- otherBtn.type = 'button';
2528
- otherBtn.className = 'modal-opt modal-other-toggle';
2529
- otherBtn.textContent = tr('modal.other');
2530
- const otherInput = document.createElement('input');
2531
- otherInput.type = 'text';
2532
- otherInput.className = 'modal-input inline';
2533
- otherInput.placeholder = tr('modal.otherHint');
2534
- let otherOpen = false;
2535
- otherBtn.addEventListener('click', () => {
2536
- otherOpen = !otherOpen;
2537
- otherInput.hidden = !otherOpen;
2538
- otherBtn.classList.toggle('is-on', otherOpen);
2539
- if (otherOpen) otherInput.focus();
2540
- });
2541
- otherInput.hidden = true;
2542
- otherWrap.append(otherBtn, otherInput);
2543
- body.appendChild(otherWrap);
2544
- // Whole-request note, only after the last question (may be left blank).
2545
- if (pending.hasSupplement) {
2546
- const noteWrap = document.createElement('div');
2547
- noteWrap.className = 'modal-note';
2548
- const nl = document.createElement('div');
2549
- nl.className = 'modal-note-label';
2550
- nl.textContent = tr('modal.note');
2551
- noteEl = document.createElement('textarea');
2552
- noteEl.rows = 2;
2553
- noteEl.className = 'modal-input';
2554
- noteEl.placeholder = tr('modal.noteHint');
2555
- noteWrap.append(nl, noteEl);
2556
- body.appendChild(noteWrap);
2557
- }
2558
- // Actions: submit the current answers. In single-select the option click
2559
- // already submitted, but Submit also works (honours the Other text box).
2560
- const submitCurrent = () => {
2561
- const other = otherOpen ? otherInput.value.trim() : '';
2562
- const list0 = [...picked];
2563
- void act('answerQuestion', [pending.id, other ? [] : list0, other, noteEl ? noteEl.value : '', true]);
2564
- };
2565
- mkBtn(total > 1 && idx < total - 1 ? tr('modal.next') : tr('modal.submit'), submitCurrent, true);
2566
- }
2567
- box.hidden = false;
2568
- }
2569
-
2570
- function copyButton(value, label) {
2571
- const b = document.createElement('button');
2572
- b.type = 'button';
2573
- b.className = 'copy-btn';
2574
- b.textContent = label || tr('copy.copy');
2575
- b.title = tr('copy.copyTitle');
2576
- let timer = null;
2577
- b.addEventListener('click', (ev) => {
2578
- ev.stopPropagation();
2579
- const done = (okState) => {
2580
- b.textContent = okState ? tr('copy.done') : tr('copy.failed');
2581
- b.classList.toggle('is-ok', okState);
2582
- b.classList.toggle('is-err', !okState);
2583
- if (timer) clearTimeout(timer);
2584
- timer = setTimeout(() => {
2585
- b.textContent = label || tr('copy.copy');
2586
- b.classList.remove('is-ok', 'is-err');
2587
- }, 1200);
2588
- };
2589
- const text = String(value == null ? '' : value);
2590
- if (navigator.clipboard && navigator.clipboard.writeText) {
2591
- navigator.clipboard.writeText(text).then(() => done(true)).catch(() => done(false));
2592
- } else {
2593
- done(false);
2594
- }
2595
- });
2596
- return b;
2597
- }
2598
-
2599
- // ------------------------------------------------------------------ rail
2600
-
2601
- function ago(ms) {
2602
- if (!ms) return '';
2603
- const diff = Date.now() - ms;
2604
- if (diff < 0) return new Date(ms).toLocaleDateString();
2605
- const min = Math.floor(diff / 60000);
2606
- if (min < 1) return tr('home.justNow');
2607
- if (min < 60) return tr('home.minutesAgo', { n: min });
2608
- const hr = Math.floor(min / 60);
2609
- if (hr < 24) return tr('home.hoursAgo', { n: hr });
2610
- const day = Math.floor(hr / 24);
2611
- if (day < 7) return tr('home.daysAgo', { n: day });
2612
- return new Date(ms).toLocaleDateString();
2613
- }
2614
-
2615
- function workspaceLabel(p) {
2616
- const parts = String(p || '').split(/[/\\]+/).filter(Boolean);
2617
- if (!parts.length) return tr('rail.noWorkspace');
2618
- return parts.slice(-2).join('/');
2619
- }
2620
-
2621
- function shortId(id) {
2622
- const s = String(id || '');
2623
- return s.length > 12 ? '\u2026' + s.slice(-10) : s;
2624
- }
2625
-
2626
- let railShape = '';
2627
- let railFilter = '';
2628
- let railData = { sessions: [], current: '' };
2629
-
2630
- function renderRail(data) {
2631
- const list = $('rail-list');
2632
- if (!list) return;
2633
- railData = data || railData;
2634
- const all = railData.sessions || [];
2635
- const current = String(railData.current || '');
2636
-
2637
- const q = railFilter.trim().toLowerCase();
2638
- const sessions = q
2639
- ? all.filter((s) => (s.id + ' ' + (s.title || '') + ' ' + (s.workspace || '')).toLowerCase().includes(q))
2640
- : all;
2641
-
2642
- const shape = current + '\u0000' + q + '\u0000'
2643
- + sessions.map((s) => s.id + ':' + s.title + ':' + s.updatedAt).join('\u0000');
2644
- if (shape === railShape) return;
2645
- railShape = shape;
2646
-
2647
- $('rail-count').textContent = !all.length ? ''
2648
- : q ? sessions.length + ' / ' + all.length
2649
- : String(all.length);
2650
-
2651
- list.replaceChildren();
2652
- if (!sessions.length) {
2653
- list.appendChild(el('rail-empty', all.length ? tr('rail.noMatch') : tr('rail.empty')));
2654
- return;
2655
- }
2656
-
2657
- const byWs = new Map();
2658
- for (const s of sessions) {
2659
- const key = workspaceLabel(s.workspace);
2660
- if (!byWs.has(key)) byWs.set(key, []);
2661
- byWs.get(key).push(s);
2662
- }
2663
- const groups = [...byWs.entries()].sort((a, b) => {
2664
- const na = Math.max(0, ...a[1].map((s) => s.updatedAt || 0));
2665
- const nb = Math.max(0, ...b[1].map((s) => s.updatedAt || 0));
2666
- return nb - na;
2667
- });
2668
-
2669
- for (const [ws, items] of groups) {
2670
- const head = document.createElement('div');
2671
- head.className = 'rail-group';
2672
- const name = document.createElement('span');
2673
- name.className = 'ws';
2674
- name.textContent = ws;
2675
- name.title = items[0].workspace || '';
2676
- head.append(name, el('mono', String(items.length)));
2677
- list.appendChild(head);
2678
- for (const s of items) list.appendChild(railRow(s, s.id === current));
2679
- }
2680
- }
2681
-
2682
- function railRow(s, isCurrent) {
2683
- const a = document.createElement('a');
2684
- a.className = 'rail-row' + (isCurrent ? ' is-current' : '');
2685
- a.href = '/s/' + encodeURIComponent(s.id) + '/';
2686
- a.title = (s.title || tr('home.untitled')) + '\n' + (s.id || '') + '\n' + (s.workspace || '');
2687
-
2688
- const top = document.createElement('span');
2689
- top.className = 'rail-row-top';
2690
- top.append(
2691
- el('rail-dot' + (isCurrent ? ' is-current' : ''), ''),
2692
- el('rail-id', shortId(s.id)),
2693
- el('rail-when', ago(s.updatedAt)),
2694
- );
2695
- a.appendChild(top);
2696
- a.appendChild(el('rail-title', s.title || tr('home.untitled')));
2697
- return a;
2698
- }
2699
-
2700
- async function loadRail() {
2701
- try {
2702
- const res = await fetch('api/sessions', { headers: { accept: 'application/json' } });
2703
- if (!res.ok) return;
2704
- renderRail(await res.json());
2705
- } catch { /* the rail is an accessory; a failed poll must not spam errors */ }
2706
- }
2707
-
2708
- function startRail() {
2709
- void loadRail();
2710
- setInterval(() => { void loadRail(); }, 10000);
2711
- const box = $('rail-filter');
2712
- if (box) {
2713
- box.addEventListener('input', () => {
2714
- railFilter = box.value;
2715
- railShape = '';
2716
- renderRail(railData);
2717
- });
2718
- }
2719
- }
2720
-
2721
- // ------------------------------------------------------------------ input
2722
-
2723
- let inputHistory = [];
2724
- let historyIdx = -1;
2725
-
2726
- function rememberInput(text) {
2727
- const t = String(text || '').trim();
2728
- if (!t) return;
2729
- if (inputHistory[inputHistory.length - 1] !== t) inputHistory.push(t);
2730
- if (inputHistory.length > 200) inputHistory.shift();
2731
- }
2732
-
2733
- function historyNavigate(dir) {
2734
- if (!inputHistory.length) return false;
2735
- const caret = input.selectionStart == null ? 0 : input.selectionStart;
2736
- const end = input.selectionEnd == null ? caret : input.selectionEnd;
2737
- if (caret !== end) return false;
2738
- if (dir < 0 && input.value.slice(0, caret).includes('\n')) return false;
2739
- if (dir > 0 && input.value.slice(end).includes('\n')) return false;
2740
-
2741
- if (historyIdx === -1) historyIdx = inputHistory.length;
2742
- historyIdx = dir < 0
2743
- ? Math.max(0, historyIdx - 1)
2744
- : Math.min(inputHistory.length, historyIdx + 1);
2745
- input.value = historyIdx >= inputHistory.length ? '' : (inputHistory[historyIdx] || '');
2746
- const at = input.value.length;
2747
- input.setSelectionRange(at, at);
2748
- autoGrow();
2749
- setPmode();
2750
- return true;
2751
- }
2752
-
2753
- function resetHistoryCursor() {
2754
- historyIdx = -1;
2755
- }
2756
-
2757
- let growTimer = null;
2758
- let growRows = 0;
2759
-
2760
- function autoGrow() {
2761
- const est = 1 + (input.value.match(/\n/g) || []).length
2762
- + Math.floor(input.value.length / 90);
2763
- if (est === growRows) return;
2764
- if (growTimer !== null) return;
2765
- growTimer = requestAnimationFrame(() => {
2766
- growTimer = null;
2767
- growRows = 1 + (input.value.match(/\n/g) || []).length
2768
- + Math.floor(input.value.length / 90);
2769
- input.style.height = 'auto';
2770
- input.style.height = Math.min(200, input.scrollHeight) + 'px';
2771
- });
2772
- }
2773
-
2774
- function setPmode() {
2775
- const shell = input.value.startsWith('!');
2776
- const node = $('pmode');
2777
- node.textContent = shell ? '!' : '\u203a';
2778
- node.title = tr(shell ? 'chat.shellMode' : 'chat.shellHint');
2779
- $('composer').classList.toggle('is-shell', shell);
2780
- }
2781
-
2782
- async function send(forced) {
2783
- const text = forced === undefined ? input.value : String(forced);
2784
- if (!text.trim()) return;
2785
- if (forced === undefined) {
2786
- input.value = '';
2787
- autoGrow();
2788
- setPmode();
2789
- }
2790
- rememberInput(text);
2791
- resetHistoryCursor();
2792
-
2793
- if (text.startsWith('!')) await act('shell', [text.replace(/^!+/, '').trim()]);
2794
- else if (text.startsWith('/')) {
2795
- // Slash commands (including /skill:<name>) go through the dispatcher, not
2796
- // the plain submit path — otherwise a command line was sent as a literal
2797
- // user message and the skill body / action never ran.
2798
- const sp = text.indexOf(' ');
2799
- const cmd = sp === -1 ? text : text.slice(0, sp);
2800
- const arg = sp === -1 ? '' : text.slice(sp + 1).trim();
2801
- await act('dispatch', [cmd, arg]);
2802
- }
2803
- else await act('submit', [text]);
2804
- }
2805
-
2806
- // ------------------------------------------------------------------ views
2807
-
2808
- const VIEW_IDS = ['chat', 'tasks', 'files', 'tools', 'commands', 'logs'];
2809
-
2810
- const VIEW_SUB = {
2811
- chat: '',
2812
- tasks: 'tasks.sub',
2813
- files: 'files.sub',
2814
- tools: 'tools.sub',
2815
- commands: 'commands.sub',
2816
- logs: 'logs.sub',
2817
- };
2818
-
2819
- function setupViews() {
2820
- for (const b of document.querySelectorAll('.tab')) {
2821
- b.addEventListener('click', () => {
2822
- for (const o of document.querySelectorAll('.tab')) o.classList.toggle('is-on', o === b);
2823
- const v = b.getAttribute('data-view');
2824
- for (const id of VIEW_IDS) $('view-' + id).hidden = id !== v;
2825
- $('view-sub').textContent = VIEW_SUB[v] ? tr(VIEW_SUB[v]) : '';
2826
- // A pane rebuilt-while-hidden never rendered: paint it once now from the
2827
- // latest status, then clear its dirty flag.
2828
- if (dirtyViews.has(v)) {
2829
- dirtyViews.delete(v);
2830
- if (v === 'tasks') renderTasks(status.tasks || []);
2831
- else if (v === 'files') renderFiles(status.files || []);
2832
- else if (v === 'tools') renderTools(status.tools || []);
2833
- else if (v === 'commands') renderCommands(status.commands || []);
2834
- }
2835
- if (v === 'chat') { win.pinned = true; scheduleWindow(); }
2836
- });
2837
- }
2838
- $('btn-interrupt').addEventListener('click', () => act('interrupt'));
2839
- $('logs-clear').addEventListener('click', () => {
2840
- $('logs').replaceChildren();
2841
- renderTabCounts(status);
2842
- });
2843
- }
2844
-
2845
- /**
2846
- * The rail on a narrow screen.
2847
- *
2848
- * Below the breakpoint the rail is no longer a column, so the ONLY way to reach
2849
- * sessions, settings or the language switch is through the header button.
2850
- * Drawing it as an overlay (rather than hiding it outright) is what keeps those
2851
- * reachable on a phone at all — `display: none` left them permanently
2852
- * inaccessible, which is a missing feature rather than a layout choice.
2853
- */
2854
- const railDrawerOpen = { on: false };
2855
-
2856
- function setRailDrawer(open) {
2857
- railDrawerOpen.on = open;
2858
- document.body.classList.toggle('rail-open', open);
2859
- const btn = $('btn-rail');
2860
- if (btn) btn.setAttribute('aria-expanded', open ? 'true' : 'false');
2861
- }
2862
-
2863
- function setupRailDrawer() {
2864
- const btn = $('btn-rail');
2865
- if (!btn) return;
2866
- btn.addEventListener('click', () => setRailDrawer(!railDrawerOpen.on));
2867
-
2868
- // A scrim click and Escape both close it, matching the settings overlay.
2869
- const scrim = $('rail-scrim');
2870
- if (scrim) scrim.addEventListener('click', () => setRailDrawer(false));
2871
- document.addEventListener('keydown', (ev) => {
2872
- if (ev.key === 'Escape' && railDrawerOpen.on) setRailDrawer(false);
2873
- });
2874
-
2875
- // Choosing a session is the reason the drawer was opened; leaving it up would
2876
- // cover the page that was just loaded.
2877
- $('rail-list').addEventListener('click', (ev) => {
2878
- if (ev.target.closest && ev.target.closest('a.rail-row')) setRailDrawer(false);
2879
- });
2880
-
2881
- // Growing past the breakpoint turns the rail back into a column, where the
2882
- // drawer state means nothing.
2883
- const mq = window.matchMedia('(max-width: 720px)');
2884
- const sync = () => { if (!mq.matches) setRailDrawer(false); };
2885
- if (mq.addEventListener) mq.addEventListener('change', sync);
2886
- else if (mq.addListener) mq.addListener(sync);
2887
- }
2888
-
2889
- // ------------------------------------------------------------------- boot
2890
-
2891
-
2892
- function main() {
2893
- applyStatic();
2894
- buildLangSwitch();
2895
- setupViews();
2896
- setupRailDrawer();
2897
- setupPanelResize();
2898
- setPmode();
2899
- startRail();
2900
-
2901
- stream.addEventListener('scroll', onScroll, { passive: true });
2902
- if (typeof ResizeObserver === 'function') {
2903
- new ResizeObserver(() => scheduleWindow()).observe(stream);
2904
- } else {
2905
- window.addEventListener('resize', () => scheduleWindow());
2906
- }
2907
-
2908
- completer = new Completer(input, $('complete'), {
2909
- getCommands: () => (status && status.commands) || [],
2910
- getFiles: () => (status && status.workspaceFiles) || [],
2911
- onAccept: (text, caret) => {
2912
- input.value = text;
2913
- input.setSelectionRange(caret, caret);
2914
- autoGrow();
2915
- setPmode();
2916
- },
2917
- onSubmit: (cmd) => {
2918
- input.value = '';
2919
- autoGrow();
2920
- setPmode();
2921
- void send(cmd);
2922
- },
2923
- });
2924
-
2925
- input.addEventListener('input', () => {
2926
- if (historyIdx !== -1 && input.value !== inputHistory[historyIdx]) resetHistoryCursor();
2927
- autoGrow();
2928
- setPmode();
2929
- completer.refresh();
2930
- });
2931
- input.addEventListener('click', () => { completer.refresh(); });
2932
- input.addEventListener('blur', () => { completer.close(); });
2933
- input.addEventListener('keydown', (ev) => {
2934
- if (completer.open) {
2935
- if (ev.key === 'ArrowDown') { ev.preventDefault(); completer.move(1); return; }
2936
- if (ev.key === 'ArrowUp') { ev.preventDefault(); completer.move(-1); return; }
2937
- if (ev.key === 'Tab') { ev.preventDefault(); completer.accept(); return; }
2938
- if (ev.key === 'Escape') { ev.preventDefault(); completer.close(); return; }
2939
- if (ev.key === 'Enter' && !ev.shiftKey) {
2940
- ev.preventDefault();
2941
- if (completer.run()) return;
2942
- void send();
2943
- return;
2944
- }
2945
- }
2946
-
2947
- if (ev.key === 'ArrowUp' || ev.key === 'ArrowDown') {
2948
- if (!historyNavigate(ev.key === 'ArrowUp' ? -1 : 1)) return;
2949
- ev.preventDefault();
2950
- return;
2951
- }
2952
-
2953
- if (ev.key === 'Enter' && !ev.shiftKey) { ev.preventDefault(); void send(); }
2954
- });
2955
- $('composer').addEventListener('submit', (ev) => { ev.preventDefault(); void send(); });
2956
-
2957
- settingsPanel = new SettingsPanel({
2958
- act: actReturning,
2959
- getStatus: () => status,
2960
- tr,
2961
- toast: (m) => toast(m),
2962
- });
2963
- attachSettings(settingsPanel);
2964
-
2965
- connect();
2966
- }
2967
-
2968
- main();
2969
-