Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Tests/AppTests/AppModelTests.swift10// Description : App model: persistence through the shared store, the key11// never leaving the secret store, the model selection rule,12// themes, local photo resizing, import/export validation,13// erase actions.14// Module : AppTests15// Repository : https://git.spboucher.ai/sp-keyboard16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import XCTest92import UIKit93import AIEngine94import KeyboardCore95import SecureStorage96import ThemeEngine97@testable import SPKeyboard9899private let fakeKey = "sk-ant-api03-" + String(repeating: "Qq7_-", count: 16)100101private final class StubService: AIService, @unchecked Sendable {102 var models: Result<[AIModelInfo], AIError> = .success([])103 var completion: Result<AIResult, AIError> = .failure(.offline)104 private(set) var completeCalls = 0105 private(set) var lastRequest: AIRequest?106107 func complete(_ request: AIRequest) async throws -> AIResult {108 completeCalls += 1109 lastRequest = request110 return try completion.get()111 }112113 func listModels() async throws -> [AIModelInfo] { try models.get() }114}115116@MainActor117final class AppModelTests: XCTestCase {118 private var store: InMemorySettingsStore!119 private var secrets: InMemorySecretStore!120 private var service: StubService!121 private var container: URL!122 private var model: AppModel!123124 override func setUp() async throws {125 store = InMemorySettingsStore()126 secrets = InMemorySecretStore()127 service = StubService()128 container = FileManager.default.temporaryDirectory.appendingPathComponent("spk-tests-" + UUID().uuidString, isDirectory: true)129 try FileManager.default.createDirectory(at: container, withIntermediateDirectories: true)130 model = AppModel(store: store, secrets: secrets, aiService: service, container: container)131 }132133 override func tearDown() async throws {134 try? FileManager.default.removeItem(at: container)135 }136137 private var allBlobs: String {138 [KeyboardSettings.storageKey, UserDictionary.storageKey, ThemeLibrary.storageKey, AISettings.storageKey, KeyboardMetrics.storageKey, "revision"]139 .compactMap { store.data(forKey: $0) }.map { String(decoding: $0, as: UTF8.self) }.joined(separator: "\n")140 }141142 // MARK: Persistence143144 func testChangesReachTheStoreAndBumpTheRevision() {145 let before = store.revision146 model.settings.keySound = true147 model.settings.oneHanded = .left148 XCTAssertGreaterThan(store.revision, before)149 XCTAssertEqual(store.load(KeyboardSettings.self).value, model.settings)150 model.ai.maxOutputTokens = 2048151 XCTAssertEqual(store.load(AISettings.self).value.maxOutputTokens, 2048)152 XCTAssertTrue(model.addWord("Saguenay"))153 XCTAssertEqual(store.load(UserDictionary.self).value.words, ["Saguenay"])154 let reopened = AppModel(store: store, secrets: secrets, aiService: service, container: container)155 XCTAssertEqual(reopened.settings, model.settings)156 XCTAssertEqual(reopened.dictionary, model.dictionary)157 }158159 func testNothingIsWrittenWhenNothingChanges() {160 let before = store.revision161 model.settings = model.settings162 model.reload()163 XCTAssertEqual(store.revision, before)164 }165166 func testReloadPicksUpWhatTheKeyboardWrote() {167 var metrics = KeyboardMetrics()168 metrics.warmAppearanceMs = 42169 metrics.hadFullAccess = true170 metrics.updatedAt = Date()171 store.save(metrics, notify: false)172 var stored = store.load(AISettings.self).value173 stored.counters.calls = 3174 store.save(stored, notify: false)175 XCTAssertNil(model.metrics.updatedAt)176 model.reload()177 XCTAssertEqual(model.metrics.warmAppearanceMs, 42)178 XCTAssertEqual(model.ai.counters.calls, 3)179 }180181 // MARK: Key182183 func testKeyLivesOnlyInTheSecretStore() throws {184 try model.saveKey(" \(fakeKey)\n")185 XCTAssertEqual(try secrets.read(SecretName.anthropicAPIKey), fakeKey)186 guard case .present(let masked) = model.keyState else { return XCTFail("\(model.keyState)") }187 XCTAssertFalse(masked.contains(fakeKey.dropFirst(10).prefix(12)))188 model.settings.keySound = true189 model.ai.maxOutputTokens = 512190 model.addWord("Chicoutimi")191 model.activateTheme(id: "lava")192 XCTAssertFalse(allBlobs.isEmpty)193 XCTAssertFalse(allBlobs.contains("sk-ant"), "the key must appear in no settings blob")194 XCTAssertFalse(String(decoding: try model.exportConfiguration(), as: UTF8.self).contains("sk-ant"))195 XCTAssertFalse(String(decoding: try model.exportTheme(BuiltInThemes.lava), as: UTF8.self).contains("sk-ant"))196 XCTAssertFalse(UserDefaults.standard.dictionaryRepresentation().values.contains { "\($0)".contains(fakeKey) })197 }198199 func testInvalidShapeIsRejectedAndNothingStored() {200 for bad in ["", "bonjour", "sk-ant-short", "sk-proj-" + String(repeating: "a", count: 60)] {201 XCTAssertThrowsError(try model.saveKey(bad)) { XCTAssertEqual($0 as? KeySaveError, .invalidShape) }202 }203 XCTAssertNil(try secrets.read(SecretName.anthropicAPIKey))204 XCTAssertEqual(model.keyState, .absent)205 }206207 func testSecretStoreFailureIsReportedWithItsCodeAndNoFallback() {208 secrets.failEverything(with: .missingEntitlement)209 XCTAssertThrowsError(try model.saveKey(fakeKey)) { XCTAssertEqual($0 as? KeySaveError, .store(code: "entitlement")) }210 XCTAssertEqual(model.keyState, .unavailable(code: "entitlement"))211 XCTAssertFalse(allBlobs.contains("sk-ant"))212 secrets.failEverything(with: nil)213 XCTAssertNil(try? secrets.read(SecretName.anthropicAPIKey) ?? nil)214 }215216 func testEraseKey() throws {217 try model.saveKey(fakeKey)218 XCTAssertTrue(model.eraseKey())219 XCTAssertEqual(model.keyState, .absent)220 XCTAssertNil(try secrets.read(SecretName.anthropicAPIKey))221 }222223 // MARK: Models224225 private let opus = AIModelInfo(id: "claude-opus-5-5", displayName: "Opus", supportsLowEffort: true)226 private let haiku = AIModelInfo(id: "claude-haiku-5-5", displayName: "Haiku", supportsLowEffort: true)227 private let other = AIModelInfo(id: "claude-other-1", displayName: "Other")228229 func testNoModelIsAssumedBeforeTheAPIListsThem() {230 XCTAssertEqual(model.ai.modelID, "")231 XCTAssertTrue(model.ai.knownModels.isEmpty)232 XCTAssertNil(model.ai.selectedModel)233 }234235 func testModelSelectionRule() {236 model.applyModels([haiku, opus])237 XCTAssertEqual(model.ai.modelID, "claude-opus-5-5", "preferred model preselected when the API returns it")238 model.selectModel("claude-haiku-5-5")239 model.applyModels([opus, haiku, other])240 XCTAssertEqual(model.ai.modelID, "claude-haiku-5-5", "an existing valid choice is kept")241 model.applyModels([other])242 XCTAssertEqual(model.ai.modelID, "", "left unset when neither the choice nor the preferred model is listed")243 model.selectModel("claude-invented-9")244 XCTAssertEqual(model.ai.modelID, "", "only listed models can be selected")245 }246247 func testConnectionTest() async throws {248 try model.saveKey(fakeKey)249 service.models = .success([haiku, opus])250 await model.testConnection()251 XCTAssertEqual(model.connectionTest, .success(modelCount: 2))252 XCTAssertEqual(store.load(AISettings.self).value.knownModels, [haiku, opus])253 service.models = .failure(.invalidKey)254 await model.testConnection()255 guard case .failure(let message) = model.connectionTest else { return XCTFail() }256 XCTAssertTrue(message.contains("401"))257 XCTAssertFalse(message.contains("sk-ant"))258 XCTAssertEqual(model.ai.knownModels, [haiku, opus], "a failed test does not wipe the known models")259 }260261 func testTrialUsesTheFixedSentenceAndCounts() async {262 model.applyModels([opus])263 service.completion = .success(AIResult(text: "ok", usage: AIUsage(inputTokens: 30, outputTokens: 12), model: "claude-opus-5-5"))264 await model.runTrial()265 XCTAssertEqual(model.trial, .success(output: "ok", inputTokens: 30, outputTokens: 12))266 XCTAssertEqual(service.completeCalls, 1)267 XCTAssertTrue(service.lastRequest?.prompt.user.contains(AppModel.trialSentence) ?? false)268 XCTAssertEqual(model.ai.counters.calls, 1)269 XCTAssertEqual(model.ai.counters.inputTokens, 30)270 service.completion = .failure(.rateLimited(retryAfter: 9))271 await model.runTrial()272 XCTAssertEqual(model.ai.counters.failures, 1)273 model.ai.countersEnabled = false274 await model.runTrial()275 XCTAssertEqual(model.ai.counters.failures, 1)276 model.resetCounters()277 XCTAssertEqual(model.ai.counters.calls, 0)278 }279280 func testTrialWithoutModelSendsNothing() async {281 await model.runTrial()282 XCTAssertEqual(service.completeCalls, 0)283 guard case .failure = model.trial else { return XCTFail() }284 }285286 func testFavoritePrompts() {287 let count = model.ai.favorites.count288 model.upsertFavorite(AIFavoritePrompt(id: "x", title: " Titre ", prompt: " Consigne "))289 XCTAssertEqual(model.ai.favorites.count, count + 1)290 XCTAssertEqual(model.ai.favorites.last, AIFavoritePrompt(id: "x", title: "Titre", prompt: "Consigne"))291 model.upsertFavorite(AIFavoritePrompt(id: "x", title: "Autre", prompt: "Consigne 2"))292 XCTAssertEqual(model.ai.favorites.count, count + 1)293 model.upsertFavorite(AIFavoritePrompt(title: " ", prompt: "x"))294 XCTAssertEqual(model.ai.favorites.count, count + 1)295 model.deleteFavorite(id: "x")296 XCTAssertEqual(model.ai.favorites.count, count)297 }298299 // MARK: Themes300301 func testActivateDuplicateEditDelete() throws {302 model.activateTheme(id: "cyberpunk")303 XCTAssertEqual(store.load(ThemeLibrary.self).value.active, BuiltInThemes.cyberpunk)304 XCTAssertEqual(model.settings.activeThemeID, "cyberpunk")305 model.activateTheme(id: "does-not-exist")306 XCTAssertEqual(model.library.active.id, "cyberpunk")307308 var copy = try XCTUnwrap(model.duplicateTheme(BuiltInThemes.galaxy))309 XCTAssertTrue(copy.id.hasPrefix("custom-"))310 XCTAssertFalse(copy.isBuiltIn)311 XCTAssertEqual(copy.name, "Galaxy (copie)")312 XCTAssertEqual(model.library.custom.count, 1)313314 model.activateTheme(id: copy.id)315 copy.metrics.cornerRadius = 500316 copy.name = "Mon thème"317 model.updateTheme(copy)318 XCTAssertEqual(model.library.active.name, "Mon thème", "the active theme follows its edits")319 XCTAssertEqual(store.load(ThemeLibrary.self).value.active.metrics.cornerRadius, 18, "values are clamped before reaching the keyboard")320321 var builtIn = BuiltInThemes.lava322 builtIn.name = "Piraté"323 model.updateTheme(builtIn)324 XCTAssertEqual(model.library.theme(id: "lava")?.name, "Lava", "built-in themes are immutable")325326 model.toggleFavoriteTheme(copy.id)327 XCTAssertEqual(model.library.favorites, [copy.id])328 model.deleteTheme(id: copy.id)329 XCTAssertTrue(model.library.custom.isEmpty)330 XCTAssertTrue(model.library.favorites.isEmpty)331 XCTAssertEqual(model.library.active.id, BuiltInThemes.defaultID)332 XCTAssertEqual(model.settings.activeThemeID, BuiltInThemes.defaultID)333 model.deleteTheme(id: "lava")334 XCTAssertEqual(BuiltInThemes.all.count, 18)335 }336337 func testLightDarkPairing() {338 let model = AppModel.inMemory()339 XCTAssertTrue(model.library.followsAppearance, "2.0 starts on the Atelier pair")340 XCTAssertEqual(model.activeThemeName, "Atelier Clair / Atelier Nuit")341 model.setPairedTheme(id: "sapin", dark: true)342 XCTAssertEqual(model.library.darkVariant?.id, "sapin")343 XCTAssertEqual(model.library.active.id, "atelier-clair")344 // Tapping a theme activates it alone.345 model.activateTheme(id: "ardoise")346 XCTAssertFalse(model.library.followsAppearance)347 XCTAssertEqual(model.activeThemeName, "Ardoise")348 model.setPairedTheme(id: "craie", dark: false)349 XCTAssertEqual(model.library.active.id, "ardoise", "no pair, nothing to assign")350 // Turning the pairing back on keeps the theme in use on its side and finds its partner.351 model.setFollowsAppearance(true)352 XCTAssertEqual(model.library.darkVariant?.id, "ardoise")353 XCTAssertEqual(model.library.active.id, "craie")354 model.setFollowsAppearance(false, currentlyDark: true)355 XCTAssertEqual(model.library.active.id, "ardoise")356 XCTAssertNil(model.library.darkVariant)357 XCTAssertEqual(AppModel.partner(of: BuiltInThemes.lava).id, BuiltInThemes.defaultID)358 }359360 func testCustomThemeLimit() {361 for _ in 0..<ThemeLibrary.maxCustomThemes { XCTAssertNotNil(model.duplicateTheme(BuiltInThemes.aurora)) }362 XCTAssertNil(model.duplicateTheme(BuiltInThemes.aurora))363 XCTAssertEqual(model.library.custom.count, ThemeLibrary.maxCustomThemes)364 }365366 func testThemeImportExport() throws {367 let data = try model.exportTheme(BuiltInThemes.toxicLime)368 let imported = try model.importTheme(data)369 XCTAssertTrue(imported.id.hasPrefix("custom-"))370 XCTAssertEqual(imported.name, "Toxic Lime")371 XCTAssertEqual(model.library.custom.map(\.id), [imported.id])372 XCTAssertThrowsError(try model.importTheme(Data("{}".utf8)))373 XCTAssertThrowsError(try model.importTheme(Data("pas du json".utf8)))374 XCTAssertThrowsError(try model.importTheme(Data(count: ThemeCodec.maxImportBytes + 1)))375 XCTAssertEqual(model.library.custom.count, 1, "a rejected import changes nothing")376 }377378 // MARK: Photos379380 private func photo(width: Int, height: Int) -> Data {381 let format = UIGraphicsImageRendererFormat()382 format.scale = 1383 let image = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: format).image { context in384 // Noisy content so the JPEG does not compress to nothing.385 for index in 0..<400 {386 UIColor(hue: CGFloat(index % 37) / 37, saturation: 0.8, brightness: 0.9, alpha: 1).setFill()387 context.fill(CGRect(x: (index * 97) % width, y: (index * 61) % height, width: width / 9, height: height / 11))388 }389 }390 return image.pngData()!391 }392393 func testBackgroundPhotoIsResizedLocallyAndBounded() throws {394 var theme = try XCTUnwrap(model.duplicateTheme(BuiltInThemes.aurora))395 theme = try model.setBackground(imageData: photo(width: 4000, height: 3000), for: theme)396 let name = try XCTUnwrap(theme.backgroundImage)397 XCTAssertTrue(Theme.isSafeImageName(name))398 let url = try XCTUnwrap(ThemeLibrary.backgroundURL(named: name, container: container))399 let stored = try Data(contentsOf: url)400 XCTAssertLessThanOrEqual(stored.count, ThemeLibrary.maxBackgroundBytes)401 let size = try XCTUnwrap(ImageResizer.pixelSize(of: stored))402 XCTAssertLessThanOrEqual(max(size.width, size.height), ThemeLibrary.maxBackgroundPixels)403 XCTAssertEqual(model.library.theme(id: theme.id)?.backgroundImage, name)404405 // Replacing the photo removes the previous file; removing it leaves no file behind.406 let replaced = try model.setBackground(imageData: photo(width: 800, height: 600), for: theme)407 XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))408 let cleared = model.removeBackground(from: replaced)409 XCTAssertNil(cleared.backgroundImage)410 let folder = container.appendingPathComponent(ThemeLibrary.backgroundsFolder)411 XCTAssertEqual((try? FileManager.default.contentsOfDirectory(atPath: folder.path))?.count ?? 0, 0)412 }413414 func testDeletingAThemeDeletesItsPhoto() throws {415 var theme = try XCTUnwrap(model.duplicateTheme(BuiltInThemes.aurora))416 theme = try model.setBackground(imageData: photo(width: 600, height: 400), for: theme)417 let url = try XCTUnwrap(ThemeLibrary.backgroundURL(named: try XCTUnwrap(theme.backgroundImage), container: container))418 XCTAssertTrue(FileManager.default.fileExists(atPath: url.path))419 model.deleteTheme(id: theme.id)420 XCTAssertFalse(FileManager.default.fileExists(atPath: url.path))421 }422423 func testBackgroundFailures() throws {424 let theme = try XCTUnwrap(model.duplicateTheme(BuiltInThemes.aurora))425 XCTAssertThrowsError(try model.setBackground(imageData: Data("pas une image".utf8), for: theme)) {426 XCTAssertEqual($0 as? AppModel.BackgroundError, .unreadableImage)427 }428 XCTAssertThrowsError(try model.setBackground(imageData: photo(width: 100, height: 100), for: BuiltInThemes.aurora))429 let detached = AppModel(store: store, secrets: secrets, aiService: service, container: nil)430 XCTAssertThrowsError(try detached.setBackground(imageData: photo(width: 100, height: 100), for: theme)) {431 XCTAssertEqual($0 as? AppModel.BackgroundError, .containerUnavailable)432 }433 XCTAssertNil(ImageResizer.resizedJPEG(from: Data(), maxPixels: 100, maxBytes: 1000))434 }435436 // MARK: Dictionary, import/export437438 func testConfigurationExportOmitsKeyAndLearnedWordsAndRoundTrips() throws {439 try model.saveKey(fakeKey)440 model.addWord("Chicoutimi")441 model.dictionary.learned = ["motsecret": 4]442 model.settings.autocorrection = false443 model.upsertSnippet(Snippet(id: "s1", title: "Test", trigger: "tst", text: "Bonjour", category: .personal))444 let data = try model.exportConfiguration()445 let text = String(decoding: data, as: UTF8.self)446 XCTAssertFalse(text.contains("sk-ant"))447 XCTAssertFalse(text.contains("motsecret"))448449 let other = AppModel(store: InMemorySettingsStore(), secrets: InMemorySecretStore(), aiService: service, container: container)450 other.activateTheme(id: "lava")451 other.dictionary.learned = ["garde": 2]452 try other.importConfiguration(data)453 XCTAssertFalse(other.settings.autocorrection)454 XCTAssertEqual(other.dictionary.words, ["Chicoutimi"])455 XCTAssertTrue(other.dictionary.snippets.contains { $0.id == "s1" })456 XCTAssertEqual(other.dictionary.learned, ["garde": 2], "learned words are neither imported nor erased")457 XCTAssertEqual(other.settings.activeThemeID, "lava")458 XCTAssertEqual(other.keyState, .absent)459 }460461 func testInvalidConfigurationIsRejectedWithoutSideEffects() {462 model.addWord("Garde")463 let before = (model.settings, model.dictionary)464 XCTAssertThrowsError(try model.importConfiguration(Data("{}".utf8)))465 XCTAssertThrowsError(try model.importConfiguration(Data(count: SettingsExport.maxImportBytes + 1)))466 XCTAssertThrowsError(try model.importConfiguration(Data(#"{"format":"sp-keyboard-theme"}"#.utf8)))467 XCTAssertEqual(model.settings, before.0)468 XCTAssertEqual(model.dictionary, before.1)469 }470471 func testWordsAndSnippets() {472 XCTAssertTrue(model.addWord("Saguenay"))473 XCTAssertFalse(model.addWord("saguenay"))474 XCTAssertFalse(model.addWord("deux mots"))475 model.removeWord("Saguenay")476 XCTAssertTrue(model.dictionary.words.isEmpty)477 let count = model.dictionary.snippets.count478 model.upsertSnippet(Snippet(id: "a", title: "T", trigger: "a b", text: "Texte", category: .message))479 XCTAssertEqual(model.dictionary.snippets.count, count + 1)480 XCTAssertEqual(model.dictionary.snippets.last?.trigger, "ab")481 model.upsertSnippet(Snippet(id: "a", title: "T2", text: "Texte 2", category: .message))482 XCTAssertEqual(model.dictionary.snippets.count, count + 1)483 model.upsertSnippet(Snippet(id: "vide", title: "V", text: ""))484 XCTAssertEqual(model.dictionary.snippets.count, count + 1)485 model.deleteSnippet(id: "a")486 XCTAssertEqual(model.dictionary.snippets.count, count)487 model.dictionary.learned = ["x1": 3, "y2": 1]488 model.removeLearnedWord("x1")489 XCTAssertEqual(model.dictionary.learned, ["y2": 1])490 model.eraseLearnedWords()491 XCTAssertTrue(model.dictionary.learned.isEmpty)492 }493494 // MARK: Erase495496 func testEraseActions() throws {497 try model.saveKey(fakeKey)498 model.settings.keySound = true499 model.addWord("Mot")500 model.applyModels([opus])501 var theme = try XCTUnwrap(model.duplicateTheme(BuiltInThemes.aurora))502 theme = try model.setBackground(imageData: photo(width: 300, height: 200), for: theme)503 var metrics = KeyboardMetrics()504 metrics.updatedAt = Date()505 store.save(metrics, notify: false)506 model.reload()507508 model.eraseDictionary()509 XCTAssertEqual(model.dictionary, UserDictionary())510 XCTAssertTrue(model.settings.keySound, "erasing the dictionary leaves preferences alone")511512 model.erasePreferences()513 XCTAssertEqual(model.settings, KeyboardSettings())514 XCTAssertEqual(model.library, ThemeLibrary())515 XCTAssertTrue(model.ai.knownModels.isEmpty)516 XCTAssertFalse(FileManager.default.fileExists(atPath: container.appendingPathComponent(ThemeLibrary.backgroundsFolder).path))517 XCTAssertTrue(model.keyState.isPresent, "erasing preferences does not touch the key")518519 model.eraseEverything()520 XCTAssertEqual(model.keyState, .absent)521 XCTAssertNil(try secrets.read(SecretName.anthropicAPIKey))522 XCTAssertNil(model.metrics.updatedAt)523 XCTAssertNil(store.data(forKey: KeyboardMetrics.storageKey))524 XCTAssertEqual(store.load(KeyboardSettings.self).value, KeyboardSettings())525 }526527 // MARK: Diagnostics528529 func testKeychainProbeReallyRoundTripsAndCleansUp() throws {530 XCTAssertEqual(model.keychainProbe(), "ok")531 XCTAssertNil(try secrets.read("diagnostic-probe"))532 secrets.failEverything(with: .interactionNotAllowed)533 XCTAssertEqual(model.keychainProbe(), "locked")534 }535536 func testRouterOpensAnEditableCopyOfABuiltInTheme() {537 var options = LaunchOptions()538 options.screen = .editor539 options.themeID = "galaxy"540 let router = AppRouter(options: options, model: model)541 XCTAssertEqual(router.tab, .themes)542 XCTAssertEqual(router.themePath.count, 1)543 XCTAssertTrue(router.themePath[0].hasPrefix("custom-"))544 XCTAssertEqual(model.library.custom.first?.name, "Galaxy (copie)")545 options.screen = .privacy546 XCTAssertEqual(AppRouter(options: options, model: model).morePath, [.privacy])547 }548}549