Open History to see the last commit
1import Charts
2import SwiftUI
3
4private enum UsageMetric: String, CaseIterable, Identifiable {
5 case cost
6 case tokens
7
8 var id: Self { self }
9 var label: String { rawValue.uppercased() }
10}
11
12private enum UsageBreakdown {
13 case model
14 case time
15}
16
17private enum UsageTab: String {
18 case usage
19 case limits
20}
21
22public struct UsageView: View {
23 private let client: any FeatureClient
24
25 @State private var loadState = UsageLoadState()
26 @State private var metric = UsageMetric.cost
27 @State private var breakdown = UsageBreakdown.model
28 @State private var tab = UsageTab.usage
29 @State private var hasActivatedUsage = false
30 @State private var resetCreditStates: [UsageResetCreditTarget: UsageResetCreditState] = [:]
31
32 public init(client: any FeatureClient, initiallyShowsLimits: Bool = false) {
33 self.client = client
34 _tab = State(initialValue: initiallyShowsLimits ? .limits : .usage)
35 }
36
37 private var windowInput: UsageSummaryInput { loadState.windowInput }
38 private var environments: [FeatureEnvironmentUsage] { loadState.environments }
39 private var merged: MergedUsage { loadState.merged }
40 private var presentation: UsagePresentation { loadState.presentation }
41 private var isLoading: Bool { loadState.isLoading }
42 private var errorMessage: String? { loadState.errorMessage }
43 private var windowDays: Binding<Int> {
44 Binding(
45 get: { loadState.windowDays },
46 set: { loadState.selectWindow(days: $0) }
47 )
48 }
49
50 public var body: some View {
51 VStack(spacing: 0) {
52 Picker("Usage view", selection: $tab) {
53 Text("Usage").tag(UsageTab.usage)
54 Text("Limits").tag(UsageTab.limits)
55 }
56 .pickerStyle(.segmented)
57 .tint(T3Colors.textPrimary)
58 .padding(.horizontal, 20)
59 .padding(.top, 16)
60 .padding(.bottom, 12)
61
62 // Both tabs stay mounted. Switching only toggles visibility, so the
63 // usage load and every limit subscription survive a tab change.
64 ZStack {
65 usageContent
66 .opacity(tab == .usage ? 1 : 0)
67 .allowsHitTesting(tab == .usage)
68 .accessibilityHidden(tab != .usage)
69 UsageLimitsView(
70 client: client,
71 resetCreditStates: $resetCreditStates,
72 isActive: tab == .limits
73 )
74 .opacity(tab == .limits ? 1 : 0)
75 .allowsHitTesting(tab == .limits)
76 .accessibilityHidden(tab != .limits)
77 }
78 }
79 .background(T3Colors.background)
80 .navigationTitle("Usage")
81 .navigationBarTitleDisplayMode(.inline)
82 .toolbar(.visible, for: .navigationBar)
83 .toolbar {
84 if tab == .usage {
85 ToolbarItem(placement: .topBarTrailing) {
86 Button("Refresh prices", systemImage: "arrow.clockwise") {
87 Task { await load(refreshPricing: true) }
88 }
89 .disabled(isLoading)
90 }
91 }
92 }
93 .t3NavigationChrome()
94 .onChange(of: tab, initial: true) { _, selected in
95 if selected == .usage { hasActivatedUsage = true }
96 }
97 .task(id: hasActivatedUsage ? loadState.windowDays : nil) {
98 guard hasActivatedUsage else { return }
99 await load()
100 }
101 }
102
103 private var usageContent: some View {
104 ScrollView {
105 LazyVStack(alignment: .leading, spacing: 20) {
106 Picker("Usage window", selection: windowDays) {
107 Text("24h").tag(1)
108 Text("7d").tag(7)
109 Text("30d").tag(30)
110 Text("90d").tag(90)
111 }
112 .pickerStyle(.segmented)
113 .tint(T3Colors.textPrimary)
114
115 coverageNotice
116
117 if isLoading, !hasCompatibleSummary,
118 environments.isEmpty || environments.contains(where: \.isPending) {
119 Text("Scanning provider transcripts")
120 .font(T3Typography.supporting)
121 .foregroundStyle(T3Colors.textTertiary)
122 .frame(maxWidth: .infinity)
123 .padding(.vertical, 64)
124 } else if let errorMessage, environments.isEmpty {
125 ContentUnavailableView {
126 Label("Couldn’t load usage", systemImage: "exclamationmark.circle")
127 } description: {
128 Text(errorMessage)
129 } actions: {
130 Button("Try again") { Task { await load() } }
131 }
132 } else if environments.isEmpty {
133 ContentUnavailableView {
134 Label("No environments", systemImage: "chart.bar.xaxis")
135 } description: {
136 Text("Connect an environment to see usage.")
137 }
138 } else if !hasCompatibleSummary {
139 ContentUnavailableView {
140 Label("Couldn’t load usage", systemImage: "exclamationmark.circle")
141 } description: {
142 Text(hasDailyOnlySummary
143 ? "This server reports daily usage. Select 7d or 30d to see it."
144 : "No compatible usage data is available.")
145 } actions: {
146 Button("Try again") { Task { await load() } }
147 }
148 } else {
149 chartSection
150 usageDivider
151 providersSection
152 usageDivider
153 totalsSection
154 usageDivider
155 breakdownSection
156 }
157 }
158 .padding(.horizontal, 20)
159 .padding(.top, 16)
160 .padding(.bottom, 32)
161 }
162 .scrollIndicators(.hidden)
163 .refreshable { await load() }
164 }
165
166 @ViewBuilder
167 private var coverageNotice: some View {
168 let failed = environments.filter { $0.errorMessage != nil }
169 let stale = environments.filter { merged.staleEnvironments.contains($0.environmentID) }
170 let hasRefreshError = errorMessage != nil && hasCompatibleSummary
171 if hasRefreshError
172 || loadState.isPartial
173 || loadState.hasPendingCachedTotals
174 || !failed.isEmpty
175 || !stale.isEmpty
176 || !merged.duplicateSources.isEmpty {
177 VStack(alignment: .leading, spacing: 6) {
178 if loadState.hasPendingCachedTotals {
179 Text(loadState.isPartial
180 ? "Updating usage. Totals are partial and include the last scan."
181 : "Updating usage. Some totals are from the last scan.")
182 } else if loadState.isPartial {
183 Text("Some environments are still reporting. Totals are partial.")
184 }
185 if hasRefreshError {
186 Text("Couldn’t refresh usage. The totals below are from the last successful scan.")
187 }
188 ForEach(failed) { environment in
189 Text("\(environment.label): \(environment.errorMessage ?? "Could not report usage.")")
190 }
191 ForEach(stale) { environment in
192 if windowInput.resolution == .hour, environment.summary?.contractVersion == 3 {
193 Text("\(environment.label) reports daily usage only. Select 7d or 30d to include it.")
194 } else {
195 Text("\(environment.label) uses an unsupported usage format and is excluded from totals.")
196 }
197 }
198 if !merged.duplicateSources.isEmpty {
199 Text(
200 "Counted once across environments sharing a transcript directory: "
201 + merged.duplicateSources.joined(separator: ", ")
202 )
203 }
204 }
205 .font(T3Typography.supporting)
206 .foregroundStyle(T3Colors.textSecondary)
207 .frame(maxWidth: .infinity, alignment: .leading)
208 }
209 }
210
211 private var chartSection: some View {
212 VStack(alignment: .leading, spacing: 16) {
213 HStack(alignment: .top, spacing: 12) {
214 VStack(alignment: .leading, spacing: 2) {
215 Text(metric == .cost ? "Raw token cost" : "Processed tokens")
216 .font(T3Typography.supporting)
217 .foregroundStyle(T3Colors.textSecondary)
218 Text(
219 metric == .cost
220 ? "\(UsageFormat.usd(merged.costUsd))*"
221 : UsageFormat.tokens(merged.totalTokens)
222 )
223 .font(.system(.largeTitle, design: .default, weight: .bold))
224 .monospacedDigit()
225 .foregroundStyle(T3Colors.textPrimary)
226 .lineLimit(1)
227 .minimumScaleFactor(0.55)
228 Text(
229 metric == .cost
230 ? "* if billed at full API rate"
231 + (merged.costQuality.unpricedShare > 0
232 ? ". Excludes \(UsageFormat.percent(merged.costQuality.unpricedShare)) unpriced records."
233 : "")
234 : "Across \(UsageFormat.count(merged.sessions)) sessions"
235 )
236 .font(T3Typography.supporting)
237 .foregroundStyle(T3Colors.textSecondary)
238 }
239 .frame(maxWidth: .infinity, alignment: .leading)
240
241 Picker("Chart metric", selection: $metric) {
242 ForEach(UsageMetric.allCases) { option in
243 Text(option.label).tag(option)
244 }
245 }
246 .pickerStyle(.segmented)
247 .fixedSize()
248 .tint(T3Colors.textPrimary)
249 }
250
251 if metric == .cost ? presentation.hasCostActivity : presentation.hasTokenActivity {
252 UsagePeriodChart(
253 segments: metric == .cost ? presentation.costSegments : presentation.tokenSegments
254 )
255 .frame(height: 180)
256 } else {
257 Text("No activity in this window.")
258 .font(T3Typography.threadBody)
259 .foregroundStyle(T3Colors.textSecondary)
260 .frame(maxWidth: .infinity, minHeight: 180)
261 }
262
263 HStack(spacing: 8) {
264 Text(presentation.sinceLabel)
265 .frame(maxWidth: .infinity, alignment: .leading)
266
267 HStack(spacing: 14) {
268 ForEach(presentation.providersByCost) { provider in
269 HStack(spacing: 5) {
270 Circle()
271 .fill(provider.provider.color)
272 .frame(width: 8, height: 8)
273 Text(provider.provider.displayName)
274 }
275 }
276 }
277 .fixedSize()
278
279 Text(presentation.untilLabel)
280 .frame(maxWidth: .infinity, alignment: .trailing)
281 }
282 .font(.caption)
283 .foregroundStyle(T3Colors.textTertiary)
284 }
285 }
286
287 @ViewBuilder
288 private var providersSection: some View {
289 let ordered = metric == .cost ? presentation.providersByCost : presentation.providersByTokens
290 if !ordered.isEmpty {
291 UsageSection(title: "Providers") {
292 VStack(spacing: 0) {
293 ForEach(Array(ordered.enumerated()), id: \.element.id) { index, provider in
294 if index > 0 { usageDivider }
295 let share = metric == .cost ? provider.costShare : provider.tokenShare
296 VStack(alignment: .leading, spacing: 8) {
297 HStack(alignment: .firstTextBaseline, spacing: 10) {
298 Circle()
299 .fill(provider.provider.color)
300 .frame(width: 10, height: 10)
301 Text(provider.provider.displayName)
302 .font(.title3)
303 .foregroundStyle(T3Colors.textPrimary)
304 Spacer(minLength: 8)
305 Text(
306 metric == .cost
307 ? UsageFormat.usd(provider.costUsd)
308 : UsageFormat.tokens(provider.totalTokens)
309 )
310 .font(.title3)
311 .monospacedDigit()
312 .foregroundStyle(T3Colors.textPrimary)
313 }
314 UsageProgressBar(value: share, color: provider.provider.color)
315 Text(
316 metric == .cost
317 ? "\(UsageFormat.percent(share)) of cost · "
318 + "\(UsageFormat.tokens(provider.totalTokens)) tokens"
319 : "\(UsageFormat.percent(share)) of tokens · \(UsageFormat.usd(provider.costUsd))"
320 )
321 .font(T3Typography.supporting)
322 .foregroundStyle(T3Colors.textSecondary)
323 }
324 .padding(.vertical, 10)
325 }
326 }
327 }
328 }
329 }
330
331 private var totalsSection: some View {
332 UsageSection(title: "Totals") {
333 let isHourly = windowInput.resolution == .hour
334 LazyVGrid(
335 columns: [GridItem(.flexible(), alignment: .topLeading), GridItem(.flexible(), alignment: .topLeading)],
336 alignment: .leading,
337 spacing: 0
338 ) {
339 UsageMetricCell(
340 label: "Processed tokens",
341 value: UsageFormat.tokens(merged.totalTokens),
342 detail: "\(UsageFormat.tokens(presentation.periodAverageTokens)) per active \(isHourly ? "hour" : "day")"
343 )
344 UsageMetricCell(
345 label: "Cache savings",
346 value: UsageFormat.usd(merged.costQuality.cacheSavingsUsd),
347 detail: merged.costUsd > 0
348 ? String(format: "%.1fx the raw cost", merged.costQuality.cacheSavingsUsd / merged.costUsd)
349 : "vs full input rates"
350 )
351 UsageMetricCell(
352 label: "Cached input",
353 value: UsageFormat.tokens(merged.cachedInputTokens),
354 detail: "\(UsageFormat.percent(presentation.cachedInputShare)) of observed input"
355 )
356 UsageMetricCell(
357 label: "Uncached input",
358 value: UsageFormat.tokens(merged.uncachedInputTokens),
359 detail: "\(UsageFormat.tokens(merged.cacheCreationTokens)) cache writes"
360 )
361 UsageMetricCell(
362 label: "Output",
363 value: UsageFormat.tokens(merged.outputTokens),
364 detail: "incl. \(UsageFormat.tokens(merged.reasoningTokens)) reasoning"
365 )
366 UsageMetricCell(
367 label: "Unpriced",
368 value: UsageFormat.percent(merged.costQuality.unpricedShare),
369 detail: "of records, excluded from cost"
370 )
371 }
372 }
373 }
374
375 private var breakdownSection: some View {
376 UsageSection(title: "Breakdown") {
377 VStack(spacing: 4) {
378 Picker("Breakdown", selection: $breakdown) {
379 Text("Model").tag(UsageBreakdown.model)
380 Text(windowInput.resolution == .hour ? "Hour" : "Day")
381 .tag(UsageBreakdown.time)
382 }
383 .pickerStyle(.segmented)
384
385 if breakdown == .model {
386 modelBreakdown
387 } else {
388 timeBreakdown
389 }
390 }
391 }
392 }
393
394 @ViewBuilder
395 private var modelBreakdown: some View {
396 if merged.models.isEmpty {
397 noActivity
398 } else {
399 VStack(spacing: 0) {
400 ForEach(Array(merged.models.enumerated()), id: \.element.id) { index, model in
401 if index > 0 { usageDivider }
402 HStack(spacing: 12) {
403 Circle()
404 .fill(model.provider.color)
405 .frame(width: 10, height: 10)
406 VStack(alignment: .leading, spacing: 2) {
407 Text(model.model)
408 .font(T3Typography.threadBody)
409 .foregroundStyle(T3Colors.textPrimary)
410 .lineLimit(1)
411 Text(
412 "\(model.costShareLabel) · "
413 + "\(UsageFormat.tokens(model.totalTokens)) tokens"
414 )
415 .font(T3Typography.supporting)
416 .foregroundStyle(T3Colors.textSecondary)
417 }
418 Spacer(minLength: 8)
419 Text(model.costLabel)
420 .font(T3Typography.threadBody)
421 .monospacedDigit()
422 .foregroundStyle(T3Colors.textPrimary)
423 }
424 .padding(.vertical, 10)
425 }
426 }
427 }
428 }
429
430 @ViewBuilder
431 private var timeBreakdown: some View {
432 if presentation.periods.isEmpty {
433 noActivity
434 } else {
435 LazyVStack(spacing: 0) {
436 ForEach(Array(presentation.periods.enumerated()), id: \.element.id) { index, period in
437 if index > 0 { usageDivider }
438 HStack(spacing: 12) {
439 Text(period.label)
440 .font(T3Typography.threadBody)
441 .foregroundStyle(T3Colors.textPrimary)
442 Spacer(minLength: 8)
443 VStack(alignment: .trailing, spacing: 2) {
444 Text(UsageFormat.usd(period.costUsd))
445 .font(T3Typography.threadBody)
446 .monospacedDigit()
447 .foregroundStyle(T3Colors.textPrimary)
448 Text(UsageFormat.tokens(period.totalTokens))
449 .font(T3Typography.supporting)
450 .foregroundStyle(T3Colors.textSecondary)
451 }
452 }
453 .padding(.vertical, 10)
454 }
455 }
456 }
457 }
458
459 private var noActivity: some View {
460 Text("No activity in this window.")
461 .font(T3Typography.threadBody)
462 .foregroundStyle(T3Colors.textSecondary)
463 .frame(maxWidth: .infinity)
464 .padding(.vertical, 24)
465 }
466
467 private var usageDivider: some View {
468 Divider().overlay(T3Colors.separator)
469 }
470
471 private var hasCompatibleSummary: Bool {
472 environments.contains {
473 $0.summary.map {
474 isCompatibleUsageContractVersion($0.contractVersion, resolution: windowInput.resolution)
475 } == true
476 }
477 }
478
479 private var hasDailyOnlySummary: Bool {
480 windowInput.resolution == .hour
481 && environments.contains { $0.summary?.contractVersion == 3 }
482 }
483
484 private func load(refreshPricing: Bool = false) async {
485 let request = loadState.begin(days: loadState.windowDays)
486 defer { loadState.finish(request) }
487 do {
488 for try await result in client.usageSummaryUpdates(request.input, refreshPricing: refreshPricing) {
489 try Task.checkCancellation()
490 loadState.receive(result, for: request)
491 }
492 } catch is CancellationError {
493 return
494 } catch {
495 loadState.fail(error, for: request)
496 }
497 }
498}
499
500private struct UsagePeriodChart: View {
501 let segments: [UsageChartSegment]
502
503 var body: some View {
504 Chart(segments) { segment in
505 BarMark(
506 x: .value("Period", segment.period),
507 yStart: .value("Start", segment.start),
508 yEnd: .value("End", segment.end)
509 )
510 .foregroundStyle(segment.provider.color)
511 }
512 .chartXAxis(.hidden)
513 .chartYAxis(.hidden)
514 .chartLegend(.hidden)
515 }
516}
517
518private struct UsageSection<Content: View>: View {
519 let title: String
520 @ViewBuilder let content: Content
521
522 var body: some View {
523 VStack(alignment: .leading, spacing: 8) {
524 Text(title)
525 .font(T3Typography.navigationTitle)
526 .foregroundStyle(T3Colors.textPrimary)
527 .accessibilityAddTraits(.isHeader)
528 content
529 }
530 }
531}
532
533private struct UsageMetricCell: View {
534 let label: String
535 let value: String
536 let detail: String
537
538 var body: some View {
539 VStack(alignment: .leading, spacing: 2) {
540 Text(label)
541 .font(T3Typography.supporting)
542 .foregroundStyle(T3Colors.textSecondary)
543 Text(value)
544 .font(.title3.weight(.medium))
545 .monospacedDigit()
546 .foregroundStyle(T3Colors.textPrimary)
547 .lineLimit(1)
548 .minimumScaleFactor(0.7)
549 Text(detail)
550 .font(.caption)
551 .foregroundStyle(T3Colors.textTertiary)
552 .lineLimit(2)
553 }
554 .padding(.vertical, 8)
555 .padding(.trailing, 12)
556 .frame(maxWidth: .infinity, alignment: .leading)
557 }
558}
559
560private struct UsageProgressBar: View {
561 let value: Double
562 let color: Color
563
564 var body: some View {
565 GeometryReader { geometry in
566 ZStack(alignment: .leading) {
567 Capsule().fill(T3Colors.subtle)
568 Capsule()
569 .fill(color)
570 .frame(width: geometry.size.width * min(max(value, 0), 1))
571 }
572 }
573 .frame(height: 4)
574 .accessibilityHidden(true)
575 }
576}
577
578extension UsageProviderKind {
579 /// Claude's brand orange. Usage charts and limit bars share this one value.
580 static let claudeColor = Color(red: 0.851, green: 0.467, blue: 0.341)
581
582 var color: Color {
583 switch self {
584 case .codex: T3Colors.textPrimary
585 case .claude: Self.claudeColor
586 case .grok: T3Colors.textSecondary
587 }
588 }
589}