hex/ios/HEXMobile/DictationController+ModelPreparation.swift
Ryan Vogel bd8da45709
iOS: Keep mic warm defaults to Off and hides where the keyboard dictates by itself (#2393)
Ryan's decision: where the keyboard can dictate by itself (iOS 26,
KeyboardLocalDictation), Keep mic warm defaults to Off and its row is hidden;
everywhere else it stays as it was. There a warm session did nothing useful
and got in the way: the keyboard records through it instead of dictating
itself, which also bypasses the speech model now running in the keyboard.

What changed
- KeyboardSelfDictation (new, HEXShared): one answer to "can this phone's
  keyboard dictate by itself?": iOS 26 or later, no keyboardNeedsHex (case 3),
  Experiments > Multilingual model not taking the language while only Hex can
  load it (case 4, unless Speech model in keyboard is on), and no record of
  Dictate opening Hex in the last 7 days. The keyboard writes that record
  (reason + time: memory, speechModel or multilingual) when its cold-start URL
  opens Hex because it can't dictate here (case 2 left no record before), and
  clears it the next time it dictates in the keyboard.
- KeyboardBridge.warmDuration: unset now reads Off where the keyboard
  dictates by itself and 15m elsewhere, worked out on each read, never stored
  (replaces the fixed 15m fallback). Nothing writes the default at first
  launch, but tapping the already-selected 15m (to warm the mic) stored it, so
  once on iOS 26 a stored 15m is taken for not chosen where the keyboard
  dictates by itself; Off, 5m and 1h stay as chosen. This runs in
  DictationController.init, where no warm session can be running yet.
- DictationController: the duration in effect is read again as Hex becomes
  active and as the keyboard opens it (refreshWarmDuration, in the new
  DictationController+WarmDefault.swift); when it turns Off an idle warm
  session ends. With Off where the keyboard dictates by itself, a keyboard
  launch that missed its recording (Timed out, or /start) no longer starts a
  15-minute warm session; it warms nothing. A Dictate that opens Hex in time
  still records one shot, as before.
- Settings > Dictation: Keep mic warm shows unless it would say Off where the
  keyboard dictates by itself; any duration in effect shows it, and once
  picked it stays on the page (so picking Off doesn't pull it from under the
  finger). No new strings.
- README's warm-session paragraph says so.

Verified
- xcodebuild test on an iOS 27.2 simulator (Mac Studio): 859 tests, 3 skipped
  (clip and replay fixtures), 0 failures. New cases in existing files:
  KeyboardBridgeTests (default per OS version 18/25/26/27, the memory record
  and its 7-day window, keyboardNeedsHex, multilingual with and without
  Speech model in keyboard, a choice kept; the one-time review of a stored
  15m) and DictationControllerTests (Off hides the row, a timed-out handoff
  warms nothing, a memory record brings 15m and the row back, clearing it
  ends the idle session). testTenSecondHandoffWindow now sets 15m explicitly,
  since it pins the warm path. iOS 18-25 covered only by passing the version
  in; not run on a real iOS 18.
- In the real app on the simulator: a fresh install shows no Keep mic warm
  row and no warm timer; an install of origin/dev with 15m stored, updated
  to this build, reads Off with the row hidden and the key removed; one with
  1h kept 1h and the row; with the keyboard's memory record set, the row came
  back with 15m. The simulator has no Apple Speech model, so Hex marks
  keyboardNeedsHex there itself; the self-dictating states were checked with
  that mark cleared.
- python3 scripts/code-shape.py passes; git diff --check clean.
2026-11-22 11:58:48 -05:00

