// One session against a scripted core and fake engines: the order of the // calls, the second pass on the utterance's audio, the edits applied, the // person's touch reported, and the ending. @testable import CottonVoice import CottonKit import XCTest /// A live engine the test drives by hand. final class FakeLive: LiveVoiceEngine, @unchecked Sendable { var hear: VoiceHearingSink? var fed = 0 func prepare() async throws {} func start(_ hear: @escaping VoiceHearingSink) async throws { self.hear = hear } func feed(_ chunk: VoiceChunk) { fed += chunk.samples.count } func finish() async {} func cancel() {} } /// A second engine that always reads the same words. final class FakeSecond: SecondVoiceEngine, @unchecked Sendable { let text: String var read: [(Int, Int)] = [] init(_ text: String) { self.text = text } func prepare() async throws {} func transcribe(_ samples: [Float], offsetMs: Int) async throws -> VoiceHearing { read.append((samples.count, offsetMs)) return VoiceHearing(final: true, text: text, startMs: offsetMs, endMs: offsetMs + samples.count / 16) } } /// An input that plays one second of silence-ish samples. final class FakeInput: VoiceAudioInput, @unchecked Sendable { func start(_ sink: @escaping VoiceChunkSink, ended: @escaping @Sendable () -> Void) throws { for index in 0 ..< 10 { sink(VoiceChunk(samples: [Float](repeating: 0.01, count: 1600), startMs: index * 100)) } } func stop() {} } @MainActor final class VoiceSessionTests: XCTestCase { private func make(_ core: ScriptedCore, live: FakeLive, second: FakeSecond?) -> VoiceSession { let store = VoiceModelStore(root: FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)) let maker = VoiceEngineMaker( live: { _, _, _, _ in live }, second: { _, _, _ in guard let second else { throw VoiceFailure.modelMissing("x") } return second }, input: { _ in FakeInput() }, opensAudioSession: false) return VoiceSession(core: core, store: store, source: .recording(URL(fileURLWithPath: "/dev/null")), engines: maker) } private func settle() async { for _ in 0 ..< 20 { await Task.yield(); try? await Task.sleep(for: .milliseconds(5)) } } /// RULE: Partial, final and second pass each reach voice.heard in order, and the second pass's correction lands in the region. func testTwoPassesReachTheCoreAndTheCorrectionLands() async throws { let core = ScriptedCore([ CottonMethod.voicePlan: .ok(#"{"session":"s1","mode":"dictate","languages":["en"],"live":{"engine":"apple.speech"},"second":{"engine":"sherpa:parakeet"},"vocabulary":["Seetha"],"downloads":[],"lines":{}}"#), CottonMethod.voiceHeard: .ok(#"{"settled":"","tentative":"I met sita","edits":[]}"#), CottonMethod.voiceEnd: .ok(#"{"text":"I met Seetha."}"#), ]) let live = FakeLive() let second = FakeSecond("I met Seetha.") let session = make(core, live: live, second: second) await session.start(VoicePlanRequest(surface: "story.writer", table: "scene", mode: .dictate)) XCTAssertEqual(session.phase, .listening) XCTAssertEqual(live.fed, 16000) live.hear?(VoiceHearing(final: false, text: "I met sita", startMs: 0, endMs: 600)) await settle() XCTAssertEqual(session.region.display, "I met sita") await core.answer(CottonMethod.voiceHeard, .ok(#"{"settled":"I met sita.","tentative":"","edits":[]}"#)) live.hear?(VoiceHearing(final: true, text: "I met sita.", startMs: 0, endMs: 900)) await settle() await core.answer(CottonMethod.voiceHeard, .ok(#"{"settled":"I met Seetha.","tentative":"","edits":[{"from":6,"to":10,"text":"Seetha"}]}"#)) await settle() // The second pass read the utterance's audio, a little either side. XCTAssertEqual(second.read.first?.1, 0) let calls = await core.calls.filter { $0.method == CottonMethod.voiceHeard }.map(\.requestJSON) XCTAssertTrue(calls.last?.contains(#""pass":"second""#) ?? false, "\(calls)") let written = await session.stop() XCTAssertEqual(session.phase, .idle) XCTAssertFalse(written.isEmpty) let methods = await core.methodsCalled() XCTAssertEqual(methods.first, CottonMethod.voicePlan) XCTAssertEqual(methods.last, CottonMethod.voiceEnd) } /// RULE: The person typing inside the dictated words sends voice.touched with the range in the core's text. func testTypingInsideTheWordsIsTouched() async throws { let core = ScriptedCore([ CottonMethod.voicePlan: .ok(#"{"session":"s2","mode":"dictate","languages":["en"],"live":{"engine":"apple.speech"},"second":null}"#), CottonMethod.voiceHeard: .ok(#"{"settled":"Ravi walks in.","tentative":"","edits":[]}"#), CottonMethod.voiceTouched: .ok(#"{"settled":"Mira walks in.","tentative":"","edits":[]}"#), ]) let live = FakeLive() let session = make(core, live: live, second: nil) await session.start(VoicePlanRequest(surface: "note", mode: .dictate)) live.hear?(VoiceHearing(final: true, text: "Ravi walks in.", startMs: 0, endMs: 900)) await settle() session.typed("Mira walks in.") await settle() let touched = await core.calls.first { $0.method == CottonMethod.voiceTouched } XCTAssertNotNil(touched) XCTAssertTrue(touched?.requestJSON.contains(#""from":0"#) ?? false) XCTAssertTrue(touched?.requestJSON.contains(#""to":4"#) ?? false) XCTAssertEqual(session.region.display, "Mira walks in.") session.cancel() } /// RULE: A plan the core cannot answer is a named failure, never a crash. func testAnUnansweredPlanIsANamedFailure() async { let core = ScriptedCore() let session = make(core, live: FakeLive(), second: nil) await session.start(VoicePlanRequest(surface: "deck", mode: .dictate)) XCTAssertEqual(session.phase, .failed(.core("unknown_method"))) } /// RULE: A command answer is handed to the shell to open. func testACommandIsHandedOn() async { let core = ScriptedCore([ CottonMethod.voicePlan: .ok(#"{"session":"s3","mode":"command","languages":["en"],"live":{"engine":"apple.speech"}}"#), CottonMethod.voiceHeard: .ok(#"{"settled":"open ravi","tentative":"","edits":[],"command":{"kind":"open","query":"ravi","table":"person","id":"p1","title":"Ravi"}}"#), ]) let live = FakeLive() let session = make(core, live: live, second: nil) var opened: VoiceCommand? session.onCommand = { opened = $0 } await session.start(VoicePlanRequest(surface: "fan", mode: .command)) live.hear?(VoiceHearing(final: true, text: "open ravi", startMs: 0, endMs: 500)) await settle() XCTAssertEqual(opened, VoiceCommand(kind: "open", query: "ravi", table: "person", id: "p1", title: "Ravi")) session.cancel() } }