hex/ios/HEXMobileTests/HexKeyGestureTests.swift
Ryan Vogel f78d6c948a
iOS: the keyboard starts listening on touch-down, with its capture page ready when it opens (#2089)
* iOS keyboard: log each step from the Hex key's touch-down to the first audio

In-keyboard dictation can lose the first words: nothing said how long the
microphone takes to open after the Hex key, or where that time goes.

What changed
- HexKeyControl reports touch-down (onPress, from the touch's own timestamp)
  through KeyboardViewModel.onHexKeyPress, before it is a tap, hold or slide.
- KeyboardLocalDictation keeps a CaptureTimeline per start and, at the first
  audio buffer, writes one probe-log line: the touch-down, the start call,
  the web view made, its page loaded, hexStart evaluated, the device list,
  getUserMedia, the stream kept, the audio context running, "started" and
  the first buffer, all in ms after touch-down. The page reports its own
  steps with Date.now(). "first audio" is the first buffer less its 4,096
  samples.
- A warm Hex session (Keep mic warm) start logs when Hex's recorder ran
  (the snapshot's recordingStartedAt), when the command was sent and when
  the keyboard saw it, from touch-down.
No behaviour changes.

Measured (anomastudio, iPhone 13 simulator, iOS 27.2, Release, Hex keyboard
in Messages, AXe taps of 100 ms and holds of 1.5 s; median of 5 tap and 3
hold runs, first dictation in a fresh keyboard process, then a second):
  tap, first dictation   862 ms (849-961)
  tap, second            154 ms (150-157)
  hold, first           1160 ms (1143-1161)
  hold, second           374 ms (373-377)
In a first dictation the web view's page takes 620-690 ms to load and
getUserMedia ~50 ms; a tap starts ~150 ms after touch-down (the lift) and a
hold ~370 ms (the 350 ms hold timer).

Verified: Release build for the simulator; the log lines above come from it.

* iOS keyboard: load the capture page when the keyboard opens, not on the Hex key

The first in-keyboard dictation after the keyboard opened waited 620-690 ms
for its capture web view's page to load before getUserMedia could even be
asked, so the first words were lost.

What changed
- KeyboardLocalDictation.prepare(in:) makes the capture web view and loads
  its page ahead of time. It asks for nothing else: no getUserMedia, no
  audio context, no audio session change, so the microphone stays closed
  and no orange dot shows until a dictation starts. It is skipped below the
  32 MB a first dictation needs (#2045's guard; that dictation opens Hex
  instead) and when neither the keyboard nor Hex has the microphone allowed.
- KeyboardViewController calls it a main-queue turn after viewDidAppear (so
  the keyboard's first frame never waits for it), only with Full Access, with
  in-keyboard dictation available and no warm Hex session (which takes the
  Hex key instead).
- A capture page whose content process ends while nothing records is now
  dropped quietly and made again by the next start. Before, the last
  dictation's handler still ran and showed a microphone error while idle;
  a prepared page lives the whole keyboard session, so this matters now.
  A recording that loses its page still fails as before.
- The probe log notes "capture prepared" (the main-thread time to make the
  web view) and "capture page loaded", with memory.

Measured (anomastudio, iPhone 13 simulator, iOS 27.2, Release, Hex keyboard
in Messages, 100 ms AXe taps, 3 runs, touch-down to first audio):
  first dictation   862 ms (849-961) before -> 282 ms (262-309)
  second dictation  154 ms (150-157) before -> 144 ms (144-148)
Memory (phys_footprint, simulator, no GPU memory counted):
  idle 3 s after the keyboard shows   27.4-27.6 MB -> 31.8-32.0 MB
  lifetime peak by the first audio    40.2-40.8 MB -> 40.7-41.2 MB
The page load itself peaks at 39.0-40.7 MB while idle. Making the web view
takes 46-112 ms of the main thread once per keyboard, right after it shows.

Verified: Release simulator build and the runs above; the probe log shows
no getUserMedia or capture start until the Hex key is pressed.

* iOS keyboard: start in-keyboard dictation on the Hex key's touch-down

A tap only started capture when the finger lifted (~100-150 ms) and push to
talk only after the 0.35 s hold timer, so the first words were lost even
with the capture page ready.

What changed
- The full keyboard's Hex key reports touch-down (onPress) and a press that
  becomes a slide to the style menu or is cancelled by the system before it
  is a tap or a hold (onPressAbandoned; HexKeyGesture.cancel() now returns
  .abandon for a pending press, .ignored once the hold fired).
- KeyboardViewController arms in-keyboard dictation at touch-down, with the
  same checks the Hex key uses to pick it (Full Access, no warm session,
  in-keyboard dictation available) and only while idle or failed.
- KeyboardLocalDictation.arm opens the microphone at once in a new .armed
  phase that the UI doesn't see (no snapshot). start() keeps it as the
  dictation (a tap's lift or the hold), so tap and push to talk behave as
  before, only listening from touch-down. discard() stops it, deletes its
  audio and transcribes nothing: on the menu, a cancelled touch, the
  keyboard hiding, a warm session taking over, or 3 s without a tap or hold.
  A failure while armed is shown only if the touch is kept.
- The capture page's hexStart now notices a hexStop that came while it
  awaited getUserMedia or the audio context (a generation count) and
  releases what it opened instead of going on; before, a stop during
  getUserMedia left the microphone open until Swift stopped it again on
  "started". A page that is idle after cancel() or discard() keeps
  listening for its process ending, and closes a stray "started".
- README: listening from touch-down, the dot during a slide, and what only
  an iPhone can measure.

Measured (anomastudio, iPhone 13 simulator, iOS 27.2, Release, Hex keyboard
in Messages, 100 ms AXe taps and 1.5 s holds; touch-down to first audio,
median and range; "before" is a8f9b707 with only the timing log):
                       before                prepare + touch-down
  tap, first          862 (849-961)          227 (146-401)
  tap, second         154 (150-157)           15 (10-18)
  hold, first        1160 (1143-1161)        322 (157-354)
  hold, second        374 (373-377)           17 (12-20)
What is left on a first dictation is WebKit's: the page's process is
suspended after its load (WebKit drops its assertion) and resuming it to
run hexStart took 0-240 ms in the simulator; a tap's recording strip also
builds its Metal scope on the main thread while WebKit waits for it.
Memory (phys_footprint, simulator, no GPU memory): idle 27.4-27.6 MB before,
31.7-32.2 MB after; lifetime peak by the first dictation 40.2-40.8 MB
before, 39.0-42.0 MB after (the page load's own peak is now at keyboard
open).

Verified live in Messages: WebKit's CoreAudioCaptureSource::start and
captureStateChanged 0 -> 2048 (what drives the orange dot) appear only
after touch-down, never when the page loads; a slide right after
touch-down logs "discarded after 118-149 ms", the capture source ends 144 ms
after it started, and nothing is transcribed; a tap is kept at ~140 ms and
Done/cancel work; a hold is kept at ~363 ms and the release stops it
(frames written, transcription attempted). The simulator shows no orange
dot even while recording, and a Home press reaches SpringBoard after the
hold fires, so the system-cancelled touch is covered by the new
HexKeyControl test rather than live.
2026-11-20 20:04:35 +00:00

171 lines
7.4 KiB
Swift

import CoreGraphics
import UIKit
import XCTest
@testable import HEX
final class HexKeyGestureTests: XCTestCase {
func testTapDictates() {
var gesture = HexKeyGesture()
gesture.touchDown(at: .zero)
XCTAssertEqual(gesture.touchMoved(to: CGPoint(x: 3, y: 2)), .ignored, "a jitter is still a tap")
XCTAssertEqual(gesture.touchUp(), .tap)
XCTAssertEqual(gesture.holdElapsed(), .ignored, "a timer left over from the tap")
XCTAssertEqual(gesture.state, .idle)
}
func testStillHoldFiresOnceAndReleaseFinishes() {
var gesture = HexKeyGesture()
gesture.touchDown(at: .zero)
XCTAssertEqual(gesture.holdElapsed(), .hold)
XCTAssertEqual(gesture.holdElapsed(), .ignored)
XCTAssertEqual(gesture.touchUp(), .release, "push to talk: lifting finishes")
XCTAssertEqual(gesture.touchUp(), .ignored)
}
func testMoveBeforeHoldOpensMenu() {
var gesture = HexKeyGesture()
gesture.touchDown(at: CGPoint(x: 20, y: 20))
XCTAssertEqual(gesture.touchMoved(to: CGPoint(x: 20, y: 9)), .openMenu)
XCTAssertEqual(gesture.holdElapsed(), .ignored, "the menu won, no dictation")
XCTAssertEqual(gesture.touchMoved(to: CGPoint(x: 0, y: -40)), .dragMenu)
XCTAssertEqual(gesture.touchUp(), .releaseMenu)
XCTAssertEqual(gesture.state, .idle)
}
func testMoveAfterHoldDoesNothing() {
var gesture = HexKeyGesture()
gesture.touchDown(at: .zero)
XCTAssertEqual(gesture.holdElapsed(), .hold)
XCTAssertEqual(gesture.touchMoved(to: CGPoint(x: 0, y: -80)), .ignored, "no menu once dictating")
XCTAssertEqual(gesture.touchUp(), .release)
}
func testCancelResets() {
var gesture = HexKeyGesture()
gesture.touchDown(at: .zero)
XCTAssertEqual(gesture.cancel(), .abandon, "a press that was neither tap nor hold: drop its capture")
XCTAssertEqual(gesture.state, .idle)
XCTAssertEqual(gesture.holdElapsed(), .ignored)
XCTAssertEqual(gesture.touchMoved(to: CGPoint(x: 50, y: 0)), .ignored)
}
func testCancelAfterHoldKeepsDictating() {
var gesture = HexKeyGesture()
gesture.touchDown(at: .zero)
XCTAssertEqual(gesture.holdElapsed(), .hold)
XCTAssertEqual(gesture.cancel(), .ignored, "the hold already dictates; Done finishes it")
XCTAssertEqual(gesture.cancel(), .ignored)
}
/// In-keyboard dictation listens from touch-down: the key reports the press at once, and
/// abandons it only when the touch is cancelled before it is a tap or a hold.
@MainActor
func testHexKeyReportsThePressAndAbandonsOnlyACancelledOne() {
let key = HexKeyControl(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
var presses = 0, abandoned = 0, dictations = 0
key.onPress = { _ in presses += 1 }
key.onPressAbandoned = { abandoned += 1 }
key.onHold = { dictations += 1 }
_ = key.beginTracking(UITouch(), with: nil)
XCTAssertEqual(presses, 1, "touch-down, before the lift")
XCTAssertEqual(dictations, 0)
key.endTracking(UITouch(), with: nil)
XCTAssertEqual(dictations, 1, "a tap keeps the capture")
XCTAssertEqual(abandoned, 0)
_ = key.beginTracking(UITouch(), with: nil)
key.cancelTracking(with: nil)
XCTAssertEqual(presses, 2)
XCTAssertEqual(abandoned, 1, "the system took the touch: drop it")
XCTAssertEqual(dictations, 1)
}
}
/// Translate what I say's switch where you dictate: "Paste in English" or as spoken, in the
/// full keyboard's Hex key menu and the dictation bar, remembered for the next dictations.
@MainActor
final class TranslationPasteSwitchTests: 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 testTheChoiceNamesBothLanguagesAndShowsOnlyWhileTranslating() {
let settings = DictationTranslationSettings(defaults: defaults)
XCTAssertNil(settings.pasteChoice(source: "es-MX"), "off: no switch")
settings.isEnabled = true
settings.targetLanguage = "en"
let choice = settings.pasteChoice(source: "es-MX")
XCTAssertEqual(choice?.translatedTitle, "Paste in English")
XCTAssertEqual(choice?.spokenTitle, "Paste in Spanish")
XCTAssertNil(settings.pasteChoice(source: "en-GB"), "dictating in the target: nothing to choose")
XCTAssertEqual(settings.pasteChoice(source: nil)?.spokenTitle, "Paste as spoken")
settings.targetLanguage = "nb"
XCTAssertEqual(settings.pasteChoice(source: "de-DE")?.translatedTitle, "Paste in Norwegian")
}
func testTheLastChoiceIsRememberedAndAsSpokenSkipsTranslation() async {
let settings = DictationTranslationSettings(defaults: defaults)
settings.isEnabled = true
settings.targetLanguage = "en"
XCTAssertTrue(settings.pastesTranslation, "translated until you pick otherwise")
settings.pastesTranslation = false
XCTAssertFalse(DictationTranslationSettings(defaults: defaults).pastesTranslation)
let translated = await DictationTranslator.translateIfEnabled(
"Nos vemos mañana.",
source: Locale.Language(identifier: "es-ES"),
settings: settings
)
XCTAssertNil(translated, "as spoken pastes the transcript itself")
}
func testTheKeyboardShowsWhereDictationsGo() {
let model = KeyboardViewModel()
model.dictationLanguage = "es-ES"
model.languageChoices = ["es-ES", "en-US"]
XCTAssertNil(model.pasteChoice)
XCTAssertEqual(model.languageSummary, "Español")
model.translationTarget = "en"
XCTAssertEqual(model.pasteChoice?.translatedTitle, "Paste in English")
XCTAssertEqual(model.languageSummary, "Español → English")
model.pastesTranslation = false
XCTAssertEqual(model.languageSummary, "Español", "as spoken")
model.hasFullAccess = false
XCTAssertNil(model.pasteChoice, "no Full Access, no translation")
}
func testTheHexKeyMenuOffersBothAndReportsThePick() {
let menu = HexStyleMenuView(frame: CGRect(x: 0, y: 0, width: 400, height: 300))
menu.languageChoices = ["es-ES", "en-US"]
menu.dictationLanguage = "es-ES"
XCTAssertFalse(labels(in: menu).contains { $0.hasPrefix("Paste") }, "no rows while translation is off")
menu.pasteChoice = TranslationPasteChoice(target: "en", source: "es-ES")
menu.pastesTranslation = false
var picked: Bool?
menu.onPasteTranslation = { picked = $0 }
let rows = controls(in: menu).filter { $0.accessibilityLabel?.hasPrefix("Paste") == true }
XCTAssertEqual(rows.map(\.accessibilityLabel), ["Paste in English", "Paste in Spanish"])
XCTAssertEqual(rows.map { $0.accessibilityTraits.contains(.selected) }, [false, true])
rows[0].sendActions(for: .touchUpInside)
XCTAssertEqual(picked, true)
}
private func controls(in view: UIView) -> [UIControl] {
view.subviews.flatMap { ($0 as? UIControl).map { [$0] } ?? [] + controls(in: $0) }
}
private func labels(in view: UIView) -> [String] {
controls(in: view).compactMap(\.accessibilityLabel)
}
}