openclacky 1.5.25 → 1.5.26

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 (91) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -0
  3. data/lib/clacky/agent/chunk_index.rb +2 -1
  4. data/lib/clacky/agent/message_compressor_helper.rb +20 -2
  5. data/lib/clacky/agent/session_serializer.rb +28 -1
  6. data/lib/clacky/agent/skill_manager.rb +2 -8
  7. data/lib/clacky/agent/time_machine.rb +108 -127
  8. data/lib/clacky/agent/tool_executor.rb +2 -11
  9. data/lib/clacky/agent.rb +15 -19
  10. data/lib/clacky/agent_config.rb +14 -4
  11. data/lib/clacky/billing/media_usage.rb +69 -0
  12. data/lib/clacky/billing/platform_billing.rb +5 -0
  13. data/lib/clacky/brand_config.rb +16 -215
  14. data/lib/clacky/default_extensions/ext-studio/agents/ext-developer/system_prompt.md +2 -80
  15. data/lib/clacky/default_extensions/ext-studio/panels/studio/view.js +1 -1
  16. data/lib/clacky/default_extensions/ext-studio/skills/ext-develop/SKILL.md +10 -96
  17. data/lib/clacky/default_extensions/git/panels/git/view.js +208 -69
  18. data/lib/clacky/default_extensions/knowledge/README.md +1 -1
  19. data/lib/clacky/default_extensions/knowledge/README.zh.md +1 -1
  20. data/lib/clacky/default_extensions/knowledge/lib/importer.rb +1 -1
  21. data/lib/clacky/default_extensions/knowledge/panels/kb/view.js +3 -3
  22. data/lib/clacky/default_extensions/meeting/api/handler.rb +23 -2
  23. data/lib/clacky/default_extensions/meeting/panels/meeting/view.js +194 -36
  24. data/lib/clacky/default_extensions/preview/icon.svg +3 -2
  25. data/lib/clacky/default_extensions/secretary/panels/work/view.js +108 -33
  26. data/lib/clacky/default_extensions/side-chat/README.md +40 -0
  27. data/lib/clacky/default_extensions/side-chat/README.zh.md +40 -0
  28. data/lib/clacky/default_extensions/side-chat/api/handler.rb +90 -0
  29. data/lib/clacky/default_extensions/side-chat/api/runtime.rb +411 -0
  30. data/lib/clacky/default_extensions/side-chat/ext.yml +16 -0
  31. data/lib/clacky/default_extensions/side-chat/icon.svg +14 -0
  32. data/lib/clacky/default_extensions/side-chat/panels/side-chat/view.js +779 -0
  33. data/lib/clacky/default_extensions/terminal/README.md +36 -0
  34. data/lib/clacky/default_extensions/terminal/README.zh.md +36 -0
  35. data/lib/clacky/default_extensions/terminal/api/handler.rb +121 -0
  36. data/lib/clacky/default_extensions/terminal/api/runtime.rb +397 -0
  37. data/lib/clacky/default_extensions/terminal/ext.yml +16 -0
  38. data/lib/clacky/default_extensions/terminal/icon.svg +13 -0
  39. data/lib/clacky/default_extensions/terminal/panels/terminal/view.js +351 -0
  40. data/lib/clacky/default_extensions/terminal/vendor/LICENSE +21 -0
  41. data/lib/clacky/default_extensions/terminal/vendor/addon-fit.js +2 -0
  42. data/lib/clacky/default_extensions/terminal/vendor/xterm.css +218 -0
  43. data/lib/clacky/default_extensions/terminal/vendor/xterm.js +2 -0
  44. data/lib/clacky/default_skills/media-gen/SKILL.md +30 -9
  45. data/lib/clacky/extension/api_extension.rb +12 -0
  46. data/lib/clacky/locales/en.rb +14 -11
  47. data/lib/clacky/locales/i18n.rb +25 -0
  48. data/lib/clacky/locales/zh.rb +14 -11
  49. data/lib/clacky/media/base.rb +11 -1
  50. data/lib/clacky/media/openai_compat.rb +271 -3
  51. data/lib/clacky/message_format/open_ai.rb +17 -0
  52. data/lib/clacky/prompts/base.md +3 -0
  53. data/lib/clacky/providers.rb +33 -20
  54. data/lib/clacky/reasoning_levels.rb +75 -0
  55. data/lib/clacky/server/channel/channel_ui_controller.rb +12 -5
  56. data/lib/clacky/server/git_panel.rb +40 -18
  57. data/lib/clacky/server/http_server.rb +62 -71
  58. data/lib/clacky/server/session_registry.rb +3 -0
  59. data/lib/clacky/ui2/markdown_renderer.rb +153 -0
  60. data/lib/clacky/ui2/strings_cjk_patch.rb +134 -124
  61. data/lib/clacky/utils/file_link_normalizer.rb +30 -3
  62. data/lib/clacky/utils/frontmatter.rb +63 -0
  63. data/lib/clacky/utils/model_pricing.rb +67 -9
  64. data/lib/clacky/version.rb +1 -1
  65. data/lib/clacky/web/app.css +722 -274
  66. data/lib/clacky/web/app.js +2 -0
  67. data/lib/clacky/web/components/chat-composer.js +504 -0
  68. data/lib/clacky/web/components/chat-navigator.js +1 -1
  69. data/lib/clacky/web/components/model-picker.js +319 -20
  70. data/lib/clacky/web/components/quote-select.js +97 -39
  71. data/lib/clacky/web/core/aside.js +137 -27
  72. data/lib/clacky/web/core/ext.js +658 -81
  73. data/lib/clacky/web/features/brand/store.js +0 -4
  74. data/lib/clacky/web/features/brand/view.js +2 -99
  75. data/lib/clacky/web/features/extensions/store.js +3 -1
  76. data/lib/clacky/web/features/extensions/view.js +14 -15
  77. data/lib/clacky/web/features/new-session/store.js +4 -0
  78. data/lib/clacky/web/features/new-session/view.js +27 -4
  79. data/lib/clacky/web/features/skills/store.js +7 -5
  80. data/lib/clacky/web/features/skills/view.js +65 -16
  81. data/lib/clacky/web/features/version/view.js +1 -1
  82. data/lib/clacky/web/features/workspace/store.js +7 -3
  83. data/lib/clacky/web/features/workspace/view.js +46 -5
  84. data/lib/clacky/web/i18n.js +104 -58
  85. data/lib/clacky/web/index.html +21 -22
  86. data/lib/clacky/web/lib/box-diagram.js +239 -0
  87. data/lib/clacky/web/sessions.js +117 -151
  88. data/lib/clacky/web/settings.js +23 -16
  89. data/lib/clacky/web/ws-dispatcher.js +4 -1
  90. data/lib/clacky.rb +2 -0
  91. metadata +24 -1
