agentgui 1.0.853 → 1.0.854

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.
@@ -1,3 +1,28 @@
1
+ /**
2
+ * Conversations Module
3
+ * Manages conversation list sidebar with real-time updates
4
+ * Includes folder browser for selecting working directory on new conversation
5
+ */
6
+
7
+ const AGENT_COLORS = {
8
+ 'claude-code': '#f97316',
9
+ 'opencode': '#3b82f6',
10
+ 'cli-opencode': '#3b82f6',
11
+ 'gemini': '#10b981',
12
+ 'cli-gemini': '#10b981',
13
+ 'kilo': '#8b5cf6',
14
+ 'cli-kilo': '#8b5cf6',
15
+ 'codex': '#ef4444',
16
+ 'cli-codex': '#ef4444',
17
+ 'default': '#6b7280'
18
+ };
19
+
20
+ function getAgentColor(agentId) {
21
+ if (!agentId) return AGENT_COLORS.default;
22
+ const key = Object.keys(AGENT_COLORS).find(k => agentId.startsWith(k));
23
+ return key ? AGENT_COLORS[key] : AGENT_COLORS.default;
24
+ }
25
+
1
26
  function pathSplit(p) {
2
27
  return p.split(/[\/\\]/).filter(Boolean);
3
28
  }
@@ -109,8 +134,682 @@ class ConversationManager {
109
134
  return ' (' + model.replace(/^claude-/i, '').replace(/-\d{8,}.*$/, '').replace(/-/g, ' ') + ')';
110
135
  }
111
136
 
