SPB Git

Repository Public

AccountScreens.swift 29.3 KB 477 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Settings/AccountScreens.swift4//  Description: Account screens reached from the settings: usage and spending limits, memory, file library, data export.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Charts11import SwiftUI1213/// Where the spending stands against the owner's limits (pure: tested without UI).14enum BudgetLevel: Equatable, Sendable {15    case none, ok, alert, reached16    /// `limit <= 0` means "no limit". The alert threshold is a percentage of the limit.17    static func of(value: Double, limit: Double, alertAtPercent: Double) -> BudgetLevel {18        guard limit > 0 else { return .none }19        if value >= limit { return .reached }20        if alertAtPercent > 0, value >= limit * min(alertAtPercent, 100) / 100 { return .alert }21        return .ok22    }23    var color: Color { switch self { case .reached: .danger; case .alert: .warning; default: .accentColor } }24}2526/// Cost Intelligence: budgets and alerts, billed vs estimated, by route, by day, by model, by conversation.27/// Every block says where its figures come from; nothing is computed beyond sums of what the server returns.28struct UsageView: View {29    @Environment(AppEnvironment.self) private var env30    @Environment(\.accessibilityReduceMotion) private var reduceMotion31    @State private var report: UsageReport?32    @State private var days = 3033    @State private var error: String?34    @State private var isLoading = false35    @State private var editingBudget = false3637    /// Series colours: an iris → neutral ramp (never provider hues).38    static let ramp: [Color] = [.accentColor, .lumenMid, .textSecondary, .muted, .borderStrong, Color.accentColor.opacity(0.45)]3940    var body: some View {41        ScrollView {42            VStack(alignment: .leading, spacing: 16) {43                if let r = report {44                    alertBanner(r)45                    budget(r)46                    period(r)47                    if let b = r.costBasis, b.exact + b.estimated > 0 { basis(b) }48                    if !r.daily.isEmpty { daily(r) }49                    if let routes = r.byRoute, !routes.isEmpty { byRoute(routes) }50                    if !r.byModel.isEmpty { byModel(r) }51                    if let convs = r.byConversation, !convs.isEmpty { byConversation(convs) }52                } else if let error {53                    ContentUnavailableView { Label("Données indisponibles", systemImage: "wifi.slash") } description: { Text(error) } actions: { Button("Réessayer") { Task { await load() } } }54                        .padding(.top, 60)55                } else { ProgressView().frame(maxWidth: .infinity).padding(.top, 120) }56            }57            .padding(16)58            .frame(maxWidth: 720).frame(maxWidth: .infinity)59        }60        .background(Color.appBackground)61        .navigationTitle("Dépenses").navigationBarTitleDisplayMode(.inline)62        .task(id: days) { await load() }63        .refreshable { await load() }64        .sheet(isPresented: $editingBudget) {65            if let r = report { BudgetEditor(limits: r.spending.limits) { await load() }.presentationDetents([.medium, .large]) }66        }67        .accessibilityIdentifier("usage.screen")68    }6970    private func load() async {71        isLoading = true; defer { isLoading = false }72        do { let r = try await env.api.usage(days: days); withAnimation(Motion.smooth(reduceMotion)) { report = r }; error = nil }73        catch { if report == nil { self.error = (error as? APIError)?.message ?? String(localized: "Chargement impossible.") } }74    }7576    // MARK: blocks7778    private func block<Content: View>(_ title: String, source: String? = nil, @ViewBuilder content: () -> Content) -> some View {79        VStack(alignment: .leading, spacing: 12) {80            Text(title).font(.spHeading).foregroundStyle(Color.textPrimary).accessibilityAddTraits(.isHeader)81            content()82            if let source, !source.isEmpty { SourceNote(text: source) }83        }84        .padding(14).frame(maxWidth: .infinity, alignment: .leading)85        .cardSurface()86    }8788    @ViewBuilder private func alertBanner(_ r: UsageReport) -> some View {89        let l = r.spending.limits90        let day = BudgetLevel.of(value: r.spending.today, limit: l.dailyLimitUsd, alertAtPercent: l.alertAtPercent)91        let month = BudgetLevel.of(value: r.spending.month, limit: l.monthlyLimitUsd, alertAtPercent: l.alertAtPercent)92        if day == .reached || month == .reached {93            Banner(kind: .error, text: day == .reached ? String(localized: "Limite du jour atteinte : les nouvelles demandes sont refusées jusqu’à demain.") : String(localized: "Limite du mois atteinte : les nouvelles demandes sont refusées."))94                .accessibilityIdentifier("usage.alert")95        } else if day == .alert || month == .alert {96            Banner(kind: .warning, text: String(localized: "Seuil d’alerte de \(Int(l.alertAtPercent)) % dépassé\(day == .alert ? String(localized: " pour aujourd’hui") : String(localized: " pour ce mois"))."))97                .accessibilityIdentifier("usage.alert")98        }99    }100101    private func budget(_ r: UsageReport) -> some View {102        let l = r.spending.limits103        return block(String(localized: "Budget"), source: String(localized: "Estimations du serveur ; la facturation des fournisseurs fait foi. Une limite atteinte refuse les nouvelles demandes.")) {104            gauge(String(localized: "Aujourd’hui"), r.spending.today, l.dailyLimitUsd, l.alertAtPercent)105            gauge(String(localized: "Ce mois-ci"), r.spending.month, l.monthlyLimitUsd, l.alertAtPercent)106            HStack {107                Label(String(localized: "Alerte à \(Int(l.alertAtPercent)) %"), systemImage: "bell").font(.spCaption).foregroundStyle(Color.muted)108                Spacer()109                Button { editingBudget = true } label: { ChipLabel(text: String(localized: "Modifier"), systemImage: "slider.horizontal.3").frame(minHeight: 44) }110                    .buttonStyle(PressScale()).accessibilityLabel(String(localized: "Modifier les limites et le seuil d’alerte")).accessibilityIdentifier("usage.editBudget")111            }112        }113    }114115    private func gauge(_ title: String, _ value: Double, _ limit: Double, _ alert: Double) -> some View {116        let level = BudgetLevel.of(value: value, limit: limit, alertAtPercent: alert)117        return VStack(alignment: .leading, spacing: 7) {118            HStack(alignment: .firstTextBaseline) {119                Text(title).font(.subheadline).foregroundStyle(Color.textSecondary)120                Spacer()121                Text(Format.usd(value)).font(.system(.title3, weight: .semibold).monospacedDigit()).foregroundStyle(Color.textPrimary).contentTransition(.numericText())122                if limit > 0 { Text("/ \(Format.usd(limit))").font(.footnote.monospacedDigit()).foregroundStyle(Color.muted) }123            }124            if limit > 0 {125                GeometryReader { geo in126                    let w = geo.size.width, fraction = min(max(value / limit, 0), 1)127                    ZStack(alignment: .leading) {128                        Capsule().fill(Color.surface2)129                        Capsule().fill(level.color).frame(width: max(fraction * w, value > 0 ? 6 : 0))130                        // the alert threshold, as a tick on the track131                        if alert > 0, alert < 100 { Rectangle().fill(Color.textSecondary.opacity(0.7)).frame(width: 1.5, height: 12).offset(x: w * alert / 100 - 0.75) }132                    }133                }134                .frame(height: 8)135                .animation(Motion.smooth(reduceMotion), value: value)136            } else { Text("Aucune limite").font(.caption).foregroundStyle(Color.muted) }137        }138        .accessibilityElement(children: .ignore)139        .accessibilityLabel(limit > 0 ? String(localized: "\(title) : \(Format.usd(value)) sur \(Format.usd(limit)), \(Int(min(value / limit, 9.99) * 100)) %") : String(localized: "\(title) : \(Format.usd(value)), aucune limite"))140    }141142    private func period(_ r: UsageReport) -> some View {143        block(String(localized: "Période")) {144            Picker("Période", selection: $days) { Text("7 jours").tag(7); Text("30 jours").tag(30); Text("90 jours").tag(90) }.pickerStyle(.segmented)145                .accessibilityIdentifier("usage.period")146            LazyVGrid(columns: [GridItem(.adaptive(minimum: 104), spacing: 12, alignment: .topLeading)], alignment: .leading, spacing: 14) {147                FactCell(title: String(localized: "Coût"), value: Format.usd(r.totals.cost))148                FactCell(title: String(localized: "Demandes"), value: r.totals.requests.formatted(), note: r.totals.errors > 0 ? String(localized: "\(r.totals.errors) erreur(s)") : nil)149                FactCell(title: String(localized: "Jetons"), value: "\(Format.tokens(r.totals.inputTokens)) → \(Format.tokens(r.totals.outputTokens))", note: String(localized: "entrée → sortie"))150                if let l = r.totals.avgLatency { FactCell(title: String(localized: "Durée moyenne"), value: Format.duration(ms: l)) }151            }152        }153    }154155    /// Billed by the provider vs estimated from tokens × list price — one stacked bar, the server's note verbatim.156    private func basis(_ b: UsageReport.CostBasis) -> some View {157        let total = b.exact + b.estimated158        return block(String(localized: "Facturé ou estimé"), source: b.note) {159            GeometryReader { geo in160                HStack(spacing: 2) {161                    if b.exact > 0 { RoundedRectangle(cornerRadius: 4, style: .continuous).fill(Color.accentColor).frame(width: max(geo.size.width * b.exact / total - 1, 4)) }162                    if b.estimated > 0 { RoundedRectangle(cornerRadius: 4, style: .continuous).fill(Color.muted.opacity(0.55)) }163                }164            }165            .frame(height: 12)166            .accessibilityHidden(true)167            HStack(alignment: .top, spacing: 16) {168                legend(Color.accentColor, String(localized: "Facturé"), b.exact, total)169                legend(Color.muted.opacity(0.55), String(localized: "Estimé"), b.estimated, total)170            }171        }172        .accessibilityIdentifier("usage.basis")173    }174175    private func legend(_ color: Color, _ title: String, _ value: Double, _ total: Double) -> some View {176        HStack(alignment: .firstTextBaseline, spacing: 7) {177            RoundedRectangle(cornerRadius: 3, style: .continuous).fill(color).frame(width: 10, height: 10)178            VStack(alignment: .leading, spacing: 1) {179                Text(title).font(.spCaption).foregroundStyle(Color.muted)180                Text(Format.usd(value)).font(.subheadline.weight(.semibold).monospacedDigit()).foregroundStyle(Color.textPrimary)181                Text(total > 0 ? String(format: "%.0f %%", value / total * 100) : "—").font(.caption2.monospacedDigit()).foregroundStyle(Color.muted)182            }183        }184        .frame(maxWidth: .infinity, alignment: .leading)185        .accessibilityElement(children: .combine)186    }187188    private func daily(_ r: UsageReport) -> some View {189        // providers ordered by cost: the biggest takes the iris, the others the neutral steps of the ramp190        let order = Dictionary(grouping: r.daily, by: \.provider).mapValues { $0.reduce(0) { $0 + $1.cost } }.sorted { $0.value > $1.value }.map { AIModel.providerLabel($0.key) }191        return block(String(localized: "Par jour"), source: String(localized: "Coût par jour et par fournisseur exécutant (USD), d’après le journal d’utilisation du serveur.")) {192            Chart(r.daily) { d in193                BarMark(x: .value("Jour", d.day, unit: .day), y: .value("Coût", d.cost), width: .ratio(0.7))194                    .foregroundStyle(by: .value("Fournisseur", AIModel.providerLabel(d.provider)))195                    .cornerRadius(2)196            }197            .chartForegroundStyleScale(domain: order, range: Array(Self.ramp.prefix(max(order.count, 1))) + Array(repeating: Color.borderStrong, count: max(order.count - Self.ramp.count, 0)))198            .chartYAxis { AxisMarks(position: .leading) { v in AxisGridLine().foregroundStyle(Color.hairline); AxisValueLabel { if let x = v.as(Double.self) { Text(Format.usd(x)).font(.caption2) } } } }199            .chartXAxis { AxisMarks(values: .automatic(desiredCount: 5)) { _ in AxisValueLabel(format: .dateTime.day().month(.abbreviated)).font(.caption2) } }200            .chartLegend(position: .bottom, alignment: .leading, spacing: 10)201            .frame(height: 190)202            .accessibilityLabel(String(localized: "Coût par jour et par fournisseur"))203            .accessibilityIdentifier("usage.dailyChart")204        }205    }206207    private func byRoute(_ routes: [UsageReport.ByRoute]) -> some View {208        let sorted = routes.sorted { $0.cost > $1.cost }, top = max(sorted.first?.cost ?? 0, 0.000001)209        return block(String(localized: "Par route"), source: String(localized: "« Facturé » = montant rapporté par le fournisseur ; le reste est estimé (jetons × prix de liste).")) {210            VStack(spacing: 0) {211                ForEach(Array(sorted.enumerated()), id: \.element.id) { i, r in212                    if i > 0 { Divider() }213                    VStack(alignment: .leading, spacing: 6) {214                        HStack(spacing: 8) {215                            ModelMark(logo: LogoRegistry.slug(for: r.provider), name: AIModel.providerLabel(r.provider), size: 18)216                            Text(AIModel.providerLabel(r.provider)).font(.subheadline.weight(.medium)).foregroundStyle(Color.textPrimary).lineLimit(1)217                            if r.route == "openrouter" || r.route == "local" { RouteBadge(route: r.route) } else { Text("direct").font(.caption2).foregroundStyle(Color.muted) }218                            Spacer(minLength: 4)219                            Text("\(r.requests)").font(.caption.monospacedDigit()).foregroundStyle(Color.muted).accessibilityLabel(String(localized: "\(r.requests) demandes"))220                            Text(Format.usd(r.cost)).font(.subheadline.weight(.semibold).monospacedDigit()).foregroundStyle(Color.textPrimary).frame(minWidth: 70, alignment: .trailing)221                        }222                        GeometryReader { geo in223                            let w = geo.size.width * r.cost / top, exact = r.cost > 0 ? min(r.costExact / r.cost, 1) : 0224                            HStack(spacing: 0) {225                                Rectangle().fill(Color.accentColor).frame(width: w * exact)226                                Rectangle().fill(Color.muted.opacity(0.55)).frame(width: w * (1 - exact))227                            }228                            .clipShape(.capsule)229                        }230                        .frame(height: 4)231                        if r.costExact > 0 { Text(String(localized: "dont \(Format.usd(r.costExact)) facturé")).font(.caption2.monospacedDigit()).foregroundStyle(Color.muted) }232                    }233                    .padding(.vertical, 9)234                    .accessibilityElement(children: .combine)235                    .accessibilityIdentifier("usage.route")236                }237            }238        }239    }240241    private func byModel(_ r: UsageReport) -> some View {242        block(String(localized: "Par modèle"), source: String(localized: "Demandes et coût par modèle sur la période (journal d’utilisation du serveur).")) {243            VStack(spacing: 0) {244                ForEach(Array(r.byModel.prefix(12).enumerated()), id: \.element.id) { i, m in245                    let model = env.catalog.model(m.modelId)246                    if i > 0 { Divider() }247                    HStack(spacing: 8) {248                        ModelChip(logo: model?.logo ?? LogoRegistry.slug(for: m.provider), creatorName: model?.creatorName ?? AIModel.providerLabel(m.provider), name: model?.displayName ?? m.modelId,249                                  route: model?.route ?? AIModel.impliedRoute(id: m.modelId, provider: m.provider), markSize: 16, font: .subheadline)250                        Spacer(minLength: 4)251                        Text("\(m.requests)").font(.caption.monospacedDigit()).foregroundStyle(Color.muted).accessibilityLabel(String(localized: "\(m.requests) demandes"))252                        Text(Format.usd(m.cost)).font(.subheadline.weight(.semibold).monospacedDigit()).foregroundStyle(Color.textPrimary).frame(minWidth: 70, alignment: .trailing)253                    }254                    .frame(minHeight: 40)255                    .accessibilityElement(children: .combine)256                }257            }258        }259    }260261    private func byConversation(_ convs: [UsageReport.ByConversation]) -> some View {262        block(String(localized: "Par conversation"), source: String(localized: "Somme des coûts enregistrés par réponse. Touche une conversation pour l’ouvrir.")) {263            VStack(spacing: 0) {264                ForEach(Array(convs.prefix(12).enumerated()), id: \.element.id) { i, c in265                    if i > 0 { Divider() }266                    Button {267                        env.haptics.selection()268                        env.open(c.conversationId); env.router.sheet = nil269                    } label: {270                        HStack(spacing: 8) {271                            VStack(alignment: .leading, spacing: 2) {272                                Text(c.title).font(.subheadline).foregroundStyle(Color.textPrimary).lineLimit(1)273                                Text([String(localized: "\(c.requests) demande(s)"), c.lastAt.map { Format.relative($0) }].compactMap { $0 }.joined(separator: " · ")).font(.caption2).foregroundStyle(Color.muted)274                            }275                            Spacer(minLength: 4)276                            Text(Format.usd(c.cost)).font(.subheadline.weight(.semibold).monospacedDigit()).foregroundStyle(Color.textPrimary)277                            Image(systemName: "chevron.right").font(.caption2.weight(.bold)).foregroundStyle(Color.muted)278                        }279                        .frame(minHeight: 46).contentShape(.rect)280                    }281                    .buttonStyle(.plain)282                    .accessibilityHint(String(localized: "Ouvre la conversation"))283                    .accessibilityIdentifier("usage.conversation")284                }285            }286        }287    }288}289290/// Daily / monthly limits and the alert threshold (settings key `spending`, shared with the web app and the Mac).291struct BudgetEditor: View {292    let limits: UsageReport.Spending.Limits293    let onSaved: () async -> Void294    @Environment(AppEnvironment.self) private var env295    @Environment(\.dismiss) private var dismiss296    @State private var daily = ""297    @State private var monthly = ""298    @State private var alert = 80.0299    @State private var saving = false300    @State private var error: String?301302    static func number(_ s: String) -> Double? {303        let t = s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".")304        guard let v = Double(t), v >= 0, v.isFinite else { return nil }305        return v306    }307308    var body: some View {309        NavigationStack {310            Form {311                Section {312                    HStack { Text("Par jour ($)"); Spacer(); TextField("10", text: $daily).keyboardType(.decimalPad).multilineTextAlignment(.trailing).frame(maxWidth: 120).accessibilityIdentifier("budget.daily") }313                    HStack { Text("Par mois ($)"); Spacer(); TextField("150", text: $monthly).keyboardType(.decimalPad).multilineTextAlignment(.trailing).frame(maxWidth: 120).accessibilityIdentifier("budget.monthly") }314                } header: { Text("Limites") } footer: { Text("0 = aucune limite. Une limite atteinte fait refuser les nouvelles demandes par le serveur (toutes les apps).") }315                Section {316                    VStack(alignment: .leading) {317                        Text(String(localized: "Alerte à \(Int(alert)) % d’une limite")).font(.subheadline.monospacedDigit())318                        Slider(value: $alert, in: 10...100, step: 5).accessibilityLabel(String(localized: "Seuil d’alerte")).accessibilityValue("\(Int(alert)) %").accessibilityIdentifier("budget.alert")319                    }320                } header: { Text("Seuil d’alerte") } footer: { Text("Au-delà du seuil, le serveur joint un avertissement aux réponses et cet écran l’affiche.") }321                if let error { Section { Text(error).font(.footnote).foregroundStyle(Color.danger) } }322            }323            .navigationTitle("Budget").navigationBarTitleDisplayMode(.inline)324            .toolbar {325                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }326                ToolbarItem(placement: .confirmationAction) {327                    Button { Task { await save() } } label: { if saving { ProgressView() } else { Text("Enregistrer").fontWeight(.semibold) } }328                        .disabled(saving || Self.number(daily) == nil || Self.number(monthly) == nil)329                        .accessibilityIdentifier("budget.save")330                }331            }332            .onAppear { daily = String(format: "%g", limits.dailyLimitUsd); monthly = String(format: "%g", limits.monthlyLimitUsd); alert = min(max(limits.alertAtPercent, 10), 100) }333        }334    }335336    private func save() async {337        guard let d = Self.number(daily), let m = Self.number(monthly) else { error = String(localized: "Montants invalides."); return }338        saving = true; defer { saving = false }339        do {340            try await env.api.updateSetting(key: "spending", value: ["dailyLimitUsd": .number(d), "monthlyLimitUsd": .number(m), "alertAtPercent": .number(alert)])341            env.haptics.success()342            await onSaved()343            dismiss()344        } catch { self.error = (error as? APIError)?.message ?? String(localized: "Enregistrement impossible.") }345    }346}347348struct MemoryView: View {349    @Environment(AppEnvironment.self) private var env350    @State private var memories: [Memory] = []351    @State private var isLoading = true352    @State private var error: String?353    @State private var showAdd = false354    @State private var newText = ""355356    var body: some View {357        List {358            ForEach(memories) { m in359                VStack(alignment: .leading, spacing: 4) {360                    Text(m.content).font(.body).foregroundStyle(m.status == "disabled" ? Color.muted : Color.textPrimary)361                    HStack(spacing: 6) {362                        Text(m.category); if m.status == "candidate" { Text("· à approuver").foregroundStyle(Color.warning) }; if m.status == "disabled" { Text("· désactivée") }363                        if let t = m.sourceTitle { Text("· \(t)").lineLimit(1) }364                    }365                    .font(.caption).foregroundStyle(Color.muted)366                }367                .swipeActions(edge: .trailing) { Button(role: .destructive) { Task { await run { try await env.api.deleteMemory(m.id) } } } label: { Label("Supprimer", systemImage: "trash") } }368                .swipeActions(edge: .leading) {369                    if m.status == "active" { Button { Task { await run { try await env.api.setMemory(m.id, status: "disabled") } } } label: { Label("Désactiver", systemImage: "pause.circle") }.tint(.gray) }370                    else { Button { Task { await run { try await env.api.setMemory(m.id, status: "active") } } } label: { Label("Activer", systemImage: "checkmark.circle") }.tint(.green) }371                }372            }373        }374        .overlay {375            if isLoading && memories.isEmpty { ProgressView() }376            else if let error, memories.isEmpty { ContentUnavailableView { Label("Mémoire indisponible", systemImage: "wifi.slash") } description: { Text(error) } }377            else if memories.isEmpty { ContentUnavailableView { Label("Aucun souvenir", systemImage: "brain.head.profile") } description: { Text("Les faits durables que tu approuves sont rappelés aux modèles dans chaque conversation.") } }378        }379        .navigationTitle("Mémoire").navigationBarTitleDisplayMode(.inline)380        .toolbar { ToolbarItem(placement: .primaryAction) { Button { showAdd = true } label: { Image(systemName: "plus") }.accessibilityLabel(String(localized: "Ajouter un souvenir")) } }381        .alert("Nouveau souvenir", isPresented: $showAdd) {382            TextField("Le propriétaire préfère…", text: $newText)383            Button("Annuler", role: .cancel) { newText = "" }384            Button("Ajouter") { let t = newText.trimmingCharacters(in: .whitespacesAndNewlines); newText = ""; if t.count >= 3 { Task { await run { try await env.api.createMemory(content: String(t.prefix(2000))) } } } }385        }386        .task { await load() }387        .refreshable { await load() }388    }389390    private func load() async {391        isLoading = true; defer { isLoading = false }392        do { memories = try await env.api.memories(); error = nil } catch { self.error = (error as? APIError)?.message }393    }394    private func run(_ op: () async throws -> Void) async {395        do { try await op(); await load() } catch { self.error = (error as? APIError)?.message }396    }397}398399struct FilesView: View {400    @Environment(AppEnvironment.self) private var env401    @State private var files: [Attachment] = []402    @State private var storage: StorageInfo?403    @State private var isLoading = true404    @State private var error: String?405    @State private var previewURL: URL?406    @State private var query = ""407408    var body: some View {409        List {410            if let s = storage {411                Section { ProgressView(value: min(s.usedBytes / max(s.quotaMb * 1_048_576, 1), 1)) { Text("\(Format.bytes(Int(s.usedBytes))) sur \(Int(s.quotaMb)) Mo · \(s.files) fichier(s)").font(.footnote) } }412            }413            ForEach(files.filter { query.isEmpty || $0.filename.localizedStandardContains(query) }) { f in414                Button { Task { do { previewURL = try await env.files.fileURL(for: f.id, filename: f.filename) } catch { self.error = (error as? APIError)?.message } } } label: {415                    HStack(spacing: 12) {416                        Image(systemName: f.isImage ? "photo" : "doc.fill").foregroundStyle(Color.accentColor).frame(width: 26)417                        VStack(alignment: .leading, spacing: 2) {418                            Text(f.filename).foregroundStyle(Color.textPrimary).lineLimit(1)419                            Text([Format.bytes(f.sizeBytes), f.conversationTitle, f.indexStatus == "indexed" ? String(localized: "indexé") : nil].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption).foregroundStyle(Color.muted).lineLimit(1)420                        }421                    }422                    .contentShape(.rect)423                }424                .buttonStyle(.plain)425                .swipeActions { Button(role: .destructive) { Task { do { try await env.api.deleteAttachment(f.id); await load() } catch { self.error = (error as? APIError)?.message } } } label: { Label("Supprimer", systemImage: "trash") } }426            }427        }428        .overlay {429            if isLoading && files.isEmpty { ProgressView() }430            else if let error, files.isEmpty { ContentUnavailableView { Label("Fichiers indisponibles", systemImage: "wifi.slash") } description: { Text(error) } }431            else if files.isEmpty { ContentUnavailableView { Label("Aucun fichier", systemImage: "folder") } description: { Text("Les fichiers joints à tes messages apparaissent ici.") } }432        }433        .searchable(text: $query, prompt: Text("Rechercher un fichier"))434        .quickLookPreview($previewURL)435        .navigationTitle("Fichiers").navigationBarTitleDisplayMode(.inline)436        .task { await load() }437        .refreshable { await load() }438    }439440    private func load() async {441        isLoading = true; defer { isLoading = false }442        do { let r = try await env.api.files(); files = r.files; storage = r.storage; error = nil } catch { self.error = (error as? APIError)?.message }443    }444}445446struct DataView: View {447    @Environment(AppEnvironment.self) private var env448    @State private var exportURL: URL?449    @State private var busy = false450    @State private var error: String?451452    var body: some View {453        Form {454            Section {455                Button { Task { await export() } } label: { HStack { Label("Préparer l’export complet (JSON)", systemImage: "square.and.arrow.down"); if busy { Spacer(); ProgressView() } } }.disabled(busy)456                if let exportURL { ShareLink(item: exportURL) { Label("Enregistrer ou partager le fichier", systemImage: "square.and.arrow.up") } }457                if let error { Text(error).font(.footnote).foregroundStyle(Color.danger) }458            } footer: {459                Text("Toutes tes conversations, projets, souvenirs et prompts, dans un fichier JSON. La suppression complète des données se fait depuis la version web (Réglages → Données), derrière une vérification de clé d’accès.")460            }461        }462        .navigationTitle("Mes données").navigationBarTitleDisplayMode(.inline)463    }464465    private func export() async {466        busy = true; defer { busy = false }467        do {468            let data = try await env.api.fullExport()469            let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spchat-preview/export", isDirectory: true)470            try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)471            let url = dir.appendingPathComponent("SP Chat - export complet - \(Date().formatted(.iso8601.year().month().day())).json")472            try data.write(to: url, options: [.atomic, .completeFileProtectionUnlessOpen])473            exportURL = url; error = nil474        } catch { self.error = (error as? APIError)?.message ?? String(localized: "Export impossible.") }475    }476}477
Files main
Menu

Theme