agentgui 1.0.274 → 1.0.276

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 (70) hide show
  1. package/CLAUDE.md +280 -280
  2. package/IPFS_DOWNLOADER.md +277 -277
  3. package/TASK_2C_COMPLETION.md +334 -334
  4. package/agentgui.ico +0 -0
  5. package/bin/gmgui.cjs +54 -54
  6. package/build-portable.js +13 -42
  7. package/database.js +1422 -1406
  8. package/lib/claude-runner.js +1130 -1130
  9. package/lib/ipfs-downloader.js +459 -459
  10. package/lib/speech.js +159 -152
  11. package/package.json +1 -1
  12. package/readme.md +76 -76
  13. package/server.js +3787 -3794
  14. package/setup-npm-token.sh +68 -68
  15. package/static/app.js +773 -773
  16. package/static/event-rendering-showcase.html +708 -708
  17. package/static/index.html +3178 -3180
  18. package/static/js/agent-auth.js +298 -298
  19. package/static/js/audio-recorder-processor.js +18 -18
  20. package/static/js/client.js +2656 -2656
  21. package/static/js/conversations.js +583 -583
  22. package/static/js/dialogs.js +267 -267
  23. package/static/js/event-consolidator.js +101 -101
  24. package/static/js/event-filter.js +311 -311
  25. package/static/js/event-processor.js +452 -452
  26. package/static/js/features.js +413 -413
  27. package/static/js/kalman-filter.js +67 -67
  28. package/static/js/progress-dialog.js +130 -130
  29. package/static/js/script-runner.js +219 -219
  30. package/static/js/streaming-renderer.js +2123 -2120
  31. package/static/js/syntax-highlighter.js +269 -269
  32. package/static/js/tts-websocket-handler.js +152 -152
  33. package/static/js/ui-components.js +431 -431
  34. package/static/js/voice.js +849 -849
  35. package/static/js/websocket-manager.js +596 -596
  36. package/static/templates/INDEX.html +465 -465
  37. package/static/templates/README.md +190 -190
  38. package/static/templates/agent-capabilities.html +56 -56
  39. package/static/templates/agent-metadata-panel.html +44 -44
  40. package/static/templates/agent-status-badge.html +30 -30
  41. package/static/templates/code-annotation-panel.html +155 -155
  42. package/static/templates/code-suggestion-panel.html +184 -184
  43. package/static/templates/command-header.html +77 -77
  44. package/static/templates/command-output-scrollable.html +118 -118
  45. package/static/templates/elapsed-time.html +54 -54
  46. package/static/templates/error-alert.html +106 -106
  47. package/static/templates/error-history-timeline.html +160 -160
  48. package/static/templates/error-recovery-options.html +109 -109
  49. package/static/templates/error-stack-trace.html +95 -95
  50. package/static/templates/error-summary.html +80 -80
  51. package/static/templates/event-counter.html +48 -48
  52. package/static/templates/execution-actions.html +97 -97
  53. package/static/templates/execution-progress-bar.html +80 -80
  54. package/static/templates/execution-stepper.html +120 -120
  55. package/static/templates/file-breadcrumb.html +118 -118
  56. package/static/templates/file-diff-viewer.html +121 -121
  57. package/static/templates/file-metadata.html +133 -133
  58. package/static/templates/file-read-panel.html +66 -66
  59. package/static/templates/file-write-panel.html +120 -120
  60. package/static/templates/git-branch-remote.html +107 -107
  61. package/static/templates/git-diff-list.html +101 -101
  62. package/static/templates/git-log-visualization.html +153 -153
  63. package/static/templates/git-status-panel.html +115 -115
  64. package/static/templates/quality-metrics-display.html +170 -170
  65. package/static/templates/terminal-output-panel.html +87 -87
  66. package/static/templates/test-results-display.html +144 -144
  67. package/static/theme.js +72 -72
  68. package/test-download-progress.js +223 -223
  69. package/test-websocket-broadcast.js +147 -147
  70. package/tests/ipfs-downloader.test.js +370 -370
