-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3533 lines (3195 loc) · 127 KB
/
Copy pathapp.js
File metadata and controls
3533 lines (3195 loc) · 127 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
/* ══════════════════════════════════════════════════
TokenTotal — 渲染进程
══════════════════════════════════════════════════ */
const models = [
// OpenAI
{ id: "gpt-5.2", name: "GPT-5.2", provider: "OpenAI", input: 1.75, cached: 0.175, output: 14, context: 400000 },
{ id: "gpt-5.2-chat", name: "GPT-5.2 Chat", provider: "OpenAI", input: 1.75, cached: 0.175, output: 14, context: 128000 },
{ id: "gpt-5.1", name: "GPT-5.1", provider: "OpenAI", input: 1.25, cached: 0.125, output: 10, context: 400000 },
{ id: "gpt-5-mini", name: "GPT-5 mini", provider: "OpenAI", input: 0.25, cached: 0.025, output: 2, context: 400000 },
{ id: "gpt-5-nano", name: "GPT-5 nano", provider: "OpenAI", input: 0.05, cached: 0.005, output: 0.4, context: 400000 },
{ id: "gpt-4.1", name: "GPT-4.1", provider: "OpenAI", input: 2, cached: 0.5, output: 8, context: 1047576 },
{ id: "gpt-4.1-mini", name: "GPT-4.1 mini", provider: "OpenAI", input: 0.4, cached: 0.1, output: 1.6, context: 1047576 },
{ id: "gpt-4.1-nano", name: "GPT-4.1 nano", provider: "OpenAI", input: 0.1, cached: 0.025, output: 0.4, context: 1047576 },
{ id: "gpt-4o", name: "GPT-4o", provider: "OpenAI", input: 2.5, cached: 1.25, output: 10, context: 128000 },
{ id: "gpt-4o-mini", name: "GPT-4o mini", provider: "OpenAI", input: 0.15, cached: 0.075, output: 0.6, context: 128000 },
// Anthropic
{ id: "claude-opus-4", name: "Claude Opus 4", provider: "Anthropic", input: 15, cached: 1.875, output: 75, context: 200000 },
{ id: "claude-sonnet-4", name: "Claude Sonnet 4", provider: "Anthropic", input: 3, cached: 0.30, output: 15, context: 200000 },
{ id: "claude-haiku-3.5", name: "Claude Haiku 3.5", provider: "Anthropic", input: 0.80, cached: 0.08, output: 4, context: 200000 },
// Google
{ id: "gemini-2.5-pro", name: "Gemini 2.5 Pro", provider: "Google", input: 1.25, cached: 0.3125, output: 10, context: 1048576 },
{ id: "gemini-2.5-flash", name: "Gemini 2.5 Flash", provider: "Google", input: 0.15, cached: 0.0375, output: 0.60, context: 1048576 },
{ id: "gemini-2.0-flash", name: "Gemini 2.0 Flash", provider: "Google", input: 0.10, cached: 0.025, output: 0.40, context: 1048576 },
// DeepSeek
{ id: "deepseek-v3", name: "DeepSeek V3", provider: "DeepSeek", input: 0.27, cached: 0.07, output: 1.10, context: 65536 },
{ id: "deepseek-r1", name: "DeepSeek R1", provider: "DeepSeek", input: 0.55, cached: 0.14, output: 2.19, context: 65536 },
];
const colors = {
cjk: "#2f8f83",
latin: "#255f85",
number: "#b1842d",
symbol: "#d96b4c",
overhead: "#6f5d99",
};
const providerColors = {
OpenAI: "#10a37f",
Anthropic: "#cc9351",
Google: "#4285f4",
DeepSeek: "#6366f1",
Local: "#2f8f83",
};
const FREE_HISTORY_LIMIT = 100;
const CNY_PER_USD = 7.2;
const DEFAULT_WORKSPACE = {
activeMemberId: "me",
wallet: {
currency: "CNY",
monthlyBudget: 300,
warningPct: 80,
tokenModelId: "gpt-5-mini",
},
members: [
{
id: "me",
name: "我",
role: "Owner",
monthlyBudget: 300,
enabled: true,
allowedModels: "all",
},
],
security: {
detectSecrets: true,
detectPII: true,
detectCustomerData: true,
blockHighRisk: false,
customKeywords: "客户资料\n合同\n身份证\n银行卡\napi key\nsecret",
},
};
const proFeatureLabels = {
connectors: "连接器同步",
localChat: "本地模型聊天",
promptEnglish: "Prompt 转英文",
cloudUsage: "官方用量拉取",
exportData: "数据导出",
unlimitedHistory: "不限历史记录",
};
const modelScenarioHints = {
"gpt-5-mini": "日常问答、轻量代码、批量任务",
"gpt-5-nano": "分类、提取、短文本批处理",
"gpt-4.1-mini": "长上下文代码和文档分析",
"gpt-4.1-nano": "低成本长上下文粗处理",
"gpt-4o-mini": "轻量聊天、多媒体边缘任务",
"claude-haiku-3.5": "快速问答、摘要、低风险任务",
"gemini-2.5-flash": "长上下文、低成本通用分析",
"gemini-2.0-flash": "高频低成本请求",
"deepseek-v3": "代码、中文、通用推理",
"deepseek-r1": "低成本推理型任务",
};
const moonSvg = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>';
const sunSvg = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>';
const estimateModes = {
balanced: { label: "标准估算", factor: 1, low: 0.88, high: 1.16 },
conservative: { label: "保守预算", factor: 1.12, low: 0.96, high: 1.3 },
code: { label: "代码密集", factor: 1.08, low: 0.92, high: 1.24 },
cjk: { label: "中文长文", factor: 0.98, low: 0.9, high: 1.12 },
};
function applyInitialTheme() {
const saved = localStorage.getItem("tokentotal-theme");
const preferred =
saved ||
(window.matchMedia?.("(prefers-color-scheme:dark)").matches
? "dark"
: "light");
document.documentElement.setAttribute("data-theme", preferred);
}
applyInitialTheme();
/* ── Storage abstraction ── */
const storage = {
isElectron: typeof window.electronAPI !== "undefined",
async getHistory() {
if (this.isElectron) return window.electronAPI.getHistory();
try { return JSON.parse(localStorage.getItem("tt-history") || "[]"); } catch { return []; }
},
async addHistory(entry) {
if (this.isElectron) return window.electronAPI.addHistory(entry);
const h = await this.getHistory();
h.push(entry);
localStorage.setItem("tt-history", JSON.stringify(h));
},
async clearHistory() {
if (this.isElectron) return window.electronAPI.clearHistory();
localStorage.setItem("tt-history", "[]");
},
async getBudget() {
if (this.isElectron) return window.electronAPI.getBudget();
try { return JSON.parse(localStorage.getItem("tt-budget") || "{}"); } catch { return {}; }
},
async setBudget(budget) {
if (this.isElectron) return window.electronAPI.setBudget(budget);
localStorage.setItem("tt-budget", JSON.stringify(budget));
},
async getSettings() {
if (this.isElectron) return window.electronAPI.getSettings();
try {
const settings = JSON.parse(localStorage.getItem("tt-settings") || "{}");
if ("openaiKey" in settings) {
delete settings.openaiKey;
localStorage.setItem("tt-settings", JSON.stringify(settings));
}
return settings;
} catch { return {}; }
},
async getLicenseStatus() {
if (this.isElectron && window.electronAPI.getLicenseStatus) {
return window.electronAPI.getLicenseStatus();
}
try {
return JSON.parse(localStorage.getItem("tt-license-status") || "null") || {
activated: false,
isPro: false,
plan: "free",
status: "free",
freeLimits: { history: FREE_HISTORY_LIMIT },
};
} catch {
return {
activated: false,
isPro: false,
plan: "free",
status: "free",
freeLimits: { history: FREE_HISTORY_LIMIT },
};
}
},
async activateLicense(licenseKey) {
if (this.isElectron && window.electronAPI.activateLicense) {
return window.electronAPI.activateLicense(licenseKey);
}
if (String(licenseKey || "").trim() === "TT-DEV-PRO") {
const status = {
activated: true,
isPro: true,
plan: "pro",
status: "active",
source: "browser-dev",
email: "developer@tokentotal.local",
features: Object.keys(proFeatureLabels),
};
localStorage.setItem("tt-license-status", JSON.stringify(status));
return { success: true, status };
}
return { success: false, error: "License 激活仅在桌面版支持" };
},
async deactivateLicense() {
if (this.isElectron && window.electronAPI.deactivateLicense) {
return window.electronAPI.deactivateLicense();
}
localStorage.removeItem("tt-license-status");
return { success: true, status: await this.getLicenseStatus() };
},
async openPurchasePage() {
if (this.isElectron && window.electronAPI.openPurchasePage) {
return window.electronAPI.openPurchasePage();
}
return { success: false, error: "Pro 购买页暂未配置" };
},
async setSetting(key, value) {
if (this.isElectron) return window.electronAPI.setSetting(key, value);
if (key === "openaiKey") {
sessionStorage.setItem("tt-session-openai-key", value);
return;
}
const s = await this.getSettings();
s[key] = value;
localStorage.setItem("tt-settings", JSON.stringify(s));
},
async clearSettings() {
if (this.isElectron) {
if (window.electronAPI.clearSettings) return window.electronAPI.clearSettings();
await window.electronAPI.setSetting("clipboardWatch", true);
await window.electronAPI.setSetting("autoSave", false);
await window.electronAPI.setSetting("startMinimized", false);
await window.electronAPI.setSetting("openaiKey", "");
return;
}
localStorage.setItem("tt-settings", "{}");
sessionStorage.removeItem("tt-session-openai-key");
},
async clearAllData() {
if (this.isElectron && window.electronAPI.clearAllData) {
return window.electronAPI.clearAllData();
}
await this.clearHistory();
await this.setBudget({});
await this.clearSettings();
},
async getAllData() {
if (this.isElectron) return window.electronAPI.getAllData();
return {
history: await this.getHistory(),
budget: await this.getBudget(),
settings: await this.getSettings(),
};
},
async importHistory(entries) {
if (this.isElectron) return window.electronAPI.importHistory(entries);
const h = await this.getHistory();
const existing = new Set(h.map((entry) => entry.externalId).filter(Boolean));
for (const entry of entries) {
if (entry.externalId && existing.has(entry.externalId)) continue;
h.push(entry);
if (entry.externalId) existing.add(entry.externalId);
}
localStorage.setItem("tt-history", JSON.stringify(h));
},
async scanLocalUsage(source) {
if (!this.isElectron || !window.electronAPI.scanLocalUsage) {
return { success: false, error: "本地采集仅在桌面应用中可用" };
}
return window.electronAPI.scanLocalUsage(source);
},
async getProxyStatus() {
if (!this.isElectron || !window.electronAPI.getProxyStatus) {
return { running: false, proxyBaseUrl: "", config: { port: 8787, targetBaseUrl: "http://127.0.0.1:11434", provider: "Local" } };
}
return window.electronAPI.getProxyStatus();
},
async startProxy(config) {
if (!this.isElectron || !window.electronAPI.startProxy) {
return { running: false, error: "本地代理仅在桌面应用中可用" };
}
return window.electronAPI.startProxy(config);
},
async stopProxy() {
if (!this.isElectron || !window.electronAPI.stopProxy) {
return { running: false, error: "本地代理仅在桌面应用中可用" };
}
return window.electronAPI.stopProxy();
},
async listOllamaModels() {
if (!this.isElectron || !window.electronAPI.listOllamaModels) {
return { success: false, error: "Ollama 模型读取仅在桌面应用中可用", models: [] };
}
return window.electronAPI.listOllamaModels();
},
async sendLocalChat(payload) {
if (!this.isElectron || !window.electronAPI.sendLocalChat) {
return { success: false, error: "本地聊天仅在桌面应用中可用" };
}
return window.electronAPI.sendLocalChat(payload);
},
};
/* ── DOM elements ── */
const els = {
// Dashboard page
dashboardSpend: document.querySelector("#dashboardSpend"),
dashboardBudget: document.querySelector("#dashboardBudget"),
dashboardRemaining: document.querySelector("#dashboardRemaining"),
dashboardCalls: document.querySelector("#dashboardCalls"),
dashboardRisk: document.querySelector("#dashboardRisk"),
dashboardActiveMember: document.querySelector("#dashboardActiveMember"),
dashboardMemberSelect: document.querySelector("#dashboardMemberSelect"),
dashboardMemberTable: document.querySelector("#dashboardMemberTable"),
dashboardAlertList: document.querySelector("#dashboardAlertList"),
// Estimate page
sourceText: document.querySelector("#sourceText"),
modelSelect: document.querySelector("#modelSelect"),
estimateMode: document.querySelector("#estimateMode"),
outputTokens: document.querySelector("#outputTokens"),
contextLimit: document.querySelector("#contextLimit"),
cacheRatio: document.querySelector("#cacheRatio"),
cacheLabel: document.querySelector("#cacheLabel"),
dailyCalls: document.querySelector("#dailyCalls"),
workDays: document.querySelector("#workDays"),
inputPrice: document.querySelector("#inputPrice"),
cachedPrice: document.querySelector("#cachedPrice"),
outputPrice: document.querySelector("#outputPrice"),
tokenCount: document.querySelector("#tokenCount"),
tokenConfidence: document.querySelector("#tokenConfidence"),
singleCost: document.querySelector("#singleCost"),
monthlyCost: document.querySelector("#monthlyCost"),
costBreakdown: document.querySelector("#costBreakdown"),
callSummary: document.querySelector("#callSummary"),
contextUsage: document.querySelector("#contextUsage"),
gaugeFill: document.querySelector("#gaugeFill"),
charCount: document.querySelector("#charCount"),
wordCount: document.querySelector("#wordCount"),
cjkCount: document.querySelector("#cjkCount"),
lineCount: document.querySelector("#lineCount"),
messageCount: document.querySelector("#messageCount"),
codeDensity: document.querySelector("#codeDensity"),
tokenBars: document.querySelector("#tokenBars"),
insightList: document.querySelector("#insightList"),
promptSlimMode: document.querySelector("#promptSlimMode"),
promptSlimRun: document.querySelector("#promptSlimRun"),
promptSlimEnglish: document.querySelector("#promptSlimEnglish"),
promptSlimCopy: document.querySelector("#promptSlimCopy"),
promptSlimApply: document.querySelector("#promptSlimApply"),
promptSlimOutput: document.querySelector("#promptSlimOutput"),
promptSlimOriginal: document.querySelector("#promptSlimOriginal"),
promptSlimNew: document.querySelector("#promptSlimNew"),
promptSlimSaved: document.querySelector("#promptSlimSaved"),
promptSlimSaving: document.querySelector("#promptSlimSaving"),
promptSlimNotes: document.querySelector("#promptSlimNotes"),
modelTable: document.querySelector("#modelTable"),
chatMode: document.querySelector("#chatMode"),
messageOverhead: document.querySelector("#messageOverhead"),
filePicker: document.querySelector("#filePicker"),
loadSample: document.querySelector("#loadSample"),
clearInput: document.querySelector("#clearInput"),
copyReport: document.querySelector("#copyReport"),
themeToggle: document.querySelector("#themeToggle"),
recordEstimate: document.querySelector("#recordEstimate"),
// Chat page
refreshChatModels: document.querySelector("#refreshChatModels"),
clearChat: document.querySelector("#clearChat"),
chatStartProxy: document.querySelector("#chatStartProxy"),
chatThread: document.querySelector("#chatThread"),
chatEmpty: document.querySelector("#chatEmpty"),
chatInput: document.querySelector("#chatInput"),
chatSend: document.querySelector("#chatSend"),
chatModel: document.querySelector("#chatModel"),
chatSystemPrompt: document.querySelector("#chatSystemPrompt"),
chatTemperature: document.querySelector("#chatTemperature"),
chatTemperatureLabel: document.querySelector("#chatTemperatureLabel"),
chatModelStatus: document.querySelector("#chatModelStatus"),
chatProxyStatus: document.querySelector("#chatProxyStatus"),
chatProxyUrl: document.querySelector("#chatProxyUrl"),
chatStatInput: document.querySelector("#chatStatInput"),
chatStatOutput: document.querySelector("#chatStatOutput"),
chatStatTotal: document.querySelector("#chatStatTotal"),
chatStatLatency: document.querySelector("#chatStatLatency"),
chatStatSpeed: document.querySelector("#chatStatSpeed"),
// Connectors page
refreshConnectors: document.querySelector("#refreshConnectors"),
connectorSyncAll: document.querySelector("#connectorSyncAll"),
connectorCopyProxy: document.querySelector("#connectorCopyProxy"),
connectorExactCount: document.querySelector("#connectorExactCount"),
connectorLocalModels: document.querySelector("#connectorLocalModels"),
connectorLocalModelNames: document.querySelector("#connectorLocalModelNames"),
connectorProxyState: document.querySelector("#connectorProxyState"),
connectorProxyUrl: document.querySelector("#connectorProxyUrl"),
connectorKeyState: document.querySelector("#connectorKeyState"),
connOllamaBadge: document.querySelector("#connOllamaBadge"),
connOllamaDetail: document.querySelector("#connOllamaDetail"),
connCompatibleBadge: document.querySelector("#connCompatibleBadge"),
connCodexBadge: document.querySelector("#connCodexBadge"),
connCodexDetail: document.querySelector("#connCodexDetail"),
connClaudeBadge: document.querySelector("#connClaudeBadge"),
connClaudeDetail: document.querySelector("#connClaudeDetail"),
connOpenAIDetail: document.querySelector("#connOpenAIDetail"),
connEnableOllama: document.querySelector("#connEnableOllama"),
connRefreshOllama: document.querySelector("#connRefreshOllama"),
connCopyCompatible: document.querySelector("#connCopyCompatible"),
connOpenProxySettings: document.querySelector("#connOpenProxySettings"),
connSyncCodex: document.querySelector("#connSyncCodex"),
connSyncClaude: document.querySelector("#connSyncClaude"),
connOpenAISettings: document.querySelector("#connOpenAISettings"),
connAnthropicSettings: document.querySelector("#connAnthropicSettings"),
connOpenRouterCopy: document.querySelector("#connOpenRouterCopy"),
connectorToolTable: document.querySelector("#connectorToolTable"),
// History page
historyRange: document.querySelector("#historyRange"),
exportCsv: document.querySelector("#exportCsv"),
clearHistory: document.querySelector("#clearHistory"),
costChart: document.querySelector("#costChart"),
chartEmpty: document.querySelector("#chartEmpty"),
histTotalCount: document.querySelector("#histTotalCount"),
histTotalTokens: document.querySelector("#histTotalTokens"),
histTotalCost: document.querySelector("#histTotalCost"),
histDailyCost: document.querySelector("#histDailyCost"),
qualityExactTokens: document.querySelector("#qualityExactTokens"),
qualityObservedTokens: document.querySelector("#qualityObservedTokens"),
qualityEstimatedTokens: document.querySelector("#qualityEstimatedTokens"),
qualityStatus: document.querySelector("#qualityStatus"),
qualityWarning: document.querySelector("#qualityWarning"),
historyTable: document.querySelector("#historyTable"),
historyEmpty: document.querySelector("#historyEmpty"),
// Budget page
budgetPeriod: document.querySelector("#budgetPeriod"),
budgetFill: document.querySelector("#budgetFill"),
budgetUsed: document.querySelector("#budgetUsed"),
budgetPct: document.querySelector("#budgetPct"),
budgetTotal: document.querySelector("#budgetTotal"),
budgetDailyAvg: document.querySelector("#budgetDailyAvg"),
budgetProjected: document.querySelector("#budgetProjected"),
budgetRemaining: document.querySelector("#budgetRemaining"),
budgetDaysLeft: document.querySelector("#budgetDaysLeft"),
providerBars: document.querySelector("#providerBars"),
providerEmpty: document.querySelector("#providerEmpty"),
budgetAmount: document.querySelector("#budgetAmount"),
budgetThreshold: document.querySelector("#budgetThreshold"),
saveBudget: document.querySelector("#saveBudget"),
syncCodex: document.querySelector("#syncCodex"),
syncClaude: document.querySelector("#syncClaude"),
syncAllUsage: document.querySelector("#syncAllUsage"),
syncStatus: document.querySelector("#syncStatus"),
budgetQualityNote: document.querySelector("#budgetQualityNote"),
costDiagnosisList: document.querySelector("#costDiagnosisList"),
recommendationTable: document.querySelector("#recommendationTable"),
recommendationEmpty: document.querySelector("#recommendationEmpty"),
walletCurrency: document.querySelector("#walletCurrency"),
walletMonthlyBudget: document.querySelector("#walletMonthlyBudget"),
walletWarningPct: document.querySelector("#walletWarningPct"),
walletTokenModel: document.querySelector("#walletTokenModel"),
walletUsdBudget: document.querySelector("#walletUsdBudget"),
walletTokenCapacity: document.querySelector("#walletTokenCapacity"),
walletMemberTable: document.querySelector("#walletMemberTable"),
saveWallet: document.querySelector("#saveWallet"),
// Team page
teamMemberName: document.querySelector("#teamMemberName"),
teamMemberRole: document.querySelector("#teamMemberRole"),
teamMemberBudget: document.querySelector("#teamMemberBudget"),
teamAddMember: document.querySelector("#teamAddMember"),
teamActiveMember: document.querySelector("#teamActiveMember"),
teamMemberTable: document.querySelector("#teamMemberTable"),
// Security page
securityDetectSecrets: document.querySelector("#securityDetectSecrets"),
securityDetectPII: document.querySelector("#securityDetectPII"),
securityDetectCustomerData: document.querySelector("#securityDetectCustomerData"),
securityBlockHighRisk: document.querySelector("#securityBlockHighRisk"),
securityKeywords: document.querySelector("#securityKeywords"),
saveSecurity: document.querySelector("#saveSecurity"),
securitySummary: document.querySelector("#securitySummary"),
securityRecentTable: document.querySelector("#securityRecentTable"),
// Settings page
settingClipboard: document.querySelector("#settingClipboard"),
settingAutoSave: document.querySelector("#settingAutoSave"),
settingStartMin: document.querySelector("#settingStartMin"),
licensePlanBadge: document.querySelector("#licensePlanBadge"),
licenseStatusText: document.querySelector("#licenseStatusText"),
licenseAccount: document.querySelector("#licenseAccount"),
licenseExpiry: document.querySelector("#licenseExpiry"),
licenseFeatureList: document.querySelector("#licenseFeatureList"),
licenseKey: document.querySelector("#licenseKey"),
licenseActivate: document.querySelector("#licenseActivate"),
licenseDeactivate: document.querySelector("#licenseDeactivate"),
licenseBuy: document.querySelector("#licenseBuy"),
licenseDevHint: document.querySelector("#licenseDevHint"),
openaiKey: document.querySelector("#openaiKey"),
apiKeyHelp: document.querySelector("#apiKeyHelp"),
fetchUsage: document.querySelector("#fetchUsage"),
proxyPort: document.querySelector("#proxyPort"),
proxyTarget: document.querySelector("#proxyTarget"),
proxyProvider: document.querySelector("#proxyProvider"),
startProxy: document.querySelector("#startProxy"),
stopProxy: document.querySelector("#stopProxy"),
proxyStatus: document.querySelector("#proxyStatus"),
proxyBaseUrl: document.querySelector("#proxyBaseUrl"),
copyProxyUrl: document.querySelector("#copyProxyUrl"),
csvPicker: document.querySelector("#csvPicker"),
exportAllData: document.querySelector("#exportAllData"),
clearAllData: document.querySelector("#clearAllData"),
// Toast
toastContainer: document.querySelector("#toastContainer"),
};
const sampleText = `system: 你是一个严谨的产品分析助手。
user: 我准备把客服知识库接入模型,需要估算每次请求的输入 token、输出预算和月度成本。
assistant: 可以。请提供知识库片段、平均问题长度、模型候选、缓存命中比例和每日调用量。
示例代码:
const estimate = ({ inputTokens, outputTokens, price }) => {
return (inputTokens * price.input + outputTokens * price.output) / 1_000_000;
};`;
let lastReport = null;
let lastPromptSlim = null;
let chatMessages = [];
let chatBusy = false;
let chatModelsLoaded = false;
let lastConnectorState = {
ollamaModels: [],
proxyStatus: null,
settings: {},
};
let lastUsageAudit = null;
let licenseStatus = {
activated: false,
isPro: false,
plan: "free",
status: "free",
freeLimits: { history: FREE_HISTORY_LIMIT },
};
/* ── Theme ── */
function isDark() {
return document.documentElement.getAttribute("data-theme") === "dark";
}
function updateThemeIcon() {
if (els.themeToggle) {
els.themeToggle.innerHTML = isDark() ? sunSvg : moonSvg;
}
}
function toggleTheme() {
const next = isDark() ? "light" : "dark";
document.documentElement.setAttribute("data-theme", next);
localStorage.setItem("tokentotal-theme", next);
updateThemeIcon();
}
/* ── Toast ── */
function showToast(message, type = "success") {
const toast = document.createElement("div");
toast.className = `toast ${type}`;
toast.textContent = message;
els.toastContainer.appendChild(toast);
setTimeout(() => {
toast.style.animation = "toastOut 0.2s ease-in forwards";
setTimeout(() => toast.remove(), 200);
}, 2000);
}
/* ── Tab switching ── */
function isProUser() {
return !!licenseStatus?.isPro;
}
function featureLabel(feature) {
return proFeatureLabels[feature] || "Pro 功能";
}
function requirePro(feature, message = "") {
if (isProUser()) return true;
const text = message || `${featureLabel(feature)} 是 Pro 功能`;
showToast(`${text},请在设置页升级`, "warn");
renderLicenseStatus();
return false;
}
async function canAddHistoryEntry() {
if (isProUser()) return true;
const history = await storage.getHistory();
if (history.length < FREE_HISTORY_LIMIT) return true;
showToast(`免费版最多保留 ${FREE_HISTORY_LIMIT} 条历史记录,请升级 Pro 解锁不限历史`, "warn");
return false;
}
function formatLicenseDate(value) {
if (!value) return "永久";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "未知";
return date.toLocaleDateString("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit" });
}
function renderLicenseStatus() {
if (!els.licensePlanBadge) return;
const isPro = isProUser();
els.licensePlanBadge.textContent = isPro ? "Pro" : "Free";
els.licensePlanBadge.className = `license-plan-badge ${isPro ? "pro" : "free"}`;
els.licenseStatusText.textContent = isPro
? "已激活 Pro,连接器、导出、本地聊天和高级转换已解锁。"
: `免费版可做核心估算和基础瘦身,历史记录上限 ${FREE_HISTORY_LIMIT} 条。`;
els.licenseAccount.textContent = isPro
? (licenseStatus.email || licenseStatus.customerName || licenseStatus.licenseId || "本机授权")
: "未激活";
els.licenseExpiry.textContent = isPro ? formatLicenseDate(licenseStatus.expiresAt) : "升级后显示";
const features = isPro
? (licenseStatus.features || Object.keys(proFeatureLabels))
: ["estimate", "promptSlim", "manualHistory"];
const labels = {
estimate: "Token 成本估算",
promptSlim: "基础 Prompt 瘦身",
manualHistory: `最多 ${FREE_HISTORY_LIMIT} 条历史记录`,
...proFeatureLabels,
};
els.licenseFeatureList.innerHTML = features
.map((feature) => `<span>${escapeHtml(labels[feature] || feature)}</span>`)
.join("");
if (els.licenseDeactivate) els.licenseDeactivate.disabled = !isPro;
if (els.licenseBuy) {
const hasPurchaseUrl = !!licenseStatus.purchaseUrl;
els.licenseBuy.textContent = hasPurchaseUrl ? "购买 Pro" : "Pro 内测说明";
els.licenseBuy.disabled = !hasPurchaseUrl;
els.licenseBuy.title = hasPurchaseUrl ? "打开购买页" : "当前免费版暂未开放自动购买";
}
if (els.licenseDevHint) {
els.licenseDevHint.textContent = isPro && licenseStatus.source === "developer"
? "当前使用开发测试授权 TT-DEV-PRO,正式发布前需要配置授权公钥。"
: "GitHub 免费版先开放核心能力;Pro 内测用户可手动输入 License Key。";
}
}
async function refreshLicenseStatus() {
licenseStatus = await storage.getLicenseStatus();
renderLicenseStatus();
return licenseStatus;
}
async function activateLicenseFromInput() {
const key = els.licenseKey?.value?.trim() || "";
if (!key) {
showToast("请输入 License Key", "warn");
return;
}
const original = els.licenseActivate.textContent;
els.licenseActivate.disabled = true;
els.licenseActivate.textContent = "激活中...";
try {
const result = await storage.activateLicense(key);
if (result.success) {
licenseStatus = result.status || await storage.getLicenseStatus();
els.licenseKey.value = "";
renderLicenseStatus();
showToast("Pro 已激活", "success");
return;
}
showToast(result.error || "License 激活失败", "warn");
} finally {
els.licenseActivate.disabled = false;
els.licenseActivate.textContent = original;
}
}
async function deactivateLicense() {
const result = await storage.deactivateLicense();
licenseStatus = result.status || await storage.getLicenseStatus();
renderLicenseStatus();
showToast("License 已停用", "info");
}
async function openPurchasePage() {
const result = await storage.openPurchasePage();
if (!result?.success) {
showToast(result?.error || "购买链接暂未配置", "warn");
}
}
function normalizeWorkspace(raw = {}) {
const workspace = {
...DEFAULT_WORKSPACE,
...raw,
wallet: { ...DEFAULT_WORKSPACE.wallet, ...(raw.wallet || {}) },
security: { ...DEFAULT_WORKSPACE.security, ...(raw.security || {}) },
members: Array.isArray(raw.members) && raw.members.length ? raw.members : DEFAULT_WORKSPACE.members,
};
if (!workspace.members.some((member) => member.id === workspace.activeMemberId)) {
workspace.activeMemberId = workspace.members[0]?.id || "me";
}
return workspace;
}
async function getWorkspace() {
const settings = await storage.getSettings();
return normalizeWorkspace(settings.workspace || {});
}
async function saveWorkspace(workspace) {
const normalized = normalizeWorkspace(workspace);
await storage.setSetting("workspace", normalized);
return normalized;
}
function currencySymbol(currency) {
return currency === "CNY" ? "¥" : "$";
}
function toDisplayMoney(usd, workspace) {
const currency = workspace?.wallet?.currency || "CNY";
const value = currency === "CNY" ? Number(usd || 0) * CNY_PER_USD : Number(usd || 0);
return `${currencySymbol(currency)}${value.toFixed(2)}`;
}
function walletBudgetUsd(workspace) {
const wallet = workspace.wallet || DEFAULT_WORKSPACE.wallet;
const amount = Number(wallet.monthlyBudget || 0);
return wallet.currency === "CNY" ? amount / CNY_PER_USD : amount;
}
function monthRange() {
const now = new Date();
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1).getTime();
const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0).getTime() + 86400000;
return { now, monthStart, monthEnd };
}
function memberForEntry(entry, workspace) {
return workspace.members.find((member) => member.id === entry.memberId) || workspace.members[0];
}
function summarizeByMember(entries, workspace) {
const summary = new Map();
for (const member of workspace.members) {
summary.set(member.id, {
member,
cost: 0,
tokens: 0,
calls: 0,
risks: 0,
});
}
for (const entry of entries) {
const member = memberForEntry(entry, workspace);
const row = summary.get(member.id) || { member, cost: 0, tokens: 0, calls: 0, risks: 0 };
row.cost += Number(entry.cost || 0);
row.tokens += Number(entry.inputTokens || 0) + Number(entry.outputTokens || 0);
row.calls += 1;
if (entry.security?.riskLevel && entry.security.riskLevel !== "low") row.risks += 1;
summary.set(member.id, row);
}
return [...summary.values()];
}
function activeMember(workspace) {
return workspace.members.find((member) => member.id === workspace.activeMemberId) || workspace.members[0];
}
function renderMemberOptions(select, workspace) {
if (!select) return;
select.innerHTML = workspace.members
.map((member) => `<option value="${escapeHtml(member.id)}">${escapeHtml(member.name)}</option>`)
.join("");
select.value = workspace.activeMemberId;
}
async function setActiveMember(memberId) {
const workspace = await getWorkspace();
if (!workspace.members.some((member) => member.id === memberId)) return;
workspace.activeMemberId = memberId;
await saveWorkspace(workspace);
await refreshWorkspaceViews();
}
async function refreshWorkspaceViews() {
const activePage = document.querySelector(".tab-page.active")?.id || "";
if (activePage === "pageDashboard") await refreshDashboard();
if (activePage === "pageBudget") await refreshBudget();
if (activePage === "pageTeam") await refreshTeam();
if (activePage === "pageSecurity") await refreshSecurity();
}
function switchTab(tabName) {
document.querySelectorAll(".tab-btn").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.tab === tabName);
btn.setAttribute("aria-selected", btn.dataset.tab === tabName);
});
document.querySelectorAll(".tab-page").forEach((page) => {
page.classList.toggle("active", page.id === "page" + tabName.charAt(0).toUpperCase() + tabName.slice(1));
});
// Refresh data when entering pages
if (tabName === "dashboard") refreshDashboard();
if (tabName === "chat") {
refreshChatProxyStatus();
loadChatModels();
}
if (tabName === "connectors") refreshConnectors();
if (tabName === "history") refreshHistory();
if (tabName === "budget") refreshBudget();
if (tabName === "team") refreshTeam();
if (tabName === "security") refreshSecurity();
}
/* ── Utilities ── */
function formatNumber(value) {
return new Intl.NumberFormat("zh-CN").format(Math.round(value || 0));
}
function formatMoney(value, precision = 4) {
return `$${(value || 0).toFixed(precision)}`;
}
function selectedModel() {
return models.find((m) => m.id === els.modelSelect.value) || models[0];
}
function selectedEstimateMode() {
return estimateModes[els.estimateMode.value] || estimateModes.balanced;
}
function setupModels() {
const providers = [];
const seen = new Set();
for (const m of models) {
if (!seen.has(m.provider)) {
seen.add(m.provider);
providers.push(m.provider);
}
}
els.modelSelect.innerHTML = providers
.map((provider) => {
const group = models.filter((m) => m.provider === provider);
const options = group
.map((m) => `<option value="${m.id}">${m.name}</option>`)
.join("");
return `<optgroup label="${provider}">${options}</optgroup>`;
})
.join("");
els.modelSelect.value = "claude-sonnet-4";
els.contextLimit.value = selectedModel().context;
}
function safeNumber(input, fallback = 0) {
const value = Number(input.value);
return Number.isFinite(value) ? value : fallback;
}
function countMatches(text, regex) {
const matches = text.match(regex);
return matches ? matches.length : 0;
}
function detectMessages(text) {
const roleLines = text.match(
/^\s*(system|user|assistant|developer|tool|function|客户|客服|用户|助手)\s*[::]/gim
);
if (roleLines) return roleLines.length;
try {
const parsed = JSON.parse(text);
if (Array.isArray(parsed)) {
return parsed.filter(
(item) => item && typeof item === "object" && "content" in item
).length;
}
if (Array.isArray(parsed.messages)) {
return parsed.messages.length;
}
} catch {
return text.trim() ? 1 : 0;
}
return text.trim() ? 1 : 0;
}
function estimateInputForText(text) {
const mode = selectedEstimateMode();
const estimate = estimateTokens(text);
const messageCount = detectMessages(text);
const overhead = els.chatMode.checked
? messageCount * Math.max(0, safeNumber(els.messageOverhead, 4)) +
(messageCount ? 2 : 0)
: 0;
const adjustedBase = Math.ceil(estimate.base * mode.factor);
return {
estimate,
mode,
messageCount,
overhead,
adjustedBase,
inputTokens: adjustedBase + overhead,
lowerInputTokens: Math.max(0, Math.floor(adjustedBase * mode.low + overhead)),
upperInputTokens: Math.ceil(adjustedBase * mode.high + overhead),
};
}
/* ── Token estimation ── */
function estimateTokens(text) {
const normalized = text.replace(/\r\n/g, "\n");
const cjk = countMatches(
normalized,
/[\u3400-\u9fff\u3040-\u30ff\uac00-\ud7af]/g
);
const latinWords =
normalized.match(/[A-Za-z]+(?:[-'][A-Za-z]+)*/g) || [];
const numbers = normalized.match(/\d+(?:[.,:]\d+)*/g) || [];
const symbols = countMatches(
normalized,
/[^\sA-Za-z0-9\u3400-\u9fff\u3040-\u30ff\uac00-\ud7af]/g
);
const whitespaceRuns = normalized.match(/\s+/g) || [];
const latinTokens = latinWords.reduce(
(sum, word) => sum + Math.max(1, Math.ceil(word.length / 4)),
0
);
const numberTokens = numbers.reduce(
(sum, n) => sum + Math.max(1, Math.ceil(n.length / 3)),
0
);
const symbolTokens = Math.ceil(symbols * 0.7);
const whitespaceTokens = Math.ceil(whitespaceRuns.length * 0.15);
const cjkTokens = Math.ceil(cjk * 1.05);
const codeChars = countMatches(
normalized,
/[{}()[\]<>/=+*;._`|\\]/g
);
const charCount = [...normalized].length;
const codeDensity = charCount ? codeChars / charCount : 0;
const lexicalTotal =
cjkTokens + latinTokens + numberTokens + symbolTokens + whitespaceTokens;
const codeAdjustedTotal = Math.ceil(
charCount / (codeDensity > 0.12 ? 3.15 : 3.75)
);
const base = Math.max(lexicalTotal, Math.ceil(codeAdjustedTotal * 0.72));
return {
base,
charCount,
cjk,
latinWordCount: latinWords.length,
lineCount: normalized.length ? normalized.split("\n").length : 0,
codeDensity,
buckets: {
cjk: cjkTokens,
latin: latinTokens,
number: numberTokens,
symbol: symbolTokens + whitespaceTokens,
},
};
}
/* ── Cost calculation ── */
function calculateForModel(model, inputTokens, outputTokens, cacheRatio) {
const cachedTokens = Math.round(inputTokens * cacheRatio);
const billableInput = Math.max(inputTokens - cachedTokens, 0);
const inputCost = (billableInput * model.input) / 1_000_000;
const cachedCost = (cachedTokens * model.cached) / 1_000_000;
const outputCost = (outputTokens * model.output) / 1_000_000;
return {
inputCost,
cachedCost,
outputCost,
total: inputCost + cachedCost + outputCost,
};
}
function modelKeyFromHistory(entry) {
return entry.modelId || entry.model || "Unknown";
}
function findCatalogModel(entry) {
const modelId = String(entry.modelId || entry.model || "").toLowerCase();