// The dictation half of the capture composer's cases (7 of its 16), case for // case — plus the cases the previous tests could not reach, which are named // where they appear. // // The whole engine runs here with no microphone, no permission prompt and no // simulator audio: `FakeRecogniser` IS the platform, and it is driven by hand // exactly as the phone's test drove `__emitSpeechEvent`. // // ONE STRENGTHENING OVER THE TYPESCRIPT: the restart cap is exercised. The hook // declares `MAX_RESTARTS = 40` and nothing held it, so a session that died on a // loop would have resurrected for ever if the constant were ever dropped. // // The swallow is NOT a strengthening and is pinned as the hook behaves. A // recogniser that fails during `starting` settles a continuation nobody holds // and tells nobody, which reads like a bug and is instead the thing // the screen's wordless-death timer is watching for. Two answers racing for one // screen is the defect; one silent engine plus one screen-side beat is the // design. import CottonKit import Foundation import XCTest @testable import CottonUI // MARK: - The platform, faked @MainActor final class FakeRecogniser: SpeechRecognizing, AudioLevelSource { /// Whether the gate lets a session through. var permission = true /// What ``access()`` answers when it does not. The default is the commonest /// real refusal — the microphone, declined — and a test that wants the /// other endings sets it. var refusal: CapabilityGateResult = .blocked(.microphone, .denied) /// Every session opened, with the hints it was opened with. private(set) var sessions: [DictationHints] = [] /// Every warm-up asked for, with its hints. private(set) var preparations: [DictationHints] = [] private(set) var stops = 0 private(set) var cancels = 0 /// Answered SYNCHRONOUSLY inside `stop()` / `cancel()`, which is how a test /// stays deterministic: the model resumes its continuation before it /// returns, so there is no window for a race to hide in. var whenStopped: (@MainActor () -> Void)? var whenCancelled: (@MainActor () -> Void)? private var sink: SpeechEventSink? private var levelSink: AudioLevelSink? func onEvent(_ sink: @escaping SpeechEventSink) { self.sink = sink } /// Runs while the OS would be asking, before it answers. var whileAsking: (() -> Void)? func access() async -> CapabilityGateResult { whileAsking?() return permission ? .ready : refusal } func prepare(_ hints: DictationHints) { preparations.append(hints) } var whenStarted: (@MainActor () -> Void)? func start(_ hints: DictationHints) { sessions.append(hints) whenStarted?() } func stop() { stops += 1 whenStopped?() } func cancel() { cancels += 1 whenCancelled?() } func onLevel(_ sink: @escaping AudioLevelSink) { levelSink = sink } // ── The hand crank ──────────────────────────────────────────────────── func emit(_ event: SpeechEvent) { sink?(event) } func meter(_ value: Double) { levelSink?(value) } /// A session that came up and heard one partial. func speak(_ text: String) { emit(.partial(text)) } /// A pause between sentences: the recogniser closes the utterance it was /// hearing and carries on. Everything it streams after this describes the /// NEXT one, from empty. func pause(_ text: String, words: [HeardWord] = []) { emit(.segment(text, words: words)) } } // MARK: - Two counters the ordered hand-over needs /// What a relay delivered, in the order it delivered it. final class Collected: @unchecked Sendable { private let lock = NSLock() private var seen: [Value] = [] var values: [Value] { lock.withLock { seen } } func append(_ value: Value) { lock.withLock { seen.append(value) } } } /// How many times a give-back actually ran. final class Counter: @unchecked Sendable { private let lock = NSLock() private var count = 0 var value: Int { lock.withLock { count } } func bump() { lock.withLock { count += 1 } } } @MainActor final class DictationModelTests: XCTestCase { private var recogniser = FakeRecogniser() override func setUp() async throws { recogniser = FakeRecogniser() } /// Short guards and a short tick, so a test that proves a timer fires does /// not wait two and a half real seconds for it. private func model(onCall: Bool = false) -> DictationModel { DictationModel( recogniser: recogniser, levels: recogniser, isOnCall: { onCall }, timings: DictationModel.Timings( stopGuard: .milliseconds(200), cancelGuard: .milliseconds(150), tick: .milliseconds(5) ) ) } /// The same model on a clock the test moves. private func clocked(_ now: @escaping @MainActor () -> Date) -> DictationModel { DictationModel( recogniser: recogniser, levels: recogniser, now: now, timings: DictationModel.Timings( stopGuard: .milliseconds(200), cancelGuard: .milliseconds(150), tick: .milliseconds(5)) ) } /// Start a dictation and bring the session up. @discardableResult private func listen( _ model: DictationModel, prefix: String = "", hints: DictationHints = DictationHints() ) async -> DictationOutcome? { let refusal = await model.start(prefix: prefix, hints: hints) if refusal == nil { recogniser.emit(.started) } return refusal } private func settled(_ check: @escaping @MainActor () -> Bool) async { for _ in 0..<200 { if check() { return } try? await Task.sleep(for: .milliseconds(5)) } } // MARK: - Endings nobody asked for func testASessionThatDiesUnaskedIsResurrectedInvisiblyKeepingItsWords() async { let model = self.model() await listen(model) recogniser.speak("call ramesh") XCTAssertEqual(recogniser.sessions.count, 1) // The recogniser ended the task on its own: no failure, just an end. recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 2) XCTAssertEqual(model.phase, .listening) XCTAssertEqual(model.liveText, "call ramesh") recogniser.emit(.started) recogniser.speak("about the cold chain") XCTAssertEqual(model.liveText, "call ramesh about the cold chain") } func testAnInterruptionEndsTheDictationWithItsWordsNoRestart() async { let model = self.model() var unasked: DictationResult? model.onUnasked = { unasked = $0 } await listen(model) recogniser.speak("pay the rent by friday") // What the platform reports when the audio session is taken: the named // failure, then the forced end. recogniser.emit(.failed(.interrupted)) recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 1, "an interruption never restarts") XCTAssertEqual(model.phase, .idle) XCTAssertEqual(unasked?.outcome, .dictationInterrupted) XCTAssertEqual(unasked?.text, "pay the rent by friday") } func testAResurrectionThatCannotStartIsAnInterruptionTooTheWordsSurvive() async { let model = self.model() var unasked: DictationResult? model.onUnasked = { unasked = $0 } await listen(model) recogniser.speak("order the seeds") recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 2) // The microphone is somebody else's now: the session just resurrected // fails before it ever reports `started`. recogniser.emit(.failed(.other)) recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 2, "nothing restarts into a mic we cannot have") XCTAssertEqual(model.phase, .idle) XCTAssertEqual(unasked?.outcome, .dictationInterrupted) XCTAssertEqual(unasked?.text, "order the seeds") } func testAnInterruptionWithNothingHeardStillNamesItself() async { let model = self.model() var unasked: DictationResult? model.onUnasked = { unasked = $0 } await listen(model) recogniser.emit(.failed(.interrupted)) recogniser.emit(.ended) XCTAssertEqual(unasked?.outcome, .dictationInterrupted) XCTAssertEqual(unasked?.text, "") } func testAFinishTheUserAskedForResolvesThroughFinishNotTheUnaskedChannel() async { let model = self.model() var unasked: DictationResult? model.onUnasked = { unasked = $0 } await listen(model) recogniser.speak("buy cotton seeds") recogniser.whenStopped = { [recogniser = self.recogniser] in recogniser.emit(.segment("buy cotton seeds")) recogniser.emit(.ended) } let result = await model.finish() XCTAssertEqual(result.outcome, .dictated) XCTAssertEqual(result.text, "buy cotton seeds") XCTAssertNil(unasked, "a tapped finish never travels the unasked channel") XCTAssertEqual(model.phase, .idle) } /// NOT in the TypeScript: the cap it declares was never exercised. func testTheRestartCapEndsTheDictationRatherThanResurrectingForEver() async { var clock = Date(timeIntervalSince1970: 1_000) let model = clocked { clock } var unasked: DictationResult? model.onUnasked = { unasked = $0 } await listen(model) recogniser.speak("the long one") for _ in 0..= 3_000 } XCTAssertEqual(model.clock, "0:03") recogniser.whenStopped = { [recogniser = self.recogniser] in recogniser.emit(.ended) } _ = await model.finish() XCTAssertEqual(model.elapsedMillis, 0) XCTAssertEqual(model.clock, "0:00") } // MARK: - Giving the microphone back /// The arm the port was missing. Any dismissal other than a tap — a /// programmatic route change, a popped host, the app backgrounded — used to /// leave the session live: `setActive(true)` standing, a tap installed, and /// the recogniser holding the microphone after the screen that owned it was /// gone. The previous hook had that arm; this is it. func testReleaseDiscardsALiveSessionAndSaysNothingToAnybody() async { let model = self.model() var unasked: DictationResult? model.onUnasked = { unasked = $0 } await listen(model) recogniser.speak("half a thought") model.release() XCTAssertEqual(recogniser.cancels, 1, "the recogniser is asked to give the mic back") XCTAssertEqual(model.phase, .idle) XCTAssertEqual(model.liveText, "") XCTAssertNil(unasked, "nobody is on the other end of a screen that has gone") } func testReleaseIsANoOpOnAnIdleModelSoAScreenMayCallItTwice() async { let model = self.model() model.release() model.release() XCTAssertEqual(recogniser.cancels, 0) XCTAssertEqual(model.phase, .idle) } /// A `CheckedContinuation` that is never resumed hangs its awaiting task for /// ever, which the hook's abandoned promise did not. A finish in flight is /// answered as the discard the release is. func testReleaseAnswersAFinishThatWasStillInFlight() async { let model = self.model() await listen(model) recogniser.speak("mid finish") recogniser.whenStopped = {} // the recogniser never answers async let finishing: DictationResult = model.finish() await settled { model.isFinishing } model.release() let result = await finishing XCTAssertEqual(result, DictationResult(outcome: .dictationCancelled, text: "")) XCTAssertEqual(model.phase, .idle) } /// The hang guard's own leak. `stop()` takes the tap down but the audio /// session is deactivated in the recogniser's `finished()`, which runs off a /// callback that — in exactly the case this guard exists for — never /// arrives. So the guard asks for the discard that does run it, and still /// keeps the words. func testAFinishWhoseEndNeverArrivesAlsoGivesTheMicrophoneBack() async { let model = self.model() await listen(model) recogniser.speak("keep these words") let result = await model.finish() XCTAssertEqual(result.outcome, .dictated) XCTAssertEqual(result.text, "keep these words") XCTAssertEqual(recogniser.cancels, 1, "nothing else would have deactivated the session") } func testACancelWhoseEndNeverArrivesGivesTheMicrophoneBackToo() async { let model = self.model() await listen(model) model.cancel() await settled { model.phase == .idle } XCTAssertGreaterThanOrEqual( recogniser.cancels, 2, "the tap asked once; the guard asked again when nothing came") } // MARK: - The clock kept across its own reset /// `settle` zeroes `elapsedMillis` exactly as the hook's `setElapsedMs(0)` /// does, and the hook's consumers still read the real number because React /// handed them the pre-settle render's value. Here it is kept explicitly, so /// an interruption's duration is the length it actually ran. func testTheClockAtTheSettleSurvivesTheResetThatFollowsIt() async { var clock = Date(timeIntervalSince1970: 2_000) let model = DictationModel( recogniser: recogniser, levels: recogniser, now: { clock }, timings: DictationModel.Timings( stopGuard: .milliseconds(200), cancelGuard: .milliseconds(150), tick: .milliseconds(5)) ) await listen(model) clock = Date(timeIntervalSince1970: 2_007) await settled { model.elapsedMillis >= 7_000 } recogniser.emit(.failed(.interrupted)) recogniser.emit(.ended) XCTAssertEqual(model.elapsedMillis, 0, "the live clock resets, as the hook's does") XCTAssertGreaterThanOrEqual( model.settledMillis, 7_000, "and the number it stood at is still readable") } // MARK: - The ordered hand-over /// `SystemSpeechRecogniser` used to spawn a fresh `Task { @MainActor … }` /// per audio buffer (~43 a second) and per recognition callback. /// Unstructured tasks enqueued on an actor are NOT order-guaranteed, and a /// `segment` that overtook a trailing `partial` would defeat the "an empty /// settle must never erase the partials" rule with the words as the price. /// One `AsyncStream` drained by one task is what replaced them. func testTheRelayDeliversInTheOrderThingsWereSent() async { let relay = MainActorRelay() let seen = Collected() relay.onValue { value in seen.append(value) } for value in 0..<500 { relay.send(value) } await settled { seen.values.count == 500 } XCTAssertEqual(seen.values, Array(0..<500)) relay.close() } /// The same claim in the words it exists for: a `segment` sent after two /// `partial`s is APPLIED after them, so the fold that guards an empty /// settle sees the segment the partials left. func testASettleSentAfterThePartialsIsAppliedAfterThem() async { let relay = MainActorRelay() let seen = Collected() relay.onValue { event in seen.append(event) } relay.send(.partial("half a")) relay.send(.partial("half a sentence")) relay.send(.segment("")) await settled { seen.values.count == 3 } XCTAssertEqual(seen.values, [.partial("half a"), .partial("half a sentence"), .segment("")]) relay.close() } /// Sent from several threads at once: what a caller hands over on one thread /// still arrives in the order that thread handed it over. func testTheRelayKeepsEachSendersOwnOrderAcrossThreads() async { let relay = MainActorRelay() let seen = Collected() relay.onValue { value in seen.append(value) } await withTaskGroup(of: Void.self) { group in for lane in ["a", "b", "c"] { group.addTask { for step in 0..<50 { relay.send("\(lane)\(step)") } } } } await settled { seen.values.count == 150 } for lane in ["a", "b", "c"] { XCTAssertEqual( seen.values.filter { $0.hasPrefix(lane) }, (0..<50).map { "\(lane)\($0)" }, "lane \(lane) arrived out of order") } relay.close() } /// The meter's throttle: the tap fires ~43 times a second and the dot cannot /// read faster than the display, so all but one reading per interval is /// dropped on the audio thread, where dropping is free. func testTheMeterThrottleAdmitsOneReadingPerInterval() { // The instants are counted from ZERO on purpose. `100 + 0.05` is not // 100.05 in binary, so `(100 + interval) - 100` is 0.049999999999997 // and a boundary written at an arbitrary offset asserts the float, not // the rule. From zero the arithmetic is exact, and the rule is what is // read. (Nothing rides on the boundary itself: a meter reading rejected // by a hundredth of a millisecond arrives on the next buffer.) let throttle = MeterThrottle() XCTAssertTrue(throttle.admits(0), "the first reading always lands") XCTAssertFalse(throttle.admits(MeterThrottle.interval / 2)) XCTAssertTrue(throttle.admits(MeterThrottle.interval), "the interval is over, exactly") XCTAssertFalse(throttle.admits(MeterThrottle.interval), "and the clock moved on the way past") XCTAssertTrue(throttle.admits(MeterThrottle.interval * 4), "a long gap admits one, not four") throttle.reset() XCTAssertTrue(throttle.admits(0), "a new session reads at once") } /// The microphone is given back ONCE, however many times the give-back is /// asked for — `deinit` and a teardown can both reach it. func testTheAudioSessionHoldGivesTheMicrophoneBackExactlyOnce() { let count = Counter() let hold = AudioSessionHold { count.bump() } hold.release() hold.release() XCTAssertEqual(count.value, 1) } // MARK: - The prefix /// The composer wrote its prefix BEFORE it called `start`, so the busy /// refusal inside `start` could not leave the previous session's prefix /// standing. Here the refusal returns from the same call, so the order has /// to be written down rather than inherited. func testABusyRefusalStillTakesTheNewPrefixRatherThanKeepingTheOldOne() async { let model = self.model(onCall: true) _ = await model.start(prefix: "first field", hints: DictationHints()) XCTAssertEqual(model.prefix, "first field") _ = await model.start(prefix: "second field", hints: DictationHints()) XCTAssertEqual( model.prefix, "second field", "a refusal never leaves the previous session's prefix standing") } // MARK: - Verbatim /// **The recogniser's words ARE the field's words.** Fillers, no capital, /// no punctuation, a spoken number and a spoken mark — every one of them /// something the retired polish pass changed on the way in. Nothing edits /// them now, and the engine asks nobody to. func testAFinishedDictationLandsWhatTheRecogniserSaidByteForByte() async { let spoken = "um so i think we should uh call ramesh about the twenty five thousand full stop" let model = self.model() await listen(model) recogniser.whenStopped = { [recogniser = self.recogniser] in recogniser.emit(.segment(spoken)) recogniser.emit(.ended) } let result = await model.finish() XCTAssertEqual(result.text, spoken) XCTAssertEqual(result.outcome, .dictated) } }