Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

UsageLimitsView.swift

541 lines23.1 KB

1import SwiftUI
2​
3struct UsageLimitsView: View {
4 let client: any FeatureClient
5 @Binding var resetCreditStates: [UsageResetCreditTarget: UsageResetCreditState]
6 /// The parent keeps this view mounted behind the usage tab. Only the visible
7 /// tab may add toolbar items.
8 var isActive = true
9​
10 @State private var environments: [FeatureEnvironmentUsageLimits] = []
11 @State private var groups: [UsageLimitsGroup] = []
12 @State private var pools: [UsageLimitPool] = []
13 @State private var showEnvironments = false
14 @State private var hasSnapshot = false
15 @State private var isRefreshing = false
16 @State private var streamError: String?
17 @State private var refreshError: String?
18 @State private var refreshErrors: [String: String] = [:]
19 @State private var now = Date()
20 @State private var subscriptionID = UUID()
21 /// Subscriptions start on the first visit and then outlive tab switches.
22 @State private var hasActivated = false
23​
24 private var hasLimits: Bool { groups.contains(where: \.hasLimits) }
25 private var isWaiting: Bool {
26 !hasSnapshot || (!environments.isEmpty && environments.allSatisfy {
27 $0.isPending && $0.providers.isEmpty && $0.sources.isEmpty
28 })
29 }
30​
31 var body: some View {
32 ScrollView {
33 LazyVStack(alignment: .leading, spacing: 24) {
34 Picker("Limits grouping", selection: $showEnvironments) {
35 Text("Pooled").tag(false)
36 Text("By environment").tag(true)
37 }
38 .pickerStyle(.segmented)
39 if let streamError { notice(streamError) }
40 if let refreshError { notice(refreshError) }
41 if isRefreshing {
42 notice("Refreshing limits...")
43 } else if hasLimits, environments.contains(where: \.isPending) {
44 notice("Some environments are still reporting limits.")
45 }
46​
47 if isWaiting, streamError == nil {
48 Text("Loading subscription limits")
49 .font(T3Typography.supporting)
50 .foregroundStyle(T3Colors.textTertiary)
51 .frame(maxWidth: .infinity)
52 .padding(.vertical, 64)
53 } else if environments.isEmpty {
54 ContentUnavailableView {
55 Label("No limits available", systemImage: "chart.bar.xaxis")
56 } description: {
57 Text("Connect an environment to see subscription limits.")
58 }
59 } else if showEnvironments {
60 ForEach(groups) { group in
61 environmentSection(group)
62 }
63 } else {
64 ForEach(environments) { environment in
65 if let error = refreshErrors[environment.id] {
66 notice("\(environment.label): Could not refresh limits. \(error)")
67 }
68 }
69 ForEach(Array(UsageLimitPooling.notices(environments).enumerated()), id: \.offset) { _, message in
70 notice(message)
71 }
72 ForEach(pools) { pool in
73 pooledSection(pool)
74 }
75 if pools.isEmpty {
76 notice("No provider reports subscription limits.")
77 }
78 }
79 }
80 .padding(.horizontal, 20)
81 .padding(.top, 12)
82 .padding(.bottom, 32)
83 }
84 .scrollIndicators(.hidden)
85 .refreshable { await refresh() }
86 .toolbar {
87 if isActive {
88 ToolbarItem(placement: .topBarTrailing) {
89 Button("Refresh limits", systemImage: "arrow.clockwise") {
90 Task { await refresh() }
91 }
92 .disabled(isRefreshing)
93 }
94 }
95 }
96 .onChange(of: isActive, initial: true) { _, active in
97 if active { hasActivated = true }
98 }
99 .task(id: hasActivated ? subscriptionID : nil) {
100 guard hasActivated else { return }
101 let subscription = subscriptionID
102 do {
103 for try await snapshot in client.usageLimitsUpdates() {
104 try Task.checkCancellation()
105 guard subscription == subscriptionID else { return }
106 receive(snapshot)
107 streamError = nil
108 }
109 } catch is CancellationError {
110 return
111 } catch {
112 streamError = "Could not load live limits. Refresh to check the latest values."
113 }
114 }
115 }
116​
117 private func pooledSection(_ pool: UsageLimitPool) -> some View {
118 VStack(alignment: .leading, spacing: 14) {
119 HStack(alignment: .firstTextBaseline) {
120 Text(UsageLimitsPresentation.providerLabel(driver: pool.driver))
121 .font(T3Typography.threadHeading3)
122 Spacer()
123 Text("\(pool.accounts.count) \(pool.accounts.count == 1 ? "account" : "accounts")")
124 .font(T3Typography.supporting)
125 .foregroundStyle(T3Colors.textSecondary)
126 }
127 ForEach(pool.windows) { window in
128 VStack(alignment: .leading, spacing: 4) {
129 HStack {
130 Text(window.label)
131 Spacer()
132 Text("\(window.remainingPercent)% left").monospacedDigit()
133 }
134 .font(T3Typography.supporting)
135 HStack(spacing: 3) {
136 ForEach(Array(window.columns.enumerated()), id: \.offset) { index, accountWindow in
137 VStack(alignment: .leading, spacing: 3) {
138 GeometryReader { geometry in
139 if let accountWindow {
140 let remaining = UsageLimitsMath.remainingPercent(accountWindow)
141 ZStack(alignment: .leading) {
142 Rectangle().fill(T3Colors.subtleStrong)
143 Rectangle().fill(remaining <= 10 ? T3Colors.danger : T3Colors.textPrimary)
144 .frame(width: geometry.size.width * remaining / 100)
145 }
146 }
147 }
148 .frame(height: 6)
149 Text(accountWindow.map { "\(index + 1): \(Int(UsageLimitsMath.remainingPercent($0)))%" } ?? "\(index + 1): N/A")
150 .font(.caption2)
151 .foregroundStyle(T3Colors.textSecondary)
152 .lineLimit(1)
153 }
154 .frame(maxWidth: .infinity)
155 }
156 }
157 HStack {
158 if let pace = window.pace { Text(pace.label) }
159 Spacer()
160 if let reset = window.resets.first(where: { $0.restoresPercent > 0 }) {
161 Text("+\(reset.restoresPercent)% on \(reset.at.formatted(date: .abbreviated, time: .shortened))")
162 }
163 }
164 .font(.caption)
165 .foregroundStyle(T3Colors.textSecondary)
166 }
167 .accessibilityElement(children: .combine)
168 }
169 ForEach(Array(pool.accounts.enumerated()), id: \.element.id) { index, account in
170 DisclosureGroup {
171 UsageLimitsAccountView(
172 driver: account.driver, instanceID: account.id,
173 label: account.label, detail: account.plan,
174 limits: account.limits, now: now
175 )
176 if let credits = account.limits.resetCredits {
177 if let redeem = account.redeem {
178 UsageResetCreditsView(
179 client: client, environmentID: redeem.environmentID,
180 input: redeem.input, isConnected: redeem.isConnected,
181 credits: credits, now: now,
182 state: resetState(environmentID: redeem.target.environmentID, account: redeem.target.account)
183 )
184 } else {
185 notice(UsageLimitsMath.creditSummary(credits, now: now))
186 }
187 }
188 } label: {
189 VStack(alignment: .leading, spacing: 2) {
190 HStack {
191 Text("\(index + 1)")
192 UsageAccountLabel(value: account.label)
193 }
194 .font(T3Typography.control)
195 Text(account.locationLabel)
196 .font(T3Typography.supporting)
197 .foregroundStyle(T3Colors.textSecondary)
198 }
199 }
200 .tint(T3Colors.textPrimary)
201 }
202 }
203 .foregroundStyle(T3Colors.textPrimary)
204 }
205​
206 private func environmentSection(_ group: UsageLimitsGroup) -> some View {
207 VStack(alignment: .leading, spacing: 14) {
208 Text(group.environment.label)
209 .font(T3Typography.threadHeading3)
210 .foregroundStyle(T3Colors.textPrimary)
211​
212 if let error = refreshErrors[group.id] {
213 notice("Could not refresh limits. \(error)")
214 }
215 if let error = group.environment.errorMessage,
216 error != refreshErrors[group.id] {
217 notice(error)
218 } else if !group.environment.isConnected, !group.environment.isPending {
219 notice(group.hasLimits
220 ? "Disconnected. Showing the last known limits."
221 : "Connect this environment to see limits.")
222 }
223​
224 if !group.hasLimits {
225 if group.environment.isPending {
226 notice("Waiting for this environment...")
227 } else if group.environment.isConnected, group.environment.errorMessage == nil {
228 notice("No provider reports subscription limits.")
229 }
230 }
231​
232 ForEach(Array(group.providers.enumerated()), id: \.element.instanceId) { index, provider in
233 if index > 0 { Divider().overlay(T3Colors.separator) }
234 if let limits = provider.usageLimits {
235 VStack(alignment: .leading, spacing: 12) {
236 UsageLimitsAccountView(
237 driver: provider.driver,
238 instanceID: provider.instanceId,
239 label: provider.displayName?.trimmingCharacters(in: .whitespacesAndNewlines)
240 .nonEmpty ?? UsageLimitsPresentation.providerLabel(driver: provider.driver),
241 detail: provider.auth.label,
242 limits: limits,
243 now: now
244 )
245 if let credits = limits.resetCredits {
246 UsageResetCreditsView(
247 client: client,
248 environmentID: group.environment.environmentID,
249 input: .provider(instanceID: provider.instanceId),
250 isConnected: group.environment.isConnected && !group.environment.isPending,
251 credits: credits,
252 now: now,
253 state: resetState(environmentID: group.id, account: .provider(provider.instanceId))
254 )
255 }
256 }
257 }
258 }
259​
260 ForEach(group.sources) { source in
261 sourceSection(source, environment: group.environment)
262 }
263 }
264 }
265​
266 private func sourceSection(_ row: UsageLimitSourceRows, environment: FeatureEnvironmentUsageLimits) -> some View {
267 VStack(alignment: .leading, spacing: 14) {
268 Text(row.source.label)
269 .font(T3Typography.control)
270 .foregroundStyle(T3Colors.textPrimary)
271 if let error = row.source.error {
272 notice(error)
273 } else if row.accounts.isEmpty {
274 notice(row.hiddenAccountCount > 0
275 ? "These accounts are shown by connected providers."
276 : "No accounts reported.")
277 } else {
278 ForEach(row.accounts) { account in
279 UsageLimitsAccountView(
280 driver: account.driver,
281 instanceID: account.id,
282 label: UsageLimitsPresentation.providerLabel(driver: account.driver),
283 detail: account.plan,
284 limits: account.usageLimits,
285 now: now
286 )
287 if let credits = account.usageLimits.resetCredits {
288 UsageResetCreditsView(
289 client: client,
290 environmentID: environment.id,
291 input: credits.nextCreditId.map {
292 .source(sourceID: row.id, accountID: account.id, creditID: $0)
293 },
294 isConnected: environment.isConnected && !environment.isPending,
295 credits: credits,
296 now: now,
297 state: resetState(
298 environmentID: environment.id,
299 account: .source(sourceID: row.id, accountID: account.id)
300 )
301 )
302 }
303 }
304 }
305 }
306 .padding(.top, 8)
307 }
308​
309 private func notice(_ message: String) -> some View {
310 Text(message)
311 .font(T3Typography.supporting)
312 .foregroundStyle(T3Colors.textSecondary)
313 .frame(maxWidth: .infinity, alignment: .leading)
314 }
315​
316 private func receive(_ snapshot: [FeatureEnvironmentUsageLimits]) {
317 environments = UsageLimitsPresentation.retainingPendingRows(snapshot, previous: environments)
318 groups = UsageLimitsPresentation.groups(environments)
319 hasSnapshot = true
320 now = Date()
321 pools = UsageLimitPooling.pools(UsageLimitPooling.accounts(environments), now: now)
322 let ids = Set(snapshot.map(\.environmentID))
323 refreshErrors = refreshErrors.filter { ids.contains($0.key) }
324 }
325​
326 private func refresh() async {
327 guard !isRefreshing else { return }
328 isRefreshing = true
329 refreshError = nil
330 refreshErrors = [:]
331 defer {
332 isRefreshing = false
333 // Each environment can end its own stream without throwing from
334 // the combined stream. Refresh must reconnect those failed streams.
335 if !Task.isCancelled { subscriptionID = UUID() }
336 }
337 do {
338 let result = try await client.refreshUsageLimits()
339 try Task.checkCancellation()
340 // Live config carries the new bars. Keep operation errors separate
341 // so a later config snapshot cannot silently remove them.
342 refreshErrors = Dictionary(uniqueKeysWithValues: result.compactMap { environment in
343 environment.errorMessage.map { (environment.environmentID, $0) }
344 })
345 if !hasSnapshot || streamError != nil { receive(result) }
346 now = Date()
347 } catch is CancellationError {
348 return
349 } catch {
350 refreshError = "Could not refresh limits. Showing the last known values."
351 }
352 }
353​
354 private func resetState(environmentID: String, account: UsageResetCreditTarget.Account) -> Binding<UsageResetCreditState> {
355 let target = UsageResetCreditTarget(environmentID: environmentID, account: account)
356 return Binding(
357 get: { resetCreditStates[target] ?? UsageResetCreditState() },
358 set: { resetCreditStates[target] = $0 }
359 )
360 }
362​
363private struct UsageLimitsAccountView: View {
364 let driver: String
365 let instanceID: String
366 let label: String
367 let detail: String?
368 let limits: ServerProviderUsageLimits
369 let now: Date
370​
371 var body: some View {
372 VStack(alignment: .leading, spacing: 12) {
373 HStack(alignment: .firstTextBaseline, spacing: 8) {
374 ProviderIcon(driver: driver, providerID: instanceID, fallbackName: label, size: 18)
375 UsageAccountLabel(value: label)
376 .font(T3Typography.control)
377 .foregroundStyle(T3Colors.textPrimary)
378 if let detail {
379 UsageAccountLabel(value: detail)
380 .font(T3Typography.supporting)
381 .foregroundStyle(T3Colors.textSecondary)
382 .lineLimit(2)
383 }
384 }
385 if let notice = UsageLimitsPresentation.limitsNotice(limits) {
386 Text(notice)
387 .font(T3Typography.supporting)
388 .foregroundStyle(T3Colors.textSecondary)
389 }
390 ForEach(UsageLimitsPresentation.visibleWindows(limits)) { window in
391 UsageLimitWindowView(window: window, driver: driver, now: now)
392 }
393 }
394 }
396​
397private struct UsageAccountLabel: View {
398 let value: String
399 @State private var isRevealed = false
400​
401 var body: some View {
402 if value.contains("@") {
403 Button {
404 isRevealed.toggle()
405 } label: {
406 Text(isRevealed ? value : "••••••@••••••")
407 }
408 .buttonStyle(.plain)
409 .accessibilityLabel(isRevealed ? "Hide account label" : "Reveal account label")
410 .onChange(of: value) { isRevealed = false }
411 } else {
412 Text(value)
413 }
414 }
416​
417private struct UsageLimitWindowView: View {
418 let window: ServerProviderUsageWindow
419 let driver: String
420 let now: Date
421​
422 var body: some View {
423 if window.resetsAt != nil {
424 TimelineView(.periodic(from: .now, by: 60)) { context in
425 content(now: context.date)
426 }
427 } else {
428 content(now: now)
429 }
430 }
431​
432 private func content(now: Date) -> some View {
433 let remaining = UsageLimitsMath.remainingPercent(window)
434 let timeLeft = UsageLimitsMath.elapsedShare(window, now: now).map { 1 - $0 }
435 let pace = UsageLimitsMath.pace(window, now: now)
436 let resetsIn = UsageLimitsMath.resetsIn(window, now: now)
437 return VStack(alignment: .leading, spacing: 4) {
438 HStack(alignment: .firstTextBaseline) {
439 Text(window.label)
440 Spacer(minLength: 8)
441 Text("\(Int(remaining))% left")
442 .monospacedDigit()
443 }
444 .font(T3Typography.supporting)
445 .foregroundStyle(T3Colors.textPrimary)
446​
447 GeometryReader { geometry in
448 ZStack(alignment: .leading) {
449 Capsule().fill(T3Colors.subtleStrong)
450 .frame(height: 6)
451 Capsule().fill(barColor(remaining: remaining))
452 .frame(width: geometry.size.width * remaining / 100, height: 6)
453 if let timeLeft {
454 Rectangle().fill(T3Colors.textSecondary)
455 .frame(width: 1, height: 12)
456 .offset(x: max(0, geometry.size.width - 1) * timeLeft)
457 }
458 }
459 .frame(height: 12)
460 }
461 .frame(height: 12)
462 .accessibilityHidden(true)
463​
464 if pace != nil || resetsIn != nil {
465 HStack(alignment: .firstTextBaseline) {
466 if let pace { Text(pace.label) }
467 Spacer(minLength: 8)
468 if let resetsIn { Text(resetsIn).monospacedDigit() }
469 }
470 .font(.caption)
471 .foregroundStyle(T3Colors.textTertiary)
472 }
473 }
474 .accessibilityElement(children: .combine)
475 }
476​
477 private func barColor(remaining: Double) -> Color {
478 if remaining <= 10 { return T3Colors.danger }
479 if remaining <= 30 { return T3Colors.warning }
480 return driver == "claudeAgent" ? UsageProviderKind.claudeColor : T3Colors.textPrimary
481 }
483​
484private struct UsageResetCreditsView: View {
485 let client: any FeatureClient
486 let environmentID: String
487 let input: ProviderConsumeResetCreditInput?
488 let isConnected: Bool
489 let credits: ServerProviderResetCredits
490 let now: Date
491 @Binding var state: UsageResetCreditState
492​
493 @State private var confirmationPresented = false
494 @State private var confirmedInput: ProviderConsumeResetCreditInput?
495​
496 var body: some View {
497 VStack(alignment: .leading, spacing: 8) {
498 Text(UsageLimitsMath.creditSummary(credits, now: now))
499 .font(T3Typography.supporting)
500 .foregroundStyle(T3Colors.textSecondary)
501 if (credits.availableCount > 0 && input != nil) || state.isPending {
502 Button(state.isPending ? "Using credit..." : "Use a reset credit") {
503 confirmedInput = input
504 confirmationPresented = true
505 }
506 .font(T3Typography.control)
507 .foregroundStyle(T3Colors.textPrimary)
508 .frame(minHeight: T3Metrics.minimumTapTarget, alignment: .leading)
509 .disabled(state.isPending || !isConnected)
510 }
511 if let status = state.statusMessage {
512 Text(status)
513 .font(T3Typography.supporting)
514 .foregroundStyle(T3Colors.textSecondary)
515 }
516 }
517 .alert("Use a reset credit?", isPresented: $confirmationPresented) {
518 Button("Cancel", role: .cancel) {}
519 Button("Use credit") { Task { await redeem() } }
520 } message: {
521 Text("This uses one credit on your account and clears the current rate-limit windows. You cannot undo it.")
522 }
523 }
524​
525 private func redeem() async {
526 // Live updates can replace the next credit while the confirmation is open.
527 // Send the credit the user saw, never a later one.
528 guard let confirmedInput,
529 state.begin(availableCount: credits.availableCount, isConnected: isConnected) else { return }
530 do {
531 let result = try await client.consumeResetCredit(environmentID: environmentID, input: confirmedInput)
532 state.finish(result.outcome, warning: result.warning)
533 } catch {
534 state.fail(error)
535 }
536 }
538​
539private extension String {
540 var nonEmpty: String? { isEmpty ? nil : self }