mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS keyboard: a failure from Hex shows for seconds, not forever, and the Hex key retries it X testers on build 56 and earlier: "The keyboard keeps either bringing me back to the app or telling me another app is using the microphone" (@itsjling) and "The another app is using audio message seems inaccurate cause it's showing for me all the time although it's working fine" (@RedaSjakur). Cause, reproduced on build 56 (2ef08aa4) in an iOS 27.2 simulator on the Mac Studio (no microphone input): Hex's dictation failed ("Hex couldn't start the microphone. Try again."), Hex was then closed, and a minute later the Hex keyboard's strip in Settings' search field still said so. Hex writes its snapshot only while it runs, so a failed snapshot (heartbeat 0, no time) stayed in the App Group, and KeyboardViewModel read any .failed snapshot as failed whatever its age. The code path is unchanged on origin/dev. With a warm session up it was worse: Hex stayed in .failed, consumeKeyboardCommand ignored every start unless the phase was .ready, and the full keyboard's Hex key (isWarm = Full Access && warm available) kept sending starts to it, so nothing recorded until Hex was opened. The keyboard's own failure snapshot also reads as available for its 6 s, so a Hex key tap right after an in-keyboard failure went to a warm session that doesn't exist. Now: - KeyboardSnapshot.messageAt: when Hex wrote the message (DictationController stamps a failure when its phase becomes failed, and keyboardMessage when set; the keyboard's own failure stamps its snapshot). The keyboard drops a message, and reads a failure as offline, 8 s after it (messageShownFor), and at once for a snapshot with no time (an earlier build's). Whether a warm session is up and any result stay as they were. - KeyboardViewModel.dictatesThroughHex (Full Access, warm available, not failed), used by the full keyboard's Hex key and its touch-down capture: after a failure both keyboards dictate in the keyboard, as the Dictation bar already did. - Hex takes a keyboard start while failed when the failure was the microphone for a keyboard dictation with the model loaded (captureFailed): the next Hex key is its Try again. Model failures still wait for Hex to get ready again. Not changed: the 32 MB memory threshold and keyboardNeedsHex, the two ways the Hex key opens Hex. In the simulator the handoffs logged "speech model missing here" after the keyboard's own asset check failed ("anomaly.hex.mobile.keyboard is not subscribed to assistant.en_US") on a sim whose Hex had never installed a model, which is the intended path; a device's reason needs its probe log. Verified: new KeyboardBridgeTests.testAFailureHexWroteAWhileAgoIsOver and DictationControllerTests.testAWarmSessionsMicrophoneFailureIsRetriedFromTheKeyboard; KeyboardBridgeTests and DictationControllerTests pass (79 tests, 0 failures, iPhone 17 Pro iOS 27.2 simulator). In the simulator with this build, the same failure no longer shows in the keyboard a minute later. * iOS keyboard: the Hex key's audio session calls leave the main thread X tester @leeladhar (iPhone 16 Pro Max, build 56 or earlier): "the keyboard freezes while using apps sometimes ... the only way to close the keyboard is to close the app completely". Not reproduced in the iOS 27.2 simulator on build 56 (2ef08aa4) or origin/dev: 24 host visits (Messages, Contacts, Settings search) with typing, the Hex key and globe switches kept one keyboard process, no crash or hang report, footprint 29-40 MB with no growth. The device cause isn't confirmed. The likeliest one left on origin/dev is the last synchronous audio server round trips on the keyboard's main thread: every Hex key touch-down set the session's category, read and preferred its inputs (KeyboardLocalDictation.microphone(for:)), asked isOtherAudioPlaying, and read the Speech Recognition status for the probe log, all before the page could start. These wait on the audio server (and TCC) with no timeout; a build 56 crash report from TestFlight shows Hex's own main thread parked in such a call (setPreferredSampleRate waiting on SetBatchProperties). #2185 moved the one on the launch path for the same reason. While blocked, no key, Done or globe responds, and the keyboard can't dismiss. Now begin() runs those on the keyboard's audio session queue (after any earlier capture's release there) and starts the page when they return, unless the job was dropped, stopped or replaced meanwhile. Done before the page was asked to start ends quietly at once instead of leaving the page to start a capture nobody wants. Verified: builds clean; in an iPhone 17 Pro iOS 27.2 simulator (WebKit's mock audio device) the Hex key's touch-down capture still starts and is kept: "first audio +124 ms after touch-down (... getUserMedia +83 ...)", 13.5 s recorded as 643,072 frames at 48 kHz (no gap), then transcription as before. * iOS keyboard: the capture page resumes an audio context iOS suspended mid-dictation TestFlight tester on X (iPhone 13 Pro Max, iOS 27, build 56 or earlier): "in progress recording dropped when I took a screenshot". What a screenshot does to an in-keyboard dictation, in an iPhone 17 Pro iOS 27.2 simulator on the Mac Studio (WebKit's mock audio device records there): - The host only going inactive doesn't stop it: with Control Center pulled down for 4 s mid-dictation the page kept sending audio (700,416 frames at 48 kHz over a 14.8 s recording, no gap). - A screenshot taken with Cmd-Shift-3 hid the keyboard and the probe log said "keyboard hidden while recording: finishing with what was said" at the shutter. The simulator can only take one through its hardware keyboard, which also turns on keyboard minimization, so it doesn't show which of the two hid it. On an iPhone, iOS 26 and 27 open the screenshot's full-screen preview over the app, and a keyboard that hides is torn down and its WebKit processes suspended, so a dictation can't keep recording through that. - On build 56 a keyboard hidden mid-recording lost the dictation: viewWillDisappear only dropped a touch-down capture, and the recording went with the view controller (reproduced in #2163). Since #2163 on origin/dev it stops, keeps what was said, and the text goes into the same field when the keyboard comes back within 30 s, else is offered as Paste dictation. The one way left for a capture to end early with the keyboard still up is the page's audio context: iOS may suspend or interrupt it for other audio and the page never resumed it, so no more audio came and the 6 s watchdog ended the dictation. The page now resumes a context that isn't running every 250 ms while it records, and stops trying when the capture stops. Not changed: a keyboard hidden by a screenshot's preview still ends the recording (with its text kept, as above). Verified: builds clean; in the simulator the touch-down capture still starts and records through Control Center with no gap (numbers above). * iOS: a spoken count reads "Test 1, 2, 3." on every speech model TestFlight (@kevin_miller, Nov 20, build 56 =2ef08aa4): "Test 1, 2, 3" came out "Test three." / "Test 3" from the keyboard's in-keyboard dictation and "test 123" in the app's Dictate box. What each speech model writes (macOS 27.2.1 on the Mac Studio, `say` clips, 4 voices): Apple's SpeechTranscriber (in-keyboard dictation) writes "Test one, 2, 3.", "Test, one, two, three.", "Testing 123.", "Counting one, two, three, four."; DictationTranscriber writes "Test 123", "Counting 1234"; Parakeet v2 through FluidAudio 0.15.5 (the app) writes "Test 1, 2, 3", "Testing 123" (no pauses), "1, 2, 3, testing". Responsible steps: - "Test three." / "Test 3": at build 56 Clean up what I say deleted every word over P(DELETE) 0.98 with no guard. The real Core ML model gives the count words but the last 0.97-0.999 ("Test one two three." -> "Test three.", "Test 1, 2, 3." -> "Test 1, 3."): it reads a count as a self-correction. CleanupGuard (#2132, after build 56) already keeps every count on origin/dev; this commit adds tests that pin it. - "test 123": Parakeet and DictationTranscriber write "123" themselves; no Hex step merges digits. Apple Intelligence's cleanup (same prompt, macOS 27.2 model) kept "Test 1, 2, 3." in 3 of 3 runs per input. - The paths still disagreed on origin/dev: the keyboard inserted "Test one, 2, 3." where the app inserted "Test 1, 2, 3.". Change: SpokenCleanupRules.spokenCounts, run by CleanupTagger.cleanIfEnabled right after spoken symbols (every style but Verbatim, English, Clean up what I say on or off, before the tagger, in the app and in-keyboard dictation), writes a count in digits: three numbers or more counting up from one, in words or digits, with only a comma or a space between them ("one, 2, 3", "one two three" -> "1, 2, 3"), and "123"... right after "test"/"testing" when it ends its clause ("Test 123" -> "Test 1, 2, 3"; "test 123 passed", "room 123", "Counting 1234" stay). Decision: the "123" split is limited to test/testing because a bare "123" is usually a real number. Format lists already never makes a list of a count (each item would be empty); tests prove it. README gains the Spoken counts paragraph. Verified on the iOS 27.2 simulator (Mac Studio), real Core ML tagger: TranscriptCleanupGuardTests 9, CleanupGuardTests 6, SpokenCleanupRulesTests 19, HinglishRomanizerTests 7, SpokenListsTests 10, InformalContractionTests 4, FrenchSpacingTests 3, CleanupTaggerTests 15, DictationControllerTests 50: 123 tests, 0 failures. New: testSpokenCountsBecomeDigits, testOtherNumbersStayAsSaid, testCountsAreNoList, testCountsKeepEveryNumberFromEverySpeechModel (also shows the guardless tagger's "Test three."), testACountReadsTheSameFromTheAppAndTheKeyboard (app with Parakeet's text vs keyboard with both Apple modules' text, every style, Lowercase).
1486 lines
58 KiB
Swift
1486 lines
58 KiB
Swift
import AVFAudio
|
||
import Foundation
|
||
import Observation
|
||
import SwiftUI
|
||
import UIKit
|
||
|
||
@MainActor
|
||
@Observable
|
||
final class DictationController {
|
||
static let shared = DictationController(
|
||
autoPrepareOnInit: ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil,
|
||
cleaner: AppleIntelligenceCleaner()
|
||
)
|
||
|
||
private static let minCaptureDuration: TimeInterval = 0.30
|
||
private static let maxCaptureDuration: TimeInterval = 60.0
|
||
private static let resultDeliveryTTL: TimeInterval = 30.0
|
||
|
||
enum Phase: Equatable {
|
||
case modelRequired
|
||
case preparingModel
|
||
case ready
|
||
case requestingPermission
|
||
case recording
|
||
case transcribing
|
||
case failed(String)
|
||
|
||
var isBusy: Bool {
|
||
switch self {
|
||
case .preparingModel, .requestingPermission, .transcribing:
|
||
true
|
||
default:
|
||
false
|
||
}
|
||
}
|
||
|
||
/// Recording and transcribing keep the screen on, so the iPhone doesn't dim and lock
|
||
/// while you talk or wait for the text.
|
||
var keepsScreenAwake: Bool {
|
||
self == .recording || self == .transcribing
|
||
}
|
||
}
|
||
|
||
private struct ActiveCaptureSession {
|
||
let generation: UInt64
|
||
let capture: any ActiveAudioCapture
|
||
let startedAt: TimeInterval
|
||
let keyboardJobID: String?
|
||
let style: DictationStyle
|
||
let usesCleanup: Bool
|
||
/// Settings › Dictation › Lowercase, read at start.
|
||
let lowercase: Bool
|
||
/// Settings › Dictation › Format lists, read at start.
|
||
let formatLists: Bool
|
||
/// Settings › Dictation › Spoken punctuation, read at start.
|
||
let spokenPunctuation: Bool
|
||
/// Settings › Dictation › End with a period, read at start.
|
||
let endsWithPeriod: Bool
|
||
/// Experiments › Hinglish, read at start.
|
||
let hinglish: Bool
|
||
let vocabularyTerms: [String]
|
||
/// Learn how I type's dictation fixes, read at start; empty while it is off.
|
||
let personalCorrections: [DictationCorrection]
|
||
/// Custom vocabulary plus the learned fixes' meant words, for Apple Speech.
|
||
let recognitionHints: [String]
|
||
/// Whether the keyboard gets the raw transcript to learn from.
|
||
let sharesHeard: Bool
|
||
let copyToPasteboard: Bool
|
||
/// The transcriber's language (BCP 47) when the capture started.
|
||
let language: String
|
||
}
|
||
|
||
private struct PendingKeyboardHandoff {
|
||
let jobID: String?
|
||
let style: DictationStyle
|
||
let requestedAt: TimeInterval
|
||
}
|
||
|
||
private var transcriber: any LocalTranscribing
|
||
private let transcriberFactory: () async -> any LocalTranscribing
|
||
private let cleaner: (any TranscriptCleaning)?
|
||
private let cleanupSettings: AppleIntelligenceCleanupSettings
|
||
private let customVocabularySettings: CustomVocabularySettings
|
||
private let lowercaseSettings: DictationLowercaseSettings
|
||
private let listSettings: DictationListSettings
|
||
private let punctuationSettings: DictationPunctuationSettings
|
||
private let periodSettings: DictationPeriodSettings
|
||
private let hinglishSettings: HinglishSettings
|
||
private let typingJournalSettings: TypingJournalSettings
|
||
private let learnedDictationCorrections: @MainActor (String?) -> [DictationCorrection]
|
||
private let audio: any AudioManaging
|
||
let keyboardBridge: KeyboardBridge
|
||
private let fileManager: FileManager
|
||
private let now: () -> TimeInterval
|
||
private let liveActivity = LiveActivityCoordinator()
|
||
|
||
private var jobGeneration: UInt64 = 0
|
||
private var modelPrepGeneration: UInt64 = 0
|
||
private var activeCapture: ActiveCaptureSession?
|
||
private var meterTask: Task<Void, Never>?
|
||
private var transcriptionTask: Task<Void, Never>?
|
||
private var keyboardSessionTask: Task<Void, Never>?
|
||
|
||
private var lastKeyboardCommandID: String?
|
||
private var lastHandledLaunchJobID: String?
|
||
private var activeKeyboardJobID: String?
|
||
private var keyboardResultID: String?
|
||
private var keyboardResultExpiresAt: TimeInterval?
|
||
private var keyboardResult: String?
|
||
private var keyboardResultHeard: String?
|
||
/// Why the result went in as spoken while Translate what I say was on, for the keyboard's note.
|
||
private var keyboardResultTranslationFailure: TranslationFailure?
|
||
/// Record typing logs: each step of the result, for the keyboard's log; nil while off.
|
||
private var keyboardResultStages: DictationStages?
|
||
private var keyboardMessage: String? {
|
||
didSet { keyboardMessageAt = keyboardMessage == nil ? nil : now() }
|
||
}
|
||
private var pendingHandoff: PendingKeyboardHandoff?
|
||
var keyboardSessionExpiresAt: TimeInterval = 0
|
||
private var suspendedWarmSessionOnInterruption = false
|
||
/// The warm session loop's restarts of a keepalive that stopped by itself. Each one
|
||
/// activates the session and reopens the microphone under every app recording at the
|
||
/// time (a screen recording too), so one that keeps stopping soon after its restart waits
|
||
/// twice as long each time (1 s, 2 s, … 30 s), not 100 ms; one that ran a while restarts
|
||
/// at once.
|
||
@ObservationIgnored private var keepaliveRestartedAt = -TimeInterval.infinity
|
||
@ObservationIgnored private var keepaliveRestartDelay: TimeInterval = 0
|
||
@ObservationIgnored private var keepaliveRestartDue: TimeInterval?
|
||
private static let steadyKeepalive: TimeInterval = 10
|
||
private static let maxKeepaliveRestartDelay: TimeInterval = 30
|
||
|
||
var phase = Phase.modelRequired {
|
||
didSet {
|
||
captureFailed = false
|
||
if case .failed = phase { failedAt = now() }
|
||
guard phase.keepsScreenAwake != oldValue.keepsScreenAwake else { return }
|
||
// Only applies while Hex is in front; nothing else in Hex sets it, so ending a
|
||
// dictation hands the screen back to Auto-Lock.
|
||
UIApplication.shared.isIdleTimerDisabled = phase.keepsScreenAwake
|
||
}
|
||
}
|
||
var isModelReady = false
|
||
var transcript = ""
|
||
@ObservationIgnored var audioLevel: Float = 0
|
||
@ObservationIgnored var loudnessDB: Float = -120
|
||
@ObservationIgnored private var rawRecordingDuration: TimeInterval = 0
|
||
private(set) var recordingWholeSeconds: Int = 0
|
||
var recordingDuration: TimeInterval {
|
||
get { rawRecordingDuration }
|
||
set {
|
||
rawRecordingDuration = newValue
|
||
let whole = max(0, Int(newValue))
|
||
if recordingWholeSeconds != whole {
|
||
recordingWholeSeconds = whole
|
||
}
|
||
}
|
||
}
|
||
private(set) var copied = false
|
||
var keyboardSessionEnabled = false
|
||
@ObservationIgnored private var rawKeyboardSessionRemaining: TimeInterval = 0
|
||
private(set) var keyboardSessionDisplayRemaining = "0:00"
|
||
var keyboardSessionRemaining: TimeInterval {
|
||
get { rawKeyboardSessionRemaining }
|
||
set {
|
||
rawKeyboardSessionRemaining = newValue
|
||
let formatted = HexTheme.formatRemaining(newValue)
|
||
if keyboardSessionDisplayRemaining != formatted {
|
||
keyboardSessionDisplayRemaining = formatted
|
||
}
|
||
}
|
||
}
|
||
@ObservationIgnored private var lastPublishedSnapshotSignature: String?
|
||
@ObservationIgnored private var lastPublishedSnapshotAt: TimeInterval = -100
|
||
/// When the phase last became failed, and when `keyboardMessage` was last set: the
|
||
/// keyboard shows a message only for a few seconds after (`KeyboardSnapshot.messageAt`).
|
||
@ObservationIgnored private var failedAt: TimeInterval?
|
||
@ObservationIgnored private var keyboardMessageAt: TimeInterval?
|
||
/// The failure on screen is a microphone that didn't start for a keyboard's dictation, with
|
||
/// the model still loaded: the keyboard's next Hex key tries again.
|
||
@ObservationIgnored private var captureFailed = false
|
||
var warmDuration: WarmSessionDuration
|
||
private(set) var style: DictationStyle
|
||
private(set) var microphone: MicrophoneChoice
|
||
private(set) var handoffNotice: String?
|
||
var engineName = "Local speech"
|
||
var transcriptionLanguage = "English"
|
||
/// The BCP 47 identifier of `transcriptionLanguage`, for the steps that depend on it.
|
||
var transcriptionLanguageID = "en-US"
|
||
/// Settings › Dictation language: a BCP 47 identifier, or nil for Automatic.
|
||
private(set) var dictationLanguage: String?
|
||
/// The keyboard's language Automatic followed when the model was last asked for
|
||
/// (`LanguageSettings.keyboardDictationLanguage`), so a switch on the space bar prepares
|
||
/// the new one.
|
||
private var followedKeyboardLanguage: String?
|
||
/// A language change made while busy, applied once the dictation in flight is done.
|
||
private var pendingLanguagePreparation = false
|
||
/// Said once Automatic moved on from a language this iPhone can't dictate yet
|
||
/// ("Russian isn't available on this iPhone yet. Hex switched to English.").
|
||
var languageNotice: String?
|
||
/// The language to offer (BCP 47) when the one chosen can't be dictated here yet.
|
||
var languageOffer: String?
|
||
private let languageSettings: LanguageSettings
|
||
private(set) var modelPreparation = ModelPreparationProgress(
|
||
fractionCompleted: 0,
|
||
detail: String(localized: "Checking the speech model")
|
||
)
|
||
/// Whether Hex is in the background, where iOS suspends it and a download's connection
|
||
/// drops.
|
||
private var isInBackground = false
|
||
/// A model download that failed while Hex was in the background, tried again on return.
|
||
private var preparationFailedInBackground = false
|
||
|
||
init(
|
||
audio: (any AudioManaging)? = nil,
|
||
keyboardBridge: KeyboardBridge? = nil,
|
||
transcriber: (any LocalTranscribing)? = nil,
|
||
transcriberFactory: (() async -> any LocalTranscribing)? = nil,
|
||
fileManager: FileManager = .default,
|
||
now: @escaping () -> TimeInterval = { Date().timeIntervalSince1970 },
|
||
autoPrepareOnInit: Bool = true,
|
||
cleaner: (any TranscriptCleaning)? = nil,
|
||
cleanupSettings: AppleIntelligenceCleanupSettings = AppleIntelligenceCleanupSettings(),
|
||
customVocabularySettings: CustomVocabularySettings = CustomVocabularySettings(),
|
||
lowercaseSettings: DictationLowercaseSettings = DictationLowercaseSettings(),
|
||
listSettings: DictationListSettings = DictationListSettings(),
|
||
punctuationSettings: DictationPunctuationSettings = DictationPunctuationSettings(),
|
||
periodSettings: DictationPeriodSettings = DictationPeriodSettings(),
|
||
hinglishSettings: HinglishSettings = HinglishSettings(),
|
||
typingJournalSettings: TypingJournalSettings = TypingJournalSettings(),
|
||
learnedDictationCorrections: (@MainActor (String?) -> [DictationCorrection])? = nil,
|
||
languageSettings: LanguageSettings = LanguageSettings()
|
||
) {
|
||
let resolvedBridge = keyboardBridge ?? KeyboardBridge()
|
||
let resolvedAudio = audio ?? SystemAudioManager()
|
||
let initialTranscriber = transcriber ?? ParakeetTranscriber()
|
||
|
||
self.audio = resolvedAudio
|
||
self.keyboardBridge = resolvedBridge
|
||
self.transcriber = initialTranscriber
|
||
self.transcriberFactory = transcriberFactory ?? Self.defaultTranscriber
|
||
self.cleaner = cleaner
|
||
self.cleanupSettings = cleanupSettings
|
||
self.customVocabularySettings = customVocabularySettings
|
||
self.lowercaseSettings = lowercaseSettings
|
||
self.listSettings = listSettings
|
||
self.punctuationSettings = punctuationSettings
|
||
self.periodSettings = periodSettings
|
||
self.hinglishSettings = hinglishSettings
|
||
self.typingJournalSettings = typingJournalSettings
|
||
self.learnedDictationCorrections = learnedDictationCorrections ?? { language in
|
||
TypingJournal.storedDictationCorrections(settings: typingJournalSettings, language: language)
|
||
}
|
||
self.fileManager = fileManager
|
||
self.now = now
|
||
self.languageSettings = languageSettings
|
||
self.dictationLanguage = languageSettings.dictationLanguage
|
||
self.followedKeyboardLanguage = languageSettings.keyboardDictationLanguage()
|
||
self.warmDuration = resolvedBridge.warmDuration
|
||
self.style = resolvedBridge.style
|
||
self.microphone = resolvedBridge.microphone
|
||
|
||
let hasCachedModel = ParakeetTranscriber.hasCachedModel
|
||
resolvedBridge.publish(.offline)
|
||
resolvedBridge.setModelInstalled(hasCachedModel)
|
||
|
||
wireAudioCallbacks()
|
||
wireSystemIntentBus()
|
||
if autoPrepareOnInit {
|
||
// At launch no dictation is running, so any Hex Live Activity is left over.
|
||
liveActivity.endImmediately()
|
||
}
|
||
|
||
if Self.applyLaunchFixtureIfPresent(to: self) {
|
||
return
|
||
}
|
||
|
||
if autoPrepareOnInit {
|
||
prepareAtLaunch(hasCachedModel: hasCachedModel)
|
||
}
|
||
}
|
||
|
||
var isRecording: Bool {
|
||
phase == .recording
|
||
}
|
||
|
||
var primaryTitle: String {
|
||
switch phase {
|
||
case .modelRequired, .failed:
|
||
"Prepare \(engineName)"
|
||
case .preparingModel:
|
||
"Preparing \(engineName)"
|
||
case .ready:
|
||
"Start dictation"
|
||
case .requestingPermission:
|
||
"Checking microphone"
|
||
case .recording:
|
||
"Finish"
|
||
case .transcribing:
|
||
"Transcribing…"
|
||
}
|
||
}
|
||
|
||
// MARK: - Settings
|
||
|
||
func setWarmDuration(_ duration: WarmSessionDuration) {
|
||
warmDuration = duration
|
||
keyboardBridge.warmDuration = duration
|
||
|
||
if keyboardSessionEnabled {
|
||
if let seconds = duration.seconds {
|
||
keyboardSessionExpiresAt = now() + seconds
|
||
keyboardSessionRemaining = seconds
|
||
publishKeyboardSnapshot()
|
||
} else if phase == .ready {
|
||
endWarmSession()
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Used by the settings segmented control: picking a duration warms immediately; picking Off ends it.
|
||
func selectWarmDuration(_ duration: WarmSessionDuration) {
|
||
setWarmDuration(duration)
|
||
if duration == .off {
|
||
if keyboardSessionEnabled {
|
||
endWarmSession()
|
||
} else {
|
||
endStaleLiveActivities()
|
||
}
|
||
} else if !keyboardSessionEnabled {
|
||
requestWarmSession()
|
||
}
|
||
}
|
||
|
||
func setStyle(_ newStyle: DictationStyle) {
|
||
style = newStyle
|
||
keyboardBridge.style = newStyle
|
||
}
|
||
|
||
/// Settings › Dictation language. Prepares the new language's model now, or once the
|
||
/// dictation in flight is done.
|
||
func setDictationLanguage(_ identifier: String?) {
|
||
let normalized = (identifier?.isEmpty == true) ? nil : identifier
|
||
guard normalized != dictationLanguage else { return }
|
||
languageSettings.chooseDictationLanguage(normalized)
|
||
applyDictationLanguage(normalized)
|
||
}
|
||
|
||
/// Picks up a language the keyboard switched to in the App Group: a pick in its language
|
||
/// switch, or, on Automatic, the keyboard's own language switched on the space bar.
|
||
func followDictationLanguageSetting() {
|
||
let stored = languageSettings.dictationLanguage
|
||
let following = languageSettings.keyboardDictationLanguage()
|
||
guard stored != dictationLanguage || following != followedKeyboardLanguage else { return }
|
||
applyDictationLanguage(stored)
|
||
}
|
||
|
||
/// Takes the language offered after the chosen one couldn't be dictated here.
|
||
func useOfferedLanguage() {
|
||
guard let languageOffer else { return }
|
||
setDictationLanguage(languageOffer)
|
||
}
|
||
|
||
private func applyDictationLanguage(_ identifier: String?) {
|
||
dictationLanguage = identifier
|
||
followedKeyboardLanguage = languageSettings.keyboardDictationLanguage()
|
||
languageNotice = nil
|
||
languageOffer = nil
|
||
switch phase {
|
||
case .recording, .transcribing, .requestingPermission:
|
||
pendingLanguagePreparation = true
|
||
case .modelRequired, .preparingModel, .ready, .failed:
|
||
prepareModel()
|
||
}
|
||
}
|
||
|
||
/// Experiments › Multilingual model (Parakeet) turned on or off: prepares the engine Hex
|
||
/// picks now, or once the dictation in flight is done.
|
||
func multilingualParakeetChanged() {
|
||
switch phase {
|
||
case .recording, .transcribing, .requestingPermission:
|
||
pendingLanguagePreparation = true
|
||
case .modelRequired, .preparingModel, .ready, .failed:
|
||
prepareModel()
|
||
}
|
||
}
|
||
|
||
/// Runs a language change that waited for the dictation in flight.
|
||
private func prepareDeferredLanguageIfNeeded() {
|
||
guard pendingLanguagePreparation else { return }
|
||
switch phase {
|
||
case .ready, .failed, .modelRequired:
|
||
pendingLanguagePreparation = false
|
||
prepareModel()
|
||
case .recording, .transcribing, .requestingPermission, .preparingModel:
|
||
break
|
||
}
|
||
}
|
||
|
||
/// The next dictation records from the new choice's input; the warm keepalive stays on
|
||
/// the iPhone's microphone whatever the choice.
|
||
func setMicrophone(_ choice: MicrophoneChoice) {
|
||
guard microphone != choice else { return }
|
||
microphone = choice
|
||
keyboardBridge.microphone = choice
|
||
}
|
||
|
||
// MARK: - Standalone & System Actions
|
||
|
||
func performPrimaryAction() {
|
||
switch phase {
|
||
case .modelRequired, .failed:
|
||
prepareModel()
|
||
case .ready:
|
||
startRecording(copyToPasteboard: false)
|
||
case .recording:
|
||
finishRecording()
|
||
case .preparingModel, .requestingPermission, .transcribing:
|
||
break
|
||
}
|
||
}
|
||
|
||
func cancelCurrentJob() {
|
||
jobGeneration &+= 1
|
||
transcriptionTask?.cancel()
|
||
transcriptionTask = nil
|
||
liveActivity.endImmediately()
|
||
|
||
if let session = activeCapture {
|
||
activeCapture = nil
|
||
stopMetering()
|
||
session.capture.stop()
|
||
try? fileManager.removeItem(at: session.capture.url)
|
||
}
|
||
|
||
if activeKeyboardJobID != nil {
|
||
keyboardMessage = nil
|
||
}
|
||
activeKeyboardJobID = nil
|
||
audioLevel = 0
|
||
loudnessDB = -120
|
||
recordingDuration = 0
|
||
if phase == .recording || phase == .transcribing || phase == .requestingPermission {
|
||
phase = .ready
|
||
}
|
||
restoreAudioAfterCapture()
|
||
publishKeyboardSnapshot()
|
||
prepareDeferredLanguageIfNeeded()
|
||
}
|
||
|
||
func clearTranscript() {
|
||
transcript = ""
|
||
copied = false
|
||
}
|
||
|
||
func copyTranscript() {
|
||
guard !transcript.isEmpty else { return }
|
||
UIPasteboard.general.string = transcript
|
||
copied = true
|
||
}
|
||
|
||
func toggleWarmSession() {
|
||
if keyboardSessionEnabled {
|
||
endWarmSession()
|
||
} else {
|
||
if warmDuration == .off {
|
||
setWarmDuration(.fifteenMinutes)
|
||
}
|
||
requestWarmSession()
|
||
}
|
||
}
|
||
|
||
func endWarmSession(message: String? = nil) {
|
||
keyboardSessionTask?.cancel()
|
||
keyboardSessionTask = nil
|
||
pendingHandoff = nil
|
||
suspendedWarmSessionOnInterruption = false
|
||
|
||
// Cancel an unaccepted in-progress recording, but preserve any already-accepted transcription!
|
||
if let session = activeCapture {
|
||
jobGeneration &+= 1
|
||
activeCapture = nil
|
||
stopMetering()
|
||
session.capture.stop()
|
||
try? fileManager.removeItem(at: session.capture.url)
|
||
activeKeyboardJobID = nil
|
||
audioLevel = 0
|
||
loudnessDB = -120
|
||
recordingDuration = 0
|
||
liveActivity.endImmediately()
|
||
if phase == .recording {
|
||
phase = .ready
|
||
}
|
||
}
|
||
|
||
keyboardSessionEnabled = false
|
||
keyboardSessionRemaining = 0
|
||
keyboardSessionExpiresAt = 0
|
||
keyboardMessage = message
|
||
|
||
if phase != .recording {
|
||
audio.deactivateSession()
|
||
}
|
||
endStaleLiveActivities()
|
||
|
||
publishKeyboardSnapshot()
|
||
// An accepted transcription the keyboard waits on keeps its heartbeat.
|
||
if keyboardJobInFlight {
|
||
startKeyboardSessionLoop()
|
||
}
|
||
}
|
||
|
||
/// Ends Live Activities no dictation owns, such as one a suspended or killed process left.
|
||
func endStaleLiveActivities() {
|
||
guard activeCapture == nil, phase != .recording, phase != .transcribing else { return }
|
||
liveActivity.endImmediately()
|
||
}
|
||
|
||
// MARK: - Keyboard Launch
|
||
|
||
func handleKeyboardLaunch(_ request: KeyboardLaunchRequest) {
|
||
if request.opensPage {
|
||
return
|
||
}
|
||
// A language picked in the keyboard: prepare it before the handoff records.
|
||
followDictationLanguageSetting()
|
||
handoffNotice = nil
|
||
|
||
let currentTime = now()
|
||
if request.isHandoffExpired(at: currentTime) {
|
||
handoffNotice = String(localized: "Timed out")
|
||
pendingHandoff = PendingKeyboardHandoff(
|
||
jobID: nil,
|
||
style: style,
|
||
requestedAt: currentTime
|
||
)
|
||
fulfillPendingHandoffOrPrepare()
|
||
return
|
||
}
|
||
|
||
switch request {
|
||
case .setup, .translationSettings:
|
||
break
|
||
|
||
case .startSession:
|
||
pendingHandoff = PendingKeyboardHandoff(
|
||
jobID: nil,
|
||
style: style,
|
||
requestedAt: currentTime
|
||
)
|
||
fulfillPendingHandoffOrPrepare()
|
||
|
||
case .startRecording(let jobID, _, let requestedStyle):
|
||
guard !jobID.isEmpty, jobID != lastHandledLaunchJobID else { return }
|
||
lastHandledLaunchJobID = jobID
|
||
if let requestedStyle {
|
||
setStyle(requestedStyle)
|
||
}
|
||
pendingHandoff = PendingKeyboardHandoff(
|
||
jobID: jobID,
|
||
style: requestedStyle ?? style,
|
||
requestedAt: currentTime
|
||
)
|
||
fulfillPendingHandoffOrPrepare()
|
||
}
|
||
}
|
||
|
||
private func fulfillPendingHandoffOrPrepare() {
|
||
guard let handoff = pendingHandoff else { return }
|
||
|
||
if now() - handoff.requestedAt > KeyboardLaunchRequest.handoffWindow {
|
||
handoffNotice = String(localized: "Timed out")
|
||
pendingHandoff = PendingKeyboardHandoff(
|
||
jobID: nil,
|
||
style: handoff.style,
|
||
requestedAt: now()
|
||
)
|
||
}
|
||
|
||
switch phase {
|
||
case .modelRequired, .failed:
|
||
prepareModel()
|
||
case .ready:
|
||
activateWarmSessionAndRunHandoff()
|
||
case .preparingModel, .requestingPermission, .recording, .transcribing:
|
||
break
|
||
}
|
||
}
|
||
|
||
private func requestWarmSession() {
|
||
pendingHandoff = PendingKeyboardHandoff(
|
||
jobID: nil,
|
||
style: style,
|
||
requestedAt: now()
|
||
)
|
||
fulfillPendingHandoffOrPrepare()
|
||
}
|
||
|
||
private func activateWarmSessionAndRunHandoff() {
|
||
guard phase == .ready else { return }
|
||
let handoff = pendingHandoff
|
||
pendingHandoff = nil
|
||
|
||
// If a one-shot recording was requested (`warmDuration == .off` and a jobID is present),
|
||
// go straight into recording and release the mic as soon as capture finishes.
|
||
if warmDuration == .off, let jobID = handoff?.jobID {
|
||
let expired = handoff.map { now() - $0.requestedAt > KeyboardLaunchRequest.handoffWindow } ?? false
|
||
if !expired {
|
||
startRecording(
|
||
keyboardJobID: jobID,
|
||
styleOverride: handoff?.style,
|
||
copyToPasteboard: false
|
||
)
|
||
// The keyboard finishes what it handed off: without the loop its Done and
|
||
// Cancel went unread and the recording ran to its 60 s limit.
|
||
startKeyboardSessionLoop()
|
||
} else {
|
||
handoffNotice = String(localized: "Timed out")
|
||
}
|
||
return
|
||
}
|
||
|
||
if keyboardSessionEnabled, audio.isKeepaliveRunning {
|
||
refreshWarmExpiry()
|
||
if let jobID = handoff?.jobID {
|
||
let expired = handoff.map { now() - $0.requestedAt > KeyboardLaunchRequest.handoffWindow } ?? false
|
||
if !expired {
|
||
startRecording(
|
||
keyboardJobID: jobID,
|
||
styleOverride: handoff?.style,
|
||
copyToPasteboard: false
|
||
)
|
||
return
|
||
} else {
|
||
handoffNotice = String(localized: "Timed out")
|
||
}
|
||
}
|
||
return
|
||
}
|
||
|
||
jobGeneration &+= 1
|
||
let requestGen = jobGeneration
|
||
phase = .requestingPermission
|
||
keyboardMessage = nil
|
||
|
||
Task {
|
||
let granted = await audio.requestPermission()
|
||
guard self.jobGeneration == requestGen else { return }
|
||
guard granted else {
|
||
phase = .failed(String(localized: "Microphone access is off. Allow it in Settings to dictate."))
|
||
publishKeyboardSnapshot()
|
||
return
|
||
}
|
||
|
||
// If we also have a fresh recording job, begin capture directly so we don't bounce keepalive -> recorder!
|
||
if let jobID = handoff?.jobID,
|
||
let requestedAt = handoff?.requestedAt,
|
||
self.now() - requestedAt <= KeyboardLaunchRequest.handoffWindow {
|
||
self.enableWarmSessionBookkeeping()
|
||
self.phase = .ready
|
||
self.startKeyboardSessionLoop()
|
||
self.startRecording(
|
||
keyboardJobID: jobID,
|
||
styleOverride: handoff?.style,
|
||
copyToPasteboard: false
|
||
)
|
||
return
|
||
}
|
||
|
||
if let jobID = handoff?.jobID, !jobID.isEmpty {
|
||
self.handoffNotice = String(localized: "Timed out")
|
||
}
|
||
|
||
do {
|
||
try audio.startKeepalive()
|
||
enableWarmSessionBookkeeping()
|
||
phase = .ready
|
||
startKeyboardSessionLoop()
|
||
publishKeyboardSnapshot()
|
||
} catch {
|
||
audio.deactivateSession()
|
||
phase = .failed(UserFacingError.message(for: error, context: .microphone))
|
||
publishKeyboardSnapshot()
|
||
}
|
||
}
|
||
}
|
||
|
||
private func enableWarmSessionBookkeeping() {
|
||
let seconds = warmDuration.seconds ?? (15 * 60)
|
||
keyboardSessionEnabled = true
|
||
keyboardSessionExpiresAt = now() + seconds
|
||
keyboardSessionRemaining = seconds
|
||
}
|
||
|
||
private func refreshWarmExpiry() {
|
||
guard keyboardSessionEnabled, let seconds = warmDuration.seconds else { return }
|
||
keyboardSessionExpiresAt = now() + seconds
|
||
keyboardSessionRemaining = seconds
|
||
}
|
||
|
||
// MARK: - Model Preparation
|
||
|
||
/// `fallbacksLeft` bounds how often Automatic moves on to another language after one
|
||
/// whose model won't install here; each move sets a language aside, so it can't loop.
|
||
func prepareModel(fallbacksLeft: Int = 2) {
|
||
modelPrepGeneration &+= 1
|
||
let prepGen = modelPrepGeneration
|
||
phase = .preparingModel
|
||
copied = false
|
||
modelPreparation = ModelPreparationProgress(
|
||
fractionCompleted: 0,
|
||
detail: String(localized: "Checking the speech model")
|
||
)
|
||
preparationFailedInBackground = false
|
||
// A few more seconds from iOS when Hex goes to the background mid-download or mid-compile.
|
||
let backgroundTime = BackgroundTime("Prepare speech model")
|
||
|
||
Task {
|
||
defer { backgroundTime.end() }
|
||
do {
|
||
let candidate = await transcriberFactory()
|
||
guard self.modelPrepGeneration == prepGen else { return }
|
||
engineName = candidate.displayName
|
||
try await candidate.prepare { [weak self] progress in
|
||
Task { @MainActor [weak self] in
|
||
guard let self, self.modelPrepGeneration == prepGen else { return }
|
||
self.modelPreparation = progress
|
||
}
|
||
}
|
||
guard self.modelPrepGeneration == prepGen else { return }
|
||
self.languageOffer = nil
|
||
self.transcriber = candidate
|
||
self.transcriptionLanguage = await candidate.languageName
|
||
self.transcriptionLanguageID = await candidate.languageIdentifier
|
||
self.keyboardBridge.setModelInstalled(true)
|
||
self.isModelReady = true
|
||
self.phase = .ready
|
||
self.publishKeyboardSnapshot()
|
||
if self.pendingHandoff != nil {
|
||
self.activateWarmSessionAndRunHandoff()
|
||
}
|
||
} catch {
|
||
guard self.modelPrepGeneration == prepGen else { return }
|
||
let unavailable = error as? SpeechModelUnavailable
|
||
if fallbacksLeft > 0, let notice = Self.switchNotice(for: error) {
|
||
// Automatic set the language aside, or Parakeet had no room: prepare what
|
||
// Hex picks now.
|
||
self.languageNotice = notice
|
||
self.prepareModel(fallbacksLeft: fallbacksLeft - 1)
|
||
return
|
||
}
|
||
self.languageOffer = unavailable.flatMap { $0.automatic ? nil : $0.fallback }
|
||
self.preparationFailedInBackground = self.isInBackground && Self.isDownloadInterruption(error)
|
||
self.keyboardBridge.setModelInstalled(ParakeetTranscriber.hasCachedModel)
|
||
self.pendingHandoff = nil
|
||
self.phase = .failed(UserFacingError.message(for: error, context: .model))
|
||
self.publishKeyboardSnapshot()
|
||
}
|
||
}
|
||
}
|
||
|
||
func appMovedToBackground() {
|
||
isInBackground = true
|
||
}
|
||
|
||
/// Picks up a download that iOS cut off while Hex was in the background; FluidAudio
|
||
/// resumes each file from the bytes it has.
|
||
func appBecameActive() {
|
||
isInBackground = false
|
||
guard preparationFailedInBackground else { return }
|
||
preparationFailedInBackground = false
|
||
if case .failed = phase, !isModelReady {
|
||
prepareModel()
|
||
}
|
||
}
|
||
|
||
nonisolated static func isDownloadInterruption(_ error: Error) -> Bool {
|
||
if error is StallWatch.Stalled || error is URLError { return true }
|
||
if (error as? ParakeetUltraTranscriber.TranscriberError) == .downloadFailed { return true }
|
||
return (error as? ParakeetTranscriber.TranscriberError) == .downloadFailed
|
||
}
|
||
|
||
// MARK: - Capture & Generation-Scoped Transcription
|
||
|
||
func startRecording(
|
||
keyboardJobID: String? = nil,
|
||
styleOverride: DictationStyle? = nil,
|
||
copyToPasteboard: Bool = false
|
||
) {
|
||
guard activeCapture == nil else { return }
|
||
if let keyboardJobID, keyboardJobID == activeKeyboardJobID {
|
||
return
|
||
}
|
||
activeKeyboardJobID = keyboardJobID
|
||
if keyboardJobID != nil {
|
||
keyboardMessage = nil
|
||
}
|
||
|
||
// Bumping generation invalidates any stale winding-down transcription task so it can never
|
||
// overwrite our new capture's phase, job state, or temporary WAV file.
|
||
jobGeneration &+= 1
|
||
let captureGeneration = jobGeneration
|
||
transcriptionTask?.cancel()
|
||
transcriptionTask = nil
|
||
let effectiveStyle = styleOverride ?? style
|
||
let usesCleanup = cleanupSettings.isEnabled
|
||
let lowercase = lowercaseSettings.isEnabled
|
||
let formatLists = listSettings.isEnabled
|
||
let spokenPunctuation = punctuationSettings.isEnabled
|
||
let endsWithPeriod = periodSettings.isEnabled
|
||
let hinglish = hinglishSettings.isEnabled
|
||
let language = transcriptionLanguageID
|
||
CleanupTagger.prepareIfEnabled(style: effectiveStyle, language: language)
|
||
let vocabularyTerms = customVocabularySettings.activeTerms
|
||
let personalCorrections = learnedDictationCorrections(language)
|
||
let recognitionHints = DictationCorrections.recognitionHints(
|
||
vocabulary: vocabularyTerms,
|
||
corrections: personalCorrections
|
||
)
|
||
let sharesHeard = typingJournalSettings.isEnabled
|
||
|
||
phase = .requestingPermission
|
||
copied = false
|
||
|
||
Task {
|
||
let granted = await audio.requestPermission()
|
||
guard self.jobGeneration == captureGeneration else { return }
|
||
guard granted else {
|
||
activeKeyboardJobID = nil
|
||
let message = String(localized: "Microphone access is off. Allow it in Settings.")
|
||
keyboardMessage = keyboardJobID == nil ? nil : message
|
||
phase = .failed(message)
|
||
publishKeyboardSnapshot()
|
||
return
|
||
}
|
||
|
||
let captureURL = fileManager.temporaryDirectory
|
||
.appendingPathComponent("hex-dictation-\(captureGeneration)-\(UUID().uuidString)")
|
||
.appendingPathExtension("wav")
|
||
|
||
do {
|
||
let capture = try audio.beginCapture(
|
||
at: captureURL,
|
||
maxDuration: Self.maxCaptureDuration,
|
||
microphone: microphone
|
||
)
|
||
guard self.jobGeneration == captureGeneration else {
|
||
capture.stop()
|
||
try? fileManager.removeItem(at: captureURL)
|
||
return
|
||
}
|
||
|
||
let startedAt = now()
|
||
activeCapture = ActiveCaptureSession(
|
||
generation: captureGeneration,
|
||
capture: capture,
|
||
startedAt: startedAt,
|
||
keyboardJobID: keyboardJobID,
|
||
style: effectiveStyle,
|
||
usesCleanup: usesCleanup,
|
||
lowercase: lowercase,
|
||
formatLists: formatLists,
|
||
spokenPunctuation: spokenPunctuation,
|
||
endsWithPeriod: endsWithPeriod,
|
||
hinglish: hinglish,
|
||
vocabularyTerms: vocabularyTerms,
|
||
personalCorrections: personalCorrections,
|
||
recognitionHints: recognitionHints,
|
||
sharesHeard: sharesHeard,
|
||
copyToPasteboard: copyToPasteboard,
|
||
language: language
|
||
)
|
||
refreshWarmExpiry()
|
||
audioLevel = 0
|
||
loudnessDB = -120
|
||
recordingDuration = 0
|
||
phase = .recording
|
||
// Only the Action Button, Control Center, and Siri (the dictations that copy)
|
||
// get a Live Activity: the keyboard and the app show their own recording UI.
|
||
if copyToPasteboard {
|
||
liveActivity.startRecording(startedAt: Date(timeIntervalSince1970: startedAt))
|
||
}
|
||
startMetering(for: captureGeneration)
|
||
publishKeyboardSnapshot()
|
||
} catch {
|
||
try? fileManager.removeItem(at: captureURL)
|
||
activeKeyboardJobID = nil
|
||
let message = UserFacingError.message(for: error, context: .microphone)
|
||
keyboardMessage = keyboardJobID == nil ? nil : message
|
||
phase = .failed(message)
|
||
captureFailed = isModelReady
|
||
restoreAudioAfterCapture()
|
||
publishKeyboardSnapshot()
|
||
}
|
||
}
|
||
}
|
||
|
||
func finishRecording() {
|
||
guard let session = activeCapture else { return }
|
||
activeCapture = nil
|
||
|
||
stopMetering()
|
||
let finalDuration = max(recordingDuration, session.capture.currentTime)
|
||
session.capture.stop()
|
||
audioLevel = 0
|
||
loudnessDB = -120
|
||
|
||
let captureURL = session.capture.url
|
||
let captureGeneration = session.generation
|
||
let keyboardJobID = session.keyboardJobID
|
||
|
||
guard finalDuration >= Self.minCaptureDuration else {
|
||
try? fileManager.removeItem(at: captureURL)
|
||
recordingDuration = 0
|
||
activeKeyboardJobID = nil
|
||
keyboardMessage = nil
|
||
phase = .ready
|
||
liveActivity.endImmediately()
|
||
restoreAudioAfterCapture()
|
||
publishKeyboardSnapshot()
|
||
prepareDeferredLanguageIfNeeded()
|
||
return
|
||
}
|
||
|
||
phase = .transcribing
|
||
liveActivity.markTranscribing(startedAt: Date(timeIntervalSince1970: session.startedAt))
|
||
restoreAudioAfterCapture()
|
||
publishKeyboardSnapshot()
|
||
|
||
let activeTranscriber = transcriber
|
||
// A keyboard's dictation finishes with Hex in the background, and in One shot nothing
|
||
// keeps Hex running once the microphone closes: iOS would suspend it mid-transcription
|
||
// and the text would never reach the keyboard.
|
||
let backgroundTime = keyboardJobID == nil ? nil : BackgroundTime("Keyboard dictation")
|
||
|
||
transcriptionTask?.cancel()
|
||
transcriptionTask = Task { [weak self] in
|
||
defer {
|
||
try? FileManager.default.removeItem(at: captureURL)
|
||
backgroundTime?.end()
|
||
}
|
||
let transcribeStarted = Date()
|
||
|
||
do {
|
||
let rawText = try await activeTranscriber.transcribe(
|
||
captureURL,
|
||
vocabulary: session.recognitionHints
|
||
)
|
||
guard let self, self.jobGeneration == captureGeneration, !Task.isCancelled else {
|
||
return
|
||
}
|
||
// The steps in-keyboard dictation runs too, plus Apple Intelligence's cleanup.
|
||
let pipeline = DictationPipeline(
|
||
style: session.style,
|
||
language: session.language,
|
||
vocabulary: session.vocabularyTerms,
|
||
corrections: session.personalCorrections,
|
||
lowercase: session.lowercase,
|
||
formatLists: session.formatLists,
|
||
spokenPunctuation: session.spokenPunctuation,
|
||
hinglish: session.hinglish,
|
||
endsWithPeriod: session.endsWithPeriod
|
||
)
|
||
let stages = await pipeline.run(rawText) { tagged in
|
||
await self.cleanedTranscriptIfEnabled(tagged, session: session)
|
||
}
|
||
let translated = stages.translated
|
||
guard self.jobGeneration == captureGeneration, !Task.isCancelled else {
|
||
return
|
||
}
|
||
let formatted = stages.formatted
|
||
self.recordingDuration = 0
|
||
self.transcript = formatted
|
||
if session.copyToPasteboard && !formatted.isEmpty {
|
||
UIPasteboard.general.string = formatted
|
||
self.copied = true
|
||
self.liveActivity.finishCopied()
|
||
} else {
|
||
self.liveActivity.endImmediately()
|
||
}
|
||
|
||
if keyboardJobID != nil {
|
||
self.keyboardResultID = UUID().uuidString
|
||
self.keyboardResult = formatted
|
||
// A translation's words can't be compared with what was heard.
|
||
self.keyboardResultHeard = session.sharesHeard && translated == nil ? stages.heard : nil
|
||
self.keyboardResultTranslationFailure = stages.translationFailure
|
||
self.keyboardResultStages = TypingLogSettings().isEnabled
|
||
? DictationStages(
|
||
engine: self.engineName,
|
||
language: self.transcriptionLanguage,
|
||
style: session.style.rawValue,
|
||
recordedMS: Int((finalDuration * 1000).rounded()),
|
||
transcribeMS: Int((Date().timeIntervalSince(transcribeStarted) * 1000).rounded()),
|
||
raw: rawText,
|
||
fixed: stages.fixed,
|
||
spelled: stages.spelled,
|
||
tagged: CleanupTaggerSettings().isEnabled && session.style != .verbatim ? stages.tagged : nil,
|
||
cleaned: session.usesCleanup && session.style != .verbatim ? stages.cleaned : nil,
|
||
translated: translated,
|
||
formatted: formatted
|
||
)
|
||
: nil
|
||
self.keyboardResultExpiresAt = self.now() + Self.resultDeliveryTTL
|
||
self.keyboardMessage = nil
|
||
}
|
||
self.activeKeyboardJobID = nil
|
||
self.refreshWarmExpiry()
|
||
self.phase = .ready
|
||
self.publishKeyboardSnapshot()
|
||
self.prepareDeferredLanguageIfNeeded()
|
||
} catch {
|
||
guard !Task.isCancelled, let self, self.jobGeneration == captureGeneration else {
|
||
return
|
||
}
|
||
self.recordingDuration = 0
|
||
self.activeKeyboardJobID = nil
|
||
self.liveActivity.endImmediately()
|
||
// Nothing was said: end quietly, as a capture too short to hold a word does.
|
||
if EmptyCapture.endsQuietly(error) {
|
||
self.keyboardMessage = nil
|
||
self.refreshWarmExpiry()
|
||
self.phase = .ready
|
||
self.publishKeyboardSnapshot()
|
||
return
|
||
}
|
||
let message = UserFacingError.message(for: error, context: .transcription)
|
||
self.keyboardMessage = keyboardJobID == nil ? nil : message
|
||
self.phase = .failed(message)
|
||
self.publishKeyboardSnapshot()
|
||
self.prepareDeferredLanguageIfNeeded()
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The cleanup experiment's one pass, before formatting. Any failure keeps the raw text.
|
||
private func cleanedTranscriptIfEnabled(
|
||
_ rawText: String,
|
||
session: ActiveCaptureSession
|
||
) async -> String {
|
||
guard session.usesCleanup,
|
||
session.style != .verbatim,
|
||
!rawText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
|
||
let cleaner,
|
||
cleaner.isAvailable,
|
||
cleaner.supports(language: session.language) else {
|
||
return rawText
|
||
}
|
||
return await cleaner.clean(rawText) ?? rawText
|
||
}
|
||
|
||
private func restoreAudioAfterCapture() {
|
||
if keyboardSessionEnabled, let seconds = warmDuration.seconds, seconds > 0 {
|
||
let remaining = keyboardSessionExpiresAt - now()
|
||
if remaining <= 0 {
|
||
keyboardSessionEnabled = false
|
||
keyboardSessionRemaining = 0
|
||
keyboardSessionExpiresAt = 0
|
||
audio.deactivateSession()
|
||
return
|
||
}
|
||
do {
|
||
try audio.startKeepalive()
|
||
} catch {
|
||
keyboardSessionEnabled = false
|
||
keyboardSessionRemaining = 0
|
||
keyboardSessionExpiresAt = 0
|
||
keyboardMessage = UserFacingError.message(for: error, context: .microphone)
|
||
audio.deactivateSession()
|
||
}
|
||
} else {
|
||
keyboardSessionEnabled = false
|
||
keyboardSessionRemaining = 0
|
||
keyboardSessionExpiresAt = 0
|
||
audio.deactivateSession()
|
||
}
|
||
}
|
||
|
||
private func startMetering(for generation: UInt64) {
|
||
stopMetering()
|
||
meterTask = Task { [weak self] in
|
||
while !Task.isCancelled {
|
||
guard let self,
|
||
let session = self.activeCapture,
|
||
session.generation == generation else {
|
||
break
|
||
}
|
||
|
||
// Recorder readiness is a sample, not the capture's lifetime. A transient
|
||
// false must not strand the app meter and keyboard heartbeat until Stop.
|
||
// Completion/interruption callbacks and explicit Stop own capture teardown.
|
||
guard session.capture.isRecording else {
|
||
try? await Task.sleep(for: .milliseconds(33))
|
||
continue
|
||
}
|
||
|
||
let db = session.capture.averagePowerDB()
|
||
self.loudnessDB = db
|
||
self.audioLevel = max(0, min(1, (db + 48) / 48))
|
||
self.recordingDuration = session.capture.currentTime
|
||
self.publishKeyboardSnapshot(minInterval: 0.10)
|
||
|
||
if self.recordingDuration >= Self.maxCaptureDuration - 0.25 {
|
||
self.finishRecording()
|
||
return
|
||
}
|
||
|
||
try? await Task.sleep(for: .milliseconds(33))
|
||
}
|
||
}
|
||
}
|
||
|
||
private func stopMetering() {
|
||
meterTask?.cancel()
|
||
meterTask = nil
|
||
}
|
||
|
||
// MARK: - Warm Session Loop & Snapshot Truth
|
||
|
||
/// A keyboard's dictation is recording or transcribing: Hex reads its commands and
|
||
/// heartbeats its snapshot until the text is in, warm session or not (One shot).
|
||
private var keyboardJobInFlight: Bool {
|
||
activeKeyboardJobID != nil
|
||
}
|
||
|
||
/// Reads the keyboard's commands and keeps its snapshot's heartbeat fresh, for a warm
|
||
/// session and for any keyboard dictation in flight. The keyboard takes a job whose
|
||
/// heartbeat stops as over (`KeyboardSnapshot.isOrphanedJob`).
|
||
private func startKeyboardSessionLoop() {
|
||
keyboardSessionTask?.cancel()
|
||
keepaliveRestartedAt = -.infinity
|
||
keepaliveRestartDelay = 0
|
||
keepaliveRestartDue = nil
|
||
keyboardSessionTask = Task { [weak self] in
|
||
while !Task.isCancelled {
|
||
guard let self, self.keyboardSessionEnabled || self.keyboardJobInFlight else { return }
|
||
|
||
// Never expire an in-flight recording or accepted transcription mid-work.
|
||
if self.keyboardSessionEnabled, self.phase != .recording && self.phase != .transcribing {
|
||
// The keyboard's language switch writes the App Group; follow it.
|
||
self.followDictationLanguageSetting()
|
||
let remaining = self.keyboardSessionExpiresAt - self.now()
|
||
if remaining <= 0 {
|
||
self.endWarmSession()
|
||
return
|
||
}
|
||
self.keyboardSessionRemaining = remaining
|
||
|
||
// Verify the keepalive engine is genuinely alive so we never publish a stuck "Ready".
|
||
if self.audio.isKeepaliveRunning {
|
||
self.keepaliveRestartDue = nil
|
||
} else if self.phase == .ready && !self.suspendedWarmSessionOnInterruption,
|
||
self.keepaliveRestartIsDue() {
|
||
do {
|
||
try self.audio.startKeepalive()
|
||
} catch {
|
||
self.endWarmSession()
|
||
return
|
||
}
|
||
}
|
||
}
|
||
|
||
self.consumeKeyboardCommand()
|
||
if self.phase != .recording {
|
||
self.publishKeyboardSnapshot(minInterval: 0.60)
|
||
}
|
||
try? await Task.sleep(for: .milliseconds(100))
|
||
}
|
||
}
|
||
}
|
||
|
||
private func keepaliveRestartIsDue() -> Bool {
|
||
let time = now()
|
||
if keepaliveRestartDue == nil {
|
||
let stoppedSoon = time - keepaliveRestartedAt < Self.steadyKeepalive
|
||
keepaliveRestartDelay = stoppedSoon
|
||
? min(max(1, keepaliveRestartDelay * 2), Self.maxKeepaliveRestartDelay)
|
||
: 0
|
||
keepaliveRestartDue = time + keepaliveRestartDelay
|
||
}
|
||
guard let due = keepaliveRestartDue, time >= due else { return false }
|
||
keepaliveRestartDue = nil
|
||
keepaliveRestartedAt = time
|
||
return true
|
||
}
|
||
|
||
func processPendingKeyboardCommandForTesting() {
|
||
consumeKeyboardCommand()
|
||
publishKeyboardSnapshot()
|
||
}
|
||
|
||
func updateRecordingDurationForTesting(_ duration: TimeInterval) {
|
||
recordingDuration = duration
|
||
}
|
||
|
||
private func consumeKeyboardCommand() {
|
||
guard let command = keyboardBridge.latestCommand(),
|
||
command.id != lastKeyboardCommandID else { return }
|
||
lastKeyboardCommandID = command.id
|
||
|
||
// Ignore stale commands left in UserDefaults from >10s ago.
|
||
guard now() - command.sentAt <= KeyboardLaunchRequest.handoffWindow else { return }
|
||
|
||
switch command.kind {
|
||
case .start:
|
||
// A warm session whose microphone failed for the last dictation stays marked failed:
|
||
// the keyboard's next Hex key is its Try again. Without this Hex ignored every
|
||
// start until it was opened, while the keyboard kept sending them.
|
||
guard phase == .ready || captureFailed, activeKeyboardJobID == nil else { return }
|
||
setStyle(command.style)
|
||
startRecording(
|
||
keyboardJobID: command.jobID,
|
||
styleOverride: command.style,
|
||
copyToPasteboard: false
|
||
)
|
||
case .stop:
|
||
guard phase == .recording, activeKeyboardJobID == command.jobID else { return }
|
||
finishRecording()
|
||
case .cancel:
|
||
guard (phase == .recording || phase == .transcribing),
|
||
activeKeyboardJobID == command.jobID else { return }
|
||
cancelCurrentJob()
|
||
}
|
||
}
|
||
|
||
private func publishKeyboardSnapshot(minInterval: TimeInterval = 0) {
|
||
let currentTime = now()
|
||
|
||
// Past its time to go in by itself the keyboard can still offer it as Paste dictation.
|
||
if let expires = keyboardResultExpiresAt, expires + KeyboardSnapshot.resultOfferWindow <= currentTime {
|
||
keyboardResultID = nil
|
||
keyboardResult = nil
|
||
keyboardResultHeard = nil
|
||
keyboardResultTranslationFailure = nil
|
||
keyboardResultStages = nil
|
||
keyboardResultExpiresAt = nil
|
||
}
|
||
|
||
let state: KeyboardDictationState
|
||
switch phase {
|
||
case .recording:
|
||
// Hardware truth guard: only claim `.recording` while an active capture is genuinely recording.
|
||
if let session = activeCapture, session.capture.isRecording {
|
||
state = .recording
|
||
} else {
|
||
state = keyboardSessionEnabled ? .ready : .offline
|
||
}
|
||
case .transcribing:
|
||
state = .transcribing
|
||
case .failed:
|
||
state = .failed
|
||
case .modelRequired, .preparingModel, .requestingPermission:
|
||
state = .offline
|
||
case .ready:
|
||
state = (keyboardSessionEnabled && audio.isKeepaliveRunning) ? .ready : .offline
|
||
}
|
||
|
||
let failureMessage: String?
|
||
let messageAt: TimeInterval?
|
||
if case .failed(let message) = phase {
|
||
failureMessage = message
|
||
messageAt = failedAt
|
||
} else {
|
||
failureMessage = keyboardMessage
|
||
messageAt = keyboardMessageAt
|
||
}
|
||
|
||
let signature = "\(state.rawValue)|\(activeKeyboardJobID ?? "")|\(keyboardResultID ?? "")|\(failureMessage ?? "")"
|
||
if minInterval > 0,
|
||
signature == lastPublishedSnapshotSignature,
|
||
currentTime - lastPublishedSnapshotAt < minInterval {
|
||
return
|
||
}
|
||
lastPublishedSnapshotSignature = signature
|
||
lastPublishedSnapshotAt = currentTime
|
||
|
||
let effectiveHeartbeat: TimeInterval
|
||
if state == .recording || state == .transcribing || (keyboardSessionEnabled && audio.isKeepaliveRunning) {
|
||
effectiveHeartbeat = currentTime
|
||
} else {
|
||
effectiveHeartbeat = 0
|
||
}
|
||
|
||
keyboardBridge.publish(
|
||
KeyboardSnapshot(
|
||
state: state,
|
||
heartbeat: effectiveHeartbeat,
|
||
expiresAt: keyboardSessionEnabled ? keyboardSessionExpiresAt : 0,
|
||
recordingStartedAt: activeCapture?.startedAt,
|
||
audioLevel: state == .recording ? audioLevel : 0,
|
||
loudnessDB: state == .recording ? loudnessDB : nil,
|
||
jobID: activeKeyboardJobID,
|
||
resultID: keyboardResultID,
|
||
resultExpiresAt: keyboardResultExpiresAt,
|
||
transcript: keyboardResult,
|
||
message: failureMessage,
|
||
heard: keyboardResultHeard,
|
||
stages: keyboardResultStages,
|
||
translationFailure: keyboardResultTranslationFailure,
|
||
messageAt: failureMessage == nil ? nil : messageAt
|
||
)
|
||
)
|
||
}
|
||
|
||
// MARK: - Audio Interruptions, Route Changes, & System Intents
|
||
|
||
private func wireAudioCallbacks() {
|
||
audio.onUnexpectedCaptureEnd = { [weak self] finishedURL, succeeded in
|
||
guard let self,
|
||
let session = self.activeCapture,
|
||
session.capture.url == finishedURL else {
|
||
return
|
||
}
|
||
if succeeded {
|
||
self.finishRecording()
|
||
} else {
|
||
self.cancelCurrentJob()
|
||
self.phase = .failed(String(localized: "Recording stopped unexpectedly."))
|
||
self.publishKeyboardSnapshot()
|
||
}
|
||
}
|
||
|
||
audio.onSystemEvent = { [weak self] event in
|
||
self?.handleAudioSystemEvent(event)
|
||
}
|
||
}
|
||
|
||
func handleAudioSystemEvent(_ event: AudioSystemEvent) {
|
||
switch event {
|
||
case .interruptionBegan:
|
||
suspendedWarmSessionOnInterruption = keyboardSessionEnabled
|
||
if phase == .recording {
|
||
// Save spoken audio if >= 300ms; otherwise cancel cleanly so "Listening" never sticks during a call.
|
||
if let session = activeCapture, max(recordingDuration, session.capture.currentTime) >= Self.minCaptureDuration {
|
||
audio.stopKeepalive()
|
||
finishRecording()
|
||
} else {
|
||
cancelCurrentJob()
|
||
keyboardMessage = String(localized: "Interrupted")
|
||
}
|
||
} else {
|
||
audio.stopKeepalive()
|
||
}
|
||
publishKeyboardSnapshot()
|
||
|
||
case .interruptionEnded(let shouldResume):
|
||
guard suspendedWarmSessionOnInterruption else { return }
|
||
suspendedWarmSessionOnInterruption = false
|
||
guard keyboardSessionEnabled, keyboardSessionExpiresAt > now() else {
|
||
endWarmSession()
|
||
return
|
||
}
|
||
if shouldResume || UIApplication.shared.applicationState == .active {
|
||
do {
|
||
try audio.startKeepalive()
|
||
publishKeyboardSnapshot()
|
||
} catch {
|
||
endWarmSession()
|
||
}
|
||
} else {
|
||
endWarmSession()
|
||
}
|
||
|
||
case .routeOldDeviceUnavailable:
|
||
// e.g. AirPods placed in case: finish active speech >= 300ms or rebind keepalive tap to built-in mic.
|
||
if phase == .recording {
|
||
if let session = activeCapture, max(recordingDuration, session.capture.currentTime) >= Self.minCaptureDuration {
|
||
finishRecording()
|
||
} else {
|
||
cancelCurrentJob()
|
||
}
|
||
} else if keyboardSessionEnabled && phase == .ready {
|
||
do {
|
||
try audio.startKeepalive()
|
||
publishKeyboardSnapshot()
|
||
} catch {
|
||
endWarmSession()
|
||
}
|
||
}
|
||
|
||
case .routeNewDeviceAvailable:
|
||
// A headset or car that just connected can take the input: the keepalive goes back
|
||
// to the iPhone's microphone, on a fresh engine for the route's format.
|
||
if keyboardSessionEnabled && phase == .ready {
|
||
try? audio.startKeepalive()
|
||
publishKeyboardSnapshot()
|
||
}
|
||
|
||
case .mediaServicesReset:
|
||
if phase == .recording {
|
||
cancelCurrentJob()
|
||
}
|
||
if keyboardSessionEnabled {
|
||
do {
|
||
try audio.startKeepalive()
|
||
publishKeyboardSnapshot()
|
||
} catch {
|
||
endWarmSession()
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
private func wireSystemIntentBus() {
|
||
Task {
|
||
await HexSystemCommandBus.shared.register { [weak self] command in
|
||
guard let self else { return nil }
|
||
return await self.performSystemCommand(command)
|
||
}
|
||
}
|
||
}
|
||
|
||
private func performSystemCommand(_ command: HexSystemCommand) async -> String? {
|
||
switch command {
|
||
case .toggleDictation:
|
||
if phase == .recording {
|
||
finishRecording()
|
||
if let task = transcriptionTask {
|
||
await task.value
|
||
}
|
||
return transcript
|
||
}
|
||
followDictationLanguageSetting()
|
||
if phase == .modelRequired || isFailedPhase {
|
||
prepareModel()
|
||
}
|
||
if phase == .preparingModel {
|
||
try? await waitUntilReady(timeoutSeconds: 10)
|
||
}
|
||
guard phase == .ready else { return nil }
|
||
startRecording(copyToPasteboard: true)
|
||
return ""
|
||
|
||
case .stopDictation:
|
||
guard phase == .recording else { return transcript }
|
||
finishRecording()
|
||
if let task = transcriptionTask {
|
||
await task.value
|
||
}
|
||
return transcript
|
||
|
||
case .cancelDictation:
|
||
cancelCurrentJob()
|
||
return nil
|
||
|
||
case .warmSession:
|
||
if !keyboardSessionEnabled {
|
||
if warmDuration == .off {
|
||
setWarmDuration(.fifteenMinutes)
|
||
}
|
||
requestWarmSession()
|
||
}
|
||
return nil
|
||
}
|
||
}
|
||
|
||
private var isFailedPhase: Bool {
|
||
if case .failed = phase { return true }
|
||
return false
|
||
}
|
||
|
||
private func waitUntilReady(timeoutSeconds: TimeInterval) async throws {
|
||
let deadline = now() + timeoutSeconds
|
||
while phase == .preparingModel && now() < deadline {
|
||
try await Task.sleep(for: .milliseconds(100))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Background time from iOS while Hex finishes a keyboard's dictation, ended when it's done
|
||
/// or when iOS asks for it back.
|
||
@MainActor
|
||
private final class BackgroundTime {
|
||
private var id = UIBackgroundTaskIdentifier.invalid
|
||
|
||
init(_ name: String) {
|
||
id = UIApplication.shared.beginBackgroundTask(withName: name) { [weak self] in
|
||
self?.end()
|
||
}
|
||
}
|
||
|
||
func end() {
|
||
guard id != .invalid else { return }
|
||
UIApplication.shared.endBackgroundTask(id)
|
||
id = .invalid
|
||
}
|
||
}
|