-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathui-frontend.js
More file actions
1848 lines (1651 loc) · 74 KB
/
Copy pathui-frontend.js
File metadata and controls
1848 lines (1651 loc) · 74 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
// ============================================================
// Codex Assistant — UI Controller
// ============================================================
// ---------- State ----------
let providers = { providers: [] };
let statusTimer = null;
let currentDefaultProvider = '';
let currentTheme = localStorage.getItem('codex-assistant-theme') || 'system';
// ---------- Theme ----------
function getSystemTheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function getEffectiveTheme() {
if (currentTheme === 'system') {
return getSystemTheme();
}
return currentTheme;
}
function setTheme(theme) {
currentTheme = theme;
localStorage.setItem('codex-assistant-theme', theme);
applyTheme();
updateThemeUI();
updateThemeRadioUI();
}
function toggleTheme() {
const themes = ['system', 'light', 'dark'];
const currentIndex = themes.indexOf(currentTheme);
const nextTheme = themes[(currentIndex + 1) % themes.length];
setTheme(nextTheme);
}
function updateThemeUI() {
const btn = document.getElementById('btn-theme');
const icon = document.getElementById('icon-theme');
if (!btn || !icon) return;
const effective = getEffectiveTheme();
if (currentTheme === 'system') {
btn.querySelector('span').textContent = '跟随系统';
icon.innerHTML = '<rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect><line x1="8" y1="21" x2="16" y2="21"></line><line x1="12" y1="17" x2="12" y2="21"></line>';
} else if (effective === 'dark') {
btn.querySelector('span').textContent = '深色模式';
icon.innerHTML = '<circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>';
} else {
btn.querySelector('span').textContent = '浅色模式';
icon.innerHTML = '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>';
}
}
function updateThemeRadioUI() {
const radio = document.querySelector('input[name="theme-mode"][value="' + currentTheme + '"]');
if (radio) radio.checked = true;
}
function applyTheme() {
const effective = getEffectiveTheme();
document.body.className = effective === 'light' ? 'theme-light' : '';
updateThemeUI();
}
// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function() {
if (currentTheme === 'system') {
applyTheme();
}
});
// ---------- CSRF Token ----------
var csrfToken = '';
function initCsrfToken() {
var meta = document.querySelector('meta[name="csrf-token"]');
if (meta) {
csrfToken = meta.getAttribute('content') || '';
} else {
console.warn('[ui] CSRF token not found in page — API writes will fail');
}
}
let toastTimer = null;
function toast(msg, type) {
type = type || 'success';
const el = document.getElementById('toast');
el.textContent = msg;
el.className = 'toast show toast-' + type;
clearTimeout(toastTimer);
toastTimer = setTimeout(function () { el.classList.remove('show'); }, 3200);
}
// ---------- API ----------
var API_TIMEOUT_MS = 30000; // 30s timeout for all API calls
async function api(path, method, body) {
method = method || 'GET';
var opts = { method: method, headers: {} };
if (body) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(body);
}
// Include CSRF token for all write requests
if (method !== 'GET' && csrfToken) {
opts.headers['X-CSRF-Token'] = csrfToken;
}
// AbortController timeout to prevent hung requests
var controller = new AbortController();
var timeoutId = setTimeout(function() { controller.abort(); }, API_TIMEOUT_MS);
opts.signal = controller.signal;
try {
var res = await fetch(path, opts);
clearTimeout(timeoutId);
return res.json();
} catch (e) {
clearTimeout(timeoutId);
if (e.name === 'AbortError') {
toast('请求超时,请检查服务是否正常运行', 'error');
throw new Error('Request timed out after ' + (API_TIMEOUT_MS / 1000) + 's');
}
throw e;
}
}
// ---------- Navigation ----------
function showPage(id, navEl) {
// Pages
document.querySelectorAll('.page').forEach(function (p) { p.classList.remove('active'); });
var page = document.getElementById('page-' + id);
if (page) page.classList.add('active');
// Nav
document.querySelectorAll('.nav-item').forEach(function (n) { n.classList.remove('active'); });
if (navEl) navEl.classList.add('active');
// Per-page init
if (id === 'logs') { loadLogs(); loadLogConfig(); }
if (id === 'env') {
// Fast calls first, so they don't queue behind slow codex checks
loadEnv();
setTimeout(function() { loadCodexppConfig(); }, 100);
}
if (id === 'settings') { loadCloseBehavior(); loadBackupList(); }
if (id === 'providers') { loadProviders(); }
}
// ---------- HTML Escape ----------
function escHtml(s) {
var d = document.createElement('div');
d.textContent = s;
return d.innerHTML;
}
function renderMarkdown(md) {
if (!md) return '';
var raw = (md + '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
raw = raw.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
var lines = raw.split('\n');
var out = '';
var inUl = false;
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (!line) { if (inUl) { out += '</ul>'; inUl = false; } continue; }
if (/^### .+/.test(line)) { if (inUl) { out += '</ul>'; inUl = false; } out += '<h3>' + escHtml(line.slice(4)) + '</h3>'; }
else if (/^## .+/.test(line)) { if (inUl) { out += '</ul>'; inUl = false; } out += '<h2>' + escHtml(line.slice(3)) + '</h2>'; }
else if (/^# .+/.test(line)) { if (inUl) { out += '</ul>'; inUl = false; } out += '<h1>' + escHtml(line.slice(2)) + '</h1>'; }
else if (/^- .+/.test(line)) { if (!inUl) { out += '<ul>'; inUl = true; } out += '<li>' + escHtml(line.slice(2)).replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>').replace(/\*(.+?)\*/g, '<em>$1</em>') + '</li>'; }
else { if (inUl) { out += '</ul>'; inUl = false; } out += '<p>' + escHtml(line).replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>').replace(/\*(.+?)\*/g, '<em>$1</em>') + '</p>'; }
}
if (inUl) { out += '</ul>'; }
return out;
}
function openExternal(url) {
api('/api/open-url', 'POST', { url: url });
}
function escAttr(s) {
return (s || '').replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
}
// ==================== Status & Dashboard ====================
var lastProxyRunning = null;
var manualStopPending = false; // 标记:用户是否刚刚手动点击了停止代理
async function loadStatus() {
try {
var d = await api('/api/status');
// Detect proxy crash
if (manualStopPending && lastProxyRunning === true && !d.proxy_running) {
manualStopPending = false;
toast('代理已停止');
} else if (lastProxyRunning === true && !d.proxy_running) {
try {
var logs = await api('/api/logs');
var recentErrors = (logs.logs || []).filter(function (l) {
return l.type === 'stderr' || (l.type === 'system' && l.msg.indexOf('退出') !== -1);
}).slice(-3);
if (recentErrors.length > 0) {
toast('代理意外停止,请检查运行日志', 'error');
}
} catch (e) { /* transient failure, will retry */ }
}
lastProxyRunning = d.proxy_running;
// Proxy status
var dotP = document.getElementById('s-dot-proxy');
var txtP = document.getElementById('s-text-proxy');
dotP.className = 'status-dot ' + (d.proxy_running ? 'running' : 'stopped');
txtP.textContent = d.proxy_running ? (d.proxy_external_alive ? '运行中(外部)' : '运行中') : '已停止';
var btnP = document.getElementById('btn-proxy');
btnP.textContent = d.proxy_running ? '停止代理' : '启动代理';
btnP.className = d.proxy_running ? 'btn btn-danger' : 'btn btn-primary';
// Codex status
var dotC = document.getElementById('s-dot-codex');
var txtC = document.getElementById('s-text-codex');
dotC.className = 'status-dot ' + (d.codex_running ? 'running' : 'stopped');
txtC.textContent = d.codex_running ? '运行中' : '未运行';
// Port
document.getElementById('s-port').textContent = d.port || '4000';
// Refresh stats when proxy is running and we haven't got data yet
// (retries on next loop if first attempt fails due to race condition)
if (d.proxy_running && _uptimeTs === 0) { loadStats(); }
if (!d.proxy_running && _uptimeTs !== 0) {
_uptimeBase = 0; _uptimeTs = 0;
var uptimeEl = document.getElementById('s-uptime');
if (uptimeEl) uptimeEl.textContent = '--';
}
// Model count
var pd = await api('/api/providers');
var totalModels = (pd.providers || []).reduce(function (s, p) { return s + (p.models || []).length; }, 0);
document.getElementById('s-models').textContent = totalModels;
// Update dropdowns
fillModelSelect();
} catch (e) { /* transient failure, will retry */ }
}
function startStatusLoop() {
loadStatus();
loadStats();
statusTimer = setInterval(function () { loadStatus(); }, 5000);
}
// ==================== Stats ====================
var _uptimeBase = 0; // server-reported seconds
var _uptimeTs = 0; // local timestamp when we got it
function startUptimeTicker() {
setInterval(function () {
var el = document.getElementById('s-uptime');
if (!el) return;
if (_uptimeTs === 0) { el.textContent = '--'; return; }
var total = _uptimeBase + Math.floor((Date.now() - _uptimeTs) / 1000);
el.textContent = formatUptime(total);
}, 200);
}
async function loadStats() {
try {
var d = await api('/api/stats');
if (!d || d.proxy_offline) {
_uptimeBase = 0; _uptimeTs = 0;
var uptimeEl = document.getElementById('s-uptime');
if (uptimeEl) uptimeEl.textContent = '--';
return;
}
_uptimeBase = d.uptime_seconds || 0;
_uptimeTs = Date.now();
} catch (e) { /* transient failure, will retry */ }
}
function formatUptime(s) {
var sec = s % 60;
if (s < 60) return s + 's';
if (s < 3600) return Math.floor(s / 60) + 'm ' + sec + 's';
return Math.floor(s / 3600) + 'h ' + Math.floor((s % 3600) / 60) + 'm ' + sec + 's';
}
// ==================== Model Display ====================
var currentAppliedModel = '';
var currentAuxModel = '';
function updateCurrentModelDisplay(allModels) {
var cardEl = document.getElementById('model-display-card');
var displayEl = document.getElementById('current-model-display');
if (!displayEl || !cardEl) return;
// If the configured model no longer exists in providers, treat as unset
if (currentAppliedModel && !allModels.some(function (m) { return m.slug === currentAppliedModel; })) {
currentAppliedModel = '';
currentAuxModel = '';
}
if (!currentAppliedModel) {
cardEl.style.display = 'block';
if (allModels && allModels.length > 0) {
displayEl.innerHTML = '<div class="model-display-value" style="color:var(--text-muted);">请配置 Codex 的提供商和模型信息并应用</div>';
} else {
displayEl.innerHTML = '<div class="model-display-value" style="color:var(--text-muted);">请至少配置一个提供商</div>';
}
return;
}
cardEl.style.display = 'block';
var mainModel = allModels.find(function (m) { return m.slug === currentAppliedModel; });
var mainName = mainModel ? mainModel.name : currentAppliedModel;
var mainColor = mainModel ? 'var(--success)' : 'var(--error)';
var auxText = '跟随主模型';
var auxColor = 'var(--success)';
if (currentAuxModel && currentAuxModel !== currentAppliedModel) {
var auxModel = allModels.find(function (m) { return m.slug === currentAuxModel; });
auxText = auxModel ? auxModel.name : currentAuxModel;
auxColor = auxModel ? 'var(--accent)' : 'var(--error)';
}
displayEl.innerHTML =
'<div class="model-display-item">' +
'<span class="model-display-label">主模型</span>' +
'<span class="model-display-value" style="color:' + mainColor + ';">' + escHtml(mainName) + '</span>' +
'</div>' +
'<div class="model-display-item">' +
'<span class="model-display-label">辅助模型</span>' +
'<span class="model-display-value" style="color:' + auxColor + ';">' + escHtml(auxText) + '</span>' +
'</div>';
}
// ==================== Model Select Dropdowns ====================
function fillModelSelect() {
var providerSelect = document.getElementById('quick-provider');
var modelSelect = document.getElementById('quick-model');
if (!providerSelect || !modelSelect) return;
var currentProvider = providerSelect.value;
var currentModel = modelSelect.value;
var providerList = providers.providers || [];
providerSelect.innerHTML = providerList.length === 0
? '<option value="">暂无提供商</option>'
: '<option value="">选择提供商</option>' + providerList.map(function (p) {
return '<option value="' + escAttr(p.name) + '">' + escHtml(p.name) + '</option>';
}).join('');
if (currentProvider && providerList.some(function (p) { return p.name === currentProvider; })) {
providerSelect.value = currentProvider;
}
onProviderChange();
var modelSelectAfter = document.getElementById('quick-model');
if (currentModel && modelSelectAfter) {
var opts = modelSelectAfter.options;
for (var i = 0; i < opts.length; i++) {
if (opts[i].value === currentModel) { modelSelectAfter.value = currentModel; break; }
}
}
fillAuxProviderSelect();
var allModels = [];
providerList.forEach(function (p) {
(p.models || []).forEach(function (m) {
allModels.push({ slug: m.slug || m.id, name: m.display_name || m.id, provider: p.name });
});
});
updateCurrentModelDisplay(allModels);
}
function onProviderChange() {
var providerSelect = document.getElementById('quick-provider');
var modelSelect = document.getElementById('quick-model');
if (!providerSelect || !modelSelect) return;
var selectedProvider = providerSelect.value;
var provider = (providers.providers || []).find(function (p) { return p.name === selectedProvider; });
if (provider && provider.models && provider.models.length > 0) {
modelSelect.innerHTML = provider.models.map(function (m) {
var slug = m.slug || m.id;
var name = m.display_name || m.id;
return '<option value="' + escAttr(slug) + '">' + escHtml(name) + '</option>';
}).join('');
} else {
modelSelect.innerHTML = '<option value="">请先选择提供商</option>';
}
}
function onAuxProviderChange() {
var providerSelect = document.getElementById('quick-aux-provider');
var modelSelect = document.getElementById('quick-aux-model');
if (!providerSelect || !modelSelect) return;
var selectedProvider = providerSelect.value;
if (!selectedProvider) {
modelSelect.innerHTML = '<option value="">跟随主模型</option>';
return;
}
var provider = (providers.providers || []).find(function (p) { return p.name === selectedProvider; });
if (provider && provider.models && provider.models.length > 0) {
modelSelect.innerHTML = provider.models.map(function (m) {
var slug = m.slug || m.id;
var name = m.display_name || m.id;
return '<option value="' + escAttr(slug) + '">' + escHtml(name) + '</option>';
}).join('');
} else {
modelSelect.innerHTML = '<option value="">该提供商无模型</option>';
}
}
function fillAuxProviderSelect() {
var providerSelect = document.getElementById('quick-aux-provider');
if (!providerSelect) return;
var currentProvider = providerSelect.value;
var currentModel = document.getElementById('quick-aux-model') ? document.getElementById('quick-aux-model').value : '';
var providerList = providers.providers || [];
providerSelect.innerHTML = '<option value="">跟随主模型</option>' +
providerList.map(function (p) {
return '<option value="' + escAttr(p.name) + '">' + escHtml(p.name) + '</option>';
}).join('');
if (currentProvider && providerList.some(function (p) { return p.name === currentProvider; })) {
providerSelect.value = currentProvider;
onAuxProviderChange();
var modelSelect = document.getElementById('quick-aux-model');
if (currentModel && modelSelect) {
var opts = modelSelect.options;
for (var i = 0; i < opts.length; i++) {
if (opts[i].value === currentModel) { modelSelect.value = currentModel; break; }
}
}
}
}
// ==================== Agent / Codex Control ====================
async function toggleProxy() {
var d = await api('/api/status');
if (d.proxy_running) {
manualStopPending = true;
await api('/api/proxy/stop', 'POST');
toast('正在停止代理...');
setTimeout(loadStatus, 500);
return;
}
// Check if any providers are configured
var pd = await api('/api/providers');
var providerCount = (pd.providers || []).length;
if (providerCount === 0) {
toast('请先在"提供商管理"中添加至少一个提供商', 'error');
return;
}
// Check if user has applied a model to Codex
if (!currentAppliedModel) {
toast('请先在"提供商管理"中选择模型并点击"应用到 Codex",然后再启动代理', 'warning');
return;
}
var result = await api('/api/proxy/start', 'POST');
if (result.success && result.port) {
document.getElementById('s-port').textContent = result.port;
var msg = '代理已启动,端口: ' + result.port;
if (result.synced && result.synced.length > 0) {
msg += '\n' + result.synced.join('\n');
}
toast(msg);
// 刷新状态
setTimeout(loadStatus, 500);
} else {
toast(result.message || '启动失败', 'error');
}
}
async function restartProxy() {
toast('正在重启代理...');
var result = await api('/api/proxy/restart', 'POST');
if (result.success) {
var msg = '代理重启成功';
if (result.port) msg += ',端口: ' + result.port;
if (result.synced && result.synced.length > 0) {
msg += '\n' + result.synced.join('\n');
}
toast(msg);
} else {
toast(result.message || '代理重启失败', 'error');
}
loadStatus();
}
async function startCodex(mode) {
// Must have a model configured before starting proxy
if (!currentAppliedModel) {
toast('请先在"快速配置 Codex"中选择模型并点击"应用配置到 Codex",然后再启动', 'warning');
return;
}
var status = await api('/api/status');
if (!status.proxy_running) {
toast('代理未运行,正在启动代理...');
var proxyResult = await api('/api/proxy/start', 'POST');
if (proxyResult.success) {
toast('代理已启动');
await new Promise(function (r) { setTimeout(r, 500); });
} else {
toast('代理启动失败: ' + (proxyResult.message || '未知错误'), 'error');
return;
}
}
var endpoint;
switch (mode) {
case 'cli': endpoint = '/api/codex/start-cli'; break;
case 'app': endpoint = '/api/codex/start-app'; break;
case 'codexpp': endpoint = '/api/codex/start-codexpp'; break;
case 'codexpp-manager': endpoint = '/api/codex/start-codexpp-manager'; break;
default: endpoint = '/api/codex/start-cli';
}
var result = await api(endpoint, 'POST');
if (result.success) {
toast(result.message);
} else {
toast(result.message || '启动失败', 'error');
}
setTimeout(loadStatus, 500);
}
async function stopCodex() {
var status = await api('/api/status');
var type = 'all';
if (status.codex_running_type) {
if (status.codex_running_type === 'codexpp') type = 'codexpp';
else if (status.codex_running_type === 'cli') type = 'cli';
else type = 'app';
}
var result = await api('/api/codex/stop', 'POST', { type: type });
toast(result.message || 'Codex 已停止');
loadStatus();
}
async function checkCodexInstalled() {
// 四项独立检测,各自并行,完成一项就更新一项 UI
api('/api/codex/check-cli').then(function(r) {
var cliBtn = document.getElementById('btn-codex-cli');
if (cliBtn) {
cliBtn.disabled = !r.ok;
cliBtn.title = r.ok ? '启动 Codex CLI' : '未安装 Codex CLI';
}
}).catch(function(){});
api('/api/codex/check-desktop').then(function(r) {
var appBtn = document.getElementById('btn-codex-app');
if (appBtn) {
appBtn.disabled = !r.ok;
var codexType = r.type || 'exe';
appBtn.textContent = '启动 Codex 桌面版';
appBtn.title = r.ok ? '启动 Codex 桌面版' : '未安装 Codex';
}
}).catch(function(){});
api('/api/codex/check-plusplus').then(function(r) {
var cppBtn = document.getElementById('btn-codexpp');
if (cppBtn) cppBtn.disabled = !r.ok;
}).catch(function(){});
api('/api/codex/check-plusplus-manager').then(function(r) {
var mgrBtn = document.getElementById('btn-codexpp-manager');
if (mgrBtn) mgrBtn.disabled = !r.ok;
}).catch(function(){});
}
// ==================== Codex Backup & Restore ====================
async function loadBackupList() {
try {
var d = await api('/api/codex-backup/list');
var statusEl = document.getElementById('backup-status');
var listEl = document.getElementById('backup-list');
if (d.isModified) {
statusEl.innerHTML = '✓ Codex 配置已被 Codex Assistant 修改(自动备份已完成)';
statusEl.style.color = 'var(--success)';
} else {
statusEl.innerHTML = '⚠ Codex 配置未被修改(由 Codex 或其他工具管理)';
statusEl.style.color = 'var(--warning)';
}
if (!d.backups || d.backups.length === 0) {
listEl.innerHTML = '<div style="color:var(--text-muted);font-size:var(--text-sm);padding:var(--space-2);">暂无备份</div>';
return;
}
listEl.innerHTML = d.backups.map(function (b) {
var date = new Date(b.time);
var dateStr = date.getFullYear() + '年' +
String(date.getMonth()+1).padStart(2,'0') + '月' +
String(date.getDate()).padStart(2,'0') + '日 ' +
String(date.getHours()).padStart(2,'0') + ':' +
String(date.getMinutes()).padStart(2,'0');
var isAuto = b.name.includes('自动') || b.name.includes('auto');
var nameShort = b.name.replace(/\.zip$/i, '');
// Lock SVG icon
var lockSvg = b.locked
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="backup-lock-icon locked"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>'
: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="backup-lock-icon"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path><line x1="12" y1="15" x2="12" y2="19"></line></svg>';
// Folder SVG icon
var folderSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="backup-action-icon"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>';
// Delete SVG icon
var delSvg = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="backup-action-icon"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>';
return '<div class="backup-item">' +
'<div class="backup-row1">' +
'<button class="backup-lock-btn" onclick="toggleLockBackup(\'' + escAttr(b.name) + '\',' + !b.locked + ')" title="' + (b.locked ? '已锁定,点击解锁' : '未锁定,点击锁定') + '">' + lockSvg + '</button>' +
'<span class="backup-name" title="' + escAttr(b.name) + '">' + escHtml(nameShort) + '</span>' +
(isAuto ? '<span class="backup-tag">自动</span>' : '<span class="backup-tag manual">手动</span>') +
'<span class="backup-date">' + dateStr + '</span>' +
'</div>' +
'<div class="backup-row2">' +
'<button class="backup-action-btn" onclick="restoreBackup(\'' + escAttr(b.name) + '\')">恢复</button>' +
'<button class="backup-action-btn" onclick="renameBackup(\'' + escAttr(b.name) + '\')">重命名</button>' +
'<button class="backup-action-btn" onclick="openBackupFolder()">' + folderSvg + ' 打开文件夹</button>' +
'<button class="backup-action-btn backup-delete-btn' + (b.locked ? ' disabled' : '') + '" onclick="' + (b.locked ? 'return' : 'deleteBackup(\'' + escAttr(b.name) + '\')') + '" title="' + (b.locked ? '已锁定,无法删除' : '删除此备份') + '"' + (b.locked ? ' disabled' : '') + '>' + delSvg + ' 删除</button>' +
'</div>' +
'</div>';
}).join('');
} catch (e) {
toast('加载备份列表失败: ' + e.message, 'error');
}
}
async function createBackup() {
try {
var result = await api('/api/codex-backup/create', 'POST');
if (result.skipped) {
toast(result.message, 'warning');
return;
}
if (!result.success) {
throw new Error(result.error || '备份失败');
}
toast('备份已创建');
await loadBackupList();
} catch (e) {
toast('备份失败: ' + e.message, 'error');
}
}
async function restoreBackup(name) {
if (!confirm('确定要恢复备份 "' + name + '" 吗?\n\n当前配置将被备份,然后恢复为备份版本。\n恢复后需要重启 Codex 才能生效。')) return;
try {
var result = await api('/api/codex-backup/restore', 'POST', { name: name });
if (!result.success) {
throw new Error(result.error || '恢复失败');
}
toast(result.message || '恢复成功');
await loadBackupList();
} catch (e) {
toast('恢复失败: ' + e.message, 'error');
}
}
async function deleteBackup(name) {
if (!confirm('确定要删除备份 "' + name + '" 吗?')) return;
try {
var result = await api('/api/codex-backup/delete', 'POST', { name: name });
if (!result.success) {
throw new Error(result.error || '删除失败');
}
toast('备份已删除');
await loadBackupList();
} catch (e) {
toast('删除失败: ' + e.message, 'error');
}
}
async function toggleLockBackup(name, locked) {
try {
var result = await api('/api/codex-backup/lock', 'POST', { name: name, locked: locked });
if (!result.success) {
throw new Error(result.error || '操作失败');
}
toast(locked ? '备份已锁定' : '备份已解锁');
await loadBackupList();
} catch (e) {
toast('操作失败: ' + e.message, 'error');
}
}
async function renameBackup(name) {
var newName = prompt('输入新的备份名称(不含 .zip 后缀):', name.replace('codex-backup-', '').replace('.zip', ''));
if (!newName || newName === name.replace('codex-backup-', '').replace('.zip', '')) return;
var fullName = 'codex-backup-' + newName + '.zip';
try {
var result = await api('/api/codex-backup/rename', 'POST', { name: name, newName: fullName });
if (!result.success) {
throw new Error(result.error || '重命名失败');
}
toast('重命名成功');
await loadBackupList();
} catch (e) {
toast('重命名失败: ' + e.message, 'error');
}
}
function openBackupFolder() {
api('/api/codex-backup/list').then(function (d) {
if (d.backupDir) {
api('/api/open-folder', 'POST', { path: d.backupDir });
}
});
}
// ==================== Codex++ manual path config ====================
async function loadCodexppConfig() {
try {
var d = await api('/api/codexpp-path');
if (d) {
if (d.codexppPath) document.getElementById('cfg-codexpp-path').value = d.codexppPath;
if (d.codexppMgrPath) document.getElementById('cfg-codexpp-mgr-path').value = d.codexppMgrPath;
}
} catch (e) { /* transient failure, will retry */ }
}
async function selectCodexppPath() {
var result = await api('/api/select-file', 'POST', {
title: '选择 Codex++ 主程序 (codex-plus-plus.exe)',
defaultPath: document.getElementById('cfg-codexpp-path').value || '',
filter: 'codex-plus-plus.exe'
});
if (result && result.success && result.path) {
document.getElementById('cfg-codexpp-path').value = result.path;
// Auto-derive manager path from same directory
var dir = result.path.replace(/[^\\/]+$/, '');
var mgrPath = dir + 'codex-plus-plus-manager.exe';
document.getElementById('cfg-codexpp-mgr-path').value = mgrPath;
toast('已选择 Codex++ 路径');
}
}
async function saveCodexppConfig() {
var codexppPath = document.getElementById('cfg-codexpp-path').value.trim();
var mgrPath = document.getElementById('cfg-codexpp-mgr-path').value.trim();
try {
var result = await api('/api/codexpp-path', 'POST', { codexppPath: codexppPath, codexppMgrPath: mgrPath });
if (!result || !result.success) {
throw new Error((result && result.error) || '保存失败');
}
toast('Codex++ 路径已保存');
await checkCodexInstalled();
} catch (e) {
toast('保存失败: ' + e.message, 'error');
}
}
async function autoDetectCodexpp() {
toast('正在自动检测...');
var result = await api('/api/codex/check-installed');
if (result && result.codexPlusPlus) {
// Auto-detection found it — fetch the saved/auto path
var pathInfo = await api('/api/codexpp-path');
if (pathInfo && pathInfo.codexppPath) {
document.getElementById('cfg-codexpp-path').value = pathInfo.codexppPath;
document.getElementById('cfg-codexpp-mgr-path').value = pathInfo.codexppMgrPath || '';
toast('自动检测成功');
} else {
toast('自动检测成功,但未获取到路径', 'error');
}
} else {
toast('未检测到 Codex++ 安装,请手动选择', 'error');
}
}
// ==================== Quick Apply Config ====================
async function quickApply() {
var model = document.getElementById('quick-model').value;
var auxProvider = document.getElementById('quick-aux-provider').value;
var auxModel = document.getElementById('quick-aux-model').value;
var port = document.getElementById('s-port').textContent;
if (!model) { toast('请先在提供商管理中添加模型', 'error'); return; }
var status = await api('/api/status');
if (!status.proxy_running) {
toast('代理未运行,正在启动...');
var proxyResult = await api('/api/proxy/start', 'POST');
if (proxyResult.success) {
await new Promise(function (r) { setTimeout(r, 500); });
} else {
toast('代理启动失败: ' + (proxyResult.message || '未知错误'), 'error');
return;
}
}
var actualModel = model;
try {
// 通过 ui-server 中转获取模型列表,避免 CORS
var modelsResponse = await api('/api/proxy-models');
var availableModels = modelsResponse.data || [];
var modelExists = availableModels.some(function (m) { return m.id === model; });
if (!modelExists) {
// 不要静默替换,让用户知道并保持原选择
toast('注意: 模型 "' + model + '" 不在代理当前模型列表中,仍将写入 Codex 配置(代理会尝试路由)', 'error');
}
} catch (e) {
console.error('Failed to check models:', e);
}
var actualAuxModel = '';
if (auxProvider && auxModel) {
actualAuxModel = auxModel;
} else {
actualAuxModel = actualModel;
}
await api('/api/update-aux-model', 'POST', {
mainModel: actualModel,
auxModel: actualAuxModel,
auxProvider: auxProvider || null
});
// Get context_window for the selected model (0 = 不配置, omit from config)
var ctxWindow = 0;
var allProviders = providers.providers || [];
for (var pi = 0; pi < allProviders.length; pi++) {
var pm = allProviders[pi].models || [];
for (var mi = 0; mi < pm.length; mi++) {
if (pm[mi].id === actualModel || pm[mi].slug === actualModel) {
ctxWindow = pm[mi].context_window || 0;
break;
}
}
}
var configBody = { model: actualModel, port: port };
if (ctxWindow > 0) configBody.context_window = ctxWindow;
await api('/api/codex-config', 'POST', configBody);
currentAppliedModel = actualModel;
currentAuxModel = actualAuxModel || actualModel;
var allModels = [];
(providers.providers || []).forEach(function (p) {
(p.models || []).forEach(function (m) {
allModels.push({ slug: m.slug || m.id, name: m.display_name || m.id, provider: p.name });
});
});
updateCurrentModelDisplay(allModels);
if (status.codex_running) {
// Codex 已运行:停止后以相同版本重启
toast('Codex 配置已更新,正在重启...');
await api('/api/codex/stop', 'POST');
await new Promise(function (r) { setTimeout(r, 500); });
var startEndpoint = '/api/codex/start-app';
if (status.codex_running_type) {
switch (status.codex_running_type) {
case 'cli': startEndpoint = '/api/codex/start-cli'; break;
case 'codexpp': startEndpoint = '/api/codex/start-codexpp'; break;
}
}
await api(startEndpoint, 'POST');
toast('Codex 配置已更新并重启');
} else {
// Codex 未运行:仅写入配置,不擅自启动(无法判断用户想用哪个版本)
toast('配置已应用到 Codex');
}
loadStatus();
}
// ==================== Providers ====================
async function loadProviders() {
providers = await api('/api/providers');
renderProviders();
fillModelSelect();
}
function renderProviders() {
var container = document.getElementById('provider-list');
var list = providers.providers || [];
if (list.length === 0) {
container.innerHTML = '<div class="empty-state">' +
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"></path></svg>' +
'<p>暂无提供商</p>' +
'<button class="btn btn-primary" onclick="showProviderModal()">添加第一个提供商</button>' +
'</div>';
return;
}
container.innerHTML = list.map(function (p, i) {
return '<div class="provider-card">' +
'<div class="provider-header">' +
'<div class="provider-info">' +
'<div class="provider-name-row">' +
'<span class="provider-name">' + escHtml(p.name) + '</span>' +
(p.name === currentDefaultProvider ? '<span class="badge badge-primary">默认</span>' : '') +
'</div>' +
'<div class="provider-url">' + escHtml(p.base_url) + '</div>' +
'<div class="provider-meta">协议:' + escHtml(p.protocol || 'openai') + ' / 模型数:' + (p.models || []).length + ' / Key:' +
(p._decrypt_warning ? '<span style="color:var(--error);" title="' + escAttr(p._decrypt_warning) + '">⚠ 需重新输入</span>' :
p.api_key ? '●●●●●●●' : '未填写') + '</div>' +
'</div>' +
'<div class="provider-actions">' +
(p._decrypt_warning ? '<span style="color:var(--warning);font-size:var(--text-xs);margin-right:var(--space-2);">⚠ 密钥已丢失,请编辑重新输入</span>' : (p.api_key ? '<button class="btn btn-sm btn-secondary" onclick="testProviderConnection(' + i + ')">测试连接</button>' : '')) +
(p.name !== currentDefaultProvider ? '<button class="btn btn-sm btn-ghost" onclick="setDefaultProvider(\'' + escAttr(p.name) + '\')">设为默认</button>' : '') +
'<button class="btn btn-sm btn-ghost" onclick="editProvider(' + i + ')">编辑</button>' +
'<button class="btn btn-sm btn-ghost" onclick="deleteProvider(' + i + ')" style="color:var(--error);">删除</button>' +
'</div>' +
'</div>' +
'<div class="model-tags">' +
(p.models || []).map(function (m) {
var ctx = m.context_window;
var ctxLabel = ctx >= 1000000 ? Math.round(ctx / 1000000) + 'M' : ctx >= 1000 ? Math.round(ctx / 1000) + 'K' : '';
return '<div class="model-tag-wrapper"><span class="model-tag">' + escHtml(m.display_name || m.id) +
'<span class="remove" onclick="event.stopPropagation();removeModel(' + i + ',\'' + escAttr(m.slug || m.id) + '\')">×</span></span>' +
(ctxLabel ? '<span class="model-context-hint">' + ctxLabel + ' 上下文</span>' : '') +
'</div>';
}).join('') +
'</div>' +
'</div>';
}).join('');
}
// ---------- Provider Modal ----------
function showProviderModal(idx) {
idx = idx !== undefined ? idx : -1;
document.getElementById('pm-title').textContent = idx >= 0 ? '编辑提供商' : '添加提供商';
document.getElementById('pm-idx').value = idx;
document.getElementById('pm-fetch-status').textContent = '';
document.getElementById('pm-fetch-status').className = 'fetch-status';
document.getElementById('pm-model-list').style.display = 'none';
document.getElementById('pm-model-hint').style.display = 'none';
if (idx >= 0 && providers.providers[idx]) {
var p = providers.providers[idx];
document.getElementById('pm-name').value = p.name || '';
document.getElementById('pm-base').value = p.base_url || '';
document.getElementById('pm-key').value = p.api_key || '';
document.getElementById('pm-protocol').value = p.protocol || 'openai';
// Show saved models with context_window
if (p.models && p.models.length > 0) {
var CTX_OPTIONS = [
{ label: '8K', value: 8192 },
{ label: '16K', value: 16384 },
{ label: '32K', value: 32768 },
{ label: '64K', value: 65536 },
{ label: '128K', value: 131072 },
{ label: '200K', value: 200000 },
{ label: '500K', value: 500000 },
{ label: '1M', value: 1048576 },
{ label: '不配置', value: 0 }
];
var KNOWN_CTX = {
'mimo-v2.5': 1048576, 'mimo-v2.5-pro': 1048576,
'deepseek-v4-pro': 1048576, 'deepseek-v4-flash': 1048576,
'deepseek-v3': 131072, 'deepseek-r1': 131072,
'gpt-4o': 128000, 'gpt-4o-mini': 128000,
'gpt-4.1': 1048576, 'gpt-4.1-mini': 1048576,
'gpt-5': 409600, 'gpt-5.2': 409600,
'gpt-5.4': 272000, 'gpt-5.4-pro': 272000,
'gpt-5.4-mini': 400000, 'gpt-5.4-nano': 128000,
'o1': 200000, 'o3': 200000, 'o3-mini': 200000, 'o4-mini': 200000,
'claude-sonnet-4-20250514': 200000, 'claude-opus-4-20250514': 200000,
'claude-haiku-3-5': 200000,
'gemini-2.5-pro': 1048576, 'gemini-2.5-flash': 1048576,
'qwen3-235b': 131072, 'qwen-max': 131072,
'mistral-large': 128000, 'llama-4-maverick': 1048576
};
var listEl = document.getElementById('pm-model-list');
listEl.innerHTML = p.models.map(function (m) {
var ctxVal = m.context_window !== undefined ? m.context_window : (KNOWN_CTX[m.id] || 0);
var opts = CTX_OPTIONS.map(function (o) {
return '<option value="' + o.value + '"' + (o.value === ctxVal ? ' selected' : '') + '>' + o.label + '</option>';
}).join('');
return '<label class="checkbox-item" style="align-items:center;">' +
'<input type="checkbox" value="' + escAttr(m.id) + '" data-name="' + escAttr(m.display_name || m.id) + '" checked>' +
'<span style="flex:1;">' + escHtml(m.display_name || m.id) + '</span>' +
'<select class="model-ctx-input" data-model="' + escAttr(m.id) + '" style="width:72px;font-size:11px;padding:2px 4px;margin:0;flex:none;">' + opts + '</select>' +
'</label>';
}).join('');
listEl.style.display = 'block';
document.getElementById('pm-model-hint').style.display = 'block';
}
} else {
document.getElementById('pm-name').value = '';
document.getElementById('pm-base').value = '';
document.getElementById('pm-key').value = '';