release: iriz 0.2.0 - диктовка на своем Маке

This commit is contained in:
public-repo-gate
2026-09-05 12:56:59 +03:00
parent 93776bfde4
commit c8193dfbc3
251 changed files with 48509 additions and 0 deletions
@@ -0,0 +1,81 @@
// Акцент семьи обязан быть ЧИТАЕМЫМ, а не просто семейным.
//
// Требование волны дословно: контраст и уменьшенная анимация проверяются в
// КАЖДОЙ теме. «Выглядит контрастно» - не мерило: числа считает WCAG.
import Foundation
import Testing
@testable import IrizSettings
@Suite("акцент семьи: контраст в обеих темах")
struct FamilyAccentTests {
/// Порог для НЕтекстового элемента по WCAG 2.2 (1.4.11). Символ секции -
/// графика: он несёт смысл, но текст секции рядом всё равно системный.
private let graphicThreshold = 3.0
@Test func акцентЧитаемВСветлойТеме() {
for role in [FamilyAccentRole.personal, .flow] {
let ratio = wcagContrastRatio(familyAccentComponents(role, dark: false),
FamilySurface.light)
#expect(ratio >= graphicThreshold,
"светлая тема, роль \(role): контраст \(ratio) ниже \(graphicThreshold)")
}
}
@Test func акцентЧитаемВТёмнойТеме() {
for role in [FamilyAccentRole.personal, .flow] {
let ratio = wcagContrastRatio(familyAccentComponents(role, dark: true),
FamilySurface.dark)
#expect(ratio >= graphicThreshold,
"тёмная тема, роль \(role): контраст \(ratio) ниже \(graphicThreshold)")
}
}
@Test func канонныеЗначенияНаБеломНЕЧитаемы_поэтомуИАдаптированы() {
// Улика, ради которой светлая тема берёт другую светлоту: канонное
// золото на белой форме даёт около 1,9:1. Если этот тест когда-нибудь
// позеленеет наоборот, значит канон поменялся - и адаптацию надо
// пересматривать, а не тащить дальше по инерции.
let gold = wcagContrastRatio(FamilyPalette.gold, FamilySurface.light)
let sky = wcagContrastRatio(FamilyPalette.sky, FamilySurface.light)
#expect(gold < graphicThreshold, "канонное золото вдруг стало читаемым на белом: \(gold)")
#expect(sky < graphicThreshold, "канонный голубой вдруг стал читаемым на белом: \(sky)")
}
@Test func цветНеЕдинственныйНосительСмысла() {
// Первая редакция этого теста требовала, чтобы две роли различались по
// ЯРКОСТИ, и покраснела: золото и голубой на рабочей светлоте дают
// 1,05:1, то есть отличаются только тоном. Требование было выдумано
// мной, а настоящее правило доступности другое: цвет не имеет права
// быть единственным носителем смысла. У каждой секции свой символ и
// своё имя, и вот это обязано быть уникальным.
let symbols = SettingsSectionSpec.allCases.map(\.symbol)
#expect(Set(symbols).count == symbols.count, "символы секций повторяются: \(symbols)")
let titles = SettingsSectionSpec.allCases.map(\.title)
#expect(Set(titles).count == titles.count, "имена секций повторяются: \(titles)")
}
@Test func смыслАкцентаНазванДляКаждойСекции() {
// Золото - личное владельца, голубой - поток. Секции без смысла
// не бывает: акцент по вкусу и есть декорация, которую канон запрещает.
let personal = SettingsSectionSpec.allCases.filter { $0.accent == .personal }
let flow = SettingsSectionSpec.allCases.filter { $0.accent == .flow }
#expect(!personal.isEmpty && !flow.isEmpty)
#expect(personal.count + flow.count == SettingsSectionSpec.allCases.count)
// Словарь и заготовки - это личное владельца по построению.
#expect(SettingsSectionSpec.corrections.accent == .personal)
#expect(SettingsSectionSpec.snippets.accent == .personal)
// Клавиши и вставка - поток: они про то, что приходит и уходит.
#expect(SettingsSectionSpec.hotkeys.accent == .flow)
#expect(SettingsSectionSpec.behavior.accent == .flow)
}
@Test func формулаКонтрастаСчитаетИзвестныеЗначения() {
// Проверка самого измерителя: чёрное на белом - ровно 21:1.
let ratio = wcagContrastRatio((0, 0, 0), (1, 1, 1))
#expect(abs(ratio - 21) < 0.01)
#expect(abs(wcagContrastRatio((1, 1, 1), (1, 1, 1)) - 1) < 0.0001)
}
}
@@ -0,0 +1,134 @@
// Окно настроек: список «приложение → профиль промпта».
//
// Ключевая проверка та же, что у заготовок: настройка не осталась обещанием —
// строка, заведённая в окне, доходит до `DictationSettings` и оттуда до
// решения, которым конвейер выбирает профиль.
import CoreGraphics
import Foundation
import IrizCore
import IrizInput
import IrizPrompt
import Testing
@testable import IrizSettings
@testable import IrizDictate
@MainActor
@Suite("Настройки: профиль по приложению")
struct SettingsAppProfilesTests {
@Test func строкаИзОкнаДоходитДоРешенияКонвейера() {
let fixture = AppProfilesFixture()
let model = fixture.makeModel()
#expect(model.appProfiles.isEmpty)
#expect(model.addAppProfile(bundleID: "com.apple.dt.Xcode", profile: .codex) == .added)
model.promptRecipient = .generic
#expect(model.save())
let map = fixture.dictationSettings.promptAppProfileMap
#expect(map.profile(forBundleID: "com.apple.dt.Xcode") == .codex)
#expect(map.profile(forBundleID: "com.apple.mail") == .generic)
#expect(map.profile(forBundleID: nil) == .generic)
}
/// Второй раз то же приложение — не вторая строка, а правка первой.
/// Иначе в списке спорили бы две записи про одну программу.
@Test func повторноеДобавлениеПравитСтрокуНаМесте() {
let model = AppProfilesFixture().makeModel()
#expect(model.addAppProfile(bundleID: "com.apple.dt.Xcode", profile: .generic) == .added)
#expect(model.addAppProfile(bundleID: "COM.APPLE.DT.XCODE", profile: .codex) == .updated)
#expect(model.appProfiles.count == 1)
#expect(model.appProfiles.first?.profile == .codex)
}
@Test func негодныйИдентификаторСтрокуНеЗаводит() {
let model = AppProfilesFixture().makeModel()
#expect(model.addAppProfile(bundleID: " ", profile: .codex) == .invalidBundleID)
#expect(model.addAppProfile(bundleID: "два слова", profile: .codex) == .invalidBundleID)
#expect(model.appProfiles.isEmpty)
}
@Test func списокНеПереполняется() {
let model = AppProfilesFixture().makeModel()
for index in 0..<PromptAppProfileMap.maximumEntries {
#expect(model.addAppProfile(bundleID: "com.example.app\(index)", profile: .codex) == .added)
}
#expect(model.addAppProfile(bundleID: "com.example.extra", profile: .codex) == .listFull)
#expect(model.appProfiles.count == PromptAppProfileMap.maximumEntries)
}
@Test func сменаПрофиляИУдалениеДоходятДоНастроек() {
let fixture = AppProfilesFixture()
let model = fixture.makeModel()
model.addAppProfile(bundleID: "com.apple.mail", profile: .codex)
model.updateAppProfile(at: 0, profile: .generic)
#expect(model.save())
#expect(fixture.dictationSettings.promptAppProfiles
== [PromptAppProfileEntry(bundleID: "com.apple.mail", profile: .generic)])
model.removeAppProfile(at: 0)
#expect(model.save())
#expect(fixture.dictationSettings.promptAppProfiles.isEmpty)
}
/// Сброс к заводским обязан убирать список: там имена программ владельца,
/// и «сбросил, а они остались» — это не сброс.
@Test func сбросУбираетСписок() {
let fixture = AppProfilesFixture()
let model = fixture.makeModel()
model.addAppProfile(bundleID: "com.apple.dt.Xcode", profile: .codex)
#expect(model.save())
#expect(model.resetToFactoryDefaults())
#expect(model.appProfiles.isEmpty)
#expect(fixture.dictationSettings.promptAppProfiles.isEmpty)
#expect(fixture.dictationSettings.promptAppProfileMap
.profile(forBundleID: "com.apple.dt.Xcode") == .codex)
}
}
@MainActor
private final class AppProfilesFixture {
let defaults: UserDefaults
let dictationSettings: DictationSettings
let layoutHotkeySettings: SettingsManager
var mode: LayoutMode = .fixing
var launchAtLogin = true
private let suiteName: String
init() {
suiteName = "ru.smltlk.settings.appprofiles.tests.\(UUID().uuidString)"
defaults = UserDefaults(suiteName: suiteName)!
defaults.removePersistentDomain(forName: suiteName)
dictationSettings = DictationSettings(defaults: defaults)
layoutHotkeySettings = SettingsManager(defaults: defaults)
}
/// Домен сносится ПОСЛЕ работы: иначе каждый прогон оставлял бы по plist
/// в ~/Library/Preferences владельца.
deinit {
let manager = FileManager()
let url = manager.homeDirectoryForCurrentUser
.appendingPathComponent("Library/Preferences/\(suiteName).plist")
try? manager.removeItem(at: url)
}
func makeModel() -> SettingsModel {
SettingsModel(
dictationSettings: dictationSettings,
layoutSettings: LayoutSettingsAccess(
readMode: { self.mode },
writeMode: { self.mode = $0 },
readLaunchAtLogin: { self.launchAtLogin },
writeLaunchAtLogin: { self.launchAtLogin = $0 }
),
layoutHotkeys: .settings(layoutHotkeySettings),
codexDetector: { _ in URL(fileURLWithPath: "/usr/bin/true") }
)
}
}
@@ -0,0 +1,479 @@
import CoreGraphics
import Foundation
import IrizCore
import IrizInput
import IrizPrompt
import Testing
@testable import IrizSettings
@testable import IrizDictate
@MainActor
@Suite("Settings model")
struct SettingsModelTests {
/// Наследник теста про `MenuHotkeyLabels`: тот проверял шесть строк справки,
/// которую меню больше не печатает. Проверяемое обещание то же — клавиши
/// в меню взяты из настроек, а промпт-режим не показывается, пока выключен.
@Test func menuKeyHintsUseConfiguredKeysAndPromptMode() {
let fixture = Fixture()
fixture.dictationSettings.hotkeyKeycode = 96
fixture.dictationSettings.hotkeyModifiers = .maskCommand
fixture.dictationSettings.promptHotkeyKeycode = 79
fixture.dictationSettings.promptHotkeyModifiers = .maskControl
fixture.layoutHotkeySettings.triggerKey = "control"
fixture.layoutHotkeySettings.triggerRightOnly = true
fixture.layoutHotkeySettings.triggerDoubleTap = true
var hints = MenuKeys.hints(dictation: fixture.dictationSettings,
layout: fixture.layoutHotkeySettings)
#expect(hints.dictation == "⌘F5")
#expect(hints.conversion == "правый ⌃ дважды")
#expect(hints.prompt == nil)
fixture.dictationSettings.promptModeEnabled = true
hints = MenuKeys.hints(dictation: fixture.dictationSettings,
layout: fixture.layoutHotkeySettings)
#expect(hints.prompt == "⌃F18")
}
/// Клавиша в меню обязана быть той, что сработает. В «Паузе» ручной триггер
/// раскладки выходит по `guard autoSwitchEnabled` — подпись обещала бы впустую.
@Test func menuHidesLayoutKeyWhenPaused() {
let fixture = Fixture()
fixture.layoutHotkeySettings.autoSwitchEnabled = true
#expect(MenuKeys.hints(dictation: fixture.dictationSettings,
layout: fixture.layoutHotkeySettings).conversion == "⌥")
fixture.layoutHotkeySettings.autoSwitchEnabled = false
#expect(MenuKeys.hints(dictation: fixture.dictationSettings,
layout: fixture.layoutHotkeySettings).conversion == nil)
}
/// Одна нотация на всё меню: глифы, как их печатает macOS, и по-русски.
/// До этого в шести строках было три нотации и английские слова.
@Test func menuKeyNamesUseRussianGlyphs() {
#expect(MenuKeys.russianKeyName(
hotkeyChoice(forKeycode: RIGHT_COMMAND_KEYCODE)) == "правый ⌘")
#expect(MenuKeys.russianKeyName(
hotkeyChoice(forKeycode: RIGHT_COMMAND_KEYCODE, modifiers: .maskControl))
== "⌃ правый ⌘")
#expect(MenuKeys.russianKeyName(
hotkeyChoice(forKeycode: 49, modifiers: [.maskCommand, .maskShift])) == "⇧⌘␣")
#expect(!MenuKeys.russianKeyName(
hotkeyChoice(forKeycode: RIGHT_COMMAND_KEYCODE, modifiers: .maskAlternate))
.contains("Command"))
}
@Test func recordedHotkeyPersists() {
let fixture = Fixture()
let model = fixture.makeModel()
let recorded = recordableHotkeyChoice(forKeycode: 0, modifiers: [.maskCommand, .maskShift])!
let prompt = recordableHotkeyChoice(forKeycode: 97, modifiers: .maskCommand)!
let layout = recordableHotkeyChoice(forKeycode: CGKeyCode(KC.rightControl))!
let switchHotkey = recordableHotkeyChoice(forKeycode: CGKeyCode(KC.rightControl),
modifiers: .maskShift)!
model.setHotkey(recorded, for: .dictation)
model.setHotkey(prompt, for: .prompt)
model.setHotkey(layout, for: .layoutConversion)
model.setHotkey(switchHotkey, for: .layoutSwitch)
#expect(model.save())
let reloaded = fixture.makeModel()
#expect(reloaded.hotkeys[.dictation] == HotkeyBinding(choice: recorded))
#expect(fixture.dictationSettings.configuredHotkey == recorded)
#expect(reloaded.hotkeys[.prompt] == HotkeyBinding(choice: prompt))
#expect(fixture.dictationSettings.configuredPromptHotkey == prompt)
#expect(reloaded.hotkeys[.layoutConversion] == HotkeyBinding(choice: layout))
#expect(fixture.layoutHotkeySettings.triggerKey == "control")
#expect(fixture.layoutHotkeySettings.triggerRightOnly)
#expect(reloaded.hotkeys[.layoutSwitch] == HotkeyBinding(choice: switchHotkey))
#expect(fixture.layoutHotkeySettings.switchHotkey == "control+shift")
#expect(!fixture.layoutHotkeySettings.switchRightOnly)
}
@Test func duplicateHotkeysBlockSave() {
let fixture = Fixture()
let model = fixture.makeModel()
let duplicate = recordableHotkeyChoice(forKeycode: 96, modifiers: .maskControl)!
model.setHotkey(duplicate, for: .dictation)
model.setHotkey(duplicate, for: .history)
#expect(model.validationMessage?.contains("Конфликт") == true)
#expect(!model.save())
#expect(fixture.dictationSettings.hotkeyKeycode == RIGHT_COMMAND_KEYCODE)
}
@Test func unsupportedLayoutHotkeyBlocksSave() {
let fixture = Fixture()
let model = fixture.makeModel()
let unsupported = recordableHotkeyChoice(forKeycode: 96, modifiers: .maskControl)!
model.setHotkey(unsupported, for: .layoutConversion)
#expect(model.validationMessage?.contains("раскладка не понимает") == true)
#expect(!model.save())
#expect(fixture.layoutHotkeySettings.triggerKey == "option")
}
@Test func dictationAndLayoutHotkeyConflictBlocksSave() {
let fixture = Fixture()
let model = fixture.makeModel()
let duplicate = recordableHotkeyChoice(forKeycode: CGKeyCode(KC.rightCommand))!
model.setHotkey(duplicate, for: .dictation)
model.setHotkey(duplicate, for: .layoutConversion)
#expect(model.validationMessage?.contains("Конфликт") == true)
#expect(!model.save())
#expect(fixture.dictationSettings.hotkeyKeycode == RIGHT_COMMAND_KEYCODE)
#expect(fixture.layoutHotkeySettings.triggerKey == "option")
}
@Test func promptHotkeyConflictBlocksSave() {
let fixture = Fixture()
let model = fixture.makeModel()
let duplicate = recordableHotkeyChoice(forKeycode: 96, modifiers: .maskControl)!
model.setHotkey(duplicate, for: .dictation)
model.setHotkey(duplicate, for: .prompt)
#expect(model.validationMessage?.contains("Конфликт") == true)
#expect(model.validationMessage?.contains("Речь → промпт") == true)
#expect(!model.save())
#expect(fixture.dictationSettings.promptHotkeyKeycode == RIGHT_COMMAND_KEYCODE)
}
@Test func reservedPromptHotkeyBlocksSave() {
let fixture = Fixture()
let model = fixture.makeModel()
let reserved = recordableHotkeyChoice(forKeycode: 49, modifiers: .maskCommand)!
model.setHotkey(reserved, for: .prompt)
#expect(model.validationMessage?.contains("занято macOS") == true)
#expect(model.validationMessage?.contains("Речь → промпт") == true)
#expect(!model.save())
}
@Test func promptModeRecipientAndCodexPathPersist() throws {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("smltlk-settings-codex-\(UUID().uuidString)", isDirectory: true)
let executable = root.appendingPathComponent("codex")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
try Data("#!/bin/sh\n".utf8).write(to: executable)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path)
let fixture = Fixture()
let model = fixture.makeModel()
model.promptModeEnabled = true
model.promptRecipient = .generic
model.codexPath = " \(executable.path) "
#expect(model.save())
let reloaded = fixture.makeModel()
#expect(reloaded.promptModeEnabled)
#expect(reloaded.promptRecipient == .generic)
#expect(reloaded.codexPath == executable.path)
#expect(reloaded.detectedCodexPath == executable.path)
}
@Test func saveAppliesPromptSettingsToLiveController() throws {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("smltlk-live-prompt-settings-\(UUID().uuidString)", isDirectory: true)
let executable = root.appendingPathComponent("codex")
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
try Data("#!/bin/sh\n".utf8).write(to: executable)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path)
let fixture = Fixture()
let controller = DictationController(settings: fixture.dictationSettings)
let model = fixture.makeModel()
let promptHotkey = recordableHotkeyChoice(forKeycode: 97, modifiers: .maskCommand)!
model.promptModeEnabled = true
model.codexPath = executable.path
model.setHotkey(promptHotkey, for: .prompt)
#expect(model.save())
#expect(controller.promptSettingsForTesting.enabled)
#expect(controller.promptSettingsForTesting.hotkey == promptHotkey)
#expect(controller.promptSettingsForTesting.codexPath == executable.path)
model.promptModeEnabled = false
#expect(model.save())
#expect(!controller.promptSettingsForTesting.enabled)
}
@Test func promptModeWithNonExecutableCodexBlocksSave() throws {
let file = FileManager.default.temporaryDirectory
.appendingPathComponent("smltlk-non-executable-codex-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: file) }
try Data("not executable".utf8).write(to: file)
try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: file.path)
let fixture = Fixture()
let model = fixture.makeModel(codexDetector: { path in
FileManager.default.isExecutableFile(atPath: path)
? URL(fileURLWithPath: path)
: nil
})
model.promptModeEnabled = true
model.codexPath = file.path
#expect(model.validationMessage?.contains("не запускается") == true)
#expect(!model.save())
#expect(!fixture.dictationSettings.promptModeEnabled)
#expect(fixture.dictationSettings.codexExecutablePath.isEmpty)
}
@Test func correctionsSurviveAddEditAndDelete() {
let fixture = Fixture()
var model = fixture.makeModel()
// Хранилище НЕ пусто: заводской словарь подсаживается при первом создании
// настроек (DictationSettings.seedDefaultTranscriptCorrectionsOnce), иначе
// владельцу пришлось бы набирать 27 записей руками. Поэтому проверяем
// относительные изменения, а не абсолютную пустоту.
let seeded = model.corrections.count
#expect(seeded > 0, "заводской словарь не подсел — проверь посев в DictationSettings")
model.addCorrection(source: "паракит", replacement: "Parakeet")
#expect(model.save())
model = fixture.makeModel()
#expect(model.corrections.count == seeded + 1)
let added = try! #require(model.corrections.firstIndex(
of: TranscriptCorrection(source: "паракит", replacement: "Parakeet")))
model.updateCorrection(at: added, replacement: "Parakeet TDT")
#expect(model.save())
model = fixture.makeModel()
#expect(model.corrections[added].replacement == "Parakeet TDT")
model.removeCorrection(at: added)
#expect(model.save())
let afterDelete = fixture.makeModel().corrections
#expect(afterDelete.count == seeded)
#expect(!afterDelete.contains { $0.source == "паракит" })
}
/// Выбранная палитра обязана дойти до плашки, а не остаться в окне
/// настроек: настройка, которую никто не читает, ХУЖЕ отсутствующей —
/// она обещает и не делает.
@Test func палитраВолныСохраняетсяИВозвращаетсяКЗаводскойПриСбросе() {
let fixture = Fixture()
let model = fixture.makeModel()
#expect(model.wavePalette == DICTATION_HUD_DEFAULT_WAVE_PALETTE)
model.wavePalette = .mono
#expect(model.save())
#expect(fixture.dictationSettings.dictationHUDWavePalette == .mono)
#expect(fixture.makeModel().wavePalette == .mono)
#expect(model.resetToFactoryDefaults())
#expect(model.wavePalette == DICTATION_HUD_DEFAULT_WAVE_PALETTE)
#expect(fixture.dictationSettings.dictationHUDWavePalette
== DICTATION_HUD_DEFAULT_WAVE_PALETTE)
}
/// Выключатель окна спасения обязан доходить до рантайма диктовки: галка,
/// которую никто не читает, обещает и не делает. Заводское состояние —
/// включено, потому что молчаливый провал доставки стоит владельцу целой
/// надиктовки.
@Test func окноСпасенияСохраняетсяИВозвращаетсяКЗаводскомуПриСбросе() {
let fixture = Fixture()
let model = fixture.makeModel()
#expect(model.rescueWindowEnabled)
model.rescueWindowEnabled = false
#expect(model.save())
#expect(!fixture.dictationSettings.rescueWindowEnabled)
#expect(!fixture.makeModel().rescueWindowEnabled)
#expect(model.resetToFactoryDefaults())
#expect(model.rescueWindowEnabled)
#expect(fixture.dictationSettings.rescueWindowEnabled)
}
@Test func resetRestoresFactoryDefaults() {
let fixture = Fixture(mode: .paused, launchAtLogin: false)
let model = fixture.makeModel()
model.setHotkey(recordableHotkeyChoice(forKeycode: 1, modifiers: .maskCommand)!, for: .dictation)
model.enterDelayText = "499"
model.pasteSuffix = .appendNewline
model.addCorrection(source: "a", replacement: "b")
model.promptModeEnabled = true
model.promptRecipient = .generic
model.codexPath = "/custom/codex"
model.setHotkey(recordableHotkeyChoice(forKeycode: 97, modifiers: .maskCommand)!, for: .prompt)
fixture.dictationSettings.promptOnboardingOffered = true
#expect(model.resetToFactoryDefaults())
#expect(model.hotkeys[.dictation] == HotkeyBinding(keycode: RIGHT_COMMAND_KEYCODE))
#expect(model.enterDelayText == "120")
#expect(model.pasteSuffix == .appendSpace)
#expect(model.layoutMode == .fixing)
#expect(model.launchAtLogin)
#expect(model.corrections.isEmpty)
#expect(!model.promptModeEnabled)
#expect(model.promptRecipient == .codex)
#expect(model.codexPath.isEmpty)
#expect(model.hotkeys[.prompt]
== HotkeyBinding(keycode: RIGHT_COMMAND_KEYCODE, modifiers: .maskControl))
#expect(!fixture.dictationSettings.promptModeEnabled)
#expect(fixture.dictationSettings.promptRecipient == .codex)
#expect(fixture.dictationSettings.codexExecutablePath.isEmpty)
#expect(!fixture.dictationSettings.promptOnboardingOffered)
#expect(fixture.mode == .fixing)
#expect(fixture.launchAtLogin)
}
/// Выбор агента переживает перезапуск, а путь хранится отдельно на каждого:
/// переключение не должно подсунуть новому агенту чужой исполняемый файл.
@Test func promptAgentChoiceAndPerAgentPathsPersist() throws {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("smltlk-agent-paths-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let codex = root.appendingPathComponent("codex")
let ollama = root.appendingPathComponent("ollama")
for executable in [codex, ollama] {
try Data("#!/bin/sh\n".utf8).write(to: executable)
try FileManager.default.setAttributes(
[.posixPermissions: 0o755],
ofItemAtPath: executable.path
)
}
let fixture = Fixture()
let model = fixture.makeModel()
model.promptModeEnabled = true
model.codexPath = codex.path
model.promptAgentID = PromptAgentCatalog.ollamaID
model.agentPath = " \(ollama.path) "
model.agentModel = " qwen2.5-coder:7b "
#expect(model.save())
let reloaded = fixture.makeModel()
#expect(reloaded.promptAgentID == PromptAgentCatalog.ollamaID)
#expect(reloaded.agentPath == ollama.path)
#expect(reloaded.agentModel == "qwen2.5-coder:7b")
#expect(reloaded.codexPath == codex.path)
// Возврат к Codex возвращает путь Codex, а не путь Ollama.
reloaded.promptAgentID = PromptAgentCatalog.codexID
#expect(reloaded.agentPath == codex.path)
}
/// Цена выбора стоит рядом с выбором и меняется вместе с ним.
@Test func destinationLineFollowsAgentChoice() {
let model = Fixture().makeModel()
model.promptAgentID = PromptAgentCatalog.ollamaID
#expect(model.agentKeepsDataLocal)
#expect(model.agentDestinationTitle.contains("на этом Маке"))
model.promptAgentID = PromptAgentCatalog.codexID
#expect(!model.agentKeepsDataLocal)
#expect(model.agentDestinationTitle.contains("OpenAI"))
model.promptAgentID = PromptAgentCatalog.claudeID
#expect(model.agentDestinationTitle.contains("Anthropic"))
model.promptAgentID = PromptAgentCatalog.kimiID
#expect(model.agentDestinationTitle.contains("Moonshot"))
}
/// `ollama run` без модели запускать нечего: сохранение должно объяснить это,
/// а не молча записать заведомо нерабочую настройку.
@Test func localAgentWithoutModelBlocksSave() throws {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("smltlk-agent-model-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
let executable = root.appendingPathComponent("ollama")
try Data("#!/bin/sh\n".utf8).write(to: executable)
try FileManager.default.setAttributes(
[.posixPermissions: 0o755],
ofItemAtPath: executable.path
)
let fixture = Fixture()
let model = fixture.makeModel()
model.promptModeEnabled = true
model.promptAgentID = PromptAgentCatalog.ollamaID
model.agentPath = executable.path
#expect(model.validationMessage?.contains("модель") == true)
#expect(!model.save())
model.agentModel = "qwen2.5-coder:7b"
#expect(model.validationMessage == nil)
#expect(model.save())
}
/// Аргументы своего CLI хранятся построчно: командная строка не собирается
/// из строки, поэтому кавычек и shell-я в этой настройке нет.
@Test func customAgentArgumentsSurviveSaveLineByLine() {
let fixture = Fixture()
let model = fixture.makeModel()
model.promptAgentID = PromptAgentCatalog.customID
model.agentCustomArguments = "--flag\n \n{prompt}\n"
#expect(model.save())
#expect(model.customArgumentsList == ["--flag", "{prompt}"])
#expect(fixture.dictationSettings.promptAgentCustomArguments == ["--flag", "{prompt}"])
#expect(model.agentAdapter.promptDelivery == .argument)
}
@Test func repeatedSaveUsesLastPersistedLoginSetting() {
let fixture = Fixture(launchAtLogin: true)
let model = fixture.makeModel()
model.launchAtLogin = false
#expect(model.save())
#expect(!fixture.launchAtLogin)
model.launchAtLogin = true
#expect(model.save())
#expect(fixture.launchAtLogin)
}
}
@MainActor
private final class Fixture {
let defaults: UserDefaults
let dictationSettings: DictationSettings
let layoutHotkeySettings: SettingsManager
var mode: LayoutMode
var launchAtLogin: Bool
init(mode: LayoutMode = .fixing, launchAtLogin: Bool = true) {
let suiteName = "ru.smltlk.settings.tests.\(UUID().uuidString)"
defaults = UserDefaults(suiteName: suiteName)!
defaults.removePersistentDomain(forName: suiteName)
dictationSettings = DictationSettings(defaults: defaults)
layoutHotkeySettings = SettingsManager(defaults: defaults)
self.mode = mode
self.launchAtLogin = launchAtLogin
}
func makeModel(
codexDetector: @escaping (String) -> URL? = {
DictationSettings.detectCodexExecutable(storedPath: $0)
}
) -> SettingsModel {
SettingsModel(
dictationSettings: dictationSettings,
layoutSettings: LayoutSettingsAccess(
readMode: { self.mode },
writeMode: { self.mode = $0 },
readLaunchAtLogin: { self.launchAtLogin },
writeLaunchAtLogin: { self.launchAtLogin = $0 }
),
layoutHotkeys: .settings(layoutHotkeySettings),
codexDetector: codexDetector
)
}
}
@@ -0,0 +1,209 @@
// Окно настроек: редактор заготовок и кнопки «Экспортировать» / «Импортировать».
//
// Ключевая проверка — что настройка не осталась обещанием: заготовка, заведённая
// в окне, доходит до `DictationSettings` и оттуда до конвейера диктовки.
import CoreGraphics
import Foundation
import IrizCore
import IrizInput
import Testing
@testable import IrizSettings
@testable import IrizDictate
@MainActor
@Suite("Настройки: заготовки")
struct SettingsSnippetsTests {
@Test func заготовкаИзОкнаДоходитДоНастроекИКонвейера() {
let fixture = TransferFixture()
let model = fixture.makeModel()
#expect(model.snippets.isEmpty)
model.addSnippet(trigger: "шапка иска", body: "В Верховный суд\nот ИП Иванова")
#expect(model.save())
let stored = fixture.dictationSettings.snippets
#expect(stored == [DictationSnippet(trigger: "шапка иска",
body: "В Верховный суд\nот ИП Иванова")])
let processed = processedDictationText(rawTranscript: "шапка иска дальше",
corrections: fixture.dictationSettings.transcriptCorrections,
snippets: stored)
#expect(processed.text.hasPrefix("В Верховный суд"))
#expect(processed.appliedSnippetCount == 1)
}
@Test func полупустаяЗаготовкаНеДаётСохранить() {
let model = TransferFixture().makeModel()
model.addSnippet(trigger: "шапка", body: "")
#expect(model.validationMessage == "У заготовки нужны и фраза, и текст.")
#expect(!model.canSave)
#expect(!model.save())
model.updateSnippet(at: 0, body: "текст")
#expect(model.validationMessage == nil)
#expect(model.save())
}
@Test func фразаБезБуквыИЦифрыНеДаётСохранить() {
let model = TransferFixture().makeModel()
model.addSnippet(trigger: "...", body: "текст")
#expect(model.validationMessage?.contains("ни буквы, ни цифры") == true)
#expect(!model.canSave)
}
@Test func удалениеЗаготовкиДоходитДоДиска() {
let fixture = TransferFixture()
let model = fixture.makeModel()
model.addSnippet(trigger: "первая фраза", body: "тело")
model.addSnippet(trigger: "вторая фраза", body: "тело")
#expect(model.save())
#expect(fixture.dictationSettings.snippets.count == 2)
model.removeSnippet(at: 0)
#expect(model.save())
#expect(fixture.dictationSettings.snippets
== [DictationSnippet(trigger: "вторая фраза", body: "тело")])
}
@Test func сбросКЗаводскимОчищаетЗаготовки() {
let fixture = TransferFixture()
let model = fixture.makeModel()
model.addSnippet(trigger: "шапка иска", body: "тело")
#expect(model.save())
#expect(model.resetToFactoryDefaults())
#expect(model.snippets.isEmpty)
#expect(fixture.dictationSettings.snippets.isEmpty)
}
}
@MainActor
@Suite("Настройки: словарь файлом")
struct SettingsDictionaryTransferTests {
/// Круг целиком через окно: выгрузили, снесли настройки, загрузили в чистое
/// окно — словарь и заготовки на месте.
@Test func кругЧерезФайлВосстанавливаетСловарьИЗаготовки() throws {
let source = TransferFixture()
let sourceModel = source.makeModel()
sourceModel.corrections = [TranscriptCorrection(source: "смолток", replacement: "smltlk")]
sourceModel.addSnippet(trigger: "шапка иска", body: "В Верховный суд")
#expect(sourceModel.save())
let data = sourceModel.exportedDictionaryData()
let empty = TransferFixture()
let emptyModel = empty.makeModel()
emptyModel.corrections = []
#expect(emptyModel.save())
let summary = try emptyModel.importDictionaryData(data)
#expect(summary.contains("добавлено"))
#expect(emptyModel.save())
#expect(empty.dictationSettings.transcriptCorrections
== [TranscriptCorrection(source: "смолток", replacement: "smltlk")])
#expect(empty.dictationSettings.snippets
== [DictationSnippet(trigger: "шапка иска", body: "В Верховный суд")])
}
/// Выгружается то, что в окне сейчас, а не то, что на диске: иначе кнопка
/// врала бы про только что набранную запись.
@Test func экспортБерётНесохранённоеСостояниеОкна() throws {
let model = TransferFixture().makeModel()
model.corrections = [TranscriptCorrection(source: "новое", replacement: "НОВОЕ")]
let document = try DictionaryTransfer.decode(model.exportedDictionaryData())
#expect(document.corrections == [TranscriptCorrection(source: "новое", replacement: "НОВОЕ")])
}
/// Негодный файл не трогает окно вообще: ни половины, ни очистки.
@Test func негодныйФайлНеМеняетОкноИНазываетПричину() {
let model = TransferFixture().makeModel()
model.corrections = [TranscriptCorrection(source: "местное", replacement: "МЕСТНОЕ")]
model.addSnippet(trigger: "местная фраза", body: "тело")
#expect(throws: DictionaryTransferError.notJSON) {
try model.importDictionaryData(Data("совсем не json".utf8))
}
#expect(model.corrections == [TranscriptCorrection(source: "местное", replacement: "МЕСТНОЕ")])
#expect(model.snippets == [DictationSnippet(trigger: "местная фраза", body: "тело")])
}
/// Импорт правит только окно. На диск он попадает общей кнопкой
/// «Сохранить» — значит, ошибочный импорт закрывается без последствий.
@Test func импортБезСохраненияДоДискаНеДоходит() throws {
let fixture = TransferFixture()
let model = fixture.makeModel()
model.corrections = []
#expect(model.save())
let data = DictionaryTransfer.encode(
corrections: [TranscriptCorrection(source: "смолток", replacement: "smltlk")],
snippets: []
)
_ = try model.importDictionaryData(data)
#expect(model.corrections.count == 1)
#expect(fixture.dictationSettings.transcriptCorrections.isEmpty)
}
@Test func столкновениеИмёнРешаетсяВПользуФайлаИНазываетсяЧислом() throws {
let model = TransferFixture().makeModel()
model.corrections = [TranscriptCorrection(source: "эцп", replacement: "местная")]
let data = DictionaryTransfer.encode(
corrections: [TranscriptCorrection(source: "ЭЦП", replacement: "ИЗ ФАЙЛА")],
snippets: []
)
let summary = try model.importDictionaryData(data)
#expect(model.corrections == [TranscriptCorrection(source: "ЭЦП", replacement: "ИЗ ФАЙЛА")])
#expect(summary == "Импорт: замен перезаписано 1.")
}
}
@MainActor
private final class TransferFixture {
let defaults: UserDefaults
let dictationSettings: DictationSettings
let layoutHotkeySettings: SettingsManager
var mode: LayoutMode = .fixing
var launchAtLogin = true
private let suiteName: String
init() {
suiteName = "ru.smltlk.settings.transfer.tests.\(UUID().uuidString)"
defaults = UserDefaults(suiteName: suiteName)!
defaults.removePersistentDomain(forName: suiteName)
dictationSettings = DictationSettings(defaults: defaults)
layoutHotkeySettings = SettingsManager(defaults: defaults)
}
/// Домен настроек сносится ПОСЛЕ работы, а не только до неё: иначе каждый
/// прогон оставлял бы по plist в ~/Library/Preferences владельца.
/// Свой FileManager и только строка имени — в nonisolated deinit больше
/// ничего трогать нельзя.
deinit {
let manager = FileManager()
let url = manager.homeDirectoryForCurrentUser
.appendingPathComponent("Library/Preferences/\(suiteName).plist")
try? manager.removeItem(at: url)
}
func makeModel() -> SettingsModel {
SettingsModel(
dictationSettings: dictationSettings,
layoutSettings: LayoutSettingsAccess(
readMode: { self.mode },
writeMode: { self.mode = $0 },
readLaunchAtLogin: { self.launchAtLogin },
writeLaunchAtLogin: { self.launchAtLogin = $0 }
),
layoutHotkeys: .settings(layoutHotkeySettings),
codexDetector: { _ in URL(fileURLWithPath: "/usr/bin/true") }
)
}
}