import AVFoundation import XCTest @testable import CottonUI /// The tap→first audio buffer figure, cold and warm, on this Mac's own /// on-device model through the one recogniser that ships (a recording plays in /// where the microphone would). A measurement, not a guard: it runs only when /// `COTTON_LISTEN_PROBE` is set, because a machine with no dictation model has /// nothing to measure. @MainActor final class ListenLatencyProbe: XCTestCase { func testTapToFirstAudioBufferColdAndWarm() async throws { guard ProcessInfo.processInfo.environment["COTTON_LISTEN_PROBE"] != nil else { throw XCTSkip("set COTTON_LISTEN_PROBE to measure") } let file = FileManager.default.temporaryDirectory.appendingPathComponent("listen-probe.caf") let format = AVAudioFormat(standardFormatWithSampleRate: 16_000, channels: 1)! let out = try AVAudioFile(forWriting: file, settings: format.settings) let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 16_000)! buffer.frameLength = 16_000 try out.write(from: buffer) let hints = DictationHints(language: "en") let cold = DictationModel.live(audio: .file(file)) let coldMs = try await firstBuffer(cold, hints: hints) cold.release() let warm = DictationModel.live(audio: .file(file)) warm.prepare(hints: hints) try await Task.sleep(for: .seconds(8)) let warmMs = try await firstBuffer(warm, hints: hints) warm.release() // A second tap on the same recogniser, warmed again after the first. try await Task.sleep(for: .seconds(8)) let againMs = try await firstBuffer(warm, hints: hints) warm.release() print("listen-probe: tap→first audio buffer cold \(coldMs) ms, warm \(warmMs) ms, second tap \(againMs) ms") } private func firstBuffer(_ model: DictationModel, hints: DictationHints) async throws -> Int { let tapped = Date() if let refusal = await model.start(prefix: "", hints: hints) { throw XCTSkip("refused: \(refusal)") } while model.waveform.isEmpty { try await Task.sleep(for: .milliseconds(2)) guard Date().timeIntervalSince(tapped) < 120 else { throw XCTSkip("no model on this Mac") } } return Int(Date().timeIntervalSince(tapped) * 1000) } }