Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Features/Settings/ProvidersView.swift4// Description: Réglages → Fournisseurs: state of every provider, key test, and set / rotate / revoke of the OpenRouter5// and Tavily keys through the server. A key is typed in a SecureField, sent once and never kept or shown.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI1213/// Key-management operations of one screen, isolated so the flow is testable without UI.14@MainActor15@Observable16final class ProvidersModel {17 private(set) var providers: [ProviderInfo] = []18 private(set) var isLoading = false19 private(set) var busy: Set<String> = []20 /// Result of the last test / change per provider (shown under its row).21 private(set) var results: [String: ProviderCheck] = [:]22 var error: String?2324 @ObservationIgnored private let api: ChatAPI25 @ObservationIgnored private let catalog: ModelCatalog26 @ObservationIgnored private let settings: AccountSettings2728 init(api: ChatAPI, catalog: ModelCatalog, settings: AccountSettings) { self.api = api; self.catalog = catalog; self.settings = settings }2930 func load() async {31 isLoading = true; defer { isLoading = false }32 do { providers = try await api.providers().providers; error = nil }33 catch { if providers.isEmpty { self.error = (error as? APIError)?.message ?? String(localized: "Chargement impossible.") } }34 }3536 func test(_ id: String) async {37 busy.insert(id); defer { busy.remove(id) }38 do { results[id] = try await api.testProvider(id) }39 catch { results[id] = ProviderCheck(ok: false, message: (error as? APIError)?.message ?? String(localized: "Test impossible.")) }40 }4142 /// Sends the key to the server (which validates it with the provider and stores it encrypted). The key is not43 /// kept by this object: the caller clears its field whatever the outcome. Returns true when the key was accepted.44 func setKey(_ id: String, key: String) async -> Bool {45 let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines)46 guard !trimmed.isEmpty else { return false }47 busy.insert(id); defer { busy.remove(id) }48 do {49 try await api.setProviderKey(id, key: trimmed)50 results[id] = ProviderCheck(ok: true, message: String(localized: "Clé validée par le fournisseur et enregistrée sur le serveur."))51 await load(); await catalog.refreshModels(); await settings.refresh()52 return true53 } catch let e as APIError {54 if e.kind == .cancelled { return false }55 results[id] = ProviderCheck(ok: false, message: e.status == 422 ? String(localized: "Clé refusée par le fournisseur : \(e.message)") : e.message)56 return false57 } catch { results[id] = ProviderCheck(ok: false, message: String(localized: "Enregistrement impossible.")); return false }58 }5960 func revoke(_ id: String) async {61 busy.insert(id); defer { busy.remove(id) }62 do {63 let fallback = try await api.deleteProviderKey(id)64 results[id] = ProviderCheck(ok: true, message: fallback ? String(localized: "Clé révoquée. La clé de l’environnement du serveur prend le relais.") : String(localized: "Clé révoquée."))65 await load(); await catalog.refreshModels(); await settings.refresh()66 } catch let e as APIError { if e.kind != .cancelled { results[id] = ProviderCheck(ok: false, message: e.message) } }67 catch { }68 }6970 func refreshCatalog() async -> String? {71 busy.insert("catalog"); defer { busy.remove("catalog") }72 let e = await catalog.refreshFromProviders()73 await load()74 return e75 }76}7778struct ProvidersView: View {79 @Environment(AppEnvironment.self) private var env80 @State private var model: ProvidersModel?81 @State private var editing: ProviderInfo?82 @State private var revoking: ProviderInfo?83 @State private var catalogMessage: String?8485 var body: some View {86 List {87 if let model {88 let executing = model.providers.filter { $0.kind != "tool" }, tools = model.providers.filter { $0.kind == "tool" }89 if !executing.isEmpty { Section { ForEach(executing) { row($0, model) } } header: { Text("Modèles") } footer: { Text("« Directe » : l’API du créateur du modèle. OpenRouter : une route vers les modèles de nombreux créateurs. Locale : le service d’inférence MacLustr AI du propriétaire.") } }90 if !tools.isEmpty { Section { ForEach(tools) { row($0, model) } } header: { Text("Outils") } }91 Section {92 Button { Task { catalogMessage = await model.refreshCatalog() ?? String(localized: "Catalogue actualisé.") } } label: {93 HStack { Label("Actualiser le catalogue", systemImage: "arrow.triangle.2.circlepath"); Spacer(); if model.busy.contains("catalog") { ProgressView() } }94 }95 .disabled(model.busy.contains("catalog"))96 .accessibilityIdentifier("providers.refresh")97 if let d = env.catalog.catalogSyncedAt { LabeledContent("Catalogue OpenRouter", value: String(localized: "\(env.catalog.openRouter.count) modèles · \(Format.relative(d))")) }98 if let catalogMessage { Text(catalogMessage).font(.footnote).foregroundStyle(Color.textSecondary) }99 } header: { Text("Catalogue") } footer: {100 Text("Les clés ne quittent jamais le serveur : aucune n’est enregistrée ni affichée sur cet appareil (le Trousseau ne garde que la session). Définir, remplacer ou révoquer une clé demande une vérification récente par clé d’accès.")101 }102 if model.providers.isEmpty, let e = model.error {103 ContentUnavailableView { Label("Fournisseurs indisponibles", systemImage: "wifi.slash") } description: { Text(e) } actions: { Button("Réessayer") { Task { await model.load() } } }104 }105 } else { HStack { Spacer(); ProgressView(); Spacer() }.listRowBackground(Color.clear) }106 }107 .navigationTitle("Fournisseurs").navigationBarTitleDisplayMode(.inline)108 .task {109 if model == nil { model = ProvidersModel(api: env.api, catalog: env.catalog, settings: env.settings) }110 await model?.load()111 }112 .task(id: env.router.tick("provider")) { if env.router.tick("provider") > 0 { await model?.load() } }113 .refreshable { await model?.load() }114 .sheet(item: $editing) { p in ProviderKeySheet(provider: p) { key in await model?.setKey(p.id, key: key) ?? false }.presentationDetents([.medium]) }115 .confirmationDialog("Révoquer la clé \(revoking?.name ?? "") ?", isPresented: Binding(get: { revoking != nil }, set: { if !$0 { revoking = nil } }), titleVisibility: .visible) {116 Button("Révoquer", role: .destructive) { if let p = revoking { Task { await model?.revoke(p.id) } }; revoking = nil }117 } message: { Text("La clé enregistrée est effacée du serveur. Si le serveur a une clé d’environnement, elle prend le relais ; sinon ce fournisseur n’est plus utilisable.") }118 }119120 private func row(_ p: ProviderInfo, _ model: ProvidersModel) -> some View {121 VStack(alignment: .leading, spacing: 10) {122 HStack(spacing: 12) {123 ModelMark(logo: (p.logo?.isEmpty == false ? p.logo : nil) ?? LogoRegistry.slug(for: p.id), name: p.name, size: 24, color: true)124 VStack(alignment: .leading, spacing: 2) {125 HStack(spacing: 6) {126 Text(p.name).font(.body.weight(.semibold)).foregroundStyle(Color.textPrimary)127 RouteBadge(route: p.route)128 }129 if p.route == "local" { Text("Inférence locale MacLustr").font(.caption).foregroundStyle(Color.textSecondary) }130 Text(Self.keyLine(p)).font(.caption).foregroundStyle(Color.muted)131 }132 Spacer(minLength: 4)133 Circle().fill(p.configured ? (p.healthState == "ok" || p.healthState == nil ? Color.success : Color.warning) : Color.muted.opacity(0.5)).frame(width: 8, height: 8)134 .accessibilityLabel(p.configured ? String(localized: "configuré") : String(localized: "non configuré"))135 }136 let facts = [p.modelsChat.map { String(localized: "\($0) modèles de conversation") }, p.validatedAt.map { String(localized: "validée \(Format.relative($0))") }, p.healthState.flatMap { $0 == "ok" ? nil : String(localized: "santé : \($0)") }].compactMap { $0 }137 if !facts.isEmpty { Text(facts.joined(separator: " · ")).font(.caption).foregroundStyle(Color.textSecondary) }138 ForEach(p.info.keys.sorted(), id: \.self) { k in LabeledContent(k, value: p.info[k] ?? "").font(.caption) }139 if let r = model.results[p.id] {140 Label(r.message.isEmpty ? (r.ok ? String(localized: "Clé valide.") : String(localized: "Échec du test.")) : r.message, systemImage: r.ok ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")141 .font(.footnote).foregroundStyle(r.ok ? Color.success : Color.danger)142 .accessibilityIdentifier("providers.result")143 }144 HStack(spacing: 8) {145 if p.configured {146 Button { Task { await model.test(p.id) } } label: { ChipLabel(text: String(localized: "Tester"), systemImage: "bolt.horizontal") }147 .accessibilityIdentifier("providers.test.\(p.id)")148 }149 if p.manageable {150 Button { editing = p } label: { ChipLabel(text: p.keySource == "stored" ? String(localized: "Remplacer la clé") : String(localized: "Définir une clé"), systemImage: "key") }151 .accessibilityIdentifier("providers.setKey.\(p.id)")152 if p.keySource == "stored" { Button { revoking = p } label: { ChipLabel(text: String(localized: "Révoquer"), systemImage: "trash") } }153 }154 if model.busy.contains(p.id) { ProgressView().controlSize(.small) }155 }156 .buttonStyle(PressScale())157 .disabled(model.busy.contains(p.id))158 }159 .padding(.vertical, 4)160 }161162 static func keyLine(_ p: ProviderInfo) -> String {163 let hint = p.keyHint.map { " \($0)" } ?? ""164 switch p.keySource {165 case "stored": return String(localized: "Clé enregistrée sur le serveur\(hint)")166 case "env": return String(localized: "Clé de l’environnement du serveur\(hint)")167 default: return p.manageable ? String(localized: "Aucune clé") : String(localized: "Non configuré sur le serveur")168 }169 }170}171172/// The only place a provider key is typed. The field is cleared as soon as the request ends, accepted or not.173struct ProviderKeySheet: View {174 let provider: ProviderInfo175 /// Returns true when the server accepted the key.176 let submit: (String) async -> Bool177 @Environment(\.dismiss) private var dismiss178 @State private var key = ""179 @State private var sending = false180 @State private var failed = false181 @FocusState private var focused: Bool182183 var body: some View {184 NavigationStack {185 Form {186 Section {187 SecureField(provider.id == "tavily" ? "tvly-…" : provider.id == "local" ? "mlx_sk_…" : "sk-or-…", text: $key)188 .textContentType(.password).autocorrectionDisabled().textInputAutocapitalization(.never)189 .font(.system(.body, design: .monospaced)).focused($focused)190 .accessibilityIdentifier("providers.keyField")191 } header: { Text("Clé \(provider.name)") } footer: {192 Text("La clé est envoyée une seule fois au serveur, qui la valide auprès de \(provider.name) puis l’enregistre chiffrée. Elle n’est ni conservée ni affichée sur cet appareil. Une clé d’accès te sera demandée.")193 }194 if failed { Section { Label("La clé n’a pas été enregistrée. Le détail est indiqué sous le fournisseur.", systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Color.danger) } }195 }196 .navigationTitle(provider.keySource == "stored" ? "Remplacer la clé" : "Définir une clé").navigationBarTitleDisplayMode(.inline)197 .toolbar {198 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { key = ""; dismiss() } }199 ToolbarItem(placement: .confirmationAction) {200 Button {201 sending = true202 Task {203 let ok = await submit(key)204 key = ""; sending = false // never kept, whatever the outcome205 if ok { dismiss() } else { failed = true; dismiss() }206 }207 } label: { if sending { ProgressView() } else { Text("Enregistrer").fontWeight(.semibold) } }208 .disabled(sending || key.trimmingCharacters(in: .whitespacesAndNewlines).count < 8)209 .accessibilityIdentifier("providers.saveKey")210 }211 }212 .interactiveDismissDisabled(sending)213 .onAppear { focused = true }214 .onDisappear { key = "" }215 }216 }217}218