Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Settings/SettingsView.swift3// Description: Settings window (⌘,): general, conversation defaults, assistant (follow-ups, standing instructions), providers and keys, memory and spending limits (server), security (passkeys, sessions), data.4import SwiftUI5import SPChatCore67struct SettingsView: View {8 @Environment(AppEnvironment.self) private var env9 var body: some View {10 @Bindable var env = env11 TabView(selection: $env.settingsTab) {12 GeneralSettings().tabItem { Label("Général", systemImage: "gearshape") }.tag(SettingsTab.general)13 ChatSettings().tabItem { Label("Conversation", systemImage: "bubble.left.and.bubble.right") }.tag(SettingsTab.chat)14 AssistantSettings().tabItem { Label("Assistant", systemImage: "sparkles") }.tag(SettingsTab.assistant)15 ProvidersSettings().tabItem { Label("Fournisseurs", systemImage: "key.horizontal") }.tag(SettingsTab.providers)16 ServerSettingsPane().tabItem { Label("Mémoire et dépenses", systemImage: "brain") }.tag(SettingsTab.server)17 SecuritySettings().tabItem { Label("Sécurité", systemImage: "lock.shield") }.tag(SettingsTab.security)18 DataSettings().tabItem { Label("Données", systemImage: "externaldrive") }.tag(SettingsTab.data)19 }20 .frame(width: 720, height: 560)21 .modifier(ToastOverlay(center: env.toasts))22 }23}2425private struct SignedOutNotice: View {26 var body: some View { EmptyStateView(systemImage: "lock", title: "Connexion requise", message: "Connecte-toi avec ta clé d'accès pour voir ces réglages.") }27}2829struct GeneralSettings: View {30 @Environment(AppEnvironment.self) private var env31 var body: some View {32 @Bindable var p = env.preferences33 Form {34 Section("Apparence") {35 Picker("Thème", selection: $p.appearance) { ForEach(AppearanceMode.allCases) { Text($0.label).tag($0) } }.pickerStyle(.segmented)36 LabeledContent("Taille du texte") {37 HStack { Slider(value: $p.textScale, in: 0.85...1.5, step: 0.05).frame(width: 220); Text("\(Int(p.textScale * 100)) %").monospacedDigit().frame(width: 48, alignment: .trailing) }38 }39 Toggle("Afficher le raisonnement des modèles", isOn: $p.showReasoning)40 }41 Section("Intégration macOS") {42 Toggle("Icône dans la barre des menus", isOn: $p.showMenuBarIcon)43 Toggle("Raccourci global ⌥⌘Espace pour le chat rapide", isOn: $p.quickChatHotKey)44 Toggle("Notification quand une réponse se termine en arrière-plan", isOn: Binding(get: { p.notifyOnCompletion }, set: { on in45 if on { Task { let ok = await env.notifications.requestAuthorization(); p.notifyOnCompletion = ok; if !ok { env.toasts.show("Notifications refusées dans Réglages Système.", isError: true) } } } else { p.notifyOnCompletion = false }46 }))47 }48 Section("À propos") {49 LabeledContent("Version", value: "\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?") (\(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "?"))")50 LabeledContent("Serveur", value: env.server.host)51 LabeledContent("Mises à jour") { Text(UpdateChecker.statusText).foregroundStyle(.secondary) }52 }53 }54 .formStyle(.grouped)55 }56}5758struct ChatSettings: View {59 @Environment(AppEnvironment.self) private var env60 var body: some View {61 @Bindable var p = env.preferences62 Form {63 Section("Rédaction") {64 Picker("Envoyer avec", selection: $p.sendWithReturn) { Text("Retour (⇧Retour : nouvelle ligne)").tag(true); Text("⌘Retour (Retour : nouvelle ligne)").tag(false) }65 Toggle("Réduire les photos avant l'envoi (2048 px, JPEG)", isOn: $p.compressImages)66 }67 Section("Nouvelles conversations") {68 Picker("Modèle", selection: $p.modelId) {69 Text("Défaut du serveur").tag(String?.none)70 ForEach(env.catalog.menuModels) { Text($0.isOpenRouter ? "\($0.displayName) — \($0.creatorName) · OpenRouter" : "\($0.displayName) — \($0.creatorName)").tag(String?.some($0.id)) }71 // a model picked from the catalogue stays selectable here even when it is not in the short list72 if let id = p.modelId, let m = env.catalog.model(id), !env.catalog.menuModels.contains(where: { $0.id == id }) { Text("\(m.displayName) — \(m.creatorName)").tag(String?.some(id)) }73 }74 Picker("Routage", selection: $p.routingMode) { ForEach(RoutingMode.allCases, id: \.self) { Text($0.label).tag($0) } }75 Picker("Effort de raisonnement", selection: $p.effort) { Text("Par défaut").tag(Effort?.none); ForEach(Effort.allCases, id: \.self) { Text($0.label).tag(Effort?.some($0)) } }76 Toggle("Outils activés", isOn: $p.toolsEnabled)77 Toggle("Recherche web activée", isOn: $p.webSearch)78 }79 Section("Compositeur") {80 Toggle("Dock des modèles favoris au-dessus du compositeur", isOn: $p.showDock)81 Toggle("Proposer un « modèle suggéré » pendant la rédaction", isOn: $p.suggestModel)82 }83 Section("Recherche et audio") {84 Toggle("Recherche sémantique dans les messages", isOn: $p.semanticSearch)85 Picker("Voix de lecture", selection: $p.ttsVoice) { ForEach(Preferences.voices, id: \.self) { Text($0.capitalized).tag($0) } }86 Picker("Langue de dictée", selection: $p.dictationLanguage) { Text("Automatique").tag(""); Text("Français").tag("fr"); Text("English").tag("en") }87 }88 }89 .formStyle(.grouped)90 .task { if env.session.phase == .signedIn, !env.catalog.loaded { await env.catalog.load() } }91 }92}9394/// Owner preferences stored on the server (shared with the web app): memory and spending limits.95struct ServerSettingsPane: View {96 @Environment(AppEnvironment.self) private var env97 @State private var memoryEnabled = true98 @State private var autoExtract = true99 @State private var daily = 10.0100 @State private var monthly = 150.0101 @State private var alert = 80.0102 @State private var loaded = false103 @State private var usage: UsageReport.Spending?104105 var body: some View {106 if env.session.phase != .signedIn { SignedOutNotice() } else {107 Form {108 Section("Mémoire") {109 Toggle("Injecter la mémoire approuvée dans les conversations", isOn: $memoryEnabled)110 Toggle("Proposer automatiquement de nouveaux souvenirs", isOn: $autoExtract).disabled(!memoryEnabled)111 }112 Section {113 LabeledContent("Limite quotidienne") { HStack { TextField("", value: $daily, format: .number.precision(.fractionLength(0...2))).frame(width: 80).multilineTextAlignment(.trailing); Text("$") } }114 LabeledContent("Limite mensuelle") { HStack { TextField("", value: $monthly, format: .number.precision(.fractionLength(0...2))).frame(width: 80).multilineTextAlignment(.trailing); Text("$") } }115 LabeledContent("Alerte à") { HStack { Slider(value: $alert, in: 10...100, step: 5).frame(width: 180); Text("\(Int(alert)) %").monospacedDigit().frame(width: 44, alignment: .trailing) } }116 if let u = usage { LabeledContent("Dépensé", value: "\(Format.usd(u.today, digits: 2)) aujourd'hui · \(Format.usd(u.month, digits: 2)) ce mois-ci") }117 } header: { Text("Dépenses") } footer: { Text("Limites locales du serveur : une fois atteintes, les nouvelles requêtes sont refusées. La facturation du fournisseur fait foi. 0 = pas de limite.") }118 Section("Intégrations du serveur") {119 ForEach(env.catalog.settings.integrations.sorted { $0.key < $1.key }, id: \.key) { k, on in120 LabeledContent(Provider.label(k)) { Label(on ? "Configuré" : "Absent", systemImage: on ? "checkmark.circle.fill" : "minus.circle").foregroundStyle(on ? Palette.success : .secondary) }121 }122 }123 HStack { Spacer(); Button("Enregistrer") { save() }.buttonStyle(.borderedProminent).disabled(!loaded) }124 }125 .formStyle(.grouped)126 .task { await load() }127 }128 }129130 private func load() async {131 await env.catalog.reloadSettings()132 let s = env.catalog.settings.settings133 memoryEnabled = s["memory"]?["enabled"]?.boolValue ?? true; autoExtract = s["memory"]?["autoExtract"]?.boolValue ?? true134 daily = s["spending"]?["dailyLimitUsd"]?.doubleValue ?? 10; monthly = s["spending"]?["monthlyLimitUsd"]?.doubleValue ?? 150; alert = s["spending"]?["alertAtPercent"]?.doubleValue ?? 80135 usage = try? await env.api.usage().spending136 loaded = true137 }138 private func save() {139 Task {140 do {141 var memory = env.catalog.settings.settings["memory"]?.objectValue ?? [:]142 memory["enabled"] = .bool(memoryEnabled); memory["autoExtract"] = .bool(autoExtract)143 try await env.api.updateSetting(key: "memory", value: memory)144 try await env.api.updateSetting(key: "spending", value: ["dailyLimitUsd": .number(max(daily, 0)), "monthlyLimitUsd": .number(max(monthly, 0)), "alertAtPercent": .number(alert)])145 await env.catalog.reloadSettings(); env.toasts.show("Réglages enregistrés")146 } catch { env.toasts.error(error) }147 }148 }149}150151// MARK: - Security152153struct SecuritySettings: View {154 @Environment(AppEnvironment.self) private var env155 @State private var overview: PasskeyOverview?156 @State private var sessions: [DeviceSession] = []157 @State private var events: [AuthEvent] = []158 @State private var codes: [String] = []159 @State private var renaming: Passkey?160 @State private var renameText = ""161 @State private var revoking: Passkey?162 @State private var newLabel = Host.current().localizedName ?? "Mac"163 @State private var busy = false164 @State private var confirmSignOutAll = false165166 var body: some View {167 if env.session.phase != .signedIn { SignedOutNotice() } else {168 Form {169 Section {170 ForEach(overview?.passkeys ?? []) { k in171 HStack {172 Image(systemName: k.synced == true ? "icloud" : "key.horizontal").foregroundStyle(.secondary).frame(width: 20)173 VStack(alignment: .leading, spacing: 1) {174 HStack { Text(k.label ?? "Clé d'accès"); if k.current { StatusPill(text: "cette session", color: Palette.iris) } }175 Text("Créée \(k.createdAt.map { Format.relative($0) } ?? "?") · utilisée \(k.lastUsedAt.map { Format.relative($0) } ?? "jamais")\(k.synced == true ? " · synchronisée" : "")").font(.caption).foregroundStyle(.secondary)176 }177 Spacer()178 Button("Renommer") { renameText = k.label ?? ""; renaming = k }.controlSize(.small)179 Button("Révoquer", role: .destructive) { revoking = k }.controlSize(.small).disabled((overview?.passkeys.count ?? 0) <= 1)180 }181 }182 HStack {183 TextField("Nom de la nouvelle clé", text: $newLabel).textFieldStyle(.roundedBorder).frame(maxWidth: 220)184 Button("Ajouter une clé d'accès sur ce Mac") { run("Clé d'accès ajoutée") { try await env.auth.reauthenticate(); try await env.auth.registerPasskey(label: newLabel) } }185 }186 } header: { Text("Clés d'accès") } footer: { Text("Ajouter, renommer ou révoquer une clé demande une vérification récente (Touch ID). La dernière clé ne peut pas être révoquée.") }187188 Section {189 LabeledContent("Codes restants", value: "\(overview?.recovery.remaining ?? 0)")190 if !codes.isEmpty {191 VStack(alignment: .leading, spacing: 4) {192 Text("Note ces codes maintenant : ils ne seront plus jamais affichés.").font(.caption).foregroundStyle(Palette.warning)193 Text(codes.joined(separator: "\n")).font(.callout.monospaced()).textSelection(.enabled)194 Button("Copier les codes") { Pasteboard.copy(codes.joined(separator: "\n")); env.toasts.show("Codes copiés — colle-les dans un endroit sûr") }.controlSize(.small)195 }196 }197 Button("Générer 8 nouveaux codes de récupération") { run(nil) { codes = try await env.auth.generateRecoveryCodes() } }198 } header: { Text("Récupération") } footer: { Text("Générer de nouveaux codes invalide les précédents.") }199200 Section("Appareils connectés") {201 ForEach(sessions) { s in202 HStack {203 Image(systemName: (s.label ?? "").contains("iPhone") ? "iphone" : "laptopcomputer").foregroundStyle(.secondary).frame(width: 20)204 VStack(alignment: .leading, spacing: 1) {205 HStack { Text(s.label ?? "Appareil"); if s.current { StatusPill(text: "ce Mac", color: Palette.iris) } }206 Text("Vu \(s.lastSeen.map { Format.relative($0) } ?? "?") · \(s.ip ?? "")").font(.caption).foregroundStyle(.secondary)207 }208 Spacer()209 if !s.current { Button("Déconnecter") { run("Appareil déconnecté") { _ = try await env.auth.revokeSession(s.id) } }.controlSize(.small) }210 }211 }212 HStack {213 Button("Déconnecter tous les autres appareils") { run("Autres appareils déconnectés") { try await env.auth.revokeAllSessions(includeCurrent: false) } }214 Spacer()215 Button("Se déconnecter de ce Mac") { Task { await env.session.signOut() } }216 }217 }218219 Section("Journal de sécurité") {220 ForEach(events.prefix(12)) { e in221 HStack { Text(e.event).font(.caption.monospaced()); Spacer(); Text(e.ip ?? "").font(.caption2).foregroundStyle(.tertiary); Text(Format.relative(e.at)).font(.caption).foregroundStyle(.secondary) }222 }223 }224 }225 .formStyle(.grouped).disabled(busy)226 .task { await load() }227 .alert("Renommer la clé d'accès", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {228 TextField("Nom", text: $renameText)229 Button("Renommer") { if let k = renaming { run("Clé renommée") { try await env.auth.renamePasskey(k.id, label: renameText) } } }230 Button("Annuler", role: .cancel) {}231 }232 .confirmationDialog("Révoquer « \(revoking?.label ?? "") » ?", isPresented: Binding(get: { revoking != nil }, set: { if !$0 { revoking = nil } }), titleVisibility: .visible) {233 Button("Révoquer la clé", role: .destructive) { if let k = revoking { run("Clé révoquée") { _ = try await env.auth.revokePasskey(k.id) } } }234 } message: { Text("Les sessions ouvertes avec cette clé seront fermées.") }235 }236 }237238 private func load() async {239 overview = try? await env.auth.passkeys(); sessions = (try? await env.auth.sessions()) ?? []; events = (try? await env.auth.events()) ?? []240 }241 private func run(_ success: String?, _ work: @escaping () async throws -> Void) {242 Task {243 busy = true; defer { busy = false }244 do { try await work(); if let success { env.toasts.show(success) }; await load() }245 catch let e as PasskeyError { if e.code != .cancelled { env.toasts.show(e.message, isError: true) } }246 catch { env.toasts.error(error) }247 }248 }249}250251// MARK: - Data252253struct DataSettings: View {254 @Environment(AppEnvironment.self) private var env255 @State private var summary: OwnerSummary?256 @State private var cacheStats: (conversations: Int, details: Int, messages: Int)?257 @State private var confirmWipe = false258 @State private var wipeText = ""259 @State private var includeUsage = false260261 var body: some View {262 if env.session.phase != .signedIn { SignedOutNotice() } else {263 Form {264 Section("Sur le serveur") {265 if let s = summary {266 LabeledContent("Conversations", value: "\(s.conversations)"); LabeledContent("Messages", value: "\(s.messages)")267 LabeledContent("Fichiers", value: "\(s.files) · \(Format.bytes(s.fileBytes))"); LabeledContent("Projets / souvenirs", value: "\(s.projects) / \(s.memories)")268 } else { ProgressView().controlSize(.small) }269 Button("Exporter toutes mes données (JSON)…") {270 Task { do { let f = try await env.api.fullExport(); SavePanel.save(f.data, name: f.filename ?? "Chat SPB - export complet.json", type: .json, env: env) } catch { env.toasts.error(error) } }271 }272 }273 Section {274 if let c = cacheStats { LabeledContent("Contenu", value: "\(c.conversations) conversations · \(c.details) fils complets · \(c.messages) messages") }275 Button("Vider le cache local") { Task { try? await env.cache?.wipe(); env.files.purge(); await refresh(); await env.conversations.refresh(); env.toasts.show("Cache local vidé") } }276 } header: { Text("Cache local (lecture hors ligne)") } footer: { Text("Le cache est stocké dans le bac à sable de l'application et effacé à la déconnexion. La session est conservée dans le trousseau de ce Mac.") }277 Section {278 Toggle("Effacer aussi l'historique des coûts", isOn: $includeUsage)279 Button("Supprimer tout mon contenu…", role: .destructive) { wipeText = ""; confirmWipe = true }280 } header: { Text("Zone dangereuse") } footer: { Text("Supprime conversations, messages, fichiers, mémoires, projets et prompts du serveur. Demande une vérification par clé d'accès. Les sauvegardes du serveur expirent sous 14 jours.") }281 }282 .formStyle(.grouped)283 .task { await refresh() }284 .alert("Supprimer définitivement tout le contenu ?", isPresented: $confirmWipe) {285 TextField("Tape SUPPRIMER TOUT", text: $wipeText)286 Button("Supprimer", role: .destructive) {287 guard wipeText == "SUPPRIMER TOUT" else { env.toasts.show("Phrase de confirmation incorrecte : rien n'a été supprimé.", isError: true); return }288 Task {289 do { try await env.api.wipeAllData(includeUsage: includeUsage); try? await env.cache?.wipe(); env.files.purge(); env.conversations.reset(); await env.conversations.refresh(); await refresh(); env.toasts.show("Contenu supprimé") }290 catch let e as PasskeyError { if e.code != .cancelled { env.toasts.show(e.message, isError: true) } } catch { env.toasts.error(error) }291 }292 }293 Button("Annuler", role: .cancel) {}294 } message: { Text("Cette action est irréversible. Tape SUPPRIMER TOUT pour confirmer.") }295 }296 }297 private func refresh() async { summary = try? await env.api.ownerSummary(); cacheStats = try? await env.cache?.stats() }298}299300/// Update architecture hook. Version 1.0 ships without automatic updates: the feed URL (Info.plist `SPChatUpdateFeedURL`)301/// is empty. See docs/UPDATES.md for the signed-appcast design this hook is reserved for.302enum UpdateChecker {303 static var feedURL: URL? { (Bundle.main.infoDictionary?["SPChatUpdateFeedURL"] as? String).flatMap { $0.isEmpty ? nil : URL(string: $0) } }304 static var statusText: String { feedURL == nil ? "Manuelles (nouveau DMG sur git.spboucher.ai)" : "Automatiques" }305}306307/// Synced assistant preferences: Smart Follow-Ups (`assistant.followUps`) and the owner's standing instructions308/// (`instructions {text, enabled}`), applied by the server to every conversation on every device.309struct AssistantSettings: View {310 @Environment(AppEnvironment.self) private var env311 @State private var followUps = true312 @State private var instructions = ""313 @State private var instructionsEnabled = false314 @State private var loaded = false315 @State private var saving = false316 @State private var savedText = ""317 @State private var savedEnabled = false318319 private var dirty: Bool { instructions != savedText || instructionsEnabled != savedEnabled }320321 var body: some View {322 if env.session.phase != .signedIn { EmptyStateView(systemImage: "lock", title: "Connexion requise", message: "Connecte-toi avec ta clé d'accès pour voir ces réglages.") } else {323 Form {324 Section {325 Toggle("Proposer des suites après chaque réponse", isOn: Binding(get: { followUps }, set: { on in followUps = on; save(key: "assistant", value: ["followUps": .bool(on)]) })).disabled(!loaded)326 } header: { Text("Smart Follow-Ups") } footer: { Text("Jusqu'à trois questions de suite, générées par le serveur après la réponse. Réglage synchronisé avec le site et l'app iOS.") }327 Section {328 Toggle("Appliquer mes instructions à toutes les conversations", isOn: $instructionsEnabled).disabled(!loaded)329 TextEditor(text: $instructions).font(.system(size: 13)).frame(minHeight: 190).scrollContentBackground(.hidden).padding(6)330 .background(DS.C.surface, in: RoundedRectangle(cornerRadius: DS.R.control)).overlay(RoundedRectangle(cornerRadius: DS.R.control).strokeBorder(DS.C.border))331 .accessibilityLabel("Instructions permanentes").accessibilityIdentifier("standing-instructions").disabled(!loaded)332 HStack {333 Text("\(instructions.count) caractères").font(.caption).foregroundStyle(.secondary)334 Spacer()335 if saving { ProgressView().controlSize(.small) }336 Button("Rétablir") { instructions = savedText; instructionsEnabled = savedEnabled }.disabled(!dirty)337 Button("Enregistrer") { save(key: "instructions", value: ["text": .string(instructions), "enabled": .bool(instructionsEnabled)]) }.buttonStyle(.borderedProminent).disabled(!dirty || saving || !loaded)338 }339 } header: { Text("Instructions permanentes") } footer: { Text("Ce texte est ajouté par le serveur au contexte de chaque conversation, quel que soit le modèle ou l'appareil (préférences de ton, langue, format…). Il compte dans les jetons d'entrée.") }340 }341 .formStyle(.grouped)342 .task { await load() }343 .onSync({ $0.settings }) { Task { if !dirty { await load() } } }344 }345 }346347 private func load() async {348 await env.catalog.reloadSettings()349 let s = env.catalog.settings.settings350 followUps = s["assistant"]?["followUps"]?.boolValue ?? true351 savedText = s["instructions"]?["text"]?.stringValue ?? ""; savedEnabled = s["instructions"]?["enabled"]?.boolValue ?? false352 instructions = savedText; instructionsEnabled = savedEnabled; loaded = true353 }354 private func save(key: String, value: [String: JSONValue]) {355 saving = true356 Task {357 defer { saving = false }358 do { try await env.api.updateSetting(key: key, value: value); await env.catalog.reloadSettings(); if key == "instructions" { savedText = instructions; savedEnabled = instructionsEnabled }; env.toasts.show("Réglage enregistré") }359 catch { env.toasts.error(error); await load() }360 }361 }362}363