mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS Privacy: Privacy policy and Support links, for App Review 5.1.1(i) App Review requires a privacy policy link inside the app. The Privacy page now has a card with two rows between Learn how I type and Advanced: - Privacy policy opens https://dev.anoma.ly/hex/privacy. - Support opens https://dev.anoma.ly/hex/iphone. Both open in Safari inside Hex (SFSafariViewController, SafariSheet). The URLs come from one base in HexLinks.swift (HexLinks.site). Moving to https://anoma.ly/hex is a one-line change once the site's production deploy serves those pages; https://anoma.ly/hex/privacy returns 404 today, while both dev.anoma.ly pages return 200. README's Privacy page entry says so. Verified: the build passes on an iPhone 18 Pro simulator (iOS 27.2). I looked at the settings-privacy render. A temporary, uncommitted hook opened the Privacy policy row's Safari sheet, which loaded the live dev.anoma.ly page. * iOS setup sheet: Continue, not Allow, before the microphone prompt App Review 5.1.1(iv) rejects a custom button that says "Allow" right before iOS's own permission prompt. The setup sheet's Microphone row had one. It now matches onboarding's Set up Hex page (#2058): the row says why ("For dictation", replacing "Required") and its button says Continue. Tapping Continue still calls requestMicrophone, so iOS asks right after. Allowed and Off are unchanged, and Off still shows Open Settings. New scene: --snap-state setup-sheet-microphone, the setup sheet before iOS has asked for the microphone. README's Setup and scene notes are updated. Verified: the build passes on an iPhone 18 Pro simulator (iOS 27.2). I looked at the setup-sheet-microphone render (For dictation, Continue) and the setup-sheet render (Allowed, no button). * iOS Privacy: Record typing logs says what it records and asks before turning on App Review 2.5.14 requires explicit consent before recording what people type. - The description now says what the feature records: "Records taps and the text you type for 14 days, on this iPhone, to export. Off by default." It replaces "Off by default. Stays on this iPhone to export" and fits on two lines. - Turning it on opens an alert before anything changes. Title: "Record typing logs?". Message: "Hex's keyboard will record each tap and the text you type or dictate with it, including the text around the cursor, for 14 days. The logs stay on this iPhone for you to export or delete. Password, code and card fields are never recorded." Turn On switches it on; Cancel leaves it off. Turning it off needs no dialog. The switch still writes only TypingLogSettings.isEnabled. - Every claim matches docs/typing-logs.md: touches on Hex's keys, the text each key produced, the text around the cursor, dictations, 14 days in the App Group, export and delete from Typing logs, and a "skipped" line only for password, one-time code and card fields. New scene: --snap-state settings-privacy-confirm opens the dialog (SettingsSnapshotFixture.confirmsTypingLogs). README and docs/typing-logs.md now describe the consent and the new path (Privacy › Advanced, no longer Experiments). Verified: the build passes on an iPhone 18 Pro simulator (iOS 27.2). I looked at the settings-privacy, settings-privacy-confirm and settings-privacy-on renders. * iOS home: Privacy policy and Support join Acknowledgements #2059 added an Acknowledgements row at the bottom of home's utility card. The privacy policy and support links read better beside it than on the Privacy page. Home's last card now has Privacy policy (hand.raised, ↗), Support (questionmark.circle, ↗) and Acknowledgements (doc.text, ›). Keyboard settings and Run setup again keep their own card above it. - Moved, not duplicated: the Privacy page's links card is removed. That page is back to "Everything stays on this iPhone", Learn how I type, and Advanced. - Links still come from HexLinks (dev.anoma.ly until production serves anoma.ly/hex/privacy) and open in Safari inside Hex. - README's Settings section now lists the links on home. Verified: the build passes on an iPhone 18 Pro simulator (iOS 27.2). I looked at the settings-home render, which still fits one screen without scrolling, and the settings-privacy render.
1579 lines
61 KiB
Swift
1579 lines
61 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
|
||
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 typingJournalSettings: TypingJournalSettings
|
||
private let learnedDictationCorrections: @MainActor () -> [DictationCorrection]
|
||
private let audio: any AudioManaging
|
||
private 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?
|
||
/// Record typing logs: each step of the result, for the keyboard's log; nil while off.
|
||
private var keyboardResultStages: DictationStages?
|
||
private var keyboardMessage: String?
|
||
private var pendingHandoff: PendingKeyboardHandoff?
|
||
private var keyboardSessionExpiresAt: TimeInterval = 0
|
||
private var suspendedWarmSessionOnInterruption = false
|
||
|
||
private(set) var phase = Phase.modelRequired {
|
||
didSet {
|
||
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
|
||
}
|
||
}
|
||
private(set) var isModelReady = false
|
||
private(set) var transcript = ""
|
||
@ObservationIgnored private(set) var audioLevel: Float = 0
|
||
@ObservationIgnored private(set) var loudnessDB: Float = -120
|
||
@ObservationIgnored private var rawRecordingDuration: TimeInterval = 0
|
||
private(set) var recordingWholeSeconds: Int = 0
|
||
private(set) var recordingDuration: TimeInterval {
|
||
get { rawRecordingDuration }
|
||
set {
|
||
rawRecordingDuration = newValue
|
||
let whole = max(0, Int(newValue))
|
||
if recordingWholeSeconds != whole {
|
||
recordingWholeSeconds = whole
|
||
}
|
||
}
|
||
}
|
||
private(set) var copied = false
|
||
private(set) var keyboardSessionEnabled = false
|
||
@ObservationIgnored private var rawKeyboardSessionRemaining: TimeInterval = 0
|
||
private(set) var keyboardSessionDisplayRemaining = "0:00"
|
||
private(set) 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
|
||
private(set) var warmDuration: WarmSessionDuration
|
||
private(set) var style: DictationStyle
|
||
private(set) var allowBluetoothMic: Bool
|
||
private(set) var handoffNotice: String?
|
||
private(set) var engineName = "Local speech"
|
||
private(set) var transcriptionLanguage = "English"
|
||
/// The BCP 47 identifier of `transcriptionLanguage`, for the steps that depend on it.
|
||
private(set) var transcriptionLanguageID = "en-US"
|
||
/// Settings › Dictation language: a BCP 47 identifier, or nil for Automatic.
|
||
private(set) var dictationLanguage: 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.").
|
||
private(set) var languageNotice: String?
|
||
/// The language to offer (BCP 47) when the one chosen can't be dictated here yet.
|
||
private(set) var languageOffer: String?
|
||
private let languageSettings: LanguageSettings
|
||
private(set) var modelPreparation = ModelPreparationProgress(
|
||
fractionCompleted: 0,
|
||
detail: "Checking model files"
|
||
)
|
||
|
||
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(),
|
||
typingJournalSettings: TypingJournalSettings = TypingJournalSettings(),
|
||
learnedDictationCorrections: (@MainActor () -> [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.typingJournalSettings = typingJournalSettings
|
||
self.learnedDictationCorrections = learnedDictationCorrections ?? {
|
||
TypingJournal.storedDictationCorrections(settings: typingJournalSettings)
|
||
}
|
||
self.fileManager = fileManager
|
||
self.now = now
|
||
self.languageSettings = languageSettings
|
||
self.dictationLanguage = languageSettings.dictationLanguage
|
||
self.warmDuration = resolvedBridge.warmDuration
|
||
self.style = resolvedBridge.style
|
||
self.allowBluetoothMic = resolvedBridge.allowBluetoothMic
|
||
|
||
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 {
|
||
// A launch after Hex ended while loading Parakeet doesn't load it again by itself,
|
||
// or it would end the same way at every launch.
|
||
let parakeetLoads = ParakeetLoadGuard()
|
||
parakeetLoads.noteLaunch()
|
||
let parakeetInterrupted = parakeetLoads.lastLoadWasInterrupted
|
||
if hasCachedModel && !parakeetInterrupted {
|
||
engineName = "Parakeet V2"
|
||
prepareModel()
|
||
} else if #available(iOS 26.0, *) {
|
||
Task { [weak self] in
|
||
guard let self else { return }
|
||
if let language = await AppleSpeechTranscriber.preferredLanguage(),
|
||
AppleSpeechTranscriber.shouldUse(language) {
|
||
self.engineName = "Apple Speech"
|
||
self.prepareModel()
|
||
} else {
|
||
self.engineName = "Parakeet V2"
|
||
if hasCachedModel {
|
||
self.phase = .failed(ParakeetLoadGuard.message)
|
||
}
|
||
}
|
||
}
|
||
} else if hasCachedModel {
|
||
engineName = "Parakeet V2"
|
||
phase = .failed(ParakeetLoadGuard.message)
|
||
}
|
||
}
|
||
}
|
||
|
||
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.
|
||
func followDictationLanguageSetting() {
|
||
let stored = languageSettings.dictationLanguage
|
||
guard stored != dictationLanguage 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
|
||
languageNotice = nil
|
||
languageOffer = nil
|
||
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
|
||
}
|
||
}
|
||
|
||
func setAllowBluetoothMic(_ allow: Bool) {
|
||
guard allowBluetoothMic != allow else { return }
|
||
allowBluetoothMic = allow
|
||
keyboardBridge.allowBluetoothMic = allow
|
||
if keyboardSessionEnabled, phase == .ready {
|
||
try? audio.startKeepalive(allowBluetooth: allow)
|
||
}
|
||
}
|
||
|
||
// 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()
|
||
}
|
||
|
||
/// 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 case .setup = request {
|
||
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 = "Timed out"
|
||
pendingHandoff = PendingKeyboardHandoff(
|
||
jobID: nil,
|
||
style: style,
|
||
requestedAt: currentTime
|
||
)
|
||
fulfillPendingHandoffOrPrepare()
|
||
return
|
||
}
|
||
|
||
switch request {
|
||
case .setup:
|
||
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 = "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
|
||
)
|
||
} else {
|
||
handoffNotice = "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 = "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("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 = "Timed out"
|
||
}
|
||
|
||
do {
|
||
try audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||
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: "Checking model files"
|
||
)
|
||
|
||
Task {
|
||
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 let unavailable, unavailable.switchedAutomatically, fallbacksLeft > 0 {
|
||
// Automatic set the language aside: prepare the one it picks now.
|
||
self.languageNotice = UserFacingError.message(for: unavailable, context: .model)
|
||
self.prepareModel(fallbacksLeft: fallbacksLeft - 1)
|
||
return
|
||
}
|
||
self.languageOffer = unavailable.flatMap { $0.automatic ? nil : $0.fallback }
|
||
self.keyboardBridge.setModelInstalled(ParakeetTranscriber.hasCachedModel)
|
||
self.pendingHandoff = nil
|
||
self.phase = .failed(UserFacingError.message(for: error, context: .model))
|
||
self.publishKeyboardSnapshot()
|
||
}
|
||
}
|
||
}
|
||
|
||
private static func defaultTranscriber() async -> any LocalTranscribing {
|
||
if #available(iOS 26.0, *),
|
||
let language = await AppleSpeechTranscriber.preferredLanguage(),
|
||
AppleSpeechTranscriber.shouldUse(language) {
|
||
return AppleSpeechTranscriber(language: language)
|
||
}
|
||
return ParakeetTranscriber()
|
||
}
|
||
|
||
// 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 language = transcriptionLanguageID
|
||
CleanupTagger.prepareIfEnabled(style: effectiveStyle, language: language)
|
||
let vocabularyTerms = customVocabularySettings.activeTerms
|
||
let personalCorrections = learnedDictationCorrections()
|
||
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 = "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,
|
||
allowBluetooth: allowBluetoothMic
|
||
)
|
||
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,
|
||
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)
|
||
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
|
||
|
||
transcriptionTask?.cancel()
|
||
transcriptionTask = Task { [weak self] in
|
||
defer {
|
||
try? FileManager.default.removeItem(at: captureURL)
|
||
}
|
||
let transcribeStarted = Date()
|
||
|
||
do {
|
||
let rawText = try await activeTranscriber.transcribe(
|
||
captureURL,
|
||
vocabulary: session.recognitionHints
|
||
)
|
||
guard let self, self.jobGeneration == captureGeneration, !Task.isCancelled else {
|
||
return
|
||
}
|
||
// Learned fixes run first, on the words as heard. Spelling runs before
|
||
// optional cleanup so cleanup sees the preferred words, then again after
|
||
// formatting because a style can lowercase a term or capitalize a
|
||
// sentence start ("iPhone" -> "IPhone"); learned capitals get the same.
|
||
let corrected = DictationCorrections.apply(session.personalCorrections, to: rawText)
|
||
let spelled = VocabularySpelling.apply(session.vocabularyTerms, to: corrected)
|
||
let tagged = await CleanupTagger.cleanIfEnabled(spelled, style: session.style, language: session.language)
|
||
let cleaned = await self.cleanedTranscriptIfEnabled(tagged, session: session)
|
||
let translated = await DictationTranslator.translateIfEnabled(
|
||
cleaned,
|
||
source: Locale(identifier: session.language).language
|
||
)
|
||
let text = translated ?? cleaned
|
||
guard self.jobGeneration == captureGeneration, !Task.isCancelled else {
|
||
return
|
||
}
|
||
// A translation is formatted in the language it is now in.
|
||
let formatLanguage = translated == nil
|
||
? session.language
|
||
: DictationTranslationSettings().targetLanguage
|
||
let formatted = VocabularySpelling.apply(
|
||
session.vocabularyTerms + DictationCorrections.spellings(session.personalCorrections),
|
||
to: TranscriptFormatter.format(text, style: session.style, language: formatLanguage)
|
||
)
|
||
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 ? rawText : nil
|
||
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: corrected,
|
||
spelled: spelled,
|
||
tagged: CleanupTaggerSettings().isEnabled && session.style != .verbatim ? tagged : nil,
|
||
cleaned: session.usesCleanup && session.style != .verbatim ? 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(allowBluetooth: allowBluetoothMic)
|
||
} 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
|
||
|
||
private func startKeyboardSessionLoop() {
|
||
keyboardSessionTask?.cancel()
|
||
keyboardSessionTask = Task { [weak self] in
|
||
while !Task.isCancelled {
|
||
guard let self, self.keyboardSessionEnabled else { return }
|
||
|
||
// Never expire an in-flight recording or accepted transcription mid-work.
|
||
if 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.phase == .ready && !self.audio.isKeepaliveRunning && !self.suspendedWarmSessionOnInterruption {
|
||
do {
|
||
try self.audio.startKeepalive(allowBluetooth: self.allowBluetoothMic)
|
||
} catch {
|
||
self.endWarmSession()
|
||
return
|
||
}
|
||
}
|
||
}
|
||
|
||
self.consumeKeyboardCommand()
|
||
if self.phase != .recording {
|
||
self.publishKeyboardSnapshot(minInterval: 0.60)
|
||
}
|
||
try? await Task.sleep(for: .milliseconds(100))
|
||
}
|
||
}
|
||
}
|
||
|
||
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:
|
||
guard phase == .ready, 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()
|
||
|
||
if let expires = keyboardResultExpiresAt, expires <= currentTime {
|
||
keyboardResultID = nil
|
||
keyboardResult = nil
|
||
keyboardResultHeard = 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?
|
||
if case .failed(let message) = phase {
|
||
failureMessage = message
|
||
} else {
|
||
failureMessage = keyboardMessage
|
||
}
|
||
|
||
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
|
||
)
|
||
)
|
||
}
|
||
|
||
// 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("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 = "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(allowBluetooth: allowBluetoothMic)
|
||
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(allowBluetooth: allowBluetoothMic)
|
||
publishKeyboardSnapshot()
|
||
} catch {
|
||
endWarmSession()
|
||
}
|
||
}
|
||
|
||
case .routeNewDeviceAvailable:
|
||
if keyboardSessionEnabled && phase == .ready && allowBluetoothMic {
|
||
try? audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||
publishKeyboardSnapshot()
|
||
}
|
||
|
||
case .mediaServicesReset:
|
||
if phase == .recording {
|
||
cancelCurrentJob()
|
||
}
|
||
if keyboardSessionEnabled {
|
||
do {
|
||
try audio.startKeepalive(allowBluetooth: allowBluetoothMic)
|
||
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))
|
||
}
|
||
}
|
||
|
||
// MARK: - Launch Fixtures for Simulator Verification (`--snap-state <name>`)
|
||
|
||
private static func applyLaunchFixtureIfPresent(to controller: DictationController) -> Bool {
|
||
let args = ProcessInfo.processInfo.arguments
|
||
guard let flagIndex = args.firstIndex(of: "--snap-state"),
|
||
flagIndex + 1 < args.count else {
|
||
return false
|
||
}
|
||
let scene = args[flagIndex + 1]
|
||
controller.engineName = "Apple Speech"
|
||
controller.transcriptionLanguage = "English"
|
||
controller.transcriptionLanguageID = "en-US"
|
||
controller.keyboardBridge.setModelInstalled(true)
|
||
controller.isModelReady = true
|
||
|
||
switch scene {
|
||
case "setup", "setup-sheet", "setup-sheet-microphone", _ where scene.hasPrefix("onboarding-") || scene.hasPrefix("settings-"):
|
||
controller.phase = .ready
|
||
controller.warmDuration = .fifteenMinutes
|
||
controller.keyboardSessionEnabled = false
|
||
|
||
case "language-unavailable":
|
||
// Russian picked by hand on an iPhone whose Apple Speech can't install it.
|
||
let unavailable = SpeechModelUnavailable(
|
||
language: "ru-RU",
|
||
reason: .notOnThisIPhone,
|
||
fallback: "en-US",
|
||
automatic: false
|
||
)
|
||
controller.isModelReady = false
|
||
controller.engineName = "Apple Speech"
|
||
controller.phase = .failed(UserFacingError.message(for: unavailable, context: .model))
|
||
controller.languageOffer = "en-US"
|
||
|
||
case "language-switched":
|
||
// Automatic moved on from Russian to English.
|
||
let unavailable = SpeechModelUnavailable(language: "ru-RU", reason: .notOnThisIPhone, fallback: "en-US")
|
||
controller.phase = .ready
|
||
controller.languageNotice = UserFacingError.message(for: unavailable, context: .model)
|
||
|
||
case "ready":
|
||
controller.phase = .ready
|
||
controller.warmDuration = .off
|
||
controller.keyboardSessionEnabled = false
|
||
controller.transcript = "Meet at ten on Thursday and bring the updated design notes."
|
||
|
||
case "warm":
|
||
controller.phase = .ready
|
||
controller.warmDuration = .fifteenMinutes
|
||
controller.keyboardSessionEnabled = true
|
||
controller.keyboardSessionRemaining = 14 * 60 + 42
|
||
controller.keyboardSessionExpiresAt = Date().timeIntervalSince1970 + 14 * 60 + 42
|
||
controller.transcript = "Meet at ten on Thursday and bring the updated design notes."
|
||
|
||
case "recording":
|
||
controller.phase = .recording
|
||
controller.warmDuration = .fifteenMinutes
|
||
controller.audioLevel = 0.74
|
||
controller.loudnessDB = -31.0
|
||
controller.recordingDuration = 6.4
|
||
controller.keyboardSessionEnabled = true
|
||
controller.keyboardSessionRemaining = 14 * 60 + 54
|
||
|
||
case "transcribing":
|
||
controller.phase = .transcribing
|
||
controller.warmDuration = .fifteenMinutes
|
||
controller.keyboardSessionEnabled = true
|
||
controller.keyboardSessionRemaining = 14 * 60 + 52
|
||
|
||
case "handoff-listening", "handoff-no-home-bar":
|
||
controller.phase = .recording
|
||
controller.audioLevel = 0.68
|
||
controller.loudnessDB = -32.5
|
||
controller.recordingDuration = 3.2
|
||
controller.keyboardSessionEnabled = true
|
||
controller.keyboardSessionRemaining = 14 * 60 + 57
|
||
Task { @MainActor in
|
||
let start = Date().timeIntervalSince1970 - 3.0
|
||
var simTime: Float = 0.0
|
||
while !Task.isCancelled {
|
||
controller.loudnessDB = DotScopeSimulation.demoLoudness(at: simTime) + 4.5
|
||
controller.recordingDuration = Date().timeIntervalSince1970 - start
|
||
simTime += 0.033
|
||
try? await Task.sleep(for: .milliseconds(33))
|
||
}
|
||
}
|
||
|
||
case "handoff-tour":
|
||
controller.phase = .recording
|
||
controller.audioLevel = 0.68
|
||
controller.loudnessDB = -32.0
|
||
controller.recordingDuration = 0.0
|
||
controller.keyboardSessionEnabled = true
|
||
controller.keyboardSessionRemaining = 14 * 60 + 58
|
||
Task { @MainActor in
|
||
let boot = Date().timeIntervalSince1970
|
||
var simTime: Float = 0.0
|
||
while !Task.isCancelled {
|
||
let elapsed = Date().timeIntervalSince1970 - boot
|
||
if elapsed < 3.4 {
|
||
if controller.phase != .recording {
|
||
withAnimation(HexMotion.stage) {
|
||
controller.phase = .recording
|
||
}
|
||
}
|
||
controller.loudnessDB = DotScopeSimulation.demoLoudness(at: simTime) + 4.5
|
||
controller.recordingDuration = elapsed
|
||
simTime += 0.033
|
||
} else if elapsed < 4.7 {
|
||
if controller.phase != .transcribing {
|
||
withAnimation(HexMotion.stage) {
|
||
controller.phase = .transcribing
|
||
}
|
||
}
|
||
controller.loudnessDB = -120.0
|
||
} else {
|
||
if controller.phase != .ready {
|
||
withAnimation(HexMotion.stage) {
|
||
controller.phase = .ready
|
||
}
|
||
}
|
||
}
|
||
try? await Task.sleep(for: .milliseconds(33))
|
||
}
|
||
}
|
||
|
||
case "hosted-keyboard-warm":
|
||
controller.phase = .ready
|
||
controller.warmDuration = .fifteenMinutes
|
||
controller.keyboardSessionEnabled = true
|
||
controller.keyboardSessionRemaining = 14 * 60 + 42
|
||
controller.keyboardSessionExpiresAt = Date().timeIntervalSince1970 + 14 * 60 + 42
|
||
Task { @MainActor in
|
||
while !Task.isCancelled {
|
||
let t = Date().timeIntervalSince1970
|
||
controller.keyboardBridge.publish(
|
||
KeyboardSnapshot(
|
||
state: .ready,
|
||
heartbeat: t,
|
||
expiresAt: t + 14 * 60 + 42
|
||
)
|
||
)
|
||
try? await Task.sleep(for: .milliseconds(250))
|
||
}
|
||
}
|
||
|
||
case "hosted-keyboard-recording", "hosted-keyboard-light":
|
||
controller.phase = .ready
|
||
controller.warmDuration = .fifteenMinutes
|
||
controller.keyboardSessionEnabled = true
|
||
controller.keyboardSessionRemaining = 14 * 60 + 55
|
||
let startWall = Date().timeIntervalSince1970 - 4.0
|
||
Task { @MainActor in
|
||
var simTime: Float = 0.4
|
||
while !Task.isCancelled {
|
||
let t = Date().timeIntervalSince1970
|
||
let db = -28.5 + 5.2 * sin(simTime * 19.0) + 2.4 * cos(simTime * 7.3)
|
||
controller.keyboardBridge.publish(
|
||
KeyboardSnapshot(
|
||
state: .recording,
|
||
heartbeat: t,
|
||
expiresAt: t + 15 * 60,
|
||
recordingStartedAt: startWall,
|
||
audioLevel: 0.78,
|
||
loudnessDB: db,
|
||
jobID: "hosted-demo-job"
|
||
)
|
||
)
|
||
simTime += 0.033
|
||
try? await Task.sleep(for: .milliseconds(33))
|
||
}
|
||
}
|
||
|
||
case "hosted-keyboard-tour":
|
||
controller.phase = .ready
|
||
controller.warmDuration = .fifteenMinutes
|
||
controller.keyboardSessionEnabled = true
|
||
controller.keyboardSessionRemaining = 14 * 60 + 58
|
||
Task { @MainActor in
|
||
let boot = Date().timeIntervalSince1970
|
||
let freshResultID = "hosted-tour-\(UUID().uuidString)"
|
||
var simTime: Float = 0.0
|
||
while !Task.isCancelled {
|
||
let t = Date().timeIntervalSince1970
|
||
let elapsed = t - boot
|
||
if elapsed < 2.5 {
|
||
controller.keyboardBridge.publish(
|
||
KeyboardSnapshot(
|
||
state: .ready,
|
||
heartbeat: t,
|
||
expiresAt: t + 15 * 60
|
||
)
|
||
)
|
||
} else if elapsed < 5.2 {
|
||
let db = DotScopeSimulation.demoLoudness(at: simTime) + 4.5
|
||
controller.keyboardBridge.publish(
|
||
KeyboardSnapshot(
|
||
state: .recording,
|
||
heartbeat: t,
|
||
expiresAt: t + 15 * 60,
|
||
recordingStartedAt: boot + 2.5,
|
||
audioLevel: 0.78,
|
||
loudnessDB: db,
|
||
jobID: "hosted-tour-job"
|
||
)
|
||
)
|
||
simTime += 0.033
|
||
} else if elapsed < 6.4 {
|
||
controller.keyboardBridge.publish(
|
||
KeyboardSnapshot(
|
||
state: .transcribing,
|
||
heartbeat: t,
|
||
expiresAt: t + 15 * 60,
|
||
jobID: "hosted-tour-job"
|
||
)
|
||
)
|
||
} else {
|
||
controller.keyboardBridge.publish(
|
||
KeyboardSnapshot(
|
||
state: .ready,
|
||
heartbeat: t,
|
||
expiresAt: t + 14 * 60 + 54,
|
||
resultID: freshResultID,
|
||
resultExpiresAt: boot + 30,
|
||
transcript: "See you at ten."
|
||
)
|
||
)
|
||
}
|
||
try? await Task.sleep(for: .milliseconds(33))
|
||
}
|
||
}
|
||
|
||
default:
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
}
|