237 lines
11 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Foundation
/// Getting the engine Hex dictates with ready: `prepareModel`, and Experiments ›
/// Multilingual model (Parakeet) downloading and loading beside the engine that dictates
/// meanwhile, including what the app does with it in the background.
extension DictationController {
// MARK: - Model Preparation
/// Experiments › Multilingual model (Parakeet) turned on or off. On, the engine Hex
/// dictates with stays while Parakeet Ultra downloads and loads beside it; a load that
/// ended Hex gets another try. Off, the download stops and is deleted, and Hex prepares
/// the engine it picks without it if Ultra was the one dictating (now, or once the
/// dictation in flight is done).
func multilingualParakeetChanged() {
let settings = MultilingualParakeetSettings()
if settings.isEnabled {
ParakeetLoadGuard(model: ParakeetUltraTranscriber.loadGuardModel).forget()
multilingualDownload.settle()
if isModelReady || phase == .preparingModel {
syncMultilingualParakeet()
return
}
} else {
settings.isModelReady = false
let download = multilingualDownload
Task {
// Nothing writes to the folder any more once `stop` returns.
await download.stop()
ParakeetUltraModel.remove()
}
if engineName != ParakeetUltraTranscriber.name, isModelReady, phase != .preparingModel {
// Ultra wasn't dictating: drop a load of it beside the engine that is.
modelPrepGeneration &+= 1
return
}
}
switch phase {
case .recording, .transcribing, .requestingPermission:
pendingLanguagePreparation = true
case .modelRequired, .preparingModel, .ready, .failed:
prepareModel()
}
}
/// `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, candidate preset: (any LocalTranscribing)? = nil) {
modelPrepGeneration &+= 1
let prepGen = modelPrepGeneration
// A load beside the engine this replaces is dropped; the end of this one decides again.
multilingualDownload.dropLoad()
startMultilingualDownloadIfWanted()
phase = .preparingModel
copied = false
modelPreparation = ModelPreparationProgress(
fractionCompleted: 0,
detail: String(localized: "Checking the speech model")
)
preparationFailedInBackground = false
watchPreparation(prepGen)
// 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() }
var candidateIsUltra = false
do {
let candidate: any LocalTranscribing
if let preset {
candidate = preset
} else {
candidate = await transcriberFactory()
}
guard self.modelPrepGeneration == prepGen else { return }
engineName = candidate.displayName
candidateIsUltra = candidate is ParakeetUltraTranscriber
try await candidate.prepare { [weak self] progress in
Task { @MainActor [weak self] in
guard let self, self.modelPrepGeneration == prepGen else { return }
if progress.fractionCompleted != self.modelPreparation.fractionCompleted
|| progress.detail != self.modelPreparation.detail {
self.preparationChangedAt = .now
self.preparationReported = true
}
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
if candidateIsUltra {
self.multilingualParakeetLoaded()
}
self.publishKeyboardSnapshot()
if self.pendingHandoff != nil {
self.activateWarmSessionAndRunHandoff()
}
self.syncMultilingualParakeet()
} catch {
guard self.modelPrepGeneration == prepGen else { return }
if candidateIsUltra, fallbacksLeft > 0, !(error is CancellationError) {
// Parakeet Ultra didn't load: the engine Hex uses without it dictates, and
// Hex says why, with Try again.
self.multilingualParakeetFailedToLoad(error)
self.prepareModel(fallbacksLeft: fallbacksLeft - 1)
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()
// A downloaded Parakeet Ultra can still dictate.
self.syncMultilingualParakeet()
}
}
}
/// Ends a preparation that has said nothing new for too long, in plain words with Try
/// again (Set up), instead of a bar that never moves: `firstReport` (30 s) before it has
/// said anything (Apple's speech service or asset store not answering leaves "Checking
/// the speech model" up for good, TestFlight build 126), `stall` (120 s) after, longer
/// than the downloads' own stall limits. Time while iOS had Hex suspended doesn't count.
/// The work it ends can't always be cancelled (an XPC call that never returns); its
/// result is dropped, and Try again starts a new one.
func watchPreparation(_ prepGen: UInt64) {
preparationChangedAt = .now
preparationReported = false
Task { [weak self] in
let clock = ContinuousClock()
var polled = clock.now
while true {
try? await Task.sleep(for: .milliseconds(500))
guard let self, self.modelPrepGeneration == prepGen, self.phase == .preparingModel else { return }
let now = clock.now
if now - polled > .seconds(5) {
self.preparationChangedAt = now
}
polled = now
let limit = self.preparationReported ? self.preparationLimits.stall : self.preparationLimits.firstReport
guard now - self.preparationChangedAt >= limit else { continue }
print("speech model preparation said nothing new for \(limit): ended")
self.modelPrepGeneration &+= 1
self.pendingHandoff = nil
self.keyboardBridge.setModelInstalled(ParakeetTranscriber.hasCachedModel)
self.phase = .failed(String(localized: "The speech model isn't ready. Try again."))
self.publishKeyboardSnapshot()
return
}
}
}
/// Parakeet V2 dictates and leaves no room to load Parakeet Ultra beside it (English
/// before iOS 26): Ultra takes its place and loads as it would at launch, rather than
/// never getting its first load. False when V2 isn't the engine.
func replaceParakeetWithMultilingual(language: String) -> Bool {
guard transcriber is ParakeetTranscriber, phase != .preparingModel else { return false }
transcriber = ParakeetTranscriber()
isModelReady = false
prepareModel(candidate: ParakeetUltraTranscriber(language: language))
return true
}
/// Loads Parakeet Ultra while the engine Hex has keeps dictating, and switches to it once
/// it's loaded; a dictation in flight isn't interrupted. A failure keeps that engine and
/// says why. Only while no other preparation runs.
func loadMultilingualParakeetBeside(language: String) {
guard phase != .preparingModel else { return }
modelPrepGeneration &+= 1
let prepGen = modelPrepGeneration
multilingualDownload.loading()
let backgroundTime = BackgroundTime("Prepare the multilingual model")
Task {
defer { backgroundTime.end() }
let candidate = ParakeetUltraTranscriber(language: language)
do {
try await candidate.prepare { _ in }
guard self.modelPrepGeneration == prepGen else { return }
self.transcriber = candidate
self.engineName = candidate.displayName
self.transcriptionLanguage = await candidate.languageName
self.transcriptionLanguageID = await candidate.languageIdentifier
self.languageOffer = nil
self.isModelReady = true
self.keyboardBridge.setModelInstalled(true)
switch self.phase {
case .modelRequired, .failed:
self.phase = .ready
default:
break
}
self.multilingualParakeetLoaded()
self.publishKeyboardSnapshot()
} catch {
guard self.modelPrepGeneration == prepGen else { return }
self.multilingualParakeetFailedToLoad(error)
}
}
}
func appMovedToBackground() {
isInBackground = true
multilingualDownload.appMovedToBackground()
}
/// 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
refreshWarmDuration()
multilingualDownload.appBecameActive()
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 }
return (error as? ParakeetTranscriber.TranscriberError) == .downloadFailed
}
}