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.
1123 lines
45 KiB
Swift
1123 lines
45 KiB
Swift
import AVFAudio
|
|
import XCTest
|
|
@testable import HEX
|
|
|
|
@MainActor
|
|
private final class FakeAudioCapture: ActiveAudioCapture {
|
|
let url: URL
|
|
var isRecording = true
|
|
var currentTime: TimeInterval
|
|
var power: Float = 0.6
|
|
|
|
init(url: URL, initialDuration: TimeInterval = 1.2) {
|
|
self.url = url
|
|
self.currentTime = initialDuration
|
|
FileManager.default.createFile(atPath: url.path, contents: Data("wav".utf8))
|
|
}
|
|
|
|
func normalizedPowerLevel() -> Float {
|
|
power
|
|
}
|
|
|
|
func stop() {
|
|
isRecording = false
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
private final class FakeAudioManager: AudioManaging {
|
|
var isKeepaliveRunning = false
|
|
var permissionGranted = true
|
|
var keepaliveShouldThrow = false
|
|
var keepaliveError: Error = CocoaError(.coderInvalidValue)
|
|
var nextCaptureDuration: TimeInterval = 1.4
|
|
var nextCaptureIsRecording = true
|
|
var deactivateCount = 0
|
|
var createdCaptures: [FakeAudioCapture] = []
|
|
|
|
var onSystemEvent: ((AudioSystemEvent) -> Void)?
|
|
var onUnexpectedCaptureEnd: ((URL, Bool) -> Void)?
|
|
|
|
func requestPermission() async -> Bool {
|
|
permissionGranted
|
|
}
|
|
|
|
func startKeepalive(allowBluetooth: Bool) throws {
|
|
if keepaliveShouldThrow {
|
|
isKeepaliveRunning = false
|
|
throw keepaliveError
|
|
}
|
|
isKeepaliveRunning = true
|
|
}
|
|
|
|
func stopKeepalive() {
|
|
isKeepaliveRunning = false
|
|
}
|
|
|
|
func deactivateSession() {
|
|
isKeepaliveRunning = false
|
|
deactivateCount += 1
|
|
}
|
|
|
|
func beginCapture(
|
|
at url: URL,
|
|
maxDuration: TimeInterval,
|
|
allowBluetooth: Bool
|
|
) throws -> any ActiveAudioCapture {
|
|
isKeepaliveRunning = false
|
|
let capture = FakeAudioCapture(url: url, initialDuration: nextCaptureDuration)
|
|
capture.isRecording = nextCaptureIsRecording
|
|
createdCaptures.append(capture)
|
|
return capture
|
|
}
|
|
}
|
|
|
|
private actor ControlledTranscriber: LocalTranscribing {
|
|
nonisolated let displayName = "Controlled Speech"
|
|
let languageName = "English"
|
|
|
|
private var gate: CheckedContinuation<String, Error>?
|
|
private var pendingResume: String?
|
|
private var cannedOutput = "ship the build"
|
|
private(set) var transcribedURLs: [URL] = []
|
|
private(set) var vocabularyArguments: [[String]] = []
|
|
private var suspendNext = false
|
|
private var nextError: Error?
|
|
|
|
func failNext(with error: Error) {
|
|
nextError = error
|
|
}
|
|
|
|
func armSuspension() {
|
|
suspendNext = true
|
|
pendingResume = nil
|
|
}
|
|
|
|
func setCannedOutput(_ text: String) {
|
|
cannedOutput = text
|
|
}
|
|
|
|
func resumeSuspended(with text: String) {
|
|
if let continuation = gate {
|
|
gate = nil
|
|
continuation.resume(returning: text)
|
|
} else {
|
|
pendingResume = text
|
|
}
|
|
}
|
|
|
|
func prepare(progressHandler: @escaping @Sendable (ModelPreparationProgress) -> Void) async throws {
|
|
progressHandler(ModelPreparationProgress(fractionCompleted: 1, detail: "Ready"))
|
|
}
|
|
|
|
func transcribe(_ audioURL: URL) async throws -> String {
|
|
transcribedURLs.append(audioURL)
|
|
if let error = nextError {
|
|
nextError = nil
|
|
throw error
|
|
}
|
|
if suspendNext {
|
|
suspendNext = false
|
|
if let early = pendingResume {
|
|
pendingResume = nil
|
|
return early
|
|
}
|
|
return try await withCheckedThrowingContinuation { continuation in
|
|
gate = continuation
|
|
}
|
|
}
|
|
return cannedOutput
|
|
}
|
|
|
|
func transcribe(_ audioURL: URL, vocabulary: [String]) async throws -> String {
|
|
vocabularyArguments.append(vocabulary)
|
|
return try await transcribe(audioURL)
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
private final class RecordingCleaner: TranscriptCleaning {
|
|
var isAvailable = true
|
|
var output: String?
|
|
private(set) var cleanedInputs: [String] = []
|
|
|
|
func clean(_ text: String) async -> String? {
|
|
cleanedInputs.append(text)
|
|
return output
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
final class DictationControllerTests: XCTestCase {
|
|
private var suiteName = ""
|
|
private var defaults: UserDefaults!
|
|
|
|
override func setUp() async throws {
|
|
suiteName = "hex.tests.\(UUID().uuidString)"
|
|
defaults = UserDefaults(suiteName: suiteName)!
|
|
}
|
|
|
|
override func tearDown() async throws {
|
|
defaults.removePersistentDomain(forName: suiteName)
|
|
}
|
|
|
|
func testStaleTranscriptionAfterSessionEndCannotClobberNewerCaptureOrDeleteItsFile() async throws {
|
|
let now = 1_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .ready)
|
|
|
|
// Start Job A and suspend its transcription in-flight.
|
|
await transcriber.armSuspension()
|
|
controller.toggleWarmSession()
|
|
try await settle()
|
|
XCTAssertTrue(controller.keyboardSessionEnabled)
|
|
|
|
bridge.send(.start, jobID: "job-a", style: .polished, sentAt: now)
|
|
controller.processPendingKeyboardCommandForTesting()
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
let firstCaptureURL = try XCTUnwrap(audio.createdCaptures.first?.url)
|
|
XCTAssertTrue(FileManager.default.fileExists(atPath: firstCaptureURL.path))
|
|
|
|
controller.finishRecording()
|
|
XCTAssertEqual(controller.phase, .transcribing)
|
|
try await settle()
|
|
|
|
// Expire / end the warm session while Job A is still transcribing, then start a new capture Job B!
|
|
controller.endWarmSession()
|
|
XCTAssertFalse(controller.keyboardSessionEnabled)
|
|
|
|
controller.startRecording(keyboardJobID: "job-b")
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
let secondCaptureURL = try XCTUnwrap(audio.createdCaptures.last?.url)
|
|
XCTAssertNotEqual(firstCaptureURL, secondCaptureURL)
|
|
XCTAssertTrue(FileManager.default.fileExists(atPath: secondCaptureURL.path))
|
|
|
|
// Complete stale Job A: it must clean up ONLY firstCaptureURL and leave Job B recording untouched!
|
|
await transcriber.resumeSuspended(with: "stale transcript")
|
|
try await settle()
|
|
|
|
XCTAssertFalse(FileManager.default.fileExists(atPath: firstCaptureURL.path))
|
|
XCTAssertTrue(FileManager.default.fileExists(atPath: secondCaptureURL.path))
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
XCTAssertEqual(controller.transcript, "")
|
|
|
|
controller.cancelCurrentJob()
|
|
XCTAssertFalse(FileManager.default.fileExists(atPath: secondCaptureURL.path))
|
|
}
|
|
|
|
func testAcceptedJobDeliversTranscriptEvenWhenWarmSessionCloses() async throws {
|
|
let now = 2_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.armSuspension()
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
controller.setWarmDuration(.off)
|
|
controller.handleKeyboardLaunch(
|
|
.startRecording(jobID: "one-shot-job", requestedAt: now, style: .casual, returnAppID: nil),
|
|
urlOpener: { _ in false }
|
|
)
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
|
|
// Finishing capture in one-shot mode immediately releases the mic while transcription completes.
|
|
controller.finishRecording()
|
|
XCTAssertEqual(controller.phase, .transcribing)
|
|
XCTAssertFalse(controller.keyboardSessionEnabled)
|
|
XCTAssertGreaterThan(audio.deactivateCount, 0)
|
|
try await settle()
|
|
|
|
await transcriber.resumeSuspended(with: "Um, Ship It Tonight.")
|
|
try await settle()
|
|
|
|
XCTAssertEqual(controller.phase, .ready)
|
|
XCTAssertEqual(controller.transcript, "ship it tonight")
|
|
let snap = bridge.snapshot()
|
|
XCTAssertTrue(snap.hasDeliverableResult(at: now + 1))
|
|
XCTAssertEqual(snap.transcript, "ship it tonight")
|
|
}
|
|
|
|
func testChosenReturnAppsKeepTheirOrderAndUntickingTheSavedAppForgetsIt() throws {
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
XCTAssertEqual(bridge.quickReturnApps, HostAppCatalog.quickChips)
|
|
|
|
let transcriber = ControlledTranscriber()
|
|
let controller = DictationController(
|
|
audio: FakeAudioManager(),
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
autoPrepareOnInit: false
|
|
)
|
|
let signal = try XCTUnwrap(HostAppCatalog.app(for: "signal"))
|
|
let t3Code = try XCTUnwrap(HostAppCatalog.app(for: "t3code"))
|
|
controller.setReturnAppID("t3code")
|
|
|
|
controller.setQuickReturnApps([t3Code, signal])
|
|
XCTAssertEqual(bridge.quickReturnApps, [t3Code, signal])
|
|
XCTAssertEqual(bridge.returnAppID, "t3code")
|
|
|
|
controller.setQuickReturnApps([signal])
|
|
XCTAssertEqual(bridge.quickReturnApps, [signal])
|
|
XCTAssertNil(bridge.returnAppID)
|
|
XCTAssertNil(controller.returnAppID)
|
|
}
|
|
|
|
func testTenSecondHandoffWindowAndAutoReturnBehavior() async throws {
|
|
var now = 5_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
var openedURLs: [URL] = []
|
|
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false,
|
|
urlOpener: { url in
|
|
openedURLs.append(url)
|
|
return url.scheme == "claude"
|
|
}
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
// 1. Expired (>10s) handoff warms session without surprise-recording.
|
|
controller.handleKeyboardLaunch(
|
|
.startRecording(jobID: "expired-job", requestedAt: now - 11.5, style: .polished, returnAppID: "claude")
|
|
)
|
|
try await settle()
|
|
XCTAssertTrue(controller.keyboardSessionEnabled)
|
|
XCTAssertEqual(controller.phase, .ready)
|
|
XCTAssertNotNil(controller.handoffNotice)
|
|
XCTAssertTrue(openedURLs.isEmpty)
|
|
|
|
// 2. Fresh handoff starts recording and opens configured host URL scheme.
|
|
now += 1
|
|
controller.handleKeyboardLaunch(
|
|
.startRecording(jobID: "fresh-job", requestedAt: now - 0.4, style: .polished, returnAppID: "claude")
|
|
)
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
XCTAssertEqual(openedURLs.map(\.absoluteString), ["claude://"])
|
|
|
|
// 3. Unsupported scheme immediately falls back to swipe guide.
|
|
controller.cancelCurrentJob()
|
|
now += 1
|
|
controller.handleKeyboardLaunch(
|
|
.startRecording(jobID: "fallback-job", requestedAt: now - 0.2, style: .polished, returnAppID: "slack")
|
|
)
|
|
try await settle()
|
|
XCTAssertEqual(controller.autoReturnState, .swipeFallback)
|
|
controller.cancelCurrentJob()
|
|
}
|
|
|
|
func testAudioInterruptionsAndRouteChangesNeverLeaveStuckListeningState() async throws {
|
|
let now = 8_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.setCannedOutput("saved before call")
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
controller.toggleWarmSession()
|
|
try await settle()
|
|
|
|
// Long capture (>= 0.3s) interrupted by phone call saves and transcribes spoken words!
|
|
audio.nextCaptureDuration = 2.1
|
|
controller.startRecording(keyboardJobID: "call-job")
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
|
|
controller.handleAudioSystemEvent(.interruptionBegan)
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .ready)
|
|
XCTAssertEqual(controller.transcript, "Saved before call.")
|
|
XCTAssertNotEqual(bridge.snapshot().state, .recording)
|
|
|
|
// Short capture (< 0.3s) interrupted cancels cleanly out of recording.
|
|
audio.nextCaptureDuration = 0.1
|
|
controller.startRecording(keyboardJobID: "short-call-job")
|
|
try await settle()
|
|
controller.handleAudioSystemEvent(.interruptionBegan)
|
|
XCTAssertEqual(controller.phase, .ready)
|
|
XCTAssertNotEqual(bridge.snapshot().state, .recording)
|
|
}
|
|
|
|
func testRecordedWAVFixtureIsValidSilentTestInput() throws {
|
|
let bundle = Bundle(for: Self.self)
|
|
let wavURL = try XCTUnwrap(
|
|
bundle.url(forResource: "term-hex-1", withExtension: "wav"),
|
|
"Expected recorded WAV fixture in test bundle"
|
|
)
|
|
let audioFile = try AVAudioFile(forReading: wavURL)
|
|
XCTAssertEqual(audioFile.fileFormat.sampleRate, 16_000, accuracy: 1)
|
|
XCTAssertGreaterThan(audioFile.length, 4_000)
|
|
}
|
|
|
|
func testSelectWarmDurationWarmsAndEndsWithoutSeparateButton() async throws {
|
|
let now = 12_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
controller.setWarmDuration(.off)
|
|
XCTAssertFalse(controller.keyboardSessionEnabled)
|
|
|
|
controller.selectWarmDuration(.fifteenMinutes)
|
|
try await settle()
|
|
XCTAssertTrue(controller.keyboardSessionEnabled)
|
|
XCTAssertTrue(audio.isKeepaliveRunning)
|
|
XCTAssertEqual(controller.warmDuration, .fifteenMinutes)
|
|
|
|
controller.selectWarmDuration(.off)
|
|
XCTAssertFalse(controller.keyboardSessionEnabled)
|
|
XCTAssertFalse(audio.isKeepaliveRunning)
|
|
}
|
|
|
|
func testMeterRecoversAfterCaptureStartsTemporarilyNotRecording() async throws {
|
|
try await checkMeterRecovery(initiallyRecording: false)
|
|
}
|
|
|
|
func testMeterRecoversAfterRecordingTemporarilyStops() async throws {
|
|
try await checkMeterRecovery(initiallyRecording: true)
|
|
}
|
|
|
|
private func checkMeterRecovery(initiallyRecording: Bool) async throws {
|
|
var now = 20_000.0
|
|
let audio = FakeAudioManager()
|
|
audio.nextCaptureIsRecording = initiallyRecording
|
|
let transcriber = ControlledTranscriber()
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
controller.startRecording(keyboardJobID: "meter-recovery")
|
|
try await settle()
|
|
let capture = try XCTUnwrap(audio.createdCaptures.last)
|
|
defer { controller.cancelCurrentJob() }
|
|
|
|
// No completion/interruption callback: the same capture becomes available again.
|
|
capture.isRecording = false
|
|
try await settle()
|
|
capture.power = 0.9
|
|
capture.currentTime = 2.4
|
|
capture.isRecording = true
|
|
now += 1
|
|
try await settle()
|
|
|
|
let db = capture.averagePowerDB()
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
XCTAssertEqual(controller.loudnessDB, db, accuracy: 0.001)
|
|
XCTAssertEqual(controller.audioLevel, (db + 48) / 48, accuracy: 0.001)
|
|
XCTAssertEqual(controller.recordingDuration, 2.4)
|
|
XCTAssertEqual(bridge.snapshot().state, .recording)
|
|
XCTAssertEqual(bridge.snapshot().effectiveLoudnessDB, db, accuracy: 0.001)
|
|
XCTAssertEqual(bridge.snapshot().heartbeat, now)
|
|
|
|
// A level-only change must still get through the keyboard publication throttle.
|
|
capture.power = 0.2
|
|
now += 1
|
|
try await settle()
|
|
XCTAssertEqual(controller.loudnessDB, capture.averagePowerDB(), accuracy: 0.001)
|
|
XCTAssertEqual(bridge.snapshot().effectiveLoudnessDB, capture.averagePowerDB(), accuracy: 0.001)
|
|
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(controller.transcript, "Ship the build.")
|
|
XCTAssertEqual(controller.audioLevel, 0)
|
|
XCTAssertEqual(bridge.snapshot().audioLevel, 0)
|
|
}
|
|
|
|
func testCleanupRunsBeforeFormattingOnlyWhenCapturedAndSkipsVerbatim() async throws {
|
|
let now = 40_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.setCannedOutput("we should use cloud code for this")
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let settings = AppleIntelligenceCleanupSettings(defaults: defaults)
|
|
let cleaner = RecordingCleaner()
|
|
cleaner.output = "We should use Claude Code for this."
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false,
|
|
cleaner: cleaner,
|
|
cleanupSettings: settings
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
// Off: the transcript is formatted exactly as before.
|
|
settings.isEnabled = false
|
|
controller.startRecording(keyboardJobID: "cleanup-off")
|
|
try await settle()
|
|
settings.isEnabled = true // A mid-capture toggle must not affect this session.
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(cleaner.cleanedInputs, [])
|
|
XCTAssertEqual(controller.transcript, "We should use cloud code for this.")
|
|
|
|
// On: the setting is captured at start, and cleanup runs before formatting.
|
|
controller.clearTranscript()
|
|
settings.isEnabled = true
|
|
controller.startRecording(keyboardJobID: "cleanup-on")
|
|
try await settle()
|
|
settings.isEnabled = false
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(cleaner.cleanedInputs, ["we should use cloud code for this"])
|
|
XCTAssertEqual(controller.transcript, "We should use Claude Code for this.")
|
|
|
|
// Verbatim skips cleanup even with the experiment on.
|
|
controller.clearTranscript()
|
|
settings.isEnabled = true
|
|
controller.startRecording(keyboardJobID: "cleanup-verbatim", styleOverride: .verbatim)
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(cleaner.cleanedInputs.count, 1)
|
|
XCTAssertEqual(controller.transcript, "we should use cloud code for this")
|
|
|
|
// A cleaner that declines leaves the raw transcript for the formatter.
|
|
controller.clearTranscript()
|
|
cleaner.output = nil
|
|
settings.isEnabled = true
|
|
controller.startRecording(keyboardJobID: "cleanup-fallback")
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(cleaner.cleanedInputs.count, 2)
|
|
XCTAssertEqual(controller.transcript, "We should use cloud code for this.")
|
|
|
|
// Empty transcripts skip cleanup too.
|
|
controller.clearTranscript()
|
|
await transcriber.setCannedOutput(" ")
|
|
settings.isEnabled = true
|
|
controller.startRecording(keyboardJobID: "cleanup-empty")
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(cleaner.cleanedInputs.count, 2)
|
|
XCTAssertEqual(controller.transcript, "")
|
|
}
|
|
|
|
func testCustomVocabularyAppliesOnlyWhenCaptured() async throws {
|
|
let now = 50_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.setCannedOutput("i use open code")
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let settings = CustomVocabularySettings(defaults: defaults)
|
|
settings.terms = ["OpenCode"]
|
|
let cleanupSettings = AppleIntelligenceCleanupSettings(defaults: defaults)
|
|
let cleaner = RecordingCleaner()
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false,
|
|
cleaner: cleaner,
|
|
cleanupSettings: cleanupSettings,
|
|
customVocabularySettings: settings
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
// Off: the transcript is formatted exactly as before.
|
|
settings.isEnabled = false
|
|
controller.startRecording(keyboardJobID: "vocabulary-off", styleOverride: .verbatim)
|
|
try await settle()
|
|
settings.isEnabled = true // A mid-capture toggle must not affect this session.
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(controller.transcript, "i use open code")
|
|
|
|
// On: the setting is captured at start, before formatting.
|
|
controller.clearTranscript()
|
|
settings.isEnabled = true
|
|
controller.startRecording(keyboardJobID: "vocabulary-on", styleOverride: .verbatim)
|
|
try await settle()
|
|
settings.isEnabled = false
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(controller.transcript, "i use OpenCode")
|
|
|
|
// Cleanup receives the spelled transcript, then formatting runs.
|
|
controller.clearTranscript()
|
|
settings.isEnabled = true
|
|
cleanupSettings.isEnabled = true
|
|
controller.startRecording(keyboardJobID: "vocabulary-cleanup", styleOverride: .polished)
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(cleaner.cleanedInputs, ["i use OpenCode"])
|
|
XCTAssertEqual(controller.transcript, "I use OpenCode.")
|
|
}
|
|
|
|
func testCustomVocabularyReachesTheTranscriberOnlyWhileEnabled() async throws {
|
|
let now = 60_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.setCannedOutput("i use open code")
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let settings = CustomVocabularySettings(defaults: defaults)
|
|
settings.terms = ["OpenCode"]
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false,
|
|
customVocabularySettings: settings
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
settings.isEnabled = false
|
|
controller.startRecording(keyboardJobID: "vocabulary-hint-off")
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
var arguments = await transcriber.vocabularyArguments
|
|
XCTAssertEqual(arguments, [[]])
|
|
|
|
settings.isEnabled = true
|
|
controller.startRecording(keyboardJobID: "vocabulary-hint-on")
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
arguments = await transcriber.vocabularyArguments
|
|
XCTAssertEqual(arguments, [[], ["OpenCode"]])
|
|
}
|
|
|
|
func testCustomVocabularySurvivesCasualFormatting() async throws {
|
|
let now = 70_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.setCannedOutput("iphone 17 broke")
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let settings = CustomVocabularySettings(defaults: defaults)
|
|
settings.terms = ["iPhone 17"]
|
|
settings.isEnabled = true
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false,
|
|
customVocabularySettings: settings
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
// Casual lowercases the whole sentence, so the second spelling pass has to
|
|
// restore the listed term.
|
|
controller.startRecording(keyboardJobID: "vocabulary-casual", styleOverride: .casual)
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(controller.transcript, "iPhone 17 broke")
|
|
}
|
|
|
|
func testCustomVocabularySurvivesPolishedFormatting() async throws {
|
|
let now = 80_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.setCannedOutput("iphone 17 broke")
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let settings = CustomVocabularySettings(defaults: defaults)
|
|
settings.terms = ["iPhone 17"]
|
|
settings.isEnabled = true
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false,
|
|
customVocabularySettings: settings
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
// Polished capitalizes the sentence start ("IPhone"), so the second pass
|
|
// has to restore the listed term.
|
|
controller.startRecording(keyboardJobID: "vocabulary-polished", styleOverride: .polished)
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(controller.transcript, "iPhone 17 broke.")
|
|
}
|
|
|
|
func testLearnedDictationFixesApplyHintAndReachTheKeyboard() async throws {
|
|
let now = 90_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.setCannedOutput("ask cloud about open code")
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let journalSettings = TypingJournalSettings(defaults: defaults)
|
|
journalSettings.isEnabled = true
|
|
let learned = [
|
|
DictationCorrection(heard: "cloud", meant: "Claude"),
|
|
DictationCorrection(heard: "open code", meant: "OpenCode"),
|
|
]
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false,
|
|
customVocabularySettings: CustomVocabularySettings(defaults: defaults),
|
|
typingJournalSettings: journalSettings,
|
|
learnedDictationCorrections: { learned }
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
controller.startRecording(keyboardJobID: "learned-on", styleOverride: .polished)
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(controller.transcript, "Ask Claude about OpenCode.")
|
|
let arguments = await transcriber.vocabularyArguments
|
|
XCTAssertEqual(arguments, [["Claude", "OpenCode"]], "meant words go to Apple Speech as hints")
|
|
XCTAssertEqual(bridge.snapshot().transcript, "Ask Claude about OpenCode.")
|
|
XCTAssertEqual(bridge.snapshot().heard, "ask cloud about open code", "the keyboard learns from the raw words")
|
|
|
|
// With Learn how I type off, the keyboard gets no raw transcript.
|
|
journalSettings.isEnabled = false
|
|
controller.clearTranscript()
|
|
controller.startRecording(keyboardJobID: "learned-off", styleOverride: .polished)
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertNil(bridge.snapshot().heard)
|
|
}
|
|
|
|
/// Clean up what I say reads its switch from the App Group at the call site, so this
|
|
/// sets the real switch and puts it back.
|
|
func testCleanupTaggerRunsAfterLearnedFixesAndSkipsVerbatim() async throws {
|
|
let tagger = CleanupTaggerSettings()
|
|
let wasEnabled = tagger.isEnabled
|
|
defer { tagger.isEnabled = wasEnabled }
|
|
CleanupTagger.shared.unload()
|
|
XCTAssertFalse(CleanupTagger.shared.isLoaded)
|
|
|
|
let now = 95_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
await transcriber.setCannedOutput("Let's ship it Tuesday, no wait, Thursday.")
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: KeyboardBridge(defaults: defaults),
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false,
|
|
cleanupSettings: AppleIntelligenceCleanupSettings(defaults: defaults),
|
|
customVocabularySettings: CustomVocabularySettings(defaults: defaults),
|
|
typingJournalSettings: TypingJournalSettings(defaults: defaults),
|
|
learnedDictationCorrections: { [DictationCorrection(heard: "ship", meant: "send")] }
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
// Off first: recording start must not load the model.
|
|
for (style, enabled, spoken) in [
|
|
(DictationStyle.polished, false, "Let's send it Tuesday, no wait, Thursday."),
|
|
(.polished, true, "Let's send it Thursday."),
|
|
(.verbatim, true, "Let's send it Tuesday, no wait, Thursday."),
|
|
] {
|
|
tagger.isEnabled = enabled
|
|
controller.clearTranscript()
|
|
controller.startRecording(keyboardJobID: "tagger-\(style)-\(enabled)", styleOverride: style)
|
|
if enabled, style == .polished {
|
|
XCTAssertTrue(CleanupTagger.shared.isLoaded, "recording start loads the model")
|
|
}
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(
|
|
controller.transcript,
|
|
TranscriptFormatter.format(spoken, style: style),
|
|
"\(style), experiment \(enabled ? "on" : "off")"
|
|
)
|
|
if !enabled {
|
|
XCTAssertFalse(CleanupTagger.shared.isLoaded, "nothing loads while the experiment is off")
|
|
}
|
|
}
|
|
}
|
|
|
|
func testDictationLanguageChangeWaitsForTheDictationInFlight() async throws {
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
let languages = LanguageSettings(defaults: defaults)
|
|
var preparations = 0
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: KeyboardBridge(defaults: defaults),
|
|
transcriber: transcriber,
|
|
transcriberFactory: {
|
|
preparations += 1
|
|
return transcriber
|
|
},
|
|
autoPrepareOnInit: false,
|
|
languageSettings: languages
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
XCTAssertEqual(preparations, 1)
|
|
XCTAssertNil(controller.dictationLanguage, "Automatic by default")
|
|
|
|
controller.setDictationLanguage("nb-NO")
|
|
try await settle()
|
|
XCTAssertEqual(languages.dictationLanguage, "nb-NO", "saved in the App Group for the keyboard")
|
|
XCTAssertEqual(preparations, 2, "an idle change prepares the new language at once")
|
|
XCTAssertEqual(controller.phase, .ready)
|
|
|
|
controller.startRecording(keyboardJobID: "language-job")
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
controller.setDictationLanguage("de-DE")
|
|
try await settle()
|
|
XCTAssertEqual(preparations, 2, "never while recording")
|
|
XCTAssertEqual(controller.phase, .recording)
|
|
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(controller.transcript, "Ship the build.")
|
|
XCTAssertEqual(preparations, 3, "prepared once the dictation is done")
|
|
XCTAssertEqual(controller.phase, .ready)
|
|
|
|
controller.setDictationLanguage(nil)
|
|
try await settle()
|
|
XCTAssertNil(languages.dictationLanguage)
|
|
XCTAssertEqual(preparations, 4)
|
|
|
|
// The keyboard's switch writes the App Group; Hex follows without writing it back.
|
|
languages.dictationLanguage = "he-IL"
|
|
controller.followDictationLanguageSetting()
|
|
try await settle()
|
|
XCTAssertEqual(controller.dictationLanguage, "he-IL")
|
|
XCTAssertEqual(preparations, 5)
|
|
controller.followDictationLanguageSetting()
|
|
try await settle()
|
|
XCTAssertEqual(preparations, 5, "no change, no preparation")
|
|
XCTAssertEqual(languages.recentDictationLanguages, ["de-DE", "nb-NO"], "picks in Hex are recents")
|
|
}
|
|
|
|
func testErrorsShowShortMessagesNeverCodesOrTypeNames() {
|
|
// 560557684 is '!int', AVAudioSession's cannotInterruptOthers.
|
|
let cannotInterrupt = NSError(domain: NSOSStatusErrorDomain, code: 560_557_684)
|
|
XCTAssertEqual(
|
|
UserFacingError.message(for: cannotInterrupt, context: .microphone),
|
|
"Another app is using audio. Try again."
|
|
)
|
|
XCTAssertEqual(UserFacingError.audioSessionCode(of: cannotInterrupt), .cannotInterruptOthers)
|
|
XCTAssertEqual(
|
|
UserFacingError.message(for: NSError(domain: NSOSStatusErrorDomain, code: 561_017_449), context: .microphone),
|
|
"Another app is using the microphone. Try again."
|
|
)
|
|
|
|
// Unknown codes and non-audio errors fall back to the context's sentence.
|
|
XCTAssertEqual(
|
|
UserFacingError.message(for: NSError(domain: NSOSStatusErrorDomain, code: -10_875), context: .microphone),
|
|
UserFacingError.Context.microphone.fallback
|
|
)
|
|
XCTAssertEqual(
|
|
UserFacingError.message(for: CocoaError(.coderInvalidValue), context: .microphone),
|
|
UserFacingError.Context.microphone.fallback
|
|
)
|
|
enum PlainFailure: Error { case broke }
|
|
let plain = UserFacingError.message(for: PlainFailure.broke, context: .transcription)
|
|
XCTAssertEqual(plain, UserFacingError.Context.transcription.fallback)
|
|
|
|
// A described error keeps its sentence.
|
|
XCTAssertEqual(
|
|
UserFacingError.message(for: ParakeetTranscriber.TranscriberError.notPrepared, context: .transcription),
|
|
"Parakeet V2 is not ready."
|
|
)
|
|
for message in [plain, UserFacingError.message(for: cannotInterrupt, context: .transcription)] {
|
|
XCTAssertFalse(message.contains("OSStatus"))
|
|
XCTAssertFalse(message.contains("PlainFailure"))
|
|
}
|
|
}
|
|
|
|
func testWarmSessionAudioErrorReachesAppAndKeyboardAsASentence() async throws {
|
|
let audio = FakeAudioManager()
|
|
audio.keepaliveShouldThrow = true
|
|
audio.keepaliveError = NSError(domain: NSOSStatusErrorDomain, code: 560_557_684)
|
|
let transcriber = ControlledTranscriber()
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { 30_000 },
|
|
autoPrepareOnInit: false
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
|
|
controller.selectWarmDuration(.fifteenMinutes)
|
|
try await settle()
|
|
|
|
XCTAssertEqual(controller.phase, .failed("Another app is using audio. Try again."))
|
|
XCTAssertEqual(bridge.snapshot().message, "Another app is using audio. Try again.")
|
|
}
|
|
|
|
func testEmptyCaptureRule() {
|
|
XCTAssertTrue(EmptyCapture.isTooShort(frames: 0, sampleRate: 48_000), "Done before the microphone came up")
|
|
XCTAssertTrue(EmptyCapture.isTooShort(frames: 4_800, sampleRate: 48_000), "0.1 s is a tap")
|
|
XCTAssertTrue(EmptyCapture.isTooShort(frames: 4_800, sampleRate: 0))
|
|
XCTAssertFalse(EmptyCapture.isTooShort(frames: 14_400, sampleRate: 48_000), "0.3 s can hold a word")
|
|
|
|
XCTAssertTrue(EmptyCapture.endsQuietly(CancellationError()))
|
|
XCTAssertTrue(EmptyCapture.endsQuietly(ParakeetTranscriber.TranscriberError.emptyTranscript))
|
|
XCTAssertFalse(EmptyCapture.endsQuietly(ParakeetTranscriber.TranscriberError.notPrepared))
|
|
XCTAssertFalse(EmptyCapture.endsQuietly(NSError(domain: NSOSStatusErrorDomain, code: 560_557_684)))
|
|
}
|
|
|
|
func testNoSpeechEndsTheKeyboardDictationQuietly() async throws {
|
|
let now = 40_000.0
|
|
let audio = FakeAudioManager()
|
|
let transcriber = ControlledTranscriber()
|
|
let bridge = KeyboardBridge(defaults: defaults)
|
|
let controller = DictationController(
|
|
audio: audio,
|
|
keyboardBridge: bridge,
|
|
transcriber: transcriber,
|
|
transcriberFactory: { transcriber },
|
|
now: { now },
|
|
autoPrepareOnInit: false
|
|
)
|
|
controller.prepareModel()
|
|
try await settle()
|
|
controller.selectWarmDuration(.fifteenMinutes)
|
|
try await settle()
|
|
|
|
await transcriber.failNext(with: ParakeetTranscriber.TranscriberError.emptyTranscript)
|
|
controller.startRecording(keyboardJobID: "silent-job")
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
|
|
XCTAssertEqual(controller.phase, .ready, "no speech is not a failure")
|
|
let snap = bridge.snapshot()
|
|
XCTAssertEqual(snap.state, .ready)
|
|
XCTAssertNil(snap.message)
|
|
XCTAssertNil(snap.transcript)
|
|
|
|
// Anything else still fails, as a sentence.
|
|
await transcriber.failNext(with: ParakeetTranscriber.TranscriberError.notPrepared)
|
|
controller.startRecording(keyboardJobID: "broken-job")
|
|
try await settle()
|
|
controller.finishRecording()
|
|
try await settle()
|
|
XCTAssertEqual(controller.phase, .failed("Parakeet V2 is not ready."))
|
|
XCTAssertEqual(bridge.snapshot().message, "Parakeet V2 is not ready.")
|
|
}
|
|
|
|
private func settle() async throws {
|
|
for _ in 0..<8 {
|
|
try await Task.sleep(for: .milliseconds(25))
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The dictation language rule: an explicit choice, else the first preferred language either
|
|
/// Apple Speech module has, `SpeechTranscriber` first.
|
|
final class SpeechLanguagePickerTests: XCTestCase {
|
|
/// SpeechTranscriber's and DictationTranscriber's locales as of iOS 26 (abridged).
|
|
private let speechLocales = ["en-US", "en-GB", "de-DE", "es-ES", "es-MX", "fr-FR", "hi-IN"]
|
|
private let dictationLocales = ["en-US", "en-GB", "de-DE", "es-ES", "es-MX", "fr-FR", "nb-NO", "da-DK", "sv-SE", "he-IL"]
|
|
|
|
private func lookup(_ list: [String]) -> (Locale) async -> Locale? {
|
|
{ wanted in
|
|
let code = wanted.language.languageCode?.identifier
|
|
let region = wanted.region?.identifier
|
|
let matches = list.map { Locale(identifier: $0) }.filter { $0.language.languageCode?.identifier == code }
|
|
return matches.first { $0.region?.identifier == region } ?? matches.first
|
|
}
|
|
}
|
|
|
|
private func pick(explicit: String? = nil, preferred: [String], current: String = "en_US") async -> SpeechLanguage? {
|
|
await SpeechLanguagePicker.pick(
|
|
explicit: explicit,
|
|
candidates: SpeechLanguagePicker.automaticCandidates(preferred: preferred, current: current),
|
|
speech: lookup(speechLocales),
|
|
dictation: lookup(dictationLocales)
|
|
)
|
|
}
|
|
|
|
func testANorwegianIPhoneGetsNorwegianFromDictationTranscriber() async {
|
|
let picked = await pick(preferred: ["nb-NO", "en-US"], current: "nb_NO")
|
|
XCTAssertEqual(picked?.identifier, "nb-NO")
|
|
XCTAssertEqual(picked?.module, .dictation)
|
|
}
|
|
|
|
func testSpeechTranscriberStaysWhereItAlreadyWorks() async {
|
|
let english = await pick(preferred: ["en-US"])
|
|
XCTAssertEqual(english?.identifier, "en-US")
|
|
XCTAssertEqual(english?.module, .speech)
|
|
let spanish = await pick(preferred: ["es-MX", "en-US"])
|
|
XCTAssertEqual(spanish?.identifier, "es-MX")
|
|
XCTAssertEqual(spanish?.module, .speech)
|
|
}
|
|
|
|
func testThePreferredOrderWinsOverTheModule() async {
|
|
// Hebrew first: DictationTranscriber's Hebrew beats SpeechTranscriber's English.
|
|
let picked = await pick(preferred: ["he-IL", "en-US"])
|
|
XCTAssertEqual(picked?.identifier, "he-IL")
|
|
XCTAssertEqual(picked?.module, .dictation)
|
|
}
|
|
|
|
func testNynorskFallsBackToBokmal() async {
|
|
XCTAssertEqual(
|
|
SpeechLanguagePicker.automaticCandidates(preferred: ["nn-NO", "en-US"], current: "nn_NO"),
|
|
["nn-NO", "nb-NO", "en-US"]
|
|
)
|
|
let picked = await pick(preferred: ["nn-NO", "en-US"], current: "nn_NO")
|
|
XCTAssertEqual(picked?.identifier, "nb-NO")
|
|
}
|
|
|
|
func testAnExplicitChoiceWinsAndFallsBackToAutomaticWhenUnsupported() async {
|
|
let danish = await pick(explicit: "da-DK", preferred: ["en-US"])
|
|
XCTAssertEqual(danish?.identifier, "da-DK")
|
|
XCTAssertEqual(danish?.module, .dictation)
|
|
let german = await pick(explicit: "de-DE", preferred: ["nb-NO"])
|
|
XCTAssertEqual(german?.identifier, "de-DE")
|
|
XCTAssertEqual(german?.module, .speech)
|
|
let klingon = await pick(explicit: "tlh", preferred: ["nb-NO", "en-US"])
|
|
XCTAssertEqual(klingon?.identifier, "nb-NO", "an unsupported choice falls back to Automatic")
|
|
}
|
|
|
|
func testUSEnglishIsTheLastResort() async {
|
|
let picked = await pick(preferred: ["xx-XX"], current: "xx_XX")
|
|
XCTAssertEqual(picked?.identifier, "en-US")
|
|
}
|
|
|
|
func testShortNamesDropTheRegionOnlyWhenItIsTheOnlyOne() {
|
|
let english = Locale(identifier: "en-US")
|
|
let names = SpeechLanguagePicker.shortNames(for: ["nb-NO", "en-US", "en-GB", "he-IL"], in: english)
|
|
XCTAssertEqual(names["nb-NO"], "Norwegian Bokmål")
|
|
XCTAssertEqual(names["he-IL"], "Hebrew")
|
|
XCTAssertEqual(names["en-US"], "English (United States)")
|
|
}
|
|
|
|
func testOnlyEnglishCountsAsEnglish() {
|
|
XCTAssertTrue(SpeechLanguagePicker.isEnglish(nil))
|
|
XCTAssertTrue(SpeechLanguagePicker.isEnglish("en-GB"))
|
|
XCTAssertFalse(SpeechLanguagePicker.isEnglish("nb-NO"))
|
|
XCTAssertFalse(SpeechLanguagePicker.isEnglish("he-IL"))
|
|
}
|
|
}
|
|
|
|
/// Real Apple Speech on real clips, through the app's `AppleSpeechTranscriber`. Skipped unless
|
|
/// `HEX_SPEECH_CLIPS` names a folder of `<language>.wav` files (`nb-NO.wav`, made with
|
|
/// `say -v Nora`); it downloads each language's model, so it needs the network. It skips the
|
|
/// Speech Recognition prompt, which a test can't answer (simctl can't grant it either).
|
|
final class AppleSpeechClipTests: XCTestCase {
|
|
func testTranscribesEachClipInItsLanguage() async throws {
|
|
guard let folder = ProcessInfo.processInfo.environment["HEX_SPEECH_CLIPS"] else {
|
|
throw XCTSkip("Set HEX_SPEECH_CLIPS to a folder of <language>.wav clips")
|
|
}
|
|
guard #available(iOS 26.0, *) else { throw XCTSkip("Apple Speech needs iOS 26") }
|
|
let clips = try FileManager.default.contentsOfDirectory(atPath: folder)
|
|
.filter { $0.hasSuffix(".wav") }
|
|
.sorted()
|
|
XCTAssertFalse(clips.isEmpty)
|
|
var report: [String] = []
|
|
for clip in clips {
|
|
let identifier = String(clip.dropLast(4))
|
|
let suite = "hex.tests.\(UUID().uuidString)"
|
|
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
|
|
defer { defaults.removePersistentDomain(forName: suite) }
|
|
let settings = LanguageSettings(defaults: defaults)
|
|
settings.dictationLanguage = identifier
|
|
guard let language = await AppleSpeechLanguages.resolve(settings: settings),
|
|
Locale(identifier: language.identifier).language.languageCode
|
|
== Locale(identifier: identifier).language.languageCode else {
|
|
report.append("\(identifier): unsupported by SpeechTranscriber and DictationTranscriber")
|
|
continue
|
|
}
|
|
let transcriber = AppleSpeechTranscriber(language: language, requestsAuthorization: false)
|
|
do {
|
|
try await transcriber.prepare { _ in }
|
|
let text = try await transcriber.transcribe(URL(fileURLWithPath: folder).appendingPathComponent(clip))
|
|
report.append("\(identifier) [\(language.module.rawValue) \(language.identifier)]: \(text)")
|
|
} catch {
|
|
report.append("\(identifier) [\(language.module.rawValue) \(language.identifier)]: FAILED \(error.localizedDescription)")
|
|
}
|
|
}
|
|
let joined = report.joined(separator: "\n")
|
|
print("HEX-SPEECH-CLIPS\n\(joined)\nHEX-SPEECH-CLIPS-END")
|
|
try? joined.write(toFile: (folder as NSString).appendingPathComponent("transcripts.txt"), atomically: true, encoding: .utf8)
|
|
}
|
|
}
|