feat(swift-ios): add usage analytics (#5933)

This commit is contained in:
Theo Browne authored and GitHub committed 2026-08-09 23:14:00 -07:00
1 parent 497f54f3e6
commit 7541fca317
9 files changed
+1344

No files matched your search

@@ -397,6 +397,56 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
await clearActiveEnvironment()
}
func usageSummaries(_ input: UsageSummaryInput) async throws -> [FeatureEnvironmentUsage] {
let environments = try await runtime.environments()
let runtime = runtime
let order = Dictionary(uniqueKeysWithValues: environments.enumerated().map {
($0.element.id, $0.offset)
})
let results = try await withThrowingTaskGroup(
of: FeatureEnvironmentUsage.self,
returning: [FeatureEnvironmentUsage].self
) { group in
for environment in environments {
group.addTask {
let probe = await runtime.ephemeralClient(for: environment)
do {
let summary = try await probe.usageSummary(input)
await probe.disconnect()
return FeatureEnvironmentUsage(
environmentID: environment.id,
label: environment.label,
summary: summary,
errorMessage: nil
)
} catch is CancellationError {
await probe.disconnect()
throw CancellationError()
} catch {
await probe.disconnect()
return FeatureEnvironmentUsage(
environmentID: environment.id,
label: environment.label,
summary: nil,
errorMessage: "This environment could not report usage."
)
}
}
}
var results: [FeatureEnvironmentUsage] = []
results.reserveCapacity(environments.count)
for try await result in group {
results.append(result)
}
return results
}
return results.sorted {
order[$0.environmentID, default: .max] < order[$1.environmentID, default: .max]
}
}
private func adoptEnvironment(
_ environment: Environment,
client newClient: T3Client
+9
View File
@@ -93,6 +93,14 @@ public actor T3Client {
)
}
public func usageSummary(_ input: UsageSummaryInput) async throws -> UsageSummary {
try await rpc.request(
RPCMethod.serverGetUsageSummary.rawValue,
payload: try JSONValue.encode(input),
as: UsageSummary.self
)
}
public func serverConfigEvents() async
-> AsyncThrowingStream<ServerConfigStreamEvent, Error>
{
@@ -1220,6 +1228,7 @@ public actor EnvironmentRuntime {
public enum RPCMethod: String, Sendable {
case serverProbe = "server.probe"
case serverGetConfig = "server.getConfig"
case serverGetUsageSummary = "server.getUsageSummary"
case dispatchCommand = "orchestration.dispatchCommand"
case getArchivedShellSnapshot = "orchestration.getArchivedShellSnapshot"
case subscribeShell = "orchestration.subscribeShell"
+103
View File
@@ -0,0 +1,103 @@
import Foundation
public let usageContractVersion = 3
public enum UsageProviderKind: String, Codable, CaseIterable, Sendable {
case codex
case claude
public var displayName: String {
switch self {
case .codex: "Codex"
case .claude: "Claude Code"
}
}
}
public enum UsageCostSource: String, Codable, Sendable {
case providerReported
case modelPriced
case unpriced
}
public struct UsageSummaryInput: Codable, Equatable, Sendable {
public let sinceDay: String
public let untilDay: String
public let timeZone: String
public init(sinceDay: String, untilDay: String, timeZone: String) {
self.sinceDay = sinceDay
self.untilDay = untilDay
self.timeZone = timeZone
}
}
public struct UsageTokenTotals: Codable, Equatable, Sendable {
public let uncachedInputTokens: Int
public let cachedInputTokens: Int
public let cacheCreationTokens: Int
public let outputTokens: Int
public let reasoningTokens: Int
}
public struct UsageBucket: Codable, Equatable, Sendable {
public let day: String
public let provider: UsageProviderKind
public let model: String
public let totals: UsageTokenTotals
public let costUsd: Double
public let cacheSavingsUsd: Double
public let costSource: UsageCostSource
public let records: Int
public let unpricedRecords: Int
public let sessions: Int
}
public struct UsageSourceFingerprint: Codable, Equatable, Hashable, Sendable {
public let hostId: String
public let provider: UsageProviderKind
public let resolvedHomePath: String
public let volumeId: String
}
public enum UsageSourceStatus: String, Codable, Sendable {
case ok
case missing
case partial
case failed
}
public struct UsageSource: Codable, Equatable, Sendable {
public let fingerprint: UsageSourceFingerprint
public let status: UsageSourceStatus
public let scannedFiles: Int
public let skippedFiles: Int
public let malformedRecords: Int
public let distinctSessions: Int
public let message: String?
}
public enum UsagePricingStatus: String, Codable, Sendable {
case fresh
case cached
case unavailable
}
public struct UsagePricing: Codable, Equatable, Sendable {
public let status: UsagePricingStatus
public let source: String
public let fetchedAt: String?
public let knownModels: Int
}
public struct UsageSummary: Codable, Equatable, Sendable {
public let contractVersion: Int
public let readAt: String
public let timeZone: String
public let sinceDay: String
public let untilDay: String
public let buckets: [UsageBucket]
public let sources: [UsageSource]
public let pricing: UsagePricing
public let scanDurationMs: Int
}
@@ -29,6 +29,7 @@ public struct SettingsView: View {
LazyVStack(alignment: .leading, spacing: 28) {
connectionSection
t3ConnectSection
generalSection
agentSection
preferencesSection
aboutSection
@@ -250,6 +251,20 @@ public struct SettingsView: View {
}
}
private var generalSection: some View {
SettingsSection(title: "General") {
NavigationLink {
UsageView(client: model.client)
} label: {
SettingsNavigationRow(
title: "Usage",
systemImage: "chart.bar.xaxis"
)
}
.buttonStyle(.plain)
}
}
private var t3ConnectSection: some View {
SettingsSection(
title: "T3 Connect",
@@ -86,6 +86,8 @@ public protocol FeatureClient: AnyObject {
func saveSettings(_ settings: FeatureSettings) async throws
func usageSummaries(_ input: UsageSummaryInput) async throws -> [FeatureEnvironmentUsage]
func cachedProjectFavicon(
environmentID: String,
workspaceRoot: String
@@ -154,6 +156,9 @@ public extension FeatureClient {
func removeEnvironment(id: String) async throws {}
func disconnect() async {}
func addProject(path: String) async throws {}
func usageSummaries(_ input: UsageSummaryInput) async throws -> [FeatureEnvironmentUsage] {
[]
}
func cachedProjectFavicon(environmentID: String, workspaceRoot: String) async -> Data? {
nil
}
@@ -0,0 +1,369 @@
import Foundation
public struct FeatureEnvironmentUsage: Identifiable, Equatable, Sendable {
public let environmentID: String
public let label: String
public let summary: UsageSummary?
public let errorMessage: String?
public var id: String { environmentID }
public init(
environmentID: String,
label: String,
summary: UsageSummary?,
errorMessage: String?
) {
self.environmentID = environmentID
self.label = label
self.summary = summary
self.errorMessage = errorMessage
}
}
struct UsageProviderTotals: Identifiable, Equatable {
let provider: UsageProviderKind
let costUsd: Double
let totalTokens: Int
let records: Int
let costShare: Double
let tokenShare: Double
var id: UsageProviderKind { provider }
}
struct UsageModelTotals: Identifiable, Equatable {
let model: String
let provider: UsageProviderKind
let costUsd: Double
let totalTokens: Int
let records: Int
let costShare: Double
var id: String { "\(provider.rawValue):\(model)" }
}
struct UsageProviderValue: Equatable {
var costUsd = 0.0
var totalTokens = 0
}
struct UsageDailyTotals: Identifiable, Equatable {
let day: String
let costUsd: Double
let totalTokens: Int
let byProvider: [UsageProviderKind: UsageProviderValue]
var id: String { day }
}
struct UsageCostQuality: Equatable {
let providerReportedShare: Double
let modelPricedShare: Double
let unpricedShare: Double
let cacheSavingsUsd: Double
}
struct MergedUsage: Equatable {
var costUsd = 0.0
var uncachedInputTokens = 0
var cachedInputTokens = 0
var cacheCreationTokens = 0
var outputTokens = 0
var reasoningTokens = 0
var totalTokens = 0
var records = 0
var sessions = 0
var providers: [UsageProviderTotals] = []
var models: [UsageModelTotals] = []
var daily: [UsageDailyTotals] = []
var costQuality = UsageCostQuality(
providerReportedShare: 0,
modelPricedShare: 0,
unpricedShare: 0,
cacheSavingsUsd: 0
)
var duplicateSources: [String] = []
var contributingEnvironments: [String] = []
var staleEnvironments: [String] = []
}
enum UsageMerger {
private struct OwnedContribution {
let buckets: [UsageBucket]
let sessions: Int
}
private struct ProviderAccumulator {
var costUsd = 0.0
var totalTokens = 0
var records = 0
}
private struct ModelAccumulator {
let provider: UsageProviderKind
var costUsd = 0.0
var totalTokens = 0
var records = 0
}
private struct DailyAccumulator {
var costUsd = 0.0
var totalTokens = 0
var byProvider: [UsageProviderKind: UsageProviderValue] = [:]
}
static func merge(
_ environments: [FeatureEnvironmentUsage],
expectedContractVersion: Int = usageContractVersion
) -> MergedUsage {
let available = environments.compactMap { environment -> (FeatureEnvironmentUsage, UsageSummary)? in
guard let summary = environment.summary else { return nil }
return (environment, summary)
}
let current = available.filter { $0.1.contractVersion == expectedContractVersion }
let staleEnvironmentIDs = available.compactMap { environment, summary in
summary.contractVersion == expectedContractVersion ? nil : environment.environmentID
}
let claims = claimSources(current)
var result = MergedUsage()
result.duplicateSources = claims.duplicates
result.staleEnvironments = staleEnvironmentIDs
var cacheSavingsUsd = 0.0
var providerReportedRecords = 0
var unpricedRecords = 0
var providers: [UsageProviderKind: ProviderAccumulator] = [:]
var models: [String: ModelAccumulator] = [:]
var daily: [String: DailyAccumulator] = [:]
for (environment, summary) in current {
let contribution = ownedContribution(
environment: environment,
summary: summary,
ownerByFingerprint: claims.ownerByFingerprint
)
if !contribution.buckets.isEmpty {
result.contributingEnvironments.append(environment.environmentID)
}
result.sessions += contribution.sessions
for bucket in contribution.buckets {
let tokens = totalTokens(bucket)
result.costUsd += bucket.costUsd
result.uncachedInputTokens += bucket.totals.uncachedInputTokens
result.cachedInputTokens += bucket.totals.cachedInputTokens
result.cacheCreationTokens += bucket.totals.cacheCreationTokens
result.outputTokens += bucket.totals.outputTokens
result.reasoningTokens += bucket.totals.reasoningTokens
result.records += bucket.records
cacheSavingsUsd += bucket.cacheSavingsUsd
unpricedRecords += bucket.unpricedRecords
if bucket.costSource == .providerReported {
providerReportedRecords += bucket.records
}
var provider = providers[bucket.provider] ?? ProviderAccumulator()
provider.costUsd += bucket.costUsd
provider.totalTokens += tokens
provider.records += bucket.records
providers[bucket.provider] = provider
let modelKey = "\(bucket.provider.rawValue) \(bucket.model)"
var model = models[modelKey] ?? ModelAccumulator(provider: bucket.provider)
model.costUsd += bucket.costUsd
model.totalTokens += tokens
model.records += bucket.records
models[modelKey] = model
var day = daily[bucket.day] ?? DailyAccumulator()
day.costUsd += bucket.costUsd
day.totalTokens += tokens
var dayProvider = day.byProvider[bucket.provider] ?? UsageProviderValue()
dayProvider.costUsd += bucket.costUsd
dayProvider.totalTokens += tokens
day.byProvider[bucket.provider] = dayProvider
daily[bucket.day] = day
}
}
result.totalTokens = result.uncachedInputTokens
+ result.cachedInputTokens
+ result.cacheCreationTokens
+ result.outputTokens
result.providers = providers.map { provider, totals in
UsageProviderTotals(
provider: provider,
costUsd: totals.costUsd,
totalTokens: totals.totalTokens,
records: totals.records,
costShare: result.costUsd == 0 ? 0 : totals.costUsd / result.costUsd,
tokenShare: result.totalTokens == 0
? 0
: Double(totals.totalTokens) / Double(result.totalTokens)
)
}
.sorted { $0.costUsd > $1.costUsd }
result.models = models.map { key, totals in
UsageModelTotals(
model: String(key.split(separator: " ", maxSplits: 1).last ?? ""),
provider: totals.provider,
costUsd: totals.costUsd,
totalTokens: totals.totalTokens,
records: totals.records,
costShare: result.costUsd == 0 ? 0 : totals.costUsd / result.costUsd
)
}
.sorted {
$0.costUsd == $1.costUsd
? $0.totalTokens > $1.totalTokens
: $0.costUsd > $1.costUsd
}
result.daily = daily.map { day, totals in
UsageDailyTotals(
day: day,
costUsd: totals.costUsd,
totalTokens: totals.totalTokens,
byProvider: totals.byProvider
)
}
.sorted { $0.day < $1.day }
result.costQuality = UsageCostQuality(
providerReportedShare: result.records == 0
? 0
: Double(providerReportedRecords) / Double(result.records),
modelPricedShare: result.records == 0
? 0
: Double(result.records - providerReportedRecords - unpricedRecords)
/ Double(result.records),
unpricedShare: result.records == 0
? 0
: Double(unpricedRecords) / Double(result.records),
cacheSavingsUsd: cacheSavingsUsd
)
return result
}
private static func claimSources(
_ environments: [(FeatureEnvironmentUsage, UsageSummary)]
) -> (ownerByFingerprint: [UsageSourceFingerprint: String], duplicates: [String]) {
var selected: [
UsageSourceFingerprint: (environmentID: String, status: UsageSourceStatus)
] = [:]
var duplicates: [String] = []
let ordered = environments.sorted { $0.0.environmentID < $1.0.environmentID }
for (environment, summary) in ordered {
for source in summary.sources where source.status != .missing {
if let current = selected[source.fingerprint] {
if source.status.ownershipPriority > current.status.ownershipPriority {
selected[source.fingerprint] = (environment.environmentID, source.status)
}
} else {
selected[source.fingerprint] = (environment.environmentID, source.status)
}
}
}
let owners = selected.mapValues(\.environmentID)
for (environment, summary) in ordered {
for source in summary.sources where source.status != .missing {
if owners[source.fingerprint] != environment.environmentID {
duplicates.append(
"\(environment.label): \(source.fingerprint.resolvedHomePath)"
)
}
}
}
return (owners, duplicates)
}
private static func ownedContribution(
environment: FeatureEnvironmentUsage,
summary: UsageSummary,
ownerByFingerprint: [UsageSourceFingerprint: String]
) -> OwnedContribution {
var providers: Set<UsageProviderKind> = []
var sessions = 0
for source in summary.sources where source.status != .missing {
if ownerByFingerprint[source.fingerprint] == environment.environmentID {
providers.insert(source.fingerprint.provider)
sessions += source.distinctSessions
}
}
return OwnedContribution(
buckets: summary.buckets.filter { providers.contains($0.provider) },
sessions: sessions
)
}
private static func totalTokens(_ bucket: UsageBucket) -> Int {
bucket.totals.uncachedInputTokens
+ bucket.totals.cachedInputTokens
+ bucket.totals.cacheCreationTokens
+ bucket.totals.outputTokens
}
}
private extension UsageSourceStatus {
var ownershipPriority: Int {
switch self {
case .missing: 0
case .failed: 1
case .partial: 2
case .ok: 3
}
}
}
enum UsageWindow {
static func make(
days: Int,
now: Date = Date(),
timeZone: TimeZone = .current
) -> UsageSummaryInput {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
let until = calendar.startOfDay(for: now)
let since = calendar.date(byAdding: .day, value: -(days - 1), to: until) ?? until
let formatter = DateFormatter()
formatter.calendar = calendar
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = timeZone
formatter.dateFormat = "yyyy-MM-dd"
return UsageSummaryInput(
sinceDay: formatter.string(from: since),
untilDay: formatter.string(from: until),
timeZone: timeZone.identifier
)
}
static func days(in input: UsageSummaryInput) -> [String] {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let parser = DateFormatter()
parser.calendar = calendar
parser.locale = Locale(identifier: "en_US_POSIX")
parser.timeZone = TimeZone(secondsFromGMT: 0)
parser.dateFormat = "yyyy-MM-dd"
guard let start = parser.date(from: input.sinceDay),
let end = parser.date(from: input.untilDay),
start <= end else {
return []
}
var result: [String] = []
var cursor = start
while cursor <= end {
result.append(parser.string(from: cursor))
guard let next = calendar.date(
byAdding: .day,
value: 1,
to: cursor
) else { break }
cursor = next
}
return result
}
}
@@ -0,0 +1,554 @@
import Charts
import SwiftUI
private enum UsageMetric: String, CaseIterable, Identifiable {
case cost
case tokens
var id: Self { self }
var label: String { rawValue.uppercased() }
}
public struct UsageView: View {
private let client: any FeatureClient
@State private var windowDays = 30
@State private var windowInput = UsageWindow.make(days: 30)
@State private var metric = UsageMetric.cost
@State private var environments: [FeatureEnvironmentUsage] = []
@State private var merged = MergedUsage()
@State private var isLoading = true
@State private var errorMessage: String?
@State private var activeLoadID: UUID?
public init(client: any FeatureClient) {
self.client = client
}
public var body: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: 24) {
Picker("Usage window", selection: $windowDays) {
Text("7 days").tag(7)
Text("30 days").tag(30)
Text("90 days").tag(90)
}
.pickerStyle(.segmented)
.tint(T3Colors.textPrimary)
coverageNotice
if isLoading, environments.isEmpty {
Text("Scanning provider transcripts…")
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textSecondary)
.frame(maxWidth: .infinity)
.padding(.vertical, 64)
} else if let errorMessage, environments.isEmpty {
ContentUnavailableView {
Label("Couldn’t load usage", systemImage: "exclamationmark.circle")
} description: {
Text(errorMessage)
} actions: {
Button("Try again") { Task { await load(input: windowInput) } }
}
} else if environments.isEmpty {
ContentUnavailableView {
Label("No environments", systemImage: "chart.bar.xaxis")
} description: {
Text("Connect an environment to see usage.")
}
} else if !hasCompatibleSummary {
ContentUnavailableView {
Label("Couldn’t load usage", systemImage: "exclamationmark.circle")
} description: {
Text("No compatible usage data is available.")
} actions: {
Button("Try again") { Task { await load(input: windowInput) } }
}
} else {
chartCard
providersSection
totalsSection
modelsSection
}
}
.padding(.horizontal, 20)
.padding(.top, 16)
.padding(.bottom, 32)
}
.scrollIndicators(.hidden)
.refreshable { await load(input: windowInput) }
.background(T3Colors.background)
.navigationTitle("Usage")
.navigationBarTitleDisplayMode(.inline)
.toolbar(.visible, for: .navigationBar)
.t3NavigationChrome()
.task(id: windowDays) {
await load(input: UsageWindow.make(days: windowDays))
}
}
@ViewBuilder
private var coverageNotice: some View {
let failed = environments.filter { $0.errorMessage != nil }
let stale = environments.filter { merged.staleEnvironments.contains($0.environmentID) }
let hasRefreshError = errorMessage != nil && hasCompatibleSummary
if hasRefreshError
|| !failed.isEmpty
|| !stale.isEmpty
|| !merged.duplicateSources.isEmpty {
VStack(alignment: .leading, spacing: 6) {
if hasRefreshError {
Text("Couldn’t refresh usage. The totals below are from the last successful scan.")
}
ForEach(failed) { environment in
Text("\(environment.label) could not report usage.")
}
ForEach(stale) { environment in
Text("\(environment.label) runs an older server version and is excluded from totals.")
}
if !merged.duplicateSources.isEmpty {
Text(
"Counted once across environments sharing a transcript directory: "
+ merged.duplicateSources.joined(separator: ", ")
)
}
}
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textSecondary)
.padding(14)
.frame(maxWidth: .infinity, alignment: .leading)
.background(T3Colors.surface, in: RoundedRectangle(cornerRadius: 16))
}
}
private var chartCard: some View {
VStack(alignment: .leading, spacing: 16) {
HStack(alignment: .top, spacing: 12) {
VStack(alignment: .leading, spacing: 2) {
Text(metric == .cost ? "Raw token cost" : "Processed tokens")
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textSecondary)
Text(
metric == .cost
? "\(UsageFormat.usd(merged.costUsd))*"
: UsageFormat.tokens(merged.totalTokens)
)
.font(.system(.largeTitle, design: .default, weight: .bold))
.monospacedDigit()
.foregroundStyle(T3Colors.textPrimary)
.lineLimit(1)
.minimumScaleFactor(0.55)
Text(
metric == .cost
? "* if billed at full API rate"
: "Across \(UsageFormat.count(merged.sessions)) sessions"
)
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textSecondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
Picker("Chart metric", selection: $metric) {
ForEach(UsageMetric.allCases) { option in
Text(option.label).tag(option)
}
}
.pickerStyle(.segmented)
.fixedSize()
.tint(T3Colors.textPrimary)
}
if merged.daily.contains(where: {
metric == .cost ? $0.costUsd > 0 : $0.totalTokens > 0
}) {
UsageDailyChart(
input: windowInput,
daily: merged.daily,
metric: metric
)
.frame(height: 180)
} else {
Text("No activity in this window.")
.font(T3Typography.threadBody)
.foregroundStyle(T3Colors.textSecondary)
.frame(maxWidth: .infinity, minHeight: 180)
}
HStack(spacing: 8) {
Text(UsageFormat.dayShort(windowInput.sinceDay))
.frame(maxWidth: .infinity, alignment: .leading)
HStack(spacing: 14) {
ForEach(merged.providers) { provider in
HStack(spacing: 5) {
Circle()
.fill(provider.provider.color)
.frame(width: 8, height: 8)
Text(provider.provider.displayName)
}
}
}
.fixedSize()
Text(UsageFormat.dayShort(windowInput.untilDay))
.frame(maxWidth: .infinity, alignment: .trailing)
}
.font(.caption)
.foregroundStyle(T3Colors.textTertiary)
}
.padding(16)
.background(T3Colors.surface, in: RoundedRectangle(cornerRadius: 24))
}
@ViewBuilder
private var providersSection: some View {
if !merged.providers.isEmpty {
UsageSection(title: "Providers") {
let ordered = merged.providers.sorted {
metric == .cost
? $0.costUsd > $1.costUsd
: $0.totalTokens > $1.totalTokens
}
VStack(spacing: 0) {
ForEach(Array(ordered.enumerated()), id: \.element.id) { index, provider in
if index > 0 { usageDivider }
let share = metric == .cost ? provider.costShare : provider.tokenShare
VStack(alignment: .leading, spacing: 9) {
HStack(alignment: .firstTextBaseline, spacing: 10) {
Circle()
.fill(provider.provider.color)
.frame(width: 10, height: 10)
Text(provider.provider.displayName)
.font(.title3)
.foregroundStyle(T3Colors.textPrimary)
Spacer(minLength: 8)
Text(
metric == .cost
? UsageFormat.usd(provider.costUsd)
: UsageFormat.tokens(provider.totalTokens)
)
.font(.title3)
.monospacedDigit()
.foregroundStyle(T3Colors.textPrimary)
}
UsageProgressBar(value: share, color: provider.provider.color)
Text(
metric == .cost
? "\(UsageFormat.percent(share)) of cost · "
+ "\(UsageFormat.tokens(provider.totalTokens)) tokens"
: "\(UsageFormat.percent(share)) of tokens · \(UsageFormat.usd(provider.costUsd))"
)
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textSecondary)
}
.padding(16)
}
}
.usageCard()
}
}
}
private var totalsSection: some View {
UsageSection(title: "Totals") {
let activeDays = merged.daily.filter { $0.totalTokens > 0 }.count
let dailyAverage = activeDays == 0 ? 0 : merged.totalTokens / activeDays
let observedInput = merged.uncachedInputTokens + merged.cachedInputTokens
let cachedShare = observedInput == 0
? 0
: Double(merged.cachedInputTokens) / Double(observedInput)
LazyVGrid(
columns: [GridItem(.flexible(), alignment: .topLeading), GridItem(.flexible(), alignment: .topLeading)],
alignment: .leading,
spacing: 0
) {
UsageMetricCell(
label: "Processed tokens",
value: UsageFormat.tokens(merged.totalTokens),
detail: "\(UsageFormat.tokens(dailyAverage)) per active day"
)
UsageMetricCell(
label: "Cache savings",
value: UsageFormat.usd(merged.costQuality.cacheSavingsUsd),
detail: merged.costUsd > 0
? String(format: "%.1fx the raw cost", merged.costQuality.cacheSavingsUsd / merged.costUsd)
: "vs full input rates"
)
UsageMetricCell(
label: "Cached input",
value: UsageFormat.tokens(merged.cachedInputTokens),
detail: "\(UsageFormat.percent(cachedShare)) of observed input"
)
UsageMetricCell(
label: "Uncached input",
value: UsageFormat.tokens(merged.uncachedInputTokens),
detail: "\(UsageFormat.tokens(merged.cacheCreationTokens)) cache writes"
)
UsageMetricCell(
label: "Output",
value: UsageFormat.tokens(merged.outputTokens),
detail: "incl. \(UsageFormat.tokens(merged.reasoningTokens)) reasoning"
)
UsageMetricCell(
label: "Unpriced",
value: UsageFormat.percent(merged.costQuality.unpricedShare),
detail: "of records, excluded from cost"
)
}
.usageCard()
}
}
@ViewBuilder
private var modelsSection: some View {
if !merged.models.isEmpty {
UsageSection(title: "By model") {
VStack(spacing: 0) {
ForEach(Array(merged.models.enumerated()), id: \.element.id) { index, model in
if index > 0 { usageDivider }
HStack(spacing: 12) {
Circle()
.fill(model.provider.color)
.frame(width: 10, height: 10)
VStack(alignment: .leading, spacing: 2) {
Text(model.model)
.font(T3Typography.threadBody)
.foregroundStyle(T3Colors.textPrimary)
.lineLimit(1)
Text(
"\(UsageFormat.percent(model.costShare)) of cost · "
+ "\(UsageFormat.tokens(model.totalTokens)) tokens"
)
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textSecondary)
}
Spacer(minLength: 8)
Text(UsageFormat.usd(model.costUsd))
.font(T3Typography.threadBody)
.monospacedDigit()
.foregroundStyle(T3Colors.textPrimary)
}
.padding(16)
}
}
.usageCard()
}
}
}
private var usageDivider: some View {
Divider().overlay(T3Colors.separator)
}
private var hasCompatibleSummary: Bool {
environments.contains {
$0.summary?.contractVersion == usageContractVersion
}
}
private func load(input: UsageSummaryInput) async {
let loadID = UUID()
activeLoadID = loadID
if input != windowInput {
windowInput = input
environments = []
merged = MergedUsage()
}
isLoading = true
defer {
if activeLoadID == loadID {
isLoading = false
}
}
do {
let result = try await client.usageSummaries(input)
try Task.checkCancellation()
guard activeLoadID == loadID else { return }
environments = result
merged = UsageMerger.merge(result)
errorMessage = nil
} catch is CancellationError {
return
} catch {
guard activeLoadID == loadID else { return }
errorMessage = error.localizedDescription
}
}
}
private struct UsageDailyChart: View {
let input: UsageSummaryInput
let daily: [UsageDailyTotals]
let metric: UsageMetric
private var segments: [UsageChartSegment] {
let dailyByDay = Dictionary(uniqueKeysWithValues: daily.map { ($0.day, $0) })
return UsageWindow.days(in: input).flatMap { day in
var start = 0.0
return UsageProviderKind.allCases.map { provider in
let totals = dailyByDay[day]?.byProvider[provider]
let value = metric == .cost
? totals?.costUsd ?? 0
: Double(totals?.totalTokens ?? 0)
defer { start += value }
return UsageChartSegment(
day: day,
provider: provider,
start: start,
end: start + value
)
}
}
}
var body: some View {
Chart(segments) { segment in
BarMark(
x: .value("Day", segment.day),
yStart: .value("Start", segment.start),
yEnd: .value("End", segment.end)
)
.foregroundStyle(segment.provider.color)
}
.chartXAxis(.hidden)
.chartYAxis(.hidden)
.chartLegend(.hidden)
}
}
private struct UsageChartSegment: Identifiable {
let day: String
let provider: UsageProviderKind
let start: Double
let end: Double
var id: String { "\(day):\(provider.rawValue)" }
}
private struct UsageSection<Content: View>: View {
let title: String
@ViewBuilder let content: Content
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(title)
.font(T3Typography.supportingStrong)
.foregroundStyle(T3Colors.textSecondary)
.padding(.horizontal, 14)
content
}
}
}
private struct UsageMetricCell: View {
let label: String
let value: String
let detail: String
var body: some View {
VStack(alignment: .leading, spacing: 2) {
Text(label)
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textSecondary)
Text(value)
.font(.title3.weight(.medium))
.monospacedDigit()
.foregroundStyle(T3Colors.textPrimary)
.lineLimit(1)
.minimumScaleFactor(0.7)
Text(detail)
.font(.caption)
.foregroundStyle(T3Colors.textTertiary)
.lineLimit(2)
}
.padding(16)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
private struct UsageProgressBar: View {
let value: Double
let color: Color
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .leading) {
Capsule().fill(T3Colors.subtle)
Capsule()
.fill(color)
.frame(width: geometry.size.width * min(max(value, 0), 1))
}
}
.frame(height: 4)
.accessibilityHidden(true)
}
}
private extension View {
func usageCard() -> some View {
background(T3Colors.surface, in: RoundedRectangle(cornerRadius: 24))
}
}
private extension UsageProviderKind {
var color: Color {
switch self {
case .codex: T3Colors.textPrimary
case .claude: Color(red: 0.851, green: 0.467, blue: 0.341)
}
}
}
private enum UsageFormat {
static func usd(_ value: Double) -> String {
value.formatted(
.currency(code: "USD")
.locale(Locale(identifier: "en_US"))
.precision(.fractionLength(2))
)
}
static func count(_ value: Int) -> String {
value.formatted(.number.locale(Locale(identifier: "en_US")))
}
static func tokens(_ value: Int) -> String {
let magnitude = abs(Double(value))
if magnitude >= 1_000_000_000_000 { return compact(Double(value) / 1_000_000_000_000, suffix: "T") }
if magnitude >= 1_000_000_000 { return compact(Double(value) / 1_000_000_000, suffix: "B") }
if magnitude >= 1_000_000 { return compact(Double(value) / 1_000_000, suffix: "M") }
if magnitude >= 1_000 { return compact(Double(value) / 1_000, suffix: "K") }
return count(value)
}
static func percent(_ value: Double) -> String {
String(format: "%.1f%%", value * 100)
}
static func dayShort(_ day: String) -> String {
let components = day.split(separator: "-")
guard components.count == 3,
let month = Int(components[1]),
let dayOfMonth = Int(components[2]),
(1...12).contains(month) else {
return day
}
let months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
]
return "\(months[month - 1]) \(dayOfMonth)"
}
private static func compact(_ value: Double, suffix: String) -> String {
let digits = abs(value) >= 100 ? 0 : abs(value) >= 10 ? 1 : 2
var formatted = String(format: "%.*f", digits, value)
while formatted.hasSuffix("0"), formatted.contains(".") {
formatted.removeLast()
}
if formatted.hasSuffix(".") { formatted.removeLast() }
return formatted + suffix
}
}
@@ -0,0 +1,65 @@
import Foundation
import XCTest
@testable import T3Code
final class UsageContractTests: XCTestCase {
func testUsageSummaryDecodesCurrentWireContract() throws {
let data = Data(
#"""
{
"contractVersion": 3,
"readAt": "2026-08-09T12:00:00.000Z",
"timeZone": "America/Los_Angeles",
"sinceDay": "2026-08-03",
"untilDay": "2026-08-09",
"buckets": [{
"day": "2026-08-09",
"provider": "codex",
"model": "gpt-5.6-sol",
"totals": {
"uncachedInputTokens": 100,
"cachedInputTokens": 200,
"cacheCreationTokens": 30,
"outputTokens": 40,
"reasoningTokens": 10
},
"costUsd": 1.25,
"cacheSavingsUsd": 2.5,
"costSource": "modelPriced",
"records": 2,
"unpricedRecords": 0,
"sessions": 1
}],
"sources": [{
"fingerprint": {
"hostId": "mac-1",
"provider": "codex",
"resolvedHomePath": "/Users/theo/.codex",
"volumeId": "1:2"
},
"status": "ok",
"scannedFiles": 3,
"skippedFiles": 0,
"malformedRecords": 0,
"distinctSessions": 1,
"message": null
}],
"pricing": {
"status": "fresh",
"source": "LiteLLM",
"fetchedAt": "2026-08-09T11:00:00.000Z",
"knownModels": 200
},
"scanDurationMs": 14
}
"""#.utf8
)
let summary = try JSONDecoder.t3.decode(UsageSummary.self, from: data)
XCTAssertEqual(summary.contractVersion, usageContractVersion)
XCTAssertEqual(summary.buckets.first?.provider, .codex)
XCTAssertEqual(summary.buckets.first?.totals.cachedInputTokens, 200)
XCTAssertEqual(summary.sources.first?.fingerprint.volumeId, "1:2")
}
}
@@ -0,0 +1,174 @@
import Foundation
import Testing
@testable import T3Code
@Suite("Usage reporting")
struct UsageModelsTests {
@Test
func mergeDoesNotCountReasoningTokensTwice() {
let report = FeatureEnvironmentUsage(
environmentID: "environment-a",
label: "Studio",
summary: summary(
provider: .codex,
costUsd: 12,
uncachedInput: 100,
cachedInput: 200,
cacheCreation: 30,
output: 40,
reasoning: 10
),
errorMessage: nil
)
let merged = UsageMerger.merge([report])
#expect(merged.totalTokens == 370)
#expect(merged.reasoningTokens == 10)
#expect(merged.providers.first?.totalTokens == 370)
#expect(merged.sessions == 1)
}
@Test
func duplicateTranscriptSourcesAreCountedOnce() {
let first = FeatureEnvironmentUsage(
environmentID: "a",
label: "First",
summary: summary(provider: .codex, costUsd: 10),
errorMessage: nil
)
let duplicate = FeatureEnvironmentUsage(
environmentID: "b",
label: "Second",
summary: summary(provider: .codex, costUsd: 50),
errorMessage: nil
)
let merged = UsageMerger.merge([duplicate, first])
#expect(merged.costUsd == 10)
#expect(merged.contributingEnvironments == ["a"])
#expect(merged.duplicateSources == ["Second: /Users/theo/.codex"])
}
@Test
func healthySourceOwnsFingerprintInsteadOfEarlierFailedSource() {
let failed = FeatureEnvironmentUsage(
environmentID: "a",
label: "Failed",
summary: summary(provider: .codex, costUsd: 50, sourceStatus: .failed),
errorMessage: nil
)
let healthy = FeatureEnvironmentUsage(
environmentID: "b",
label: "Healthy",
summary: summary(provider: .codex, costUsd: 10),
errorMessage: nil
)
let merged = UsageMerger.merge([failed, healthy])
#expect(merged.costUsd == 10)
#expect(merged.contributingEnvironments == ["b"])
#expect(merged.duplicateSources == ["Failed: /Users/theo/.codex"])
}
@Test
func staleContractsDoNotChangeTotals() {
let current = FeatureEnvironmentUsage(
environmentID: "current",
label: "Current",
summary: summary(provider: .codex, costUsd: 10),
errorMessage: nil
)
let stale = FeatureEnvironmentUsage(
environmentID: "stale",
label: "Stale",
summary: summary(contractVersion: 2, provider: .claude, costUsd: 25),
errorMessage: nil
)
let merged = UsageMerger.merge([current, stale])
#expect(merged.costUsd == 10)
#expect(merged.staleEnvironments == ["stale"])
}
@Test
func calendarWindowStaysInclusiveAcrossDaylightSavingTime() throws {
let timeZone = try #require(TimeZone(identifier: "America/Los_Angeles"))
let now = try #require(
ISO8601DateFormatter().date(from: "2024-03-10T19:00:00Z")
)
let window = UsageWindow.make(days: 7, now: now, timeZone: timeZone)
#expect(window.sinceDay == "2024-03-04")
#expect(window.untilDay == "2024-03-10")
#expect(UsageWindow.days(in: window).count == 7)
}
private func summary(
contractVersion: Int = usageContractVersion,
provider: UsageProviderKind,
costUsd: Double,
uncachedInput: Int = 100,
cachedInput: Int = 0,
cacheCreation: Int = 0,
output: Int = 20,
reasoning: Int = 0,
sourceStatus: UsageSourceStatus = .ok
) -> UsageSummary {
let path = provider == .codex ? "/Users/theo/.codex" : "/Users/theo/.claude"
return UsageSummary(
contractVersion: contractVersion,
readAt: "2026-08-09T12:00:00.000Z",
timeZone: "America/Los_Angeles",
sinceDay: "2026-08-03",
untilDay: "2026-08-09",
buckets: [
UsageBucket(
day: "2026-08-09",
provider: provider,
model: provider == .codex ? "gpt-5.6-sol" : "claude-opus-4-1",
totals: UsageTokenTotals(
uncachedInputTokens: uncachedInput,
cachedInputTokens: cachedInput,
cacheCreationTokens: cacheCreation,
outputTokens: output,
reasoningTokens: reasoning
),
costUsd: costUsd,
cacheSavingsUsd: 0,
costSource: .modelPriced,
records: 1,
unpricedRecords: 0,
sessions: 1
),
],
sources: [
UsageSource(
fingerprint: UsageSourceFingerprint(
hostId: "host",
provider: provider,
resolvedHomePath: path,
volumeId: "1:2"
),
status: sourceStatus,
scannedFiles: 1,
skippedFiles: 0,
malformedRecords: 0,
distinctSessions: 1,
message: nil
),
],
pricing: UsagePricing(
status: .fresh,
source: "LiteLLM",
fetchedAt: nil,
knownModels: 1
),
scanDurationMs: 1
)
}
}