forked from steipete/CodexBar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMenuCardView.swift
More file actions
1576 lines (1459 loc) · 59.5 KB
/
MenuCardView.swift
File metadata and controls
1576 lines (1459 loc) · 59.5 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 AppKit
import CodexBarCore
import SwiftUI
/// SwiftUI card used inside the NSMenu to mirror Apple's rich menu panels.
struct UsageMenuCardView: View {
struct Model {
enum PercentStyle: String {
case left
case used
var labelSuffix: String {
switch self {
case .left: "left"
case .used: "used"
}
}
var accessibilityLabel: String {
switch self {
case .left: "Usage remaining"
case .used: "Usage used"
}
}
}
struct Metric: Identifiable {
let id: String
let title: String
let percent: Double
let percentStyle: PercentStyle
let statusText: String?
let resetText: String?
let detailText: String?
let detailLeftText: String?
let detailRightText: String?
let pacePercent: Double?
let paceOnTop: Bool
init(
id: String,
title: String,
percent: Double,
percentStyle: PercentStyle,
statusText: String? = nil,
resetText: String?,
detailText: String?,
detailLeftText: String?,
detailRightText: String?,
pacePercent: Double?,
paceOnTop: Bool)
{
self.id = id
self.title = title
self.percent = percent
self.percentStyle = percentStyle
self.statusText = statusText
self.resetText = resetText
self.detailText = detailText
self.detailLeftText = detailLeftText
self.detailRightText = detailRightText
self.pacePercent = pacePercent
self.paceOnTop = paceOnTop
}
var percentLabel: String {
String(format: "%.0f%% %@", self.percent, self.percentStyle.labelSuffix)
}
}
enum SubtitleStyle {
case info
case loading
case error
}
struct TokenUsageSection {
let sessionLine: String
let monthLine: String
let hintLine: String?
let errorLine: String?
let errorCopyText: String?
}
struct ProviderCostSection {
let title: String
let percentUsed: Double
let spendLine: String
}
let provider: UsageProvider
let providerName: String
let email: String
let subtitleText: String
let subtitleStyle: SubtitleStyle
let planText: String?
let metrics: [Metric]
let usageNotes: [String]
let creditsText: String?
let creditsRemaining: Double?
let creditsHintText: String?
let creditsHintCopyText: String?
let providerCost: ProviderCostSection?
let tokenUsage: TokenUsageSection?
let placeholder: String?
let progressColor: Color
}
let model: Model
let width: CGFloat
@Environment(\.menuItemHighlighted) private var isHighlighted
static func popupMetricTitle(provider: UsageProvider, metric: Model.Metric) -> String {
if provider == .openrouter, metric.id == "primary" {
return "API key limit"
}
return metric.title
}
var body: some View {
VStack(alignment: .leading, spacing: 6) {
UsageMenuCardHeaderView(model: self.model)
if self.hasDetails {
Divider()
}
if self.model.metrics.isEmpty {
if !self.model.usageNotes.isEmpty {
UsageNotesContent(notes: self.model.usageNotes)
} else if let placeholder = self.model.placeholder {
Text(placeholder)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.font(.subheadline)
}
} else {
let hasUsage = !self.model.metrics.isEmpty || !self.model.usageNotes.isEmpty
let hasCredits = self.model.creditsText != nil
let hasProviderCost = self.model.providerCost != nil
let hasCost = self.model.tokenUsage != nil || hasProviderCost
VStack(alignment: .leading, spacing: 12) {
if hasUsage {
VStack(alignment: .leading, spacing: 12) {
ForEach(self.model.metrics, id: \.id) { metric in
MetricRow(
metric: metric,
title: Self.popupMetricTitle(provider: self.model.provider, metric: metric),
progressColor: self.model.progressColor)
}
if !self.model.usageNotes.isEmpty {
UsageNotesContent(notes: self.model.usageNotes)
}
}
}
if hasUsage, hasCredits || hasCost {
Divider()
}
if let credits = self.model.creditsText {
CreditsBarContent(
creditsText: credits,
creditsRemaining: self.model.creditsRemaining,
hintText: self.model.creditsHintText,
hintCopyText: self.model.creditsHintCopyText,
progressColor: self.model.progressColor)
}
if hasCredits, hasCost {
Divider()
}
if let providerCost = self.model.providerCost {
ProviderCostContent(
section: providerCost,
progressColor: self.model.progressColor)
}
if hasProviderCost, self.model.tokenUsage != nil {
Divider()
}
if let tokenUsage = self.model.tokenUsage {
VStack(alignment: .leading, spacing: 6) {
Text("Cost")
.font(.body)
.fontWeight(.medium)
Text(tokenUsage.sessionLine)
.font(.footnote)
Text(tokenUsage.monthLine)
.font(.footnote)
if let hint = tokenUsage.hintLine, !hint.isEmpty {
Text(hint)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(4)
.fixedSize(horizontal: false, vertical: true)
}
if let error = tokenUsage.errorLine, !error.isEmpty {
Text(error)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.error(self.isHighlighted))
.lineLimit(4)
.fixedSize(horizontal: false, vertical: true)
.overlay {
ClickToCopyOverlay(copyText: tokenUsage.errorCopyText ?? error)
}
}
}
}
}
.padding(.bottom, self.model.creditsText == nil ? 6 : 0)
}
}
.padding(.horizontal, 16)
.padding(.top, 2)
.padding(.bottom, 2)
.frame(width: self.width, alignment: .leading)
}
private var hasDetails: Bool {
!self.model.metrics.isEmpty || !self.model.usageNotes.isEmpty || self.model.placeholder != nil ||
self.model.tokenUsage != nil ||
self.model.providerCost != nil
}
}
private struct UsageMenuCardHeaderView: View {
let model: UsageMenuCardView.Model
@Environment(\.menuItemHighlighted) private var isHighlighted
var body: some View {
VStack(alignment: .leading, spacing: 3) {
HStack(alignment: .firstTextBaseline) {
Text(self.model.providerName)
.font(.headline)
.fontWeight(.semibold)
Spacer()
Text(self.model.email)
.font(.subheadline)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
}
let subtitleAlignment: VerticalAlignment = self.model.subtitleStyle == .error ? .top : .firstTextBaseline
HStack(alignment: subtitleAlignment) {
Text(self.model.subtitleText)
.font(.footnote)
.foregroundStyle(self.subtitleColor)
.lineLimit(self.model.subtitleStyle == .error ? 4 : 1)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
.layoutPriority(1)
.padding(.bottom, self.model.subtitleStyle == .error ? 4 : 0)
Spacer()
if self.model.subtitleStyle == .error, !self.model.subtitleText.isEmpty {
CopyIconButton(copyText: self.model.subtitleText, isHighlighted: self.isHighlighted)
}
if let plan = self.model.planText {
Text(plan)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(1)
}
}
}
}
private var subtitleColor: Color {
switch self.model.subtitleStyle {
case .info: MenuHighlightStyle.secondary(self.isHighlighted)
case .loading: MenuHighlightStyle.secondary(self.isHighlighted)
case .error: MenuHighlightStyle.error(self.isHighlighted)
}
}
}
private struct CopyIconButtonStyle: ButtonStyle {
let isHighlighted: Bool
func makeBody(configuration: Configuration) -> some View {
configuration.label
.padding(4)
.background {
RoundedRectangle(cornerRadius: 4, style: .continuous)
.fill(MenuHighlightStyle.secondary(self.isHighlighted).opacity(configuration.isPressed ? 0.18 : 0))
}
.scaleEffect(configuration.isPressed ? 0.94 : 1)
.animation(.easeOut(duration: 0.12), value: configuration.isPressed)
}
}
private struct CopyIconButton: View {
let copyText: String
let isHighlighted: Bool
@State private var didCopy = false
@State private var resetTask: Task<Void, Never>?
var body: some View {
Button {
self.copyToPasteboard()
withAnimation(.easeOut(duration: 0.12)) {
self.didCopy = true
}
self.resetTask?.cancel()
self.resetTask = Task { @MainActor in
try? await Task.sleep(for: .seconds(0.9))
withAnimation(.easeOut(duration: 0.2)) {
self.didCopy = false
}
}
} label: {
Image(systemName: self.didCopy ? "checkmark" : "doc.on.doc")
.font(.caption2.weight(.semibold))
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.frame(width: 18, height: 18)
}
.buttonStyle(CopyIconButtonStyle(isHighlighted: self.isHighlighted))
.accessibilityLabel(self.didCopy ? "Copied" : "Copy error")
}
private func copyToPasteboard() {
let pb = NSPasteboard.general
pb.clearContents()
pb.setString(self.copyText, forType: .string)
}
}
private struct ProviderCostContent: View {
let section: UsageMenuCardView.Model.ProviderCostSection
let progressColor: Color
@Environment(\.menuItemHighlighted) private var isHighlighted
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Text(self.section.title)
.font(.body)
.fontWeight(.medium)
UsageProgressBar(
percent: self.section.percentUsed,
tint: self.progressColor,
accessibilityLabel: "Extra usage spent")
HStack(alignment: .firstTextBaseline) {
Text(self.section.spendLine)
.font(.footnote)
Spacer()
Text(String(format: "%.0f%% used", min(100, max(0, self.section.percentUsed))))
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
}
}
}
}
private struct MetricRow: View {
let metric: UsageMenuCardView.Model.Metric
let title: String
let progressColor: Color
@Environment(\.menuItemHighlighted) private var isHighlighted
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Text(self.title)
.font(.body)
.fontWeight(.medium)
if let statusText = self.metric.statusText {
Text(statusText)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(1)
} else {
UsageProgressBar(
percent: self.metric.percent,
tint: self.progressColor,
accessibilityLabel: self.metric.percentStyle.accessibilityLabel,
pacePercent: self.metric.pacePercent,
paceOnTop: self.metric.paceOnTop)
VStack(alignment: .leading, spacing: 2) {
HStack(alignment: .firstTextBaseline) {
Text(self.metric.percentLabel)
.font(.footnote)
.lineLimit(1)
Spacer()
if let rightLabel = self.metric.resetText {
Text(rightLabel)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(1)
}
}
if self.metric.detailLeftText != nil || self.metric.detailRightText != nil {
HStack(alignment: .firstTextBaseline) {
if let detailLeft = self.metric.detailLeftText {
Text(detailLeft)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.primary(self.isHighlighted))
.lineLimit(1)
}
Spacer()
if let detailRight = self.metric.detailRightText {
Text(detailRight)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(1)
}
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
if let detail = self.metric.detailText {
Text(detail)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(1)
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
private struct UsageNotesContent: View {
let notes: [String]
@Environment(\.menuItemHighlighted) private var isHighlighted
var body: some View {
VStack(alignment: .leading, spacing: 4) {
ForEach(Array(self.notes.enumerated()), id: \.offset) { _, note in
Text(note)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(2)
.fixedSize(horizontal: false, vertical: true)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
struct UsageMenuCardHeaderSectionView: View {
let model: UsageMenuCardView.Model
let showDivider: Bool
let width: CGFloat
var body: some View {
VStack(alignment: .leading, spacing: 6) {
UsageMenuCardHeaderView(model: self.model)
if self.showDivider {
Divider()
}
}
.padding(.horizontal, 16)
.padding(.top, 2)
.padding(.bottom, self.model.subtitleStyle == .error ? 2 : 0)
.frame(width: self.width, alignment: .leading)
}
}
struct UsageMenuCardUsageSectionView: View {
let model: UsageMenuCardView.Model
let showBottomDivider: Bool
let bottomPadding: CGFloat
let width: CGFloat
@Environment(\.menuItemHighlighted) private var isHighlighted
var body: some View {
VStack(alignment: .leading, spacing: 12) {
if self.model.metrics.isEmpty {
if !self.model.usageNotes.isEmpty {
UsageNotesContent(notes: self.model.usageNotes)
} else if let placeholder = self.model.placeholder {
Text(placeholder)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.font(.subheadline)
}
} else {
ForEach(self.model.metrics, id: \.id) { metric in
MetricRow(
metric: metric,
title: UsageMenuCardView.popupMetricTitle(provider: self.model.provider, metric: metric),
progressColor: self.model.progressColor)
}
if !self.model.usageNotes.isEmpty {
UsageNotesContent(notes: self.model.usageNotes)
}
}
if self.showBottomDivider {
Divider()
}
}
.padding(.horizontal, 16)
.padding(.top, 10)
.padding(.bottom, self.bottomPadding)
.frame(width: self.width, alignment: .leading)
}
}
struct UsageMenuCardCreditsSectionView: View {
let model: UsageMenuCardView.Model
let showBottomDivider: Bool
let topPadding: CGFloat
let bottomPadding: CGFloat
let width: CGFloat
var body: some View {
if let credits = self.model.creditsText {
VStack(alignment: .leading, spacing: 6) {
CreditsBarContent(
creditsText: credits,
creditsRemaining: self.model.creditsRemaining,
hintText: self.model.creditsHintText,
hintCopyText: self.model.creditsHintCopyText,
progressColor: self.model.progressColor)
if self.showBottomDivider {
Divider()
}
}
.padding(.horizontal, 16)
.padding(.top, self.topPadding)
.padding(.bottom, self.bottomPadding)
.frame(width: self.width, alignment: .leading)
}
}
}
private struct CreditsBarContent: View {
private static let fullScaleTokens: Double = 1000
let creditsText: String
let creditsRemaining: Double?
let hintText: String?
let hintCopyText: String?
let progressColor: Color
@Environment(\.menuItemHighlighted) private var isHighlighted
private var percentLeft: Double? {
guard let creditsRemaining else { return nil }
let percent = (creditsRemaining / Self.fullScaleTokens) * 100
return min(100, max(0, percent))
}
private var scaleText: String {
let scale = UsageFormatter.tokenCountString(Int(Self.fullScaleTokens))
return "\(scale) tokens"
}
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Text("Credits")
.font(.body)
.fontWeight(.medium)
if let percentLeft {
UsageProgressBar(
percent: percentLeft,
tint: self.progressColor,
accessibilityLabel: "Credits remaining")
HStack(alignment: .firstTextBaseline) {
Text(self.creditsText)
.font(.caption)
Spacer()
Text(self.scaleText)
.font(.caption)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
}
} else {
Text(self.creditsText)
.font(.caption)
}
if let hintText, !hintText.isEmpty {
Text(hintText)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(4)
.fixedSize(horizontal: false, vertical: true)
.overlay {
ClickToCopyOverlay(copyText: self.hintCopyText ?? hintText)
}
}
}
}
}
struct UsageMenuCardCostSectionView: View {
let model: UsageMenuCardView.Model
let topPadding: CGFloat
let bottomPadding: CGFloat
let width: CGFloat
@Environment(\.menuItemHighlighted) private var isHighlighted
var body: some View {
let hasTokenCost = self.model.tokenUsage != nil
return Group {
if hasTokenCost {
VStack(alignment: .leading, spacing: 10) {
if let tokenUsage = self.model.tokenUsage {
VStack(alignment: .leading, spacing: 6) {
Text("Cost")
.font(.body)
.fontWeight(.medium)
Text(tokenUsage.sessionLine)
.font(.caption)
Text(tokenUsage.monthLine)
.font(.caption)
if let hint = tokenUsage.hintLine, !hint.isEmpty {
Text(hint)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.secondary(self.isHighlighted))
.lineLimit(4)
.fixedSize(horizontal: false, vertical: true)
}
if let error = tokenUsage.errorLine, !error.isEmpty {
Text(error)
.font(.footnote)
.foregroundStyle(MenuHighlightStyle.error(self.isHighlighted))
.lineLimit(4)
.fixedSize(horizontal: false, vertical: true)
.overlay {
ClickToCopyOverlay(copyText: tokenUsage.errorCopyText ?? error)
}
}
}
}
}
.padding(.horizontal, 16)
.padding(.top, self.topPadding)
.padding(.bottom, self.bottomPadding)
.frame(width: self.width, alignment: .leading)
}
}
}
}
struct UsageMenuCardExtraUsageSectionView: View {
let model: UsageMenuCardView.Model
let topPadding: CGFloat
let bottomPadding: CGFloat
let width: CGFloat
var body: some View {
Group {
if let providerCost = self.model.providerCost {
ProviderCostContent(
section: providerCost,
progressColor: self.model.progressColor)
.padding(.horizontal, 16)
.padding(.top, self.topPadding)
.padding(.bottom, self.bottomPadding)
.frame(width: self.width, alignment: .leading)
}
}
}
}
// MARK: - Model factory
extension UsageMenuCardView.Model {
struct Input {
let provider: UsageProvider
let metadata: ProviderMetadata
let snapshot: UsageSnapshot?
let codexProjection: CodexConsumerProjection?
let credits: CreditsSnapshot?
let creditsError: String?
let dashboard: OpenAIDashboardSnapshot?
let dashboardError: String?
let tokenSnapshot: CostUsageTokenSnapshot?
let tokenError: String?
let account: AccountInfo
let isRefreshing: Bool
let lastError: String?
let usageBarsShowUsed: Bool
let resetTimeDisplayStyle: ResetTimeDisplayStyle
let tokenCostUsageEnabled: Bool
let showOptionalCreditsAndExtraUsage: Bool
let sourceLabel: String?
let kiloAutoMode: Bool
let hidePersonalInfo: Bool
let claudePeakHoursEnabled: Bool
let weeklyPace: UsagePace?
let now: Date
init(
provider: UsageProvider,
metadata: ProviderMetadata,
snapshot: UsageSnapshot?,
codexProjection: CodexConsumerProjection? = nil,
credits: CreditsSnapshot?,
creditsError: String?,
dashboard: OpenAIDashboardSnapshot?,
dashboardError: String?,
tokenSnapshot: CostUsageTokenSnapshot?,
tokenError: String?,
account: AccountInfo,
isRefreshing: Bool,
lastError: String?,
usageBarsShowUsed: Bool,
resetTimeDisplayStyle: ResetTimeDisplayStyle,
tokenCostUsageEnabled: Bool,
showOptionalCreditsAndExtraUsage: Bool,
sourceLabel: String? = nil,
kiloAutoMode: Bool = false,
hidePersonalInfo: Bool,
claudePeakHoursEnabled: Bool = true,
weeklyPace: UsagePace? = nil,
now: Date)
{
self.provider = provider
self.metadata = metadata
self.snapshot = snapshot
self.codexProjection = codexProjection
self.credits = credits
self.creditsError = creditsError
self.dashboard = dashboard
self.dashboardError = dashboardError
self.tokenSnapshot = tokenSnapshot
self.tokenError = tokenError
self.account = account
self.isRefreshing = isRefreshing
self.lastError = lastError
self.usageBarsShowUsed = usageBarsShowUsed
self.resetTimeDisplayStyle = resetTimeDisplayStyle
self.tokenCostUsageEnabled = tokenCostUsageEnabled
self.showOptionalCreditsAndExtraUsage = showOptionalCreditsAndExtraUsage
self.sourceLabel = sourceLabel
self.kiloAutoMode = kiloAutoMode
self.hidePersonalInfo = hidePersonalInfo
self.claudePeakHoursEnabled = claudePeakHoursEnabled
self.weeklyPace = weeklyPace
self.now = now
}
}
static func make(_ input: Input) -> UsageMenuCardView.Model {
let planText = Self.plan(
for: input.provider,
snapshot: input.snapshot,
account: input.account,
metadata: input.metadata)
let metrics = Self.metrics(input: input)
let usageNotes = Self.usageNotes(input: input)
let creditsText: String? = if input.provider == .openrouter {
nil
} else if input.codexProjection != nil, !input.showOptionalCreditsAndExtraUsage {
nil
} else {
Self.creditsLine(metadata: input.metadata, credits: input.credits, error: input.creditsError)
}
let providerCost: ProviderCostSection? = if input.provider == .claude, !input.showOptionalCreditsAndExtraUsage {
nil
} else {
Self.providerCostSection(provider: input.provider, cost: input.snapshot?.providerCost)
}
let tokenUsage = Self.tokenUsageSection(
provider: input.provider,
enabled: input.tokenCostUsageEnabled,
snapshot: input.tokenSnapshot,
error: input.tokenError)
let subtitle = Self.subtitle(
snapshot: input.snapshot,
isRefreshing: input.isRefreshing,
lastError: input.lastError)
let redacted = Self.redactedText(input: input, subtitle: subtitle)
let placeholder = input.snapshot == nil && !input.isRefreshing && input.lastError == nil ? "No usage yet" : nil
return UsageMenuCardView.Model(
provider: input.provider,
providerName: input.metadata.displayName,
email: redacted.email,
subtitleText: redacted.subtitleText,
subtitleStyle: subtitle.style,
planText: planText,
metrics: metrics,
usageNotes: usageNotes,
creditsText: creditsText,
creditsRemaining: input.credits?.remaining,
creditsHintText: redacted.creditsHintText,
creditsHintCopyText: redacted.creditsHintCopyText,
providerCost: providerCost,
tokenUsage: tokenUsage,
placeholder: placeholder,
progressColor: Self.progressColor(for: input.provider))
}
private static func usageNotes(input: Input) -> [String] {
if input.provider == .kilo {
var notes = Self.kiloLoginDetails(snapshot: input.snapshot)
let resolvedSource = input.sourceLabel?
.trimmingCharacters(in: .whitespacesAndNewlines)
.lowercased()
if input.kiloAutoMode,
resolvedSource == "cli",
!notes.contains(where: { $0.caseInsensitiveCompare("Using CLI fallback") == .orderedSame })
{
notes.append("Using CLI fallback")
}
return notes
}
if input.provider == .claude, input.claudePeakHoursEnabled {
let peakStatus = ClaudePeakHours.status(at: input.now)
return [peakStatus.label]
}
guard input.provider == .openrouter,
let openRouter = input.snapshot?.openRouterUsage
else {
return []
}
return switch openRouter.keyQuotaStatus {
case .available: []
case .noLimitConfigured: ["No limit set for the API key"]
case .unavailable: ["API key limit unavailable right now"]
}
}
private static func email(
for provider: UsageProvider,
snapshot: UsageSnapshot?,
account: AccountInfo,
metadata: ProviderMetadata) -> String
{
if let email = snapshot?.accountEmail(for: provider), !email.isEmpty { return email }
if metadata.usesAccountFallback,
let email = account.email, !email.isEmpty
{
return email
}
return ""
}
private static func plan(
for provider: UsageProvider,
snapshot: UsageSnapshot?,
account: AccountInfo,
metadata: ProviderMetadata) -> String?
{
if provider == .kilo {
guard let pass = self.kiloLoginPass(snapshot: snapshot) else {
return nil
}
return self.planDisplay(pass)
}
if let plan = snapshot?.loginMethod(for: provider), !plan.isEmpty {
return self.planDisplay(plan)
}
if metadata.usesAccountFallback,
let plan = account.plan, !plan.isEmpty
{
return Self.planDisplay(plan)
}
return nil
}
private static func planDisplay(_ text: String) -> String {
let cleaned = CodexPlanFormatting.displayName(text) ?? UsageFormatter.cleanPlanName(text)
return cleaned.isEmpty ? text : cleaned
}
private static func kiloLoginPass(snapshot: UsageSnapshot?) -> String? {
self.kiloLoginParts(snapshot: snapshot).pass
}
private static func kiloLoginDetails(snapshot: UsageSnapshot?) -> [String] {
self.kiloLoginParts(snapshot: snapshot).details
}
private static func kiloLoginParts(snapshot: UsageSnapshot?) -> (pass: String?, details: [String]) {
guard let loginMethod = snapshot?.loginMethod(for: .kilo) else {
return (nil, [])
}
let parts = loginMethod
.components(separatedBy: "·")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
guard !parts.isEmpty else {
return (nil, [])
}
let first = parts[0]
if self.isKiloActivitySegment(first) {
return (nil, parts)
}
return (first, Array(parts.dropFirst()))
}
private static func isKiloActivitySegment(_ text: String) -> Bool {
let normalized = text.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return normalized.hasPrefix("auto top-up:")
}
private static func subtitle(
snapshot: UsageSnapshot?,
isRefreshing: Bool,
lastError: String?) -> (text: String, style: SubtitleStyle)
{
if let lastError, !lastError.isEmpty {
return (lastError.trimmingCharacters(in: .whitespacesAndNewlines), .error)
}
if isRefreshing, snapshot == nil {
return ("Refreshing...", .loading)
}
if let updated = snapshot?.updatedAt {
return (UsageFormatter.updatedString(from: updated), .info)
}
return ("Not fetched yet", .info)
}
private struct RedactedText {
let email: String
let subtitleText: String
let creditsHintText: String?
let creditsHintCopyText: String?
}
private static func redactedText(
input: Input,
subtitle: (text: String, style: SubtitleStyle)) -> RedactedText
{
let email = PersonalInfoRedactor.redactEmail(
Self.email(
for: input.provider,
snapshot: input.snapshot,
account: input.account,
metadata: input.metadata),
isEnabled: input.hidePersonalInfo)
let subtitleText = PersonalInfoRedactor.redactEmails(in: subtitle.text, isEnabled: input.hidePersonalInfo)
?? subtitle.text
let creditsHintText = PersonalInfoRedactor.redactEmails(
in: Self.dashboardHint(error: input.dashboardError),
isEnabled: input.hidePersonalInfo)
let creditsHintCopyText = Self.creditsHintCopyText(
dashboardError: input.dashboardError,
hidePersonalInfo: input.hidePersonalInfo)
return RedactedText(
email: email,
subtitleText: subtitleText,
creditsHintText: creditsHintText,
creditsHintCopyText: creditsHintCopyText)
}
private static func creditsHintCopyText(dashboardError: String?, hidePersonalInfo: Bool) -> String? {
guard let dashboardError, !dashboardError.isEmpty else { return nil }
return hidePersonalInfo ? "" : dashboardError
}
private static func metrics(input: Input) -> [Metric] {
guard let snapshot = input.snapshot else { return [] }
if input.provider == .antigravity {
return Self.antigravityMetrics(input: input, snapshot: snapshot)
}
var metrics: [Metric] = []
let percentStyle: PercentStyle = input.usageBarsShowUsed ? .used : .left
let zaiUsage = input.provider == .zai ? snapshot.zaiUsage : nil
let zaiTokenDetail = Self.zaiLimitDetailText(limit: zaiUsage?.tokenLimit)
let zaiTimeDetail = Self.zaiLimitDetailText(limit: zaiUsage?.timeLimit)
let zaiSessionDetail = Self.zaiLimitDetailText(limit: zaiUsage?.sessionTokenLimit)
let openRouterQuotaDetail = Self.openRouterQuotaDetail(provider: input.provider, snapshot: snapshot)
if input.provider == .codex, let codexProjection = input.codexProjection {
metrics.append(contentsOf: Self.codexRateMetrics(
input: input,
projection: codexProjection,
percentStyle: percentStyle))
} else if let primary = snapshot.primary {
metrics.append(Self.primaryMetric(
input: input,
primary: primary,
percentStyle: percentStyle,
zaiTokenDetail: zaiTokenDetail,
openRouterQuotaDetail: openRouterQuotaDetail))
}
if input.provider != .codex, let weekly = snapshot.secondary {
metrics.append(Self.secondaryMetric(
input: input,
weekly: weekly,
percentStyle: percentStyle,
zaiTimeDetail: zaiTimeDetail))
}
if input.metadata.supportsOpus, let opus = snapshot.tertiary {
var tertiaryDetailText: String?
if input.provider == .alibaba,
let detail = opus.resetDescription,
!detail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
{
tertiaryDetailText = detail
}
if input.provider == .zai, let detail = zaiSessionDetail {
tertiaryDetailText = detail
}
// Perplexity purchased credits don't reset; show balance without "Resets" prefix.
let opusResetText: String? = input.provider == .perplexity
? opus.resetDescription?.trimmingCharacters(in: .whitespacesAndNewlines)
: Self.resetText(for: opus, style: input.resetTimeDisplayStyle, now: input.now)
metrics.append(Metric(
id: "tertiary",
title: input.metadata.opusLabel ?? "Sonnet",
percent: Self.clamped(input.usageBarsShowUsed ? opus.usedPercent : opus.remainingPercent),
percentStyle: percentStyle,
resetText: opusResetText,
detailText: tertiaryDetailText,
detailLeftText: nil,
detailRightText: nil,
pacePercent: nil,