@clagentic/console 1.0.0-beta.1

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 (221) hide show
  1. package/CREDITS.md +3 -0
  2. package/LICENSE +21 -0
  3. package/README.md +250 -0
  4. package/bin/cli.js +2812 -0
  5. package/lib/agents-favorites.js +164 -0
  6. package/lib/agents.js +282 -0
  7. package/lib/ask-user-mcp-server.js +120 -0
  8. package/lib/browser-mcp-server.js +484 -0
  9. package/lib/build-user-env.js +63 -0
  10. package/lib/certs/fullchain.pem +47 -0
  11. package/lib/certs/privkey.pem +5 -0
  12. package/lib/cli-sessions.js +265 -0
  13. package/lib/codex-defaults.js +18 -0
  14. package/lib/config.js +332 -0
  15. package/lib/crisis-safety.js +60 -0
  16. package/lib/daemon-projects.js +164 -0
  17. package/lib/daemon.js +1602 -0
  18. package/lib/dm.js +128 -0
  19. package/lib/ipc.js +125 -0
  20. package/lib/ipv4-only.js +39 -0
  21. package/lib/mcp-local.js +385 -0
  22. package/lib/notes.js +141 -0
  23. package/lib/os-users.js +529 -0
  24. package/lib/pages.js +1325 -0
  25. package/lib/project-connection.js +302 -0
  26. package/lib/project-external-trigger.js +236 -0
  27. package/lib/project-file-watch.js +120 -0
  28. package/lib/project-filesystem.js +528 -0
  29. package/lib/project-http.js +753 -0
  30. package/lib/project-image.js +95 -0
  31. package/lib/project-knowledge.js +88 -0
  32. package/lib/project-loop.js +1304 -0
  33. package/lib/project-mcp.js +374 -0
  34. package/lib/project-memory.js +39 -0
  35. package/lib/project-notifications.js +262 -0
  36. package/lib/project-sessions.js +1581 -0
  37. package/lib/project-user-mention.js +193 -0
  38. package/lib/project-user-message.js +628 -0
  39. package/lib/project.js +1303 -0
  40. package/lib/public/app.js +1031 -0
  41. package/lib/public/apple-touch-icon.png +0 -0
  42. package/lib/public/claude-code-avatar.png +0 -0
  43. package/lib/public/codex-avatar.png +0 -0
  44. package/lib/public/console-icon.png +0 -0
  45. package/lib/public/css/admin.css +736 -0
  46. package/lib/public/css/agent-picker.css +119 -0
  47. package/lib/public/css/base.css +235 -0
  48. package/lib/public/css/channel-layout.css +441 -0
  49. package/lib/public/css/command-palette.css +559 -0
  50. package/lib/public/css/debate.css +1609 -0
  51. package/lib/public/css/diff.css +139 -0
  52. package/lib/public/css/filebrowser.css +1976 -0
  53. package/lib/public/css/highlight.css +144 -0
  54. package/lib/public/css/home-hub.css +545 -0
  55. package/lib/public/css/icon-strip.css +1856 -0
  56. package/lib/public/css/input.css +1349 -0
  57. package/lib/public/css/loop.css +1248 -0
  58. package/lib/public/css/mention.css +317 -0
  59. package/lib/public/css/menus.css +857 -0
  60. package/lib/public/css/messages.css +1833 -0
  61. package/lib/public/css/mobile-nav.css +1332 -0
  62. package/lib/public/css/notifications-center.css +296 -0
  63. package/lib/public/css/overlays.css +1273 -0
  64. package/lib/public/css/playbook.css +264 -0
  65. package/lib/public/css/profile.css +397 -0
  66. package/lib/public/css/rewind.css +671 -0
  67. package/lib/public/css/scheduler-modal.css +1495 -0
  68. package/lib/public/css/scheduler.css +1420 -0
  69. package/lib/public/css/server-settings.css +909 -0
  70. package/lib/public/css/session-search.css +159 -0
  71. package/lib/public/css/sidebar.css +2012 -0
  72. package/lib/public/css/skills.css +789 -0
  73. package/lib/public/css/sticky-notes.css +854 -0
  74. package/lib/public/css/stt.css +155 -0
  75. package/lib/public/css/title-bar.css +674 -0
  76. package/lib/public/css/tooltip.css +67 -0
  77. package/lib/public/css/user-settings.css +702 -0
  78. package/lib/public/emoji-data.json +1 -0
  79. package/lib/public/favicon-banded-32.png +0 -0
  80. package/lib/public/favicon-banded.png +0 -0
  81. package/lib/public/favicon-dark.svg +32 -0
  82. package/lib/public/favicon.svg +32 -0
  83. package/lib/public/icon-192.png +0 -0
  84. package/lib/public/icon-512.png +0 -0
  85. package/lib/public/icon-banded-76.png +0 -0
  86. package/lib/public/icon-banded-96.png +0 -0
  87. package/lib/public/icon-mono.svg +25 -0
  88. package/lib/public/icons/email/gmail.svg +7 -0
  89. package/lib/public/icons/email/outlook.svg +35 -0
  90. package/lib/public/icons/email/yahoo.svg +1 -0
  91. package/lib/public/index.html +1946 -0
  92. package/lib/public/manifest.json +27 -0
  93. package/lib/public/markdown-worker.js +43 -0
  94. package/lib/public/marked.min.js +6 -0
  95. package/lib/public/modules/admin.js +954 -0
  96. package/lib/public/modules/agent-picker.js +429 -0
  97. package/lib/public/modules/app-connection.js +216 -0
  98. package/lib/public/modules/app-cursors.js +492 -0
  99. package/lib/public/modules/app-dm.js +265 -0
  100. package/lib/public/modules/app-favicon.js +231 -0
  101. package/lib/public/modules/app-header.js +242 -0
  102. package/lib/public/modules/app-home-hub.js +432 -0
  103. package/lib/public/modules/app-loop-ui.js +691 -0
  104. package/lib/public/modules/app-loop-wizard.js +439 -0
  105. package/lib/public/modules/app-messages.js +1415 -0
  106. package/lib/public/modules/app-misc.js +463 -0
  107. package/lib/public/modules/app-notifications.js +651 -0
  108. package/lib/public/modules/app-panels.js +1061 -0
  109. package/lib/public/modules/app-projects.js +875 -0
  110. package/lib/public/modules/app-rate-limit.js +529 -0
  111. package/lib/public/modules/app-rendering.js +739 -0
  112. package/lib/public/modules/app-skills-install.js +285 -0
  113. package/lib/public/modules/avatar.js +36 -0
  114. package/lib/public/modules/command-palette.js +491 -0
  115. package/lib/public/modules/console-logo.js +162 -0
  116. package/lib/public/modules/context-sources.js +365 -0
  117. package/lib/public/modules/diff.js +412 -0
  118. package/lib/public/modules/dom-refs.js +21 -0
  119. package/lib/public/modules/emoji-picker.js +222 -0
  120. package/lib/public/modules/events.js +21 -0
  121. package/lib/public/modules/filebrowser.js +1966 -0
  122. package/lib/public/modules/fileicons.js +172 -0
  123. package/lib/public/modules/icons.js +80 -0
  124. package/lib/public/modules/input.js +1102 -0
  125. package/lib/public/modules/longpress.js +74 -0
  126. package/lib/public/modules/markdown.js +486 -0
  127. package/lib/public/modules/mcp-ui.js +295 -0
  128. package/lib/public/modules/mention.js +1093 -0
  129. package/lib/public/modules/notifications.js +613 -0
  130. package/lib/public/modules/playbook.js +578 -0
  131. package/lib/public/modules/profile.js +594 -0
  132. package/lib/public/modules/project-settings.js +849 -0
  133. package/lib/public/modules/project-switcher.js +375 -0
  134. package/lib/public/modules/qrcode.js +87 -0
  135. package/lib/public/modules/rewind.js +381 -0
  136. package/lib/public/modules/scheduler-config.js +1611 -0
  137. package/lib/public/modules/scheduler-history.js +131 -0
  138. package/lib/public/modules/scheduler.js +1689 -0
  139. package/lib/public/modules/server-settings.js +842 -0
  140. package/lib/public/modules/session-search.js +456 -0
  141. package/lib/public/modules/settings-defaults.js +253 -0
  142. package/lib/public/modules/sidebar-mobile.js +1425 -0
  143. package/lib/public/modules/sidebar-projects.js +2022 -0
  144. package/lib/public/modules/sidebar-sessions.js +1548 -0
  145. package/lib/public/modules/sidebar-users.js +449 -0
  146. package/lib/public/modules/sidebar.js +348 -0
  147. package/lib/public/modules/skills.js +793 -0
  148. package/lib/public/modules/state.js +3 -0
  149. package/lib/public/modules/sticky-notes.js +1221 -0
  150. package/lib/public/modules/store.js +34 -0
  151. package/lib/public/modules/stt.js +266 -0
  152. package/lib/public/modules/terminal.js +987 -0
  153. package/lib/public/modules/theme.js +812 -0
  154. package/lib/public/modules/tool-palette.js +562 -0
  155. package/lib/public/modules/tools.js +2285 -0
  156. package/lib/public/modules/tooltip.js +150 -0
  157. package/lib/public/modules/user-settings.js +544 -0
  158. package/lib/public/modules/utils.js +56 -0
  159. package/lib/public/modules/ws-ref.js +26 -0
  160. package/lib/public/style.css +34 -0
  161. package/lib/public/sw.js +159 -0
  162. package/lib/push.js +149 -0
  163. package/lib/scheduler.js +471 -0
  164. package/lib/sdk-bridge.js +1792 -0
  165. package/lib/sdk-message-processor.js +740 -0
  166. package/lib/sdk-message-queue.js +42 -0
  167. package/lib/sdk-skill-discovery.js +131 -0
  168. package/lib/sdk-worker.js +677 -0
  169. package/lib/server-admin.js +712 -0
  170. package/lib/server-auth.js +737 -0
  171. package/lib/server-dm.js +170 -0
  172. package/lib/server-palette.js +104 -0
  173. package/lib/server-settings.js +553 -0
  174. package/lib/server-skills.js +280 -0
  175. package/lib/server.js +1390 -0
  176. package/lib/session-search.js +693 -0
  177. package/lib/sessions.js +946 -0
  178. package/lib/smtp.js +221 -0
  179. package/lib/terminal-manager.js +219 -0
  180. package/lib/terminal.js +39 -0
  181. package/lib/themes/ayu-light.json +9 -0
  182. package/lib/themes/catppuccin-latte.json +9 -0
  183. package/lib/themes/catppuccin-mocha.json +9 -0
  184. package/lib/themes/clagentic-dark.json +10 -0
  185. package/lib/themes/clagentic-light.json +10 -0
  186. package/lib/themes/dracula.json +9 -0
  187. package/lib/themes/everforest-light.json +9 -0
  188. package/lib/themes/everforest.json +9 -0
  189. package/lib/themes/github-light.json +9 -0
  190. package/lib/themes/gruvbox-dark.json +9 -0
  191. package/lib/themes/gruvbox-light.json +9 -0
  192. package/lib/themes/monokai.json +9 -0
  193. package/lib/themes/nord-light.json +9 -0
  194. package/lib/themes/nord.json +9 -0
  195. package/lib/themes/one-dark.json +9 -0
  196. package/lib/themes/one-light.json +9 -0
  197. package/lib/themes/rose-pine-dawn.json +9 -0
  198. package/lib/themes/rose-pine.json +9 -0
  199. package/lib/themes/solarized-dark.json +9 -0
  200. package/lib/themes/solarized-light.json +9 -0
  201. package/lib/themes/tokyo-night-light.json +9 -0
  202. package/lib/themes/tokyo-night.json +9 -0
  203. package/lib/updater.js +124 -0
  204. package/lib/user-presence.js +92 -0
  205. package/lib/users-auth.js +146 -0
  206. package/lib/users-permissions.js +118 -0
  207. package/lib/users-preferences.js +254 -0
  208. package/lib/users.js +465 -0
  209. package/lib/utils.js +64 -0
  210. package/lib/worktree.js +134 -0
  211. package/lib/ws-schema.js +464 -0
  212. package/lib/yoke/adapters/claude-worker.js +759 -0
  213. package/lib/yoke/adapters/claude.js +1599 -0
  214. package/lib/yoke/adapters/codex.js +1559 -0
  215. package/lib/yoke/codex-app-server.js +352 -0
  216. package/lib/yoke/index.js +319 -0
  217. package/lib/yoke/instructions.js +61 -0
  218. package/lib/yoke/interface.js +98 -0
  219. package/lib/yoke/mcp-bridge-server.js +302 -0
  220. package/lib/yoke/package.json +7 -0
  221. package/package.json +72 -0
