hex/ios/HEXShared/KeyboardSurface+ViewModel.swift
Ryan Vogel 2558076aad
iOS keyboard: nothing opens Hex unless the person taps Open Hex (#2707)
* iOS keyboard: nothing opens Hex unless the person taps Open Hex

A dictation tap (the Hex key, Dictate, the bar's Hex mark, a hold on the
strip, two-thumb Dictate) opened Hex without saying so in four cases on
iOS 26 and later. Ryan asked that nothing in the keyboard takes people to
Hex unless they tapped something that says it will.

- Multilingual model: removed the hand-off. With Experiments › Multilingual
  model on and ready in Hex, every dictation in its 25 languages (English
  included) opened Hex unless the keyboard had the model loaded at that
  moment (any fresh keyboard process, the first compile, Speech model in
  keyboard off, Two-language dictation, a keyboard limit under 131 MB, a
  memory warning). The keyboard now dictates those languages itself, with
  the model once loaded and Apple's speech recognition until then, as
  English already did. Removed KeyboardSelfDictation.Reason.multilingual,
  MultilingualParakeetSettings.keyboardOpensHex and isModelReady (only that
  read it), KeyboardParakeetSettings.keyboardHasMultilingualModel and
  KeyboardParakeet.dictatesMultilingualHere. The Experiments row no longer
  says "Once ready, keyboard dictation opens Hex."
- Speech model missing twice, short of memory, Hex not set up: from iOS 26
  a dictation tap now shows one line saying why ("Download English in Hex
  to dictate", "Not enough memory to dictate here", "Finish setting up Hex
  to dictate") with Open Hex and a ✕, in the bar's top row and the full
  keyboard's strip (KeyboardDictationBlock), for 8 s. Only Open Hex opens
  Hex (to record there, as the tap used to). The second failure to get the
  speech model shows the line by itself; it goes once the keyboard can
  dictate again. The keyboard's error for that case uses the same words.
- With a warm session the bar's Hex mark dictated by opening Hex; it now
  dictates through the warm session as Dictate does, and VoiceOver names it
  for what it does (Dictate, Set up Hex, or before iOS 26 Open Hex). The Hex
  key's VoiceOver label says "Open Hex to dictate" only where it does.
- The translation note: a tap anywhere on it in the bar opened Hex. Now
  only its Open Hex chip opens Hex's Settings, and a ✕ puts it away (both
  keyboards); the strip notice's title shrinks to 0.7 to fit beside the ✕.

Before iOS 26 nothing changes for a dictation tap: KeyboardDictationBlock
.resolve is nil there and the tap opens Hex as before (Ryan decides).

A simulator-only App Group key (simulator.keyboardMemoryShort) stands in
for a keyboard short of memory, for screenshots.

Verified: build for the simulator; DictationSSOTTests, KeyboardBridgeTests,
SpeechModelInstallTests and the changed DictationControllerTests case pass
on basebook's iOS 27.2 simulator (new cases in DictationSSOTTests); every
line, both keyboards, light and dark, English and Chinese, on the real
keyboard in a host app on the simulator; code-shape --check passes.

* iOS: Hex gets the keyboard's Apple model ready when it dictates with the multilingual model

With Hex's engine on the multilingual model, KeyboardSpeechPreparation
took the keyboard's speech as following Hex (keyboardSpeechFollowsApp was
true for Parakeet Ultra) because the keyboard used to send those
dictations to Hex. Since the previous commit the keyboard dictates them
itself, with Apple's speech recognition until it has the multilingual
model loaded, so Hex now gets that language's Apple model ready for the
keyboard as it does with Parakeet V2. Without this, the keyboard would
have had to download it on its first dictation.

Verified: DictationSSOTTests' engine case updated to expect it; the full
suite runs on the Studio.

* iOS keyboard: say a language is unavailable instead of "Download it in Hex"; bar labels in Chinese

Two follow-ups the coordinator asked for on this pull request.

- When Hex found that Apple has no speech model for the dictation
  language on this iPhone (KeyboardSpeechPreparation's hand-off: Speech
  lists nothing, or the language isn't on this iPhone with nothing to fall
  back to), a dictation tap said "Download <language> in Hex to dictate",
  which downloading can't fix. Hex now marks that case
  (LanguageSettings.keyboardLanguageUnavailable, beside keyboardNeedsHex),
  the keyboard's reason is .languageUnavailable, and the line says
  "<Language> isn't available on this iPhone yet" with only a ✕: no Open
  Hex, since Hex can't download it either. The keyboard's own failures to
  get a model it should have keep "Download <language> in Hex to dictate"
  with Open Hex. A strip notice with no button hides its chip.
