-
Notifications
You must be signed in to change notification settings - Fork 854
Expand file tree
/
Copy pathindex.mjs
More file actions
1013 lines (978 loc) · 37.5 KB
/
index.mjs
File metadata and controls
1013 lines (978 loc) · 37.5 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
import Browser from 'webextension-polyfill'
import {
deleteConversation,
generateAnswersWithChatgptWebApi,
sendMessageFeedback,
} from '../services/apis/chatgpt-web'
import { generateAnswersWithBingWebApi } from '../services/apis/bing-web.mjs'
import {
generateAnswersWithOpenAiApi,
generateAnswersWithGptCompletionApi,
} from '../services/apis/openai-api'
import { generateAnswersWithCustomApi } from '../services/apis/custom-api.mjs'
import { generateAnswersWithOllamaApi } from '../services/apis/ollama-api.mjs'
import { generateAnswersWithAzureOpenaiApi } from '../services/apis/azure-openai-api.mjs'
import { generateAnswersWithClaudeApi } from '../services/apis/claude-api.mjs'
import { generateAnswersWithChatGLMApi } from '../services/apis/chatglm-api.mjs'
import { generateAnswersWithWaylaidwandererApi } from '../services/apis/waylaidwanderer-api.mjs'
import { generateAnswersWithOpenRouterApi } from '../services/apis/openrouter-api.mjs'
import { generateAnswersWithAimlApi } from '../services/apis/aiml-api.mjs'
import {
defaultConfig,
getUserConfig,
setUserConfig,
isUsingChatgptWebModel,
isUsingBingWebModel,
isUsingGptCompletionApiModel,
isUsingChatgptApiModel,
isUsingCustomModel,
isUsingOllamaApiModel,
isUsingAzureOpenAiApiModel,
isUsingClaudeApiModel,
isUsingChatGLMApiModel,
isUsingGithubThirdPartyApiModel,
isUsingGeminiWebModel,
isUsingClaudeWebModel,
isUsingMoonshotApiModel,
isUsingMoonshotWebModel,
isUsingOpenRouterApiModel,
isUsingAimlApiModel,
isUsingDeepSeekApiModel,
isUsingMiniMaxApiModel,
} from '../config/index.mjs'
import '../_locales/i18n'
import { openUrl } from '../utils/open-url'
import {
getBardCookies,
getBingAccessToken,
getChatGptAccessToken,
getClaudeSessionKey,
registerPortListener,
} from '../services/wrappers.mjs'
import { refreshMenu } from './menus.mjs'
import { registerCommands } from './commands.mjs'
import { generateAnswersWithBardWebApi } from '../services/apis/bard-web.mjs'
import { generateAnswersWithClaudeWebApi } from '../services/apis/claude-web.mjs'
import { generateAnswersWithMoonshotCompletionApi } from '../services/apis/moonshot-api.mjs'
import { generateAnswersWithMoonshotWebApi } from '../services/apis/moonshot-web.mjs'
import { isUsingModelName } from '../utils/model-name-convert.mjs'
import { generateAnswersWithDeepSeekApi } from '../services/apis/deepseek-api.mjs'
import { generateAnswersWithMiniMaxApi } from '../services/apis/minimax-api.mjs'
import { redactSensitiveFields } from './redact.mjs'
const RECONNECT_CONFIG = {
MAX_ATTEMPTS: 5,
BASE_DELAY_MS: 1000, // Base delay in milliseconds
BACKOFF_MULTIPLIER: 2, // Multiplier for exponential backoff
STABLE_CONNECT_RESET_DELAY_MS: 3000, // Reset retries only after connection stays stable
}
function setPortProxy(port, proxyTabId) {
try {
console.debug(`[background] Attempting to connect to proxy tab: ${proxyTabId}`)
if (port._reconnectTimerId) {
clearTimeout(port._reconnectTimerId)
port._reconnectTimerId = null
}
if (port._reconnectStabilityTimerId) {
clearTimeout(port._reconnectStabilityTimerId)
port._reconnectStabilityTimerId = null
}
if (port.proxy) {
const previousProxy = port.proxy
try {
if (port._proxyOnMessage) previousProxy.onMessage.removeListener(port._proxyOnMessage)
if (port._proxyOnDisconnect) {
previousProxy.onDisconnect.removeListener(port._proxyOnDisconnect)
}
} catch (e) {
console.warn(
'[background] Error removing old listeners from previous port.proxy instance:',
e,
)
}
try {
if (typeof previousProxy.disconnect === 'function') {
previousProxy.disconnect()
}
} catch (e) {
console.warn('[background] Error disconnecting previous port.proxy instance:', e)
} finally {
port.proxy = null
port._proxyTabId = null
}
}
if (port._portOnMessage) port.onMessage.removeListener(port._portOnMessage)
if (port._portOnDisconnect) port.onDisconnect.removeListener(port._portOnDisconnect)
port.proxy = Browser.tabs.connect(proxyTabId, { name: 'background-to-content-script-proxy' })
port._proxyTabId = proxyTabId
port._isClosed = false
console.debug(`[background] Successfully connected to proxy tab: ${proxyTabId}`)
port._proxyOnMessage = (msg) => {
const redactedMsg = redactSensitiveFields(msg)
console.debug('[background] Message from proxy tab (redacted):', redactedMsg)
if (port._reconnectAttempts) {
port._reconnectAttempts = 0
console.debug('[background] Reset reconnect attempts after successful proxy message.')
}
if (port._isClosed) {
console.debug('[background] Main port closed; skipping proxy message.')
return
}
try {
port.postMessage(msg)
} catch (e) {
console.warn('[background] Failed to post message to main port (likely disconnected):', e)
}
}
port._portOnMessage = (msg) => {
if (msg?.session && !msg?.stop) {
console.debug('[background] Session message handled by executeApi; skipping proxy forward.')
return
}
const redactedMsg = redactSensitiveFields(msg)
console.debug('[background] Message to proxy tab (redacted):', redactedMsg)
if (port.proxy) {
try {
port.proxy.postMessage(msg)
} catch (e) {
console.error(
'[background] Error posting message to proxy tab in _portOnMessage:',
e,
redactedMsg,
)
try {
// Attempt to notify the original sender about the failure
port.postMessage({
error:
'Failed to forward message to target tab. Tab might be closed or an extension error occurred.',
})
} catch (notifyError) {
console.error(
'[background] Error sending forwarding failure notification back to original sender:',
notifyError,
)
}
}
} else {
console.warn('[background] Port proxy not available to send message:', redactedMsg)
}
}
port._proxyOnDisconnect = () => {
console.warn(`[background] Proxy tab ${proxyTabId} disconnected.`)
const proxyRef = port.proxy
port.proxy = null
port._proxyTabId = null
if (port._reconnectTimerId) {
clearTimeout(port._reconnectTimerId)
port._reconnectTimerId = null
}
if (port._reconnectStabilityTimerId) {
clearTimeout(port._reconnectStabilityTimerId)
port._reconnectStabilityTimerId = null
}
if (proxyRef) {
if (port._proxyOnMessage) {
try {
proxyRef.onMessage.removeListener(port._proxyOnMessage)
} catch (e) {
console.warn(
'[background] Error removing _proxyOnMessage from disconnected proxyRef:',
e,
)
}
}
if (port._proxyOnDisconnect) {
try {
proxyRef.onDisconnect.removeListener(port._proxyOnDisconnect)
} catch (e) {
console.warn(
'[background] Error removing _proxyOnDisconnect from disconnected proxyRef:',
e,
)
}
}
}
port._reconnectAttempts = (port._reconnectAttempts || 0) + 1
if (port._reconnectAttempts >= RECONNECT_CONFIG.MAX_ATTEMPTS) {
console.error(
`[background] Max reconnect attempts (${RECONNECT_CONFIG.MAX_ATTEMPTS}) reached for tab ${proxyTabId}. Giving up.`,
)
if (port._portOnMessage) {
try {
port.onMessage.removeListener(port._portOnMessage)
} catch (e) {
console.warn('[background] Error removing _portOnMessage on max retries:', e)
}
}
if (port._portOnDisconnect) {
try {
port.onDisconnect.removeListener(port._portOnDisconnect)
} catch (e) {
console.warn('[background] Error removing _portOnDisconnect on max retries:', e)
}
}
try {
port.postMessage({
error: `Connection to ChatGPT tab lost after ${RECONNECT_CONFIG.MAX_ATTEMPTS} attempts. Please refresh the page.`,
})
} catch (e) {
console.warn('[background] Error sending final error message on max retries:', e)
}
return
}
const delay =
Math.pow(RECONNECT_CONFIG.BACKOFF_MULTIPLIER, port._reconnectAttempts - 1) *
RECONNECT_CONFIG.BASE_DELAY_MS
console.log(
`[background] Attempting reconnect #${port._reconnectAttempts} in ${
delay / 1000
}s for tab ${proxyTabId}.`,
)
port._reconnectTimerId = setTimeout(async () => {
if (port._isClosed) {
console.debug('[background] Main port closed; skipping proxy reconnect.')
return
}
port._reconnectTimerId = null
try {
await Browser.tabs.get(proxyTabId)
} catch (error) {
console.warn(
`[background] Proxy tab ${proxyTabId} no longer exists. Aborting reconnect.`,
error,
)
return
}
console.debug(
`[background] Retrying connection to tab ${proxyTabId}, attempt ${port._reconnectAttempts}.`,
)
try {
setPortProxy(port, proxyTabId)
} catch (error) {
console.warn(`[background] Error reconnecting to tab ${proxyTabId}:`, error)
}
}, delay)
}
port._portOnDisconnect = () => {
console.log(
'[background] Main port disconnected (e.g. popup/sidebar closed). Cleaning up proxy connections and listeners.',
)
port._isClosed = true
if (port._reconnectTimerId) {
clearTimeout(port._reconnectTimerId)
port._reconnectTimerId = null
}
if (port._reconnectStabilityTimerId) {
clearTimeout(port._reconnectStabilityTimerId)
port._reconnectStabilityTimerId = null
}
if (port._portOnMessage) {
try {
port.onMessage.removeListener(port._portOnMessage)
} catch (e) {
console.warn('[background] Error removing _portOnMessage on main port disconnect:', e)
}
}
const proxyRef = port.proxy
if (proxyRef) {
if (port._proxyOnMessage) {
try {
proxyRef.onMessage.removeListener(port._proxyOnMessage)
} catch (e) {
console.warn(
'[background] Error removing _proxyOnMessage from proxyRef on main port disconnect:',
e,
)
}
}
if (port._proxyOnDisconnect) {
try {
proxyRef.onDisconnect.removeListener(port._proxyOnDisconnect)
} catch (e) {
console.warn(
'[background] Error removing _proxyOnDisconnect from proxyRef on main port disconnect:',
e,
)
}
}
try {
proxyRef.disconnect()
} catch (e) {
console.warn('[background] Error disconnecting proxyRef on main port disconnect:', e)
}
port.proxy = null
port._proxyTabId = null
}
if (port._portOnDisconnect) {
try {
port.onDisconnect.removeListener(port._portOnDisconnect)
} catch (e) {
console.warn('[background] Error removing _portOnDisconnect on main port disconnect:', e)
}
}
port._reconnectAttempts = 0
}
port.proxy.onMessage.addListener(port._proxyOnMessage)
port.onMessage.addListener(port._portOnMessage)
port.proxy.onDisconnect.addListener(port._proxyOnDisconnect)
port.onDisconnect.addListener(port._portOnDisconnect)
// A connect() call can succeed and then disconnect immediately if the tab isn't ready.
// Only reset retries after the new proxy remains connected for a short stable window.
const connectedProxy = port.proxy
port._reconnectStabilityTimerId = setTimeout(() => {
port._reconnectStabilityTimerId = null
if (port._isClosed || port.proxy !== connectedProxy) {
return
}
if (port._reconnectAttempts) {
port._reconnectAttempts = 0
console.debug('[background] Reset reconnect attempts after stable proxy connection.')
}
}, RECONNECT_CONFIG.STABLE_CONNECT_RESET_DELAY_MS)
} catch (error) {
console.error(`[background] Error in setPortProxy for tab ${proxyTabId}:`, error)
}
}
async function executeApi(session, port, config) {
console.log(
`[background] executeApi called for model: ${session.modelName}, apiMode: ${session.apiMode}`,
)
const redactedSession = redactSensitiveFields(session)
const redactedConfig = redactSensitiveFields(config)
console.debug('[background] Full session details (redacted):', redactedSession)
console.debug('[background] Full config details (redacted):', redactedConfig)
if (session.apiMode) {
console.debug(
'[background] Session apiMode details (redacted):',
redactSensitiveFields(session.apiMode),
)
}
try {
if (isUsingCustomModel(session)) {
console.debug('[background] Using Custom Model API')
if (!session.apiMode)
await generateAnswersWithCustomApi(
port,
session.question,
session,
config.customModelApiUrl.trim() || 'http://localhost:8000/v1/chat/completions',
config.customApiKey,
config.customModelName,
)
else
await generateAnswersWithCustomApi(
port,
session.question,
session,
session.apiMode.customUrl?.trim() ||
config.customModelApiUrl.trim() ||
'http://localhost:8000/v1/chat/completions',
session.apiMode.apiKey?.trim() || config.customApiKey,
session.apiMode.customName,
)
} else if (isUsingChatgptWebModel(session)) {
console.debug('[background] Using ChatGPT Web Model')
let tabId
if (
config.chatgptTabId &&
config.customChatGptWebApiUrl === defaultConfig.customChatGptWebApiUrl
) {
try {
const tab = await Browser.tabs.get(config.chatgptTabId)
if (tab) tabId = tab.id
} catch (e) {
console.warn(
`[background] Failed to get ChatGPT tab with ID ${config.chatgptTabId}:`,
e.message,
)
}
}
if (tabId) {
console.debug(`[background] ChatGPT Tab ID ${tabId} found.`)
const hasMatchingProxy = Boolean(port.proxy && port._proxyTabId === tabId)
if (!hasMatchingProxy) {
if (port.proxy) {
console.debug(
`[background] Existing proxy tab ${port._proxyTabId} does not match ${tabId}; reconnecting.`,
)
} else {
console.debug('[background] port.proxy not found, calling setPortProxy.')
}
setPortProxy(port, tabId)
}
if (port.proxy && port._proxyTabId === tabId) {
if (hasMatchingProxy) {
console.debug('[background] Proxy already established; forwarding session.')
}
console.debug('[background] Posting message to proxy tab:', { session: redactedSession })
try {
port.proxy.postMessage({ session })
} catch (e) {
console.warn(
'[background] Error posting message to existing proxy tab in executeApi (ChatGPT Web Model):',
e,
'. Attempting to reconnect.',
{ session: redactedSession },
)
setPortProxy(port, tabId)
if (port.proxy) {
console.debug('[background] Proxy re-established. Attempting to post message again.')
try {
port.proxy.postMessage({ session })
console.info('[background] Successfully posted session after proxy reconnection.')
} catch (e2) {
console.error(
'[background] Error posting message even after proxy reconnection:',
e2,
{ session: redactedSession },
)
try {
port.postMessage({
error:
'Failed to communicate with ChatGPT tab after reconnection attempt. Try refreshing the page.',
})
} catch (notifyError) {
console.error(
'[background] Error sending final communication failure notification back:',
notifyError,
)
}
}
} else {
console.error(
'[background] Failed to re-establish proxy connection. Cannot send session.',
)
try {
port.postMessage({
error:
'Could not re-establish connection to ChatGPT tab. Try refreshing the page.',
})
} catch (notifyError) {
console.error(
'[background] Error sending re-establishment failure notification back:',
notifyError,
)
}
}
}
} else {
console.error(
'[background] Failed to send message: port.proxy is still not available after initial setPortProxy attempt.',
)
try {
port.postMessage({
error: 'Failed to initialize connection to ChatGPT tab. Try refreshing the page.',
})
} catch (notifyError) {
console.error(
'[background] Error sending initial connection failure notification back:',
notifyError,
)
}
}
} else {
console.debug('[background] No valid ChatGPT Tab ID found. Using direct API call.')
const accessToken = await getChatGptAccessToken()
await generateAnswersWithChatgptWebApi(port, session.question, session, accessToken)
}
} else if (isUsingClaudeWebModel(session)) {
console.debug('[background] Using Claude Web Model')
const sessionKey = await getClaudeSessionKey()
await generateAnswersWithClaudeWebApi(port, session.question, session, sessionKey)
} else if (isUsingMoonshotWebModel(session)) {
console.debug('[background] Using Moonshot Web Model')
await generateAnswersWithMoonshotWebApi(port, session.question, session, config)
} else if (isUsingBingWebModel(session)) {
console.debug('[background] Using Bing Web Model')
const accessToken = await getBingAccessToken()
if (isUsingModelName('bingFreeSydney', session)) {
console.debug('[background] Using Bing Free Sydney model')
await generateAnswersWithBingWebApi(port, session.question, session, accessToken, true)
} else {
await generateAnswersWithBingWebApi(port, session.question, session, accessToken)
}
} else if (isUsingGeminiWebModel(session)) {
console.debug('[background] Using Gemini Web Model')
const cookies = await getBardCookies()
await generateAnswersWithBardWebApi(port, session.question, session, cookies)
} else if (isUsingChatgptApiModel(session)) {
console.debug('[background] Using OpenAI API Model')
await generateAnswersWithOpenAiApi(port, session.question, session, config.apiKey)
} else if (isUsingClaudeApiModel(session)) {
console.debug('[background] Using Anthropic API Model')
await generateAnswersWithClaudeApi(port, session.question, session)
} else if (isUsingMoonshotApiModel(session)) {
console.debug('[background] Using Moonshot API Model')
await generateAnswersWithMoonshotCompletionApi(
port,
session.question,
session,
config.moonshotApiKey,
)
} else if (isUsingChatGLMApiModel(session)) {
console.debug('[background] Using ChatGLM API Model')
await generateAnswersWithChatGLMApi(port, session.question, session)
} else if (isUsingDeepSeekApiModel(session)) {
console.debug('[background] Using DeepSeek API Model')
await generateAnswersWithDeepSeekApi(port, session.question, session, config.deepSeekApiKey)
} else if (isUsingMiniMaxApiModel(session)) {
console.debug('[background] Using MiniMax API Model')
await generateAnswersWithMiniMaxApi(port, session.question, session, config.minimaxApiKey)
} else if (isUsingOllamaApiModel(session)) {
console.debug('[background] Using Ollama API Model')
await generateAnswersWithOllamaApi(port, session.question, session)
} else if (isUsingOpenRouterApiModel(session)) {
console.debug('[background] Using OpenRouter API Model')
await generateAnswersWithOpenRouterApi(
port,
session.question,
session,
config.openRouterApiKey,
)
} else if (isUsingAimlApiModel(session)) {
console.debug('[background] Using AIML API Model')
await generateAnswersWithAimlApi(port, session.question, session, config.aimlApiKey)
} else if (isUsingAzureOpenAiApiModel(session)) {
console.debug('[background] Using Azure OpenAI API Model')
await generateAnswersWithAzureOpenaiApi(port, session.question, session)
} else if (isUsingGptCompletionApiModel(session)) {
console.debug('[background] Using GPT Completion API Model')
await generateAnswersWithGptCompletionApi(port, session.question, session, config.apiKey)
} else if (isUsingGithubThirdPartyApiModel(session)) {
console.debug('[background] Using Github Third Party API Model')
await generateAnswersWithWaylaidwandererApi(port, session.question, session)
} else {
console.warn('[background] Unknown model or session configuration:', redactedSession)
port.postMessage({ error: 'Unknown model configuration' })
}
} catch (error) {
console.error(`[background] Error in executeApi for model ${session.modelName}:`, error)
throw error
}
}
Browser.runtime.onMessage.addListener(async (message, sender) => {
console.debug('[background] Received message type:', message?.type, 'from sender:', sender?.id)
try {
switch (message.type) {
case 'FEEDBACK': {
console.log('[background] Processing FEEDBACK message')
const token = await getChatGptAccessToken()
await sendMessageFeedback(token, message.data)
break
}
case 'DELETE_CONVERSATION': {
console.log('[background] Processing DELETE_CONVERSATION message')
const token = await getChatGptAccessToken()
await deleteConversation(token, message.data.conversationId)
break
}
case 'NEW_URL': {
console.log('[background] Processing NEW_URL message:', message.data)
await Browser.tabs.create({
url: message.data.url,
pinned: message.data.pinned,
})
if (message.data.jumpBack) {
const jumpBackTabId = sender.tab?.id
if (!jumpBackTabId) {
console.warn('[background] NEW_URL jumpBack missing sender tab id:', sender)
return null
}
console.debug('[background] Setting jumpBackTabId:', jumpBackTabId)
await setUserConfig({
notificationJumpBackTabId: jumpBackTabId,
})
}
break
}
case 'SET_CHATGPT_TAB': {
const chatgptTabId = sender.tab?.id
console.log('[background] Processing SET_CHATGPT_TAB message. Tab ID:', chatgptTabId)
if (!chatgptTabId) {
console.warn('[background] SET_CHATGPT_TAB missing sender tab id:', sender)
break
}
await setUserConfig({
chatgptTabId,
})
break
}
case 'ACTIVATE_URL':
console.log('[background] Processing ACTIVATE_URL message:', message.data)
await Browser.tabs.update(message.data.tabId, { active: true })
break
case 'OPEN_URL':
console.log('[background] Processing OPEN_URL message:', message.data)
openUrl(message.data.url)
break
case 'OPEN_CHAT_WINDOW': {
console.log('[background] Processing OPEN_CHAT_WINDOW message')
const config = await getUserConfig()
const url = Browser.runtime.getURL('IndependentPanel.html')
const tabs = await Browser.tabs.query({ url: url, windowType: 'popup' })
if (!config.alwaysCreateNewConversationWindow && tabs.length > 0) {
console.debug('[background] Focusing existing chat window:', tabs[0].windowId)
await Browser.windows.update(tabs[0].windowId, { focused: true })
} else {
console.debug('[background] Creating new chat window.')
await Browser.windows.create({
url: url,
type: 'popup',
width: 500,
height: 650,
})
}
break
}
case 'REFRESH_MENU':
console.log('[background] Processing REFRESH_MENU message')
refreshMenu()
break
case 'PIN_TAB': {
console.log('[background] Processing PIN_TAB message:', message.data)
const data = message.data ?? {}
let tabId = data.tabId ?? sender.tab?.id
if (tabId) {
await Browser.tabs.update(tabId, { pinned: true })
if (data.saveAsChatgptConfig) {
console.debug('[background] Saving pinned tab as ChatGPT config tab:', tabId)
await setUserConfig({ chatgptTabId: tabId })
}
} else {
console.warn('[background] No tabId found for PIN_TAB message.')
}
break
}
case 'FETCH': {
const senderId = sender?.id
const senderUrl = sender?.url || sender?.documentUrl || sender?.origin
const extensionOrigin = new URL(Browser.runtime.getURL('/')).origin
const isTrustedExtensionSenderWithoutId =
!senderId && typeof senderUrl === 'string' && senderUrl.startsWith(`${extensionOrigin}/`)
if (senderId !== Browser.runtime.id && !isTrustedExtensionSenderWithoutId) {
console.warn('[background] Rejecting FETCH message from untrusted sender:', sender)
return [null, { message: 'Unauthorized sender' }]
}
const fetchInput =
message.data?.input instanceof URL ? message.data.input.toString() : message.data?.input
if (typeof fetchInput !== 'string') {
console.warn('[background] Invalid FETCH input:', message.data?.input)
return [null, { message: 'Invalid fetch input' }]
}
let validatedUrl
try {
const url = new URL(fetchInput)
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
console.warn('[background] Rejecting FETCH for non-http(s) URL:', fetchInput)
return [null, { message: 'Unsupported fetch protocol' }]
}
validatedUrl = url.toString()
} catch (error) {
console.warn('[background] Invalid FETCH input URL:', fetchInput, error)
return [null, { message: 'Invalid fetch URL' }]
}
console.log('[background] Processing FETCH message for URL:', validatedUrl)
if (validatedUrl.includes('bing.com')) {
console.debug('[background] Fetching Bing access token for FETCH message.')
const accessToken = await getBingAccessToken()
await setUserConfig({ bingAccessToken: accessToken })
}
try {
const response = await fetch(validatedUrl, message.data?.init)
const text = await response.text()
const responseObject = {
// Defined for clarity before conditional error property
body: text,
ok: response.ok,
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers),
}
if (!response.ok) {
responseObject.error = `HTTP error ${response.status}: ${response.statusText}`
console.warn(
`[background] FETCH received error status: ${response.status} for ${validatedUrl}`,
)
}
console.debug(
`[background] FETCH successful for ${validatedUrl}, status: ${response.status}`,
)
return [responseObject, null]
} catch (error) {
console.error(`[background] FETCH error for ${validatedUrl}:`, error)
return [null, { message: error.message }]
}
}
case 'GET_COOKIE': {
const senderId = sender?.id
if (!senderId || senderId !== Browser.runtime.id) {
console.warn('[background] Rejecting GET_COOKIE message from untrusted sender:', sender)
return null
}
const cookieUrlInput = message?.data?.url
const cookieNameInput = message?.data?.name
if (
typeof cookieUrlInput !== 'string' ||
!cookieUrlInput.trim() ||
typeof cookieNameInput !== 'string' ||
!cookieNameInput.trim()
) {
console.warn('[background] Rejecting GET_COOKIE with invalid payload:', message.data)
return null
}
let cookieUrl
try {
cookieUrl = new URL(cookieUrlInput.trim())
} catch (error) {
console.warn('[background] Rejecting GET_COOKIE with invalid URL:', cookieUrlInput)
return null
}
if (cookieUrl.protocol !== 'http:' && cookieUrl.protocol !== 'https:') {
console.warn(
'[background] Rejecting GET_COOKIE with disallowed protocol:',
cookieUrl.protocol,
)
return null
}
const cookieName = cookieNameInput.trim()
console.debug('[background] Processing GET_COOKIE message for:', cookieUrl.href)
try {
const cookie = await Browser.cookies.get({
url: cookieUrl.href,
name: cookieName,
})
console.debug('[background] Cookie found:', cookie ? 'yes' : 'no')
return cookie?.value
} catch (error) {
console.error(
`[background] Error getting cookie ${cookieName} for ${cookieUrl.href}:`,
error,
)
return null
}
}
default:
console.warn('[background] Unknown message type received:', message.type)
}
} catch (error) {
console.error(
`[background] Error processing message type ${message.type}:`,
error,
'Original message:',
message,
)
if (message.type === 'FETCH') {
return [null, { message: error.message }]
}
}
})
try {
Browser.webRequest.onBeforeRequest.addListener(
(details) => {
try {
console.debug('[background] onBeforeRequest triggered for URL:', details.url)
if (
details.url.includes('/public_key') &&
!details.url.includes(defaultConfig.chatgptArkoseReqParams)
) {
console.log('[background] Capturing Arkose public_key request:', details.url)
let formData = new URLSearchParams()
if (details.requestBody?.formData) {
for (const k in details.requestBody.formData) {
const values = details.requestBody.formData[k]
if (Array.isArray(values)) {
for (const value of values) {
formData.append(k, value)
}
} else if (values != null) {
formData.append(k, values)
}
}
}
const formString =
formData.toString() ||
(details.requestBody?.raw?.[0]?.bytes
? new TextDecoder('utf-8').decode(new Uint8Array(details.requestBody.raw[0].bytes))
: '')
if (!formString) {
console.warn(
'[background] Arkose request captured without body; skipping config update.',
)
return
}
setUserConfig({
chatgptArkoseReqUrl: details.url,
chatgptArkoseReqForm: formString,
})
.then(() => {
console.log('[background] Arkose req url and form saved successfully.')
})
.catch((e) => console.error('[background] Error saving Arkose req url and form:', e))
}
} catch (error) {
console.error('[background] Error in onBeforeRequest listener callback:', error, details)
}
},
{
urls: ['https://*.openai.com/*', 'https://*.chatgpt.com/*'],
types: ['xmlhttprequest'],
},
['requestBody'],
)
Browser.webRequest.onBeforeSendHeaders.addListener(
(details) => {
try {
console.debug('[background] onBeforeSendHeaders triggered for URL:', details.url)
const headers = details.requestHeaders
let modified = false
for (let i = 0; i < headers.length; i++) {
const header = headers[i]
if (!header || !header.name) {
continue
}
const headerNameLower = header.name.toLowerCase()
if (headerNameLower === 'origin') {
header.value = 'https://www.bing.com'
modified = true
} else if (headerNameLower === 'referer') {
header.value = 'https://www.bing.com/search?q=Bing+AI&showconv=1&FORM=hpcodx'
modified = true
}
}
if (modified) {
console.debug(
'[background] Modified headers for Bing (names only):',
headers.map((header) => header?.name).filter(Boolean),
)
}
return { requestHeaders: headers }
} catch (error) {
console.error(
'[background] Error in onBeforeSendHeaders listener callback:',
error,
details,
)
return { requestHeaders: details.requestHeaders }
}
},
{
urls: ['wss://sydney.bing.com/*', 'https://www.bing.com/*'],
types: ['xmlhttprequest', 'websocket'],
},
['requestHeaders', ...(Browser.runtime.getManifest().manifest_version < 3 ? ['blocking'] : [])],
)
Browser.webRequest.onBeforeSendHeaders.addListener(
(details) => {
const headers = details.requestHeaders
for (let i = 0; i < headers.length; i++) {
const header = headers[i]
if (!header || !header.name) {
continue
}
const headerNameLower = header.name.toLowerCase()
if (headerNameLower === 'origin') {
header.value = 'https://claude.ai'
} else if (headerNameLower === 'referer') {
header.value = 'https://claude.ai'
}
}
return { requestHeaders: headers }
},
{
urls: ['https://claude.ai/*'],
types: ['xmlhttprequest'],
},
['requestHeaders', ...(Browser.runtime.getManifest().manifest_version < 3 ? ['blocking'] : [])],
)
Browser.tabs.onUpdated.addListener(async (tabId, info, tab) => {
const outerTryCatchError = (error) => {
console.error(
'[background] Error in tabs.onUpdated listener callback (outer):',
error,
tabId,
info,
)
}
try {
if (!tab.url) {
console.debug(
`[background] Skipping side panel update for tabId: ${tabId}. Tab URL: ${tab.url}, Info Status: ${info.status}`,
)
return
}
console.debug(
`[background] tabs.onUpdated event for tabId: ${tabId}, status: ${info.status}, url: ${tab.url}. Proceeding with side panel update.`,
)
let sidePanelSet = false
try {
if (Browser.sidePanel && typeof Browser.sidePanel.setOptions === 'function') {
await Browser.sidePanel.setOptions({
tabId,
path: 'IndependentPanel.html',
enabled: true,
})
console.debug(
`[background] Side panel options set for tab ${tabId} using Browser.sidePanel`,
)
sidePanelSet = true
}
} catch (browserError) {
console.warn('[background] Browser.sidePanel.setOptions failed:', browserError.message)
}
if (!sidePanelSet) {
console.debug('[background] Attempting chrome.sidePanel.setOptions as fallback.')
const chromeApi = globalThis.chrome
if (chromeApi?.sidePanel && typeof chromeApi.sidePanel.setOptions === 'function') {
try {
await chromeApi.sidePanel.setOptions({
tabId,
path: 'IndependentPanel.html',
enabled: true,
})
console.debug(
`[background] Side panel options set for tab ${tabId} using chrome.sidePanel`,
)
sidePanelSet = true
} catch (chromeError) {
console.error(
'[background] chrome.sidePanel.setOptions also failed:',
chromeError.message,
)
}
}
}
if (!sidePanelSet) {
console.warn(
'[background] SidePanel API (Browser.sidePanel or chrome.sidePanel) not available or setOptions failed in this browser. Side panel options not set for tab:',
tabId,
)
}
} catch (error) {
outerTryCatchError(error)
}
})
} catch (error) {
console.error('[background] Error setting up webRequest or tabs listeners:', error)
}
try {
registerPortListener(async (session, port, config) => {
console.debug(
`[background] Port listener triggered for session: ${session.modelName}, port: ${port.name}`,
)
await executeApi(session, port, config)
})
console.log('[background] Port listener registered successfully.')
} catch (error) {
console.error('[background] Error registering port listener:', error)
}