hex/ios/HEXShared/KeyboardSurface+ViewModel.swift
Ryan Vogel 56a93e80b2
iOS keyboard: stale microphone errors clear, Hex key audio calls leave the main thread, counts read 1, 2, 3 (#2203)
* 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).
2026-11-21 10:08:42 -05:00

347 lines
14 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 Combine
import SwiftUI
import UIKit
/// The dictation bar's state: its phase, the style and language trays, the message and
/// transcript, and the clock the surface reads. Kept beside the surface view.
@MainActor
final class KeyboardViewModel: ObservableObject {
enum PickerTray: Equatable {
case none
case style
case language
/// More languages…: every other language Apple Speech has, in place of the keys.
case moreLanguages
}
enum StagePhase: Equatable {
case idle
case recording
case transcribing
case failed
}
struct PendingCommand: Equatable {
let kind: KeyboardCommandKind
let jobID: String
let sentAt: TimeInterval
}
static let commandAckTimeout: TimeInterval = 1.6
let clock = KeyboardClockModel()
@Published var hasFullAccess = true
@Published var needsGlobeKey = true
/// The bar's return key for the field's type, as the full keyboard's, and whether it's on.
@Published var returnKey = ReturnKeyStyle(.default)
@Published var returnKeyEnabled = true
@Published var isModelInstalled = false
@Published private(set) var isWarmAvailable = false
@Published private(set) var stagePhase: StagePhase = .idle
@Published private(set) var statusMessage: String?
/// A tap on Dictate or the Hex key records through Hex's warm session. Not while the last
/// dictation shows as failed: the keyboard's own failure keeps its snapshot live for a few
/// seconds, which isn't a session, and the bar already dictates in the keyboard then.
var dictatesThroughHex: Bool {
hasFullAccess && isWarmAvailable && stagePhase != .failed
}
@Published var style: DictationStyle = .polished
@Published var activeTray: PickerTray = .none
/// Settings › Dictation language (nil for Automatic), what Automatic resolves to, and the
/// languages the keyboard's quick switch offers. Empty choices hide the switch.
@Published var dictationLanguage: String?
@Published var automaticLanguage: String?
@Published var languageChoices: [String] = []
/// Every other language Apple Speech has, for More languages… (`DictationLanguageSwitch.more`).
@Published var moreLanguages: [String] = []
/// The language a long press on its chip offered to remove: Remove shows beside it.
@Published var removingLanguage: String?
/// Translate what I say's target (BCP 47) while it is on, else nil.
@Published var translationTarget: String?
/// The last dictation went in as spoken while Translate what I say was on: both keyboards
/// say so for a few seconds, with the fix, which opens Hex's Settings.
@Published var translationNote: TranslationFailure?
/// Translate what I say's target whether it is on or off, for the keyboards' Translate to
/// <language> switch; nil hides the switch (no Apple translation before iOS 26).
@Published var translationLanguage: String?
/// The targets the full keyboard's Hex key menu offers (`DictationTranslationSettings.targetChoices`).
@Published var translationTargetChoices: [String] = []
/// Record typing logs is recording this field: both keyboards show a small mark the
/// whole time, so logging is never hidden.
@Published var isLoggingTyping = false
/// The dictation bar's emoji key: Settings › Keyboard › Emoji, in a field that takes emoji.
@Published var showsEmojiKey = true
/// A finished dictation the keyboard didn't insert by itself (it missed its moment, or
/// the keyboard came back in another field): the full keyboard's strip offers Paste
/// dictation, which calls `onPasteDictation`.
@Published var offeredDictation: String?
// Non-published live telemetry read directly by `DotScopeHostView` / button tap handlers
// so 25–30 Hz polling never invalidates SwiftUI views mid-spring.
var liveLoudnessDB: Float = -62.0
var currentTimestamp: TimeInterval = Date().timeIntervalSince1970
private(set) var currentSnapshot: KeyboardSnapshot = .offline
var coldStartURL: URL = KeyboardLaunchRequest.startSession(requestedAt: nil).url
private(set) var pendingCommand: PendingCommand?
var onDictateTap: (() -> Void)?
var onLocalDictateTap: (() -> Void)?
/// The finger landed on the full keyboard's Hex key (wall clock), before it is a tap,
/// a hold or a slide.
var onHexKeyPress: ((TimeInterval) -> Void)?
/// That press became a slide (the style menu) or was cancelled before it was a tap or a hold.
var onHexKeyAbandon: (() -> Void)?
var onStopTap: (() -> Void)?
var onCancelTap: (() -> Void)?
var onStyleSelected: ((DictationStyle) -> Void)?
/// A language picked in the keyboard's switch; nil is Automatic.
var onLanguageSelected: ((String?) -> Void)?
/// A language taken off the keyboard's switch (a long press on it, then Remove).
var onLanguageRemoved: ((String) -> Void)?
/// Translate to <language> switched on (true) or off where you dictate.
var onTranslationToggled: ((Bool) -> Void)?
/// A target picked in the Hex key menu; it also turns translation on.
var onTranslationTargetSelected: ((String) -> Void)?
var onSpace: (() -> Void)?
/// The dictation bar's space bar slid as a trackpad: move the cursor by this many characters.
var onMoveCursor: ((Int) -> Void)?
/// A trackpad step or a long press that opened Remove, for the selection haptic.
var onSelectionStep: (() -> Void)?
/// A punctuation key on the dictation bar.
var onInsertText: ((String) -> Void)?
/// The dictation bar's emoji key: the full keyboard's emoji panel opens in its place.
var onEmojiTap: (() -> Void)?
var onDelete: (() -> Void)?
var onReturn: (() -> Void)?
var onOpenURL: ((URL) -> Void)?
var onPasteDictation: (() -> Void)?
/// The dictation bar's light haptic for each press; the keyboard allows it with Full
/// Access and Experiments › Haptics, as the full keyboard's keys.
var onKeyFeedback: (() -> Void)?
weak var inputViewController: UIInputViewController?
/// The language dictation uses now, when known.
var effectiveLanguage: String? {
dictationLanguage ?? automaticLanguage
}
/// Its own short name ("Norsk", "English"), for the switch and the space bar.
var languageLabel: String? {
effectiveLanguage.map(DictationLanguageSwitch.nativeName(for:))
}
var showsLanguageSwitch: Bool {
hasFullAccess && !(languageChoices.isEmpty && moreLanguages.isEmpty)
}
/// "Paste in English" or "Paste in Spanish", when Translate what I say is on and you
/// dictate in another language than its target.
var pasteChoice: TranslationPasteChoice? {
guard hasFullAccess, let translationTarget else { return nil }
return TranslationPasteChoice(target: translationTarget, source: effectiveLanguage)
}
/// The keyboards' Translate to <language> switch can show: Full Access and a target.
var showsTranslationSwitch: Bool {
hasFullAccess && translationLanguage != nil
}
/// Dictations paste translated: Translate what I say is on. The Hex key wears the target's
/// badge ("EN") the whole time.
var isTranslating: Bool {
hasFullAccess && translationTarget != nil
}
/// The target while `isTranslating`, for the badge beside the Hex key ("EN").
var translatingTo: String? {
isTranslating ? translationTarget : nil
}
/// The language label with where dictations go while they paste translated:
/// "Español → English".
var languageSummary: String? {
guard let languageLabel else { return nil }
guard let target = pasteChoice?.target else { return languageLabel }
return "\(languageLabel) → \(DictationLanguageSwitch.nativeName(for: target))"
}
var dotScopePhase: DotScopePhase {
switch stagePhase {
case .idle:
return .idle
case .recording:
return .recording
case .transcribing:
return .processing
case .failed:
return .failed
}
}
func setActiveTray(_ tray: PickerTray, reduceMotion: Bool) {
guard activeTray != tray else { return }
withAnimation(HexMotion.trayAnimation(reduceMotion: reduceMotion)) {
activeTray = tray
removingLanguage = nil
}
}
func setPendingCommand(_ command: PendingCommand?, now: TimeInterval, animated: Bool) {
currentTimestamp = now
pendingCommand = command
reconcileVisualState(
hasFullAccess: hasFullAccess,
snapshot: currentSnapshot,
isModelInstalled: isModelInstalled,
style: style,
now: now,
animated: animated
)
}
func applyBridgeState(
hasFullAccess newFullAccess: Bool,
snapshot newSnapshot: KeyboardSnapshot,
isModelInstalled newModelInstalled: Bool,
style newStyle: DictationStyle,
now: TimeInterval,
clearPending: Bool = false,
animated: Bool
) {
// A job Hex stopped heartbeating for is over (Hex ended, crashed or was suspended
// mid-dictation): without this its last snapshot held every keyboard in recording or
// transcribing for good, with Done and Cancel sent to no one.
// A failure Hex wrote a while ago is over too (`KeyboardSnapshot.hasStaleMessage`).
let newSnapshot = newSnapshot.droppingOrphanedJob(at: now).droppingStaleMessage(at: now)
currentTimestamp = now
currentSnapshot = newSnapshot
liveLoudnessDB = newSnapshot.state == .recording ? newSnapshot.effectiveLoudnessDB : -62.0
if clearPending {
pendingCommand = nil
} else if let pending = pendingCommand {
let expired = now - pending.sentAt >= Self.commandAckTimeout
let acknowledged = (pending.kind == .start && newSnapshot.state == .recording)
|| (pending.kind == .stop && newSnapshot.state != .recording)
|| (pending.kind == .cancel && newSnapshot.state != .recording)
if expired || acknowledged {
pendingCommand = nil
}
}
let recordingElapsed: TimeInterval? = if newSnapshot.state == .recording {
newSnapshot.recordingElapsed(at: now)
} else if let pending = pendingCommand, pending.kind == .start {
max(0, now - pending.sentAt)
} else {
nil
}
let warmRemaining: TimeInterval? = newSnapshot.isAvailable(at: now)
? max(0, newSnapshot.expiresAt - now)
: nil
clock.update(recordingElapsed: recordingElapsed, warmRemaining: warmRemaining)
reconcileVisualState(
hasFullAccess: newFullAccess,
snapshot: newSnapshot,
isModelInstalled: newModelInstalled,
style: newStyle,
now: now,
animated: animated
)
}
/// Convenience for deterministic preview/snapshot fixtures (`KeyboardPreviewHost`).
func configureFixture(
snapshot: KeyboardSnapshot,
now: TimeInterval,
hasFullAccess: Bool = true,
isModelInstalled: Bool = true,
style: DictationStyle = .polished,
activeTray: PickerTray = .none
) {
self.activeTray = activeTray
applyBridgeState(
hasFullAccess: hasFullAccess,
snapshot: snapshot,
isModelInstalled: isModelInstalled,
style: style,
now: now,
clearPending: true,
animated: false
)
}
private func reconcileVisualState(
hasFullAccess newFullAccess: Bool,
snapshot snap: KeyboardSnapshot,
isModelInstalled newModelInstalled: Bool,
style newStyle: DictationStyle,
now: TimeInterval,
animated: Bool
) {
let nextWarm = newFullAccess && snap.isAvailable(at: now)
let nextStage = computeStagePhase(snapshot: snap, now: now, hasFullAccess: newFullAccess)
let trimmedMsg = snap.message?.trimmingCharacters(in: .whitespacesAndNewlines)
let nextMessage = (trimmedMsg?.isEmpty == false) ? trimmedMsg : nil
let changed = hasFullAccess != newFullAccess
|| isWarmAvailable != nextWarm
|| isModelInstalled != newModelInstalled
|| stagePhase != nextStage
|| statusMessage != nextMessage
|| style != newStyle
guard changed else { return }
let commit = {
self.hasFullAccess = newFullAccess
self.isWarmAvailable = nextWarm
self.isModelInstalled = newModelInstalled
self.stagePhase = nextStage
self.statusMessage = nextMessage
self.style = newStyle
}
if animated {
withAnimation(HexMotion.stageAnimation(reduceMotion: UIAccessibility.isReduceMotionEnabled)) {
commit()
}
} else {
commit()
}
}
private func computeStagePhase(
snapshot snap: KeyboardSnapshot,
now: TimeInterval,
hasFullAccess: Bool
) -> StagePhase {
guard hasFullAccess else { return .idle }
if let pending = pendingCommand, now - pending.sentAt < Self.commandAckTimeout {
switch pending.kind {
case .cancel:
return .idle
case .stop where snap.state == .recording:
return .transcribing
case .start where snap.state != .recording:
return .recording
default:
break
}
}
switch snap.state {
case .recording:
return .recording
case .transcribing:
return .transcribing
case .failed:
return .failed
case .offline, .ready:
return .idle
}
}
}