-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidepanel.js
More file actions
2294 lines (1947 loc) · 94.4 KB
/
sidepanel.js
File metadata and controls
2294 lines (1947 loc) · 94.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SideLlama Side Panel JavaScript - Final Corrected Version
class SideLlamaChat {
constructor() {
this.currentConversationId = 'conv_' + Date.now();
this.currentModel = 'qwen2.5:7b'; // Default fallback, will be updated from settings
this.isTyping = false;
this.currentlySendingMessage = false; // Track if we're in the middle of sendMessage()
// Track event listeners for cleanup
this.eventListeners = new Map();
this.boundMethods = new Map();
this.activeTimeouts = new Set(); // Track timeouts for cleanup
this.messages = [];
this.contextEnabled = false;
this.searchEnabled = false;
this.currentContext = null;
// Simple streaming system (like working old version)
this.streamingMessageElement = null;
this.streamingContent = '';
// Attachment system
this.pendingAttachments = [];
// Stop functionality
this.currentAbortController = null;
this.settings = {
streamingEnabled: true, // Enable streaming by default for better UX
systemPrompt: '',
serperApiKey: ''
};
this.initializeElements();
this.bindEvents();
this.loadSettings().then(() => {
this.loadInitialData();
});
this.setupMessageListener();
}
initializeElements() {
this.messagesContainer = document.getElementById('messagesContainer');
this.messageInput = document.getElementById('messageInput');
this.sendButton = document.getElementById('sendButton');
this.stopButton = document.getElementById('stopButton');
this.typingIndicator = document.getElementById('typingIndicator');
this.currentModelDisplay = document.getElementById('currentModel');
this.contextStatus = document.getElementById('contextStatus');
this.menuButton = document.getElementById('menuButton');
this.dropdownMenu = document.getElementById('dropdownMenu');
this.modelSelectBtn = document.getElementById('modelSelectBtn');
this.deleteHistoryBtn = document.getElementById('deleteHistoryBtn');
this.settingsBtn = document.getElementById('settingsBtn');
// Toolbar buttons
this.contextToggle = document.getElementById('contextToggle');
this.searchToggle = document.getElementById('searchToggle');
// Other elements
this.fileInput = document.getElementById('fileInput');
this.searchContainer = document.getElementById('searchContainer');
this.searchInput = document.getElementById('searchInput');
this.searchButton = document.getElementById('searchButton');
this.contextIndicator = document.getElementById('contextIndicator');
this.contextText = document.getElementById('contextText');
this.contextClose = document.getElementById('contextClose');
// Quick model switching elements
this.quickModelSelect = document.getElementById('quickModelSelect');
this.quickModelName = document.getElementById('quickModelName');
this.quickModelDropdown = document.getElementById('quickModelDropdown');
this.modelCapabilities = document.getElementById('modelCapabilities');
// Attachment elements
this.attachmentsPreview = document.getElementById('attachmentsPreview');
this.attachmentsList = document.getElementById('attachmentsList');
}
async loadSettings() {
try {
const result = await chrome.storage.sync.get('sideLlamaSettings');
const savedSettings = result.sideLlamaSettings || {};
// Update current model from settings
if (savedSettings.defaultModel) {
this.currentModel = savedSettings.defaultModel;
}
// Merge with existing settings
this.settings = {
...this.settings,
...savedSettings
};
// Load conversation history if enabled
if (this.settings.saveHistory !== false) {
await this.loadConversationHistory();
}
} catch (error) {
this.handleError(error, 'Failed to load settings', false);
}
}
// Helper methods for managing event listeners to prevent memory leaks
addEventListenerTracked(element, event, handler, options = false) {
const key = `${element.constructor.name}_${event}_${Math.random()}`;
this.eventListeners.set(key, { element, event, handler, options });
element.addEventListener(event, handler, options);
return key;
}
removeEventListenerTracked(key) {
const listener = this.eventListeners.get(key);
if (listener) {
listener.element.removeEventListener(listener.event, listener.handler, listener.options);
this.eventListeners.delete(key);
}
}
// Helper method to track timeouts for cleanup
setTimeoutTracked(callback, delay) {
const timeoutId = setTimeout(() => {
this.activeTimeouts.delete(timeoutId);
callback();
}, delay);
this.activeTimeouts.add(timeoutId);
return timeoutId;
}
// Helper method to add tracked event listeners to dynamic elements
addEventListenerToElement(element, event, handler, options = false) {
const key = this.addEventListenerTracked(element, event, handler, options);
return key;
}
cleanup() {
// Remove all tracked event listeners
for (const [key, listener] of this.eventListeners) {
listener.element.removeEventListener(listener.event, listener.handler, listener.options);
}
this.eventListeners.clear();
this.boundMethods.clear();
// Clear all active timeouts
this.activeTimeouts.forEach(timeoutId => {
clearTimeout(timeoutId);
});
this.activeTimeouts.clear();
// Abort any active requests
if (this.currentAbortController) {
this.currentAbortController.abort();
this.currentAbortController = null;
}
console.log('🧹 SideLlama cleanup completed');
}
cleanupInactiveTimeouts() {
// Only clear non-critical timeouts (like status bar clearing)
// Keep critical timeouts (like performance stats) running
let clearedCount = 0;
this.activeTimeouts.forEach(timeoutId => {
// This is a simple implementation - in practice you might want to categorize timeouts
if (Math.random() > 0.5) { // Simplified logic - could be enhanced with timeout metadata
clearTimeout(timeoutId);
this.activeTimeouts.delete(timeoutId);
clearedCount++;
}
});
if (clearedCount > 0) {
console.log(`🧹 Cleaned up ${clearedCount} inactive timeouts`);
}
}
// Consistent error handling system
handleError(error, context = '', showToUser = true, logLevel = 'error') {
const errorMessage = error instanceof Error ? error.message : String(error);
const fullMessage = context ? `${context}: ${errorMessage}` : errorMessage;
// Always log to console for debugging
if (logLevel === 'warn') {
console.warn(`🦙 ${fullMessage}`, error);
} else {
console.error(`🦙 ${fullMessage}`, error);
}
// Show to user if requested
if (showToUser) {
this.updateStatusBar(`❌ ${fullMessage}`);
}
return fullMessage;
}
// Helper for handling async operation errors
async handleAsyncError(asyncOperation, context = '', showErrorToUser = true) {
try {
return await asyncOperation();
} catch (error) {
this.handleError(error, context, showErrorToUser);
throw error; // Re-throw so caller can handle if needed
}
}
async loadConversationHistory() {
try {
const result = await chrome.storage.local.get('sideLlamaConversation');
const savedConversation = result.sideLlamaConversation;
if (savedConversation && savedConversation.messages && savedConversation.messages.length > 0) {
this.messages = savedConversation.messages;
this.currentConversationId = savedConversation.id || this.currentConversationId;
// Rebuild UI from saved messages
this.rebuildConversationUI();
console.log(`🦙 Loaded ${this.messages.length} messages from conversation history`);
}
} catch (error) {
this.handleError(error, 'Failed to load conversation history', false);
}
}
async saveConversationHistory() {
try {
if (this.settings.saveHistory === false) {
return;
}
// Trim messages to stay within context limits if needed
const trimmedMessages = this.trimMessagesToContextLimit(this.messages);
const conversationData = {
id: this.currentConversationId,
messages: trimmedMessages,
lastUpdated: Date.now()
};
await chrome.storage.local.set({ sideLlamaConversation: conversationData });
} catch (error) {
this.handleError(error, 'Failed to save conversation history', false);
}
}
trimMessagesToContextLimit(messages) {
const contextLength = this.settings.contextLength || 128000;
const maxHistoryLength = this.settings.maxHistoryLength || 100;
// First, limit by number of messages (O(1) operation)
if (messages.length <= maxHistoryLength) {
return messages; // No trimming needed
}
let trimmedMessages = messages.slice(-maxHistoryLength);
// Fast character estimation with early exit
const maxChars = contextLength * 3; // Leave buffer space
let totalChars = 0;
// Count from the end, exit early if under limit
for (let i = trimmedMessages.length - 1; i >= 0; i--) {
const messageChars = (trimmedMessages[i].content || '').length;
totalChars += messageChars;
// Early exit if we're way under the limit (optimization)
if (i < trimmedMessages.length - 10 && totalChars < maxChars * 0.5) {
break; // No need to count everything if we're well under limit
}
if (totalChars > maxChars) {
// Keep system messages when trimming
const systemMsgs = trimmedMessages.slice(0, i + 1).filter(msg => msg.role === 'system');
const recentMsgs = trimmedMessages.slice(i + 1);
return [...systemMsgs, ...recentMsgs];
}
}
return trimmedMessages;
}
rebuildConversationUI() {
// Clear existing UI but keep typing indicator
const existingIndicator = this.typingIndicator.cloneNode(true);
this.messagesContainer.innerHTML = '';
// Rebuild messages from history
this.messages.forEach(msg => {
if (msg.role === 'user') {
this.createMessage('user', msg.content, { saveHistory: false });
} else if (msg.role === 'assistant') {
this.createMessage('assistant', msg.content, { saveHistory: false });
} else if (msg.role === 'system') {
this.createMessage('system', msg.content, { saveHistory: false });
}
});
// Re-add typing indicator
this.messagesContainer.appendChild(existingIndicator);
this.scrollToBottom();
}
async saveModelToSettings(modelName) {
try {
const result = await chrome.storage.sync.get('sideLlamaSettings');
const settings = result.sideLlamaSettings || {};
settings.defaultModel = modelName;
await chrome.storage.sync.set({ sideLlamaSettings: settings });
this.settings.defaultModel = modelName;
} catch (error) {
this.handleError(error, 'Failed to save model to settings', false);
}
}
bindEvents() {
// Use tracked event listeners to prevent memory leaks
this.addEventListenerTracked(this.sendButton, 'click', () => this.sendMessage());
this.addEventListenerTracked(this.stopButton, 'click', () => this.stopGeneration());
this.addEventListenerTracked(this.messageInput, 'keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.sendMessage();
}
});
this.addEventListenerTracked(this.menuButton, 'click', (e) => { e.stopPropagation(); this.toggleMenu(); });
this.addEventListenerTracked(document, 'click', () => { this.closeMenu(); });
this.addEventListenerTracked(this.modelSelectBtn, 'click', () => { this.toggleModelSelector(); this.closeMenu(); });
this.addEventListenerTracked(this.deleteHistoryBtn, 'click', () => { this.clearChat(); this.closeMenu(); });
this.addEventListenerTracked(this.settingsBtn, 'click', () => { this.openSettings(); this.closeMenu(); });
// Toolbar button events
this.addEventListenerTracked(this.contextToggle, 'click', () => {
this.togglePageContext();
});
this.addEventListenerTracked(this.searchToggle, 'click', () => {
this.toggleWebSearch();
});
// File input events
this.addEventListenerTracked(this.fileInput, 'change', (e) => {
this.handleFileUpload(e);
});
// Search events
this.addEventListenerTracked(this.searchButton, 'click', () => {
this.performWebSearch();
});
this.addEventListenerTracked(this.searchInput, 'keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
this.performWebSearch();
}
});
// Context indicator close
this.addEventListenerTracked(this.contextClose, 'click', () => {
this.contextEnabled = false;
this.currentContext = null;
this.contextIndicator.style.display = 'none';
this.contextToggle.style.color = '';
});
// Quick model switching events
this.addEventListenerTracked(this.quickModelSelect, 'click', (e) => {
e.stopPropagation();
this.toggleQuickModelDropdown();
});
// Close dropdown when clicking outside
this.addEventListenerTracked(document, 'click', (e) => {
if (!this.quickModelSelect.contains(e.target)) {
this.closeQuickModelDropdown();
}
});
// Image paste functionality - only handle on document level to avoid duplication
this.addEventListenerTracked(document, 'paste', (e) => {
// Only handle if focus is on message input or somewhere else in sidepanel
if (document.activeElement === this.messageInput || !e.target.closest('input, textarea')) {
this.handlePaste(e);
}
});
// Drag and drop functionality
this.addEventListenerTracked(this.messageInput, 'dragover', (e) => {
e.preventDefault();
e.stopPropagation();
this.messageInput.style.backgroundColor = 'var(--accent)';
});
this.addEventListenerTracked(this.messageInput, 'dragleave', (e) => {
e.preventDefault();
e.stopPropagation();
this.messageInput.style.backgroundColor = '';
});
this.addEventListenerTracked(this.messageInput, 'drop', (e) => {
e.preventDefault();
e.stopPropagation();
this.messageInput.style.backgroundColor = '';
this.handleDrop(e);
});
// Cleanup on page unload to prevent memory leaks
this.addEventListenerTracked(window, 'beforeunload', () => {
this.cleanup();
});
// Also cleanup on visibility change (when side panel is hidden)
this.addEventListenerTracked(document, 'visibilitychange', () => {
if (document.hidden && !this.isTyping) {
// Only cleanup inactive timeouts when not actively typing
this.cleanupInactiveTimeouts();
}
});
}
async loadInitialData() {
try {
const settingsResult = await this.sendChromeMessage({ type: 'GET_SETTINGS' });
if (settingsResult.success) {
this.settings = { ...this.settings, ...settingsResult.settings };
}
const status = await this.sendChromeMessage({ type: 'CHECK_OLLAMA_STATUS' });
if (status.status !== 'connected') {
this.updateStatusBar('❌ Ollama connection failed');
}
// Update UI with loaded model
this.updateModelDisplay();
// Initialize model capabilities display
this.updateModelCapabilitiesDisplay();
// Initialize input placeholder
this.updateInputPlaceholder();
} catch (error) {
this.handleError(error, 'Initialization failed');
}
}
updateModelDisplay() {
// Update all model display elements
if (this.currentModelDisplay) {
this.currentModelDisplay.textContent = this.currentModel;
}
if (this.quickModelName) {
this.quickModelName.textContent = this.currentModel;
}
}
updateModelCapabilitiesDisplay() {
const capabilities = this.getModelCapabilitiesFromName(this.currentModel);
if (this.modelCapabilities) {
this.modelCapabilities.textContent = capabilities.join(' • ');
}
}
setupMessageListener() {
if (typeof chrome === 'undefined' || !chrome.runtime) return;
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
try {
switch (message.type) {
case 'STREAMING_RESPONSE':
this.handleStreamingResponse(message.data);
break;
case 'FINAL_RESPONSE':
this.handleUnifiedResponse(message.data);
break;
case 'CONTEXT_INFO':
this.showContextStatus(message.data.messageCount, message.data.trimmedCount);
break;
case 'SYSTEM_MESSAGE':
// Route error messages and temporary status to status bar
if (typeof message.data === 'string' &&
(message.data.startsWith('❌') ||
message.data.startsWith('⚠️') ||
message.data.startsWith('🛠️') ||
message.data.includes('tool(s)') ||
message.data.includes('Failed to') ||
message.data.includes('Error'))) {
this.updateStatusBar(message.data);
} else {
this.addSystemMessage(message.data);
}
break;
case 'ADD_USER_MESSAGE':
this.addUserMessageWithAttachments(message.data.message);
break;
case 'SEND_AI_MESSAGE':
this.handleAIMessageRequest(message.data);
break;
case 'CONTEXT_MENU_ACTION':
this.handleContextMenuAction(message.data);
break;
case 'MODEL_PULL_PROGRESS':
this.handleModelPullProgress(message.data);
break;
case 'CONTEXT_MENU_SCREENSHOT':
const attachmentId = `attachment_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `screenshot-${timestamp}.png`;
const dataUrl = message.dataUrl;
// Estimate size from dataUrl length (base64 is ~4/3 of original size)
const size = dataUrl.length * 0.75;
const attachment = {
id: attachmentId,
file: null, // No file object available
filename: filename,
type: 'image/png',
dataUrl: dataUrl,
size: size,
isTextFile: false
};
this.pendingAttachments.push(attachment);
this.renderAttachmentPreview(attachment);
this.showAttachmentsPreview();
this.addSystemMessage('📸 Screenshot added to message input.');
break;
case 'PERFORMANCE_STATS':
this.displayPerformanceStats(message.data);
break;
}
}
catch (error) {
console.error('Error handling message:', error);
this.updateStatusBar('❌ Error processing message');
}
// No return true needed as we are not using sendResponse in the sidepanel
});
}
async handleContextMenuAction(data) {
const { action, selectionText } = data;
const contextResult = await this.sendChromeMessage({ type: 'EXTRACT_PAGE_CONTEXT' });
if (!contextResult.success) {
this.updateStatusBar('❌ Failed to get page context');
return;
}
const context = contextResult.context;
let prompt = '';
let userMessage = '';
if (action === 'summarize') {
userMessage = `📄 Summarize this page: ${context.title}`;
prompt = `Please provide a concise summary of this webpage:\n\n**Title:** ${context.title}\n**URL:** ${context.url}\n\n**Content:**\n${context.content}`;
}
else if (action === 'explain' && selectionText) {
userMessage = `🔍 Explain: "${selectionText.substring(0, 50)}..."`;
prompt = `Please explain this selected text from the webpage "${context.title}":\n\n**Selected Text:**\n"${selectionText}"\n\n**Page Context:**\n${context.content.substring(0, 2000)}`;
}
if (prompt) {
this.addUserMessageWithAttachments(userMessage);
this.showTyping();
this.sendChromeMessage({
type: 'SEND_MESSAGE',
data: { message: prompt, model: this.currentModel, messages: this.messages, context }
}).catch(error => {
this.hideTyping();
this.updateStatusBar('❌ Context menu error: ' + error.message);
});
}
}
// ===== SIMPLE STREAMING SYSTEM (WORKING VERSION) =====
prepareStreamingMessage() {
// Reset streaming content
this.streamingContent = '';
// Create streaming message element using markdown-enabled structure
const messageDiv = document.createElement('div');
messageDiv.className = 'message-item';
const timestamp = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
messageDiv.innerHTML = `
<div class="flex flex-col gap-2 p-3">
<div class="flex items-center gap-2">
<div class="w-6 h-6 bg-blue-500 rounded-lg flex items-center justify-center text-white text-xs">🤖</div>
<div class="font-mono text-xs font-bold">${this.currentModel}</div>
<div class="text-xs text-muted-foreground ml-auto">${timestamp}</div>
</div>
<div class="message-content text-sm">
<div class="content-text markdown-content streaming"></div>
</div>
</div>
`;
// Insert before typing indicator to maintain proper order
if (this.typingIndicator && this.typingIndicator.parentNode === this.messagesContainer) {
this.messagesContainer.insertBefore(messageDiv, this.typingIndicator);
} else {
this.messagesContainer.appendChild(messageDiv);
}
this.streamingMessageElement = messageDiv.querySelector('.content-text');
// Don't fully hide typing yet - keep stop button visible during streaming
// Only hide the typing indicator dots, but keep stop button active
const typingElement = document.getElementById('typingIndicator');
if (typingElement) {
typingElement.classList.remove('show');
}
this.scrollToBottom();
}
handleStreamingResponse(data) {
// Only create the message bubble if we receive actual content.
// This prevents creating a blank message for tool-only responses.
if (data.content && data.content.length > 0 && !this.streamingMessageElement) {
this.prepareStreamingMessage();
}
// If the streaming element exists, append content to it.
if (this.streamingMessageElement) {
if (data.content && data.content.length > 0) {
if (!this.streamingContent) {
this.streamingContent = '';
}
this.streamingContent += data.content;
// Update the display with formatted markdown (streaming mode)
this.streamingMessageElement.innerHTML = this.formatText(this.streamingContent, true);
this.scrollToBottom();
}
}
// When the stream is finished
if (data.done) {
// If a message bubble was created, finalize it.
if (this.streamingMessageElement) {
if (this.streamingContent) {
this.streamingMessageElement.innerHTML = this.formatText(this.streamingContent, false);
this.streamingMessageElement.classList.remove('streaming');
}
this.finishStreaming();
} else {
// If no bubble was created (e.g., tool-call-only response), just clean up.
this.hideTyping();
this.enableUserInput();
console.log('🦙 Streaming finished with only tool calls, no message bubble created.');
}
}
}
finishStreaming() {
// CRITICAL FIX: Clear sending flag when streaming is complete
this.currentlySendingMessage = false;
// Clean up streaming state
this.hideTyping(); // This will hide stop button and show send button
this.hideThinkingIndicator();
// Save the final message to conversation history
if (this.streamingContent && this.streamingContent.trim()) {
this.messages.push({
role: 'assistant',
content: this.streamingContent.trim(),
timestamp: Date.now()
});
this.saveConversationHistory();
}
this.streamingMessageElement = null;
this.streamingContent = '';
this.enableUserInput();
console.log('🦙 Streaming completed - input re-enabled');
}
showThinkingIndicator(thinkingText) {
let thinkingDiv = document.getElementById('thinkingIndicator');
if (!thinkingDiv) {
thinkingDiv = document.createElement('div');
thinkingDiv.id = 'thinkingIndicator';
thinkingDiv.className = 'thinking-indicator p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg mb-2';
thinkingDiv.innerHTML = `
<div class="flex items-center justify-between cursor-pointer" onclick="this.nextElementSibling.classList.toggle('hidden'); this.querySelector('.chevron').classList.toggle('rotate-180')">
<div class="text-xs font-semibold text-blue-400">🧠 AI Thinking Process</div>
<svg class="chevron w-3 h-3 text-blue-400 transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
</svg>
</div>
<div class="thinking-content hidden text-xs text-blue-300 max-h-32 overflow-y-auto mt-2 font-mono whitespace-pre-wrap bg-black/20 p-2 rounded border border-blue-500/20"></div>
`;
// Insert before typing indicator
if (this.typingIndicator && this.typingIndicator.parentNode === this.messagesContainer) {
this.messagesContainer.insertBefore(thinkingDiv, this.typingIndicator);
} else {
this.messagesContainer.appendChild(thinkingDiv);
}
}
const thinkingContent = thinkingDiv.querySelector('.thinking-content');
if (thinkingContent) {
thinkingContent.textContent = thinkingText;
}
this.scrollToBottom();
}
hideThinkingIndicator() {
const thinkingDiv = document.getElementById('thinkingIndicator');
if (thinkingDiv) {
thinkingDiv.remove();
}
}
showContextStatus(messageCount = null, trimmedCount = null) {
if (!this.contextStatus) return;
let statusText = '📝 Context: Processing conversation history';
if (messageCount && trimmedCount) {
statusText = `📝 Context: Sending ${messageCount} messages (${trimmedCount} summarized)`;
} else if (messageCount) {
statusText = `📝 Context: Sending ${messageCount} recent messages`;
}
this.contextStatus.textContent = statusText;
this.contextStatus.classList.remove('hidden');
}
hideContextStatus() {
if (this.contextStatus) {
this.contextStatus.classList.add('hidden');
}
}
handleUnifiedResponse(data) {
// CRITICAL FIX: Clear sending flag when response is complete
this.currentlySendingMessage = false;
this.hideTyping();
this.hideContextStatus();
this.enableUserInput(); // Re-enable input for non-streaming responses
if (data.success && data.message && data.message.trim()) {
this.addAssistantMessage(data.message);
}
else if (!data.success) {
this.updateStatusBar('❌ ' + (data.error || 'An unknown error occurred'));
}
}
handleAIMessageRequest(data) {
// Handle AI message requests from service worker (context menus, etc.)
this.showTyping();
// Send the AI request through the normal message system
this.sendChromeMessage({
type: 'SEND_MESSAGE',
data: {
message: data.message,
model: data.model || this.currentModel,
context: data.context,
conversationId: data.conversationId || this.currentConversationId,
stream: this.settings.streamingEnabled,
messages: this.messages
}
}).catch(error => {
this.hideTyping();
this.updateStatusBar('❌ Failed to send AI request: ' + error.message);
});
}
// ===== UNIFIED MESSAGE DISPLAY SYSTEM =====
createMessage(role, content = '', options = {}) {
const messageId = `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
const timestamp = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
const messageDiv = document.createElement('div');
messageDiv.className = 'message-item';
messageDiv.id = messageId;
if (role === 'user') {
messageDiv.innerHTML = `
<div class="flex justify-end p-2">
<div class="max-w-[80%] flex flex-col space-y-1">
<div class="bg-muted rounded-2xl rounded-br-sm px-4 py-2">
<div class="text-sm markdown-content">${this.formatText(content, false)}</div>
</div>
<div class="text-muted-foreground text-xs text-right">${timestamp}</div>
</div>
</div>
`;
} else if (role === 'assistant') {
messageDiv.innerHTML = `
<div class="flex flex-col gap-2 p-2">
<div class="flex items-center gap-2">
<div class="w-6 h-6 bg-blue-500 rounded-lg flex items-center justify-center text-white text-xs">🤖</div>
<div class="font-mono text-xs font-bold">${this.currentModel}</div>
<div class="text-xs text-muted-foreground ml-auto">${timestamp}</div>
</div>
<div class="message-content text-sm">
<div class="content-text markdown-content ${options.streaming ? 'streaming' : ''} ${options.typing ? 'typing' : ''}">${this.formatText(content, options.streaming)}</div>
</div>
</div>
`;
} else if (role === 'system') {
messageDiv.innerHTML = `
<div class="flex justify-center p-1">
<div class="text-xs text-muted-foreground bg-muted px-3 py-1 rounded-full markdown-content">
${this.formatText(content, false)}
</div>
</div>
`;
}
// Add to container before typing indicator (maintains proper order)
if (this.typingIndicator && this.typingIndicator.parentNode === this.messagesContainer) {
this.messagesContainer.insertBefore(messageDiv, this.typingIndicator);
} else {
this.messagesContainer.appendChild(messageDiv);
}
this.scrollToBottom();
// Add to conversation history (except system messages and typing indicators)
if (role !== 'system' && !options.typing && options.saveHistory !== false) {
this.messages.push({ role, content, timestamp });
// Auto-save conversation history
this.saveConversationHistory();
}
return messageDiv;
}
updateMessage(messageElement, content) {
const contentElement = messageElement.querySelector('.content-text');
if (contentElement) {
contentElement.innerHTML = this.formatText(content);
this.scrollToBottom();
}
}
formatText(text, isStreaming = false) {
if (text === null || text === undefined) return '';
const textStr = String(text);
// For streaming content, we need to be more careful about partial markdown
if (isStreaming) {
return this.formatStreamingText(textStr);
}
// For complete text, use full Marked.js processing
return this.formatCompleteText(textStr);
}
formatStreamingText(text) {
// During streaming, we can't use full markdown parsing because
// the content might be incomplete. Use basic formatting instead.
let html = this.escapeHtml(text);
// Only apply basic formatting that works with partial content
html = html
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em>$1</em>')
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\n/g, '<br>');
// Basic link detection for streaming
html = html.replace(/https?:\/\/[^\s<]+/g, (match) => {
const sanitizedUrl = this.sanitizeUrl(match);
if (sanitizedUrl) {
return `<a href="${sanitizedUrl}" target="_blank" rel="noopener noreferrer">${this.escapeHtml(match)}</a>`;
}
return this.escapeHtml(match);
});
return html;
}
formatCompleteText(text) {
try {
// Configure Marked with security settings
if (typeof marked !== 'undefined') {
marked.setOptions({
breaks: true, // Convert single line breaks to <br>
gfm: true, // GitHub Flavored Markdown
sanitize: false, // We'll handle sanitization ourselves
smartLists: true, // Better list parsing
smartypants: true, // Don't convert quotes/dashes
xhtml: false, // Use HTML5 tags
pedantic: false // Don't be overly strict
});
// Use Marked to parse the markdown
let html = marked.parse(text);
// Fix spacing issues by normalizing whitespace
html = html.replace(/\n+/g, '\n'); // Remove excessive newlines
html = html.replace(/\s+/g, ' '); // Normalize whitespace within lines
html = html.replace(/>\s+</g, '><'); // Remove spaces between tags
// Post-process for security: sanitize URLs
html = html.replace(/href="([^"]*)"/g, (match, url) => {
const sanitizedUrl = this.sanitizeUrl(url);
return sanitizedUrl ? `href="${sanitizedUrl}"` : 'href="#"';
});
// Add target="_blank" and rel="noopener noreferrer" to all links
html = html.replace(/<a /g, '<a target="_blank" rel="noopener noreferrer" ');
return html;
} else {
// Fallback if Marked.js isn't loaded
console.warn('Marked.js not available, falling back to basic formatting');
return this.formatStreamingText(text);
}
} catch (error) {
console.error('Error parsing markdown:', error);
// Fallback to basic formatting on error
return this.formatStreamingText(text);
}
}
sanitizeUrl(url) {
try {
const parsed = new URL(url);
// Only allow http and https protocols
if (['http:', 'https:'].includes(parsed.protocol)) {
return parsed.href;
}
return null; // Reject javascript:, data:, etc.
} catch (e) {
return null; // Invalid URL
}
}
sanitizeDataUrl(dataUrl) {
// Validate that this is a legitimate data URL
if (typeof dataUrl !== 'string') {
return '';
}
// Must start with data: and have valid MIME type
if (!dataUrl.startsWith('data:')) {
return '';
}
try {
// Parse the data URL to validate structure
const [header, data] = dataUrl.split(',');
if (!header || !data) {
return '';
}
// Validate MIME type is safe (only allow common image types)
const mimeMatch = header.match(/^data:([^;]+)/);
if (!mimeMatch) {
return '';
}
const mimeType = mimeMatch[1].toLowerCase();
const allowedMimeTypes = [
'image/jpeg', 'image/jpg', 'image/png', 'image/gif',
'image/webp', 'image/svg+xml', 'image/bmp'
];
if (!allowedMimeTypes.includes(mimeType)) {
return '';
}
// Validate base64 data if specified
if (header.includes('base64')) {
// Basic validation - should only contain valid base64 characters
if (!/^[A-Za-z0-9+/]*=*$/.test(data)) {
return '';
}
}
return dataUrl;
} catch (e) {
return '';
}
}
escapeHtml(text) {
// Use shared utility to eliminate code duplication
return SharedUtils.escapeHtml(text);
}
addAssistantMessage(content, streaming = false) {
return this.createMessage('assistant', content, { streaming });