- The dictation bar's Dictate, Set up and Set up Hex labels were plain
  strings, so the keyboard showed them in English on a Chinese iPhone. They
  are localized now (听写, 开始设置, 设置 Hex were already in the catalog).

Verified: DictationSSOTTests (new cases for the unavailable line and
reason), KeyboardBridgeTests, SpeechModelInstallTests and
DictationControllerTests pass on basebook's iOS 27.2 simulator (143 tests).

* iOS docs: the keyboard's line when a language isn't available on the iPhone

Documents the previous commit: where Hex found Apple has no speech model for
the dictation language, the keyboard says so with only a ✕.
2026-11-24 17:27:40 -05:00

601 lines
25 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
/// Which dictation starts when a finger lands on Dictate or the Hex key.
/// Every surface (dictation bar, full keyboard, selection dictation, auto-start, touch-down
/// arming) switches on this single resolution.
nonisolated enum DictationRoute: Equatable, Sendable {
/// Full Access is off: open Hex's setup sheet or show the Full Access hint.
case setUp
/// Full Access is on, but Hex's speech model isn't installed yet and the keyboard can't
/// dictate by itself: from iOS 26 the keyboard says to finish setting up Hex, with Open
/// Hex (`KeyboardDictationBlock`); before, Dictate opens Hex to finish setup.
case needsModel
/// Hex's warm session takes the dictation (including warm retry after a failure).
case warm
/// In-keyboard dictation (iOS 26+) runs in the keyboard's own process.
case inKeyboard
/// In-keyboard dictation can't take it. The reason says why (`memory`, `speechModel`), or
/// is nil where in-keyboard dictation isn't supported. From iOS 26 the keyboard says why
/// with Open Hex (`KeyboardDictationBlock`); before, Dictate opens Hex to record there.
case opensHex(KeyboardSelfDictation.Reason?)
static func resolve(
hasFullAccess: Bool,
isModelInstalled: Bool,
isWarmAvailable: Bool,
localAvailable: Bool,
opensHexReason: KeyboardSelfDictation.Reason?
) -> DictationRoute {
guard hasFullAccess else { return .setUp }
// In-keyboard dictation uses the keyboard's own speech model, not Hex's, so it still
// dictates while Hex's isn't installed (a first download, Continue without a model, a
// failed preparation), as 1.0.4 did. A warm session needs Hex's model.
guard isModelInstalled else { return localAvailable ? .inKeyboard : .needsModel }
if isWarmAvailable { return .warm }
if localAvailable { return .inKeyboard }
return .opensHex(opensHexReason)
}
/// Whether dictation starts without leaving the host app (warm session or in-keyboard).
var dictatesInPlace: Bool {
self == .warm || self == .inKeyboard
}
}
/// Why a dictation tap can't dictate where you are, from iOS 26: both keyboards say so in one
/// line with Open Hex and ✕, and nothing opens unless Open Hex is tapped. Before iOS 26 a
/// dictation tap there still opens Hex to record, as it always has (`resolve` is nil).
nonisolated enum KeyboardDictationBlock: Equatable, Sendable {
/// The keyboard couldn't get this language's speech model (BCP 47) twice in a row; Hex
/// downloads it (`LanguageSettings.keyboardNeedsHex`).
case speechModel(language: String)
/// Hex found Apple has no speech model for this language on this iPhone: downloading in
/// Hex can't help, so the line has no Open Hex (`LanguageSettings.keyboardLanguageUnavailable`).
case languageUnavailable(language: String)
/// Less memory left than a dictation needs to start (`KeyboardLocalDictation.hasMemoryToStart`).
/// Dictate works again by itself once there is.
case memory
/// Hex's own speech model isn't set up, and the keyboard can't dictate by itself.
case setUp
var line: String {
switch self {
case .speechModel(let language):
String(localized: "Download \(SpeechModelUnavailable.interfaceName(language)) in Hex to dictate")
case .languageUnavailable(let language):
String(localized: "\(SpeechModelUnavailable.interfaceName(language)) isn't available on this iPhone yet")
case .memory:
String(localized: "Not enough memory to dictate here")
case .setUp:
String(localized: "Finish setting up Hex to dictate")
}
}
/// Whether the line offers Open Hex: where Hex can do what it says.
var opensHex: Bool {
if case .languageUnavailable = self { return false }
return true
}
/// What a dictation tap on `route` says instead of dictating, or nil where it dictates (or
/// asks for Full Access), and before iOS 26, where it opens Hex. `language` is the one
/// dictation uses, for the speech model's line.
static func resolve(
route: DictationRoute,
language: String?,
osMajorVersion: Int = ProcessInfo.processInfo.operatingSystemVersion.majorVersion
) -> KeyboardDictationBlock? {
guard osMajorVersion >= KeyboardSelfDictation.firstVersion else { return nil }
switch route {
case .setUp, .warm, .inKeyboard:
return nil
case .needsModel:
return .setUp
case .opensHex(.speechModel):
return .speechModel(language: language ?? "en-US")
case .opensHex(.languageUnavailable):
return .languageUnavailable(language: language ?? "en-US")
case .opensHex(.memory):
return .memory
case .opensHex(.openedHex), .opensHex(nil):
// Only before iOS 26 (`KeyboardSelfDictation.handoffReason`).
return nil
}
}
}
/// 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 starting
case recording
case transcribing
case failed
}
/// Mutually exclusive status shown in the dictation bar's leading slot and read by the full
/// keyboard's strip for failures.
enum StatusSlot: Equatable {
case none
case noAccess
case starting
case recording
case message(String, isFailure: Bool)
case translationNote(TranslationFailure)
/// A dictation tap couldn't dictate here: why, with Open Hex and ✕.
case dictationBlock(KeyboardDictationBlock)
case warm
}
struct PendingCommand: Equatable {
let kind: KeyboardCommandKind
let jobID: String
let sentAt: TimeInterval
}
static let commandAckTimeout: TimeInterval = 1.6
let clock = KeyboardClockModel()
/// The words so far while the keyboard records with live words on (`LiveDictationPreviewHost`).
let liveText = LiveDictationText()
@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?
/// Why Dictate opens Hex when in-keyboard dictation can't take it, fed by `KeyboardViewController`.
var opensHexReason: KeyboardSelfDictation.Reason?
/// The single precedence table for what happens when a finger lands to dictate.
var route: DictationRoute {
DictationRoute.resolve(
hasFullAccess: hasFullAccess,
isModelInstalled: isModelInstalled,
isWarmAvailable: isWarmAvailable,
localAvailable: onLocalDictateTap != nil,
opensHexReason: opensHexReason
)
}
/// A tap on Dictate or the Hex key records through Hex's warm session (including retrying
/// after a warm-session failure).
var dictatesThroughHex: Bool {
route == .warm
}
/// Push-to-talk is available when idle or after a failure and dictation stays in-place.
var canPushToTalk: Bool {
route.dictatesInPlace && (stagePhase == .idle || stagePhase == .failed)
}
/// Single mutually exclusive status for the leading bar slot and full-keyboard failure strip.
var statusSlot: StatusSlot {
guard hasFullAccess else { return .noAccess }
switch stagePhase {
case .starting:
return .starting
case .recording:
return .recording
case .transcribing:
return .none
case .failed:
if let dictationBlock { return .dictationBlock(dictationBlock) }
if let statusMessage { return .message(statusMessage, isFailure: true) }
if let translationNote { return .translationNote(translationNote) }
return isWarmAvailable ? .warm : .none
case .idle:
if let dictationBlock { return .dictationBlock(dictationBlock) }
if let translationNote { return .translationNote(translationNote) }
if let statusMessage { return .message(statusMessage, isFailure: false) }
if let stoppedNote { return .message("\(stoppedNote.title). \(stoppedNote.detail)", isFailure: false) }
return isWarmAvailable ? .warm : .none
}
}
/// What both keyboards say beside Paste dictation while `offeredDictationStoppedAfter` shows.
var stoppedNote: (title: String, detail: String)? {
guard hasFullAccess, offeredDictation != nil, let offeredDictationStoppedAfter else { return nil }
return KeyboardInterruptedRecording.note(stoppedAfter: offeredDictationStoppedAfter)
}
/// What the last dictation tap said instead of dictating (`KeyboardDictationBlock`), for
/// `dictationBlockDuration` or until its ✕, its Open Hex, or a route that dictates here.
@Published private(set) var dictationBlock: KeyboardDictationBlock?
private var dictationBlockWork: Task<Void, Never>?
static let dictationBlockDuration: Duration = .seconds(8)
/// The line a dictation tap shows on this route instead of dictating (from iOS 26).
var routeDictationBlock: KeyboardDictationBlock? {
KeyboardDictationBlock.resolve(route: route, language: effectiveLanguage)
}
/// A dictation tap opens Hex: only before iOS 26, where the keyboard can't dictate itself.
var dictationTapOpensHex: Bool {
switch route {
case .needsModel, .opensHex: routeDictationBlock == nil
case .setUp, .warm, .inKeyboard: false
}
}
/// Dictate, the Hex key or the bar's Hex mark where the route can't dictate in place: from
/// iOS 26 the line that says why, with Open Hex; before, Hex opens to record, as always.
func dictateWhereUnavailable() {
if let block = routeDictationBlock {
showDictationBlock(block)
} else {
onOpenURL?(coldStartURL)
}
}
func showDictationBlock(_ block: KeyboardDictationBlock) {
dictationBlockWork?.cancel()
dictationBlock = block
UIAccessibility.post(notification: .announcement, argument: block.line)
dictationBlockWork = Task { [weak self] in
try? await Task.sleep(for: Self.dictationBlockDuration)
guard !Task.isCancelled else { return }
self?.dictationBlock = nil
}
}
func dismissDictationBlock() {
dictationBlockWork?.cancel()
dictationBlockWork = nil
if dictationBlock != nil { dictationBlock = nil }
}
/// In-keyboard dictation came or went: dictating here again puts the line away, and losing
/// the speech model at a dictation (the second time in a row) says so as a tap would.
func localDictationChanged(available: Bool, was: Bool?, reason: KeyboardSelfDictation.Reason?) {
if available { return dismissDictationBlock() }
if was == true, reason == .speechModel, let block = routeDictationBlock { showDictationBlock(block) }
}
/// The line's Open Hex: the one way a dictation the keyboard can't take goes to Hex.
func openHexForDictationBlock() {
guard dictationBlock?.opensHex != false else { return }
dismissDictationBlock()
onOpenURL?(coldStartURL)
}
func showStoppedNote(_ stoppedAfter: TimeInterval?) {
stoppedNoteWork?.cancel()
offeredDictationStoppedAfter = stoppedAfter
guard stoppedAfter != nil else { return }
stoppedNoteWork = Task { [weak self] in
try? await Task.sleep(for: Self.stoppedNoteDuration)
guard !Task.isCancelled else { return }
self?.offeredDictationStoppedAfter = nil
}
}
/// Failure message shown consistently by both the dictation bar and the full keyboard.
var failureMessage: String? {
if case .message(let text, isFailure: true) = statusSlot { return text }
return nil
}
@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] = []
/// 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 and the dictation
/// bar's top row offer Paste dictation, which calls `onPasteDictation`.
@Published var offeredDictation: String?
/// Where an offered dictation stopped when the keyboard closed during it, said beside
/// Paste dictation for a few seconds (`showStoppedNote`).
@Published private(set) var offeredDictationStoppedAfter: TimeInterval?
private var stoppedNoteWork: Task<Void, Never>?
static let stoppedNoteDuration: Duration = .seconds(8)
// 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)?
/// The translation note's ✕.
var onDismissTranslationNote: (() -> 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 .starting:
return .starting
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 == .starting || newSnapshot.state == .recording))
|| (pending.kind == .stop && newSnapshot.state != .starting && newSnapshot.state != .recording)
|| (pending.kind == .cancel && newSnapshot.state != .starting && newSnapshot.state != .recording)
if expired || acknowledged {
pendingCommand = nil
}
}
let recordingElapsed: TimeInterval? = if newSnapshot.state == .recording {
newSnapshot.recordingElapsed(at: now)
} 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 .stop where snap.state == .starting:
return .idle
case .start where snap.state != .recording:
return .starting
default:
break
}
}
switch snap.state {
case .starting:
return .starting
case .recording:
return .recording
case .transcribing:
return .transcribing
case .failed:
return .failed
case .offline, .ready:
return .idle
}
}
}