137
+ setupDelegatedListeners() {
138
+ let draggedId = null;
139
+ this.listEl.addEventListener('dragstart', (e) => {
140
+ const item = e.target.closest('[data-drag-conv]');
141
+ if (!item) return;
142
+ draggedId = item.dataset.dragConv;
143
+ item.style.opacity = '0.5';
144
+ e.dataTransfer.effectAllowed = 'move';
145
+ });
146
+ this.listEl.addEventListener('dragend', (e) => {
147
+ const item = e.target.closest('[data-drag-conv]');
148
+ if (item) item.style.opacity = '';
149
+ draggedId = null;
150
+ });
151
+ this.listEl.addEventListener('dragover', (e) => {
152
+ const item = e.target.closest('[data-drag-conv]');
153
+ if (item && draggedId) { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; }
154
+ });
155
+ this.listEl.addEventListener('drop', (e) => {
156
+ e.preventDefault();
157
+ const target = e.target.closest('[data-drag-conv]');
158
+ if (!target || !draggedId || target.dataset.dragConv === draggedId) return;
159
+ const pinnedItems = [...this.listEl.querySelectorAll('[data-drag-conv]')];
160
+ const draggedEl = pinnedItems.find(el => el.dataset.dragConv === draggedId);
161
+ if (!draggedEl) return;
162
+ this.listEl.insertBefore(draggedEl, target);
163
+ const newOrder = [...this.listEl.querySelectorAll('[data-drag-conv]')].map(el => el.dataset.dragConv);
164
+ window.wsClient?.rpc('conv.reorder', { order: newOrder }).catch(() => {});
165
+ });
166
+
167
+ const bulkBar = document.getElementById('bulkActionBar');
168
+ const bulkCount = document.getElementById('bulkCount');
169
+ const updateBulkBar = () => {
170
+ const checked = this.getSelectedIds().length;
171
+ if (bulkBar) bulkBar.style.display = checked > 0 ? 'flex' : 'none';
172
+ if (bulkCount) bulkCount.textContent = `${checked} selected`;
173
+ };
174
+ this.listEl.addEventListener('change', (e) => {
175
+ if (e.target.matches('.conversation-item-checkbox')) updateBulkBar();
176
+ });
177
+ document.getElementById('bulkArchiveBtn')?.addEventListener('click', () => this.bulkArchive());
178
+ document.getElementById('bulkDeleteBtn')?.addEventListener('click', () => this.bulkDelete());
179
+
180
+ this.listEl.addEventListener('click', (e) => {
181
+ const exportBtn = e.target.closest('[data-export-conv]');
182
+ if (exportBtn) {
183
+ e.stopPropagation();
184
+ this.exportConversation(exportBtn.dataset.exportConv);
185
+ return;
186
+ }
187
+ const archiveBtn = e.target.closest('[data-archive-conv]');
188
+ if (archiveBtn) {
189
+ e.stopPropagation();
190
+ this.archiveConversation(archiveBtn.dataset.archiveConv);
191
+ return;
192
+ }
193
+ const deleteBtn = e.target.closest('[data-delete-conv]');
194
+ if (deleteBtn) {
195
+ e.stopPropagation();
196
+ const convId = deleteBtn.dataset.deleteConv;
197
+ const conv = this.conversations.find(c => c.id === convId);
198
+ this.confirmDelete(convId, conv?.title || 'Untitled');
199
+ return;
200
+ }
201
+ const item = e.target.closest('[data-conv-id]');
202
+ if (item) {
203
+ this.select(item.dataset.convId);
204
+ }
205
+ });
206
+ }
207
+
208
+ setupFolderBrowser() {
209
+ this.folderBrowser.modal = document.getElementById('folderBrowserModal');
210
+ this.folderBrowser.listEl = document.getElementById('folderList');
211
+ this.folderBrowser.breadcrumbEl = document.getElementById('folderBreadcrumb');
212
+
213
+ if (!this.folderBrowser.modal) return;
214
+
215
+ const closeBtn = this.folderBrowser.modal.querySelector('[data-folder-close]');
216
+ const cancelBtn = this.folderBrowser.modal.querySelector('[data-folder-cancel]');
217
+ const selectBtn = this.folderBrowser.modal.querySelector('[data-folder-select]');
218
+
219
+ closeBtn?.addEventListener('click', () => this.closeFolderBrowser());
220
+ cancelBtn?.addEventListener('click', () => this.closeFolderBrowser());
221
+ selectBtn?.addEventListener('click', () => this.confirmFolderSelection());
222
+
223
+ this.folderBrowser.modal.addEventListener('click', (e) => {
224
+ if (e.target === this.folderBrowser.modal) this.closeFolderBrowser();
225
+ });
226
+
227
+ this.folderBrowser.homePathReady = this.fetchHomePath();
228
+ }
229
+
230
+ async fetchHomePath() {
231
+ try {
232
+ const res = await fetch(`${window.__BASE_URL || '/gm'}/api/home`);
233
+ const data = await res.json();
234
+ this.folderBrowser.homePath = data.home || '~';
235
+ this.folderBrowser.cwdPath = data.cwd || null;
236
+ } catch (e) {
237
+ console.error('Failed to fetch home path:', e);
238
+ }
239
+ }
240
+
241
+ async openFolderBrowser() {
242
+ window.dispatchEvent(new CustomEvent('preparing-new-conversation'));
243
+ if (!this.folderBrowser.modal) {
244
+ this.createNew();
245
+ return;
246
+ }
247
+ if (this.folderBrowser.homePathReady) {
248
+ await this.folderBrowser.homePathReady;
249
+ }
250
+ const startPath = this.folderBrowser.cwdPath || '~';
251
+ this.folderBrowser.currentPath = startPath;
252
+ this.folderBrowser.modal.classList.add('visible');
253
+ this.loadFolders(startPath);
254
+ }
255
+
256
+ closeFolderBrowser() {
257
+ this.folderBrowser.modal?.classList.remove('visible');
258
+ }
259
+
260
+ async loadFolders(dirPath) {
261
+ this.folderBrowser.currentPath = dirPath;
262
+ this.renderBreadcrumb(dirPath);
263
+
264
+ if (!this.folderBrowser.listEl) return;
265
+ this.folderBrowser.listEl.innerHTML = '<li class="folder-list-loading">Loading...</li>';
266
+
267
+ try {
268
+ const data = await window.wsClient.rpc('folders', { path: dirPath });
269
+ const folders = data.folders || [];
270
+
271
+ this.folderBrowser.listEl.innerHTML = '';
272
+
273
+ const isAtRoot = dirPath === '~' || dirPath === '/' || dirPath === this.folderBrowser.homePath || /^[A-Za-z]:[\\\/]?$/.test(dirPath);
274
+ if (!isAtRoot) {
275
+ const parentPath = this.getParentPath(dirPath);
276
+ const upItem = document.createElement('li');
277
+ upItem.className = 'folder-list-item';
278
+ upItem.innerHTML = '<span class="folder-list-item-icon">..</span><span class="folder-list-item-name">Parent Directory</span>';
279
+ upItem.addEventListener('click', () => this.loadFolders(parentPath));
280
+ this.folderBrowser.listEl.appendChild(upItem);
281
+ }
282
+
283
+ if (folders.length === 0 && this.folderBrowser.listEl.children.length === 0) {
284
+ this.folderBrowser.listEl.innerHTML = '<li class="folder-list-empty">No subdirectories</li>';
285
+ return;
286
+ }
287
+
288
+ for (const folder of folders) {
289
+ const li = document.createElement('li');
290
+ li.className = 'folder-list-item';
291
+ li.innerHTML = `<span class="folder-list-item-icon">&#128193;</span><span class="folder-list-item-name">${this.escapeHtml(folder.name)}</span>`;
292
+ li.addEventListener('click', () => {
293
+ const expandedBase = dirPath === '~' ? this.folderBrowser.homePath : dirPath;
294
+ const separator = expandedBase.includes('\\') ? '\\' : '/';
295
+ const base = expandedBase.replace(/[\/\\]+$/, '');
296
+ const newPath = base + separator + folder.name;
297
+ this.loadFolders(newPath);
298
+ });
299
+ this.folderBrowser.listEl.appendChild(li);
300
+ }
301
+ } catch (err) {
302
+ console.error('Failed to load folders:', err);
303
+ this.folderBrowser.listEl.innerHTML = `<li class="folder-list-error">Error: ${this.escapeHtml(err.message)}</li>`;
304
+ }
305
+ }
306
+
307
+ getParentPath(dirPath) {
308
+ const expanded = dirPath === '~' ? this.folderBrowser.homePath : dirPath;
309
+ const parts = pathSplit(expanded);
310
+ const isWindows = expanded.includes('\\') || /^[A-Za-z]:/.test(expanded);
311
+ const separator = isWindows ? '\\' : '/';
312
+ if (parts.length <= 1) {
313
+ return isWindows && parts[0] && parts[0].endsWith(':') ? parts[0] + separator : separator;
314
+ }
315
+ parts.pop();
316
+ if (isWindows) {
317
+ const joined = parts.join(separator);
318
+ return parts.length === 1 && parts[0].endsWith(':') ? joined + separator : joined;
319
+ }
320
+ return separator + parts.join(separator);
321
+ }
322
+
323
+ renderBreadcrumb(dirPath) {
324
+ if (!this.folderBrowser.breadcrumbEl) return;
325
+
326
+ const expanded = dirPath === '~' ? this.folderBrowser.homePath : dirPath;
327
+ const parts = pathSplit(expanded);
328
+ const isWin = expanded.includes('\\') || /^[A-Za-z]:/.test(expanded);
329
+ const separator = isWin ? '\\' : '/';
330
+ const rootPath = isWin && parts[0] && /^[A-Za-z]:$/.test(parts[0]) ? parts[0] + separator : separator;
331
+
332
+ let html = '';
333
+ html += `<span class="folder-breadcrumb-segment" data-path="${this.escapeHtml(rootPath)}">${this.escapeHtml(rootPath)} </span>`;
334
+
335
+ let accumulated = '';
336
+ const isDriveLetter = isWin && parts[0] && /^[A-Za-z]:$/.test(parts[0]);
337
+ for (let i = 0; i < parts.length; i++) {
338
+ if (i === 0 && isDriveLetter) {
339
+ accumulated = parts[0];
340
+ } else {
341
+ accumulated += separator + parts[i];
342
+ }
343
+ const segPath = (i === 0 && isDriveLetter) ? rootPath : accumulated;
344
+ const isLast = i === parts.length - 1;
345
+ html += `<span class="folder-breadcrumb-separator">${separator}</span>`;
346
+ html += `<span class="folder-breadcrumb-segment${isLast ? '' : ''}" data-path="${this.escapeHtml(segPath)}">${this.escapeHtml(parts[i])}</span>`;
347
+ }
348
+
349
+ this.folderBrowser.breadcrumbEl.innerHTML = html;
350
+
351
+ this.folderBrowser.breadcrumbEl.querySelectorAll('.folder-breadcrumb-segment').forEach(seg => {
352
+ seg.addEventListener('click', () => {
353
+ const p = seg.dataset.path;
354
+ if (p) this.loadFolders(p);
355
+ });
356
+ });
357
+ }
358
+
359
+ confirmFolderSelection() {
360
+ const currentPath = this.folderBrowser.currentPath;
361
+ const expanded = currentPath === '~' ? this.folderBrowser.homePath : currentPath;
362
+ this.closeFolderBrowser();
363
+
364
+ const dirName = pathBasename(expanded) || 'root';
365
+ window.dispatchEvent(new CustomEvent('create-new-conversation', {
366
+ detail: { workingDirectory: expanded, title: dirName }
367
+ }));
368
+ }
369
+
370
+ setupDeleteAllButton() {
371
+ this.deleteAllBtn = document.getElementById('deleteAllConversationsBtn');
372
+ if (!this.deleteAllBtn) return;
373
+ this.deleteAllBtn.addEventListener('click', () => this.confirmDeleteAll());
374
+ }
375
+
376
+ async confirmDeleteAll() {
377
+ if (this.conversations.length === 0) {
378
+ window.UIDialog.alert('No conversations to delete', 'Information');
379
+ return;
380
+ }
381
+
382
+ const confirmed = await window.UIDialog.confirm(
383
+ `Delete all ${this.conversations.length} conversation(s) and associated Claude Code artifacts?\n\nThis action cannot be undone.`,
384
+ 'Delete All Conversations'
385
+ );
386
+ if (!confirmed) return;
387
+
388
+ try {
389
+ this.deleteAllBtn.disabled = true;
390
+ await window.wsClient.rpc('conv.del.all', {});
391
+ console.log('[ConversationManager] Deleted all conversations');
392
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'CLEAR_ALL' });
393
+ window.ConversationState?.clear('delete_all');
394
+ window.dispatchEvent(new CustomEvent('conversation-deselected'));
395
+ this.render();
396
+ } catch (err) {
397
+ console.error('[ConversationManager] Delete all error:', err);
398
+ window.UIDialog.alert('Failed to delete all conversations: ' + (err.message || 'Unknown error'), 'Error');
399
+ } finally {
400
+ this.deleteAllBtn.disabled = false;
401
+ }
402
+ }
403
+
404
+ setupCloneUI() {
405
+ this.cloneBtn = document.getElementById('cloneRepoBtn');
406
+ this.cloneBar = document.getElementById('cloneInputBar');
407
+ this.cloneInput = document.getElementById('cloneRepoInput');
408
+ this.cloneGoBtn = document.getElementById('cloneGoBtn');
409
+ this.cloneCancelBtn = document.getElementById('cloneCancelBtn');
410
+
411
+ if (!this.cloneBtn || !this.cloneBar) return;
412
+
413
+ this.cloneBtn.addEventListener('click', () => this.toggleCloneBar());
414
+
415
+ this.cloneCancelBtn?.addEventListener('click', () => this.hideCloneBar());
416
+
417
+ this.cloneGoBtn?.addEventListener('click', () => this.performClone());
418
+
419
+ this.cloneInput?.addEventListener('keydown', (e) => {
420
+ if (e.key === 'Enter') this.performClone();
421
+ if (e.key === 'Escape') this.hideCloneBar();
422
+ });
423
+ }
424
+
425
+ toggleCloneBar() {
426
+ if (!this.cloneBar) return;
427
+ const visible = this.cloneBar.style.display !== 'none';
428
+ if (visible) {
429
+ this.hideCloneBar();
430
+ } else {
431
+ this.cloneBar.style.display = 'flex';
432
+ this.cloneInput.value = '';
433
+ this.cloneInput.focus();
434
+ this.removeCloneStatus();
435
+ }
436
+ }
437
+
438
+ hideCloneBar() {
439
+ if (this.cloneBar) this.cloneBar.style.display = 'none';
440
+ this.removeCloneStatus();
441
+ }
442
+
443
+ removeCloneStatus() {
444
+ const existing = this.sidebarEl?.querySelector('.clone-status');
445
+ if (existing) existing.remove();
446
+ }
447
+
448
+ showCloneStatus(message, type) {
449
+ this.removeCloneStatus();
450
+ const statusEl = document.createElement('div');
451
+ statusEl.className = `clone-status ${type}`;
452
+ statusEl.textContent = message;
453
+ if (this.cloneBar && this.cloneBar.parentNode) {
454
+ this.cloneBar.parentNode.insertBefore(statusEl, this.cloneBar.nextSibling);
455
+ }
456
+ if (type === 'clone-success' || type === 'clone-error') {
457
+ setTimeout(() => statusEl.remove(), 5000);
458
+ }
459
+ }
460
+
461
+ async performClone() {
462
+ const repo = (this.cloneInput?.value || '').trim();
463
+ if (!repo) return;
464
+ if (!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo)) {
465
+ this.showCloneStatus('Invalid format. Use org/repo', 'clone-error');
466
+ return;
467
+ }
468
+
469
+ this.cloneGoBtn.disabled = true;
470
+ this.cloneInput.disabled = true;
471
+ this.showCloneStatus(`Cloning ${repo}...`, 'cloning');
472
+
473
+ try {
474
+ const data = await window.wsClient.rpc('clone', { repo });
475
+
476
+ this.showCloneStatus(`Cloned ${data.name}`, 'clone-success');
477
+ this.hideCloneBar();
478
+
479
+ window.dispatchEvent(new CustomEvent('create-new-conversation', {
480
+ detail: { workingDirectory: data.path, title: data.name }
481
+ }));
482
+ } catch (err) {
483
+ this.showCloneStatus(err.message || 'Clone failed', 'clone-error');
484
+ } finally {
485
+ if (this.cloneGoBtn) this.cloneGoBtn.disabled = false;
486
+ if (this.cloneInput) this.cloneInput.disabled = false;
487
+ }
488
+ }
489
+
490
+ showLoading() {
491
+ if (!this.listEl) return;
492
+ this.listEl.innerHTML = '';
493
+ if (this.emptyEl) {
494
+ this.emptyEl.textContent = 'Loading...';
495
+ this.emptyEl.style.display = 'block';
496
+ }
497
+ }
498
+
499
+ async loadConversations() {
500
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'LOAD_START' });
501
+ try {
502
+ const base = window.__BASE_URL || '/gm';
503
+ const res = await fetch(base + '/api/conversations');
504
+ if (!res.ok) throw new Error('HTTP ' + res.status);
505
+ const data = await res.json();
506
+ const convList = data.conversations || [];
507
+
508
+ if (window.convListMachineAPI) {
509
+ window.convListMachineAPI.send({ type: 'LOAD_DONE', conversations: convList });
510
+ }
511
+
512
+ const clientStreamingMap = window.agentGuiClient?.state?.streamingConversations;
513
+ for (const conv of this.conversations) {
514
+ const serverStreaming = conv.isStreaming === 1 || conv.isStreaming === true;
515
+ const clientStreaming = clientStreamingMap ? clientStreamingMap.has(conv.id) : false;
516
+ if (serverStreaming || clientStreaming) {
517
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'SET_STREAMING', id: conv.id });
518
+ } else {
519
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'CLEAR_STREAMING', id: conv.id });
520
+ }
521
+ }
522
+
523
+ this.render();
524
+ } catch (err) {
525
+ console.error('Failed to load conversations:', err);
526
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'LOAD_ERROR' });
527
+ if (this.conversations.length === 0) {
528
+ this.showEmpty('Failed to load conversations');
529
+ }
530
+ }
531
+ }
532
+
533
+ _convVnode(conv) {
534
+ const h = window.webjsx?.createElement;
535
+ if (!h) return null;
536
+ const isActive = conv.id === this.activeId;
537
+ const isStreaming = this.streamingConversations.has(conv.id);
538
+ const title = conv.title || `Conversation ${conv.id.slice(0, 8)}`;
539
+ const now = Date.now();
540
+ const ts = conv.updated_at || conv.created_at;
541
+ const tsMs = ts ? new Date(ts).getTime() : 0;
542
+ const diffMs = now - tsMs;
543
+ const diffMins = Math.floor(diffMs / 60000);
544
+ const diffHrs = Math.floor(diffMs / 3600000);
545
+ const diffDays = Math.floor(diffMs / 86400000);
546
+ let timestamp;
547
+ if (diffMins < 1) timestamp = 'just now';
548
+ else if (diffMins < 60) timestamp = diffMins + 'm ago';
549
+ else if (diffHrs < 24) timestamp = diffHrs + 'h ago';
550
+ else if (diffDays < 7) timestamp = diffDays + 'd ago';
551
+ else timestamp = ts ? new Date(ts).toLocaleDateString() : 'Unknown';
552
+ const agentColor = getAgentColor(conv.agentId || conv.agentType);
553
+ const agent = this.getAgentDisplayName(conv.agentId || conv.agentType);
554
+ const modelLabel = this.formatModelLabel(conv.model);
555
+ const wd = conv.workingDirectory ? pathBasename(conv.workingDirectory) : '';
556
+ const metaParts = [agent + modelLabel];
557
+ if (wd) metaParts.push(wd);
558
+ const badge = isStreaming
559
+ ? h('span', { class: 'conversation-streaming-badge', title: 'Streaming in progress' }, h('span', { class: 'streaming-dot' }))
560
+ : null;
561
+ const dragAttrs = conv.pinned ? { draggable: 'true', 'data-drag-conv': conv.id } : {};
562
+ return h('li', { class: 'conversation-item' + (isActive ? ' active' : '') + (conv.pinned ? ' pinned' : ''), 'data-conv-id': conv.id, ...dragAttrs },
563
+ h('div', { class: 'conversation-item-content' },
564
+ h('div', { class: 'conversation-item-title', style: 'display:flex;align-items:center;gap:0.375rem;' },
565
+ h('span', { class: 'agent-color-dot', style: `background:${agentColor}` }),
566
+ ...(badge ? [badge, title] : [title])
567
+ ),
568
+ h('div', { class: 'conversation-item-meta', style: 'display:flex;justify-content:space-between;' },
569
+ h('span', {}, metaParts.join(' \u2022 ')),
570
+ h('span', { style: 'font-size:0.7rem;color:var(--color-text-muted);flex-shrink:0;margin-left:0.5rem;' }, timestamp)
571
+ )
572
+ ),
573
+ h('input', { type: 'checkbox', class: 'conversation-item-checkbox', 'data-bulk-check': conv.id, title: 'Select for bulk action', onclick: 'event.stopPropagation()' }),
574
+ h('button', { class: 'conversation-item-export', title: 'Export as markdown', 'data-export-conv': conv.id },
575
+ h('svg', { width: '14', height: '14', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' },
576
+ h('path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }),
577
+ h('polyline', { points: '7 10 12 15 17 10' }),
578
+ h('line', { x1: '12', y1: '15', x2: '12', y2: '3' })
579
+ )
580
+ ),
581
+ h('button', { class: 'conversation-item-archive', title: 'Archive conversation', 'data-archive-conv': conv.id },
582
+ h('svg', { width: '14', height: '14', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' },
583
+ h('path', { d: 'M21 8v13H3V8' }),
584
+ h('path', { d: 'M1 3h22v5H1z' }),
585
+ h('path', { d: 'M10 12h4' })
586
+ )
587
+ ),
588
+ h('button', { class: 'conversation-item-delete', title: 'Delete conversation', 'data-delete-conv': conv.id },
589
+ h('svg', { width: '14', height: '14', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2' },
590
+ h('polyline', { points: '3 6 5 6 21 6' }),
591
+ h('path', { d: 'M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2' })
592
+ )
593
+ )
594
+ );
595
+ }
596
+
597
+ _getDateGroup(conv) {
598
+ const ts = conv.updated_at || conv.created_at;
599
+ if (!ts) return 'Older';
600
+ const now = new Date();
601
+ const d = new Date(ts);
602
+ const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
603
+ const yesterdayStart = new Date(todayStart - 86400000);
604
+ const weekStart = new Date(todayStart - 6 * 86400000);
605
+ if (d >= todayStart) return 'Today';
606
+ if (d >= yesterdayStart) return 'Yesterday';
607
+ if (d >= weekStart) return 'Last 7 days';
608
+ return 'Older';
609
+ }
610
+
611
+ render() {
612
+ if (!this.listEl) return;
613
+ if (this.conversations.length === 0) { this.showEmpty(); return; }
614
+ this.emptyEl.style.display = 'none';
615
+ const h = window.webjsx?.createElement;
616
+ const sorted = [...this.conversations].sort((a, b) => {
617
+ const aTs = a.updated_at || a.created_at || 0;
618
+ const bTs = b.updated_at || b.created_at || 0;
619
+ return new Date(bTs) - new Date(aTs);
620
+ });
621
+
622
+ // Pinned items float to top
623
+ const pinned = sorted.filter(c => c.pinned);
624
+ const unpinned = sorted.filter(c => !c.pinned);
625
+
626
+ if (h && window.webjsx?.applyDiff) {
627
+ const groups = ['Today', 'Yesterday', 'Last 7 days', 'Older'];
628
+ const grouped = {};
629
+ groups.forEach(g => { grouped[g] = []; });
630
+ unpinned.forEach(c => { const g = this._getDateGroup(c); if (grouped[g]) grouped[g].push(c); });
631
+
632
+ const vnodes = [];
633
+ pinned.forEach(c => { const vn = this._convVnode(c); if (vn) vnodes.push(vn); });
634
+ groups.forEach(group => {
635
+ if (grouped[group].length === 0) return;
636
+ vnodes.push(h('li', { class: 'conv-date-group-header', 'data-group': group }, group));
637
+ grouped[group].forEach(c => { const vn = this._convVnode(c); if (vn) vnodes.push(vn); });
638
+ });
639
+ window.webjsx.applyDiff(this.listEl, vnodes);
640
+ } else {
641
+ this._renderFallback(sorted);
642
+ }
643
+ }
644
+
645
+ _renderFallback(sorted) {
646
+ const existingMap = {};
647
+ for (const child of Array.from(this.listEl.children)) {
648
+ if (child.dataset.convId) existingMap[child.dataset.convId] = child;
649
+ }
650
+ const frag = document.createDocumentFragment();
651
+ for (const conv of sorted) {
652
+ const el = existingMap[conv.id] || document.createElement('li');
653
+ el.className = 'conversation-item' + (conv.id === this.activeId ? ' active' : '');
654
+ el.dataset.convId = conv.id;
655
+ delete existingMap[conv.id];
656
+ frag.appendChild(el);
657
+ }
658
+ for (const orphan of Object.values(existingMap)) orphan.remove();
659
+ this.listEl.appendChild(frag);
660
+ }
661
+
662
+ async confirmDelete(convId, title) {
663
+ const confirmed = await window.UIDialog.confirm(
664
+ `Delete conversation "${title || 'Untitled'}"?\n\nThis will also delete any associated Claude Code session data. This action cannot be undone.`,
665
+ 'Delete Conversation'
666
+ );
667
+ if (!confirmed) return;
668
+
669
+ try {
670
+ await window.wsClient.rpc('conv.del', { id: convId });
671
+ console.log(`[ConversationManager] Deleted conversation ${convId}`);
672
+ this.deleteConversation(convId);
673
+ } catch (err) {
674
+ console.error('[ConversationManager] Delete error:', err);
675
+ window.UIDialog.alert('Failed to delete conversation: ' + (err.message || 'Unknown error'), 'Error');
676
+ }
677
+ }
678
+
679
+ select(convId) {
680
+ const result = window.ConversationState?.selectConversation(convId, 'user_click', 1) || { success: false };
681
+ if (!result.success && result.reason !== 'already_selected') {
682
+ console.error('[ConvMgr] activeId mutation rejected:', result.reason);
683
+ return;
684
+ }
685
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'SELECT', id: convId });
686
+
687
+ document.querySelectorAll('.conversation-item').forEach(item => {
688
+ item.classList.remove('active');
689
+ });
690
+
691
+ const active = document.querySelector(`[data-conv-id="${convId}"]`);
692
+ if (active) active.classList.add('active');
693
+
694
+ window.dispatchEvent(new CustomEvent('conversation-selected', {
695
+ detail: { conversationId: convId }
696
+ }));
697
+ }
698
+
699
+ createNew() {
700
+ window.dispatchEvent(new CustomEvent('preparing-new-conversation'));
701
+ window.dispatchEvent(new CustomEvent('create-new-conversation'));
702
+ }
703
+
704
+ showEmpty(message = 'No conversations yet') {
705
+ if (!this.listEl) return;
706
+ this.listEl.innerHTML = '';
707
+ this.emptyEl.textContent = message;
708
+ this.emptyEl.style.display = 'block';
709
+ }
710
+
711
+ addConversation(conv) {
712
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'ADD', conversation: conv });
713
+ this.render();
714
+ }
715
+
716
+ updateConversation(convId, updates) {
717
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'UPDATE', conversation: Object.assign({ id: convId }, updates) });
718
+ this.render();
719
+ }
720
+
721
+ deleteConversation(convId) {
722
+ const wasActive = this.activeId === convId;
723
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'DELETE', id: convId });
724
+ if (wasActive) {
725
+ window.ConversationState?.deleteConversation(convId, 1);
726
+ window.dispatchEvent(new CustomEvent('conversation-deselected'));
727
+ }
728
+ this.render();
729
+ }
730
+
731
+ getSelectedIds() {
732
+ return [...this.listEl.querySelectorAll('.conversation-item-checkbox:checked')].map(cb => cb.dataset.bulkCheck);
733
+ }
734
+
735
+ async bulkArchive() {
736
+ const ids = this.getSelectedIds();
737
+ if (ids.length === 0) return;
738
+ if (!await window.UIDialog?.confirm(`Archive ${ids.length} conversation(s)?`, 'Bulk Archive')) return;
739
+ const base = window.__BASE_URL || '';
740
+ for (const id of ids) {
741
+ try { await fetch(`${base}/api/conversations/${id}/archive`, { method: 'POST' }); } catch (_) {}
742
+ this.deleteConversation(id);
743
+ }
744
+ }
745
+
746
+ async bulkDelete() {
747
+ const ids = this.getSelectedIds();
748
+ if (ids.length === 0) return;
749
+ if (!await window.UIDialog?.confirm(`Permanently delete ${ids.length} conversation(s)?`, 'Bulk Delete')) return;
750
+ for (const id of ids) {
751
+ this.confirmDelete(id, '');
752
+ }
753
+ }
754
+
755
+ async exportConversation(convId) {
756
+ try {
757
+ const result = await window.wsClient.rpc('conv.export', { id: convId, format: 'markdown' });
758
+ const blob = new Blob([result.markdown], { type: 'text/markdown' });
759
+ const url = URL.createObjectURL(blob);
760
+ const a = document.createElement('a');
761
+ a.href = url;
762
+ a.download = (result.title || 'conversation').replace(/[^a-zA-Z0-9_-]/g, '_') + '.md';
763
+ a.click();
764
+ URL.revokeObjectURL(url);
765
+ } catch (e) {
766
+ console.error('[export] Failed:', e.message);
767
+ }
768
+ }
769
+
770
+ async archiveConversation(convId) {
771
+ try {
772
+ const resp = await fetch(`${window.__BASE_URL || ''}/api/conversations/${convId}/archive`, { method: 'POST' });
773
+ if (!resp.ok) return;
774
+ this.deleteConversation(convId);
775
+ } catch (e) {
776
+ console.error('[archive] Failed:', e.message);
777
+ }
778
+ }
779
+
780
+ setupWebSocketListener() {
781
+ window.addEventListener('ws-message', (event) => {
782
+ const msg = event.detail;
783
+
784
+ if (msg.type === 'conversation_created') {
785
+ this.addConversation(msg.conversation);
786
+ } else if (msg.type === 'conversation_updated') {
787
+ this.updateConversation(msg.conversation.id, msg.conversation);
788
+ } else if (msg.type === 'conversation_deleted') {
789
+ this.deleteConversation(msg.conversationId);
790
+ } else if (msg.type === 'all_conversations_deleted') {
791
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'CLEAR_ALL' });
792
+ window.ConversationState?.clear('all_deleted');
793
+ this.showEmpty('No conversations yet');
794
+ } else if (msg.type === 'streaming_start' && msg.conversationId) {
795
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'SET_STREAMING', id: msg.conversationId });
796
+ this.render();
797
+ } else if ((msg.type === 'streaming_complete' || msg.type === 'streaming_error') && msg.conversationId) {
798
+ if (window.convListMachineAPI) window.convListMachineAPI.send({ type: 'CLEAR_STREAMING', id: msg.conversationId });
799
+ this.render();
800
+ }
801
+ });
802
+ }
803
+
112
804
  escapeHtml(text) {
113
805
  return window._escHtml(text);
114
806
  }
115
807
  }
116
808
 
809
+ if (document.readyState === 'loading') {
810
+ document.addEventListener('DOMContentLoaded', () => {
811
+ window.conversationManager = new ConversationManager();
812
+ });
813
+ } else {
814
+ window.conversationManager = new ConversationManager();
815
+ }