Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraUI/Sources/Lab/UsageLab.swift10// Module : Lab11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import Charts90import AstraCore91import AstraDesign92import AstraPersistence9394/// Usage and cost, drawn from the ledger every finished generation writes to. Costs keep their basis; unknown costs stay unknown.95struct UsageLabView: View {96 enum Period: Int, CaseIterable, Identifiable {97 case week = 7, month = 30, quarter = 90, all = 098 var id: Int { rawValue }99 var title: String { switch self { case .week: "7 days"; case .month: "30 days"; case .quarter: "90 days"; case .all: "All" } }100 var start: Date? { self == .all ? nil : Calendar.current.date(byAdding: .day, value: -(rawValue - 1), to: Calendar.current.startOfDay(for: Date())) }101 }102 enum Measure: String, CaseIterable, Identifiable {103 case tokens, cost104 var id: String { rawValue }105 var title: String { self == .tokens ? "Tokens" : "Cost" }106 }107 struct BasisRow: Identifiable, Equatable {108 var basis: CostEstimate.Basis109 var requests: Int110 var costUSD: Double?111 var id: String { basis.rawValue }112 }113 struct Loaded: Equatable {114 var total: UsageAggregate115 var days: [UsageAggregate]116 var providers: [UsageAggregate]117 var models: [UsageAggregate]118 var basis: [BasisRow]119 }120 struct BarRow: Identifiable {121 var label: String122 var group: UsageAggregate123 var id: String { label }124 }125 struct DayPoint: Identifiable, UsageDayPoint {126 var date: Date127 var series: String128 var value: Double129 var id: String { "\(date.timeIntervalSinceReferenceDate)-\(series)" }130 }131132 @Environment(AppModel.self) private var app133 @State private var period: Period = .month134 @State private var measure: Measure = .tokens135 @State private var loaded: Loaded?136 @State private var error: String?137 @State private var exported: ExportedFile?138139 var body: some View {140 LabPage(title: "Usage and cost") {141 Picker("Period", selection: $period) { ForEach(Period.allCases) { Text($0.title).tag($0) } }142 .pickerStyle(.segmented).accessibilityIdentifier("usage-period")143 if let error { NoticeCard(.error, title: "Usage could not be read", message: error) }144 if let loaded {145 if loaded.total.requests == 0 {146 EmptyStateView(symbol: "chart.bar.xaxis", title: "Nothing recorded in this period",147 message: "Each finished answer adds one line to the ledger, with the tokens the provider or the on-device runtime reported. Nothing is estimated after the fact.")148 .frame(maxWidth: .infinity)149 } else {150 totals(loaded.total)151 Picker("Measure", selection: $measure) { ForEach(Measure.allCases) { Text($0.title).tag($0) } }152 .pickerStyle(.segmented).accessibilityIdentifier("usage-measure")153 if measure == .cost, loaded.total.unpricedRequests == loaded.total.requests {154 NoticeCard(.info, title: "No cost is known for this period", message: "These requests ran on device or on models without a published price. Switch to Tokens to see the activity.")155 } else {156 dayChart(loaded.days)157 breakdown("By provider", loaded.providers, identifier: "usage-by-provider")158 breakdown("By model", Array(loaded.models.prefix(8)), identifier: "usage-by-model",159 footer: loaded.models.count > 8 ? "The 8 most used of \(loaded.models.count) models." : nil)160 }161 basisCard(loaded)162 }163 } else if error == nil { LabLoading() }164 }165 .toolbar {166 ToolbarItem(placement: .topBarTrailing) {167 Menu {168 Button { export(.csv) } label: { Label("Export CSV", systemImage: "tablecells") }169 Button { export(.json) } label: { Label("Export JSON", systemImage: "curlybraces") }170 } label: { Label("Export", systemImage: "square.and.arrow.up") }171 .disabled((loaded?.total.requests ?? 0) == 0)172 .accessibilityIdentifier("usage-export")173 }174 }175 .task(id: period) { for await _ in app.store.changes(in: [.usage]) { await load() } }176 .sheet(item: $exported) { ShareSheet(items: [$0.url]) }177 }178179 // MARK: Totals180181 private func totals(_ total: UsageAggregate) -> some View {182 AstraCard {183 VStack(alignment: .leading, spacing: AstraSpace.md) {184 SectionTitle("Totals", detail: period == .all ? "All time" : "Last \(period.title)")185 LazyVGrid(columns: [GridItem(.adaptive(minimum: 96), spacing: AstraSpace.md, alignment: .topLeading)], alignment: .leading, spacing: AstraSpace.md) {186 MetricTile("Requests", value: LabFormat.count(total.requests), symbol: "arrow.up.arrow.down")187 MetricTile("Input", value: LabFormat.compact(total.inputTokens), unit: "tok", symbol: "arrow.up")188 MetricTile("Output", value: LabFormat.compact(total.outputTokens), unit: "tok", symbol: "arrow.down")189 MetricTile("Cached input", value: total.cachedInputTokens > 0 ? LabFormat.compact(total.cachedInputTokens) : nil, unit: "tok", symbol: "bolt.horizontal")190 MetricTile("Reasoning", value: total.reasoningTokens > 0 ? LabFormat.compact(total.reasoningTokens) : nil, unit: "tok", symbol: "brain")191 MetricTile("Known cost", value: total.unpricedRequests == total.requests ? nil : CostEstimate.format(total.costUSD), symbol: "dollarsign.circle")192 }193 if total.unpricedRequests > 0 {194 Text("\(total.unpricedRequests) of \(total.requests) requests have no known cost and are not in the cost total.")195 .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)196 }197 }198 }199 .accessibilityIdentifier("usage-totals")200 }201202 // MARK: Charts203204 private func points(_ days: [UsageAggregate]) -> [DayPoint] {205 let parser = DateFormatter()206 parser.calendar = Calendar(identifier: .gregorian); parser.locale = Locale(identifier: "en_US_POSIX"); parser.timeZone = .current; parser.dateFormat = "yyyy-MM-dd"207 return days.flatMap { day -> [DayPoint] in208 guard let date = parser.date(from: day.key) else { return [] }209 switch measure {210 case .tokens: return [DayPoint(date: date, series: "Input", value: Double(day.inputTokens)), DayPoint(date: date, series: "Output", value: Double(day.outputTokens))]211 case .cost: return [DayPoint(date: date, series: "Cost", value: day.costUSD)]212 }213 }214 }215216 /// The x domain of the per-day chart: from the first day with data (at least six days back) to the end of today.217 private func dayDomain<P>(_ data: [P]) -> (range: ClosedRange<Date>, span: Int) where P: UsageDayPoint {218 let calendar = Calendar.current219 let end = calendar.date(byAdding: .day, value: 1, to: calendar.startOfDay(for: Date())) ?? Date()220 let weekAgo = calendar.date(byAdding: .day, value: -7, to: end) ?? end221 let first = data.map(\.date).min().map { calendar.startOfDay(for: $0) } ?? weekAgo222 let start = min(first, weekAgo)223 return (start...end, max(1, calendar.dateComponents([.day], from: start, to: end).day ?? 7))224 }225226 private func dayChart(_ days: [UsageAggregate]) -> some View {227 let data = points(days)228 let busiest = days.max { value($0) < value($1) }229 return AstraCard {230 VStack(alignment: .leading, spacing: AstraSpace.md) {231 SectionTitle(measure == .tokens ? "Tokens per day" : "Cost per day", detail: measure == .cost ? "Known costs, US$" : nil)232 Chart(data) { point in233 BarMark(x: .value("Day", point.date, unit: .day), y: .value(measure.title, point.value))234 .foregroundStyle(by: .value("Kind", point.series))235 .cornerRadius(2)236 }237 .chartForegroundStyleScale(domain: measure == .tokens ? ["Input", "Output"] : ["Cost"],238 range: measure == .tokens ? [AstraColor.indigo, AstraColor.cyan] : [AstraColor.violet])239 .chartLegend(measure == .tokens ? .visible : .hidden)240 .chartYAxis {241 AxisMarks { mark in242 AxisGridLine().foregroundStyle(AstraColor.stroke)243 AxisValueLabel { if let v = mark.as(Double.self) { Text(axisLabel(v)).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary) } }244 }245 }246 .chartXAxis {247 // one tick per whole day (or every few days on long ranges), so a date is never repeated248 AxisMarks(values: .stride(by: .day, count: max(1, dayDomain(data).span / 5))) { _ in249 AxisGridLine().foregroundStyle(AstraColor.stroke)250 AxisValueLabel(format: .dateTime.month(.abbreviated).day(), centered: true).font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary)251 }252 }253 // always show at least a week, so a single day of activity is one bar among empty days rather than a wall254 .chartXScale(domain: dayDomain(data).range)255 .frame(height: 200)256 .accessibilityLabel(measure == .tokens ? "Tokens per day" : "Cost per day")257 .accessibilityValue(busiest.map { "\(days.count) day\(days.count == 1 ? "" : "s") with activity. Busiest day \($0.label): \(spoken($0))." } ?? "No data")258 .accessibilityIdentifier("usage-day-chart")259 }260 }261 }262263 private func breakdown(_ title: String, _ groups: [UsageAggregate], identifier: String, footer: String? = nil) -> some View {264 let rows = uniqueLabels(groups)265 return AstraCard {266 VStack(alignment: .leading, spacing: AstraSpace.md) {267 SectionTitle(title, detail: measure == .tokens ? "Tokens" : "Known cost, US$")268 Chart(rows) { row in269 BarMark(x: .value(measure.title, value(row.group)), y: .value("Name", row.label))270 .foregroundStyle(measure == .tokens ? AstraColor.indigo : AstraColor.violet)271 .cornerRadius(3)272 .annotation(position: .trailing, alignment: .leading, spacing: AstraSpace.xs) {273 Text(display(row.group)).font(AstraFont.micro).foregroundStyle(AstraColor.textSecondary)274 }275 }276 .chartXAxis(.hidden)277 .chartXScale(domain: 0...max(rows.map { value($0.group) }.max() ?? 1, .leastNonzeroMagnitude) * 1.3)278 .chartYAxis {279 AxisMarks(preset: .aligned, position: .leading) { _ in280 AxisValueLabel().font(AstraFont.caption).foregroundStyle(AstraColor.textPrimary)281 }282 }283 .frame(height: CGFloat(rows.count) * 38 + 12)284 .accessibilityLabel(title)285 .accessibilityValue(groups.map { "\($0.label): \(spoken($0))" }.joined(separator: ". "))286 .accessibilityIdentifier(identifier)287 if let footer { Text(footer).font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary) }288 }289 }290 }291292 private func basisCard(_ loaded: Loaded) -> some View {293 AstraCard {294 VStack(alignment: .leading, spacing: AstraSpace.sm) {295 SectionTitle("Where the cost figures come from")296 ForEach(loaded.basis) { row in297 FactRow(label: LabFormat.basis(row.basis),298 value: "\(row.requests) request\(row.requests == 1 ? "" : "s")" + (row.costUSD.map { " · " + CostEstimate.format($0) } ?? ""))299 }300 Text("A provider's own figure is used when it reports one. Otherwise the cost is the reported tokens multiplied by the price published on the date shown with each model. It is an estimate, never an invoice; your provider's dashboard is the reference.")301 .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)302 }303 }304 }305306 // MARK: Values307308 private func value(_ group: UsageAggregate) -> Double { measure == .tokens ? Double(group.totalTokens) : group.costUSD }309 private func display(_ group: UsageAggregate) -> String {310 if measure == .tokens { return LabFormat.compact(group.totalTokens) }311 return group.unpricedRequests == group.requests ? "unknown" : CostEstimate.format(group.costUSD)312 }313 private func spoken(_ group: UsageAggregate) -> String {314 measure == .tokens ? "\(group.totalTokens) tokens" : (group.unpricedRequests == group.requests ? "cost unknown" : CostEstimate.format(group.costUSD))315 }316 private func axisLabel(_ v: Double) -> String { measure == .tokens ? LabFormat.compact(Int(v)) : CostEstimate.format(v) }317318 /// Chart categories must be unique and short enough to leave room for the bars.319 private func uniqueLabels(_ groups: [UsageAggregate]) -> [BarRow] {320 var seen: [String: Int] = [:]321 return groups.map { group in322 var label = group.label.split(separator: "/").last.map(String.init) ?? group.label323 if label.count > 20 { label = String(label.prefix(19)) + "…" }324 let n = (seen[label] ?? 0) + 1325 seen[label] = n326 return BarRow(label: n > 1 ? "\(label) (\(n))" : label, group: group)327 }328 }329330 // MARK: Data331332 private func load() async {333 let store = app.store, start = period.start334 do {335 async let total = store.usageTotal(from: start)336 async let days = store.usageAggregates(by: .day, from: start)337 async let providers = store.usageAggregates(by: .provider, from: start)338 async let models = store.usageAggregates(by: .model, from: start)339 let records = try await store.usageRecords(from: start)340 var basis: [CostEstimate.Basis: BasisRow] = [:]341 for record in records {342 var row = basis[record.costBasis] ?? BasisRow(basis: record.costBasis, requests: 0, costUSD: nil)343 row.requests += 1344 if let cost = record.costUSD, record.costBasis != .onDevice { row.costUSD = (row.costUSD ?? 0) + cost }345 basis[record.costBasis] = row346 }347 let order: [CostEstimate.Basis] = [.reportedByProvider, .estimatedFromUsage, .estimatedFromText, .onDevice, .unavailable]348 loaded = Loaded(total: try await total, days: try await days, providers: try await providers, models: try await models,349 basis: order.compactMap { basis[$0] })350 error = nil351 } catch { self.error = AstraError.wrap(error).message }352 }353354 private func export(_ format: ExportFormat) {355 let store = app.store, start = period.start356 Task {357 do { exported = app.exportedFile(try await store.exportUsage(format, from: start), name: "astra-usage", ext: format.fileExtension) }358 catch { app.show(AstraError.wrap(error).message, .error) }359 }360 }361}362363/// What the per-day chart needs from a data point.364protocol UsageDayPoint { var date: Date { get } }365