mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS: launch screen in the app's first-frame black
The launch screen's LaunchBackground was a dark teal (sRGB 7,17,20, shown
as about 2,17,19) for the ~1.5 s before the app's first frame, which is
HexTheme.bgDeep (0x0A0B0D). It now uses bgDeep's exact components, so
launch hands over to the app without a colour jump.
Verified: built for Simulator; fresh-install launch recorded.
* iOS: onboarding follows the desktop's pages, with the polish fixes
Dax found the iPhone onboarding annoying; Ryan and Dax asked for the
desktop's flow. The three pages (Welcome, Set up Hex, Try the keyboard)
become the desktop's six, in its order and copy style:
1. Setting up Hex: the speech model starts downloading as onboarding
opens (whichever engine transcriberFactory picks). Before, only home's
"Set up" started a Parakeet download, so onboarding said "You're all
set" while home said "Finish setup · 1 step". A launch that found
Parakeet ended mid-load stays failed (ParakeetLoadGuard) until Try
again. Moves on after a beat; a failed start holds it with Try again.
2. With Hex: a short demo, a reply dictated with the Hex key. Skip.
3. Let Hex hear you: Microphone and Hex keyboard rows with a one-line
detail that stays (steady heights) and one-line copy ("With Full
Access", no mid-phrase wrap). A done row shows only its check (the
Keyboard row used to keep its Open Settings pill). The pill and the
page's button say Continue before iOS's prompt (App Review 5.1.1(iv)),
Continue never needs the microphone, and the page moves on once both
rows are done. No Skip.
4. Almost ready: only while the model downloads, with its progress;
Continue without a model only after a failure or 30 s without progress.
5. Your turn: the practice. The field keeps the keyboard up (the old
page unfocused it ~150 ms after the first letter) and counts once a
dictation arrives (lastInsertedResultID changes) or three words are
typed with Full Access. An empty dictation says "Hex didn't hear any
words. Try again a little louder." on this page only; the keyboard
notes it in the App Group (keyboard.lastEmptyDictationAt) and still
shows nothing itself. Skip.
6. Hex is ready: only once every step (model included) is done, else
"Almost ready" with what's left. Start using Hex never waits.
The download's pill (language and percent) sits in the top bar until the
model is ready; Skip shows on the demo and the practice only. The page
counter and Back are gone, as on the desktop. Saved pages from earlier
builds resume on their new equivalents. Snapshot scenes are renamed
onboarding-setup/-demo/-permissions(-done)/-waiting/-failed/-try(-done,
-empty,-off)/-ready, plus onboarding-tour. zh-Hans strings added.
Verified: xcodebuild test on an iOS 27.2 simulator (385 tests, 0
failures, 1 skipped), including new KeyboardBridgeTests for the empty
dictation note, the practice rule, and saved-page migration; English and
Chinese snapshots of every page; a fresh-install recording.
* iOS onboarding: the practice field takes focus when Hex comes back
Coming back from Settings with both permission rows done moves straight
on to Your turn, but the page opened before Hex was active again, so its
field never took focus and the keyboard stayed down. The page now
focuses the field again when the scene becomes active (unless it already
has focus).
Verified: fresh-install recording on an iOS 27.2 simulator: back from
Settings, Your turn opens with the keyboard up.
* iOS: Ready waits for the model the Hex key itself dictates with
On iOS 26 the keyboard transcribes inside itself with Apple Speech,
whatever Hex uses. When Hex dictates with Parakeet (an English iPhone
without SpeechTranscriber, or a cached Parakeet model), onboarding and
home said Ready while the keyboard's Apple Speech model wasn't there,
and the first Hex key tap said "Open Hex to download English."
KeyboardSpeechPreparation (owned by ContentView, started at launch)
prepares the keyboard's engine:
- Hex dictates with Apple Speech: Hex's model is the same one, so it
follows Hex's.
- Otherwise it resolves the keyboard's language (AppleSpeechLanguages,
as the keyboard does) and installs it with AppleSpeechAssets.install,
the keyboard's own call, which also clears keyboardNeedsHex.
- Apple has no model for it on this iPhone, or Speech lists nothing: it
marks keyboardNeedsHex, so the Hex key opens Hex (which dictates with
its own model) from the first tap instead of after a failed one.
Re-marked at each launch, as the mark lasts a day.
- A failed download (connection) shows on onboarding with Try again.
Why not have the keyboard use Hex's Parakeet: it can't load within a
keyboard extension's memory limit, and handing every dictation to Hex
leaves the app being typed in each time. In-keyboard Apple Speech stays
the path, with the handoff only where Apple has no model.
Onboarding's model stage combines both (OnboardingModel.combine): ready
only when both are, a failure first, fractions averaged only when the
keyboard actually downloads. Home's status line and the setup sheet's
Speech model row count it the same way.
Verified: xcodebuild test, iOS 27.2 simulator: 386 tests, 0 failures,
1 skipped (new: the combine rules). In the simulator (no Apple Speech
assets: "not subscribed to assistant.en_US") it marks the handoff and
onboarding goes on to Parakeet's Ready; a real iPhone must confirm the
Apple Speech download path.
* iOS onboarding: the desktop's motion, the pill flying between places
The desktop onboarding's motion (onboarding_kit/landing.rs, pill.rs):
- Each page's parts roll in 8 pt with a fade on a 0.34 s zero-bounce
spring, 0.05 s apart (onboardingStagger), and the leaving page lifts
away 8 pt on 0.26 s. Replaces the old 28 pt sideways page slide.
- The download pill flies from under Setting up Hex to the top bar and
stays there across pages (matchedGeometryEffect), on the desktop's
0.42 s flight spring.
- Reduce Motion: parts fade without moving or staggering, the pill
cross-fades, pages fade.
Stills (--snap-state) show every part at once.
"Watch another one" stays off: on the desktop it fills a long download
on Almost ready; on iPhone the demo is ~6 s and moves on by itself, so a
replay control would only add a label.
Verified: xcodebuild test (386, 0 failures, 1 skipped); fresh-install
recording on an iOS 27.2 simulator, frames checked at each page change.
* iOS onboarding: steady progress and an untruncated pill in flight
Two things the recording showed:
- In the simulator the keyboard's Apple Speech download starts, then
can't be had and hands off to Hex; that short attempt still counted as
half of onboarding's progress, so the percent jumped from 0% to 50%.
A handoff no longer counts as a download.
- The pill flew with its frame, so the small pill's language truncated
("Engli… 2%") for about half a second after landing. It now flies by
position only; each pill keeps its own size.
Verified: fresh-install recording on an iOS 27.2 simulator, frames at
15 fps around the Setting up Hex to demo change, and the percent climbing
from 0% in steps.
410 lines
13 KiB
Swift
410 lines
13 KiB
Swift
import Foundation
|
|
|
|
nonisolated enum KeyboardDictationState: String, Codable, Sendable {
|
|
case offline
|
|
case ready
|
|
case recording
|
|
case transcribing
|
|
case failed
|
|
}
|
|
|
|
nonisolated enum WarmSessionDuration: String, Codable, CaseIterable, Sendable {
|
|
case off
|
|
case fiveMinutes
|
|
case fifteenMinutes
|
|
case oneHour
|
|
|
|
var seconds: TimeInterval? {
|
|
switch self {
|
|
case .off: nil
|
|
case .fiveMinutes: 5 * 60
|
|
case .fifteenMinutes: 15 * 60
|
|
case .oneHour: 60 * 60
|
|
}
|
|
}
|
|
|
|
var shortLabel: String {
|
|
switch self {
|
|
case .off: String(localized: "Off")
|
|
case .fiveMinutes: String(localized: "5m")
|
|
case .fifteenMinutes: String(localized: "15m")
|
|
case .oneHour: String(localized: "1h")
|
|
}
|
|
}
|
|
|
|
var title: String {
|
|
switch self {
|
|
case .off: String(localized: "One shot")
|
|
case .fiveMinutes: String(localized: "5 minutes")
|
|
case .fifteenMinutes: String(localized: "15 minutes")
|
|
case .oneHour: String(localized: "1 hour")
|
|
}
|
|
}
|
|
}
|
|
|
|
nonisolated enum KeyboardCommandKind: String, Codable, Sendable {
|
|
case start
|
|
case stop
|
|
case cancel
|
|
}
|
|
|
|
nonisolated struct KeyboardCommand: Codable, Equatable, Sendable {
|
|
let id: String
|
|
let kind: KeyboardCommandKind
|
|
let jobID: String
|
|
let style: DictationStyle
|
|
let sentAt: TimeInterval
|
|
|
|
init(
|
|
id: String = UUID().uuidString,
|
|
kind: KeyboardCommandKind,
|
|
jobID: String,
|
|
style: DictationStyle = .polished,
|
|
sentAt: TimeInterval = Date().timeIntervalSince1970
|
|
) {
|
|
self.id = id
|
|
self.kind = kind
|
|
self.jobID = jobID
|
|
self.style = style
|
|
self.sentAt = sentAt
|
|
}
|
|
}
|
|
|
|
nonisolated enum KeyboardLaunchRequest: Equatable, Sendable {
|
|
/// Any cold-start recording handoff older than 10 seconds warms the session instead of surprise-recording.
|
|
static let handoffWindow: TimeInterval = 10.0
|
|
|
|
/// Opens Hex's keyboard setup screen without starting a session.
|
|
case setup
|
|
case startSession(requestedAt: TimeInterval?)
|
|
case startRecording(
|
|
jobID: String,
|
|
requestedAt: TimeInterval?,
|
|
style: DictationStyle?
|
|
)
|
|
|
|
init?(url: URL) {
|
|
guard url.scheme == "hex-dictation", url.host == "keyboard" else { return nil }
|
|
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
|
|
let query = components?.queryItems ?? []
|
|
|
|
func value(_ name: String) -> String? {
|
|
guard let v = query.first(where: { $0.name == name })?.value, !v.isEmpty else {
|
|
return nil
|
|
}
|
|
return v
|
|
}
|
|
|
|
let requestedAt = value("ts").flatMap(TimeInterval.init)
|
|
let style = value("style").flatMap(DictationStyle.init(rawValue:))
|
|
|
|
switch url.path {
|
|
case "/setup":
|
|
self = .setup
|
|
case "/start":
|
|
self = .startSession(requestedAt: requestedAt)
|
|
case "/record":
|
|
guard let jobID = value("job") else { return nil }
|
|
self = .startRecording(
|
|
jobID: jobID,
|
|
requestedAt: requestedAt,
|
|
style: style
|
|
)
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
var requestedAt: TimeInterval? {
|
|
switch self {
|
|
case .setup:
|
|
nil
|
|
case .startSession(let ts), .startRecording(_, let ts, _):
|
|
ts
|
|
}
|
|
}
|
|
|
|
func isHandoffExpired(at now: TimeInterval = Date().timeIntervalSince1970) -> Bool {
|
|
guard let requestedAt else { return false }
|
|
return now - requestedAt > Self.handoffWindow
|
|
}
|
|
|
|
var url: URL {
|
|
var components = URLComponents()
|
|
components.scheme = "hex-dictation"
|
|
components.host = "keyboard"
|
|
|
|
var items: [URLQueryItem] = []
|
|
switch self {
|
|
case .setup:
|
|
components.path = "/setup"
|
|
|
|
case .startSession(let requestedAt):
|
|
components.path = "/start"
|
|
if let requestedAt {
|
|
items.append(URLQueryItem(name: "ts", value: String(format: "%.3f", requestedAt)))
|
|
}
|
|
|
|
case .startRecording(let jobID, let requestedAt, let style):
|
|
components.path = "/record"
|
|
items.append(URLQueryItem(name: "job", value: jobID))
|
|
if let requestedAt {
|
|
items.append(URLQueryItem(name: "ts", value: String(format: "%.3f", requestedAt)))
|
|
}
|
|
if let style {
|
|
items.append(URLQueryItem(name: "style", value: style.rawValue))
|
|
}
|
|
}
|
|
|
|
if !items.isEmpty {
|
|
components.queryItems = items
|
|
}
|
|
return components.url!
|
|
}
|
|
}
|
|
|
|
nonisolated struct KeyboardSnapshot: Codable, Equatable, Sendable {
|
|
let state: KeyboardDictationState
|
|
let heartbeat: TimeInterval
|
|
let expiresAt: TimeInterval
|
|
let recordingStartedAt: TimeInterval?
|
|
let audioLevel: Float
|
|
let loudnessDB: Float?
|
|
let jobID: String?
|
|
let resultID: String?
|
|
let resultExpiresAt: TimeInterval?
|
|
let transcript: String?
|
|
let message: String?
|
|
/// The raw transcript behind `transcript`, before cleanup and formatting, sent only while
|
|
/// Learn how I type is on so the keyboard can tell misheard words from formatting.
|
|
/// Nil when it can't be learned from (translated) or the experiment is off.
|
|
let heard: String?
|
|
/// Record typing logs: what each step of the dictation made of it, sent only while
|
|
/// that experiment is on.
|
|
let stages: DictationStages?
|
|
|
|
init(
|
|
state: KeyboardDictationState,
|
|
heartbeat: TimeInterval,
|
|
expiresAt: TimeInterval,
|
|
recordingStartedAt: TimeInterval? = nil,
|
|
audioLevel: Float = 0,
|
|
loudnessDB: Float? = nil,
|
|
jobID: String? = nil,
|
|
resultID: String? = nil,
|
|
resultExpiresAt: TimeInterval? = nil,
|
|
transcript: String? = nil,
|
|
message: String? = nil,
|
|
heard: String? = nil,
|
|
stages: DictationStages? = nil
|
|
) {
|
|
self.state = state
|
|
self.heartbeat = heartbeat
|
|
self.expiresAt = expiresAt
|
|
self.recordingStartedAt = recordingStartedAt
|
|
self.audioLevel = audioLevel
|
|
self.loudnessDB = loudnessDB
|
|
self.jobID = jobID
|
|
self.resultID = resultID
|
|
self.resultExpiresAt = resultExpiresAt
|
|
self.transcript = transcript
|
|
self.message = message
|
|
self.heard = heard
|
|
self.stages = stages
|
|
}
|
|
|
|
var effectiveLoudnessDB: Float {
|
|
loudnessDB ?? DotScopeSimulation.loudness(fromNormalized: audioLevel)
|
|
}
|
|
|
|
static let offline = KeyboardSnapshot(
|
|
state: .offline,
|
|
heartbeat: 0,
|
|
expiresAt: 0
|
|
)
|
|
|
|
var isAvailable: Bool {
|
|
isAvailable(at: Date().timeIntervalSince1970)
|
|
}
|
|
|
|
/// True while the background warm session or an active capture/transcription heartbeat is live.
|
|
func isAvailable(at now: TimeInterval) -> Bool {
|
|
let heartbeatFresh = now - heartbeat < 3.0 && heartbeat > 0
|
|
guard heartbeatFresh else { return false }
|
|
if state == .recording || state == .transcribing {
|
|
return true
|
|
}
|
|
return expiresAt > now
|
|
}
|
|
|
|
/// Accepted jobs keep their completed transcript deliverable even after a one-shot or expiring session closes.
|
|
func hasDeliverableResult(at now: TimeInterval = Date().timeIntervalSince1970) -> Bool {
|
|
guard let resultID, !resultID.isEmpty,
|
|
let transcript, !transcript.isEmpty else {
|
|
return false
|
|
}
|
|
if let resultExpiresAt {
|
|
return resultExpiresAt > now
|
|
}
|
|
return true
|
|
}
|
|
|
|
func recordingElapsed(at now: TimeInterval = Date().timeIntervalSince1970) -> TimeInterval {
|
|
guard state == .recording, let recordingStartedAt else { return 0 }
|
|
return max(0, now - recordingStartedAt)
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
struct KeyboardBridge {
|
|
nonisolated static let appGroup = "group.anomaly.hex.mobile"
|
|
|
|
private enum Key {
|
|
static let command = "keyboard.command"
|
|
static let modelInstalled = "model.installed"
|
|
static let snapshot = "keyboard.snapshot"
|
|
static let warmDuration = "settings.warmDuration"
|
|
static let style = "settings.dictationStyle"
|
|
static let allowBluetoothMic = "settings.allowBluetoothMic"
|
|
static let lastInsertedResultID = "keyboard.lastInsertedResultID"
|
|
static let fullAccessSeenAt = "keyboard.fullAccessSeenAt"
|
|
static let appMicrophoneAllowed = "app.microphoneAllowed"
|
|
static let lastEmptyDictationAt = "keyboard.lastEmptyDictationAt"
|
|
}
|
|
|
|
private let defaults: UserDefaults?
|
|
private let encoder = JSONEncoder()
|
|
private let decoder = JSONDecoder()
|
|
|
|
init(defaults: UserDefaults? = UserDefaults(suiteName: Self.appGroup)) {
|
|
self.defaults = defaults
|
|
}
|
|
|
|
func send(
|
|
_ kind: KeyboardCommandKind,
|
|
jobID: String,
|
|
style: DictationStyle? = nil,
|
|
sentAt: TimeInterval = Date().timeIntervalSince1970
|
|
) {
|
|
let command = KeyboardCommand(
|
|
kind: kind,
|
|
jobID: jobID,
|
|
style: style ?? self.style,
|
|
sentAt: sentAt
|
|
)
|
|
guard let data = try? encoder.encode(command) else { return }
|
|
defaults?.set(data, forKey: Key.command)
|
|
}
|
|
|
|
func latestCommand() -> KeyboardCommand? {
|
|
guard let data = defaults?.data(forKey: Key.command) else { return nil }
|
|
return try? decoder.decode(KeyboardCommand.self, from: data)
|
|
}
|
|
|
|
var isModelInstalled: Bool {
|
|
defaults?.bool(forKey: Key.modelInstalled) ?? false
|
|
}
|
|
|
|
func setModelInstalled(_ installed: Bool) {
|
|
defaults?.set(installed, forKey: Key.modelInstalled)
|
|
}
|
|
|
|
var warmDuration: WarmSessionDuration {
|
|
get {
|
|
guard let raw = defaults?.string(forKey: Key.warmDuration),
|
|
let parsed = WarmSessionDuration(rawValue: raw) else {
|
|
return .fifteenMinutes
|
|
}
|
|
return parsed
|
|
}
|
|
nonmutating set {
|
|
defaults?.set(newValue.rawValue, forKey: Key.warmDuration)
|
|
}
|
|
}
|
|
|
|
var style: DictationStyle {
|
|
get {
|
|
guard let raw = defaults?.string(forKey: Key.style),
|
|
let parsed = DictationStyle(rawValue: raw) else {
|
|
return .polished
|
|
}
|
|
return parsed
|
|
}
|
|
nonmutating set {
|
|
defaults?.set(newValue.rawValue, forKey: Key.style)
|
|
}
|
|
}
|
|
|
|
var allowBluetoothMic: Bool {
|
|
get {
|
|
defaults?.bool(forKey: Key.allowBluetoothMic) ?? false
|
|
}
|
|
nonmutating set {
|
|
defaults?.set(newValue, forKey: Key.allowBluetoothMic)
|
|
}
|
|
}
|
|
|
|
var lastInsertedResultID: String? {
|
|
get {
|
|
defaults?.string(forKey: Key.lastInsertedResultID)
|
|
}
|
|
nonmutating set {
|
|
defaults?.set(newValue, forKey: Key.lastInsertedResultID)
|
|
}
|
|
}
|
|
|
|
/// When the keyboard last ran with Full Access. Without Full Access the keyboard
|
|
/// cannot write to the App Group at all, so only the keyboard sets this.
|
|
var fullAccessSeenAt: TimeInterval? {
|
|
get {
|
|
let value = defaults?.double(forKey: Key.fullAccessSeenAt) ?? 0
|
|
return value > 0 ? value : nil
|
|
}
|
|
nonmutating set {
|
|
if let newValue {
|
|
defaults?.set(newValue, forKey: Key.fullAccessSeenAt)
|
|
} else {
|
|
defaults?.removeObject(forKey: Key.fullAccessSeenAt)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether Hex has the microphone, as the app last read it. Only the app sets this. A
|
|
/// keyboard process keeps the permission it read when it started (iOS doesn't update it
|
|
/// there), so a keyboard opened before Hex was allowed the microphone needs the app's word.
|
|
var appMicrophoneAllowed: Bool {
|
|
get {
|
|
defaults?.bool(forKey: Key.appMicrophoneAllowed) ?? false
|
|
}
|
|
nonmutating set {
|
|
guard newValue != appMicrophoneAllowed else { return }
|
|
defaults?.set(newValue, forKey: Key.appMicrophoneAllowed)
|
|
}
|
|
}
|
|
|
|
/// When the keyboard's own dictation last ended with nothing to insert (no speech, or too
|
|
/// short). The keyboard stays quiet about it; onboarding's practice says it heard nothing.
|
|
var lastEmptyDictationAt: TimeInterval? {
|
|
get {
|
|
let value = defaults?.double(forKey: Key.lastEmptyDictationAt) ?? 0
|
|
return value > 0 ? value : nil
|
|
}
|
|
nonmutating set {
|
|
if let newValue {
|
|
defaults?.set(newValue, forKey: Key.lastEmptyDictationAt)
|
|
} else {
|
|
defaults?.removeObject(forKey: Key.lastEmptyDictationAt)
|
|
}
|
|
}
|
|
}
|
|
|
|
func publish(_ snapshot: KeyboardSnapshot) {
|
|
guard let data = try? encoder.encode(snapshot) else { return }
|
|
defaults?.set(data, forKey: Key.snapshot)
|
|
}
|
|
|
|
func snapshot() -> KeyboardSnapshot {
|
|
guard let data = defaults?.data(forKey: Key.snapshot) else { return .offline }
|
|
return (try? decoder.decode(KeyboardSnapshot.self, from: data)) ?? .offline
|
|
}
|
|
}
|