@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,739 @@
1
+ // app-rendering.js - Message rendering, streaming, scroll management, system messages
2
+ // Extracted from app.js (PR-28)
3
+
4
+ import { store } from './store.js';
5
+ import { getWs } from './ws-ref.js';
6
+ import { getMessagesEl, getInputEl, getSendBtn } from './dom-refs.js';
7
+ import { escapeHtml, copyToClipboard } from './utils.js';
8
+ import { renderMarkdown, renderMarkdownAsync, highlightCodeBlocks, renderMermaidBlocks } from './markdown.js';
9
+ import { iconHtml, refreshIcons } from './icons.js';
10
+ import { userAvatarUrl } from './avatar.js';
11
+ import { closeToolGroup } from './tools.js';
12
+ import { showImageModal, showPasteModal } from './app-misc.js';
13
+ import { sendMessage, hasSendableContent } from './input.js';
14
+ import { getChatLayout } from './theme.js';
15
+ import { getScheduledMsgEl } from './app-rate-limit.js';
16
+
17
+ export var VENDOR_AVATARS = {
18
+ claude: "/claude-code-avatar.png",
19
+ codex: "/codex-avatar.png",
20
+ };
21
+ export var VENDOR_NAMES = {
22
+ claude: "Claude Code",
23
+ codex: "Codex",
24
+ };
25
+ var NEW_MSG_BTN_DEFAULT = "\u2193 Latest";
26
+ var NEW_MSG_BTN_ACTIVITY = "\u2193 New activity";
27
+
28
+ // --- Module-owned state (not in store) ---
29
+ var turnCounter = 0;
30
+ var prependAnchor = null;
31
+ var activityEl = null;
32
+ var highlightTimer = null;
33
+ var streamBuffer = "";
34
+ var streamDrainTimer = null;
35
+ var streamRenderLen = 0; // length of currentFullText at last innerHTML render
36
+ var streamRenderPending = false; // true while worker parse is in flight
37
+ var currentFullTextLocal = ""; // module-local accumulator — not in store during streaming
38
+
39
+ export function resetCurrentFullText(v) {
40
+ currentFullTextLocal = v || "";
41
+ }
42
+ var isUserScrolledUp = false;
43
+ var scrollThreshold = 150;
44
+
45
+ // --- Sticky-bottom mode ---
46
+ // While armed, a ResizeObserver re-pins #messages to scrollHeight on every
47
+ // height change so deferred content (tools, syntax highlighting, images,
48
+ // IntersectionObserver-driven reflows) doesn't strand the user mid-page.
49
+ // The scroll listener in app.js consults getStickyBottom() and ignores
50
+ // growth-induced scroll events while armed.
51
+ //
52
+ // Disarm rules:
53
+ // - Real user input (wheel / touchmove / PageUp / Home / ArrowUp): immediate.
54
+ // - Quiet detector: armStickyBottom(durationMs) treats durationMs as the
55
+ // QUIET WINDOW, not a hard timer. Each ResizeObserver callback resets
56
+ // a debounce timer; sticky-bottom only disarms after no resize for
57
+ // durationMs. Long-settling sessions (large todo widgets, slow code
58
+ // highlighting) keep extending the window naturally.
59
+ // - Hard ceiling: a separate cap prevents pathological lock-in.
60
+ var stickyBottom = false;
61
+ var stickyBottomQuietTimer = null;
62
+ var stickyBottomCeilingTimer = null;
63
+ var stickyBottomQuietMs = 750;
64
+ var stickyBottomCeilingMs = 8000;
65
+ var stickyBottomResizeObs = null;
66
+ var stickyBottomInputBound = false;
67
+
68
+ export function getStickyBottom() { return stickyBottom; }
69
+
70
+ function pinToBottomNow() {
71
+ var messagesEl = getMessagesEl();
72
+ if (!messagesEl) return;
73
+ messagesEl.scrollTop = messagesEl.scrollHeight;
74
+ }
75
+
76
+ function ensureStickyInfrastructure() {
77
+ var messagesEl = getMessagesEl();
78
+ if (!messagesEl) return;
79
+ if (!stickyBottomResizeObs && typeof ResizeObserver !== "undefined") {
80
+ stickyBottomResizeObs = new ResizeObserver(function () {
81
+ if (!stickyBottom) return;
82
+ // Re-pin on every layout change while armed.
83
+ pinToBottomNow();
84
+ // Reset the quiet timer — settling has not finished yet.
85
+ if (stickyBottomQuietTimer) clearTimeout(stickyBottomQuietTimer);
86
+ stickyBottomQuietTimer = setTimeout(disarmStickyBottom, stickyBottomQuietMs);
87
+ });
88
+ // Observe the scroller itself. Child elements are picked up via
89
+ // MutationObserver below so we never accumulate O(n) observations
90
+ // across hundreds of messages — that caused a ResizeObserver callback
91
+ // storm on every autoResize() (textarea height change) on desktop.
92
+ stickyBottomResizeObs.observe(messagesEl);
93
+ }
94
+ // NOTE: We intentionally do NOT observe individual child elements of
95
+ // #messages. The ResizeObserver on #messages itself fires whenever the
96
+ // container's scrollHeight changes (image loads, tool expansions, syntax
97
+ // highlighting all change child heights which flow up to the scroller).
98
+ // Observing each child individually accumulates O(n messages) observations
99
+ // over a session's lifetime. When the textarea grows (autoResize) and the
100
+ // flex layout recalculates, the browser fires a ResizeObserver callback for
101
+ // every observed element — 50+ no-op callbacks per keypress in a long
102
+ // session. The container-level observer is sufficient for sticky-bottom
103
+ // purposes and costs a single callback per layout change.
104
+ if (!stickyBottomInputBound) {
105
+ stickyBottomInputBound = true;
106
+ var disarmOnUserScroll = function () { disarmStickyBottom(); };
107
+ messagesEl.addEventListener("wheel", disarmOnUserScroll, { passive: true });
108
+ messagesEl.addEventListener("touchmove", disarmOnUserScroll, { passive: true });
109
+ document.addEventListener("keydown", function (e) {
110
+ if (!stickyBottom) return;
111
+ if (e.key === "PageUp" || e.key === "Home" || e.key === "ArrowUp") {
112
+ disarmStickyBottom();
113
+ }
114
+ });
115
+ }
116
+ }
117
+
118
+ export function armStickyBottom(durationMs) {
119
+ if (prependAnchor) return; // never fight pagination
120
+ ensureStickyInfrastructure();
121
+ stickyBottom = true;
122
+ isUserScrolledUp = false;
123
+ var newMsgBtn = document.getElementById("new-msg-btn");
124
+ if (newMsgBtn) {
125
+ newMsgBtn.classList.add("hidden");
126
+ newMsgBtn.textContent = NEW_MSG_BTN_DEFAULT;
127
+ }
128
+ pinToBottomNow();
129
+ // Quiet window: callers pass intended quiet duration; ResizeObserver
130
+ // resets this each time layout changes, so the actual armed duration
131
+ // stretches to "no resize for durationMs".
132
+ stickyBottomQuietMs = durationMs || 750;
133
+ if (stickyBottomQuietTimer) clearTimeout(stickyBottomQuietTimer);
134
+ stickyBottomQuietTimer = setTimeout(disarmStickyBottom, stickyBottomQuietMs);
135
+ // Hard ceiling so we never lock the scroller indefinitely if some
136
+ // animation/observer keeps firing forever.
137
+ if (stickyBottomCeilingTimer) clearTimeout(stickyBottomCeilingTimer);
138
+ stickyBottomCeilingTimer = setTimeout(disarmStickyBottom, stickyBottomCeilingMs);
139
+ }
140
+
141
+ export function disarmStickyBottom() {
142
+ stickyBottom = false;
143
+ if (stickyBottomQuietTimer) { clearTimeout(stickyBottomQuietTimer); stickyBottomQuietTimer = null; }
144
+ if (stickyBottomCeilingTimer) { clearTimeout(stickyBottomCeilingTimer); stickyBottomCeilingTimer = null; }
145
+ }
146
+
147
+ export function initRendering() {
148
+ // Update input placeholder when vendor changes
149
+ store.subscribe(function (state, prev) {
150
+ if (state.currentVendor !== prev.currentVendor) {
151
+ var inputEl = document.getElementById("input");
152
+ if (inputEl) {
153
+ inputEl.placeholder = "Message " + (VENDOR_NAMES[state.currentVendor] || VENDOR_NAMES.claude) + "...";
154
+ }
155
+ }
156
+ });
157
+ }
158
+
159
+ // --- State accessors (module-local, not in store) ---
160
+ export function getTurnCounter() { return turnCounter; }
161
+ export function setTurnCounter(v) { turnCounter = v; }
162
+ export function getPrependAnchor() { return prependAnchor; }
163
+ export function setPrependAnchor(v) { prependAnchor = v; }
164
+ export function getActivityEl() { return activityEl; }
165
+ export function setActivityEl(v) { activityEl = v; }
166
+ export function getIsUserScrolledUp() { return isUserScrolledUp; }
167
+ export function setIsUserScrolledUp(v) { isUserScrolledUp = v; }
168
+
169
+ // --- Rendering functions ---
170
+
171
+ export function addToMessages(el) {
172
+ var messagesEl = getMessagesEl();
173
+ if (prependAnchor) messagesEl.insertBefore(el, prependAnchor);
174
+ else messagesEl.appendChild(el);
175
+ var _sme = getScheduledMsgEl();
176
+ if (_sme && el !== _sme && _sme.parentNode === messagesEl) {
177
+ messagesEl.appendChild(_sme);
178
+ }
179
+ }
180
+
181
+ export function scrollToBottom() {
182
+ if (prependAnchor) return;
183
+ var newMsgBtn = document.getElementById("new-msg-btn");
184
+ if (isUserScrolledUp) {
185
+ newMsgBtn.textContent = NEW_MSG_BTN_ACTIVITY;
186
+ newMsgBtn.classList.remove("hidden");
187
+ return;
188
+ }
189
+ var messagesEl = getMessagesEl();
190
+ requestAnimationFrame(function () {
191
+ messagesEl.scrollTop = messagesEl.scrollHeight;
192
+ });
193
+ }
194
+
195
+ export function forceScrollToBottom() {
196
+ if (prependAnchor) return;
197
+ // Arm sticky-bottom mode so deferred layout (tool widgets, code highlighting,
198
+ // image loads) can't strand the user partway down — single-rAF pin captures
199
+ // a stale scrollHeight, then growth below pushes the bottom further away.
200
+ // The quiet detector extends the window automatically while layout shifts.
201
+ armStickyBottom(750);
202
+ }
203
+
204
+ export function getMsgTime() {
205
+ var _ts = store.get('currentMsgTs');
206
+ var d = _ts ? new Date(_ts) : new Date();
207
+ var time = String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0");
208
+ var now = new Date();
209
+ if (d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()) {
210
+ return time;
211
+ }
212
+ return (d.getMonth() + 1) + "/" + d.getDate() + " " + time;
213
+ }
214
+
215
+ export function shouldGroupMessage(senderClass) {
216
+ var _s = store.snap();
217
+ if (_s.replayingHistory && !_s.currentMsgTs) return false;
218
+ var prev = getMessagesEl().lastElementChild;
219
+ if (!prev || !prev.classList.contains(senderClass)) return false;
220
+ var prevTime = prev.querySelector(".dm-bubble-time");
221
+ if (!prevTime) return false;
222
+ return prevTime.textContent === getMsgTime();
223
+ }
224
+
225
+ export function ensureAssistantBlock() {
226
+ var _el = store.get('currentMsgEl');
227
+ if (!_el) {
228
+ _el = document.createElement("div");
229
+ _el.className = "msg-assistant";
230
+ _el.dataset.turn = turnCounter;
231
+
232
+ var grouped = shouldGroupMessage("msg-assistant");
233
+ if (grouped) _el.classList.add("grouped");
234
+
235
+ var vendor = store.get('currentVendor') || "claude";
236
+ var avi = document.createElement("img");
237
+ avi.className = "dm-bubble-avatar dm-bubble-avatar-mate";
238
+ avi.src = VENDOR_AVATARS[vendor] || VENDOR_AVATARS.claude;
239
+ _el.appendChild(avi);
240
+
241
+ var contentWrap = document.createElement("div");
242
+ contentWrap.className = "dm-bubble-content";
243
+
244
+ var header = document.createElement("div");
245
+ header.className = "dm-bubble-header";
246
+ var nameSpan = document.createElement("span");
247
+ nameSpan.className = "dm-bubble-name";
248
+ nameSpan.textContent = VENDOR_NAMES[vendor] || VENDOR_NAMES.claude;
249
+ header.appendChild(nameSpan);
250
+ var timeSpan = document.createElement("span");
251
+ timeSpan.className = "dm-bubble-time";
252
+ timeSpan.textContent = getMsgTime();
253
+ header.appendChild(timeSpan);
254
+ contentWrap.appendChild(header);
255
+
256
+ var mdDiv = document.createElement("div");
257
+ mdDiv.className = "md-content";
258
+ mdDiv.dir = "auto";
259
+ contentWrap.appendChild(mdDiv);
260
+ _el.appendChild(contentWrap);
261
+ addToMessages(_el);
262
+ currentFullTextLocal = "";
263
+ store.set({ currentMsgEl: _el, currentFullText: "" });
264
+ }
265
+ return _el;
266
+ }
267
+
268
+ // Single document-level click handler shared across all copy handlers.
269
+ // Replaces per-message document.addEventListener to prevent listener leak
270
+ // (previously grew unbounded with conversation length).
271
+ var _primedCopyEl = null;
272
+ var _primedCopyReset = null;
273
+ document.addEventListener("click", function (e) {
274
+ if (_primedCopyEl && !_primedCopyEl.contains(e.target)) {
275
+ if (_primedCopyReset) _primedCopyReset();
276
+ }
277
+ });
278
+
279
+ export function addCopyHandler(msgEl, rawText) {
280
+ var primed = false;
281
+ var resetTimer = null;
282
+
283
+ var isTouchDevice = "ontouchstart" in window;
284
+
285
+ var hint = document.createElement("div");
286
+ hint.className = "msg-copy-hint";
287
+ hint.textContent = (isTouchDevice ? "Tap" : "Click") + " to grab this";
288
+ msgEl.appendChild(hint);
289
+
290
+ function reset() {
291
+ primed = false;
292
+ if (_primedCopyEl === msgEl) { _primedCopyEl = null; _primedCopyReset = null; }
293
+ msgEl.classList.remove("copy-primed", "copy-done");
294
+ hint.textContent = (isTouchDevice ? "Tap" : "Click") + " to grab this";
295
+ }
296
+
297
+ msgEl.addEventListener("click", function (e) {
298
+ if (e.target.closest("a, pre, code")) return;
299
+ var sel = window.getSelection();
300
+ if (sel && sel.toString().length > 0) return;
301
+
302
+ if (!primed) {
303
+ primed = true;
304
+ _primedCopyEl = msgEl;
305
+ _primedCopyReset = reset;
306
+ msgEl.classList.add("copy-primed");
307
+ hint.textContent = isTouchDevice ? "Tap again to grab" : "Click again to grab";
308
+ clearTimeout(resetTimer);
309
+ resetTimer = setTimeout(reset, 3000);
310
+ } else {
311
+ clearTimeout(resetTimer);
312
+ copyToClipboard(rawText).then(function () {
313
+ msgEl.classList.remove("copy-primed");
314
+ msgEl.classList.add("copy-done");
315
+ hint.textContent = "Grabbed!";
316
+ resetTimer = setTimeout(reset, 1500);
317
+ });
318
+ }
319
+ });
320
+ }
321
+
322
+ export function appendDelta(text) {
323
+ ensureAssistantBlock();
324
+ streamBuffer += text;
325
+ if (!streamDrainTimer) {
326
+ streamDrainTimer = requestAnimationFrame(drainStreamTick);
327
+ }
328
+ }
329
+
330
+ // Minimum number of new characters required before we re-render innerHTML.
331
+ // Smaller = more responsive to short bursts; larger = fewer layout thrashes.
332
+ // 30 chars is roughly half a typical word-wrapped line and imperceptible
333
+ // as a rendering delay at normal streaming speeds.
334
+ var STREAM_RENDER_MIN_DELTA = 30;
335
+
336
+ function drainStreamTick() {
337
+ streamDrainTimer = null;
338
+ var msgEl = store.get('currentMsgEl');
339
+ if (!msgEl || streamBuffer.length === 0) return;
340
+
341
+ // If a worker parse is already in flight, wait — the completion callback
342
+ // will reschedule the drain so nothing is lost.
343
+ if (streamRenderPending) return;
344
+
345
+ var n;
346
+ var len = streamBuffer.length;
347
+ if (len > 200) { n = Math.ceil(len / 4); }
348
+ else if (len > 80) { n = 8; }
349
+ else if (len > 30) { n = 5; }
350
+ else if (len > 10) { n = 2; }
351
+ else { n = 1; }
352
+
353
+ var chunk = streamBuffer.slice(0, n);
354
+ streamBuffer = streamBuffer.slice(n);
355
+ // Accumulate into module-local var — no store.set here.
356
+ // store.currentFullText is only written at flush/finalize so external
357
+ // callers (save/restore in app-header, app-projects, app-messages) see a
358
+ // consistent value at rest. Eliminates 11 subscriber invocations +
359
+ // a full Object.assign state copy on every animation frame tick.
360
+ currentFullTextLocal += chunk;
361
+
362
+ // Only re-render markdown when enough new content has arrived so we
363
+ // avoid a full innerHTML replacement + Highlight.js debounce on every
364
+ // animation frame. The difference is invisible at normal streaming
365
+ // speeds but halves layout work on long responses.
366
+ if (currentFullTextLocal.length - streamRenderLen >= STREAM_RENDER_MIN_DELTA || streamBuffer.length === 0) {
367
+ streamRenderLen = currentFullTextLocal.length;
368
+ var textSnapshot = currentFullTextLocal;
369
+ var contentEl = msgEl.querySelector(".md-content");
370
+
371
+ streamRenderPending = true;
372
+ renderMarkdownAsync(textSnapshot).then(function (html) {
373
+ // Use setTimeout(0) rather than applying inline in the microtask.
374
+ // Microtasks run before the browser can process pending input events,
375
+ // so an innerHTML write here would block keypress handling. A task
376
+ // (setTimeout 0) lets the browser drain the input event queue first,
377
+ // eliminating contention between stream renders and typing.
378
+ setTimeout(function () {
379
+ streamRenderPending = false;
380
+ // Only apply if this message is still the active one
381
+ var currentMsgEl = store.get('currentMsgEl');
382
+ if (currentMsgEl && currentMsgEl === msgEl && contentEl.isConnected) {
383
+ contentEl.innerHTML = html;
384
+ if (highlightTimer) clearTimeout(highlightTimer);
385
+ highlightTimer = setTimeout(function () {
386
+ highlightCodeBlocks(contentEl);
387
+ }, 150);
388
+ scrollToBottom();
389
+ }
390
+ // Drain any buffer that accumulated while we were waiting for the worker
391
+ if (streamBuffer.length > 0 && !streamDrainTimer) {
392
+ streamDrainTimer = requestAnimationFrame(drainStreamTick);
393
+ }
394
+ }, 0);
395
+ });
396
+ } else if (streamBuffer.length > 0) {
397
+ streamDrainTimer = requestAnimationFrame(drainStreamTick);
398
+ }
399
+ }
400
+
401
+ export function flushStreamBuffer() {
402
+ if (streamDrainTimer) { cancelAnimationFrame(streamDrainTimer); streamDrainTimer = null; }
403
+ streamRenderPending = false;
404
+ if (streamBuffer.length > 0) {
405
+ currentFullTextLocal += streamBuffer;
406
+ streamBuffer = "";
407
+ }
408
+ streamRenderLen = 0;
409
+ // Sync accumulated text back to the store so external callers see the
410
+ // final value (save/restore paths in app-header, app-projects, app-messages).
411
+ store.set({ currentFullText: currentFullTextLocal });
412
+ }
413
+
414
+ export function finalizeAssistantBlock() {
415
+ flushStreamBuffer();
416
+ var msgEl = store.get('currentMsgEl');
417
+ var textToRender = currentFullTextLocal;
418
+
419
+ // Clear state before async work — subsequent messages must not inherit
420
+ // this block's el or text.
421
+ currentFullTextLocal = "";
422
+ store.set({ currentMsgEl: null, currentFullText: "" });
423
+
424
+ if (msgEl) {
425
+ var contentEl = msgEl.querySelector(".md-content");
426
+ // Async final render: the heaviest parse of the whole response.
427
+ // Moves marked.parse() off the main thread for the end-of-response
428
+ // spike that caused the "builds up then catches up" stall.
429
+ if (contentEl && textToRender) {
430
+ renderMarkdownAsync(textToRender).then(function (html) {
431
+ setTimeout(function () {
432
+ if (contentEl.isConnected) {
433
+ contentEl.innerHTML = html;
434
+ highlightCodeBlocks(contentEl);
435
+ renderMermaidBlocks(contentEl);
436
+ }
437
+ }, 0);
438
+ });
439
+ } else if (contentEl) {
440
+ highlightCodeBlocks(contentEl);
441
+ renderMermaidBlocks(contentEl);
442
+ }
443
+ if (textToRender) {
444
+ addCopyHandler(msgEl, textToRender);
445
+ }
446
+ closeToolGroup();
447
+ }
448
+ }
449
+
450
+ export function addUserMessage(text, images, pastes, fromUserId, fromUserName) {
451
+ if (!text && (!images || images.length === 0) && (!pastes || pastes.length === 0)) return;
452
+ var myUserId = store.get('myUserId');
453
+ // Only treat as "other user" if we're in multi-user mode AND myUserId is
454
+ // already known AND the message is from a different user. If myUserId is
455
+ // null (init race — /api/me hasn't returned yet), assume the message is
456
+ // from the local user to prevent avatar/name bleed-through in bubble view.
457
+ var isMultiUser = store.get('isMultiUserMode');
458
+ var isOtherUser = isMultiUser && myUserId && fromUserId && fromUserId !== myUserId;
459
+ var div = document.createElement("div");
460
+ div.className = "msg-user" + (isOtherUser ? " msg-user-other" : "");
461
+ div.dataset.turn = ++turnCounter;
462
+ if (shouldGroupMessage("msg-user")) div.classList.add("grouped");
463
+ var bubble = document.createElement("div");
464
+ bubble.className = "bubble";
465
+ bubble.dir = "auto";
466
+
467
+ if (images && images.length > 0) {
468
+ var imgRow = document.createElement("div");
469
+ imgRow.className = "bubble-images";
470
+ for (var i = 0; i < images.length; i++) {
471
+ var img = document.createElement("img");
472
+ if (images[i].url) {
473
+ img.src = images[i].url;
474
+ } else if (images[i].data) {
475
+ img.src = "data:" + images[i].mediaType + ";base64," + images[i].data;
476
+ }
477
+ img.loading = "lazy";
478
+ img.className = "bubble-img";
479
+ img.addEventListener("click", function () { showImageModal(this.src); });
480
+ img.addEventListener("error", function () {
481
+ var placeholder = document.createElement("div");
482
+ placeholder.className = "bubble-img-expired";
483
+ placeholder.textContent = "Image deleted";
484
+ this.parentNode.replaceChild(placeholder, this);
485
+ });
486
+ imgRow.appendChild(img);
487
+ }
488
+ bubble.appendChild(imgRow);
489
+ }
490
+
491
+ if (pastes && pastes.length > 0) {
492
+ var pasteRow = document.createElement("div");
493
+ pasteRow.className = "bubble-pastes";
494
+ for (var p = 0; p < pastes.length; p++) {
495
+ (function (pasteText) {
496
+ var chip = document.createElement("div");
497
+ chip.className = "bubble-paste";
498
+ var preview = pasteText.substring(0, 60).replace(/\n/g, " ");
499
+ if (pasteText.length > 60) preview += "...";
500
+ chip.innerHTML = '<span class="bubble-paste-preview">' + escapeHtml(preview) + '</span><span class="bubble-paste-label">PASTED</span>';
501
+ chip.addEventListener("click", function (e) {
502
+ e.stopPropagation();
503
+ showPasteModal(pasteText);
504
+ });
505
+ pasteRow.appendChild(chip);
506
+ })(pastes[p]);
507
+ }
508
+ bubble.appendChild(pasteRow);
509
+ }
510
+
511
+ if (text) {
512
+ var textEl = document.createElement("span");
513
+ textEl.textContent = text;
514
+ bubble.appendChild(textEl);
515
+ }
516
+
517
+
518
+ var cachedAllUsers = store.get('cachedAllUsers');
519
+ var _targetUser;
520
+ var _displayName;
521
+ if (isOtherUser) {
522
+ _targetUser = cachedAllUsers.find(function (u) { return u.id === fromUserId; });
523
+ _displayName = fromUserName || (_targetUser && (_targetUser.displayName || _targetUser.username)) || "User";
524
+ } else {
525
+ _targetUser = cachedAllUsers.find(function (u) { return u.id === myUserId; });
526
+ if (!_targetUser) {
527
+ try { _targetUser = JSON.parse(localStorage.getItem("clagentic_my_user") || localStorage.getItem("clay_my_user") || "null"); } catch(e) {}
528
+ }
529
+ _displayName = document.body.dataset.myDisplayName || "";
530
+ if (!_displayName) {
531
+ _displayName = (_targetUser && (_targetUser.displayName || _targetUser.username)) || "Me";
532
+ }
533
+ }
534
+
535
+ var avi = document.createElement("img");
536
+ avi.className = "dm-bubble-avatar" + (isOtherUser ? " dm-bubble-avatar-other" : " dm-bubble-avatar-me");
537
+ avi.src = isOtherUser
538
+ ? userAvatarUrl(_targetUser || { id: fromUserId }, 36)
539
+ : (document.body.dataset.myAvatarUrl || userAvatarUrl(_targetUser || { id: myUserId }, 36));
540
+ div.appendChild(avi);
541
+
542
+ var contentWrap = document.createElement("div");
543
+ contentWrap.className = "dm-bubble-content";
544
+
545
+ var header = document.createElement("div");
546
+ header.className = "dm-bubble-header";
547
+ var nameSpan = document.createElement("span");
548
+ nameSpan.className = "dm-bubble-name";
549
+ nameSpan.textContent = _displayName;
550
+ header.appendChild(nameSpan);
551
+ var timeSpan = document.createElement("span");
552
+ timeSpan.className = "dm-bubble-time";
553
+ timeSpan.textContent = getMsgTime();
554
+ header.appendChild(timeSpan);
555
+ contentWrap.appendChild(header);
556
+ contentWrap.appendChild(bubble);
557
+ div.appendChild(contentWrap);
558
+
559
+ var actions = document.createElement("div");
560
+ actions.className = "msg-actions";
561
+ actions.innerHTML =
562
+ '<span class="msg-action-time">' + getMsgTime() + '</span>' +
563
+ '<button class="msg-action-btn msg-action-copy" type="button" title="Copy">' + iconHtml("copy") + '</button>' +
564
+ '<button class="msg-action-btn msg-action-fork" type="button" title="Fork">' + iconHtml("git-branch") + '</button>' +
565
+ (((store.get('vendorCapabilities') || {}).rewind !== false) ? '<button class="msg-action-btn msg-action-rewind msg-user-rewind-btn" type="button" title="Rewind">' + iconHtml("rotate-ccw") + '</button>' : '') +
566
+ '<button class="msg-action-btn msg-action-hidden msg-action-edit" type="button" title="Edit">' + iconHtml("pencil") + '</button>';
567
+ div.appendChild(actions);
568
+
569
+ actions.querySelector(".msg-action-copy").addEventListener("click", function () {
570
+ var self = this;
571
+ copyToClipboard(text || "");
572
+ self.innerHTML = iconHtml("check");
573
+ refreshIcons(actions);
574
+ setTimeout(function () { self.innerHTML = iconHtml("copy"); refreshIcons(actions); }, 1200);
575
+ });
576
+
577
+ addToMessages(div);
578
+ refreshIcons(div);
579
+ forceScrollToBottom();
580
+ }
581
+
582
+ export function addSystemMessage(text, isError) {
583
+ var div = document.createElement("div");
584
+ div.className = "sys-msg" + (isError ? " error" : "");
585
+ div.innerHTML = '<span class="sys-text"></span>';
586
+ div.querySelector(".sys-text").textContent = text;
587
+ addToMessages(div);
588
+ scrollToBottom();
589
+ }
590
+
591
+ export function addConflictMessage(msg) {
592
+ var div = document.createElement("div");
593
+ div.className = "conflict-msg";
594
+ var header = document.createElement("div");
595
+ header.className = "conflict-header";
596
+ header.textContent = msg.text || "Another Claude Code process is already running.";
597
+ div.appendChild(header);
598
+
599
+ var hint = document.createElement("div");
600
+ hint.className = "conflict-hint";
601
+ hint.textContent = "Kill the conflicting process to continue, or use the existing Claude Code session.";
602
+ div.appendChild(hint);
603
+
604
+ for (var i = 0; i < msg.processes.length; i++) {
605
+ var p = msg.processes[i];
606
+ var row = document.createElement("div");
607
+ row.className = "conflict-process";
608
+
609
+ var info = document.createElement("span");
610
+ info.className = "conflict-pid";
611
+ info.textContent = "PID " + p.pid;
612
+ row.appendChild(info);
613
+
614
+ var cmd = document.createElement("code");
615
+ cmd.className = "conflict-cmd";
616
+ cmd.textContent = p.command.length > 80 ? p.command.substring(0, 80) + "..." : p.command;
617
+ cmd.title = p.command;
618
+ row.appendChild(cmd);
619
+
620
+ var killBtn = document.createElement("button");
621
+ killBtn.className = "conflict-kill-btn";
622
+ killBtn.textContent = "Kill Process";
623
+ killBtn.setAttribute("data-pid", p.pid);
624
+ killBtn.addEventListener("click", function() {
625
+ var pid = parseInt(this.getAttribute("data-pid"), 10);
626
+ getWs().send(JSON.stringify({ type: "kill_process", pid: pid }));
627
+ this.disabled = true;
628
+ this.textContent = "Killing...";
629
+ });
630
+ row.appendChild(killBtn);
631
+ div.appendChild(row);
632
+ }
633
+
634
+ addToMessages(div);
635
+ scrollToBottom();
636
+ }
637
+
638
+ export function addContextOverflowMessage(msg) {
639
+ var div = document.createElement("div");
640
+ div.className = "context-overflow-msg";
641
+
642
+ var header = document.createElement("div");
643
+ header.className = "context-overflow-header";
644
+ header.textContent = msg.text || "Conversation too long to continue.";
645
+ div.appendChild(header);
646
+
647
+ var hint = document.createElement("div");
648
+ hint.className = "context-overflow-hint";
649
+ hint.textContent = "The conversation has exceeded the model's context limit. Please start a new conversation to continue.";
650
+ div.appendChild(hint);
651
+
652
+ var btn = document.createElement("button");
653
+ btn.className = "context-overflow-btn";
654
+ btn.textContent = "New Conversation";
655
+ btn.addEventListener("click", function() {
656
+ getWs().send(JSON.stringify({ type: "new_session" }));
657
+ });
658
+ div.appendChild(btn);
659
+
660
+ addToMessages(div);
661
+ scrollToBottom();
662
+ }
663
+
664
+ // --- Pre-thinking (instant dots before server responds) ---
665
+
666
+ export function showClaudePreThinking() {
667
+ if (getChatLayout() !== "channel") return;
668
+ removePreThinking();
669
+ var vendor = store.get('currentVendor') || "claude";
670
+ var vendorAvatar = VENDOR_AVATARS[vendor] || VENDOR_AVATARS.claude;
671
+ var vendorName = VENDOR_NAMES[vendor] || VENDOR_NAMES.claude;
672
+ doShowPreThinking(vendorName, vendorAvatar);
673
+ }
674
+
675
+ export function removePreThinking() {
676
+ var messagesEl = getMessagesEl();
677
+ if (!messagesEl) return;
678
+ var els = messagesEl.querySelectorAll(".channel-pre-thinking");
679
+ for (var i = 0; i < els.length; i++) {
680
+ els[i].remove();
681
+ }
682
+ }
683
+
684
+ function doShowPreThinking(name, avatar) {
685
+ var _el = document.createElement("div");
686
+ _el.className = "thinking-item channel-thinking channel-pre-thinking";
687
+ _el.innerHTML =
688
+ '<img class="dm-bubble-avatar" src="' + escapeHtml(avatar) + '" alt="" style="display:block">' +
689
+ '<div class="dm-bubble-content">' +
690
+ '<div class="dm-bubble-header"><span class="dm-bubble-name">' + escapeHtml(name) + '</span></div>' +
691
+ '<div class="thinking-dots"><span></span><span></span><span></span></div>' +
692
+ '</div>';
693
+ if (activityEl && activityEl.parentNode) {
694
+ activityEl.parentNode.insertBefore(_el, activityEl);
695
+ } else {
696
+ addToMessages(_el);
697
+ }
698
+ refreshIcons(_el);
699
+ scrollToBottom();
700
+ }
701
+
702
+ // --- Ghost suggestion (prompt recommendation as ghost text) ---
703
+
704
+ var _ghostSuggestionText = "";
705
+
706
+ export function getGhostSuggestion() {
707
+ return _ghostSuggestionText;
708
+ }
709
+
710
+ export function showSuggestionChips(suggestion) {
711
+ if (!suggestion || store.get('processing')) return;
712
+ // Only show ghost text when there is no sendable content — typed text,
713
+ // pending pastes, pending images, or pending files all suppress the
714
+ // suggestion so Enter can't accidentally send it instead of the user's
715
+ // actual attached content.
716
+ if (hasSendableContent()) return;
717
+ _ghostSuggestionText = suggestion;
718
+ var ghostEl = document.getElementById("ghost-suggestion");
719
+ if (!ghostEl) return;
720
+ ghostEl.innerHTML = escapeHtml(suggestion) +
721
+ ' <span class="ghost-hint"><kbd>Enter</kbd> to send</span>';
722
+ ghostEl.classList.remove("hidden");
723
+ // Toggle class on wrap so CSS avoids :has() recalc on every keypress (Firefox perf)
724
+ var wrap = document.getElementById("input-textarea-wrap");
725
+ if (wrap) wrap.classList.add("ghost-active");
726
+ }
727
+
728
+ export function hideSuggestionChips() {
729
+ if (!_ghostSuggestionText) return; // already hidden, skip DOM touch
730
+ _ghostSuggestionText = "";
731
+ var ghostEl = document.getElementById("ghost-suggestion");
732
+ if (ghostEl) {
733
+ ghostEl.innerHTML = "";
734
+ ghostEl.classList.add("hidden");
735
+ }
736
+ // Remove class from wrap to match CSS selector change (no :has() recalc)
737
+ var wrap = document.getElementById("input-textarea-wrap");
738
+ if (wrap) wrap.classList.remove("ghost-active");
739
+ }