@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,1966 @@
1
+ import { iconHtml, refreshIcons } from './icons.js';
2
+ import { escapeHtml, copyToClipboard } from './utils.js';
3
+ import { renderMarkdown, highlightCodeBlocks, renderMermaidBlocks, exportMarkdownAsPdf } from './markdown.js';
4
+ import { closeSidebar } from './sidebar.js';
5
+ import { closeTerminal } from './terminal.js';
6
+ import { renderUnifiedDiff, renderSplitDiff } from './diff.js';
7
+ import { initFileIcons, getFileIconSvg, getFolderIconSvg } from './fileicons.js';
8
+
9
+ var ctx;
10
+ var showDropHint = function () {};
11
+ var treeData = {}; // path -> { loaded, children }
12
+ var currentContent = null; // last read file content for copy
13
+ var currentFilePath = null; // path of the currently viewed file
14
+ var isRendered = false; // markdown render toggle state
15
+ var currentIsMarkdown = false;
16
+ var historyVisible = false;
17
+ var currentHistoryEntries = [];
18
+ var pendingNavigate = null; // { sessionLocalId, assistantUuid }
19
+ var selectedEntries = []; // up to 2 selected for compare
20
+ var compareMode = false;
21
+ var inlineDiffActive = false;
22
+ var gitDiffCache = {}; // hash -> diff text
23
+ var pendingGitDiff = null; // callback for pending git diff
24
+ var fileAtCache = {}; // hash -> file content
25
+ var pendingFileAt = null; // callback for pending file-at
26
+
27
+ export function initFileBrowser(_ctx) {
28
+ ctx = _ctx;
29
+
30
+ // Load material file icons in background
31
+ initFileIcons().then(function () {
32
+ // Re-render tree if already loaded, so file icons appear
33
+ if (treeData["."] && treeData["."].loaded) {
34
+ renderTree();
35
+ }
36
+ });
37
+
38
+ // --- Keyboard navigation ---
39
+ // Arrow keys move a "keyboard focus" ring through visible tree items,
40
+ // Enter activates (opens a file or toggles a folder), Left/Right
41
+ // collapses/expands folders and ascends/descends into them. The tree
42
+ // gets a tabindex so it can receive focus and keydown events.
43
+ if (ctx.fileTreeEl) {
44
+ ctx.fileTreeEl.setAttribute('tabindex', '0');
45
+ ctx.fileTreeEl.addEventListener('keydown', handleTreeKeyDown);
46
+ // When the user clicks any tree row, promote it to keyboard focus
47
+ // as well so subsequent arrow keys continue from that position.
48
+ ctx.fileTreeEl.addEventListener('click', function (e) {
49
+ var row = e.target && e.target.closest && e.target.closest('.file-tree-item');
50
+ if (row) setKbFocus(row);
51
+ });
52
+ }
53
+
54
+ // Search input <-> tree keyboard bridge:
55
+ // Enter in the search box drops focus back onto the tree and
56
+ // highlights the first visible result so the user can keep
57
+ // navigating with arrows. ArrowDown does the same for convenience.
58
+ var searchInput = document.getElementById('fb-search-input');
59
+ if (searchInput) {
60
+ searchInput.addEventListener('keydown', function (e) {
61
+ if (e.key === 'Enter' || e.key === 'ArrowDown') {
62
+ e.preventDefault();
63
+ focusFileTree();
64
+ var items = getVisibleTreeItems();
65
+ if (items.length) setKbFocus(items[0]);
66
+ }
67
+ });
68
+ }
69
+
70
+ // --- Drag-and-drop file paths into message input ---
71
+ var inputEl = document.getElementById("input");
72
+ var dropHintEl = null;
73
+ var dropHintTimer = null;
74
+
75
+ showDropHint = function () {
76
+ if (!inputEl) return;
77
+ if (!dropHintEl) {
78
+ dropHintEl = document.createElement("div");
79
+ dropHintEl.className = "fb-drop-hint";
80
+ dropHintEl.textContent = "Drop here to insert file path";
81
+ inputEl.parentElement.style.position = "relative";
82
+ inputEl.parentElement.appendChild(dropHintEl);
83
+ }
84
+ dropHintEl.classList.add("visible");
85
+ clearTimeout(dropHintTimer);
86
+ // Auto-hide after drag ends without drop
87
+ dropHintTimer = setTimeout(function () { hideDropHint(); }, 3000);
88
+ }
89
+
90
+ function hideDropHint() {
91
+ clearTimeout(dropHintTimer);
92
+ if (dropHintEl) dropHintEl.classList.remove("visible");
93
+ }
94
+
95
+ if (inputEl) {
96
+ inputEl.addEventListener("dragover", function (e) {
97
+ if (e.dataTransfer.types.indexOf("text/plain") !== -1) {
98
+ e.preventDefault();
99
+ e.dataTransfer.dropEffect = "copy";
100
+ inputEl.classList.add("drop-target");
101
+ }
102
+ });
103
+ inputEl.addEventListener("dragleave", function () {
104
+ inputEl.classList.remove("drop-target");
105
+ });
106
+ inputEl.addEventListener("drop", function (e) {
107
+ inputEl.classList.remove("drop-target");
108
+ hideDropHint();
109
+ var filePath = e.dataTransfer.getData("text/plain");
110
+ if (!filePath) return;
111
+ e.preventDefault();
112
+ var cursorPos = inputEl.selectionStart || 0;
113
+ var before = inputEl.value.substring(0, cursorPos);
114
+ var after = inputEl.value.substring(cursorPos);
115
+ var prefix = before.length > 0 && before[before.length - 1] !== " " && before[before.length - 1] !== "\n" ? " " : "";
116
+ var suffix = after.length > 0 && after[0] !== " " && after[0] !== "\n" ? " " : "";
117
+ inputEl.value = before + prefix + filePath + suffix + after;
118
+ var newPos = cursorPos + prefix.length + filePath.length + suffix.length;
119
+ inputEl.setSelectionRange(newPos, newPos);
120
+ inputEl.focus();
121
+ inputEl.dispatchEvent(new Event("input", { bubbles: true }));
122
+ });
123
+ // Hide hint when drag ends anywhere on the page
124
+ document.addEventListener("dragend", function () {
125
+ inputEl.classList.remove("drop-target");
126
+ hideDropHint();
127
+ });
128
+ }
129
+
130
+ // Close button
131
+ document.getElementById("file-viewer-close").addEventListener("click", function () {
132
+ closeFileViewer();
133
+ });
134
+
135
+ // Fullscreen toggle
136
+ document.getElementById("file-viewer-fullscreen").addEventListener("click", function () {
137
+ var isFs = ctx.fileViewerEl.classList.toggle("panel-fullscreen");
138
+ var icon = this.querySelector("[data-lucide]");
139
+ if (icon) {
140
+ icon.setAttribute("data-lucide", isFs ? "minimize-2" : "maximize-2");
141
+ refreshIcons();
142
+ }
143
+ });
144
+
145
+ // Copy button
146
+ document.getElementById("file-viewer-copy").addEventListener("click", function () {
147
+ if (currentContent) copyToClipboard(currentContent);
148
+ });
149
+
150
+ // Markdown render toggle
151
+ document.getElementById("file-viewer-render").addEventListener("click", function () {
152
+ if (!currentContent || !currentIsMarkdown) return;
153
+ isRendered = !isRendered;
154
+ renderBody();
155
+ });
156
+
157
+ // PDF export button
158
+ document.getElementById("file-viewer-pdf").addEventListener("click", function () {
159
+ if (!isRendered || !currentIsMarkdown) return;
160
+ var mdEl = document.querySelector(".file-viewer-markdown");
161
+ if (!mdEl) return;
162
+ var btn = document.getElementById("file-viewer-pdf");
163
+ btn.disabled = true;
164
+ exportMarkdownAsPdf(mdEl, currentFilePath).then(function () {
165
+ btn.disabled = false;
166
+ }).catch(function (err) {
167
+ btn.disabled = false;
168
+ console.error("PDF export failed:", err);
169
+ });
170
+ });
171
+
172
+ // History button
173
+ document.getElementById("file-viewer-history").addEventListener("click", function () {
174
+ if (currentHistoryEntries.length === 0) return;
175
+ historyVisible = !historyVisible;
176
+ inlineDiffActive = false;
177
+ compareMode = false;
178
+ selectedEntries = [];
179
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
180
+ if (historyVisible) {
181
+ renderHistoryPanel();
182
+ } else {
183
+ rerenderFileContent();
184
+ }
185
+ });
186
+
187
+ // File viewer refresh button
188
+ var viewerRefreshBtn = document.getElementById("file-viewer-refresh");
189
+ if (viewerRefreshBtn) {
190
+ viewerRefreshBtn.addEventListener("click", function () {
191
+ if (!currentFilePath) return;
192
+ viewerRefreshBtn.classList.add("spinning");
193
+ setTimeout(function () { viewerRefreshBtn.classList.remove("spinning"); }, 500);
194
+ requestFileContent(currentFilePath);
195
+ });
196
+ }
197
+
198
+ // Refresh button
199
+ var refreshBtn = document.getElementById("file-panel-refresh");
200
+ if (refreshBtn) {
201
+ refreshBtn.addEventListener("click", function () {
202
+ refreshBtn.classList.add("spinning");
203
+ setTimeout(function () { refreshBtn.classList.remove("spinning"); }, 500);
204
+ refreshTree();
205
+ });
206
+ }
207
+
208
+ // ESC to close
209
+ document.addEventListener("keydown", function (e) {
210
+ if (e.key === "Escape" && !ctx.fileViewerEl.classList.contains("hidden")) {
211
+ closeFileViewer();
212
+ }
213
+ });
214
+
215
+ // --- File search ---
216
+ var fbSearchInput = document.getElementById("fb-search-input");
217
+ var searchDebounce = null;
218
+
219
+ if (fbSearchInput) {
220
+ fbSearchInput.addEventListener("input", function () {
221
+ var q = fbSearchInput.value.trim();
222
+ if (searchDebounce) clearTimeout(searchDebounce);
223
+ if (!q) {
224
+ renderTree();
225
+ restoreExpanded({});
226
+ return;
227
+ }
228
+ searchDebounce = setTimeout(function () {
229
+ if (ctx.ws && ctx.connected) {
230
+ ctx.ws.send(JSON.stringify({ type: "fs_search", query: q }));
231
+ }
232
+ }, 200);
233
+ });
234
+ fbSearchInput.addEventListener("keydown", function (e) {
235
+ if (e.key === "Escape" && fbSearchInput.value) {
236
+ e.stopPropagation();
237
+ fbSearchInput.value = "";
238
+ renderTree();
239
+ restoreExpanded({});
240
+ }
241
+ });
242
+ }
243
+ }
244
+
245
+ // --- Keyboard navigation helpers ---
246
+
247
+ var _kbFocused = null;
248
+
249
+ export function focusFileTree() {
250
+ if (!ctx || !ctx.fileTreeEl) return;
251
+ ctx.fileTreeEl.focus();
252
+ if (!_kbFocused) {
253
+ var first = ctx.fileTreeEl.querySelector('.file-tree-item');
254
+ if (first) setKbFocus(first);
255
+ }
256
+ }
257
+
258
+ function setKbFocus(el) {
259
+ if (_kbFocused && _kbFocused !== el) _kbFocused.classList.remove('fb-kb-focus');
260
+ _kbFocused = el || null;
261
+ if (el) {
262
+ el.classList.add('fb-kb-focus');
263
+ if (el.scrollIntoView) el.scrollIntoView({ block: 'nearest' });
264
+ }
265
+ }
266
+
267
+ function isDirRow(row) {
268
+ // Folder rows carry the chevron; file rows use a spacer instead.
269
+ return !!(row && row.querySelector && row.querySelector('.file-tree-chevron'));
270
+ }
271
+
272
+ function getVisibleTreeItems() {
273
+ if (!ctx || !ctx.fileTreeEl) return [];
274
+ var all = ctx.fileTreeEl.querySelectorAll('.file-tree-item');
275
+ var out = [];
276
+ for (var i = 0; i < all.length; i++) {
277
+ var el = all[i];
278
+ // Skip anything nested inside a hidden .file-tree-children subtree.
279
+ var hidden = false;
280
+ var p = el.parentNode;
281
+ while (p && p !== ctx.fileTreeEl) {
282
+ if (p.classList && p.classList.contains('file-tree-children') && p.classList.contains('hidden')) {
283
+ hidden = true;
284
+ break;
285
+ }
286
+ p = p.parentNode;
287
+ }
288
+ if (!hidden) out.push(el);
289
+ }
290
+ return out;
291
+ }
292
+
293
+ function moveKbFocus(delta) {
294
+ var items = getVisibleTreeItems();
295
+ if (items.length === 0) return;
296
+ var idx = _kbFocused ? items.indexOf(_kbFocused) : -1;
297
+ if (idx === -1) {
298
+ idx = delta > 0 ? 0 : items.length - 1;
299
+ } else {
300
+ idx = Math.max(0, Math.min(items.length - 1, idx + delta));
301
+ }
302
+ setKbFocus(items[idx]);
303
+ }
304
+
305
+ function kbExpandOrDescend() {
306
+ if (!_kbFocused) return;
307
+ if (!isDirRow(_kbFocused)) return;
308
+ if (!_kbFocused.classList.contains('expanded')) {
309
+ _kbFocused.click(); // triggers the existing expand handler
310
+ return;
311
+ }
312
+ // Already expanded — move focus to first child.
313
+ var children = _kbFocused.nextElementSibling;
314
+ if (children && children.classList.contains('file-tree-children')) {
315
+ var first = children.querySelector('.file-tree-item');
316
+ if (first) setKbFocus(first);
317
+ }
318
+ }
319
+
320
+ function kbCollapseOrAscend() {
321
+ if (!_kbFocused) return;
322
+ if (isDirRow(_kbFocused) && _kbFocused.classList.contains('expanded')) {
323
+ _kbFocused.click(); // triggers existing collapse handler
324
+ return;
325
+ }
326
+ // On a file or a collapsed folder — move focus to the parent folder.
327
+ var container = _kbFocused.parentNode;
328
+ if (container && container.classList && container.classList.contains('file-tree-children')) {
329
+ var parentRow = container.previousElementSibling;
330
+ if (parentRow && parentRow.classList && parentRow.classList.contains('file-tree-item')) {
331
+ setKbFocus(parentRow);
332
+ }
333
+ }
334
+ }
335
+
336
+ function kbActivate() {
337
+ if (_kbFocused) _kbFocused.click();
338
+ }
339
+
340
+ function handleTreeKeyDown(e) {
341
+ // Any arrow key with an empty tree (e.g. "No files found" for a
342
+ // search query) hands focus back to the search input so the user
343
+ // can fix the query without clicking.
344
+ var isArrow = e.key === 'ArrowDown' || e.key === 'ArrowUp'
345
+ || e.key === 'ArrowLeft' || e.key === 'ArrowRight';
346
+ if (isArrow && getVisibleTreeItems().length === 0) {
347
+ e.preventDefault();
348
+ var emptySearch = document.getElementById('fb-search-input');
349
+ if (emptySearch) {
350
+ if (_kbFocused) _kbFocused.classList.remove('fb-kb-focus');
351
+ _kbFocused = null;
352
+ emptySearch.focus();
353
+ try { emptySearch.select(); } catch (err) { /* ignore */ }
354
+ }
355
+ return;
356
+ }
357
+
358
+ if (e.key === 'ArrowDown') { e.preventDefault(); moveKbFocus(1); return; }
359
+ if (e.key === 'ArrowUp') {
360
+ e.preventDefault();
361
+ // At the top of the visible tree, pressing Up hands focus to the
362
+ // search box — a natural escape upward. Enter there brings focus
363
+ // back to the tree (handled by the search input's keydown below).
364
+ var items = getVisibleTreeItems();
365
+ if (items.length && _kbFocused === items[0]) {
366
+ var searchInput = document.getElementById('fb-search-input');
367
+ if (searchInput) {
368
+ if (_kbFocused) _kbFocused.classList.remove('fb-kb-focus');
369
+ searchInput.focus();
370
+ try { searchInput.select(); } catch (err) { /* ignore */ }
371
+ return;
372
+ }
373
+ }
374
+ moveKbFocus(-1);
375
+ return;
376
+ }
377
+ if (e.key === 'ArrowRight'){ e.preventDefault(); kbExpandOrDescend(); return; }
378
+ if (e.key === 'ArrowLeft') { e.preventDefault(); kbCollapseOrAscend(); return; }
379
+ if (e.key === 'Enter') { e.preventDefault(); kbActivate(); return; }
380
+ if (e.key === 'Home') { e.preventDefault(); var items3 = getVisibleTreeItems(); if (items3.length) setKbFocus(items3[0]); return; }
381
+ if (e.key === 'End') { e.preventDefault(); var items4 = getVisibleTreeItems(); if (items4.length) setKbFocus(items4[items4.length - 1]); return; }
382
+ }
383
+
384
+ // --- File watch helpers ---
385
+ function sendWatch(filePath) {
386
+ if (ctx.ws && ctx.connected) {
387
+ ctx.ws.send(JSON.stringify({ type: "fs_watch", path: filePath }));
388
+ }
389
+ }
390
+
391
+ function sendUnwatch() {
392
+ if (ctx.ws && ctx.connected) {
393
+ ctx.ws.send(JSON.stringify({ type: "fs_unwatch" }));
394
+ }
395
+ }
396
+
397
+ export function closeFileViewer() {
398
+ sendUnwatch();
399
+ inlineDiffActive = false;
400
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
401
+ ctx.fileViewerEl.classList.remove("panel-fullscreen");
402
+ ctx.fileViewerEl.classList.add("hidden");
403
+ // Reset fullscreen icon
404
+ var fsIcon = document.querySelector("#file-viewer-fullscreen [data-lucide]");
405
+ if (fsIcon) {
406
+ fsIcon.setAttribute("data-lucide", "maximize-2");
407
+ refreshIcons();
408
+ }
409
+ }
410
+
411
+ export function resetFileBrowser() {
412
+ // Close viewer
413
+ closeFileViewer();
414
+ // Clear all cached state
415
+ treeData = {};
416
+ currentContent = null;
417
+ currentFilePath = null;
418
+ isRendered = false;
419
+ currentIsMarkdown = false;
420
+ historyVisible = false;
421
+ currentHistoryEntries = [];
422
+ pendingNavigate = null;
423
+ selectedEntries = [];
424
+ compareMode = false;
425
+ inlineDiffActive = false;
426
+ gitDiffCache = {};
427
+ pendingGitDiff = null;
428
+ fileAtCache = {};
429
+ pendingFileAt = null;
430
+ // Clear tree UI
431
+ if (ctx && ctx.fileTreeEl) ctx.fileTreeEl.innerHTML = "";
432
+ // Hide the file browser panel, show sessions panel
433
+ var filesPanel = document.getElementById("sidebar-panel-files");
434
+ var sessionsPanel = document.getElementById("sidebar-panel-sessions");
435
+ var sessionsHeaderContent = document.getElementById("sessions-header-content");
436
+ if (filesPanel) filesPanel.classList.add("hidden");
437
+ if (sessionsPanel) sessionsPanel.classList.remove("hidden");
438
+ if (sessionsHeaderContent) sessionsHeaderContent.classList.remove("hidden");
439
+ }
440
+
441
+ var pendingOpenMode = null; // { type: "diff", oldStr, newStr } or null
442
+
443
+ export function openFile(filePath, opts) {
444
+ if (!filePath) return;
445
+ if (opts && opts.diff) {
446
+ pendingOpenMode = { type: "diff", oldStr: opts.diff.oldStr, newStr: opts.diff.newStr };
447
+ } else {
448
+ pendingOpenMode = null;
449
+ }
450
+ requestFileContent(filePath);
451
+ }
452
+
453
+ function renderBody() {
454
+ var bodyEl = document.getElementById("file-viewer-body");
455
+ var renderBtn = document.getElementById("file-viewer-render");
456
+ var pdfBtn = document.getElementById("file-viewer-pdf");
457
+
458
+ if (isRendered) {
459
+ bodyEl.innerHTML = '<div class="file-viewer-markdown">' + renderMarkdown(currentContent) + '</div>';
460
+ // Rewrite relative image src to use /api/file endpoint
461
+ var fileDir = currentFilePath ? currentFilePath.replace(/[^/]*$/, "") : "";
462
+ var imgs = bodyEl.querySelectorAll(".file-viewer-markdown img");
463
+ for (var i = 0; i < imgs.length; i++) {
464
+ var src = imgs[i].getAttribute("src");
465
+ if (src && !src.startsWith("http://") && !src.startsWith("https://") && !src.startsWith("data:") && !src.startsWith("api/file")) {
466
+ var resolvedPath = fileDir + src;
467
+ imgs[i].src = "api/file?path=" + encodeURIComponent(resolvedPath);
468
+ }
469
+ }
470
+ highlightCodeBlocks(bodyEl);
471
+ renderMermaidBlocks(bodyEl);
472
+ renderBtn.classList.add("active");
473
+ renderBtn.title = "Show raw";
474
+ pdfBtn.classList.remove("hidden");
475
+ } else {
476
+ var pre = document.createElement("pre");
477
+ var code = document.createElement("code");
478
+ code.className = "language-markdown";
479
+ code.textContent = currentContent;
480
+ pre.appendChild(code);
481
+ bodyEl.innerHTML = "";
482
+ bodyEl.appendChild(pre);
483
+ if (typeof hljs !== "undefined") {
484
+ hljs.highlightElement(code);
485
+ }
486
+ renderBtn.classList.remove("active");
487
+ renderBtn.title = "Render markdown";
488
+ pdfBtn.classList.add("hidden");
489
+ }
490
+ refreshIcons();
491
+ }
492
+
493
+ export function loadRootDirectory() {
494
+ if (treeData["."] && treeData["."].loaded) return;
495
+ requestDirectory(".");
496
+ }
497
+
498
+ export function refreshTree() {
499
+ // Collect currently expanded directory paths
500
+ var expandedDirs = ["."];
501
+ var expandedEls = ctx.fileTreeEl.querySelectorAll(".file-tree-item.expanded");
502
+ for (var i = 0; i < expandedEls.length; i++) {
503
+ var childEl = expandedEls[i].nextElementSibling;
504
+ if (childEl && childEl.dataset.parentPath) {
505
+ expandedDirs.push(childEl.dataset.parentPath);
506
+ }
507
+ }
508
+ // Clear cache for expanded dirs and re-request them
509
+ for (var j = 0; j < expandedDirs.length; j++) {
510
+ delete treeData[expandedDirs[j]];
511
+ requestDirectory(expandedDirs[j]);
512
+ }
513
+ }
514
+
515
+ function requestDirectory(dirPath) {
516
+ if (ctx.ws && ctx.connected) {
517
+ ctx.ws.send(JSON.stringify({ type: "fs_list", path: dirPath }));
518
+ }
519
+ }
520
+
521
+ function requestFileContent(filePath) {
522
+ if (ctx.ws && ctx.connected) {
523
+ ctx.ws.send(JSON.stringify({ type: "fs_read", path: filePath }));
524
+ }
525
+ }
526
+
527
+ var pendingRefresh = false;
528
+
529
+ export function refreshIfOpen(filePath) {
530
+ if (!currentFilePath || ctx.fileViewerEl.classList.contains("hidden")) return;
531
+ // Don't refresh while history panel or inline diff is showing
532
+ if (historyVisible || inlineDiffActive) return;
533
+ // Compare by suffix — tool paths are absolute, currentFilePath is relative
534
+ if (filePath === currentFilePath || filePath.endsWith("/" + currentFilePath)) {
535
+ pendingRefresh = true;
536
+ requestFileContent(currentFilePath);
537
+ }
538
+ }
539
+
540
+ // --- WS handlers ---
541
+
542
+ export function handleFsSearch(msg) {
543
+ var entries = msg.entries || [];
544
+ var query = (msg.query || "").trim().toLowerCase();
545
+ if (!query) return;
546
+
547
+ ctx.fileTreeEl.innerHTML = "";
548
+
549
+ if (entries.length === 0) {
550
+ ctx.fileTreeEl.innerHTML = '<div class="fb-search-empty">No files found</div>';
551
+ return;
552
+ }
553
+
554
+ // Build a tree structure from flat search results
555
+ var tree = {};
556
+ for (var i = 0; i < entries.length; i++) {
557
+ var entry = entries[i];
558
+ var parts = entry.path.split("/");
559
+ var node = tree;
560
+ for (var j = 0; j < parts.length; j++) {
561
+ if (!node[parts[j]]) node[parts[j]] = {};
562
+ if (j === parts.length - 1) {
563
+ node[parts[j]]._entry = entry;
564
+ } else {
565
+ node = node[parts[j]];
566
+ }
567
+ }
568
+ }
569
+
570
+ renderFilteredTree(ctx.fileTreeEl, tree, 0, query);
571
+ refreshIcons();
572
+ }
573
+
574
+ function renderFilteredTree(container, tree, depth, query) {
575
+ var keys = Object.keys(tree);
576
+ var dirs = [];
577
+ var files = [];
578
+ for (var i = 0; i < keys.length; i++) {
579
+ if (keys[i] === "_entry") continue;
580
+ var node = tree[keys[i]];
581
+ var entry = node._entry;
582
+ if (entry && entry.type === "file") {
583
+ files.push(keys[i]);
584
+ } else {
585
+ dirs.push(keys[i]);
586
+ }
587
+ }
588
+ dirs.sort(function (a, b) {
589
+ var aH = a.charAt(0) === ".";
590
+ var bH = b.charAt(0) === ".";
591
+ if (aH !== bH) return aH ? 1 : -1;
592
+ return a.localeCompare(b);
593
+ });
594
+ files.sort(function (a, b) {
595
+ var aH = a.charAt(0) === ".";
596
+ var bH = b.charAt(0) === ".";
597
+ if (aH !== bH) return aH ? 1 : -1;
598
+ return a.localeCompare(b);
599
+ });
600
+
601
+ var allKeys = dirs.concat(files);
602
+ for (var k = 0; k < allKeys.length; k++) {
603
+ var name = allKeys[k];
604
+ var node = tree[name];
605
+ var entry = node._entry;
606
+ var isDir = !entry || entry.type === "dir";
607
+
608
+ var row = document.createElement("div");
609
+ row.className = "file-tree-item" + (isDir ? " expanded" : "");
610
+ row.style.paddingLeft = (8 + depth * 16) + "px";
611
+ if (entry) {
612
+ row.draggable = true;
613
+ row.dataset.path = entry.path;
614
+ row.addEventListener("dragstart", function (e) {
615
+ var cwd = ctx.cwd || "";
616
+ var rel = this.dataset.path;
617
+ var abs = cwd ? cwd.replace(/\/$/, "") + "/" + rel : rel;
618
+ e.dataTransfer.setData("text/plain", abs);
619
+ e.dataTransfer.effectAllowed = "copy";
620
+ });
621
+ }
622
+
623
+ var nameHtml = highlightMatch(name, query);
624
+
625
+ if (isDir) {
626
+ row.innerHTML =
627
+ '<span class="file-tree-chevron">' + iconHtml("chevron-right") + '</span>' +
628
+ '<span class="file-tree-icon file-tree-folder-icon"></span>' +
629
+ '<span class="file-tree-name">' + nameHtml + '</span>';
630
+
631
+ (function (iconEl, n) {
632
+ getFolderIconSvg(n, true, function (svg) { iconEl.innerHTML = svg; });
633
+ })(row.querySelector(".file-tree-folder-icon"), name);
634
+
635
+ var childContainer = document.createElement("div");
636
+ childContainer.className = "file-tree-children";
637
+
638
+ // Toggle expand/collapse on click
639
+ (function (rowEl, childEl, folderName) {
640
+ rowEl.addEventListener("click", function (e) {
641
+ e.stopPropagation();
642
+ var isExpanded = rowEl.classList.contains("expanded");
643
+ rowEl.classList.toggle("expanded");
644
+ childEl.classList.toggle("hidden", isExpanded);
645
+ var folderIconEl = rowEl.querySelector(".file-tree-folder-icon");
646
+ if (folderIconEl) {
647
+ getFolderIconSvg(folderName, !isExpanded, function (svg) { folderIconEl.innerHTML = svg; });
648
+ }
649
+ });
650
+ })(row, childContainer, name);
651
+
652
+ container.appendChild(row);
653
+ container.appendChild(childContainer);
654
+ renderFilteredTree(childContainer, node, depth + 1, query);
655
+ } else {
656
+ row.innerHTML =
657
+ '<span class="file-tree-spacer"></span>' +
658
+ '<span class="file-tree-icon">' + getFileIconSvg(name) + '</span>' +
659
+ '<span class="file-tree-name">' + nameHtml + '</span>';
660
+
661
+ (function (filePath, rowEl) {
662
+ rowEl.addEventListener("click", function (e) {
663
+ e.stopPropagation();
664
+ var prev = ctx.fileTreeEl.querySelector(".file-tree-item.active");
665
+ if (prev) prev.classList.remove("active");
666
+ rowEl.classList.add("active");
667
+ requestFileContent(filePath);
668
+ if (window.innerWidth <= 768) closeSidebar();
669
+ });
670
+ })(entry.path, row);
671
+
672
+ container.appendChild(row);
673
+ }
674
+ }
675
+ }
676
+
677
+ function highlightMatch(text, query) {
678
+ var lower = text.toLowerCase();
679
+ var idx = lower.indexOf(query);
680
+ if (idx === -1) return escapeHtml(text);
681
+ return escapeHtml(text.substring(0, idx)) +
682
+ '<mark>' + escapeHtml(text.substring(idx, idx + query.length)) + '</mark>' +
683
+ escapeHtml(text.substring(idx + query.length));
684
+ }
685
+
686
+ export function handleFsList(msg) {
687
+ var dirPath = msg.path || ".";
688
+ treeData[dirPath] = { loaded: true, children: msg.entries || [] };
689
+
690
+ if (msg.error) {
691
+ if (dirPath === ".") {
692
+ ctx.fileTreeEl.innerHTML = '<div class="file-tree-error">' + escapeHtml(msg.error) + '</div>';
693
+ } else {
694
+ var errEl = ctx.fileTreeEl.querySelector('.file-tree-children[data-parent-path="' + dirPath + '"]');
695
+ if (errEl) {
696
+ errEl.innerHTML = '<div class="file-tree-error">' + escapeHtml(msg.error) + '</div>';
697
+ }
698
+ }
699
+ return;
700
+ }
701
+
702
+ // Root level
703
+ if (dirPath === ".") {
704
+ // Preserve expanded state across re-render
705
+ var expandedSet = {};
706
+ var expandedEls = ctx.fileTreeEl.querySelectorAll(".file-tree-item.expanded");
707
+ for (var ei = 0; ei < expandedEls.length; ei++) {
708
+ var sib = expandedEls[ei].nextElementSibling;
709
+ if (sib && sib.dataset.parentPath) expandedSet[sib.dataset.parentPath] = true;
710
+ }
711
+ renderTree();
712
+ restoreExpanded(expandedSet);
713
+ return;
714
+ }
715
+
716
+ // Sub-directory: re-render its child container
717
+ var childEl = ctx.fileTreeEl.querySelector('.file-tree-children[data-parent-path="' + dirPath + '"]');
718
+ if (childEl) {
719
+ childEl.innerHTML = "";
720
+ var depth = dirPath.split("/").length;
721
+ renderEntries(childEl, treeData[dirPath].children, depth);
722
+ refreshIcons();
723
+ }
724
+ }
725
+
726
+ export function handleDirChanged(msg) {
727
+ var dirPath = msg.path || ".";
728
+ var oldData = treeData[dirPath];
729
+ treeData[dirPath] = { loaded: true, children: msg.entries || [] };
730
+
731
+ // Only re-render if the entries actually changed
732
+ if (oldData && oldData.loaded) {
733
+ var oldKeys = (oldData.children || []).map(function (e) { return e.name + ":" + e.type; }).sort().join(",");
734
+ var newKeys = (msg.entries || []).map(function (e) { return e.name + ":" + e.type; }).sort().join(",");
735
+ if (oldKeys === newKeys) return;
736
+ }
737
+
738
+ // Collect expanded directories before re-render
739
+ var expandedSet = {};
740
+ var expandedEls = ctx.fileTreeEl.querySelectorAll(".file-tree-item.expanded");
741
+ for (var i = 0; i < expandedEls.length; i++) {
742
+ var sib = expandedEls[i].nextElementSibling;
743
+ if (sib && sib.dataset.parentPath) expandedSet[sib.dataset.parentPath] = true;
744
+ }
745
+
746
+ if (dirPath === ".") {
747
+ renderTree();
748
+ // Restore expanded state
749
+ restoreExpanded(expandedSet);
750
+ } else {
751
+ var childEl = ctx.fileTreeEl.querySelector('.file-tree-children[data-parent-path="' + dirPath + '"]');
752
+ if (childEl && !childEl.classList.contains("hidden")) {
753
+ childEl.innerHTML = "";
754
+ var depth = dirPath.split("/").length;
755
+ renderEntries(childEl, treeData[dirPath].children, depth);
756
+ refreshIcons();
757
+ }
758
+ }
759
+ }
760
+
761
+ function restoreExpanded(expandedSet) {
762
+ var containers = ctx.fileTreeEl.querySelectorAll(".file-tree-children");
763
+ for (var i = 0; i < containers.length; i++) {
764
+ var p = containers[i].dataset.parentPath;
765
+ if (p && expandedSet[p] && treeData[p] && treeData[p].loaded) {
766
+ containers[i].classList.remove("hidden");
767
+ var row = containers[i].previousElementSibling;
768
+ if (row) row.classList.add("expanded");
769
+ containers[i].innerHTML = "";
770
+ var depth = p.split("/").length;
771
+ renderEntries(containers[i], treeData[p].children, depth);
772
+ }
773
+ }
774
+ // Restore active file highlight
775
+ if (currentFilePath && !ctx.fileViewerEl.classList.contains("hidden")) {
776
+ var items = ctx.fileTreeEl.querySelectorAll(".file-tree-item");
777
+ for (var j = 0; j < items.length; j++) {
778
+ var nameEl = items[j].querySelector(".file-tree-name");
779
+ if (nameEl && nameEl.textContent === currentFilePath.split("/").pop()) {
780
+ items[j].classList.add("active");
781
+ break;
782
+ }
783
+ }
784
+ }
785
+ refreshIcons();
786
+ }
787
+
788
+ export function handleFsRead(msg) {
789
+ showFileContent(msg);
790
+ }
791
+
792
+ // --- Tree rendering ---
793
+
794
+ function renderTree() {
795
+ var root = treeData["."];
796
+ if (!root || !root.children || root.children.length === 0) {
797
+ ctx.fileTreeEl.innerHTML = '<div class="file-tree-empty">No files</div>';
798
+ return;
799
+ }
800
+ ctx.fileTreeEl.innerHTML = "";
801
+ renderEntries(ctx.fileTreeEl, root.children, 0);
802
+ refreshIcons();
803
+ }
804
+
805
+ function sortEntries(entries) {
806
+ return entries.slice().sort(function (a, b) {
807
+ if (a.type !== b.type) return a.type === "dir" ? -1 : 1;
808
+ var aH = a.name.charAt(0) === ".";
809
+ var bH = b.name.charAt(0) === ".";
810
+ if (aH !== bH) return aH ? 1 : -1;
811
+ return a.name.localeCompare(b.name);
812
+ });
813
+ }
814
+
815
+ function renderEntries(container, entries, depth) {
816
+ var sorted = sortEntries(entries);
817
+
818
+ for (var i = 0; i < sorted.length; i++) {
819
+ var entry = sorted[i];
820
+ var row = document.createElement("div");
821
+ row.className = "file-tree-item";
822
+ row.style.paddingLeft = (8 + depth * 16) + "px";
823
+
824
+ row.draggable = true;
825
+ row.dataset.path = entry.path;
826
+ row.addEventListener("dragstart", function (e) {
827
+ var cwd = ctx.cwd || "";
828
+ var rel = this.dataset.path;
829
+ var abs = cwd ? cwd.replace(/\/$/, "") + "/" + rel : rel;
830
+ e.dataTransfer.setData("text/plain", abs);
831
+ e.dataTransfer.effectAllowed = "copy";
832
+ showDropHint();
833
+ });
834
+
835
+ if (entry.type === "dir") {
836
+ row.innerHTML =
837
+ '<span class="file-tree-chevron">' + iconHtml("chevron-right") + '</span>' +
838
+ '<span class="file-tree-icon file-tree-folder-icon"></span>' +
839
+ '<span class="file-tree-name">' + escapeHtml(entry.name) + '</span>';
840
+
841
+ // Async-load folder icon SVG
842
+ (function (iconEl, name) {
843
+ getFolderIconSvg(name, false, function (svg) {
844
+ iconEl.innerHTML = svg;
845
+ });
846
+ })(row.querySelector(".file-tree-folder-icon"), entry.name);
847
+
848
+ var childContainer = document.createElement("div");
849
+ childContainer.className = "file-tree-children hidden";
850
+ childContainer.dataset.parentPath = entry.path;
851
+
852
+ (function (dirPath, childEl, rowEl, folderName) {
853
+ rowEl.addEventListener("click", function (e) {
854
+ e.stopPropagation();
855
+ var isExpanded = rowEl.classList.contains("expanded");
856
+ if (isExpanded) {
857
+ rowEl.classList.remove("expanded");
858
+ childEl.classList.add("hidden");
859
+ } else {
860
+ rowEl.classList.add("expanded");
861
+ childEl.classList.remove("hidden");
862
+ if (!treeData[dirPath] || !treeData[dirPath].loaded) {
863
+ childEl.innerHTML = '<div class="file-tree-loading">Loading...</div>';
864
+ requestDirectory(dirPath);
865
+ } else {
866
+ childEl.innerHTML = "";
867
+ var d = dirPath.split("/").length;
868
+ renderEntries(childEl, treeData[dirPath].children, d);
869
+ refreshIcons();
870
+ }
871
+ }
872
+ // Swap folder icon open/closed
873
+ var folderIconEl = rowEl.querySelector(".file-tree-folder-icon");
874
+ if (folderIconEl) {
875
+ getFolderIconSvg(folderName, !isExpanded, function (svg) {
876
+ folderIconEl.innerHTML = svg;
877
+ });
878
+ }
879
+ });
880
+ })(entry.path, childContainer, row, entry.name);
881
+
882
+ container.appendChild(row);
883
+ container.appendChild(childContainer);
884
+ } else {
885
+ var fileSvg = getFileIconSvg(entry.name);
886
+ row.innerHTML =
887
+ '<span class="file-tree-spacer"></span>' +
888
+ '<span class="file-tree-icon">' + fileSvg + '</span>' +
889
+ '<span class="file-tree-name">' + escapeHtml(entry.name) + '</span>';
890
+
891
+ (function (filePath, rowEl) {
892
+ rowEl.addEventListener("click", function (e) {
893
+ e.stopPropagation();
894
+ // Mark active
895
+ var prev = ctx.fileTreeEl.querySelector(".file-tree-item.active");
896
+ if (prev) prev.classList.remove("active");
897
+ rowEl.classList.add("active");
898
+ requestFileContent(filePath);
899
+ // Mobile: close sidebar
900
+ if (window.innerWidth <= 768) {
901
+ closeSidebar();
902
+ }
903
+ });
904
+ })(entry.path, row);
905
+
906
+ container.appendChild(row);
907
+ }
908
+ }
909
+ }
910
+
911
+
912
+ // --- File viewer ---
913
+
914
+ function showFileContent(msg) {
915
+ var pathEl = document.getElementById("file-viewer-path");
916
+ var bodyEl = document.getElementById("file-viewer-body");
917
+ var renderBtn = document.getElementById("file-viewer-render");
918
+
919
+ pathEl.textContent = msg.path;
920
+ var keepRenderState = pendingRefresh && msg.path === currentFilePath;
921
+ var prevRendered = isRendered;
922
+ pendingRefresh = false;
923
+ currentContent = null;
924
+ currentFilePath = msg.path;
925
+ currentIsMarkdown = false;
926
+ if (!keepRenderState) isRendered = false;
927
+ renderBtn.classList.add("hidden");
928
+ renderBtn.classList.remove("active");
929
+ document.getElementById("file-viewer-pdf").classList.add("hidden");
930
+
931
+ if (msg.error) {
932
+ bodyEl.innerHTML = '<div class="file-tree-error">' + escapeHtml(msg.error) + '</div>';
933
+ } else if (msg.binary) {
934
+ if (msg.imageUrl) {
935
+ bodyEl.innerHTML = '<div class="file-viewer-image"><img src="' + escapeHtml(msg.imageUrl) + '" alt="' + escapeHtml(msg.path) + '"></div>';
936
+ } else {
937
+ bodyEl.innerHTML = '<div class="file-viewer-binary">Binary file (' + formatSize(msg.size) + ')</div>';
938
+ }
939
+ } else {
940
+ currentContent = msg.content;
941
+ var ext = msg.path.split(".").pop().toLowerCase();
942
+ currentIsMarkdown = (ext === "md" || ext === "mdx");
943
+
944
+ if (currentIsMarkdown) {
945
+ renderBtn.classList.remove("hidden");
946
+ renderBtn.title = "Render markdown";
947
+ }
948
+
949
+ // Show raw by default, use renderBody for markdown toggle
950
+ if (currentIsMarkdown) {
951
+ renderBody();
952
+ } else {
953
+ renderCodeWithLineNumbers(bodyEl, msg.content, ext);
954
+ }
955
+ }
956
+
957
+ closeTerminal();
958
+ ctx.fileViewerEl.classList.remove("hidden");
959
+ sendWatch(msg.path);
960
+ refreshIcons();
961
+
962
+ // If opened with a diff request, show full-file split diff in wide mode
963
+ if (pendingOpenMode && pendingOpenMode.type === "diff" && currentContent != null) {
964
+ var diffOpts = pendingOpenMode;
965
+ pendingOpenMode = null;
966
+ historyVisible = false;
967
+ compareMode = false;
968
+ selectedEntries = [];
969
+ currentHistoryEntries = [];
970
+ gitDiffCache = {};
971
+ fileAtCache = {};
972
+ var historyBtn2 = document.getElementById("file-viewer-history");
973
+ historyBtn2.classList.add("hidden");
974
+ historyBtn2.classList.remove("active");
975
+ requestFileHistory(msg.path);
976
+ showInlineDiff(diffOpts.oldStr, diffOpts.newStr);
977
+ return;
978
+ }
979
+ pendingOpenMode = null;
980
+
981
+ // Request edit history for this file (skip on auto-refresh)
982
+ if (!keepRenderState) {
983
+ historyVisible = false;
984
+ compareMode = false;
985
+ selectedEntries = [];
986
+ currentHistoryEntries = [];
987
+ gitDiffCache = {};
988
+ fileAtCache = {};
989
+ var historyBtn = document.getElementById("file-viewer-history");
990
+ historyBtn.classList.add("hidden");
991
+ historyBtn.classList.remove("active");
992
+ requestFileHistory(msg.path);
993
+ }
994
+ }
995
+
996
+ export function handleFileChanged(msg) {
997
+ if (!msg.path || msg.path !== currentFilePath) return;
998
+ if (ctx.fileViewerEl.classList.contains("hidden")) return;
999
+ if (historyVisible || inlineDiffActive) return;
1000
+ if (msg.content === currentContent) return;
1001
+
1002
+ var bodyEl = document.getElementById("file-viewer-body");
1003
+ var scrollPos = bodyEl ? bodyEl.scrollTop : 0;
1004
+ pendingRefresh = true;
1005
+ showFileContent(msg);
1006
+ if (bodyEl) bodyEl.scrollTop = scrollPos;
1007
+ }
1008
+
1009
+ function showInlineDiff(oldStr, newStr) {
1010
+ var bodyEl = document.getElementById("file-viewer-body");
1011
+ inlineDiffActive = true;
1012
+ ctx.fileViewerEl.classList.add("file-viewer-wide");
1013
+
1014
+ if (!currentContent) return;
1015
+
1016
+ // Reconstruct full "before" file by replacing new_string with old_string
1017
+ var fileBefore = currentContent;
1018
+ var fileAfter = currentContent;
1019
+ if (newStr && oldStr != null) {
1020
+ var pos = currentContent.indexOf(newStr);
1021
+ if (pos >= 0) {
1022
+ fileBefore = currentContent.substring(0, pos) + oldStr + currentContent.substring(pos + newStr.length);
1023
+ }
1024
+ }
1025
+
1026
+ var diffLang = currentLang();
1027
+ var viewMode = "split";
1028
+
1029
+ function render() {
1030
+ bodyEl.innerHTML = "";
1031
+
1032
+ // Top bar
1033
+ var topBar = document.createElement("div");
1034
+ topBar.className = "file-history-view-bar";
1035
+
1036
+ var backBtn = document.createElement("button");
1037
+ backBtn.className = "file-history-compare-back";
1038
+ backBtn.textContent = "Back to file";
1039
+ backBtn.addEventListener("click", function () {
1040
+ inlineDiffActive = false;
1041
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
1042
+ rerenderFileContent();
1043
+ });
1044
+ topBar.appendChild(backBtn);
1045
+
1046
+ var toggleWrap = document.createElement("div");
1047
+ toggleWrap.className = "file-history-view-toggle";
1048
+
1049
+ var splitBtn = document.createElement("button");
1050
+ splitBtn.className = "file-history-toggle-btn" + (viewMode === "split" ? " active" : "");
1051
+ splitBtn.textContent = "Split";
1052
+ splitBtn.addEventListener("click", function () {
1053
+ viewMode = "split";
1054
+ render();
1055
+ });
1056
+
1057
+ var unifiedBtn = document.createElement("button");
1058
+ unifiedBtn.className = "file-history-toggle-btn" + (viewMode === "unified" ? " active" : "");
1059
+ unifiedBtn.textContent = "Unified";
1060
+ unifiedBtn.addEventListener("click", function () {
1061
+ viewMode = "unified";
1062
+ render();
1063
+ });
1064
+
1065
+ var sourceBtn = document.createElement("button");
1066
+ sourceBtn.className = "file-history-toggle-btn" + (viewMode === "source" ? " active" : "");
1067
+ sourceBtn.textContent = "Source";
1068
+ sourceBtn.addEventListener("click", function () {
1069
+ viewMode = "source";
1070
+ render();
1071
+ });
1072
+
1073
+ toggleWrap.appendChild(splitBtn);
1074
+ toggleWrap.appendChild(unifiedBtn);
1075
+ toggleWrap.appendChild(sourceBtn);
1076
+ topBar.appendChild(toggleWrap);
1077
+ bodyEl.appendChild(topBar);
1078
+
1079
+ if (viewMode === "source") {
1080
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
1081
+ var sourceWrap = document.createElement("div");
1082
+ sourceWrap.className = "file-history-diff-full";
1083
+ var ext = currentFilePath ? currentFilePath.split(".").pop().toLowerCase() : "";
1084
+ var lang = mapExtToLanguage(ext);
1085
+ var pre = document.createElement("pre");
1086
+ pre.className = "file-viewer-code-content";
1087
+ var codeEl = document.createElement("code");
1088
+ if (lang) codeEl.className = "language-" + lang;
1089
+ codeEl.textContent = fileAfter;
1090
+ pre.appendChild(codeEl);
1091
+ sourceWrap.appendChild(pre);
1092
+ bodyEl.appendChild(sourceWrap);
1093
+ if (typeof hljs !== "undefined" && lang) {
1094
+ hljs.highlightElement(codeEl);
1095
+ }
1096
+ } else {
1097
+ ctx.fileViewerEl.classList.add("file-viewer-wide");
1098
+
1099
+ // Full-file diff
1100
+ var diffWrap = document.createElement("div");
1101
+ diffWrap.className = "file-history-diff-full";
1102
+
1103
+ if (viewMode === "split") {
1104
+ diffWrap.appendChild(renderSplitDiff(fileBefore, fileAfter, diffLang));
1105
+ } else {
1106
+ diffWrap.appendChild(renderUnifiedDiff(fileBefore, fileAfter, diffLang));
1107
+ }
1108
+
1109
+ bodyEl.appendChild(diffWrap);
1110
+
1111
+ // Scroll to first changed row
1112
+ requestAnimationFrame(function () {
1113
+ var firstChange = diffWrap.querySelector(".diff-row-change, .diff-row-add, .diff-row-remove");
1114
+ if (firstChange) {
1115
+ firstChange.scrollIntoView({ behavior: "smooth", block: "center" });
1116
+ }
1117
+ });
1118
+ }
1119
+ }
1120
+
1121
+ render();
1122
+ }
1123
+
1124
+ function mapExtToLanguage(ext) {
1125
+ var map = {
1126
+ js: "javascript", ts: "typescript", jsx: "javascript", tsx: "typescript",
1127
+ py: "python", rb: "ruby", go: "go", rs: "rust", java: "java",
1128
+ css: "css", html: "xml", xml: "xml", json: "json", yaml: "yaml",
1129
+ yml: "yaml", md: "markdown", sh: "bash", bash: "bash", zsh: "bash",
1130
+ sql: "sql", c: "c", cpp: "cpp", h: "c", hpp: "cpp",
1131
+ cs: "csharp", swift: "swift", kt: "kotlin", vue: "xml", svelte: "xml"
1132
+ };
1133
+ return map[ext] || null;
1134
+ }
1135
+
1136
+ function currentLang() {
1137
+ if (!currentFilePath) return null;
1138
+ var ext = currentFilePath.split(".").pop().toLowerCase();
1139
+ return mapExtToLanguage(ext);
1140
+ }
1141
+
1142
+ function renderCodeWithLineNumbers(bodyEl, content, ext) {
1143
+ var lang = mapExtToLanguage(ext);
1144
+ var lines = content.split("\n");
1145
+ var lineCount = lines.length;
1146
+
1147
+ var viewer = document.createElement("div");
1148
+ viewer.className = "file-viewer-code";
1149
+
1150
+ var gutter = document.createElement("pre");
1151
+ gutter.className = "file-viewer-gutter";
1152
+ var nums = [];
1153
+ for (var i = 1; i <= lineCount; i++) nums.push(i);
1154
+ gutter.textContent = nums.join("\n");
1155
+
1156
+ var codeWrap = document.createElement("pre");
1157
+ codeWrap.className = "file-viewer-code-content";
1158
+ var codeEl = document.createElement("code");
1159
+ if (lang) codeEl.className = "language-" + lang;
1160
+ codeEl.textContent = content;
1161
+ codeWrap.appendChild(codeEl);
1162
+
1163
+ viewer.appendChild(gutter);
1164
+ viewer.appendChild(codeWrap);
1165
+
1166
+ bodyEl.innerHTML = "";
1167
+ bodyEl.appendChild(viewer);
1168
+
1169
+ if (typeof hljs !== "undefined" && lang) {
1170
+ hljs.highlightElement(codeEl);
1171
+ }
1172
+ }
1173
+
1174
+ function formatSize(bytes) {
1175
+ if (bytes < 1024) return bytes + " B";
1176
+ if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB";
1177
+ return (bytes / 1048576).toFixed(1) + " MB";
1178
+ }
1179
+
1180
+ // --- File edit history ---
1181
+
1182
+ function requestFileHistory(filePath) {
1183
+ if (ctx.ws && ctx.connected) {
1184
+ ctx.ws.send(JSON.stringify({ type: "fs_file_history", path: filePath }));
1185
+ }
1186
+ }
1187
+
1188
+ function requestGitDiff(hash, hash2) {
1189
+ if (ctx.ws && ctx.connected) {
1190
+ var msg = { type: "fs_git_diff", path: currentFilePath, hash: hash };
1191
+ if (hash2) msg.hash2 = hash2;
1192
+ ctx.ws.send(JSON.stringify(msg));
1193
+ }
1194
+ }
1195
+
1196
+ export function handleFileHistory(msg) {
1197
+ currentHistoryEntries = msg.entries || [];
1198
+ var historyBtn = document.getElementById("file-viewer-history");
1199
+
1200
+ if (currentHistoryEntries.length > 0 && currentContent !== null) {
1201
+ historyBtn.classList.remove("hidden");
1202
+ } else {
1203
+ historyBtn.classList.add("hidden");
1204
+ historyVisible = false;
1205
+ }
1206
+
1207
+ if (historyVisible && !compareMode) {
1208
+ renderHistoryPanel();
1209
+ }
1210
+ }
1211
+
1212
+ export function handleGitDiff(msg) {
1213
+ if (msg.hash && msg.diff !== undefined) {
1214
+ var key = msg.hash2 ? msg.hash + ".." + msg.hash2 : msg.hash;
1215
+ gitDiffCache[key] = msg.diff;
1216
+ }
1217
+ if (pendingGitDiff) {
1218
+ var cb = pendingGitDiff;
1219
+ pendingGitDiff = null;
1220
+ cb(msg);
1221
+ }
1222
+ }
1223
+
1224
+ function requestFileAt(hash) {
1225
+ if (ctx.ws && ctx.connected) {
1226
+ ctx.ws.send(JSON.stringify({ type: "fs_file_at", path: currentFilePath, hash: hash }));
1227
+ }
1228
+ }
1229
+
1230
+ export function handleFileAt(msg) {
1231
+ if (msg.hash && msg.content !== undefined) {
1232
+ fileAtCache[msg.hash] = msg.content;
1233
+ }
1234
+ if (pendingFileAt) {
1235
+ var cb = pendingFileAt;
1236
+ pendingFileAt = null;
1237
+ cb(msg);
1238
+ }
1239
+ }
1240
+
1241
+ function rerenderFileContent() {
1242
+ var historyBtn = document.getElementById("file-viewer-history");
1243
+ historyBtn.classList.remove("active");
1244
+
1245
+ if (!currentContent || !currentFilePath) return;
1246
+ var bodyEl = document.getElementById("file-viewer-body");
1247
+ var ext = currentFilePath.split(".").pop().toLowerCase();
1248
+
1249
+ if (currentIsMarkdown) {
1250
+ renderBody();
1251
+ } else {
1252
+ renderCodeWithLineNumbers(bodyEl, currentContent, ext);
1253
+ }
1254
+ refreshIcons();
1255
+ }
1256
+
1257
+ function isEntrySelected(entry) {
1258
+ for (var i = 0; i < selectedEntries.length; i++) {
1259
+ if (selectedEntries[i] === entry) return i + 1;
1260
+ }
1261
+ return 0;
1262
+ }
1263
+
1264
+ function toggleSelect(entry) {
1265
+ var idx = -1;
1266
+ for (var i = 0; i < selectedEntries.length; i++) {
1267
+ if (selectedEntries[i] === entry) { idx = i; break; }
1268
+ }
1269
+ if (idx >= 0) {
1270
+ selectedEntries.splice(idx, 1);
1271
+ } else {
1272
+ if (selectedEntries.length >= 2) selectedEntries.shift();
1273
+ selectedEntries.push(entry);
1274
+ }
1275
+ var bodyEl = document.getElementById("file-viewer-body");
1276
+ var scrollPos = bodyEl ? bodyEl.scrollTop : 0;
1277
+ renderHistoryPanel();
1278
+ if (bodyEl) {
1279
+ if (selectedEntries.length === 2) {
1280
+ // Both slots filled: scroll compare bar into view
1281
+ requestAnimationFrame(function () {
1282
+ var compareBtn = bodyEl.querySelector(".file-history-compare-btn");
1283
+ if (compareBtn) {
1284
+ compareBtn.scrollIntoView({ behavior: "smooth", block: "center" });
1285
+ }
1286
+ });
1287
+ } else {
1288
+ // Restore scroll position
1289
+ bodyEl.scrollTop = scrollPos;
1290
+ }
1291
+ }
1292
+ }
1293
+
1294
+ function renderHistoryPanel() {
1295
+ var bodyEl = document.getElementById("file-viewer-body");
1296
+ var historyBtn = document.getElementById("file-viewer-history");
1297
+ historyBtn.classList.add("active");
1298
+
1299
+ bodyEl.innerHTML = "";
1300
+
1301
+ var panel = document.createElement("div");
1302
+ panel.className = "file-history-panel";
1303
+
1304
+ // Header
1305
+ var header = document.createElement("div");
1306
+ header.className = "file-history-header";
1307
+
1308
+ var headerTitle = document.createElement("span");
1309
+ headerTitle.textContent = "History (" + currentHistoryEntries.length + ")";
1310
+ header.appendChild(headerTitle);
1311
+
1312
+ panel.appendChild(header);
1313
+
1314
+ // Compare bar
1315
+ var compareBar = document.createElement("div");
1316
+ compareBar.className = "file-history-compare-bar-slots";
1317
+
1318
+ var compareLabel = document.createElement("span");
1319
+ compareLabel.className = "compare-bar-label";
1320
+ compareLabel.innerHTML = iconHtml("arrow-left-right") + " Compare";
1321
+ compareBar.appendChild(compareLabel);
1322
+
1323
+ var slotsRow = document.createElement("div");
1324
+ slotsRow.className = "compare-slots-row";
1325
+
1326
+ var slotA = document.createElement("div");
1327
+ slotA.className = "file-history-compare-slot";
1328
+ if (selectedEntries.length >= 1) {
1329
+ slotA.classList.add("filled");
1330
+ slotA.innerHTML = '<span class="compare-slot-num">A</span><span class="compare-slot-text"></span><button class="compare-slot-clear">\u00d7</button>';
1331
+ slotA.querySelector(".compare-slot-text").textContent = shortEntryLabel(selectedEntries[0]);
1332
+ slotA.querySelector(".compare-slot-clear").addEventListener("click", function () {
1333
+ selectedEntries.splice(0, 1);
1334
+ renderHistoryPanel();
1335
+ });
1336
+ } else {
1337
+ slotA.innerHTML = '<span class="compare-slot-num">A</span><span class="compare-slot-placeholder">Select entry below</span>';
1338
+ }
1339
+
1340
+ var arrowSpan = document.createElement("span");
1341
+ arrowSpan.className = "compare-slot-arrow";
1342
+ arrowSpan.innerHTML = iconHtml("arrow-right");
1343
+
1344
+ var slotB = document.createElement("div");
1345
+ slotB.className = "file-history-compare-slot";
1346
+ if (selectedEntries.length >= 2) {
1347
+ slotB.classList.add("filled");
1348
+ slotB.innerHTML = '<span class="compare-slot-num">B</span><span class="compare-slot-text"></span><button class="compare-slot-clear">\u00d7</button>';
1349
+ slotB.querySelector(".compare-slot-text").textContent = shortEntryLabel(selectedEntries[1]);
1350
+ slotB.querySelector(".compare-slot-clear").addEventListener("click", function () {
1351
+ selectedEntries.splice(1, 1);
1352
+ renderHistoryPanel();
1353
+ });
1354
+ } else {
1355
+ slotB.innerHTML = '<span class="compare-slot-num">B</span><span class="compare-slot-placeholder">Select entry below</span>';
1356
+ }
1357
+
1358
+ slotsRow.appendChild(slotA);
1359
+ slotsRow.appendChild(arrowSpan);
1360
+ slotsRow.appendChild(slotB);
1361
+
1362
+ if (selectedEntries.length === 2) {
1363
+ var compareBtn = document.createElement("button");
1364
+ compareBtn.className = "file-history-compare-btn";
1365
+ compareBtn.innerHTML = iconHtml("arrow-left-right") + " Compare";
1366
+ compareBtn.addEventListener("click", function () {
1367
+ compareMode = true;
1368
+ renderCompareView();
1369
+ });
1370
+ slotsRow.appendChild(compareBtn);
1371
+ }
1372
+
1373
+ compareBar.appendChild(slotsRow);
1374
+ panel.appendChild(compareBar);
1375
+
1376
+ var list = document.createElement("div");
1377
+ list.className = "file-history-list";
1378
+
1379
+ for (var i = 0; i < currentHistoryEntries.length; i++) {
1380
+ var item = currentHistoryEntries[i];
1381
+ var entry = document.createElement("div");
1382
+ entry.className = "file-history-entry";
1383
+ if (item.source === "git") entry.classList.add("git-entry");
1384
+
1385
+ var selNum = isEntrySelected(item);
1386
+ if (selNum) {
1387
+ entry.classList.add("selected");
1388
+ entry.dataset.selectNum = selNum;
1389
+ }
1390
+
1391
+ // Header row
1392
+ var entryHeader = document.createElement("div");
1393
+ entryHeader.className = "file-history-entry-header";
1394
+
1395
+ var titleSpan = document.createElement("span");
1396
+ titleSpan.className = "file-history-title";
1397
+
1398
+ if (item.source === "git") {
1399
+ titleSpan.textContent = item.message || "No message";
1400
+ } else {
1401
+ // Use assistant's pre-edit reasoning as title (explains what Claude is doing)
1402
+ titleSpan.textContent = item.assistantSnippet || item.toolName + " " + (currentFilePath || "").split("/").pop();
1403
+ }
1404
+ entryHeader.appendChild(titleSpan);
1405
+
1406
+ var badge = document.createElement("span");
1407
+ badge.className = "file-history-badge";
1408
+ if (item.source === "git") {
1409
+ badge.classList.add("badge-commit");
1410
+ badge.textContent = "Git Commit";
1411
+ } else {
1412
+ badge.textContent = item.toolName === "Write" ? "Claude Write" : "Claude Edit";
1413
+ }
1414
+ entryHeader.appendChild(badge);
1415
+
1416
+ entry.appendChild(entryHeader);
1417
+
1418
+ // Subtitle: code-based summary for Edit entries
1419
+ if (item.source === "session" && item.toolName === "Edit" && (item.old_string || item.new_string)) {
1420
+ var codeSummary = editCodeSummary(item.old_string || "", item.new_string || "");
1421
+ if (codeSummary) {
1422
+ var subtitleEl = document.createElement("div");
1423
+ subtitleEl.className = "file-history-code-subtitle";
1424
+ subtitleEl.textContent = codeSummary;
1425
+ entry.appendChild(subtitleEl);
1426
+ }
1427
+ }
1428
+
1429
+ // Meta line
1430
+ if (item.source === "git") {
1431
+ var sub = document.createElement("div");
1432
+ sub.className = "file-history-meta";
1433
+ sub.textContent = item.hash.substring(0, 7) + " by " + (item.author || "unknown") + formatTimeAgo(item.timestamp);
1434
+ entry.appendChild(sub);
1435
+ } else {
1436
+ var sessionMeta = document.createElement("div");
1437
+ sessionMeta.className = "file-history-meta";
1438
+ var shortSession = (item.sessionTitle || "Untitled");
1439
+ if (shortSession.length > 20) shortSession = shortSession.substring(0, 20) + "...";
1440
+ sessionMeta.textContent = shortSession;
1441
+ entry.appendChild(sessionMeta);
1442
+ }
1443
+
1444
+ // Diff preview for session edits (inline unified)
1445
+ if (item.source === "session") {
1446
+ var diffContainer = document.createElement("div");
1447
+ diffContainer.className = "file-history-diff diff-compact";
1448
+
1449
+ if (item.toolName === "Edit" && (item.old_string || item.new_string)) {
1450
+ var unifiedEl = renderUnifiedDiff(item.old_string || "", item.new_string || "", currentLang());
1451
+ diffContainer.appendChild(unifiedEl);
1452
+ } else {
1453
+ var writeBadge = document.createElement("div");
1454
+ writeBadge.className = "file-history-write-badge";
1455
+ writeBadge.textContent = "Full file write";
1456
+ diffContainer.appendChild(writeBadge);
1457
+ }
1458
+ entry.appendChild(diffContainer);
1459
+ }
1460
+
1461
+ // Action buttons row
1462
+ var actions = document.createElement("div");
1463
+ actions.className = "file-history-actions";
1464
+
1465
+ // View diff / View file button (both git and session)
1466
+ (function (itemData) {
1467
+ var hasEditDiff = itemData.source === "session" && itemData.toolName === "Edit" && (itemData.old_string || itemData.new_string);
1468
+ var viewBtn = document.createElement("button");
1469
+ viewBtn.className = "file-history-action-btn";
1470
+ viewBtn.textContent = hasEditDiff ? "View diff" : "View file";
1471
+ viewBtn.addEventListener("click", function (e) {
1472
+ e.stopPropagation();
1473
+ viewEntryFile(itemData);
1474
+ });
1475
+ actions.appendChild(viewBtn);
1476
+
1477
+ // Navigate to conversation link (session only)
1478
+ if (itemData.source === "session" && itemData.assistantUuid && itemData.sessionLocalId) {
1479
+ var navBtn = document.createElement("button");
1480
+ navBtn.className = "file-history-action-btn file-history-nav-btn";
1481
+ navBtn.textContent = "Go to chat";
1482
+ navBtn.addEventListener("click", function (e) {
1483
+ e.stopPropagation();
1484
+ navigateToEdit(itemData);
1485
+ });
1486
+ actions.appendChild(navBtn);
1487
+ }
1488
+ })(item);
1489
+
1490
+ entry.appendChild(actions);
1491
+
1492
+ // Click handler: always toggle selection
1493
+ (function (itemData, entryEl) {
1494
+ entryEl.addEventListener("click", function () {
1495
+ toggleSelect(itemData);
1496
+ });
1497
+ })(item, entry);
1498
+
1499
+ list.appendChild(entry);
1500
+ }
1501
+
1502
+ panel.appendChild(list);
1503
+ bodyEl.appendChild(panel);
1504
+ refreshIcons();
1505
+ }
1506
+
1507
+ function renderCompareView() {
1508
+ var bodyEl = document.getElementById("file-viewer-body");
1509
+ bodyEl.innerHTML = "";
1510
+ ctx.fileViewerEl.classList.add("file-viewer-wide");
1511
+
1512
+ var wrapper = document.createElement("div");
1513
+ wrapper.className = "file-history-compare-view";
1514
+
1515
+ // Back button
1516
+ var backBar = document.createElement("div");
1517
+ backBar.className = "file-history-compare-bar";
1518
+
1519
+ var backBtn = document.createElement("button");
1520
+ backBtn.className = "file-history-compare-back";
1521
+ backBtn.textContent = "Back to timeline";
1522
+ backBtn.addEventListener("click", function () {
1523
+ compareMode = false;
1524
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
1525
+ renderHistoryPanel();
1526
+ });
1527
+ backBar.appendChild(backBtn);
1528
+ wrapper.appendChild(backBar);
1529
+
1530
+ var a = selectedEntries[0];
1531
+ var b = selectedEntries[1];
1532
+
1533
+ // Loading state while fetching
1534
+ var loadingEl = document.createElement("div");
1535
+ loadingEl.className = "file-history-write-badge";
1536
+ loadingEl.textContent = "Loading...";
1537
+ wrapper.appendChild(loadingEl);
1538
+ bodyEl.appendChild(wrapper);
1539
+
1540
+ // A = "before" state of entry A, B = "after" state of entry B
1541
+ resolveEntryContentBefore(a, function (contentA) {
1542
+ resolveEntryContent(b, function (contentB) {
1543
+ loadingEl.remove();
1544
+ renderCompareDiff(wrapper, a, contentA, b, contentB);
1545
+ });
1546
+ });
1547
+ }
1548
+
1549
+ function resolveEntryContent(entry, cb) {
1550
+ if (entry.source === "git") {
1551
+ if (fileAtCache[entry.hash] !== undefined) {
1552
+ cb(fileAtCache[entry.hash]);
1553
+ return;
1554
+ }
1555
+ pendingFileAt = function () {
1556
+ cb(fileAtCache[entry.hash] || "");
1557
+ };
1558
+ requestFileAt(entry.hash);
1559
+ return;
1560
+ }
1561
+ // Session edit: reconstruct full file with the edit applied
1562
+ if (entry.toolName === "Edit" && entry.new_string != null && currentContent) {
1563
+ var pos = currentContent.indexOf(entry.new_string);
1564
+ if (pos >= 0 && entry.old_string != null) {
1565
+ // Return full file with new_string in place (current state contains it)
1566
+ cb(currentContent);
1567
+ } else {
1568
+ cb(currentContent || "");
1569
+ }
1570
+ return;
1571
+ }
1572
+ // Write or fallback: use current file content (best approximation)
1573
+ cb(currentContent || "");
1574
+ }
1575
+
1576
+ // Reconstruct the full file as it was BEFORE this edit was applied
1577
+ function resolveEntryContentBefore(entry, cb) {
1578
+ if (entry.source === "git") {
1579
+ // For git, get the parent commit's version
1580
+ resolveEntryContent(entry, cb);
1581
+ return;
1582
+ }
1583
+ if (entry.toolName === "Edit" && entry.new_string != null && entry.old_string != null && currentContent) {
1584
+ var pos = currentContent.indexOf(entry.new_string);
1585
+ if (pos >= 0) {
1586
+ cb(currentContent.substring(0, pos) + entry.old_string + currentContent.substring(pos + entry.new_string.length));
1587
+ return;
1588
+ }
1589
+ }
1590
+ cb(currentContent || "");
1591
+ }
1592
+
1593
+ function renderCompareDiff(container, a, contentA, b, contentB) {
1594
+ var viewMode = "split";
1595
+
1596
+ function render() {
1597
+ // Remove previous diff content (keep back bar)
1598
+ var old = container.querySelector(".file-history-compare-content");
1599
+ if (old) old.remove();
1600
+
1601
+ var content = document.createElement("div");
1602
+ content.className = "file-history-compare-content";
1603
+
1604
+ // Label bar with toggle
1605
+ var labelBar = document.createElement("div");
1606
+ labelBar.className = "file-history-view-bar";
1607
+
1608
+ var labelText = document.createElement("span");
1609
+ labelText.className = "file-history-split-label";
1610
+ labelText.style.flex = "1";
1611
+ labelText.textContent = describeEntry(a) + " vs " + describeEntry(b);
1612
+ labelBar.appendChild(labelText);
1613
+
1614
+ var toggleWrap = document.createElement("div");
1615
+ toggleWrap.className = "file-history-view-toggle";
1616
+
1617
+ var splitBtn = document.createElement("button");
1618
+ splitBtn.className = "file-history-toggle-btn" + (viewMode === "split" ? " active" : "");
1619
+ splitBtn.textContent = "Split";
1620
+ splitBtn.addEventListener("click", function () {
1621
+ viewMode = "split";
1622
+ render();
1623
+ });
1624
+
1625
+ var unifiedBtn = document.createElement("button");
1626
+ unifiedBtn.className = "file-history-toggle-btn" + (viewMode === "unified" ? " active" : "");
1627
+ unifiedBtn.textContent = "Unified";
1628
+ unifiedBtn.addEventListener("click", function () {
1629
+ viewMode = "unified";
1630
+ render();
1631
+ });
1632
+
1633
+ var sourceBtn = document.createElement("button");
1634
+ sourceBtn.className = "file-history-toggle-btn" + (viewMode === "source" ? " active" : "");
1635
+ sourceBtn.textContent = "Source";
1636
+ sourceBtn.addEventListener("click", function () {
1637
+ viewMode = "source";
1638
+ render();
1639
+ });
1640
+
1641
+ toggleWrap.appendChild(splitBtn);
1642
+ toggleWrap.appendChild(unifiedBtn);
1643
+ toggleWrap.appendChild(sourceBtn);
1644
+ labelBar.appendChild(toggleWrap);
1645
+ content.appendChild(labelBar);
1646
+
1647
+ var diffLang = currentLang();
1648
+
1649
+ if (viewMode === "source") {
1650
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
1651
+ var sourceWrap = document.createElement("div");
1652
+ sourceWrap.className = "file-history-diff-full";
1653
+ var ext = currentFilePath ? currentFilePath.split(".").pop().toLowerCase() : "";
1654
+ var lang = mapExtToLanguage(ext);
1655
+ var pre = document.createElement("pre");
1656
+ pre.className = "file-viewer-code-content";
1657
+ var codeEl = document.createElement("code");
1658
+ if (lang) codeEl.className = "language-" + lang;
1659
+ codeEl.textContent = contentB;
1660
+ pre.appendChild(codeEl);
1661
+ sourceWrap.appendChild(pre);
1662
+ content.appendChild(sourceWrap);
1663
+ container.appendChild(content);
1664
+ if (typeof hljs !== "undefined" && lang) {
1665
+ hljs.highlightElement(codeEl);
1666
+ }
1667
+ } else {
1668
+ ctx.fileViewerEl.classList.add("file-viewer-wide");
1669
+
1670
+ // Diff content
1671
+ var diffWrap = document.createElement("div");
1672
+ diffWrap.className = "file-history-diff-full";
1673
+
1674
+ if (viewMode === "split") {
1675
+ diffWrap.appendChild(renderSplitDiff(contentA, contentB, diffLang));
1676
+ } else {
1677
+ diffWrap.appendChild(renderUnifiedDiff(contentA, contentB, diffLang));
1678
+ }
1679
+
1680
+ content.appendChild(diffWrap);
1681
+ container.appendChild(content);
1682
+
1683
+ // Scroll to first change
1684
+ requestAnimationFrame(function () {
1685
+ var firstChange = diffWrap.querySelector(".diff-row-change, .diff-row-add, .diff-row-remove");
1686
+ if (firstChange) {
1687
+ firstChange.scrollIntoView({ behavior: "smooth", block: "center" });
1688
+ }
1689
+ });
1690
+ }
1691
+ }
1692
+
1693
+ render();
1694
+ }
1695
+
1696
+ function editCodeSummary(oldStr, newStr) {
1697
+ // Find the first meaningful added or changed line to use as a subtitle
1698
+ var oldLines = oldStr ? oldStr.split("\n") : [];
1699
+ var newLines = newStr ? newStr.split("\n") : [];
1700
+ var oldSet = {};
1701
+ for (var i = 0; i < oldLines.length; i++) {
1702
+ var trimmed = oldLines[i].trim();
1703
+ if (trimmed) oldSet[trimmed] = true;
1704
+ }
1705
+ // Find first new line not in old
1706
+ for (var j = 0; j < newLines.length; j++) {
1707
+ var line = newLines[j].trim();
1708
+ if (line && !oldSet[line] && line.length > 2) {
1709
+ if (line.length > 80) line = line.substring(0, 80) + "...";
1710
+ return "+ " + line;
1711
+ }
1712
+ }
1713
+ // Fallback: find first removed line
1714
+ var newSet = {};
1715
+ for (var k = 0; k < newLines.length; k++) {
1716
+ var t = newLines[k].trim();
1717
+ if (t) newSet[t] = true;
1718
+ }
1719
+ for (var l = 0; l < oldLines.length; l++) {
1720
+ var oLine = oldLines[l].trim();
1721
+ if (oLine && !newSet[oLine] && oLine.length > 2) {
1722
+ if (oLine.length > 80) oLine = oLine.substring(0, 80) + "...";
1723
+ return "- " + oLine;
1724
+ }
1725
+ }
1726
+ return null;
1727
+ }
1728
+
1729
+ function describeEntry(entry) {
1730
+ if (entry.source === "git") return entry.hash.substring(0, 7) + " " + (entry.message || "").substring(0, 40);
1731
+ return (entry.sessionTitle || "Untitled") + " (" + (entry.toolName || "Edit") + ")";
1732
+ }
1733
+
1734
+ function shortEntryLabel(entry) {
1735
+ if (entry.source === "git") {
1736
+ var msg = (entry.message || "").substring(0, 24);
1737
+ if ((entry.message || "").length > 24) msg += "...";
1738
+ return entry.hash.substring(0, 7) + " " + msg;
1739
+ }
1740
+ return (entry.assistantSnippet || entry.toolName || "Edit").substring(0, 30);
1741
+ }
1742
+
1743
+ function formatTimeAgo(ts) {
1744
+ if (!ts) return "";
1745
+ var diff = Date.now() - ts;
1746
+ if (diff < 60000) return ", just now";
1747
+ if (diff < 3600000) return ", " + Math.floor(diff / 60000) + "m ago";
1748
+ if (diff < 86400000) return ", " + Math.floor(diff / 3600000) + "h ago";
1749
+ var d = new Date(ts);
1750
+ return ", " + d.toLocaleDateString();
1751
+ }
1752
+
1753
+
1754
+ function viewEntryFile(entry) {
1755
+ var viewerEl = ctx.fileViewerEl;
1756
+ var bodyEl = document.getElementById("file-viewer-body");
1757
+ bodyEl.innerHTML = '<div class="file-history-write-badge">Loading...</div>';
1758
+
1759
+ // Widen the viewer for diff
1760
+ viewerEl.classList.add("file-viewer-wide");
1761
+
1762
+ // For session edits with old/new, show diff. For git or Write, show file content.
1763
+ var hasEditDiff = entry.source === "session" && entry.toolName === "Edit" && (entry.old_string || entry.new_string);
1764
+
1765
+ if (hasEditDiff) {
1766
+ renderViewFileDiff(entry);
1767
+ } else {
1768
+ resolveEntryContent(entry, function (content) {
1769
+ renderViewFileContent(entry, content);
1770
+ });
1771
+ }
1772
+ }
1773
+
1774
+ function renderViewFileDiff(entry) {
1775
+ var bodyEl = document.getElementById("file-viewer-body");
1776
+
1777
+ // Reconstruct full before/after files
1778
+ var oldStr = entry.old_string || "";
1779
+ var newStr = entry.new_string || "";
1780
+ var fileAfter = currentContent || "";
1781
+ var fileBefore = fileAfter;
1782
+ if (newStr) {
1783
+ var pos = fileAfter.indexOf(newStr);
1784
+ if (pos >= 0) {
1785
+ fileBefore = fileAfter.substring(0, pos) + oldStr + fileAfter.substring(pos + newStr.length);
1786
+ }
1787
+ }
1788
+
1789
+ var diffLang = currentLang();
1790
+ var viewMode = "split";
1791
+
1792
+ function render() {
1793
+ bodyEl.innerHTML = "";
1794
+
1795
+ // Top bar: back + toggle
1796
+ var topBar = document.createElement("div");
1797
+ topBar.className = "file-history-view-bar";
1798
+
1799
+ var backBtn = document.createElement("button");
1800
+ backBtn.className = "file-history-compare-back";
1801
+ backBtn.textContent = "Back to timeline";
1802
+ backBtn.addEventListener("click", function () {
1803
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
1804
+ renderHistoryPanel();
1805
+ });
1806
+ topBar.appendChild(backBtn);
1807
+
1808
+ var toggleWrap = document.createElement("div");
1809
+ toggleWrap.className = "file-history-view-toggle";
1810
+
1811
+ var splitBtn = document.createElement("button");
1812
+ splitBtn.className = "file-history-toggle-btn" + (viewMode === "split" ? " active" : "");
1813
+ splitBtn.textContent = "Split";
1814
+ splitBtn.addEventListener("click", function () {
1815
+ viewMode = "split";
1816
+ render();
1817
+ });
1818
+
1819
+ var unifiedBtn = document.createElement("button");
1820
+ unifiedBtn.className = "file-history-toggle-btn" + (viewMode === "unified" ? " active" : "");
1821
+ unifiedBtn.textContent = "Unified";
1822
+ unifiedBtn.addEventListener("click", function () {
1823
+ viewMode = "unified";
1824
+ render();
1825
+ });
1826
+
1827
+ var sourceBtn = document.createElement("button");
1828
+ sourceBtn.className = "file-history-toggle-btn" + (viewMode === "source" ? " active" : "");
1829
+ sourceBtn.textContent = "Source";
1830
+ sourceBtn.addEventListener("click", function () {
1831
+ viewMode = "source";
1832
+ render();
1833
+ });
1834
+
1835
+ toggleWrap.appendChild(splitBtn);
1836
+ toggleWrap.appendChild(unifiedBtn);
1837
+ toggleWrap.appendChild(sourceBtn);
1838
+ topBar.appendChild(toggleWrap);
1839
+ bodyEl.appendChild(topBar);
1840
+
1841
+ // Label
1842
+ var label = document.createElement("div");
1843
+ label.className = "file-history-split-label";
1844
+ label.textContent = describeEntry(entry);
1845
+ bodyEl.appendChild(label);
1846
+
1847
+ if (viewMode === "source") {
1848
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
1849
+ var sourceWrap = document.createElement("div");
1850
+ sourceWrap.className = "file-history-diff-full";
1851
+ var ext = currentFilePath ? currentFilePath.split(".").pop().toLowerCase() : "";
1852
+ var lang = mapExtToLanguage(ext);
1853
+ var pre = document.createElement("pre");
1854
+ pre.className = "file-viewer-code-content";
1855
+ var codeEl = document.createElement("code");
1856
+ if (lang) codeEl.className = "language-" + lang;
1857
+ codeEl.textContent = fileAfter;
1858
+ pre.appendChild(codeEl);
1859
+ sourceWrap.appendChild(pre);
1860
+ bodyEl.appendChild(sourceWrap);
1861
+ if (typeof hljs !== "undefined" && lang) {
1862
+ hljs.highlightElement(codeEl);
1863
+ }
1864
+ } else {
1865
+ ctx.fileViewerEl.classList.add("file-viewer-wide");
1866
+
1867
+ var diffWrap = document.createElement("div");
1868
+ diffWrap.className = "file-history-diff-full";
1869
+
1870
+ if (viewMode === "split") {
1871
+ diffWrap.appendChild(renderSplitDiff(fileBefore, fileAfter, diffLang));
1872
+ } else {
1873
+ diffWrap.appendChild(renderUnifiedDiff(fileBefore, fileAfter, diffLang));
1874
+ }
1875
+
1876
+ bodyEl.appendChild(diffWrap);
1877
+
1878
+ // Scroll to first change
1879
+ requestAnimationFrame(function () {
1880
+ var firstChange = diffWrap.querySelector(".diff-row-change, .diff-row-add, .diff-row-remove");
1881
+ if (firstChange) {
1882
+ firstChange.scrollIntoView({ behavior: "smooth", block: "center" });
1883
+ }
1884
+ });
1885
+ }
1886
+ }
1887
+
1888
+ render();
1889
+ }
1890
+
1891
+ function renderViewFileContent(entry, content) {
1892
+ var bodyEl = document.getElementById("file-viewer-body");
1893
+ bodyEl.innerHTML = "";
1894
+
1895
+ // Back bar
1896
+ var topBar = document.createElement("div");
1897
+ topBar.className = "file-history-view-bar";
1898
+ var backBtn = document.createElement("button");
1899
+ backBtn.className = "file-history-compare-back";
1900
+ backBtn.textContent = "Back to timeline";
1901
+ backBtn.addEventListener("click", function () {
1902
+ ctx.fileViewerEl.classList.remove("file-viewer-wide");
1903
+ renderHistoryPanel();
1904
+ });
1905
+ topBar.appendChild(backBtn);
1906
+ bodyEl.appendChild(topBar);
1907
+
1908
+ // Label
1909
+ var label = document.createElement("div");
1910
+ label.className = "file-history-split-label";
1911
+ label.textContent = describeEntry(entry);
1912
+ bodyEl.appendChild(label);
1913
+
1914
+ // Code with line numbers
1915
+ var codeContainer = document.createElement("div");
1916
+ codeContainer.className = "file-history-split-code";
1917
+ codeContainer.style.flex = "1";
1918
+ codeContainer.style.overflow = "hidden";
1919
+ var ext = (currentFilePath || "").split(".").pop().toLowerCase();
1920
+ renderCodeWithLineNumbers(codeContainer, content, ext);
1921
+ bodyEl.appendChild(codeContainer);
1922
+ }
1923
+
1924
+ function navigateToEdit(edit) {
1925
+ // If already in the same session, scroll directly without replaying history
1926
+ if (ctx.activeSessionId === edit.sessionLocalId) {
1927
+ scrollToToolElement(edit.toolId, edit.assistantUuid);
1928
+ if (window.innerWidth <= 768) closeFileViewer();
1929
+ return;
1930
+ }
1931
+
1932
+ pendingNavigate = {
1933
+ sessionLocalId: edit.sessionLocalId,
1934
+ assistantUuid: edit.assistantUuid,
1935
+ toolId: edit.toolId,
1936
+ };
1937
+
1938
+ if (ctx.ws && ctx.connected) {
1939
+ ctx.ws.send(JSON.stringify({ type: "switch_session", id: edit.sessionLocalId }));
1940
+ }
1941
+
1942
+ // Close file viewer on mobile
1943
+ if (window.innerWidth <= 768) {
1944
+ closeFileViewer();
1945
+ }
1946
+ }
1947
+
1948
+ function scrollToToolElement(toolId, assistantUuid) {
1949
+ requestAnimationFrame(function () {
1950
+ var target = toolId ? ctx.messagesEl.querySelector('[data-tool-id="' + toolId + '"]') : null;
1951
+ if (!target && assistantUuid) {
1952
+ target = ctx.messagesEl.querySelector('[data-uuid="' + assistantUuid + '"]');
1953
+ }
1954
+ if (target) {
1955
+ target.scrollIntoView({ behavior: "smooth", block: "center" });
1956
+ target.classList.add("message-blink");
1957
+ setTimeout(function () { target.classList.remove("message-blink"); }, 2000);
1958
+ }
1959
+ });
1960
+ }
1961
+
1962
+ export function getPendingNavigate() {
1963
+ var nav = pendingNavigate;
1964
+ pendingNavigate = null;
1965
+ return nav;
1966
+ }