Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : App/AppModel.swift10// Description : The app's single source of truth: typing settings, user11// dictionary, theme library and SP AI settings persisted12// through the shared store (the extension reloads on13// revision change), and the Anthropic key, which lives only14// in the secret store and is never kept in memory by the15// model.16// Module : App17// Repository : https://git.spboucher.ai/sp-keyboard18// Created : 2026-12-0119// Last Modified : 2026-12-0120//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import Observation95import AIEngine96import KeyboardCore97import SecureStorage98import ThemeEngine99100/// What the app can actually verify about the stored key.101enum KeyState: Equatable {102 case absent103 /// Masked form only (`sk-ant-…AAAA`).104 case present(masked: String)105 /// Diagnostic code of the secret store failure.106 case unavailable(code: String)107108 var isPresent: Bool {109 if case .present = self { return true }110 return false111 }112}113114enum ConnectionTestState: Equatable {115 case idle116 case running117 case success(modelCount: Int)118 case failure(String)119}120121enum TrialState: Equatable {122 case idle123 case running124 case success(output: String, inputTokens: Int, outputTokens: Int)125 case failure(String)126}127128enum KeySaveError: Error, Equatable {129 case invalidShape130 case store(code: String)131}132133@MainActor134@Observable135final class AppModel {136 @ObservationIgnored let store: SettingsBlobStoring137 @ObservationIgnored let secrets: SecretStoring138 @ObservationIgnored let aiService: AIService139 /// Root of the shared container (photos are stored under `Backgrounds/`); `nil` when unreachable.140 @ObservationIgnored let container: URL?141 @ObservationIgnored private var isLoading = false142143 var settings = KeyboardSettings() {144 didSet { if !isLoading, settings != oldValue { store.save(settings) } }145 }146 var dictionary = UserDictionary() {147 didSet { if !isLoading, dictionary != oldValue { store.save(dictionary) } }148 }149 var library = ThemeLibrary() {150 didSet { if !isLoading, library != oldValue { store.save(library) } }151 }152 var ai = AISettings() {153 didSet { if !isLoading, ai != oldValue { store.save(ai) } }154 }155 private(set) var metrics = KeyboardMetrics()156 private(set) var keyState: KeyState = .absent157 private(set) var connectionTest: ConnectionTestState = .idle158 private(set) var trial: TrialState = .idle159 private(set) var settingsOutcome: SettingsLoadOutcome = .missing160161 /// Fixed, fictional sentence used by the billable trial. Never user text.162 static let trialSentence = "Bonjour, je voudrait savoir si tu est disponible demain a 14 h."163 static let preferredModelID = "claude-opus-5-5"164165 init(store: SettingsBlobStoring, secrets: SecretStoring, aiService: AIService, container: URL?) {166 self.store = store167 self.secrets = secrets168 self.aiService = aiService169 self.container = container170 reload()171 }172173 /// Production wiring: App Group store, shared Keychain group, direct Anthropic client.174 static func live() -> AppModel {175 let secrets = KeychainStore.shared()176 return AppModel(store: AppGroupSettingsStore(), secrets: secrets,177 aiService: AnthropicClient(transport: URLSessionAITransport(), secrets: secrets),178 container: SharedContainer.directory)179 }180181 // MARK: Loading182183 /// Re-reads everything from the store (the extension may have written counters, favourites, metrics).184 func reload() {185 isLoading = true186 defer { isLoading = false }187 let loaded = store.load(KeyboardSettings.self)188 settingsOutcome = loaded.outcome189 settings = loaded.value190 dictionary = store.load(UserDictionary.self).value191 library = store.load(ThemeLibrary.self).value192 ai = store.load(AISettings.self).value193 metrics = store.load(KeyboardMetrics.self).value194 refreshKeyState()195 }196197 var isSharedContainerReachable: Bool { store.isShared }198199 // MARK: Anthropic key (secret store only)200201 func refreshKeyState() {202 do {203 if let key = try secrets.read(SecretName.anthropicAPIKey), !key.isEmpty {204 keyState = .present(masked: APIKeyFormat.masked(key))205 } else {206 keyState = .absent207 }208 } catch let error as SecretStoreError {209 keyState = .unavailable(code: error.diagnosticCode)210 } catch {211 keyState = .unavailable(code: "unknown")212 }213 }214215 /// Validates the shape and writes the key to the secret store. There is no other place it could go:216 /// a store failure is reported with its code.217 func saveKey(_ raw: String) throws(KeySaveError) {218 guard APIKeyFormat.looksValid(raw) else { throw .invalidShape }219 do {220 try secrets.write(APIKeyFormat.normalized(raw), for: SecretName.anthropicAPIKey)221 } catch let error as SecretStoreError {222 refreshKeyState()223 throw .store(code: error.diagnosticCode)224 } catch {225 refreshKeyState()226 throw .store(code: "unknown")227 }228 connectionTest = .idle229 trial = .idle230 refreshKeyState()231 }232233 @discardableResult234 func eraseKey() -> Bool {235 defer { refreshKeyState() }236 connectionTest = .idle237 trial = .idle238 do {239 try secrets.delete(SecretName.anthropicAPIKey)240 return true241 } catch {242 return false243 }244 }245246 // MARK: Connection test and model choice247248 /// Lists the models available to the key (a free call) and applies the selection rule.249 func testConnection() async {250 guard connectionTest != .running else { return }251 connectionTest = .running252 do {253 let models = try await aiService.listModels()254 applyModels(models)255 connectionTest = .success(modelCount: models.count)256 } catch let error as AIError {257 connectionTest = .failure(AIPanelView.describe(error))258 } catch {259 connectionTest = .failure("Erreur inattendue.")260 }261 }262263 /// Keeps the current model when the API still lists it; otherwise preselects the preferred one only if264 /// the API returned it; otherwise leaves the choice unset. No model is ever assumed.265 func applyModels(_ models: [AIModelInfo]) {266 var copy = ai267 copy.knownModels = models268 if !models.contains(where: { $0.id == copy.modelID }) {269 copy.modelID = models.contains { $0.id == Self.preferredModelID } ? Self.preferredModelID : ""270 }271 ai = copy272 }273274 func selectModel(_ id: String) {275 guard ai.knownModels.contains(where: { $0.id == id }) else { return }276 ai.modelID = id277 trial = .idle278 }279280 /// Sends the fixed fictional sentence through the selected model. Billable: only on an explicit tap.281 func runTrial() async {282 guard trial != .running else { return }283 guard let model = ai.selectedModel else {284 trial = .failure(AIPanelView.describe(.noModelSelected))285 return286 }287 trial = .running288 let prompt = AIPromptBuilder.build(action: .correct, source: Self.trialSentence, outputLanguage: .sameAsSource)289 do {290 let result = try await aiService.complete(AIRequest(model: model, prompt: prompt, maxOutputTokens: ai.maxOutputTokens))291 if ai.countersEnabled { ai.counters.record(result.usage) }292 trial = .success(output: result.text, inputTokens: result.usage.inputTokens, outputTokens: result.usage.outputTokens)293 } catch let error as AIError {294 if ai.countersEnabled { ai.counters.failures += 1 }295 trial = .failure(AIPanelView.describe(error))296 } catch {297 trial = .failure("Erreur inattendue.")298 }299 }300301 func resetCounters() { ai.counters = AICounters() }302303 // MARK: Favourite prompts304305 func upsertFavorite(_ favorite: AIFavoritePrompt) {306 let title = favorite.title.trimmingCharacters(in: .whitespacesAndNewlines)307 let prompt = favorite.prompt.trimmingCharacters(in: .whitespacesAndNewlines)308 guard !title.isEmpty, !prompt.isEmpty else { return }309 let clean = AIFavoritePrompt(id: favorite.id, title: title, prompt: prompt)310 if let index = ai.favorites.firstIndex(where: { $0.id == clean.id }) {311 ai.favorites[index] = clean312 } else if ai.favorites.count < AISettings.maxFavorites {313 ai.favorites.append(clean)314 }315 ai = ai.migrated()316 }317318 func deleteFavorite(id: String) { ai.favorites.removeAll { $0.id == id } }319320 // MARK: Themes321322 func activateTheme(id: String) {323 guard let theme = library.theme(id: id) else { return }324 var copy = library325 copy.active = theme326 library = copy327 settings.activeThemeID = theme.id328 }329330 /// Creates an editable copy of any theme. Returns `nil` when the custom-theme limit is reached.331 @discardableResult332 func duplicateTheme(_ theme: Theme) -> Theme? {333 guard library.custom.count < ThemeLibrary.maxCustomThemes else { return nil }334 var copy = theme335 copy.id = "custom-" + UUID().uuidString.lowercased()336 copy.name = String((theme.name + " (copie)").prefix(Theme.maxNameLength))337 copy.backgroundImage = nil338 var updated = library339 updated.upsert(copy)340 library = updated341 return library.theme(id: copy.id)342 }343344 /// Saves an edited custom theme (built-ins are immutable). The active theme follows its edits.345 func updateTheme(_ theme: Theme) {346 guard !theme.isBuiltIn else { return }347 var updated = library348 updated.upsert(theme)349 library = updated350 }351352 func deleteTheme(id: String) {353 guard let theme = library.custom.first(where: { $0.id == id }) else { return }354 if let image = theme.backgroundImage { removeBackground(named: image) }355 var updated = library356 updated.delete(id: id)357 library = updated358 if settings.activeThemeID == id { settings.activeThemeID = library.active.id }359 }360361 func toggleFavoriteTheme(_ id: String) {362 var updated = library363 updated.toggleFavorite(id)364 library = updated365 }366367 func exportTheme(_ theme: Theme) throws -> Data { try ThemeCodec.export(theme) }368369 /// Imports a validated theme file as a new custom theme.370 @discardableResult371 func importTheme(_ data: Data) throws -> Theme {372 let theme = try ThemeCodec.import(data)373 guard library.custom.count < ThemeLibrary.maxCustomThemes else { throw ThemeCodecError.malformed("limite de thèmes atteinte") }374 var updated = library375 updated.upsert(theme)376 library = updated377 return theme378 }379380 // MARK: Background photos (local files only)381382 enum BackgroundError: Error, Equatable { case containerUnavailable, unreadableImage, tooLarge, writeFailed }383384 /// Resizes the picked photo locally and stores it in the shared container. Returns the updated theme.385 func setBackground(imageData: Data, for theme: Theme) throws(BackgroundError) -> Theme {386 guard !theme.isBuiltIn else { throw .writeFailed }387 guard let container else { throw .containerUnavailable }388 guard let jpeg = ImageResizer.resizedJPEG(from: imageData, maxPixels: ThemeLibrary.maxBackgroundPixels,389 maxBytes: ThemeLibrary.maxBackgroundBytes) else { throw .unreadableImage }390 guard jpeg.count <= ThemeLibrary.maxBackgroundBytes else { throw .tooLarge }391 let name = "bg-" + UUID().uuidString.lowercased() + ".jpg"392 guard let url = ThemeLibrary.backgroundURL(named: name, container: container) else { throw .writeFailed }393 do {394 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)395 try jpeg.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])396 } catch {397 throw .writeFailed398 }399 if let old = theme.backgroundImage { removeBackground(named: old) }400 var updated = theme401 updated.backgroundImage = name402 updateTheme(updated)403 return updated404 }405406 func removeBackground(from theme: Theme) -> Theme {407 if let name = theme.backgroundImage { removeBackground(named: name) }408 var updated = theme409 updated.backgroundImage = nil410 updateTheme(updated)411 return updated412 }413414 private func removeBackground(named name: String) {415 guard let url = ThemeLibrary.backgroundURL(named: name, container: container) else { return }416 try? FileManager.default.removeItem(at: url)417 }418419 private func removeAllBackgrounds() {420 guard let container else { return }421 try? FileManager.default.removeItem(at: container.appendingPathComponent(ThemeLibrary.backgroundsFolder, isDirectory: true))422 }423424 // MARK: Dictionary and snippets425426 @discardableResult427 func addWord(_ raw: String) -> Bool {428 var copy = dictionary429 let added = copy.addWord(raw)430 if added { dictionary = copy }431 return added432 }433434 func removeWord(_ word: String) { dictionary.words.removeAll { $0 == word } }435 func eraseLearnedWords() { dictionary.learned = [:] }436 func removeLearnedWord(_ word: String) { dictionary.learned[word] = nil }437438 func upsertSnippet(_ snippet: Snippet) {439 guard !snippet.text.isEmpty else { return }440 var copy = dictionary441 if let index = copy.snippets.firstIndex(where: { $0.id == snippet.id }) {442 copy.snippets[index] = snippet443 } else if copy.snippets.count < UserDictionary.maxSnippets {444 copy.snippets.append(snippet)445 }446 dictionary = copy.migrated()447 }448449 func deleteSnippet(id: String) { dictionary.snippets.removeAll { $0.id == id } }450451 // MARK: Configuration import / export (never the key, never learned words)452453 func exportConfiguration() throws -> Data {454 try SettingsExport(settings: settings, dictionary: dictionary).encoded()455 }456457 func importConfiguration(_ data: Data) throws {458 let imported = try SettingsExport.decode(data)459 var newSettings = imported.settings460 // The active theme is not part of the exchange file: keep the one in use here.461 newSettings.activeThemeID = library.active.id462 settings = newSettings463 var copy = dictionary464 copy.words = imported.words465 copy.snippets = imported.snippets466 dictionary = copy.migrated()467 }468469 // MARK: Erase470471 func erasePreferences() {472 settings = KeyboardSettings()473 removeAllBackgrounds()474 library = ThemeLibrary()475 var freshAI = AISettings()476 freshAI.knownModels = []477 ai = freshAI478 connectionTest = .idle479 trial = .idle480 }481482 func eraseDictionary() { dictionary = UserDictionary() }483484 func eraseEverything() {485 erasePreferences()486 eraseDictionary()487 store.remove(KeyboardMetrics.self)488 metrics = KeyboardMetrics()489 eraseKey()490 }491492 // MARK: Diagnostics493494 /// Really exercises the secret store: write, read back, delete a probe item. Returns "ok" or a code.495 func keychainProbe() -> String {496 let name = "diagnostic-probe"497 let value = "probe-" + UUID().uuidString498 do {499 try secrets.write(value, for: name)500 let read = try secrets.read(name)501 try secrets.delete(name)502 return read == value ? "ok" : "mismatch"503 } catch let error as SecretStoreError {504 return error.diagnosticCode505 } catch {506 return "unknown"507 }508 }509510 var appVersion: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "?" }511 var appBuild: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "?" }512}513