1049 lines · 41.1 KB · Swift
RawDownload
import CodexBarCoreimport CryptoKitimport Foundationimport Observation struct SpendDashboardConfiguration: Equatable, Sendable {    let costUsageEnabled: Bool    let providerIDs: [String]    let codexAccountIdentities: [String]    let codexAccountDisplayNames: [String: String]    let sourceOwnershipFingerprints: [String]    let sourceRevisions: [String]     init(        costUsageEnabled: Bool,        providerIDs: [String],        codexAccountIdentities: [String],        codexAccountDisplayNames: [String: String] = [:],        sourceOwnershipFingerprints: [String] = [],        sourceRevisions: [String] = [])    {        self.costUsageEnabled = costUsageEnabled        self.providerIDs = providerIDs        self.codexAccountIdentities = codexAccountIdentities        self.codexAccountDisplayNames = codexAccountDisplayNames        self.sourceOwnershipFingerprints = sourceOwnershipFingerprints        self.sourceRevisions = sourceRevisions    }} struct CodexSpendScanRequest: Equatable, Sendable {    let id: String    let displayName: String    let source: CodexActiveSource    let homePath: String    let authFingerprint: String?    let authFileWasReadable: Bool    let cacheIdentity: String} enum SpendDashboardRequestBuildMode: Equatable, Sendable {    case refreshMissing    case forceRefresh    case captureOnly     var forcesLoader: Bool {        self == .forceRefresh    }     func shouldRefresh(hasPublication: Bool) -> Bool {        switch self {        case .refreshMissing: !hasPublication        case .forceRefresh: true        case .captureOnly: false        }    }} struct SpendDashboardLoadRequest: Sendable {    let configuration: SpendDashboardConfiguration    let capturedInputs: [SpendDashboardModel.ProviderInput]    let unavailableSourceIDs: Set<String>    let confirmedEmptySourceIDs: Set<String>    let codexRequests: [CodexSpendScanRequest]    let now: Date    let force: Bool     init(        configuration: SpendDashboardConfiguration,        capturedInputs: [SpendDashboardModel.ProviderInput],        unavailableSourceIDs: Set<String>,        confirmedEmptySourceIDs: Set<String> = [],        codexRequests: [CodexSpendScanRequest],        now: Date,        force: Bool)    {        self.configuration = configuration        self.capturedInputs = capturedInputs        self.unavailableSourceIDs = unavailableSourceIDs        self.confirmedEmptySourceIDs = confirmedEmptySourceIDs        self.codexRequests = codexRequests        self.now = now        self.force = force    }} struct SpendDashboardLoadResult: Sendable {    let inputs: [SpendDashboardModel.ProviderInput]    let failedSourceIDs: Set<String>    let invalidatedSourceIDs: Set<String>     init(        inputs: [SpendDashboardModel.ProviderInput],        failedSourceIDs: Set<String>,        invalidatedSourceIDs: Set<String> = [])    {        self.inputs = inputs        self.failedSourceIDs = failedSourceIDs        self.invalidatedSourceIDs = invalidatedSourceIDs    }     var failedSourceCount: Int {        self.failedSourceIDs.count    }} struct CodexSpendSnapshotLoadContext: Sendable {    let account: CodexSpendScanRequest    let cacheRoot: URL    let now: Date    let force: Bool    let historyDays: Int    let refreshPricingInBackground: Bool    let includePiSessions: Bool} enum SpendDashboardSource {    typealias CodexSnapshotLoader = @Sendable (CodexSpendSnapshotLoadContext) async throws        -> CostUsageTokenSnapshot     static let scanDays = 30     @MainActor    static func configuration(settings: SettingsStore, store: UsageStore) -> SpendDashboardConfiguration {        let providers = self.costCapableProviders(store: store)        let codexRequests = providers.contains(.codex)            ? self.codexRequests(settings: settings, store: store)            : []        return self.configuration(            settings: settings,            store: store,            providers: providers,            codexRequests: codexRequests)    }     @MainActor    private static func configuration(        settings: SettingsStore,        store: UsageStore,        providers: [UsageProvider],        codexRequests: [CodexSpendScanRequest]) -> SpendDashboardConfiguration    {        SpendDashboardConfiguration(            costUsageEnabled: settings.costUsageEnabled,            providerIDs: providers.map(\.rawValue),            codexAccountIdentities: codexRequests.map { "\($0.id)|\($0.cacheIdentity)" },            codexAccountDisplayNames: self.codexDisplayNamesByID(codexRequests),            sourceOwnershipFingerprints: self.sourceOwnershipFingerprints(                providers: providers,                settings: settings,                store: store),            sourceRevisions: self.sourceRevisions(providers: providers, settings: settings, store: store))    }     @MainActor    static func makeRequest(        settings: SettingsStore,        store: UsageStore,        mode: SpendDashboardRequestBuildMode,        now: Date? = nil,        nowProvider: @escaping @Sendable () -> Date = { Date() }) async -> SpendDashboardLoadRequest    {        guard settings.costUsageEnabled else {            return SpendDashboardLoadRequest(                configuration: self.configuration(settings: settings, store: store),                capturedInputs: [],                unavailableSourceIDs: [],                codexRequests: [],                now: now ?? nowProvider(),                force: mode.forcesLoader)        }         let initialProviders = self.costCapableProviders(store: store)        let providerBaselines = initialProviders.filter { $0 != .codex }.map { provider in            (                provider: provider,                publication: store.tokenSnapshotPublicationForCurrentProviderConfig(for: provider),                publicationRevision: store.tokenSnapshotPublicationRevision(for: provider))        }        for baseline in providerBaselines where mode.shouldRefresh(hasPublication: baseline.publication != nil) {            if UsageStore.tokenCostRequiresProviderSnapshot(baseline.provider) {                await store.refreshProvider(baseline.provider)            } else {                await store.refreshTokenUsageNow(for: baseline.provider, force: true)            }        }         // A later provider refresh can suspend while an earlier provider publishes again.        // Capture every provider only after all refresh work finishes so the request owns the        // newest same-scope publication available at this boundary.        let captureNow = now ?? nowProvider()        let providers = self.costCapableProviders(store: store)        let codexRequests = providers.contains(.codex)            ? self.codexRequests(settings: settings, store: store)            : []        let configuration = self.configuration(            settings: settings,            store: store,            providers: providers,            codexRequests: codexRequests)        guard configuration.costUsageEnabled else {            return SpendDashboardLoadRequest(                configuration: configuration,                capturedInputs: [],                unavailableSourceIDs: [],                codexRequests: [],                now: captureNow,                force: mode.forcesLoader)        }         var inputs: [SpendDashboardModel.ProviderInput] = []        var unavailableSourceIDs: Set<String> = []        var confirmedEmptySourceIDs: Set<String> = []        for provider in providers where provider != .codex {            guard let baseline = providerBaselines.first(where: { $0.provider == provider }) else {                unavailableSourceIDs.insert(provider.rawValue)                continue            }            let shouldRefresh = mode.shouldRefresh(hasPublication: baseline.publication != nil)            let current = store.tokenSnapshotPublicationForCurrentProviderConfig(for: provider)            guard let current else {                unavailableSourceIDs.insert(provider.rawValue)                continue            }            if shouldRefresh, baseline.publicationRevision == current.publicationRevision {                unavailableSourceIDs.insert(provider.rawValue)                continue            }            guard let snapshot = current.snapshot else {                confirmedEmptySourceIDs.insert(provider.rawValue)                continue            }            inputs.append(SpendDashboardModel.ProviderInput(                provider: provider,                displayName: store.metadata(for: provider).displayName,                snapshot: snapshot))        }        return SpendDashboardLoadRequest(            configuration: configuration,            capturedInputs: inputs,            unavailableSourceIDs: unavailableSourceIDs,            confirmedEmptySourceIDs: confirmedEmptySourceIDs,            codexRequests: codexRequests,            now: captureNow,            force: mode.forcesLoader)    }     static func load(_ request: SpendDashboardLoadRequest) async -> SpendDashboardLoadResult {        await self.load(request, codexSnapshotLoader: { context in            try await self.loadCodexSnapshot(context)        })    }     static func load(        _ request: SpendDashboardLoadRequest,        codexSnapshotLoader: CodexSnapshotLoader) async -> SpendDashboardLoadResult    {        var inputs = request.capturedInputs        var failedSourceIDs = request.unavailableSourceIDs        var invalidatedSourceIDs: Set<String> = []        for account in request.codexRequests {            let sourceID = "codex:\(account.id)"            do {                guard self.currentAuthFingerprint(for: account) == account.authFingerprint else {                    failedSourceIDs.insert(sourceID)                    invalidatedSourceIDs.insert(sourceID)                    continue                }                let cacheRoot = UsageStore.costUsageCacheDirectory()                    .appendingPathComponent("accounts", isDirectory: true)                    .appendingPathComponent(account.cacheIdentity, isDirectory: true)                let snapshot = try await codexSnapshotLoader(CodexSpendSnapshotLoadContext(                    account: account,                    cacheRoot: cacheRoot,                    now: request.now,                    force: request.force,                    historyDays: Self.scanDays,                    refreshPricingInBackground: false,                    includePiSessions: false))                try Task.checkCancellation()                guard self.currentAuthFingerprint(for: account) == account.authFingerprint else {                    failedSourceIDs.insert(sourceID)                    invalidatedSourceIDs.insert(sourceID)                    continue                }                inputs.append(SpendDashboardModel.ProviderInput(                    id: sourceID,                    provider: .codex,                    displayName: account.displayName,                    modelProviderName: ProviderDescriptorRegistry.descriptor(for: .codex).metadata.displayName,                    snapshot: snapshot))            } catch is CancellationError {                failedSourceIDs.formUnion(request.codexRequests.map { "codex:\($0.id)" })                return SpendDashboardLoadResult(                    inputs: [],                    failedSourceIDs: failedSourceIDs,                    invalidatedSourceIDs: invalidatedSourceIDs)            } catch {                failedSourceIDs.insert(sourceID)            }        }        let lateInvalidatedSourceIDs = Set(request.codexRequests.compactMap { account in            self.currentAuthFingerprint(for: account) == account.authFingerprint                ? nil                : "codex:\(account.id)"        })        failedSourceIDs.formUnion(lateInvalidatedSourceIDs)        invalidatedSourceIDs.formUnion(lateInvalidatedSourceIDs)        inputs.removeAll { lateInvalidatedSourceIDs.contains($0.id) }        return SpendDashboardLoadResult(            inputs: inputs,            failedSourceIDs: failedSourceIDs,            invalidatedSourceIDs: invalidatedSourceIDs)    }     private static func loadCodexSnapshot(        _ context: CodexSpendSnapshotLoadContext) async throws -> CostUsageTokenSnapshot    {        try await CostUsageFetcher(cacheRoot: context.cacheRoot).loadTokenSnapshot(            provider: .codex,            environment: CodexHomeScope.scopedEnvironment(base: [:], codexHome: context.account.homePath),            now: context.now,            forceRefresh: context.force,            codexHomePath: context.account.homePath,            historyDays: context.historyDays,            refreshPricingInBackground: context.refreshPricingInBackground,            includePiSessions: context.includePiSessions)    }     @MainActor    static func costCapableProviders(store: UsageStore) -> [UsageProvider] {        store.enabledProvidersForDisplay().filter {            ProviderDescriptorRegistry.descriptor(for: $0).tokenCost.supportsTokenCost        }    }     @MainActor    static func codexRequests(settings: SettingsStore, store: UsageStore) -> [CodexSpendScanRequest] {        let accounts = settings.codexVisibleAccountProjection.visibleAccounts        let providerName = store.metadata(for: .codex).displayName        return accounts.enumerated().compactMap { index, account in            let homePath: String? = switch account.selectionSource {            case .liveSystem:                settings.liveSystemCodexHomePath(forActiveSource: .liveSystem)            case let .managedAccount(id):                settings.managedCodexRemoteHomePath(forActiveSource: .managedAccount(id: id))            case let .profileHome(path):                settings.profileCodexHomePath(forActiveSource: .profileHome(path: path))            }            return self.codexRequest(                account: account,                homePath: homePath,                providerName: providerName,                index: index,                count: accounts.count)        }    }     @MainActor    private static func sourceRevisions(        providers: [UsageProvider],        settings: SettingsStore,        store: UsageStore) -> [String]    {        ["settings:\(settings.configRevision)"] + providers.compactMap { provider in            guard provider != .codex else { return nil }            let current = store.tokenSnapshotPublicationForCurrentProviderConfig(for: provider)            guard let current else { return "\(provider.rawValue):unavailable" }            guard let snapshot = current.snapshot else {                return "\(provider.rawValue):empty:\(current.publicationRevision)"            }            return "\(provider.rawValue):snapshot:\(current.publicationRevision):\(self.snapshotRevision(snapshot))"        }    }     private static func snapshotRevision(_ snapshot: CostUsageTokenSnapshot) -> String {        var encoder = SpendDashboardSnapshotRevisionEncoder()        encoder.append(snapshot.currencyCode)        encoder.append(snapshot.historyDays)        encoder.append(snapshot.historyCoverageIsEstablished)        encoder.append(snapshot.updatedAt.timeIntervalSinceReferenceDate)        encoder.append(snapshot.last30DaysTokens)        encoder.append(snapshot.last30DaysCostUSD)        encoder.append(snapshot.daily.count)        for entry in snapshot.daily {            encoder.append(entry.date)            encoder.append(entry.inputTokens)            encoder.append(entry.cacheReadTokens)            encoder.append(entry.cacheCreationTokens)            encoder.append(entry.outputTokens)            encoder.append(entry.totalTokens)            encoder.append(entry.requestCount)            encoder.append(entry.costUSD)            encoder.append(entry.modelBreakdowns?.count)            for breakdown in entry.modelBreakdowns ?? [] {                encoder.append(breakdown.modelName)                encoder.append(breakdown.totalTokens)                encoder.append(breakdown.requestCount)                encoder.append(breakdown.costUSD)                encoder.append(breakdown.standardCostUSD)                encoder.append(breakdown.priorityCostUSD)                encoder.append(breakdown.standardTokens)                encoder.append(breakdown.priorityTokens)            }        }        return encoder.finalize()    }     @MainActor    private static func sourceOwnershipFingerprints(        providers: [UsageProvider],        settings: SettingsStore,        store: UsageStore) -> [String]    {        providers.compactMap { provider in            guard provider != .codex else { return nil }            var config = settings.providerConfig(for: provider) ?? ProviderConfig(id: provider)            config.enabled = nil            config.quotaWarnings = nil            // The dashboard follows the effective account, not the whole saved-account collection.            // Inactive-account edits must not invalidate visible spend for the selected account.            config.tokenAccounts = nil            let encoder = JSONEncoder()            encoder.outputFormatting = [.sortedKeys]            let encoded = (try? encoder.encode(config)) ?? Data()            let scope = store.tokenSnapshotScopeSignature(for: provider)            let accountOwnership = settings.effectiveSelectedTokenAccount(for: provider)                .map { store.tokenAccountSnapshotCacheKey(provider: provider, account: $0) }                ?? "ambient"            return "\(provider.rawValue):\(self.sha256(encoded)):\(self.sha256(scope)):" +                self.sha256(accountOwnership)        }    }     static func codexRequest(        account: CodexVisibleAccount,        homePath: String?,        providerName: String,        index: Int,        count: Int) -> CodexSpendScanRequest?    {        guard let homePath = CodexHomeScope.normalizedHomePath(homePath) else { return nil }        var isDirectory: ObjCBool = false        guard FileManager.default.fileExists(atPath: homePath, isDirectory: &isDirectory),              isDirectory.boolValue,              FileManager.default.isReadableFile(atPath: homePath)        else { return nil }        let sourceToken = self.sourceToken(account.selectionSource)        let liveAuthFingerprint = CodexAuthFingerprint.fingerprint(homePath: homePath)        let authFingerprint = liveAuthFingerprint            ?? CodexAuthFingerprint.normalize(account.authFingerprint)        let cacheIdentity = self.sha256([            account.id,            sourceToken,            homePath,            authFingerprint ?? "missing-auth",        ].joined(separator: "\u{0}"))        let displayName = count == 1            ? providerName            : "\(providerName) · #\(codexBarLocalizedInteger(index + 1))"        return CodexSpendScanRequest(            id: account.id,            displayName: displayName,            source: account.selectionSource,            homePath: homePath,            authFingerprint: authFingerprint,            authFileWasReadable: liveAuthFingerprint != nil,            cacheIdentity: cacheIdentity)    }     private static func codexDisplayNamesByID(_ requests: [CodexSpendScanRequest]) -> [String: String] {        requests.reduce(into: [:]) { result, request in            result["codex:\(request.id)"] = request.displayName        }    }     private static func sourceToken(_ source: CodexActiveSource) -> String {        switch source {        case .liveSystem: "live"        case let .managedAccount(id): "managed:\(id.uuidString.lowercased())"        case let .profileHome(path): "profile:\(path)"        }    }     private static func sha256(_ value: String) -> String {        self.sha256(Data(value.utf8))    }     private static func sha256(_ value: Data) -> String {        SHA256.hash(data: value).map { String(format: "%02x", $0) }.joined()    }     private static func currentAuthFingerprint(for request: CodexSpendScanRequest) -> String? {        let current = CodexAuthFingerprint.fingerprint(homePath: request.homePath)        return request.authFileWasReadable ? current : current ?? request.authFingerprint    }} private struct SpendDashboardSnapshotRevisionEncoder {    private var hasher = SHA256()

Lines 1–500 of 1049.