SPB Git

Repository Public

UsageScreen.swift 32.5 KB 554 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/UsageScreen.swift3// Description: Cost Intelligence: budget and alert threshold, totals, spend over time, by route (direct vs OpenRouter), billed vs estimated, by model, by conversation, by kind and project (Swift Charts, iris ramp).4import SwiftUI5import Charts6import SPChatCore78@Observable final class UsageViewModel {9    enum Period: String, CaseIterable, Identifiable {10        case week, month30, quarter, thisMonth, custom11        var id: String { rawValue }12        var label: String { switch self { case .week: "7 jours"; case .month30: "30 jours"; case .quarter: "90 jours"; case .thisMonth: "Ce mois"; case .custom: "Personnalisé" } }13        func start(now: Date = Date()) -> Date {14            switch self {15            case .week: now.addingTimeInterval(-7 * 86_400)16            case .month30, .custom: now.addingTimeInterval(-30 * 86_400)17            case .quarter: now.addingTimeInterval(-90 * 86_400)18            case .thisMonth: Calendar.current.dateInterval(of: .month, for: now)?.start ?? now.addingTimeInterval(-30 * 86_400)19            }20        }21    }2223    var period: Period = .month3024    /// Bounds of the custom period (whole days, local calendar).25    var customFrom = Calendar.current.startOfDay(for: Date().addingTimeInterval(-13 * 86_400))26    var customTo = Date()27    /// Empty string = every provider.28    var provider = ""29    private(set) var report: UsageReport?30    private(set) var loading = false31    private(set) var error: String?32    private(set) var savingBudget = false33    @ObservationIgnored private var generation = 03435    /// The interval asked to the server for the current period.36    func interval(now: Date = Date(), calendar: Calendar = .current) -> (from: Date, to: Date) {37        guard period == .custom else { return (period.start(now: now), now.addingTimeInterval(60)) }38        let a = min(customFrom, customTo), b = max(customFrom, customTo)39        let end = calendar.date(byAdding: .day, value: 1, to: calendar.startOfDay(for: b)) ?? b40        return (calendar.startOfDay(for: a), end)41    }4243    func load(_ api: APIClient) async {44        generation += 1; let mine = generation45        loading = true; error = nil46        do {47            let i = interval()48            let r = try await api.usage(from: i.from, to: i.to, provider: provider.isEmpty ? nil : provider)49            guard mine == generation else { return }50            report = r51        } catch {52            guard mine == generation else { return }53            if (error as? APIError)?.kind != .cancelled { self.error = (error as? LocalizedError)?.errorDescription ?? String(describing: error) }54        }55        loading = false56    }5758    /// Shows a report that was obtained elsewhere (tests, previews).59    func show(_ r: UsageReport) { report = r; error = nil; loading = false }6061    /// `PATCH /api/settings {key: "spending"}` — the limits are the server's (shared with the web and iOS apps); 0 = no limit.62    func saveBudget(daily: Double, monthly: Double, alertAtPercent: Double, env: AppEnvironment) async -> Bool {63        savingBudget = true; defer { savingBudget = false }64        do {65            try await env.api.updateSetting(key: "spending", value: ["dailyLimitUsd": .number(max(daily, 0)), "monthlyLimitUsd": .number(max(monthly, 0)), "alertAtPercent": .number(min(max(alertAtPercent, 0), 100))])66            await env.catalog.reloadSettings()67            await load(env.api)68            env.toasts.show("Limites de dépenses enregistrées")69            return true70        } catch { env.toasts.error(error); return false }71    }72}7374struct UsageScreen: View {75    @Bindable var window: WindowModel76    @Environment(AppEnvironment.self) private var env77    @State private var model: UsageViewModel78    @State private var showBudgetEditor = false7980    /// `model` lets a caller (tests, previews) show a prepared state; the screen owns a fresh one otherwise.81    init(window: WindowModel, model: UsageViewModel = UsageViewModel()) { self.window = window; _model = State(initialValue: model) }8283    static let kindLabels: [String: String] = ["chat": "Conversation", "compare": "Arena", "research": "Recherche", "title": "Titres", "memory": "Mémoire", "embedding": "Embeddings",84                                               "image": "Images", "tts": "Synthèse vocale", "stt": "Transcription", "judge": "Juge de l'Arena", "tool": "Outils", "lens": "Lens", "followups": "Suggestions de suite"]85    private static let fr = Locale(identifier: "fr_CA")8687    var body: some View {88        ScrollView {89            VStack(alignment: .leading, spacing: DS.S.xl) {90                header91                if let error = model.error {92                    Banner(kind: .error, text: "Impossible de charger l'utilisation : \(error)", actionTitle: "Réessayer", action: { reload() })93                }94                if let report = model.report {95                    budget(report.spending)96                    if report.totals.requests == 0 {97                        EmptyStateView(systemImage: "chart.bar.xaxis", title: "Aucune utilisation sur cette période", message: "Change la période ou le fournisseur pour voir d'autres données.")98                            .frame(maxWidth: .infinity, minHeight: 220)99                    } else {100                        tiles(report)101                        overTime(report)102                        HStack(alignment: .top, spacing: DS.S.xl) {103                            byRoute(report.byRoute)104                            costBasis(report)105                        }106                        byModel(report.byModel, total: report.totals.cost)107                        if !report.byConversation.isEmpty { byConversation(report.byConversation) }108                        HStack(alignment: .top, spacing: DS.S.xl) {109                            byKind(report.byKind, total: report.totals.cost)110                            if report.byProject.count > 1 || report.byProject.contains(where: { $0.projectId != nil }) { byProject(report.byProject, total: report.totals.cost) }111                        }112                    }113                    Label(report.costBasis?.note ?? "Les montants sont des estimations locales, calculées à partir des jetons mesurés et des prix connus. La facturation réelle des fournisseurs peut différer.", systemImage: "info.circle")114                        .font(DS.F.caption).foregroundStyle(DS.C.muted)115                } else if model.loading {116                    Text("Chargement de l'utilisation…").font(DS.F.uiRegular).foregroundStyle(DS.C.muted).frame(maxWidth: .infinity, minHeight: 260)117                } else if model.error == nil {118                    EmptyStateView(systemImage: "chart.bar.xaxis", title: "Aucune donnée").frame(maxWidth: .infinity, minHeight: 260)119                }120            }121            .padding(DS.S.xxl).frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity)122        }123        .background(DS.C.bg)124        .accessibilityIdentifier("usage-screen")125        .task { if model.report == nil { await model.load(env.api) } }126        .onChange(of: model.period) { reload() }127        .onChange(of: model.provider) { reload() }128        .onChange(of: model.customFrom) { if model.period == .custom { reload() } }129        .onChange(of: model.customTo) { if model.period == .custom { reload() } }130    }131132    private func reload() { Task { await model.load(env.api) } }133134    // MARK: Header135136    private var header: some View {137        @Bindable var model = model138        return VStack(alignment: .leading, spacing: DS.S.l) {139            HStack(alignment: .firstTextBaseline, spacing: DS.S.l) {140                VStack(alignment: .leading, spacing: 2) {141                    Text("Utilisation").font(DS.F.title).foregroundStyle(DS.C.text)142                    Text("Ce que coûtent tes requêtes, par route, par modèle et par conversation — chaque montant dit s'il est facturé ou estimé.").font(DS.F.uiRegular).foregroundStyle(DS.C.text2).lineLimit(2)143                }144                Spacer(minLength: DS.S.l)145                if model.loading { Text("Actualisation…").font(DS.F.caption).foregroundStyle(DS.C.muted) }146                IconButton(systemImage: "arrow.clockwise", label: "Actualiser") { reload() }.disabled(model.loading)147            }148            HStack(spacing: DS.S.l) {149                Picker("Période", selection: $model.period) {150                    ForEach(UsageViewModel.Period.allCases) { Text($0.label).tag($0) }151                }152                .pickerStyle(.segmented).labelsHidden().fixedSize().accessibilityLabel("Période")153                if model.period == .custom {154                    DatePicker("Du", selection: $model.customFrom, in: ...model.customTo, displayedComponents: .date).fixedSize()155                    DatePicker("au", selection: $model.customTo, in: model.customFrom...Date(), displayedComponents: .date).fixedSize()156                }157                Spacer(minLength: DS.S.m)158                Picker("Fournisseur", selection: $model.provider) {159                    Text("Tous les fournisseurs").tag("")160                    ForEach(Provider.known, id: \.self) { Text(Provider.label($0)).tag($0) }161                }162                .labelsHidden().fixedSize().accessibilityLabel("Fournisseur")163            }164        }165    }166167    // MARK: Budget168169    private func budget(_ s: UsageReport.Spending) -> some View {170        VStack(alignment: .leading, spacing: DS.S.l) {171            HStack {172                Text("Budget").font(DS.F.heading).foregroundStyle(DS.C.text)173                Spacer()174                Button("Modifier les limites…") { showBudgetEditor = true }.controlSize(.small).accessibilityIdentifier("usage-edit-budget")175                    .popover(isPresented: $showBudgetEditor, arrowEdge: .bottom) {176                        BudgetEditor(limits: s.limits, saving: model.savingBudget) { d, m, a in177                            Task { if await model.saveBudget(daily: d, monthly: m, alertAtPercent: a, env: env) { showBudgetEditor = false } }178                        }179                    }180            }181            HStack(alignment: .top, spacing: DS.S.xxxl) {182                SpendingGauge(title: "Aujourd'hui", spent: s.today, limit: s.limits.dailyLimitUsd, alertAtPercent: s.limits.alertAtPercent)183                SpendingGauge(title: "Ce mois", spent: s.month, limit: s.limits.monthlyLimitUsd, alertAtPercent: s.limits.alertAtPercent)184            }185            Text("Limites enregistrées sur le serveur, communes au web et aux apps. Une limite atteinte refuse les nouvelles requêtes ; le trait marque le seuil d'alerte.").font(DS.F.caption).foregroundStyle(DS.C.muted)186        }187        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.xl)188    }189190    // MARK: Totals191192    private func tiles(_ r: UsageReport) -> some View {193        let t = r.totals194        let costSource: String = {195            guard let b = r.costBasis else { return "estimé" }196            if b.exact > 0 && b.estimated > 0 { return "\(Format.usd(b.exact, digits: 3)) facturé · \(Format.usd(b.estimated, digits: 3)) estimé" }197            return b.exact > 0 ? "facturé" : "estimé"198        }()199        return LazyVGrid(columns: Array(repeating: GridItem(.flexible(minimum: 120), spacing: DS.S.l), count: 5), spacing: DS.S.l) {200            UsageTile(title: "Coût de la période", value: Format.usd(t.cost, digits: 3), detail: costSource)201            UsageTile(title: "Requêtes", value: t.requests.formatted(.number.locale(Self.fr)), detail: t.errors > 0 ? "\(t.errors) en erreur" : "aucune erreur", tint: nil, detailTint: t.errors > 0 ? DS.C.danger : nil)202            UsageTile(title: "Jetons en entrée", value: Format.tokens(t.inputTokens), detail: t.cachedTokens > 0 ? "dont \(Format.tokens(t.cachedTokens)) lus en cache" : nil)203            UsageTile(title: "Jetons en sortie", value: Format.tokens(t.outputTokens), detail: t.reasoningTokens > 0 ? "dont \(Format.tokens(t.reasoningTokens)) de raisonnement" : nil)204            UsageTile(title: "Latence moyenne", value: Format.duration(ms: t.avgLatency), detail: t.avgTtft.map { "1er jeton : \(Format.duration(ms: $0))" })205        }206    }207208    // MARK: Over time209210    private func overTime(_ r: UsageReport) -> some View {211        let daily = r.daily212        // the provider that costs the most gets the strongest tone of the ramp213        let spent = Dictionary(daily.map { ($0.provider, $0.cost) }, uniquingKeysWith: +)214        let providers = spent.keys.sorted { (spent[$0] ?? 0, $1) > (spent[$1] ?? 0, $0) }215        var utc = Calendar(identifier: .gregorian); utc.timeZone = .gmt216        var dayFormat = Date.FormatStyle.dateTime.day().month(.abbreviated).locale(Self.fr); dayFormat.timeZone = .gmt217        var monthFormat = Date.FormatStyle.dateTime.month(.wide).year().locale(Self.fr); monthFormat.timeZone = .gmt218        return VStack(alignment: .leading, spacing: DS.S.l) {219            HStack(alignment: .firstTextBaseline) {220                Text("Dépense dans le temps").font(DS.F.heading).foregroundStyle(DS.C.text)221                Spacer()222                Text("par jour (UTC) et par fournisseur facturé").font(DS.F.caption).foregroundStyle(DS.C.muted)223            }224            if daily.isEmpty {225                Text("Aucune dépense sur cette période.").font(DS.F.uiRegular).foregroundStyle(DS.C.muted).frame(maxWidth: .infinity, minHeight: 120)226            } else {227                Chart(daily) { d in228                    BarMark(x: .value("Jour", d.day, unit: .day, calendar: utc), y: .value("Coût ($)", d.cost))229                        .foregroundStyle(by: .value("Fournisseur", Provider.label(d.provider)))230                        .cornerRadius(2)231                        .accessibilityLabel("\(d.day.formatted(dayFormat)), \(Provider.label(d.provider))")232                        .accessibilityValue("\(Format.usd(d.cost)), \(d.requests) requêtes")233                }234                .chartForegroundStyleScale(domain: providers.map { Provider.label($0) }, range: providers.indices.map { ChartScale.color($0, of: providers.count) })235                .chartXAxis { AxisMarks(values: .automatic(desiredCount: 8)) { _ in AxisGridLine().foregroundStyle(DS.C.border); AxisValueLabel(format: dayFormat).foregroundStyle(DS.C.muted) } }236                .chartYAxis { AxisMarks { v in AxisGridLine().foregroundStyle(DS.C.border); AxisValueLabel { if let c = v.as(Double.self) { Text(String(format: c < 1 ? "%.2f $" : "%.0f $", c)).foregroundStyle(DS.C.muted) } } } }237                .chartLegend(position: .bottom, alignment: .leading)238                .frame(height: 220)239            }240            if !r.monthly.isEmpty {241                Divider()242                HStack(alignment: .top, spacing: DS.S.xxxl) {243                    ForEach(r.monthly.prefix(6)) { m in244                        SourcedFigure(label: m.month.formatted(monthFormat), value: Format.usd(m.cost, digits: 3))245                            .frame(maxWidth: 170, alignment: .leading)246                    }247                    Spacer(minLength: 0)248                }249                Text("Mois civils complets, quelle que soit la période choisie.").font(.system(size: 10)).foregroundStyle(DS.C.muted)250            }251        }252        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.xl)253    }254255    // MARK: Route256257    private func byRoute(_ rows: [UsageReport.ByRoute]) -> some View {258        let direct = rows.filter { $0.route != "openrouter" && $0.route != "local" }.reduce(0) { $0 + $1.cost }, viaOR = rows.filter { $0.route == "openrouter" }.reduce(0) { $0 + $1.cost }259        let localRequests = rows.filter { $0.route == "local" }.reduce(0) { $0 + $1.requests }260        let top = rows.map(\.cost).max() ?? 0261        return VStack(alignment: .leading, spacing: DS.S.l) {262            Text("Par route").font(DS.F.heading).foregroundStyle(DS.C.text)263            if rows.isEmpty {264                Text("Le serveur ne fournit pas la répartition par route.").font(DS.F.uiRegular).foregroundStyle(DS.C.muted)265            } else {266                HStack(alignment: .top, spacing: DS.S.xxl) {267                    SourcedFigure(label: "API directes", value: Format.usd(direct, digits: 3), source: share(direct, of: direct + viaOR))268                    SourcedFigure(label: "Via OpenRouter", value: Format.usd(viaOR, digits: 3), source: share(viaOR, of: direct + viaOR))269                    if localRequests > 0 { SourcedFigure(label: "Local (MacLustr)", value: "0 $", source: "\(localRequests) requête\(localRequests > 1 ? "s" : "") · rien de facturé") }270                }271                Divider()272                Grid(alignment: .leading, horizontalSpacing: DS.S.l, verticalSpacing: DS.S.m) {273                    ForEach(rows) { r in274                        GridRow {275                            HStack(spacing: DS.S.s) {276                                ModelMark(logo: r.provider, name: Provider.label(r.provider), size: 15)277                                Text(Provider.label(r.provider)).font(DS.F.ui).foregroundStyle(DS.C.text).lineLimit(1)278                                RouteBadge(route: r.route)279                            }280                            ShareBar(fraction: top > 0 ? r.cost / top : 0, color: r.route == "openrouter" ? ChartScale.color(2, of: 3) : DS.C.accent).frame(minWidth: 60, maxWidth: .infinity)281                            Text("\(r.requests) req.").font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted).gridColumnAlignment(.trailing)282                            Text(Format.usd(r.cost)).font(DS.F.ui.monospacedDigit()).foregroundStyle(DS.C.text).gridColumnAlignment(.trailing)283                        }284                        .accessibilityElement(children: .ignore)285                        .accessibilityLabel("\(Provider.label(r.provider)), \(Provider.routeLabel(r.route)) : \(Format.usd(r.cost)), \(r.requests) requêtes")286                    }287                }288            }289        }290        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.xl)291    }292293    private func share(_ part: Double, of total: Double) -> String { total > 0 ? String(format: "%.0f %% de la période", part / total * 100) : " " }294295    // MARK: Billed vs estimated296297    private func costBasis(_ r: UsageReport) -> some View {298        VStack(alignment: .leading, spacing: DS.S.l) {299            Text("Facturé ou estimé").font(DS.F.heading).foregroundStyle(DS.C.text)300            if let b = r.costBasis {301                let total = b.exact + b.estimated302                HStack(alignment: .top, spacing: DS.S.xxl) {303                    SourcedFigure(label: "Facturé (exact)", value: Format.usd(b.exact, digits: 3), source: share(b.exact, of: total))304                    SourcedFigure(label: "Estimé", value: Format.usd(b.estimated, digits: 3), source: share(b.estimated, of: total))305                }306                GeometryReader { geo in307                    HStack(spacing: 2) {308                        if b.exact > 0 { RoundedRectangle(cornerRadius: 3).fill(DS.C.accent).frame(width: max(geo.size.width * (total > 0 ? b.exact / total : 0), 4)) }309                        RoundedRectangle(cornerRadius: 3).fill(ChartScale.color(3, of: 4))310                    }311                }312                .frame(height: 10)313                .accessibilityElement(children: .ignore).accessibilityLabel("Facturé \(Format.usd(b.exact)), estimé \(Format.usd(b.estimated))")314                HStack(spacing: DS.S.xl) {315                    LegendSwatch(color: DS.C.accent, text: "Facturé (exact)")316                    LegendSwatch(color: ChartScale.color(3, of: 4), text: "Estimé")317                }318                if let note = b.note, !note.isEmpty { Text(note).font(DS.F.caption).foregroundStyle(DS.C.text2).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }319                let exactRoutes = r.byRoute.filter { $0.costExact > 0 }320                if !exactRoutes.isEmpty {321                    Text("Montants facturés rapportés par : " + exactRoutes.map { "\(Provider.label($0.provider)) (\(Format.usd($0.costExact, digits: 3)))" }.joined(separator: ", ") + ".").font(DS.F.caption).foregroundStyle(DS.C.muted)322                }323            } else {324                Text("Le serveur ne distingue pas encore les montants facturés des estimations : tous les coûts affichés sont des estimations (jetons × prix connus).").font(DS.F.uiRegular).foregroundStyle(DS.C.muted)325            }326        }327        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.xl)328    }329330    // MARK: Tables331332    private func byModel(_ rows: [UsageReport.ByModel], total: Double) -> some View {333        let top = rows.map(\.cost).max() ?? 0334        return VStack(alignment: .leading, spacing: DS.S.l) {335            Text("Par modèle").font(DS.F.heading).foregroundStyle(DS.C.text)336            Grid(alignment: .trailing, horizontalSpacing: DS.S.xl, verticalSpacing: DS.S.m) {337                GridRow {338                    Text("Modèle").gridColumnAlignment(.leading)339                    Text("Part").gridColumnAlignment(.leading)340                    Text("Coût"); Text("Requêtes"); Text("Entrée"); Text("Sortie"); Text("Latence moy."); Text("Erreurs")341                }342                .font(DS.F.caption).foregroundStyle(DS.C.muted)343                Divider().gridCellUnsizedAxes(.horizontal)344                ForEach(rows) { r in345                    GridRow {346                        ModelChip(identity: env.catalog.identity(for: r.modelId), markSize: 15, font: DS.F.uiRegular)347                            .frame(maxWidth: .infinity, alignment: .leading)348                            .help("\(r.modelId) — facturé par \(Provider.label(r.provider))")349                        ShareBar(fraction: top > 0 ? r.cost / top : 0, color: DS.C.accent).frame(width: 150)350                        Text(Format.usd(r.cost)).foregroundStyle(DS.C.text)351                        Text(String(r.requests))352                        Text(Format.tokens(r.inputTokens))353                        Text(Format.tokens(r.outputTokens))354                        Text(Format.duration(ms: r.avgLatency))355                        Text(String(r.errors)).foregroundStyle(r.errors > 0 ? DS.C.danger : DS.C.muted)356                    }357                    .font(DS.F.uiRegular.monospacedDigit()).foregroundStyle(DS.C.text2)358                    .accessibilityElement(children: .ignore)359                    .accessibilityLabel("\(env.catalog.identity(for: r.modelId).accessibilityText) : \(r.requests) requêtes, \(Format.usd(r.cost)), \(r.errors) erreurs")360                }361            }362        }363        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.xl)364    }365366    private func byConversation(_ rows: [UsageReport.ByConversation]) -> some View {367        let top = rows.map(\.cost).max() ?? 0368        return VStack(alignment: .leading, spacing: DS.S.m) {369            HStack(alignment: .firstTextBaseline) {370                Text("Par conversation").font(DS.F.heading).foregroundStyle(DS.C.text)371                Spacer()372                Text("les \(rows.count) plus coûteuses de la période · clic pour ouvrir").font(DS.F.caption).foregroundStyle(DS.C.muted)373            }374            VStack(spacing: 0) {375                ForEach(rows) { r in ConversationCostRow(row: r, fraction: top > 0 ? r.cost / top : 0) { window.open(r.conversationId) } }376            }377        }378        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.xl)379    }380381    private func byKind(_ rows: [UsageReport.ByKind], total: Double) -> some View {382        breakdown(title: "Par type d'usage", rows: rows.map { (Self.kindLabels[$0.kind] ?? $0.kind, $0.requests, $0.cost) })383    }384    private func byProject(_ rows: [UsageReport.ByProject], total: Double) -> some View {385        breakdown(title: "Par projet", rows: rows.map { ($0.projectId == nil ? "Hors projet" : $0.project, $0.requests, $0.cost) })386    }387    private func breakdown(title: String, rows: [(label: String, requests: Int, cost: Double)]) -> some View {388        let top = rows.map(\.cost).max() ?? 0389        return VStack(alignment: .leading, spacing: DS.S.l) {390            Text(title).font(DS.F.heading).foregroundStyle(DS.C.text)391            Grid(alignment: .trailing, horizontalSpacing: DS.S.l, verticalSpacing: DS.S.m) {392                ForEach(Array(rows.enumerated()), id: \.offset) { _, r in393                    GridRow {394                        Text(r.label).font(DS.F.uiRegular).foregroundStyle(DS.C.text).lineLimit(1).gridColumnAlignment(.leading)395                        ShareBar(fraction: top > 0 ? r.cost / top : 0, color: DS.C.accent).frame(minWidth: 50, maxWidth: .infinity)396                        Text("\(r.requests) req.").font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted)397                        Text(Format.usd(r.cost)).font(DS.F.uiRegular.monospacedDigit()).foregroundStyle(DS.C.text)398                    }399                    .accessibilityElement(children: .ignore).accessibilityLabel("\(r.label) : \(Format.usd(r.cost)), \(r.requests) requêtes")400                }401            }402        }403        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.xl)404    }405}406407// MARK: - Pieces408409private struct UsageTile: View {410    let title: String411    let value: String412    var detail: String?413    var tint: Color?414    var detailTint: Color?415    var body: some View {416        VStack(alignment: .leading, spacing: 3) {417            Text(title).font(DS.F.caption).foregroundStyle(DS.C.muted).lineLimit(1)418            Text(value).font(.system(size: 22, weight: .semibold).monospacedDigit()).foregroundStyle(tint ?? DS.C.text).lineLimit(1).minimumScaleFactor(0.7).contentTransition(.numericText())419            Text(detail ?? " ").font(.system(size: 10.5)).foregroundStyle(detailTint ?? DS.C.muted).lineLimit(1).minimumScaleFactor(0.8)420        }421        .frame(maxWidth: .infinity, alignment: .leading).card(padding: DS.S.l)422        .accessibilityElement(children: .ignore).accessibilityLabel("\(title) : \(value)\(detail.map { ", " + $0 } ?? "")")423    }424}425426/// Thin horizontal bar: the share of a row relative to the largest row of its table.427private struct ShareBar: View {428    let fraction: Double429    let color: Color430    var body: some View {431        GeometryReader { geo in432            ZStack(alignment: .leading) {433                Capsule().fill(DS.C.surface2)434                Capsule().fill(color).frame(width: fraction > 0 ? max(geo.size.width * min(fraction, 1), 3) : 0)435            }436        }437        .frame(height: 6).accessibilityHidden(true)438    }439}440441private struct LegendSwatch: View {442    let color: Color443    let text: String444    var body: some View {445        HStack(spacing: 5) { RoundedRectangle(cornerRadius: 2).fill(color).frame(width: 10, height: 10); Text(text).font(DS.F.caption).foregroundStyle(DS.C.text2) }446    }447}448449private struct ConversationCostRow: View {450    let row: UsageReport.ByConversation451    let fraction: Double452    let open: () -> Void453    @State private var hover = false454    var body: some View {455        Button(action: open) {456            HStack(spacing: DS.S.l) {457                Image(systemName: "bubble.left").font(.system(size: 11)).foregroundStyle(DS.C.muted)458                Text(row.title.isEmpty ? "Sans titre" : row.title).font(DS.F.uiRegular).foregroundStyle(DS.C.text).lineLimit(1).frame(maxWidth: .infinity, alignment: .leading)459                ShareBar(fraction: fraction, color: DS.C.accent).frame(width: 140)460                Text("\(row.requests) req.").font(DS.F.caption.monospacedDigit()).foregroundStyle(DS.C.muted).frame(width: 56, alignment: .trailing)461                Text(row.lastAt.map { Format.relative($0) } ?? "—").font(DS.F.caption).foregroundStyle(DS.C.muted).frame(width: 64, alignment: .trailing)462                Text(Format.usd(row.cost)).font(DS.F.ui.monospacedDigit()).foregroundStyle(DS.C.text).frame(width: 78, alignment: .trailing)463                Image(systemName: "chevron.right").font(.system(size: 9, weight: .semibold)).foregroundStyle(DS.C.muted.opacity(hover ? 1 : 0.4))464            }465            .padding(.horizontal, DS.S.m).padding(.vertical, 7).contentShape(Rectangle())466            .background(hover ? DS.C.surface2 : .clear, in: RoundedRectangle(cornerRadius: DS.R.chip, style: .continuous))467        }468        .buttonStyle(.plain).onHover { hover = $0 }469        .accessibilityLabel("\(row.title.isEmpty ? "Sans titre" : row.title) : \(Format.usd(row.cost)), \(row.requests) requêtes. Ouvrir la conversation")470        .accessibilityIdentifier("usage-conversation-row")471    }472}473474/// Spending of a day / month against its limit; the tick marks the alert threshold.475private struct SpendingGauge: View {476    let title: String477    let spent: Double478    let limit: Double479    let alertAtPercent: Double480481    private var fraction: Double { limit > 0 ? min(max(spent / limit, 0), 1) : 0 }482    private var alert: Double { min(max(alertAtPercent / 100, 0), 1) }483    private var color: Color { limit > 0 && spent >= limit ? DS.C.danger : (limit > 0 && spent / limit >= alert ? DS.C.warn : DS.C.accent) }484    private var status: String {485        guard limit > 0 else { return "Aucune limite définie" }486        if spent >= limit { return "Limite atteinte" }487        if spent / limit >= alert { return "Seuil d'alerte (\(Int(alertAtPercent)) %) dépassé" }488        return String(format: "%.0f %% de la limite · alerte à %d %%", spent / limit * 100, Int(alertAtPercent))489    }490491    var body: some View {492        VStack(alignment: .leading, spacing: DS.S.s) {493            HStack(alignment: .firstTextBaseline) {494                Text(title).font(DS.F.ui).foregroundStyle(DS.C.text2)495                Spacer()496                Text(Format.usd(spent)).font(.system(size: 15, weight: .semibold).monospacedDigit()).foregroundStyle(DS.C.text)497                if limit > 0 { Text("/ \(Format.usd(limit))").font(DS.F.uiRegular.monospacedDigit()).foregroundStyle(DS.C.muted) }498            }499            GeometryReader { geo in500                ZStack(alignment: .leading) {501                    Capsule().fill(DS.C.surface2)502                    if limit > 0 {503                        Capsule().fill(color).frame(width: max(geo.size.width * fraction, fraction > 0 ? 4 : 0))504                        Rectangle().fill(DS.C.text.opacity(0.55)).frame(width: 1.5, height: geo.size.height + 6).offset(x: geo.size.width * alert - 1)505                    }506                }507            }508            .frame(height: 8)509            Text(status).font(DS.F.caption).foregroundStyle(limit > 0 && spent / limit >= alert ? color : DS.C.muted)510        }511        .frame(maxWidth: .infinity, alignment: .leading)512        .accessibilityElement(children: .ignore)513        .accessibilityLabel("\(title) : \(Format.usd(spent))\(limit > 0 ? " sur \(Format.usd(limit))" : ""). \(status)")514    }515}516517/// Edits the server's spending limits (settings key `spending`).518private struct BudgetEditor: View {519    let saving: Bool520    let onSave: (Double, Double, Double) -> Void521    @State private var daily: Double522    @State private var monthly: Double523    @State private var alert: Double524525    init(limits: UsageReport.Spending.Limits, saving: Bool, onSave: @escaping (Double, Double, Double) -> Void) {526        self.saving = saving; self.onSave = onSave527        _daily = State(initialValue: limits.dailyLimitUsd); _monthly = State(initialValue: limits.monthlyLimitUsd); _alert = State(initialValue: limits.alertAtPercent)528    }529530    var body: some View {531        VStack(alignment: .leading, spacing: DS.S.l) {532            Text("Limites de dépenses").font(DS.F.heading)533            Grid(alignment: .leading, horizontalSpacing: DS.S.l, verticalSpacing: DS.S.m) {534                GridRow {535                    Text("Limite quotidienne").foregroundStyle(DS.C.text2)536                    HStack(spacing: 4) { TextField("Limite quotidienne", value: $daily, format: .number.precision(.fractionLength(0...2))).labelsHidden().frame(width: 90).multilineTextAlignment(.trailing); Text("$") }537                }538                GridRow {539                    Text("Limite mensuelle").foregroundStyle(DS.C.text2)540                    HStack(spacing: 4) { TextField("Limite mensuelle", value: $monthly, format: .number.precision(.fractionLength(0...2))).labelsHidden().frame(width: 90).multilineTextAlignment(.trailing); Text("$") }541                }542                GridRow {543                    Text("Alerte à").foregroundStyle(DS.C.text2)544                    HStack { Slider(value: $alert, in: 10...100, step: 5).frame(width: 150).accessibilityLabel("Seuil d'alerte"); Text("\(Int(alert)) %").monospacedDigit().frame(width: 44, alignment: .trailing) }545                }546            }547            .font(DS.F.uiRegular)548            Text("0 = pas de limite. La facturation du fournisseur fait foi.").font(DS.F.caption).foregroundStyle(DS.C.muted)549            HStack { Spacer(); Button(saving ? "Enregistrement…" : "Enregistrer") { onSave(daily, monthly, alert) }.buttonStyle(.borderedProminent).tint(DS.C.accent).disabled(saving).keyboardShortcut(.defaultAction) }550        }551        .padding(DS.S.xl).fixedSize()552    }553}554
Files main
Menu

Theme