Cotton code
913 lines · 42.2 KB · SwiftRaw
// The dictation engine: one tap, words streaming into the field, and an ending// that always has a name.//// **THE MIC IS A TAP, NOT A HOLD.** The 2026-08-15 amendment retired the// hold-to-record voice note: you tap, you speak, the transcript arrives as you// talk, you tap again. Nothing in this file — and nothing that drives it — may// grow a long-press.//// **WHAT THE RECOGNISER SAID IS WHAT LANDS.** Nothing between// `DictationTranscriber`'s final transcript and the field edits the words — no// punctuation pass, no capitalisation, no filler-stripping, no model rewrite.// The polish pass that used to sit here (a Haiku call behind `capture.route`// that repaired punctuation, proper nouns and spoken punctuation marks) is// GONE, code and route arm both, until post-processing is designed rather than// inherited. The only text rule left is assembly — `VoiceTake`'s fold and// splice, which decide where a span JOINS its neighbours and never what it// says. Guards: the `…ByteForByte` case in `DictationModelTests`, and the// verbatim case in each of `BodyDictationTests` and `ComposerTests`.//// **Every ending is NAMED and carries its sentence** (`VoiceTake.swift`). Seven// outcomes, and the channels they arrive on are different for a reason:// `finish()` and `cancel()` are endings the person ASKED for, so their result// goes back to the caller that awaited them; an interruption and a session that// could not be resurrected are endings NOBODY asked for, so they go to// ``onUnasked``, because on that path there is no caller waiting to be told.//// **A recogniser that never comes up at all is the third case, and it is// SILENT here.** A failure during `starting` calls `settle()`, which resolves// a continuation nobody holds yet and calls nothing else; the screen learns of// it by watching the engine go idle without a word (its own wordless-death// timer). Speaking it down ``onUnasked`` instead would put two// sources of truth in a race for one screen, and the loser writes the wrong// one.//// FIVE DELIBERATE DIFFERENCES FROM THE TYPESCRIPT, written down because a silent// one is a defect somebody re-introduces:////   • **``release()`` resumes a continuation the hook simply abandoned.** The//     hook's unmount cleanup aborts the//     recogniser and clears the guard, leaving an in-flight `stop()` promise//     unresolved — harmless in JavaScript, where nothing is waiting once the//     component is gone. A `CheckedContinuation` that is never resumed hangs//     its awaiting task for ever, so a finish in flight is answered as the//     discard this is.//   • **The recogniser is a protocol, not a native module.** `SpeechRecognizing`//     and `AudioLevelSource` are the whole platform surface, so this model is//     unit-tested with no microphone, no permission prompt and no simulator —//     the same reason `CottonCalling` exists (design P17).//     `SystemSpeechRecogniser.swift` is the real one.//   • **The events are an enum, not five string-keyed subscriptions.** The//     recognizer's `result` event carried an `isFinal` flag and a possibly//     absent transcript; here `partial`/`segment`/`final` are separate cases and//     the transcript is not optional, so the "an empty final must never erase//     the partials" rule is a line of code rather than a `??` chain — and the//     third state that flag cannot express, an utterance closing mid-session,//     has a name instead of going unnoticed.//   • **The phase is one property, not a state and a ref.** React needed both//     (`phase` for the render, `phaseRef` for the event handlers, kept in step//     by hand); on the main actor there is one value and the handlers read it.//   • **The two hang guards and the timer take their durations from//     ``Timings``.** They are 2.5 s / 1.5 s / 1 s exactly as the hook hard-codes//     them, but a test that had to wait two and a half real seconds to prove the//     guard fires is a test nobody runs.import CottonKitimport Foundationimport os// MARK: - The platform seams/// What one recogniser session says, in the order it says it.////// A session's life is `started` → many `partial`, cut into stretches by/// `segment` → `ended`; a failure interrupts it anywhere and `ended` still/// follows. A session that was asked to stop settles its last stretch as a/// `segment` before its `ended`.public enum SpeechEvent: Sendable, Equatable {    /// The session is live and the microphone is ours.    case started    /// The transcript of the utterance IN PROGRESS — cumulative within that    /// utterance, so it REPLACES the live segment rather than appending to it.    case partial(String)    /// **A stretch was SETTLED**, and the session runs on.    ///    /// The transcriber finalises a long dictation stretch by stretch; this is    /// the text of the stretch it just settled, with the model's confidence in    /// each word, and every `partial` after it describes the NEXT stretch from    /// empty. Nothing ever restates a settled stretch, so this is the event that    /// COMMITS — without it the screen loses everything heard before each    /// pause, which is the defect this case was added for (build 146,    /// 2026-09-12).    ///    /// May be empty when a stretch was cut down mid-word — and then the    /// partials streamed since the last one ARE the words (the fold below).    case segment(String, words: [HeardWord] = [])    case failed(SpeechFailure)    /// The session is over, however it ended. Always last.    case ended}/// Why a session failed — the four kinds the lifecycle actually branches on.////// The platform reports dozens; collapsing them here rather than at the call/// site keeps the branching total, and a recogniser implementation that meets a/// code it does not recognise answers ``other``, which is the "the end event/// follows and the restart ladder handles it" path.public enum SpeechFailure: String, Sendable, Equatable, CaseIterable {    /// Microphone or speech-recognition permission is refused.    case notAllowed    /// The audio session belongs to somebody else now — a call, Siri, an alarm.    case interrupted    /// We asked for this: the session was cancelled from ``DictationModel/cancel()``.    case aborted    /// The device has no on-device model for the person's language, and    /// nothing is sent anywhere instead.    case unavailable    /// Anything else: no speech, an audio-capture hiccup, a route change.    case other}/// Where a recogniser's events go. **Main-actor by declaration**, so a fake in a/// test drives the model synchronously and the real one hops threads once, at/// the edge, rather than every reader guessing.public typealias SpeechEventSink = @MainActor @Sendable (SpeechEvent) -> Void/// Everything the platform's recogniser does, behind a protocol.@MainActorpublic protocol SpeechRecognizing: AnyObject, Sendable {    /// Where events go. ONE sink: a second call replaces the first, as the    /// core's own event stream does.    func onEvent(_ sink: @escaping SpeechEventSink)    /// Ask for everything a dictation needs — the microphone and speech    /// recognition, in that order — and answer where it stands.    ///    /// **Never a `Bool`, and it is called BEFORE anything platform is built.**    /// A bare yes/no cannot say whether Settings would help, and the whole    /// point of the gate is that no audio engine, recogniser or capture session    /// exists until this has answered `.ready`    /// (`CottonKit/Capabilities/DeviceCapability.swift`). Anything else is an    /// ending the model names and the caller speaks — never an error.    func access() async -> CapabilityGateResult    /// Make the next ``start(_:)`` warm: the model loaded and prepared for    /// these hints, so the tap only opens the microphone. Never opens the    /// microphone, never asks the OS for anything, and is safe to call again    /// (a slot already warm for the same hints is kept).    func prepare(_ hints: DictationHints)    /// Begin a session, listening in the hints' language for the hints' words.    func start(_ hints: DictationHints)    /// Finish: the session settles its transcript and ends.    func stop()    /// Discard: the session ends with ``SpeechFailure/aborted`` and no final.    func cancel()}/// Where the meter's readings go — 0…1, already folded.public typealias AudioLevelSink = @MainActor @Sendable (Double) -> Void/// The meter behind the listening line's waveform.////// Its own protocol rather than a sixth `SpeechEvent` case, because the two/// answer different questions — "what did they say" and "is anything reaching/// the microphone at all" — and a screen that shows a level while a recogniser/// is deaf is telling the truth about a real failure. `SystemSpeechRecogniser`/// happens to satisfy both, since only the thing holding the audio tap can/// measure it.@MainActorpublic protocol AudioLevelSource: AnyObject, Sendable {    func onLevel(_ sink: @escaping AudioLevelSink)}// MARK: - Pure rules/// What a dictation listens for: the words it is told to expect, grouped by/// why each is there, and the person's language.////// The groups go in as `AnalysisContext.contextualStrings`, one tag per group/// (people, places, projects, this screen, words a person added), so the model/// is told what KIND of word each is, not only the word.public struct DictationHints: Sendable, Equatable {    public struct Group: Sendable, Equatable {        public let tag: String        public let terms: [String]        public init(tag: String, terms: [String]) {            self.tag = tag            self.terms = terms        }    }    /// Apple's ceiling for contextual strings. Past it the tail is not an    /// error — it is SILENTLY IGNORED, which is worse, which is why both sides    /// of the boundary clamp (the crate caps its ranked list too).    public static let maxTerms = 100    /// In the order the core ranked them. **The ORDER is not ours** — the core    /// answers it already ranked (screen and links, visible list, manual,    /// database and global names, with use and recency inside each band), and    /// re-sorting here would be a second implementation of that ranking; it    /// decides which hundred terms the recogniser is listening for.    public let groups: [Group]    /// The person's language (BCP-47 — `en`, `hi`), from their setting; nil is    /// the device's own.    public let language: String?    /// The person's own language model, compiled on this device    /// (`VoiceModel.swift`), when this process has one loaded for the locale.    public var model: VoiceModelFiles?    public init(groups: [Group] = [], language: String? = nil, model: VoiceModelFiles? = nil) {        var left = Self.maxTerms        self.groups = groups.compactMap { group in            let terms = Array(group.terms.filter { !$0.isEmpty }.prefix(left))            left -= terms.count            return terms.isEmpty ? nil : Group(tag: group.tag, terms: terms)        }        self.language = language        self.model = model    }    /// Every hinted term, in rank order.    public var terms: [String] { groups.flatMap(\.terms) }    /// The locale to listen in: the person's language with this device's    /// region, so an English speaker in India is heard by the Indian English    /// model. Never a literal: with no language set it is the device's own.    public var locale: Locale {        guard let language, !language.isEmpty else { return Locale.current }        let wanted = Locale.Language(identifier: language)        guard let code = wanted.languageCode else { return Locale.current }        return Locale(languageCode: code, script: wanted.script, languageRegion: Locale.current.region)    }}/// One word the model settled, and how sure it was (0…1; nil when it did not/// say — a word still streaming, or a word the snap replaced).public struct HeardWord: Sendable, Equatable {    public let text: String    public let confidence: Double?    public init(text: String, confidence: Double?) {        self.text = text        self.confidence = confidence    }}/// The meter's fold — raw reading to the 0…1 the dot breathes on.public enum DictationLevel {    /// The phone's own fold: `expo-speech-recognition` reported roughly -2…10.    public static func fold(raw: Double) -> Double {        min(1, max(0, (raw + 2) / 12))    }    /// AVFoundation has no such scale — an audio tap hands over samples — so    /// the system meter converts RMS to dBFS and lands on the same 0…1 here.    /// The floor is -50 dB: below that a quiet office reads as silence, which    /// is what a person watching the dot expects it to mean.    public static func fold(decibels: Double) -> Double {        min(1, max(0, (decibels + 50) / 50))    }}// MARK: - The lifecycle/// Where a dictation stands. `starting` and `listening` are both "live" to a/// person; they are separate because the failure ladder branches on which.public enum DictationPhase: String, Sendable, Equatable {    case idle    case starting    case listening    case finishing}/// What a finished dictation hands back: everything heard, already folded, and/// the settled words with the model's confidence in each — what a voice/// conversation reads to decide whether to ask again.public struct DictationResult: Sendable, Equatable {    public let outcome: DictationOutcome    public let text: String    public let words: [HeardWord]    public init(outcome: DictationOutcome, text: String, words: [HeardWord] = []) {        self.outcome = outcome        self.text = text        self.words = words    }}/// Live dictation over the platform recogniser: tap to start, partials stream/// into ``fieldText``, ``finish()`` answers the whole transcript, ``cancel()``/// discards it.////// **Sessions are MORTAL.** A session the analyzer gives up on mid-dictation is/// not the end of the dictation, so this model STITCHES: an `ended` nobody/// asked for folds the live segment into the committed text and opens a fresh/// session, invisibly (cap ``maxRestarts``).////// **A SESSION IS ALSO MANY STRETCHES, and that is a different stitch.** The/// transcriber settles a stretch at a time and starts its volatile transcript/// over each time (`SystemSpeechRecogniser`); ``SpeechEvent/segment(_:words:)`` is/// that cut, and it commits, because the words before a pause are never restated. A/// partial that was allowed to REPLACE them is the defect this stitch exists/// for: on build 146 the screen went blank every ten to fifty seconds, at each/// pause, and only the sentence since the last one survived. Guard:/// `DictationModelTests`' utterance-segmentation block.////// **An interruption is not a mortal session.** When the audio session is taken/// by a call, Siri or an alarm, the microphone is somebody else's until they are/// done — resurrecting into it fails on the spot, and looping to the restart cap/// used to take the words with it (2026-09-04: three minutes of dictation, one/// phone call, an empty field). iOS's own dictation stops and keeps what it/// heard; so does this: the dictation ENDS at once, named/// ``DictationOutcome/dictationInterrupted``, with the words.@MainActor@Observablepublic final class DictationModel {    /// How long the two hang guards and the display timer wait.    ///    /// The defaults are the hook's own hard-coded numbers. They are a value here    /// only so a test can prove the guards fire without waiting for them.    public struct Timings: Sendable {        /// A finish whose final `ended` never arrives still lands its words.        public var stopGuard: Duration        /// A discard's `ended` is near-instant; the same guard, shorter.        public var cancelGuard: Duration        /// The listening clock — display only.        public var tick: Duration        public init(            stopGuard: Duration = .milliseconds(2500),            cancelGuard: Duration = .milliseconds(1500),            tick: Duration = .seconds(1)        ) {            self.stopGuard = stopGuard            self.cancelGuard = cancelGuard            self.tick = tick        }    }    /// Sessions die quietly mid-dictation; cap how often one is resurrected so a    /// hard failure cannot loop for ever. Generous — a long note restarts every    /// minute or so at worst.    public static let maxRestarts = 40    /// A session that ends this soon after it came up, without one word heard,    /// never really came up: the model cannot run here. ``maxDeadOnArrival`` of    /// them in a row end the dictation as unavailable — before, forty of them    /// burned the restart cap in about twelve seconds and ended every dictation    /// 'interrupted'. A session that lived longer and heard nothing is a pause.    public static let deadOnArrival: TimeInterval = 1    public static let maxDeadOnArrival = 3    // ── What a screen draws ───────────────────────────────────────────────    public private(set) var phase: DictationPhase = .idle    /// Everything heard so far: the committed segments and the live tail,    /// already whitespace-folded.    public private(set) var liveText: String = ""    /// What the field held when dictation started. Kept PAST the ending on    /// purpose: the caller lands the words after the model has gone idle, and it    /// needs to know what to fold them onto.    public private(set) var prefix: String = ""    /// The meter, 0…1, or 0 when no source was injected.    public private(set) var level: Double = 0    /// The last ``DictationWaveform/barCount`` readings, oldest first — what    /// the listening line DRAWS.    ///    /// Kept here rather than accumulated in a view: the readings arrive about    /// twenty a second from the audio tap, and a view that sampled them would    /// need a timer of its own running at the same rate to catch them. A single    /// reading also cannot draw a waveform — the shape IS the history — so the    /// history is model state, and a test can drive it.    public private(set) var waveform: [Double] = []    /// How long this dictation has been running, in whole milliseconds — the    /// type `CaptureText.formatClock` takes, for the reason stated there.    public private(set) var elapsedMillis: Int = 0    /// The clock as it stood at the LAST settle.    ///    /// ``elapsedMillis`` is zeroed on the way to idle, exactly as the hook's    /// `setElapsedMs(0)` is — but the hook's consumers still read the real    /// number on the interruption path, because React handed them the value    /// captured at the render BEFORE the settle. A Swift property is read live,    /// so the number has to be kept somewhere to survive its own reset; this is    /// that somewhere, for a screen that reads the clock after the settle.    public private(set) var settledMillis = 0    /// The OS is being asked for the microphone and speech: on the first tap    /// its question stands over the screen, and nothing of the take draws    /// until it is answered (walker, architect 16 Oct 2026).    public private(set) var askingAccess = false    /// The listening line's answer: a session is live or coming up — never    /// while the OS is still asking for permission.    public var isListening: Bool { (phase == .starting && !askingAccess) || phase == .listening }    /// The tapped finish has been asked for and the words have not landed yet.    public var isFinishing: Bool { phase == .finishing }    /// The field is dictation's rather than the writer's — the whole live span,    /// finishing included, because the words are still arriving.    public var isLive: Bool { isListening || isFinishing }    /// What the field must show right now.    ///    /// Read it only while ``isLive``; once the model settles this is the prefix    /// alone and the caller's own text is the truth again.    public var fieldText: String { VoiceTake.foldDictationSegment(prefix, liveText) }    /// `m:ss`, for the listening line.    public var clock: String { CaptureText.formatClock(millis: elapsedMillis) }    /// The listening line's own sentence.    public var statusLine: String {        ShellLines.line("capture", isFinishing ? "dictation.finishing" : "dictation.listening")    }    // ── The endings nobody asked for ──────────────────────────────────────    /// The ONE channel for an ending nobody asked for: an interruption, or a    /// session past the restart cap. A recogniser that never came up at all    /// does NOT travel this channel — see the header.    ///    /// It carries everything heard, and **the host MUST land those words** —    /// through the same function its finish tap uses — because nobody is    /// awaiting ``finish()`` on this path and ``liveText`` is cleared by then.    public var onUnasked: ((DictationResult) -> Void)?    // ── Injected ──────────────────────────────────────────────────────────    private let recogniser: any SpeechRecognizing    private let levels: (any AudioLevelSource)?    /// A live Cotton call owns the microphone; ``start(prefix:hints:)``    /// refuses over one. Injected as a closure because the call store is not    /// ported yet — the ENDING exists and is testable, and the day calls land    /// there is one line to pass.    private let isOnCall: @MainActor () -> Bool    private let now: @MainActor () -> Date    private let timings: Timings    /// The snap's dictionary: is this a word of the dictation's language?    private let dictionary: DictationSnap.Dictionary    // ── The session's own state ───────────────────────────────────────────    /// Text from finished segments — what the stitching commits.    private var committed = ""    /// The live segment — the utterance in progress. An utterance restates    /// itself from its own beginning on every partial, so this is REPLACED per    /// event, never appended to; ``commit(_:)`` is what moves it into    /// ``committed`` when the recogniser closes it.    private var segment = ""    /// Why the session is ending: the person finished, the person discarded, or    /// nobody (a mortal session).    private enum StopMode { case none, stop, abort }    private var stopMode: StopMode = .none    private var restarts = 0    /// A resurrection has been asked for and has not yet reported `started` — a    /// failure in that window means the new session never came up.    private var restartPending = false    /// When the current session reported `started`, whether it has heard a    /// word, and how many sessions in a row died on arrival.    private var sessionStartedAt = Date(timeIntervalSince1970: 0)    private var heardThisSession = false    private var deadInARow = 0    /// Whether any session of this dictation heard a word.    private var heardAny = false    private var startedAt = Date(timeIntervalSince1970: 0)    /// The first meter reading of this dictation is the first audio buffer    /// the microphone handed over: its distance from the tap is the number a    /// person feels, and the log says it.    private var awaitingFirstBuffer = false    private static let log = Logger(subsystem: "com.cottondb.dictation", category: "listen")    private var hints = DictationHints()    /// The words of every settled stretch, with the model's confidence.    private var settledWords: [HeardWord] = []    private var pending: CheckedContinuation<DictationResult, Never>?    private var hangGuard: Task<Void, Never>?    private var ticker: Task<Void, Never>?    /// **This model fires no haptic**, and takes none. A feel belongs to the    /// control that was tapped, not to an engine three layers under it:    /// `/take`'s ✕ / Done / → Cotton fire none at all, while the composer's    /// mic, ✓ and ✕ each fire their own `press`. One engine cannot be right    /// for both.    public init(        recogniser: any SpeechRecognizing,        levels: (any AudioLevelSource)? = nil,        isOnCall: @escaping @MainActor () -> Bool = { false },        now: @escaping @MainActor () -> Date = Date.init,        timings: Timings = Timings(),        dictionary: @escaping DictationSnap.Dictionary = DictationSnap.systemDictionary    ) {        self.recogniser = recogniser        self.levels = levels        self.isOnCall = isOnCall        self.now = now        self.timings = timings        self.dictionary = dictionary        recogniser.onEvent { [weak self] event in self?.handle(event) }        levels?.onLevel { [weak self] value in            guard let self, self.isLive else { return }            if self.awaitingFirstBuffer {                self.awaitingFirstBuffer = false                let ms = Int(self.now().timeIntervalSince(self.startedAt) * 1000)                Self.log.notice("listen: tap→first audio buffer \(ms, privacy: .public) ms")            }            self.level = value            self.waveform.append(value)            if self.waveform.count > DictationWaveform.barCount {                self.waveform.removeFirst(self.waveform.count - DictationWaveform.barCount)            }        }    }    // ── The three things a person does ────────────────────────────────────    /// Tap the mic.    ///    /// Answers `nil` when a session is coming up, and otherwise the ending that    /// happened INSTEAD — the two refusals that arrive before a single word:    /// the microphone is on a call, or permission is refused. The caller speaks    /// the sentence, because it is the caller that has a screen.    @discardableResult    public func start(prefix: String, hints: DictationHints) async -> DictationOutcome? {        guard phase == .idle else { return nil }        // Set BEFORE the refusal below, as the composer does it        // a busy refusal must not leave the PREVIOUS session's prefix standing.        self.prefix = prefix        // Starting the recogniser over a live call would steal the call's input        // — the zero-audio-samples class of defect.        if isOnCall() { return .dictationOnCall }        self.hints = hints        committed = ""        settledWords = []        segment = ""        liveText = ""        level = 0        waveform = []        restarts = 0        restartPending = false        deadInARow = 0        heardAny = false        elapsedMillis = 0        startedAt = now()        awaitingFirstBuffer = true        phase = .starting        // THE GATE, BEFORE ANY PLATFORM OBJECT EXISTS. A refusal is an ending        // with a sentence, never an error and never a retry: `unavailable` is        // the device saying it has no such thing at all, which no permission        // can fix, and everything else is a decision only the person can        // change.        askingAccess = true        let access = await recogniser.access()        askingAccess = false        switch access {        case .ready:            break        case .blocked(_, let access):            phase = .idle            return access == .unavailable ? .dictationUnavailable : .dictationDenied        }        openSession()        return nil    }    /// Make the next tap warm (``SpeechRecognizing/prepare(_:)``): called when    /// the screen that owns the mic comes up and on every return to the    /// foreground, never on the tap.    public func prepare(hints: DictationHints) {        recogniser.prepare(hints)    }    /// Tap ✓. Resolves with everything heard.    @discardableResult    public func finish() async -> DictationResult {        guard phase != .idle else {            return DictationResult(outcome: .dictationEmpty, text: "")        }        // The body runs synchronously on this actor, so a recogniser that        // answers inside `stop()` resumes the continuation before this call        // returns — which is legal, and is what makes a test of this        // deterministic instead of a race.        return await withCheckedContinuation { continuation in            self.pending = continuation            self.stopMode = .stop            self.phase = .finishing            self.recogniser.stop()            self.armStopGuard()        }    }    /// Tap ✕ — a deliberate discard. The caller names the ending    /// (``DictationOutcome/dictationCancelled``), which owes no sentence; there    /// is nothing to wait for, so this does not answer one.    public func cancel() {        guard phase != .idle else { return }        stopMode = .abort        phase = .finishing        recogniser.cancel()        armCancelGuard()    }    /// Give the microphone back without naming an ending.    ///    /// **This is the arm for a dismissal nobody tapped** — the app backgrounded,    /// the screen popped, the host deallocated. It is the unmount cleanup:    /// abort the recogniser, clear the guard, tell nobody. Without it a session outlives the screen that owned    /// it, and the only finding in the review that misbehaves after the person    /// has left is exactly that.    ///    /// Idempotent, and a no-op on an idle model, so a screen may call it from    /// `.onDisappear` and from a scene-phase change both.    public func release() {        hangGuard?.cancel()        hangGuard = nil        ticker?.cancel()        ticker = nil        guard phase != .idle else { return }        stopMode = .abort        phase = .finishing        recogniser.cancel()        // A recogniser that answered inside `cancel()` has already settled this.        guard phase != .idle else { return }        settle(DictationResult(outcome: .dictationCancelled, text: ""))    }    /// The last resort, for the object that was let go with a session live.    ///    /// A `@MainActor` class's `deinit` is nonisolated under Swift 6, so neither    /// the timers nor the phase can be reached here — and they do not need to    /// be: both timer tasks hold `[weak self]` and go no-op the moment this    /// object is gone. The microphone is what cannot wait, and `recogniser` is    /// a `Sendable` `let`, which a nonisolated `deinit` MAY read.    /// `SystemSpeechRecogniser` gives the audio session back in its own    /// `deinit` too; this arm is the one that fires while something else still    /// holds a reference to it.    deinit {        let recogniser = self.recogniser        Task { @MainActor in recogniser.cancel() }    }    // ── The recogniser's events ───────────────────────────────────────────    private var composed: String {        VoiceTake.foldDictationSegment(committed, segment)    }    /// Keep a span the recogniser has SETTLED — an utterance it closed at a    /// pause, or the session's own final — and start the live tail again from    /// empty.    ///    /// One function for both because it is one rule, and writing it twice is    /// how the two drift: what is settled is committed, and the two awkward    /// shapes a settled span can have (empty, or a restatement of what is    /// already held) are decided in one place.    private func commit(_ transcript: String, words: [HeardWord] = []) {        // A settled span that arrives EMPTY — a session cut down mid-word, an        // utterance the recogniser would not stand behind — has nothing of its        // own to say, and the partials streamed since the last boundary ARE the        // words. Never let an empty settle erase them.        let settled = transcript.isEmpty ? segment : transcript        settledWords += transcript.isEmpty ? Self.unscored(segment) : words        committed = VoiceTake.foldSettledSpan(            committed: committed, live: segment, settled: settled)        segment = ""        liveText = composed    }    private func openSession() {        recogniser.start(hints)    }    /// Words the model never settled — a live tail kept by a stop or a cut —    /// carry no confidence.    private static func unscored(_ text: String) -> [HeardWord] {        text.split(whereSeparator: \.isWhitespace).map { HeardWord(text: String($0), confidence: nil) }    }    /// Everything heard: the settled words, then the live tail's.    private var composedWords: [HeardWord] { settledWords + Self.unscored(segment) }    private func handle(_ event: SpeechEvent) {        switch event {        case .started:            restartPending = false            sessionStartedAt = now()            heardThisSession = false            if phase == .starting {                phase = .listening                startTicker()            }        case .partial(let transcript):            guard phase == .listening || phase == .finishing else { return }            heard()            segment = transcript            liveText = composed        case .segment(let transcript, let words):            guard phase == .listening || phase == .finishing else { return }            if !transcript.isEmpty { heard() }            commit(transcript, words: words)        case .failed(let failure):            handle(failure: failure)        case .ended:            handleEnded()        }    }    private func handle(failure: SpeechFailure) {        if phase == .starting {            // SILENT, deliberately: `settle`            // resolves a continuation nobody holds before `finish()` has been            // called, and nothing else is told. The screen names this state by            // watching the engine go idle without a word — its own            // wordless-death timer, which is where the sentence comes            // from. Two sources of truth for one screen would race, and the            // loser writes the wrong one.            settle(                DictationResult(                    outcome: failure == .notAllowed ? .dictationDenied : .dictationUnavailable,                    text: ""                ))            return        }        // No model for the language: nothing to restart into, and the words        // heard so far are kept.        if failure == .unavailable && phase == .listening {            unavailable()            return        }        guard phase == .listening else { return }  // finishing: `ended` settles        if failure == .aborted && stopMode == .abort { return }        // The microphone is somebody else's — a call, Siri, an alarm — or the        // session just resurrected never came up because it is. Either way there        // is nothing to restart into: end now, named, with the words. The        // `ended` that follows finds this model idle and is ignored.        if failure == .interrupted || restartPending {            interrupt()            return        }        // Anything else: the `ended` follows and the restart ladder takes it.    }    private func handleEnded() {        switch stopMode {        case .abort:            settle(DictationResult(outcome: .dictationCancelled, text: ""))        case .stop:            settle(heardSoFar(.dictated))        case .none:            guard phase == .listening else { return }            // Nobody asked for this: the session died. Stitch — commit the            // segment and resurrect, unless the cap is reached.            settledWords = composedWords            committed = composed            segment = ""            if !heardThisSession && now().timeIntervalSince(sessionStartedAt) < Self.deadOnArrival {                deadInARow += 1                guard deadInARow < Self.maxDeadOnArrival else {                    // Nothing ever came up: the device has no recogniser that                    // runs, which is not an interruption.                    if heardAny { interrupt() } else { unavailable() }                    return                }            }            if restarts < DictationModel.maxRestarts {                restarts += 1                restartPending = true                openSession()            } else {                interrupt()            }        }    }    private func heard() {        heardThisSession = true        heardAny = true        deadInARow = 0    }    private func unavailable() {        restartPending = false        unasked(DictationResult(outcome: .dictationUnavailable, text: composed, words: composedWords))    }    /// What a finish lands: everything heard, or the empty ending.    private func heardSoFar(_ outcome: DictationOutcome) -> DictationResult {        let text = composed        return snapped(DictationResult(            outcome: text.isEmpty ? .dictationEmpty : outcome, text: text, words: composedWords))    }    /// The ending nobody asked for: settle, THEN hand the words over — after    /// settling, so a host that writes them into its field is writing into an    /// idle composer rather than a live one.    private func interrupt() {        restartPending = false        unasked(DictationResult(outcome: .dictationInterrupted, text: composed, words: composedWords))    }    private func unasked(_ result: DictationResult) {        let landing = snapped(result)        settle(landing)        onUnasked?(landing)    }    /// The words as they land: every near-miss of a hinted name snapped to the    /// name (`DictationSnap`). Only words that are landing are snapped — a    /// discard has none.    private func snapped(_ result: DictationResult) -> DictationResult {        guard !result.text.isEmpty, !hints.terms.isEmpty else { return result }        let names = hints.terms        let language = DictationSnap.language(of: hints.locale)        return DictationResult(            outcome: result.outcome,            text: DictationSnap.apply(result.text, names: names, language: language, isWord: dictionary),            words: DictationSnap.apply(result.words, names: names, language: language, isWord: dictionary))    }    private func settle(_ result: DictationResult) {        hangGuard?.cancel()        hangGuard = nil        ticker?.cancel()        ticker = nil        let waiting = pending        pending = nil        stopMode = .none        committed = ""        segment = ""        settledWords = []        liveText = ""        level = 0        settledMillis = elapsedMillis        elapsedMillis = 0        phase = .idle        waiting?.resume(returning: result)    }    // ── The timers ────────────────────────────────────────────────────────    private func armStopGuard() {        // A recogniser that answered synchronously has already settled this        // dictation; arming a guard onto an idle model would leave a task        // sleeping against a session that is over.        guard phase == .finishing else { return }        hangGuard?.cancel()        let delay = timings.stopGuard        hangGuard = Task { [weak self] in            try? await Task.sleep(for: delay)            guard !Task.isCancelled, let self, self.phase == .finishing else { return }            // THE RECOGNISER NEVER ANSWERED, so nothing has given the audio            // session back: `stop()` took the tap down, but deactivation lives            // in the recogniser's own `finished()`, which runs off a callback            // that — in exactly the case this guard exists for — never arrives.            // Ask for the discard that does run it, then keep the words.            self.recogniser.cancel()            guard self.phase == .finishing else { return }  // the cancel settled it            // Keep what was heard rather than hanging the composer: no ending            // without a word.            self.settle(self.heardSoFar(.dictated))        }    }    private func armCancelGuard() {        // A recogniser that answered synchronously has already settled this        // dictation; arming a guard onto an idle model would leave a task        // sleeping against a session that is over.        guard phase == .finishing else { return }        hangGuard?.cancel()        let delay = timings.cancelGuard        hangGuard = Task { [weak self] in            try? await Task.sleep(for: delay)            guard !Task.isCancelled, let self, self.phase == .finishing else { return }            // The same reason as the stop guard's: an `ended` that never came            // means the audio session was never given back.            self.recogniser.cancel()            guard self.phase == .finishing else { return }            self.settle(DictationResult(outcome: .dictationCancelled, text: ""))        }    }    /// The listening clock — display only, and driven while a session is live.    private func startTicker() {        ticker?.cancel()        let interval = timings.tick        ticker = Task { [weak self] in            while !Task.isCancelled {                try? await Task.sleep(for: interval)                guard !Task.isCancelled, let self, self.phase == .listening else { return }                self.elapsedMillis = Int(                    self.now().timeIntervalSince(self.startedAt) * 1000)            }        }    }}// MARK: - The one constructorextension DictationModel {    /// **THE constructor.** Every microphone in the app gets its dictation here    /// — OneInput, the chat composer, EditingRow, the capture dock, the new    /// thought, Take, Report a problem — and so does the accuracy harness's    /// recording (`scripts/voicegate`), so what is measured is what ships.    /// Guard: `CapabilityGateSweepTests` (no other line builds a recogniser).    ///    /// A system older than iOS 26 / macOS 26 has no on-device dictation model,    /// and says so at the tap (`dictationUnavailable`); there is no other engine.    public static func live(        audio: DictationAudio = .microphone,        isOnCall: @escaping @MainActor () -> Bool = { false }    ) -> DictationModel {        if #available(iOS 26.0, macOS 26.0, *) {            let recogniser = SystemSpeechRecogniser(audio: audio)            return DictationModel(recogniser: recogniser, levels: recogniser, isOnCall: isOnCall)        }        return DictationModel(recogniser: NoDictation(), isOnCall: isOnCall)    }}