-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage.go
More file actions
1521 lines (1438 loc) · 46 KB
/
Copy pathusage.go
File metadata and controls
1521 lines (1438 loc) · 46 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/charmbracelet/lipgloss"
)
// ── usage + availability ─────────────────────────────────────────────────────
type usageWin struct {
label string
pct int
tier string
secs int64 // seconds until reset (relative)
dur int64 // window length in seconds
prov string
stale bool // retained from the last successful fetch after a refresh omitted this window
missing bool // never observed: rendered as a deterministic placeholder row
observed int64 // Unix timestamp of the last real value; retained across cache fallback
}
// resetCredits tracks OpenAI reset credits: how many are currently available
// and the seconds until each available credit expires (relative, unsorted).
type resetCredits struct {
avail int
exp []int64
}
type availability struct {
bucket map[string]string // bucket -> "ok" | "maxed" | "unauthed"
reset map[string]int64
wins []usageWin
credits resetCredits
accountCredits map[accountKey]resetCredits
ok bool
accounts map[string][]account
accountUsage map[accountKey][]usageWin
accountsOK bool
selectionApplied bool
accountsStale bool
// deepseek is the DeepSeek prepaid balance: nil when the snapshot carries
// no DeepSeek credential (the group is hidden entirely — an absent API key
// is the normal state, unlike a metered subscription).
deepseek *deepseekBalance
}
func fetchBrokerUsage(broker brokerConfig) ([]byte, error) {
if broker.URL == "" || broker.Token == "" {
return nil, errors.New("central auth broker is not configured")
}
req, err := http.NewRequest(http.MethodGet, strings.TrimRight(broker.URL, "/")+"/v1/usage", nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+broker.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, resp.Body)
return nil, fmt.Errorf("usage endpoint returned %s", resp.Status)
}
return io.ReadAll(resp.Body)
}
type usageCacheWin struct {
Label string `json:"label"`
Pct int `json:"pct"`
Tier string `json:"tier,omitempty"`
ResetsAt int64 `json:"resetsAt"`
Dur int64 `json:"dur"`
Provider string `json:"provider"`
Observed int64 `json:"observed"`
}
type usageCacheAccount struct {
Provider string `json:"provider"`
IdentityKey string `json:"identityKey"`
Wins []usageCacheWin `json:"wins"`
}
type usageCacheFile struct {
SavedAt int64 `json:"savedAt"`
Accounts map[string][]account `json:"accounts"`
Deepseek *usageCacheBalance `json:"deepseekBalance,omitempty"`
Usage []usageCacheAccount `json:"usage"`
}
// usageCacheBalance caches the DeepSeek balance VALUE only — never the key.
type usageCacheBalance struct {
Currency string `json:"currency"`
Total string `json:"totalBalance"`
FetchedAt int64 `json:"fetchedAt"`
}
func emptyAvailability() availability {
return availability{
bucket: map[string]string{}, reset: map[string]int64{},
accounts: map[string][]account{}, accountUsage: map[accountKey][]usageWin{},
accountCredits: map[accountKey]resetCredits{},
}
}
// parseAvailability associates broker usage with stable identities from the
// same snapshot. observedAt is the cache observation time; reset countdowns
// remain relative to now because the broker payload stores absolute deadlines.
func parseAvailability(accounts map[string][]account, accountsOK bool, out []byte, observedAt int64) availability {
a := emptyAvailability()
a.accounts, a.accountsOK = accounts, accountsOK
type limit struct {
Label string `json:"label"`
Scope struct {
Tier string `json:"tier"`
} `json:"scope"`
Amount struct {
UsedFraction float64 `json:"usedFraction"`
} `json:"amount"`
Window struct {
ResetsAt int64 `json:"resetsAt"`
DurationMs int64 `json:"durationMs"`
} `json:"window"`
}
var doc struct {
Reports []struct {
Provider string `json:"provider"`
Email string `json:"email"`
AccountID string `json:"accountId"`
Metadata struct {
Email string `json:"email"`
AccountID string `json:"accountId"`
} `json:"metadata"`
Limits []limit `json:"limits"`
ResetCredits struct {
AvailableCount int `json:"availableCount"`
Credits []struct {
ExpiresAt string `json:"expiresAt"`
Status string `json:"status"`
} `json:"credits"`
} `json:"resetCredits"`
} `json:"reports"`
}
if len(out) == 0 || json.Unmarshal(out, &doc) != nil {
return a
}
a.ok = true
provSeen := map[string]bool{}
now := time.Now().Unix()
if observedAt <= 0 {
observedAt = now
}
for _, r := range doc.Reports {
provSeen[r.Provider] = true
reportWins := make([]usageWin, 0, len(r.Limits))
for _, l := range r.Limits {
pct := int(l.Amount.UsedFraction*100 + 0.5)
win := usageWin{label: l.Label, pct: pct, tier: l.Scope.Tier,
secs: l.Window.ResetsAt/1000 - now, dur: l.Window.DurationMs / 1000,
prov: r.Provider, observed: observedAt}
reportWins = append(reportWins, win)
a.wins = append(a.wins, win)
bkt := bucketForProviderTier(r.Provider, l.Scope.Tier)
if bkt == "" {
continue
}
if pct >= 100 {
a.bucket[bkt] = "maxed"
a.reset[bkt] = l.Window.ResetsAt/1000 - now
} else if a.bucket[bkt] != "maxed" {
a.bucket[bkt] = "ok"
}
}
email, accountID := r.Metadata.Email, r.Metadata.AccountID
if email == "" {
email = r.Email
}
if accountID == "" {
accountID = r.AccountID
}
var matchedKey accountKey
matched := false
for _, acct := range a.accounts[r.Provider] {
if (email != "" && acct.Email != "" && strings.EqualFold(email, acct.Email)) ||
(accountID != "" && accountID == acct.IdentityKey) {
matchedKey = accountKey{Provider: acct.Provider, IdentityKey: acct.IdentityKey}
a.accountUsage[matchedKey] = append(a.accountUsage[matchedKey], reportWins...)
matched = true
break
}
}
if r.Provider == openAIProvider {
credits := resetCredits{avail: r.ResetCredits.AvailableCount}
for _, c := range r.ResetCredits.Credits {
if c.Status != "available" {
continue
}
if t, err := time.Parse(time.RFC3339, c.ExpiresAt); err == nil {
credits.exp = append(credits.exp, t.Unix()-now)
}
}
a.credits.avail += credits.avail
a.credits.exp = append(a.credits.exp, credits.exp...)
if matched {
attributed := a.accountCredits[matchedKey]
attributed.avail += credits.avail
attributed.exp = append(attributed.exp, credits.exp...)
a.accountCredits[matchedKey] = attributed
}
}
}
for _, prov := range providerRegistry {
if !prov.Metered {
continue
}
for _, b := range prov.buckets() {
if !provSeen[prov.ID] {
a.bucket[b] = "unauthed"
} else if _, ok := a.bucket[b]; !ok {
a.bucket[b] = "ok"
}
}
}
return a
}
// loadAvailability reads one central snapshot and one aggregate usage report,
// plus — when the snapshot carries a DeepSeek api_key — the upstream prepaid
// balance, fetched concurrently so neither request delays the other.
func loadAvailability(broker brokerConfig) availability {
accounts, err := loadAccounts(broker)
accountsOK := err == nil
if !accountsOK {
accounts = map[string][]account{}
}
var ds *deepseekBalance
var wg sync.WaitGroup
if key := deepseekAPIKey(accounts); key != "" {
wg.Add(1)
go func() {
defer wg.Done()
bal, err := fetchDeepSeekBalance(key)
if err != nil {
// Degrade to an explicit "unavailable" row; other providers
// are unaffected.
bal = deepseekBalance{fetchedAt: time.Now().Unix()}
}
ds = &bal
}()
}
out, err := fetchBrokerUsage(broker)
if err != nil {
out = nil
}
wg.Wait()
a := parseAvailability(accounts, accountsOK, out, 0)
a.deepseek = ds
return a
}
func loadUsageCache(path string) availability {
a := emptyAvailability()
if path == "" {
return a
}
body, err := os.ReadFile(path)
if err != nil {
return a
}
var cached usageCacheFile
if json.Unmarshal(body, &cached) != nil || cached.SavedAt <= 0 || len(cached.Usage) == 0 {
return a
}
a.accounts, a.accountsOK, a.ok = cached.Accounts, true, true
provSeen := map[string]bool{}
for _, entry := range cached.Usage {
key := accountKey{Provider: entry.Provider, IdentityKey: entry.IdentityKey}
for _, cachedWin := range entry.Wins {
win := usageWin{
label: cachedWin.Label, pct: cachedWin.Pct, tier: cachedWin.Tier,
secs: cachedWin.ResetsAt - time.Now().Unix(), dur: cachedWin.Dur, prov: cachedWin.Provider,
observed: cachedWin.Observed, stale: true,
}
a.accountUsage[key] = append(a.accountUsage[key], win)
a.wins = append(a.wins, win)
provSeen[win.prov] = true
bucket := bucketForProviderTier(win.prov, win.tier)
if bucket == "" {
continue
}
if win.pct >= 100 {
a.bucket[bucket], a.reset[bucket] = "maxed", win.secs
} else if a.bucket[bucket] != "maxed" {
a.bucket[bucket] = "ok"
}
}
}
if cached.Deepseek != nil {
a.deepseek = &deepseekBalance{
ok: true, currency: cached.Deepseek.Currency, total: cached.Deepseek.Total,
fetchedAt: cached.Deepseek.FetchedAt, stale: true,
}
}
for _, prov := range providerRegistry {
if !prov.Metered {
continue
}
for _, bucket := range prov.buckets() {
if !provSeen[prov.ID] {
a.bucket[bucket] = "unauthed"
} else if _, ok := a.bucket[bucket]; !ok {
a.bucket[bucket] = "ok"
}
}
}
return a
}
func saveUsageCache(path string, a availability) {
if path == "" || !a.ok {
return
}
now := time.Now().Unix()
cached := usageCacheFile{SavedAt: now, Accounts: a.accounts}
if a.deepseek != nil && a.deepseek.ok {
cached.Deepseek = &usageCacheBalance{
Currency: a.deepseek.currency, Total: a.deepseek.total, FetchedAt: a.deepseek.fetchedAt,
}
}
for key, wins := range a.accountUsage {
entry := usageCacheAccount{Provider: key.Provider, IdentityKey: key.IdentityKey}
for _, win := range wins {
if win.missing {
continue
}
observed := win.observed
if observed <= 0 {
observed = now
}
entry.Wins = append(entry.Wins, usageCacheWin{
Label: win.label, Pct: win.pct, Tier: win.tier,
ResetsAt: observed + win.secs, Dur: win.dur,
Provider: win.prov, Observed: observed,
})
}
if len(entry.Wins) > 0 {
cached.Usage = append(cached.Usage, entry)
}
}
if len(cached.Usage) == 0 {
return
}
sort.Slice(cached.Usage, func(i, j int) bool {
if cached.Usage[i].Provider != cached.Usage[j].Provider {
return cached.Usage[i].Provider < cached.Usage[j].Provider
}
return cached.Usage[i].IdentityKey < cached.Usage[j].IdentityKey
})
body, err := json.Marshal(cached)
if err != nil {
return
}
body = append(body, '\n')
_ = atomicPrivateWrite(path, body)
}
// bucketForProviderTier maps a usage report's (provider, tier) scope onto the
// quota bucket it constrains: the provider's main window, or a special tier's
// dedicated window. Unmetered and unknown providers own no buckets.
func bucketForProviderTier(prov, tier string) string {
p := providerByID(prov)
if p == nil || !p.Metered {
return ""
}
if tier == "" || tier == "-" {
return p.mainBucket()
}
for _, s := range p.Special {
if s.Bucket == tier {
return p.BucketBase + "-" + s.Bucket
}
}
return ""
}
func (a availability) down(bucket string) bool {
return a.bucket[bucket] == "maxed" || a.bucket[bucket] == "unauthed"
}
// reconcileUsage folds a freshly fetched availability over the one currently
// shown, so a flaky upstream never wipes known-good data. It returns the
// availability to display plus whether the whole panel is stale:
//
// - a total fetch failure after any prior success keeps the previous
// availability wholesale and reports it stale — the control row shows a
// refresh-failed warning instead of dropping to the unauthenticated error;
// - a successful payload that omits an account's usage retains that
// account's last observed rows, visibly marked stale with their age;
// - a successful Anthropic payload that only omits the flaky Fable window
// retains the last Fable row, along with its bucket/reset routing state;
// - a successful Anthropic payload with no Fable window ever observed
// appends a deterministic unavailable placeholder, so the datum appearing
// on a later refresh never pops the panel geometry.
//
// Fresh values always win; nothing is fabricated — retained rows are visibly
// marked stale and placeholders carry no numbers.
func reconcileUsage(prev, next availability) (availability, bool) {
if !next.ok {
if prev.ok {
return prev, true
}
return next, false
}
if !next.accountsOK && prev.accountsOK {
next.accounts, next.accountsOK, next.accountsStale = prev.accounts, true, true
}
next.accountUsage = reconcileAccountUsage(prev.accountUsage, next.accountUsage, next.accounts)
if next.deepseek != nil && !next.deepseek.ok && prev.deepseek != nil && prev.deepseek.ok {
// A failed balance refresh keeps the last known value, visibly stale —
// same retention contract as the metered windows.
retained := *prev.deepseek
retained.stale = true
next.deepseek = &retained
}
hasClaude, hasFable := false, false
for _, w := range next.wins {
if w.prov != anthropicProvider {
continue
}
hasClaude = true
if w.tier == "fable" {
hasFable = true
}
}
if !hasClaude || hasFable {
return next, false
}
for _, w := range prev.wins {
if w.prov == anthropicProvider && w.tier == "fable" && !w.missing {
w.stale = true
next.wins = append(next.wins, w)
// Carry the bucket/reset state observed with the retained window:
// loadAvailability defaults an unseen bucket to "ok", which would
// route onto a fable the last real datum said was maxed.
if st, ok := prev.bucket["claude-fable"]; ok {
next.bucket["claude-fable"] = st
}
if r, ok := prev.reset["claude-fable"]; ok {
next.reset["claude-fable"] = r
}
return next, false
}
}
next.wins = append(next.wins, fablePlaceholder)
return next, false
}
func reconcileAccountUsage(prev, next map[accountKey][]usageWin, accounts map[string][]account) map[accountKey][]usageWin {
if next == nil {
next = map[accountKey][]usageWin{}
}
active := map[accountKey]bool{}
for _, providerAccounts := range accounts {
for _, acct := range providerAccounts {
active[accountKey{Provider: acct.Provider, IdentityKey: acct.IdentityKey}] = true
}
}
if len(active) == 0 {
for key := range next {
active[key] = true
}
}
for key := range active {
wins := next[key]
hasFresh := false
for _, w := range wins {
if !w.missing {
hasFresh = true
break
}
}
if !hasFresh {
retained := make([]usageWin, 0, len(prev[key]))
for _, w := range prev[key] {
if w.missing {
continue
}
w.stale = true
retained = append(retained, w)
}
if len(retained) > 0 {
next[key] = retained
}
continue
}
if key.Provider != anthropicProvider {
continue
}
hasClaude, hasFable := false, false
for _, w := range wins {
if w.prov != anthropicProvider {
continue
}
if !w.missing {
hasClaude = true
}
if w.tier == "fable" {
hasFable = true
}
}
if !hasClaude || hasFable {
continue
}
retained := false
for _, w := range prev[key] {
if w.prov == anthropicProvider && w.tier == "fable" && !w.missing {
w.stale = true
next[key] = append(next[key], w)
retained = true
break
}
}
if !retained {
next[key] = append(next[key], fablePlaceholder)
}
}
return next
}
// fablePlaceholder is the never-observed fable window's deterministic
// stand-in: the real payload label (so shortWin renders the same "7d fable"
// tag) and window length, with no usage numbers to fabricate.
var fablePlaceholder = usageWin{label: "Claude 7 Day (Fable)", tier: "fable", dur: 7 * 24 * 3600, prov: anthropicProvider, missing: true}
type usageGroupKey struct {
prov string
tier string
dur int64
label string
}
type usageGroup struct {
win usageWin
count int64
pctSum int64
secsSum int64
observed int64
}
func knownUsageWindow(w usageWin) bool {
label := shortWin(w.label)
bucket := bucketForProviderTier(w.prov, w.tier)
p := providerByID(w.prov)
if bucket == "" || p == nil {
return false
}
if bucket == p.mainBucket() {
return label == "5h" || label == "7d"
}
suffix := strings.TrimPrefix(bucket, p.BucketBase+"-")
return label == "5h "+suffix || label == "7d "+suffix
}
// selectedAvailability derives account-sensitive usage and routing availability
// solely from enabled broker identities. Unmatched reports never enter this seam.
func selectedAvailability(a availability, disabled map[accountKey]bool) availability {
selected := a
selected.selectionApplied = true
selected.accounts = map[string][]account{}
selected.accountUsage = map[accountKey][]usageWin{}
selected.accountCredits = map[accountKey]resetCredits{}
selected.bucket = map[string]string{}
selected.reset = map[string]int64{}
selected.wins = nil
selected.credits = resetCredits{}
enabledProviders := map[string]bool{}
groups := map[usageGroupKey]*usageGroup{}
missing := map[usageGroupKey]usageWin{}
var groupOrder []usageGroupKey
for prov, accounts := range a.accounts {
for _, acct := range accounts {
key := accountKey{Provider: acct.Provider, IdentityKey: acct.IdentityKey}
if disabled[key] {
continue
}
selected.accounts[prov] = append(selected.accounts[prov], acct)
enabledProviders[acct.Provider] = true
wins := a.accountUsage[key]
if credits, ok := a.accountCredits[key]; ok {
selected.accountCredits[key] = credits
selected.credits.avail += credits.avail
selected.credits.exp = append(selected.credits.exp, credits.exp...)
}
for _, win := range wins {
if win.prov != acct.Provider || !knownUsageWindow(win) {
continue
}
selected.accountUsage[key] = append(selected.accountUsage[key], win)
groupKey := usageGroupKey{prov: win.prov, tier: win.tier, dur: win.dur, label: shortWin(win.label)}
if win.missing {
if _, ok := missing[groupKey]; !ok {
placeholder := win
placeholder.label = groupKey.label
missing[groupKey] = placeholder
groupOrder = append(groupOrder, groupKey)
}
continue
}
group := groups[groupKey]
if group == nil {
aggregate := win
aggregate.label = groupKey.label
group = &usageGroup{win: aggregate}
groups[groupKey] = group
groupOrder = append(groupOrder, groupKey)
}
pct, secs := int64(win.pct), win.secs
if pct < 0 {
pct = 0
}
if secs < 0 {
secs = 0
}
group.count++
group.pctSum += pct
group.secsSum += secs
group.win.stale = group.win.stale || win.stale
if win.observed > 0 && (group.observed == 0 || win.observed < group.observed) {
group.observed = win.observed
}
}
}
}
seen := map[usageGroupKey]bool{}
for _, key := range groupOrder {
if seen[key] {
continue
}
seen[key] = true
if group := groups[key]; group != nil {
group.win.pct = int((group.pctSum + group.count/2) / group.count)
group.win.secs = (group.secsSum + group.count/2) / group.count
group.win.observed = group.observed
selected.wins = append(selected.wins, group.win)
} else {
selected.wins = append(selected.wins, missing[key])
}
}
for _, prov := range providerRegistry {
if !prov.Metered {
continue
}
for _, bucket := range prov.buckets() {
if enabledProviders[prov.ID] {
selected.bucket[bucket] = "ok"
} else {
selected.bucket[bucket] = "unauthed"
}
}
}
for _, win := range selected.wins {
bucket := bucketForProviderTier(win.prov, win.tier)
if bucket == "" || win.missing || win.pct < 100 {
continue
}
selected.bucket[bucket] = "maxed"
// Multiple quota windows can constrain one route. The route becomes
// usable only after the last maxed aggregate resets, so retain the
// longest selected reset rather than whichever account/map came last.
if win.secs > selected.reset[bucket] {
selected.reset[bucket] = win.secs
}
}
return selected
}
const usageBarNaturalW = 10
func barStr(p, width int) string {
if width < 0 {
width = 0
}
var r, g float64
if p <= 50 {
r, g = 90+float64(p)*3, 200
} else {
r, g = 235, 200-float64(p-50)*3
}
if r > 235 {
r = 235
}
if g < 60 {
g = 60
}
fill := (p*width + 50) / 100
if fill > width {
fill = width
}
if fill < 0 {
fill = 0
}
filled := lipgloss.NewStyle().Foreground(lipgloss.Color(fmt.Sprintf("#%02x%02x46", clampByte(r), clampByte(g)))).Render(strings.Repeat("█", fill))
return filled + stDim.Render(strings.Repeat("░", width-fill))
}
func fmtReset(s int64) string {
if s < 0 {
s = 0
}
switch {
case s >= 86400:
return fmt.Sprintf("%dd%dh", s/86400, (s%86400)/3600)
case s >= 3600:
return fmt.Sprintf("%dh%dm", s/3600, (s%3600)/60)
}
return fmt.Sprintf("%dm", s/60)
}
func shortWin(l string) string {
switch l {
case "5 hours", "Claude 5 Hour", "Codex 5 Hour", "OpenAI 5 Hour":
return "5h"
case "7 days", "Claude 7 Day", "Codex 7 Day", "OpenAI 7 Day":
return "7d"
case "5 hours (Spark)", "Codex 5 Hour (Spark)", "OpenAI 5 Hour (Spark)":
return "5h spark"
case "7 days (Spark)", "Codex 7 Day (Spark)", "OpenAI 7 Day (Spark)":
return "7d spark"
case "Claude 7 Day (Fable)":
return "7d fable"
}
return l
}
// usageCtrlLine is the Usage chrome's bottom action row: central refresh state,
// account-manager access, and any account persistence error.
func (m *model) usageCtrlLine() string {
var parts []string
if m.broker.URL != "" {
switch {
case !m.avail.ok && (m.fetching || m.nextRefresh.IsZero()):
parts = append(parts, stDim.Render(m.spin.View()+" fetching usage…"))
case m.fetching:
parts = append(parts, stWarn.Render(gReset+" refreshing…"))
case m.usageStale:
// A failed refresh kept the previous data on screen: the warning
// takes the countdown's slot (same row, similar width) so the
// measured panel geometry — and with it the medium/collapsed
// breakpoint — barely moves on a flaky refresh.
parts = append(parts, stWarn.Render("refresh failed · stale")+
stDim.Render(" · ")+stKey.Render("r")+stDim.Render(" retry"))
default:
rem := time.Until(m.nextRefresh)
if rem < 0 {
rem = 0
}
s := int(rem.Seconds())
parts = append(parts,
stDim.Render(fmt.Sprintf("next refresh %d:%02d · ", s/60, s%60))+
stKey.Render("r")+stDim.Render(" now"))
}
}
identityAction := "full ids"
if m.fullUsageIDs {
identityAction = "short ids"
}
parts = append(parts, stKey.Render("i")+stDim.Render(" "+identityAction))
parts = append(parts, stKey.Render("v")+stDim.Render(" accounts"))
if len(parts) == 0 {
return ""
}
line := " " + strings.Join(parts, stDim.Render(" · "))
if m.accountErr != "" {
line += "\n" + stBrk.Render(" account update failed: "+m.accountErr)
}
return line
}
// compactDisplayIdentity produces a deliberately lossy display label. Email
// matching continues to use the untouched broker identity; this helper is only
// for the compact Usage heading.
func compactDisplayIdentity(identity string) string {
normalized := strings.ToLower(strings.TrimSpace(identity))
at := strings.IndexByte(normalized, '@')
if at > 0 && at == strings.LastIndexByte(normalized, '@') {
local, domain := normalized[:at], normalized[at+1:]
dot := strings.LastIndexByte(domain, '.')
valid := dot > 0 && dot < len(domain)-1 &&
!strings.HasPrefix(local, ".") && !strings.HasSuffix(local, ".") &&
!strings.Contains(local, "..") && !strings.Contains(domain, "..") &&
strings.IndexFunc(normalized, func(r rune) bool {
return unicode.IsSpace(r) || unicode.IsControl(r)
}) < 0
if valid {
localRunes := []rune(local)
if len(localRunes) > 2 {
localRunes = localRunes[:2]
}
return string(localRunes) + "*"
}
}
if normalized == "" {
return "id unavailable"
}
runes := []rune(normalized)
if len(runes) > 2 {
runes = runes[:2]
}
return string(runes) + "*"
}
func usageDisplayIdentity(identity string, full bool) string {
if full {
if identity = strings.TrimSpace(identity); identity != "" {
return identity
}
return "id unavailable"
}
return compactDisplayIdentity(identity)
}
type compactProviderIdentity struct {
label string
reporting bool
}
// providerIdentities preserves broker snapshot order and collapses repeated
// copies of the same stable account. Compact ambiguity is intentional; pressing
// i reveals full addresses when disambiguation matters.
func providerIdentities(a availability, prov string, full bool) []compactProviderIdentity {
accounts := a.accounts[prov]
identities := make([]compactProviderIdentity, 0, len(accounts))
seenAccounts := map[string]bool{}
for _, acct := range accounts {
stableID := acct.IdentityKey
if stableID == "" {
stableID = acct.Email
}
if stableID != "" {
stableID = acct.Provider + "\x00" + stableID
if seenAccounts[stableID] {
continue
}
seenAccounts[stableID] = true
}
identity := acct.Email
if identity == "" {
identity = acct.IdentityKey
}
label := usageDisplayIdentity(identity, full)
reporting := false
for _, win := range a.accountUsage[accountKey{Provider: acct.Provider, IdentityKey: acct.IdentityKey}] {
if !win.missing {
reporting = true
break
}
}
identities = append(identities, compactProviderIdentity{
label: label, reporting: reporting,
})
}
return identities
}
// providerHeading keeps the provider's established color and puts compact,
// enabled snapshot identities in a dim parenthetical suffix.
func providerHeading(prov string, identities []compactProviderIdentity) string {
col, name := "#8a93a6", prov
if p := providerByID(prov); p != nil {
col, name = p.Color, p.Label
}
heading := lipgloss.NewStyle().Foreground(lipgloss.Color(col)).Bold(true).Render(name)
if len(identities) == 0 {
return heading
}
labels := make([]string, 0, len(identities))
for _, identity := range identities {
labels = append(labels, identity.label)
}
return heading + " " + stDim.Render("("+strings.Join(labels, " + ")+")")
}
// providerIdentityBlockFor keeps missing usage explicit without spending a
// separate row on accounts already represented by aggregate usage bars.
func providerIdentityBlockFor(a availability, prov string, checking, full bool) []string {
identities := providerIdentities(a, prov, full)
if checking && len(identities) == 0 {
identities = []compactProviderIdentity{{label: "checking account…"}}
}
rows := []string{padLeft(providerHeading(prov, identities), gut)}
if checking {
return rows
}
if !a.accountsOK {
return append(rows, stWarn.Render(" account status unavailable"))
}
if len(identities) == 0 {
if a.selectionApplied {
return append(rows, stDim.Render(" no enabled accounts"))
}
return append(rows, stBrk.Render(" not authenticated"))
}
unavailable := 0
for _, identity := range identities {
if !identity.reporting {
unavailable++
}
}
if unavailable > 0 {
status := " usage unavailable"
if len(identities) > 1 {
noun := "account"
if unavailable > 1 {
noun = "accounts"
}
status += fmt.Sprintf(" for %d %s", unavailable, noun)
}
rows = append(rows, stWarn.Render(status))
}
if a.accountsStale {
rows = append(rows, stWarn.Render(" identity cached"))
}
return rows
}
func providerIdentityBlock(a availability, prov string, checking bool) []string {
return providerIdentityBlockFor(a, prov, checking, false)
}
// identityLines keeps provider and broker-reported account state visible even
// when no usage rows exist.
func identityLinesFor(a availability) string {
var lines []string
for i, prov := range meteredProviderIDs() {
if i > 0 {
lines = append(lines, "")
}
lines = append(lines, providerIdentityBlock(a, prov, false)...)
}
return strings.Join(lines, "\n")
}
func (m *model) selectedLaunchAvailability() availability {
return selectedAvailability(m.avail, m.accountSelections.CurrentDisabled())
}
func (m *model) selectedUsageAvailability() availability {
disabled := m.accountSelections.CurrentDisabled()
if m.manager {
disabled = m.managerDisplayedDisabled()
}
return selectedAvailability(m.avail, disabled)
}
func (m *model) identityLines() string {
return identityLinesFor(m.selectedUsageAvailability())
}
// usagePanel is the composition-agnostic Usage band sized for the current
// terminal width — the wide layout's full-width footer form.
func (m *model) usagePanel() string { return m.usagePanelFor(m.w) }
// usagePanelFor renders central account usage with local visibility and account
// manager cues. There is no selectable vault or profile identity.
func (m *model) usagePanelFor(w int) string {
return m.usagePanelLayout(w, false)
}
func (m *model) usagePanelStackedFor(w int) string {
return m.usagePanelLayout(w, true)
}
func (m *model) usagePanelLayout(w int, stacked bool) string {
title := m.pill("usage")
title += " " + stCueKey.Render("s") + stCue.Render(" · hide")
innerWidth := max(0, w-gut)
out := padLeft(title, gut) + "\n" +
"\n" + m.usageBodyLayout(innerWidth, stacked)
if ctrl := m.usageCtrlLine(); ctrl != "" && !m.manager {
out += "\n\n" + ctrl // blank row: air between provider content and the control row
}
return out
}
// usageRenderGroup keeps provider chrome and usage rows separate until layout
// has assigned the provider its real display width. That is the composition seam