-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpopup.js
More file actions
1658 lines (1414 loc) · 56.8 KB
/
popup.js
File metadata and controls
1658 lines (1414 loc) · 56.8 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
const Errors = window.AISummaryErrors;
const Trust = window.AISummaryTrust;
const ProviderPresets = window.AISummaryProviderPresets;
const Theme = window.AISummaryTheme;
const UiFormat = window.AISummaryUiFormat;
const UiLabels = window.AISummaryUiLabels;
const Constants = window.AISummaryConstants;
const UrlUtils = window.AISummaryUrlUtils;
const SETTINGS_KEYS = [
'providerPreset',
'aiProvider',
'endpointMode',
'apiKey',
'aiBaseURL',
'modelName',
'systemPrompt',
'autoTranslate',
'defaultLanguage',
'themePreference',
'themePalette',
'privacyMode',
'defaultAllowHistory',
'defaultAllowShare',
'entrypointAutoStart',
'entrypointSimpleMode',
'entrypointReuseHistory'
];
const PROFILES_INDEX_KEY = 'yilanProfilesIndexV1';
const ACTIVE_PROFILE_ID_KEY = 'yilanActiveProfileIdV1';
const PROFILE_KEY_PREFIX = 'yilanProfileV1:';
const MODELS_CACHE_STORAGE_KEY = 'yilanModelsCacheV1';
const ACTIVE_TAB_STORAGE_KEY = 'popupActiveTab';
const IDLE_STATUS_TEXT = '设置修改后会自动保存。';
const WAITING_AUTOSAVE_TEXT = '检测到变更,输入停顿后会自动保存。';
const BASE_URL_SECURITY_HINT = '远程接口必须使用 HTTPS;HTTP 仅允许本机或局域网地址。';
const BASE_URL_INVALID_MESSAGE = 'Base URL 仅支持 HTTPS;HTTP 仅允许本机或局域网地址。';
const PROVIDER_FALLBACK_HINTS = {
openai: '留空时使用 OpenAI 默认根地址,也可以直接填写完整 endpoint。',
anthropic: '留空时使用 Anthropic 默认根地址,也可以填写兼容根地址。'
};
const THEME_PREFERENCE_LABELS = {
system: '自动跟随系统',
light: '固定浅色',
dark: '固定深色'
};
const THEME_EFFECTIVE_LABELS = {
light: '浅色',
dark: '深色'
};
const THEME_PALETTE_LABELS = {
jade: '松石绿',
slate: '雾蓝',
copper: '岩茶棕',
plum: '檀紫'
};
const THEME_PALETTE_HINTS = {
jade: '默认方案,清爽、稳定,适合长期阅读',
slate: '蓝灰倾向更克制,适合弱化品牌色干扰',
copper: '偏茶棕的暖调方案,保留温度但不偏黄',
plum: '更有识别度的深檀色调,适合强调品牌感'
};
const autoFillState = {
baseURL: '',
modelName: ''
};
const saveState = {
timer: null,
lastSavedSignature: '',
requestId: 0
};
const profileState = {
activeId: '',
index: []
};
const $ = (id) => document.getElementById(id);
function getRuntimeErrorMessage(errorLike) {
if (!errorLike) {
return typeof Errors?.getUserMessage === 'function' ? Errors.getUserMessage(null) : 'Unknown error.';
}
if (typeof errorLike === 'string') {
return errorLike || (typeof Errors?.getUserMessage === 'function' ? Errors.getUserMessage(null) : 'Unknown error.');
}
const hasMessage = typeof errorLike?.message === 'string' && errorLike.message.trim();
const hasCode = typeof errorLike?.code === 'string' && errorLike.code.trim();
// Prefer raw messages for plain `{ message: string }` objects (e.g. chrome.runtime.lastError),
// otherwise Errors.getUserMessage() will fall back to a generic "Unknown error" catalog message.
if (hasMessage && !hasCode) return errorLike.message.trim();
if (typeof Errors?.getUserMessage === 'function') {
return Errors.getUserMessage(errorLike);
}
if (hasMessage) return errorLike.message.trim();
return String(errorLike);
}
function buildErrorDetailsText(errorLike, diagnostics) {
if (!errorLike && !diagnostics) return '';
const error = errorLike && typeof errorLike === 'object' ? errorLike : null;
const diag = diagnostics || (errorLike && typeof errorLike === 'object' ? errorLike.diagnostics : null);
const lines = [];
if (error?.code) lines.push(`code: ${error.code}`);
if (typeof error?.httpStatus === 'number' && error.httpStatus) lines.push(`httpStatus: ${error.httpStatus}`);
if (error?.endpointHost) lines.push(`endpointHost: ${error.endpointHost}`);
if (error?.provider) lines.push(`provider: ${error.provider}`);
if (error?.endpointMode) lines.push(`endpointMode: ${error.endpointMode}`);
if (error?.stage) lines.push(`stage: ${error.stage}`);
if (error?.detail) lines.push(`detail: ${String(error.detail).trim()}`);
if (diag?.baseUrl) lines.push(`requestUrl: ${diag.baseUrl}`);
if (diag?.adapterId) lines.push(`adapterId: ${diag.adapterId}`);
if (diag?.model) lines.push(`model: ${diag.model}`);
if (diag?.requestedEndpointMode) lines.push(`requestedEndpointMode: ${diag.requestedEndpointMode}`);
if (diag?.autoEndpointSelected) lines.push(`autoEndpointSelected: ${diag.autoEndpointSelected}`);
if (Array.isArray(diag?.autoEndpointTried) && diag.autoEndpointTried.length) {
lines.push(`autoEndpointTried: ${diag.autoEndpointTried.join(' -> ')}`);
}
if (diag?.autoBaseUrlAdjusted) {
lines.push(`autoBaseUrlAdjusted: true (appliedV1: ${diag.autoBaseUrlAppliedV1 ? 'yes' : 'no'})`);
}
return lines.join('\n').trim();
}
function storageGet(keys) {
return new Promise((resolve, reject) => {
chrome.storage.sync.get(keys, (items) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(items || {});
});
});
}
function storageSet(payload) {
return new Promise((resolve, reject) => {
chrome.storage.sync.set(payload, () => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve();
});
});
}
function storageRemove(keys) {
return new Promise((resolve, reject) => {
chrome.storage.sync.remove(keys, () => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve();
});
});
}
function storageLocalGet(keys) {
return new Promise((resolve, reject) => {
chrome.storage.local.get(keys, (items) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(items || {});
});
});
}
function storageLocalSet(payload) {
return new Promise((resolve, reject) => {
chrome.storage.local.set(payload, () => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve();
});
});
}
function runtimeSendMessage(message) {
return new Promise((resolve) => {
chrome.runtime.sendMessage(message, (response) => {
if (chrome.runtime.lastError) {
resolve({ success: false, error: { message: chrome.runtime.lastError.message } });
return;
}
resolve(response || {});
});
});
}
function setStatus(text, tone) {
const node = $('status');
if (!node) return;
node.textContent = text;
node.className = 'status' + (tone ? ' ' + tone : '');
}
function setStatusDetails(text) {
const detailsNode = $('statusDetails');
const textNode = $('statusDetailsText');
if (!detailsNode || !textNode) return;
const value = String(text || '').trim();
if (!value) {
detailsNode.hidden = true;
detailsNode.open = false;
textNode.textContent = '';
return;
}
textNode.textContent = value;
detailsNode.hidden = false;
}
const formatDateTime = (value) => UiFormat.formatDateTime(value, { emptyText: '未记录', includeYear: false });
function setBadge(id, text, tone) {
const node = $(id);
if (!node) return;
node.textContent = text;
node.className = 'status-badge' + (tone ? ' ' + tone : '');
}
function getSaveSuccessText(settings) {
return settings.privacyMode ? '已自动保存,当前处于无痕模式。' : '已自动保存。';
}
function renderThemeHint(preference, theme) {
const normalizedPreference = Theme.normalizePreference(preference);
const effectiveTheme = Theme.resolveTheme(normalizedPreference || theme);
const preferenceLabel = THEME_PREFERENCE_LABELS[normalizedPreference] || THEME_PREFERENCE_LABELS.system;
const effectiveLabel = THEME_EFFECTIVE_LABELS[effectiveTheme] || THEME_EFFECTIVE_LABELS.light;
$('themeHint').textContent = normalizedPreference === 'system'
? `${preferenceLabel}。当前生效:${effectiveLabel};系统主题变化时会自动切换。`
: `${preferenceLabel}。当前 popup 和侧栏会保持 ${effectiveLabel} 模式。`;
}
function syncThemePreferenceControl(preference, options = {}) {
const result = Theme.applyPreference(preference, { force: options.force !== false });
const field = $('themePreference');
if (field) {
field.value = result.preference;
}
renderThemeHint(result.preference, result.theme);
return result;
}
function renderPaletteHint(palette) {
const normalizedPalette = Theme.normalizePalette(palette);
const label = THEME_PALETTE_LABELS[normalizedPalette] || THEME_PALETTE_LABELS.jade;
const hint = THEME_PALETTE_HINTS[normalizedPalette] || THEME_PALETTE_HINTS.jade;
const hintNode = $('paletteHint');
if (!hintNode) return;
hintNode.textContent = `${label}:${hint}。会同步到 popup、侧栏和阅读页。`;
}
function setPaletteControlState(palette) {
const normalizedPalette = Theme.normalizePalette(palette);
const field = $('themePalette');
if (field) {
field.value = normalizedPalette;
}
document.querySelectorAll('[data-palette-option]').forEach((button) => {
const isSelected = button.dataset.paletteOption === normalizedPalette;
button.classList.toggle('active', isSelected);
button.setAttribute('aria-checked', isSelected ? 'true' : 'false');
});
renderPaletteHint(normalizedPalette);
}
function syncThemePaletteControl(palette, options = {}) {
const result = Theme.applyPalette(palette, { force: options.force !== false });
setPaletteControlState(result.palette);
return result;
}
function renderEntrypointStatus(entrypoints) {
const contextMenu = entrypoints?.contextMenu || {};
const shortcut = entrypoints?.shortcut || {};
const contextMenuReady = contextMenu.status === 'ready';
$('contextMenuDesc').textContent = contextMenuReady
? '右键菜单已注册,可以在网页空白区域直接启动摘要。'
: (contextMenu.lastError || '右键菜单还没准备好,建议点击“检查入口”尝试修复。');
setBadge(
'contextMenuBadge',
contextMenuReady ? '已就绪' : '待修复',
contextMenuReady ? 'success' : 'warning'
);
const shortcutAssigned = shortcut.status === 'assigned' && shortcut.shortcut;
$('shortcutDesc').textContent = shortcutAssigned
? `当前绑定:${shortcut.shortcut}`
: '没有检测到生效中的快捷键,请前往快捷键设置页确认 Alt + S。';
setBadge(
'shortcutBadge',
shortcutAssigned ? '已绑定' : shortcut.status === 'missing' ? '缺失' : '未绑定',
shortcutAssigned ? 'success' : shortcut.status === 'missing' ? 'error' : 'warning'
);
$('entrypointMeta').textContent = [
`菜单最近校验:${formatDateTime(contextMenu.lastEnsuredAt)}`,
`菜单最近触发:${formatDateTime(contextMenu.lastTriggeredAt)}`,
`快捷键最近触发:${formatDateTime(shortcut.lastTriggeredAt)}`
].join(' · ');
}
function buildEndpointPreview(provider, endpointMode) {
if (provider === 'anthropic') return '/v1/messages';
if (endpointMode === 'responses') return '/responses';
if (endpointMode === 'chat_completions') return '/chat/completions';
if (endpointMode === 'legacy_completions') return '/completions';
return '自动试探';
}
function getEndpointModeLabel(mode) {
return ProviderPresets?.ENDPOINT_MODE_META?.[mode]?.label || mode || '自动判断';
}
function pickEffectiveBaseURLInput(rawInput, fallbackBaseUrl) {
const normalized = normalizeBaseURLInput(rawInput);
if (normalized) return normalized;
return String(fallbackBaseUrl || '').trim();
}
function getConnectionFieldSettings() {
return {
providerPreset: $('providerPreset')?.value || 'custom',
aiProvider: $('aiProvider')?.value || '',
endpointMode: $('endpointMode')?.value || '',
aiBaseURL: normalizeBaseURLInput($('baseURL')?.value || ''),
modelName: $('modelName')?.value || ''
};
}
function renderEndpointPreview() {
const previewNode = $('endpointPreview');
if (!previewNode) return;
const { provider, endpointMode, route, profile } = getCurrentSelection();
const rawInput = $('baseURL')?.value || '';
const defaultBaseUrl = provider === 'anthropic' ? 'https://api.anthropic.com' : 'https://api.openai.com/v1';
const baseRoot = pickEffectiveBaseURLInput(rawInput, route?.baseUrl || profile?.baseUrl || defaultBaseUrl);
if (!baseRoot) {
previewNode.textContent = '';
return;
}
const openaiDetected = UrlUtils?.detectOpenAiEndpointModeFromUrl?.(baseRoot) || '';
const anthropicDetected = UrlUtils?.detectAnthropicEndpointModeFromUrl?.(baseRoot) || '';
const isFullEndpoint = !!(openaiDetected || anthropicDetected);
const lines = [];
if (isFullEndpoint) {
const detectedMode = openaiDetected || anthropicDetected;
lines.push(`实际请求地址:${baseRoot}`);
lines.push(`接口模式:${getEndpointModeLabel(detectedMode)}(已识别完整 endpoint)`);
lines.push('说明:完整 endpoint 会优先于 Endpoint Mode 拼接。');
previewNode.textContent = lines.join('\n');
return;
}
if (provider === 'anthropic') {
const root = UrlUtils?.stripAnthropicMessagesSuffix?.(baseRoot) || baseRoot;
lines.push(`实际请求地址:${root}/v1/messages`);
lines.push(`接口模式:${getEndpointModeLabel('messages')}`);
previewNode.textContent = lines.join('\n');
return;
}
const root = UrlUtils?.stripOpenAiEndpointSuffix?.(baseRoot) || baseRoot;
const hasV1 = /\/v1$/i.test(root);
if (endpointMode === 'auto') {
lines.push(`实际请求地址:${root}/responses -> ${root}/chat/completions -> ${root}/completions`);
lines.push('接口模式:自动判断');
lines.push(hasV1 ? 'Base URL 已包含 /v1。' : 'Base URL 未包含 /v1,连接测试可在明确报错时自动修正。');
previewNode.textContent = lines.join('\n');
return;
}
const path = buildEndpointPreview(provider, endpointMode);
if (path && path.startsWith('/')) {
lines.push(`实际请求地址:${root}${path}`);
lines.push(`接口模式:${getEndpointModeLabel(endpointMode)}`);
lines.push(hasV1 ? 'Base URL 已包含 /v1。' : 'Base URL 未包含 /v1,连接测试可在明确报错时自动修正。');
previewNode.textContent = lines.join('\n');
return;
}
previewNode.textContent = '';
}
function inferPresetId(settings) {
const stored = String(settings?.providerPreset || '').trim();
if (stored) return stored;
return ProviderPresets.inferPresetFromSettings(settings);
}
function inferEndpointMode(settings, presetId, provider) {
const stored = String(settings?.endpointMode || '').trim();
if (stored) {
return ProviderPresets.normalizeEndpointMode(stored, provider, presetId);
}
const baseUrl = String(settings?.aiBaseURL || '').toLowerCase();
if (baseUrl.includes('/chat/completions')) {
return ProviderPresets.normalizeEndpointMode('chat_completions', provider, presetId);
}
if (baseUrl.includes('/responses')) {
return ProviderPresets.normalizeEndpointMode('responses', provider, presetId);
}
if (/\/completions(?:$|[?#])/i.test(baseUrl)) {
return ProviderPresets.normalizeEndpointMode('legacy_completions', provider, presetId);
}
if (provider === 'anthropic') {
return ProviderPresets.normalizeEndpointMode('messages', provider, presetId);
}
return ProviderPresets.normalizeEndpointMode('', provider, presetId);
}
function renderPresetOptions() {
const select = $('providerPreset');
select.innerHTML = '';
ProviderPresets.listPresets().forEach((preset) => {
const option = document.createElement('option');
option.value = preset.id;
option.textContent = preset.label;
select.appendChild(option);
});
}
function syncRouteOptions(presetId, preferredRouteId, preferredProvider) {
const select = $('providerRoute');
const routes = ProviderPresets.getProviderRoutes(presetId);
select.innerHTML = '';
routes.forEach((route) => {
const option = document.createElement('option');
option.value = route.routeId;
option.textContent = route.label;
select.appendChild(option);
});
let route = preferredRouteId ? ProviderPresets.getProviderRoute(presetId, preferredRouteId) : null;
if (route && preferredProvider && route.aiProvider !== preferredProvider) {
route = null;
}
if (!route) {
route = ProviderPresets.inferRouteFromSettings(getConnectionFieldSettings(), presetId);
}
if (route && preferredProvider && route.aiProvider !== preferredProvider) {
route = ProviderPresets.getDefaultRoute(presetId, preferredProvider);
}
if (!route) {
route = ProviderPresets.getDefaultRoute(presetId);
}
if (route?.routeId) {
select.value = route.routeId;
}
return route;
}
function syncProviderOptions(presetId, preferredProvider) {
const allowed = new Set(ProviderPresets.getProviderOptions(presetId));
const providerSelect = $('aiProvider');
const candidate = preferredProvider || providerSelect.value;
Array.from(providerSelect.options).forEach((option) => {
const supported = allowed.has(option.value);
option.disabled = !supported;
option.textContent = UiLabels.getProviderLabel(option.value, { variant: 'settings', fallback: option.value });
});
providerSelect.value = ProviderPresets.normalizeProvider(candidate, presetId);
return providerSelect.value;
}
function syncEndpointModeOptions(presetId, provider, preferredMode, route) {
const select = $('endpointMode');
const routeModes = Array.isArray(route?.endpointModes) ? route.endpointModes : [];
const modes = routeModes.length ? routeModes : ProviderPresets.getEndpointModes(presetId, provider);
const fallbackMode = route?.defaultEndpointMode || '';
const requestedMode = preferredMode || fallbackMode;
const nextMode = modes.includes(requestedMode)
? requestedMode
: ProviderPresets.normalizeEndpointMode(fallbackMode || requestedMode, provider, presetId);
select.innerHTML = '';
modes.forEach((mode) => {
const meta = ProviderPresets.ENDPOINT_MODE_META[mode] || { label: mode };
const option = document.createElement('option');
option.value = mode;
option.textContent = meta.label;
select.appendChild(option);
});
select.value = modes.includes(nextMode) ? nextMode : (modes[0] || nextMode);
return select.value;
}
function getCurrentSelection() {
const presetId = $('providerPreset').value || 'custom';
const selectedRouteId = $('providerRoute')?.value || '';
const route = ProviderPresets.getProviderRoute(presetId, selectedRouteId)
|| ProviderPresets.inferRouteFromSettings(getConnectionFieldSettings(), presetId);
const provider = ProviderPresets.normalizeProvider($('aiProvider').value || route?.aiProvider || '', presetId);
const endpointMode = ProviderPresets.normalizeEndpointMode($('endpointMode').value || route?.defaultEndpointMode || '', provider, presetId);
const preset = ProviderPresets.getPreset(presetId);
const profile = ProviderPresets.getProviderProfile(presetId, provider);
return { presetId, provider, endpointMode, preset, profile, route };
}
function maybeApplySuggestedValue(fieldId, suggestedValue, options = {}) {
if (typeof suggestedValue === 'undefined') return;
const field = $(fieldId);
const currentValue = String(field.value || '').trim();
const autoKey = fieldId === 'baseURL' ? 'baseURL' : 'modelName';
const previousAutoValue = autoFillState[autoKey] || '';
const shouldApply = options.force || !currentValue || currentValue === previousAutoValue;
if (shouldApply) {
field.value = String(suggestedValue || '');
}
}
function renderConnectionSummary(selection) {
const { preset, route, provider, endpointMode } = selection;
const baseUrl = normalizeBaseURLInput($('baseURL')?.value || '') || route?.baseUrl || '';
const model = String($('modelName')?.value || '').trim() || route?.defaultModel || selection.profile?.defaultModel || '默认模型';
const routeLabel = route?.label || '自定义地址';
$('connectionProviderValue').textContent = preset?.label || '自定义兼容接口';
$('connectionRouteValue').textContent = routeLabel;
$('connectionEndpointValue').textContent = `${UiLabels.getProviderLabel(provider, { variant: 'settings', fallback: provider })} · ${getEndpointModeLabel(endpointMode)}`;
$('connectionBaseUrlValue').textContent = baseUrl || '需要填写自定义 Base URL';
$('connectionModelValue').textContent = model;
}
function setAdvancedSettingsState(presetId) {
const details = $('advancedConnectionSettings');
if (!details) return;
if (presetId === 'custom') {
details.open = true;
}
}
function updateHints() {
const selection = getCurrentSelection();
const { provider, endpointMode, preset, profile, route } = selection;
const endpointMeta = ProviderPresets.ENDPOINT_MODE_META[endpointMode] || { description: '' };
const endpointPreview = buildEndpointPreview(provider, endpointMode);
const sourceText = preset?.sourceUrl
? `来源:${preset.sourceUrl}${preset.verifiedAt ? `(${preset.verifiedAt})` : ''}`
: '';
$('presetHint').textContent = preset?.hint || '选择服务商后会自动填入推荐接口地址。';
$('routeHint').textContent = [route?.hint || '', route?.keyHint || ''].filter(Boolean).join(' ');
$('apiKeyHint').textContent = route?.keyHint || '填写所选服务商的 API Key。';
$('endpointModeHint').textContent = [
endpointMeta.description || '',
endpointPreview ? `当前会按这个模式补最终路径:${endpointPreview}。` : ''
].filter(Boolean).join(' ');
const baseUrlHint = route?.baseUrl
? `推荐根地址:${route.baseUrl}。需要代理或私有网关时可直接覆盖。`
: (PROVIDER_FALLBACK_HINTS[provider] || '');
$('baseURLHint').textContent = [baseUrlHint, BASE_URL_SECURITY_HINT].filter(Boolean).join(' ');
$('modelHint').textContent = profile?.defaultModel
? `推荐模型:${profile.defaultModel}。如果你有专属模型 ID,也可以直接覆盖。`
: '请填写目标厂商实际可用的模型名称。';
$('providerCatalogMeta').textContent = sourceText;
$('baseURL').placeholder = route?.baseUrl || profile?.baseUrl || '留空使用默认地址';
$('modelName').placeholder = route?.defaultModel || profile?.defaultModel || (provider === 'anthropic' ? 'claude-sonnet-4-20250514' : 'gpt-4o-mini');
setAdvancedSettingsState(selection.presetId);
renderConnectionSummary(selection);
renderEndpointPreview();
}
function syncSelectionState(options = {}) {
const presetId = $('providerPreset').value || 'custom';
let route = syncRouteOptions(presetId, options.preferredRouteId, options.preferredProvider);
const provider = syncProviderOptions(presetId, route?.aiProvider || options.preferredProvider);
if (!route || route.aiProvider !== provider) {
route = syncRouteOptions(presetId, '', provider);
}
const endpointMode = syncEndpointModeOptions(
presetId,
provider,
options.preferredEndpointMode || route?.defaultEndpointMode || $('endpointMode').value,
route
);
$('aiProvider').value = provider;
$('endpointMode').value = endpointMode;
if (route?.routeId) $('providerRoute').value = route.routeId;
if (options.syncSuggestedValues) {
const shouldForce = !!options.forceSuggestedValues;
maybeApplySuggestedValue('baseURL', route?.baseUrl || '', { force: shouldForce });
maybeApplySuggestedValue('modelName', route?.defaultModel || '', { force: shouldForce });
}
autoFillState.baseURL = route?.baseUrl || '';
autoFillState.modelName = route?.defaultModel || '';
updateHints();
}
function validateBaseURL(url) {
if (!url) return true;
if (UrlUtils?.isAllowedModelEndpointUrl) return UrlUtils.isAllowedModelEndpointUrl(url);
try {
const parsed = new URL(url);
return parsed.protocol === 'https:';
} catch {
return false;
}
}
function normalizeBaseURLInput(value) {
if (UrlUtils?.normalizeBaseURLInput) return UrlUtils.normalizeBaseURLInput(value);
const raw = String(value || '').trim();
if (!raw) return '';
let normalized = raw;
if (!/^https?:\/\//i.test(normalized)) {
// Treat bare domains/hosts as HTTPS by default for convenience.
if (/^[a-z0-9.-]+(?::\d+)?(?:\/|$)/i.test(normalized)) {
normalized = 'https://' + normalized;
}
}
try {
const parsed = new URL(normalized);
parsed.hash = '';
parsed.search = '';
parsed.pathname = String(parsed.pathname || '').replace(/\/+$/, '') || '/';
return parsed.toString().replace(/\/$/, '');
} catch {
return String(normalized).replace(/\/+$/, '');
}
}
function getProviderCredentialValidation(settings) {
const presetId = String(settings?.providerPreset || '').trim();
const provider = String(settings?.aiProvider || '').trim();
const profile = ProviderPresets?.getProviderProfile?.(presetId, provider);
const route = ProviderPresets?.inferRouteFromSettings?.(settings, presetId);
const baseUrl = String(settings?.aiBaseURL || route?.baseUrl || profile?.baseUrl || '').trim();
const apiKey = String(settings?.apiKey || '').trim();
if (!ProviderPresets?.validateCredentials) {
return { valid: true, message: '' };
}
return ProviderPresets.validateCredentials(presetId, provider, baseUrl, apiKey);
}
function collectSettings() {
const presetId = $('providerPreset').value || 'custom';
const provider = ProviderPresets.normalizeProvider($('aiProvider').value, presetId);
const endpointMode = ProviderPresets.normalizeEndpointMode($('endpointMode').value, provider, presetId);
return {
providerPreset: presetId,
aiProvider: provider,
endpointMode,
apiKey: $('apiKey').value.trim(),
aiBaseURL: normalizeBaseURLInput($('baseURL').value.trim()),
modelName: $('modelName').value.trim(),
systemPrompt: $('systemPrompt').value.trim(),
autoTranslate: $('autoTranslate').checked,
defaultLanguage: $('defaultLanguage').value,
themePreference: Theme.normalizePreference($('themePreference').value),
themePalette: Theme.normalizePalette($('themePalette')?.value),
privacyMode: $('privacyMode').checked,
defaultAllowHistory: $('defaultAllowHistory').checked,
defaultAllowShare: $('defaultAllowShare').checked,
entrypointAutoStart: $('entrypointAutoStart').checked,
entrypointSimpleMode: $('entrypointSimpleMode').checked,
entrypointReuseHistory: $('entrypointReuseHistory').checked
};
}
function createSettingsSignature(settings) {
return JSON.stringify(settings);
}
function createProfileId() {
try {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return 'prof_' + crypto.randomUUID();
}
} catch {}
return 'prof_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 10);
}
function getProfileStorageKey(id) {
const safeId = String(id || '').trim();
return safeId ? PROFILE_KEY_PREFIX + safeId : '';
}
function normalizeProfilesIndex(value) {
if (!Array.isArray(value)) return [];
const output = [];
const seen = new Set();
value.forEach((item) => {
if (!item || typeof item !== 'object') return;
const id = String(item.id || '').trim();
if (!id || seen.has(id)) return;
seen.add(id);
const name = String(item.name || '').trim() || '未命名';
output.push({
id,
name,
updatedAt: String(item.updatedAt || ''),
lastUsedAt: String(item.lastUsedAt || ''),
providerPreset: String(item.providerPreset || ''),
aiProvider: String(item.aiProvider || '')
});
});
return output;
}
function upsertProfilesIndexEntry(index, entry, options = {}) {
const next = [];
const id = String(entry?.id || '').trim();
if (!id) return normalizeProfilesIndex(index);
const allowReorder = options.prepend === true;
let replaced = false;
(index || []).forEach((item) => {
if (!item || typeof item !== 'object') return;
const itemId = String(item.id || '').trim();
if (!itemId) return;
if (itemId === id) {
next.push(Object.assign({}, item, entry));
replaced = true;
} else {
next.push(item);
}
});
if (!replaced) {
if (allowReorder) next.unshift(entry);
else next.push(entry);
}
return normalizeProfilesIndex(next);
}
function removeProfilesIndexEntry(index, id) {
const targetId = String(id || '').trim();
if (!targetId) return normalizeProfilesIndex(index);
return normalizeProfilesIndex((index || []).filter((item) => String(item?.id || '').trim() !== targetId));
}
function findProfileIndexEntry(id) {
const safeId = String(id || '').trim();
if (!safeId) return null;
return (profileState.index || []).find((entry) => entry && entry.id === safeId) || null;
}
function renderProfileSelector() {
const select = $('profileSelect');
if (!select) return;
const activeId = profileState.activeId || '';
select.innerHTML = '';
const unboundOption = document.createElement('option');
unboundOption.value = '';
unboundOption.textContent = '当前配置(未绑定)';
select.appendChild(unboundOption);
(profileState.index || []).forEach((entry) => {
const option = document.createElement('option');
option.value = entry.id;
const presetLabel = ProviderPresets?.getPreset?.(entry.providerPreset)?.label || entry.providerPreset || 'custom';
option.textContent = entry.name + ' · ' + presetLabel;
select.appendChild(option);
});
select.value = activeId;
renderProfileHint();
}
function renderProfileHint() {
const hint = $('profileHint');
if (!hint) return;
const activeId = profileState.activeId || '';
const activeEntry = findProfileIndexEntry(activeId);
hint.textContent = activeId && activeEntry
? `已绑定:${activeEntry.name}。后续修改会自动更新该配置。`
: '未绑定:可以选择配置方案,或点击“另存为”创建一个可快速切换的配置。';
const renameBtn = $('profileRenameBtn');
const deleteBtn = $('profileDeleteBtn');
if (renameBtn) renameBtn.disabled = !activeId;
if (deleteBtn) deleteBtn.disabled = !activeId;
}
async function updateProfilesStorage(index, activeId) {
const payload = {
[PROFILES_INDEX_KEY]: normalizeProfilesIndex(index)
};
if (typeof activeId !== 'undefined') {
payload[ACTIVE_PROFILE_ID_KEY] = String(activeId || '').trim();
}
await storageSet(payload);
}
async function activateProfile(profileId) {
const id = String(profileId || '').trim();
const select = $('profileSelect');
if (!id) {
profileState.activeId = '';
await updateProfilesStorage(profileState.index, '');
renderProfileSelector();
setStatus('已切换到当前配置(未绑定)。', 'success');
setStatusDetails('');
return;
}
const key = getProfileStorageKey(id);
if (!key) return;
const items = await storageGet([key]);
const profileSettings = items?.[key] && typeof items[key] === 'object' ? items[key] : null;
if (!profileSettings) {
if (select) select.value = profileState.activeId || '';
setStatus('未找到该配置方案的数据,可能已被删除。', 'error');
return;
}
applySettingsToForm(profileSettings);
await persistSettings({ force: true, silentStatus: true, skipSuccessStatus: true });
profileState.activeId = id;
const now = new Date().toISOString();
profileState.index = upsertProfilesIndexEntry(profileState.index, Object.assign({}, findProfileIndexEntry(id) || { id, name: '未命名' }, {
id,
lastUsedAt: now,
providerPreset: profileSettings.providerPreset || '',
aiProvider: profileSettings.aiProvider || ''
}));
await updateProfilesStorage(profileState.index, id);
renderProfileSelector();
setStatus('已切换配置方案。', 'success');
setStatusDetails('');
}
async function createOrCloneProfile(name, settings, options = {}) {
const safeName = String(name || '').trim();
if (!safeName) return null;
const payloadSettings = Object.assign({}, settings || {});
const id = createProfileId();
const now = new Date().toISOString();
const key = getProfileStorageKey(id);
if (!key) return null;
const entry = {
id,
name: safeName,
updatedAt: now,
lastUsedAt: now,
providerPreset: payloadSettings.providerPreset || '',
aiProvider: payloadSettings.aiProvider || ''
};
const nextIndex = upsertProfilesIndexEntry(profileState.index, entry, { prepend: true });
const nextActiveId = options.activate === false ? (profileState.activeId || '') : id;
await storageSet(Object.assign({
[key]: payloadSettings,
[PROFILES_INDEX_KEY]: nextIndex,
[ACTIVE_PROFILE_ID_KEY]: nextActiveId
}, options.writeSettings !== false ? payloadSettings : {}));
profileState.index = nextIndex;
profileState.activeId = nextActiveId;
renderProfileSelector();
return id;
}
function getModelsCacheKeyFromSettings(settings) {
const provider = String(settings?.aiProvider || '').trim().toLowerCase();
if (!provider) return '';
const baseUrl = normalizeBaseURLInput(settings?.aiBaseURL || '');
if (!baseUrl) return provider;
if (provider === 'openai') {
const root = UrlUtils?.stripOpenAiEndpointSuffix?.(baseUrl) || baseUrl;
return provider + '|' + String(root || '').toLowerCase();
}
if (provider === 'anthropic') {
const root = UrlUtils?.stripAnthropicMessagesSuffix?.(baseUrl) || baseUrl;
return provider + '|' + String(root || '').toLowerCase();
}
return provider + '|' + String(baseUrl || '').toLowerCase();
}
function renderModelOptions(models, meta = {}) {
const datalist = $('modelNameOptions');
if (!datalist) return;
datalist.innerHTML = '';
const ids = Array.isArray(models) ? models.map((item) => (typeof item === 'string' ? item : item?.id)).filter(Boolean) : [];
ids.forEach((id) => {
const option = document.createElement('option');
option.value = String(id);
datalist.appendChild(option);
});
const hint = $('modelListHint');
if (!hint) return;
if (!ids.length) {
hint.textContent = meta.message || '';
return;
}
const fetchedAt = meta.fetchedAt ? formatDateTime(meta.fetchedAt) : '';
hint.textContent = fetchedAt ? `已加载 ${ids.length} 个模型(${fetchedAt})。` : `已加载 ${ids.length} 个模型。`;
}
async function loadCachedModelOptions(settings) {
try {
const cacheKey = getModelsCacheKeyFromSettings(settings);
if (!cacheKey) return;
const items = await storageLocalGet([MODELS_CACHE_STORAGE_KEY]);
const cache = items?.[MODELS_CACHE_STORAGE_KEY];
const entry = cache && typeof cache === 'object' ? cache?.[cacheKey] : null;
const models = Array.isArray(entry?.models) ? entry.models : [];
if (!models.length) return;
renderModelOptions(models, { fetchedAt: entry?.fetchedAt || '' });
} catch {
// Ignore local cache failures.
}
}
async function refreshModelOptions(options = {}) {
const button = $('refreshModelsBtn');
if (button) {
button.disabled = true;
button.textContent = '刷新中...';
}
try {