mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
* iOS: retry '!int' audio activation mixable and show audio errors as sentences
TestFlight testers saw "The operation couldn't be completed. (OSStatus error
560557684.)" in the keyboard strip and the app's setup card. 560557684 is
'!int' (AVAudioSession cannotInterruptOthers): a non-mixable session (the
Bluetooth-microphone .record category) going active from the background while
another app plays or records.
- AudioBackend: when setActive(true) fails with '!int', set .playAndRecord
with .mixWithOthers (keeping HFP when Bluetooth is allowed) and activate
once more, so the warm keepalive and captures start alongside the other
app's audio instead of failing.
- New UserFacingError (HEXShared, app and keyboard): AVAudioSession codes map
to short sentences ("Another app is using audio. Try again."); other
microphone errors get "Hex couldn't start the microphone. Try again.";
transcription and model errors keep their description only when it reads
as a sentence, never Foundation's "couldn't be completed (… error N)" or a
Swift type name.
- DictationController: every error it shows (phase .failed and the
keyboard's message) goes through UserFacingError instead of
localizedDescription.
Verified: xcodebuild test on the iPhone 18 Pro simulator, 179 tests pass,
including new tests for the code-to-sentence mapping and for a warm session
whose keepalive throws '!int' reaching the app and keyboard snapshot as
"Another app is using audio. Try again.". The background '!int' retry itself
needs a physical iPhone (music playing, Bluetooth mic allowed, warm session).
* iOS: end empty dictations quietly and keep error text human in the keyboard
Tapping Done (or ✕) in the keyboard's dictation screen without speaking
showed "Transcription failed: HEXKeyboard.(unknown context at $1…)": the
in-keyboard path printed the error's domain (a private Swift type name),
code and description for Apple Speech's "no words" result.
- New EmptyCapture rule (HEXShared): a capture under 0.3 s (or none at all)
is a tap, and an engine's no-speech error or a cancellation means nothing
was said; both end quietly. Engines say so through NoSpeechError
(Parakeet's and Apple Speech's emptyTranscript, the keyboard's
KeyboardSpeech.Failure.empty).
- KeyboardLocalDictation: Done before the microphone came up, or a capture
too short to hold a word, returns to idle without transcribing (and a late
"started" from WebKit stops the capture instead of opening a file);
no-speech ends quietly; a transcription error from a cancelled or
superseded job is dropped; every other failure shows a sentence from
UserFacingError or the keyboard's own copy, while the probe log keeps the
domain and code. KeyboardSpeech.Failure's descriptions are now sentences.
- DictationController (warm session and app): an engine's no-speech error
returns to Ready with no message instead of failing.
Verified: xcodebuild test on the iPhone 18 Pro simulator after rebasing onto
origin/dev (bba07c64), 210 tests pass (1 skipped as before), including new
tests for the empty-capture rule and for a warm keyboard dictation whose
transcriber hears nothing (Ready, no message) next to one that fails (a
sentence). The in-keyboard WebKit capture path needs a physical iPhone.
* iOS: start Live Activities only for system dictations and end them reliably
Testers saw Hex's activity (dots + ✓, expanded "Copied") stay in the
Dynamic Island, even with Keep mic warm Off. The ✓/Copied look is the
widget's stale rendering of an activity nobody ended: every recording
(keyboard warm dictations and in-app ones included) requested an activity,
and the end ran in a detached task that a suspending app (microphone just
released) could skip, so it went stale and stayed for hours.
- DictationController requests an activity only for dictations that copy
(Action Button, Control Center, Siri/Shortcuts); the keyboard and the app
show their own recording UI. Removed: the activity for keyboard and in-app
dictations.
- LiveActivityCoordinator: ending (cancel, failure, short capture, warm
session cancel) ends every Hex activity there is at that moment with
.immediate; Copied still lingers 2 s via .after. Ends run under a UIKit
background task, and a dictation that is transcribing keeps one until its
activity ends. A current activity the system already ended is replaced
rather than updated.
- Stale activities end at launch (DictationController.shared init), when Hex
becomes active, and when the warm session ends or Keep mic warm is set to
Off, unless a dictation is recording or transcribing.
- README: when Live Activities show and end.
Verified: xcodebuild test on the iPhone 18 Pro simulator, 210 tests pass
(1 skipped as before). A temporary, uncommitted test on the simulator showed
no activity for a warm keyboard dictation, one for a copy dictation that
ended after Copied, one ended at once on cancel, and an orphan activity
ended by Keep mic warm › Off. The Dynamic Island itself, and background
suspension timing, need a physical iPhone.
* iOS: give the dictation bar's keys the full keyboard's light haptic
The full keyboard taps under the finger (Experiments › Haptics, with Full
Access); the dictation bar's keys had no haptic at all.
- KeyboardViewModel gains onKeyFeedback; every control on the dictation bar
calls it: Hex mark, Dictate / Set up, ✕ and Done, Swipe and its return-app
chips, the style and language triggers and chips, the tray's close button,
space, return, and delete (each repeat, as the full keyboard's delete).
- KeyboardViewController plays a light impact at the full keyboard's 0.65
intensity, under the same rule the full keyboard now shares
(allowsKeyHaptics: Full Access and FullKeyboardSettings().haptics).
- Experiments: the Haptics switch moves out of the Full keyboard group so it
shows whether or not the full keyboard is on; same key
(settings.keyboardHaptics), subtitle now says it covers Hex's keys.
Verified: xcodebuild test on the iPhone 18 Pro simulator, 210 tests pass (1
skipped as before); Experiments rendered with --snap-state experiments shows
Haptics after Keyboard layout, outside the Full keyboard rows. The haptic
itself (and its Full Access gate) needs a physical iPhone; the simulator has
no Taptic Engine.
* iOS: lowercase a dictation that continues a sentence
A tester typed a few words, dictated, and the dictation started with a
capital as if it began a sentence: speech engines capitalize every result.
- TranscriptFormatter.startsSentence(after:): the text before the cursor ends
a sentence when it is empty or only spaces, or its last mark is . ! ? … 。
or a line break (closing quotes and brackets after them count too).
- TranscriptFormatter.continuingSentence: mid-sentence, the first letter goes
lowercase unless the first word is "I" or an I' contraction, all capitals
(2+ letters), has capitals inside (McDonald's), or its lowercase form isn't
in the dictation language's dictionary (likely a name).
- insertionText takes that dictionary (isWord; nil keeps the case), never
adds a second space after one already there (spaces at the start of the
dictation are dropped), and adds none after an opening ( [ { " “ ‘ « ¿ ¡.
- KeyboardViewController (the one place both keyboards insert a dictation)
passes a UITextChecker for the dictation language (Apple Speech's last
resolved language, else Settings' or Automatic's, else the first
preferred language), mapped by KeyboardLanguage.spellCheckLanguage(
forDictation:available:). German and Luxembourgish keep the case: on the
simulator de_DE accepts "auto" and "haus", so the name guard can't protect
their nouns. A language with no dictionary keeps the case too.
- README: the rule.
Verified: xcodebuild test on the iPhone 18 Pro simulator, 213 tests pass (1
skipped as before), with new tests for the sentence-start rule, the
exceptions, spacing, and the language-to-dictionary mapping. A temporary,
uncommitted test on the simulator's real UITextChecker found "sarah" and
"london" unknown and "the"/"that's" known in en_US, es and de_DE. How each
host app reports documentContextBeforeInput is unverified on a device.
* iOS: push to talk on the Hex key and the dictation bar's Dictate
A tester asked to hold to talk instead of tapping Dictate and then Done.
Rule: holding still for 0.35 s (HexKeyGesture.holdDuration, the Hex key's
existing hold) starts dictation at once, and lifting the finger finishes it
as Done does. A quick tap keeps tap to start, Done to finish. On the Hex key,
sliding more than 10 pt before the hold fires still opens the style menu;
once dictation has started, moving changes nothing. Push to talk applies
only when dictation runs in the keyboard (warm session or in-keyboard
dictation); a hold that opens Hex stays a tap.
- HexKeyGesture: a fired hold's touch-up is now .release (was ignored).
Changed: before, a hold started dictation and the release did nothing.
- HexKeyControl calls onHoldRelease; FullKeyboardView finishes the dictation
the hold started (model.onStopTap, logged as dictation_stop from
hex_key_release). The recording fade keeps a still-tracking Hex key in
the window at alpha 0 instead of hiding it, so its touch keeps arriving.
- KeyboardSurfaceView: the well tracks the press with a simultaneous
DragGesture on the same state machine (the Dictate button stops taking
touches once recording shows), starts with the light haptic
(onKeyFeedback: Haptics setting and Full Access), and finishes on release;
the button's own touch-up action skips a press the hold took.
- Accessibility hints mention holding; README and docs/typing-logs.md
describe it.
Verified: xcodebuild test on the iPhone 18 Pro simulator, 213 tests pass (1
skipped as before), including the updated HexKeyGesture tests (hold then
release finishes; moving after the hold is ignored). The dictation bar
renders as before (--snap-state keyboard-warm). Real touches (hold timing,
the bar's buttons with the well's gesture, the Hex key's touch surviving the
recording panel) were not driven on the simulator and need a physical
iPhone.
600 lines
25 KiB
Swift
600 lines
25 KiB
Swift
import AVFAudio
|
||
import Foundation
|
||
import os
|
||
import Speech
|
||
import UIKit
|
||
import WebKit
|
||
|
||
/// Experiment: record and transcribe inside the keyboard extension, so dictation
|
||
/// needs no Hex app process. Each step is logged to the App Group container
|
||
/// (`keyboard-capture-probe.log`) to measure permission and memory limits.
|
||
@MainActor
|
||
final class KeyboardLocalDictation {
|
||
private enum Phase {
|
||
case idle
|
||
case recording(jobID: String, startedAt: TimeInterval)
|
||
case transcribing(jobID: String)
|
||
case finished(jobID: String, resultID: String, transcript: String, heard: String?, stages: DictationStages?)
|
||
case failed(message: String, until: TimeInterval)
|
||
}
|
||
|
||
private var phase: Phase = .idle
|
||
private var capture: KeyboardWebCapture?
|
||
private var pcmFile: KeyboardPCMFile?
|
||
private var loudness: Float = -62
|
||
private var transcription: Task<Void, Never>?
|
||
/// Learn how I type's dictation fixes, read when a dictation starts; empty while off.
|
||
var corrections: () -> [DictationCorrection] = { [] }
|
||
private var activeCorrections: [DictationCorrection] = []
|
||
|
||
static var isSupported: Bool {
|
||
if #available(iOS 26.0, *) { return true }
|
||
return false
|
||
}
|
||
|
||
var isActive: Bool {
|
||
switch phase {
|
||
case .recording, .transcribing: true
|
||
default: false
|
||
}
|
||
}
|
||
|
||
func snapshot(now: TimeInterval) -> KeyboardSnapshot? {
|
||
switch phase {
|
||
case .idle:
|
||
return nil
|
||
case .recording(let jobID, let startedAt):
|
||
return KeyboardSnapshot(
|
||
state: .recording,
|
||
heartbeat: now,
|
||
expiresAt: now + 60,
|
||
recordingStartedAt: startedAt,
|
||
loudnessDB: loudness,
|
||
jobID: jobID
|
||
)
|
||
case .transcribing(let jobID):
|
||
return KeyboardSnapshot(state: .transcribing, heartbeat: now, expiresAt: now + 60, jobID: jobID)
|
||
case .finished(let jobID, let resultID, let transcript, let heard, let stages):
|
||
return KeyboardSnapshot(
|
||
state: .ready,
|
||
heartbeat: now,
|
||
expiresAt: now + 1,
|
||
jobID: jobID,
|
||
resultID: resultID,
|
||
transcript: transcript,
|
||
heard: heard,
|
||
stages: stages
|
||
)
|
||
case .failed(let message, let until):
|
||
guard until > now else {
|
||
phase = .idle
|
||
return nil
|
||
}
|
||
return KeyboardSnapshot(state: .failed, heartbeat: now, expiresAt: until, message: message)
|
||
}
|
||
}
|
||
|
||
func markDelivered(resultID: String) {
|
||
if case .finished(_, let current, _, _, _) = phase, current == resultID {
|
||
phase = .idle
|
||
}
|
||
}
|
||
|
||
/// The keyboard extension itself may not record (audiomxd: "it is an extension and
|
||
/// doesn't have entitlements to record audio"), so capture runs in WebKit's media
|
||
/// process through getUserMedia, attributed to Hex's microphone permission.
|
||
/// With Always use iPhone microphone (the app's default), capture uses the iPhone's own
|
||
/// microphone and mixes with other audio, so a car or headset keeps playing music
|
||
/// instead of switching to call audio, which pauses it and stalls the start.
|
||
func start(in host: UIView, allowBluetoothMic: Bool) {
|
||
guard !isActive else { return }
|
||
let log = KeyboardProbeLog.shared
|
||
log.write("start(web): mic=\(Self.describe(AVAudioApplication.shared.recordPermission)) speech=\(Self.describe(SFSpeechRecognizer.authorizationStatus())) \(KeyboardProbeLog.memory())")
|
||
guard AVAudioApplication.shared.recordPermission == .granted else {
|
||
fail("Allow the microphone in Hex first")
|
||
return
|
||
}
|
||
let jobID = UUID().uuidString
|
||
let requestedAt = Date()
|
||
activeCorrections = corrections()
|
||
loudness = -62
|
||
phase = .recording(jobID: jobID, startedAt: requestedAt.timeIntervalSince1970)
|
||
let capture = capture ?? KeyboardWebCapture(host: host)
|
||
self.capture = capture
|
||
capture.onEvent = { [weak self] event in
|
||
self?.handle(event, jobID: jobID, requestedAt: requestedAt)
|
||
}
|
||
if !allowBluetoothMic {
|
||
Self.preferBuiltInMicrophone()
|
||
}
|
||
capture.start(preferBuiltIn: !allowBluetoothMic)
|
||
}
|
||
|
||
/// Lets music or navigation that the capture paused resume.
|
||
private static func releaseAudioSession() {
|
||
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
|
||
}
|
||
|
||
private static func preferBuiltInMicrophone() {
|
||
let session = AVAudioSession.sharedInstance()
|
||
do {
|
||
try session.setCategory(
|
||
.playAndRecord,
|
||
mode: .measurement,
|
||
options: [.mixWithOthers, .allowBluetoothA2DP, .defaultToSpeaker]
|
||
)
|
||
if let builtIn = session.availableInputs?.first(where: { $0.portType == .builtInMic }) {
|
||
try session.setPreferredInput(builtIn)
|
||
}
|
||
} catch {
|
||
KeyboardProbeLog.shared.write("built-in mic preference failed: \(describe(error))")
|
||
}
|
||
}
|
||
|
||
private func handle(_ event: KeyboardWebCapture.Event, jobID: String, requestedAt: Date) {
|
||
let log = KeyboardProbeLog.shared
|
||
switch event {
|
||
case .started(let sampleRate, let device):
|
||
log.write("web capture started in \(Int(Date().timeIntervalSince(requestedAt) * 1000)) ms at \(Int(sampleRate)) Hz from \(device) \(KeyboardProbeLog.memory())")
|
||
guard case .recording(let current, _) = phase, current == jobID else {
|
||
// Done came before the microphone did: nothing to record.
|
||
capture?.stop()
|
||
return
|
||
}
|
||
do {
|
||
let url = FileManager.default.temporaryDirectory.appendingPathComponent("keyboard-\(jobID).wav")
|
||
pcmFile = try KeyboardPCMFile(url: url, sampleRate: sampleRate)
|
||
} catch {
|
||
capture?.stop()
|
||
fail(UserFacingError.Context.microphone.fallback, detail: "Could not create audio file: \(Self.describe(error))")
|
||
}
|
||
case .samples(let data, let peak):
|
||
pcmFile?.append(data)
|
||
loudness = peak > 0 ? max(-62, 20 * log10(peak)) : -62
|
||
case .stopped:
|
||
finishRecording(jobID: jobID)
|
||
case .failed(let message):
|
||
capture?.stop()
|
||
pcmFile = nil
|
||
fail(
|
||
message.hasPrefix("NotAllowedError") ? "Allow the microphone in Hex first" : UserFacingError.Context.microphone.fallback,
|
||
detail: "Web capture: \(message)"
|
||
)
|
||
case .processTerminated:
|
||
pcmFile = nil
|
||
capture = nil
|
||
fail(UserFacingError.Context.microphone.fallback, detail: "WebKit capture process ended")
|
||
}
|
||
}
|
||
|
||
func cancel() {
|
||
transcription?.cancel()
|
||
transcription = nil
|
||
capture?.onEvent = nil
|
||
capture?.stop()
|
||
if let url = pcmFile?.url { try? FileManager.default.removeItem(at: url) }
|
||
pcmFile = nil
|
||
phase = .idle
|
||
Self.releaseAudioSession()
|
||
KeyboardProbeLog.shared.write("cancelled")
|
||
}
|
||
|
||
func stop() {
|
||
guard case .recording = phase else { return }
|
||
capture?.stop()
|
||
}
|
||
|
||
private func finishRecording(jobID: String) {
|
||
guard case .recording(_, let startedAt) = phase else { return }
|
||
guard let file = pcmFile else {
|
||
endQuietly("stopped before the microphone started")
|
||
return
|
||
}
|
||
pcmFile = nil
|
||
Self.releaseAudioSession()
|
||
let seconds = Date().timeIntervalSince1970 - startedAt
|
||
let frames = file.close()
|
||
KeyboardProbeLog.shared.write("stopped after \(String(format: "%.1f", seconds)) s, frames=\(frames) \(KeyboardProbeLog.memory())")
|
||
guard !EmptyCapture.isTooShort(frames: frames, sampleRate: file.sampleRate) else {
|
||
try? FileManager.default.removeItem(at: file.url)
|
||
endQuietly("too short to hold a word")
|
||
return
|
||
}
|
||
guard #available(iOS 26.0, *) else { return }
|
||
phase = .transcribing(jobID: jobID)
|
||
let url = file.url
|
||
let fixes = activeCorrections
|
||
let hints = DictationCorrections.recognitionHints(vocabulary: [], corrections: fixes)
|
||
transcription = Task { [weak self] in
|
||
let started = Date()
|
||
do {
|
||
let (heard, language) = try await KeyboardSpeech.transcribe(url, hints: hints)
|
||
try? FileManager.default.removeItem(at: url)
|
||
let locale = language.identifier
|
||
let corrected = DictationCorrections.apply(fixes, to: heard)
|
||
let style = KeyboardBridge().style
|
||
let cleaned = await CleanupTagger.cleanIfEnabled(corrected, style: style, language: locale)
|
||
let translated = await DictationTranslator.translateIfEnabled(
|
||
cleaned,
|
||
source: language.locale.language
|
||
)
|
||
let text = translated ?? cleaned
|
||
KeyboardProbeLog.shared.write("transcribed in \(String(format: "%.2f", Date().timeIntervalSince(started))) s: \(text.count) chars \(KeyboardProbeLog.memory())")
|
||
guard let self, !Task.isCancelled else { return }
|
||
// Record typing logs keeps every step; nothing is kept while it is off.
|
||
let stages: DictationStages? = TypingLogSettings().isEnabled
|
||
? DictationStages(
|
||
engine: language.module == .dictation
|
||
? "Apple Speech (keyboard, DictationTranscriber)"
|
||
: "Apple Speech (keyboard)",
|
||
locale: locale,
|
||
style: style.rawValue,
|
||
recordedMS: Int((seconds * 1000).rounded()),
|
||
transcribeMS: Int((Date().timeIntervalSince(started) * 1000).rounded()),
|
||
raw: heard,
|
||
fixed: corrected,
|
||
tagged: CleanupTaggerSettings().isEnabled && style != .verbatim ? cleaned : nil,
|
||
translated: translated
|
||
)
|
||
: nil
|
||
// A translation's words can't be compared with what was heard, so it isn't learned from.
|
||
self.phase = .finished(
|
||
jobID: jobID,
|
||
resultID: UUID().uuidString,
|
||
transcript: text,
|
||
heard: translated == nil ? heard : nil,
|
||
stages: stages
|
||
)
|
||
} catch {
|
||
try? FileManager.default.removeItem(at: url)
|
||
guard let self, !Task.isCancelled,
|
||
case .transcribing(let current) = self.phase, current == jobID else { return }
|
||
if EmptyCapture.endsQuietly(error) {
|
||
self.endQuietly("no speech")
|
||
} else {
|
||
self.fail(
|
||
UserFacingError.message(for: error, context: .transcription),
|
||
detail: "Transcription failed: \(Self.describe(error))"
|
||
)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// `message` is what the keyboard shows; `detail`, for the log only, may carry codes.
|
||
private func fail(_ message: String, detail: String? = nil) {
|
||
Self.releaseAudioSession()
|
||
KeyboardProbeLog.shared.write("FAILED: \(detail ?? message) \(KeyboardProbeLog.memory())")
|
||
phase = .failed(message: message, until: Date().timeIntervalSince1970 + 6)
|
||
}
|
||
|
||
/// Nothing to insert and nothing wrong: back to idle without a message.
|
||
private func endQuietly(_ reason: String) {
|
||
Self.releaseAudioSession()
|
||
KeyboardProbeLog.shared.write("ended quietly: \(reason)")
|
||
phase = .idle
|
||
}
|
||
|
||
private static func describe(_ error: Error) -> String {
|
||
let ns = error as NSError
|
||
return "\(ns.domain) \(ns.code) \(ns.localizedDescription)"
|
||
}
|
||
|
||
private static func describe(_ permission: AVAudioApplication.recordPermission) -> String {
|
||
switch permission {
|
||
case .granted: "granted"
|
||
case .denied: "denied"
|
||
case .undetermined: "undetermined"
|
||
@unknown default: "unknown"
|
||
}
|
||
}
|
||
|
||
private static func describe(_ status: SFSpeechRecognizerAuthorizationStatus) -> String {
|
||
switch status {
|
||
case .authorized: "authorized"
|
||
case .denied: "denied"
|
||
case .restricted: "restricted"
|
||
case .notDetermined: "notDetermined"
|
||
@unknown default: "unknown"
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 16-bit mono PCM chunks from the page, written as a WAV file.
|
||
@MainActor
|
||
private final class KeyboardPCMFile {
|
||
let url: URL
|
||
private var file: AVAudioFile?
|
||
private let format: AVAudioFormat
|
||
private var frames: AVAudioFramePosition = 0
|
||
|
||
init(url: URL, sampleRate: Double) throws {
|
||
self.url = url
|
||
guard let format = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: sampleRate, channels: 1, interleaved: true) else {
|
||
throw CocoaError(.featureUnsupported)
|
||
}
|
||
self.format = format
|
||
file = try AVAudioFile(forWriting: url, settings: format.settings, commonFormat: .pcmFormatInt16, interleaved: true)
|
||
}
|
||
|
||
func append(_ data: Data) {
|
||
let count = data.count / 2
|
||
guard count > 0, let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(count)) else { return }
|
||
buffer.frameLength = AVAudioFrameCount(count)
|
||
data.withUnsafeBytes { raw in
|
||
guard let base = raw.baseAddress, let target = buffer.int16ChannelData?[0] else { return }
|
||
memcpy(target, base, count * 2)
|
||
}
|
||
try? file?.write(from: buffer)
|
||
frames += AVAudioFramePosition(count)
|
||
}
|
||
|
||
var sampleRate: Double { format.sampleRate }
|
||
|
||
func close() -> AVAudioFramePosition {
|
||
file = nil
|
||
return frames
|
||
}
|
||
}
|
||
|
||
@MainActor
|
||
private final class KeyboardWebCapture: NSObject, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
|
||
enum Event {
|
||
case started(sampleRate: Double, device: String)
|
||
case samples(Data, peak: Float)
|
||
case stopped
|
||
case failed(String)
|
||
case processTerminated
|
||
}
|
||
|
||
var onEvent: ((Event) -> Void)?
|
||
private let webView: WKWebView
|
||
private var isLoaded = false
|
||
private var startWhenLoaded = false
|
||
|
||
init(host: UIView) {
|
||
let configuration = WKWebViewConfiguration()
|
||
configuration.allowsInlineMediaPlayback = true
|
||
configuration.mediaTypesRequiringUserActionForPlayback = []
|
||
webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 2, height: 2), configuration: configuration)
|
||
super.init()
|
||
configuration.userContentController.add(WeakMessageHandler(self), name: "hex")
|
||
webView.navigationDelegate = self
|
||
webView.uiDelegate = self
|
||
webView.isUserInteractionEnabled = false
|
||
webView.alpha = 0.02
|
||
host.addSubview(webView)
|
||
webView.loadHTMLString(Self.page, baseURL: URL(string: "https://keyboard.hex.local/"))
|
||
}
|
||
|
||
private var preferBuiltIn = true
|
||
|
||
func start(preferBuiltIn: Bool) {
|
||
self.preferBuiltIn = preferBuiltIn
|
||
guard isLoaded else {
|
||
startWhenLoaded = true
|
||
return
|
||
}
|
||
webView.evaluateJavaScript("hexStart(\(preferBuiltIn))")
|
||
}
|
||
|
||
func stop() {
|
||
startWhenLoaded = false
|
||
webView.evaluateJavaScript("hexStop()")
|
||
}
|
||
|
||
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
||
isLoaded = true
|
||
if startWhenLoaded {
|
||
startWhenLoaded = false
|
||
start(preferBuiltIn: preferBuiltIn)
|
||
}
|
||
}
|
||
|
||
func webView(
|
||
_ webView: WKWebView,
|
||
requestMediaCapturePermissionFor origin: WKSecurityOrigin,
|
||
initiatedByFrame frame: WKFrameInfo,
|
||
type: WKMediaCaptureType,
|
||
decisionHandler: @escaping @MainActor (WKPermissionDecision) -> Void
|
||
) {
|
||
decisionHandler(type == .microphone ? .grant : .deny)
|
||
}
|
||
|
||
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
|
||
isLoaded = false
|
||
onEvent?(.processTerminated)
|
||
}
|
||
|
||
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
|
||
guard let body = message.body as? [String: Any], let type = body["type"] as? String else { return }
|
||
switch type {
|
||
case "started":
|
||
onEvent?(.started(sampleRate: (body["rate"] as? Double) ?? 48_000, device: (body["device"] as? String) ?? "unknown"))
|
||
case "pcm":
|
||
guard let encoded = body["data"] as? String, let data = Data(base64Encoded: encoded) else { return }
|
||
onEvent?(.samples(data, peak: Float((body["peak"] as? Double) ?? 0)))
|
||
case "stopped":
|
||
onEvent?(.stopped)
|
||
case "error":
|
||
onEvent?(.failed((body["message"] as? String) ?? "unknown"))
|
||
default:
|
||
break
|
||
}
|
||
}
|
||
|
||
private static let page = """
|
||
<!doctype html><meta charset="utf-8"><script>
|
||
let ctx, stream, source, node, running = false;
|
||
const post = (m) => webkit.messageHandlers.hex.postMessage(m);
|
||
const base = { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false };
|
||
async function builtInMicrophone() {
|
||
const inputs = (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "audioinput");
|
||
const found = inputs.find((d) => /iphone|ipad|built-in/i.test(d.label));
|
||
return found ? found.deviceId : null;
|
||
}
|
||
async function hexStart(preferBuiltIn) {
|
||
if (running) return;
|
||
running = true;
|
||
try {
|
||
let id = preferBuiltIn ? await builtInMicrophone() : null;
|
||
stream = await navigator.mediaDevices.getUserMedia({ audio: id ? { ...base, deviceId: { exact: id } } : base });
|
||
if (preferBuiltIn && !id) {
|
||
id = await builtInMicrophone();
|
||
if (id && stream.getAudioTracks()[0].getSettings().deviceId !== id) {
|
||
stream.getTracks().forEach((t) => t.stop());
|
||
stream = await navigator.mediaDevices.getUserMedia({ audio: { ...base, deviceId: { exact: id } } });
|
||
}
|
||
}
|
||
ctx = new AudioContext();
|
||
await ctx.resume();
|
||
source = ctx.createMediaStreamSource(stream);
|
||
node = ctx.createScriptProcessor(4096, 1, 1);
|
||
node.onaudioprocess = (event) => {
|
||
if (!running) return;
|
||
const input = event.inputBuffer.getChannelData(0);
|
||
const pcm = new Int16Array(input.length);
|
||
let peak = 0;
|
||
for (let i = 0; i < input.length; i++) {
|
||
const s = Math.max(-1, Math.min(1, input[i]));
|
||
peak = Math.max(peak, Math.abs(s));
|
||
pcm[i] = s < 0 ? s * 0x8000 : s * 0x7fff;
|
||
}
|
||
const bytes = new Uint8Array(pcm.buffer);
|
||
let binary = "";
|
||
for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
|
||
post({ type: "pcm", data: btoa(binary), peak });
|
||
};
|
||
source.connect(node);
|
||
node.connect(ctx.destination);
|
||
post({ type: "started", rate: ctx.sampleRate, device: stream.getAudioTracks()[0].label });
|
||
} catch (error) {
|
||
running = false;
|
||
post({ type: "error", message: (error && (error.name + ": " + error.message)) || String(error) });
|
||
}
|
||
}
|
||
async function hexStop() {
|
||
const wasRunning = running;
|
||
running = false;
|
||
try { node && node.disconnect(); source && source.disconnect(); } catch (e) {}
|
||
if (stream) stream.getTracks().forEach((t) => t.stop());
|
||
if (ctx) { try { await ctx.close(); } catch (e) {} }
|
||
ctx = stream = source = node = null;
|
||
if (wasRunning) post({ type: "stopped" });
|
||
}
|
||
</script>
|
||
"""
|
||
}
|
||
|
||
private final class WeakMessageHandler: NSObject, WKScriptMessageHandler {
|
||
weak var target: WKScriptMessageHandler?
|
||
|
||
init(_ target: WKScriptMessageHandler) {
|
||
self.target = target
|
||
}
|
||
|
||
func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
|
||
target?.userContentController(controller, didReceive: message)
|
||
}
|
||
}
|
||
|
||
@available(iOS 26.0, *)
|
||
private enum KeyboardSpeech {
|
||
enum Failure: LocalizedError, NoSpeechError {
|
||
case noLocale
|
||
case assetsMissing(String)
|
||
case empty
|
||
|
||
var errorDescription: String? {
|
||
switch self {
|
||
case .noLocale: "Apple Speech doesn't have your language on this iPhone."
|
||
case .assetsMissing: "Speech for your language is still downloading. Try again soon."
|
||
case .empty: "No speech detected"
|
||
}
|
||
}
|
||
|
||
var meansNoSpeech: Bool {
|
||
if case .empty = self { return true }
|
||
return false
|
||
}
|
||
}
|
||
|
||
/// The transcript and the language it was transcribed in.
|
||
static func transcribe(_ url: URL, hints: [String]) async throws -> (String, SpeechLanguage) {
|
||
let log = KeyboardProbeLog.shared
|
||
// The same rule as the app's (Settings › Dictation language, else Automatic), so the
|
||
// keyboard uses the assets Hex downloaded.
|
||
guard let language = await AppleSpeechLanguages.resolve() else { throw Failure.noLocale }
|
||
let locale = language.locale
|
||
let speech = AppleSpeechModule(language)
|
||
let status = await AssetInventory.status(forModules: [speech.module])
|
||
log.write("speech locale=\(locale.identifier) module=\(speech.name) assets=\(status) available=\(SpeechTranscriber.isAvailable)")
|
||
if status != .installed {
|
||
let started = Date()
|
||
_ = try? await AssetInventory.reserve(locale: locale)
|
||
if let request = try await AssetInventory.assetInstallationRequest(supporting: [speech.module]) {
|
||
log.write("downloading speech assets")
|
||
try await request.downloadAndInstall()
|
||
}
|
||
let after = await AssetInventory.status(forModules: [speech.module])
|
||
log.write("speech assets \(after) after \(String(format: "%.1f", Date().timeIntervalSince(started))) s \(KeyboardProbeLog.memory())")
|
||
guard after == .installed else { throw Failure.assetsMissing("\(after)") }
|
||
}
|
||
|
||
let analyzer = SpeechAnalyzer(
|
||
modules: [speech.module],
|
||
options: SpeechAnalyzer.Options(priority: .userInitiated, modelRetention: .whileInUse)
|
||
)
|
||
let file = try AVAudioFile(forReading: url)
|
||
// Learn how I type's meant words, best effort, as the app does for custom vocabulary.
|
||
if !hints.isEmpty {
|
||
let context = AnalysisContext()
|
||
context.contextualStrings[.general] = hints
|
||
try? await analyzer.setContext(context)
|
||
}
|
||
try await analyzer.start(inputAudioFile: file, finishAfterFile: true)
|
||
log.write("analyzer started \(KeyboardProbeLog.memory())")
|
||
|
||
let text = try await speech.finalText()
|
||
guard !text.isEmpty else { throw Failure.empty }
|
||
return (text, language)
|
||
}
|
||
}
|
||
|
||
final class KeyboardProbeLog: @unchecked Sendable {
|
||
static let shared = KeyboardProbeLog()
|
||
|
||
private let logger = Logger(subsystem: "anomaly.hex.mobile.keyboard", category: "capture-probe")
|
||
private let lock = NSLock()
|
||
private let url = FileManager.default
|
||
.containerURL(forSecurityApplicationGroupIdentifier: KeyboardBridge.appGroup)?
|
||
.appendingPathComponent("keyboard-capture-probe.log")
|
||
|
||
func write(_ message: String) {
|
||
logger.notice("\(message, privacy: .public)")
|
||
guard let url else { return }
|
||
let line = "\(ISO8601DateFormatter().string(from: Date())) \(message)\n"
|
||
lock.withLock {
|
||
if let handle = try? FileHandle(forWritingTo: url) {
|
||
handle.seekToEndOfFile()
|
||
handle.write(Data(line.utf8))
|
||
try? handle.close()
|
||
} else {
|
||
try? Data(line.utf8).write(to: url)
|
||
}
|
||
}
|
||
}
|
||
|
||
static func memory() -> String {
|
||
var info = task_vm_info_data_t()
|
||
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<natural_t>.size)
|
||
let result = withUnsafeMutablePointer(to: &info) {
|
||
$0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
|
||
task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
|
||
}
|
||
}
|
||
let footprint = result == KERN_SUCCESS ? Double(info.phys_footprint) / 1_048_576 : -1
|
||
let available = Double(os_proc_available_memory()) / 1_048_576
|
||
return String(format: "[footprint %.1f MB, headroom %.1f MB]", footprint, available)
|
||
}
|
||
}
|