@@ -0,0 +1,2285 @@
1
+ import { escapeHtml, copyToClipboard } from './utils.js';
2
+ import { iconHtml, refreshIcons } from './icons.js';
3
+ import { renderMarkdown, highlightCodeBlocks, renderMermaidBlocks } from './markdown.js';
4
+ import { renderUnifiedDiff, renderSplitDiff, renderPatchDiff, reconstructPatchSources } from './diff.js';
5
+ import { openFile } from './filebrowser.js';
6
+ import { getChatLayout } from './theme.js';
7
+ import { store } from './store.js';
8
+ import { VENDOR_NAMES } from './app-rendering.js';
9
+
10
+ var ctx;
11
+
12
+ // During history replay, individual tool renders (todos, file edits, command
13
+ // outputs) must not auto-scroll. The history_done handler arms sticky-bottom
14
+ // which pins the viewport to the true bottom after the whole replay settles.
15
+ // Per-tool scroll calls during replay fight that and re-anchor the user to
16
+ // whichever tool widget grew last (commonly the todo widget).
17
+ function maybeScrollToBottom() {
18
+ if (store.get('replayingHistory')) return;
19
+ if (ctx && ctx.scrollToBottom) ctx.scrollToBottom();
20
+ }
21
+
22
+ // --- Plan mode state ---
23
+ var inPlanMode = false;
24
+ var planContent = null;
25
+ var currentPlanCardEl = null;
26
+
27
+ // --- Todo state ---
28
+ var todoItems = [];
29
+ var todoWidgetEl = null;
30
+ var todoWidgetVisible = true; // whether in-chat widget is in viewport
31
+ var todoObserver = null;
32
+ // When a session is resumed without a live SDK process and still has
33
+ // pending/in_progress items, the widget is rendered in compact mode
34
+ // (header + count only) so it doesn't anchor visual position mid-page
35
+ // or extend the sticky-bottom settle window with a tall element.
36
+ var todoDeadCompact = false;
37
+ var todoMeta = {
38
+ variant: "tasks",
39
+ title: "Tasks",
40
+ icon: "list-checks",
41
+ showProgress: true,
42
+ showCompletedCount: true,
43
+ stickyEnabled: true,
44
+ };
45
+
46
+ // --- Tool tracking ---
47
+ var tools = {};
48
+ var currentThinking = null;
49
+ var thinkingGroup = null; // { el, count, totalDuration }
50
+ var pendingPermissions = {};
51
+
52
+ // --- Tool group tracking ---
53
+ var currentToolGroup = null;
54
+ var toolGroupCounter = 0;
55
+ var toolGroups = {};
56
+
57
+ // --- Tool helpers ---
58
+ var PLAN_MODE_TOOLS = { EnterPlanMode: 1, ExitPlanMode: 1 };
59
+ var TODO_TOOLS = { TodoWrite: 1, TaskCreate: 1, TaskUpdate: 1, TaskList: 1, TaskGet: 1 };
60
+ var HIDDEN_RESULT_TOOLS = { EnterPlanMode: 1, ExitPlanMode: 1, TaskCreate: 1, TaskUpdate: 1, TaskList: 1, TaskGet: 1, TodoWrite: 1 };
61
+
62
+ // --- Tool group helpers ---
63
+ function closeToolGroup() {
64
+ if (currentToolGroup) {
65
+ currentToolGroup.closed = true;
66
+ }
67
+ currentToolGroup = null;
68
+ }
69
+
70
+ function findToolGroup(groupId) {
71
+ return toolGroups[groupId] || null;
72
+ }
73
+
74
+ function toolGroupSummary(group) {
75
+ var names = group.toolNames;
76
+ var count = names.length;
77
+ var allDone = group.doneCount >= count;
78
+
79
+ // Count by tool name
80
+ var counts = {};
81
+ for (var i = 0; i < names.length; i++) {
82
+ counts[names[i]] = (counts[names[i]] || 0) + 1;
83
+ }
84
+ var uniqueNames = Object.keys(counts);
85
+
86
+ if (uniqueNames.length === 1) {
87
+ var name = uniqueNames[0];
88
+ var n = counts[name];
89
+ if (allDone) {
90
+ switch (name) {
91
+ case "Read": return "Read " + n + " file" + (n > 1 ? "s" : "");
92
+ case "Edit": return "Edited " + n + " file" + (n > 1 ? "s" : "");
93
+ case "Write": return "Wrote " + n + " file" + (n > 1 ? "s" : "");
94
+ case "Bash": return "Ran " + n + " command" + (n > 1 ? "s" : "");
95
+ case "Grep": return "Searched " + n + " pattern" + (n > 1 ? "s" : "");
96
+ case "Glob": return "Found " + n + " pattern" + (n > 1 ? "s" : "");
97
+ case "Task": return "Ran " + n + " task" + (n > 1 ? "s" : "");
98
+ case "WebSearch": return "Searched " + n + " quer" + (n > 1 ? "ies" : "y");
99
+ case "WebFetch": return "Fetched " + n + " URL" + (n > 1 ? "s" : "");
100
+ default: return "Ran " + n + " tool" + (n > 1 ? "s" : "");
101
+ }
102
+ }
103
+ switch (name) {
104
+ case "Read": return "Reading " + n + " file" + (n > 1 ? "s" : "") + "...";
105
+ case "Edit": return "Editing " + n + " file" + (n > 1 ? "s" : "") + "...";
106
+ case "Write": return "Writing " + n + " file" + (n > 1 ? "s" : "") + "...";
107
+ case "Bash": return "Running " + n + " command" + (n > 1 ? "s" : "") + "...";
108
+ case "Grep": return "Searching " + n + " pattern" + (n > 1 ? "s" : "") + "...";
109
+ case "Glob": return "Finding " + n + " pattern" + (n > 1 ? "s" : "") + "...";
110
+ case "Task": return "Running " + n + " task" + (n > 1 ? "s" : "") + "...";
111
+ case "WebSearch": return "Searching " + n + " quer" + (n > 1 ? "ies" : "y") + "...";
112
+ case "WebFetch": return "Fetching " + n + " URL" + (n > 1 ? "s" : "") + "...";
113
+ default: return "Running " + n + " tool" + (n > 1 ? "s" : "") + "...";
114
+ }
115
+ }
116
+
117
+ // Mixed tools
118
+ if (allDone) return "Ran " + count + " tools";
119
+ return "Running " + count + " tools...";
120
+ }
121
+
122
+ function updateToolGroupHeader(group) {
123
+ if (!group || !group.el) return;
124
+ var label = group.el.querySelector(".tool-group-label");
125
+ if (label) label.textContent = toolGroupSummary(group);
126
+
127
+ var allDone = group.doneCount >= group.toolCount;
128
+ var statusIcon = group.el.querySelector(".tool-group-status-icon");
129
+ var bullet = group.el.querySelector(".tool-group-bullet");
130
+
131
+ if (allDone) {
132
+ group.el.classList.add("done");
133
+ if (group.errorCount > 0) {
134
+ statusIcon.innerHTML = '<span class="err-icon">' + iconHtml("alert-triangle") + '</span>';
135
+ if (bullet) bullet.classList.add("error");
136
+ } else {
137
+ statusIcon.innerHTML = '<span class="check">' + iconHtml("check") + '</span>';
138
+ }
139
+ refreshIcons(group.el);
140
+ }
141
+
142
+ // Show group header only when 2+ visible tools
143
+ var header = group.el.querySelector(".tool-group-header");
144
+ if (group.toolCount >= 2) {
145
+ header.style.display = "";
146
+ // When 2+ tools, ensure collapsed by default (unless user already toggled)
147
+ if (!group.userToggled && !group.el.classList.contains("expanded-by-user")) {
148
+ group.el.classList.add("collapsed");
149
+ }
150
+ } else {
151
+ header.style.display = "none";
152
+ group.el.classList.remove("collapsed");
153
+ }
154
+ }
155
+
156
+ function isPlanFile(filePath) {
157
+ return filePath && filePath.indexOf(".claude/plans/") !== -1;
158
+ }
159
+
160
+ export function toolSummary(name, input) {
161
+ if (!input || typeof input !== "object") return "";
162
+ switch (name) {
163
+ case "Read": return shortPath(input.file_path);
164
+ case "Edit": return shortPath(input.file_path);
165
+ case "Write": return shortPath(input.file_path);
166
+ case "Bash": return (input.command || "").substring(0, 80);
167
+ case "Glob": return input.pattern || "";
168
+ case "Grep": return (input.pattern || "") + (input.path ? " in " + shortPath(input.path) : "");
169
+ case "WebFetch": return input.url || "";
170
+ case "WebSearch": return input.query || "";
171
+ case "Task": return input.description || "";
172
+ case "EnterPlanMode": return "";
173
+ case "ExitPlanMode": return "";
174
+ default: return JSON.stringify(input).substring(0, 60);
175
+ }
176
+ }
177
+
178
+ export function toolActivityText(name, input) {
179
+ if (name === "Bash" && input && input.description) return input.description;
180
+ if (name === "Read" && input && input.file_path) return "Reading " + shortPath(input.file_path);
181
+ if (name === "Edit" && input && input.file_path) return "Editing " + shortPath(input.file_path);
182
+ if (name === "Write" && input && input.file_path) return "Writing " + shortPath(input.file_path);
183
+ if (name === "Grep" && input && input.pattern) return "Searching for " + input.pattern;
184
+ if (name === "Glob" && input && input.pattern) return "Finding " + input.pattern;
185
+ if (name === "WebSearch" && input && input.query) return "Searching: " + input.query;
186
+ if (name === "WebFetch") return "Fetching URL...";
187
+ if (name === "Task" && input && input.description) return input.description;
188
+ if (name === "EnterPlanMode") return "Entering plan mode...";
189
+ if (name === "ExitPlanMode") return "Finalizing the plan...";
190
+ return "Running " + name + "...";
191
+ }
192
+
193
+ function shortPath(p) {
194
+ if (!p) return "";
195
+ var parts = p.split("/");
196
+ return parts.length > 3 ? ".../" + parts.slice(-3).join("/") : p;
197
+ }
198
+
199
+ // --- AskUserQuestion ---
200
+ export function renderAskUserQuestion(toolId, input) {
201
+ ctx.finalizeAssistantBlock();
202
+ stopThinking();
203
+ closeToolGroup();
204
+
205
+ var questions = input.questions || [];
206
+ if (questions.length === 0) return;
207
+
208
+ var container = document.createElement("div");
209
+ container.className = "ask-user-container";
210
+ container.dataset.toolId = toolId;
211
+
212
+ var mateContentWrap = null;
213
+
214
+ var answers = {};
215
+ var multiSelections = {};
216
+
217
+ questions.forEach(function (q, qIdx) {
218
+ var qDiv = document.createElement("div");
219
+ qDiv.className = "ask-user-question";
220
+
221
+ if (q.header) {
222
+ var qHeader = document.createElement("div");
223
+ qHeader.className = "ask-user-question-header";
224
+ qHeader.textContent = q.header;
225
+ qDiv.appendChild(qHeader);
226
+ }
227
+
228
+ var qText = document.createElement("div");
229
+ qText.className = "ask-user-question-text";
230
+ qText.textContent = q.question || "";
231
+ qDiv.appendChild(qText);
232
+
233
+ var optionsDiv = document.createElement("div");
234
+ optionsDiv.className = "ask-user-options";
235
+
236
+ var isMulti = q.multiSelect || false;
237
+ if (isMulti) multiSelections[qIdx] = new Set();
238
+
239
+ (q.options || []).forEach(function (opt) {
240
+ var btn = document.createElement("button");
241
+ btn.className = "ask-user-option";
242
+ btn.innerHTML =
243
+ '<div class="option-label"></div>' +
244
+ (opt.description ? '<div class="option-desc"></div>' : '');
245
+ btn.querySelector(".option-label").textContent = opt.label;
246
+ if (opt.description) btn.querySelector(".option-desc").textContent = opt.description;
247
+ if (opt.markdown) {
248
+ var pre = document.createElement("pre");
249
+ pre.className = "option-markdown";
250
+ pre.textContent = opt.markdown;
251
+ btn.appendChild(pre);
252
+ }
253
+
254
+ btn.addEventListener("click", function () {
255
+ if (container.classList.contains("answered")) return;
256
+
257
+ if (isMulti) {
258
+ var set = multiSelections[qIdx];
259
+ if (set.has(opt.label)) {
260
+ set.delete(opt.label);
261
+ btn.classList.remove("selected");
262
+ } else {
263
+ set.add(opt.label);
264
+ btn.classList.add("selected");
265
+ }
266
+ } else {
267
+ optionsDiv.querySelectorAll(".ask-user-option").forEach(function (b) {
268
+ b.classList.remove("selected");
269
+ });
270
+ btn.classList.add("selected");
271
+ answers[qIdx] = opt.label;
272
+ var otherInput = qDiv.querySelector(".ask-user-other input");
273
+ if (otherInput) otherInput.value = "";
274
+ }
275
+ });
276
+
277
+ optionsDiv.appendChild(btn);
278
+ });
279
+
280
+ qDiv.appendChild(optionsDiv);
281
+
282
+ // "Other" text input
283
+ var otherDiv = document.createElement("div");
284
+ otherDiv.className = "ask-user-other";
285
+ var otherInput = document.createElement("input");
286
+ otherInput.type = "text";
287
+ otherInput.placeholder = "Other...";
288
+ otherInput.addEventListener("input", function () {
289
+ if (container.classList.contains("answered")) return;
290
+ if (otherInput.value.trim()) {
291
+ optionsDiv.querySelectorAll(".ask-user-option").forEach(function (b) {
292
+ b.classList.remove("selected");
293
+ });
294
+ if (isMulti) multiSelections[qIdx] = new Set();
295
+ answers[qIdx] = otherInput.value.trim();
296
+ }
297
+ });
298
+ otherInput.addEventListener("keydown", function (e) {
299
+ if (e.key === "Enter" && !e.shiftKey) {
300
+ e.preventDefault();
301
+ submitAskUserAnswer(container, toolId, questions, answers, multiSelections);
302
+ }
303
+ });
304
+ otherDiv.appendChild(otherInput);
305
+ qDiv.appendChild(otherDiv);
306
+ container.appendChild(qDiv);
307
+ });
308
+
309
+ // Submit button: always show
310
+ var submitBtn = document.createElement("button");
311
+ submitBtn.className = "ask-user-submit";
312
+ submitBtn.textContent = "Submit";
313
+ submitBtn.addEventListener("click", function () {
314
+ submitAskUserAnswer(container, toolId, questions, answers, multiSelections);
315
+ });
316
+ container.appendChild(submitBtn);
317
+
318
+ // Skip button
319
+ var skipBtn = document.createElement("button");
320
+ skipBtn.className = "ask-user-skip";
321
+ skipBtn.textContent = "Skip";
322
+ skipBtn.addEventListener("click", function () {
323
+ if (container.classList.contains("answered")) return;
324
+ container.classList.add("answered");
325
+ enableMainInput();
326
+ if (ctx.ws && ctx.connected) {
327
+ ctx.ws.send(JSON.stringify({ type: "stop" }));
328
+ }
329
+ });
330
+ container.appendChild(skipBtn);
331
+
332
+ // Mate DM: move all content into the bubble content wrapper
333
+ if (mateContentWrap) {
334
+ var children = [];
335
+ for (var ci = 0; ci < container.childNodes.length; ci++) {
336
+ if (container.childNodes[ci] !== container.querySelector(".dm-bubble-avatar")) {
337
+ children.push(container.childNodes[ci]);
338
+ }
339
+ }
340
+ for (var cj = 0; cj < children.length; cj++) {
341
+ mateContentWrap.appendChild(children[cj]);
342
+ }
343
+ container.appendChild(mateContentWrap);
344
+ }
345
+
346
+ ctx.addToMessages(container);
347
+ disableMainInput();
348
+ ctx.setActivity(null);
349
+ maybeScrollToBottom();
350
+ }
351
+
352
+ export function disableMainInput() {
353
+ ctx.inputEl.disabled = true;
354
+ ctx.inputEl.placeholder = "Answer the question above to continue...";
355
+ }
356
+
357
+ export function enableMainInput() {
358
+ ctx.inputEl.disabled = false;
359
+ if (document.body.classList.contains("mate-dm-active") && document.body.dataset.mateName) {
360
+ ctx.inputEl.placeholder = "Message " + document.body.dataset.mateName + "...";
361
+ } else {
362
+ var _v = store.get('currentVendor') || "claude";
363
+ ctx.inputEl.placeholder = "Message " + (VENDOR_NAMES[_v] || VENDOR_NAMES.claude) + "...";
364
+ }
365
+ }
366
+
367
+ function submitAskUserAnswer(container, toolId, questions, answers, multiSelections) {
368
+ if (container.classList.contains("answered")) return;
369
+
370
+ var result = {};
371
+ for (var i = 0; i < questions.length; i++) {
372
+ var q = questions[i];
373
+ if (q.multiSelect && multiSelections[i] && multiSelections[i].size > 0) {
374
+ result[i] = Array.from(multiSelections[i]).join(", ");
375
+ } else if (answers[i]) {
376
+ result[i] = answers[i];
377
+ }
378
+ }
379
+
380
+ if (Object.keys(result).length === 0) return;
381
+
382
+ container.classList.add("answered");
383
+ enableMainInput();
384
+ if (ctx.stopUrgentBlink) ctx.stopUrgentBlink();
385
+
386
+ // Show user's answers inline
387
+ showAnswerSummary(container, questions, result);
388
+
389
+ if (ctx.ws && ctx.connected) {
390
+ ctx.ws.send(JSON.stringify({
391
+ type: "ask_user_response",
392
+ toolId: toolId,
393
+ answers: result,
394
+ }));
395
+ }
396
+ }
397
+
398
+ function showAnswerSummary(container, questions, answers) {
399
+ if (!answers || Object.keys(answers).length === 0) return;
400
+ var existing = container.querySelector(".ask-user-answer-summary");
401
+ if (existing) return;
402
+ var summary = document.createElement("div");
403
+ summary.className = "ask-user-answer-summary";
404
+ for (var key in answers) {
405
+ if (!answers.hasOwnProperty(key)) continue;
406
+ var row = document.createElement("div");
407
+ row.className = "ask-user-answer-row";
408
+ var qi = parseInt(key, 10);
409
+ var label = (questions && questions[qi] && questions[qi].question) ? questions[qi].question : "Answer";
410
+ row.innerHTML = '<span class="ask-user-answer-label">' + escapeHtml(label) + '</span>' +
411
+ '<span class="ask-user-answer-value">' + escapeHtml(String(answers[key])) + '</span>';
412
+ summary.appendChild(row);
413
+ }
414
+ // Insert before submit button
415
+ var submitBtn = container.querySelector(".ask-user-submit");
416
+ if (submitBtn) {
417
+ submitBtn.parentNode.insertBefore(summary, submitBtn);
418
+ } else {
419
+ container.appendChild(summary);
420
+ }
421
+ }
422
+
423
+ export function markAskUserAnswered(toolId, answers) {
424
+ var container = document.querySelector('.ask-user-container[data-tool-id="' + toolId + '"]');
425
+ if (container && !container.classList.contains("answered")) {
426
+ container.classList.add("answered");
427
+ enableMainInput();
428
+ // Restore answers from history replay
429
+ if (answers && Object.keys(answers).length > 0) {
430
+ // Find matching questions from the tool_executing input
431
+ var questions = null;
432
+ var askQuestions = container.querySelectorAll(".ask-user-question");
433
+ if (askQuestions.length > 0) {
434
+ questions = [];
435
+ for (var qi = 0; qi < askQuestions.length; qi++) {
436
+ var qTextEl = askQuestions[qi].querySelector(".ask-user-question-text");
437
+ questions.push({ question: qTextEl ? qTextEl.textContent : "" });
438
+ }
439
+ }
440
+ showAnswerSummary(container, questions, answers);
441
+ // Also mark selected options to match the answers
442
+ for (var key in answers) {
443
+ if (!answers.hasOwnProperty(key)) continue;
444
+ var idx = parseInt(key, 10);
445
+ if (askQuestions[idx]) {
446
+ var answerVal = String(answers[key]);
447
+ var options = askQuestions[idx].querySelectorAll(".ask-user-option");
448
+ var matched = false;
449
+ for (var oi = 0; oi < options.length; oi++) {
450
+ var labelEl = options[oi].querySelector(".option-label");
451
+ if (labelEl && labelEl.textContent === answerVal) {
452
+ options[oi].classList.add("selected");
453
+ matched = true;
454
+ }
455
+ }
456
+ // If not matched to an option, fill the "Other" input
457
+ if (!matched) {
458
+ var otherInput = askQuestions[idx].querySelector(".ask-user-other input");
459
+ if (otherInput) otherInput.value = answerVal;
460
+ }
461
+ }
462
+ }
463
+ }
464
+ }
465
+ }
466
+
467
+ // --- Permission request ---
468
+ function permissionInputSummary(toolName, input) {
469
+ if (!input || typeof input !== "object") return "";
470
+ switch (toolName) {
471
+ case "Bash": return input.command || input.description || "";
472
+ case "Edit": return shortPath(input.file_path);
473
+ case "Write": return shortPath(input.file_path);
474
+ case "Read": return shortPath(input.file_path);
475
+ case "Glob": return input.pattern || "";
476
+ case "Grep": return (input.pattern || "") + (input.path ? " in " + shortPath(input.path) : "");
477
+ default: return toolSummary(toolName, input);
478
+ }
479
+ }
480
+
481
+ export function renderPermissionRequest(requestId, toolName, toolInput, decisionReason, mateId, vendor) {
482
+ if (pendingPermissions[requestId]) return;
483
+ ctx.finalizeAssistantBlock();
484
+ stopThinking();
485
+ closeToolGroup();
486
+
487
+ // ExitPlanMode: render as plan confirmation instead of generic permission
488
+ if (toolName === "ExitPlanMode") {
489
+ renderPlanPermission(requestId);
490
+ return;
491
+ }
492
+
493
+ // Channel layout: conversational "Can I ...?" style
494
+ if (getChatLayout() === "channel") {
495
+ renderConversationalPermission(requestId, toolName, toolInput, mateId, vendor);
496
+ return;
497
+ }
498
+
499
+ // Bubble layout: formal "Permission Required" dialog
500
+ renderFormalPermission(requestId, toolName, toolInput, decisionReason);
501
+ }
502
+
503
+ function renderFormalPermission(requestId, toolName, toolInput, decisionReason) {
504
+ var container = document.createElement("div");
505
+ container.className = "permission-container";
506
+ container.dataset.requestId = requestId;
507
+
508
+ // Header
509
+ var header = document.createElement("div");
510
+ header.className = "permission-header";
511
+ header.innerHTML =
512
+ '<span class="permission-icon">' + iconHtml("shield") + '</span>' +
513
+ '<span class="permission-title">Permission Required</span>';
514
+
515
+ // Body
516
+ var body = document.createElement("div");
517
+ body.className = "permission-body";
518
+
519
+ var summary = document.createElement("div");
520
+ summary.className = "permission-summary";
521
+ var summaryText = permissionInputSummary(toolName, toolInput);
522
+ summary.innerHTML =
523
+ '<span class="permission-tool-name"></span>' +
524
+ (summaryText ? '<span class="permission-tool-desc"></span>' : '');
525
+ summary.querySelector(".permission-tool-name").textContent = toolName;
526
+ if (summaryText) {
527
+ summary.querySelector(".permission-tool-desc").textContent = summaryText;
528
+ }
529
+ body.appendChild(summary);
530
+
531
+ if (decisionReason) {
532
+ var reason = document.createElement("div");
533
+ reason.className = "permission-reason";
534
+ reason.textContent = decisionReason;
535
+ body.appendChild(reason);
536
+ }
537
+
538
+ // Collapsible details
539
+ var details = document.createElement("details");
540
+ details.className = "permission-details";
541
+ var detailsSummary = document.createElement("summary");
542
+ detailsSummary.textContent = "Details";
543
+ var detailsPre = document.createElement("pre");
544
+ detailsPre.textContent = JSON.stringify(toolInput, null, 2);
545
+ details.appendChild(detailsSummary);
546
+ details.appendChild(detailsPre);
547
+ body.appendChild(details);
548
+
549
+ // Actions
550
+ var actions = document.createElement("div");
551
+ actions.className = "permission-actions";
552
+
553
+ var allowBtn = document.createElement("button");
554
+ allowBtn.className = "permission-btn permission-allow";
555
+ allowBtn.textContent = "Allow Once";
556
+ allowBtn.addEventListener("click", function () {
557
+ sendPermissionResponse(container, requestId, "allow");
558
+ });
559
+
560
+ var allowAlwaysBtn = document.createElement("button");
561
+ allowAlwaysBtn.className = "permission-btn permission-allow-session";
562
+ allowAlwaysBtn.textContent = "Allow for Session";
563
+ allowAlwaysBtn.addEventListener("click", function () {
564
+ sendPermissionResponse(container, requestId, "allow_always");
565
+ });
566
+
567
+ var denyBtn = document.createElement("button");
568
+ denyBtn.className = "permission-btn permission-deny";
569
+ denyBtn.textContent = "Deny";
570
+ denyBtn.addEventListener("click", function () {
571
+ sendPermissionResponse(container, requestId, "deny");
572
+ });
573
+
574
+ actions.appendChild(allowBtn);
575
+ actions.appendChild(allowAlwaysBtn);
576
+ actions.appendChild(denyBtn);
577
+
578
+ container.appendChild(header);
579
+ container.appendChild(body);
580
+ container.appendChild(actions);
581
+ ctx.addToMessages(container);
582
+
583
+ pendingPermissions[requestId] = container;
584
+ refreshIcons(container);
585
+ ctx.setActivity(null);
586
+ maybeScrollToBottom();
587
+ }
588
+
589
+ function renderPlanPermission(requestId) {
590
+ if (pendingPermissions[requestId]) return;
591
+ var container = document.createElement("div");
592
+ container.className = "permission-container plan-permission";
593
+ container.dataset.requestId = requestId;
594
+
595
+ // Header
596
+ var header = document.createElement("div");
597
+ header.className = "permission-header plan-permission-header";
598
+ header.innerHTML =
599
+ '<span class="permission-icon">' + iconHtml("check-circle") + '</span>' +
600
+ '<span class="permission-title">Plan Approval</span>';
601
+
602
+ // Body (plan content already visible above, no need to repeat)
603
+ var body = document.createElement("div");
604
+ body.className = "permission-body";
605
+
606
+ // Actions row 1: main buttons
607
+ var actions = document.createElement("div");
608
+ actions.className = "permission-actions plan-permission-actions";
609
+
610
+ // Option 1: Clear context & auto-accept
611
+ var clearBtn = document.createElement("button");
612
+ clearBtn.className = "permission-btn plan-btn-clear";
613
+ var contextPct = ctx.getContextPercent ? ctx.getContextPercent() : 0;
614
+ clearBtn.innerHTML = iconHtml("refresh-cw") + ' <span>Clear context' +
615
+ (contextPct > 0 ? ' <span class="plan-ctx-pct">(' + contextPct + '% used)</span>' : '') +
616
+ ' &amp; auto-accept</span>';
617
+ clearBtn.addEventListener("click", function () {
618
+ sendPlanResponse(container, requestId, "allow_clear_context");
619
+ });
620
+
621
+ // Option 2: Auto-accept edits
622
+ var approveBtn = document.createElement("button");
623
+ approveBtn.className = "permission-btn permission-allow";
624
+ approveBtn.textContent = "Auto-accept edits";
625
+ approveBtn.addEventListener("click", function () {
626
+ sendPlanResponse(container, requestId, "allow_accept_edits");
627
+ });
628
+
629
+ // Option 3: Manually approve edits
630
+ var manualBtn = document.createElement("button");
631
+ manualBtn.className = "permission-btn permission-allow-session";
632
+ manualBtn.textContent = "Manually approve";
633
+ manualBtn.addEventListener("click", function () {
634
+ sendPlanResponse(container, requestId, "allow");
635
+ });
636
+
637
+ // Option 4: Reject
638
+ var rejectBtn = document.createElement("button");
639
+ rejectBtn.className = "permission-btn permission-deny";
640
+ rejectBtn.textContent = "Reject";
641
+ rejectBtn.addEventListener("click", function () {
642
+ sendPlanResponse(container, requestId, "deny");
643
+ });
644
+
645
+ actions.appendChild(clearBtn);
646
+ actions.appendChild(approveBtn);
647
+ actions.appendChild(manualBtn);
648
+ actions.appendChild(rejectBtn);
649
+
650
+ // Feedback input row (Option 4: tell Claude what to change)
651
+ var feedbackRow = document.createElement("div");
652
+ feedbackRow.className = "plan-feedback-row";
653
+ var feedbackInput = document.createElement("input");
654
+ feedbackInput.type = "text";
655
+ feedbackInput.className = "plan-feedback-input";
656
+ feedbackInput.placeholder = "Tell Claude what to change...";
657
+ var feedbackSendBtn = document.createElement("button");
658
+ feedbackSendBtn.className = "plan-feedback-send";
659
+ feedbackSendBtn.innerHTML = iconHtml("arrow-up");
660
+ feedbackSendBtn.disabled = true;
661
+
662
+ feedbackInput.addEventListener("input", function () {
663
+ feedbackSendBtn.disabled = !feedbackInput.value.trim();
664
+ });
665
+ feedbackInput.addEventListener("keydown", function (e) {
666
+ if (e.key === "Enter" && !e.shiftKey && feedbackInput.value.trim()) {
667
+ e.preventDefault();
668
+ submitPlanFeedback();
669
+ }
670
+ });
671
+ feedbackSendBtn.addEventListener("click", function () {
672
+ if (feedbackInput.value.trim()) submitPlanFeedback();
673
+ });
674
+
675
+ function submitPlanFeedback() {
676
+ var text = feedbackInput.value.trim();
677
+ if (!text) return;
678
+ sendPlanResponse(container, requestId, "deny_with_feedback", text);
679
+ }
680
+
681
+ feedbackRow.appendChild(feedbackInput);
682
+ feedbackRow.appendChild(feedbackSendBtn);
683
+
684
+ container.appendChild(header);
685
+ container.appendChild(body);
686
+ container.appendChild(actions);
687
+ container.appendChild(feedbackRow);
688
+ ctx.addToMessages(container);
689
+
690
+ pendingPermissions[requestId] = container;
691
+ refreshIcons(container);
692
+ ctx.setActivity(null);
693
+ maybeScrollToBottom();
694
+ // Focus the feedback input after render
695
+ setTimeout(function () { feedbackInput.focus(); }, 50);
696
+ }
697
+
698
+ function sendPlanResponse(container, requestId, decision, feedback) {
699
+ if (container.classList.contains("resolved")) return;
700
+ container.classList.add("resolved");
701
+ if (ctx.stopUrgentBlink) ctx.stopUrgentBlink();
702
+
703
+ var labelMap = {
704
+ "allow": "Approved (manual)",
705
+ "allow_accept_edits": "Approved (auto-accept)",
706
+ "allow_clear_context": "Approved (clear + auto-accept)",
707
+ "deny": "Rejected",
708
+ "deny_with_feedback": "Feedback sent",
709
+ };
710
+ var label = labelMap[decision] || decision;
711
+ var isDeny = decision === "deny" || decision === "deny_with_feedback";
712
+ var resolvedClass = isDeny ? "resolved-denied" : "resolved-allowed";
713
+ container.classList.add(resolvedClass);
714
+
715
+ // Replace actions + feedback with decision label
716
+ var actionsEl = container.querySelector(".plan-permission-actions");
717
+ if (actionsEl) {
718
+ actionsEl.innerHTML = '<span class="permission-decision-label">' + label + '</span>';
719
+ }
720
+ var feedbackRowEl = container.querySelector(".plan-feedback-row");
721
+ if (feedbackRowEl) feedbackRowEl.remove();
722
+
723
+ if (ctx.ws && ctx.connected) {
724
+ var payload = {
725
+ type: "permission_response",
726
+ requestId: requestId,
727
+ decision: decision,
728
+ };
729
+ if (feedback) payload.feedback = feedback;
730
+ if (decision === "allow_clear_context" && planContent) {
731
+ payload.planContent = planContent;
732
+ }
733
+ ctx.ws.send(JSON.stringify(payload));
734
+ }
735
+
736
+ delete pendingPermissions[requestId];
737
+ }
738
+
739
+ function matePermissionInfo(toolName, toolInput) {
740
+ var input = toolInput && typeof toolInput === "object" ? toolInput : {};
741
+ var verb = "use " + toolName;
742
+ var target = "";
743
+
744
+ switch (toolName) {
745
+ case "Write": verb = "write to"; target = shortPath(input.file_path); break;
746
+ case "Edit": verb = "edit"; target = shortPath(input.file_path); break;
747
+ case "Read": verb = "read"; target = shortPath(input.file_path); break;
748
+ case "Bash": verb = "run"; target = input.description || (input.command || "").substring(0, 80); break;
749
+ case "Grep": verb = "search"; target = input.pattern || ""; break;
750
+ case "Glob": verb = "search for files in"; target = input.pattern || ""; break;
751
+ case "WebFetch": verb = "fetch"; target = input.url || ""; break;
752
+ case "WebSearch": verb = "search the web for"; target = input.query || ""; break;
753
+ }
754
+ return { verb: verb, target: target };
755
+ }
756
+
757
+ function resolvePermissionIdentity(mateId, vendor) {
758
+ // Use vendor name and avatar
759
+ var vendorAvatars = { claude: "/claude-code-avatar.png", codex: "/codex-avatar.png" };
760
+ var vendorName = (vendor && VENDOR_NAMES[vendor]) || VENDOR_NAMES.claude;
761
+ return {
762
+ name: vendorName,
763
+ avatar: (vendor && vendorAvatars[vendor]) || vendorAvatars.claude,
764
+ };
765
+ }
766
+
767
+ function renderConversationalPermission(requestId, toolName, toolInput, mateId, vendor) {
768
+ var identity = resolvePermissionIdentity(mateId, vendor);
769
+ var info = matePermissionInfo(toolName, toolInput);
770
+ var askMsg = "Can I " + info.verb + (info.target ? " " + info.target : "") + "?";
771
+
772
+ var container = document.createElement("div");
773
+ container.className = "permission-container";
774
+ container.dataset.requestId = requestId;
775
+
776
+ // Avatar (left column)
777
+ var avi = document.createElement("img");
778
+ avi.className = "dm-bubble-avatar dm-bubble-avatar-mate";
779
+ avi.src = identity.avatar;
780
+ avi.alt = "";
781
+ container.appendChild(avi);
782
+
783
+ // Content (right column)
784
+ var content = document.createElement("div");
785
+ content.className = "dm-bubble-content";
786
+
787
+ // Name + time header
788
+ var headerRow = document.createElement("div");
789
+ headerRow.className = "dm-bubble-header";
790
+ headerRow.innerHTML =
791
+ '<span class="dm-bubble-name">' + escapeHtml(identity.name) + '</span>' +
792
+ '<span class="dm-bubble-time">' + String(new Date().getHours()).padStart(2, "0") + ":" + String(new Date().getMinutes()).padStart(2, "0") + '</span>';
793
+ content.appendChild(headerRow);
794
+
795
+ // Ask text
796
+ var askEl = document.createElement("div");
797
+ askEl.className = "perm-ask";
798
+ askEl.textContent = askMsg;
799
+ content.appendChild(askEl);
800
+
801
+ // Collapsible details
802
+ var details = document.createElement("details");
803
+ details.className = "perm-details";
804
+ var summary = document.createElement("summary");
805
+ summary.textContent = "Details";
806
+ var pre = document.createElement("pre");
807
+ pre.textContent = JSON.stringify(toolInput, null, 2);
808
+ details.appendChild(summary);
809
+ details.appendChild(pre);
810
+ content.appendChild(details);
811
+
812
+ // Buttons
813
+ var actions = document.createElement("div");
814
+ actions.className = "permission-actions";
815
+
816
+ var allowBtn = document.createElement("button");
817
+ allowBtn.className = "perm-reply perm-allow";
818
+ allowBtn.textContent = "Sure";
819
+ allowBtn.addEventListener("click", function () {
820
+ sendPermissionResponse(container, requestId, "allow");
821
+ });
822
+
823
+ var alwaysBtn = document.createElement("button");
824
+ alwaysBtn.className = "perm-reply perm-always";
825
+ alwaysBtn.textContent = "Allow for session";
826
+ alwaysBtn.addEventListener("click", function () {
827
+ sendPermissionResponse(container, requestId, "allow_always");
828
+ });
829
+
830
+ var denyBtn = document.createElement("button");
831
+ denyBtn.className = "perm-reply perm-deny";
832
+ denyBtn.textContent = "No";
833
+ denyBtn.addEventListener("click", function () {
834
+ sendPermissionResponse(container, requestId, "deny");
835
+ });
836
+
837
+ actions.appendChild(allowBtn);
838
+ actions.appendChild(alwaysBtn);
839
+ actions.appendChild(denyBtn);
840
+ content.appendChild(actions);
841
+
842
+ container.appendChild(content);
843
+
844
+ ctx.addToMessages(container);
845
+ pendingPermissions[requestId] = container;
846
+ refreshIcons(container);
847
+ ctx.setActivity(null);
848
+ maybeScrollToBottom();
849
+ }
850
+
851
+ function sendPermissionResponse(container, requestId, decision) {
852
+ if (container.classList.contains("resolved")) return;
853
+ container.classList.add("resolved");
854
+ if (ctx.stopUrgentBlink) ctx.stopUrgentBlink();
855
+
856
+ var label = decision === "deny" ? "Denied" : decision === "allow_always" ? "Allowed for session" : "Allowed";
857
+ var resolvedClass = decision === "deny" ? "resolved-denied" : "resolved-allowed";
858
+ container.classList.add(resolvedClass);
859
+
860
+ // Replace actions with decision label
861
+ var actions = container.querySelector(".permission-actions");
862
+ if (actions) {
863
+ actions.innerHTML = '<span class="permission-decision-label">' + label + '</span>';
864
+ }
865
+
866
+ if (ctx.ws && ctx.connected) {
867
+ ctx.ws.send(JSON.stringify({
868
+ type: "permission_response",
869
+ requestId: requestId,
870
+ decision: decision,
871
+ }));
872
+ }
873
+
874
+ delete pendingPermissions[requestId];
875
+ }
876
+
877
+ export function markPermissionResolved(requestId, decision) {
878
+ var container = pendingPermissions[requestId];
879
+ if (!container) {
880
+ // Find by data attribute (history replay)
881
+ container = ctx.messagesEl.querySelector('[data-request-id="' + requestId + '"]');
882
+ }
883
+ if (!container || container.classList.contains("resolved")) return;
884
+
885
+ container.classList.add("resolved");
886
+
887
+ // Plan-specific decisions
888
+ var planLabelMap = {
889
+ "allow_accept_edits": "Approved (auto-accept)",
890
+ "allow_clear_context": "Approved (clear + auto-accept)",
891
+ "deny_with_feedback": "Feedback sent",
892
+ };
893
+ var isDeny = decision === "deny" || decision === "deny_with_feedback";
894
+ var resolvedClass = isDeny ? "resolved-denied" : "resolved-allowed";
895
+ container.classList.add(resolvedClass);
896
+
897
+ var label = planLabelMap[decision] || (decision === "deny" ? "Denied" : decision === "allow_always" ? "Allowed for session" : "Allowed");
898
+ var actions = container.querySelector(".permission-actions") || container.querySelector(".plan-permission-actions");
899
+ if (actions) {
900
+ actions.innerHTML = '<span class="permission-decision-label">' + label + '</span>';
901
+ }
902
+ // Remove feedback row if present (plan permission)
903
+ var feedbackRow = container.querySelector(".plan-feedback-row");
904
+ if (feedbackRow) feedbackRow.remove();
905
+
906
+ delete pendingPermissions[requestId];
907
+ }
908
+
909
+ export function markPermissionCancelled(requestId) {
910
+ var container = pendingPermissions[requestId];
911
+ if (!container) {
912
+ container = ctx.messagesEl.querySelector('[data-request-id="' + requestId + '"]');
913
+ }
914
+ if (!container || container.classList.contains("resolved")) return;
915
+
916
+ container.classList.add("resolved", "resolved-cancelled");
917
+ var actions = container.querySelector(".permission-actions");
918
+ if (actions) {
919
+ actions.innerHTML = '<span class="permission-decision-label">Cancelled</span>';
920
+ }
921
+
922
+ delete pendingPermissions[requestId];
923
+ }
924
+
925
+ // --- MCP elicitation rendering ---
926
+
927
+ var pendingElicitations = {};
928
+
929
+ export function renderElicitationRequest(msg) {
930
+ if (pendingElicitations[msg.requestId]) return;
931
+ ctx.finalizeAssistantBlock();
932
+ stopThinking();
933
+ closeToolGroup();
934
+
935
+ var container = document.createElement("div");
936
+ container.className = "permission-container elicitation-container";
937
+ container.dataset.requestId = msg.requestId;
938
+
939
+ // Header
940
+ var header = document.createElement("div");
941
+ header.className = "permission-header";
942
+ header.innerHTML =
943
+ '<span class="permission-icon">' + iconHtml("key") + '</span>' +
944
+ '<span class="permission-title">' + escapeHtml(msg.serverName || "MCP Server") + ' requests input</span>';
945
+
946
+ // Body
947
+ var body = document.createElement("div");
948
+ body.className = "permission-body";
949
+
950
+ if (msg.message) {
951
+ var messageEl = document.createElement("div");
952
+ messageEl.className = "permission-reason";
953
+ messageEl.textContent = msg.message;
954
+ body.appendChild(messageEl);
955
+ }
956
+
957
+ // Form fields (form mode) or URL button (url mode)
958
+ var formData = {};
959
+
960
+ if (msg.mode === "url" && msg.url) {
961
+ var urlInfo = document.createElement("div");
962
+ urlInfo.className = "elicitation-url-info";
963
+ urlInfo.style.cssText = "margin-top: 8px; font-size: 12px; color: var(--text-muted);";
964
+ urlInfo.textContent = "Opens: " + msg.url;
965
+ body.appendChild(urlInfo);
966
+ } else if (msg.requestedSchema && msg.requestedSchema.properties) {
967
+ var formEl = document.createElement("div");
968
+ formEl.className = "elicitation-form";
969
+ formEl.style.cssText = "margin-top: 8px; display: flex; flex-direction: column; gap: 8px;";
970
+
971
+ var props = msg.requestedSchema.properties;
972
+ var required = msg.requestedSchema.required || [];
973
+ var propNames = Object.keys(props);
974
+ for (var i = 0; i < propNames.length; i++) {
975
+ var propName = propNames[i];
976
+ var prop = props[propName];
977
+ var isRequired = required.indexOf(propName) !== -1;
978
+
979
+ var fieldWrapper = document.createElement("div");
980
+ fieldWrapper.style.cssText = "display: flex; flex-direction: column; gap: 2px;";
981
+
982
+ var label = document.createElement("label");
983
+ label.style.cssText = "font-size: 12px; font-weight: 500; color: var(--text-secondary);";
984
+ label.textContent = propName + (isRequired ? " *" : "");
985
+ if (prop.description) {
986
+ label.title = prop.description;
987
+ }
988
+
989
+ var input;
990
+ if (prop.type === "boolean") {
991
+ input = document.createElement("input");
992
+ input.type = "checkbox";
993
+ input.dataset.propName = propName;
994
+ input.dataset.propType = "boolean";
995
+ } else if (prop.enum) {
996
+ input = document.createElement("select");
997
+ input.dataset.propName = propName;
998
+ input.dataset.propType = "enum";
999
+ input.style.cssText = "padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--input-bg); color: var(--text-primary); font-size: 13px;";
1000
+ for (var ei = 0; ei < prop.enum.length; ei++) {
1001
+ var opt = document.createElement("option");
1002
+ opt.value = prop.enum[ei];
1003
+ opt.textContent = prop.enum[ei];
1004
+ input.appendChild(opt);
1005
+ }
1006
+ } else {
1007
+ input = document.createElement("input");
1008
+ input.type = prop.type === "number" || prop.type === "integer" ? "number" : "text";
1009
+ input.dataset.propName = propName;
1010
+ input.dataset.propType = prop.type || "string";
1011
+ input.placeholder = prop.description || propName;
1012
+ input.style.cssText = "padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border); background: var(--input-bg); color: var(--text-primary); font-size: 13px;";
1013
+ }
1014
+
1015
+ fieldWrapper.appendChild(label);
1016
+ fieldWrapper.appendChild(input);
1017
+ formEl.appendChild(fieldWrapper);
1018
+ }
1019
+ body.appendChild(formEl);
1020
+ }
1021
+
1022
+ // Actions
1023
+ var actions = document.createElement("div");
1024
+ actions.className = "permission-actions";
1025
+
1026
+ var acceptBtn = document.createElement("button");
1027
+ acceptBtn.className = "permission-btn permission-allow";
1028
+
1029
+ if (msg.mode === "url" && msg.url) {
1030
+ acceptBtn.textContent = "Open & Approve";
1031
+ acceptBtn.addEventListener("click", function () {
1032
+ window.open(msg.url, "_blank");
1033
+ sendElicitationResponse(container, msg.requestId, "accept", {});
1034
+ });
1035
+ } else {
1036
+ acceptBtn.textContent = "Submit";
1037
+ acceptBtn.addEventListener("click", function () {
1038
+ // Collect form values
1039
+ var content = {};
1040
+ var inputs = container.querySelectorAll("[data-prop-name]");
1041
+ for (var j = 0; j < inputs.length; j++) {
1042
+ var inp = inputs[j];
1043
+ var name = inp.dataset.propName;
1044
+ var pType = inp.dataset.propType;
1045
+ if (pType === "boolean") {
1046
+ content[name] = inp.checked;
1047
+ } else if (pType === "number" || pType === "integer") {
1048
+ content[name] = Number(inp.value);
1049
+ } else {
1050
+ content[name] = inp.value;
1051
+ }
1052
+ }
1053
+ sendElicitationResponse(container, msg.requestId, "accept", content);
1054
+ });
1055
+ }
1056
+
1057
+ var denyBtn = document.createElement("button");
1058
+ denyBtn.className = "permission-btn permission-deny";
1059
+ denyBtn.textContent = "Deny";
1060
+ denyBtn.addEventListener("click", function () {
1061
+ sendElicitationResponse(container, msg.requestId, "reject", null);
1062
+ });
1063
+
1064
+ actions.appendChild(acceptBtn);
1065
+ actions.appendChild(denyBtn);
1066
+
1067
+ container.appendChild(header);
1068
+ container.appendChild(body);
1069
+ container.appendChild(actions);
1070
+ ctx.addToMessages(container);
1071
+
1072
+ pendingElicitations[msg.requestId] = container;
1073
+ refreshIcons(container);
1074
+ ctx.setActivity(null);
1075
+ maybeScrollToBottom();
1076
+ }
1077
+
1078
+ function sendElicitationResponse(container, requestId, action, content) {
1079
+ if (container.classList.contains("resolved")) return;
1080
+ container.classList.add("resolved");
1081
+ if (ctx.stopUrgentBlink) ctx.stopUrgentBlink();
1082
+
1083
+ var label = action === "reject" ? "Denied" : "Submitted";
1084
+ var resolvedClass = action === "reject" ? "resolved-denied" : "resolved-allowed";
1085
+ container.classList.add(resolvedClass);
1086
+
1087
+ var actions = container.querySelector(".permission-actions");
1088
+ if (actions) {
1089
+ actions.innerHTML = '<span class="permission-decision-label">' + label + '</span>';
1090
+ }
1091
+
1092
+ if (ctx.ws && ctx.connected) {
1093
+ var msg = {
1094
+ type: "elicitation_response",
1095
+ requestId: requestId,
1096
+ action: action,
1097
+ };
1098
+ if (action === "accept" && content) {
1099
+ msg.content = content;
1100
+ }
1101
+ ctx.ws.send(JSON.stringify(msg));
1102
+ }
1103
+
1104
+ delete pendingElicitations[requestId];
1105
+ }
1106
+
1107
+ export function markElicitationResolved(requestId, action) {
1108
+ var container = pendingElicitations[requestId];
1109
+ if (!container) {
1110
+ container = ctx.messagesEl.querySelector('.elicitation-container[data-request-id="' + requestId + '"]');
1111
+ }
1112
+ if (!container || container.classList.contains("resolved")) return;
1113
+
1114
+ container.classList.add("resolved");
1115
+ var isDeny = action === "reject";
1116
+ container.classList.add(isDeny ? "resolved-denied" : "resolved-allowed");
1117
+
1118
+ var label = isDeny ? "Denied" : "Submitted";
1119
+ var actionsEl = container.querySelector(".permission-actions");
1120
+ if (actionsEl) {
1121
+ actionsEl.innerHTML = '<span class="permission-decision-label">' + label + '</span>';
1122
+ }
1123
+ delete pendingElicitations[requestId];
1124
+ }
1125
+
1126
+ // --- Plan mode rendering ---
1127
+ export function renderPlanBanner(type) {
1128
+ ctx.finalizeAssistantBlock();
1129
+ stopThinking();
1130
+ closeToolGroup();
1131
+
1132
+ var el = document.createElement("div");
1133
+ el.className = "plan-banner";
1134
+
1135
+ if (type === "enter") {
1136
+ inPlanMode = true;
1137
+ planContent = null;
1138
+ currentPlanCardEl = null;
1139
+ el.innerHTML =
1140
+ '<span class="plan-banner-icon">' + iconHtml("map") + '</span>' +
1141
+ '<span class="plan-banner-text">Entered plan mode</span>' +
1142
+ '<span class="plan-banner-hint">Exploring codebase and designing implementation...</span>';
1143
+ el.classList.add("plan-enter");
1144
+ } else {
1145
+ inPlanMode = false;
1146
+ el.innerHTML =
1147
+ '<span class="plan-banner-icon">' + iconHtml("check-circle") + '</span>' +
1148
+ '<span class="plan-banner-text">Plan ready for review</span>';
1149
+ el.classList.add("plan-exit");
1150
+ }
1151
+
1152
+ ctx.addToMessages(el);
1153
+ refreshIcons(el);
1154
+ maybeScrollToBottom();
1155
+ return el;
1156
+ }
1157
+
1158
+ export function renderPlanCard(content) {
1159
+ ctx.finalizeAssistantBlock();
1160
+ closeToolGroup();
1161
+ planContent = content;
1162
+
1163
+ var el = currentPlanCardEl && currentPlanCardEl.isConnected ? currentPlanCardEl : null;
1164
+ var header;
1165
+ var body;
1166
+ var isNew = !el;
1167
+ if (!el) {
1168
+ el = document.createElement("div");
1169
+ el.className = "plan-card";
1170
+
1171
+ header = document.createElement("div");
1172
+ header.className = "plan-card-header";
1173
+ header.innerHTML =
1174
+ '<span class="plan-card-icon">' + iconHtml("file-text") + '</span>' +
1175
+ '<span class="plan-card-title">Implementation Plan</span>' +
1176
+ '<button class="plan-card-copy" title="Copy plan">' + iconHtml("copy") + '</button>' +
1177
+ '<span class="plan-card-chevron">' + iconHtml("chevron-down") + '</span>';
1178
+
1179
+ body = document.createElement("div");
1180
+ body.className = "plan-card-body";
1181
+
1182
+ header.addEventListener("click", function () {
1183
+ el.classList.toggle("collapsed");
1184
+ });
1185
+
1186
+ el.appendChild(header);
1187
+ el.appendChild(body);
1188
+ ctx.addToMessages(el);
1189
+ currentPlanCardEl = el;
1190
+ } else {
1191
+ header = el.querySelector(".plan-card-header");
1192
+ body = el.querySelector(".plan-card-body");
1193
+ }
1194
+
1195
+ body.innerHTML = renderMarkdown(content);
1196
+ highlightCodeBlocks(body);
1197
+ renderMermaidBlocks(body);
1198
+
1199
+ var copyBtn = header.querySelector(".plan-card-copy");
1200
+ if (copyBtn) {
1201
+ copyBtn.onclick = function (e) {
1202
+ e.stopPropagation();
1203
+ copyToClipboard(content).then(function () {
1204
+ copyBtn.innerHTML = iconHtml("check");
1205
+ refreshIcons(copyBtn);
1206
+ setTimeout(function () {
1207
+ copyBtn.innerHTML = iconHtml("copy");
1208
+ refreshIcons(copyBtn);
1209
+ }, 1500);
1210
+ });
1211
+ };
1212
+ }
1213
+
1214
+ refreshIcons(el);
1215
+ if (isNew) maybeScrollToBottom();
1216
+ return el;
1217
+ }
1218
+
1219
+ // --- Todo rendering ---
1220
+ function todoStatusIcon(status) {
1221
+ switch (status) {
1222
+ case "completed": return iconHtml("check-circle");
1223
+ case "in_progress": return iconHtml("loader", "icon-spin");
1224
+ default: return iconHtml("circle");
1225
+ }
1226
+ }
1227
+
1228
+ export function handleTodoWrite(input) {
1229
+ if (!input || !Array.isArray(input.todos)) return;
1230
+ todoMeta = normalizeTodoMeta(input.meta);
1231
+ todoItems = input.todos.map(function (t, i) {
1232
+ return {
1233
+ id: t.id || String(i + 1),
1234
+ content: t.content || t.subject || "",
1235
+ status: t.status || "pending",
1236
+ activeForm: t.activeForm || "",
1237
+ };
1238
+ });
1239
+ // A fresh TodoWrite during replay is just historical state. After replay
1240
+ // ends, applyDeadSessionTodoCompaction (called from history_done) decides
1241
+ // whether to compact. During live operation, sessionIsProcessing is true
1242
+ // and applyDeadSessionTodoCompaction is a no-op for compaction.
1243
+ renderTodoWidget();
1244
+ applyDeadSessionTodoCompaction();
1245
+ }
1246
+
1247
+ export function handleTaskCreate(input) {
1248
+ if (!input) return;
1249
+ todoMeta = normalizeTodoMeta();
1250
+ var id = String(todoItems.length + 1);
1251
+ todoItems.push({
1252
+ id: id,
1253
+ content: input.subject || input.description || "",
1254
+ status: "pending",
1255
+ activeForm: input.activeForm || "",
1256
+ });
1257
+ renderTodoWidget();
1258
+ }
1259
+
1260
+ export function handleTaskUpdate(input) {
1261
+ if (!input || !input.taskId) return;
1262
+ todoMeta = normalizeTodoMeta();
1263
+ for (var i = 0; i < todoItems.length; i++) {
1264
+ if (todoItems[i].id === input.taskId) {
1265
+ if (input.status === "deleted") {
1266
+ todoItems.splice(i, 1);
1267
+ } else {
1268
+ if (input.status) todoItems[i].status = input.status;
1269
+ if (input.subject) todoItems[i].content = input.subject;
1270
+ if (input.activeForm) todoItems[i].activeForm = input.activeForm;
1271
+ }
1272
+ break;
1273
+ }
1274
+ }
1275
+ renderTodoWidget();
1276
+ }
1277
+
1278
+ function normalizeTodoMeta(meta) {
1279
+ if (meta && meta.variant === "plan") {
1280
+ return {
1281
+ variant: "plan",
1282
+ title: "Plan",
1283
+ icon: "map",
1284
+ showProgress: false,
1285
+ showCompletedCount: false,
1286
+ stickyEnabled: false,
1287
+ };
1288
+ }
1289
+ return {
1290
+ variant: "tasks",
1291
+ title: "Tasks",
1292
+ icon: "list-checks",
1293
+ showProgress: true,
1294
+ showCompletedCount: true,
1295
+ stickyEnabled: true,
1296
+ };
1297
+ }
1298
+
1299
+ function renderTodoWidget() {
1300
+ if (todoItems.length === 0) {
1301
+ if (todoWidgetEl) { todoWidgetEl.remove(); todoWidgetEl = null; }
1302
+ if (todoObserver) { todoObserver.disconnect(); todoObserver = null; }
1303
+ todoWidgetVisible = true;
1304
+ todoMeta = normalizeTodoMeta();
1305
+ updateTodoSticky();
1306
+ return;
1307
+ }
1308
+
1309
+ var isNew = !todoWidgetEl;
1310
+ if (isNew) {
1311
+ todoWidgetEl = document.createElement("div");
1312
+ todoWidgetEl.className = "todo-widget";
1313
+ }
1314
+ todoWidgetEl.className = "todo-widget"
1315
+ + (todoMeta.variant === "plan" ? " todo-widget-plan" : "")
1316
+ + (todoDeadCompact ? " todo-widget-dead-compact" : "");
1317
+
1318
+ var completed = 0;
1319
+ for (var i = 0; i < todoItems.length; i++) {
1320
+ if (todoItems[i].status === "completed") completed++;
1321
+ }
1322
+
1323
+ var countText = todoMeta.showCompletedCount
1324
+ ? (completed + "/" + todoItems.length)
1325
+ : (todoItems.length + " " + (todoItems.length === 1 ? "step" : "steps"));
1326
+
1327
+ var html = '<div class="todo-header">' +
1328
+ '<span class="todo-header-icon">' + iconHtml(todoMeta.icon) + '</span>' +
1329
+ '<span class="todo-header-title">' + todoMeta.title + '</span>' +
1330
+ '<span class="todo-header-count">' + countText + '</span>' +
1331
+ '</div>';
1332
+ if (todoMeta.showProgress) {
1333
+ html += '<div class="todo-progress"><div class="todo-progress-bar" style="width:' +
1334
+ (todoItems.length > 0 ? Math.round(completed / todoItems.length * 100) : 0) + '%"></div></div>';
1335
+ }
1336
+ html += '<div class="todo-items">';
1337
+ for (var i = 0; i < todoItems.length; i++) {
1338
+ var t = todoItems[i];
1339
+ var statusClass = t.status === "completed" ? "completed" : t.status === "in_progress" ? "in-progress" : "pending";
1340
+ html += '<div class="todo-item ' + statusClass + '">' +
1341
+ '<span class="todo-item-icon">' + todoStatusIcon(t.status) + '</span>' +
1342
+ '<span class="todo-item-text">' + escapeHtml(t.status === "in_progress" && t.activeForm ? t.activeForm : t.content) + '</span>' +
1343
+ '</div>';
1344
+ }
1345
+ html += '</div>';
1346
+
1347
+ todoWidgetEl.innerHTML = html;
1348
+
1349
+ if (isNew) {
1350
+ ctx.addToMessages(todoWidgetEl);
1351
+ setupTodoObserver();
1352
+ // Click-to-expand for compact mode. Toggling the override class lets
1353
+ // the user inspect items without permanently un-compacting the widget.
1354
+ todoWidgetEl.addEventListener("click", function (e) {
1355
+ if (!todoWidgetEl.classList.contains("todo-widget-dead-compact")) return;
1356
+ // Only expand on header click, not on items inside an already-expanded view
1357
+ var header = e.target.closest(".todo-header");
1358
+ if (!header) return;
1359
+ todoWidgetEl.classList.toggle("todo-widget-dead-expanded");
1360
+ });
1361
+ }
1362
+ updateTodoSticky();
1363
+ refreshIcons(todoWidgetEl);
1364
+ maybeScrollToBottom();
1365
+ }
1366
+
1367
+ export function applyDeadSessionTodoCompaction() {
1368
+ // Called after history_done and on status changes. Decides whether the
1369
+ // current session is "dead" (resumed, no live SDK process) and whether
1370
+ // the todo widget has unfinished items that will never resolve.
1371
+ var isLive = !!store.get('sessionIsProcessing');
1372
+ var hasUnfinished = false;
1373
+ for (var i = 0; i < todoItems.length; i++) {
1374
+ var s = todoItems[i].status;
1375
+ if (s === "in_progress" || s === "pending") { hasUnfinished = true; break; }
1376
+ }
1377
+ todoDeadCompact = !isLive && hasUnfinished;
1378
+ if (todoWidgetEl) {
1379
+ todoWidgetEl.classList.toggle("todo-widget-dead-compact", todoDeadCompact);
1380
+ if (!todoDeadCompact) todoWidgetEl.classList.remove("todo-widget-dead-expanded");
1381
+ }
1382
+ }
1383
+
1384
+ function setupTodoObserver() {
1385
+ if (todoObserver) { todoObserver.disconnect(); todoObserver = null; }
1386
+ if (!todoWidgetEl) return;
1387
+
1388
+ var messagesEl = document.getElementById("messages");
1389
+ if (!messagesEl) return;
1390
+
1391
+ todoObserver = new IntersectionObserver(function (entries) {
1392
+ todoWidgetVisible = entries[0].isIntersecting;
1393
+ updateTodoStickyVisibility();
1394
+ }, { root: messagesEl, threshold: 0 });
1395
+
1396
+ todoObserver.observe(todoWidgetEl);
1397
+ }
1398
+
1399
+ function updateTodoStickyVisibility() {
1400
+ var stickyEl = document.getElementById("todo-sticky");
1401
+ if (!stickyEl) return;
1402
+ if (!todoMeta.stickyEnabled) {
1403
+ stickyEl.classList.add("hidden");
1404
+ return;
1405
+ }
1406
+
1407
+ if (todoWidgetVisible) {
1408
+ stickyEl.classList.add("hidden");
1409
+ } else {
1410
+ // Only show if there are active (non-completed) tasks
1411
+ var hasActive = false;
1412
+ for (var i = 0; i < todoItems.length; i++) {
1413
+ if (todoItems[i].status !== "completed") { hasActive = true; break; }
1414
+ }
1415
+ if (hasActive) {
1416
+ stickyEl.classList.remove("hidden");
1417
+ }
1418
+ }
1419
+ }
1420
+
1421
+ function updateTodoSticky() {
1422
+ var stickyEl = document.getElementById("todo-sticky");
1423
+ if (!stickyEl) return;
1424
+ if (!todoMeta.stickyEnabled) {
1425
+ stickyEl.classList.add("hidden");
1426
+ stickyEl.innerHTML = "";
1427
+ return;
1428
+ }
1429
+
1430
+ // Hide if no active tasks (all completed or empty)
1431
+ var hasActive = false;
1432
+ for (var i = 0; i < todoItems.length; i++) {
1433
+ if (todoItems[i].status !== "completed") { hasActive = true; break; }
1434
+ }
1435
+ if (!hasActive) {
1436
+ stickyEl.classList.add("hidden");
1437
+ return;
1438
+ }
1439
+
1440
+ var completed = 0;
1441
+ for (var i = 0; i < todoItems.length; i++) {
1442
+ if (todoItems[i].status === "completed") completed++;
1443
+ }
1444
+ var pct = Math.round(completed / todoItems.length * 100);
1445
+ var wasCollapsed = stickyEl.innerHTML === "" ? true : stickyEl.classList.contains("collapsed");
1446
+
1447
+ var inProgressItem = null;
1448
+ for (var j = 0; j < todoItems.length; j++) {
1449
+ if (todoItems[j].status === "in_progress") { inProgressItem = todoItems[j]; break; }
1450
+ }
1451
+
1452
+ var html = '<div class="todo-sticky-inner">' +
1453
+ '<div class="todo-sticky-header">' +
1454
+ '<span class="todo-sticky-icon">' + iconHtml("list-checks") + '</span>' +
1455
+ '<span class="todo-sticky-title">Tasks</span>' +
1456
+ (inProgressItem ? '<span class="todo-sticky-active">' + iconHtml("loader", "icon-spin") + ' ' + escapeHtml(inProgressItem.activeForm || inProgressItem.content) + '</span>' : '') +
1457
+ '<span class="todo-sticky-count">' + completed + '/' + todoItems.length + '</span>' +
1458
+ '<span class="todo-sticky-chevron">' + iconHtml("chevron-down") + '</span>' +
1459
+ '</div>' +
1460
+ '<div class="todo-sticky-progress"><div class="todo-sticky-progress-bar" style="width:' + pct + '%"></div></div>' +
1461
+ '<div class="todo-sticky-items">';
1462
+
1463
+ for (var i = 0; i < todoItems.length; i++) {
1464
+ var t = todoItems[i];
1465
+ var statusClass = t.status === "completed" ? "completed" : t.status === "in_progress" ? "in-progress" : "pending";
1466
+ html += '<div class="todo-sticky-item ' + statusClass + '">' +
1467
+ '<span class="todo-sticky-item-icon">' + todoStatusIcon(t.status) + '</span>' +
1468
+ '<span class="todo-sticky-item-text">' + escapeHtml(t.status === "in_progress" && t.activeForm ? t.activeForm : t.content) + '</span>' +
1469
+ '</div>';
1470
+ }
1471
+
1472
+ html += '</div></div>';
1473
+ stickyEl.innerHTML = html;
1474
+
1475
+ // Only show sticky when in-chat widget is not visible in viewport
1476
+ if (todoWidgetVisible) {
1477
+ stickyEl.classList.add("hidden");
1478
+ } else {
1479
+ stickyEl.classList.remove("hidden");
1480
+ }
1481
+ if (wasCollapsed) stickyEl.classList.add("collapsed");
1482
+
1483
+ stickyEl.querySelector(".todo-sticky-header").addEventListener("click", function () {
1484
+ stickyEl.classList.toggle("collapsed");
1485
+ });
1486
+
1487
+ refreshIcons(stickyEl);
1488
+ }
1489
+
1490
+ // --- Thinking ---
1491
+ export function startThinking() {
1492
+ ctx.finalizeAssistantBlock();
1493
+
1494
+ // Reuse existing thinking group if consecutive
1495
+ if (thinkingGroup && thinkingGroup.el.classList.contains("done")) {
1496
+ var el = thinkingGroup.el;
1497
+ el.classList.remove("done");
1498
+ el.querySelector(".thinking-content").textContent = "";
1499
+ currentThinking = { el: el, fullText: "", startTime: Date.now() };
1500
+ refreshIcons(el);
1501
+ maybeScrollToBottom();
1502
+ ctx.setActivity("thinking");
1503
+ return;
1504
+ }
1505
+
1506
+ var el = document.createElement("div");
1507
+ el.className = "thinking-item";
1508
+
1509
+ el.innerHTML =
1510
+ '<div class="thinking-header">' +
1511
+ '<span class="thinking-chevron">' + iconHtml("chevron-right") + '</span>' +
1512
+ '<span class="thinking-label">Thinking</span>' +
1513
+ '<span class="thinking-duration"></span>' +
1514
+ '<span class="thinking-spinner">' + iconHtml("loader", "icon-spin") + '</span>' +
1515
+ '</div>' +
1516
+ '<div class="thinking-content"></div>';
1517
+
1518
+ el.querySelector(".thinking-header").addEventListener("click", function () {
1519
+ el.classList.toggle("expanded");
1520
+ });
1521
+
1522
+ ctx.addToMessages(el);
1523
+ refreshIcons(el);
1524
+ maybeScrollToBottom();
1525
+ thinkingGroup = { el: el, count: 0, totalDuration: 0 };
1526
+ currentThinking = { el: el, fullText: "", startTime: Date.now() };
1527
+ ctx.setActivity("thinking");
1528
+ }
1529
+
1530
+ export function appendThinking(text) {
1531
+ if (!currentThinking) return;
1532
+ currentThinking.fullText += text;
1533
+ currentThinking.el.querySelector(".thinking-content").textContent = currentThinking.fullText;
1534
+ maybeScrollToBottom();
1535
+ }
1536
+
1537
+ export function stopThinking(duration) {
1538
+ if (!currentThinking) return;
1539
+ var secs = typeof duration === "number" ? duration : (Date.now() - currentThinking.startTime) / 1000;
1540
+ currentThinking.el.classList.add("done");
1541
+ if (thinkingGroup && thinkingGroup.el === currentThinking.el) {
1542
+ thinkingGroup.count++;
1543
+ thinkingGroup.totalDuration += secs;
1544
+ currentThinking.el.querySelector(".thinking-duration").textContent = " " + thinkingGroup.totalDuration.toFixed(1) + "s";
1545
+ } else {
1546
+ currentThinking.el.querySelector(".thinking-duration").textContent = " " + secs.toFixed(1) + "s";
1547
+ }
1548
+ // If no thinking text was streamed (e.g. Codex reasoning items arrive
1549
+ // with encrypted/hidden content, or Claude without extended-thinking),
1550
+ // the expand affordance is misleading because there's nothing inside.
1551
+ // Strip the chevron and the click handler so the header reads as a
1552
+ // plain label.
1553
+ var hasContent = !!(currentThinking.fullText && currentThinking.fullText.length > 0);
1554
+ if (!hasContent) {
1555
+ currentThinking.el.classList.add("empty");
1556
+ var chev = currentThinking.el.querySelector(".thinking-chevron");
1557
+ if (chev) chev.style.display = "none";
1558
+ var hdr = currentThinking.el.querySelector(".thinking-header");
1559
+ if (hdr) {
1560
+ hdr.style.cursor = "default";
1561
+ // Replace click listener by cloning the node (cheapest way to strip listeners).
1562
+ var clone = hdr.cloneNode(true);
1563
+ hdr.parentNode.replaceChild(clone, hdr);
1564
+ }
1565
+ }
1566
+ currentThinking = null;
1567
+ }
1568
+
1569
+ export function resetThinkingGroup() {
1570
+ thinkingGroup = null;
1571
+ }
1572
+
1573
+ // --- Tool items ---
1574
+ export function createToolItem(id, name) {
1575
+ ctx.finalizeAssistantBlock();
1576
+ stopThinking();
1577
+
1578
+ // Group management: create new group or reuse existing open group
1579
+ if (!currentToolGroup || currentToolGroup.closed) {
1580
+ toolGroupCounter++;
1581
+ var groupEl = document.createElement("div");
1582
+ groupEl.className = "tool-group";
1583
+ groupEl.dataset.groupId = "g" + toolGroupCounter;
1584
+
1585
+ var toolGroupInner =
1586
+ '<div class="tool-group-header" style="display:none">' +
1587
+ '<span class="tool-group-chevron">' + iconHtml("chevron-right") + '</span>' +
1588
+ '<span class="tool-group-bullet"></span>' +
1589
+ '<span class="tool-group-label">Running...</span>' +
1590
+ '<span class="tool-group-status-icon">' + iconHtml("loader", "icon-spin") + '</span>' +
1591
+ '</div>' +
1592
+ '<div class="tool-group-items"></div>';
1593
+
1594
+ groupEl.innerHTML = toolGroupInner;
1595
+
1596
+ groupEl.querySelector(".tool-group-header").addEventListener("click", function () {
1597
+ groupEl.classList.toggle("collapsed");
1598
+ if (currentToolGroup) currentToolGroup.userToggled = true;
1599
+ });
1600
+
1601
+ ctx.addToMessages(groupEl);
1602
+ refreshIcons(groupEl);
1603
+
1604
+ currentToolGroup = {
1605
+ el: groupEl,
1606
+ id: "g" + toolGroupCounter,
1607
+ toolNames: [],
1608
+ toolCount: 0,
1609
+ doneCount: 0,
1610
+ errorCount: 0,
1611
+ closed: false,
1612
+ };
1613
+ toolGroups[currentToolGroup.id] = currentToolGroup;
1614
+ }
1615
+
1616
+ var el = document.createElement("div");
1617
+ el.className = "tool-item";
1618
+ el.dataset.toolId = id;
1619
+ el.innerHTML =
1620
+ '<div class="tool-header">' +
1621
+ '<span class="tool-chevron">' + iconHtml("chevron-right") + '</span>' +
1622
+ '<span class="tool-bullet"></span>' +
1623
+ '<span class="tool-name"></span>' +
1624
+ '<span class="tool-desc"></span>' +
1625
+ '<span class="tool-status-icon">' + iconHtml("loader", "icon-spin") + '</span>' +
1626
+ '</div>' +
1627
+ '<div class="tool-subtitle">' +
1628
+ '<span class="tool-connector">&#9492;</span>' +
1629
+ '<span class="tool-subtitle-text">Running...</span>' +
1630
+ '</div>';
1631
+
1632
+ el.querySelector(".tool-name").textContent = name;
1633
+
1634
+ // Append to group instead of messages directly
1635
+ currentToolGroup.el.querySelector(".tool-group-items").appendChild(el);
1636
+ currentToolGroup.toolNames.push(name);
1637
+ currentToolGroup.toolCount++;
1638
+ updateToolGroupHeader(currentToolGroup);
1639
+
1640
+ refreshIcons(el);
1641
+ maybeScrollToBottom();
1642
+
1643
+ tools[id] = { el: el, name: name, input: null, done: false, groupId: currentToolGroup.id };
1644
+ ctx.setActivity("Running " + name + "...");
1645
+ }
1646
+
1647
+ export function updateToolExecuting(id, name, input) {
1648
+ var tool = tools[id];
1649
+ if (!tool) return;
1650
+
1651
+ tool.input = input;
1652
+ var descEl = tool.el.querySelector(".tool-desc");
1653
+ descEl.textContent = toolSummary(name, input);
1654
+
1655
+ // Make file path clickable for Read/Edit/Write tools
1656
+ var filePath = input && input.file_path;
1657
+ if (filePath && (name === "Read" || name === "Edit" || name === "Write")) {
1658
+ descEl.classList.add("tool-desc-link");
1659
+ descEl.dataset.filePath = filePath;
1660
+ descEl.insertAdjacentHTML("beforeend", '<span class="tool-desc-link-icon">' + iconHtml("external-link") + '</span>');
1661
+ refreshIcons(descEl);
1662
+ (function (toolName, toolInput) {
1663
+ descEl.onclick = function (e) {
1664
+ e.stopPropagation();
1665
+ if (toolName === "Edit" && toolInput && (toolInput.old_string || toolInput.new_string)) {
1666
+ openFile(filePath, { diff: { oldStr: toolInput.old_string || "", newStr: toolInput.new_string || "" } });
1667
+ } else {
1668
+ openFile(filePath);
1669
+ }
1670
+ };
1671
+ })(name, input);
1672
+ }
1673
+
1674
+ ctx.setActivity(toolActivityText(name, input));
1675
+
1676
+ var subtitleText = tool.el.querySelector(".tool-subtitle-text");
1677
+ if (subtitleText) subtitleText.textContent = toolActivityText(name, input);
1678
+
1679
+ maybeScrollToBottom();
1680
+ }
1681
+
1682
+ // Shared chrome (filename header + unified/split toggle) for diff renderings.
1683
+ // makeUnified and makeSplit are factories that return a fresh body element.
1684
+ function buildDiffChrome(filePath, linkOldStr, linkNewStr, makeUnified, makeSplit) {
1685
+ var wrapper = document.createElement("div");
1686
+ wrapper.className = "edit-diff";
1687
+
1688
+ var header = document.createElement("div");
1689
+ header.className = "edit-diff-header";
1690
+
1691
+ var pathSpan = document.createElement("span");
1692
+ pathSpan.className = "edit-diff-path edit-diff-path-link";
1693
+ pathSpan.textContent = filePath || "";
1694
+ if (filePath) {
1695
+ (function (fp, os, ns) {
1696
+ pathSpan.addEventListener("click", function (e) {
1697
+ e.stopPropagation();
1698
+ openFile(fp, { diff: { oldStr: os || "", newStr: ns || "" } });
1699
+ });
1700
+ })(filePath, linkOldStr, linkNewStr);
1701
+ }
1702
+ header.appendChild(pathSpan);
1703
+
1704
+ var isMobile = "ontouchstart" in window;
1705
+ var isSplit = false;
1706
+
1707
+ var unifiedBtn = document.createElement("button");
1708
+ unifiedBtn.className = "edit-diff-toggle active";
1709
+ unifiedBtn.innerHTML = iconHtml("list");
1710
+ unifiedBtn.title = "Unified view";
1711
+
1712
+ var splitBtn = document.createElement("button");
1713
+ splitBtn.className = "edit-diff-toggle";
1714
+ splitBtn.innerHTML = iconHtml("columns-2");
1715
+ splitBtn.title = "Split view";
1716
+
1717
+ var toggleWrap = document.createElement("span");
1718
+ toggleWrap.className = "edit-diff-toggles";
1719
+ if (isMobile) toggleWrap.style.display = "none";
1720
+ toggleWrap.appendChild(unifiedBtn);
1721
+ toggleWrap.appendChild(splitBtn);
1722
+ header.appendChild(toggleWrap);
1723
+
1724
+ wrapper.appendChild(header);
1725
+
1726
+ var currentBody = makeUnified();
1727
+ wrapper.appendChild(currentBody);
1728
+
1729
+ unifiedBtn.addEventListener("click", function (e) {
1730
+ e.stopPropagation();
1731
+ if (!isSplit) return;
1732
+ isSplit = false;
1733
+ unifiedBtn.classList.add("active");
1734
+ splitBtn.classList.remove("active");
1735
+ wrapper.removeChild(currentBody);
1736
+ currentBody = makeUnified();
1737
+ wrapper.appendChild(currentBody);
1738
+ refreshIcons(wrapper);
1739
+ });
1740
+
1741
+ splitBtn.addEventListener("click", function (e) {
1742
+ e.stopPropagation();
1743
+ if (isSplit) return;
1744
+ isSplit = true;
1745
+ splitBtn.classList.add("active");
1746
+ unifiedBtn.classList.remove("active");
1747
+ wrapper.removeChild(currentBody);
1748
+ currentBody = makeSplit();
1749
+ wrapper.appendChild(currentBody);
1750
+ refreshIcons(wrapper);
1751
+ });
1752
+
1753
+ return wrapper;
1754
+ }
1755
+
1756
+ function renderEditDiff(oldStr, newStr, filePath) {
1757
+ var lang = getLanguageFromPath(filePath);
1758
+ return buildDiffChrome(
1759
+ filePath,
1760
+ oldStr,
1761
+ newStr,
1762
+ function () { return renderUnifiedDiff(oldStr, newStr, lang); },
1763
+ function () { return renderSplitDiff(oldStr, newStr, lang); }
1764
+ );
1765
+ }
1766
+
1767
+ function renderPatchDiffBlock(patchText, filePath) {
1768
+ var lang = getLanguageFromPath(filePath);
1769
+ var sources = reconstructPatchSources(patchText);
1770
+ return buildDiffChrome(
1771
+ filePath,
1772
+ sources.oldStr,
1773
+ sources.newStr,
1774
+ function () { return renderPatchDiff(patchText, lang); },
1775
+ function () { return renderSplitDiff(sources.oldStr, sources.newStr, lang); }
1776
+ );
1777
+ }
1778
+
1779
+ function isDiffContent(text) {
1780
+ var lines = text.split("\n");
1781
+ var hasHunkHeader = false;
1782
+ var hasPatchLine = false;
1783
+ for (var i = 0; i < Math.min(lines.length, 20); i++) {
1784
+ var l = lines[i];
1785
+ if (l.startsWith("@@")) hasHunkHeader = true;
1786
+ if (l.startsWith("---") || l.startsWith("+++")) hasPatchLine = true;
1787
+ if ((l.startsWith("+") && !l.startsWith("+++")) || (l.startsWith("-") && !l.startsWith("---"))) {
1788
+ hasPatchLine = true;
1789
+ }
1790
+ }
1791
+ return (hasHunkHeader && hasPatchLine) || hasPatchLine;
1792
+ }
1793
+
1794
+ function getLanguageFromPath(filePath) {
1795
+ if (!filePath) return null;
1796
+ var parts = filePath.split("/");
1797
+ var filename = parts[parts.length - 1].toLowerCase();
1798
+ var dotIdx = filename.lastIndexOf(".");
1799
+ if (dotIdx === -1 || dotIdx === filename.length - 1) return null;
1800
+ var ext = filename.substring(dotIdx + 1);
1801
+ var map = {
1802
+ js: "javascript", jsx: "javascript", mjs: "javascript", cjs: "javascript",
1803
+ ts: "typescript", tsx: "typescript", mts: "typescript",
1804
+ py: "python", rb: "ruby", rs: "rust", go: "go",
1805
+ java: "java", kt: "kotlin", kts: "kotlin",
1806
+ cs: "csharp", cpp: "cpp", cc: "cpp", c: "c", h: "c", hpp: "cpp",
1807
+ css: "css", scss: "scss", less: "less",
1808
+ html: "xml", htm: "xml", xml: "xml", svg: "xml",
1809
+ json: "json", yaml: "yaml", yml: "yaml",
1810
+ md: "markdown", sh: "bash", bash: "bash", zsh: "bash",
1811
+ sql: "sql", swift: "swift", php: "php",
1812
+ toml: "ini", ini: "ini", conf: "ini",
1813
+ lua: "lua", r: "r", pl: "perl",
1814
+ ex: "elixir", exs: "elixir",
1815
+ erl: "erlang", hs: "haskell",
1816
+ graphql: "graphql", gql: "graphql",
1817
+ };
1818
+ return map[ext] || null;
1819
+ }
1820
+
1821
+ function parseLineNumberedContent(text) {
1822
+ var lines = text.split("\n");
1823
+ if (lines.length > 0 && lines[lines.length - 1] === "") {
1824
+ lines.pop();
1825
+ }
1826
+ if (lines.length === 0) return null;
1827
+
1828
+ var pattern = /^\s*(\d+)[→\t](.*)$/;
1829
+ var checkCount = Math.min(lines.length, 5);
1830
+ var matchCount = 0;
1831
+ for (var i = 0; i < checkCount; i++) {
1832
+ if (pattern.test(lines[i])) matchCount++;
1833
+ }
1834
+ if (matchCount < Math.ceil(checkCount * 0.6)) return null;
1835
+
1836
+ var numbers = [];
1837
+ var code = [];
1838
+ for (var i = 0; i < lines.length; i++) {
1839
+ var m = lines[i].match(pattern);
1840
+ if (m) {
1841
+ numbers.push(m[1]);
1842
+ code.push(m[2]);
1843
+ } else {
1844
+ numbers.push("");
1845
+ code.push(lines[i]);
1846
+ }
1847
+ }
1848
+ return { numbers: numbers, code: code };
1849
+ }
1850
+
1851
+ var IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".bmp", ".ico"]);
1852
+
1853
+ function isImagePath(filePath) {
1854
+ if (!filePath) return false;
1855
+ var dotIdx = filePath.lastIndexOf(".");
1856
+ if (dotIdx === -1) return false;
1857
+ return IMAGE_EXTS.has(filePath.substring(dotIdx).toLowerCase());
1858
+ }
1859
+
1860
+ export function updateToolResult(id, content, isError, images) {
1861
+ var tool = tools[id];
1862
+ if (!tool) return;
1863
+
1864
+ var subtitleText = tool.el.querySelector(".tool-subtitle-text");
1865
+ if (subtitleText && tool.input) {
1866
+ subtitleText.textContent = toolActivityText(tool.name, tool.input);
1867
+ }
1868
+
1869
+ var resultBlock = document.createElement("div");
1870
+ var displayContent = content || "(no output)";
1871
+ displayContent = displayContent.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "").trim();
1872
+ if (displayContent.length > 10000) displayContent = displayContent.substring(0, 10000) + "\n... (truncated)";
1873
+
1874
+ var hasEditDiff = !isError && tool.name === "Edit" && tool.input && tool.input.old_string && tool.input.new_string;
1875
+ var expandByDefault = hasEditDiff || (!isError && tool.name === "Edit" && isDiffContent(displayContent));
1876
+ if (expandByDefault) {
1877
+ resultBlock.className = "tool-result-block";
1878
+ tool.el.classList.add("expanded");
1879
+ } else {
1880
+ resultBlock.className = "tool-result-block collapsed";
1881
+ }
1882
+
1883
+ if (hasEditDiff) {
1884
+ resultBlock.appendChild(renderEditDiff(tool.input.old_string, tool.input.new_string, tool.input.file_path));
1885
+ } else if (!isError && isDiffContent(displayContent)) {
1886
+ var patchFilePath = tool.input && tool.input.file_path ? tool.input.file_path : null;
1887
+ if (patchFilePath) {
1888
+ resultBlock.appendChild(renderPatchDiffBlock(displayContent, patchFilePath));
1889
+ } else {
1890
+ resultBlock.appendChild(renderPatchDiff(displayContent, null));
1891
+ }
1892
+ } else if (!isError && tool.name === "Read" && tool.input && tool.input.file_path && isImagePath(tool.input.file_path)) {
1893
+ // Image file: show inline preview
1894
+ var imgWrap = document.createElement("div");
1895
+ imgWrap.className = "tool-result-image";
1896
+ var img = document.createElement("img");
1897
+ if (images && images.length > 0) {
1898
+ img.src = "data:" + images[0].mediaType + ";base64," + images[0].data;
1899
+ } else {
1900
+ img.src = "api/file?path=" + encodeURIComponent(tool.input.file_path);
1901
+ }
1902
+ img.alt = tool.input.file_path.split("/").pop();
1903
+ img.draggable = false;
1904
+ img.addEventListener("click", function (e) {
1905
+ e.stopPropagation();
1906
+ e.preventDefault();
1907
+ if (ctx.showImageModal) ctx.showImageModal(this.src);
1908
+ });
1909
+ imgWrap.appendChild(img);
1910
+ resultBlock.appendChild(imgWrap);
1911
+ resultBlock.className = "tool-result-block";
1912
+ tool.el.classList.add("expanded");
1913
+ } else if (!isError && tool.name === "Read" && tool.input && tool.input.file_path) {
1914
+ var parsed = parseLineNumberedContent(displayContent);
1915
+ if (parsed) {
1916
+ var lang = getLanguageFromPath(tool.input.file_path);
1917
+ var viewer = document.createElement("div");
1918
+ viewer.className = "code-viewer";
1919
+
1920
+ var gutter = document.createElement("pre");
1921
+ gutter.className = "code-gutter";
1922
+ gutter.textContent = parsed.numbers.join("\n");
1923
+
1924
+ var codeBlock = document.createElement("pre");
1925
+ codeBlock.className = "code-content";
1926
+ var codeText = parsed.code.join("\n");
1927
+
1928
+ if (lang) {
1929
+ try {
1930
+ var highlighted = hljs.highlight(codeText, { language: lang });
1931
+ var codeEl = document.createElement("code");
1932
+ codeEl.className = "hljs language-" + lang;
1933
+ codeEl.innerHTML = highlighted.value;
1934
+ codeBlock.appendChild(codeEl);
1935
+ } catch (e) {
1936
+ codeBlock.textContent = codeText;
1937
+ }
1938
+ } else {
1939
+ codeBlock.textContent = codeText;
1940
+ }
1941
+
1942
+ viewer.appendChild(gutter);
1943
+ viewer.appendChild(codeBlock);
1944
+
1945
+ // Sync vertical scroll between gutter and code
1946
+ viewer.addEventListener("scroll", function () {
1947
+ gutter.scrollTop = viewer.scrollTop;
1948
+ codeBlock.scrollTop = viewer.scrollTop;
1949
+ });
1950
+
1951
+ resultBlock.appendChild(viewer);
1952
+ } else {
1953
+ var pre = document.createElement("pre");
1954
+ pre.textContent = displayContent;
1955
+ resultBlock.appendChild(pre);
1956
+ }
1957
+ } else {
1958
+ var pre = document.createElement("pre");
1959
+ if (isError) pre.className = "is-error";
1960
+ pre.textContent = displayContent;
1961
+ resultBlock.appendChild(pre);
1962
+ }
1963
+ tool.el.appendChild(resultBlock);
1964
+
1965
+ tool.el.querySelector(".tool-header").addEventListener("click", function () {
1966
+ resultBlock.classList.toggle("collapsed");
1967
+ tool.el.classList.toggle("expanded");
1968
+ });
1969
+
1970
+ markToolDone(id, isError);
1971
+ maybeScrollToBottom();
1972
+ }
1973
+
1974
+ export function markToolDone(id, isError) {
1975
+ var tool = tools[id];
1976
+ if (!tool || tool.done) return;
1977
+
1978
+ tool.done = true;
1979
+ if (!tool.el) return; // hidden tool (plan mode)
1980
+
1981
+ tool.el.classList.add("done");
1982
+ if (isError) tool.el.classList.add("error");
1983
+
1984
+ var icon = tool.el.querySelector(".tool-status-icon");
1985
+ if (isError) {
1986
+ icon.innerHTML = '<span class="err-icon">' + iconHtml("alert-triangle") + '</span>';
1987
+ } else {
1988
+ icon.innerHTML = '<span class="check">' + iconHtml("check") + '</span>';
1989
+ }
1990
+ refreshIcons(icon);
1991
+
1992
+ // Update group state
1993
+ if (tool.groupId) {
1994
+ var group = findToolGroup(tool.groupId);
1995
+ if (group) {
1996
+ group.doneCount++;
1997
+ if (isError) group.errorCount++;
1998
+ updateToolGroupHeader(group);
1999
+ }
2000
+ }
2001
+ }
2002
+
2003
+ export function markAllToolsDone() {
2004
+ for (var id in tools) {
2005
+ if (tools.hasOwnProperty(id) && !tools[id].done) {
2006
+ markToolDone(id, false);
2007
+ }
2008
+ }
2009
+ }
2010
+
2011
+ // --- Sub-agent (Task tool) log ---
2012
+ export function updateSubagentActivity(parentToolId, text) {
2013
+ var tool = tools[parentToolId];
2014
+ if (!tool || !tool.el) return;
2015
+
2016
+ // Update subtitle text with current activity
2017
+ var subtitleText = tool.el.querySelector(".tool-subtitle-text");
2018
+ if (subtitleText) subtitleText.textContent = text;
2019
+
2020
+ // Update or create the subagent log
2021
+ var log = tool.el.querySelector(".subagent-log");
2022
+ if (!log) {
2023
+ log = document.createElement("div");
2024
+ log.className = "subagent-log";
2025
+ tool.el.appendChild(log);
2026
+ }
2027
+
2028
+ ctx.setActivity(text);
2029
+ maybeScrollToBottom();
2030
+ }
2031
+
2032
+ export function addSubagentToolEntry(parentToolId, toolName, toolId, text) {
2033
+ var tool = tools[parentToolId];
2034
+ if (!tool || !tool.el) return;
2035
+
2036
+ // Update subtitle
2037
+ var subtitleText = tool.el.querySelector(".tool-subtitle-text");
2038
+ if (subtitleText) subtitleText.textContent = text;
2039
+
2040
+ // Create log if needed
2041
+ var log = tool.el.querySelector(".subagent-log");
2042
+ if (!log) {
2043
+ log = document.createElement("div");
2044
+ log.className = "subagent-log";
2045
+ tool.el.appendChild(log);
2046
+ }
2047
+
2048
+ // Add entry
2049
+ var entry = document.createElement("div");
2050
+ entry.className = "subagent-log-entry";
2051
+ entry.innerHTML =
2052
+ '<span class="subagent-log-bullet"></span>' +
2053
+ '<span class="subagent-log-tool"></span>' +
2054
+ '<span class="subagent-log-text"></span>';
2055
+ entry.querySelector(".subagent-log-tool").textContent = toolName;
2056
+ entry.querySelector(".subagent-log-text").textContent = text;
2057
+ log.appendChild(entry);
2058
+
2059
+ // Auto-scroll to latest entry
2060
+ log.scrollTop = log.scrollHeight;
2061
+
2062
+ ctx.setActivity(text);
2063
+ maybeScrollToBottom();
2064
+ }
2065
+
2066
+ function fmtTokens(n) {
2067
+ if (n >= 1000000) return (n / 1000000).toFixed(1) + "M";
2068
+ if (n >= 1000) return (n / 1000).toFixed(1) + "K";
2069
+ return String(n);
2070
+ }
2071
+
2072
+ function fmtDuration(ms) {
2073
+ var secs = Math.floor(ms / 1000);
2074
+ if (secs >= 60) return Math.floor(secs / 60) + "m " + (secs % 60) + "s";
2075
+ return secs + "s";
2076
+ }
2077
+
2078
+ export function updateSubagentProgress(parentToolId, usage, lastToolName, summary) {
2079
+ var tool = tools[parentToolId];
2080
+ if (!tool || !tool.el) return;
2081
+ var progressEl = tool.el.querySelector(".subagent-progress");
2082
+ if (!progressEl) {
2083
+ progressEl = document.createElement("div");
2084
+ progressEl.className = "subagent-progress";
2085
+ var log = tool.el.querySelector(".subagent-log");
2086
+ if (log) tool.el.insertBefore(progressEl, log);
2087
+ else tool.el.appendChild(progressEl);
2088
+ }
2089
+ var parts = [];
2090
+ if (usage) {
2091
+ if (usage.total_tokens) parts.push(fmtTokens(usage.total_tokens) + " tokens");
2092
+ if (usage.tool_uses) parts.push(usage.tool_uses + " tools");
2093
+ if (usage.duration_ms) parts.push(fmtDuration(usage.duration_ms));
2094
+ }
2095
+ if (lastToolName) parts.push(lastToolName);
2096
+ progressEl.textContent = parts.join(" · ");
2097
+
2098
+ // AI-generated progress summary (agentProgressSummaries)
2099
+ if (summary) {
2100
+ var summaryEl = tool.el.querySelector(".subagent-summary");
2101
+ if (!summaryEl) {
2102
+ summaryEl = document.createElement("div");
2103
+ summaryEl.className = "subagent-summary";
2104
+ progressEl.parentNode.insertBefore(summaryEl, progressEl.nextSibling);
2105
+ }
2106
+ summaryEl.textContent = summary;
2107
+ }
2108
+ }
2109
+
2110
+ export function initSubagentStop(parentToolId, taskId) {
2111
+ var tool = tools[parentToolId];
2112
+ if (!tool || !tool.el) return;
2113
+ var header = tool.el.querySelector(".tool-header");
2114
+ if (!header || header.querySelector(".subagent-stop-btn")) return;
2115
+ var btn = document.createElement("button");
2116
+ btn.className = "subagent-stop-btn";
2117
+ btn.textContent = "Stop";
2118
+ btn.addEventListener("click", function(e) {
2119
+ e.stopPropagation();
2120
+ if (ctx.ws) ctx.ws.send(JSON.stringify({ type: "stop_task", taskId: taskId, parentToolId: parentToolId }));
2121
+ btn.disabled = true;
2122
+ btn.textContent = "Stopping...";
2123
+ });
2124
+ header.appendChild(btn);
2125
+ }
2126
+
2127
+ export function updateSubagentTaskStatus(parentToolId, patch) {
2128
+ var tool = tools[parentToolId];
2129
+ if (!tool || !tool.el) return;
2130
+ if (patch.description) {
2131
+ var summaryEl = tool.el.querySelector(".subagent-summary");
2132
+ if (!summaryEl) {
2133
+ var progressEl = tool.el.querySelector(".subagent-progress");
2134
+ if (progressEl) {
2135
+ summaryEl = document.createElement("div");
2136
+ summaryEl.className = "subagent-summary";
2137
+ progressEl.parentNode.insertBefore(summaryEl, progressEl.nextSibling);
2138
+ }
2139
+ }
2140
+ if (summaryEl) summaryEl.textContent = patch.description;
2141
+ }
2142
+ if (patch.status === "failed" || patch.status === "killed") {
2143
+ var subtitleText = tool.el.querySelector(".tool-subtitle-text");
2144
+ if (subtitleText) subtitleText.textContent = patch.status === "failed" ? "Agent failed" : "Agent killed";
2145
+ var stopBtn = tool.el.querySelector(".subagent-stop-btn");
2146
+ if (stopBtn) stopBtn.remove();
2147
+ }
2148
+ }
2149
+
2150
+ export function markSubagentDone(parentToolId, status, summary, usage) {
2151
+ var tool = tools[parentToolId];
2152
+ if (!tool || !tool.el) return;
2153
+
2154
+ var label = "Agent finished";
2155
+ if (status === "failed") label = "Agent failed";
2156
+ else if (status === "stopped") label = "Agent stopped";
2157
+
2158
+ var subtitleText = tool.el.querySelector(".tool-subtitle-text");
2159
+ if (subtitleText) subtitleText.textContent = label;
2160
+
2161
+ // Remove stop button
2162
+ var stopBtn = tool.el.querySelector(".subagent-stop-btn");
2163
+ if (stopBtn) stopBtn.remove();
2164
+
2165
+ // Final usage update
2166
+ if (usage) updateSubagentProgress(parentToolId, usage, null);
2167
+ }
2168
+
2169
+ var _lastCumulativeCost = 0;
2170
+
2171
+ export function resetTurnMetaCost() {
2172
+ _lastCumulativeCost = 0;
2173
+ }
2174
+
2175
+ export function addTurnMeta(cost, duration) {
2176
+ closeToolGroup();
2177
+ var div = document.createElement("div");
2178
+ div.className = "turn-meta";
2179
+ div.dataset.turn = ctx.turnCounter;
2180
+ var parts = [];
2181
+ if (cost != null) {
2182
+ // cost is cumulative total_cost_usd from the SDK.
2183
+ // When the SDK session restarts, total_cost_usd resets to 0 so cost
2184
+ // can drop below _lastCumulativeCost. In that case the entire cost
2185
+ // value IS the delta for this turn (fresh SDK session).
2186
+ var delta = cost - _lastCumulativeCost;
2187
+ if (delta < 0) delta = cost;
2188
+ _lastCumulativeCost = cost;
2189
+ var deltaStr = delta > 0 ? "+$" + delta.toFixed(4) : "$0.0000";
2190
+ parts.push(deltaStr + " \u2192 $" + cost.toFixed(4));
2191
+ }
2192
+ if (duration != null) parts.push((duration / 1000).toFixed(1) + "s");
2193
+ if (parts.length) {
2194
+ div.textContent = parts.join(" \u00b7 ");
2195
+ ctx.addToMessages(div);
2196
+ maybeScrollToBottom();
2197
+ }
2198
+ }
2199
+
2200
+ // --- Tool group exports ---
2201
+ export { closeToolGroup };
2202
+
2203
+ export function removeToolFromGroup(toolId) {
2204
+ var tool = tools[toolId];
2205
+ if (!tool || !tool.groupId) return;
2206
+ var group = findToolGroup(tool.groupId);
2207
+ if (!group) return;
2208
+ group.toolCount--;
2209
+ // Remove tool name from the names array (remove first occurrence)
2210
+ var idx = group.toolNames.indexOf(tool.name);
2211
+ if (idx !== -1) group.toolNames.splice(idx, 1);
2212
+ if (tool.done) group.doneCount--;
2213
+ updateToolGroupHeader(group);
2214
+ }
2215
+
2216
+ // Expose state getters and reset
2217
+ export function getTools() { return tools; }
2218
+ export function isInPlanMode() { return inPlanMode; }
2219
+ export function getPlanContent() { return planContent; }
2220
+ export function setPlanContent(c) { planContent = c; }
2221
+ export function isPlanFilePath(fp) { return isPlanFile(fp); }
2222
+ export function getPlanModeTools() { return PLAN_MODE_TOOLS; }
2223
+ export function getTodoTools() { return TODO_TOOLS; }
2224
+ export function getHiddenResultTools() { return HIDDEN_RESULT_TOOLS; }
2225
+
2226
+ export function saveToolState() {
2227
+ return {
2228
+ tools: tools,
2229
+ currentThinking: currentThinking,
2230
+ todoWidgetEl: todoWidgetEl,
2231
+ todoMeta: todoMeta,
2232
+ inPlanMode: inPlanMode,
2233
+ planContent: planContent,
2234
+ currentPlanCardEl: currentPlanCardEl,
2235
+ currentToolGroup: currentToolGroup,
2236
+ toolGroupCounter: toolGroupCounter,
2237
+ toolGroups: toolGroups,
2238
+ lastCumulativeCost: _lastCumulativeCost,
2239
+ };
2240
+ }
2241
+
2242
+ export function restoreToolState(saved) {
2243
+ tools = saved.tools;
2244
+ currentThinking = saved.currentThinking;
2245
+ todoWidgetEl = saved.todoWidgetEl;
2246
+ todoMeta = saved.todoMeta || normalizeTodoMeta();
2247
+ inPlanMode = saved.inPlanMode;
2248
+ planContent = saved.planContent;
2249
+ currentPlanCardEl = saved.currentPlanCardEl || null;
2250
+ currentToolGroup = saved.currentToolGroup;
2251
+ toolGroupCounter = saved.toolGroupCounter;
2252
+ toolGroups = saved.toolGroups;
2253
+ _lastCumulativeCost = saved.lastCumulativeCost || 0;
2254
+ if (todoWidgetEl) {
2255
+ setupTodoObserver();
2256
+ }
2257
+ }
2258
+
2259
+ export function resetToolState() {
2260
+ tools = {};
2261
+ currentThinking = null;
2262
+ thinkingGroup = null;
2263
+ inPlanMode = false;
2264
+ planContent = null;
2265
+ currentPlanCardEl = null;
2266
+ todoItems = [];
2267
+ todoMeta = normalizeTodoMeta();
2268
+ todoWidgetEl = null;
2269
+ todoWidgetVisible = true;
2270
+ if (todoObserver) { todoObserver.disconnect(); todoObserver = null; }
2271
+ pendingPermissions = {};
2272
+ pendingElicitations = {};
2273
+ currentToolGroup = null;
2274
+ toolGroupCounter = 0;
2275
+ toolGroups = {};
2276
+ // NOTE: do NOT reset _lastCumulativeCost here — it must persist across
2277
+ // turns so addTurnMeta can compute per-turn deltas. It is only cleared
2278
+ // on new conversation via resetTurnMetaCost().
2279
+ var stickyEl = document.getElementById("todo-sticky");
2280
+ if (stickyEl) { stickyEl.classList.add("hidden"); stickyEl.innerHTML = ""; }
2281
+ }
2282
+
2283
+ export function initTools(_ctx) {
2284
+ ctx = _ctx;
2285
+ }