Open History to see the last commit
1import CryptoKit
2import Foundation
3import WidgetKit
4
5struct PlatformSubscriptionUsageObservationKey: Equatable {
6 struct Environment: Equatable {
7 let id: String
8 let name: String
9 let endpoint: String
10 let connectionState: FeatureConnection.State?
11 }
12
13 let isActive: Bool
14 let environments: [Environment]
15 let accountID: String?
16
17 init(isActive: Bool, environments: [FeatureEnvironment], accountID: String? = nil) {
18 self.isActive = isActive
19 self.accountID = accountID
20 self.environments = environments.map {
21 Environment(id: $0.id, name: $0.name, endpoint: $0.endpoint, connectionState: $0.connectionState)
22 }
23 }
24
25 var scopeID: String {
26 let identifiers = [accountID ?? ""] + environments.sorted { $0.id < $1.id }.flatMap { [$0.id, $0.endpoint] }
27 // Length prefixes make the digest unambiguous even when an identifier
28 // contains a separator. Neither labels nor transient connection state
29 // change which account data the saved snapshot belongs to.
30 let input = identifiers.map { "\($0.utf8.count):\($0)" }.joined()
31 return SHA256.hash(data: Data(input.utf8)).map { String(format: "%02x", $0) }.joined()
32 }
33}
34
35enum PlatformSubscriptionUsageSnapshot {
36 static func retainingPendingSnapshot(
37 _ incoming: T3SubscriptionUsageSnapshot,
38 previous: T3SubscriptionUsageSnapshot?,
39 isPending: Bool
40 ) -> T3SubscriptionUsageSnapshot {
41 guard isPending, let scopeID = incoming.scopeID,
42 let previous, previous.scopeID == scopeID,
43 previous.providers.contains(where: { !$0.windows.isEmpty }) else { return incoming }
44 // Pooled display values have no per-environment contributions to merge.
45 // Keep the whole saved reading until every environment answers.
46 return T3SubscriptionUsageSnapshot(providers: previous.providers.map {
47 var provider = $0
48 provider.hasPartialData = true
49 return provider
50 }, scopeID: scopeID)
51 }
52
53 static func make(_ environments: [FeatureEnvironmentUsageLimits]) -> T3SubscriptionUsageSnapshot {
54 let pools = UsageLimitPooling.pools(UsageLimitPooling.accounts(environments), now: .distantPast)
55 return T3SubscriptionUsageSnapshot(providers: ["codex", "claudeAgent"].map { driver in
56 let pool = pools.first { $0.driver == driver }
57 let checked = pool?.accounts.map { UsageFormat.isoDate($0.limits.checkedAt) } ?? []
58 let checkedAt = checked.contains(where: { $0 == nil }) ? nil : checked.compactMap { $0 }.min()
59 let expiresAt = checkedAt.map { checkedAt in
60 min(checkedAt.addingTimeInterval(15 * 60), pool?.windows.flatMap(\.resets).map(\.at).min() ?? .distantFuture)
61 }
62 let ordered = pool?.windows.sorted { $0.remainingPercent < $1.remainingPercent } ?? []
63 let primary = [ordered.first { $0.kind == .session }, ordered.first { $0.kind == .weekly }].compactMap { $0 }
64 let selected = Array((primary + ordered.filter { row in !primary.contains(where: { $0.id == row.id }) }).prefix(6))
65 .sorted { $0.remainingPercent < $1.remainingPercent }
66 let partial = environments.contains { environment in
67 environment.isPending || !environment.isConnected || environment.errorMessage != nil
68 || environment.sources.contains { source in
69 source.error != nil || source.accounts.contains {
70 $0.driver == driver && $0.usageLimits.unavailable?.reason != .unsupported
71 && UsageLimitsPresentation.limitsNotice($0.usageLimits) != nil
72 }
73 }
74 || UsageLimitsPresentation.providersWithLimits(environment.providers).contains {
75 $0.driver == driver && $0.usageLimits?.unavailable?.reason != .unsupported
76 && $0.usageLimits.map { UsageLimitsPresentation.limitsNotice($0) != nil } == true
77 }
78 }
79 return .init(
80 id: driver, name: UsageLimitsPresentation.providerLabel(driver: driver),
81 accountCount: pool?.accounts.count ?? 0,
82 checkedAt: checkedAt, expiresAt: expiresAt,
83 windows: selected.map { window in
84 .init(id: window.id, kind: window.kind.rawValue, label: String(window.label.prefix(120)), remaining: window.remainingPercent, resetAt: window.resets.first?.at)
85 },
86 totalWindows: ordered.count, hasPartialData: partial
87 )
88 })
89 }
90}
91
92/// The foreground host observes config updates and makes one refresh attempt on
93/// activation. No timer, background socket, or widget-owned transport is needed.
94@MainActor
95final class PlatformSubscriptionUsageCoordinator {
96 // The writer outlives views. Its ordering must outlive their coordinators too.
97 private static var nextGeneration = 0
98 private var environments: [FeatureEnvironmentUsageLimits] = []
99 private var generation = 0
100 private var lastRefresh: Date?
101 private var lastRefreshEnvironmentIDs: Set<String> = []
102 private var scopeID: String?
103 private var previousSnapshot: T3SubscriptionUsageSnapshot?
104
105 func observe(client: any FeatureClient, key: PlatformSubscriptionUsageObservationKey) async {
106 Self.nextGeneration += 1
107 generation = Self.nextGeneration
108 let currentGeneration = generation
109 let environmentIDs = key.environments.map(\.id)
110 if scopeID != key.scopeID {
111 environments = []
112 lastRefresh = nil
113 scopeID = key.scopeID
114 }
115 let savedSnapshot = await PlatformSubscriptionUsageWriter.shared.load()
116 guard !Task.isCancelled, generation == currentGeneration else { return }
117 previousSnapshot = savedSnapshot
118 environments = UsageLimitsPresentation.retainingPendingRows(key.environments.map {
119 .init(environmentID: $0.id, label: $0.name, isPending: true)
120 }, previous: environments)
121 await publish()
122 guard !environmentIDs.isEmpty else { return }
123 let hasWidget = await withCheckedContinuation { continuation in
124 WidgetCenter.shared.getCurrentConfigurations { result in
125 continuation.resume(returning: (try? result.get())?.contains {
126 $0.kind == T3SubscriptionUsageSnapshotStore.kind
127 } ?? false)
128 }
129 }
130 guard hasWidget, !Task.isCancelled, generation == currentGeneration else { return }
131
132 // Bound probes across rapid scene and connection changes.
133 let currentIDs = Set(environmentIDs)
134 let shouldRefresh = !currentIDs.isSubset(of: lastRefreshEnvironmentIDs)
135 || (lastRefresh.map { Date().timeIntervalSince($0) >= 5 * 60 } ?? true)
136 if shouldRefresh {
137 lastRefresh = Date()
138 lastRefreshEnvironmentIDs = currentIDs
139 }
140 let refreshTask: Task<Void, Never>? = shouldRefresh ? Task { @MainActor in
141 // Refresh emits config events. Do not overwrite newer stream
142 // data with the operation result if the two complete out of order.
143 _ = try? await client.refreshUsageLimits()
144 } : nil
145 await withTaskCancellationHandler {
146 do {
147 for try await rows in client.usageLimitsUpdates() {
148 guard !Task.isCancelled, generation == currentGeneration else { break }
149 environments = UsageLimitsPresentation.retainingPendingRows(rows, previous: environments)
150 await publish()
151 }
152 } catch {
153 guard !Task.isCancelled, generation == currentGeneration else { return }
154 environments = environments.map {
155 .init(environmentID: $0.id, label: $0.label, providers: $0.providers, sources: $0.sources,
156 isConnected: false, errorMessage: "Could not read limits.")
157 }
158 await publish()
159 }
160 } onCancel: {
161 refreshTask?.cancel()
162 }
163 refreshTask?.cancel()
164 await refreshTask?.value
165 }
166
167 private func publish() async {
168 var incoming = PlatformSubscriptionUsageSnapshot.make(environments)
169 incoming.scopeID = scopeID
170 let snapshot = PlatformSubscriptionUsageSnapshot.retainingPendingSnapshot(
171 incoming, previous: previousSnapshot, isPending: environments.contains(where: \.isPending)
172 )
173 let saved = await PlatformSubscriptionUsageWriter.shared.save(snapshot, generation: generation)
174 if saved { WidgetCenter.shared.reloadTimelines(ofKind: T3SubscriptionUsageSnapshotStore.kind) }
175 }
176}
177
178private actor PlatformSubscriptionUsageWriter {
179 static let shared = PlatformSubscriptionUsageWriter()
180 private var generation = 0
181 private var previous: T3SubscriptionUsageSnapshot?
182
183 func load() -> T3SubscriptionUsageSnapshot {
184 previous ?? T3SubscriptionUsageSnapshotStore.load()
185 }
186
187 func save(_ snapshot: T3SubscriptionUsageSnapshot, generation: Int) -> Bool {
188 guard generation >= self.generation else { return false }
189 self.generation = generation
190 guard snapshot != previous else { return false }
191 do {
192 try T3SubscriptionUsageSnapshotStore.save(snapshot)
193 previous = snapshot
194 return true
195 } catch { return false }
196 }
197}