793 lines · 32.9 KB · Swift
RawDownload
import CodexBarCoreimport SwiftUI struct InlineUsageDashboardModel: Equatable {    struct KPI: Equatable {        let title: String        let value: String        let emphasis: Bool    }     struct Point: Equatable, Identifiable {        let id: String        let label: String        let value: Double        let accessibilityValue: String    }     enum ValueStyle: Equatable {        case currencyUSD        case currency(symbol: String)        case tokens        case points    }     let accessibilityLabel: String    let valueStyle: ValueStyle    let kpis: [KPI]    let points: [Point]    let detailLines: [String]    /// Provider branding color used to fill the mini usage bars. When nil the bars fall back to a    /// neutral palette derived from `valueStyle`.    var barColor: Color?} extension UsageMenuCardView.Model {    static func apiProviderUsageNotes(input: Input) -> [String]? {        if input.provider == .openai,           let usage = input.snapshot?.openAIAPIUsage        {            return self.openAIAPIUsageNotes(usage)        }         if input.provider == .deepgram,           let usage = input.snapshot?.deepgramUsage        {            return usage.displayLines        }         if input.provider == .minimax,           input.showOptionalCreditsAndExtraUsage,           let billing = input.snapshot?.minimaxUsage?.billingSummary        {            return [                String(format: L("Today: %@ tokens"), UsageFormatter.tokenCountString(billing.todayTokens)),                String(                    format: L("Last 30 days: %@ tokens"),                    UsageFormatter.tokenCountString(billing.last30DaysTokens)),            ]        }         if input.provider == .deepseek,           input.showOptionalCreditsAndExtraUsage,           let usage = input.snapshot?.deepseekUsage        {            let symbol = usage.currency == "CNY" ? "¥" : "$"            let todayCostStr = usage.todayCost.map { "\(symbol)\(String(format: "%.4f", max(0, $0)))" } ?? "—"            return [                String(                    format: L("Today: %@ · %@ tokens"),                    todayCostStr,                    UsageFormatter.tokenCountString(usage.todayTokens)),                String(format: L("This month: %@ tokens"), UsageFormatter.tokenCountString(usage.currentMonthTokens)),            ]        }         if input.provider == .poe,           let usage = input.snapshot?.poeUsage        {            return self.poeUsageNotes(usage)        }         if input.provider == .ollama,           input.snapshot?.identity?.loginMethod == "API key"        {            return [L("API key verified. Ollama does not expose Cloud quota limits through the API.")]        }         return nil    }     static func openAIAPIUsageNotes(_ usage: OpenAIAPIUsageSnapshot) -> [String] {        let today = usage.latestDay        let seven = usage.last7Days        let thirty = usage.last30Days        let historyLabel = usage.historyWindowLabel        let todayNote = String(            format: L("Today: %@ · %@ tokens"),            UsageFormatter.usdString(today.costUSD),            UsageFormatter.tokenCountString(today.totalTokens))        let sevenDayNote = "7d: \(UsageFormatter.usdString(seven.costUSD)) · " +            "\(UsageFormatter.tokenCountString(seven.requests)) \(L("requests"))"        let thirtyDayNote =            "\(historyLabel): \(UsageFormatter.tokenCountString(thirty.totalTokens)) \(L("tokens")) · " +            "\(UsageFormatter.tokenCountString(thirty.requests)) \(L("requests"))"        var notes: [String] = [            todayNote,            sevenDayNote,            thirtyDayNote,        ]        if let topModel = usage.topModels.first {            notes.append("\(L("Top model")): \(topModel.name)")        }        return notes    }     static func poeUsageNotes(_ usage: PoeUsageHistorySnapshot) -> [String] {        let today = usage.latestDay        let week = usage.last7Days        let month = usage.last30Days        let todayUSD = today.costUSD.map { " · \(UsageFormatter.usdString($0))" } ?? ""        let weekUSD = week.costUSD.map { " · \(UsageFormatter.usdString($0))" } ?? ""        let monthUSD = month.costUSD.map { " · \(UsageFormatter.usdString($0))" } ?? ""        let todayLine = "Today: \(Self.pointsSummary(today.points)) · " +            "\(UsageFormatter.tokenCountString(today.requests)) \(L("requests"))\(todayUSD)"        let weekLine = "7d: \(Self.pointsSummary(week.points)) · " +            "\(UsageFormatter.tokenCountString(week.requests)) \(L("requests"))\(weekUSD)"        let monthLine = "30d: \(Self.pointsSummary(month.points)) · " +            "\(UsageFormatter.tokenCountString(month.requests)) \(L("requests"))\(monthUSD)"        var notes = [            todayLine,            weekLine,            monthLine,        ]        if let topModel = usage.topModels.first {            notes.append("\(L("Top model")): \(topModel.name) (\(Self.pointsSummary(topModel.points)))")        }        if !usage.topUsageTypes.isEmpty {            let mix = usage.topUsageTypes.prefix(2)                .map { "\($0.name): \(Self.pointsSummary($0.points))" }                .joined(separator: " · ")            notes.append("Usage mix: \(mix)")        }        return notes    }     static func inlineUsageDashboard(input: Input) -> InlineUsageDashboardModel? {        guard var model = self.resolveInlineUsageDashboard(input: input) else { return nil }        model.barColor = Self.inlineDashboardBarColor(for: input.provider)        return model    }     /// Provider branding color for the inline usage bars, matching the provider's switcher tab and    /// detailed cost-history chart.    static func inlineDashboardBarColor(for provider: UsageProvider) -> Color {        let color = ProviderDescriptorRegistry.descriptor(for: provider).branding.color        return Color(red: color.red, green: color.green, blue: color.blue)    }     private static func resolveInlineUsageDashboard(input: Input) -> InlineUsageDashboardModel? {        if self.usesProviderCostHistoryAsPrimaryDashboard(input.provider),           let tokenSnapshot = primaryCostHistorySnapshot(input: input),           !tokenSnapshot.daily.isEmpty        {            return self.costHistoryInlineDashboard(provider: input.provider, snapshot: tokenSnapshot)        }        if input.provider == .claude,           let usage = input.snapshot?.claudeAdminAPIUsage        {            return Self.claudeAdminAPIInlineDashboard(usage)        }        if input.provider == .openrouter,           let usage = input.snapshot?.openRouterUsage        {            return Self.openRouterInlineDashboard(usage)        }        if input.provider == .zai,           let modelUsage = input.snapshot?.zaiUsage?.modelUsage        {            return Self.zaiInlineDashboard(modelUsage: modelUsage, now: input.now)        }        if input.provider == .minimax,           input.showOptionalCreditsAndExtraUsage,           let billing = input.snapshot?.minimaxUsage?.billingSummary,           !billing.daily.isEmpty        {            return Self.minimaxInlineDashboard(billing)        }        if input.provider == .deepseek,           input.showOptionalCreditsAndExtraUsage,           let usage = input.snapshot?.deepseekUsage,           !usage.daily.isEmpty        {            return Self.deepseekInlineDashboard(usage)        }        if input.provider == .poe,           let usage = input.snapshot?.poeUsage,           !usage.daily.isEmpty        {            return Self.poeInlineDashboard(usage)        }        if [.codex, .claude, .vertexai, .bedrock].contains(input.provider),           input.tokenCostUsageEnabled,           let tokenSnapshot = input.tokenSnapshot,           !tokenSnapshot.daily.isEmpty        {            return Self.costHistoryInlineDashboard(provider: input.provider, snapshot: tokenSnapshot)        }        return nil    }     static func usesProviderCostHistoryAsPrimaryDashboard(_ provider: UsageProvider) -> Bool {        provider == .openai || provider == .mistral    }     static func primaryCostHistorySnapshot(input: Input) -> CostUsageTokenSnapshot? {        switch input.provider {        case .openai:            if let projected = input.snapshot?.openAIAPIUsage?.toCostUsageTokenSnapshot() {                return projected            }            return input.snapshot == nil ? input.tokenSnapshot : nil        case .mistral:            if let projected = input.snapshot?.mistralUsage?.toCostUsageTokenSnapshot() {                return projected            }            return input.snapshot == nil ? input.tokenSnapshot : nil        default:            return input.tokenSnapshot        }    }     static func poeInlineDashboard(_ usage: PoeUsageHistorySnapshot) -> InlineUsageDashboardModel {        let today = usage.latestDay        let week = usage.last7Days        let month = usage.last30Days        let points = usage.daily.suffix(30).map {            InlineUsageDashboardModel.Point(                id: $0.day,                label: Self.shortDayLabel($0.day),                value: $0.points,                accessibilityValue: "\($0.day): \(Self.pointsSummary($0.points))")        }        var details = ["30d requests: \(UsageFormatter.tokenCountString(month.requests))"]        if let topModel = usage.topModel {            details.append("\(L("Top model")): \(topModel)")        }        if !usage.topUsageTypes.isEmpty {            let mix = usage.topUsageTypes.prefix(3)                .map { "\($0.name): \(Self.pointsSummary($0.points))" }                .joined(separator: " · ")            details.append("Usage mix: \(mix)")        }        if let usd = today.costUSD, usd > 0 {            details.append("Today USD: \(UsageFormatter.usdString(usd))")        }        if let usd = week.costUSD, usd > 0 {            details.append("7d USD: \(UsageFormatter.usdString(usd))")        }        if let usd = month.costUSD, usd > 0 {            details.append("30d USD: \(UsageFormatter.usdString(usd))")        }        let recent = usage.recentEntries(limit: 2)        if !recent.isEmpty {            let text = recent.map { "\($0.model) \(Self.pointsSummary($0.points))" }.joined(separator: " · ")            details.append("Recent: \(text)")        }        return InlineUsageDashboardModel(            accessibilityLabel: "Poe points usage trend",            valueStyle: .points,            kpis: [                .init(title: L("Today"), value: Self.pointsSummary(today.points), emphasis: true),                .init(title: "7d", value: Self.pointsSummary(week.points), emphasis: false),                .init(title: "30d", value: Self.pointsSummary(month.points), emphasis: false),                .init(title: L("Requests"), value: UsageFormatter.tokenCountString(month.requests), emphasis: false),            ],            points: points,            detailLines: details)    }     static func pointsSummary(_ value: Double) -> String {        let clamped = max(0, value)        if clamped.rounded() == clamped {            return "\(UsageFormatter.tokenCountString(Int(clamped))) points"        }        return "\(String(format: "%.1f", clamped)) points"    }     private static func costHistoryInlineDashboard(        provider: UsageProvider,        snapshot: CostUsageTokenSnapshot) -> InlineUsageDashboardModel    {        let historyDays = max(1, min(365, snapshot.historyDays))        let historyTitle = snapshot.historyLabel            ?? (historyDays == 1                ? L("Today")                : historyDays == 30                ? L("30d cost")                : "\(String(format: L("Last %d days"), historyDays)) \(L("Cost"))")        let tokenHistoryTitle = snapshot.historyLabel.map { "\($0) \(L("tokens"))" }            ?? (historyDays == 1                ? L("Today tokens")                : historyDays == 30                ? L("30d tokens")                : String(format: L("%@ tokens"), String(format: L("Last %d days"), historyDays)))        let requestHistoryTitle = snapshot.historyLabel.map { "\($0) \(L("requests"))" }            ?? (historyDays == 1                ? L("Today requests")                : historyDays == 30                ? L("30d requests")                : String(format: L("%@ requests"), String(format: L("Last %d days"), historyDays)))        let periodLabel = snapshot.historyLabel?.lowercased()            ?? (historyDays == 1 ? "today" : "\(historyDays) day")        let points = snapshot.daily.suffix(historyDays).compactMap { entry -> InlineUsageDashboardModel.Point? in            guard let cost = entry.costUSD else { return nil }            return InlineUsageDashboardModel.Point(                id: entry.date,                label: Self.shortDayLabel(entry.date),                value: cost,                accessibilityValue: "\(entry.date): \(Self.costString(cost, currencyCode: snapshot.currencyCode))")        }        let latest = snapshot.daily.max { lhs, rhs in lhs.date < rhs.date }        var details: [String] = []        if let topModel = Self.topCostModel(from: snapshot.daily) {            details.append("\(L("Top model")): \(Self.shortModelName(topModel))")        }        if let requestCount = snapshot.last30DaysRequests {            details.append("\(requestHistoryTitle): \(UsageFormatter.tokenCountString(requestCount)) \(L("requests"))")        }        if let hint = Self.tokenUsageHint(provider: provider) {            details.append(hint)        } else {            details.append(L("cost_estimate_hint"))        }        let providerName = ProviderDefaults.metadata[provider]?.displayName ?? provider.rawValue        return InlineUsageDashboardModel(            accessibilityLabel: "\(providerName) \(periodLabel) cost trend",            valueStyle: Self.costValueStyle(currencyCode: snapshot.currencyCode),            kpis: [                .init(                    title: provider == .bedrock || provider == .mistral ? L("Latest") : L("Today"),                    value: latest?.costUSD.map { Self.costString($0, currencyCode: snapshot.currencyCode) } ?? "—",                    emphasis: true),                .init(                    title: historyTitle,                    value: snapshot.last30DaysCostUSD                        .map { Self.costString($0, currencyCode: snapshot.currencyCode) } ?? "—",                    emphasis: false),                .init(                    title: tokenHistoryTitle,                    value: snapshot.last30DaysTokens.map(UsageFormatter.tokenCountString) ?? "—",                    emphasis: false),            ] + Self.costHistoryTrailingKPIs(snapshot: snapshot, latest: latest),            points: points,            detailLines: details)    }     private static func costHistoryTrailingKPIs(        snapshot: CostUsageTokenSnapshot,        latest: CostUsageDailyReport.Entry?)        -> [InlineUsageDashboardModel.KPI]    {        if let requests = snapshot.last30DaysRequests {            return [                .init(                    title: L("Requests"),                    value: UsageFormatter.tokenCountString(requests),                    emphasis: false),            ]        }        return [            .init(                title: L("Latest tokens"),                value: latest?.totalTokens.map(UsageFormatter.tokenCountString) ?? "—",                emphasis: false),        ]    }     fileprivate static func claudeAdminAPIInlineDashboard(_ usage: ClaudeAdminAPIUsageSnapshot)        -> InlineUsageDashboardModel    {        let today = usage.latestDay        let last7 = usage.last7Days        let last30 = usage.last30Days        let points = usage.daily.suffix(30).map {            InlineUsageDashboardModel.Point(                id: $0.day,                label: Self.shortDayLabel($0.day),                value: $0.costUSD,                accessibilityValue: "\($0.day): \(UsageFormatter.usdString($0.costUSD))")        }        var details = [            "30d: \(UsageFormatter.tokenCountString(last30.totalTokens)) \(L("tokens"))",            "\(L("Cache read")): \(UsageFormatter.tokenCountString(last30.cacheReadInputTokens)) \(L("tokens"))",        ]        if let topModel = usage.topModels.first {            details.append("\(L("Top model")): \(Self.shortModelName(topModel.name))")        }        return InlineUsageDashboardModel(            accessibilityLabel: L("Claude Admin API 30 day spend trend"),            valueStyle: .currencyUSD,            kpis: [                .init(title: L("Today"), value: UsageFormatter.usdString(today.costUSD), emphasis: true),                .init(title: L("7d spend"), value: UsageFormatter.usdString(last7.costUSD), emphasis: false),                .init(                    title: L("30d spend"),                    value: UsageFormatter.usdString(last30.costUSD),                    emphasis: false),                .init(                    title: L("Today tokens"),                    value: UsageFormatter.tokenCountString(today.totalTokens),                    emphasis: false),            ],            points: points,            detailLines: details)    }     private static func openRouterInlineDashboard(_ usage: OpenRouterUsageSnapshot) -> InlineUsageDashboardModel? {        let periodValues: [(String, String, Double?)] = [            ("day", L("Today"), usage.keyUsageDaily),            ("week", L("Week"), usage.keyUsageWeekly),            ("month", L("Month"), usage.keyUsageMonthly),        ]        let points = periodValues.compactMap { id, label, value -> InlineUsageDashboardModel.Point? in            guard let value else { return nil }            return InlineUsageDashboardModel.Point(                id: id,                label: label,                value: value,                accessibilityValue: "\(label): \(Self.openRouterCurrencyString(value))")        }        guard !points.isEmpty else { return nil }        var details: [String] = []        if let rate = usage.rateLimit {            details.append(String(format: L("Rate limit: %d / %@"), rate.requests, rate.interval))        }        switch usage.keyQuotaStatus {        case .available:            if let remaining = usage.keyRemaining {                details.append("\(L("Key remaining")): \(Self.openRouterCurrencyString(remaining))")            }        case .noLimitConfigured:            details.append(L("No limit set for the API key"))        case .unavailable:            details.append(L("API key limit unavailable right now"))        }        return InlineUsageDashboardModel(            accessibilityLabel: L("OpenRouter API key spend trend"),            valueStyle: .currencyUSD,            kpis: [                .init(title: L("Balance"), value: Self.openRouterCurrencyString(usage.balance), emphasis: true),                .init(                    title: L("Today"),                    value: usage.keyUsageDaily.map(Self.openRouterCurrencyString) ?? "—",                    emphasis: false),                .init(                    title: L("Week"),                    value: usage.keyUsageWeekly.map(Self.openRouterCurrencyString) ?? "—",                    emphasis: false),                .init(                    title: L("Month"),                    value: usage.keyUsageMonthly.map(Self.openRouterCurrencyString) ?? "—",                    emphasis: false),            ],            points: points,            detailLines: details)    }     private static func zaiInlineDashboard(modelUsage: ZaiModelUsageData, now: Date) -> InlineUsageDashboardModel? {        let bars = ZaiHourlyBars.from(modelData: modelUsage, range: .last24h, now: now)        guard !bars.isEmpty else { return nil }        let total = bars.reduce(0) { $0 + $1.totalTokens }        let latest = bars.last        let peak = bars.max { $0.totalTokens < $1.totalTokens }        let points = bars.enumerated().map { index, bar in            InlineUsageDashboardModel.Point(                id: "\(index)-\(bar.label)",                label: bar.label,                value: Double(bar.totalTokens),                accessibilityValue: "\(bar.label): \(UsageFormatter.tokenCountString(bar.totalTokens)) \(L("tokens"))")        }        let topModel = Self.topZaiModel(from: bars)        return InlineUsageDashboardModel(            accessibilityLabel: L("z.ai hourly token trend"),            valueStyle: .tokens,            kpis: [                .init(title: L("24h tokens"), value: UsageFormatter.tokenCountString(total), emphasis: true),                .init(                    title: L("Latest hour"),                    value: latest.map { UsageFormatter.tokenCountString($0.totalTokens) } ?? "—",                    emphasis: false),                .init(                    title: L("Peak hour"),                    value: peak.map { UsageFormatter.tokenCountString($0.totalTokens) } ?? "—",                    emphasis: false),                .init(title: L("Models"), value: "\(modelUsage.modelNames.count)", emphasis: false),            ],            points: points,            detailLines: topModel.map { ["\(L("Top model")): \(Self.shortModelName($0))"] } ?? [])    } 

Lines 1–500 of 793.