fix: improve model setup and native workflows
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
import AppKit
|
||||
import Testing
|
||||
@testable import IrizDictate
|
||||
|
||||
@Suite("плашка: доступные кнопки и уменьшение движения")
|
||||
@MainActor
|
||||
struct DictationHUDAccessibilityTests {
|
||||
@Test func действиеAXИспользуетАктуальнуюКнопку() {
|
||||
let button = DictationHUDActionButton(action: dictationHUDActions(isRecording: false)[0])
|
||||
var invoked: [DictationHUDActionID] = []
|
||||
button.onPress = { invoked.append($0) }
|
||||
#expect(button.isAccessibilityElement())
|
||||
#expect(button.accessibilityRole() == .button)
|
||||
#expect(button.accessibilityLabel() == button.action.title)
|
||||
#expect(button.accessibilityPerformPress())
|
||||
button.action = dictationHUDActions(isRecording: true)[0]
|
||||
#expect(button.accessibilityLabel() == button.action.title)
|
||||
#expect(button.toolTip == button.action.title)
|
||||
#expect(button.accessibilityPerformPress())
|
||||
#expect(invoked == [.record, .record])
|
||||
button.isHidden = true
|
||||
#expect(!button.accessibilityPerformPress())
|
||||
#expect(invoked.count == 2)
|
||||
}
|
||||
|
||||
@Test func копированиеИЗакрытиеИмеютСемантикуИДействия() {
|
||||
// Обработчики-заглушки: настоящий буфер обмена тест не меняет.
|
||||
let copy = DictationHUDCopyPill(frame: .zero)
|
||||
let close = DictationHUDCloseRing(frame: .zero)
|
||||
var copies = 0
|
||||
var closes = 0
|
||||
copy.title = "Скопировать"
|
||||
copy.onPress = { copies += 1 }
|
||||
close.onPress = { closes += 1 }
|
||||
for button in [copy as NSView, close as NSView] {
|
||||
#expect(button.isAccessibilityElement())
|
||||
#expect(button.accessibilityRole() == .button)
|
||||
#expect(button.accessibilityLabel()?.isEmpty == false)
|
||||
#expect(button.accessibilityPerformPress())
|
||||
}
|
||||
#expect(copies == 1)
|
||||
#expect(closes == 1)
|
||||
copy.title = "Скопировано"
|
||||
#expect(copy.accessibilityLabel() == "Скопировано")
|
||||
close.isHidden = true
|
||||
#expect(!close.accessibilityPerformPress())
|
||||
#expect(closes == 1)
|
||||
}
|
||||
|
||||
@Test func сменаНастройкиОстанавливаетУжеНачатыйHover() throws {
|
||||
let center = NotificationCenter()
|
||||
var reduced = false
|
||||
let button = DictationHUDActionButton(
|
||||
action: dictationHUDActions(isRecording: false)[0],
|
||||
reduceMotion: { reduced }, displayOptionsCenter: center)
|
||||
button.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
|
||||
button.forceHover(true)
|
||||
let layer = try #require(button.layer)
|
||||
#expect(layer.animation(forKey: "irizHoverLift") != nil)
|
||||
reduced = true
|
||||
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
|
||||
#expect(layer.animation(forKey: "irizHoverLift") == nil)
|
||||
#expect(CATransform3DIsIdentity(layer.transform))
|
||||
button.forceHover(false)
|
||||
button.forceHover(true)
|
||||
#expect(layer.animation(forKey: "irizHoverLift") == nil)
|
||||
#expect(CATransform3DIsIdentity(layer.transform))
|
||||
reduced = false
|
||||
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
|
||||
#expect(layer.animation(forKey: "irizHoverLift") != nil)
|
||||
}
|
||||
|
||||
@Test func ожиданиеПеречитываетНастройкуБезТаймераУровня() throws {
|
||||
let center = NotificationCenter()
|
||||
let surface = AccessibilityHUDSurface()
|
||||
var reduced = false
|
||||
let presenter = DictationHUDPresenter(
|
||||
level: { 0 }, pipelineState: { .transcribing }, historyHint: { "" },
|
||||
reduceMotion: { reduced }, displayOptionsCenter: center, surface: { surface })
|
||||
presenter.pipelineStateChanged(.transcribing)
|
||||
#expect(!presenter.isPollingLevel)
|
||||
#expect(try #require(surface.content).animatesWaiting)
|
||||
reduced = true
|
||||
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
|
||||
let still = try #require(surface.content)
|
||||
#expect(still.stage == .recognizing)
|
||||
#expect(!still.animatesWaiting)
|
||||
reduced = false
|
||||
center.post(name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil)
|
||||
#expect(try #require(surface.content).animatesWaiting)
|
||||
#expect(!presenter.isPollingLevel)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class AccessibilityHUDSurface: DictationHUDSurface {
|
||||
var content: DictationHUDContent?
|
||||
func present(_ content: DictationHUDContent) { self.content = content }
|
||||
func dismiss() { content = nil }
|
||||
}
|
||||
@@ -131,6 +131,92 @@ struct DictationHistorySearchTests {
|
||||
|
||||
// MARK: - Порядок
|
||||
|
||||
@Suite("UI-MACOS-208/209: загрузка истории и приватное превью")
|
||||
struct DictationHistoryLoadingTests {
|
||||
@MainActor
|
||||
@Test func поздняяСотняНеПерезаписываетПолныйПоиск() {
|
||||
let model = DictationHistoryModel()
|
||||
let recent = DictationHistoryEntry(directory: URL(fileURLWithPath: "/tmp/recent"), text: "свежее")
|
||||
let older = DictationHistoryEntry(directory: URL(fileURLWithPath: "/tmp/older"), text: "старый ответ")
|
||||
let partial = model.beginLoading(all: false)
|
||||
let full = model.beginLoading(all: true)
|
||||
model.completeLoading(.success([recent, older]), generation: full, all: true)
|
||||
model.completeLoading(.success([recent]), generation: partial, all: false)
|
||||
#expect(model.entries == [recent, older])
|
||||
#expect(model.didLoadAll)
|
||||
#expect(!model.isLoading)
|
||||
|
||||
let closed = model.beginLoading(all: true)
|
||||
model.cancelLoading()
|
||||
model.completeLoading(.success([]), generation: closed, all: true)
|
||||
#expect(model.entries == [recent, older])
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func previewНеВызываетДажеПровайдерРеальногоКаталога() {
|
||||
let model = DictationHistoryModel(preview: true)
|
||||
var rootCalls = 0
|
||||
model.query = "закрытая запись"
|
||||
model.reload {
|
||||
rootCalls += 1
|
||||
throw CocoaError(.fileReadNoPermission)
|
||||
}
|
||||
#expect(rootCalls == 0)
|
||||
#expect(model.entries.isEmpty)
|
||||
#expect(!model.isLoading)
|
||||
#expect(model.notice == nil)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func ошибкаЧтенияНеВыдаётсяЗаПустуюИсторию() {
|
||||
let model = DictationHistoryModel()
|
||||
let generation = model.beginLoading(all: true)
|
||||
model.completeLoading(.failure(CocoaError(.fileReadNoPermission)),
|
||||
generation: generation, all: true)
|
||||
#expect(!model.isLoading)
|
||||
#expect(!model.didLoadAll)
|
||||
#expect(model.noticeIsError)
|
||||
#expect(model.notice?.isEmpty == false)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func повторноеОткрытиеСЗапросомИОчисткаВидятЗаписиЗаПределамиПятисот() async throws {
|
||||
let root = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("iriz-history-full-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
for index in 0..<503 {
|
||||
_ = try makeEntryOnDisk(in: root, label: String(format: "%04d", index),
|
||||
raw: index == 0 ? "самая старая искомая фраза" : "свежая запись")
|
||||
}
|
||||
// Это снимок для подтверждения «Очистить всё»; реальные удаления не нужны.
|
||||
#expect(try readDictationHistoryEntries(in: root).count == 503)
|
||||
#expect(try readDictationHistoryEntries(in: root, limit: DICTATION_HISTORY_VISIBLE_LIMIT).count == 100)
|
||||
|
||||
let model = DictationHistoryModel()
|
||||
model.query = "искомая фраза"
|
||||
for _ in 0..<2 {
|
||||
model.reload { root }
|
||||
for _ in 0..<500 {
|
||||
if !model.isLoading { break }
|
||||
try await Task.sleep(nanoseconds: 10_000_000)
|
||||
}
|
||||
#expect(!model.isLoading)
|
||||
#expect(model.didLoadAll)
|
||||
#expect(model.entries.count == 503)
|
||||
#expect(model.visible.map(\.label) == ["0000"])
|
||||
model.cancelLoading()
|
||||
}
|
||||
}
|
||||
|
||||
@Test func commandCУступаетВыделенномуТекстуПоиска() {
|
||||
#expect(dictationHistoryKeyAction(keyCode: 8, charactersIgnoringModifiers: "c",
|
||||
hasCommand: true, hasTextSelection: true) == .passThrough)
|
||||
#expect(dictationHistoryKeyAction(keyCode: 8, charactersIgnoringModifiers: "c",
|
||||
hasCommand: true, hasTextSelection: false) == .copySelected)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("Порядок записей истории")
|
||||
struct DictationHistoryOrderTests {
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import Foundation
|
||||
import IrizCore
|
||||
import Testing
|
||||
|
||||
@testable import IrizDictate
|
||||
|
||||
@MainActor
|
||||
@Suite("Кнопка записи в знакомстве и HUD")
|
||||
struct DictationUIToggleTests {
|
||||
private func makeController() -> (DictationController, () -> Void) {
|
||||
let name = "iriz-ui-toggle-" + UUID().uuidString
|
||||
let defaults = UserDefaults(suiteName: name)!
|
||||
let settings = DictationSettings(defaults: defaults)
|
||||
settings.playFeedbackSounds = false
|
||||
let controller = DictationController(settings: settings,
|
||||
insertionStats: InsertionStats(defaults: defaults))
|
||||
return (controller, { removeSuiteFile(named: name, defaults: defaults) })
|
||||
}
|
||||
|
||||
@Test("повторное нажатие завершает запись вместо отказа alreadyRecording")
|
||||
func secondClickFinishesRecording() {
|
||||
let (controller, cleanup) = makeController()
|
||||
defer { cleanup() }
|
||||
// Только пустой буфер: опора не включает микрофон и не запускает ASR.
|
||||
controller.simulateActiveRecordingForTesting()
|
||||
#expect(controller.isRecordingActive)
|
||||
controller.toggleDictationFromUI()
|
||||
#expect(!controller.isRecordingActive)
|
||||
#expect(!controller.audioStateForTesting.isRunning)
|
||||
#expect(controller.state == .ready)
|
||||
}
|
||||
|
||||
@Test("нажатие во время разбора не запускает и не отменяет запись")
|
||||
func busyProcessingIsPreserved() {
|
||||
let (controller, cleanup) = makeController()
|
||||
defer { cleanup() }
|
||||
#expect(controller.beginMeetingProcessing() != nil)
|
||||
controller.toggleDictationFromUI()
|
||||
#expect(controller.isBusyForTesting)
|
||||
#expect(controller.state == .transcribing)
|
||||
#expect(!controller.isRecordingActive)
|
||||
controller.stop()
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,63 @@ import Testing
|
||||
|
||||
@Suite("Решения конвейера встречи")
|
||||
struct MeetingPipelineTests {
|
||||
@MainActor
|
||||
@Test("отменённый разбор не читает запись и не начинает распознавание")
|
||||
func отменаДоНачалаОстанавливаетКонвейер() async {
|
||||
let task = Task { @MainActor in
|
||||
withUnsafeCurrentTask { $0?.cancel() }
|
||||
var startedStages: [String] = []
|
||||
do {
|
||||
_ = try await MeetingPipeline().run(
|
||||
audio: URL(fileURLWithPath: "/iriz-test-no-audio.wav"), title: "Встреча",
|
||||
progress: { startedStages.append($0) })
|
||||
Issue.record("Отменённый разбор не должен завершаться успешно")
|
||||
} catch is CancellationError {
|
||||
#expect(startedStages.isEmpty)
|
||||
} catch {
|
||||
Issue.record("Отмена подменена отказом обработки: \(error)")
|
||||
}
|
||||
}
|
||||
await task.value
|
||||
}
|
||||
|
||||
@Test("без времён слов полный текст сохраняется даже при успешной диаризации")
|
||||
func текстБезТайминговНеТеряется() {
|
||||
let spans = [SpeakerSpan(speaker: "speaker-1", start: 0, end: 12)]
|
||||
let tokenCases: [[DictationTokenTiming]] = [
|
||||
[], [DictationTokenTiming(token: " ", start: 0, end: 1, confidence: 1)]
|
||||
]
|
||||
for tokens in tokenCases {
|
||||
let transcript = AudioFileTranscript(text: "Первая реплика.\nВторая реплика.",
|
||||
processingSeconds: 1, audioSeconds: 12,
|
||||
tokenTimings: tokens)
|
||||
let resolved = meetingSpeakerTurns(transcript: transcript, spans: spans)
|
||||
#expect(!resolved.speakersResolved)
|
||||
#expect(resolved.turns == [SpeakerTurn(speaker: "Запись", text: transcript.text,
|
||||
start: 0, end: 12)])
|
||||
let document = MeetingProtocolDocument(title: "Встреча", recordedAt: Date(),
|
||||
audioSeconds: 12, turns: resolved.turns)
|
||||
#expect(document.text().contains(transcript.text))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("при пригодных таймингах сохраняются реплики и имена говорящих")
|
||||
func таймингиПозволяютРазделитьГоворящих() {
|
||||
let transcript = AudioFileTranscript(text: "Да. Нет.", processingSeconds: 1, audioSeconds: 2,
|
||||
tokenTimings: [
|
||||
DictationTokenTiming(token: "Да.", start: 0, end: 1, confidence: 1),
|
||||
DictationTokenTiming(token: "Нет.", start: 1, end: 2, confidence: 1)
|
||||
])
|
||||
let resolved = meetingSpeakerTurns(
|
||||
transcript: transcript,
|
||||
spans: [SpeakerSpan(speaker: "one", start: 0, end: 1),
|
||||
SpeakerSpan(speaker: "two", start: 1, end: 2)],
|
||||
names: SpeakerNames(names: ["one": "Анна", "two": "Борис"]))
|
||||
#expect(resolved.speakersResolved)
|
||||
#expect(resolved.turns.map(\.speaker) == ["Анна", "Борис"])
|
||||
#expect(resolved.turns.map(\.text) == ["Да.", "Нет."])
|
||||
}
|
||||
|
||||
@Test("отказы названы поимённо")
|
||||
func отказыНазваныПоимённо() {
|
||||
// Разбирать будут запись заседания: «не смог» без причины неотличимо
|
||||
|
||||
@@ -5,12 +5,41 @@
|
||||
// разница между режимами - сохранённый звук, и путаница здесь стоит записи
|
||||
// заседания.
|
||||
import AppKit
|
||||
import Foundation
|
||||
import IrizCore
|
||||
import Testing
|
||||
|
||||
@testable import IrizDictate
|
||||
|
||||
@Suite("Состояние записи встречи")
|
||||
struct MeetingRecordingStateTests {
|
||||
@Test("встреча записывается до трёх часов, диктовка — до двадцати минут")
|
||||
func отдельныйПределВстречи() {
|
||||
#expect(DictationController.recordingLimitSeconds(for: .meeting) == 3 * 60 * 60)
|
||||
for purpose in [DictationRecordingPurpose.dictation, .prompt, .translation] {
|
||||
#expect(DictationController.recordingLimitSeconds(for: purpose) == 20 * 60)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test("разбор встречи показывает занятость и блокирует повторное распознавание")
|
||||
func разборЗанимаетОбщийКонвейер() {
|
||||
let name = "iriz-meeting-processing-\(UUID().uuidString)"
|
||||
let defaults = UserDefaults(suiteName: name)!
|
||||
defer { removeSuiteFile(named: name, defaults: defaults) }
|
||||
let controller = DictationController(settings: DictationSettings(defaults: defaults),
|
||||
insertionStats: InsertionStats(defaults: defaults))
|
||||
#expect(controller.beginMeetingProcessing() != nil)
|
||||
#expect(controller.state == .transcribing)
|
||||
#expect(controller.isBusyForTesting)
|
||||
#expect(controller.beginMeetingProcessing() == nil)
|
||||
#expect(dictationStartRefusal(modelReady: true, isRecording: false,
|
||||
isBusy: controller.isBusyForTesting,
|
||||
secureInputActive: false) == .transcriptionInFlight)
|
||||
controller.stop()
|
||||
#expect(!controller.isBusyForTesting)
|
||||
}
|
||||
|
||||
@Test("у записи встречи свой цвет, не совпадающий ни с одним другим")
|
||||
func свойЦвет() {
|
||||
let meeting = dictationHUDWaveColor(.meeting)
|
||||
|
||||
@@ -90,4 +90,47 @@ struct MeetingStoreTests {
|
||||
let text = try String(contentsOf: second.transcript, encoding: .utf8)
|
||||
#expect(text == "второй")
|
||||
}
|
||||
|
||||
@Test("разные русские записи одной минуты не перезаписывают друг друга")
|
||||
func коллизияНазванийНеЗатираетАрхив() throws {
|
||||
let root = try sandbox()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let firstAudio = try fakeAudio(in: root)
|
||||
let secondAudio = root.appendingPathComponent("second.wav")
|
||||
let secondData = Data([0x01, 0x02, 0x03])
|
||||
try secondData.write(to: secondAudio)
|
||||
let date = Date(timeIntervalSince1970: 1_757_000_000)
|
||||
let first = try MeetingStore.save(audio: firstAudio, protocolText: "первый",
|
||||
at: date, title: "Встреча", in: root)
|
||||
let second = try MeetingStore.save(audio: secondAudio, protocolText: "второй",
|
||||
at: date, title: "Заседание", in: root)
|
||||
|
||||
#expect(first.directory != second.directory)
|
||||
#expect(try Data(contentsOf: first.audio) == Data(contentsOf: firstAudio))
|
||||
#expect(try String(contentsOf: first.transcript, encoding: .utf8) == "первый")
|
||||
#expect(try Data(contentsOf: second.audio) == secondData)
|
||||
#expect(try String(contentsOf: second.transcript, encoding: .utf8) == "второй")
|
||||
}
|
||||
|
||||
@Test("отказ нового сохранения оставляет старую пару целой и убирает staging")
|
||||
func отказСохраненияНеРазрушаетАрхив() throws {
|
||||
let root = try sandbox()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let audio = try fakeAudio(in: root)
|
||||
let date = Date(timeIntervalSince1970: 1_757_000_000)
|
||||
let saved = try MeetingStore.save(audio: audio, protocolText: "сохранённый протокол",
|
||||
at: date, title: "Встреча", in: root)
|
||||
let missing = root.appendingPathComponent("missing.wav")
|
||||
|
||||
#expect(throws: (any Error).self) {
|
||||
try MeetingStore.save(audio: missing, protocolText: "не сохранится",
|
||||
at: date, title: "Встреча", in: root)
|
||||
}
|
||||
#expect(try Data(contentsOf: saved.audio) == Data(contentsOf: audio))
|
||||
#expect(try String(contentsOf: saved.transcript, encoding: .utf8) == "сохранённый протокол")
|
||||
let children = try FileManager.default.contentsOfDirectory(
|
||||
at: MeetingStore.meetingsDirectory(in: root), includingPropertiesForKeys: nil)
|
||||
#expect(children.map { $0.resolvingSymlinksInPath().path }
|
||||
== [saved.directory.resolvingSymlinksInPath().path])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import Foundation
|
||||
import IrizCore
|
||||
import Testing
|
||||
|
||||
@testable import IrizDictate
|
||||
|
||||
@Suite("Подготовка и восстановление модели без сети")
|
||||
struct SpeechModelRecoveryTests {
|
||||
@Test("сетевые ошибки установки объясняют причину и действие без технического кода")
|
||||
func installErrorsExplainRecovery() {
|
||||
let cases: [(URLError.Code, String, String)] = [
|
||||
(.notConnectedToInternet, "speechModel.error.offline", "Нет подключения к интернету. Подключись к сети и повтори скачивание."),
|
||||
(.networkConnectionLost, "speechModel.error.connectionLost", "Соединение прервалось. Проверь интернет и повтори скачивание."),
|
||||
(.timedOut, "speechModel.error.timeout", "Сервер не ответил вовремя. Повтори скачивание чуть позже."),
|
||||
(.cancelled, "speechModel.error.cancelled", "Скачивание отменено. Его можно запустить снова.")
|
||||
]
|
||||
for (code, key, fallback) in cases {
|
||||
let message = speechModelInstallFailureMessage(for: URLError(code))
|
||||
#expect(message == L(key, fallback))
|
||||
#expect(!message.contains("NSURLErrorDomain"))
|
||||
}
|
||||
#expect(speechModelInstallFailureMessage(for: CancellationError())
|
||||
== speechModelInstallFailureMessage(for: URLError(.cancelled)))
|
||||
let unknown = NSError(domain: "fixture", code: 42,
|
||||
userInfo: [NSLocalizedDescriptionKey: "Подробности отказа"])
|
||||
#expect(speechModelInstallFailureMessage(for: unknown) == "Подробности отказа")
|
||||
}
|
||||
|
||||
private func sandbox() throws -> URL {
|
||||
let root = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("iriz-model-recovery-" + UUID().uuidString, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
return root
|
||||
}
|
||||
|
||||
@Test("пустая или неполная папка не означает установленную модель")
|
||||
func cacheRequiresEveryModelFile() throws {
|
||||
let root = try sandbox()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
|
||||
for file in ModelIntegrity.parakeetV3DownloadFiles {
|
||||
let target = root.appendingPathComponent(file.relativePath)
|
||||
try FileManager.default.createDirectory(at: target.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true)
|
||||
try Data("fixture".utf8).write(to: target)
|
||||
}
|
||||
// Быстрый UI-probe проверяет состав. SHA-256 проверяется отдельно.
|
||||
#expect(speechModelCacheIsComplete(for: .multilingualV3, at: root))
|
||||
let vocabulary = root.appendingPathComponent("parakeet_vocab.json")
|
||||
try Data().write(to: vocabulary)
|
||||
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
|
||||
try FileManager.default.removeItem(at: vocabulary)
|
||||
#expect(!speechModelCacheIsComplete(for: .multilingualV3, at: root))
|
||||
}
|
||||
|
||||
@Test("Whisper требует непустой файл, каталог с именем модели не подходит")
|
||||
func whisperRequiresNonemptyFile() throws {
|
||||
let root = try sandbox()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let model = root.appendingPathComponent("ggml-large-v3-turbo.bin")
|
||||
try FileManager.default.createDirectory(at: model, withIntermediateDirectories: false)
|
||||
#expect(!speechModelCacheIsComplete(for: .whisperTurbo, at: root))
|
||||
try FileManager.default.removeItem(at: model)
|
||||
try Data().write(to: model)
|
||||
#expect(!speechModelCacheIsComplete(for: .whisperTurbo, at: root))
|
||||
try Data("fixture".utf8).write(to: model)
|
||||
#expect(speechModelCacheIsComplete(for: .whisperTurbo, at: root))
|
||||
}
|
||||
|
||||
@Test("адреса скачивания ограничены файлами закреплённого манифеста")
|
||||
func downloadsUsePinnedAllowlist() throws {
|
||||
for file in ModelIntegrity.parakeetV3DownloadFiles {
|
||||
let url = try speechModelDownloadURL(for: file)
|
||||
#expect(url.scheme == "https")
|
||||
#expect(url.host == "huggingface.co")
|
||||
#expect(url.path.contains("/resolve/" + ModelIntegrity.parakeetV3RepositoryCommit + "/"))
|
||||
#expect(!url.path.contains("/resolve/main/"))
|
||||
}
|
||||
#expect(throws: URLError.self) {
|
||||
try speechModelDownloadURL(for: ModelFileDigest(relativePath: "../outside.bin",
|
||||
sha256: String(repeating: "0", count: 64)))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("публикация новой модели сохраняет предыдущую копию")
|
||||
func publicationKeepsPreviousCache() throws {
|
||||
let root = try sandbox()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let cache = root.appendingPathComponent("cache", isDirectory: true)
|
||||
let staging = root.appendingPathComponent("staging", isDirectory: true)
|
||||
for url in [cache, staging] {
|
||||
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
|
||||
}
|
||||
try Data("previous".utf8).write(to: cache.appendingPathComponent("model"))
|
||||
try Data("new".utf8).write(to: staging.appendingPathComponent("model"))
|
||||
try publishSpeechModelCache(from: staging, to: cache)
|
||||
#expect(try String(contentsOf: cache.appendingPathComponent("model"), encoding: .utf8) == "new")
|
||||
let backups = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)
|
||||
.filter { $0.lastPathComponent.hasPrefix(".iriz-model-backup-") }
|
||||
let backup = try #require(backups.first)
|
||||
#expect(backups.count == 1)
|
||||
#expect(try String(contentsOf: backup.appendingPathComponent("model"), encoding: .utf8) == "previous")
|
||||
}
|
||||
|
||||
@Test("отказ публикации возвращает предыдущую модель на прежнее место")
|
||||
func failedPublicationRestoresCache() throws {
|
||||
let root = try sandbox()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let cache = root.appendingPathComponent("cache", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true)
|
||||
try Data("previous".utf8).write(to: cache.appendingPathComponent("model"))
|
||||
#expect(throws: (any Error).self) {
|
||||
try publishSpeechModelCache(from: root.appendingPathComponent("missing"), to: cache)
|
||||
}
|
||||
#expect(try String(contentsOf: cache.appendingPathComponent("model"), encoding: .utf8) == "previous")
|
||||
let entries = try FileManager.default.contentsOfDirectory(atPath: root.path)
|
||||
#expect(entries == ["cache"])
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test("после установки можно повторить неудачный прогрев без записи и изменения настроек")
|
||||
func failedPreparationCanRetry() async {
|
||||
let name = "iriz-model-preparation-" + UUID().uuidString
|
||||
let defaults = UserDefaults(suiteName: name)!
|
||||
defer { removeSuiteFile(named: name, defaults: defaults) }
|
||||
let settings = DictationSettings(defaults: defaults)
|
||||
settings.speechEngine = .multilingualV3
|
||||
let probe = ModelPreparationProbe()
|
||||
let controller = DictationController(settings: settings,
|
||||
insertionStats: InsertionStats(defaults: defaults),
|
||||
modelLoader: { try await probe.load($0) })
|
||||
#expect(controller.prepareAfterModelInstallation())
|
||||
#expect(controller.state == .warmingUp)
|
||||
#expect(!controller.prepareAfterModelInstallation())
|
||||
await controller.pendingWarmUp?.value
|
||||
guard case .unavailable = controller.state else {
|
||||
Issue.record("Первый отказ загрузчика должен оставаться видимым")
|
||||
return
|
||||
}
|
||||
#expect(controller.prepareAfterModelInstallation())
|
||||
#expect(controller.state == .warmingUp)
|
||||
await controller.pendingWarmUp?.value
|
||||
#expect(controller.state == .ready)
|
||||
#expect(!controller.isRecordingActive)
|
||||
#expect(settings.speechEngine == .multilingualV3)
|
||||
#expect(await probe.profiles == [.multilingualV3, .multilingualV3])
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test("сохранённый выбор установленного движка восстанавливает unavailable без перезапуска")
|
||||
func changingEngineRetriesPreparation() async {
|
||||
let name = "iriz-model-selection-" + UUID().uuidString
|
||||
let defaults = UserDefaults(suiteName: name)!
|
||||
defer { removeSuiteFile(named: name, defaults: defaults) }
|
||||
let settings = DictationSettings(defaults: defaults)
|
||||
settings.speechEngine = .whisperTurbo
|
||||
let probe = ModelPreparationProbe()
|
||||
let controller = DictationController(settings: settings,
|
||||
insertionStats: InsertionStats(defaults: defaults),
|
||||
modelLoader: { try await probe.load($0) })
|
||||
#expect(controller.prepareAfterModelInstallation())
|
||||
await controller.pendingWarmUp?.value
|
||||
guard case .unavailable = controller.state else {
|
||||
Issue.record("Первый отказ должен быть видимым")
|
||||
return
|
||||
}
|
||||
settings.speechEngine = .multilingualV3
|
||||
controller.applySettings()
|
||||
#expect(controller.state == .warmingUp)
|
||||
await controller.pendingWarmUp?.value
|
||||
#expect(controller.state == .ready)
|
||||
#expect(await probe.profiles == [.whisperTurbo, .multilingualV3])
|
||||
#expect(!controller.isRecordingActive)
|
||||
controller.applySettings()
|
||||
#expect(controller.pendingWarmUp == nil)
|
||||
}
|
||||
}
|
||||
|
||||
private actor ModelPreparationProbe {
|
||||
private(set) var profiles: [SpeechModelProfile] = []
|
||||
|
||||
func load(_ profile: SpeechModelProfile) throws {
|
||||
profiles.append(profile)
|
||||
if profiles.count == 1 { throw URLError(.cannotOpenFile) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user