hex/ios/HEXMobileTests/KeyboardBridgeTests.swift
Ryan Vogel 62f2064db1
iOS: a handoff to Hex can't leave the keyboard stuck, and dismissed dictations still deliver (#2163)
* iOS: a dictation handed to Hex can't leave the keyboard stuck

TestFlight build 56 (iPhone 14, iOS 27.2.1): dictate in the keyboard, dismiss
it, dictate again (Hex opens and records), swipe back: the keyboard stayed in
recording, no text arrived, and it never healed.

Reproduced on an iOS 27.2 simulator (iPhone 14) with the exact sequence in a
Safari field and a simulated microphone in Hex:
- With Hex alive and a warm session, the handoff works: Done in the keyboard
  stops Hex and the text goes in.
- When Hex stops during the handoff (killed here; build 56 could also crash
  in AVAudioRecorder's callback, fixed by RetiredRecorders), the App Group
  snapshot keeps saying recording with a heartbeat that only ages. The
  keyboard trusted the state alone, so every keyboard after showed a
  recording; Done and Cancel were written for no one. It lasted through
  dismissing, new keyboard processes, everything until Hex was opened again.
- With One shot, Hex never read the keyboard's commands after a handoff (only
  the warm session loop did): Done flipped back to recording and the
  recording ran to its 60 s limit.

Fix:
- KeyboardSnapshot.isOrphanedJob: a recording or transcription whose
  heartbeat is more than 6 s old is over. KeyboardViewModel drops it (reads as
  offline, any result kept), so the keyboard returns to idle and dictates again.
  The heartbeat is wall-clock time, so a new keyboard process reads an
  orphaned App Group snapshot the same way.
- DictationController runs its keyboard loop while any keyboard job is in
  flight, not only in a warm session: One shot handoffs read Done and Cancel,
  and every keyboard transcription keeps heartbeating (endWarmSession restarts
  it for an accepted transcription). Before, One shot published no heartbeat
  while transcribing.
- Hex asks for background time while it finishes a keyboard's transcription:
  in One shot nothing kept Hex running once its microphone closed.

Tests: KeyboardBridgeTests.testAJobHexStoppedHeartbeatingForNoLongerHoldsTheKeyboard,
DictationControllerTests.testAKeyboardHandoffFinishedFromTheKeyboardDeliversItsTextInEitherMode
and testAOneShotHandoffCancelledFromTheKeyboardStops; with the next commit the full HEXMobile suite
passes (477 tests, one skipped as before) on the iOS 27.2 simulator.

* iOS: a keyboard dictation cut short by dismissing the keyboard still delivers its text

Steps 1 and 2 of the TestFlight build 56 report (dictate in the keyboard,
then dismiss it). On the iOS 27.2 simulator the keyboard's viewWillDisappear
called KeyboardLocalDictation.discard, which only drops a touch-down capture:
a recording stayed .recording, WebKit kept the microphone until the view
controller was torn down about a second later (a new one comes with each
appearance), and what was said was lost with it (its WAV left in tmp). A
transcription in flight finished into a deallocated object and was dropped.
Nothing of it reached the App Group: the next keyboard started idle.

Now:
- keyboardWillHide: a recording stops its capture at once and finishes with
  what was said without waiting for the page (WebKit may not answer once the
  keyboard is gone); a transcription carries on. Either job's text is held in
  the App Group (KeyboardHeldDictation, keyboard.heldDictation), so the next
  keyboard, in this process or a new one, inserts it into the same field when
  it comes back there within 30 s, and offers it otherwise.
- Paste dictation: the full keyboard's strip offers a dictation the keyboard
  didn't insert by itself (a held one for another field or past its 30 s, or
  Hex's result that came after its 30 s, such as Done in Hex then back late),
  for 10 minutes. Hex keeps a keyboard result in its snapshot for that long
  (KeyboardSnapshot.resultOfferWindow); only Paste reads it, never the
  clipboard. After a handoff the field's documentIdentifier changes (seen on
  the simulator), so Hex's results still go into whichever field is open.
- Self-heal for in-keyboard dictation (KeyboardJobWatchdog), checked on each
  poll: a capture without audio for 6 s finishes with what it heard, a
  transcription stuck for 2 minutes is given up and the keyboard goes idle.
- Hex's results also arrive while an in-keyboard dictation shows (the local
  snapshot used to hide them entirely).

Tests: KeyboardBridgeTests.testADictationTheKeyboardFinishedAfterItHidReachesTheNextKeyboard
and testAResultPastItsTimeToGoInIsOfferedForTenMinutes, and the offer window
in DictationControllerTests' handoff test; the full HEXMobile suite passes
(477 tests, one skipped as before) on the iOS 27.2 simulator.
2026-11-21 08:31:48 +00:00