@@ -0,0 +1,779 @@
1
+ // ── Official panel: side chat ─────────────────────────────────────────────
2
+ //
3
+ // A read-only branch of the conversation shown in the right-hand aside. The
4
+ // user opens it mid-task to ask about something they did not understand,
5
+ // without scrolling to the composer and interrupting the main thread.
6
+ //
7
+ // The branch itself lives in the openclacky process (see api/runtime.rb): a
8
+ // fork_subagent of the session's agent with the write tools denied. This file
9
+ // owns only the view, and it rides the main WebSocket — the frames are
10
+ // namespaced `ext.side_chat.`, so no second socket is needed.
11
+ //
12
+ // Rendering reuses the main conversation's vocabulary on purpose: the same
13
+ // `.msg` / `.msg-user` / `.msg-assistant` / `.tool-group` classes, the same
14
+ // markdown pipeline (Sessions.renderMarkdown), the same composer component
15
+ // (ChatComposer). A message has to read the same in both places, and the quote
16
+ // chips have to behave the same, which only happens if the DOM does too.
17
+ // ─────────────────────────────────────────────────────────────────────────
18
+
19
+ (() => {
20
+ if (!window.Clacky || !Clacky.ext) return;
21
+
22
+ const API_BASE = "/api/ext/side-chat";
23
+ const WS_PREFIX = "ext.side_chat.";
24
+ const SLOT = "session.aside";
25
+ const TAB_ID = "side-chat";
26
+ const STREAM_RENDER_MS = 60;
27
+ const BOTTOM_SLACK = 48;
28
+
29
+ const t = (key, fallback, params) => {
30
+ const value = (typeof I18n !== "undefined") ? I18n.t(key, params) : null;
31
+ return (value && value !== key) ? value : fallback;
32
+ };
33
+
34
+ const session = () => (window.Clacky && Clacky.ext && Clacky.ext.context && Clacky.ext.context.sessionId) || null;
35
+ const sessionsApi = () => (window.Clacky && Clacky.Sessions) || null;
36
+ const toolViewApi = () => {
37
+ const api = sessionsApi();
38
+ return (api && api.toolView) || null;
39
+ };
40
+
41
+ const runtimes = new Map(); // sessionId -> runtime (one branch per session)
42
+
43
+ function el(tag, className, text) {
44
+ const node = document.createElement(tag);
45
+ if (className) node.className = className;
46
+ if (text != null) node.textContent = text;
47
+ return node;
48
+ }
49
+
50
+ function markdown(text) {
51
+ const api = sessionsApi();
52
+ if (api && typeof api.renderMarkdown === "function") return api.renderMarkdown(text || "");
53
+ const node = el("div");
54
+ node.textContent = text || "";
55
+ return escapeHtml(node.innerHTML);
56
+ }
57
+
58
+ function referenceBadges(references) {
59
+ const api = sessionsApi();
60
+ if (!api || typeof api.renderReferenceBadge !== "function") return "";
61
+ return (references || []).map(api.renderReferenceBadge).join(" ");
62
+ }
63
+
64
+ function styles() {
65
+ if (document.getElementById("side-chat-ext-css")) return;
66
+ const style = document.createElement("style");
67
+ style.id = "side-chat-ext-css";
68
+ style.textContent = `
69
+ .sidechat { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
70
+ /* Same scroll container as #messages, sized for a narrow column. */
71
+ .sidechat-body { padding: 0.75rem 0.75rem 0.5rem; gap: 0.5rem; }
72
+ .sidechat-body .msg { max-width: 100%; font-size: 0.85rem; padding: 0.5rem 0.75rem; }
73
+ .sidechat-body .msg-user-wrap { padding-bottom: 0; }
74
+ .sidechat-body .msg p:first-child { margin-top: 0; }
75
+ .sidechat-body .msg p:last-child { margin-bottom: 0; }
76
+ .sidechat-body .tool-group { max-width: 100%; }
77
+ .sidechat-opening { margin: auto; padding: 1.5rem 1rem; text-align: center; font-size: 0.8rem;
78
+ line-height: 1.6; color: var(--color-text-tertiary); }
79
+ .sidechat-note { font-size: 0.75rem; line-height: 1.5; color: var(--color-text-tertiary);
80
+ padding: 0 0.25rem; }
81
+ .sidechat-note-error { color: var(--color-danger, #dc2626); }
82
+ .sidechat-foot { flex: none;
83
+ padding: 0.5rem 0.625rem 0.625rem; display: flex; flex-direction: column; }
84
+ .sidechat-composer { flex: none; }
85
+ /* Taller than one line for a comfortable click target; the padding has to
86
+ absorb the extra height, or the line box sticks to the top of the box
87
+ and any chip in it reads as sitting too high. */
88
+ .sidechat-composer .composer-input { min-height: 2.25rem; padding-top: 0.375rem; padding-bottom: 0.375rem; }
89
+ `;
90
+ document.head.appendChild(style);
91
+ }
92
+
93
+ // ── Runtime ──────────────────────────────────────────────────────────────
94
+
95
+ function ensureRuntime(sessionId) {
96
+ let rt = runtimes.get(sessionId);
97
+ if (rt) return rt;
98
+ rt = {
99
+ sessionId: sessionId,
100
+ chatId: null,
101
+ status: "idle", // idle | opening | running
102
+ entries: [],
103
+ streaming: null,
104
+ progress: null,
105
+ progressEl: null,
106
+ progressTimer: null,
107
+ notes: [],
108
+ pendingQuotes: [],
109
+ pendingFresh: false,
110
+ forking: false,
111
+ queued: null,
112
+ el: null,
113
+ opening: null,
114
+ renderTimer: null,
115
+ pinBottom: true,
116
+ disposed: false,
117
+ };
118
+ runtimes.set(sessionId, rt);
119
+ bindWs();
120
+ return rt;
121
+ }
122
+
123
+ function create(ctx) {
124
+ const sessionId = ctx && ctx.sessionId;
125
+ if (!sessionId) return null;
126
+ const rt = ensureRuntime(sessionId);
127
+ rt.dispose = () => {
128
+ if (rt.disposed) return;
129
+ rt.disposed = true;
130
+ if (rt.renderTimer) { clearTimeout(rt.renderTimer); rt.renderTimer = null; }
131
+ clearProgress(rt);
132
+ if (rt.chatId && window.Clacky && Clacky.WS) {
133
+ Clacky.WS.send({ type: "ext.side_chat.close", chat_id: rt.chatId });
134
+ }
135
+ rt.chatId = null;
136
+ rt.el = null;
137
+ runtimes.delete(sessionId);
138
+ };
139
+ return rt;
140
+ }
141
+
142
+ // ── Transport ────────────────────────────────────────────────────────────
143
+
144
+ function wsSend(frame) {
145
+ if (!window.Clacky || !Clacky.WS) return;
146
+ Clacky.WS.send(frame);
147
+ }
148
+
149
+ function attach(rt) {
150
+ if (!rt.chatId) return;
151
+ wsSend({ type: "ext.side_chat.attach", chat_id: rt.chatId });
152
+ }
153
+
154
+ // The socket has no unsubscribe, so the extension subscribes once for the
155
+ // module and routes each frame to the runtime that owns the branch. Binding a
156
+ // handler per runtime would leave a dead closure behind on every session
157
+ // switch, all of them still running their filter on every frame.
158
+ let wsBound = false;
159
+ function bindWs() {
160
+ if (wsBound || !window.Clacky || !Clacky.WS) return;
161
+ wsBound = true;
162
+ Clacky.WS.onEvent(onWsEvent);
163
+ }
164
+
165
+ function onWsEvent(event) {
166
+ if (!event || typeof event.type !== "string") return;
167
+
168
+ if (event.type === "_ws_connected") {
169
+ // A reconnect loses every panel's binding; the server drops the
170
+ // connection reference with it.
171
+ runtimes.forEach((rt) => { if (!rt.disposed && rt.chatId) attach(rt); });
172
+ return;
173
+ }
174
+ if (!event.type.startsWith(WS_PREFIX)) return;
175
+ runtimes.forEach((rt) => onServerEvent(rt, event));
176
+ }
177
+
178
+ // Opens the branch. `fresh` drops the existing one so the panel catches up
179
+ // with the main thread when it has moved on.
180
+ function openChat(rt, options) {
181
+ const fresh = !!(options && options.fresh);
182
+ if (rt.opening) return rt.opening;
183
+ if (rt.chatId && !fresh) {
184
+ attach(rt);
185
+ return Promise.resolve();
186
+ }
187
+
188
+ rt.status = "opening";
189
+ if (fresh) rt.forking = true;
190
+ scheduleRender(rt, 0);
191
+
192
+ rt.opening = fetch(API_BASE + "/open", {
193
+ method: "POST",
194
+ headers: { "Content-Type": "application/json" },
195
+ body: JSON.stringify({ session_id: rt.sessionId, fresh: fresh }),
196
+ })
197
+ .then((response) => response.json().catch(() => ({})).then((data) => ({ response, data })))
198
+ .then(({ response, data }) => {
199
+ if (!response.ok || !data.chat_id) {
200
+ throw new Error(data.error || ("HTTP " + response.status));
201
+ }
202
+ if (fresh) {
203
+ rt.entries = [];
204
+ rt.streaming = null;
205
+ rt.notes = [];
206
+ rt.pinBottom = true;
207
+ clearProgress(rt);
208
+ }
209
+ rt.chatId = data.chat_id;
210
+ rt.status = "idle";
211
+ attach(rt);
212
+ })
213
+ .catch((error) => {
214
+ rt.status = "idle";
215
+ rt.notes.push({
216
+ kind: "error",
217
+ text: t("sidechat.openFailed", "Could not open the side chat: {{error}}", {
218
+ error: (error && error.message) || String(error),
219
+ }),
220
+ });
221
+ })
222
+ .then(() => {
223
+ rt.opening = null;
224
+ rt.forking = false;
225
+ renderMessages(rt);
226
+ flushQueued(rt);
227
+ if (rt.el && rt.el.composer) rt.el.composer.focus();
228
+ });
229
+
230
+ return rt.opening;
231
+ }
232
+
233
+ function flushQueued(rt) {
234
+ const queued = rt.queued;
235
+ if (!queued || !rt.chatId) return;
236
+ rt.queued = null;
237
+ queued.forEach((payload) => deliver(rt, payload));
238
+ }
239
+
240
+ function deliver(rt, payload) {
241
+ // A quote picked in the main conversation promises nothing until the user
242
+ // actually sends: the old branch is replaced here, not when the quote was
243
+ // clicked, so an abandoned quote leaves the conversation untouched.
244
+ const refork = !!rt.pendingFresh && !!rt.chatId;
245
+ if (refork || rt.forking || !rt.chatId) {
246
+ rt.pendingFresh = false;
247
+ // Queued rather than sent: the new branch does not exist until /open
248
+ // answers, and a second message in that window must join the queue
249
+ // instead of hitting the branch being replaced.
250
+ rt.queued = (rt.queued || []).concat([payload]);
251
+ if (!rt.forking) openChat(rt, { fresh: refork });
252
+ return;
253
+ }
254
+ wsSend({
255
+ type: "ext.side_chat.send",
256
+ chat_id: rt.chatId,
257
+ text: payload.text || "",
258
+ files: payload.files || [],
259
+ references: payload.references || [],
260
+ });
261
+ }
262
+
263
+ function onServerEvent(rt, event) {
264
+ if (!event || rt.disposed) return;
265
+ if (typeof event.type !== "string" || !event.type.startsWith(WS_PREFIX)) return;
266
+ if (event.chat_id !== rt.chatId) return;
267
+
268
+ switch (event.type.slice(WS_PREFIX.length)) {
269
+ case "attached":
270
+ rt.status = event.running ? "running" : "idle";
271
+ renderMessages(rt);
272
+ break;
273
+
274
+ case "user":
275
+ rt.streaming = null;
276
+ // The main conversation force-scrolls on a user message ("user just
277
+ // sent one"); reading history must not hide the question you asked.
278
+ rt.pinBottom = true;
279
+ rt.entries.push({
280
+ kind: "user",
281
+ text: event.text || "",
282
+ references: event.references || [],
283
+ files: event.files || [],
284
+ });
285
+ renderMessages(rt);
286
+ break;
287
+
288
+ case "event":
289
+ onAgentEvent(rt, event.event || {});
290
+ break;
291
+
292
+ case "turn":
293
+ rt.status = "idle";
294
+ rt.streaming = null;
295
+ clearProgress(rt);
296
+ renderMessages(rt);
297
+ break;
298
+
299
+ case "busy":
300
+ rt.status = "running";
301
+ renderMessages(rt);
302
+ break;
303
+
304
+ case "gone":
305
+ rt.chatId = null;
306
+ rt.streaming = null;
307
+ rt.status = "idle";
308
+ clearProgress(rt);
309
+ rt.notes.push({ kind: "note", text: t("sidechat.gone", "This side chat expired — open it again to start a new one.") });
310
+ renderMessages(rt);
311
+ break;
312
+
313
+ default:
314
+ break;
315
+ }
316
+ }
317
+
318
+ function onAgentEvent(rt, event) {
319
+ switch (event.type) {
320
+ case "assistant_message_delta":
321
+ if (!rt.streaming) rt.streaming = { text: "" };
322
+ rt.streaming.text += event.delta || "";
323
+ scheduleRender(rt, STREAM_RENDER_MS);
324
+ break;
325
+
326
+ case "assistant_message_stream_end":
327
+ // The final text arrives as `assistant_message`; dropping the preview
328
+ // here keeps the swap from showing the text twice.
329
+ if (rt.streaming) { rt.streaming = null; scheduleRender(rt); }
330
+ break;
331
+
332
+ case "assistant_message":
333
+ rt.streaming = null;
334
+ clearProgress(rt);
335
+ if (event.content && String(event.content).trim()) {
336
+ rt.entries.push({ kind: "assistant", text: event.content });
337
+ }
338
+ scheduleRender(rt);
339
+ break;
340
+
341
+ case "tool_call":
342
+ rt.entries.push({
343
+ kind: "tool",
344
+ name: event.name || "tool",
345
+ args: event.args,
346
+ summary: event.summary || "",
347
+ state: "running",
348
+ result: null,
349
+ ui: null,
350
+ expanded: false,
351
+ });
352
+ rt.status = "running";
353
+ clearProgress(rt);
354
+ scheduleRender(rt);
355
+ break;
356
+
357
+ case "tool_result": {
358
+ const running = lastRunningTool(rt);
359
+ if (running) {
360
+ running.state = "ok";
361
+ running.result = (event.result == null) ? "" : String(event.result);
362
+ running.ui = event.ui || null;
363
+ }
364
+ scheduleRender(rt);
365
+ break;
366
+ }
367
+
368
+ case "tool_error":
369
+ rt.notes.push({ kind: "note", text: "⚠ Tool error: " + String(event.error || event.message || "") });
370
+ scheduleRender(rt);
371
+ break;
372
+
373
+ case "progress":
374
+ if (event.phase === "active" || event.status === "start") {
375
+ const previous = rt.progress;
376
+ rt.progress = {
377
+ text: event.message || "",
378
+ type: event.progress_type || "thinking",
379
+ metadata: event.metadata || {},
380
+ startedAt: event.started_at || (previous && previous.startedAt) || Date.now(),
381
+ lastChunkAt: Date.now(),
382
+ };
383
+ startProgressTicker(rt);
384
+ } else {
385
+ clearProgress(rt);
386
+ }
387
+ scheduleRender(rt);
388
+ break;
389
+
390
+ case "error":
391
+ rt.streaming = null;
392
+ clearProgress(rt);
393
+ rt.notes.push({
394
+ kind: "error",
395
+ text: t("sidechat.failed", "Side chat failed: {{error}}", {
396
+ error: event.message || "",
397
+ }),
398
+ });
399
+ scheduleRender(rt);
400
+ break;
401
+
402
+ // info / warning / tool_args: transient chatter that a narrow panel has no
403
+ // room for. The main conversation still shows the full trail.
404
+ default:
405
+ break;
406
+ }
407
+ }
408
+
409
+ function lastRunningTool(rt) {
410
+ for (let i = rt.entries.length - 1; i >= 0; i -= 1) {
411
+ const entry = rt.entries[i];
412
+ if (entry.kind === "tool") return entry.state === "running" ? entry : null;
413
+ if (entry.kind === "assistant" || entry.kind === "user") return null;
414
+ }
415
+ return null;
416
+ }
417
+
418
+ // ── Progress line ────────────────────────────────────────────────────────
419
+ //
420
+ // Same line the main conversation shows ("思考中… (3s · 120 tok)"): the
421
+ // formatter is borrowed from Sessions rather than reimplemented, so elapsed
422
+ // seconds, token counts and the model's own label read identically in both
423
+ // places instead of drifting apart.
424
+
425
+ function progressLine(rt) {
426
+ const p = rt.progress;
427
+ if (!p) return "";
428
+ const api = sessionsApi();
429
+ const label = (api && typeof api._buildDisplayText === "function")
430
+ ? api._buildDisplayText(p.text, p.type, p.metadata)
431
+ : (p.text || t("chat.thinking", "Thinking…"));
432
+ if (api && typeof api._composeProgressLine === "function") {
433
+ return api._composeProgressLine(label, p.startedAt, p.metadata, p.lastChunkAt);
434
+ }
435
+ const secs = Math.floor((Date.now() - p.startedAt) / 1000);
436
+ return secs > 0 ? label.replace(/(?:\.{2,}|…)\s*$/, "") + "… (" + secs + "s)" : label;
437
+ }
438
+
439
+ // Only the text of the line ticks, not the whole body: a full render would
440
+ // re-parse every markdown bubble four times a second.
441
+ function startProgressTicker(rt) {
442
+ if (rt.progressTimer) return;
443
+ rt.progressTimer = setInterval(() => {
444
+ const node = rt.progressEl;
445
+ if (!node || !node.isConnected) return;
446
+ node.textContent = progressLine(rt);
447
+ }, 250);
448
+ }
449
+
450
+ function clearProgress(rt) {
451
+ if (rt.progressTimer) {
452
+ clearInterval(rt.progressTimer);
453
+ rt.progressTimer = null;
454
+ }
455
+ rt.progress = null;
456
+ rt.progressEl = null;
457
+ }
458
+
459
+ // ── Rendering ────────────────────────────────────────────────────────────
460
+
461
+ function scheduleRender(rt, delay) {
462
+ if (rt.disposed || !rt.el) return;
463
+ if (rt.renderTimer) return;
464
+ rt.renderTimer = setTimeout(() => {
465
+ rt.renderTimer = null;
466
+ renderMessages(rt);
467
+ }, delay || 16);
468
+ }
469
+
470
+ // Status only ever changes together with a render, so the composer's
471
+ // send/stop swap rides along instead of being wired into every event.
472
+ function syncComposer(rt) {
473
+ const composer = rt.el && rt.el.composer;
474
+ if (composer) composer.setRunning(rt.status === "running");
475
+ }
476
+
477
+ const nearBottom = (node) => node.scrollHeight - node.scrollTop - node.clientHeight < BOTTOM_SLACK;
478
+
479
+ // The host mounts a tab body hidden and flips .active only after render()
480
+ // returns, so on the first pass the body has no height and a scrollTop write
481
+ // is dropped. The intent to stay pinned therefore lives on the runtime, not
482
+ // in one assignment: the resize observer in render() replays it once the
483
+ // panel is actually laid out. A body with no height yet is left alone.
484
+ function scrollToBottom(rt) {
485
+ const body = rt.el && rt.el.body;
486
+ if (body && body.clientHeight > 0) body.scrollTop = body.scrollHeight;
487
+ }
488
+
489
+ function renderMessages(rt) {
490
+ const body = rt.el && rt.el.body;
491
+ if (!body) return;
492
+ syncComposer(rt);
493
+
494
+ const frag = document.createDocumentFragment();
495
+
496
+ if (rt.status === "opening" && !rt.entries.length && !rt.streaming && !rt.notes.length) {
497
+ const opening = el("div", "sidechat-opening");
498
+ opening.textContent = t("sidechat.opening", "Opening…");
499
+ frag.appendChild(opening);
500
+ }
501
+
502
+ let index = 0;
503
+ while (index < rt.entries.length) {
504
+ const entry = rt.entries[index];
505
+ if (entry.kind !== "tool") {
506
+ frag.appendChild(renderEntry(entry));
507
+ index += 1;
508
+ continue;
509
+ }
510
+ const run = [];
511
+ while (index < rt.entries.length && rt.entries[index].kind === "tool") {
512
+ run.push(rt.entries[index]);
513
+ index += 1;
514
+ }
515
+ frag.appendChild(renderToolRun(rt, run));
516
+ }
517
+
518
+ if (rt.streaming && rt.streaming.text) {
519
+ const bubble = el("div", "msg msg-assistant");
520
+ bubble.innerHTML = markdown(rt.streaming.text);
521
+ frag.appendChild(bubble);
522
+ }
523
+
524
+ if (rt.progress) {
525
+ const line = el("div", "progress-msg", progressLine(rt));
526
+ rt.progressEl = line;
527
+ frag.appendChild(line);
528
+ } else {
529
+ rt.progressEl = null;
530
+ }
531
+
532
+ rt.notes.forEach((note) => {
533
+ frag.appendChild(el("div", note.kind === "error" ? "sidechat-note sidechat-note-error" : "sidechat-note", note.text));
534
+ });
535
+
536
+ body.replaceChildren(frag);
537
+ if (rt.pinBottom) scrollToBottom(rt);
538
+ }
539
+
540
+ function renderEntry(entry) {
541
+ if (entry.kind === "user") {
542
+ const wrap = el("div", "msg-user-wrap");
543
+ const bubble = el("div", "msg msg-user");
544
+ const badges = referenceBadges(entry.references);
545
+ // marked appends a newline after the closing tag; the bubble is pre-wrap,
546
+ // so that newline would render as an empty trailing line.
547
+ const text = entry.text ? markdown(entry.text).replace(/\s+$/, "") : "";
548
+ const attachments = (entry.files || []).map((file) =>
549
+ `<span class="msg-pdf-badge"><span class="msg-pdf-badge-info"><span class="msg-pdf-badge-name">${escapeHtml(file.name || "")}</span></span></span>`
550
+ ).join(" ");
551
+ bubble.innerHTML =
552
+ (badges ? badges + (text || attachments ? "<br>" : "") : "") +
553
+ (attachments ? attachments + (text ? "<br>" : "") : "") +
554
+ text;
555
+ wrap.appendChild(bubble);
556
+ return wrap;
557
+ }
558
+
559
+ const bubble = el("div", "msg msg-assistant");
560
+ bubble.innerHTML = markdown(entry.text);
561
+ return bubble;
562
+ }
563
+
564
+ // One group for a run of consecutive tool calls, built with the main
565
+ // conversation's own helpers (Clacky.Sessions.toolView): same rows, same
566
+ // collapse header, same args pane / diff / stdout. The panel re-renders from
567
+ // `entries` on every frame, so the expanded state travels on the entry
568
+ // instead of the DOM.
569
+ function renderToolRun(rt, run) {
570
+ const api = toolViewApi();
571
+ if (!api) return renderToolPlain(run);
572
+
573
+ const group = api.makeGroup();
574
+ const promoted = [];
575
+ run.forEach((entry) => {
576
+ const item = api.addCall(group, entry.name, entry.args, entry.summary);
577
+ if (rt) item.dataset.sidechatIndex = String(rt.entries.indexOf(entry));
578
+ if (entry.state === "ok") {
579
+ api.complete(item, entry.result, { ui: entry.ui });
580
+ if (entry.ui && api.isPromoted && api.isPromoted(entry.ui)) promoted.push(entry.ui);
581
+ }
582
+ if (entry.expanded) api.toggleDetails(item);
583
+ });
584
+ if (run.every((entry) => entry.state !== "running")) api.collapse(group);
585
+ if (run[0].runExpanded) group.classList.add("expanded");
586
+ if (!promoted.length || !api.promoteResult) return group;
587
+ // Cards sit after the run, where the main conversation puts them.
588
+ const out = document.createDocumentFragment();
589
+ out.appendChild(group);
590
+ promoted.forEach((ui) => api.promoteResult(out, ui));
591
+ return out;
592
+ }
593
+
594
+ // Only reachable if sessions.js is an older build without the export.
595
+ function renderToolPlain(run) {
596
+ const group = el("div", "tool-group expanded");
597
+ const body = el("div", "tool-group-body");
598
+ run.forEach((entry) => {
599
+ const item = el("div", "tool-item");
600
+ const header = el("div", "tool-item-header");
601
+ header.appendChild(el("span", "tool-item-name", "⚙ " + (entry.summary || entry.name)));
602
+ header.appendChild(el("span", entry.state === "running" ? "tool-item-status running" : "tool-item-status ok",
603
+ entry.state === "running" ? "…" : "✓"));
604
+ item.appendChild(header);
605
+ body.appendChild(item);
606
+ });
607
+ group.appendChild(body);
608
+ return group;
609
+ }
610
+
611
+ // ── Panel body ───────────────────────────────────────────────────────────
612
+
613
+ function render(container, ctx, runtime) {
614
+ if (!runtime || !container) return undefined;
615
+ const rt = runtime;
616
+ styles();
617
+ container.replaceChildren();
618
+
619
+ const root = el("div", "sidechat");
620
+ const body = el("div", "chat-messages-scroll sidechat-body");
621
+ const foot = el("div", "sidechat-foot");
622
+ const composerHost = el("div", "sidechat-composer");
623
+ foot.appendChild(composerHost);
624
+ root.appendChild(body);
625
+ root.appendChild(foot);
626
+ container.appendChild(root);
627
+
628
+ rt.el = { root: root, body: body, composerHost: composerHost, composer: null };
629
+
630
+ // Reading the user's scroll is the only input: leaving the bottom unpins,
631
+ // returning pins. Every render() below appends to the same body, so the
632
+ // pin has to be re-applied there rather than computed from a DOM that is
633
+ // about to be replaced.
634
+ body.addEventListener("scroll", () => { rt.pinBottom = nearBottom(body); });
635
+ if (typeof ResizeObserver === "function") {
636
+ // Fires when the host reveals the tab (display:none → laid out) and on
637
+ // every width/padding change, which is exactly when a dropped scrollTop
638
+ // can finally be applied.
639
+ const observer = new ResizeObserver(() => { if (rt.pinBottom) scrollToBottom(rt); });
640
+ observer.observe(body);
641
+ rt.el.observer = observer;
642
+ }
643
+
644
+ // The main conversation delegates tool-header clicks from #messages; the
645
+ // panel lives outside that node, so it needs its own delegation to open
646
+ // the args / stdout pane.
647
+ body.addEventListener("click", (e) => {
648
+ const groupHeader = e.target.closest && e.target.closest(".tool-group-header");
649
+ if (groupHeader) {
650
+ // The group's own handler already toggled it; remember the choice so
651
+ // the next render does not snap a run the user opened back shut.
652
+ const group = groupHeader.closest(".tool-group");
653
+ const first = group && group.querySelector(".tool-item");
654
+ const entry = first && rt.entries[Number(first.dataset.sidechatIndex)];
655
+ if (entry) entry.runExpanded = group.classList.contains("expanded");
656
+ return;
657
+ }
658
+ const header = e.target.closest && e.target.closest(".tool-item-header.tool-item-expandable");
659
+ if (!header) return;
660
+ e.preventDefault();
661
+ e.stopPropagation();
662
+ const item = header.closest(".tool-item");
663
+ const api = toolViewApi();
664
+ if (api) api.toggleDetails(item);
665
+ const entry = rt.entries[Number(item.dataset.sidechatIndex)];
666
+ if (entry) entry.expanded = item.classList.contains("expanded");
667
+ });
668
+
669
+ if (window.Clacky && Clacky.ChatComposer) {
670
+ rt.el.composer = Clacky.ChatComposer.create({
671
+ mount: composerHost,
672
+ slash: false,
673
+ dropZone: composerHost,
674
+ placeholder: () => t("sidechat.placeholder", "Ask about this conversation…"),
675
+ hasExtra: (input) => QuoteSelect.list(input).length > 0,
676
+ onSend: (payload) => sendFromComposer(rt, payload),
677
+ onStop: () => interrupt(rt),
678
+ });
679
+ }
680
+
681
+ renderMessages(rt);
682
+ flushQuotes(rt);
683
+ // The branch is forked on the first send, not on open: a panel the user
684
+ // merely looked at must not pin a snapshot of the conversation.
685
+ if (rt.chatId) attach(rt);
686
+
687
+ return () => {
688
+ // Leaving the tab keeps the branch alive server-side (it is reaped after
689
+ // an hour idle) but drops this connection's binding.
690
+ if (rt.chatId) wsSend({ type: "ext.side_chat.detach", chat_id: rt.chatId });
691
+ if (rt.el && rt.el.observer) rt.el.observer.disconnect();
692
+ rt.el = null;
693
+ };
694
+ }
695
+
696
+ function sendFromComposer(rt, payload) {
697
+ const input = rt.el && rt.el.composer && rt.el.composer.input;
698
+ // Read the quote chips while the composer still holds them: submit() calls
699
+ // onSend before clearing.
700
+ const references = input ? QuoteSelect.toReferences(input) : [];
701
+ deliver(rt, {
702
+ text: (payload && payload.text) || "",
703
+ files: (payload && payload.files) || [],
704
+ references: references,
705
+ });
706
+ }
707
+
708
+ function interrupt(rt) {
709
+ if (!rt.chatId) return;
710
+ wsSend({ type: "ext.side_chat.interrupt", chat_id: rt.chatId });
711
+ }
712
+
713
+ // Quotes selected in the main conversation land in this composer as chips, so
714
+ // the panel's first question carries the passage the user was looking at.
715
+ function flushQuotes(rt) {
716
+ const input = rt.el && rt.el.composer && rt.el.composer.input;
717
+ if (!input || !input.isConnected || !rt.pendingQuotes.length) return;
718
+ const pending = rt.pendingQuotes;
719
+ rt.pendingQuotes = [];
720
+ pending.forEach((snap) => QuoteSelect.stage(snap, input));
721
+ }
722
+
723
+ // ── Entry point for the selection bar ────────────────────────────────────
724
+
725
+ function ask(quote) {
726
+ const sessionId = session();
727
+ if (!sessionId) return;
728
+ const rt = ensureRuntime(sessionId);
729
+ if (quote && quote.text) rt.pendingQuotes.push({ role: quote.role, index: quote.index, text: quote.text });
730
+ reveal();
731
+ if (rt.chatId) {
732
+ // A quote picked in the main conversation asks about the thread as it
733
+ // stands now, so the send that follows starts a new branch — that is how
734
+ // a side chat catches up after the main thread has moved on. The reset
735
+ // waits for the send: forking on the click would wipe a conversation the
736
+ // user only meant to look at. Chips already staged in the composer
737
+ // survive either way.
738
+ rt.pendingFresh = true;
739
+ } else {
740
+ rt.entries = [];
741
+ rt.streaming = null;
742
+ rt.notes = [];
743
+ rt.pinBottom = true;
744
+ renderMessages(rt);
745
+ }
746
+ // activateTab paints the body before it returns, so the composer is here by
747
+ // now; when it is not (the slot has nothing to paint), the chip stays
748
+ // pending and lands on the next render instead of spinning on frames.
749
+ flushQuotes(rt);
750
+ if (rt.el && rt.el.composer) rt.el.composer.focus();
751
+ }
752
+
753
+ function reveal() {
754
+ const api = window.Clacky && Clacky.Aside;
755
+ if (api && api.open) api.open();
756
+ // The host's activateTab runs the whole paint synchronously, so this either
757
+ // shows the panel now or never: a false return means the slot has nothing
758
+ // registered to paint, and asking again on the next frame asks the same
759
+ // question.
760
+ if (window.Clacky && Clacky.ext) Clacky.ext.activateTab(SLOT, TAB_ID);
761
+ }
762
+
763
+ function available() {
764
+ return !!(window.Clacky && Clacky.WS && session());
765
+ }
766
+
767
+ Clacky.SideChat = { ask: ask, available: available };
768
+
769
+ Clacky.ext.ui.mount(SLOT, { create: create, render: render }, {
770
+ order: 34,
771
+ tab: {
772
+ id: TAB_ID,
773
+ label: () => t("sidechat.tab", "Side chat"),
774
+ icon:
775
+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
776
+ '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><path d="M13 8H7"/><path d="M17 12H7"/></svg>',
777
+ },
778
+ });
779
+ })();