948 lines · 39.2 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?    /// ISO 4217 currency code for cost dashboards. When non-nil, `MiniUsageBars` shows a max-cost scale label.    /// Nil for token/points dashboards.    var currencyCode: String?} 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 == .clawrouter,           let usage = input.snapshot?.clawRouterUsage        {            var notes = [                "\(UsageFormatter.tokenCountString(usage.requestCount)) \(L("requests")) · " +                    "\(UsageFormatter.tokenCountString(usage.totalTokens)) \(L("tokens"))",            ]            if usage.errorCount > 0 {                notes.append("\(usage.successCount) succeeded · \(usage.errorCount) failed")            }            if !usage.providers.isEmpty {                let mix = usage.providers.prefix(5)                    .map { "\($0.provider): \(UsageFormatter.tokenCountString($0.requestCount))" }                    .joined(separator: " · ")                notes.append("Routed providers: \(mix)")            }            return notes        }         if input.provider == .wayfinder,           let usage = input.snapshot?.wayfinderUsage        {            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 {            if input.isRefreshing {                return []            }            if input.snapshot?.primary == nil {                if input.snapshot?.deepseekDetailedUsageState == .webSessionRequired {                    return [L("Sign in to DeepSeek Platform in Chrome for detailed usage.")]                }                if input.snapshot?.deepseekDetailedUsageState == .profileSelectionRequired {                    return [L("Select a DeepSeek Chrome profile in Settings.")]                }            }            guard input.tokenCostInlineDashboardEnabled,                  input.showOptionalCreditsAndExtraUsage            else { return nil }            guard let usage = input.snapshot?.deepseekUsage else {                if input.snapshot?.deepseekDetailedUsageState == .webSessionRequired {                    return [L("Sign in to DeepSeek Platform in Chrome for detailed usage.")]                }                if input.snapshot?.deepseekDetailedUsageState == .profileSelectionRequired {                    return [L("Select a DeepSeek Chrome profile in Settings.")]                }                return [L("Detailed usage unavailable.")]            }            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, now: input.now)        }         if input.provider == .ollama,           input.snapshot?.identity?.loginMethod == "API key"        {            return [L("API key verified. Cloud quotas need browser cookies. Sign in to Ollama.")]        }         return nil    }     static func openAIAPIUsageNotes(_ usage: OpenAIAPIUsageSnapshot) -> [String] {        let today = usage.currentDay        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,        now: Date = Date(),        calendar: Calendar = .current) -> [String]    {        let today = usage.currentDay(now: now, calendar: calendar)        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,                comparisonPeriodsEnabled: input.costComparisonPeriodsEnabled)        }        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.isRefreshing,           input.tokenCostInlineDashboardEnabled,           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, now: input.now)        }        if [.codex, .claude, .vertexai, .bedrock, .cursor, .opencodego].contains(input.provider),           input.tokenCostInlineDashboardEnabled,           let tokenSnapshot = input.tokenSnapshot,           !tokenSnapshot.daily.isEmpty || tokenSnapshot.meteredCostUSD != nil        {            return Self.costHistoryInlineDashboard(                provider: input.provider,                snapshot: tokenSnapshot,                comparisonPeriodsEnabled: input.costComparisonPeriodsEnabled)        }        return nil    }     static func usesProviderCostHistoryAsPrimaryDashboard(_ provider: UsageProvider) -> Bool {        provider == .openai || provider == .mistral || provider == .groq    }     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        case .groq:            if let projected = input.snapshot?.groqConsoleUsage?.toCostUsageTokenSnapshot() {                return projected            }            return input.snapshot == nil ? input.tokenSnapshot : nil        default:            return input.tokenSnapshot        }    }     static func poeInlineDashboard(        _ usage: PoeUsageHistorySnapshot,        now: Date = Date(),        calendar: Calendar = .current) -> InlineUsageDashboardModel    {        let today = usage.currentDay(now: now, calendar: calendar)        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,        comparisonPeriodsEnabled: Bool) -> InlineUsageDashboardModel    {        let historyDays = max(1, min(365, snapshot.historyDays))        let defaultHistoryTitle = snapshot.historyLabel            ?? (historyDays == 1                ? L("Today")                : historyDays == 30                ? L("30d cost")                : "\(String(format: L("Last %d days"), historyDays)) \(L("Cost"))")        let codexHistoryPeriod = snapshot.historyLabel            ?? (historyDays == 1                ? L("Today")                : historyDays == 30                ? "30d"                : String(format: L("Last %d days"), historyDays))        let historyTitle = provider == .codex ? codexHistoryPeriod : defaultHistoryTitle        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 accessibilityCostLabel: String = if let historyLabel = snapshot.historyLabel {            L("%@ cost", historyLabel)        } else if historyDays == 30 {            L("30d cost")        } else {            L("%@ cost", historyDays == 1 ? L("Today") : String(format: L("Last %d days"), historyDays))        }        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 = CostUsageTokenSnapshot.latestEntry(in: snapshot.daily)        let usesLatestPrimary = provider == .bedrock || provider == .mistral        let primaryCostUSD = usesLatestPrimary ? latest?.costUSD : snapshot.sessionCostUSD        var details: [String] = []        if comparisonPeriodsEnabled {            details.append(contentsOf: snapshot.comparisonSummaries().map {                Self.costWindowLine(summary: $0, currencyCode: snapshot.currencyCode)            })        }        if let topModel = Self.topCostModel(from: snapshot.daily) {            details.append("\(L("Top model")): \(Self.shortModelName(topModel))")        }        if provider == .codex {            details.append(L("codex_api_estimate_hint"))        }        if provider != .groq {            if let requestCount = snapshot.last30DaysRequests {                details                    .append("\(requestHistoryTitle): \(UsageFormatter.tokenCountString(requestCount)) \(L("requests"))")            }            if provider != .codex {                let hintLines = Self.tokenUsageHintLines(provider: provider)                if hintLines.isEmpty == false {                    details.append(contentsOf: hintLines)                } else {                    details.append(L("cost_estimate_hint"))                }            }        }        let providerName = ProviderDefaults.metadata[provider]?.displayName ?? provider.rawValue        let accessibilityLabel = L(            "%@: %@",            providerName,            accessibilityCostLabel)        var kpis = [            InlineUsageDashboardModel.KPI(                title: usesLatestPrimary ? L("Latest") : L("Today"),                value: primaryCostUSD.map { Self.costString($0, currencyCode: snapshot.currencyCode) } ?? "—",                emphasis: true),            .init(                title: historyTitle,                value: snapshot.last30DaysCostUSD                    .map { Self.costString($0, currencyCode: snapshot.currencyCode) } ?? "—",                emphasis: false),        ]        let tokenHistoryKPI = InlineUsageDashboardModel.KPI(            title: tokenHistoryTitle,            value: snapshot.last30DaysTokens.map(UsageFormatter.tokenCountString) ?? "—",            emphasis: false)        let trailingKPIs = Self.costHistoryTrailingKPIs(snapshot: snapshot, latest: latest)        if snapshot.last30DaysRequests == nil {            kpis.append(contentsOf: trailingKPIs)            kpis.append(tokenHistoryKPI)        } else {            kpis.append(tokenHistoryKPI)            kpis.append(contentsOf: trailingKPIs)        }        if provider == .cursor, let meteredCostUSD = snapshot.meteredCostUSD {            kpis.insert(                .init(                    title: "Cursor-metered",                    value: Self.costString(meteredCostUSD, currencyCode: snapshot.currencyCode),                    emphasis: true),                at: 0)        }        var model = InlineUsageDashboardModel(            accessibilityLabel: accessibilityLabel,            valueStyle: Self.costValueStyle(currencyCode: snapshot.currencyCode),            kpis: kpis,            points: points,            detailLines: details)        model.currencyCode = snapshot.currencyCode        return model    }     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

Lines 1–500 of 948.