hex/ios/HEXMobile/Onboarding.swift
Ryan Vogel b849b63f01
iOS: Multilingual model (Parakeet Ultra) experiment, off by default (#2197)
* iOS: Parakeet's preparation, compile record and load guard take a model name

A second Parakeet model (Parakeet Ultra, next commit) needs its own load guard
and compile record, and its own words while it downloads, without changing V2's.

- ParakeetLoadGuard(model:) and ParakeetCompileRecord(key:) name their
  UserDefaults keys; the defaults ("parakeet.loadStartedAt",
  "parakeet.loadInterrupted", "parakeet.compiledForSystem") are V2's keys as
  before, so V2's state carries over.
- ParakeetLoadGuard.forget() clears an interrupted load, for a person who asks
  to try again.
- ParakeetPreparationProgress takes the download's detail, defaulting to V2's
  "Downloading the speech model".
- ParakeetProgressFeed is no longer private to ParakeetTranscriber.swift.

Nothing V2 does changes: same keys, same words, same progress.

Verified: xcodebuild test on an iPhone 17 Pro Max iOS 26.4 simulator (Mac
Studio), 575 tests, 0 failures, 1 skipped, with the next commit applied.

* iOS: Experiments › Multilingual model (Parakeet) dictates 25 languages, mixed in a sentence

A TestFlight tester (iPhone 17 Pro Max, iOS 26.6.2, build 56) asked for Parakeet
Ultra: they mix Dutch phrases and English words in one sentence, which Apple
Speech, one locale at a time, gets wrong, and Ultra on desktop Hex gets right.

The experiment is off by default. While it's on, Hex dictates Parakeet Ultra's
25 languages (Moondream's post-training of NVIDIA Parakeet TDT 0.6B v3, CC BY
4.0) with FluidInference's Core ML build of it; other languages keep the engine
Hex picks without it.

- MultilingualParakeetSettings (HEXShared, App Group): the switch, Ultra's
  languages, and the rule both processes use: the language set, else the
  keyboard's language Automatic follows, else the iPhone's first, on iPhones
  with 6 GB or more.
- ParakeetUltraModel: the 18 files FluidAudio's v3 path reads, pinned to
  revision 95eaa59 with sizes and SHA-256 (632 MB), downloaded into
  Application Support (out of backups) with Range resume from a .partial and a
  digest check before each file gets its name, hashed in 4 MB chunks drained
  one at a time (without that the encoder's 594 MB stayed in memory during the
  check). FluidAudio 0.15.5 has no .ultra (0.17.7 added it) and its loader
  replaces a folder it can't load with v3's download, so Hex loads the four
  models itself and hands FluidAudio v3 AsrModels. The pin stays at 0.15.5, so
  V2 and everything else run the same FluidAudio as before.
- ParakeetUltraTranscriber: download through StallWatch (90 s, as V2), stopped
  if the switch goes off mid-way; load and transcribe as V2. Chosen only with
  1.5 GB left (os_proc_available_memory), as #2190 does for V2, and set aside
  after a load that ended Hex or found too little memory (its own
  ParakeetLoadGuard keys) until the switch is turned off and on; then home says
  Hex uses its usual model.
- Engine choice: DictationController.defaultTranscriber and prepareAtLaunch ask
  for Ultra first; with the switch off they only delete a download it left.
  multilingualParakeetChanged prepares the new engine now, or after the
  dictation in flight. Download failures count as interruptions, retried once
  back in the foreground.
- Keyboard: the model can't load in a keyboard, so while Ultra takes the
  dictation language, Dictate and the Hex key open Hex, as before iOS 26
  (KeyboardViewController), and KeyboardSpeechPreparation follows the app
  instead of downloading Apple's model. A warm session still dictates without
  leaving the app.
- Settings › Experiments › "Multilingual model (Parakeet)": "25 languages,
  even mixed in a sentence. 632.2 MB download. Keyboard dictation opens Hex.",
  disabled with "Needs an iPhone with 6 GB of memory or more" below that. On
  downloads it; off deletes it. The preparation bar (#2171) says "Downloading
  632.2 MB · Wi-Fi recommended". zh-Hans for every new string.
- Acknowledgements and ios/README.md credit Parakeet Ultra, NVIDIA Parakeet TDT
  0.6B v3 and FluidInference's conversion (CC BY 4.0).
- Onboarding's language line checks for "Parakeet V2" by name, not any
  "Parakeet", so Ultra isn't taken for English.

Measured on the Mac Studio (~/dev/experiments/2026-11-21-hex-multilingual-parakeet,
159 macOS say clips: Dutch-English sentences spoken by Xander and Ellen and
spliced with Samantha, pure Dutch, pure English): word error rate on the mixed
sentences 7.5% for Ultra against 26.9% for Apple Speech nl-NL
(DictationTranscriber) and ~80% for Apple Speech en-US and Parakeet V2; pure
Dutch 0.9% (Apple nl-NL 0.4%), pure English 0% (Apple en-US 0%). Core ML on the
Mac: compile 7.4 s (V2 11.4 s), same speed as V2.

Verified: xcodebuild test on an iPhone 17 Pro Max iOS 26.4 simulator, 575
tests, 0 failures, 1 skipped, with new cases in DictationControllerTests (off
by default, language and memory rules, separate guard, download words, pinned
files, re-prepare on toggle). In that simulator a fresh install with the switch
on downloaded, checked and loaded Ultra in under 10 s and became ready, and the
app's ParakeetUltraTranscriber transcribed the test clips (a throwaway case,
not committed). The simulator has no microphone here and runs Core ML on the
CPU: a real iPhone must confirm load memory, Neural Engine compile time, speed,
the keyboard opening Hex, and dictation of real speech.

* iOS: Acknowledgements credit Parakeet V2

Hex downloads NVIDIA Parakeet TDT 0.6B v2 (FluidInference's Core ML conversion)
to dictate English, and its licence, CC BY 4.0, asks for credit, but
Settings › Acknowledgements and the README named only the data Hex ships and,
since the previous commit, Parakeet Ultra.

- AcknowledgementsView and ios/README.md's Acknowledgements credit NVIDIA's
  model and FluidInference's conversion, both CC BY 4.0, with links, and say
  the conversion stores the encoder at reduced precision and Hex uses it
  unchanged.

FluidAudio stays at 0.15.5.

Verified: generic build (CODE_SIGNING_ALLOWED=NO) and xcodebuild test on an
iPhone 17 Pro Max simulator on the Mac Studio, all tests passing.
2026-11-21 09:29:13 -05:00

941 lines
37 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 SwiftUI
import UIKit
/// Where the speech model stands, as onboarding shows it.
struct OnboardingModel: Equatable {
enum Stage: Equatable {
case starting
case downloading(Double)
case ready
case failed(String)
}
var stage: Stage
/// The language it's for, in Hex's interface language ("English").
var language: String
/// What Hex's own model is doing ("Optimizing for this iPhone… about a minute"), while it
/// prepares.
var detail: String?
/// Whether Hex downloads a model for it: not for Apple's on-device recognizer before iOS 26,
/// which only needs Speech Recognition allowed.
var downloads = true
var isReady: Bool { stage == .ready }
var isFailed: Bool {
if case .failed = stage { return true }
return false
}
var fraction: Double {
switch stage {
case .downloading(let fraction): fraction
case .ready: 1
default: 0
}
}
/// Hex's own model and the one the Hex key dictates with (KeyboardSpeechPreparation): ready
/// only once both are, so Ready means the Hex key works in other apps.
@MainActor
init(dictation: DictationController, keyboard: KeyboardSpeechPreparation) {
let app: Stage
if dictation.isModelReady {
app = .ready
} else {
switch dictation.phase {
case .preparingModel:
app = .downloading(dictation.modelPreparation.fractionCompleted)
detail = dictation.modelPreparation.detail
case .failed(let message): app = .failed(message)
default: app = .starting
}
}
let keys: Stage? = switch keyboard.state {
case .ready, .followsApp: keyboard.downloads ? .ready : nil
case .downloading(let fraction): .downloading(fraction)
case .failed(let message): .failed(message)
case .checking: .starting
}
stage = Self.combine(app, keys)
downloads = dictation.engineDownloads
let id: String
if dictation.isModelReady {
id = dictation.transcriptionLanguageID
} else if dictation.engineName == "Parakeet V2" {
id = "en-US"
} else {
id = LanguageSettings().effectiveDictationLanguage ?? Locale.preferredLanguages.first ?? "en-US"
}
language = SpeechModelUnavailable.interfaceName(id)
}
init(stage: Stage, language: String, detail: String? = nil) {
self.stage = stage
self.language = language
self.detail = detail
}
/// One stage for two downloads: a failure first, then ready only when both are, else the
/// two fractions averaged (a ready one counts as whole). No "b": the keyboard has nothing
/// to download.
static func combine(_ a: Stage, _ b: Stage?) -> Stage {
guard let b else { return a }
if case .failed = a { return a }
if case .failed = b { return b }
if a == .ready, b == .ready { return .ready }
if a == .starting, b == .starting { return .starting }
func fraction(_ stage: Stage) -> Double {
switch stage {
case .ready: 1
case .downloading(let value): value
default: 0
}
}
return .downloading((fraction(a) + fraction(b)) / 2)
}
}
struct OnboardingView: View {
@Environment(\.scenePhase) private var scenePhase
@Environment(\.accessibilityReduceMotion) private var reduceMotion
let dictation: DictationController
let monitor: KeyboardSetupMonitor
let keyboardSpeech: KeyboardSpeechPreparation
@Binding var page: OnboardingPage?
@Namespace private var pillSpace
@State private var tryText = OnboardingFixture.current == .tryDone ? "On my way, see you at ten." : ""
@State private var fixtureModel: OnboardingModel? = OnboardingView.initialFixtureModel
private static var initialFixtureModel: OnboardingModel? {
guard let fixture = OnboardingFixture.current else { return nil }
let english = SpeechModelUnavailable.interfaceName("en-US")
if fixture == .failed {
return OnboardingModel(
stage: .failed(String(localized: "Hex couldn't download the speech model. Check your connection and try again.")),
language: english
)
}
if let fraction = fixture.modelFraction {
return OnboardingModel(
stage: .downloading(fraction),
language: english,
detail: String(localized: "Downloading the speech model")
)
}
return OnboardingModel(stage: .ready, language: english)
}
private var model: OnboardingModel {
fixtureModel ?? OnboardingModel(dictation: dictation, keyboard: keyboardSpeech)
}
var body: some View {
ZStack {
switch page {
case .setup?:
OnboardingSetupPage(model: model, onRetry: retryModel) { go(to: .demo) }
.transition(pageTransition)
case .demo?:
OnboardingDemoPage(model: model) { go(to: .permissions) }
.transition(pageTransition)
case .permissions?:
OnboardingPermissionsPage(monitor: monitor, model: model) {
go(to: model.isReady ? .practice : .waiting)
}
.transition(pageTransition)
case .waiting?:
OnboardingWaitingPage(
model: model,
onRetry: retryModel,
onWithoutModel: finish,
onReady: { go(to: .practice) }
)
.transition(pageTransition)
case .practice?:
OnboardingPracticePage(monitor: monitor, model: model, text: $tryText) {
go(to: .ready)
}
.transition(pageTransition)
case .ready?:
OnboardingReadyPage(
monitor: monitor,
model: model,
onRetry: retryModel,
onTryAgain: { go(to: .practice) },
onStart: finish
)
.transition(pageTransition)
case nil:
EmptyView()
}
}
.frame(maxWidth: 500)
.padding(.horizontal, 20)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.environment(\.onboardingPillSpace, reduceMotion ? nil : pillSpace)
.task {
while !Task.isCancelled {
monitor.refresh()
try? await Task.sleep(for: .seconds(1))
}
}
.onChange(of: scenePhase) { _, phase in
if phase == .active {
monitor.refresh()
}
}
.task { await startModelDownload() }
.task { await runTour() }
}
/// The model starts downloading as onboarding opens, as on the desktop. Launch already
/// prepares a cached Parakeet or Apple Speech; this starts the Parakeet download that home's
/// Set up used to wait for, or, before iOS 26, gets Apple's on-device recognizer ready,
/// which asks for Speech Recognition here. A launch that found Parakeet ended mid-load
/// takes Apple's engine instead (SpeechEngineChoice), or stays failed where there's none.
private func startModelDownload() async {
guard !OnboardingFixture.isSnapshot else { return }
// Launch decides Apple Speech or Parakeet in a task of its own; let it answer first.
try? await Task.sleep(for: .milliseconds(600))
guard !Task.isCancelled, !dictation.isModelReady, dictation.phase == .modelRequired else { return }
dictation.prepareModel()
}
private func retryModel() {
guard !OnboardingFixture.isSnapshot else { return }
if !dictation.isModelReady {
dictation.prepareModel()
}
keyboardSpeech.start(retry: true) { dictation.engineName }
}
/// "onboarding-tour": steps through every page on the fixture timeline.
private func runTour() async {
guard OnboardingFixture.current == .tour else { return }
typealias Tour = OnboardingFixture.Tour
if Tour.start == nil {
Tour.start = Date().addingTimeInterval(Tour.leadIn)
}
let english = SpeechModelUnavailable.interfaceName("en-US")
while !Task.isCancelled {
let t = Tour.elapsed
monitor.refresh()
fixtureModel = t < Tour.modelReady
? OnboardingModel(stage: .downloading(min(0.97, 0.05 + 0.92 * max(0, t) / Tour.modelReady)), language: english)
: OnboardingModel(stage: .ready, language: english)
if t >= Tour.done {
finish()
return
} else if t >= Tour.toReady, page == .practice {
go(to: .ready)
} else if t >= Tour.text, tryText.isEmpty {
tryText = "On my way, see you at ten."
} else if t >= Tour.toTry, page == .waiting {
go(to: .practice)
} else if t >= Tour.toWaiting, page == .permissions {
go(to: .waiting)
} else if t >= Tour.toPermissions, page == .demo {
go(to: .permissions)
} else if t >= Tour.toDemo, page == .setup {
go(to: .demo)
}
try? await Task.sleep(for: .milliseconds(33))
}
}
/// The page leaving lifts away as the desktop's roll does; the arriving page's parts roll in
/// themselves, staggered (onboardingStagger).
private var pageTransition: AnyTransition {
guard !reduceMotion else { return .opacity }
return .asymmetric(
insertion: .identity,
removal: AnyTransition.opacity
.combined(with: .offset(y: -OnboardingMotion.travel))
.animation(OnboardingMotion.exit)
)
}
private func go(to next: OnboardingPage) {
guard page != next else { return }
OnboardingProgress.save(next)
// The pill flies on the desktop's flight spring; the rest follows its own springs.
withAnimation(reduceMotion ? HexMotion.reducedFade : OnboardingMotion.fly) {
page = next
}
}
private func finish() {
OnboardingProgress.complete()
withAnimation(HexMotion.settleAnimation(reduceMotion: reduceMotion)) {
page = nil
}
}
}
// MARK: - Setting up Hex
/// Page 1: the model downloads by itself from the start, and the page moves on to the demo
/// after a beat. Only a failed start holds it, with Try again.
private struct OnboardingSetupPage: View {
let model: OnboardingModel
let onRetry: () -> Void
let onNext: () -> Void
var body: some View {
VStack(spacing: 0) {
Spacer(minLength: 24)
VStack(spacing: 14) {
HexMarkView(size: 56)
.padding(.bottom, 10)
.onboardingStagger(0)
OnboardingTitle("Setting up Hex")
.onboardingStagger(1)
HStack(spacing: 6) {
Text(model.isReady ? "Ready" : model.downloads ? "Downloading" : "Preparing")
OnboardingLanguageCapsule(language: model.language)
Text("speech model")
}
.font(.system(size: 15))
.foregroundStyle(HexTheme.textMuted)
.lineLimit(1)
.minimumScaleFactor(0.8)
.onboardingStagger(2)
if case .failed(let message) = model.stage {
OnboardingFailure(message: message, onRetry: onRetry)
.padding(.top, 6)
OnboardingQuietButton(title: "Continue", action: onNext)
} else {
OnboardingProgressPill(model: model, large: true)
.padding(.top, 6)
.onboardingStagger(3)
}
}
.frame(maxWidth: .infinity)
Spacer(minLength: 24)
OnboardingPrivacyLine()
.padding(.bottom, 16)
.onboardingStagger(4)
}
.task(id: model.isFailed) {
guard OnboardingFixture.autoAdvances, !model.isFailed else { return }
try? await Task.sleep(for: .seconds(2.6))
guard !Task.isCancelled else { return }
onNext()
}
}
}
// MARK: - The demo
/// Page 2, optional: a reply dictated with the Hex key, then on to permissions. Skip passes it.
private struct OnboardingDemoPage: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
let model: OnboardingModel
let onNext: () -> Void
@State private var beat = OnboardingFixture.current == .demo ? 3 : 0
@State private var shownWords = OnboardingFixture.current == .demo ? Int.max : 0
private var reply: String { String(localized: "On my way. Oat or regular?") }
private var replyWords: [Substring] { reply.split(separator: " ", omittingEmptySubsequences: true) }
private var typed: String {
replyWords.prefix(shownWords).joined(separator: " ")
}
var body: some View {
VStack(spacing: 0) {
OnboardingTopBar(model: model, onSkip: onNext)
VStack(spacing: 10) {
OnboardingTitle("With Hex")
Text("Tap the Hex key and say it.")
.font(.system(size: 15))
.foregroundStyle(HexTheme.textMuted)
}
.padding(.top, 12)
.padding(.bottom, 24)
.onboardingStagger(1)
stage
.onboardingStagger(2)
Spacer(minLength: 16)
}
.task { await play() }
}
private var stage: some View {
VStack(alignment: .leading, spacing: 14) {
HStack(spacing: 10) {
Text(verbatim: "S")
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(HexTheme.textBase)
.frame(width: 30, height: 30)
.background(Color.white.opacity(0.12), in: Circle())
Text(verbatim: "Sam")
.font(.system(size: 15, weight: .semibold))
.foregroundStyle(HexTheme.textBase)
Spacer()
}
bubble(String(localized: "Are you near the store? Could you grab some milk?"), mine: false)
if beat >= 4 {
bubble(reply, mine: true)
.transition(.opacity.combined(with: .offset(y: 6)))
}
HStack(spacing: 10) {
Group {
if beat >= 4 || typed.isEmpty {
Text("Message").foregroundStyle(HexTheme.textFaint)
} else {
Text(typed).foregroundStyle(HexTheme.textBase)
}
}
.font(.system(size: 15))
.lineLimit(1)
Spacer(minLength: 8)
// The Hex key, lit while it listens.
HexMarkView(size: 16, color: beat == 1 || beat == 2 ? HexTheme.textContrast : HexTheme.textBase)
.frame(width: 34, height: 30)
.background(beat == 1 || beat == 2 ? HexTheme.bgContrast : Color.white.opacity(0.09), in: Capsule())
}
.padding(.leading, 14)
.padding(.trailing, 6)
.frame(height: 42)
.background(Color.white.opacity(0.06), in: Capsule())
}
.padding(16)
.background(HexTheme.bgBase, in: RoundedRectangle(cornerRadius: HexTheme.cardRadius, style: .continuous))
.animation(HexMotion.settleAnimation(reduceMotion: reduceMotion), value: beat)
.animation(HexMotion.reducedFade, value: shownWords)
.accessibilityElement(children: .combine)
}
private func bubble(_ text: String, mine: Bool) -> some View {
HStack {
if mine { Spacer(minLength: 40) }
Text(text)
.font(.system(size: 15))
.foregroundStyle(mine ? HexTheme.textContrast : HexTheme.textBase)
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(mine ? HexTheme.bgContrast : Color.white.opacity(0.09), in: RoundedRectangle(cornerRadius: 16, style: .continuous))
if !mine { Spacer(minLength: 40) }
}
}
/// Hex key down, the words arrive, sent, then on to permissions.
private func play() async {
guard OnboardingFixture.current != .demo else { return }
if reduceMotion {
beat = 4
shownWords = Int.max
} else {
try? await Task.sleep(for: .seconds(0.9))
beat = 1
try? await Task.sleep(for: .seconds(0.9))
beat = 2
for index in 1...replyWords.count {
guard !Task.isCancelled else { return }
shownWords = index
try? await Task.sleep(for: .seconds(0.2))
}
beat = 3
try? await Task.sleep(for: .seconds(0.6))
beat = 4
}
try? await Task.sleep(for: .seconds(1.8))
guard !Task.isCancelled, OnboardingFixture.autoAdvances else { return }
onNext()
}
}
// MARK: - Permissions
/// Page 3: the microphone and the Hex keyboard. No Skip, as on the desktop, but Continue never
/// waits on them: someone who declines the microphone can still type with Hex and allow it
/// later (App Review 5.1.1(iv)). Full Access can't be verified from the app; the practice
/// checks it. Moves on by itself once both rows are done.
private struct OnboardingPermissionsPage: View {
@Environment(\.openURL) private var openURL
let monitor: KeyboardSetupMonitor
let model: OnboardingModel
let onContinue: () -> Void
@State private var showsKeyboardFallback = false
private var microphoneDone: Bool { monitor.microphone == .granted }
private var keyboardDone: Bool { monitor.keyboardAdded == true }
/// Before iOS's microphone prompt, Hex's own buttons say Continue or Open Settings, never
/// Allow (App Review 5.1.1(iv)).
private func continueTapped() {
if monitor.microphone == .undetermined {
monitor.requestMicrophone { onContinue() }
} else {
onContinue()
}
}
var body: some View {
VStack(spacing: 0) {
OnboardingTopBar(model: model, onSkip: nil)
Spacer(minLength: 16)
VStack(spacing: 10) {
OnboardingTitle("Let Hex hear you")
Text("Hex listens only after you tap the Hex key.")
.font(.system(size: 15))
.foregroundStyle(HexTheme.textMuted)
.multilineTextAlignment(.center)
}
.padding(.bottom, 24)
.onboardingStagger(1)
VStack(spacing: 0) {
OnboardingPermissionRow(
icon: "mic",
title: "Microphone",
detail: "So Hex can hear you",
done: microphoneDone,
// iOS asks right after this tap, so the pill says Continue, never Allow.
actionTitle: monitor.microphone == .denied ? "Open Settings" : "Continue"
) {
if monitor.microphone == .denied {
openSettings(openURL)
} else {
monitor.requestMicrophone()
}
}
Rectangle().fill(HexTheme.borderWeak).frame(height: 0.5)
OnboardingPermissionRow(
icon: "keyboard",
title: "Hex keyboard",
detail: "With Full Access",
done: keyboardDone,
actionTitle: "Open Settings"
) {
openSettings(openURL)
}
}
.padding(.horizontal, 16)
.background(HexTheme.bgBase, in: RoundedRectangle(cornerRadius: HexTheme.cardRadius, style: .continuous))
.onboardingStagger(2)
VStack(alignment: .leading, spacing: 8) {
Text("Keyboards › Hex Keyboard › Allow Full Access")
Button {
withAnimation(HexMotion.reducedFade) { showsKeyboardFallback.toggle() }
} label: {
Text("Don't see Keyboards?")
.underline()
}
.buttonStyle(.plain)
if showsKeyboardFallback {
Text("General › Keyboard › Keyboards › Add New Keyboard › Hex")
.transition(.opacity)
}
}
.font(.system(size: 13))
.foregroundStyle(HexTheme.textMuted)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 4)
.padding(.top, 14)
.opacity(keyboardDone ? 0 : 1)
.accessibilityHidden(keyboardDone)
.onboardingStagger(3)
Spacer(minLength: 16)
OnboardingPrivacyLine()
.padding(.bottom, 14)
.onboardingStagger(4)
OnboardingPrimaryButton(title: "Continue", enabled: monitor.keyboardAdded != false, action: continueTapped)
.padding(.bottom, 12)
.onboardingStagger(5)
}
.task(id: microphoneDone && keyboardDone) {
guard OnboardingFixture.autoAdvances, microphoneDone, keyboardDone else { return }
try? await Task.sleep(for: .seconds(0.8))
guard !Task.isCancelled else { return }
onContinue()
}
}
}
// MARK: - Almost ready
/// Page 4, only while the model still downloads: the practice needs it. Continue without a
/// model shows only once the download failed or stalled.
private struct OnboardingWaitingPage: View {
let model: OnboardingModel
let onRetry: () -> Void
let onWithoutModel: () -> Void
let onReady: () -> Void
var body: some View {
VStack(spacing: 0) {
Spacer(minLength: 24)
OnboardingModelWait(model: model, onRetry: onRetry, onWithoutModel: onWithoutModel)
.onboardingStagger(1)
Spacer(minLength: 24)
}
.task(id: model.isReady) {
guard OnboardingFixture.autoAdvances, model.isReady else { return }
try? await Task.sleep(for: .seconds(0.7))
guard !Task.isCancelled else { return }
onReady()
}
}
}
/// "Almost ready" with the download's progress, Try again after a failure, and Continue without
/// a model after a failure or 30 s without progress.
struct OnboardingModelWait: View {
let model: OnboardingModel
let onRetry: () -> Void
let onWithoutModel: () -> Void
@State private var lastFraction = -1.0
@State private var stalled = OnboardingFixture.current == .failed
/// A download that gained nothing for this long has stalled.
private static let stallAfter: Duration = .seconds(30)
var body: some View {
VStack(spacing: 14) {
OnboardingTitle("Almost ready")
Text("Finishing the speech model so Hex can hear you.")
.font(.system(size: 15))
.foregroundStyle(HexTheme.textMuted)
.multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true)
if case .failed(let message) = model.stage {
OnboardingFailure(message: message, onRetry: onRetry)
.padding(.top, 6)
} else {
VStack(alignment: .leading, spacing: 8) {
ProgressView(value: model.fraction)
.tint(HexTheme.textBase)
HStack(alignment: .firstTextBaseline, spacing: 8) {
if let detail = model.detail {
Text(detail)
.lineLimit(2)
.fixedSize(horizontal: false, vertical: true)
}
Spacer(minLength: 0)
Text(model.fraction, format: .percent.precision(.fractionLength(0)))
.monospacedDigit()
}
.font(.system(size: 13))
.foregroundStyle(HexTheme.textMuted)
}
.frame(maxWidth: 260)
.padding(.top, 10)
}
if model.isFailed || stalled {
VStack(spacing: 6) {
OnboardingQuietButton(title: "Continue without a model", action: onWithoutModel)
Text(model.downloads ? "Dictation won't work until the speech model downloads." : "Dictation won't work until speech recognition is ready.")
.font(.system(size: 13))
.foregroundStyle(HexTheme.textFaint)
.multilineTextAlignment(.center)
}
.padding(.top, 10)
}
}
.frame(maxWidth: .infinity)
.task(id: model.fraction) {
guard !model.isReady, !model.isFailed else { return }
if lastFraction != model.fraction {
lastFraction = model.fraction
if OnboardingFixture.current != .failed { stalled = false }
}
try? await Task.sleep(for: Self.stallAfter)
guard !Task.isCancelled else { return }
stalled = true
}
}
}
// MARK: - Your turn
/// Page 5, optional: the practice, with the Hex keyboard in a field that keeps the keyboard up.
/// It counts once a dictation arrives or a few words are typed, and the done state keeps the
/// keyboard.
private struct OnboardingPracticePage: View {
@Environment(\.openURL) private var openURL
@Environment(\.scenePhase) private var scenePhase
@Environment(\.accessibilityReduceMotion) private var reduceMotion
let monitor: KeyboardSetupMonitor
let model: OnboardingModel
@Binding var text: String
let onNext: () -> Void
@State private var dictated = OnboardingFixture.current == .tryDone
@State private var heardNothing = OnboardingFixture.current == .tryEmpty
@State private var keyboardActivity = 0
@State private var lastSwitchAt: Date?
@State private var keyboardCameUpAt = Date.distantPast
@State private var fullAccessLooksOff = OnboardingFixture.current == .tryOff
@FocusState private var fieldFocused: Bool
/// How long the keyboard gets to report Full Access after a switch or new text.
private static let fullAccessGrace: Duration = .seconds(4)
/// The keyboard coming up (focus, or back from Settings) also posts an input mode change.
private static let keyboardSettle: TimeInterval = 1.5
private var hasText: Bool {
!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
private var complete: Bool {
OnboardingPractice.isDone(text: text, dictated: dictated, fullAccessOn: monitor.fullAccessOn)
}
var body: some View {
VStack(spacing: 0) {
OnboardingTopBar(model: model, onSkip: complete ? nil : onNext)
ScrollView {
VStack(alignment: .leading, spacing: 16) {
HStack(alignment: .center, spacing: 10) {
if complete {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 24, weight: .medium))
.foregroundStyle(HexTheme.success)
.transition(.opacity.combined(with: .scale(scale: 0.9)))
}
OnboardingTitle(complete ? "That's Hex" : "Your turn")
.contentTransition(.opacity)
}
.onboardingStagger(1)
Group {
if complete {
Text("It types wherever your cursor is, in any app.")
} else {
Text("Switch to Hex with \(Image(systemName: "globe")), then tap the Hex key.")
}
}
.font(.system(size: 15))
.foregroundStyle(HexTheme.textMuted)
.fixedSize(horizontal: false, vertical: true)
.padding(.top, -8)
.onboardingStagger(2)
TextField("Say anything…", text: $text, axis: .vertical)
.font(.system(size: 17))
.foregroundStyle(HexTheme.textBase)
.focused($fieldFocused)
.lineLimit(2...5)
.padding(.horizontal, 16)
.padding(.vertical, 14)
.background(HexTheme.bgBase, in: RoundedRectangle(cornerRadius: HexTheme.cardRadius, style: .continuous))
.onboardingStagger(3)
if heardNothing && !complete {
HStack(alignment: .top, spacing: 8) {
Image(systemName: "waveform")
.font(.system(size: 13, weight: .medium))
.padding(.top, 1)
Text("Hex didn't hear any words. Try again a little louder.")
}
.font(.system(size: 13))
.foregroundStyle(HexTheme.textMuted)
.padding(.horizontal, 4)
.transition(.opacity)
}
if fullAccessLooksOff && !monitor.fullAccessOn {
fullAccessNote
.transition(.opacity.combined(with: .scale(scale: 0.98)))
}
}
.padding(.top, 12)
.padding(.bottom, 16)
}
.scrollBounceBehavior(.basedOnSize)
OnboardingPrimaryButton(title: "Continue", action: onNext)
.hexControlReveal(complete, reduceMotion: reduceMotion, scale: 0.96)
.allowsHitTesting(complete)
.padding(.top, 8)
.padding(.bottom, 12)
}
.animation(HexMotion.settleAnimation(reduceMotion: reduceMotion), value: complete)
.animation(HexMotion.settleAnimation(reduceMotion: reduceMotion), value: fullAccessLooksOff)
.animation(HexMotion.reducedFade, value: heardNothing)
.onAppear {
guard OnboardingFixture.current != .tryDone else { return }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
fieldFocused = true
}
}
.task { await watchKeyboardDictations() }
.onReceive(NotificationCenter.default.publisher(for: UITextInputMode.currentInputModeDidChangeNotification)) { _ in
lastSwitchAt = Date()
noteKeyboardActivity()
}
.onChange(of: fieldFocused) { _, focused in
if focused { keyboardCameUpAt = Date() }
}
.onChange(of: scenePhase) { _, phase in
guard phase == .active else { return }
keyboardCameUpAt = Date()
// The page can open while Hex comes back from Settings, before it can take focus.
if !fieldFocused && OnboardingFixture.current != .tryDone {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { fieldFocused = true }
}
}
.onChange(of: text) { _, _ in
if hasText {
heardNothing = false
noteKeyboardActivity()
}
}
.onChange(of: monitor.fullAccessOn) { _, on in
if on { fullAccessLooksOff = false }
}
.task(id: keyboardActivity) {
// iOS tells only the keyboard about Full Access, and the keyboard writes it to the
// App Group as soon as it opens with it; nothing a few seconds after a keyboard
// switch or new text means it's off (or the Hex keyboard isn't the one up).
guard keyboardActivity > 0 else { return }
try? await Task.sleep(for: Self.fullAccessGrace)
guard !Task.isCancelled, !monitor.fullAccessOn else { return }
if !hasText, let switchedAt = lastSwitchAt,
abs(switchedAt.timeIntervalSince(keyboardCameUpAt)) < Self.keyboardSettle {
return
}
fullAccessLooksOff = true
}
}
/// The keyboard's dictations, through the App Group: a new inserted result means one
/// arrived; a new empty one means it heard nothing (the keyboard itself stays quiet).
private func watchKeyboardDictations() async {
guard !OnboardingFixture.isSnapshot else { return }
let bridge = KeyboardBridge()
let insertedAtStart = bridge.lastInsertedResultID
var emptyAtStart = bridge.lastEmptyDictationAt
while !Task.isCancelled {
try? await Task.sleep(for: .milliseconds(250))
if bridge.lastInsertedResultID != insertedAtStart {
dictated = true
heardNothing = false
}
let empty = bridge.lastEmptyDictationAt
if let empty, empty != emptyAtStart {
emptyAtStart = empty
if !dictated { heardNothing = true }
}
}
}
private func noteKeyboardActivity() {
guard !monitor.fullAccessOn else { return }
keyboardActivity += 1
}
private var fullAccessNote: some View {
VStack(alignment: .leading, spacing: 14) {
HStack(alignment: .top, spacing: 10) {
Image(systemName: "exclamationmark.circle.fill")
.font(.system(size: 16, weight: .medium))
.foregroundStyle(HexTheme.warmMic)
.padding(.top, 1)
Text("Turn on Allow Full Access")
.font(.system(size: 15, weight: .medium))
.foregroundStyle(HexTheme.textBase)
}
.accessibilityElement(children: .combine)
OnboardingSecondaryButton(title: "Open Settings", icon: "gearshape.fill") {
openSettings(openURL)
}
}
.padding(16)
.background(HexTheme.bgBase, in: RoundedRectangle(cornerRadius: HexTheme.cardRadius, style: .continuous))
}
}
// MARK: - Hex is ready
/// Page 6. "Hex is ready" only once every step is done (the model included); until then it
/// says what's left. Start using Hex never waits on it (App Review 5.1.1(iv)).
private struct OnboardingReadyPage: View {
@Environment(\.openURL) private var openURL
let monitor: KeyboardSetupMonitor
let model: OnboardingModel
let onRetry: () -> Void
let onTryAgain: () -> Void
let onStart: () -> Void
private enum Left {
case nothing
case model
case microphone
case keyboard
case fullAccess
}
private var left: Left {
if !model.isReady { return .model }
if monitor.microphone != .granted { return .microphone }
if monitor.keyboardAdded == false { return .keyboard }
if !monitor.fullAccessOn { return .fullAccess }
return .nothing
}
var body: some View {
VStack(spacing: 0) {
Spacer(minLength: 24)
Group {
switch left {
case .model:
OnboardingModelWait(model: model, onRetry: onRetry, onWithoutModel: onStart)
default:
VStack(spacing: 14) {
if left == .nothing {
HexMarkView(size: 56)
.padding(.bottom, 10)
}
OnboardingTitle(left == .nothing ? "Hex is ready" : "Almost ready")
subtitle
.font(.system(size: 15))
.foregroundStyle(HexTheme.textMuted)
.multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true)
if left == .microphone || left == .keyboard {
OnboardingQuietButton(title: "Open Settings") { openSettings(openURL) }
.padding(.top, 4)
}
}
.frame(maxWidth: .infinity)
}
}
.onboardingStagger(1)
Spacer(minLength: 24)
if left != .model {
OnboardingQuietButton(title: "Try again", action: onTryAgain)
.padding(.bottom, 8)
.onboardingStagger(2)
}
OnboardingPrimaryButton(title: "Start using Hex", action: onStart)
.padding(.bottom, 12)
.onboardingStagger(3)
}
}
@ViewBuilder
private var subtitle: some View {
switch left {
case .nothing, .model: Text("Tap the Hex key in any app to talk.")
case .microphone: Text("Turn on the microphone in Settings so Hex can hear you.")
case .keyboard: Text("Add the Hex keyboard in Settings.")
case .fullAccess: Text("Use the Hex keyboard once to finish.")
}
}
}