SPB Git

Repository Public

AIConfigView.swift 18.7 KB 402 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : App/Screens/AIConfigView.swift10// Description      : SP AI configuration (bring your own Anthropic key): secure11//                    entry stored only in the Keychain, free connection test,12//                    model choice among the models the key really has, output13//                    language, token budget, default tone, favourite prompts,14//                    local counters and the privacy notice.15// Module           : App16// Repository       : https://git.spboucher.ai/sp-keyboard17// Created          : 2026-12-0118// Last Modified    : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import SwiftUI93import AIEngine94import SecureStorage9596struct AIConfigView: View {97    @Environment(AppModel.self) private var model98    /// Draft of the key while it is being typed. Cleared as soon as it is saved; never persisted or copied.99    @State private var keyDraft = ""100    @State private var revealKey = false101    @State private var keyMessage: String?102    @State private var keyMessageIsError = false103    @State private var confirmErase = false104    @State private var editedFavorite: AIFavoritePrompt?105106    var body: some View {107        @Bindable var model = model108        Form {109            Section {110                keyStatus111                HStack {112                    Group {113                        if revealKey {114                            TextField("sk-ant-…", text: $keyDraft)115                        } else {116                            SecureField("sk-ant-…", text: $keyDraft)117                        }118                    }119                    .textInputAutocapitalization(.never)120                    .autocorrectionDisabled()121                    .textContentType(.password)122                    .privacySensitive()123                    .accessibilityLabel("Clé Anthropic")124                    .accessibilityIdentifier("ai.keyField")125                    Button {126                        revealKey.toggle()127                    } label: {128                        Image(systemName: revealKey ? "eye.slash" : "eye")129                            .frame(width: 44, height: 44)130                            .contentShape(Rectangle())131                    }132                    .buttonStyle(.borderless)133                    .accessibilityLabel(revealKey ? "Masquer la clé saisie" : "Afficher la clé saisie")134                    .accessibilityIdentifier("ai.reveal")135                }136                Button("Enregistrer dans le trousseau") { saveKey() }137                    .disabled(keyDraft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)138                    .accessibilityIdentifier("ai.saveKey")139                if let keyMessage {140                    Text(keyMessage)141                        .font(.footnote)142                        .foregroundStyle(keyMessageIsError ? .red : .secondary)143                        .accessibilityIdentifier("ai.keyMessage")144                }145                if model.keyState.isPresent {146                    Button("Effacer la clé", role: .destructive) { confirmErase = true }147                        .accessibilityIdentifier("ai.eraseKey")148                }149            } header: {150                Text("Clé Anthropic")151            } footer: {152                Text("La clé est rangée uniquement dans le trousseau de cet appareil (non synchronisée), partagé avec le clavier. Elle n'est écrite dans aucun fichier, journal ou réglage, et n'est plus affichée après l'enregistrement.")153            }154155            Section {156                Button {157                    Task { await model.testConnection() }158                } label: {159                    HStack {160                        Label("Tester la connexion", systemImage: "antenna.radiowaves.left.and.right")161                        if model.connectionTest == .running {162                            Spacer()163                            ProgressView()164                        }165                    }166                }167                .disabled(!model.keyState.isPresent || model.connectionTest == .running)168                .accessibilityIdentifier("ai.test")169                switch model.connectionTest {170                case .idle, .running:171                    EmptyView()172                case .success(let count):173                    Label("Connexion réussie : \(count) modèles disponibles pour cette clé.", systemImage: "checkmark.circle.fill")174                        .font(.footnote)175                        .foregroundStyle(.green)176                        .accessibilityIdentifier("ai.testResult")177                case .failure(let message):178                    Label(message, systemImage: "xmark.octagon.fill")179                        .font(.footnote)180                        .foregroundStyle(.red)181                        .accessibilityIdentifier("ai.testResult")182                }183                if model.ai.knownModels.isEmpty {184                    Text("Aucun modèle connu. Testez la connexion pour obtenir la liste des modèles de votre clé.")185                        .font(.footnote)186                        .foregroundStyle(.secondary)187                } else {188                    Picker("Modèle", selection: Binding(get: { model.ai.modelID }, set: { model.selectModel($0) })) {189                        if model.ai.selectedModel == nil { Text("Aucun").tag("") }190                        ForEach(model.ai.knownModels) { Text($0.displayName).tag($0.id) }191                    }192                    .accessibilityIdentifier("ai.model")193                }194            } header: {195                Text("Connexion et modèle")196            } footer: {197                Text("Le test liste les modèles (appel gratuit, aucun texte envoyé). La liste vient d'Anthropic : l'app n'invente aucun nom de modèle.")198            }199200            Section("Résultat") {201                Picker("Langue de sortie", selection: $model.ai.outputLanguage) {202                    Text("Celle du texte").tag(AIOutputLanguage.sameAsSource)203                    Text("Français").tag(AIOutputLanguage.french)204                    Text("English").tag(AIOutputLanguage.english)205                    Text("Español").tag(AIOutputLanguage.spanish)206                }207                Picker("Ton par défaut", selection: $model.ai.defaultTone) {208                    ForEach(AITone.allCases, id: \.self) { Text(Self.name($0)).tag($0) }209                }210                LabeledSlider(title: "Budget de tokens par réponse",211                              value: Binding(get: { Double(model.ai.maxOutputTokens) }, set: { model.ai.maxOutputTokens = Int($0) }),212                              range: Double(AISettings.outputTokenRange.lowerBound)...Double(AISettings.outputTokenRange.upperBound), step: 128) { "\(Int($0))" }213            }214215            Section {216                ForEach(model.ai.favorites) { favorite in217                    Button {218                        editedFavorite = favorite219                    } label: {220                        VStack(alignment: .leading, spacing: 2) {221                            Text(favorite.title).foregroundStyle(.primary)222                            Text(favorite.prompt).font(.footnote).foregroundStyle(.secondary).lineLimit(2)223                        }224                        .frame(maxWidth: .infinity, alignment: .leading)225                        .contentShape(Rectangle())226                    }227                    .buttonStyle(.plain)228                    .accessibilityHint("Modifier ce prompt")229                }230                .onDelete { offsets in231                    offsets.map { model.ai.favorites[$0].id }.forEach(model.deleteFavorite)232                }233                Button {234                    editedFavorite = AIFavoritePrompt(title: "", prompt: "")235                } label: {236                    Label("Ajouter un prompt", systemImage: "plus")237                }238                .disabled(model.ai.favorites.count >= AISettings.maxFavorites)239                .accessibilityIdentifier("ai.addFavorite")240            } header: {241                Text("Prompts favoris")242            } footer: {243                Text("Ils apparaissent dans le panneau ✦ SP AI du clavier. Balayez pour supprimer.")244            }245246            Section {247                Toggle("Compter les appels et les tokens", isOn: $model.ai.countersEnabled)248                if model.ai.countersEnabled {249                    LabeledContent("Appels réussis", value: "\(model.ai.counters.calls)")250                    LabeledContent("Échecs", value: "\(model.ai.counters.failures)")251                    LabeledContent("Tokens envoyés", value: "\(model.ai.counters.inputTokens)")252                    LabeledContent("Tokens reçus", value: "\(model.ai.counters.outputTokens)")253                    LabeledContent("Depuis", value: model.ai.counters.since.formatted(date: .abbreviated, time: .shortened))254                    Button("Remettre les compteurs à zéro") { model.resetCounters() }255                }256            } header: {257                Text("Compteurs locaux")258            } footer: {259                Text("Des nombres seulement, gardés sur l'appareil. Aucun texte n'est conservé.")260            }261262            Section {263                Button {264                    Task { await model.runTrial() }265                } label: {266                    HStack {267                        Label("Essai facturable", systemImage: "paperplane")268                        if model.trial == .running {269                            Spacer()270                            ProgressView()271                        }272                    }273                }274                .disabled(!model.keyState.isPresent || model.ai.selectedModel == nil || model.trial == .running)275                .accessibilityIdentifier("ai.trial")276                switch model.trial {277                case .idle, .running:278                    EmptyView()279                case .success(let output, let input, let outputTokens):280                    VStack(alignment: .leading, spacing: 4) {281                        Text(output).font(.callout)282                        Text("\(input) tokens envoyés, \(outputTokens) reçus").font(.footnote).foregroundStyle(.secondary)283                    }284                    .accessibilityIdentifier("ai.trialResult")285                case .failure(let message):286                    Text(message).font(.footnote).foregroundStyle(.red).accessibilityIdentifier("ai.trialResult")287                }288            } header: {289                Text("Essai")290            } footer: {291                Text("Envoie cette phrase fictive au modèle choisi pour la corriger : « \(AppModel.trialSentence) ». Cet appel est facturé à votre clé (quelques dizaines de tokens).")292            }293294            Section("Confidentialité de SP AI") {295                Text("SP AI n'agit que sur demande : vous choisissez un texte, vous le voyez, puis vous touchez « Envoyer à Claude ». Ce texte est alors transmis directement à l'API d'Anthropic avec votre clé. Rien n'est envoyé pendant la frappe ordinaire.")296                Text("L'usage de l'API peut être facturé à votre compte Anthropic. SP Keyboard ne promet ni conservation nulle ni confidentialité absolue : la conservation et l'utilisation des données par Anthropic dépendent des conditions applicables à votre compte.")297                Link("Conditions commerciales d'Anthropic", destination: URL(string: "https://www.anthropic.com/legal/commercial-terms")!)298                Link("Politique de confidentialité d'Anthropic", destination: URL(string: "https://www.anthropic.com/legal/privacy")!)299            }300            .font(.footnote)301        }302        .navigationTitle("SP AI")303        .navigationBarTitleDisplayMode(.inline)304        .onDisappear {305            keyDraft = ""306            revealKey = false307        }308        .confirmationDialog("Effacer la clé du trousseau?", isPresented: $confirmErase, titleVisibility: .visible) {309            Button("Effacer la clé", role: .destructive) {310                keyMessageIsError = !model.eraseKey()311                keyMessage = keyMessageIsError ? "Le trousseau a refusé la suppression." : "Clé effacée de cet appareil."312            }313        } message: {314            Text("SP AI cessera de fonctionner jusqu'à ce qu'une clé soit saisie de nouveau. La clé reste valide chez Anthropic : révoquez-la dans la console Anthropic si elle a été exposée.")315        }316        .sheet(item: $editedFavorite) { favorite in317            FavoriteEditor(favorite: favorite) { model.upsertFavorite($0) }318        }319    }320321    @ViewBuilder private var keyStatus: some View {322        switch model.keyState {323        case .present(let masked):324            StatusRow(title: "Clé enregistrée", detail: masked, level: .good)325                .accessibilityIdentifier("ai.keyStatus")326        case .absent:327            StatusRow(title: "Aucune clé", detail: "SP AI est désactivé. Le clavier fonctionne sans clé.", level: .neutral)328                .accessibilityIdentifier("ai.keyStatus")329        case .unavailable(let code):330            StatusRow(title: "Trousseau inaccessible", detail: "Code \(code). La clé n'est jamais rangée ailleurs.", level: .warning)331                .accessibilityIdentifier("ai.keyStatus")332        }333    }334335    private func saveKey() {336        do {337            try model.saveKey(keyDraft)338            keyDraft = ""339            revealKey = false340            keyMessageIsError = false341            keyMessage = "Clé enregistrée dans le trousseau. Testez la connexion."342        } catch {343            keyMessageIsError = true344            switch error {345            case .invalidShape:346                keyMessage = "Ce texte n'a pas la forme d'une clé Anthropic (elle commence par « sk-ant- »). Rien n'a été enregistré."347            case .store(let code):348                keyMessage = "Le trousseau a refusé l'écriture (code \(code)). La clé n'a été enregistrée nulle part."349            }350        }351    }352353    static func name(_ tone: AITone) -> String {354        switch tone {355        case .professional: "Professionnel"356        case .friendly: "Amical"357        case .direct: "Direct"358        case .warm: "Chaleureux"359        case .academic: "Universitaire"360        case .humorous: "Humoristique"361        }362    }363}364365private struct FavoriteEditor: View {366    @State var favorite: AIFavoritePrompt367    var onSave: (AIFavoritePrompt) -> Void368    @Environment(\.dismiss) private var dismiss369370    var body: some View {371        NavigationStack {372            Form {373                Section("Titre") {374                    TextField("Ex. : Courriel poli", text: $favorite.title)375                        .accessibilityIdentifier("favorite.title")376                }377                Section {378                    TextField("Consigne donnée à Claude", text: $favorite.prompt, axis: .vertical)379                        .lineLimit(3...8)380                        .accessibilityIdentifier("favorite.prompt")381                } header: {382                    Text("Consigne")383                } footer: {384                    Text("600 caractères au plus. La consigne s'applique au texte que vous choisissez dans le clavier.")385                }386            }387            .navigationTitle("Prompt favori")388            .navigationBarTitleDisplayMode(.inline)389            .toolbar {390                ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } }391                ToolbarItem(placement: .confirmationAction) {392                    Button("Enregistrer") {393                        onSave(favorite)394                        dismiss()395                    }396                    .disabled(favorite.title.trimmingCharacters(in: .whitespaces).isEmpty || favorite.prompt.trimmingCharacters(in: .whitespaces).isEmpty)397                }398            }399        }400    }401}402
Files main
Menu

Theme