@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,1548 @@
1
+ // sidebar-sessions.js - Session list, search, presence, countdown, CLI picker
2
+ // Extracted from sidebar.js (PR-35)
3
+
4
+ import { avatarUrl, userAvatarUrl } from './avatar.js';
5
+ import { escapeHtml } from './utils.js';
6
+ import { iconHtml, refreshIcons } from './icons.js';
7
+ import { openSearch as openSessionSearch } from './session-search.js';
8
+ import { store } from './store.js';
9
+ import { getWs } from './ws-ref.js';
10
+ import { getSessionListEl } from './dom-refs.js';
11
+ import { dismissOverlayPanels, closeSidebar, updatePageTitle, spawnDustParticles } from './sidebar.js';
12
+ import { showConfirm } from './app-misc.js';
13
+ import { getUpcomingSchedules } from './scheduler.js';
14
+ import { refreshMobileChatSheet } from './sidebar-mobile.js';
15
+ import { openAgentPicker, openAgentPickerForPreferred } from './agent-picker.js';
16
+ import { getCachedProjects } from './app-projects.js';
17
+
18
+
19
+ // --- Session state ---
20
+ var cachedSessions = [];
21
+ var searchQuery = "";
22
+ var searchMatchIds = null; // null = no search, Set of matched session IDs
23
+ var searchDebounce = null;
24
+ var expandedLoopGroups = new Set();
25
+ var expandedLoopRuns = new Set();
26
+
27
+ // Fingerprint of the last rendered session list. When the server sends a
28
+ // session_list that hashes identically to the previous render, skip the
29
+ // full innerHTML teardown + rebuild. Fields that affect rendering:
30
+ // id, title, active, isProcessing, bookmarked, lastActivity, loop (id+role),
31
+ // sessionVisibility, agentName. Presence avatars are updated separately by
32
+ // updateSessionPresence() and don't need a full rebuild.
33
+ var _sessionListFingerprint = "";
34
+
35
+ // --- Session presence (multi-user: who is viewing which session) ---
36
+ var sessionPresence = {}; // { sessionId: [{ id, displayName, avatarStyle, avatarSeed }] }
37
+
38
+ // --- Countdown timer for upcoming schedules ---
39
+ var countdownTimer = null;
40
+ var countdownContainer = null;
41
+
42
+ // --- Session context menu ---
43
+ var sessionCtxMenu = null;
44
+ var sessionCtxSessionId = null;
45
+ var draggedSessionId = null;
46
+ var draggedSessionBookmarked = false;
47
+ var openResumePickerModal = function () {};
48
+ var headerSearchOpen = false;
49
+ var armedDeleteSessionId = null;
50
+ var armedDeleteTimer = null;
51
+
52
+ export function openResumePicker() {
53
+ openResumePickerModal();
54
+ }
55
+
56
+ function sendSessionBookmark(sessionId, bookmarked) {
57
+ if (getWs() && store.get('connected')) {
58
+ getWs().send(JSON.stringify({ type: "set_session_bookmark", sessionId: sessionId, bookmarked: !!bookmarked }));
59
+ }
60
+ }
61
+
62
+ function compareSessionListItems(a, b) {
63
+ var aData = a && a.type === "session" ? a.data : a;
64
+ var bData = b && b.type === "session" ? b.data : b;
65
+ var aBookmarked = !!(aData && aData.bookmarked);
66
+ var bBookmarked = !!(bData && bData.bookmarked);
67
+ if (aBookmarked !== bBookmarked) return aBookmarked ? -1 : 1;
68
+ if (aBookmarked && bBookmarked) {
69
+ var ao = aData && typeof aData.favoriteOrder === "number" ? aData.favoriteOrder : Number.MAX_SAFE_INTEGER;
70
+ var bo = bData && typeof bData.favoriteOrder === "number" ? bData.favoriteOrder : Number.MAX_SAFE_INTEGER;
71
+ if (ao !== bo) return ao - bo;
72
+ }
73
+ return (b.lastActivity || 0) - (a.lastActivity || 0);
74
+ }
75
+
76
+ function clearSessionDragIndicators() {
77
+ var listEl = getSessionListEl();
78
+ if (!listEl) return;
79
+ var active = listEl.querySelectorAll(".session-favorites-divider.drag-hover, .session-regular-drop.drag-hover, .session-item.dragging");
80
+ for (var i = 0; i < active.length; i++) {
81
+ active[i].classList.remove("drag-hover", "dragging");
82
+ }
83
+ }
84
+
85
+ function setupSessionDragHandlers(el, session) {
86
+ el.setAttribute("draggable", "true");
87
+
88
+ el.addEventListener("dragstart", function (e) {
89
+ draggedSessionId = session.id;
90
+ draggedSessionBookmarked = !!session.bookmarked;
91
+ e.dataTransfer.effectAllowed = "move";
92
+ e.dataTransfer.setData("text/plain", String(session.id));
93
+
94
+ var ghost = document.createElement("div");
95
+ ghost.textContent = session.title || "New Session";
96
+ ghost.style.cssText = "position:fixed;left:-200px;top:-200px;max-width:220px;padding:8px 12px;border-radius:10px;" +
97
+ "background:var(--sidebar-active);color:var(--text);font-size:13px;font-weight:600;pointer-events:none;z-index:-1;";
98
+ document.body.appendChild(ghost);
99
+ e.dataTransfer.setDragImage(ghost, 18, 18);
100
+ setTimeout(function () { ghost.remove(); }, 0);
101
+
102
+ setTimeout(function () { el.classList.add("dragging"); }, 0);
103
+ });
104
+
105
+ el.addEventListener("dragend", function () {
106
+ clearSessionDragIndicators();
107
+ draggedSessionId = null;
108
+ draggedSessionBookmarked = false;
109
+ });
110
+
111
+ if (session.bookmarked) {
112
+ el.addEventListener("dragover", function (e) {
113
+ if (!draggedSessionId || draggedSessionId === session.id) return;
114
+ e.preventDefault();
115
+ e.dataTransfer.dropEffect = "move";
116
+ var rect = el.getBoundingClientRect();
117
+ var insertBefore = e.clientY < rect.top + rect.height / 2;
118
+ el.classList.remove("drag-over-above", "drag-over-below");
119
+ el.classList.add(insertBefore ? "drag-over-above" : "drag-over-below");
120
+ });
121
+
122
+ el.addEventListener("dragleave", function () {
123
+ el.classList.remove("drag-over-above", "drag-over-below");
124
+ });
125
+
126
+ el.addEventListener("drop", function (e) {
127
+ if (!draggedSessionId || draggedSessionId === session.id) return;
128
+ e.preventDefault();
129
+ var rect = el.getBoundingClientRect();
130
+ var insertBefore = e.clientY < rect.top + rect.height / 2;
131
+ el.classList.remove("drag-over-above", "drag-over-below");
132
+ if (draggedSessionBookmarked) {
133
+ if (getWs() && store.get('connected')) {
134
+ getWs().send(JSON.stringify({
135
+ type: "reorder_session_bookmarks",
136
+ sourceId: draggedSessionId,
137
+ targetId: session.id,
138
+ insertBefore: insertBefore,
139
+ }));
140
+ }
141
+ } else {
142
+ sendSessionBookmark(draggedSessionId, true);
143
+ }
144
+ });
145
+ }
146
+ }
147
+
148
+ function setupBookmarkDropTarget(el, bookmarked) {
149
+ el.addEventListener("dragover", function (e) {
150
+ if (!draggedSessionId) return;
151
+ e.preventDefault();
152
+ e.dataTransfer.dropEffect = "move";
153
+ el.classList.add("drag-hover");
154
+ });
155
+
156
+ el.addEventListener("dragleave", function () {
157
+ el.classList.remove("drag-hover");
158
+ });
159
+
160
+ el.addEventListener("drop", function (e) {
161
+ if (!draggedSessionId) return;
162
+ e.preventDefault();
163
+ el.classList.remove("drag-hover");
164
+ if (draggedSessionBookmarked !== !!bookmarked) {
165
+ sendSessionBookmark(draggedSessionId, !!bookmarked);
166
+ }
167
+ clearSessionDragIndicators();
168
+ draggedSessionId = null;
169
+ draggedSessionBookmarked = false;
170
+ });
171
+ }
172
+
173
+ function spawnSessionDeleteParticles(sessionId) {
174
+ if (!spawnDustParticles) return;
175
+ setTimeout(function () {
176
+ var el = getSessionListEl().querySelector('[data-session-id="' + sessionId + '"]');
177
+ if (!el) return;
178
+ var rect = el.getBoundingClientRect();
179
+ spawnDustParticles(rect.left + rect.width / 2, rect.top + rect.height / 2);
180
+ }, 0);
181
+ }
182
+
183
+ function confirmDeleteSession(session) {
184
+ showConfirm('Delete "' + (session.title || "New Session") + '"? This session and its history will be permanently removed.', function () {
185
+ var ws = getWs();
186
+ if (ws && store.get('connected')) {
187
+ ws.send(JSON.stringify({ type: "delete_session", id: session.id }));
188
+ spawnSessionDeleteParticles(session.id);
189
+ }
190
+ });
191
+ }
192
+
193
+ function clearArmedSessionDelete() {
194
+ if (armedDeleteTimer) {
195
+ clearTimeout(armedDeleteTimer);
196
+ armedDeleteTimer = null;
197
+ }
198
+ if (armedDeleteSessionId !== null) {
199
+ var prevBtn = getSessionListEl() ? getSessionListEl().querySelector('.session-close-btn[data-session-id="' + armedDeleteSessionId + '"]') : null;
200
+ if (prevBtn) {
201
+ prevBtn.classList.remove("armed");
202
+ prevBtn.innerHTML = iconHtml("x");
203
+ prevBtn.title = "Delete session";
204
+ prevBtn.setAttribute("aria-label", "Delete session");
205
+ refreshIcons();
206
+ }
207
+ }
208
+ armedDeleteSessionId = null;
209
+ }
210
+
211
+ function armSessionDelete(closeBtn, session) {
212
+ clearArmedSessionDelete();
213
+ armedDeleteSessionId = session.id;
214
+ closeBtn.classList.add("armed");
215
+ closeBtn.innerHTML = iconHtml("check");
216
+ closeBtn.title = "Click again to delete";
217
+ closeBtn.setAttribute("aria-label", "Click again to delete");
218
+ refreshIcons();
219
+ armedDeleteTimer = setTimeout(function () {
220
+ clearArmedSessionDelete();
221
+ }, 1800);
222
+ }
223
+
224
+ function deleteSessionImmediately(session) {
225
+ var ws = getWs();
226
+ if (ws && store.get('connected')) {
227
+ ws.send(JSON.stringify({ type: "delete_session", id: session.id }));
228
+ spawnSessionDeleteParticles(session.id);
229
+ }
230
+ }
231
+
232
+ function collectItemSessionIds(item) {
233
+ if (!item) return [];
234
+ if (item.type === "session" && item.data && typeof item.data.id === "number") {
235
+ if (!isSessionVisibleBySearch(item.data.id)) return [];
236
+ return [item.data.id];
237
+ }
238
+ if (item.type === "loop" && Array.isArray(item.children)) {
239
+ var ids = [];
240
+ for (var i = 0; i < item.children.length; i++) {
241
+ if (typeof item.children[i].id === "number" && isSessionVisibleBySearch(item.children[i].id)) {
242
+ ids.push(item.children[i].id);
243
+ }
244
+ }
245
+ return ids;
246
+ }
247
+ return [];
248
+ }
249
+
250
+ function confirmDeleteSessionGroup(groupLabel, sessionIds) {
251
+ if (!Array.isArray(sessionIds) || sessionIds.length === 0) return;
252
+ var count = sessionIds.length;
253
+ var noun = count === 1 ? "session" : "sessions";
254
+ showConfirm('Clear "' + groupLabel + '"? ' + count + " " + noun + ' will be permanently removed.', function () {
255
+ var ws = getWs();
256
+ if (ws && store.get('connected')) {
257
+ ws.send(JSON.stringify({ type: "bulk_delete_sessions", sessionIds: sessionIds }));
258
+ }
259
+ });
260
+ }
261
+
262
+ function createSessionGroupHeader(group, sessionIds) {
263
+ var header = document.createElement("div");
264
+ header.className = "session-group-header";
265
+
266
+ var label = document.createElement("span");
267
+ label.className = "session-group-header-label";
268
+ label.textContent = group;
269
+ header.appendChild(label);
270
+
271
+ if ((!store.get('permissions') || store.get('permissions').sessionDelete !== false) && Array.isArray(sessionIds) && sessionIds.length > 0) {
272
+ var clearBtn = document.createElement("button");
273
+ clearBtn.className = "session-group-clear-btn";
274
+ clearBtn.type = "button";
275
+ clearBtn.textContent = "Clear";
276
+ clearBtn.addEventListener("click", function (e) {
277
+ e.preventDefault();
278
+ e.stopPropagation();
279
+ confirmDeleteSessionGroup(group, sessionIds);
280
+ });
281
+ header.appendChild(clearBtn);
282
+ }
283
+
284
+ return header;
285
+ }
286
+
287
+ function appendSessionCloseButton(el, session) {
288
+ if (store.get('permissions') && store.get('permissions').sessionDelete === false) return;
289
+
290
+ var closeBtn = document.createElement("button");
291
+ closeBtn.className = "session-close-btn";
292
+ closeBtn.dataset.sessionId = session.id;
293
+ closeBtn.type = "button";
294
+ closeBtn.title = "Delete session";
295
+ closeBtn.setAttribute("aria-label", "Delete session");
296
+ closeBtn.innerHTML = iconHtml("x");
297
+ closeBtn.addEventListener("click", function (e) {
298
+ e.preventDefault();
299
+ e.stopPropagation();
300
+ if (armedDeleteSessionId === session.id) {
301
+ clearArmedSessionDelete();
302
+ deleteSessionImmediately(session);
303
+ return;
304
+ }
305
+ armSessionDelete(closeBtn, session);
306
+ });
307
+ el.appendChild(closeBtn);
308
+ }
309
+
310
+ function renderSessionTopActions() {
311
+ var wrap = document.createElement("div");
312
+ wrap.className = "session-top-actions";
313
+
314
+ var isDm = store.get('dmMode');
315
+
316
+ // Resolve preferred agent for the current project
317
+ var currentSlug = store.get('currentSlug');
318
+ var preferredAgent = null;
319
+ if (currentSlug && !isDm) {
320
+ var projects = getCachedProjects();
321
+ for (var pi = 0; pi < projects.length; pi++) {
322
+ if (projects[pi].slug === currentSlug) {
323
+ preferredAgent = projects[pi].preferredAgent || null;
324
+ break;
325
+ }
326
+ }
327
+ }
328
+
329
+ // Row 1: two equal primary actions — New Session + Agent Chat
330
+ var newBtn = document.createElement("button");
331
+ newBtn.className = "session-top-action";
332
+ newBtn.type = "button";
333
+ newBtn.innerHTML = iconHtml("plus") + '<span>New Session</span>';
334
+ newBtn.addEventListener("click", function () {
335
+ if (getWs() && store.get('connected')) {
336
+ getWs().send(JSON.stringify({ type: "new_session" }));
337
+ }
338
+ });
339
+ wrap.appendChild(newBtn);
340
+
341
+ // Agent Chat (full picker) — hidden in dmMode
342
+ if (!isDm) {
343
+ var agentBtn = document.createElement("button");
344
+ agentBtn.className = "session-top-action";
345
+ agentBtn.type = "button";
346
+ agentBtn.innerHTML = iconHtml("message-circle-plus") + '<span>Agent Chat</span>';
347
+ agentBtn.addEventListener("click", function () {
348
+ openAgentPicker();
349
+ });
350
+ wrap.appendChild(agentBtn);
351
+ }
352
+
353
+ // Row 2 (optional): preferred agent quick-launch — full width, only when set.
354
+ // Shows nothing when no preferred agent is configured (no placeholder clutter).
355
+ if (!isDm && preferredAgent) {
356
+ var favBtn = document.createElement("button");
357
+ favBtn.type = "button";
358
+ favBtn.className = "session-top-action session-top-action--preferred";
359
+ favBtn.innerHTML = iconHtml("bot") + '<span>' + escapeHtml(preferredAgent.name) + '</span>';
360
+ favBtn.title = 'Start chat with ' + preferredAgent.name;
361
+ favBtn.addEventListener("click", function () {
362
+ var ws = getWs();
363
+ if (ws && store.get('connected')) {
364
+ ws.send(JSON.stringify({
365
+ type: "new_session",
366
+ agentName: preferredAgent.name,
367
+ agentKind: preferredAgent.kind,
368
+ agentPluginName: preferredAgent.pluginName || null,
369
+ }));
370
+ }
371
+ });
372
+ wrap.appendChild(favBtn);
373
+ }
374
+
375
+ return wrap;
376
+ }
377
+
378
+ function runSessionSearch(query) {
379
+ var normalizedQuery = query || "";
380
+ var trimmedQuery = normalizedQuery.trim();
381
+ searchQuery = normalizedQuery;
382
+ if (searchDebounce) {
383
+ clearTimeout(searchDebounce);
384
+ searchDebounce = null;
385
+ }
386
+ if (!trimmedQuery) {
387
+ searchMatchIds = null;
388
+ renderSessionList(null);
389
+ return;
390
+ }
391
+ searchDebounce = setTimeout(function () {
392
+ if (getWs() && store.get('connected')) {
393
+ getWs().send(JSON.stringify({ type: "search_sessions", query: searchQuery }));
394
+ }
395
+ }, 200);
396
+ }
397
+
398
+ function syncHeaderSearchUi() {
399
+ var searchInline = document.getElementById("session-header-search-inline");
400
+ var searchInput = document.getElementById("session-header-search-input");
401
+ var searchClear = document.getElementById("session-header-search-clear");
402
+ var searchBtn = document.getElementById("session-header-search-btn");
403
+ var filterCount = document.getElementById("session-filter-count");
404
+ var isOpen = headerSearchOpen || !!searchQuery;
405
+ if (!searchInline || !searchInput || !searchClear || !searchBtn || !filterCount) return;
406
+ searchInline.classList.toggle("hidden", !isOpen);
407
+ searchBtn.classList.toggle("active", isOpen);
408
+ if (searchInput.value !== searchQuery) {
409
+ searchInput.value = searchQuery;
410
+ }
411
+ searchClear.classList.toggle("hidden", !searchQuery);
412
+ if (!searchQuery || searchMatchIds === null) {
413
+ filterCount.classList.add("hidden");
414
+ filterCount.textContent = "";
415
+ } else {
416
+ filterCount.classList.remove("hidden");
417
+ filterCount.textContent = String(searchMatchIds.size);
418
+ }
419
+ }
420
+
421
+ function openHeaderSearch() {
422
+ headerSearchOpen = true;
423
+ syncHeaderSearchUi();
424
+ var searchInput = document.getElementById("session-header-search-input");
425
+ if (searchInput) {
426
+ requestAnimationFrame(function () {
427
+ searchInput.focus();
428
+ searchInput.select();
429
+ });
430
+ }
431
+ }
432
+
433
+ function closeHeaderSearch() {
434
+ headerSearchOpen = false;
435
+ syncHeaderSearchUi();
436
+ }
437
+
438
+ function clearSessionSearch(shouldBlur, input, shouldClose) {
439
+ if (searchDebounce) {
440
+ clearTimeout(searchDebounce);
441
+ searchDebounce = null;
442
+ }
443
+ searchQuery = "";
444
+ searchMatchIds = null;
445
+ if (shouldClose) {
446
+ headerSearchOpen = false;
447
+ }
448
+ syncHeaderSearchUi();
449
+ renderSessionList(null);
450
+ if (shouldBlur && input) {
451
+ input.blur();
452
+ }
453
+ }
454
+
455
+ export function initSidebarSessions() {
456
+
457
+ document.addEventListener("click", function () {
458
+ closeSessionCtxMenu();
459
+ clearArmedSessionDelete();
460
+ });
461
+
462
+ var searchBtn = document.getElementById("session-header-search-btn");
463
+ var searchInput = document.getElementById("session-header-search-input");
464
+ var searchClear = document.getElementById("session-header-search-clear");
465
+ var searchInline = document.getElementById("session-header-search-inline");
466
+
467
+ if (searchBtn && searchInput && searchClear && searchInline) {
468
+ searchBtn.addEventListener("click", function () {
469
+ if (!headerSearchOpen && !searchQuery) {
470
+ openHeaderSearch();
471
+ return;
472
+ }
473
+ if (!searchQuery) {
474
+ closeHeaderSearch();
475
+ return;
476
+ }
477
+ searchInput.focus();
478
+ searchInput.select();
479
+ });
480
+
481
+ searchInput.addEventListener("input", function () {
482
+ runSessionSearch(searchInput.value);
483
+ syncHeaderSearchUi();
484
+ });
485
+
486
+ searchInput.addEventListener("keydown", function (e) {
487
+ if (e.key === "Escape") {
488
+ e.preventDefault();
489
+ if (searchInput.value.trim()) {
490
+ clearSessionSearch(false, searchInput, false);
491
+ return;
492
+ }
493
+ clearSessionSearch(true, searchInput, true);
494
+ }
495
+ });
496
+
497
+ searchInput.addEventListener("blur", function () {
498
+ setTimeout(function () {
499
+ if (!searchQuery && document.activeElement !== searchBtn && document.activeElement !== searchClear) {
500
+ closeHeaderSearch();
501
+ }
502
+ }, 0);
503
+ });
504
+
505
+ searchClear.addEventListener("click", function () {
506
+ clearSessionSearch(false, searchInput, false);
507
+ searchInput.focus();
508
+ });
509
+
510
+ syncHeaderSearchUi();
511
+ }
512
+
513
+ // --- Resume session picker ---
514
+ var resumeModal = document.getElementById("resume-modal");
515
+ var resumeCancel = document.getElementById("resume-cancel");
516
+ var pickerLoading = document.getElementById("resume-picker-loading");
517
+ var pickerEmpty = document.getElementById("resume-picker-empty");
518
+ var pickerList = document.getElementById("resume-picker-list");
519
+
520
+ function openResumeModal() {
521
+ resumeModal.classList.remove("hidden");
522
+ pickerLoading.classList.remove("hidden");
523
+ pickerEmpty.classList.add("hidden");
524
+ pickerList.classList.add("hidden");
525
+ pickerList.innerHTML = "";
526
+ if (getWs() && store.get('connected')) {
527
+ getWs().send(JSON.stringify({ type: "list_cli_sessions" }));
528
+ }
529
+ }
530
+ openResumePickerModal = openResumeModal;
531
+
532
+ function closeResumeModal() {
533
+ resumeModal.classList.add("hidden");
534
+ }
535
+
536
+ resumeCancel.addEventListener("click", closeResumeModal);
537
+ resumeModal.querySelector(".confirm-backdrop").addEventListener("click", closeResumeModal);
538
+
539
+ // --- Import CLI palette tile ---
540
+ // The button is created by tool-palette.js with this ID; we wire the handler here.
541
+ var importCliBtn = document.getElementById("import-cli-btn");
542
+ if (importCliBtn) {
543
+ importCliBtn.addEventListener("click", function () {
544
+ openResumePickerModal();
545
+ });
546
+ }
547
+
548
+ // --- Schedule countdown timer ---
549
+ startCountdownTimer();
550
+ }
551
+
552
+ // --- Getters for cross-module access ---
553
+
554
+ export function getCachedSessions() {
555
+ return cachedSessions;
556
+ }
557
+
558
+ export function getSearchQuery() {
559
+ return searchQuery;
560
+ }
561
+
562
+ export function getSearchMatchIds() {
563
+ return searchMatchIds;
564
+ }
565
+
566
+ export function getExpandedLoopGroups() {
567
+ return expandedLoopGroups;
568
+ }
569
+
570
+ export function getExpandedLoopRuns() {
571
+ return expandedLoopRuns;
572
+ }
573
+
574
+ // --- Context menu ---
575
+
576
+ function closeSessionCtxMenu() {
577
+ if (sessionCtxMenu) {
578
+ sessionCtxMenu.remove();
579
+ sessionCtxMenu = null;
580
+ sessionCtxSessionId = null;
581
+ }
582
+ }
583
+
584
+ function showSessionCtxMenu(anchorBtn, sessionId, title, cliSid, sessionData) {
585
+ closeSessionCtxMenu();
586
+ sessionCtxSessionId = sessionId;
587
+
588
+ var menu = document.createElement("div");
589
+ menu.className = "session-ctx-menu";
590
+
591
+ var bookmarkItem = document.createElement("button");
592
+ bookmarkItem.className = "session-ctx-item";
593
+ bookmarkItem.innerHTML = iconHtml(sessionData && sessionData.bookmarked ? "arrow-down" : "arrow-up") + " <span>" + (sessionData && sessionData.bookmarked ? "Remove from Favorites" : "Add to Favorites") + "</span>";
594
+ bookmarkItem.addEventListener("click", function (e) {
595
+ e.stopPropagation();
596
+ closeSessionCtxMenu();
597
+ sendSessionBookmark(sessionId, !(sessionData && sessionData.bookmarked));
598
+ });
599
+ menu.appendChild(bookmarkItem);
600
+
601
+ var renameItem = document.createElement("button");
602
+ renameItem.className = "session-ctx-item";
603
+ renameItem.innerHTML = iconHtml("pencil") + " <span>Rename</span>";
604
+ renameItem.addEventListener("click", function (e) {
605
+ e.stopPropagation();
606
+ closeSessionCtxMenu();
607
+ startInlineRename(sessionId, title);
608
+ });
609
+ menu.appendChild(renameItem);
610
+
611
+ // Session visibility toggle (only the session owner can change)
612
+ if (store.get('isMultiUserMode') && sessionData && sessionData.ownerId && sessionData.ownerId === store.get('myUserId')) {
613
+ var currentVis = (sessionData && sessionData.sessionVisibility) || "shared";
614
+ var isPrivate = currentVis === "private";
615
+ var visItem = document.createElement("button");
616
+ visItem.className = "session-ctx-item";
617
+ visItem.innerHTML = iconHtml(isPrivate ? "eye" : "eye-off") + " <span>" + (isPrivate ? "Make Shared" : "Make Private") + "</span>";
618
+ visItem.addEventListener("click", function (e) {
619
+ e.stopPropagation();
620
+ closeSessionCtxMenu();
621
+ var newVis = isPrivate ? "shared" : "private";
622
+ if (getWs() && store.get('connected')) {
623
+ getWs().send(JSON.stringify({ type: "set_session_visibility", sessionId: sessionId, visibility: newVis }));
624
+ }
625
+ });
626
+ menu.appendChild(visItem);
627
+ }
628
+
629
+ if (!store.get('permissions') || store.get('permissions').sessionDelete !== false) {
630
+ var deleteItem = document.createElement("button");
631
+ deleteItem.className = "session-ctx-item session-ctx-delete";
632
+ deleteItem.innerHTML = iconHtml("trash-2") + " <span>Delete</span>";
633
+ deleteItem.addEventListener("click", function (e) {
634
+ e.stopPropagation();
635
+ closeSessionCtxMenu();
636
+ confirmDeleteSession({ id: sessionId, title: title });
637
+ });
638
+ menu.appendChild(deleteItem);
639
+ }
640
+
641
+ document.body.appendChild(menu);
642
+ sessionCtxMenu = menu;
643
+ refreshIcons();
644
+
645
+ // Position: fixed relative to the anchor button
646
+ requestAnimationFrame(function () {
647
+ var btnRect = anchorBtn.getBoundingClientRect();
648
+ menu.style.position = "fixed";
649
+ menu.style.top = (btnRect.bottom + 2) + "px";
650
+ menu.style.right = (window.innerWidth - btnRect.right) + "px";
651
+ menu.style.left = "auto";
652
+ // If menu overflows below viewport, flip up
653
+ var menuRect = menu.getBoundingClientRect();
654
+ if (menuRect.bottom > window.innerHeight - 8) {
655
+ menu.style.top = (btnRect.top - menuRect.height - 2) + "px";
656
+ }
657
+ });
658
+ }
659
+
660
+ function showLoopCtxMenu(anchorBtn, loopId, loopName, childCount) {
661
+ closeSessionCtxMenu();
662
+
663
+ var menu = document.createElement("div");
664
+ menu.className = "session-ctx-menu";
665
+
666
+ var renameItem = document.createElement("button");
667
+ renameItem.className = "session-ctx-item";
668
+ renameItem.innerHTML = iconHtml("pencil") + " <span>Rename</span>";
669
+ renameItem.addEventListener("click", function (e) {
670
+ e.stopPropagation();
671
+ closeSessionCtxMenu();
672
+ startLoopInlineRename(loopId, loopName);
673
+ });
674
+ menu.appendChild(renameItem);
675
+
676
+ if (!store.get('permissions') || store.get('permissions').sessionDelete !== false) {
677
+ var deleteItem = document.createElement("button");
678
+ deleteItem.className = "session-ctx-item session-ctx-delete";
679
+ deleteItem.innerHTML = iconHtml("trash-2") + " <span>Delete</span>";
680
+ deleteItem.addEventListener("click", function (e) {
681
+ e.stopPropagation();
682
+ closeSessionCtxMenu();
683
+ var msg = 'Delete "' + (loopName || "Loop") + '"';
684
+ if (childCount > 1) msg += " and its " + childCount + " sessions";
685
+ msg += "? This cannot be undone.";
686
+ showConfirm(msg, function () {
687
+ if (getWs() && store.get('connected')) {
688
+ getWs().send(JSON.stringify({ type: "delete_loop_group", loopId: loopId }));
689
+ }
690
+ });
691
+ });
692
+ menu.appendChild(deleteItem);
693
+ }
694
+
695
+ document.body.appendChild(menu);
696
+ sessionCtxMenu = menu;
697
+ refreshIcons();
698
+
699
+ requestAnimationFrame(function () {
700
+ var btnRect = anchorBtn.getBoundingClientRect();
701
+ menu.style.position = "fixed";
702
+ menu.style.top = (btnRect.bottom + 2) + "px";
703
+ menu.style.right = (window.innerWidth - btnRect.right) + "px";
704
+ menu.style.left = "auto";
705
+ var menuRect = menu.getBoundingClientRect();
706
+ if (menuRect.bottom > window.innerHeight - 8) {
707
+ menu.style.top = (btnRect.top - menuRect.height - 2) + "px";
708
+ }
709
+ });
710
+ }
711
+
712
+ // --- Inline rename ---
713
+
714
+ function startInlineRename(sessionId, currentTitle) {
715
+ var el = getSessionListEl().querySelector('.session-item[data-session-id="' + sessionId + '"]');
716
+ if (!el) return;
717
+ var textSpan = el.querySelector(".session-item-text");
718
+ if (!textSpan) return;
719
+
720
+ var input = document.createElement("input");
721
+ input.type = "text";
722
+ input.className = "session-rename-input";
723
+ input.value = currentTitle || "New Session";
724
+
725
+ var originalHtml = textSpan.innerHTML;
726
+ textSpan.innerHTML = "";
727
+ textSpan.appendChild(input);
728
+ input.focus();
729
+ input.select();
730
+
731
+ function commitRename() {
732
+ var newTitle = input.value.trim();
733
+ if (newTitle && newTitle !== currentTitle && getWs() && store.get('connected')) {
734
+ getWs().send(JSON.stringify({ type: "rename_session", id: sessionId, title: newTitle }));
735
+ }
736
+ // Restore text (server will send updated session_list)
737
+ textSpan.innerHTML = originalHtml;
738
+ if (newTitle && newTitle !== currentTitle) {
739
+ textSpan.textContent = newTitle;
740
+ }
741
+ }
742
+
743
+ input.addEventListener("keydown", function (e) {
744
+ if (e.key === "Enter") { e.preventDefault(); commitRename(); }
745
+ if (e.key === "Escape") { e.preventDefault(); textSpan.innerHTML = originalHtml; }
746
+ });
747
+ input.addEventListener("blur", commitRename);
748
+ input.addEventListener("click", function (e) { e.stopPropagation(); });
749
+ }
750
+
751
+ function startLoopInlineRename(loopId, currentName) {
752
+ var el = getSessionListEl().querySelector('.session-loop-group[data-loop-id="' + loopId + '"]');
753
+ if (!el) return;
754
+ var textSpan = el.querySelector(".session-item-text");
755
+ if (!textSpan) return;
756
+
757
+ var input = document.createElement("input");
758
+ input.type = "text";
759
+ input.className = "session-rename-input";
760
+ input.value = currentName || "Loop";
761
+
762
+ var originalHtml = textSpan.innerHTML;
763
+ textSpan.innerHTML = "";
764
+ textSpan.appendChild(input);
765
+ input.focus();
766
+ input.select();
767
+
768
+ function commitRename() {
769
+ var newName = input.value.trim();
770
+ if (newName && newName !== currentName && getWs() && store.get('connected')) {
771
+ getWs().send(JSON.stringify({ type: "loop_registry_rename", id: loopId, name: newName }));
772
+ }
773
+ textSpan.innerHTML = originalHtml;
774
+ if (newName && newName !== currentName) {
775
+ // Update text inline immediately
776
+ var nameNode = textSpan.querySelector(".session-loop-name");
777
+ if (nameNode) nameNode.textContent = newName;
778
+ }
779
+ }
780
+
781
+ input.addEventListener("keydown", function (e) {
782
+ if (e.key === "Enter") { e.preventDefault(); commitRename(); }
783
+ if (e.key === "Escape") { e.preventDefault(); textSpan.innerHTML = originalHtml; }
784
+ });
785
+ input.addEventListener("blur", commitRename);
786
+ input.addEventListener("click", function (e) { e.stopPropagation(); });
787
+ }
788
+
789
+ // --- Date grouping / highlighting ---
790
+
791
+ export function getDateGroup(ts) {
792
+ var now = new Date();
793
+ var d = new Date(ts);
794
+ var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
795
+ var yesterday = new Date(today.getTime() - 86400000);
796
+ var weekAgo = new Date(today.getTime() - 7 * 86400000);
797
+ if (d >= today) return "Today";
798
+ if (d >= yesterday) return "Yesterday";
799
+ if (d >= weekAgo) return "This Week";
800
+ return "Older";
801
+ }
802
+
803
+ export function highlightMatch(text, query) {
804
+ if (!query) return escapeHtml(text);
805
+ var lower = text.toLowerCase();
806
+ var qLower = query.toLowerCase();
807
+ var idx = lower.indexOf(qLower);
808
+ if (idx === -1) return escapeHtml(text);
809
+ var before = text.substring(0, idx);
810
+ var match = text.substring(idx, idx + query.length);
811
+ var after = text.substring(idx + query.length);
812
+ return escapeHtml(before) + '<mark class="session-highlight">' + escapeHtml(match) + '</mark>' + escapeHtml(after);
813
+ }
814
+
815
+ function isSessionVisibleBySearch(sessionId) {
816
+ if (searchMatchIds === null) return true;
817
+ return searchMatchIds.has(sessionId);
818
+ }
819
+
820
+ // --- Loop child / run / group rendering ---
821
+
822
+ function renderLoopChild(s) {
823
+ var el = document.createElement("div");
824
+ var isMatch = searchMatchIds !== null && searchMatchIds.has(s.id);
825
+ el.className = "session-loop-child" + (s.active ? " active" : "") + (isMatch ? " search-match" : "");
826
+ el.dataset.sessionId = s.id;
827
+
828
+ var textSpan = document.createElement("span");
829
+ textSpan.className = "session-item-text";
830
+ var textHtml = "";
831
+ if (s.isProcessing) {
832
+ textHtml += '<span class="session-processing"></span>';
833
+ }
834
+ if (s.loop) {
835
+ var isRalphChild = s.loop.source === "ralph";
836
+ var roleName = s.loop.role === "crafting" ? "Crafting" : s.loop.role === "judge" ? "Judge" : (isRalphChild ? "Coder" : "Run");
837
+ var iterSuffix = s.loop.role === "crafting" ? "" : " #" + s.loop.iteration;
838
+ var roleCls = s.loop.role === "crafting" ? " crafting" : (!isRalphChild ? " scheduled" : "");
839
+ textHtml += '<span class="session-loop-role-badge' + roleCls + '">' + roleName + iterSuffix + '</span>';
840
+ }
841
+ textSpan.innerHTML = textHtml;
842
+ el.appendChild(textSpan);
843
+ appendSessionCloseButton(el, s);
844
+
845
+ el.addEventListener("click", (function (id) {
846
+ return function () {
847
+ if (getWs() && store.get('connected')) {
848
+ getWs().send(JSON.stringify({ type: "switch_session", id: id }));
849
+ dismissOverlayPanels();
850
+ closeSidebar();
851
+ }
852
+ };
853
+ })(s.id));
854
+
855
+ return el;
856
+ }
857
+
858
+ function renderLoopGroup(loopId, children, groupKey) {
859
+ var visibleChildren = children;
860
+ if (searchMatchIds !== null) {
861
+ visibleChildren = [];
862
+ for (var vi = 0; vi < children.length; vi++) {
863
+ if (isSessionVisibleBySearch(children[vi].id)) {
864
+ visibleChildren.push(children[vi]);
865
+ }
866
+ }
867
+ if (visibleChildren.length === 0) {
868
+ return null;
869
+ }
870
+ }
871
+
872
+ var gk = groupKey || loopId;
873
+
874
+ // Sub-group children by startedAt (each run)
875
+ var runMap = {};
876
+ for (var i = 0; i < visibleChildren.length; i++) {
877
+ var runKey = String(visibleChildren[i].loop && visibleChildren[i].loop.startedAt || 0);
878
+ if (!runMap[runKey]) runMap[runKey] = [];
879
+ runMap[runKey].push(visibleChildren[i]);
880
+ }
881
+ var runKeys = Object.keys(runMap);
882
+
883
+ // Sort each run's children by iteration then role
884
+ for (var ri = 0; ri < runKeys.length; ri++) {
885
+ runMap[runKeys[ri]].sort(function (a, b) {
886
+ var ai = (a.loop && a.loop.iteration) || 0;
887
+ var bi = (b.loop && b.loop.iteration) || 0;
888
+ if (ai !== bi) return ai - bi;
889
+ var ar = (a.loop && a.loop.role === "judge") ? 1 : 0;
890
+ var br = (b.loop && b.loop.role === "judge") ? 1 : 0;
891
+ return ar - br;
892
+ });
893
+ }
894
+
895
+ // Sort runs by startedAt descending (newest first)
896
+ runKeys.sort(function (a, b) { return Number(b) - Number(a); });
897
+
898
+ var expanded = expandedLoopGroups.has(gk);
899
+ var hasActive = false;
900
+ var anyProcessing = false;
901
+ var latestSession = visibleChildren[0];
902
+ for (var ci = 0; ci < visibleChildren.length; ci++) {
903
+ if (visibleChildren[ci].active) hasActive = true;
904
+ if (visibleChildren[ci].isProcessing) anyProcessing = true;
905
+ if ((visibleChildren[ci].lastActivity || 0) > (latestSession.lastActivity || 0)) {
906
+ latestSession = visibleChildren[ci];
907
+ }
908
+ }
909
+
910
+ var loopName = (visibleChildren[0].loop && visibleChildren[0].loop.name) || "Loop";
911
+ var isRalph = visibleChildren[0].loop && visibleChildren[0].loop.source === "ralph";
912
+ var isCrafting = false;
913
+ for (var j = 0; j < visibleChildren.length; j++) {
914
+ if (visibleChildren[j].loop && visibleChildren[j].loop.role === "crafting") isCrafting = true;
915
+ }
916
+
917
+ var runCount = runKeys.length;
918
+
919
+ var wrapper = document.createElement("div");
920
+ wrapper.className = "session-loop-wrapper";
921
+
922
+ // Group header row
923
+ var el = document.createElement("div");
924
+ var groupClass = "session-loop-group" + (hasActive ? " active" : "") + (expanded ? " expanded" : "");
925
+ if (!isRalph) groupClass += " scheduled";
926
+ el.className = groupClass;
927
+ el.dataset.loopId = loopId;
928
+
929
+ var chevron = document.createElement("button");
930
+ chevron.className = "session-loop-chevron";
931
+ chevron.innerHTML = iconHtml("chevron-right");
932
+ chevron.addEventListener("click", (function (lid) {
933
+ return function (e) {
934
+ e.stopPropagation();
935
+ if (expandedLoopGroups.has(lid)) {
936
+ expandedLoopGroups.delete(lid);
937
+ } else {
938
+ expandedLoopGroups.add(lid);
939
+ }
940
+ renderSessionList(null);
941
+ };
942
+ })(gk));
943
+ el.appendChild(chevron);
944
+
945
+ var textSpan = document.createElement("span");
946
+ textSpan.className = "session-item-text";
947
+ var textHtml = "";
948
+ if (anyProcessing) {
949
+ textHtml += '<span class="session-processing"></span>';
950
+ }
951
+ var groupIcon = isRalph ? "repeat" : "calendar-clock";
952
+ var iconClass = isRalph ? "" : " scheduled";
953
+ textHtml += '<span class="session-loop-icon' + iconClass + '">' + iconHtml(groupIcon) + '</span>';
954
+ textHtml += '<span class="session-loop-name">' + escapeHtml(loopName) + '</span>';
955
+ if (isCrafting && children.length === 1) {
956
+ textHtml += '<span class="session-loop-badge crafting">Crafting</span>';
957
+ } else {
958
+ var countLabel = runCount === 1 ? visibleChildren.length : runCount + (runCount === 1 ? " run" : " runs");
959
+ var countClass = isRalph ? "" : " scheduled";
960
+ textHtml += '<span class="session-loop-count' + countClass + '">' + countLabel + '</span>';
961
+ }
962
+ textSpan.innerHTML = textHtml;
963
+ el.appendChild(textSpan);
964
+
965
+ // More button (ellipsis)
966
+ var moreBtn = document.createElement("button");
967
+ moreBtn.className = "session-more-btn";
968
+ moreBtn.innerHTML = iconHtml("ellipsis");
969
+ moreBtn.title = "More options";
970
+ moreBtn.addEventListener("click", (function (lid, name, count, btn) {
971
+ return function (e) {
972
+ e.stopPropagation();
973
+ showLoopCtxMenu(btn, lid, name, count);
974
+ };
975
+ })(loopId, loopName, visibleChildren.length, moreBtn));
976
+ el.appendChild(moreBtn);
977
+
978
+ // Click row (not chevron/more) -> switch to latest session
979
+ el.addEventListener("click", (function (id) {
980
+ return function () {
981
+ if (getWs() && store.get('connected')) {
982
+ getWs().send(JSON.stringify({ type: "switch_session", id: id }));
983
+ dismissOverlayPanels();
984
+ closeSidebar();
985
+ }
986
+ };
987
+ })(latestSession.id));
988
+
989
+ wrapper.appendChild(el);
990
+
991
+ // Expanded: show runs as sub-groups
992
+ if (expanded) {
993
+ var childContainer = document.createElement("div");
994
+ childContainer.className = "session-loop-children";
995
+
996
+ if (runCount === 1) {
997
+ // Single run: show sessions directly (no extra nesting)
998
+ var singleRun = runMap[runKeys[0]];
999
+ for (var sk = 0; sk < singleRun.length; sk++) {
1000
+ childContainer.appendChild(renderLoopChild(singleRun[sk]));
1001
+ }
1002
+ } else {
1003
+ // Multiple runs: render each run as a collapsible sub-group
1004
+ for (var rk = 0; rk < runKeys.length; rk++) {
1005
+ childContainer.appendChild(renderLoopRun(gk, runKeys[rk], runMap[runKeys[rk]], isRalph));
1006
+ }
1007
+ }
1008
+
1009
+ wrapper.appendChild(childContainer);
1010
+ }
1011
+
1012
+ return wrapper;
1013
+ }
1014
+
1015
+ function renderLoopRun(parentGk, startedAtKey, sessions, isRalph) {
1016
+ var runGk = parentGk + ":" + startedAtKey;
1017
+ var expanded = expandedLoopRuns.has(runGk);
1018
+ var startedAt = Number(startedAtKey);
1019
+ var timeLabel = startedAt ? new Date(startedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : "Unknown";
1020
+
1021
+ var hasActive = false;
1022
+ var anyProcessing = false;
1023
+ var latestSession = sessions[0];
1024
+ for (var i = 0; i < sessions.length; i++) {
1025
+ if (sessions[i].active) hasActive = true;
1026
+ if (sessions[i].isProcessing) anyProcessing = true;
1027
+ if ((sessions[i].lastActivity || 0) > (latestSession.lastActivity || 0)) {
1028
+ latestSession = sessions[i];
1029
+ }
1030
+ }
1031
+
1032
+ var wrapper = document.createElement("div");
1033
+ wrapper.className = "session-loop-run-wrapper";
1034
+
1035
+ var el = document.createElement("div");
1036
+ el.className = "session-loop-run" + (hasActive ? " active" : "") + (expanded ? " expanded" : "") + (isRalph ? "" : " scheduled");
1037
+
1038
+ var chevron = document.createElement("button");
1039
+ chevron.className = "session-loop-chevron";
1040
+ chevron.innerHTML = iconHtml("chevron-right");
1041
+ chevron.addEventListener("click", (function (rk) {
1042
+ return function (e) {
1043
+ e.stopPropagation();
1044
+ if (expandedLoopRuns.has(rk)) {
1045
+ expandedLoopRuns.delete(rk);
1046
+ } else {
1047
+ expandedLoopRuns.add(rk);
1048
+ }
1049
+ renderSessionList(null);
1050
+ };
1051
+ })(runGk));
1052
+ el.appendChild(chevron);
1053
+
1054
+ var textSpan = document.createElement("span");
1055
+ textSpan.className = "session-item-text";
1056
+ var textHtml = "";
1057
+ if (anyProcessing) {
1058
+ textHtml += '<span class="session-processing"></span>';
1059
+ }
1060
+ textHtml += '<span class="session-loop-run-time">' + escapeHtml(timeLabel) + '</span>';
1061
+ textHtml += '<span class="session-loop-count' + (isRalph ? "" : " scheduled") + '">' + sessions.length + '</span>';
1062
+ textSpan.innerHTML = textHtml;
1063
+ el.appendChild(textSpan);
1064
+
1065
+ // Click row -> switch to latest session of this run
1066
+ el.addEventListener("click", (function (id) {
1067
+ return function () {
1068
+ if (getWs() && store.get('connected')) {
1069
+ getWs().send(JSON.stringify({ type: "switch_session", id: id }));
1070
+ dismissOverlayPanels();
1071
+ closeSidebar();
1072
+ }
1073
+ };
1074
+ })(latestSession.id));
1075
+
1076
+ wrapper.appendChild(el);
1077
+
1078
+ if (expanded) {
1079
+ var childContainer = document.createElement("div");
1080
+ childContainer.className = "session-loop-children";
1081
+ for (var k = 0; k < sessions.length; k++) {
1082
+ childContainer.appendChild(renderLoopChild(sessions[k]));
1083
+ }
1084
+ wrapper.appendChild(childContainer);
1085
+ }
1086
+
1087
+ return wrapper;
1088
+ }
1089
+
1090
+ // --- Session item rendering ---
1091
+
1092
+ function renderSessionItem(s) {
1093
+ var el = document.createElement("div");
1094
+ var isMatch = searchMatchIds !== null && searchMatchIds.has(s.id);
1095
+ el.className = "session-item" + (s.active ? " active" : "") + (isMatch ? " search-match" : "");
1096
+ el.dataset.sessionId = s.id;
1097
+
1098
+ var textSpan = document.createElement("span");
1099
+ textSpan.className = "session-item-text";
1100
+ var textHtml = "";
1101
+ if (s.isProcessing) {
1102
+ textHtml += '<span class="session-processing"></span>';
1103
+ }
1104
+ if (store.get('isMultiUserMode') && s.sessionVisibility === "private") {
1105
+ textHtml += '<span class="session-private-icon" title="Private session">' + iconHtml("lock") + '</span>';
1106
+ }
1107
+ // lr-7db0 — agent badge for sessions cast as a named agent via the SDK `agent` option.
1108
+ // Icon-only with the agent name in `title` matches the lock-icon convention for
1109
+ // private sessions (above) and prevents the agent name from bleeding into the
1110
+ // window title via .session-item-text.textContent in sidebar.js:updatePageTitle.
1111
+ if (s.agentName) {
1112
+ textHtml += '<span class="session-agent-badge" title="Agent: ' + escapeHtml(s.agentName) + '">'
1113
+ + iconHtml("bot") + '</span>';
1114
+ }
1115
+ textHtml += highlightMatch(s.title || "New Session", searchQuery);
1116
+ textSpan.innerHTML = textHtml;
1117
+ el.appendChild(textSpan);
1118
+
1119
+ // Right-click / long-press: context menu
1120
+ el.addEventListener("contextmenu", (function(id, title, cliSid, anchor, sData) {
1121
+ return function(e) {
1122
+ e.preventDefault();
1123
+ e.stopPropagation();
1124
+ showSessionCtxMenu(anchor, id, title, cliSid, sData);
1125
+ };
1126
+ })(s.id, s.title, s.cliSessionId, el, s));
1127
+
1128
+ // Unread badge
1129
+ var unreadBadge = document.createElement("span");
1130
+ unreadBadge.className = "session-unread-badge";
1131
+ unreadBadge.dataset.sessionId = s.id;
1132
+ if (s.unread > 0) {
1133
+ unreadBadge.textContent = s.unread > 99 ? "99+" : String(s.unread);
1134
+ unreadBadge.classList.add("has-unread");
1135
+ }
1136
+ el.appendChild(unreadBadge);
1137
+ appendSessionCloseButton(el, s);
1138
+
1139
+ el.addEventListener("click", (function (id) {
1140
+ return function () {
1141
+ if (getWs() && store.get('connected')) {
1142
+ var pendingQuery = searchQuery || "";
1143
+ getWs().send(JSON.stringify({ type: "switch_session", id: id }));
1144
+ dismissOverlayPanels();
1145
+ closeSidebar();
1146
+ if (pendingQuery) {
1147
+ setTimeout(function () { openSessionSearch(pendingQuery); }, 400);
1148
+ }
1149
+ }
1150
+ };
1151
+ })(s.id));
1152
+
1153
+ // Presence avatars (multi-user)
1154
+ renderPresenceAvatars(el, String(s.id));
1155
+ setupSessionDragHandlers(el, s);
1156
+
1157
+ return el;
1158
+ }
1159
+
1160
+ // --- Main session list ---
1161
+
1162
+ function _fingerprintSessions(list, expanded, expandedRuns) {
1163
+ var parts = [];
1164
+ for (var i = 0; i < list.length; i++) {
1165
+ var s = list[i];
1166
+ parts.push(
1167
+ s.id + "," +
1168
+ (s.title || "") + "," +
1169
+ (s.active ? "1" : "0") + "," +
1170
+ (s.isProcessing ? "1" : "0") + "," +
1171
+ (s.bookmarked ? "1" : "0") + "," +
1172
+ (s.lastActivity || 0) + "," +
1173
+ (s.sessionVisibility || "") + "," +
1174
+ (s.agentName || "") + "," +
1175
+ (s.loop ? (s.loop.loopId + ":" + s.loop.role + ":" + s.loop.source) : "")
1176
+ );
1177
+ }
1178
+ // Include expanded state so chevron toggles still trigger a re-render
1179
+ expanded.forEach(function (id) { parts.push("exp:" + id); });
1180
+ expandedRuns.forEach(function (id) { parts.push("run:" + id); });
1181
+ return parts.join("|");
1182
+ }
1183
+
1184
+ export function renderSessionList(sessions) {
1185
+ if (sessions) cachedSessions = sessions;
1186
+
1187
+ // Skip full rebuild when session data hasn't changed. Server often
1188
+ // re-broadcasts session_list after unrelated events (session switches,
1189
+ // WS reconnects, presence updates). Each rebuild does innerHTML="" on the
1190
+ // entire sidebar list + re-creates all elements + calls refreshIcons().
1191
+ // Include search state so filter changes always trigger a rebuild.
1192
+ var fp = _fingerprintSessions(cachedSessions, expandedLoopGroups, expandedLoopRuns) +
1193
+ "|sq:" + searchQuery + "|sm:" + (searchMatchIds ? searchMatchIds.size : "null");
1194
+ if (fp === _sessionListFingerprint) {
1195
+ // Still need to refresh mobile sheet and search UI on null calls
1196
+ if (refreshMobileChatSheet) refreshMobileChatSheet();
1197
+ syncHeaderSearchUi();
1198
+ if (updatePageTitle) updatePageTitle();
1199
+ return;
1200
+ }
1201
+ _sessionListFingerprint = fp;
1202
+
1203
+ // If mobile chat sheet is open, refresh it
1204
+ if (refreshMobileChatSheet) refreshMobileChatSheet();
1205
+
1206
+ getSessionListEl().innerHTML = "";
1207
+
1208
+ // Partition: loop sessions vs normal sessions
1209
+ // Group by loopId + date so all runs of the same task on the same day are merged
1210
+ var loopGroups = {}; // groupKey -> [sessions]
1211
+ var normalSessions = [];
1212
+ for (var i = 0; i < cachedSessions.length; i++) {
1213
+ var s = cachedSessions[i];
1214
+ if (s.loop && s.loop.loopId && s.loop.role === "crafting" && s.loop.source !== "ralph") {
1215
+ // Task crafting sessions live in the scheduler calendar, not the main list.
1216
+ continue;
1217
+ } else if (s.loop && s.loop.loopId) {
1218
+ var startedAt = s.loop.startedAt || 0;
1219
+ var dateStr = startedAt ? new Date(startedAt).toISOString().slice(0, 10) : "unknown";
1220
+ var groupKey = s.loop.loopId + ":" + dateStr;
1221
+ if (!loopGroups[groupKey]) loopGroups[groupKey] = [];
1222
+ loopGroups[groupKey].push(s);
1223
+ } else {
1224
+ normalSessions.push(s);
1225
+ }
1226
+ }
1227
+
1228
+ // Build virtual items: normal sessions + one entry per loop group (using latest child's lastActivity)
1229
+ var items = [];
1230
+ for (var j = 0; j < normalSessions.length; j++) {
1231
+ items.push({ type: "session", data: normalSessions[j], lastActivity: normalSessions[j].lastActivity || 0 });
1232
+ }
1233
+ var groupKeys = Object.keys(loopGroups);
1234
+ for (var k = 0; k < groupKeys.length; k++) {
1235
+ var gk = groupKeys[k];
1236
+ var children = loopGroups[gk];
1237
+ var realLoopId = children[0].loop.loopId;
1238
+ var maxActivity = 0;
1239
+ for (var m = 0; m < children.length; m++) {
1240
+ var act = children[m].lastActivity || 0;
1241
+ if (act > maxActivity) maxActivity = act;
1242
+ }
1243
+ items.push({ type: "loop", loopId: realLoopId, groupKey: gk, children: children, lastActivity: maxActivity });
1244
+ }
1245
+
1246
+ // Sort by lastActivity descending
1247
+ items.sort(compareSessionListItems);
1248
+
1249
+ var bookmarkedItems = [];
1250
+ var regularItems = [];
1251
+ for (var n = 0; n < items.length; n++) {
1252
+ var item = items[n];
1253
+ if (item.type === "session" && item.data && !isSessionVisibleBySearch(item.data.id)) {
1254
+ continue;
1255
+ }
1256
+ if (item.type === "session" && item.data && item.data.bookmarked) {
1257
+ bookmarkedItems.push(item);
1258
+ } else {
1259
+ regularItems.push(item);
1260
+ }
1261
+ }
1262
+
1263
+ var favoritesContainer = document.createElement("div");
1264
+ favoritesContainer.className = "session-favorites-section";
1265
+ setupBookmarkDropTarget(favoritesContainer, true);
1266
+ if (bookmarkedItems.length === 0) {
1267
+ var emptyHint = document.createElement("div");
1268
+ emptyHint.className = "session-favorites-empty";
1269
+ emptyHint.textContent = "Drag and drop sessions here to add favorites.";
1270
+ favoritesContainer.appendChild(emptyHint);
1271
+ }
1272
+ for (var bi = 0; bi < bookmarkedItems.length; bi++) {
1273
+ favoritesContainer.appendChild(renderSessionItem(bookmarkedItems[bi].data));
1274
+ }
1275
+
1276
+ var divider = document.createElement("div");
1277
+ divider.className = "session-favorites-divider";
1278
+
1279
+ var regularContainer = document.createElement("div");
1280
+ regularContainer.className = "session-regular-drop";
1281
+ setupBookmarkDropTarget(regularContainer, false);
1282
+ var stickyTop = document.createElement("div");
1283
+ stickyTop.className = "session-list-sticky-top";
1284
+ stickyTop.appendChild(renderSessionTopActions());
1285
+ stickyTop.appendChild(favoritesContainer);
1286
+ stickyTop.appendChild(divider);
1287
+ getSessionListEl().appendChild(stickyTop);
1288
+
1289
+ var currentGroup = "";
1290
+ var currentGroupIds = [];
1291
+ for (var ri = 0; ri < regularItems.length; ri++) {
1292
+ var item = regularItems[ri];
1293
+ var group = getDateGroup(item.lastActivity || 0);
1294
+ if (group !== currentGroup) {
1295
+ currentGroup = group;
1296
+ currentGroupIds = [];
1297
+ for (var gi = ri; gi < regularItems.length; gi++) {
1298
+ if (getDateGroup(regularItems[gi].lastActivity || 0) !== group) break;
1299
+ var groupIds = collectItemSessionIds(regularItems[gi]);
1300
+ for (var gj = 0; gj < groupIds.length; gj++) currentGroupIds.push(groupIds[gj]);
1301
+ }
1302
+ if (group !== "Today") {
1303
+ regularContainer.appendChild(createSessionGroupHeader(group, currentGroupIds));
1304
+ }
1305
+ }
1306
+ if (item.type === "loop") {
1307
+ var loopEl = renderLoopGroup(item.loopId, item.children, item.groupKey);
1308
+ if (loopEl) {
1309
+ regularContainer.appendChild(loopEl);
1310
+ }
1311
+ } else {
1312
+ regularContainer.appendChild(renderSessionItem(item.data));
1313
+ }
1314
+ }
1315
+ getSessionListEl().appendChild(regularContainer);
1316
+ refreshIcons();
1317
+ if (updatePageTitle) updatePageTitle();
1318
+ syncHeaderSearchUi();
1319
+ }
1320
+
1321
+ // --- Search results ---
1322
+
1323
+ export function handleSearchResults(msg) {
1324
+ if (msg.query !== searchQuery) return; // stale response
1325
+ var ids = new Set();
1326
+ for (var i = 0; i < msg.results.length; i++) {
1327
+ ids.add(msg.results[i].id);
1328
+ }
1329
+ searchMatchIds = ids;
1330
+ renderSessionList(null);
1331
+ }
1332
+
1333
+ // --- Session presence ---
1334
+
1335
+ export function updateSessionPresence(presence) {
1336
+ sessionPresence = presence;
1337
+ // Update presence avatars on existing session items without full re-render
1338
+ var items = getSessionListEl().querySelectorAll("[data-session-id]");
1339
+ for (var i = 0; i < items.length; i++) {
1340
+ renderPresenceAvatars(items[i], items[i].dataset.sessionId);
1341
+ }
1342
+ }
1343
+
1344
+ export function getSessionPresenceUsers(sessionId) {
1345
+ return sessionPresence[String(sessionId)] || sessionPresence[sessionId] || [];
1346
+ }
1347
+
1348
+ function presenceAvatarUrl(userOrStyle, seed) {
1349
+ if (userOrStyle && typeof userOrStyle === "object") return userAvatarUrl(userOrStyle, 24);
1350
+ return avatarUrl(userOrStyle || "thumbs", seed, 24);
1351
+ }
1352
+
1353
+ function renderPresenceAvatars(el, sessionId) {
1354
+ // Remove existing presence container
1355
+ var existing = el.querySelector(".session-presence");
1356
+ if (existing) existing.remove();
1357
+
1358
+ var users = sessionPresence[sessionId];
1359
+ if (!users || users.length === 0) return;
1360
+
1361
+ var container = document.createElement("span");
1362
+ container.className = "session-presence";
1363
+
1364
+ var max = 3;
1365
+ var shown = users.length > max ? max : users.length;
1366
+ for (var i = 0; i < shown; i++) {
1367
+ var u = users[i];
1368
+ var img = document.createElement("img");
1369
+ img.className = "session-presence-avatar";
1370
+ img.src = presenceAvatarUrl(u);
1371
+ img.alt = u.displayName;
1372
+ img.dataset.tip = u.displayName + (u.username ? " (@" + u.username + ")" : "");
1373
+ if (i > 0) img.style.marginLeft = "-6px";
1374
+ container.appendChild(img);
1375
+ }
1376
+ if (users.length > max) {
1377
+ var more = document.createElement("span");
1378
+ more.className = "session-presence-more";
1379
+ more.textContent = "+" + (users.length - max);
1380
+ container.appendChild(more);
1381
+ }
1382
+
1383
+ // Insert before the more-btn
1384
+ var moreBtn = el.querySelector(".session-more-btn");
1385
+ if (moreBtn) {
1386
+ el.insertBefore(container, moreBtn);
1387
+ } else {
1388
+ el.appendChild(container);
1389
+ }
1390
+ }
1391
+
1392
+ // --- Session badge ---
1393
+
1394
+ export function updateSessionBadge(sessionId, count) {
1395
+ var badge = document.querySelector('.session-unread-badge[data-session-id="' + sessionId + '"]');
1396
+ if (!badge) return;
1397
+ if (count > 0) {
1398
+ badge.textContent = count > 99 ? "99+" : String(count);
1399
+ badge.classList.add("has-unread");
1400
+ } else {
1401
+ badge.textContent = "";
1402
+ badge.classList.remove("has-unread");
1403
+ }
1404
+ }
1405
+
1406
+ // --- Countdown timer ---
1407
+
1408
+ function startCountdownTimer() {
1409
+ // Only arm the 1s interval when there are schedules within the 3-minute
1410
+ // window. Without this guard the interval fired every second for the
1411
+ // entire session lifetime even with no upcoming schedules.
1412
+ if (countdownTimer) return;
1413
+ var upcoming = getUpcomingSchedules(3 * 60 * 1000);
1414
+ if (upcoming.length === 0) return;
1415
+ countdownTimer = setInterval(updateCountdowns, 1000);
1416
+ }
1417
+
1418
+ function stopCountdownTimer() {
1419
+ if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null; }
1420
+ }
1421
+
1422
+ function updateCountdowns() {
1423
+ if (!getSessionListEl()) return;
1424
+ var upcoming = getUpcomingSchedules(3 * 60 * 1000); // 3 minutes
1425
+
1426
+ // Remove stale container
1427
+ if (countdownContainer && !getSessionListEl().contains(countdownContainer)) {
1428
+ countdownContainer = null;
1429
+ }
1430
+
1431
+ if (upcoming.length === 0) {
1432
+ if (countdownContainer) {
1433
+ countdownContainer.remove();
1434
+ countdownContainer = null;
1435
+ }
1436
+ stopCountdownTimer();
1437
+ return;
1438
+ }
1439
+
1440
+ if (!countdownContainer) {
1441
+ countdownContainer = document.createElement("div");
1442
+ countdownContainer.className = "session-countdown-group";
1443
+ var stickyTop = getSessionListEl().querySelector(".session-list-sticky-top");
1444
+ if (stickyTop && stickyTop.nextSibling) {
1445
+ getSessionListEl().insertBefore(countdownContainer, stickyTop.nextSibling);
1446
+ } else if (stickyTop) {
1447
+ getSessionListEl().appendChild(countdownContainer);
1448
+ } else {
1449
+ getSessionListEl().insertBefore(countdownContainer, getSessionListEl().firstChild);
1450
+ }
1451
+ }
1452
+
1453
+ var html = "";
1454
+ var now = Date.now();
1455
+ for (var i = 0; i < upcoming.length; i++) {
1456
+ var u = upcoming[i];
1457
+ var remaining = Math.max(0, Math.ceil((u.nextRunAt - now) / 1000));
1458
+ var min = Math.floor(remaining / 60);
1459
+ var sec = remaining % 60;
1460
+ var timeStr = min + ":" + (sec < 10 ? "0" : "") + sec;
1461
+ var colorStyle = u.color ? " style=\"border-left-color:" + u.color + "\"" : "";
1462
+ html += '<div class="session-countdown-item"' + colorStyle + '>';
1463
+ html += '<span class="session-countdown-name">' + escapeHtml(u.name) + '</span>';
1464
+ html += '<span class="session-countdown-badge">' + timeStr + '</span>';
1465
+ html += '</div>';
1466
+ }
1467
+ countdownContainer.innerHTML = html;
1468
+ }
1469
+
1470
+ // --- CLI session picker ---
1471
+
1472
+ function relativeTime(isoString) {
1473
+ if (!isoString) return "";
1474
+ var ms = Date.now() - new Date(isoString).getTime();
1475
+ var sec = Math.floor(ms / 1000);
1476
+ if (sec < 60) return "just now";
1477
+ var min = Math.floor(sec / 60);
1478
+ if (min < 60) return min + "m ago";
1479
+ var hr = Math.floor(min / 60);
1480
+ if (hr < 24) return hr + "h ago";
1481
+ var days = Math.floor(hr / 24);
1482
+ if (days < 30) return days + "d ago";
1483
+ return new Date(isoString).toLocaleDateString();
1484
+ }
1485
+
1486
+ export function populateCliSessionList(sessions) {
1487
+ var pickerLoading = document.getElementById("resume-picker-loading");
1488
+ var pickerEmpty = document.getElementById("resume-picker-empty");
1489
+ var pickerList = document.getElementById("resume-picker-list");
1490
+ if (!pickerLoading || !pickerList) return;
1491
+
1492
+ pickerLoading.classList.add("hidden");
1493
+
1494
+ if (!sessions || sessions.length === 0) {
1495
+ pickerEmpty.classList.remove("hidden");
1496
+ pickerList.classList.add("hidden");
1497
+ return;
1498
+ }
1499
+
1500
+ pickerEmpty.classList.add("hidden");
1501
+ pickerList.classList.remove("hidden");
1502
+ pickerList.innerHTML = "";
1503
+
1504
+ for (var i = 0; i < sessions.length; i++) {
1505
+ var s = sessions[i];
1506
+ var item = document.createElement("div");
1507
+ item.className = "cli-session-item";
1508
+
1509
+ var title = document.createElement("div");
1510
+ title.className = "cli-session-title";
1511
+ title.textContent = s.firstPrompt || "Untitled session";
1512
+ item.appendChild(title);
1513
+
1514
+ var meta = document.createElement("div");
1515
+ meta.className = "cli-session-meta";
1516
+ if (s.lastActivity) {
1517
+ var time = document.createElement("span");
1518
+ time.textContent = relativeTime(s.lastActivity);
1519
+ meta.appendChild(time);
1520
+ }
1521
+ if (s.model) {
1522
+ var model = document.createElement("span");
1523
+ model.className = "badge";
1524
+ model.textContent = s.model;
1525
+ meta.appendChild(model);
1526
+ }
1527
+ if (s.gitBranch) {
1528
+ var branch = document.createElement("span");
1529
+ branch.className = "badge";
1530
+ branch.textContent = s.gitBranch;
1531
+ meta.appendChild(branch);
1532
+ }
1533
+ item.appendChild(meta);
1534
+
1535
+ (function (sessionId) {
1536
+ item.addEventListener("click", function () {
1537
+ if (getWs() && store.get('connected')) {
1538
+ getWs().send(JSON.stringify({ type: "resume_session", cliSessionId: sessionId }));
1539
+ }
1540
+ var modal = document.getElementById("resume-modal");
1541
+ if (modal) modal.classList.add("hidden");
1542
+ closeSidebar();
1543
+ });
1544
+ })(s.sessionId);
1545
+
1546
+ pickerList.appendChild(item);
1547
+ }
1548
+ }