@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,1102 @@
1
+ import { iconHtml, refreshIcons } from './icons.js';
2
+ import { setRewindMode, isRewindMode } from './rewind.js';
3
+ import { renderPicker as renderContextPicker } from './context-sources.js';
4
+ import { checkForMention, showMentionMenu, hideMentionMenu, isMentionMenuVisible, mentionMenuKeydown, setMentionAtIdx, parseMentionFromInput, clearMentionState, stickyReapplyMention, sendUserMention, renderUserMention, removeMentionChip } from './mention.js';
5
+ import { store } from './store.js';
6
+ import { sendWsQuiet } from './ws-ref.js';
7
+
8
+ var ctx;
9
+
10
+ // --- State ---
11
+ var pendingImages = []; // [{data: base64, mediaType: "image/png"}]
12
+ var pendingPastes = []; // [{text: string, preview: string}]
13
+ var pendingFiles = []; // [{name: string, path: string}]
14
+ var uploadingCount = 0;
15
+ var slashActiveIdx = -1;
16
+ var slashFiltered = [];
17
+ var isComposing = false;
18
+ var isRemoteInput = false;
19
+ var scheduleDelayMs = 0; // 0 = no schedule, >0 = delay in ms
20
+ var _setScheduleDelayFn = null; // set by initInput
21
+ var slashMenuBound = false;
22
+
23
+ export function hasSendableContent() {
24
+ return !!(
25
+ (ctx && ctx.inputEl && ctx.inputEl.value.trim()) ||
26
+ pendingPastes.length > 0 ||
27
+ pendingImages.length > 0 ||
28
+ pendingFiles.length > 0
29
+ );
30
+ }
31
+
32
+ export function getScheduleDelay() {
33
+ return scheduleDelayMs;
34
+ }
35
+
36
+ export function setScheduleDelayMs(ms) {
37
+ scheduleDelayMs = ms;
38
+ // Trigger visual update if initInput has been called
39
+ if (_setScheduleDelayFn) _setScheduleDelayFn(ms);
40
+ }
41
+
42
+ export function clearScheduleDelay() {
43
+ scheduleDelayMs = 0;
44
+ var btn = document.getElementById("schedule-btn");
45
+ if (btn) {
46
+ btn.classList.remove("schedule-active", "schedule-expanded");
47
+ var lbl = btn.querySelector(".schedule-delay-label");
48
+ if (lbl) lbl.remove();
49
+ var inp = btn.querySelector(".schedule-inline-input");
50
+ if (inp) inp.remove();
51
+ btn.title = "Schedule message";
52
+ }
53
+ }
54
+
55
+ export function setScheduleBtnDisabled(disabled) {
56
+ var btn = document.getElementById("schedule-btn");
57
+ if (!btn) return;
58
+ btn.disabled = disabled;
59
+ if (disabled) {
60
+ btn.style.opacity = "0.3";
61
+ btn.style.pointerEvents = "none";
62
+ } else {
63
+ btn.style.opacity = "";
64
+ btn.style.pointerEvents = "";
65
+ }
66
+ }
67
+
68
+ export var builtinCommands = [
69
+ { name: "clear", desc: "Clear conversation" },
70
+ { name: "context", desc: "Context window usage" },
71
+ { name: "rewind", desc: "Toggle rewind mode" },
72
+ { name: "usage", desc: "Toggle usage panel" },
73
+ { name: "status", desc: "Process status and resource usage" },
74
+ ];
75
+
76
+ // --- Send ---
77
+ export function sendMessage() {
78
+ // DM mode intercept: if in DM mode, route to DM handler instead
79
+ if (ctx.isDmMode && ctx.isDmMode() && ctx.handleDmSend) {
80
+ ctx.handleDmSend();
81
+ return;
82
+ }
83
+ var text = ctx.inputEl.value.trim();
84
+ var images = pendingImages.slice();
85
+ if (!text && images.length === 0 && pendingPastes.length === 0 && pendingFiles.length === 0) return;
86
+ if (uploadingCount > 0) return; // wait for uploads to finish
87
+ hideSlashMenu();
88
+ if (ctx.hideSuggestionChips) ctx.hideSuggestionChips();
89
+
90
+ if (text === "/clear") {
91
+ ctx.inputEl.value = "";
92
+ clearPendingImages();
93
+ autoResize();
94
+ if (ctx.ws && ctx.connected) {
95
+ ctx.ws.send(JSON.stringify({ type: "new_session" }));
96
+ }
97
+ return;
98
+ }
99
+
100
+ if (text === "/rewind") {
101
+ ctx.inputEl.value = "";
102
+ clearPendingImages();
103
+ autoResize();
104
+ if (ctx.messageUuidMap().length === 0) {
105
+ ctx.addSystemMessage("No rewind points available in this session.", true);
106
+ } else {
107
+ setRewindMode(!isRewindMode());
108
+ }
109
+ return;
110
+ }
111
+
112
+ if (text === "/context") {
113
+ ctx.inputEl.value = "";
114
+ clearPendingImages();
115
+ autoResize();
116
+ if (ctx.toggleContextPanel) ctx.toggleContextPanel();
117
+ return;
118
+ }
119
+
120
+ if (text === "/usage") {
121
+ ctx.inputEl.value = "";
122
+ clearPendingImages();
123
+ autoResize();
124
+ if (ctx.toggleUsagePanel) ctx.toggleUsagePanel();
125
+ return;
126
+ }
127
+
128
+ if (text === "/status") {
129
+ ctx.inputEl.value = "";
130
+ clearPendingImages();
131
+ autoResize();
132
+ if (ctx.toggleStatusPanel) ctx.toggleStatusPanel();
133
+ return;
134
+ }
135
+
136
+ if (!ctx.connected) {
137
+ ctx.addSystemMessage("Not connected — message not sent.", true);
138
+ return;
139
+ }
140
+
141
+ // Check for @mention: if a user was selected, route to mention handler.
142
+ var mention = parseMentionFromInput(text);
143
+ if (mention && mention.kind === "user") {
144
+ hideMentionMenu();
145
+ if (ctx.hideSuggestionChips) ctx.hideSuggestionChips();
146
+ var uMentionImages = pendingImages.slice();
147
+ var uMentionPastes = pendingPastes.map(function (p) { return p.text; });
148
+ var uMentionFiles = pendingFiles.slice();
149
+ var uMentionText = mention.text;
150
+ if (uMentionFiles.length > 0) {
151
+ var uFilePaths = uMentionFiles.map(function (f) { return "[Uploaded file: " + f.path + "]"; }).join("\n");
152
+ uMentionText = uMentionText ? uFilePaths + "\n\n" + uMentionText : uFilePaths;
153
+ }
154
+ // Optimistic local render so the sender sees their own message immediately.
155
+ // The server uses sendToSessionOthers, so this tab does not get a duplicate echo.
156
+ var myUserId = ctx.myUserId ? ctx.myUserId() : null;
157
+ var myDisplayName = ctx.myDisplayName ? ctx.myDisplayName() : "Me";
158
+ renderUserMention({
159
+ from: myUserId,
160
+ fromName: myDisplayName,
161
+ targetUserId: mention.userId,
162
+ targetName: mention.mateName,
163
+ text: uMentionText,
164
+ images: uMentionImages.length > 0 ? uMentionImages : null,
165
+ pastes: uMentionPastes.length > 0 ? uMentionPastes : null,
166
+ });
167
+ sendUserMention(mention.userId, uMentionText, uMentionPastes, uMentionImages);
168
+ ctx.inputEl.value = "";
169
+ stickyReapplyMention();
170
+ sendInputSync();
171
+ clearPendingImages();
172
+ autoResize();
173
+ ctx.inputEl.focus();
174
+ return;
175
+ }
176
+
177
+ // Prepend file paths to text
178
+ var files = pendingFiles.slice();
179
+ if (files.length > 0) {
180
+ var filePaths = files.map(function (f) { return "[Uploaded file: " + f.path + "]"; }).join("\n");
181
+ text = text ? filePaths + "\n\n" + text : filePaths;
182
+ }
183
+
184
+ var pastes = pendingPastes.map(function (p) { return p.text; });
185
+
186
+ // Scheduled message: queue message with timer delay
187
+ if (scheduleDelayMs > 0) {
188
+ var resetsAt = Date.now() + scheduleDelayMs;
189
+ ctx.ws.send(JSON.stringify({ type: "schedule_message", text: text || "", resetsAt: resetsAt }));
190
+ clearScheduleDelay();
191
+ ctx.inputEl.value = "";
192
+ sendInputSync();
193
+ clearPendingImages();
194
+ autoResize();
195
+ ctx.inputEl.focus();
196
+ return;
197
+ }
198
+
199
+ ctx.currentMsgTs = Date.now();
200
+ ctx.addUserMessage(text, images.length > 0 ? images : null, pastes.length > 0 ? pastes : null);
201
+
202
+ var payload = { type: "message", text: text || "" };
203
+ if (images.length > 0) {
204
+ payload.images = images;
205
+ }
206
+ if (pastes.length > 0) {
207
+ payload.pastes = pastes;
208
+ }
209
+ // Include selected vendor for session binding (server uses on first message)
210
+ var _selVendor = store.get("currentVendor") || null;
211
+ if (_selVendor) payload.vendor = _selVendor;
212
+ ctx.ws.send(JSON.stringify(payload));
213
+
214
+ // Hide vendor toggle after first message (vendor is locked to this session)
215
+ var _vtw2 = document.getElementById("vendor-toggle-wrap");
216
+ if (_vtw2) { _vtw2.classList.remove("hidden"); _vtw2.classList.add("locked"); }
217
+ store.set({ vendorSelectionLocked: false });
218
+
219
+ // Show pre-thinking dots before server responds.
220
+ // Channel layout: rich pre-thinking bubble via showClaudePreThinking().
221
+ // Bubble layout: simple activity-inline dots via setActivity("thinking").
222
+ if (ctx.showClaudePreThinking) {
223
+ ctx.showClaudePreThinking();
224
+ }
225
+ if (!document.body.classList.contains("wide-view") && ctx.setActivity) {
226
+ ctx.setActivity("thinking");
227
+ }
228
+
229
+ ctx.inputEl.value = "";
230
+ sendInputSync();
231
+ clearPendingImages();
232
+ autoResize();
233
+ ctx.inputEl.focus();
234
+ // Input cleared — switch back to stop mode if still processing
235
+ if (ctx.processing && ctx.setSendBtnMode) {
236
+ ctx.setSendBtnMode("stop");
237
+ }
238
+ }
239
+
240
+ var INPUT_MAX_HEIGHT = 120;
241
+ var autoResizeLastLines = 1;
242
+ var autoResizeAtMax = false; // true when last measured height hit INPUT_MAX_HEIGHT
243
+ var autoResizeSoftWrapTick = 0; // throttle the soft-wrap scrollHeight check
244
+ var autoResizeFrame = null;
245
+
246
+ // Reset the line-count cache so the next autoResize() always measures.
247
+ // Call before any situation where the textarea content is replaced externally
248
+ // (session switch, draft restore) to prevent the skip-guard from freezing
249
+ // the height at stale values.
250
+ export function resetAutoResize() {
251
+ if (autoResizeFrame) {
252
+ cancelAnimationFrame(autoResizeFrame);
253
+ autoResizeFrame = null;
254
+ }
255
+ autoResizeLastLines = -1;
256
+ autoResizeAtMax = false;
257
+ autoResizeSoftWrapTick = 0;
258
+ }
259
+
260
+ export function scheduleAutoResize() {
261
+ if (autoResizeFrame) return;
262
+ autoResizeFrame = requestAnimationFrame(function () {
263
+ autoResizeFrame = null;
264
+ autoResize();
265
+ });
266
+ }
267
+
268
+ export function autoResize() {
269
+ if (autoResizeFrame) {
270
+ cancelAnimationFrame(autoResizeFrame);
271
+ autoResizeFrame = null;
272
+ }
273
+ // Count newlines as a cheap proxy for whether height can have changed.
274
+ // Avoids the forced synchronous layout (style=auto then scrollHeight read)
275
+ // on every keypress when the line count hasn't changed — the main cause
276
+ // of typing lag that worsens as the textarea fills up.
277
+ //
278
+ // Extra guard: if we already hit the height cap on the previous resize
279
+ // and the line count has only stayed the same or grown, there is no
280
+ // possible change in rendered height — skip the forced layout entirely.
281
+ // This eliminates the reflow on backspace-within-a-capped-textarea where
282
+ // each deletion decrements lines but the textarea stays at max height.
283
+ //
284
+ // Note: this proxy intentionally counts only hard newlines (\n). Visual
285
+ // word-wrap does NOT increment the count, so autoResize() misses growth
286
+ // caused purely by soft wrapping. This is acceptable on desktop where the
287
+ // input is wide, but on narrow mobile viewports words wrap much earlier.
288
+ // The fix: if scrollHeight already exceeds the current pixel height, treat
289
+ // that as a line-count change regardless of the newline count. This catches
290
+ // soft-wrap expansion without triggering a full reflow on every keypress.
291
+ var val = ctx.inputEl.value;
292
+ // Count newlines via indexOf — faster than char-by-char loop in JS engines
293
+ // (avoids per-character bounds check overhead; O(n) but with lower constant).
294
+ var lines = 1;
295
+ var pos = 0;
296
+ while ((pos = val.indexOf("\n", pos)) !== -1) { lines++; pos++; }
297
+
298
+ // Fast path: line count unchanged and we're at max height — nothing to do.
299
+ if (autoResizeAtMax && lines >= autoResizeLastLines) return;
300
+
301
+ // Fast path: line count unchanged and not at max — check for soft-wrap
302
+ // growth ONLY when the count stayed the same, to avoid a forced layout
303
+ // on every keypress when lines are actively changing (the common case).
304
+ if (lines === autoResizeLastLines) {
305
+ // Soft-wrap check: reading scrollHeight forces a synchronous layout.
306
+ // Throttle to every 16 calls so single-line typing pays this cost at
307
+ // most once every ~16 keypresses rather than every keypress.
308
+ autoResizeSoftWrapTick = (autoResizeSoftWrapTick + 1) % 16;
309
+ if (autoResizeSoftWrapTick !== 0) return;
310
+ var softWrapGrew = ctx.inputEl.scrollHeight > ctx.inputEl.offsetHeight + 2;
311
+ if (!softWrapGrew) return;
312
+ }
313
+
314
+ autoResizeLastLines = lines;
315
+ ctx.inputEl.style.height = "auto";
316
+ var newH = Math.min(ctx.inputEl.scrollHeight, INPUT_MAX_HEIGHT);
317
+ autoResizeAtMax = (newH >= INPUT_MAX_HEIGHT);
318
+ ctx.inputEl.style.height = newH + "px";
319
+ }
320
+
321
+ // --- File path extraction from clipboard ---
322
+ function extractFilePaths(cd) {
323
+ var paths = [];
324
+
325
+ // 1. Check text/uri-list for file:// URIs (Finder on some browsers)
326
+ var uriList = cd.getData("text/uri-list");
327
+ if (uriList) {
328
+ var lines = uriList.split(/\r?\n/);
329
+ for (var i = 0; i < lines.length; i++) {
330
+ var line = lines[i].trim();
331
+ if (line && !line.startsWith("#") && line.startsWith("file://")) {
332
+ paths.push(decodeURIComponent(line.replace("file://", "")));
333
+ }
334
+ }
335
+ if (paths.length > 0) return paths;
336
+ }
337
+
338
+ // 2. Check if text/plain looks like file path(s) while files are present
339
+ // (Finder Cmd+C puts filename in text/plain, Cmd+Option+C puts full path)
340
+ if (cd.files && cd.files.length > 0) {
341
+ var plainText = cd.getData("text/plain");
342
+ if (plainText) {
343
+ var textLines = plainText.split(/\r?\n/).filter(function (l) { return l.trim(); });
344
+ for (var i = 0; i < textLines.length; i++) {
345
+ var p = textLines[i].trim();
346
+ if (p.startsWith("/") || p.startsWith("~")) {
347
+ paths.push(p);
348
+ }
349
+ }
350
+ if (paths.length > 0) return paths;
351
+ }
352
+ // 3. Fallback: files present but no path in text, use filenames
353
+ for (var i = 0; i < cd.files.length; i++) {
354
+ var f = cd.files[i];
355
+ if (f.name && f.type.indexOf("image/") !== 0) {
356
+ paths.push(f.name);
357
+ }
358
+ }
359
+ }
360
+
361
+ return paths;
362
+ }
363
+
364
+ // --- Insert text at cursor in textarea ---
365
+ function insertTextAtCursor(text) {
366
+ var el = ctx.inputEl;
367
+ el.focus();
368
+ var start = el.selectionStart;
369
+ var end = el.selectionEnd;
370
+ var before = el.value.substring(0, start);
371
+ var after = el.value.substring(end);
372
+ // Add space before if cursor is right after non-space text
373
+ if (before.length > 0 && before[before.length - 1] !== " " && before[before.length - 1] !== "\n") {
374
+ text = " " + text;
375
+ }
376
+ el.value = before + text + after;
377
+ el.selectionStart = el.selectionEnd = start + text.length;
378
+ autoResize();
379
+ sendInputSync();
380
+ }
381
+
382
+ // --- Image paste ---
383
+ function addPendingImage(dataUrl) {
384
+ var commaIdx = dataUrl.indexOf(",");
385
+ if (commaIdx === -1) return;
386
+ var header = dataUrl.substring(0, commaIdx);
387
+ var data = dataUrl.substring(commaIdx + 1);
388
+ var typeMatch = header.match(/data:(image\/[^;,]+)/);
389
+ if (!typeMatch || !data) return;
390
+ pendingImages.push({ mediaType: typeMatch[1], data: data });
391
+ renderInputPreviews();
392
+ }
393
+
394
+ function removePendingImage(idx) {
395
+ pendingImages.splice(idx, 1);
396
+ renderInputPreviews();
397
+ }
398
+
399
+ export function clearPendingImages() {
400
+ pendingImages = [];
401
+ pendingPastes = [];
402
+ pendingFiles = [];
403
+ renderInputPreviews();
404
+ }
405
+
406
+ function removePendingPaste(idx) {
407
+ pendingPastes.splice(idx, 1);
408
+ renderInputPreviews();
409
+ }
410
+
411
+ function removePendingFile(idx) {
412
+ pendingFiles.splice(idx, 1);
413
+ renderInputPreviews();
414
+ }
415
+
416
+ function renderInputPreviews() {
417
+ var bar = ctx.imagePreviewBar;
418
+ bar.innerHTML = "";
419
+ if (pendingImages.length === 0 && pendingPastes.length === 0 && pendingFiles.length === 0 && uploadingCount === 0) {
420
+ bar.classList.remove("visible");
421
+ return;
422
+ }
423
+ bar.classList.add("visible");
424
+ // Hide any ghost suggestion as soon as attached content appears — Enter
425
+ // must not silently swallow the user's paste/image/file.
426
+ if (ctx && ctx.hideSuggestionChips) ctx.hideSuggestionChips();
427
+
428
+ // Image thumbnails
429
+ for (var i = 0; i < pendingImages.length; i++) {
430
+ (function (idx) {
431
+ var wrap = document.createElement("div");
432
+ wrap.className = "image-preview-thumb";
433
+ var img = document.createElement("img");
434
+ img.src = "data:" + pendingImages[idx].mediaType + ";base64," + pendingImages[idx].data;
435
+ img.addEventListener("click", function () {
436
+ if (ctx.showImageModal) ctx.showImageModal(this.src);
437
+ });
438
+ var removeBtn = document.createElement("button");
439
+ removeBtn.className = "image-preview-remove";
440
+ removeBtn.innerHTML = iconHtml("x");
441
+ removeBtn.addEventListener("click", function () {
442
+ removePendingImage(idx);
443
+ });
444
+ wrap.appendChild(img);
445
+ wrap.appendChild(removeBtn);
446
+ bar.appendChild(wrap);
447
+ })(i);
448
+ }
449
+
450
+ // File chips
451
+ for (var fi = 0; fi < pendingFiles.length; fi++) {
452
+ (function (idx) {
453
+ var chip = document.createElement("div");
454
+ chip.className = "file-chip";
455
+ var icon = document.createElement("span");
456
+ icon.className = "file-chip-icon";
457
+ icon.innerHTML = iconHtml("file");
458
+ var nameSpan = document.createElement("span");
459
+ nameSpan.className = "file-chip-name";
460
+ nameSpan.textContent = pendingFiles[idx].name;
461
+ var removeBtn = document.createElement("button");
462
+ removeBtn.className = "file-chip-remove";
463
+ removeBtn.innerHTML = iconHtml("x");
464
+ removeBtn.addEventListener("click", function (e) {
465
+ e.stopPropagation();
466
+ removePendingFile(idx);
467
+ });
468
+ chip.appendChild(icon);
469
+ chip.appendChild(nameSpan);
470
+ chip.appendChild(removeBtn);
471
+ bar.appendChild(chip);
472
+ })(fi);
473
+ }
474
+
475
+ // Uploading indicator
476
+ if (uploadingCount > 0) {
477
+ var chip = document.createElement("div");
478
+ chip.className = "file-chip file-chip-uploading";
479
+ var spinner = document.createElement("span");
480
+ spinner.className = "file-chip-spinner";
481
+ var label = document.createElement("span");
482
+ label.className = "file-chip-name";
483
+ label.textContent = "Uploading" + (uploadingCount > 1 ? " (" + uploadingCount + ")" : "") + "...";
484
+ chip.appendChild(spinner);
485
+ chip.appendChild(label);
486
+ bar.appendChild(chip);
487
+ }
488
+
489
+ // Pasted content chips
490
+ for (var j = 0; j < pendingPastes.length; j++) {
491
+ (function (idx) {
492
+ var chip = document.createElement("div");
493
+ chip.className = "pasted-chip";
494
+ var preview = document.createElement("span");
495
+ preview.className = "pasted-chip-preview";
496
+ preview.textContent = pendingPastes[idx].preview;
497
+ var label = document.createElement("span");
498
+ label.className = "pasted-chip-label";
499
+ label.textContent = "PASTED";
500
+ var removeBtn = document.createElement("button");
501
+ removeBtn.className = "pasted-chip-remove";
502
+ removeBtn.innerHTML = iconHtml("x");
503
+ removeBtn.addEventListener("click", function (e) {
504
+ e.stopPropagation();
505
+ removePendingPaste(idx);
506
+ });
507
+ chip.appendChild(preview);
508
+ chip.appendChild(label);
509
+ chip.appendChild(removeBtn);
510
+ bar.appendChild(chip);
511
+ })(j);
512
+ }
513
+
514
+ refreshIcons();
515
+ }
516
+
517
+ var MAX_IMAGE_BYTES = 5 * 1024 * 1024; // 5 MB
518
+ var RESIZE_MAX_DIM = 1920;
519
+ var RESIZE_QUALITY = 0.85;
520
+ var MAX_UPLOAD_BYTES = 50 * 1024 * 1024; // 50 MB
521
+
522
+ // --- File upload ---
523
+ function uploadFile(file) {
524
+ if (file.size > MAX_UPLOAD_BYTES) {
525
+ if (ctx.addSystemMessage) ctx.addSystemMessage("File too large (max 50MB): " + file.name, true);
526
+ return;
527
+ }
528
+ uploadingCount++;
529
+ renderInputPreviews();
530
+ var reader = new FileReader();
531
+ reader.onload = function (ev) {
532
+ var dataUrl = ev.target.result;
533
+ var commaIdx = dataUrl.indexOf(",");
534
+ var b64 = commaIdx !== -1 ? dataUrl.substring(commaIdx + 1) : "";
535
+
536
+ var xhr = new XMLHttpRequest();
537
+ xhr.open("POST", ctx.basePath + "api/upload");
538
+ xhr.setRequestHeader("Content-Type", "application/json");
539
+ xhr.onload = function () {
540
+ uploadingCount--;
541
+ if (xhr.status === 200) {
542
+ try {
543
+ var resp = JSON.parse(xhr.responseText);
544
+ pendingFiles.push({ name: resp.name || file.name, path: resp.path });
545
+ } catch (e) {}
546
+ } else {
547
+ if (ctx.addSystemMessage) ctx.addSystemMessage("Upload failed: " + file.name, true);
548
+ }
549
+ renderInputPreviews();
550
+ if (ctx.processing && ctx.setSendBtnMode) {
551
+ ctx.setSendBtnMode(hasSendableContent() ? "send" : "stop");
552
+ }
553
+ };
554
+ xhr.onerror = function () {
555
+ uploadingCount--;
556
+ if (ctx.addSystemMessage) ctx.addSystemMessage("Upload failed: " + file.name, true);
557
+ renderInputPreviews();
558
+ if (ctx.processing && ctx.setSendBtnMode) {
559
+ ctx.setSendBtnMode(hasSendableContent() ? "send" : "stop");
560
+ }
561
+ };
562
+ xhr.send(JSON.stringify({ name: file.name, data: b64 }));
563
+ };
564
+ reader.readAsDataURL(file);
565
+ }
566
+
567
+ function readImageBlob(blob) {
568
+ var reader = new FileReader();
569
+ reader.onload = function (ev) {
570
+ var dataUrl = ev.target.result;
571
+ // Check base64 payload size (~3/4 of base64 length)
572
+ var commaIdx = dataUrl.indexOf(",");
573
+ var b64 = commaIdx !== -1 ? dataUrl.substring(commaIdx + 1) : "";
574
+ var estimatedBytes = b64.length * 0.75;
575
+
576
+ if (estimatedBytes <= MAX_IMAGE_BYTES) {
577
+ addPendingImage(dataUrl);
578
+ return;
579
+ }
580
+
581
+ // Resize via canvas
582
+ var img = new Image();
583
+ img.onload = function () {
584
+ var w = img.naturalWidth;
585
+ var h = img.naturalHeight;
586
+ var scale = Math.min(RESIZE_MAX_DIM / Math.max(w, h), 1);
587
+ var nw = Math.round(w * scale);
588
+ var nh = Math.round(h * scale);
589
+ var canvas = document.createElement("canvas");
590
+ canvas.width = nw;
591
+ canvas.height = nh;
592
+ var cx = canvas.getContext("2d");
593
+ cx.drawImage(img, 0, 0, nw, nh);
594
+ var resized = canvas.toDataURL("image/jpeg", RESIZE_QUALITY);
595
+ addPendingImage(resized);
596
+ };
597
+ img.src = dataUrl;
598
+ };
599
+ reader.readAsDataURL(blob);
600
+ }
601
+
602
+ // --- Slash menu ---
603
+ function getAllCommands() {
604
+ return builtinCommands.concat(ctx.slashCommands());
605
+ }
606
+
607
+ function showSlashMenu(filter) {
608
+ var query = filter.toLowerCase();
609
+ slashFiltered = getAllCommands().filter(function (c) {
610
+ return c.name.toLowerCase().indexOf(query) !== -1;
611
+ });
612
+ if (slashFiltered.length === 0) { hideSlashMenu(); return; }
613
+
614
+ slashActiveIdx = 0;
615
+ ctx.slashMenu.innerHTML = slashFiltered.map(function (c, i) {
616
+ return '<div class="slash-item' + (i === 0 ? ' active' : '') + '" data-idx="' + i + '">' +
617
+ '<span class="slash-cmd">/' + c.name + '</span>' +
618
+ '<span class="slash-desc">' + c.desc + '</span>' +
619
+ '</div>';
620
+ }).join("");
621
+ ctx.slashMenu.classList.add("visible");
622
+ }
623
+
624
+ export function hideSlashMenu() {
625
+ if (slashFiltered.length === 0 && slashActiveIdx === -1) return; // already hidden
626
+ ctx.slashMenu.classList.remove("visible");
627
+ ctx.slashMenu.innerHTML = "";
628
+ slashActiveIdx = -1;
629
+ slashFiltered = [];
630
+ }
631
+
632
+ function selectSlashItem(idx) {
633
+ if (idx < 0 || idx >= slashFiltered.length) return;
634
+ var cmd = slashFiltered[idx];
635
+ ctx.inputEl.value = "/" + cmd.name + " ";
636
+ hideSlashMenu();
637
+ autoResize();
638
+ ctx.inputEl.focus();
639
+ }
640
+
641
+ function updateSlashHighlight() {
642
+ ctx.slashMenu.querySelectorAll(".slash-item").forEach(function (el, i) {
643
+ el.classList.toggle("active", i === slashActiveIdx);
644
+ });
645
+ var activeEl = ctx.slashMenu.querySelector(".slash-item.active");
646
+ if (activeEl) activeEl.scrollIntoView({ block: "nearest" });
647
+ }
648
+
649
+ // --- Input sync across devices ---
650
+ var inputSyncTimer = null;
651
+ function scheduleSendInputSync() {
652
+ if (inputSyncTimer) clearTimeout(inputSyncTimer);
653
+ inputSyncTimer = setTimeout(function () {
654
+ inputSyncTimer = null;
655
+ sendInputSync();
656
+ }, 100);
657
+ }
658
+
659
+ function sendInputSync() {
660
+ if (isRemoteInput) return;
661
+ if (!ctx.ws || !ctx.connected) return;
662
+ // In DM mode, send typing indicator instead of input_sync
663
+ if (ctx.isDmMode && ctx.isDmMode()) {
664
+ var hasText = ctx.inputEl.value.length > 0;
665
+ var dk = ctx.getDmKey ? ctx.getDmKey() : null;
666
+ if (dk) sendWsQuiet({ type: "dm_typing", dmKey: dk, typing: hasText });
667
+ return;
668
+ }
669
+ sendWsQuiet({ type: "input_sync", text: ctx.inputEl.value });
670
+ }
671
+
672
+ export function handleInputSync(text) {
673
+ isRemoteInput = true;
674
+ ctx.inputEl.value = text;
675
+ autoResize();
676
+ isRemoteInput = false;
677
+ // Sync send/stop button state
678
+ if (ctx.processing && ctx.setSendBtnMode) {
679
+ ctx.setSendBtnMode(hasSendableContent() ? "send" : "stop");
680
+ }
681
+ }
682
+
683
+ function createFileInput(accept, capture, multiple) {
684
+ var input = document.createElement("input");
685
+ input.type = "file";
686
+ if (accept) input.accept = accept;
687
+ if (capture) input.setAttribute("capture", capture);
688
+ if (multiple) input.multiple = true;
689
+ input.style.display = "none";
690
+ document.body.appendChild(input);
691
+
692
+ input.addEventListener("change", function () {
693
+ if (input.files) {
694
+ for (var i = 0; i < input.files.length; i++) {
695
+ if (input.files[i].type.indexOf("image/") === 0) {
696
+ readImageBlob(input.files[i]);
697
+ } else {
698
+ uploadFile(input.files[i]);
699
+ }
700
+ }
701
+ }
702
+ document.body.removeChild(input);
703
+ });
704
+
705
+ input.click();
706
+ }
707
+
708
+ // --- Init ---
709
+ export function initInput(_ctx) {
710
+ ctx = _ctx;
711
+
712
+ if (!slashMenuBound && ctx.slashMenu) {
713
+ slashMenuBound = true;
714
+ ctx.slashMenu.addEventListener("click", function (e) {
715
+ var item = e.target.closest(".slash-item");
716
+ if (!item) return;
717
+ selectSlashItem(parseInt(item.dataset.idx, 10));
718
+ });
719
+ }
720
+
721
+ // File (clip) button — opens file picker for all types
722
+ var attachFileBtn = document.getElementById("attach-file-btn");
723
+ if (attachFileBtn) {
724
+ attachFileBtn.addEventListener("click", function (e) {
725
+ e.stopPropagation();
726
+ createFileInput(null, null, true);
727
+ });
728
+ }
729
+
730
+ // Image button — opens image picker (OS handles camera/gallery choice)
731
+ var attachImageBtn = document.getElementById("attach-image-btn");
732
+ if (attachImageBtn) {
733
+ attachImageBtn.addEventListener("click", function (e) {
734
+ e.stopPropagation();
735
+ createFileInput("image/*", null, true);
736
+ });
737
+ }
738
+
739
+ // Mobile "+" button -> unified bottom sheet with attach/image + context sources
740
+ var moreBtn = document.getElementById("input-more-btn");
741
+ var moreSheet = document.getElementById("input-more-sheet");
742
+ function openMoreSheet() {
743
+ if (!moreSheet) return;
744
+ // Render context sources into mobile sheet containers
745
+ try { renderContextPicker("-mobile"); } catch (e) {}
746
+ moreSheet.classList.remove("hidden");
747
+ requestAnimationFrame(function () { moreSheet.classList.add("open"); });
748
+ }
749
+ function closeMoreSheet() {
750
+ if (!moreSheet) return;
751
+ moreSheet.classList.remove("open");
752
+ setTimeout(function () { moreSheet.classList.add("hidden"); }, 250);
753
+ }
754
+ if (moreBtn && moreSheet) {
755
+ moreBtn.addEventListener("click", function (e) {
756
+ e.stopPropagation();
757
+ openMoreSheet();
758
+ });
759
+ var backdrop = moreSheet.querySelector(".input-more-backdrop");
760
+ if (backdrop) backdrop.addEventListener("click", closeMoreSheet);
761
+
762
+ var moreAttach = document.getElementById("input-more-attach");
763
+ if (moreAttach) moreAttach.addEventListener("click", function () {
764
+ closeMoreSheet();
765
+ createFileInput(null, null, true);
766
+ });
767
+ var moreImage = document.getElementById("input-more-image");
768
+ if (moreImage) moreImage.addEventListener("click", function () {
769
+ closeMoreSheet();
770
+ createFileInput("image/*", null, true);
771
+ });
772
+ }
773
+
774
+ // Schedule button — inline expand with minute input
775
+ var scheduleBtn = document.getElementById("schedule-btn");
776
+ var scheduleInlineInput = null;
777
+ var scheduleInlineLabel = null;
778
+ var scheduleOutsideHandler = null;
779
+
780
+ function formatDelayLabel(ms) {
781
+ var mins = Math.round(ms / 60000);
782
+ if (mins < 60) return mins + "m";
783
+ var hrs = Math.floor(mins / 60);
784
+ var rem = mins % 60;
785
+ return rem > 0 ? hrs + "h " + rem + "m" : hrs + "h";
786
+ }
787
+
788
+ function collapseScheduleBtn() {
789
+ if (!scheduleBtn) return;
790
+ scheduleBtn.classList.remove("schedule-expanded");
791
+ if (scheduleInlineInput) { scheduleInlineInput.remove(); scheduleInlineInput = null; }
792
+ if (scheduleInlineLabel) { scheduleInlineLabel.remove(); scheduleInlineLabel = null; }
793
+ if (scheduleOutsideHandler) {
794
+ document.removeEventListener("mousedown", scheduleOutsideHandler);
795
+ scheduleOutsideHandler = null;
796
+ }
797
+ }
798
+
799
+ function setScheduleDelay(ms) {
800
+ scheduleDelayMs = ms;
801
+ if (!scheduleBtn) return;
802
+ collapseScheduleBtn();
803
+ if (ms > 0) {
804
+ scheduleBtn.classList.add("schedule-active", "schedule-expanded");
805
+ scheduleBtn.title = "Scheduled: " + formatDelayLabel(ms) + " (click to clear)";
806
+ scheduleInlineLabel = document.createElement("span");
807
+ scheduleInlineLabel.className = "schedule-delay-label";
808
+ scheduleInlineLabel.textContent = formatDelayLabel(ms);
809
+ scheduleBtn.appendChild(scheduleInlineLabel);
810
+ } else {
811
+ scheduleBtn.classList.remove("schedule-active", "schedule-expanded");
812
+ scheduleBtn.title = "Schedule message";
813
+ }
814
+ }
815
+ _setScheduleDelayFn = setScheduleDelay;
816
+
817
+ function expandScheduleInput() {
818
+ if (!scheduleBtn) return;
819
+ scheduleBtn.classList.add("schedule-expanded");
820
+ scheduleInlineInput = document.createElement("input");
821
+ scheduleInlineInput.type = "number";
822
+ scheduleInlineInput.min = "1";
823
+ scheduleInlineInput.max = "1440";
824
+ scheduleInlineInput.placeholder = "min";
825
+ scheduleInlineInput.className = "schedule-inline-input";
826
+ scheduleBtn.appendChild(scheduleInlineInput);
827
+
828
+ setTimeout(function () { scheduleInlineInput.focus(); }, 0);
829
+
830
+ scheduleInlineInput.addEventListener("click", function (e) { e.stopPropagation(); });
831
+ scheduleInlineInput.addEventListener("keydown", function (e) {
832
+ if (e.key === "Enter") {
833
+ e.preventDefault();
834
+ var val = parseInt(scheduleInlineInput.value, 10);
835
+ if (val >= 1 && val <= 1440) {
836
+ setScheduleDelay(val * 60000);
837
+ } else {
838
+ collapseScheduleBtn();
839
+ }
840
+ } else if (e.key === "Escape") {
841
+ collapseScheduleBtn();
842
+ }
843
+ });
844
+
845
+ // Close on outside click
846
+ setTimeout(function () {
847
+ scheduleOutsideHandler = function (ev) {
848
+ if (!scheduleBtn.contains(ev.target)) {
849
+ if (scheduleInlineInput) {
850
+ var val = parseInt(scheduleInlineInput.value, 10);
851
+ if (val >= 1 && val <= 1440) {
852
+ setScheduleDelay(val * 60000);
853
+ } else {
854
+ collapseScheduleBtn();
855
+ }
856
+ }
857
+ document.removeEventListener("mousedown", scheduleOutsideHandler);
858
+ scheduleOutsideHandler = null;
859
+ }
860
+ };
861
+ document.addEventListener("mousedown", scheduleOutsideHandler);
862
+ }, 0);
863
+ }
864
+
865
+ if (scheduleBtn) {
866
+ scheduleBtn.addEventListener("click", function (e) {
867
+ e.stopPropagation();
868
+ if (scheduleDelayMs > 0) {
869
+ setScheduleDelay(0);
870
+ return;
871
+ }
872
+ if (scheduleInlineInput) {
873
+ collapseScheduleBtn();
874
+ } else {
875
+ expandScheduleInput();
876
+ }
877
+ });
878
+ }
879
+
880
+
881
+ // Paste handler
882
+ document.addEventListener("paste", function (e) {
883
+ // Don't intercept paste when typing in modals or other non-chat inputs
884
+ var target = e.target;
885
+ if (target && target.closest && target.closest(".sticky-note, #notes-archive, #ralph-wizard, .confirm-modal, .scheduler-detail, .us-modal")) return;
886
+
887
+ var cd = e.clipboardData;
888
+ if (!cd) return;
889
+
890
+ var found = false;
891
+
892
+ // Try clipboardData.files first (better Safari/iOS support)
893
+ if (cd.files && cd.files.length > 0) {
894
+ for (var i = 0; i < cd.files.length; i++) {
895
+ if (cd.files[i].type.indexOf("image/") === 0) {
896
+ found = true;
897
+ readImageBlob(cd.files[i]);
898
+ } else if (cd.files[i].name) {
899
+ found = true;
900
+ uploadFile(cd.files[i]);
901
+ }
902
+ }
903
+ }
904
+
905
+ // Fall back to clipboardData.items
906
+ if (!found && cd.items) {
907
+ for (var i = 0; i < cd.items.length; i++) {
908
+ if (cd.items[i].type.indexOf("image/") === 0) {
909
+ var blob = cd.items[i].getAsFile();
910
+ if (blob) {
911
+ found = true;
912
+ readImageBlob(blob);
913
+ }
914
+ } else if (cd.items[i].kind === "file") {
915
+ var fileBlob = cd.items[i].getAsFile();
916
+ if (fileBlob && fileBlob.name) {
917
+ found = true;
918
+ uploadFile(fileBlob);
919
+ }
920
+ }
921
+ }
922
+ }
923
+
924
+ // File path paste: detect file:// URIs or Finder file references
925
+ if (!found) {
926
+ var filePaths = extractFilePaths(cd);
927
+ if (filePaths.length > 0) {
928
+ e.preventDefault();
929
+ insertTextAtCursor(filePaths.join("\n"));
930
+ found = true;
931
+ }
932
+ }
933
+
934
+ // Long text paste → pasted chip
935
+ if (!found) {
936
+ var pastedText = cd.getData("text/plain");
937
+ if (pastedText && pastedText.length >= 500) {
938
+ e.preventDefault();
939
+ var preview = pastedText.substring(0, 50).replace(/\n/g, " ");
940
+ if (pastedText.length > 50) preview += "...";
941
+ pendingPastes.push({ text: pastedText, preview: preview });
942
+ renderInputPreviews();
943
+ found = true;
944
+ }
945
+ }
946
+
947
+ if (found) e.preventDefault();
948
+ });
949
+
950
+ // Input event handlers
951
+ ctx.inputEl.addEventListener("input", function () {
952
+ if (ctx.disarmStickyBottom) ctx.disarmStickyBottom();
953
+ scheduleAutoResize();
954
+ scheduleSendInputSync();
955
+ // Only hide ghost chips when one is actually visible — avoids a DOM query
956
+ // + classList mutation (which triggers :has() recalc) on every keypress.
957
+ if (ctx.hideSuggestionChips && ctx.getGhostSuggestion && ctx.getGhostSuggestion()) ctx.hideSuggestionChips();
958
+ var val = ctx.inputEl.value;
959
+ if (val.startsWith("/") && !val.includes(" ") && val.length > 1) {
960
+ showSlashMenu(val.substring(1));
961
+ hideMentionMenu();
962
+ } else if (val === "/") {
963
+ showSlashMenu("");
964
+ hideMentionMenu();
965
+ } else {
966
+ hideSlashMenu();
967
+ // Check for @mention — skip selectionStart read (forced layout) when
968
+ // there is no @ in the value at all.
969
+ if (val.indexOf("@") !== -1) {
970
+ var mentionCheck = checkForMention(val, ctx.inputEl.selectionStart);
971
+ if (mentionCheck.active) {
972
+ setMentionAtIdx(mentionCheck.startIdx);
973
+ showMentionMenu(mentionCheck.query);
974
+ } else {
975
+ hideMentionMenu();
976
+ }
977
+ } else {
978
+ hideMentionMenu();
979
+ }
980
+ }
981
+ // Toggle send/stop button based on input content during processing
982
+ if (ctx.processing && ctx.setSendBtnMode) {
983
+ ctx.setSendBtnMode(hasSendableContent() ? "send" : "stop");
984
+ }
985
+ });
986
+
987
+ ctx.inputEl.addEventListener("compositionstart", function () { isComposing = true; });
988
+ ctx.inputEl.addEventListener("compositionend", function () { isComposing = false; });
989
+
990
+ ctx.inputEl.addEventListener("keydown", function (e) {
991
+ // @Mention menu keyboard navigation
992
+ if (isMentionMenuVisible()) {
993
+ if (mentionMenuKeydown(e)) return;
994
+ }
995
+
996
+ if (slashFiltered.length > 0 && ctx.slashMenu.classList.contains("visible")) {
997
+ if (e.key === "ArrowDown") {
998
+ e.preventDefault();
999
+ slashActiveIdx = (slashActiveIdx + 1) % slashFiltered.length;
1000
+ updateSlashHighlight();
1001
+ return;
1002
+ }
1003
+ if (e.key === "ArrowUp") {
1004
+ e.preventDefault();
1005
+ slashActiveIdx = (slashActiveIdx - 1 + slashFiltered.length) % slashFiltered.length;
1006
+ updateSlashHighlight();
1007
+ return;
1008
+ }
1009
+ if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {
1010
+ e.preventDefault();
1011
+ selectSlashItem(slashActiveIdx);
1012
+ return;
1013
+ }
1014
+ if (e.key === "Escape") {
1015
+ e.preventDefault();
1016
+ hideSlashMenu();
1017
+ return;
1018
+ }
1019
+ }
1020
+
1021
+ // Backspace on empty input: remove mention chip if present
1022
+ if (e.key === "Backspace" && ctx.inputEl.value === "" && document.getElementById("input-mention-chip")) {
1023
+ e.preventDefault();
1024
+ removeMentionChip();
1025
+ return;
1026
+ }
1027
+
1028
+ // Ctrl+J: insert newline (like Claude CLI)
1029
+ if (e.key === "j" && e.ctrlKey && !e.metaKey) {
1030
+ e.preventDefault();
1031
+ var ta = ctx.inputEl;
1032
+ var start = ta.selectionStart;
1033
+ var end = ta.selectionEnd;
1034
+ var val = ta.value;
1035
+ ta.value = val.substring(0, start) + "\n" + val.substring(end);
1036
+ ta.selectionStart = ta.selectionEnd = start + 1;
1037
+ autoResize();
1038
+ return;
1039
+ }
1040
+
1041
+ if (e.key === "Enter" && !e.shiftKey && !isComposing) {
1042
+ // Mobile: Enter inserts newline, send via button only
1043
+ if ("ontouchstart" in window) {
1044
+ return;
1045
+ }
1046
+ e.preventDefault();
1047
+ // While Claude is processing and the user has nothing queued, Enter
1048
+ // must not adopt a ghost suggestion — pressing Enter while waiting
1049
+ // should be a no-op, not a send of a stale suggestion the user never
1050
+ // typed. Predicate is the live state, not the button's CSS class —
1051
+ // the class can drift on mobile after backgrounding/reconnect and
1052
+ // wedge the input. (lr-e6b5 follow-up)
1053
+ if (ctx.processing && !hasSendableContent()) {
1054
+ return;
1055
+ }
1056
+ // If input has no sendable content but ghost suggestion is showing, adopt it.
1057
+ // Use hasSendableContent() instead of checking inputEl.value alone so that
1058
+ // pending images, pastes, or files block the ghost-text adoption — otherwise
1059
+ // pressing Enter with only a pasted image/block queued would send the
1060
+ // suggestion instead of the user's actual content.
1061
+ var ghost = ctx.getGhostSuggestion ? ctx.getGhostSuggestion() : "";
1062
+ if (!hasSendableContent() && ghost) {
1063
+ ctx.inputEl.value = ghost;
1064
+ if (ctx.hideSuggestionChips) ctx.hideSuggestionChips();
1065
+ }
1066
+ sendMessage();
1067
+ }
1068
+ });
1069
+
1070
+ // Mobile: switch enterkeyhint to "enter" so keyboard shows return key
1071
+ if ("ontouchstart" in window) {
1072
+ ctx.inputEl.setAttribute("enterkeyhint", "enter");
1073
+ }
1074
+
1075
+ // Send/Stop button — gate on live state, not the button's CSS class.
1076
+ // If Claude is processing and the user has nothing queued, the click
1077
+ // is a Stop, never a send (no ghost-suggestion adoption from a Stop
1078
+ // click). Otherwise it's a send. The CSS class is just a visual cue
1079
+ // and can drift on mobile after backgrounding/reconnect; predicating
1080
+ // user-facing behavior on it wedges the input on mobile. (lr-e6b5 follow-up)
1081
+ ctx.sendBtn.addEventListener("click", function () {
1082
+ if (ctx.processing && !hasSendableContent()) {
1083
+ if (ctx.connected) {
1084
+ ctx.ws.send(JSON.stringify({ type: "stop" }));
1085
+ }
1086
+ return;
1087
+ }
1088
+ // Adopt ghost suggestion if input is empty
1089
+ var ghost = ctx.getGhostSuggestion ? ctx.getGhostSuggestion() : "";
1090
+ if (!hasSendableContent() && ghost) {
1091
+ ctx.inputEl.value = ghost;
1092
+ if (ctx.hideSuggestionChips) ctx.hideSuggestionChips();
1093
+ sendMessage();
1094
+ return;
1095
+ }
1096
+ if (hasSendableContent()) {
1097
+ sendMessage();
1098
+ return;
1099
+ }
1100
+ });
1101
+ ctx.sendBtn.addEventListener("dblclick", function (e) { e.preventDefault(); });
1102
+ }