import AVFoundationimportSpeechimport XCTest@testable importCottonUI/// The dictation accuracy harness (`scripts/ui-tests-stub.sh --voice <out>`),/// not a check: it is skipped unless the runner points it at a rendered corpus./// It plays every utterance (synthetic, or the owner's own read of the script/// — see `scripts/voicegate/run.sh`) through THE app's dictation —/// `DictationModel.live(audio: .file(_))`, the one constructor every/// microphone uses — with no hints, with the corpus's hints, and with the/// hints plus the person's language model compiled from them (the app's own/// `VoiceModelCompiler`, compiled and loaded on this Mac), in two/// renderings (the corpus's mixed voices, and the Indian English voice alone),/// then probes the synthesizer: every name the corpus speaks, said alone by/// the voice that speaks it, heard plain and with that one name as the only/// hint. It writes what it heard, and what the engine was handed, for/// `scripts/voicegate/report.py` to score.////// It runs on the Mac because the iOS simulator cannot run the speech model:/// it has the language's assets but answers no audio format, and refuses every/// buffer as "Audio format is not supported" (14 Oct 2026, iOS 27.0).@MainActorfinalclassVoiceGateTests: XCTestCase {privatestructCorpus: Decodable {structUtterance: Decodable { let voice: String?; let text: String }let hints: [String: [String]]let utterances: [Utterance] }privatestructProbe: Decodable { let voice: String; let name: String; let file: String }func testTheCorpusThroughTheShippedDictation() asyncthrows {guardlet folder = ProcessInfo.processInfo.environment["COTTON_VOICEGATE_DIR"] else {throw XCTSkip("the accuracy harness runs only from scripts/ui-tests-stub.sh --voice") }guard #available(macOS 26.0, iOS 26.0, *) else { throw XCTSkip("dictation needs macOS 26") }let root = URL(fileURLWithPath: folder)let corpus = try JSONDecoder().decode(Corpus.self, from: Data(contentsOf: root.appendingPathComponent("corpus.json")))let probes = try JSONDecoder().decode([Probe].self, from: Data(contentsOf: root.appendingPathComponent("probes.json")))// The hints as the core hands them over: grouped by why each is there.let hinted = DictationHints( groups: ["manual", "people", "places", "projects", "screen"].map {DictationHints.Group(tag: $0, terms: corpus.hints[$0] ?? []) }, language: "en")let plain = DictationHints(language: "en")var lines: [String] = []SystemSpeechRecogniser.trace = { lines.append($0) }defer { SystemSpeechRecogniser.trace = nil }// The person's own language model, compiled on this Mac from the same// hints by the app's own compiler and loaded the app's way (compile,// then the second prepare) — what the "model" run adds to "hinted".var modelled = hintediflet locale = awaitVoiceModelKeeper.transcriberLocale(hinted.locale) {let own = VoiceCorpus(names: hinted.groups)let fingerprint = own.fingerprint(locale: locale.identifier)let files = VoiceModelFiles(locale: locale.identifier, fingerprint: fingerprint, folder: root.appendingPathComponent("model/\(fingerprint)"))let compiler = VoiceModelCompiler()let clock = ContinuousClock()let began = clock.nowtryawait compiler.compile(own, locale: locale, into: files)tryawait compiler.load(files, locale: locale) modelled.model = files lines = ["compiled \(VoiceModelCompiler.pronunciations(own.names.flatMap(\.terms), locale: locale).count) spellings in \(clock.now - began)"] }let compiledLine = linesvar runs: [String: [String]] = [:]var outcomes: [String: [String]] = [:]var trace: [String: [String]] = [:]// The second-voice rendering exists only for the synthetic corpus.for (set, prefix) in [("", "u"), ("rishi-", "r")]whereFileManager.default.fileExists(atPath: root.appendingPathComponent("\(prefix)01.wav").path) {let files = corpus.utterances.indices.map { root.appendingPathComponent(String(format: "\(prefix)%02d.wav", $0 + 1)) }for (name, hints) in [("plain", plain), ("hinted", hinted), ("model", modelled)] where name != "model" || modelled.model != nil {var heard: [String] = []var how: [String] = []for (n, file) in files.enumerated() { lines = []let result = tryawait hear(file, hints: hints) heard.append(result.text) how.append("\(result.outcome)")// Every session: the context is on the analyzer before the// start, and the start is before the first buffer.let started = lines.firstIndex(of: "started; audio follows")let held = lines.filter { $0.hasPrefix("context ") } XCTAssertNotNil(started, "\(set)\(name) u\(n + 1): never started")if name != "plain" { XCTAssertFalse(held.isEmpty, "\(set)\(name) u\(n + 1): the analyzer held no hints") XCTAssertTrue(lines.lastIndex { $0.hasPrefix("context ") }! < started!, "context after the start") }if name == "model" { XCTAssertTrue(lines.contains { $0.hasPrefix("language model ") && !$0.hasSuffix(" none") },"\(set)model u\(n + 1): the transcriber was not handed the model") }if n == 0 { trace[set + name] = (name == "model" ? compiledLine : []) + lines } } runs[set + name] = heard outcomes[set + name] = how } }var probed: [[String: String]] = []for probe in probes {let file = root.appendingPathComponent(probe.file)let alone = DictationHints(groups: [DictationHints.Group(tag: "people", terms: [probe.name])], language: "en")let bare = tryawait hear(file, hints: plain).textlet helped = tryawait hear(file, hints: alone).text probed.append(["voice": probe.voice, "name": probe.name, "plain": bare, "hinted": helped]) }let answer: [String: Any] = ["engine": "DictationTranscriber \(plain.locale.identifier) (Mac)","runs": runs, "outcomes": outcomes, "trace": trace, "probes": probed, ]let data = try JSONSerialization.data(withJSONObject: answer, options: [.prettyPrinted, .sortedKeys])try data.write(to: root.appendingPathComponent("heard.json")) }/// One utterance: tap, speak (the recording plays in at its own pace), a/// breath of silence, tap ✓.privatefunc hear(_ file: URL, hints: DictationHints) asyncthrows -> DictationResult {let dictation = DictationModel.live(audio: .file(file))iflet refusal = await dictation.start(prefix: "", hints: hints) { XCTFail("dictation refused: \(refusal)")returnDictationResult(outcome: refusal, text: "") }// The model's locale and assets are fetched on first use.var waited = 0while dictation.phase == .starting {tryawaitTask.sleep(for: .milliseconds(50)) waited += 1guard waited < 2400else { throw XCTSkip("dictation never came up in 2 minutes") } }guard dictation.phase == .listening else { XCTFail("dictation never came up")returnDictationResult(outcome: .dictationUnavailable, text: "") }let audio = try AVAudioFile(forReading: file)tryawaitTask.sleep(for: .seconds(Double(audio.length) / audio.processingFormat.sampleRate + 0.8))returnawait dictation.finish() }}