681 lines
33 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import XCTest
@testable import HEX
@MainActor
final class KeyboardBridgeTests: XCTestCase {
func testSnapshotAvailabilityRequiresFreshHeartbeatAndActiveSession() {
let now = 1_000.0
let available = snapshot(state: .ready, heartbeat: now - 2.9, expiresAt: now + 1)
let stale = snapshot(state: .ready, heartbeat: now - 3.0, expiresAt: now + 1)
let expired = snapshot(state: .ready, heartbeat: now, expiresAt: now)
let transcribingAfterSessionEnd = snapshot(state: .transcribing, heartbeat: now - 0.5, expiresAt: 0)
XCTAssertTrue(available.isAvailable(at: now))
XCTAssertFalse(stale.isAvailable(at: now))
XCTAssertFalse(expired.isAvailable(at: now))
XCTAssertTrue(transcribingAfterSessionEnd.isAvailable(at: now))
}
func testDeliverableResultSurvivesWarmSessionShutdownUntilTTL() {
let now = 5_000.0
let closedWithResult = KeyboardSnapshot(
state: .offline,
heartbeat: 0,
expiresAt: 0,
resultID: "res-1",
resultExpiresAt: now + 25,
transcript: "Ship it."
)
XCTAssertFalse(closedWithResult.isAvailable(at: now))
XCTAssertTrue(closedWithResult.hasDeliverableResult(at: now))
XCTAssertFalse(closedWithResult.hasDeliverableResult(at: now + 26))
}
/// TestFlight build 56: dictate in the keyboard, dismiss it, dictate again (Hex opens and
/// records), swipe back. Hex ended mid-job and its last snapshot still said recording, so
/// every keyboard after showed a recording nothing would finish: Done and Cancel went to
/// no one, and no text came until Hex was opened again.
func testAJobHexStoppedHeartbeatingForNoLongerHoldsTheKeyboard() {
let t0 = 10_000.0
let recording = KeyboardSnapshot(
state: .recording,
heartbeat: t0,
expiresAt: t0 + 900,
recordingStartedAt: t0 - 3,
audioLevel: 0.4,
jobID: "handoff"
)
let model = KeyboardViewModel()
func show(_ snapshot: KeyboardSnapshot, at now: TimeInterval, on model: KeyboardViewModel) {
model.applyBridgeState(
hasFullAccess: true,
snapshot: snapshot,
isModelInstalled: true,
style: .polished,
now: now,
animated: false
)
}
show(recording, at: t0, on: model)
XCTAssertEqual(model.stagePhase, .recording)
show(recording, at: t0 + 5, on: model)
XCTAssertEqual(model.stagePhase, .recording, "a late heartbeat isn't a Hex that ended")
// Done, sent to a Hex that will never read it.
model.setPendingCommand(
KeyboardViewModel.PendingCommand(kind: .stop, jobID: "handoff", sentAt: t0 + 6),
now: t0 + 6,
animated: false
)
XCTAssertEqual(model.stagePhase, .transcribing)
show(recording, at: t0 + 7, on: model)
XCTAssertEqual(model.stagePhase, .idle, "the job is over: the Hex key dictates again")
XCTAssertNil(model.pendingCommand)
XCTAssertNil(model.currentSnapshot.jobID)
XCTAssertFalse(model.isWarmAvailable)
// A keyboard opened later, in this process or a new one, reads the same snapshot the same way.
let later = KeyboardViewModel()
show(recording, at: t0 + 600, on: later)
XCTAssertEqual(later.stagePhase, .idle)
let transcribing = KeyboardSnapshot(state: .transcribing, heartbeat: t0, expiresAt: 0, jobID: "handoff")
show(transcribing, at: t0 + 2, on: later)
XCTAssertEqual(later.stagePhase, .transcribing)
show(transcribing, at: t0 + 7, on: later)
XCTAssertEqual(later.stagePhase, .idle)
XCTAssertTrue(
KeyboardSnapshot(state: .recording, heartbeat: 0, expiresAt: 0, jobID: "handoff").isOrphanedJob(at: t0),
"never heartbeated"
)
// A result the snapshot carries still arrives, and a Hex heartbeating again is live again.
let finished = KeyboardSnapshot(
state: .transcribing,
heartbeat: t0,
expiresAt: 0,
jobID: "handoff",
resultID: "result",
resultExpiresAt: t0 + 30,
transcript: "Ship it."
)
XCTAssertTrue(finished.droppingOrphanedJob(at: t0 + 7).hasDeliverableResult(at: t0 + 7))
let back = KeyboardSnapshot(state: .recording, heartbeat: t0 + 600, expiresAt: t0 + 900, jobID: "next")
show(back, at: t0 + 600, on: later)
XCTAssertEqual(later.stagePhase, .recording)
}
/// The same keyboard's own dictation: one still recording or transcribing when the keyboard
/// was dismissed finishes without it, goes back into its field when the keyboard returns
/// there while it's fresh, and is offered as Paste dictation anywhere else or later. A
/// capture that went quiet or a transcription that never returns resets the keyboard.
func testADictationTheKeyboardFinishedAfterItHidReachesTheNextKeyboard() {
let suiteName = "hex.tests.heldDictation.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)!
defer { defaults.removePersistentDomain(forName: suiteName) }
let bridge = KeyboardBridge(defaults: defaults)
let field = UUID()
let held = KeyboardHeldDictation(
id: "held",
text: "Meet at ten.",
heard: "meet at ten",
document: field,
finishedAt: 1_000
)
XCTAssertNil(bridge.heldDictation)
bridge.heldDictation = held
XCTAssertEqual(KeyboardBridge(defaults: defaults).heldDictation, held, "a new keyboard process finds it")
XCTAssertEqual(held.delivery(in: field, at: 1_010), .insert)
XCTAssertEqual(held.delivery(in: nil, at: 1_010), .insert, "a field UIKit hasn't named yet")
XCTAssertEqual(held.delivery(in: UUID(), at: 1_010), .offer, "another field")
XCTAssertEqual(held.delivery(in: field, at: 1_031), .offer, "back after its time to go in by itself")
XCTAssertEqual(held.delivery(in: field, at: 1_000 + KeyboardSnapshot.resultOfferWindow), .expired)
bridge.heldDictation = nil
XCTAssertNil(KeyboardBridge(defaults: defaults).heldDictation)
XCTAssertFalse(KeyboardJobWatchdog.isStalled(.recording, lastProgress: 100, now: 105), "a capture still starting")
XCTAssertTrue(KeyboardJobWatchdog.isStalled(.recording, lastProgress: 100, now: 107), "no audio for 7 s")
XCTAssertFalse(KeyboardJobWatchdog.isStalled(.transcribing, lastProgress: 100, now: 160), "a long dictation")
XCTAssertTrue(KeyboardJobWatchdog.isStalled(.transcribing, lastProgress: 100, now: 230))
}
/// Hex's text that came after its time to go in by itself (Done in Hex, then back late)
/// is offered as Paste dictation for ten minutes rather than lost.
func testAResultPastItsTimeToGoInIsOfferedForTenMinutes() {
let snap = KeyboardSnapshot(
state: .offline,
heartbeat: 0,
expiresAt: 0,
resultID: "result",
resultExpiresAt: 5_030,
transcript: "Ship it."
)
XCTAssertTrue(snap.hasDeliverableResult(at: 5_029))
XCTAssertFalse(snap.hasDeliverableResult(at: 5_031))
XCTAssertTrue(snap.hasOfferableResult(at: 5_031))
XCTAssertFalse(snap.hasOfferableResult(at: 5_030 + KeyboardSnapshot.resultOfferWindow))
XCTAssertFalse(KeyboardSnapshot.offline.hasOfferableResult(at: 5_031))
}
func testKeyboardMessagesRoundTripThroughJSON() throws {
let command = KeyboardCommand(
id: "command",
kind: .stop,
jobID: "job",
style: .casual,
sentAt: 42.5
)
let snap = snapshot(state: .recording, heartbeat: 10, expiresAt: 20)
let encoder = JSONEncoder()
let decoder = JSONDecoder()
XCTAssertEqual(
try decoder.decode(KeyboardCommand.self, from: encoder.encode(command)),
command
)
XCTAssertEqual(
try decoder.decode(KeyboardSnapshot.self, from: encoder.encode(snap)),
snap
)
}
func testKeyboardRecordingLaunchRoundTripsMetadataAndEnforcesTenSecondWindow() {
let t0 = 2_000.0
let request = KeyboardLaunchRequest.startRecording(
jobID: "job with spaces",
requestedAt: t0,
style: .casual
)
let decoded = KeyboardLaunchRequest(url: request.url)
XCTAssertEqual(decoded, request)
XCTAssertFalse(request.isHandoffExpired(at: t0 + 9.9))
XCTAssertTrue(request.isHandoffExpired(at: t0 + 10.1))
}
func testKeyboardSessionLaunchDoesNotRequestRecording() {
let request = KeyboardLaunchRequest.startSession(requestedAt: 100)
XCTAssertEqual(KeyboardLaunchRequest(url: request.url), request)
// A keyboard from before the return-app setting went away may still send `return=`.
XCTAssertEqual(
KeyboardLaunchRequest(url: URL(string: "hex-dictation://keyboard/start?ts=100&return=messages")!),
request
)
}
func testKeyboardSetupLaunchRoundTripsWithoutAHandoff() {
let request = KeyboardLaunchRequest.setup
XCTAssertEqual(request.url.absoluteString, "hex-dictation://keyboard/setup")
XCTAssertEqual(KeyboardLaunchRequest(url: request.url), request)
XCTAssertFalse(request.isHandoffExpired(at: 1_000_000))
}
@MainActor
func testFullAccessSeenAtIsStoredInTheAppGroup() {
let suiteName = "hex.tests.fullAccess.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)!
defer { defaults.removePersistentDomain(forName: suiteName) }
let bridge = KeyboardBridge(defaults: defaults)
XCTAssertNil(bridge.fullAccessSeenAt)
bridge.fullAccessSeenAt = 1_234
XCTAssertEqual(KeyboardBridge(defaults: defaults).fullAccessSeenAt, 1_234)
}
@MainActor
func testFullAccessReportsAreStoredInTheAppGroup() {
let suiteName = "hex.tests.fullAccessReports.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)!
defer { defaults.removePersistentDomain(forName: suiteName) }
let bridge = KeyboardBridge(defaults: defaults)
XCTAssertNil(bridge.fullAccessOnReport)
XCTAssertNil(bridge.fullAccessOffReport)
bridge.fullAccessSeenAt = 50
XCTAssertEqual(
bridge.fullAccessOnReport,
KeyboardFullAccessReport(isOn: true, at: 50, launchedAt: 0),
"an earlier keyboard's word counts, as from the oldest process"
)
let on = KeyboardFullAccessReport(isOn: true, at: 100, launchedAt: 90)
let off = KeyboardFullAccessReport(isOn: false, at: 200, launchedAt: 190)
bridge.recordFullAccess(on)
bridge.recordFullAccess(off)
let reread = KeyboardBridge(defaults: defaults)
XCTAssertEqual(reread.fullAccessOnReport, on)
XCTAssertEqual(reread.fullAccessOffReport, off)
XCTAssertEqual(reread.fullAccessSeenAt, 100, "an on still sets the key earlier builds read")
}
func testFullAccessTrustsTheNewestReportFromANewerKeyboard() {
func report(_ isOn: Bool, at: TimeInterval, launched: TimeInterval) -> KeyboardFullAccessReport {
KeyboardFullAccessReport(isOn: isOn, at: at, launchedAt: launched)
}
let resolve = KeyboardFullAccess.resolve
XCTAssertEqual(resolve(nil, nil, 0), .unconfirmed)
XCTAssertEqual(resolve(report(true, at: 10, launched: 5), nil, 1_000), .on, "an on stays on")
XCTAssertEqual(resolve(nil, report(false, at: 120, launched: 110), 100), .off, "seen off since Hex came back")
XCTAssertEqual(
resolve(nil, report(false, at: 80, launched: 70), 100), .unconfirmed,
"seen off before Hex came back from Settings: Full Access may have been turned on since"
)
XCTAssertEqual(
resolve(report(true, at: 150, launched: 140), report(false, at: 120, launched: 110), 100), .on,
"the grant is newer"
)
XCTAssertEqual(
resolve(report(true, at: 150, launched: 140), report(false, at: 160, launched: 110), 100), .on,
"a keyboard started before the grant still says off: stale"
)
XCTAssertEqual(
resolve(report(true, at: 150, launched: 140), report(false, at: 160, launched: 140), 100), .off,
"the same keyboard saw it turned off"
)
XCTAssertEqual(
resolve(report(true, at: 50, launched: 40), report(false, at: 80, launched: 70), 100), .unconfirmed,
"turned off after the last on, then Hex went to the background: it may be on again"
)
}
@MainActor
func testSetupMonitorFollowsTheKeyboardsReports() {
let suiteName = "hex.tests.setupMonitor.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)!
defer { defaults.removePersistentDomain(forName: suiteName) }
let bridge = KeyboardBridge(defaults: defaults)
let monitor = KeyboardSetupMonitor(bridge: bridge, activeSince: 1_000)
XCTAssertEqual(monitor.fullAccess, .unconfirmed)
bridge.recordFullAccess(KeyboardFullAccessReport(isOn: false, at: 1_010, launchedAt: 1_005))
monitor.refresh()
XCTAssertEqual(monitor.fullAccess, .off, "the keyboard said off while Hex was up")
monitor.cameToForeground(at: 1_020)
XCTAssertEqual(monitor.fullAccess, .unconfirmed, "back from Settings: off is no longer known")
// No refresh call: the keyboard's Darwin notification brings the report in.
bridge.recordFullAccess(KeyboardFullAccessReport(isOn: true, at: 1_030, launchedAt: 1_025))
let deadline = Date().addingTimeInterval(3)
while monitor.fullAccess != .on, Date() < deadline {
RunLoop.main.run(until: Date().addingTimeInterval(0.02))
}
XCTAssertEqual(monitor.fullAccess, .on)
XCTAssertTrue(monitor.fullAccessOn)
}
@MainActor
func testEmptyKeyboardDictationIsNotedInTheAppGroup() {
let suiteName = "hex.tests.emptyDictation.\(UUID().uuidString)"
let defaults = UserDefaults(suiteName: suiteName)!
defer { defaults.removePersistentDomain(forName: suiteName) }
let bridge = KeyboardBridge(defaults: defaults)
XCTAssertNil(bridge.lastEmptyDictationAt)
bridge.lastEmptyDictationAt = 2_000
XCTAssertEqual(KeyboardBridge(defaults: defaults).lastEmptyDictationAt, 2_000)
bridge.lastEmptyDictationAt = nil
XCTAssertNil(KeyboardBridge(defaults: defaults).lastEmptyDictationAt)
}
func testOnboardingPracticeCountsADictationOrAFewTypedWords() {
XCTAssertFalse(OnboardingPractice.isDone(text: "S", dictated: false, fullAccessOn: true), "one letter")
XCTAssertFalse(OnboardingPractice.isDone(text: "See you", dictated: false, fullAccessOn: true))
XCTAssertTrue(OnboardingPractice.isDone(text: "See you at", dictated: false, fullAccessOn: true))
XCTAssertFalse(OnboardingPractice.isDone(text: "See you at ten", dictated: false, fullAccessOn: false), "not the Hex keyboard")
XCTAssertTrue(OnboardingPractice.isDone(text: "", dictated: true, fullAccessOn: false), "a dictation arrived")
XCTAssertGreaterThanOrEqual(OnboardingPractice.words(in: "我们十点见"), 2, "Chinese splits into words without spaces")
}
func testOnboardingIsReadyOnlyOnceHexAndTheHexKeyModelsAre() {
typealias Stage = OnboardingModel.Stage
XCTAssertEqual(OnboardingModel.combine(.ready, .ready), .ready)
XCTAssertEqual(OnboardingModel.combine(.ready, .downloading(0.4)), .downloading(0.7), "Parakeet ready, the keyboard's Apple Speech still downloading")
XCTAssertEqual(OnboardingModel.combine(.downloading(0.2), .ready), .downloading(0.6))
XCTAssertEqual(OnboardingModel.combine(.ready, .starting), .downloading(0.5))
XCTAssertEqual(OnboardingModel.combine(.starting, .starting), .starting)
XCTAssertEqual(OnboardingModel.combine(.ready, .failed("no")), .failed("no"))
XCTAssertEqual(OnboardingModel.combine(.failed("app"), .failed("keys")), .failed("app"))
XCTAssertEqual(OnboardingModel.combine(.downloading(0.2), nil), .downloading(0.2), "nothing for the keyboard to download")
XCTAssertEqual(OnboardingModel.combine(.ready, nil), .ready)
}
func testOnboardingResumesPagesEarlierBuildsSaved() {
XCTAssertEqual(OnboardingPage(saved: "welcome"), .setup)
XCTAssertEqual(OnboardingPage(saved: "allow"), .permissions)
XCTAssertEqual(OnboardingPage(saved: "try"), .practice)
XCTAssertEqual(OnboardingPage(saved: "waiting"), .waiting)
XCTAssertNil(OnboardingPage(saved: "nope"))
XCTAssertEqual(OnboardingPage.allCases, [.setup, .demo, .permissions, .waiting, .practice, .ready])
XCTAssertEqual(OnboardingPage.allCases.filter(\.isOptional), [.demo, .practice])
}
func testKeyboardRecordingLaunchRequiresAJob() {
let url = URL(string: "hex-dictation://keyboard/record")!
XCTAssertNil(KeyboardLaunchRequest(url: url))
}
func testTranscriptStylesFormatDeterministically() {
let raw = "um let's ship the ios build tonight"
XCTAssertEqual(
TranscriptFormatter.format(raw, style: .polished),
"Let's ship the ios build tonight."
)
XCTAssertEqual(
TranscriptFormatter.format("Um, sounds good.", style: .casual),
"sounds good"
)
XCTAssertEqual(
TranscriptFormatter.format("um keep raw words", style: .verbatim),
"um keep raw words"
)
XCTAssertEqual(
TranscriptFormatter.format("First item bullet check signing bullet test keyboard", style: .notes),
"First item\n- Check signing\n- Test keyboard"
)
}
func testFillerTrimmingFollowsTheDictationLanguage() {
// "er" is Norwegian for "is"; English trims it as a filler, Norwegian must not.
XCTAssertEqual(
TranscriptFormatter.format("det er bra, eh, vi ses", style: .polished, language: "nb-NO"),
"Det er bra, vi ses."
)
XCTAssertEqual(
TranscriptFormatter.format("er I think so", style: .polished, language: "en-US"),
"I think so."
)
// Portuguese "um" is "a"; a language without a filler list trims nothing.
XCTAssertEqual(
TranscriptFormatter.format("um café, por favor", style: .casual, language: "pt-BR"),
"um café, por favor"
)
XCTAssertEqual(
TranscriptFormatter.format("um let's go", style: .polished),
"Let's go.",
"no language is English, as before"
)
}
func testSmartInsertionSpacingRespectsSurroundingContext() {
XCTAssertEqual(
TranscriptFormatter.insertionText(for: "world.", beforeContext: "Hello", afterContext: nil),
" world."
)
XCTAssertEqual(
TranscriptFormatter.insertionText(for: "world.", beforeContext: "Hello ", afterContext: nil),
"world."
)
XCTAssertEqual(
TranscriptFormatter.insertionText(for: "Hello", beforeContext: nil, afterContext: "world"),
"Hello "
)
}
func testDictationContinuingASentenceStartsLowercase() {
let words: Set<String> = ["that's", "the", "self", "a", "don't"]
func insert(_ text: String, after before: String?) -> String {
TranscriptFormatter.insertionText(for: text, beforeContext: before, afterContext: nil, isWord: words.contains)
}
XCTAssertEqual(insert("That's great.", after: "I think"), " that's great.")
XCTAssertEqual(insert("The plan works.", after: "and so "), "the plan works.")
XCTAssertEqual(insert("Self-driving cars.", after: "I like"), " self-driving cars.")
XCTAssertEqual(insert("A dog.", after: "We saw"), " a dog.")
// A sentence start keeps its capital.
for before in [nil, "", " ", "Hello.", "Hello. ", "Really?", "Yes!", "Wait…", "Line one\n", "He said \"stop.\" "] {
XCTAssertTrue(TranscriptFormatter.startsSentence(after: before), String(describing: before))
XCTAssertEqual(insert("The end.", after: before).trimmingCharacters(in: .whitespaces), "The end.")
}
XCTAssertFalse(TranscriptFormatter.startsSentence(after: "Note: "))
XCTAssertFalse(TranscriptFormatter.startsSentence(after: "see (this)"))
// I, its contractions, acronyms, inner capitals and names keep theirs.
XCTAssertEqual(insert("I think so.", after: "and"), " I think so.")
XCTAssertEqual(insert("I'm here.", after: "and"), " I'm here.")
XCTAssertEqual(insert("I’ll go.", after: "and"), " I’ll go.")
XCTAssertEqual(insert("NASA launched it.", after: "and"), " NASA launched it.")
XCTAssertEqual(insert("McDonald's is open.", after: "and"), " McDonald's is open.")
XCTAssertEqual(insert("Sarah said so.", after: "and"), " Sarah said so.", "not a word in lowercase: a name")
XCTAssertEqual(insert("iPhone works.", after: "my"), " iPhone works.")
// Without a dictionary the case is left alone.
XCTAssertEqual(
TranscriptFormatter.insertionText(for: "That's it.", beforeContext: "and", afterContext: nil),
" That's it."
)
}
func testDictationSpacingNeverDoublesOrSplitsAnOpeningMark() {
XCTAssertEqual(TranscriptFormatter.insertionText(for: " world", beforeContext: "Hello ", afterContext: nil), "world")
XCTAssertEqual(TranscriptFormatter.insertionText(for: " world", beforeContext: "Hello", afterContext: nil), " world")
XCTAssertEqual(TranscriptFormatter.insertionText(for: "world", beforeContext: "Hello\t", afterContext: nil), "world")
for opening in ["(", "[", "\"", "“", "‘", "«", "¿", "¡"] {
XCTAssertEqual(
TranscriptFormatter.insertionText(for: "Hola", beforeContext: "Dijo " + opening, afterContext: nil),
"Hola",
opening
)
}
XCTAssertEqual(TranscriptFormatter.insertionText(for: ", right", beforeContext: "Okay", afterContext: nil), ", right")
}
func testDictationDictionaryFollowsTheDictationLanguage() {
let available = ["en_US", "nb", "de_DE", "fr_FR", "es"]
XCTAssertEqual(KeyboardLanguage.spellCheckLanguage(forDictation: "nb-NO", available: available), "nb")
XCTAssertEqual(KeyboardLanguage.spellCheckLanguage(forDictation: "de-DE", available: available), "de_DE")
XCTAssertEqual(KeyboardLanguage.spellCheckLanguage(forDictation: "es-419", available: available), "es")
XCTAssertEqual(KeyboardLanguage.spellCheckLanguage(forDictation: "fr-CA", available: available), "fr_FR")
XCTAssertEqual(KeyboardLanguage.spellCheckLanguage(forDictation: "en-GB", available: available), "en_US")
XCTAssertNil(KeyboardLanguage.spellCheckLanguage(forDictation: "he-IL", available: available))
// German capitalizes every noun, and its dictionary takes them in lowercase too.
XCTAssertFalse(TranscriptFormatter.lowercasesContinuations(in: "de-DE"))
XCTAssertFalse(TranscriptFormatter.lowercasesContinuations(in: "de_CH"))
XCTAssertTrue(TranscriptFormatter.lowercasesContinuations(in: "en-US"))
XCTAssertTrue(TranscriptFormatter.lowercasesContinuations(in: "nb-NO"))
}
func testAppIntentMetadataContainsNoApplePlatformNames() throws {
var texts = [
String(localized: DictateWithHexIntent.title),
String(localized: WarmHexKeyboardIntent.title),
String(localized: ToggleHexControlIntent.title),
String(localized: StopHexDictationIntent.title),
String(localized: CancelHexDictationIntent.title),
String(localized: DictateWithHexIntent.description.descriptionText),
String(localized: WarmHexKeyboardIntent.description.descriptionText),
String(localized: ToggleHexControlIntent.description.descriptionText),
String(localized: StopHexDictationIntent.description.descriptionText),
String(localized: CancelHexDictationIntent.description.descriptionText),
]
// Read user-facing strings from compiled Metadata.appintents inside HEX.app and HEXWidgets.appex,
// plus source literals when #filePath is not CAS prefix-mapped (/^wt).
let userKeys: Set<String> = ["title", "shortTitle", "description", "key", "phrases", "basePhrases", "template"]
func collectUserStrings(_ node: Any) {
if let dict = node as? [String: Any] {
for (k, v) in dict {
if userKeys.contains(k) {
if let s = v as? String {
texts.append(s)
} else if let arr = v as? [String] {
texts.append(contentsOf: arr)
} else {
collectUserStrings(v)
}
} else {
collectUserStrings(v)
}
}
} else if let arr = node as? [Any] {
for item in arr {
collectUserStrings(item)
}
}
}
var metadataFilesRead = 0
var metadataRoots: [URL] = [
Bundle.main.bundleURL.appendingPathComponent("Metadata.appintents"),
]
if let plugIns = Bundle.main.builtInPlugInsURL {
metadataRoots.append(
plugIns.appendingPathComponent("HEXWidgets.appex/Metadata.appintents")
)
}
for root in metadataRoots where FileManager.default.fileExists(atPath: root.path) {
if let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: nil) {
for case let url as URL in enumerator {
guard ["json", "actionsdata", "phrasesdata"].contains(url.pathExtension),
let data = try? Data(contentsOf: url),
let obj = try? JSONSerialization.jsonObject(with: data) else {
continue
}
metadataFilesRead += 1
collectUserStrings(obj)
}
}
}
XCTAssertGreaterThan(metadataFilesRead, 0, "Expected compiled Metadata.appintents in host bundle")
let ios = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
if FileManager.default.fileExists(atPath: ios.appendingPathComponent("HEXMobile/HexIntents.swift").path) {
for file in [
"HEXMobile/HexIntents.swift",
"HEXActivity/HexActivityAttributes.swift",
"HEXActivity/HexControlIntents.swift",
"HEXWidgets/HexDictationControl.swift",
] {
let source = try String(contentsOf: ios.appendingPathComponent(file), encoding: .utf8)
for line in source.split(separator: "\n") where !line.trimmingCharacters(in: .whitespaces).hasPrefix("//") {
texts.append(contentsOf: line.split(separator: "\"", omittingEmptySubsequences: false)
.enumerated().filter { $0.offset % 2 == 1 }.map { String($0.element) })
}
}
}
let forbidden = ["iphone", "ipad", "apple", "siri", "macos", "ios", "watch", "airpods", "vision"]
for text in texts {
let lower = text.lowercased()
for word in forbidden {
XCTAssertFalse(lower.contains(word), "Intent string '\(text)' contains forbidden word '\(word)'")
}
}
}
private func snapshot(
state: KeyboardDictationState,
heartbeat: TimeInterval,
expiresAt: TimeInterval
) -> KeyboardSnapshot {
KeyboardSnapshot(
state: state,
heartbeat: heartbeat,
expiresAt: expiresAt,
recordingStartedAt: heartbeat - 2,
audioLevel: 0.5,
jobID: "job",
resultID: "result",
resultExpiresAt: heartbeat + 30,
transcript: "hello",
message: nil
)
}
}
/// The keyboard's quick dictation-language switch.
final class DictationLanguageSwitchTests: XCTestCase {
private let supported = ["en-US", "en-GB", "es-ES", "es-MX", "de-DE", "nb-NO", "he-IL", "fr-FR"]
func testOffersTheCurrentThenRecentThenPreferredLanguages() {
XCTAssertEqual(
DictationLanguageSwitch.choices(
current: "de-DE",
recent: ["he-IL", "de-DE"],
preferred: ["nb-NO", "en-US"],
supported: supported
),
["de-DE", "he-IL", "nb-NO", "en-US"]
)
}
func testMatchesPreferredLanguagesToOnesAppleTranscribes() {
let choices = DictationLanguageSwitch.choices(
current: nil,
recent: [],
preferred: ["nn-NO", "es-419", "es", "en-AU", "tlh", "fr-CA", "en-GB", "de-AT"],
supported: supported
)
// Nynorsk is Bokmål; "es-419" and "es" find Spain's Spanish; Klingon has none.
XCTAssertEqual(choices, ["nb-NO", "es-ES", "en-US", "fr-FR", "en-GB"])
XCTAssertEqual(choices.count, DictationLanguageSwitch.maxChoices)
}
func testWithoutAListEveryLanguageIsOffered() {
XCTAssertEqual(
DictationLanguageSwitch.choices(current: nil, recent: [], preferred: ["nb_NO", "en"], supported: []),
["nb-NO", "en"]
)
}
func testNamesEachLanguageInItself() {
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "nb-NO"), "Norsk")
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "en-US"), "English")
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "es-ES"), "Español")
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "de-DE"), "Deutsch")
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "he-IL"), "עברית")
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "ru-RU"), "Русский")
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "sr-Latn-RS"), "Srpski")
XCTAssertEqual(
DictationLanguageSwitch.nativeNames(for: ["en-US", "en-GB", "nb-NO"]),
["en-US": "English (US)", "en-GB": "English (GB)", "nb-NO": "Norsk"]
)
}
/// Experiments › Hinglish offers Hindi in the Hex key's language menu, named Hinglish.
func testHinglishOffersHindiByThatName() throws {
let suite = "hex.tests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let hinglish = HinglishSettings(defaults: defaults)
let supported = self.supported + ["hi-IN"]
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "hi-IN", hinglish: hinglish), "हिन्दी")
XCTAssertEqual(
DictationLanguageSwitch.choices(current: "de-DE", recent: ["he-IL"], preferred: ["en-US"], supported: supported),
["de-DE", "he-IL", "en-US"]
)
hinglish.isEnabled = true
XCTAssertEqual(DictationLanguageSwitch.nativeName(for: "hi-IN", hinglish: hinglish), "Hinglish")
XCTAssertEqual(
DictationLanguageSwitch.nativeNames(for: ["hi-IN", "en-US"], hinglish: hinglish),
["hi-IN": "Hinglish", "en-US": "English"]
)
XCTAssertEqual(
DictationLanguageSwitch.choices(
current: "de-DE", recent: ["he-IL"], preferred: ["en-US"], supported: supported, hinglish: true
),
["de-DE", "he-IL", "hi-IN", "en-US"]
)
XCTAssertEqual(
DictationLanguageSwitch.choices(current: nil, recent: [], preferred: ["en-US"], supported: ["en-US"], hinglish: true),
["en-US"],
"not offered where Apple has no Hindi"
)
}
func testAChoiceMovesToTheFrontOfTheRecents() throws {
let suite = "hex.tests.\(UUID().uuidString)"
let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))
defer { defaults.removePersistentDomain(forName: suite) }
let settings = LanguageSettings(defaults: defaults)
for id in ["nb-NO", "es-ES", "de-DE", "he-IL", "fr-FR", "en-GB", "es-ES"] {
settings.chooseDictationLanguage(id)
}
XCTAssertEqual(settings.dictationLanguage, "es-ES")
XCTAssertEqual(settings.recentDictationLanguages, ["es-ES", "en-GB", "fr-FR", "he-IL", "de-DE"])
settings.chooseDictationLanguage(nil)
XCTAssertNil(settings.dictationLanguage, "Automatic")
XCTAssertEqual(settings.recentDictationLanguages.first, "es-ES", "Automatic isn't a recent")
}
}