// 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.importCottonKitimportFoundationimport XCTest@testable importCottonUI// MARK: - The platform, faked@MainActorfinalclassFakeRecogniser: 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 = 0private(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)?privatevar sink: SpeechEventSink?privatevar 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.finalclassCollected<Value: Sendable>: @unchecked Sendable {privatelet lock = NSLock()privatevar 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.finalclassCounter: @unchecked Sendable {privatelet lock = NSLock()privatevar count = 0var value: Int { lock.withLock { count } }func bump() { lock.withLock { count += 1 } }}@MainActorfinalclassDictationModelTests: XCTestCase {privatevar recogniser = FakeRecogniser()overridefunc setUp() asyncthrows { 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.privatefunc 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.privatefunc 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. @discardableResultprivatefunc 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 }privatefunc settled(_ check: @escaping @MainActor () -> Bool) async {for _ in0..<200 {if check() { return }try? awaitTask.sleep(for: .milliseconds(5)) } }// MARK: - Endings nobody asked forfunc 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 _ in0..<DictationModel.maxRestarts {// Each session lives a minute — mortal, not dead on arrival. clock += 60 recogniser.emit(.ended) recogniser.emit(.started) } clock += 60 XCTAssertEqual(recogniser.sessions.count, DictationModel.maxRestarts + 1) recogniser.emit(.ended) XCTAssertEqual( recogniser.sessions.count, DictationModel.maxRestarts + 1,"the cap holds — nothing resurrects a forty-first time") XCTAssertEqual(unasked?.outcome, .dictationInterrupted) XCTAssertEqual(unasked?.text, "the long one") }/// RULE: A session that ends at once without a word never came up, and three in a row end the dictation (named interrupted once words were heard, so they are kept); a session that lived and heard nothing is a pause and counts for nothing (the simulator's every dictation ended 'interrupted' at 12 s).func testThreeSessionsDeadOnArrivalInARowEndTheDictationAndAPauseIsNotOne() async {var clock = Date(timeIntervalSince1970: 1_000)let model = clocked { clock }var unasked: DictationResult? model.onUnasked = { unasked = $0 }await listen(model) recogniser.speak("buy bread") clock += 8 recogniser.emit(.ended) recogniser.emit(.started) clock += 8 recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 3, "a session that lived and heard nothing is a pause, not a death") recogniser.emit(.started) recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 4) recogniser.emit(.started) recogniser.emit(.ended) recogniser.emit(.started) recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 5, "three dead on arrival in a row end it") XCTAssertEqual(model.phase, .idle) XCTAssertEqual(unasked?.outcome, .dictationInterrupted) XCTAssertEqual(unasked?.text, "buy bread") }func testADictationWhoseEverySessionDiesOnArrivalSaysItIsUnavailable() async {let clock = Date(timeIntervalSince1970: 1_000)let model = clocked { clock }var unasked: DictationResult? model.onUnasked = { unasked = $0 }await listen(model)for _ in0..<DictationModel.maxDeadOnArrival - 1 { recogniser.emit(.ended) recogniser.emit(.started) } recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, DictationModel.maxDeadOnArrival) XCTAssertEqual(model.phase, .idle) XCTAssertEqual(unasked?.outcome, .dictationUnavailable, "nothing ever came up: not an interruption") }/// No model for the language mid-dictation: nothing to restart into, so/// the dictation ends at once, named, with what it heard.func testAModelUnavailableMidDictationEndsItAtOnceKeepingTheWords() async {let model = self.model()var unasked: DictationResult? model.onUnasked = { unasked = $0 }await listen(model) recogniser.speak("buy bread") recogniser.emit(.failed(.unavailable)) recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 1, "nothing restarts into a model that is not there") XCTAssertEqual(model.phase, .idle) XCTAssertEqual(unasked?.outcome, .dictationUnavailable) XCTAssertEqual(unasked?.text, "buy bread") }// MARK: - The transcriptfunc testAnEmptySettleNeverErasesTheStreamedPartials() async {let model = self.model()await listen(model) recogniser.speak("half a sentence")// A session cut down mid-word settles its last stretch as "". recogniser.emit(.segment("")) XCTAssertEqual(model.liveText, "half a sentence") }func testAPartialReplacesTheSegmentRatherThanAppendingToIt() async {let model = self.model()await listen(model) recogniser.speak("call") recogniser.speak("call ramesh") XCTAssertEqual(model.liveText, "call ramesh", "an utterance restates itself in full") }// MARK: - A session cut into utterances/// **THE BUILD-146 DEFECT, in one test.** The recogniser closes an/// utterance at a pause and starts its next transcript from empty; a model/// that let the following partial REPLACE the live text lost everything/// spoken before that pause — the screen going blank every ten to fifty/// seconds, which is exactly what the owner saw.func testAClosedUtteranceIsKeptAndTheNextOneStartsFromEmpty() async {let model = self.model()await listen(model) recogniser.speak("one") recogniser.speak("one two") recogniser.pause("One two.") XCTAssertEqual(model.liveText, "One two.")// The pause is over and the recogniser is describing a NEW utterance. recogniser.speak("three") XCTAssertEqual(model.liveText, "One two. three") recogniser.speak("three four") XCTAssertEqual(model.liveText, "One two. three four") recogniser.pause("Three four.") recogniser.speak("five") XCTAssertEqual(model.liveText, "One two. Three four. five") }func testAStopSettlingOnlyTheLastStretchKeepsTheOnesBeforeIt() async {let model = self.model()await listen(model) recogniser.speak("one two") recogniser.pause("One two.") recogniser.speak("three") recogniser.whenStopped = { [recogniser = self.recogniser] in// A stop settles the stretch in progress: the tail alone. recogniser.emit(.segment("Three.")) recogniser.emit(.ended) }let result = await model.finish() XCTAssertEqual(result.outcome, .dictated) XCTAssertEqual(result.text, "One two. Three.") }func testASettleRestatingTheWholeSessionSaysItOnceNotTwice() async {let model = self.model()await listen(model) recogniser.speak("one two") recogniser.pause("One two.") recogniser.speak("three") recogniser.whenStopped = { [recogniser = self.recogniser] in// The other shape, which a path that segments but still restates// would send. Same words land, and none of them twice. recogniser.emit(.segment("One two. Three.")) recogniser.emit(.ended) }let result = await model.finish() XCTAssertEqual(result.outcome, .dictated) XCTAssertEqual(result.text, "One two. Three.") }/// A stop may settle its last stretch BLANK after earlier stretches were/// settled. Nothing may be lost to that.func testABlankLastSettleAfterAClosedUtteranceKeepsEverythingHeard() async {let model = self.model()await listen(model) recogniser.speak("one two") recogniser.pause("One two.") recogniser.speak("three") recogniser.whenStopped = { [recogniser = self.recogniser] in recogniser.emit(.segment("")) recogniser.emit(.ended) }let result = await model.finish() XCTAssertEqual(result.outcome, .dictated) XCTAssertEqual(result.text, "One two. three") }func testAnEmptyUtteranceEndErasesNothing() async {let model = self.model()await listen(model) recogniser.speak("half a sentence") recogniser.pause("") XCTAssertEqual(model.liveText, "half a sentence")// And the stretch it closed is committed, so the next one appends. recogniser.speak("and the rest") XCTAssertEqual(model.liveText, "half a sentence and the rest") }/// A short second utterance that opens with the word already committed is/// NEW, not the session restated — the case a bare prefix test would eat.func testAnUtteranceRepeatingTheOpeningWordIsStillItsOwn() async {let model = self.model()await listen(model) recogniser.speak("no") recogniser.pause("No.") recogniser.speak("no thanks") recogniser.pause("No thanks.") XCTAssertEqual(model.liveText, "No. No thanks.") }/// The two stitches meet: a session that closed an utterance and THEN died/// unasked keeps both halves across the resurrection.func testUtterancesSurviveAMortalSessionsResurrection() async {let model = self.model()await listen(model) recogniser.speak("one two") recogniser.pause("One two.") recogniser.speak("three") recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 2) XCTAssertEqual(model.liveText, "One two. three") recogniser.emit(.started) recogniser.speak("four") XCTAssertEqual(model.liveText, "One two. three four") }/// The words a finish hands back: every settled stretch's, with the/// model's confidence, then the live tail's, unscored.func testAFinishCarriesTheSettledWordsThenTheUnscoredTail() async {let model = self.model()await listen(model) recogniser.speak("one two") recogniser.pause("One two.", words: [HeardWord(text: "One", confidence: 0.9), HeardWord(text: "two.", confidence: 0.4)]) recogniser.speak("three") recogniser.whenStopped = { [recogniser = self.recogniser] in recogniser.emit(.segment("")) recogniser.emit(.ended) }let result = await model.finish() XCTAssertEqual( result.words, [HeardWord(text: "One", confidence: 0.9), HeardWord(text: "two.", confidence: 0.4),HeardWord(text: "three", confidence: nil), ]) }/// RULE: what a finish lands has every near-miss of a hinted name snapped to the name, text and words alike, and only what lands is snapped — the snap is the deterministic second chance after the contextual strings, applied once, where the words leave the engine.func testAFinishLandsTheSnappedName() async {let model = DictationModel( recogniser: recogniser, levels: recogniser, timings: DictationModel.Timings(stopGuard: .milliseconds(200), cancelGuard: .milliseconds(150), tick: .milliseconds(5)), dictionary: { word, _ in ["call", "tomorrow"].contains(word.lowercased()) })await listen(model, hints: DictationHints(groups: [DictationHints.Group(tag: "people", terms: ["Anvika Rathore"])])) recogniser.pause("Call Anvika Rathor tomorrow", words: [HeardWord(text: "Call", confidence: 0.9), HeardWord(text: "Anvika", confidence: 0.8),HeardWord(text: "Rathor", confidence: 0.3), HeardWord(text: "tomorrow", confidence: 0.9)]) recogniser.whenStopped = { [recogniser = self.recogniser] in recogniser.emit(.ended) }let result = await model.finish() XCTAssertEqual(result.text, "Call Anvika Rathore tomorrow") XCTAssertEqual(result.words[2], HeardWord(text: "Rathore", confidence: nil)) }func testFieldTextIsThePrefixFoldedWithWhatIsBeingHeard() async {let model = self.model()await listen(model, prefix: "meeting notes") recogniser.speak("call ramesh") XCTAssertEqual(model.fieldText, "meeting notes call ramesh") XCTAssertTrue(model.isListening) XCTAssertFalse(model.isFinishing) }func testAFinishWithNothingHeardIsEmptyRatherThanDictated() async {let model = self.model()await listen(model) recogniser.whenStopped = { [recogniser = self.recogniser] in recogniser.emit(.ended) }let result = await model.finish() XCTAssertEqual(result, DictationResult(outcome: .dictationEmpty, text: "")) }func testAFinishWhoseEndNeverArrivesStillKeepsWhatWasHeard() async {let model = self.model()await listen(model) recogniser.speak("keep these words")// The recogniser answers nothing at all — the hang guard is the only// thing between this person and a composer that never comes back.let result = await model.finish() XCTAssertEqual(result.outcome, .dictated) XCTAssertEqual(result.text, "keep these words") }func testCancelDiscardsTheDictationAndItsWords() async {let model = self.model()var unasked: DictationResult? model.onUnasked = { unasked = $0 }await listen(model) recogniser.speak("never mind") recogniser.whenCancelled = { [recogniser = self.recogniser] in recogniser.emit(.failed(.aborted)) recogniser.emit(.ended) } model.cancel() XCTAssertEqual(model.phase, .idle) XCTAssertEqual(model.liveText, "") XCTAssertNil(unasked, "a deliberate discard is not an ending nobody asked for") }func testACancelWhoseEndNeverArrivesStillGoesIdle() async {let model = self.model()await listen(model) model.cancel()await settled { model.phase == .idle } XCTAssertEqual(model.phase, .idle) }// MARK: - Starting, and the two refusals that come before a wordfunc testTheMicOnACallRefusesBeforeAWordIsHeard() async {let model = self.model(onCall: true)let refusal = await model.start(prefix: "", hints: DictationHints()) XCTAssertEqual(refusal, .dictationOnCall) XCTAssertTrue(recogniser.sessions.isEmpty, "the call keeps its own microphone") XCTAssertEqual(model.phase, .idle) }/// RULE: on the first tap the OS asks for the microphone BEFORE anything of the take draws — the listening line stays down while the question stands, granted or refused (walker, architect 16 Oct 2026).func testNothingListensWhileThePermissionIsAsked() async {for granted in [true, false] { recogniser.permission = grantedlet model = self.model()var listeningWhileAsked: Bool? recogniser.whileAsking = { listeningWhileAsked = model.isListening }await model.start(prefix: "", hints: DictationHints()) XCTAssertEqual(listeningWhileAsked, false, "granted \(granted): the take drew before the OS answered") XCTAssertEqual(model.isListening, granted) model.cancel() } }func testDeniedPermissionNamesItsEndingAndOpensNoSession() async { recogniser.permission = falselet model = self.model()let refusal = await model.start(prefix: "", hints: DictationHints()) XCTAssertEqual(refusal, .dictationDenied) XCTAssertTrue(recogniser.sessions.isEmpty) XCTAssertEqual(model.phase, .idle) }/// A failure during `starting` calls `settle`, which resolves a/// continuation nobody holds yet, and calls nothing else. It reaches/// NOBODY, on purpose — the screen names this state by watching the engine/// go idle without a word.func testARecogniserThatNeverComesUpGoesQUIETLYIdleAndTellsNobody() async {let model = self.model()var unasked: DictationResult? model.onUnasked = { unasked = $0 }await model.start(prefix: "", hints: DictationHints()) recogniser.emit(.failed(.other)) XCTAssertNil(unasked, "a recogniser that never came up speaks down no channel") XCTAssertEqual(model.phase, .idle, "and it does go idle, which is what the screen watches") XCTAssertEqual(model.liveText, "", "with nothing heard, which is the other half") }func testPermissionRefusedDuringASessionIsAlsoSilentAndNeverRetried() async {let model = self.model()var unasked: DictationResult? model.onUnasked = { unasked = $0 }await model.start(prefix: "", hints: DictationHints()) recogniser.emit(.failed(.notAllowed)) XCTAssertNil(unasked) XCTAssertEqual(model.phase, .idle) XCTAssertEqual( recogniser.sessions.count, 1, "a refusal is never retried") }// MARK: - The hintsfunc testTheHintsReachEverySessionInTheOrderTheyArrived() async {let hints = DictationHints( groups: [DictationHints.Group(tag: "people", terms: ["Ramesh"]),DictationHints.Group(tag: "places", terms: ["Tin Factory"]), ], language: "en")let model = self.model()await listen(model, hints: hints) XCTAssertEqual(recogniser.sessions.first, hints) XCTAssertEqual(recogniser.sessions.first?.terms, ["Ramesh", "Tin Factory"]) recogniser.speak("call ramesh") recogniser.emit(.ended) XCTAssertEqual(recogniser.sessions.count, 2) XCTAssertEqual(recogniser.sessions.last, hints, "a resurrected session listens for the same words") }/// RULE: Apple silently ignores contextual strings past its hundred, so the hints keep the first hundred across all groups in the core's order (earlier groups win) and drop blank terms and emptied groups.func testTheHintsAreCappedAtApplesHundredAcrossGroupsEarlierGroupsWin() {let hints = DictationHints(groups: [DictationHints.Group(tag: "people", terms: (1...60).map { "person \($0)" } + [""]),DictationHints.Group(tag: "empty", terms: ["", ""]),DictationHints.Group(tag: "places", terms: (1...60).map { "place \($0)" }),DictationHints.Group(tag: "late", terms: ["never heard"]), ]) XCTAssertEqual(hints.terms.count, DictationHints.maxTerms) XCTAssertEqual(hints.groups.map(\.tag), ["people", "places"]) XCTAssertEqual(hints.groups[0].terms.count, 60) XCTAssertEqual(hints.groups[1].terms.count, 40) XCTAssertEqual(hints.terms.first, "person 1") XCTAssertEqual(hints.terms.last, "place 40") XCTAssertEqual(DictationHints().terms, []) }/// The person's language with this device's region, and the device's own/// locale when no language is set.func testTheHintsLocaleIsThePersonsLanguageWithTheDevicesRegion() {let hindi = DictationHints(language: "hi").locale XCTAssertEqual(hindi.language.languageCode?.identifier, "hi") XCTAssertEqual(hindi.region, Locale.current.region) XCTAssertEqual(DictationHints().locale, Locale.current) XCTAssertEqual(DictationHints(language: "").locale, Locale.current) }// MARK: - The meter and the clockfunc testTheMeterOnlyReadsWhileASessionIsLive() async {let model = self.model() recogniser.meter(0.8) XCTAssertEqual(model.level, 0, "an idle model shows no level")await listen(model) recogniser.meter(0.8) XCTAssertEqual(model.level, 0.8, accuracy: 0.0001) }func testTheLevelFoldsClampToTheDotsZeroToOne() { XCTAssertEqual(DictationLevel.fold(raw: -2), 0, accuracy: 0.0001) XCTAssertEqual(DictationLevel.fold(raw: 10), 1, accuracy: 0.0001) XCTAssertEqual(DictationLevel.fold(raw: 4), 0.5, accuracy: 0.0001) XCTAssertEqual(DictationLevel.fold(raw: -99), 0, accuracy: 0.0001) XCTAssertEqual(DictationLevel.fold(raw: 99), 1, accuracy: 0.0001) XCTAssertEqual(DictationLevel.fold(decibels: -50), 0, accuracy: 0.0001) XCTAssertEqual(DictationLevel.fold(decibels: 0), 1, accuracy: 0.0001) XCTAssertEqual(DictationLevel.fold(decibels: -25), 0.5, accuracy: 0.0001) XCTAssertEqual(DictationLevel.fold(decibels: -200), 0, accuracy: 0.0001) }func testTheClockCountsFromTheTapAndResetsWhenTheDictationEnds() async {var clock = Date(timeIntervalSince1970: 1_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: 1_003)await settled { model.elapsedMillis >= 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 answersasynclet 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<Int>()let seen = Collected<Int>() relay.onValue { value in seen.append(value) }for value in0..<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<SpeechEvent>()let seen = Collected<SpeechEvent>() 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<String>()let seen = Collected<String>() relay.onValue { value in seen.append(value) }await withTaskGroup(of: Void.self) { group infor lane in ["a", "b", "c"] { group.addTask {for step in0..<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) }}