mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
What changed
- Experiments › Clean up what I say (off by default, App Group key
experiments.cleanupTagger): Hex's trained cleanup tagger removes ums,
repeats, and the words a spoken correction replaces ("3pm, actually 4pm"),
on the iPhone, in in-keyboard dictation and in app dictation. It runs after
transcription and learned fixes (in the app also after custom vocabulary),
before Apple Intelligence cleanup, translation, and formatting, and never
for Verbatim. When both cleanups are on, Apple Intelligence now receives the
tagged text instead of the raw transcript; nothing else changes while the
experiment is off.
- Model: the BERT L-4/H-512 token classifier (ckpt-1200k-l4h512) converted to
an int8 Core ML ML Program (coremltools 9, fp16 compute, enumerated lengths
16/32/64/128 plus a length input that masks the padding; the output is
logit(DELETE) - logit(KEEP)), 28.5 MB, with its WordPiece vocabulary. Both
ship once, in HEXKeyboard.appex (HEXKeyboard/CleanupTagger/), and the app
loads them from its embedded keyboard extension. Core ML codegen is off for
the keyboard target.
- HEXShared: CleanupTokenizer (Hugging Face BertTokenizer: special tokens,
BertNormalizer, BertPreTokenizer, WordPiece, byte-exact vocabulary keys,
HF's Unicode 8.0 character classes), CleanupReconstruction (a port of
js/reconstruct.js with JavaScript's UTF-16 casing), and CleanupTagger
(chunks of whole words within 128 tokens, P(DELETE) > 0.98, one serial
queue, 150 ms budget). A timeout, an error, or a result with no words left
keeps the transcript. The model loads when a dictation starts recording with
the experiment on, stays loaded, and is freed on a memory warning. It runs
on the Neural Engine or the CPU, never the GPU.
- Call sites: one each in KeyboardLocalDictation (after DictationCorrections,
before translation) and DictationController (after VocabularySpelling,
before the Apple Intelligence pass). prepareIfEnabled runs at recording
start, in KeyboardViewController and in DictationController.startRecording.
Why
- In the simulator the first load took 0.15 s on the CPU and 0.8 s on the GPU
path, both over the 150 ms budget. So loading starts when recording starts,
and the GPU isn't used (it also added 30 MB of footprint, against 3 MB on the
CPU, which keeps the int8 weights memory-mapped).
- Threshold 0.98, not the exported 0.95: 1/45 false deletes on hand-written
clean sentences against 3/45, with the same self-correction accuracy.
Verified
- xcodebuild test on the iPhone 18 Pro simulator: 168 tests, 0 failures,
including the new CleanupTaggerTests and DictationControllerTests
testCleanupTaggerRunsAfterLearnedFixesAndSkipsVerbatim. After the fixtures
were rewritten one case per line (same content), CleanupTaggerTests and
DictationControllerTests passed again (28 tests).
- Parity on the 137 hand-written sentences at 0.98: labels match the fp32
checkpoint on all 1,128 words, and 136/137 outputs match the ONNX int8
pipeline. #120 ("The cat keeps trying to scratch that chair.") differs on
two words that ONNX keeps (P 0.9725/0.9794) and Core ML deletes (0.984).
The fp32 checkpoint also deletes them (0.9879/0.9853), so the difference
comes from ONNX's int8 activations. 128/137 outputs match the hand-written
targets. The tokenizer matches HF on 1,891 words, and reconstruction matches
reconstruct.js on 670 cases.
- Simulator, CPU path: load 140-161 ms, first sentence after load about 8 ms,
then 3.3 ms median and 7.5 ms p95 per sentence; phys_footprint +2.9 MB.
- The Release generic iOS build with CODE_SIGNING_ALLOWED=NO succeeds.
HEXKeyboard.appex is 30.2 MB (model 27.8 MB, vocabulary 0.2 MB).
- Not verified on a physical iPhone: Neural Engine load time, latency, and the
keyboard extension's footprint next to Apple Speech.
Note: this adds a 28.4 MB binary (weight.bin) to git; the repo has no LFS.
811 lines
31 KiB
Swift
811 lines
31 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 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 CocoaError(.coderInvalidValue)
|
|
}
|
|
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
|
|
|
|
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 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")
|
|
}
|
|
}
|
|
}
|
|
|
|
private func settle() async throws {
|
|
for _ in 0..<8 {
|
|
try await Task.sleep(for: .milliseconds(25))
|
|
}
|
|
}
|
|
}
|