forked from shiftonetothree/chrome-LLM-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1328 lines (1142 loc) · 44.9 KB
/
Copy pathpopup.js
File metadata and controls
1328 lines (1142 loc) · 44.9 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
// Popup script - handles multiple LLM providers
// =============================================================================
// TabDataStore — central data layer for all per-tab state
// Data lives as long as the extension page is open (sidepanel mode).
// View just switches which tab's data it renders — no data is destroyed on tab switch.
// =============================================================================
class TabDataStore {
constructor() {
this._tabs = {}; // tabId -> { tabId, pageContext, conversationHistory, streaming, dirty }
}
// ---- internal helpers ----
_storageKey(tabId) {
return `conversation_${tabId}`;
}
_ensure(tabId) {
if (!this._tabs[tabId]) {
this._tabs[tabId] = {
tabId,
pageContext: null,
conversationHistory: [],
streaming: null, // { messageId, content, done, stopped, toolMessages }
dirty: false
};
}
return this._tabs[tabId];
}
// ---- lifecycle ----
getOrCreate(tabId) {
return this._ensure(tabId);
}
remove(tabId) {
delete this._tabs[tabId];
}
// ---- conversation operations ----
getConversation(tabId) {
return this._ensure(tabId).conversationHistory;
}
appendMessage(tabId, message) {
const t = this._ensure(tabId);
t.conversationHistory.push(message);
t.dirty = true;
}
appendToolMessages(tabId, msgs) {
const t = this._ensure(tabId);
for (const m of msgs) {
t.conversationHistory.push(m);
}
t.dirty = true;
}
setConversation(tabId, history) {
const t = this._ensure(tabId);
t.conversationHistory = history;
t.dirty = false; // just loaded, not dirty
}
clearConversation(tabId) {
const t = this._ensure(tabId);
t.conversationHistory = [];
t.dirty = true;
}
// ---- streaming operations (pure memory, no persistence) ----
startStreaming(tabId, messageId) {
const t = this._ensure(tabId);
t.streaming = { messageId, content: '', done: false, stopped: false, toolMessages: [] };
}
updateStreamContent(tabId, content) {
const t = this._ensure(tabId);
if (t.streaming) t.streaming.content = content;
}
updateStreamDone(tabId, done) {
const t = this._ensure(tabId);
if (t.streaming) t.streaming.done = done;
}
updateStreamToolMessages(tabId, toolMessages) {
const t = this._ensure(tabId);
if (t.streaming) t.streaming.toolMessages = toolMessages;
}
getStreaming(tabId) {
const t = this._tabs[tabId];
return t ? t.streaming : null;
}
stopStreaming(tabId) {
const t = this._ensure(tabId);
if (!t.streaming) return '';
t.streaming.done = true;
t.streaming.stopped = true;
return t.streaming.content;
}
finalizeStreaming(tabId) {
const t = this._ensure(tabId);
if (!t.streaming) return;
const s = t.streaming;
if (s.content) {
t.conversationHistory.push({ role: 'assistant', content: s.content });
}
if (s.toolMessages && s.toolMessages.length > 0) {
for (const tm of s.toolMessages) {
t.conversationHistory.push(tm);
}
}
t.streaming = null;
t.dirty = true;
}
// ---- page context ----
getPageContext(tabId) {
const t = this._tabs[tabId];
return t ? t.pageContext : null;
}
setPageContext(tabId, ctx) {
this._ensure(tabId).pageContext = ctx;
}
// ---- persistence ----
async persist(tabId) {
const t = this._tabs[tabId];
if (!t) return;
try {
const key = this._storageKey(tabId);
await chrome.storage.local.set({
[key]: {
history: t.conversationHistory,
pageContext: t.pageContext,
savedAt: Date.now()
}
});
t.dirty = false;
} catch (error) {
console.error('[DataStore] Error saving conversation:', error);
}
}
async load(tabId) {
try {
const key = this._storageKey(tabId);
const result = await chrome.storage.local.get([key]);
if (result[key]) {
const t = this._ensure(tabId);
t.conversationHistory = result[key].history || [];
if (result[key].pageContext) {
t.pageContext = result[key].pageContext;
}
t.dirty = false;
return result[key];
}
} catch (error) {
console.error('[DataStore] Error loading conversation:', error);
}
return null;
}
async removePersisted(tabId) {
try {
await chrome.storage.local.remove([this._storageKey(tabId)]);
} catch (error) {
console.error('[DataStore] Error removing conversation:', error);
}
}
// Check if tab has any data (for UI to decide whether to show welcome message)
hasConversation(tabId) {
const t = this._tabs[tabId];
return t && t.conversationHistory.length > 0;
}
}
// =============================================================================
// Global state — View layer only
// =============================================================================
const store = new TabDataStore();
let activeTabId = null; // currently displayed tab
let activeStreamEl = null; // streaming message DOM element in the active tab
let isFirstChunkAfterStreamStart = false;
let isFetchingModels = false;
let lastDebugInfo = { systemContent: '', userText: '' };
let searchEngines = null;
let enabledSearchEngines = { bing: true, google: false, baidu: false, wikipedia: false };
// DOM Elements
const chatContainer = document.getElementById('chatContainer');
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const stopBtn = document.getElementById('stopBtn');
const statusEl = document.getElementById('status');
const pageTitleEl = document.getElementById('pageTitle');
const pageUrlEl = document.getElementById('pageUrl');
const contextBanner = document.getElementById('contextBanner');
const loadingIndicator = document.getElementById('loadingIndicator');
const apiKeyInput = document.getElementById('apiKey');
const providerSelect = document.getElementById('providerSelect');
const modelSelect = document.getElementById('modelSelect');
const customEndpointRow = document.getElementById('customEndpointRow');
const customEndpointInput = document.getElementById('customEndpoint');
const refreshModelsBtn = document.getElementById('refreshModelsBtn');
const configToggleRow = document.getElementById('configToggleRow');
const toggleConfigBtn = document.getElementById('toggleConfigBtn');
// Provider presets
const PROVIDERS = {
openai: { name: 'OpenAI', endpoint: 'https://api.openai.com/v1/chat/completions', modelsEndpoint: 'https://api.openai.com/v1/models', modelKey: 'id', defaultModel: 'gpt-4o' },
deepseek: { name: 'DeepSeek', endpoint: 'https://api.deepseek.com/v1/chat/completions', modelsEndpoint: 'https://api.deepseek.com/v1/models', modelKey: 'id', defaultModel: 'deepseek-chat' },
siliconflow: { name: 'SiliconFlow', endpoint: 'https://api.siliconflow.cn/v1/chat/completions', modelsEndpoint: 'https://api.siliconflow.cn/v1/models', modelKey: 'id', defaultModel: 'deepseek-ai/DeepSeek-V2.5' },
ollama: { name: 'Ollama', endpoint: 'http://localhost:11434/v1/chat/completions', modelsEndpoint: 'http://localhost:11434/api/tags', modelKey: 'name', defaultModel: 'llama3' },
custom: { name: 'Custom', endpoint: '', modelsEndpoint: '', modelKey: 'id', defaultModel: '' }
};
// =============================================================================
// View helpers — pure DOM manipulation
// =============================================================================
// Allowed tags/attributes for AI-generated Markdown content
const ALLOWED_TAGS = new Set([
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'p', 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
'a', 'strong', 'b', 'em', 'i', 'u', 's', 'del', 'sub', 'sup',
'code', 'pre', 'blockquote',
'table', 'thead', 'tbody', 'tr', 'th', 'td',
'hr', 'br', 'img', 'span', 'div',
'section', 'article', 'header', 'footer'
]);
const ALLOWED_ATTRS = new Set([
'href', 'src', 'alt', 'title', 'class', 'id', 'target', 'rel',
'width', 'height', 'colspan', 'rowspan', 'scope'
]);
function sanitizeHTML(html) {
try {
const doc = new DOMParser().parseFromString('<div>' + html + '</div>', 'text/html');
const container = doc.body.firstChild;
function cleanNode(node) {
if (node.nodeType === Node.TEXT_NODE) return;
if (node.nodeType === Node.ELEMENT_NODE) {
if (!ALLOWED_TAGS.has(node.tagName.toLowerCase())) {
// Replace disallowed tag with its text content
const text = node.textContent;
node.replaceWith(document.createTextNode(text));
return;
}
// Remove disallowed attributes
const attrsToRemove = [];
for (const attr of node.attributes) {
if (!ALLOWED_ATTRS.has(attr.name.toLowerCase())) {
attrsToRemove.push(attr.name);
} else if (attr.name.toLowerCase() === 'href' && attr.value.trim().toLowerCase().startsWith('javascript:')) {
attrsToRemove.push(attr.name);
}
}
for (const name of attrsToRemove) {
node.removeAttribute(name);
}
// Recursively clean children (iterate backwards since we may replace nodes)
let child = node.firstChild;
while (child) {
const next = child.nextSibling;
cleanNode(child);
child = next;
}
}
}
cleanNode(container);
return container.innerHTML;
} catch (e) {
// Fallback: return text-only version
const div = document.createElement('div');
div.textContent = html;
return div.innerHTML;
}
}
function addMessage(role, content) {
const msg = document.createElement('div');
msg.className = `message ${role}`;
const fontSize = (fontSizeSlider?.value || 12) + 'px';
if (role === 'assistant' && typeof marked !== 'undefined' && content) {
const parsed = marked.parse(content);
if (parsed && parsed.trim()) {
msg.innerHTML = sanitizeHTML(parsed);
} else {
msg.textContent = content;
}
} else {
msg.textContent = content || '';
}
msg.style.fontSize = fontSize;
chatContainer.appendChild(msg);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
function addPlaceholderMessage(text) {
const msg = document.createElement('div');
msg.className = 'message assistant placeholder-message';
msg.textContent = text;
chatContainer.appendChild(msg);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
function showLoading(show) {
loadingIndicator.classList.toggle('active', show);
}
function restoreInputState() {
showLoading(false);
sendBtn.style.display = 'block';
stopBtn.style.display = 'none';
userInput.disabled = false;
userInput.focus();
}
function renderConversation(tabId) {
const history = store.getConversation(tabId);
history.forEach(msg => {
if (msg.role === 'tool') return;
if (msg.role === 'assistant' && msg.tool_calls) return;
addMessage(msg.role, msg.content);
});
}
// Render or update the streaming message element from the store
function renderStreamingMessage(tabId) {
const streaming = store.getStreaming(tabId);
if (!streaming) return;
const content = streaming.content || '';
if (streaming.done) {
// Finalize streaming into a regular message
if (activeStreamEl) {
const currentFontSize = fontSizeSlider?.value || 12;
if (typeof marked !== 'undefined' && content) {
activeStreamEl.innerHTML = sanitizeHTML(marked.parse(content));
} else {
activeStreamEl.textContent = content || '(已停止生成)';
}
activeStreamEl.style.fontSize = currentFontSize + 'px';
activeStreamEl.classList.remove('streaming');
activeStreamEl = null;
}
store.finalizeStreaming(tabId);
store.persist(tabId);
restoreInputState();
statusEl.textContent = streaming.stopped ? '已停止' : '就绪';
} else {
// Update or create streaming element
if (!activeStreamEl) {
activeStreamEl = document.createElement('div');
activeStreamEl.className = 'message assistant streaming';
chatContainer.appendChild(activeStreamEl);
showLoading(true);
sendBtn.style.display = 'none';
stopBtn.style.display = 'block';
}
const currentFontSize = fontSizeSlider?.value || 12;
let shouldScrollToBottom;
if (isFirstChunkAfterStreamStart) {
shouldScrollToBottom = true;
isFirstChunkAfterStreamStart = false;
} else {
const threshold = 50;
shouldScrollToBottom = chatContainer.scrollTop + chatContainer.clientHeight >= chatContainer.scrollHeight - threshold;
}
if (typeof marked !== 'undefined' && content) {
activeStreamEl.innerHTML = sanitizeHTML(marked.parse(content)) + '<span class="streaming-cursor">▊</span>';
} else if (content) {
activeStreamEl.textContent = content;
} else {
activeStreamEl.innerHTML = '<span class="streaming-cursor">▊</span>';
}
activeStreamEl.style.fontSize = currentFontSize + 'px';
if (shouldScrollToBottom) {
chatContainer.scrollTop = chatContainer.scrollHeight;
}
}
}
// Switch the view to a different tab — load data from store, render UI
async function switchToTab(tabId) {
if (!tabId) return;
const prevTabId = activeTabId;
const isDifferentTab = prevTabId !== null && prevTabId !== tabId;
// If switching AWAY from a tab that has an active stream, we DON'T clear
// the streaming state in the store — data stays. We just detach the DOM element.
if (isDifferentTab) {
activeStreamEl = null;
isFirstChunkAfterStreamStart = false;
restoreInputState();
}
activeTabId = tabId;
store.getOrCreate(tabId);
// Clear UI
chatContainer.innerHTML = '';
activeStreamEl = null;
isFirstChunkAfterStreamStart = false;
// Load page context from store (memory) — fetch fresh if switching tabs
let pageContext = store.getPageContext(tabId);
if (isDifferentTab || !pageContext) {
statusEl.textContent = '加载页面...';
if (pageTitleEl) pageTitleEl.textContent = '正在加载页面内容...';
if (pageUrlEl) pageUrlEl.textContent = '';
if (contextBanner) contextBanner.style.borderLeft = '3px solid #666';
try {
const response = await chrome.tabs.sendMessage(tabId, { type: 'GET_PAGE_CONTENT' });
if (response && response.content) {
store.setPageContext(tabId, response.content);
pageContext = response.content;
}
} catch (error) {
// Page may not be injectable — that's OK
}
}
// Update header UI
if (pageContext) {
if (pageTitleEl) pageTitleEl.textContent = pageContext.title || '无标题页面';
if (pageUrlEl) pageUrlEl.textContent = pageContext.url;
if (contextBanner) contextBanner.style.borderLeft = '3px solid #4ade80';
statusEl.textContent = '就绪';
statusEl.classList.add('ready');
} else {
if (pageTitleEl) pageTitleEl.textContent = '无法提取页面内容';
statusEl.textContent = '页面受限';
}
// Render existing conversation from store
if (store.hasConversation(tabId)) {
renderConversation(tabId);
} else if (!apiKeyInput.value.trim()) {
addPlaceholderMessage('👋 你好!请先在顶部配置你的 AI API,然后就可以开始对话了。');
}
// If this tab has a live stream in the store, render it
const streaming = store.getStreaming(tabId);
if (streaming && !streaming.done) {
activeStreamEl = document.createElement('div');
activeStreamEl.className = 'message assistant streaming';
const currentFontSize = fontSizeSlider?.value || 12;
activeStreamEl.style.fontSize = currentFontSize + 'px';
const content = streaming.content || '';
if (typeof marked !== 'undefined' && content) {
activeStreamEl.innerHTML = sanitizeHTML(marked.parse(content)) + '<span class="streaming-cursor">▊</span>';
} else if (content) {
activeStreamEl.textContent = content;
} else {
activeStreamEl.innerHTML = '<span class="streaming-cursor">▊</span>';
}
chatContainer.appendChild(activeStreamEl);
chatContainer.scrollTop = chatContainer.scrollHeight;
showLoading(true);
sendBtn.style.display = 'none';
stopBtn.style.display = 'block';
statusEl.textContent = '接收中...';
} else if (streaming && streaming.done) {
// Stream completed while we were away — finalize it
store.finalizeStreaming(tabId);
store.persist(tabId);
// Re-render to show the finalized message
chatContainer.innerHTML = '';
renderConversation(tabId);
}
}
// =============================================================================
// Config & Provider Logic
// =============================================================================
async function loadConfig() {
const result = await chrome.storage.local.get(['provider', 'apiKey', 'model', 'customEndpoint', 'searchEngines']);
if (result.provider) providerSelect.value = result.provider;
if (result.apiKey) apiKeyInput.value = result.apiKey;
if (result.model) {}
if (result.customEndpoint) customEndpointInput.value = result.customEndpoint;
if (result.searchEngines) {
enabledSearchEngines = result.searchEngines;
}
try {
const resp = await chrome.runtime.sendMessage({ type: 'GET_SEARCH_ENGINES' });
if (resp && resp.engines) {
searchEngines = resp.engines;
}
} catch (e) {
console.error('Failed to fetch search engines:', e);
}
customEndpointRow.classList.toggle('show', providerSelect.value === 'custom');
updateModelSelectState();
showConfig();
if (result.provider && result.apiKey) {
fetchModels();
}
}
async function saveConfig() {
await chrome.storage.local.set({
provider: providerSelect.value,
apiKey: apiKeyInput.value,
model: modelSelect.value,
customEndpoint: customEndpointInput.value
});
}
function updateModelSelectState() {
const hasProvider = !!providerSelect.value;
const hasApiKey = !!apiKeyInput.value.trim();
const isCustom = providerSelect.value === 'custom';
modelSelect.disabled = !hasProvider || !hasApiKey;
if (!hasProvider) {
modelSelect.innerHTML = '<option value="">-- 选择提供商 --</option>';
} else if (!hasApiKey) {
modelSelect.innerHTML = '<option value="">-- 填写 API Key --</option>';
} else if (isCustom) {
modelSelect.innerHTML = '<option value="">-- 自定义模型名称 --</option>';
}
refreshModelsBtn.style.display = hasProvider && hasApiKey && !isCustom ? 'block' : 'none';
}
async function fetchModels() {
const provider = providerSelect.value;
const apiKey = apiKeyInput.value.trim();
if (!provider || !apiKey) return;
if (isFetchingModels) return;
isFetchingModels = true;
const originalText = refreshModelsBtn.textContent;
refreshModelsBtn.textContent = '⏳';
refreshModelsBtn.disabled = true;
try {
const response = await chrome.runtime.sendMessage({
type: 'FETCH_MODELS',
config: { provider, apiKey, customEndpoint: customEndpointInput.value.trim() }
});
if (response.error) throw new Error(response.error);
modelSelect.innerHTML = '<option value="">-- 选择模型 --</option>';
if (response.models && response.models.length > 0) {
response.models.forEach(model => {
const option = document.createElement('option');
option.value = model;
option.textContent = model;
modelSelect.appendChild(option);
});
const providerPreset = PROVIDERS[provider];
if (providerPreset?.defaultModel) {
const defaultExists = response.models.find(m =>
m.toLowerCase().includes(providerPreset.defaultModel.toLowerCase())
);
if (defaultExists) modelSelect.value = defaultExists;
}
} else {
modelSelect.innerHTML = '<option value="">-- 无法获取,自动填充 --</option>';
}
const saved = await chrome.storage.local.get(['model']);
if (saved.model && modelSelect.querySelector(`option[value="${saved.model}"]`)) {
modelSelect.value = saved.model;
}
statusEl.textContent = '已加载 ' + (response.models?.length || 0) + ' 个模型';
statusEl.classList.add('ready');
hideConfig();
} catch (error) {
console.error('Error fetching models:', error);
statusEl.textContent = '获取模型失败';
statusEl.classList.add('error');
modelSelect.innerHTML = '<option value="">-- 获取失败 --</option>';
showConfig();
setTimeout(() => {
statusEl.classList.remove('error');
statusEl.textContent = '就绪';
}, 2000);
} finally {
isFetchingModels = false;
refreshModelsBtn.textContent = originalText;
refreshModelsBtn.disabled = false;
}
}
function showConfig() {
configToggleRow.classList.add('show');
toggleConfigBtn.classList.add('active');
}
function hideConfig() {
configToggleRow.classList.remove('show');
toggleConfigBtn.classList.remove('active');
}
// =============================================================================
// Page Context & Tools
// =============================================================================
function buildSystemContent() {
const pageContext = activeTabId ? store.getPageContext(activeTabId) : null;
let systemContent = 'You are a helpful AI assistant.';
if (pageContext) {
systemContent = `You are an AI assistant helping the user understand a webpage.\n\n`;
systemContent += `Page Title: ${pageContext.title}\n`;
systemContent += `Page URL: ${pageContext.url}\n\n`;
systemContent += `Page Content:\n${pageContext.text}\n\n`;
if (pageContext.subtitles && pageContext.subtitles.raw) {
const formattedSubtitles = pageContext.subtitles.raw.map(item => {
const fromSec = item.from || 0;
const min = Math.floor(fromSec / 60);
const sec = Math.floor(fromSec % 60);
const timestamp = `${min}:${sec.toString().padStart(2, '0')}`;
const text = (item.content || '').replace(/<[^>]+>/g, '').trim();
return `[${timestamp}] ${text}`;
}).join('\n');
systemContent += `=== Subtitles ===\n${formattedSubtitles}\n\n`;
}
if (pageContext.comments && pageContext.comments.length > 0) {
const commentsStr = pageContext.comments
.map(c => {
const prefix = c.isReply ? '[Reply] ' : '[Comment] ';
const userPart = c.user ? c.user + ': ' : '';
const timePart = c.time ? ` (${c.time})` : '';
return prefix + userPart + c.text + timePart;
})
.join('\n');
systemContent += `=== Comments ===\n${commentsStr}\n\n`;
}
systemContent += `Please answer the user's questions based on this content. Be helpful and concise.
You have access to web search tools (up to 3 uses total per response).
Use web search when:
- The user asks you to verify/fact-check information
- The user needs real-time/current information not present in the page content
- The user explicitly asks you to search for something
- You are uncertain about a claim and need to verify it
Available search tools — use ONLY those listed here:`;
const enabledEntries = Object.entries(searchEngines || {}).filter(([id]) => enabledSearchEngines[id]);
const disabledEntries = Object.entries(searchEngines || {}).filter(([id]) => !enabledSearchEngines[id]);
if (enabledEntries.length > 0) {
for (const [id, eng] of enabledEntries) {
systemContent += '\n- ' + eng.toolName + ': ' + eng.toolDescription;
}
} else {
systemContent += '\n- No search tools enabled.';
}
if (disabledEntries.length > 0) {
systemContent += '\n\nThe following tools are DISABLED and will return an error if called: ' +
disabledEntries.map(([id, eng]) => eng.toolName + ' (' + eng.name + ')').join(', ') + '. ' +
'DO NOT call these — pick from the available tools above instead.';
}
systemContent += `
Search results include titles, URLs, and snippets. Use these to provide accurate, up-to-date answers with source citations.
If you run out of searches, answer based on what you already found. If no results were found, state that honestly.`;
}
return systemContent;
}
async function refreshPageContext() {
if (!activeTabId) return false;
try {
const response = await chrome.tabs.sendMessage(activeTabId, { type: 'GET_PAGE_CONTENT' });
if (response && response.content) {
store.setPageContext(activeTabId, response.content);
if (pageTitleEl) pageTitleEl.textContent = response.content.title || '无标题页面';
if (pageUrlEl) pageUrlEl.textContent = response.content.url;
if (contextBanner) contextBanner.style.borderLeft = '3px solid #4ade80';
return true;
}
} catch (error) {
console.error('Error refreshing page context:', error);
}
return false;
}
function buildSearchTools() {
if (!searchEngines) return [];
const tools = [];
for (const [id, engine] of Object.entries(searchEngines)) {
if (!enabledSearchEngines[id]) continue;
tools.push({
type: 'function',
function: {
name: engine.toolName,
description: engine.toolDescription,
parameters: {
type: 'object',
properties: {
query: {
type: 'string',
description: 'The search query. Be specific and use keywords for best results.'
}
},
required: ['query']
}
}
});
}
return tools;
}
// =============================================================================
// Send / Stop Stream
// =============================================================================
async function sendMessage() {
const text = userInput.value.trim();
if (!text) return;
const provider = providerSelect.value;
const apiKey = apiKeyInput.value.trim();
const model = modelSelect.value;
const customEndpoint = customEndpointInput.value.trim();
if (!provider) { addMessage('error', '请先选择一个 AI 提供商。'); return; }
if (!apiKey) { addMessage('error', '请先填写 API Key。'); return; }
if (!model && provider !== 'custom') { addMessage('error', '请先选择一个模型,或手动输入模型名称。'); return; }
const userText = text;
const placeholder = chatContainer.querySelector('.placeholder-message');
if (placeholder) placeholder.remove();
addMessage('user', text);
userInput.value = '';
store.appendMessage(activeTabId, { role: 'user', content: text });
await store.persist(activeTabId);
showLoading(true);
sendBtn.style.display = 'none';
stopBtn.style.display = 'block';
statusEl.textContent = '刷新页面内容...';
try {
await refreshPageContext();
statusEl.textContent = '发送中...';
const systemContent = buildSystemContent();
lastDebugInfo = { systemContent, userText };
const messages = [
{ role: 'system', content: systemContent },
...store.getConversation(activeTabId)
];
const actualModel = model || (provider === 'custom' ? 'custom-model' : '');
const config = { provider, apiKey, model: actualModel, customEndpoint };
const tools = buildSearchTools();
chrome.runtime.sendMessage({
type: 'SEND_TO_AI',
config,
messages,
tools,
senderTabId: activeTabId
}).catch(error => {
addMessage('error', `错误: ${error.message}`);
restoreInputState();
store.getConversation(activeTabId).pop();
store.persist(activeTabId);
statusEl.textContent = '就绪';
});
} catch (error) {
addMessage('error', `错误: ${error.message}`);
store.getConversation(activeTabId).pop();
await store.persist(activeTabId);
statusEl.textContent = '就绪';
}
}
function stopStream() {
const streaming = store.getStreaming(activeTabId);
if (!streaming || !streaming.messageId) return;
console.log('[POPUP] User requested stop stream for tab:', activeTabId);
statusEl.textContent = '正在停止...';
chrome.runtime.sendMessage({
type: 'STOP_STREAM',
senderTabId: activeTabId
}).catch(() => {});
// Finalize locally
if (activeStreamEl) {
const currentFontSize = fontSizeSlider?.value || 12;
const content = streaming.content || '';
if (typeof marked !== 'undefined' && content) {
activeStreamEl.innerHTML = sanitizeHTML(marked.parse(content));
} else {
activeStreamEl.textContent = content || '(已停止生成)';
}
activeStreamEl.style.fontSize = currentFontSize + 'px';
activeStreamEl.classList.remove('streaming');
activeStreamEl = null;
}
store.finalizeStreaming(activeTabId);
store.persist(activeTabId);
isFirstChunkAfterStreamStart = false;
restoreInputState();
statusEl.textContent = '已停止';
}
// =============================================================================
// Initialization (DOMContentLoaded)
// =============================================================================
document.addEventListener('DOMContentLoaded', async () => {
await loadConfig();
statusEl.textContent = '加载页面...';
// Get the active content tab (not the extension page itself)
const currentWindow = await chrome.windows.getLastFocused();
const resp = await chrome.runtime.sendMessage({
type: 'GET_ACTIVE_CONTENT_TAB',
windowId: currentWindow.id
});
const initialTabId = resp.tabId;
if (initialTabId) {
// Load conversation from storage into store
await store.load(initialTabId);
// Fetch page context
try {
const response = await chrome.tabs.sendMessage(initialTabId, { type: 'GET_PAGE_CONTENT' });
if (response && response.content) {
store.setPageContext(initialTabId, response.content);
if (pageTitleEl) pageTitleEl.textContent = response.content.title || '无标题页面';
if (pageUrlEl) pageUrlEl.textContent = response.content.url;
if (contextBanner) contextBanner.style.borderLeft = '3px solid #4ade80';
statusEl.textContent = '就绪';
statusEl.classList.add('ready');
} else {
if (pageTitleEl) pageTitleEl.textContent = '无法提取页面内容';
statusEl.textContent = '页面受限';
}
} catch (error) {
if (pageTitleEl) pageTitleEl.textContent = '无法访问此页面';
if (pageUrlEl) pageUrlEl.textContent = error.message;
statusEl.textContent = '页面错误';
}
// Set active tab BEFORE rendering (renderConversation uses activeTabId)
activeTabId = initialTabId;
if (store.hasConversation(initialTabId)) {
renderConversation(initialTabId);
statusEl.textContent = '已恢复对话';
setTimeout(() => {
if (statusEl.textContent === '已恢复对话') {
statusEl.textContent = '就绪';
}
}, 2000);
} else if (!apiKeyInput.value.trim()) {
addPlaceholderMessage('👋 你好!请先在顶部配置你的 AI API,然后就可以开始对话了。');
}
// Reconnect to any active stream (popup closed/reopened mid-stream)
const streamState = await chrome.runtime.sendMessage({
type: 'GET_STREAM_STATE',
senderTabId: initialTabId
}).catch(() => ({ active: false }));
if (streamState && streamState.active) {
console.log('[POPUP] Reconnecting to active stream, messageId:', streamState.messageId, 'content length:', (streamState.content || '').length);
store.startStreaming(initialTabId, streamState.messageId);
store.updateStreamContent(initialTabId, streamState.content || '');
if (streamState.done) {
store.updateStreamDone(initialTabId, true);
if (streamState.toolMessages) {
store.updateStreamToolMessages(initialTabId, streamState.toolMessages);
}
store.finalizeStreaming(initialTabId);
store.persist(initialTabId);
// Re-render to show finalized message
chatContainer.innerHTML = '';
renderConversation(initialTabId);
} else {
// Show live content with cursor
activeStreamEl = document.createElement('div');
activeStreamEl.className = 'message assistant streaming';
const currentFontSize = fontSizeSlider?.value || 12;
activeStreamEl.style.fontSize = currentFontSize + 'px';
const content = streamState.content || '';
if (typeof marked !== 'undefined' && content) {
activeStreamEl.innerHTML = sanitizeHTML(marked.parse(content)) + '<span class="streaming-cursor">▊</span>';
} else if (content) {
activeStreamEl.textContent = content;
} else {
activeStreamEl.innerHTML = '<span class="streaming-cursor">▊</span>';
}
chatContainer.appendChild(activeStreamEl);
chatContainer.scrollTop = chatContainer.scrollHeight;
showLoading(true);
sendBtn.style.display = 'none';
stopBtn.style.display = 'block';
statusEl.textContent = '接收中...';
}
}
} else {
activeTabId = initialTabId;
if (pageTitleEl) pageTitleEl.textContent = '无可用页面';
statusEl.textContent = '无活动页面';
if (!apiKeyInput.value.trim()) {
addPlaceholderMessage('👋 你好!请先在顶部配置你的 AI API,然后就可以开始对话了。');
}
}
});
// =============================================================================
// Streaming Message Handling (chrome.runtime.onMessage)
// =============================================================================
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('[POPUP] Received message type:', request.type, 'senderTabId:', request.senderTabId, 'activeTabId:', activeTabId);
const msgTabId = request.senderTabId;
const isActive = msgTabId === activeTabId;
if (request.type === 'STREAM_START') {
console.log('[POPUP] STREAM_START received, messageId:', request.messageId);
// Always update store regardless of whether this tab is active
store.startStreaming(msgTabId, request.messageId);
if (isActive) {
// If already have a streaming element (reconnect), skip
if (activeStreamEl && store.getStreaming(msgTabId)) {
console.log('[POPUP] STREAM_START skipped - already have streaming element');
sendResponse({ received: true });
return true;
}
isFirstChunkAfterStreamStart = true;
activeStreamEl = document.createElement('div');
activeStreamEl.className = 'message assistant streaming';
const currentFontSize = fontSizeSlider?.value || 12;
activeStreamEl.style.fontSize = currentFontSize + 'px';
activeStreamEl.innerHTML = '<span class="streaming-cursor">▊</span>';
chatContainer.appendChild(activeStreamEl);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
sendResponse({ received: true });
return true;
}
if (request.type === 'STREAM_CHUNK') {
const content = request.content || '';