hex/ios/HEXKeyboard/KeyboardSpeech.swift
Ryan Vogel 2d7dff5feb
iOS keyboard: a notification no longer ends an in-keyboard dictation (#2472)
A tester on build 147 (iPhone19,7, iOS 27.2.1): "Dictation stops whenever I
get any notification... Calls stopping it are fine." In-keyboard dictation
records through WebKit in a hidden web view. When iOS gives the audio
session to another sound, WebKit interrupts the page's AudioContext (no
more audio) and mutes the microphone track. It unmutes the track when
WebKit hears the interruption end, but resumes the context only when iOS
says it may (ShouldResume). Some captures fail and end the track. The
page's only defence was a 250 ms ctx.resume(). So:
- a context that didn't come back within 6 s hit the keyboard's watchdog
  ("capture silent"), which finished the dictation with the words so far;
- a track left muted or ended under a running context sent silence for
  good: the dictation went on, but nothing after the sound was heard.

- The capture page reports each track mute/unmute/ended and each context
  statechange (and any change its 250 ms check sees) to the keyboard, with
  the page's time. The keyboard writes every one to the probe log.
- Every 250 ms the page still resumes a context that isn't running. Once
  it runs, it opens the microphone again for a track that ended or stayed
  muted for 3 s (backing off 1, 2, 4, then 8 s), into the same context and
  ScriptProcessor. The same job, file, live words and Type as I speak
  carry on; the gap is missing audio.
- KeyboardCaptureWatch (HEXShared) keeps the recording's clock. While the
  page says it's interrupted, the 6 s quiet rule doesn't count, and quiet
  counts again from when it's back. Interrupted past
  KeyboardJobWatchdog.captureInterruption (15 s: a call, an alarm), it
  finishes with what was said, as before.
- Simulator only (#if targetEnvironment(simulator)): capture-debug.js in
  the App Group runs once in the capture page, and each recording is kept
  as capture-debug.wav, so interruptions can be driven by hand where there
  is no microphone or interruption.
- KeyboardSpeech and KeyboardProbeLog move unchanged to their own files to
  make room: KeyboardLocalDictation.swift 1,398 -> 1,389 lines.
- The app's own recorder (AudioBackend, finishing on interruptionBegan) is
  unchanged.
- ios/docs/dictation.md describes the behaviour.

Verified:
- HEXMobile suite on an iPhone 17 Pro iOS 27.2 simulator (Mac Studio): 952
  tests, 0 failures, including the new KeyboardBridgeTests case (interrupted
  time isn't quiet, quiet restarts at the end, the 15 s limit, a muted
  track's silence counts as interrupted).
- Release simulator build of Hex in a text field. A recorded voice (two
  sentences, 9 s apart) stood in for the microphone, and each interruption
  was driven 5 s in. The kept recordings were transcribed:
  - context suspended 2 s, track muted then unmuted 2 s, both together,
    track muted for good (reopened at +3 s), track stopped (reopened at
    once): each kept both sentences in one dictation;
  - context held suspended: finished at 15 s with the first sentence only.
- Nothing was run on an iPhone. Which of these a notification causes there
  is unverified.
2026-11-23 00:04:17 -05:00

88 lines
4.2 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 AVFAudio
import Foundation
import Speech
@available(iOS 26.0, *)
enum KeyboardSpeech {
enum Failure: HexDescribedError, NoSpeechError {
case noLocale
case empty
var errorDescription: String? {
switch self {
case .noLocale: String(localized: "Apple's speech recognition can't dictate this language on this iPhone.")
case .empty: String(localized: "No speech heard.")
}
}
var meansNoSpeech: Bool {
if case .empty = self { return true }
return false
}
}
/// The transcript and the language it was transcribed in.
static func transcribe(_ url: URL, hints: [String]) async throws -> (String, SpeechLanguage) {
let log = KeyboardProbeLog.shared
// The same rule as the app's (Settings › Dictation language, else Automatic), so the
// keyboard uses the assets Hex downloaded.
let settings = LanguageSettings()
guard let picked = await AppleSpeechLanguages.resolve(settings: settings) else {
// Only Speech listing languages, none of them the iPhone's, means it lacks yours.
guard await AppleSpeechLanguages.listsNone() else { throw Failure.noLocale }
log.write("speech lists no languages in the keyboard: handing over to Hex")
throw SpeechModelNeedsHex.handOff(settings.effectiveDictationLanguage ?? "en-US", settings: settings)
}
log.write("speech locale=\(picked.identifier) module=\(picked.module.rawValue) available=\(SpeechTranscriber.isAvailable)")
// The model the app uses, else the same language on `DictationTranscriber`. One the
// keyboard can't get (released since Hex downloaded it, or a download that failed here)
// is Hex's to download: the Hex key opens Hex until it installs.
let started = Date()
let language: SpeechLanguage
do {
// The keyboard's failures set nothing aside for Hex (`setsAside`): they are often
// the keyboard's own reservation, not the language.
language = try await AppleSpeechAssets.install(picked, settings: settings, setsAside: false, log: { log.write($0) })
} catch {
throw SpeechModelNeedsHex.keyboardError(for: error, language: picked.identifier, settings: settings)
}
if language != picked || Date().timeIntervalSince(started) > 0.5 {
log.write("speech assets ready (\(language.module.rawValue) \(language.identifier)) after \(String(format: "%.1f", Date().timeIntervalSince(started))) s \(KeyboardProbeLog.memory())")
}
let speech = AppleSpeechModule(language)
// Experiments › Two-language dictation: the same recording read by a second installed
// language too, merged word by word; the pipeline still runs as the primary language.
let twoLanguage = TwoLanguageDictationSettings()
if twoLanguage.isEnabled,
let pair = await AppleSpeechTwoLanguage.usablePair(for: language),
let merged = await AppleSpeechTwoLanguage.transcribe(
url,
pair: pair,
vocabulary: hints,
lingeringModels: false
) {
guard !merged.text.isEmpty else { throw Failure.empty }
log.write("two-language \(pair.secondary.identifier(.bcp47)) won=\(merged.winner.rawValue) \(KeyboardProbeLog.memory())")
return (merged.text, language)
}
let analyzer = SpeechAnalyzer(
modules: [speech.module],
options: SpeechAnalyzer.Options(priority: .userInitiated, modelRetention: .whileInUse)
)
let file = try AVAudioFile(forReading: url)
// Custom vocabulary and Learn how I type's meant words, best effort, as the app does.
if !hints.isEmpty {
let context = AnalysisContext()
context.contextualStrings[.general] = hints
try? await analyzer.setContext(context)
}
try await analyzer.start(inputAudioFile: file, finishAfterFile: true)
log.write("analyzer started \(KeyboardProbeLog.memory())")
let text = try await speech.finalText()
guard !text.isEmpty else { throw Failure.empty }
return (text, language)
}
}