-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1170 lines (1080 loc) · 48.1 KB
/
Copy pathindex.html
File metadata and controls
1170 lines (1080 loc) · 48.1 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Key Manager</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
:root {
--surface: oklch(0.105 0.01 260);
--surface-raised: oklch(0.145 0.012 260);
--surface-sunken: oklch(0.075 0.008 260);
--border: oklch(0.22 0.018 260);
--text-primary: oklch(0.93 0.006 260);
--text-secondary: oklch(0.6 0.008 260);
--text-tertiary: oklch(0.4 0.006 260);
--accent: oklch(0.68 0.16 240);
--accent-hover: oklch(0.74 0.15 240);
--accent-glow: oklch(0.68 0.16 240 / 0.15);
--success: oklch(0.67 0.17 150);
--success-glow: oklch(0.67 0.17 150 / 0.12);
--danger: oklch(0.56 0.2 25);
--danger-glow: oklch(0.56 0.2 25 / 0.12);
--warning: oklch(0.76 0.14 85);
--text-on-accent: oklch(0.98 0.002 250);
}
body {
font-family: -apple-system, "Microsoft YaHei", sans-serif;
background: radial-gradient(ellipse at 50% 20%, oklch(0.13 0.015 260), var(--surface));
color: var(--text-primary);
min-height: 100vh;
padding: 24px;
}
.container { max-width: 780px; margin: 0 auto; }
h1 {
font-size: 20px; font-weight: 600; margin-bottom: 24px;
color: var(--text-primary);
letter-spacing: -0.3px;
}
.section {
background: var(--surface-raised);
border: 1px solid var(--border);
border-radius: 10px;
padding: 20px;
margin-bottom: 16px;
box-shadow: 0 2px 4px oklch(0 0 0 / 0.2);
}
.section-title {
font-size: 13px; font-weight: 600;
color: var(--accent);
text-transform: uppercase;
letter-spacing: 0.8px;
margin-bottom: 14px;
}
textarea {
width: 100%; height: 100px;
background: var(--surface-sunken);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text-primary);
font-family: "Cascadia Code", "Fira Code", monospace;
font-size: 13px;
padding: 12px; resize: vertical; outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
}
textarea:focus {
border-color: var(--accent);
box-shadow: 0 0 0 1px var(--accent), 0 0 16px var(--accent-glow);
}
textarea::placeholder { color: var(--text-tertiary); }
input[type="text"] {
width: 100%;
background: var(--surface-sunken);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text-primary);
font-size: 13px;
padding: 10px 12px; outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
}
input[type="text"]:focus {
border-color: var(--accent);
box-shadow: 0 0 0 1px var(--accent), 0 0 12px var(--accent-glow);
}
input[type="text"]::placeholder { color: var(--text-tertiary); }
.hint { font-size: 12px; color: var(--text-tertiary); margin-top: 8px; }
.form-label { font-size: 12px; color: var(--text-secondary); margin-bottom: 6px; display: block; }
.btn-row { display: flex; gap: 10px; margin-top: 14px; flex-wrap: wrap; }
button {
padding: 9px 18px; border-radius: 7px; border: none; font-size: 13px; font-weight: 500;
cursor: pointer; transition: background 0.15s, box-shadow 0.2s;
}
.btn-primary {
background: var(--accent); color: var(--text-on-accent);
box-shadow: 0 0 10px var(--accent-glow);
}
.btn-primary:hover {
background: var(--accent-hover);
box-shadow: 0 0 18px var(--accent-glow);
}
.btn-secondary {
background: transparent; color: var(--text-secondary);
border: 1px solid var(--border);
}
.btn-secondary:hover {
border-color: var(--text-tertiary); color: var(--text-primary);
background: oklch(1 0 0 / 0.03);
}
.btn-danger {
background: var(--danger); color: var(--text-on-accent);
box-shadow: 0 0 8px var(--danger-glow);
}
.btn-danger:hover {
background: color-mix(in oklch, var(--danger), oklch(0 0 0) 10%);
box-shadow: 0 0 16px var(--danger-glow);
}
.btn-copy {
background: var(--success); color: var(--text-on-accent);
box-shadow: 0 0 8px var(--success-glow);
}
.btn-copy:hover {
background: color-mix(in oklch, var(--success), oklch(0 0 0) 10%);
box-shadow: 0 0 16px var(--success-glow);
}
/* tabs */
.tabs { display: flex; gap: 4px; margin-bottom: 14px; flex-wrap: wrap; }
.tab {
padding: 8px 16px; border-radius: 7px;
border: 1px solid var(--border); background: var(--surface-sunken);
color: var(--text-tertiary); font-size: 13px; cursor: pointer;
transition: background 0.15s, color 0.15s, border-color 0.15s, box-shadow 0.2s;
display: flex; align-items: center; gap: 8px;
min-width: 56px; justify-content: center;
}
.tab:hover {
background: var(--surface-raised); color: var(--text-secondary);
border-color: oklch(0.3 0.02 260);
}
.tab.active {
background: var(--accent); color: var(--text-on-accent); border-color: var(--accent);
box-shadow: 0 0 12px var(--accent-glow);
}
.tab .tab-del {
background: none; border: none; color: inherit; opacity: 0.4; cursor: pointer;
font-size: 15px; padding: 0 2px; line-height: 1;
}
.tab .tab-del:hover { opacity: 1; color: var(--danger); }
.tab-add {
padding: 8px 14px; border-radius: 7px;
border: 1px dashed var(--border); background: transparent;
color: var(--text-tertiary); font-size: 13px; cursor: pointer;
transition: border-color 0.15s, color 0.15s;
}
.tab-add:hover { border-color: var(--text-tertiary); color: var(--text-secondary); }
.protocol-bar {
display: flex; align-items: center; gap: 10px; margin-bottom: 14px;
background: var(--surface-sunken);
border: 1px solid var(--border);
border-radius: 8px; padding: 10px 14px;
}
.protocol-bar label { font-size: 12px; color: var(--text-secondary); white-space: nowrap; }
.protocol-bar input {
flex: 1; background: transparent; border: none;
color: var(--text-primary); font-size: 13px;
font-family: "Cascadia Code", "Fira Code", monospace; outline: none;
}
.stats { display: flex; gap: 20px; margin-bottom: 14px; flex-wrap: wrap; }
.stat { font-size: 13px; color: var(--text-secondary); }
.stat span { color: var(--text-primary); font-weight: 600; }
.key-list { display: flex; flex-direction: column; gap: 6px; max-height: 400px; overflow-y: auto; }
.key-item {
display: flex; align-items: center; gap: 10px;
background: var(--surface-sunken);
border: 1px solid var(--border);
border-radius: 7px; padding: 10px 14px;
font-family: "Cascadia Code", "Fira Code", monospace;
font-size: 12px;
transition: border-color 0.15s;
}
.key-item:hover {
border-color: oklch(0.3 0.025 260);
}
.key-text {
flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
color: var(--text-primary);
}
.key-del {
background: none; border: none; color: var(--text-tertiary); cursor: pointer;
font-size: 16px; min-width: 44px; min-height: 44px;
display: inline-flex; align-items: center; justify-content: center; border-radius: 4px;
}
.key-del:hover { color: var(--danger); background: var(--danger-glow); }
.toast {
position: fixed; bottom: 30px; left: 50%; transform: translateX(-50%);
background: var(--surface-raised); color: var(--text-primary);
padding: 10px 20px; border-radius: 8px;
font-size: 13px; opacity: 0; transition: opacity 0.3s; pointer-events: none; z-index: 999;
border: 1px solid var(--border);
box-shadow: 0 4px 16px oklch(0 0 0 / 0.3);
}
.toast.show { opacity: 1; }
.empty { text-align: center; padding: 30px; color: var(--text-tertiary); font-size: 13px; }
.modal-overlay {
display: none; position: fixed; inset: 0;
background: oklch(0 0 0 / 0.65);
z-index: 100;
align-items: center; justify-content: center;
}
.modal-overlay.show { display: flex; }
.modal {
background: var(--surface-raised);
border: 1px solid var(--border);
border-radius: 12px; padding: 24px;
width: 400px; max-width: 90vw;
box-shadow: 0 8px 32px oklch(0 0 0 / 0.4);
}
.modal h3 { font-size: 15px; margin-bottom: 16px; color: var(--text-primary); }
.modal .field { margin-bottom: 12px; }
.modal .field:last-of-type { margin-bottom: 16px; }
.status-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
.status-dot.success {
background: var(--success);
box-shadow: 0 0 6px var(--success-glow);
}
.status-dot.fail {
background: var(--danger);
box-shadow: 0 0 6px var(--danger-glow);
}
.status-dot.testing {
background: var(--warning);
box-shadow: 0 0 6px oklch(0.76 0.14 85 / 0.2);
animation: pulse 1s infinite;
}
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; } }
@keyframes spin { to { transform: rotate(360deg); } }
.btn-loading {
pointer-events: none;
opacity: 0.7;
display: inline-flex;
align-items: center;
gap: 6px;
}
.btn-loading::before {
content: '';
width: 14px; height: 14px;
border: 2px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
.key-test-btn {
background: transparent; border: 1px solid var(--border); color: var(--text-tertiary);
cursor: pointer; font-size: 11px; padding: 3px 10px; border-radius: 4px;
white-space: nowrap; min-height: 32px;
transition: border-color 0.15s, color 0.15s;
}
.key-test-btn:hover { border-color: var(--accent); color: var(--accent); }
.key-test-btn:disabled { opacity: 0.4; cursor: not-allowed; }
.key-latency {
font-family: "Cascadia Code", "Fira Code", monospace;
font-size: 11px; color: var(--text-tertiary);
min-width: 55px; text-align: right;
}
.key-error {
font-size: 11px; color: var(--danger);
max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.test-all-btn {
background: var(--accent); color: var(--text-on-accent);
box-shadow: 0 0 10px var(--accent-glow);
}
.test-all-btn:hover {
background: var(--accent-hover);
box-shadow: 0 0 18px var(--accent-glow);
}
.tab.virtual { background: var(--surface); color: var(--text-secondary); }
.tab.virtual.active {
background: var(--accent); color: var(--text-on-accent); border-color: var(--accent);
box-shadow: 0 0 12px var(--accent-glow);
}
.key-group-tag {
font-size: 11px; color: var(--text-tertiary);
padding: 2px 6px; border: 1px solid var(--border);
border-radius: 4px; margin-right: 6px; flex-shrink: 0;
}
/* stats page */
.stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 18px; }
.stat-card {
background: var(--surface-sunken); border: 1px solid var(--border);
border-radius: 10px; padding: 16px;
}
.stat-card .label {
font-size: 12px; color: var(--text-secondary);
margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.5px;
}
.stat-card .value {
font-size: 28px; font-weight: 600; color: var(--text-primary);
font-family: "Cascadia Code", "Fira Code", monospace;
}
.stat-card.added .value { color: var(--success); }
.stat-card.removed .value { color: var(--danger); }
.stat-card.current .value { color: var(--accent); }
.stat-card.ok .value { color: var(--success); }
.chart-block {
background: var(--surface-sunken); border: 1px solid var(--border);
border-radius: 10px; padding: 18px; margin-bottom: 12px;
}
.chart-title {
font-size: 13px; color: var(--text-secondary);
margin-bottom: 14px; font-weight: 500;
}
.bar-row { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; font-size: 12px; }
.bar-row .name { width: 130px; color: var(--text-primary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bar-row .track { flex: 1; height: 18px; background: var(--surface-raised); border-radius: 4px; overflow: hidden; }
.bar-row .fill { height: 100%; background: var(--accent); border-radius: 4px; }
.bar-row .num { width: 50px; text-align: right; color: var(--text-tertiary); font-family: "Cascadia Code", "Fira Code", monospace; }
.donut-wrap { display: flex; align-items: center; gap: 24px; }
.donut { width: 160px; height: 160px; flex-shrink: 0; }
.donut-legend { flex: 1; display: flex; flex-direction: column; gap: 8px; font-size: 13px; }
.donut-legend .item { display: flex; align-items: center; gap: 8px; color: var(--text-primary); }
.donut-legend .swatch { width: 12px; height: 12px; border-radius: 3px; flex-shrink: 0; background: currentColor; }
.donut-legend .num { margin-left: auto; color: var(--text-tertiary); font-family: "Cascadia Code", "Fira Code", monospace; }
@media (max-width: 640px) { .stats-grid { grid-template-columns: repeat(2, 1fr); } }
@media (pointer: coarse) {
.key-test-btn { min-height: 44px; padding: 10px 16px; font-size: 13px; }
.key-del { min-width: 48px; min-height: 48px; }
}
/* donut chart colors */
.donut-bg { stroke: oklch(0.22 0.018 260); }
.donut-center { fill: var(--text-primary); }
.donut-label { fill: var(--text-tertiary); }
.donut-segment-success { color: var(--success); }
.donut-segment-fail { color: var(--danger); }
.donut-segment-untested { color: var(--text-tertiary); }
.donut-empty-msg { color: var(--text-tertiary); }
:focus-visible {
outline: 2px solid var(--accent); outline-offset: 2px;
}
textarea:focus-visible, input:focus-visible, .protocol-bar input:focus-visible {
outline: 2px solid var(--accent); outline-offset: 1px;
}
@media (prefers-reduced-motion: reduce) {
.status-dot.testing { animation: none; opacity: 0.5; }
.toast { transition: none; }
}
/* scrollbar styling */
.key-list::-webkit-scrollbar { width: 6px; }
.key-list::-webkit-scrollbar-track { background: transparent; }
.key-list::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 3px;
}
.key-list::-webkit-scrollbar-thumb:hover { background: oklch(0.3 0.02 260); }
</style>
</head>
<body>
<main>
<div class="container">
<h1>API Key Manager</h1>
<!-- 分组 Tabs -->
<div class="section" role="region" aria-label="分组">
<div class="section-title">分组</div>
<div class="tabs" id="tabs"></div>
<div class="protocol-bar" id="protocolBar">
<label for="protocolInput">接口协议:</label>
<input type="text" id="protocolInput" placeholder="https://api.example.com/v1/chat/completions">
<label for="modelInput">模型:</label>
<input type="text" id="modelInput" placeholder="默认 gpt-3.5-turbo" style="max-width:180px">
</div>
</div>
<!-- 添加密钥 -->
<div class="section" id="addSection" role="region" aria-label="添加密钥">
<div class="section-title">添加密钥到「<span id="currentGroupName">-</span>」</div>
<textarea id="input" aria-label="API 密钥输入" placeholder="粘贴 API 密钥,每行一个 支持原始密钥和 Base64 编码的密钥,自动识别解密"></textarea>
<div class="hint">支持批量输入,每行一个密钥。Base64 编码的会自动解码后保存。</div>
<div class="btn-row">
<button class="btn-primary" id="btnAddKeys" onclick="handleAddKeys()">添加并去重</button>
<button class="btn-secondary" onclick="document.getElementById('input').value=''">清空输入</button>
</div>
</div>
<!-- 密钥列表 -->
<div class="section" id="listSection" role="region" aria-label="密钥列表">
<div class="section-title">「<span id="listGroupName">-</span>」的密钥</div>
<div class="stats">
<div class="stat">当前分组 <span id="count">0</span> 条</div>
<div class="stat" id="addedStat">本次新增 <span id="added">0</span> 条</div>
<div class="stat" id="skippedStat">去重跳过 <span id="skipped">0</span> 条</div>
</div>
<div class="key-list" id="keyList">
<div class="empty">暂无保存的密钥</div>
</div>
<div class="btn-row" id="listBtnRow">
<button class="btn-copy" onclick="handleCopyKeys()">复制当前分组密钥</button>
<button class="btn-secondary" onclick="handleExportKeys()">导出当前分组</button>
<button class="test-all-btn" id="btnTestAll" onclick="handleTestAllKeys()">一键测试全部</button>
<button class="btn-danger" id="btnRemoveFailed" onclick="handleRemoveFailed()" style="display:none">一键剔除失败</button>
</div>
</div>
<!-- 统计视图 -->
<div id="statsView" style="display:none">
<div class="stats-grid">
<div class="stat-card added"><div class="label">累计添加</div><div class="value" id="sTotalAdded">0</div></div>
<div class="stat-card removed"><div class="label">累计剔除</div><div class="value" id="sTotalRemoved">0</div></div>
<div class="stat-card current"><div class="label">当前总数</div><div class="value" id="sCurrentTotal">0</div></div>
<div class="stat-card ok"><div class="label">最近可用</div><div class="value" id="sOkCount">0</div></div>
</div>
<div class="chart-block">
<div class="chart-title">每个分组的密钥数量</div>
<div id="sBarChart"></div>
</div>
<div class="chart-block">
<div class="chart-title">最近测试状态分布</div>
<div class="donut-wrap">
<svg class="donut" id="sDonut" viewBox="0 0 42 42"></svg>
<div class="donut-legend" id="sDonutLegend"></div>
</div>
</div>
</div>
<!-- 智能分发视图 -->
<div id="distView" style="display:none">
<div class="section">
<div class="section-title">智能分发</div>
<div class="hint" style="margin-bottom:12px;margin-top:0">粘贴一批密钥,系统会自动用所有已配置接口的分组逐个测试,第一个测试通过的分组即为归入目标。全部失败则剔除。</div>
<textarea id="distInput" aria-label="密钥输入" placeholder="粘贴 API 密钥,每行一个 支持原始密钥和 Base64 编码的密钥"></textarea>
<div class="btn-row">
<button class="btn-primary" id="btnDistribute" onclick="handleDistribute()">开始分发</button>
<button class="btn-secondary" onclick="document.getElementById('distInput').value=''">清空输入</button>
</div>
</div>
<div class="section" id="distResultSection" style="display:none">
<div class="section-title">分发结果</div>
<div class="stats" id="distSummary"></div>
<div class="key-list" id="distResultList"></div>
</div>
</div>
</div>
</main>
<!-- 新建分组弹窗 -->
<div class="modal-overlay" id="modal" role="dialog" aria-modal="true" aria-labelledby="modal-title">
<div class="modal">
<h3 id="modal-title">新建分组</h3>
<div class="field">
<label class="form-label" for="newGroupName">分组名称</label>
<input type="text" id="newGroupName" placeholder="例如 OpenAI、Claude、自研模型">
</div>
<div class="field">
<label class="form-label" for="newGroupProtocol">接口协议(可选)</label>
<input type="text" id="newGroupProtocol" placeholder="例如 https://api.openai.com/v1/chat/completions">
</div>
<div class="field">
<label class="form-label" for="newGroupModel">模型名称(可选)</label>
<input type="text" id="newGroupModel" placeholder="默认 gpt-3.5-turbo">
</div>
<div class="btn-row">
<button class="btn-primary" onclick="handleAddGroup()">创建</button>
<button class="btn-secondary" onclick="closeModal()">取消</button>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<script>
// ─── State ───────────────────────────────────────────────────
const ALL_VIEW = '__all__';
const STATS_VIEW = '__stats__';
const DIST_VIEW = '__dist__';
const state = { groups: [], activeGroupId: null, testResults: {}, allKeys: [], stats: null };
let rendering = false;
function isVirtual(id) { return id === ALL_VIEW || id === STATS_VIEW || id === DIST_VIEW; }
// ─── API ─────────────────────────────────────────────────────
async function apiFetch(path, options = {}) {
const res = await fetch(path, {
headers: { 'Content-Type': 'application/json', ...options.headers },
...options
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
return data;
}
async function refreshGroups() {
state.groups = await apiFetch('/api/groups');
if (state.groups.length === 0) {
await apiFetch('/api/groups', {
method: 'POST', body: JSON.stringify({ name: '默认', protocol: '', model: '' })
});
state.groups = await apiFetch('/api/groups');
}
const saved = localStorage.getItem('activeGroupId');
if (saved === ALL_VIEW || saved === STATS_VIEW || saved === DIST_VIEW) {
state.activeGroupId = saved;
} else {
const savedId = parseInt(saved);
state.activeGroupId = (savedId && state.groups.some(g => g.id === savedId))
? savedId : STATS_VIEW;
}
}
async function refreshAllKeys() {
try { state.allKeys = await apiFetch('/api/all-keys'); } catch { state.allKeys = []; }
}
async function refreshStats() {
try { state.stats = await apiFetch('/api/stats'); } catch { state.stats = null; }
}
async function refreshTestResults() {
try { state.testResults = await apiFetch('/api/test-results'); } catch {}
}
// ─── Helpers ─────────────────────────────────────────────────
function getActiveGroup() {
if (isVirtual(state.activeGroupId)) return null;
return state.groups.find(g => g.id === state.activeGroupId) || state.groups[0] || null;
}
function showToast(msg) {
const t = document.getElementById('toast');
t.textContent = msg; t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 2000);
}
function escHtml(s) {
const d = document.createElement('div'); d.textContent = s; return d.innerHTML;
}
function openModal() {
const overlay = document.getElementById('modal');
overlay.classList.add('show');
document.getElementById('newGroupName').value = '';
document.getElementById('newGroupProtocol').value = '';
document.getElementById('newGroupModel').value = '';
const input = document.getElementById('newGroupName');
setTimeout(() => input.focus(), 50);
overlay.onkeydown = (e) => {
if (e.key !== 'Tab') return;
const focusable = Array.from(overlay.querySelectorAll('input, button, [tabindex]:not([tabindex="-1"])'));
if (focusable.length === 0) return;
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault(); last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault(); first.focus();
}
};
}
function closeModal() {
const overlay = document.getElementById('modal');
overlay.classList.remove('show');
}
// ─── Render ──────────────────────────────────────────────────
function render() {
renderTabs();
const view = state.activeGroupId;
const protocolBar = document.getElementById('protocolBar');
const addSection = document.getElementById('addSection');
const listSection = document.getElementById('listSection');
const statsView = document.getElementById('statsView');
const distView = document.getElementById('distView');
distView.style.display = 'none';
if (view === STATS_VIEW) {
protocolBar.style.display = 'none';
addSection.style.display = 'none';
listSection.style.display = 'none';
statsView.style.display = 'block';
renderStats();
return;
}
if (view === DIST_VIEW) {
protocolBar.style.display = 'none';
addSection.style.display = 'none';
listSection.style.display = 'none';
statsView.style.display = 'none';
distView.style.display = '';
return;
}
statsView.style.display = 'none';
listSection.style.display = '';
if (view === ALL_VIEW) {
protocolBar.style.display = 'none';
addSection.style.display = 'none';
renderAllKeysList();
} else {
protocolBar.style.display = '';
addSection.style.display = '';
renderProtocolBar();
renderKeyList();
}
}
function renderTabs() {
const el = document.getElementById('tabs');
el.setAttribute('role', 'tablist');
const isActive = (id) => id === state.activeGroupId;
const groupsHtml = state.groups.map(g =>
`<div role="tab" class="tab ${isActive(g.id) ? 'active' : ''}" data-group-id="${g.id}"
aria-selected="${isActive(g.id)}" tabindex="${isActive(g.id) ? '0' : '-1'}">
${escHtml(g.name)} <span style="opacity:0.5;font-size:11px">(${g.keys.length})</span>
${state.groups.length > 1 ? `<span class="tab-del" data-action="delete-group" data-group-id="${g.id}" aria-label="删除分组" title="删除分组">×</span>` : ''}
</div>`
).join('');
const totalKeys = state.groups.reduce((s, g) => s + g.keys.length, 0);
const allTab = `<div role="tab" class="tab virtual ${isActive(ALL_VIEW) ? 'active' : ''}" data-group-id="${ALL_VIEW}"
aria-selected="${isActive(ALL_VIEW)}" tabindex="${isActive(ALL_VIEW) ? '0' : '-1'}">
汇总 <span style="opacity:0.5;font-size:11px">(${totalKeys})</span>
</div>`;
const statsTab = `<div role="tab" class="tab virtual ${isActive(STATS_VIEW) ? 'active' : ''}" data-group-id="${STATS_VIEW}"
aria-selected="${isActive(STATS_VIEW)}" tabindex="${isActive(STATS_VIEW) ? '0' : '-1'}">
统计
</div>`;
const distTab = `<div role="tab" class="tab virtual ${isActive(DIST_VIEW) ? 'active' : ''}" data-group-id="${DIST_VIEW}"
aria-selected="${isActive(DIST_VIEW)}" tabindex="${isActive(DIST_VIEW) ? '0' : '-1'}">
智能分发
</div>`;
el.innerHTML = statsTab + distTab + allTab + groupsHtml + '<button class="tab-add" id="btnAddGroup">+ 新建分组</button>';
el.onclick = (e) => {
if (e.target.closest('.tab-del')) return;
const tab = e.target.closest('.tab');
if (!tab || !tab.dataset.groupId) return;
const raw = tab.dataset.groupId;
const gid = isVirtual(raw) ? raw : parseInt(raw);
if (gid) { state.activeGroupId = gid; localStorage.setItem('activeGroupId', gid); onViewChanged(); }
};
el.onkeydown = (e) => {
const tabs = Array.from(el.querySelectorAll('[role="tab"]'));
const cur = tabs.indexOf(document.activeElement);
if (cur === -1) return;
let next = -1;
switch (e.key) {
case 'ArrowRight': next = (cur + 1) % tabs.length; break;
case 'ArrowLeft': next = (cur - 1 + tabs.length) % tabs.length; break;
case 'Home': next = 0; break;
case 'End': next = tabs.length - 1; break;
default: return;
}
e.preventDefault();
const target = tabs[next];
if (!target) return;
const raw = target.dataset.groupId;
const gid = isVirtual(raw) ? raw : parseInt(raw);
if (gid && gid !== state.activeGroupId) {
state.activeGroupId = gid;
localStorage.setItem('activeGroupId', gid);
onViewChanged().then(() => {
const el2 = document.querySelector(`[data-group-id="${CSS.escape(String(raw))}"]`);
el2?.focus();
});
} else {
target.focus();
}
};
el.querySelectorAll('.tab-del').forEach(btn => {
btn.onclick = (e) => { e.stopPropagation(); handleDeleteGroup(parseInt(btn.dataset.groupId)); };
});
const addBtn = document.getElementById('btnAddGroup');
if (addBtn) addBtn.onclick = openModal;
}
async function onViewChanged() {
if (state.activeGroupId === ALL_VIEW) {
await refreshAllKeys();
await refreshTestResults();
} else if (state.activeGroupId === STATS_VIEW) {
await refreshStats();
}
render();
}
function renderProtocolBar() {
const group = getActiveGroup();
rendering = true;
document.getElementById('protocolInput').value = group?.protocol || '';
document.getElementById('modelInput').value = group?.model || '';
rendering = false;
document.getElementById('currentGroupName').textContent = group?.name || '-';
document.getElementById('listGroupName').textContent = group?.name || '-';
}
function renderKeyList() {
document.getElementById('listGroupName').textContent = getActiveGroup()?.name || '-';
document.getElementById('addedStat').style.display = '';
document.getElementById('skippedStat').style.display = '';
document.getElementById('btnRemoveFailed').style.display = 'none';
const group = getActiveGroup();
if (!group) {
document.getElementById('keyList').innerHTML = '<div class="empty">没有分组,请先创建一个</div>';
document.getElementById('count').textContent = '0';
return;
}
document.getElementById('count').textContent = group.keys.length;
if (group.keys.length === 0) {
document.getElementById('keyList').innerHTML = '<div class="empty">暂无保存的密钥</div>';
return;
}
const results = state.testResults;
document.getElementById('keyList').innerHTML = group.keys.map(k => {
const r = results[k.api_key];
const dotHtml = r ? `<span class="status-dot ${r.ok ? 'success' : 'fail'}" title="${r.ok ? '可用' : '不可用'}"></span>` : '';
const latencyHtml = r && r.latency != null ? `<span class="key-latency">${r.latency}ms</span>` : '';
const errHtml = r && !r.ok && r.error ? `<span class="key-error" title="${escHtml(r.error)}">${escHtml(r.error)}</span>` : '';
return `<div class="key-item" data-key-id="${k.id}" data-api-key="${escHtml(k.api_key)}">
${dotHtml}
<span class="key-text" title="${escHtml(k.api_key)}">${escHtml(k.api_key)}</span>
${latencyHtml}
${errHtml}
<button class="key-test-btn" data-action="test-key">测试</button>
<button class="key-del" data-action="delete-key" aria-label="删除密钥" title="删除">×</button>
</div>`;
}).join('');
}
function renderAllKeysList() {
document.getElementById('listGroupName').textContent = '汇总';
document.getElementById('addedStat').style.display = 'none';
document.getElementById('skippedStat').style.display = 'none';
document.getElementById('btnRemoveFailed').style.display = '';
const items = state.allKeys || [];
document.getElementById('count').textContent = items.length;
if (items.length === 0) {
document.getElementById('keyList').innerHTML = '<div class="empty">没有任何密钥</div>';
return;
}
const results = state.testResults;
document.getElementById('keyList').innerHTML = items.map(k => {
const r = results[k.api_key];
const dotHtml = r ? `<span class="status-dot ${r.ok ? 'success' : 'fail'}" title="${r.ok ? '可用' : '不可用'}"></span>` : '';
const latencyHtml = r && r.latency != null ? `<span class="key-latency">${r.latency}ms</span>` : '';
const errHtml = r && !r.ok && r.error ? `<span class="key-error" title="${escHtml(r.error)}">${escHtml(r.error)}</span>` : '';
return `<div class="key-item" data-key-id="${k.id}" data-api-key="${escHtml(k.api_key)}">
${dotHtml}
<span class="key-group-tag">${escHtml(k.group_name)}</span>
<span class="key-text" title="${escHtml(k.api_key)}">${escHtml(k.api_key)}</span>
${latencyHtml}
${errHtml}
</div>`;
}).join('');
}
function renderStats() {
const s = state.stats;
if (!s) {
document.getElementById('statsView').innerHTML = '<div class="chart-block"><div class="empty">加载中…</div></div>';
return;
}
document.getElementById('sTotalAdded').textContent = s.total_added;
document.getElementById('sTotalRemoved').textContent = s.total_removed;
document.getElementById('sCurrentTotal').textContent = s.current_total;
document.getElementById('sOkCount').textContent = s.ok_count;
const max = Math.max(1, ...s.per_group.map(g => g.count));
const barEl = document.getElementById('sBarChart');
barEl.innerHTML = s.per_group.length === 0
? '<div class="empty">暂无分组</div>'
: s.per_group.map(g => {
const pct = (g.count / max * 100).toFixed(1);
return `<div class="bar-row">
<div class="name" title="${escHtml(g.name)}">${escHtml(g.name)}</div>
<div class="track"><div class="fill" style="width:${pct}%"></div></div>
<div class="num">${g.count}</div>
</div>`;
}).join('');
renderDonut(s.ok_count, s.fail_count, s.untested_count);
}
function renderDonut(ok, fail, untested) {
const total = ok + fail + untested;
const svg = document.getElementById('sDonut');
const legend = document.getElementById('sDonutLegend');
if (total === 0) {
svg.innerHTML = '<circle cx="21" cy="21" r="15.9" fill="none" class="donut-bg" stroke-width="4"/>';
legend.innerHTML = '<div class="item donut-empty-msg">还没有测试数据</div>';
return;
}
const segs = [
{ label: '可用', value: ok, cls: 'donut-segment-success' },
{ label: '不可用', value: fail, cls: 'donut-segment-fail' },
{ label: '未测试', value: untested, cls: 'donut-segment-untested' },
];
const C = 2 * Math.PI * 15.9155;
let offset = 25;
let parts = '<circle cx="21" cy="21" r="15.9155" fill="none" class="donut-bg" stroke-width="4"/>';
segs.forEach(seg => {
if (seg.value === 0) return;
const len = (seg.value / total) * C;
parts += `<circle cx="21" cy="21" r="15.9155" fill="none"
class="${seg.cls}" stroke="currentColor" stroke-width="4"
stroke-dasharray="${len.toFixed(3)} ${(C - len).toFixed(3)}"
stroke-dashoffset="${(-offset + 25).toFixed(3)}"
transform="rotate(-90 21 21)"/>`;
offset += len;
});
parts += `<text x="21" y="21" text-anchor="middle" dominant-baseline="central" class="donut-center" font-size="6" font-weight="600">${total}</text>`;
parts += `<text x="21" y="27" text-anchor="middle" dominant-baseline="central" class="donut-label" font-size="3">已测试</text>`;
svg.innerHTML = parts;
legend.innerHTML = segs.map(seg => {
const pct = total ? ((seg.value / total) * 100).toFixed(1) : '0.0';
return `<div class="item">
<span class="swatch ${seg.cls}"></span>
${seg.label}
<span class="num">${seg.value} · ${pct}%</span>
</div>`;
}).join('');
}
// ─── Group Actions ───────────────────────────────────────────
async function handleDeleteGroup(id) {
if (state.groups.length <= 1) { showToast('至少保留一个分组'); return; }
const group = state.groups.find(g => g.id === id);
if (!group) return;
if (!confirm(`确定删除分组「${group.name}」及其 ${group.keys.length} 条密钥?`)) return;
try {
await apiFetch(`/api/groups/${id}`, { method: 'DELETE' });
await refreshGroups();
render();
showToast(`已删除「${group.name}」`);
} catch (e) { showToast('删除失败: ' + e.message); }
}
async function handleAddGroup() {
const name = document.getElementById('newGroupName').value.trim();
if (!name) { showToast('请输入分组名称'); return; }
const protocol = document.getElementById('newGroupProtocol').value.trim();
const model = document.getElementById('newGroupModel').value.trim();
try {
await apiFetch('/api/groups', {
method: 'POST', body: JSON.stringify({ name, protocol, model })
});
await refreshGroups();
closeModal();
render();
showToast(`已创建分组「${name}」`);
} catch (e) { showToast('创建失败: ' + e.message); }
}
let saveTimer = null;
function debouncedSave() {
if (rendering) return;
clearTimeout(saveTimer);
saveTimer = setTimeout(async () => {
const group = getActiveGroup();
if (!group) return;
const protocol = document.getElementById('protocolInput').value;
const model = document.getElementById('modelInput').value;
try {
await apiFetch(`/api/groups/${group.id}`, {
method: 'PUT',
body: JSON.stringify({ name: group.name, protocol, model })
});
group.protocol = protocol;
group.model = model;
} catch (e) { showToast('保存失败: ' + e.message); }
}, 500);
}
// ─── Key Actions ─────────────────────────────────────────────
async function handleAddKeys() {
const btn = document.getElementById('btnAddKeys');
const raw = document.getElementById('input').value;
if (!raw.trim()) { showToast('请输入密钥'); return; }
const group = getActiveGroup();
if (!group) { showToast('请先选择分组'); return; }
const keyLines = raw.split('\n').map(l => l.trim()).filter(Boolean);
if (keyLines.length === 0) { showToast('没有有效的密钥'); return; }
const prevText = btn.textContent;
btn.classList.add('btn-loading');
btn.textContent = '测试中…';
try {
const result = await apiFetch(`/api/groups/${group.id}/keys`, {
method: 'POST', body: JSON.stringify({ keys: keyLines })
});
await refreshGroups();
render();
document.getElementById('added').textContent = result.added;
document.getElementById('skipped').textContent = result.skipped;
document.getElementById('input').value = '';
if (result.added === 0 && result.skipped === 0 && result.failed === 0) {
showToast('没有有效的密钥');
} else if (result.failed > 0 && result.added === 0 && result.skipped === 0) {
showToast(`全部测试失败,未添加任何密钥(${result.failed} 条失败)`);
} else {
let msg = `新增 ${result.added} 条`;
const parts = [];
if (result.skipped > 0) parts.push(`跳过 ${result.skipped} 条重复`);
if (result.failed > 0) parts.push(`${result.failed} 条测试失败未添加`);
if (parts.length > 0) msg += ',' + parts.join(',');
showToast(msg);
}
} catch (e) { showToast('添加失败: ' + e.message); }
finally {
btn.classList.remove('btn-loading');
btn.textContent = prevText;
}
}
async function handleDeleteKey(keyId) {
try {
await apiFetch(`/api/keys/${keyId}`, { method: 'DELETE' });
await refreshGroups();
render();
showToast('已删除');
} catch (e) { showToast('删除失败: ' + e.message); }
}
function handleCopyKeys() {
const group = getActiveGroup();
if (!group || group.keys.length === 0) { showToast('当前分组没有密钥'); return; }
let text = group.keys.map(k => k.api_key).join('\n');
if (group.protocol) text = `# ${group.protocol}\n${text}`;
navigator.clipboard.writeText(text).then(() => {
showToast(`已复制「${group.name}」的 ${group.keys.length} 条密钥`);
}).catch(() => {
const ta = document.createElement('textarea');
ta.value = text; document.body.appendChild(ta); ta.select();
document.execCommand('copy'); document.body.removeChild(ta);
showToast(`已复制「${group.name}」的 ${group.keys.length} 条密钥`);
});
}
function handleExportKeys() {
const group = getActiveGroup();
if (!group || group.keys.length === 0) { showToast('当前分组没有密钥'); return; }
let content = '';
if (group.protocol) content += `# ${group.protocol}\n`;
content += group.keys.map(k => k.api_key).join('\n');
const blob = new Blob([content], { type: 'text/plain' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `${group.name}-keys.txt`;
a.click();
URL.revokeObjectURL(a.href);
showToast('已导出');
}
// ─── Test Actions ────────────────────────────────────────────
async function handleTestKey(keyId, apiKey) {
const group = getActiveGroup();
if (!group || !group.protocol) { showToast('请先填写接口协议地址'); return; }
const item = document.querySelector(`.key-item[data-key-id="${keyId}"]`);
const btn = item?.querySelector('.key-test-btn');
const dot = item?.querySelector('.status-dot');
if (dot) dot.remove();
if (btn) { btn.disabled = true; btn.textContent = '测试中…'; }
const td = document.createElement('span');
td.className = 'status-dot testing';
if (item) item.insertBefore(td, item.firstChild);
try {
const result = await apiFetch('/api/test', {