-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAiOverviewControlWidget.qml
More file actions
4174 lines (3738 loc) · 185 KB
/
Copy pathAiOverviewControlWidget.qml
File metadata and controls
4174 lines (3738 loc) · 185 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import Quickshell
import Quickshell.Io
import qs.Common
import qs.Services
import qs.Widgets
import qs.Modules.Plugins
PluginComponent {
id: root
property var providers: []
property bool isLoading: false
property bool hasError: false
property string errorMessage: ""
property string lastUpdated: ""
property real lastUpdatedMs: 0
property string rawJsonBuffer: ""
property string rawStderrBuffer: ""
property bool binaryReady: false
property int fetchTimeoutMs: 45000
property bool usageDidTimeout: false
property int usageRequestId: 0
property int timedOutRequestId: -1
property string providerSelection: (pluginData.providerSelection || "codex,claude,copilot").trim()
property bool showErrorProviders: String(pluginData.showErrorProviders ?? "true") === "true"
property string pillMode: (pluginData.pillMode || "auto")
property string pillProviders: (pluginData.pillProviders || providerSelection).trim()
property string densityMode: pluginData.densityMode || "comfortable"
property string providerFilter: ""
property string providerStatusFilter: "all"
property string focusedProviderId: ""
property bool allExpanded: false
property var usageHistory: ({})
property string historyBuffer: ""
property string retryBuffer: ""
property string retryingProviderId: ""
// In-process dispatch bookkeeping. The helper owns the durable state so
// this remains only a cheap guard between refreshes in this instance.
property var notifiedMap: ({})
property color providerLogoColor: {
const saved = String(pluginData.providerLogoColor || "").trim();
return saved.length > 0 ? saved : Theme.primary;
}
property bool notifyEnabled: String(pluginData.quotaNotifications ?? "true") === "true"
property int notifyThreshold: {
const parsed = parseInt(pluginData.notifyThreshold || "85");
return Number.isFinite(parsed) && parsed > 0 && parsed <= 100 ? parsed : 85;
}
property bool showClaudeProjects: String(pluginData.showClaudeProjects ?? "true") === "true"
// Antigravity normally groups quotas exactly as its own Models screen:
// Gemini and Claude/OpenAI. Per-model rows remain available for advanced
// troubleshooting without making every account card noisy by default.
property bool showAntigravityModelDetails: String(pluginData.showAntigravityModelDetails ?? "false") === "true"
// Per-provider overrides: "claude:90,codex:75" beats the global threshold.
readonly property var notifyThresholdOverrides: {
const raw = String(pluginData.notifyThresholds || "").trim();
const map = {};
if (raw.length === 0) return map;
const pairs = raw.split(",");
for (let i = 0; i < pairs.length; i++) {
const kv = pairs[i].split(":");
if (kv.length !== 2) continue;
const id = kv[0].trim().toLowerCase();
const value = parseInt(kv[1].trim());
if (id.length > 0 && Number.isFinite(value) && value > 0 && value <= 100) {
map[id] = value;
}
}
return map;
}
function thresholdFor(providerId) {
const override = notifyThresholdOverrides[normalizeProviderId(providerId)];
return override !== undefined ? override : notifyThreshold;
}
// Minutes between repeats of the same alert; 0 = once per quota window.
readonly property int notifyCooldownSecs: {
const parsed = parseInt(pluginData.notifyCooldownMinutes || "0");
if (!Number.isFinite(parsed) || parsed <= 0) return 999999999;
return parsed * 60;
}
property string pinnedProvidersCsv: (pluginData.pinnedProviders || "").trim()
readonly property var pinnedProviders: {
const parts = pinnedProvidersCsv.split(",");
const result = [];
for (let i = 0; i < parts.length; i++) {
const id = parts[i].trim().toLowerCase();
if (id.length > 0 && result.indexOf(id) < 0) result.push(id);
}
return result;
}
property string pendingProviderId: availableProviderOptions[0] || "codex"
property string claudeRateLimitTier: ""
property real claudeFiveHourUtil: 0
property string claudeFiveHourReset: ""
property real claudeSevenDayUtil: 0
property string claudeSevenDayReset: ""
property real claudeScopedLimitUtil: 0
property string claudeScopedLimitReset: ""
property string claudeScopedLimitModel: ""
property bool claudeExtraUsageEnabled: false
property int claudeWeekMessages: 0
property int claudeWeekSessions: 0
property real claudeWeekTokens: 0
property real claudeMonthTokens: 0
property int claudeAlltimeSessions: 0
property int claudeAlltimeMessages: 0
property string claudeFirstSession: ""
property real claudeTodayCost: 0
property real claudeWeekCost: 0
property real claudeMonthCost: 0
property var claudeDailyTokens: [0, 0, 0, 0, 0, 0, 0]
property var claudeDailyCosts: [0, 0, 0, 0, 0, 0, 0]
property var dayLabels: [Qt.locale(root.i18nLocale).dayName(1, Locale.ShortFormat), Qt.locale(root.i18nLocale).dayName(2, Locale.ShortFormat), Qt.locale(root.i18nLocale).dayName(3, Locale.ShortFormat), Qt.locale(root.i18nLocale).dayName(4, Locale.ShortFormat), Qt.locale(root.i18nLocale).dayName(5, Locale.ShortFormat), Qt.locale(root.i18nLocale).dayName(6, Locale.ShortFormat), Qt.locale(root.i18nLocale).dayName(0, Locale.ShortFormat)]
readonly property int currentWeekdayIndex: (new Date().getDay() + 6) % 7
readonly property string i18nLocale: AiOverviewControlI18n.normalizedLocale
function t(key, fallback, params) {
root.i18nLocale;
return AiOverviewControlI18n.tr(key, fallback, params);
}
property int refreshIntervalMs: {
const val = pluginData.refreshInterval;
const parsed = val ? parseInt(val) : 120000;
return Number.isFinite(parsed) ? parsed : 120000;
}
// Resolved imperatively in Component.onCompleted — Qt.resolvedUrl is only reliable
// when called from the file's own execution context, not from a declarative binding
// that may be evaluated before the component URL context is established.
property string _pluginDir: ""
property string providerUsageScript: _pluginDir + "/providers/get-provider-usage"
property string claudeUsageScript: _pluginDir + "/providers/get-claude-usage"
property string copilotUsageScript: _pluginDir + "/providers/get-copilot-usage"
property string usageHistoryScript: _pluginDir + "/providers/get-usage-history"
property string notifyAlertScript: _pluginDir + "/providers/send-quota-alert"
property string nineRouterAnalyticsScript: _pluginDir + "/providers/get-9router-analytics"
property var nineStats: null
property string nineStatsBuffer: ""
readonly property var availableProviderOptions: [
"codex",
"claude",
"copilot",
"antigravity",
"gemini",
"9router",
"openrouter",
"deepseek",
"kimi",
"mistral",
"glm",
"zai",
"minimax",
"qwen",
"nvidia",
"cloudflare",
"vertexai",
"byteplus",
"ollama",
"together",
"groq",
"cohere",
"replicate",
"fireworks",
"ai21",
"xai",
"kilo",
"perplexity",
"cursor",
"cline",
"opencode",
"kiro",
"warp",
"amp"
]
ListModel {
id: claudeModelList
}
ListModel {
id: claudeProjectList
}
readonly property var selectedProviders: {
const parts = providerSelection.split(",");
const result = [];
for (let i = 0; i < parts.length; i++) {
const value = parts[i].trim().toLowerCase();
if (value.length > 0 && result.indexOf(value) < 0) {
result.push(value);
}
}
return result.length > 0 ? result : ["codex"];
}
readonly property var successfulProviders: {
const result = [];
for (let i = 0; i < providers.length; i++) {
const provider = providers[i];
if (provider && provider.usage && !provider.error) {
result.push(provider);
}
}
return result;
}
readonly property var errorProviders: {
const result = [];
for (let i = 0; i < providers.length; i++) {
const provider = providers[i];
if (provider && provider.error) {
result.push(provider);
}
}
return result;
}
readonly property var displayProviders: {
if (showErrorProviders) {
return providers;
}
const result = [];
for (let i = 0; i < providers.length; i++) {
const provider = providers[i];
if (provider && !provider.error) {
result.push(provider);
}
}
return result;
}
readonly property var filteredDisplayProviders: {
const query = providerFilter.trim().toLowerCase();
const result = [];
for (let i = 0; i < displayProviders.length; i++) {
const provider = displayProviders[i];
if (providerStatusFilter === "live" && (provider.error || !provider.usage)) continue;
if (providerStatusFilter === "issues" && !provider.error && !root.hasPartialAccountErrors(provider)) continue;
if (query.length > 0) {
const haystack = `${providerName(provider.provider)} ${provider.provider} ${providerSourceLabel(provider)}`.toLowerCase();
if (haystack.indexOf(query) < 0) continue;
}
result.push(provider);
}
// Pinned first, then most-used so attention lands where quota is
// burning; failed providers sink to the end without hiding.
result.sort(function(a, b) {
const aPin = pinnedProviders.indexOf(a.provider) >= 0 ? 0 : 1;
const bPin = pinnedProviders.indexOf(b.provider) >= 0 ? 0 : 1;
if (aPin !== bPin) return aPin - bPin;
const aErr = a.error ? 1 : 0;
const bErr = b.error ? 1 : 0;
if (aErr !== bErr) return aErr - bErr;
return providerPercent(b) - providerPercent(a);
});
return result;
}
readonly property var pillDisplayProviders: {
if (pillMode === "top") {
// Single most-critical provider: highest primary usage wins.
let best = null;
let bestPercent = -1;
for (let i = 0; i < successfulProviders.length; i++) {
const percent = providerPercent(successfulProviders[i]);
if (percent > bestPercent) {
bestPercent = percent;
best = successfulProviders[i];
}
}
return best ? [best] : [];
}
if (pillMode === "custom") {
const ids = pillProviders.split(",");
const result = [];
for (let i = 0; i < ids.length; i++) {
const id = ids[i].trim().toLowerCase();
if (id.length === 0) continue;
for (let j = 0; j < providers.length; j++) {
if (providers[j] && providers[j].provider === id && !providers[j].error) {
result.push(providers[j]);
break;
}
}
}
// Custom mode is strict: never widen the pill by silently falling
// back to every successful provider when the chosen subset has no
// current data.
return result;
}
// auto: show all with usedPercent > 0, else all successful
const active = [];
for (let i = 0; i < successfulProviders.length; i++) {
if (providerPercent(successfulProviders[i]) > 0) {
active.push(successfulProviders[i]);
}
}
return active.length > 0 ? active : successfulProviders;
}
readonly property var pillPrimaryProvider: pillDisplayProviders.length > 0 ? pillDisplayProviders[0] : null
readonly property real pillPrimaryPercent: pillPrimaryProvider ? providerPercent(pillPrimaryProvider) : 0
readonly property color pillAccent: pillPrimaryProvider ? providerAccent(pillPrimaryProvider.provider) : Theme.surfaceVariantText
readonly property var providerData: {
for (let i = 0; i < pinnedProviders.length; i++) {
for (let j = 0; j < successfulProviders.length; j++) {
if (successfulProviders[j].provider === pinnedProviders[i]) {
return successfulProviders[j];
}
}
}
let bestProvider = null;
let bestPercent = -1;
for (let i = 0; i < successfulProviders.length; i++) {
const provider = successfulProviders[i];
const percent = Number(provider.usage && provider.usage.primary ? provider.usage.primary.usedPercent || 0 : 0);
if (percent > bestPercent) {
bestPercent = percent;
bestProvider = provider;
}
}
return bestProvider || (providers.length > 0 ? providers[0] : null);
}
readonly property bool hasProviderData: !!providerData && !!providerData.usage
readonly property var usageData: hasProviderData ? providerData.usage : null
readonly property var primaryWindow: usageData ? usageData.primary : null
readonly property real primaryPercent: primaryWindow ? Number(primaryWindow.usedPercent || 0) : 0
readonly property color heroAccent: getUsageColor(primaryPercent)
// Cross-provider rollup: the fleet's quota pressure at a glance. Aggregates
// the primary window of every live provider — average load, the hottest
// provider, how many are near their cap, and the soonest reset. Percent is
// the only unit comparable across heterogeneous providers, so we summarise
// load rather than faking a cross-provider monetary total. staleTickMs is
// touched so nextResetLabel re-evaluates on the same cadence as the hero.
readonly property var fleetRollup: {
const live = successfulProviders;
const out = { count: live.length, avg: 0, peak: 0, peakName: "", peakId: "", atRisk: 0, nextResetMs: 0 };
if (live.length === 0) {
return out;
}
let sum = 0;
let loadCount = 0;
let nextMs = Infinity;
for (let i = 0; i < live.length; i++) {
const percent = providerPercent(live[i]);
const win = primaryUsageWindow(live[i]);
// Only timed quota windows contribute to the average load. Balance,
// analytics, and informational cards report 0% by design — folding
// them in would dilute the fleet average toward zero and misstate
// real quota pressure. Peak / at-risk / reset still scan everyone.
const isQuotaLoad = win && win.windowMinutes !== null && win.windowMinutes !== undefined;
if (isQuotaLoad) {
sum += percent;
loadCount++;
}
if (percent > out.peak) {
out.peak = percent;
out.peakName = providerName(live[i].provider);
out.peakId = live[i].provider;
}
if (percent >= 80) {
out.atRisk++;
}
if (win && win.resetsAt) {
const ms = new Date(win.resetsAt).getTime();
if (!isNaN(ms) && ms > Date.now() && ms < nextMs) {
nextMs = ms;
}
}
}
out.avg = loadCount > 0 ? sum / loadCount : 0;
if (nextMs !== Infinity) {
out.nextResetMs = nextMs;
}
return out;
}
readonly property string fleetNextResetLabel: {
staleTickMs;
return fleetRollup.nextResetMs > 0 ? formatTimeUntil(fleetRollup.nextResetMs) : "—";
}
readonly property string accountEmail: {
if (!usageData) {
return "";
}
if (usageData.identity && usageData.identity.accountEmail) {
return usageData.identity.accountEmail;
}
return usageData.accountEmail || "";
}
readonly property string loginMethod: {
if (!usageData) {
return "";
}
if (usageData.identity && usageData.identity.loginMethod) {
return usageData.identity.loginMethod;
}
return usageData.loginMethod || "";
}
readonly property string statusTitle: {
if (isLoading && !hasProviderData) {
return t("status.syncing", "Syncing usage");
}
if (hasError) {
return t("status.needs_attention", "Needs attention");
}
if (!hasProviderData) {
return t("status.waiting", "Waiting for data");
}
return t("status.online", "AI telemetry online");
}
readonly property string statusSubtitle: {
if (isLoading && !hasProviderData) {
return t("status.fetching", "Fetching usage windows from local provider helpers.");
}
if (hasError) {
return errorMessage;
}
if (!hasProviderData) {
return t("status.no_data_hint", "Run your configured AI CLIs and refresh to populate usage windows.");
}
const resetLabel = primaryWindow ? formatTimeUntil(primaryWindow.resetsAt) : "";
if (!resetLabel) {
return t("status.windows_available", "Provider windows are available.");
}
return t("status.primary_resets", "Primary window resets in {time}.", { time: resetLabel });
}
readonly property bool isDataStale: {
staleTickMs;
return lastUpdatedMs > 0 && (Date.now() - lastUpdatedMs) > refreshIntervalMs * 2;
}
function getUsageColor(percent) {
if (percent >= 80) {
return Theme.error;
}
if (percent >= 60) {
return Theme.warning;
}
return Theme.success;
}
function capitalizeFirst(value) {
if (!value) {
return "";
}
return value.charAt(0).toUpperCase() + value.slice(1);
}
function getWindowLabel(windowMinutes) {
if (!windowMinutes) {
return "";
}
if (windowMinutes <= 300) {
return t("window.session", "Session");
}
if (windowMinutes <= 10080) {
return t("window.weekly", "Weekly");
}
if (windowMinutes <= 43200) {
return t("window.monthly", "Monthly");
}
return `${Math.floor(windowMinutes / 1440)}d`;
}
function formatTimeUntil(isoDate) {
if (!isoDate) {
return "";
}
const diff = new Date(isoDate).getTime() - Date.now();
if (diff <= 0) {
return t("time.now", "now");
}
const mins = Math.floor(diff / 60000);
if (mins < 60) {
return `${mins}m`;
}
const hours = Math.floor(mins / 60);
if (hours < 24) {
return `${hours}h ${mins % 60}m`;
}
const days = Math.floor(hours / 24);
return `${days}d ${hours % 24}h`;
}
function formatUsageLine(windowData) {
if (!windowData) {
return "";
}
if (windowData.displayValue && String(windowData.displayValue).length > 0) {
return String(windowData.displayValue);
}
const percent = Math.round(Number(windowData.usedPercent || 0));
const reset = formatTimeUntil(windowData.resetsAt);
return reset.length > 0 ? `${percent}% · ${reset}` : `${percent}%`;
}
function formatUsageError(exitCode) {
if (rawStderrBuffer.length > 0) return rawStderrBuffer.trim();
return t("error.helper_exit", "provider helper exited with code {code}", { code: exitCode });
}
function providerName(providerId) {
const names = {
codex: "Codex",
claude: "Claude",
copilot: "Copilot",
antigravity: "Antigravity",
cursor: "Cursor",
gemini: "Gemini",
openrouter: "OpenRouter",
"9router": "9Router",
deepseek: "DeepSeek",
kimi: "Kimi",
moonshot: "Kimi",
mistral: "Mistral",
glm: "GLM",
zhipu: "GLM",
zai: "Z.ai",
minimax: "MiniMax",
qwen: "Qwen",
dashscope: "Qwen",
alibaba: "Qwen",
nvidia: "NVIDIA NIM",
nim: "NVIDIA NIM",
cloudflare: "Cloudflare AI",
vertexai: "Vertex AI",
vertex: "Vertex AI",
byteplus: "BytePlus Ark",
ark: "BytePlus Ark",
modelark: "BytePlus Ark",
ollama: "Ollama",
together: "Together AI",
groq: "Groq",
cohere: "Cohere",
replicate: "Replicate",
fireworks: "Fireworks AI",
ai21: "AI21",
xai: "xAI",
grok: "xAI",
perplexity: "Perplexity",
cline: "Cline",
opencode: "OpenCode",
kilo: "Kilo",
kiro: "Kiro",
amp: "Amp",
warp: "Warp"
};
return names[providerId] || capitalizeFirst(providerId || "provider");
}
function normalizeProviderId(providerId) {
return String(providerId || "").trim().toLowerCase();
}
function notificationProviderId(providerId) {
const aliases = {
agy: "antigravity", moonshot: "kimi", zhipu: "glm",
dashscope: "qwen", alibaba: "qwen", nim: "nvidia",
vertex: "vertexai", ark: "byteplus", modelark: "byteplus",
grok: "xai"
};
const normalized = normalizeProviderId(providerId);
return aliases[normalized] || normalized;
}
function notificationIconPath(providerId) {
const canonicalId = notificationProviderId(providerId);
if (canonicalId.length === 0 || _pluginDir.length === 0) {
return "dialog-warning";
}
const extension = canonicalId === "byteplus" ? ".png" : ".svg";
// DMS accepts a local path as the notification app icon, which lets
// its popup use the same provider mark as the dashboard card.
return _pluginDir + "/assets/provider-logos/" + canonicalId + extension;
}
function notificationWindowKey(providerId, windowData) {
const canonicalId = notificationProviderId(providerId);
const minutes = Math.max(0, Math.round(Number(windowData && windowData.windowMinutes || 0)));
// Keep the identity independent of translated display text. Changing
// the DMS/plugin locale must never re-arm a quota alert.
let windowKind = "usage";
if (minutes > 0 && minutes <= 300) windowKind = "session";
else if (minutes > 0 && minutes <= 10080) windowKind = "weekly";
else if (minutes > 0 && minutes <= 43200) windowKind = "monthly";
else if (minutes > 0) windowKind = `${Math.floor(minutes / 1440)}d`;
const resetMs = new Date(windowData && windowData.resetsAt || "").getTime();
if (Number.isFinite(resetMs) && resetMs > 0) {
// Some APIs recalculate a reset timestamp by a few seconds on
// every poll. Bucket it by its quota duration so that drift does
// not look like a brand-new quota window.
const periodMs = minutes > 0
? Math.max(60 * 60 * 1000, minutes * 60 * 1000)
: 24 * 60 * 60 * 1000;
return `${canonicalId}:${windowKind}:${minutes}:${Math.floor(resetMs / periodMs)}`;
}
return `${canonicalId}:${windowKind}:${minutes}:static`;
}
function providersCsv(list) {
const result = [];
for (let i = 0; i < list.length; i++) {
const provider = normalizeProviderId(list[i]);
if (provider.length > 0 && result.indexOf(provider) < 0) {
result.push(provider);
}
}
return result.join(",");
}
function saveProviderSelection(csv) {
const normalized = providersCsv(csv.split(","));
if (normalized.length === 0) return;
const tracked = normalized.split(",");
const currentPillIds = providersCsv(pillProviders.split(",")).split(",");
const nextPillIds = [];
for (let i = 0; i < currentPillIds.length; i++) {
if (tracked.indexOf(currentPillIds[i]) >= 0) nextPillIds.push(currentPillIds[i]);
}
if (nextPillIds.length === 0) nextPillIds.push(tracked[0]);
pillProviders = nextPillIds.join(",");
providerSelection = normalized;
providers = [];
PluginService.savePluginData("aiOverviewControl", "providerSelection", normalized);
PluginService.savePluginData("aiOverviewControl", "pillProviders", pillProviders);
if (procUsage.running) {
procUsage.running = false;
}
usageDidTimeout = false;
timedOutRequestId = -1;
refresh();
}
function addProvider(providerId) {
const provider = normalizeProviderId(providerId);
if (provider.length === 0) return;
const next = selectedProviders.slice();
if (next.indexOf(provider) < 0) {
next.push(provider);
saveProviderSelection(next.join(","));
focusedProviderId = provider;
}
}
function removeProvider(providerId) {
const provider = normalizeProviderId(providerId);
const next = [];
for (let i = 0; i < selectedProviders.length; i++) {
if (selectedProviders[i] !== provider) {
next.push(selectedProviders[i]);
}
}
if (next.length === 0) {
next.push(availableProviderOptions[0] || "codex");
}
if (focusedProviderId === provider) {
focusedProviderId = "";
}
saveProviderSelection(next.join(","));
}
function providerPercent(provider) {
const windowData = primaryUsageWindow(provider);
if (!windowData) {
return 0;
}
return Number(windowData.usedPercent || 0);
}
function providerStatus(provider) {
if (!provider) return "missing";
if (provider.error) return "error";
if (hasPartialAccountErrors(provider)) return "partial";
if (provider.usage) return "active";
return "empty";
}
function providerStatusLabel(provider) {
const status = root.providerStatus(provider);
if (status === "error") return t("status.error", "Error");
if (status === "partial") return t("status.partial", "Partial");
if (status === "active") return t("status.online", "Live");
if (status === "empty") return t("status.waiting", "Waiting");
return t("status.none", "(none)");
}
function providerSourceLabel(provider) {
const source = provider && provider.source ? String(provider.source) : "local";
return source.length > 0 ? source : "local";
}
function providerErrorText(provider) {
if (!provider || !provider.error) {
return "";
}
const rawMessage = provider.error.message || provider.error.kind || "Provider returned an error.";
if (String(rawMessage).charAt(0) === "[") {
try {
const firstLine = String(rawMessage).split("\n")[0];
const parsed = JSON.parse(firstLine);
const list = Array.isArray(parsed) ? parsed : [parsed];
for (let i = 0; i < list.length; i++) {
if (list[i] && list[i].provider === provider.provider && list[i].error) {
return list[i].error.message || list[i].error.kind || rawMessage;
}
}
if (list[0] && list[0].error) {
return list[0].error.message || list[0].error.kind || rawMessage;
}
} catch (error) {
return rawMessage;
}
}
return rawMessage;
}
function providerAccount(provider) {
const usage = provider && provider.usage ? provider.usage : null;
if (!usage) return "—";
const accounts = accountsForProvider(provider);
if (provider.provider === "antigravity" && accounts.length >= 2) {
return t("card.accounts_count", "{count} local accounts", { count: accounts.length });
}
if (usage.identity && usage.identity.accountEmail) return usage.identity.accountEmail;
return usage.accountEmail || "—";
}
function providerLogin(provider) {
const usage = provider && provider.usage ? provider.usage : null;
if (!usage) return "—";
if (usage.identity && usage.identity.loginMethod) return usage.identity.loginMethod;
return usage.loginMethod || "—";
}
function providerCredits(provider) {
if (!provider || !provider.credits) return "—";
return String(provider.credits.remaining ?? "—");
}
function providerUpdatedMs(provider) {
const value = provider && provider.usage ? provider.usage.updatedAt : "";
if (!value) return lastUpdatedMs;
const parsed = new Date(value).getTime();
return Number.isFinite(parsed) ? parsed : lastUpdatedMs;
}
function providerUpdatedLabel(provider) {
const value = providerUpdatedMs(provider);
return value > 0 ? Qt.formatDateTime(new Date(value), "hh:mm:ss") : lastUpdated;
}
function compactPath(value) {
const text = String(value || "");
if (text.length === 0) return "none";
const parts = text.split("/");
if (parts.length <= 2) return text;
return `…/${parts.slice(-2).join("/")}`;
}
// Provider fallback icons live in ProviderLogo.defaultIcon (single source);
// callers pass only providerId.
function providerAccent(providerId) {
if (providerId === "claude") return Theme.warning;
if (providerId === "codex") return Theme.success;
if (providerId === "copilot") return Theme.primary;
if (providerId === "antigravity") return Theme.primary;
if (providerId === "gemini") return Theme.secondary;
if (providerId === "openrouter") return Theme.primary;
if (providerId === "9router") return Theme.secondary;
if (providerId === "deepseek") return Theme.primary;
if (providerId === "kimi" || providerId === "moonshot") return Theme.secondary;
if (providerId === "mistral") return Theme.warning;
if (providerId === "glm" || providerId === "zhipu" || providerId === "zai") return Theme.primary;
if (providerId === "minimax") return Theme.success;
if (providerId === "qwen" || providerId === "dashscope" || providerId === "alibaba") return Theme.warning;
if (providerId === "nvidia" || providerId === "nim") return Theme.success;
if (providerId === "cloudflare") return Theme.warning;
if (providerId === "vertexai" || providerId === "vertex") return Theme.primary;
if (providerId === "byteplus" || providerId === "ark" || providerId === "modelark") return Theme.secondary;
if (providerId === "together") return Theme.primary;
if (providerId === "groq") return Theme.success;
if (providerId === "cohere") return Theme.secondary;
if (providerId === "replicate") return Theme.primary;
if (providerId === "fireworks") return Theme.warning;
if (providerId === "xai" || providerId === "grok") return Theme.primary;
if (providerId === "ai21") return Theme.secondary;
return Theme.secondary;
}
function windowsForProvider(provider) {
const usage = provider && provider.usage ? provider.usage : null;
if (!usage) return [];
const accounts = accountsForProvider(provider);
if (provider.provider === "antigravity" && showAntigravityModelDetails
&& accounts.length === 1 && accounts[0].modelWindows && accounts[0].modelWindows.length) {
const modelWindows = accounts[0].modelWindows;
const detailed = [];
for (let i = 0; i < modelWindows.length; i++) {
detailed.push({ key: `model-${i}`, label: modelWindows[i].resetDescription || modelWindows[i].name || "", data: modelWindows[i] });
}
return detailed;
}
const windows = [];
if (usage.primary) windows.push({ key: "primary", label: usage.primary.resetDescription || getWindowLabel(usage.primary.windowMinutes), data: usage.primary });
if (usage.secondary) windows.push({ key: "secondary", label: usage.secondary.resetDescription || getWindowLabel(usage.secondary.windowMinutes), data: usage.secondary });
if (usage.tertiary) windows.push({ key: "tertiary", label: usage.tertiary.resetDescription || t("window.tertiary", "Tertiary"), data: usage.tertiary });
return windows;
}
function primaryUsageWindow(provider) {
const usage = provider && provider.usage ? provider.usage : null;
if (!usage) return null;
return usage.primary || usage.secondary || usage.tertiary || null;
}
// Providers exposing more than one signed-in account (Antigravity surfaces
// every local IDE / Google session) carry an `accounts` array.
function accountsForProvider(provider) {
if (!provider || !provider.accounts || !provider.accounts.length) return [];
return provider.accounts;
}
function accountErrorsForProvider(provider) {
if (!provider || !provider.accountErrors || !provider.accountErrors.length) return [];
return provider.accountErrors;
}
function hasPartialAccountErrors(provider) {
return !!provider && !!provider.usage && !provider.error && accountErrorsForProvider(provider).length > 0;
}
function partialAccountErrorText(provider) {
const errors = accountErrorsForProvider(provider);
if (errors.length === 0) return "";
const countLabel = t("card.account_errors_count", "{count} account(s) unavailable", { count: errors.length });
const first = errors[0];
const account = first.email || first.install || t("card.account", "Account");
const message = first.message || t("status.error", "Error");
return countLabel + " · " + account + ": " + message;
}
function hasMultipleAccounts(provider) {
return accountsForProvider(provider).length >= 2 && !!provider && !provider.error;
}
function accountLabel(account) {
return account && account.install ? account.install : t("card.account", "Account");
}
function accountEmailFor(account) {
return account && account.email ? account.email : "";
}
function accountWorstPercent(account) {
if (!account || !account.windows || !account.windows.length) return 0;
let worst = 0;
for (let i = 0; i < account.windows.length; i++) {
const p = Number(account.windows[i].usedPercent || 0);
if (p > worst) worst = p;
}
return worst;
}
function accountWindows(account) {
if (!account) return [];
if (showAntigravityModelDetails && account.modelWindows && account.modelWindows.length) {
return account.modelWindows;
}
return account.windows || [];
}
function providerReset(provider) {
const windowData = primaryUsageWindow(provider);
if (!windowData) return "—";
return formatTimeUntil(windowData.resetsAt);
}
function providerSubtitle(provider) {
if (!provider) return t("status.provider_missing", "No provider data");
if (provider.error) return root.providerErrorText(provider);
const source = provider.source || "local";
const windowData = primaryUsageWindow(provider);
if (windowData && windowData.displayValue && String(windowData.displayValue).length > 0) {
const label = windowData.resetDescription || t("status.usage", "usage");
const reset = provider.provider === "antigravity" ? formatTimeUntil(windowData.resetsAt) : "";
if (reset && reset !== "—") {
return `${source} · ${label} · ${windowData.displayValue} · ${t("status.reset", "reset")} ${reset}`;
}
return `${source} · ${label} · ${windowData.displayValue}`;
}
const reset = providerReset(provider);
return (reset && reset !== "—") ? `${source} · ${t("status.reset", "reset")} ${reset}` : `${source} · ${t("status.no_reset", "no reset window")}`;
}
function formatTokens(n) {
const value = Number(n || 0);
if (value >= 1000000000) return `${(value / 1000000000).toFixed(1)}B`;
if (value >= 1000000) return `${(value / 1000000).toFixed(1)}M`;
if (value >= 1000) return `${(value / 1000).toFixed(1)}K`;
return Math.round(value).toString();
}
function formatCost(usd) {
const value = Number(usd || 0);
if (value >= 1000) return `$${(value / 1000).toFixed(1)}K`;
if (value >= 100) return `$${Math.round(value)}`;
return `$${value.toFixed(2)}`;
}
function formatTier(tier) {
if (!tier) return "—";
if (tier.indexOf("max_20x") >= 0) return "Max 20x";
if (tier.indexOf("max_5x") >= 0) return "Max 5x";
if (tier.indexOf("pro") >= 0) return "Pro";
if (tier.indexOf("free") >= 0) return "Free";
return tier;
}
function parseNumberList(value) {
const parts = value.split(",");
const result = [];
for (let i = 0; i < 7; i++) {
result.push(i < parts.length ? Number(parts[i] || 0) : 0);
}
return result;
}
function parseClaudeLine(line) {
const idx = line.indexOf("=");
if (idx < 0) return;
const key = line.substring(0, idx);
const val = line.substring(idx + 1);
if (key === "RATE_LIMIT_TIER") claudeRateLimitTier = val;
else if (key === "FIVE_HOUR_UTIL") claudeFiveHourUtil = Number(val || 0);
else if (key === "FIVE_HOUR_RESET") claudeFiveHourReset = val;
else if (key === "SEVEN_DAY_UTIL") claudeSevenDayUtil = Number(val || 0);
else if (key === "SEVEN_DAY_RESET") claudeSevenDayReset = val;
else if (key === "SCOPED_LIMIT_UTIL") claudeScopedLimitUtil = Number(val || 0);
else if (key === "SCOPED_LIMIT_RESET") claudeScopedLimitReset = val;
else if (key === "SCOPED_LIMIT_MODEL") claudeScopedLimitModel = val;
else if (key === "EXTRA_USAGE_ENABLED") claudeExtraUsageEnabled = (val === "true");
else if (key === "WEEK_MESSAGES") claudeWeekMessages = parseInt(val) || 0;
else if (key === "WEEK_SESSIONS") claudeWeekSessions = parseInt(val) || 0;
else if (key === "WEEK_TOKENS") claudeWeekTokens = Number(val || 0);
else if (key === "MONTH_TOKENS") claudeMonthTokens = Number(val || 0);
else if (key === "ALLTIME_SESSIONS") claudeAlltimeSessions = parseInt(val) || 0;
else if (key === "ALLTIME_MESSAGES") claudeAlltimeMessages = parseInt(val) || 0;
else if (key === "FIRST_SESSION") claudeFirstSession = val;
else if (key === "TODAY_COST") claudeTodayCost = Number(val || 0);
else if (key === "WEEK_COST") claudeWeekCost = Number(val || 0);
else if (key === "MONTH_COST") claudeMonthCost = Number(val || 0);
else if (key === "DAILY") claudeDailyTokens = parseNumberList(val);
else if (key === "DAILY_COSTS") claudeDailyCosts = parseNumberList(val);
else if (key === "WEEK_MODELS") {
claudeModelList.clear();
if (val.length > 0) {
const pairs = val.split(",");
for (let i = 0; i < pairs.length; i++) {
const kv = pairs[i].split(":");
if (kv.length === 2) {
claudeModelList.append({ modelName: capitalizeFirst(kv[0]), modelTokens: Number(kv[1] || 0), modelCost: 0 });
}
}
}
}
else if (key === "WEEK_MODEL_COSTS") {
// Arrives after WEEK_MODELS: enrich the already-built model rows.
if (val.length > 0) {
const pairs = val.split(",");
for (let i = 0; i < pairs.length; i++) {
const kv = pairs[i].split(":");
if (kv.length !== 2) continue;
const name = capitalizeFirst(kv[0]);
for (let j = 0; j < claudeModelList.count; j++) {
if (claudeModelList.get(j).modelName === name) {
claudeModelList.setProperty(j, "modelCost", Number(kv[1] || 0));
break;
}
}
}
}
}
else if (key === "WEEK_PROJECTS") {
claudeProjectList.clear();
if (val.length > 0) {
const pairs = val.split(",");
for (let i = 0; i < pairs.length; i++) {
const cut = pairs[i].lastIndexOf(":");