package/static/app.js CHANGED
@@ -1,773 +1,773 @@
1
- const BASE_URL = window.__BASE_URL || '';
2
-
3
- class ReconnectingWebSocket {
4
- constructor(url, options = {}) {
5
- this.url = url;
6
- this.reconnectDelay = options.reconnectDelay || 1000;
7
- this.maxReconnectDelay = options.maxReconnectDelay || 30000;
8
- this.reconnectDecay = options.reconnectDecay || 1.5;
9
- this.currentDelay = this.reconnectDelay;
10
- this.ws = null;
11
- this.listeners = new Map();
12
- this.reconnectAttempts = 0;
13
- this.maxReconnectAttempts = options.maxReconnectAttempts || Infinity;
14
- this.shouldReconnect = true;
15
- this.connect();
16
- }
17
-
18
- connect() {
19
- this.ws = new WebSocket(this.url);
20
-
21
- this.ws.onopen = (e) => {
22
- this.currentDelay = this.reconnectDelay;
23
- this.reconnectAttempts = 0;
24
- this.emit('open', e);
25
- };
26
-
27
- this.ws.onmessage = (e) => {
28
- this.emit('message', e);
29
- };
30
-
31
- this.ws.onerror = (e) => {
32
- this.emit('error', e);
33
- };
34
-
35
- this.ws.onclose = (e) => {
36
- this.emit('close', e);
37
- if (this.shouldReconnect && this.reconnectAttempts < this.maxReconnectAttempts) {
38
- setTimeout(() => {
39
- this.reconnectAttempts++;
40
- this.currentDelay = Math.min(
41
- this.currentDelay * this.reconnectDecay,
42
- this.maxReconnectDelay
43
- );
44
- console.log(`Attempting to reconnect (${this.reconnectAttempts})...`);
45
- this.connect();
46
- }, this.currentDelay);
47
- }
48
- };
49
- }
50
-
51
- on(event, callback) {
52
- if (!this.listeners.has(event)) {
53
- this.listeners.set(event, []);
54
- }
55
- this.listeners.get(event).push(callback);
56
- }
57
-
58
- emit(event, data) {
59
- const callbacks = this.listeners.get(event);
60
- if (callbacks) {
61
- callbacks.forEach(cb => cb(data));
62
- }
63
- }
64
-
65
- send(data) {
66
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
67
- this.ws.send(data);
68
- }
69
- }
70
-
71
- close() {
72
- this.shouldReconnect = false;
73
- if (this.ws) {
74
- this.ws.close();
75
- }
76
- }
77
- }
78
-
79
- class GMGUIApp {
80
- constructor() {
81
- this.conversations = new Map();
82
- this.currentConversation = null;
83
- this.agents = new Map();
84
- this.selectedAgent = null;
85
- this.ws = null;
86
- }
87
-
88
- async init() {
89
- console.log('[APP] Initializing');
90
-
91
- this.setupEventListeners();
92
- await this.fetchAgents();
93
-
94
- const savedAgent = localStorage.getItem('gmgui-selectedAgent');
95
- if (savedAgent && this.agents.has(savedAgent)) {
96
- this.selectedAgent = savedAgent;
97
- } else if (this.agents.size > 0) {
98
- this.selectedAgent = Array.from(this.agents.keys())[0];
99
- localStorage.setItem('gmgui-selectedAgent', this.selectedAgent);
100
- }
101
-
102
- await this.fetchConversations();
103
- this.connectWebSocket();
104
- this.renderAll();
105
- console.log('[APP] Ready');
106
- }
107
-
108
- async fetchAgents() {
109
- try {
110
- const res = await fetch(BASE_URL + '/api/agents');
111
- const data = await res.json();
112
- for (const agent of data.agents || []) {
113
- this.agents.set(agent.id, agent);
114
- }
115
- } catch (e) {
116
- console.error('[APP] Error fetching agents:', e);
117
- }
118
- }
119
-
120
- async fetchConversations() {
121
- try {
122
- const res = await fetch(BASE_URL + '/api/conversations');
123
- const data = await res.json();
124
- this.conversations.clear();
125
- for (const conv of data.conversations || []) {
126
- this.conversations.set(conv.id, conv);
127
- }
128
- console.log('[APP] Loaded', this.conversations.size, 'conversations');
129
- } catch (e) {
130
- console.error('[APP] Error fetching conversations:', e);
131
- }
132
- }
133
-
134
- async fetchMessages(conversationId) {
135
- try {
136
- const res = await fetch(BASE_URL + `/api/conversations/${conversationId}/messages`);
137
- const data = await res.json();
138
- return data.messages || [];
139
- } catch (e) {
140
- console.error('[APP] Error fetching messages:', e);
141
- return [];
142
- }
143
- }
144
-
145
- connectWebSocket() {
146
- const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
147
- this.ws = new ReconnectingWebSocket(`${proto}//${location.host}${BASE_URL}/sync`);
148
-
149
- this.ws.on('open', () => {
150
- console.log('[WS] Connected');
151
- document.getElementById('connectionStatus').textContent = 'Connected';
152
- });
153
-
154
- this.ws.on('message', (e) => {
155
- try {
156
- const event = JSON.parse(e.data);
157
- this.handleEvent(event);
158
- } catch (err) {
159
- console.error('[WS] Parse error:', err);
160
- }
161
- });
162
-
163
- this.ws.on('close', () => {
164
- console.log('[WS] Disconnected, reconnecting...');
165
- document.getElementById('connectionStatus').textContent = 'Reconnecting...';
166
- });
167
-
168
- this.ws.on('error', (err) => {
169
- console.error('[WS] Error:', err);
170
- document.getElementById('connectionStatus').textContent = 'Error';
171
- });
172
- }
173
-
174
- handleEvent(event) {
175
- if (event.type === 'message_created') {
176
- this.handleMessageReceived(event.message);
177
- } else if (event.type === 'conversations_updated') {
178
- this.fetchConversations().then(() => this.renderChatHistory());
179
- }
180
- }
181
-
182
- addMessageToDisplay(message) {
183
- if (this.currentConversation && message.conversationId === this.currentConversation) {
184
- const chatDiv = document.getElementById('chatMessages');
185
- if (!chatDiv) return;
186
-
187
- const msgEl = document.createElement('div');
188
- msgEl.className = `message ${message.role}`;
189
-
190
- // Try to parse content as JSON for structured display
191
- let contentHtml = '';
192
- try {
193
- const parsed = typeof message.content === 'string' ? JSON.parse(message.content) : message.content;
194
- if (parsed && parsed.type === 'claude_execution' && parsed.blocks) {
195
- // Render each block with appropriate formatting
196
- contentHtml = '<div class="execution-blocks">';
197
- for (const block of parsed.blocks) {
198
- contentHtml += this.renderMessageBlock(block);
199
- }
200
- contentHtml += '</div>';
201
- } else {
202
- throw new Error('Not a claude_execution message');
203
- }
204
- } catch (e) {
205
- // Fallback: try to parse and beautify, or render as plain text
206
- try {
207
- const parsed = typeof message.content === 'string' ? JSON.parse(message.content) : message.content;
208
- contentHtml = `<div class="message-content">${this.renderParameters(parsed)}</div>`;
209
- } catch (parseErr) {
210
- const text = typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
211
- contentHtml = `<div class="message-content"><pre>${this.escapeHtml(text)}</pre></div>`;
212
- }
213
- }
214
-
215
- msgEl.innerHTML = contentHtml;
216
- chatDiv.appendChild(msgEl);
217
- chatDiv.scrollTop = chatDiv.scrollHeight;
218
- }
219
- }
220
-
221
- renderMessageBlock(block) {
222
- if (!block) return '';
223
-
224
- let html = '<div class="message-block">';
225
-
226
- switch (block.type) {
227
- case 'text': {
228
- const text = block.text || '';
229
- const beautified = this.markdownToHtml(text);
230
- html += `<div class="block-text">${beautified}</div>`;
231
- break;
232
- }
233
-
234
- case 'tool_use': {
235
- html += `<div class="block-tool-use">`;
236
- html += `<strong class="tool-name">${this.escapeHtml(block.name || 'Tool')}</strong>`;
237
- const paramHtml = this.renderParameters(block.input || {});
238
- html += `<div class="tool-input">${paramHtml}</div>`;
239
- html += `</div>`;
240
- break;
241
- }
242
-
243
- case 'tool_result': {
244
- html += `<div class="block-tool-result">`;
245
- html += `<strong>Result:</strong>`;
246
- let resultHtml;
247
- if (typeof block.result === 'string') {
248
- try {
249
- const parsed = JSON.parse(block.result);
250
- resultHtml = this.renderParameters(parsed);
251
- } catch (e) {
252
- resultHtml = `<pre>${this.escapeHtml(block.result)}</pre>`;
253
- }
254
- } else {
255
- resultHtml = this.renderParameters(block.result);
256
- }
257
- html += `<div class="tool-result">${resultHtml}</div>`;
258
- html += `</div>`;
259
- break;
260
- }
261
-
262
- case 'file_operation':
263
- html += `<div class="block-file-op">`;
264
- html += `<strong class="file-action">${this.escapeHtml(block.action || 'File Operation')}</strong>`;
265
- html += `<div class="file-path">${this.escapeHtml(block.path || '')}</div>`;
266
- if (block.content) {
267
- html += `<div class="file-content"><pre>${this.escapeHtml(block.content.substring(0, 500))}</pre></div>`;
268
- }
269
- html += `</div>`;
270
- break;
271
-
272
- default:
273
- html += `<div class="block-unknown">${this.escapeHtml(JSON.stringify(block, null, 2))}</div>`;
274
- }
275
-
276
- html += '</div>';
277
- return html;
278
- }
279
-
280
- handleMessageReceived(message) {
281
- if (message.role === 'user') {
282
- document.getElementById('messageInput').value = '';
283
- document.getElementById('messageInput').focus();
284
- }
285
- }
286
-
287
- async sendMessage() {
288
- const input = document.getElementById('messageInput');
289
- const content = input.value.trim();
290
-
291
- if (!content || !this.currentConversation || !this.selectedAgent) return;
292
-
293
- try {
294
- const res = await fetch(BASE_URL + `/api/conversations/${this.currentConversation}/messages`, {
295
- method: 'POST',
296
- headers: { 'Content-Type': 'application/json' },
297
- body: JSON.stringify({
298
- content,
299
- agentId: this.selectedAgent
300
- })
301
- });
302
-
303
- if (res.ok) {
304
- input.value = '';
305
- }
306
- } catch (e) {
307
- console.error('[APP] Error sending message:', e);
308
- }
309
- }
310
-
311
- async createConversation(title = 'New Conversation') {
312
- if (!this.selectedAgent) {
313
- console.error('[APP] No agent selected');
314
- return;
315
- }
316
-
317
- try {
318
- const res = await fetch(BASE_URL + '/api/conversations', {
319
- method: 'POST',
320
- headers: { 'Content-Type': 'application/json' },
321
- body: JSON.stringify({ title, agentId: this.selectedAgent })
322
- });
323
-
324
- if (res.ok) {
325
- const data = await res.json();
326
- await this.fetchConversations();
327
- this.renderChatHistory();
328
- if (data.conversation) {
329
- this.selectConversation(data.conversation.id);
330
- }
331
- }
332
- } catch (e) {
333
- console.error('[APP] Error creating conversation:', e);
334
- }
335
- }
336
-
337
- selectConversation(convId) {
338
- this.currentConversation = convId;
339
- document.querySelectorAll('.chat-item').forEach(el => el.classList.remove('active'));
340
- const el = document.querySelector(`[data-conv-id="${convId}"]`);
341
- if (el) el.classList.add('active');
342
- this.renderChatMessages();
343
- }
344
-
345
- async renderChatMessages() {
346
- const chatDiv = document.getElementById('chatMessages');
347
- if (!chatDiv || !this.currentConversation) return;
348
-
349
- chatDiv.innerHTML = '';
350
- const messages = await this.fetchMessages(this.currentConversation);
351
- for (const msg of messages) {
352
- const msgEl = document.createElement('div');
353
- msgEl.className = `message ${msg.role}`;
354
-
355
- // Try to parse content as JSON for structured display
356
- let contentHtml = '';
357
- try {
358
- const parsed = typeof msg.content === 'string' ? JSON.parse(msg.content) : msg.content;
359
- if (parsed && parsed.type === 'claude_execution' && parsed.blocks) {
360
- // Render each block with appropriate formatting
361
- contentHtml = '<div class="execution-blocks">';
362
- for (const block of parsed.blocks) {
363
- contentHtml += this.renderMessageBlock(block);
364
- }
365
- contentHtml += '</div>';
366
- } else {
367
- throw new Error('Not a claude_execution message');
368
- }
369
- } catch (e) {
370
- // Fallback: try to parse and beautify, or render as plain text
371
- try {
372
- const parsed = typeof msg.content === 'string' ? JSON.parse(msg.content) : msg.content;
373
- contentHtml = `<div class="message-content">${this.renderParameters(parsed)}</div>`;
374
- } catch (parseErr) {
375
- const text = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content);
376
- contentHtml = `<div class="message-content"><pre>${this.escapeHtml(text)}</pre></div>`;
377
- }
378
- }
379
-
380
- msgEl.innerHTML = contentHtml;
381
- chatDiv.appendChild(msgEl);
382
- }
383
- }
384
-
385
- renderChatHistory() {
386
- const list = document.getElementById('chatList');
387
- if (!list) return;
388
-
389
- list.innerHTML = '';
390
- const convs = Array.from(this.conversations.values())
391
- .sort((a, b) => (b.updated_at || 0) - (a.updated_at || 0));
392
-
393
- for (const conv of convs) {
394
- const el = document.createElement('div');
395
- el.className = 'chat-item';
396
- el.setAttribute('data-conv-id', conv.id);
397
- el.innerHTML = `<div class="chat-item-title">${this.escapeHtml(conv.title || 'Untitled')}</div>`;
398
- el.onclick = () => this.selectConversation(conv.id);
399
- list.appendChild(el);
400
- }
401
- }
402
-
403
- renderAll() {
404
- this.renderChatHistory();
405
- if (this.conversations.size > 0 && !this.currentConversation) {
406
- const firstConv = Array.from(this.conversations.values())[0];
407
- this.selectConversation(firstConv.id);
408
- }
409
- }
410
-
411
- setupEventListeners() {
412
- const sendBtn = document.getElementById('sendBtn');
413
- if (sendBtn) {
414
- sendBtn.onclick = () => this.sendMessage();
415
- }
416
-
417
- const input = document.getElementById('messageInput');
418
- if (input) {
419
- input.addEventListener('keypress', (e) => {
420
- if (e.key === 'Enter' && !e.shiftKey) {
421
- e.preventDefault();
422
- this.sendMessage();
423
- }
424
- });
425
- }
426
-
427
- const newConvBtn = document.getElementById('newConversationBtn');
428
- if (newConvBtn) {
429
- newConvBtn.onclick = () => this.createConversation();
430
- }
431
- }
432
-
433
- parseMarkdownCodeBlocks(text) {
434
- const parts = [];
435
- const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
436
- let lastIndex = 0;
437
- let match;
438
-
439
- while ((match = codeBlockRegex.exec(text)) !== null) {
440
- // Add text before code block
441
- if (match.index > lastIndex) {
442
- parts.push({
443
- type: 'text',
444
- content: text.substring(lastIndex, match.index)
445
- });
446
- }
447
-
448
- // Add code block
449
- const language = match[1] || 'text';
450
- const code = match[2];
451
- parts.push({
452
- type: 'code',
453
- language,
454
- content: code
455
- });
456
-
457
- lastIndex = codeBlockRegex.lastIndex;
458
- }
459
-
460
- // Add remaining text
461
- if (lastIndex < text.length) {
462
- parts.push({
463
- type: 'text',
464
- content: text.substring(lastIndex)
465
- });
466
- }
467
-
468
- return parts.length > 0 ? parts : [{ type: 'text', content: text }];
469
- }
470
-
471
- markdownToHtml(markdown) {
472
- const lines = markdown.split('\n');
473
- let html = '';
474
- let inList = false;
475
- let listType = null;
476
- let i = 0;
477
-
478
- while (i < lines.length) {
479
- const line = lines[i];
480
- const trimmed = line.trim();
481
-
482
- // Code blocks
483
- if (trimmed.startsWith('```')) {
484
- if (inList) {
485
- html += listType === 'ul' ? '</ul>' : '</ol>';
486
- inList = false;
487
- }
488
- const match = trimmed.match(/^```(\w*)/);
489
- const lang = (match && match[1]) || 'text';
490
- i++;
491
- const codeLines = [];
492
- while (i < lines.length && !lines[i].trim().startsWith('```')) {
493
- codeLines.push(lines[i]);
494
- i++;
495
- }
496
- const clCount = codeLines.length;
497
- html += `<details class="collapsible-code"><summary class="collapsible-code-summary">${this.escapeHtml(lang)} - ${clCount} line${clCount !== 1 ? 's' : ''}</summary><div class="code-block" data-language="${this.escapeHtml(lang)}"><pre><code>${this.escapeHtml(codeLines.join('\n'))}</code></pre></div></details>`;
498
- i++;
499
- continue;
500
- }
501
-
502
- // Headings
503
- if (trimmed.startsWith('#')) {
504
- if (inList) {
505
- html += listType === 'ul' ? '</ul>' : '</ol>';
506
- inList = false;
507
- }
508
- const match = trimmed.match(/^(#+)\s+(.*)/);
509
- if (match) {
510
- const level = match[1].length;
511
- const text = this.escapeAndFormatInline(match[2]);
512
- html += `<h${level}>${text}</h${level}>`;
513
- i++;
514
- continue;
515
- }
516
- }
517
-
518
- // Lists
519
- if (trimmed.match(/^[-*+]\s/)) {
520
- if (!inList) {
521
- html += '<ul>';
522
- inList = true;
523
- listType = 'ul';
524
- }
525
- const match = trimmed.match(/^[-*+]\s+(.*)/);
526
- if (match) {
527
- const text = this.escapeAndFormatInline(match[1]);
528
- html += `<li>${text}</li>`;
529
- }
530
- i++;
531
- continue;
532
- }
533
-
534
- if (trimmed.match(/^\d+\.\s/)) {
535
- if (!inList || listType !== 'ol') {
536
- if (inList) html += '</ul>';
537
- html += '<ol>';
538
- inList = true;
539
- listType = 'ol';
540
- }
541
- const match = trimmed.match(/^\d+\.\s+(.*)/);
542
- if (match) {
543
- const text = this.escapeAndFormatInline(match[1]);
544
- html += `<li>${text}</li>`;
545
- }
546
- i++;
547
- continue;
548
- }
549
-
550
- // End list if not a list item
551
- if (inList && trimmed && !trimmed.match(/^[-*+]\s/) && !trimmed.match(/^\d+\.\s/)) {
552
- html += listType === 'ul' ? '</ul>' : '</ol>';
553
- inList = false;
554
- }
555
-
556
- // Paragraphs
557
- if (trimmed) {
558
- const text = this.escapeAndFormatInline(trimmed);
559
- html += `<p>${text}</p>`;
560
- }
561
-
562
- i++;
563
- }
564
-
565
- // Close any open list
566
- if (inList) {
567
- html += listType === 'ul' ? '</ul>' : '</ol>';
568
- }
569
-
570
- return html;
571
- }
572
-
573
- escapeAndFormatInline(text) {
574
- text = this.escapeHtml(text);
575
- // Bold and italic (must be before single asterisk)
576
- text = text.replace(/\*\*\*(.*?)\*\*\*/g, '<strong><em>$1</em></strong>');
577
- text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
578
- text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
579
- text = text.replace(/__(.*?)__/g, '<strong>$1</strong>');
580
- text = text.replace(/_(.*?)_/g, '<em>$1</em>');
581
- // Inline code
582
- text = text.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');
583
- // Links
584
- text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
585
- return text;
586
- }
587
-
588
- renderCodeBlock(language, code) {
589
- if (language === 'html') {
590
- return `<div class="html-block">
591
- <div class="html-header">Rendered HTML</div>
592
- <div class="html-content">${code}</div>
593
- </div>`;
594
- } else {
595
- const lcCount = code.split('\n').length;
596
- return `<details class="collapsible-code"><summary class="collapsible-code-summary">${this.escapeHtml(language)} - ${lcCount} line${lcCount !== 1 ? 's' : ''}</summary><div class="code-block" data-language="${this.escapeHtml(language)}">
597
- <pre><code>${this.escapeHtml(code)}</code></pre>
598
- </div></details>`;
599
- }
600
- }
601
-
602
- escapeHtml(text) {
603
- const div = document.createElement('div');
604
- div.textContent = text;
605
- return div.innerHTML;
606
- }
607
-
608
- renderParameters(obj, depth = 0) {
609
- if (obj === null || obj === undefined) {
610
- return `<span style="color: var(--text-tertiary);">null</span>`;
611
- }
612
-
613
- if (typeof obj === 'string') {
614
- const isPath = obj.includes('/') || obj.includes('\\');
615
- const isUrl = obj.startsWith('http://') || obj.startsWith('https://');
616
- if (isPath || isUrl) {
617
- return `<code style="color: var(--text-secondary); background: transparent;">${this.escapeHtml(obj)}</code>`;
618
- }
619
- return `<span>"${this.escapeHtml(obj)}"</span>`;
620
- }
621
-
622
- if (typeof obj === 'number' || typeof obj === 'boolean') {
623
- return `<span style="color: var(--color-info);">${obj}</span>`;
624
- }
625
-
626
- if (Array.isArray(obj)) {
627
- if (obj.length === 0) {
628
- return `<span style="color: var(--text-tertiary);">[]</span>`;
629
- }
630
- const maxItems = depth === 0 ? 10 : 5;
631
- const items = obj.slice(0, maxItems).map(item => this.renderParameters(item, depth + 1));
632
- const more = obj.length > maxItems ? `<span style="color: var(--text-tertiary);">... ${obj.length - maxItems} more</span>` : '';
633
- return `<span style="color: var(--text-tertiary);">[</span> ${items.join(', ')} ${more} <span style="color: var(--text-tertiary);">]</span>`;
634
- }
635
-
636
- if (typeof obj === 'object') {
637
- const keys = Object.keys(obj);
638
- if (keys.length === 0) {
639
- return `<span style="color: var(--text-tertiary);">{}</span>`;
640
- }
641
- const maxKeys = depth === 0 ? 15 : 8;
642
- const pairs = keys.slice(0, maxKeys).map(key => {
643
- const keyHtml = `<span style="color: var(--color-primary);">${this.escapeHtml(key)}</span>`;
644
- const valHtml = this.renderParameters(obj[key], depth + 1);
645
- return `${keyHtml}: ${valHtml}`;
646
- });
647
- const more = keys.length > maxKeys ? `<span style="color: var(--text-tertiary);">... ${keys.length - maxKeys} more</span>` : '';
648
- return `<div style="margin-left: ${depth * 1.5}rem;"><span style="color: var(--text-tertiary);">{</span><br/>${pairs.map(p => `&nbsp;&nbsp;${p}`).join(',<br/>')}<br/>${more}<span style="color: var(--text-tertiary);">}</span></div>`;
649
- }
650
-
651
- return `<span>${this.escapeHtml(String(obj))}</span>`;
652
- }
653
- }
654
-
655
- const app = new GMGUIApp();
656
-
657
- function initializeApp() {
658
- app.init().catch(err => {
659
- console.error('[CRITICAL] Failed to initialize app:', err);
660
- });
661
- }
662
-
663
- function sendMessage() {
664
- app.sendMessage();
665
- }
666
-
667
- function showNewChatModal() {
668
- const modal = document.getElementById('newChatModal');
669
- if (modal) {
670
- modal.style.display = 'flex';
671
- }
672
- }
673
-
674
- function closeNewChatModal() {
675
- const modal = document.getElementById('newChatModal');
676
- if (modal) {
677
- modal.style.display = 'none';
678
- }
679
- }
680
-
681
- async function createChatInWorkspace() {
682
- const title = await window.UIDialog.prompt('Enter a title for the conversation:', 'New Conversation', 'New Chat');
683
- if (title) {
684
- app.createConversation(title);
685
- closeNewChatModal();
686
- }
687
- }
688
-
689
- function createChatInFolder() {
690
- const folderModal = document.getElementById('folderBrowserModal');
691
- if (folderModal) {
692
- folderModal.style.display = 'flex';
693
- closeNewChatModal();
694
- }
695
- }
696
-
697
- function closeFolderBrowser() {
698
- const modal = document.getElementById('folderBrowserModal');
699
- if (modal) {
700
- modal.style.display = 'none';
701
- }
702
- }
703
-
704
- function confirmFolderSelection() {
705
- const folderPath = document.getElementById('folderPath')?.value;
706
- if (folderPath) {
707
- const title = `Chat in ${folderPath}`;
708
- app.createConversation(title);
709
- closeFolderBrowser();
710
- }
711
- }
712
-
713
- function browseFolders() {
714
- // Placeholder for folder browsing functionality
715
- console.log('Folder browsing not yet implemented');
716
- }
717
-
718
- function toggleSidebar() {
719
- const sidebar = document.getElementById('sidebar');
720
- if (sidebar) {
721
- sidebar.classList.toggle('collapsed');
722
- }
723
- }
724
-
725
- function switchTab(tab) {
726
- if (tab === 'settings') {
727
- const panel = document.getElementById('settingsPanel');
728
- if (panel) {
729
- panel.style.display = 'flex';
730
- }
731
- const main = document.querySelector('.main-content');
732
- if (main) {
733
- main.style.display = 'none';
734
- }
735
- } else if (tab === 'chat') {
736
- const panel = document.getElementById('settingsPanel');
737
- if (panel) {
738
- panel.style.display = 'none';
739
- }
740
- const main = document.querySelector('.main-content');
741
- if (main) {
742
- main.style.display = 'flex';
743
- }
744
- }
745
- }
746
-
747
- function triggerFileUpload() {
748
- const input = document.getElementById('fileInput');
749
- if (input) {
750
- input.click();
751
- }
752
- }
753
-
754
- function handleFileUpload() {
755
- console.log('File upload not yet implemented');
756
- }
757
-
758
- function closeScreenshotModal() {
759
- const modal = document.getElementById('screenshotModal');
760
- if (modal) {
761
- modal.style.display = 'none';
762
- }
763
- }
764
-
765
- function sendScreenshot() {
766
- console.log('Send screenshot not yet implemented');
767
- }
768
-
769
- function downloadScreenshot() {
770
- console.log('Download screenshot not yet implemented');
771
- }
772
-
773
- window.addEventListener('load', initializeApp);
1
+ const BASE_URL = window.__BASE_URL || '';
2
+
3
+ class ReconnectingWebSocket {
4
+ constructor(url, options = {}) {
5
+ this.url = url;
6
+ this.reconnectDelay = options.reconnectDelay || 1000;
7
+ this.maxReconnectDelay = options.maxReconnectDelay || 30000;
8
+ this.reconnectDecay = options.reconnectDecay || 1.5;
9
+ this.currentDelay = this.reconnectDelay;
10
+ this.ws = null;
11
+ this.listeners = new Map();
12
+ this.reconnectAttempts = 0;
13
+ this.maxReconnectAttempts = options.maxReconnectAttempts || Infinity;
14
+ this.shouldReconnect = true;
15
+ this.connect();
16
+ }
17
+
18
+ connect() {
19
+ this.ws = new WebSocket(this.url);
20
+
21
+ this.ws.onopen = (e) => {
22
+ this.currentDelay = this.reconnectDelay;
23
+ this.reconnectAttempts = 0;
24
+ this.emit('open', e);
25
+ };
26
+
27
+ this.ws.onmessage = (e) => {
28
+ this.emit('message', e);
29
+ };
30
+
31
+ this.ws.onerror = (e) => {
32
+ this.emit('error', e);
33
+ };
34
+
35
+ this.ws.onclose = (e) => {
36
+ this.emit('close', e);
37
+ if (this.shouldReconnect && this.reconnectAttempts < this.maxReconnectAttempts) {
38
+ setTimeout(() => {
39
+ this.reconnectAttempts++;
40
+ this.currentDelay = Math.min(
41
+ this.currentDelay * this.reconnectDecay,
42
+ this.maxReconnectDelay
43
+ );
44
+ console.log(`Attempting to reconnect (${this.reconnectAttempts})...`);
45
+ this.connect();
46
+ }, this.currentDelay);
47
+ }
48
+ };
49
+ }
50
+
51
+ on(event, callback) {
52
+ if (!this.listeners.has(event)) {
53
+ this.listeners.set(event, []);
54
+ }
55
+ this.listeners.get(event).push(callback);
56
+ }
57
+
58
+ emit(event, data) {
59
+ const callbacks = this.listeners.get(event);
60
+ if (callbacks) {
61
+ callbacks.forEach(cb => cb(data));
62
+ }
63
+ }
64
+
65
+ send(data) {
66
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
67
+ this.ws.send(data);
68
+ }
69
+ }
70
+
71
+ close() {
72
+ this.shouldReconnect = false;
73
+ if (this.ws) {
74
+ this.ws.close();
75
+ }
76
+ }
77
+ }
78
+
79
+ class GMGUIApp {
80
+ constructor() {
81
+ this.conversations = new Map();
82
+ this.currentConversation = null;
83
+ this.agents = new Map();
84
+ this.selectedAgent = null;
85
+ this.ws = null;
86
+ }
87
+
88
+ async init() {
89
+ console.log('[APP] Initializing');
90
+
91
+ this.setupEventListeners();
92
+ await this.fetchAgents();
93
+
94
+ const savedAgent = localStorage.getItem('gmgui-selectedAgent');
95
+ if (savedAgent && this.agents.has(savedAgent)) {
96
+ this.selectedAgent = savedAgent;
97
+ } else if (this.agents.size > 0) {
98
+ this.selectedAgent = Array.from(this.agents.keys())[0];
99
+ localStorage.setItem('gmgui-selectedAgent', this.selectedAgent);
100
+ }
101
+
102
+ await this.fetchConversations();
103
+ this.connectWebSocket();
104
+ this.renderAll();
105
+ console.log('[APP] Ready');
106
+ }
107
+
108
+ async fetchAgents() {
109
+ try {
110
+ const res = await fetch(BASE_URL + '/api/agents');
111
+ const data = await res.json();
112
+ for (const agent of data.agents || []) {
113
+ this.agents.set(agent.id, agent);
114
+ }
115
+ } catch (e) {
116
+ console.error('[APP] Error fetching agents:', e);
117
+ }
118
+ }
119
+
120
+ async fetchConversations() {
121
+ try {
122
+ const res = await fetch(BASE_URL + '/api/conversations');
123
+ const data = await res.json();
124
+ this.conversations.clear();
125
+ for (const conv of data.conversations || []) {
126
+ this.conversations.set(conv.id, conv);
127
+ }
128
+ console.log('[APP] Loaded', this.conversations.size, 'conversations');
129
+ } catch (e) {
130
+ console.error('[APP] Error fetching conversations:', e);
131
+ }
132
+ }
133
+
134
+ async fetchMessages(conversationId) {
135
+ try {
136
+ const res = await fetch(BASE_URL + `/api/conversations/${conversationId}/messages`);
137
+ const data = await res.json();
138
+ return data.messages || [];
139
+ } catch (e) {
140
+ console.error('[APP] Error fetching messages:', e);
141
+ return [];
142
+ }
143
+ }
144
+
145
+ connectWebSocket() {
146
+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
147
+ this.ws = new ReconnectingWebSocket(`${proto}//${location.host}${BASE_URL}/sync`);
148
+
149
+ this.ws.on('open', () => {
150
+ console.log('[WS] Connected');
151
+ document.getElementById('connectionStatus').textContent = 'Connected';
152
+ });
153
+
154
+ this.ws.on('message', (e) => {
155
+ try {
156
+ const event = JSON.parse(e.data);
157
+ this.handleEvent(event);
158
+ } catch (err) {
159
+ console.error('[WS] Parse error:', err);
160
+ }
161
+ });
162
+
163
+ this.ws.on('close', () => {
164
+ console.log('[WS] Disconnected, reconnecting...');
165
+ document.getElementById('connectionStatus').textContent = 'Reconnecting...';
166
+ });
167
+
168
+ this.ws.on('error', (err) => {
169
+ console.error('[WS] Error:', err);
170
+ document.getElementById('connectionStatus').textContent = 'Error';
171
+ });
172
+ }
173
+
174
+ handleEvent(event) {
175
+ if (event.type === 'message_created') {
176
+ this.handleMessageReceived(event.message);
177
+ } else if (event.type === 'conversations_updated') {
178
+ this.fetchConversations().then(() => this.renderChatHistory());
179
+ }
180
+ }
181
+
182
+ addMessageToDisplay(message) {
183
+ if (this.currentConversation && message.conversationId === this.currentConversation) {
184
+ const chatDiv = document.getElementById('chatMessages');
185
+ if (!chatDiv) return;
186
+
187
+ const msgEl = document.createElement('div');
188
+ msgEl.className = `message ${message.role}`;
189
+
190
+ // Try to parse content as JSON for structured display
191
+ let contentHtml = '';
192
+ try {
193
+ const parsed = typeof message.content === 'string' ? JSON.parse(message.content) : message.content;
194
+ if (parsed && parsed.type === 'claude_execution' && parsed.blocks) {
195
+ // Render each block with appropriate formatting
196
+ contentHtml = '<div class="execution-blocks">';
197
+ for (const block of parsed.blocks) {
198
+ contentHtml += this.renderMessageBlock(block);
199
+ }
200
+ contentHtml += '</div>';
201
+ } else {
202
+ throw new Error('Not a claude_execution message');
203
+ }
204
+ } catch (e) {
205
+ // Fallback: try to parse and beautify, or render as plain text
206
+ try {
207
+ const parsed = typeof message.content === 'string' ? JSON.parse(message.content) : message.content;
208
+ contentHtml = `<div class="message-content">${this.renderParameters(parsed)}</div>`;
209
+ } catch (parseErr) {
210
+ const text = typeof message.content === 'string' ? message.content : JSON.stringify(message.content);
211
+ contentHtml = `<div class="message-content"><pre>${this.escapeHtml(text)}</pre></div>`;
212
+ }
213
+ }
214
+
215
+ msgEl.innerHTML = contentHtml;
216
+ chatDiv.appendChild(msgEl);
217
+ chatDiv.scrollTop = chatDiv.scrollHeight;
218
+ }
219
+ }
220
+
221
+ renderMessageBlock(block) {
222
+ if (!block) return '';
223
+
224
+ let html = '<div class="message-block">';
225
+
226
+ switch (block.type) {
227
+ case 'text': {
228
+ const text = block.text || '';
229
+ const beautified = this.markdownToHtml(text);
230
+ html += `<div class="block-text">${beautified}</div>`;
231
+ break;
232
+ }
233
+
234
+ case 'tool_use': {
235
+ html += `<div class="block-tool-use">`;
236
+ html += `<strong class="tool-name">${this.escapeHtml(block.name || 'Tool')}</strong>`;
237
+ const paramHtml = this.renderParameters(block.input || {});
238
+ html += `<div class="tool-input">${paramHtml}</div>`;
239
+ html += `</div>`;
240
+ break;
241
+ }
242
+
243
+ case 'tool_result': {
244
+ html += `<div class="block-tool-result">`;
245
+ html += `<strong>Result:</strong>`;
246
+ let resultHtml;
247
+ if (typeof block.result === 'string') {
248
+ try {
249
+ const parsed = JSON.parse(block.result);
250
+ resultHtml = this.renderParameters(parsed);
251
+ } catch (e) {
252
+ resultHtml = `<pre>${this.escapeHtml(block.result)}</pre>`;
253
+ }
254
+ } else {
255
+ resultHtml = this.renderParameters(block.result);
256
+ }
257
+ html += `<div class="tool-result">${resultHtml}</div>`;
258
+ html += `</div>`;
259
+ break;
260
+ }
261
+
262
+ case 'file_operation':
263
+ html += `<div class="block-file-op">`;
264
+ html += `<strong class="file-action">${this.escapeHtml(block.action || 'File Operation')}</strong>`;
265
+ html += `<div class="file-path">${this.escapeHtml(block.path || '')}</div>`;
266
+ if (block.content) {
267
+ html += `<div class="file-content"><pre>${this.escapeHtml(block.content.substring(0, 500))}</pre></div>`;
268
+ }
269
+ html += `</div>`;
270
+ break;
271
+
272
+ default:
273
+ html += `<div class="block-unknown">${this.escapeHtml(JSON.stringify(block, null, 2))}</div>`;
274
+ }
275
+
276
+ html += '</div>';
277
+ return html;
278
+ }
279
+
280
+ handleMessageReceived(message) {
281
+ if (message.role === 'user') {
282
+ document.getElementById('messageInput').value = '';
283
+ document.getElementById('messageInput').focus();
284
+ }
285
+ }
286
+
287
+ async sendMessage() {
288
+ const input = document.getElementById('messageInput');
289
+ const content = input.value.trim();
290
+
291
+ if (!content || !this.currentConversation || !this.selectedAgent) return;
292
+
293
+ try {
294
+ const res = await fetch(BASE_URL + `/api/conversations/${this.currentConversation}/messages`, {
295
+ method: 'POST',
296
+ headers: { 'Content-Type': 'application/json' },
297
+ body: JSON.stringify({
298
+ content,
299
+ agentId: this.selectedAgent
300
+ })
301
+ });
302
+
303
+ if (res.ok) {
304
+ input.value = '';
305
+ }
306
+ } catch (e) {
307
+ console.error('[APP] Error sending message:', e);
308
+ }
309
+ }
310
+
311
+ async createConversation(title = 'New Conversation') {
312
+ if (!this.selectedAgent) {
313
+ console.error('[APP] No agent selected');
314
+ return;
315
+ }
316
+
317
+ try {
318
+ const res = await fetch(BASE_URL + '/api/conversations', {
319
+ method: 'POST',
320
+ headers: { 'Content-Type': 'application/json' },
321
+ body: JSON.stringify({ title, agentId: this.selectedAgent })
322
+ });
323
+
324
+ if (res.ok) {
325
+ const data = await res.json();
326
+ await this.fetchConversations();
327
+ this.renderChatHistory();
328
+ if (data.conversation) {
329
+ this.selectConversation(data.conversation.id);
330
+ }
331
+ }
332
+ } catch (e) {
333
+ console.error('[APP] Error creating conversation:', e);
334
+ }
335
+ }
336
+
337
+ selectConversation(convId) {
338
+ this.currentConversation = convId;
339
+ document.querySelectorAll('.chat-item').forEach(el => el.classList.remove('active'));
340
+ const el = document.querySelector(`[data-conv-id="${convId}"]`);
341
+ if (el) el.classList.add('active');
342
+ this.renderChatMessages();
343
+ }
344
+
345
+ async renderChatMessages() {
346
+ const chatDiv = document.getElementById('chatMessages');
347
+ if (!chatDiv || !this.currentConversation) return;
348
+
349
+ chatDiv.innerHTML = '';
350
+ const messages = await this.fetchMessages(this.currentConversation);
351
+ for (const msg of messages) {
352
+ const msgEl = document.createElement('div');
353
+ msgEl.className = `message ${msg.role}`;
354
+
355
+ // Try to parse content as JSON for structured display
356
+ let contentHtml = '';
357
+ try {
358
+ const parsed = typeof msg.content === 'string' ? JSON.parse(msg.content) : msg.content;
359
+ if (parsed && parsed.type === 'claude_execution' && parsed.blocks) {
360
+ // Render each block with appropriate formatting
361
+ contentHtml = '<div class="execution-blocks">';
362
+ for (const block of parsed.blocks) {
363
+ contentHtml += this.renderMessageBlock(block);
364
+ }
365
+ contentHtml += '</div>';
366
+ } else {
367
+ throw new Error('Not a claude_execution message');
368
+ }
369
+ } catch (e) {
370
+ // Fallback: try to parse and beautify, or render as plain text
371
+ try {
372
+ const parsed = typeof msg.content === 'string' ? JSON.parse(msg.content) : msg.content;
373
+ contentHtml = `<div class="message-content">${this.renderParameters(parsed)}</div>`;
374
+ } catch (parseErr) {
375
+ const text = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content);
376
+ contentHtml = `<div class="message-content"><pre>${this.escapeHtml(text)}</pre></div>`;
377
+ }
378
+ }
379
+
380
+ msgEl.innerHTML = contentHtml;
381
+ chatDiv.appendChild(msgEl);
382
+ }
383
+ }
384
+
385
+ renderChatHistory() {
386
+ const list = document.getElementById('chatList');
387
+ if (!list) return;
388
+
389
+ list.innerHTML = '';
390
+ const convs = Array.from(this.conversations.values())
391
+ .sort((a, b) => (b.updated_at || 0) - (a.updated_at || 0));
392
+
393
+ for (const conv of convs) {
394
+ const el = document.createElement('div');
395
+ el.className = 'chat-item';
396
+ el.setAttribute('data-conv-id', conv.id);
397
+ el.innerHTML = `<div class="chat-item-title">${this.escapeHtml(conv.title || 'Untitled')}</div>`;
398
+ el.onclick = () => this.selectConversation(conv.id);
399
+ list.appendChild(el);
400
+ }
401
+ }
402
+
403
+ renderAll() {
404
+ this.renderChatHistory();
405
+ if (this.conversations.size > 0 && !this.currentConversation) {
406
+ const firstConv = Array.from(this.conversations.values())[0];
407
+ this.selectConversation(firstConv.id);
408
+ }
409
+ }
410
+
411
+ setupEventListeners() {
412
+ const sendBtn = document.getElementById('sendBtn');
413
+ if (sendBtn) {
414
+ sendBtn.onclick = () => this.sendMessage();
415
+ }
416
+
417
+ const input = document.getElementById('messageInput');
418
+ if (input) {
419
+ input.addEventListener('keypress', (e) => {
420
+ if (e.key === 'Enter' && !e.shiftKey) {
421
+ e.preventDefault();
422
+ this.sendMessage();
423
+ }
424
+ });
425
+ }
426
+
427
+ const newConvBtn = document.getElementById('newConversationBtn');
428
+ if (newConvBtn) {
429
+ newConvBtn.onclick = () => this.createConversation();
430
+ }
431
+ }
432
+
433
+ parseMarkdownCodeBlocks(text) {
434
+ const parts = [];
435
+ const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
436
+ let lastIndex = 0;
437
+ let match;
438
+
439
+ while ((match = codeBlockRegex.exec(text)) !== null) {
440
+ // Add text before code block
441
+ if (match.index > lastIndex) {
442
+ parts.push({
443
+ type: 'text',
444
+ content: text.substring(lastIndex, match.index)
445
+ });
446
+ }
447
+
448
+ // Add code block
449
+ const language = match[1] || 'text';
450
+ const code = match[2];
451
+ parts.push({
452
+ type: 'code',
453
+ language,
454
+ content: code
455
+ });
456
+
457
+ lastIndex = codeBlockRegex.lastIndex;
458
+ }
459
+
460
+ // Add remaining text
461
+ if (lastIndex < text.length) {
462
+ parts.push({
463
+ type: 'text',
464
+ content: text.substring(lastIndex)
465
+ });
466
+ }
467
+
468
+ return parts.length > 0 ? parts : [{ type: 'text', content: text }];
469
+ }
470
+
471
+ markdownToHtml(markdown) {
472
+ const lines = markdown.split('\n');
473
+ let html = '';
474
+ let inList = false;
475
+ let listType = null;
476
+ let i = 0;
477
+
478
+ while (i < lines.length) {
479
+ const line = lines[i];
480
+ const trimmed = line.trim();
481
+
482
+ // Code blocks
483
+ if (trimmed.startsWith('```')) {
484
+ if (inList) {
485
+ html += listType === 'ul' ? '</ul>' : '</ol>';
486
+ inList = false;
487
+ }
488
+ const match = trimmed.match(/^```(\w*)/);
489
+ const lang = (match && match[1]) || 'text';
490
+ i++;
491
+ const codeLines = [];
492
+ while (i < lines.length && !lines[i].trim().startsWith('```')) {
493
+ codeLines.push(lines[i]);
494
+ i++;
495
+ }
496
+ const clCount = codeLines.length;
497
+ html += `<details class="collapsible-code"><summary class="collapsible-code-summary">${this.escapeHtml(lang)} - ${clCount} line${clCount !== 1 ? 's' : ''}</summary><div class="code-block" data-language="${this.escapeHtml(lang)}"><pre><code>${this.escapeHtml(codeLines.join('\n'))}</code></pre></div></details>`;
498
+ i++;
499
+ continue;
500
+ }
501
+
502
+ // Headings
503
+ if (trimmed.startsWith('#')) {
504
+ if (inList) {
505
+ html += listType === 'ul' ? '</ul>' : '</ol>';
506
+ inList = false;
507
+ }
508
+ const match = trimmed.match(/^(#+)\s+(.*)/);
509
+ if (match) {
510
+ const level = match[1].length;
511
+ const text = this.escapeAndFormatInline(match[2]);
512
+ html += `<h${level}>${text}</h${level}>`;
513
+ i++;
514
+ continue;
515
+ }
516
+ }
517
+
518
+ // Lists
519
+ if (trimmed.match(/^[-*+]\s/)) {
520
+ if (!inList) {
521
+ html += '<ul>';
522
+ inList = true;
523
+ listType = 'ul';
524
+ }
525
+ const match = trimmed.match(/^[-*+]\s+(.*)/);
526
+ if (match) {
527
+ const text = this.escapeAndFormatInline(match[1]);
528
+ html += `<li>${text}</li>`;
529
+ }
530
+ i++;
531
+ continue;
532
+ }
533
+
534
+ if (trimmed.match(/^\d+\.\s/)) {
535
+ if (!inList || listType !== 'ol') {
536
+ if (inList) html += '</ul>';
537
+ html += '<ol>';
538
+ inList = true;
539
+ listType = 'ol';
540
+ }
541
+ const match = trimmed.match(/^\d+\.\s+(.*)/);
542
+ if (match) {
543
+ const text = this.escapeAndFormatInline(match[1]);
544
+ html += `<li>${text}</li>`;
545
+ }
546
+ i++;
547
+ continue;
548
+ }
549
+
550
+ // End list if not a list item
551
+ if (inList && trimmed && !trimmed.match(/^[-*+]\s/) && !trimmed.match(/^\d+\.\s/)) {
552
+ html += listType === 'ul' ? '</ul>' : '</ol>';
553
+ inList = false;
554
+ }
555
+
556
+ // Paragraphs
557
+ if (trimmed) {
558
+ const text = this.escapeAndFormatInline(trimmed);
559
+ html += `<p>${text}</p>`;
560
+ }
561
+
562
+ i++;
563
+ }
564
+
565
+ // Close any open list
566
+ if (inList) {
567
+ html += listType === 'ul' ? '</ul>' : '</ol>';
568
+ }
569
+
570
+ return html;
571
+ }
572
+
573
+ escapeAndFormatInline(text) {
574
+ text = this.escapeHtml(text);
575
+ // Bold and italic (must be before single asterisk)
576
+ text = text.replace(/\*\*\*(.*?)\*\*\*/g, '<strong><em>$1</em></strong>');
577
+ text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
578
+ text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
579
+ text = text.replace(/__(.*?)__/g, '<strong>$1</strong>');
580
+ text = text.replace(/_(.*?)_/g, '<em>$1</em>');
581
+ // Inline code
582
+ text = text.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');
583
+ // Links
584
+ text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
585
+ return text;
586
+ }
587
+
588
+ renderCodeBlock(language, code) {
589
+ if (language === 'html') {
590
+ return `<div class="html-block">
591
+ <div class="html-header">Rendered HTML</div>
592
+ <div class="html-content">${code}</div>
593
+ </div>`;
594
+ } else {
595
+ const lcCount = code.split('\n').length;
596
+ return `<details class="collapsible-code"><summary class="collapsible-code-summary">${this.escapeHtml(language)} - ${lcCount} line${lcCount !== 1 ? 's' : ''}</summary><div class="code-block" data-language="${this.escapeHtml(language)}">
597
+ <pre><code>${this.escapeHtml(code)}</code></pre>
598
+ </div></details>`;
599
+ }
600
+ }
601
+
602
+ escapeHtml(text) {
603
+ const div = document.createElement('div');
604
+ div.textContent = text;
605
+ return div.innerHTML;
606
+ }
607
+
608
+ renderParameters(obj, depth = 0) {
609
+ if (obj === null || obj === undefined) {
610
+ return `<span style="color: var(--text-tertiary);">null</span>`;
611
+ }
612
+
613
+ if (typeof obj === 'string') {
614
+ const isPath = obj.includes('/') || obj.includes('\\');
615
+ const isUrl = obj.startsWith('http://') || obj.startsWith('https://');
616
+ if (isPath || isUrl) {
617
+ return `<code style="color: var(--text-secondary); background: transparent;">${this.escapeHtml(obj)}</code>`;
618
+ }
619
+ return `<span>"${this.escapeHtml(obj)}"</span>`;
620
+ }
621
+
622
+ if (typeof obj === 'number' || typeof obj === 'boolean') {
623
+ return `<span style="color: var(--color-info);">${obj}</span>`;
624
+ }
625
+
626
+ if (Array.isArray(obj)) {
627
+ if (obj.length === 0) {
628
+ return `<span style="color: var(--text-tertiary);">[]</span>`;
629
+ }
630
+ const maxItems = depth === 0 ? 10 : 5;
631
+ const items = obj.slice(0, maxItems).map(item => this.renderParameters(item, depth + 1));
632
+ const more = obj.length > maxItems ? `<span style="color: var(--text-tertiary);">... ${obj.length - maxItems} more</span>` : '';
633
+ return `<span style="color: var(--text-tertiary);">[</span> ${items.join(', ')} ${more} <span style="color: var(--text-tertiary);">]</span>`;
634
+ }
635
+
636
+ if (typeof obj === 'object') {
637
+ const keys = Object.keys(obj);
638
+ if (keys.length === 0) {
639
+ return `<span style="color: var(--text-tertiary);">{}</span>`;
640
+ }
641
+ const maxKeys = depth === 0 ? 15 : 8;
642
+ const pairs = keys.slice(0, maxKeys).map(key => {
643
+ const keyHtml = `<span style="color: var(--color-primary);">${this.escapeHtml(key)}</span>`;
644
+ const valHtml = this.renderParameters(obj[key], depth + 1);
645
+ return `${keyHtml}: ${valHtml}`;
646
+ });
647
+ const more = keys.length > maxKeys ? `<span style="color: var(--text-tertiary);">... ${keys.length - maxKeys} more</span>` : '';
648
+ return `<div style="margin-left: ${depth * 1.5}rem;"><span style="color: var(--text-tertiary);">{</span><br/>${pairs.map(p => `&nbsp;&nbsp;${p}`).join(',<br/>')}<br/>${more}<span style="color: var(--text-tertiary);">}</span></div>`;
649
+ }
650
+
651
+ return `<span>${this.escapeHtml(String(obj))}</span>`;
652
+ }
653
+ }
654
+
655
+ const app = new GMGUIApp();
656
+
657
+ function initializeApp() {
658
+ app.init().catch(err => {
659
+ console.error('[CRITICAL] Failed to initialize app:', err);
660
+ });
661
+ }
662
+
663
+ function sendMessage() {
664
+ app.sendMessage();
665
+ }
666
+
667
+ function showNewChatModal() {
668
+ const modal = document.getElementById('newChatModal');
669
+ if (modal) {
670
+ modal.style.display = 'flex';
671
+ }
672
+ }
673
+
674
+ function closeNewChatModal() {
675
+ const modal = document.getElementById('newChatModal');
676
+ if (modal) {
677
+ modal.style.display = 'none';
678
+ }
679
+ }
680
+
681
+ async function createChatInWorkspace() {
682
+ const title = await window.UIDialog.prompt('Enter a title for the conversation:', 'New Conversation', 'New Chat');
683
+ if (title) {
684
+ app.createConversation(title);
685
+ closeNewChatModal();
686
+ }
687
+ }
688
+
689
+ function createChatInFolder() {
690
+ const folderModal = document.getElementById('folderBrowserModal');
691
+ if (folderModal) {
692
+ folderModal.style.display = 'flex';
693
+ closeNewChatModal();
694
+ }
695
+ }
696
+
697
+ function closeFolderBrowser() {
698
+ const modal = document.getElementById('folderBrowserModal');
699
+ if (modal) {
700
+ modal.style.display = 'none';
701
+ }
702
+ }
703
+
704
+ function confirmFolderSelection() {
705
+ const folderPath = document.getElementById('folderPath')?.value;
706
+ if (folderPath) {
707
+ const title = `Chat in ${folderPath}`;
708
+ app.createConversation(title);
709
+ closeFolderBrowser();
710
+ }
711
+ }
712
+
713
+ function browseFolders() {
714
+ // Placeholder for folder browsing functionality
715
+ console.log('Folder browsing not yet implemented');
716
+ }
717
+
718
+ function toggleSidebar() {
719
+ const sidebar = document.getElementById('sidebar');
720
+ if (sidebar) {
721
+ sidebar.classList.toggle('collapsed');
722
+ }
723
+ }
724
+
725
+ function switchTab(tab) {
726
+ if (tab === 'settings') {
727
+ const panel = document.getElementById('settingsPanel');
728
+ if (panel) {
729
+ panel.style.display = 'flex';
730
+ }
731
+ const main = document.querySelector('.main-content');
732
+ if (main) {
733
+ main.style.display = 'none';
734
+ }
735
+ } else if (tab === 'chat') {
736
+ const panel = document.getElementById('settingsPanel');
737
+ if (panel) {
738
+ panel.style.display = 'none';
739
+ }
740
+ const main = document.querySelector('.main-content');
741
+ if (main) {
742
+ main.style.display = 'flex';
743
+ }
744
+ }
745
+ }
746
+
747
+ function triggerFileUpload() {
748
+ const input = document.getElementById('fileInput');
749
+ if (input) {
750
+ input.click();
751
+ }
752
+ }
753
+
754
+ function handleFileUpload() {
755
+ console.log('File upload not yet implemented');
756
+ }
757
+
758
+ function closeScreenshotModal() {
759
+ const modal = document.getElementById('screenshotModal');
760
+ if (modal) {
761
+ modal.style.display = 'none';
762
+ }
763
+ }
764
+
765
+ function sendScreenshot() {
766
+ console.log('Send screenshot not yet implemented');
767
+ }
768
+
769
+ function downloadScreenshot() {
770
+ console.log('Download screenshot not yet implemented');
771
+ }
772
+
773
+ window.addEventListener('load', initializeApp);