From c6773572baef46b3778531a7b0dd71d1104bd4c9 Mon Sep 17 00:00:00 2001 From: MarcusJRLee <7527115+MarcusJRLee@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:51:25 -0500 Subject: [PATCH] Dictation: land the first press in Chromium web fields Brave builds a page's accessibility tree only after an application-level request, so the first press after it started or dropped its tree found no field, accepted the page's web area and typed into the body, or tripped a caret guard; the next press worked. Capture now wakes the tree with one app-role read on its first settling read and re-reads for up to 500 ms; web targets must expose settable selected text; and web carets are revalidated by AXSelectedTextMarkerRange, because Gemini's numeric offset flips 10<->38 while the caret never moves. Adds the --verify-focused-text-delivery diagnostic and the opt-in scripts/check_web_text_delivery.sh cold-browser first-press check (~1.5 s). Co-Authored-By: Claude Opus 5.5 --- .claude/skills/verify/SKILL.md | 1 + .mjrlee_repo_setup/test_ownership.toml | 9 + .../application_entry.swift | 55 ++++- .../focused_text_delivery_self_check.swift | 197 ++++++++++++++++ .../focused_text_target.swift | 218 ++++++++++++++---- .../transcript_writer.swift | 30 ++- .../focused_text_target_tests.swift | 104 +++++++-- .../terminal_text_delivery_tests.swift | 59 ++++- docs/CONTRIBUTING.md | 7 + docs/architecture.md | 3 +- docs/decisions/macos_text_delivery.md | 33 ++- docs/voice_cujs.md | 2 +- scripts/check_web_text_delivery.sh | 104 +++++++++ scripts/fixtures/web_text_delivery.html | 24 ++ 14 files changed, 759 insertions(+), 87 deletions(-) create mode 100644 Sources/HardwareControllerMac/focused_text_delivery_self_check.swift create mode 100755 scripts/check_web_text_delivery.sh create mode 100644 scripts/fixtures/web_text_delivery.html diff --git a/.claude/skills/verify/SKILL.md b/.claude/skills/verify/SKILL.md index bebc339..79e03dd 100644 --- a/.claude/skills/verify/SKILL.md +++ b/.claude/skills/verify/SKILL.md @@ -31,6 +31,7 @@ Evidence from a stale bundle is not evidence: rebuild before driving. | Launch smoke | `scripts/smoke_app.sh "dist/Hardware Controller.app" --demo` | | Installed signed app | `scripts/install_app.sh` (verifies, installs, launches, smokes, checks speech) | | Installed speech service | `scripts/check_speech_engine.sh` (load, decode, IPC, crash, recover) | +| Web text delivery | `scripts/check_web_text_delivery.sh` (first press into a fresh Chromium page; focuses a throwaway window) | | iOS simulator | `scripts/check_ios.sh`, then the simulator tools for manual paths | Demo flags (combine freely): diff --git a/.mjrlee_repo_setup/test_ownership.toml b/.mjrlee_repo_setup/test_ownership.toml index 66dd8cf..fb3c4a2 100644 --- a/.mjrlee_repo_setup/test_ownership.toml +++ b/.mjrlee_repo_setup/test_ownership.toml @@ -231,6 +231,10 @@ tests = ["Tests/HardwareControllerMacTests/transcribe_cpp_speech_engine_test.swi source = "Sources/HardwareControllerMac/speech_engine_self_check.swift" tests = ["Tests/HardwareControllerMacTests/transcribe_cpp_speech_engine_test.swift"] +[[owner]] +source = "Sources/HardwareControllerMac/focused_text_delivery_self_check.swift" +tests = ["Tests/HardwareControllerMacTests/focused_text_target_tests.swift"] + [[owner]] source = "Sources/hardware_controller_asr_service/main.swift" tests = ["Tests/hardware_controller_asr_service_kit_tests/asr_service_core_test.swift"] @@ -323,6 +327,11 @@ path = "scripts/check_speech_engine.sh" kind = "thin wrapper" reason = "Runs the installed app's speech self-check, which is the test." +[[exempt]] +path = "scripts/check_web_text_delivery.sh" +kind = "thin wrapper" +reason = "Runs the installed app's web text delivery self-check, which is the test." + [[exempt]] path = "scripts/build_app.sh" kind = "thin wrapper" diff --git a/Sources/HardwareControllerApp/application_entry.swift b/Sources/HardwareControllerApp/application_entry.swift index a30793b..c7bc639 100644 --- a/Sources/HardwareControllerApp/application_entry.swift +++ b/Sources/HardwareControllerApp/application_entry.swift @@ -5,24 +5,57 @@ import HardwareControllerMac /// /// `--verify-speech-engine PACKAGE AUDIO` must run from the installed bundle, /// because launchd resolves the XPC service only inside its containing app. +/// `--verify-focused-text-delivery PID MARKER` must be launched by +/// LaunchServices, because only then does the bundle's own Accessibility +/// grant apply. @main enum ApplicationEntry { static func main() { let arguments = CommandLine.arguments - guard let flag = arguments.firstIndex(of: "--verify-speech-engine") else { - HardwareControllerApp.main() - return + if let flag = arguments.firstIndex(of: "--verify-speech-engine") { + guard arguments.count > flag + 2 else { + usage("--verify-speech-engine PACKAGE AUDIO") + } + let package = URL(filePath: arguments[flag + 1], directoryHint: .isDirectory) + let audio = URL(filePath: arguments[flag + 2]) + runDiagnostic { + let report = await SpeechEngineSelfCheck.run(packageURL: package, audioURL: audio) + return (report.lines, report.passed) + } } - guard arguments.count > flag + 2 else { - FileHandle.standardError.write(Data("Usage: --verify-speech-engine PACKAGE AUDIO\n".utf8)) - exit(2) + if let flag = arguments.firstIndex(of: "--verify-focused-text-delivery") { + guard + arguments.count > flag + 2, + let target = pid_t(arguments[flag + 1]), + target > 0, + !arguments[flag + 2].isEmpty + else { + usage("--verify-focused-text-delivery PID MARKER") + } + let marker = arguments[flag + 2] + runDiagnostic { + let report = await FocusedTextDeliverySelfCheck.run( + targetProcessIdentifier: target, + marker: marker + ) + return (report.lines, report.passed) + } } - let package = URL(filePath: arguments[flag + 1], directoryHint: .isDirectory) - let audio = URL(filePath: arguments[flag + 2]) + HardwareControllerApp.main() + } + + private static func usage(_ synopsis: String) -> Never { + FileHandle.standardError.write(Data("Usage: \(synopsis)\n".utf8)) + exit(2) + } + + private static func runDiagnostic( + _ body: @escaping @Sendable () async -> (lines: [String], passed: Bool) + ) -> Never { Task { - let report = await SpeechEngineSelfCheck.run(packageURL: package, audioURL: audio) - print(report.lines.joined(separator: "\n")) - exit(report.passed ? 0 : 1) + let result = await body() + print(result.lines.joined(separator: "\n")) + exit(result.passed ? 0 : 1) } dispatchMain() } diff --git a/Sources/HardwareControllerMac/focused_text_delivery_self_check.swift b/Sources/HardwareControllerMac/focused_text_delivery_self_check.swift new file mode 100644 index 0000000..fa9a623 --- /dev/null +++ b/Sources/HardwareControllerMac/focused_text_delivery_self_check.swift @@ -0,0 +1,197 @@ +import AppKit +@preconcurrency import ApplicationServices +import Foundation +import HardwareControllerCore + +/// Proves Dictation delivery into the focused text field of one app. +/// +/// `Hardware Controller --verify-focused-text-delivery PID MARKER` waits until +/// PID owns the frontmost window, captures its focused field with the +/// production targeter, delivers MARKER once through the production writer +/// after a press-length hold, and reads the field back. It must be launched +/// by LaunchServices (`open -n -g`) so the app's own Accessibility grant +/// applies. Launching can still take keyboard focus from the target, so the +/// caller activates PID after launch and this check waits for it using +/// window-server state alone, never Accessibility, which would wake the +/// target's accessibility tree before the capture under test. +public enum FocusedTextDeliverySelfCheck { + public struct Report: Sendable { + public var lines: [String] = [] + public var passed = true + + mutating func record(_ line: String, passed: Bool = true) { + lines.append("\(passed ? "PASS" : "FAIL") \(line)") + self.passed = self.passed && passed + } + } + + public static func run( + targetProcessIdentifier: pid_t, + marker: String, + activationTimeout: Duration = .seconds(10), + hold: Duration = .seconds(1), + readBackTimeout: Duration = .seconds(2) + ) async -> Report { + var report = Report() + guard AccessibilityPermission.isTrusted else { + report.record("accessibility not trusted; launch with open -n", passed: false) + return report + } + let activationDeadline = ContinuousClock.now + activationTimeout + while frontmostWindowOwner() != targetProcessIdentifier { + guard ContinuousClock.now < activationDeadline else { + report.record( + "activation: pid \(targetProcessIdentifier) never owned the frontmost window", + passed: false) + return report + } + try? await Task.sleep(for: .milliseconds(20)) + } + + let targeter = AccessibilityFocusedTextTargeting() + let start = ContinuousClock.now + let target: FocusedTextTarget + do { + target = try targeter.capture().guardedDeliveryCopy() + } catch { + report.record( + "capture: \(error) ms=\(milliseconds(since: start)) \(describeFocus())", + passed: false + ) + return report + } + report.record( + "capture ms=\(milliseconds(since: start)) route=\(route(of: target.deliveryCapability)) " + + "role=\(target.role ?? "none")" + ) + + // A real press delivers only after speech ends, so ownership must survive + // the gap, including any accessibility tree the first capture woke up. + try? await Task.sleep(for: hold) + do { + try SafeTranscriptWriter( + targeter: targeter, + inserter: AdaptiveFocusedTextInserter() + ).insert(marker, into: target) + } catch { + let current = AdaptiveFocusedTextInserter().selectedRange(in: target) + report.record( + "insert: \(error) captured=\(describe(target.selectedRange)) current=\(describe(current))", + passed: false + ) + return report + } + + // Buffered events reach the field asynchronously, so poll the value. + let deadline = ContinuousClock.now + readBackTimeout + while ContinuousClock.now < deadline { + if value(of: target.element)?.contains(marker) == true { + report.record("delivered ms=\(milliseconds(since: start))") + return report + } + try? await Task.sleep(for: .milliseconds(20)) + } + let ownership = targeter.ownershipFailure(for: target).map { "\($0)" } ?? "intact" + report.record( + "delivered: marker absent from the field; ownership=\(ownership)", + passed: false + ) + return report + } + + /// Reads the owner of the topmost normal window from the window server. + private static func frontmostWindowOwner() -> pid_t? { + let windows = + CGWindowListCopyWindowInfo( + [.optionOnScreenOnly, .excludeDesktopElements], + kCGNullWindowID + ) as? [[String: Any]] ?? [] + return windows.first { ($0[kCGWindowLayer as String] as? Int) == 0 }?[ + kCGWindowOwnerPID as String + ] as? pid_t + } + + /// Names what capture saw, without reading any field text. + private static func describeFocus() -> String { + guard let front = NSWorkspace.shared.frontmostApplication else { + return "frontmost=none" + } + let frontmost = "frontmost=\(front.bundleIdentifier ?? "unknown")[\(front.processIdentifier)]" + let application = AXUIElementCreateApplication(front.processIdentifier) + var window: CFTypeRef? + let windowResult = AXUIElementCopyAttributeValue( + application, kAXFocusedWindowAttribute as CFString, &window) + var focusedApplication: CFTypeRef? + AXUIElementCopyAttributeValue( + AXUIElementCreateSystemWide(), kAXFocusedApplicationAttribute as CFString, &focusedApplication + ) + var keyboardPID: pid_t = 0 + if let focusedApplication, CFGetTypeID(focusedApplication) == AXUIElementGetTypeID() { + AXUIElementGetPid(unsafeDowncast(focusedApplication, to: AXUIElement.self), &keyboardPID) + } + let prefix = frontmost + " focusedWindow=\(windowResult.rawValue) keyboardApp=\(keyboardPID)" + var value: CFTypeRef? + let focusedResult = AXUIElementCopyAttributeValue( + application, + kAXFocusedUIElementAttribute as CFString, + &value + ) + guard + focusedResult == .success, + let value, + CFGetTypeID(value) == AXUIElementGetTypeID() + else { + return "\(prefix) focused=none(\(focusedResult.rawValue))" + } + let element = unsafeDowncast(value, to: AXUIElement.self) + var role: CFTypeRef? + AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &role) + var settable = DarwinBoolean(false) + let settableResult = AXUIElementIsAttributeSettable( + element, + kAXSelectedTextAttribute as CFString, + &settable + ) + return "\(prefix) focused=\((role as? String) ?? "unknown") " + + "selectedTextSettable=\(settableResult == .success && settable.boolValue)" + } + + private static func describe(_ range: FocusedTextRange?) -> String { + range.map { "\($0.location)+\($0.length)" } ?? "none" + } + + private static func route( + of capability: FocusedTextDeliveryCapability + ) -> String { + switch capability { + case .finalOnly: + "accessibility" + case .liveComposition: + "live" + case .bufferedEvent(_, .capturedProcess): + "terminal" + case .bufferedEvent(_, .focusedForeground): + "web" + } + } + + private static func value(of element: AXUIElement) -> String? { + var value: CFTypeRef? + guard + AXUIElementCopyAttributeValue( + element, + kAXValueAttribute as CFString, + &value + ) == .success + else { + return nil + } + return value as? String + } + + private static func milliseconds(since start: ContinuousClock.Instant) -> Int { + let elapsed = ContinuousClock.now - start + return Int(elapsed.components.seconds * 1000) + + Int(elapsed.components.attoseconds / 1_000_000_000_000_000) + } +} diff --git a/Sources/HardwareControllerMac/focused_text_target.swift b/Sources/HardwareControllerMac/focused_text_target.swift index 75a247f..0fdb527 100644 --- a/Sources/HardwareControllerMac/focused_text_target.swift +++ b/Sources/HardwareControllerMac/focused_text_target.swift @@ -13,6 +13,28 @@ public struct FocusedTextRange: Equatable, Sendable { } } +/// An opaque caret position from `AXSelectedTextMarkerRange`. +/// +/// Web engines number a caret by text offsets that also count text around +/// the field, such as a placeholder, so an empty Gemini prompt reports 10 +/// and then 38 while its caret never moves. Text markers name the caret's +/// node and offset instead; they stay equal across those page changes and +/// change when the caret moves. Equality is `CFEqual`. +public struct AccessibilityTextMarker: Equatable, @unchecked Sendable { + let value: CFTypeRef + + init(_ value: CFTypeRef) { + self.value = value + } + + public static func == ( + lhs: AccessibilityTextMarker, + rhs: AccessibilityTextMarker + ) -> Bool { + CFEqual(lhs.value, rhs.value) + } +} + public enum BufferedTextEventDestination: Equatable, Sendable @@ -166,6 +188,9 @@ public final class FocusedTextTarget: public let supportsMultilineText: Bool public let selectedRange: FocusedTextRange? public let deliveryCapability: FocusedTextDeliveryCapability + /// The caret as a text marker, when the target exposes one; delivery + /// revalidates it in place of the numeric anchor. + let caretMarker: AccessibilityTextMarker? let guardsCapturedCaret: Bool let element: AXUIElement @@ -179,6 +204,7 @@ public final class FocusedTextTarget: selectedRange: FocusedTextRange? = nil, deliveryCapability: FocusedTextDeliveryCapability = .finalOnly, + caretMarker: AccessibilityTextMarker? = nil, guardsCapturedCaret: Bool = false ) { self.element = element @@ -189,6 +215,7 @@ public final class FocusedTextTarget: self.supportsMultilineText = supportsMultilineText self.selectedRange = selectedRange self.deliveryCapability = deliveryCapability + self.caretMarker = caretMarker self.guardsCapturedCaret = guardsCapturedCaret } @@ -231,6 +258,7 @@ public final class FocusedTextTarget: supportsMultilineText: supportsMultilineText, selectedRange: selectedRange, deliveryCapability: deliveryCapability, + caretMarker: caretMarker, guardsCapturedCaret: true ) } @@ -252,17 +280,99 @@ extension FocusedTextTargeting { } } +/// One read of the focused element during capture. +enum FocusedTextCaptureAttempt { + case captured(Target) + /// No editable field is exposed yet; a later read may find one. + case settling +} + +/// Wakes on-demand page accessibility, then bounds the wait for an editor. +/// +/// Chromium-family browsers build a page's accessibility tree only after an +/// application-level request and expose it asynchronously. Until then the +/// app reports no focus, a bare group, or the page's web area, so the first +/// press after the browser started, or after it dropped an idle tree, found +/// no field while the next press worked. The first settling read therefore +/// calls `wake` once, then capture re-reads until an editor appears or +/// `timeout` passes. Definitive failures, such as a secure field or an +/// existing selection, still throw at once. +struct FocusedTextCaptureSettling { + static let standard = FocusedTextCaptureSettling( + timeout: .milliseconds(500), + pollInterval: .milliseconds(10) + ) + + let timeout: Duration + let pollInterval: Duration + + func capture( + now: () -> ContinuousClock.Instant = { ContinuousClock.now }, + sleep: (Duration) -> Void = { Thread.sleep(forTimeInterval: $0.seconds) }, + wake: () -> Void, + attempt: () throws -> FocusedTextCaptureAttempt + ) throws -> Target { + let deadline = now() + timeout + var hasWoken = false + while true { + if case .captured(let target) = try attempt() { + return target + } + if !hasWoken { + hasWoken = true + wake() + continue + } + guard now() < deadline else { + throw TranscriptionFailure.noFocusedTextField + } + sleep(pollInterval) + } + } +} + +extension Duration { + fileprivate var seconds: TimeInterval { + TimeInterval(components.seconds) + + TimeInterval(components.attoseconds) / 1e18 + } +} + public struct AccessibilityFocusedTextTargeting: FocusedTextTargeting { public init() {} + /// Captures synchronously so commands queued behind a press still run in + /// order; the bounded settle wait is no longer than a slow Accessibility + /// call already is. public func capture() throws -> FocusedTextTarget { guard AccessibilityPermission.isTrusted else { throw TranscriptionFailure.noFocusedTextField } + return try FocusedTextCaptureSettling.standard.capture( + wake: wakeOnDemandAccessibility, + attempt: captureOnce + ) + } + + /// Asks the frontmost app for its role, the application-level request + /// that makes Chromium-family browsers build page accessibility; asking + /// for the focused element alone never does. Other apps answer it as a + /// plain read. + private func wakeOnDemandAccessibility() { + guard let application = NSWorkspace.shared.frontmostApplication else { + return + } + _ = attribute( + kAXRoleAttribute, + from: AXUIElementCreateApplication(application.processIdentifier) + ) + } + + private func captureOnce() throws -> FocusedTextCaptureAttempt { guard let element = focusedElement() else { - throw TranscriptionFailure.noFocusedTextField + return .settling } if attribute( kAXSubroleAttribute, @@ -302,16 +412,24 @@ public struct AccessibilityFocusedTextTargeting: contextLabels: context.labels, contextRoles: context.roles ) + let destination = FocusedTextDeliveryPolicy.bufferedEventDestination( + for: metadata + ) + // A terminal consumes events without exposing settable text. Everything + // else, including web content, must expose an editable selection: a web + // area or group without one is a page that has no editable focus yet. + guard + destination == .capturedProcess + || isSettable(kAXSelectedTextAttribute, on: element) + else { + return .settling + } let deliveryCapability: FocusedTextDeliveryCapability - if let destination = - FocusedTextDeliveryPolicy.bufferedEventDestination( - for: metadata - ) - { - guard - let range = selectedTextRange(from: element), - range.length == 0 - else { + if let destination { + guard let range = selectedTextRange(from: element) else { + return .settling + } + guard range.length == 0 else { throw TranscriptionFailure.noFocusedTextField } deliveryCapability = .bufferedEvent( @@ -319,17 +437,6 @@ public struct AccessibilityFocusedTextTargeting: destination: destination ) } else { - var isSettable = DarwinBoolean(false) - guard - AXUIElementIsAttributeSettable( - element, - kAXSelectedTextAttribute as CFString, - &isSettable - ) == .success, - isSettable.boolValue - else { - throw TranscriptionFailure.noFocusedTextField - } deliveryCapability = liveCompositionAnchor(from: element).map { FocusedTextDeliveryCapability @@ -337,20 +444,48 @@ public struct AccessibilityFocusedTextTargeting: } ?? .finalOnly } - return FocusedTextTarget( - element: element, - processIdentifier: processIdentifier, - applicationName: applicationName, - applicationBundleIdentifier: metadata.applicationBundleIdentifier, - role: metadata.role, - supportsMultilineText: - metadata.role == kAXTextAreaRole as String - && FocusedTextDeliveryPolicy.bufferedEventDestination( - for: metadata - ) == nil, - selectedRange: selectedTextRange(from: element), - deliveryCapability: deliveryCapability - ) + return .captured( + FocusedTextTarget( + element: element, + processIdentifier: processIdentifier, + applicationName: applicationName, + applicationBundleIdentifier: metadata.applicationBundleIdentifier, + role: metadata.role, + supportsMultilineText: + metadata.role == kAXTextAreaRole as String + && destination == nil, + selectedRange: selectedTextRange(from: element), + deliveryCapability: deliveryCapability, + caretMarker: destination == .focusedForeground + ? AccessibilityFocusedTextTargeting.caretMarker(of: element) : nil + )) + } + + static func caretMarker(of element: AXUIElement) -> AccessibilityTextMarker? { + var value: CFTypeRef? + guard + AXUIElementCopyAttributeValue( + element, + "AXSelectedTextMarkerRange" as CFString, + &value + ) == .success, + let value + else { + return nil + } + return AccessibilityTextMarker(value) + } + + private func isSettable( + _ attribute: String, + on element: AXUIElement + ) -> Bool { + var isSettable = DarwinBoolean(false) + return AXUIElementIsAttributeSettable( + element, + attribute as CFString, + &isSettable + ) == .success && isSettable.boolValue } public func isStillFocused( @@ -541,21 +676,12 @@ public struct AccessibilityFocusedTextTargeting: private func liveCompositionAnchor( from element: AXUIElement ) -> FocusedTextRange? { - var isSettable = DarwinBoolean(false) guard - AXUIElementIsAttributeSettable( - element, - kAXSelectedTextRangeAttribute as CFString, - &isSettable - ) == .success, - isSettable.boolValue + isSettable(kAXSelectedTextRangeAttribute, on: element), + let range = selectedTextRange(from: element) else { return nil } - - guard let range = selectedTextRange(from: element) else { - return nil - } guard range.length == 0 else { return nil } diff --git a/Sources/HardwareControllerMac/transcript_writer.swift b/Sources/HardwareControllerMac/transcript_writer.swift index 23817d8..17f94a5 100644 --- a/Sources/HardwareControllerMac/transcript_writer.swift +++ b/Sources/HardwareControllerMac/transcript_writer.swift @@ -17,9 +17,19 @@ public protocol FocusedTextInserting: Sendable { _ range: FocusedTextRange, in target: FocusedTextTarget ) -> Bool + + func caretMarker( + in target: FocusedTextTarget + ) -> AccessibilityTextMarker? } extension FocusedTextInserting { + public func caretMarker( + in target: FocusedTextTarget + ) -> AccessibilityTextMarker? { + nil + } + public func selectedRange( in target: FocusedTextTarget ) -> FocusedTextRange? { @@ -300,6 +310,18 @@ public struct AdaptiveFocusedTextInserter: ) -> Bool { accessibility.select(range, in: target) } + + public func caretMarker( + in target: FocusedTextTarget + ) -> AccessibilityTextMarker? { + let operation = { + AccessibilityFocusedTextTargeting.caretMarker(of: target.element) + } + guard target.processIdentifier == getpid(), !Thread.isMainThread else { + return operation() + } + return DispatchQueue.main.sync(execute: operation) + } } public protocol TranscriptWriting: Sendable { @@ -352,7 +374,13 @@ public struct SafeTranscriptWriter< target.deliveryCapability { try validateOwnership(of: target) - guard inserter.selectedRange(in: target) == anchor else { + let caretIsUnchanged = + if let marker = target.caretMarker { + inserter.caretMarker(in: target) == marker + } else { + inserter.selectedRange(in: target) == anchor + } + guard caretIsUnchanged else { throw TranscriptionFailure.caretChanged } guard inserter.insert(text, into: target) else { diff --git a/Tests/HardwareControllerMacTests/focused_text_target_tests.swift b/Tests/HardwareControllerMacTests/focused_text_target_tests.swift index 866f955..9a1d263 100644 --- a/Tests/HardwareControllerMacTests/focused_text_target_tests.swift +++ b/Tests/HardwareControllerMacTests/focused_text_target_tests.swift @@ -61,7 +61,8 @@ struct FocusedTextTargetTests { deliveryCapability: .bufferedEvent( anchor: anchor, destination: .focusedForeground - ) + ), + caretMarker: AccessibilityTextMarker("caret" as CFString) ) let guarded = try target.guardedDeliveryCopy() @@ -74,6 +75,7 @@ struct FocusedTextTargetTests { ) ) #expect(guarded.guardsCapturedCaret) + #expect(guarded.caretMarker == target.caretMarker) } @Test @@ -117,29 +119,73 @@ struct FocusedTextTargetTests { ) } - /// Exercises semantic web-target capture against a real focused field. - @Test( - .enabled( - if: - ProcessInfo.processInfo.environment[ - "HC_RUN_WEB_TARGET_INTEGRATION" - ] == "1" - ) - ) - func focusedWebContentUsesForegroundBufferedDelivery() - throws - { - let target = - try AccessibilityFocusedTextTargeting().capture() - guard - case .bufferedEvent(_, .focusedForeground) = - target.deliveryCapability - else { - Issue.record( - "The focused target was not editable web content." + @Test + func captureSettlingWakesOnceThenWaitsForAnEditableField() throws { + var clock = SettlingClock() + var reads = 0 + var wakes = 0 + let target = try FocusedTextCaptureSettling.standard.capture( + now: { clock.now }, + sleep: { clock.advance($0) }, + wake: { wakes += 1 }, + attempt: { () -> FocusedTextCaptureAttempt in + reads += 1 + return reads < 4 ? .settling : .captured(reads) + } + ) + + #expect(target == 4) + #expect(wakes == 1) + #expect(clock.slept == .milliseconds(20)) + } + + @Test + func captureSettlingNeverWakesAReadyField() throws { + var clock = SettlingClock() + var wakes = 0 + let target = try FocusedTextCaptureSettling.standard.capture( + now: { clock.now }, + sleep: { clock.advance($0) }, + wake: { wakes += 1 }, + attempt: { () -> FocusedTextCaptureAttempt in .captured(1) } + ) + + #expect(target == 1) + #expect(wakes == 0) + #expect(clock.slept == .zero) + } + + @Test + func captureSettlingFailsOnceTheBoundPasses() { + var clock = SettlingClock() + #expect(throws: TranscriptionFailure.noFocusedTextField) { + try FocusedTextCaptureSettling.standard.capture( + now: { clock.now }, + sleep: { clock.advance($0) }, + wake: {}, + attempt: { () -> FocusedTextCaptureAttempt in .settling } + ) + } + #expect(clock.slept == FocusedTextCaptureSettling.standard.timeout) + } + + @Test + func captureSettlingNeverRetriesADefinitiveFailure() { + var clock = SettlingClock() + var reads = 0 + #expect(throws: TranscriptionFailure.secureTextField) { + try FocusedTextCaptureSettling.standard.capture( + now: { clock.now }, + sleep: { clock.advance($0) }, + wake: {}, + attempt: { () throws -> FocusedTextCaptureAttempt in + reads += 1 + throw TranscriptionFailure.secureTextField + } ) - return } + #expect(reads == 1) + #expect(clock.slept == .zero) } @Test @@ -179,3 +225,17 @@ struct FocusedTextTargetTests { #expect(point == CGPoint(x: 122, y: 572)) } } + +/// A manual clock: only the settle loop's own sleeps move time forward. +private struct SettlingClock { + let start = ContinuousClock.now + var slept: Duration = .zero + + var now: ContinuousClock.Instant { + start + slept + } + + mutating func advance(_ duration: Duration) { + slept += duration + } +} diff --git a/Tests/HardwareControllerMacTests/terminal_text_delivery_tests.swift b/Tests/HardwareControllerMacTests/terminal_text_delivery_tests.swift index 51deba2..c56910b 100644 --- a/Tests/HardwareControllerMacTests/terminal_text_delivery_tests.swift +++ b/Tests/HardwareControllerMacTests/terminal_text_delivery_tests.swift @@ -215,6 +215,39 @@ struct TerminalTextDeliveryTests { #expect(inserter.inserted.isEmpty) } + /// A web caret is revalidated by text marker, because its numeric offset + /// also counts page text around the field. + @Test + func webWriterTrustsAnUnchangedMarkerOverAShiftedOffset() throws { + let inserter = TerminalRecordingInserter( + selectedRange: FocusedTextRange(location: 38, length: 0), + caretMarker: AccessibilityTextMarker("caret" as CFString) + ) + try SafeTranscriptWriter( + targeter: TerminalFocusTargeter(isFocused: true), + inserter: inserter + ).insert("hello", into: webTarget(marker: "caret")) + + #expect(inserter.inserted == ["hello"]) + } + + @Test + func webWriterRejectsAMovedMarkerOrAMissingOne() { + for current in [AccessibilityTextMarker("moved" as CFString), nil] { + let inserter = TerminalRecordingInserter( + selectedRange: FocusedTextRange(location: 10, length: 0), + caretMarker: current + ) + #expect(throws: TranscriptionFailure.caretChanged) { + try SafeTranscriptWriter( + targeter: TerminalFocusTargeter(isFocused: true), + inserter: inserter + ).insert("hello", into: webTarget(marker: "caret")) + } + #expect(inserter.inserted.isEmpty) + } + } + @Test func terminalWriterPostsFinalTextAsOneInsertion() throws { let inserter = TerminalRecordingInserter( @@ -269,6 +302,19 @@ struct TerminalTextDeliveryTests { ) } + private func webTarget(marker: String) -> FocusedTextTarget { + FocusedTextTarget( + element: AXUIElementCreateSystemWide(), + processIdentifier: 42, + applicationName: "Brave Browser", + deliveryCapability: .bufferedEvent( + anchor: FocusedTextRange(location: 10, length: 0), + destination: .focusedForeground + ), + caretMarker: AccessibilityTextMarker(marker as CFString) + ) + } + private func terminalTarget() -> FocusedTextTarget { FocusedTextTarget( element: AXUIElementCreateSystemWide(), @@ -340,10 +386,15 @@ private final class TerminalRecordingInserter: { private let lock = NSLock() private let range: FocusedTextRange + private let marker: AccessibilityTextMarker? private var storage: [String] = [] - init(selectedRange: FocusedTextRange) { + init( + selectedRange: FocusedTextRange, + caretMarker: AccessibilityTextMarker? = nil + ) { range = selectedRange + marker = caretMarker } var inserted: [String] { @@ -365,4 +416,10 @@ private final class TerminalRecordingInserter: ) -> FocusedTextRange? { range } + + func caretMarker( + in target: FocusedTextTarget + ) -> AccessibilityTextMarker? { + marker + } } diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 0a85161..da5ed4b 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -136,6 +136,13 @@ HC_RUN_IOS_ASR_PERFORMANCE=1 scripts/check_voice_asr_bridge.sh TEST_RUNNER_HC_RUN_KEYCHAIN_BENCHMARK=1 scripts/check_ios.sh ``` +First-press Dictation delivery into a Chromium web field (Brave, Chrome, +Chromium, or Edge; about 4 s; opens and focuses a throwaway browser window): + +```bash +scripts/check_web_text_delivery.sh +``` + Real speech through the macOS recognizer: ```bash diff --git a/docs/architecture.md b/docs/architecture.md index 51e980d..c0f8d7e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -70,7 +70,8 @@ Profile the runtime must adopt, or a typed `ProfileEditFailure`. The runtime saves atomically, installs the new resolver after cancelling active Actions, then publishes. Inactive edits never touch the resolver. -**Local Dictation.** Begin captures the target and starts on-device +**Local Dictation.** Begin captures the target, waking a browser's page +accessibility and waiting up to 500 ms for its editor, and starts on-device recognition. Stable Accessibility ranges get reversible live text; other fields get final text; web and terminal targets get one guarded payload. Finalization has a five-second watchdog. diff --git a/docs/decisions/macos_text_delivery.md b/docs/decisions/macos_text_delivery.md index cbdd36d..2013ad3 100644 --- a/docs/decisions/macos_text_delivery.md +++ b/docs/decisions/macos_text_delivery.md @@ -1,7 +1,7 @@ # macOS text delivery - **Status:** Accepted -- **Updated:** 2026-11-03 +- **Updated:** 2026-11-17 - **Replaces:** 0002, 0006, 0007, 0009, and the delivery part of 0005 ## Context @@ -18,7 +18,7 @@ clipboard on its own. | Stable readable and settable selection range | Live, in the field | Commit the session-owned span in place. | | Settable selected text, no stable range | Transcript HUD | `AXSelectedText` insertion of final text. | | Validated terminal (Terminal, Cursor's terminal) | Transcript HUD | One buffered Unicode event to the captured process. | -| Editable descendant of `AXWebArea` | Transcript HUD | One buffered Unicode event through `cghidEventTap`. | +| Editable (settable selected text) element in `AXWebArea` | Transcript HUD | One buffered Unicode event through `cghidEventTap`. | | Secure, unfocused, changed, or unknown | None | No automatic delivery; explicit copy recovery. | ## Decision @@ -31,8 +31,18 @@ clipboard on its own. - Classify in order: validated terminal, web content, then native Accessibility capability. Terminal means native Terminal with an empty readable range, or Cursor only when its focused element identifies a - terminal or shell. Web content means any editable descendant of the standard - `AXWebArea` role; never inspect browser, site, or field identity. + terminal or shell. Web content means an element with settable selected text + inside the standard `AXWebArea` role, including an editable web area itself; + never inspect browser, site, or field identity. A focused web area or group + without settable text is a page with no editable focus, never a target. +- Chromium-family browsers build page accessibility only after an + application-level request; asking for the focused element never triggers + it. Until then the first capture sees no focus, a bare group, or the web + area. On its first such read, capture asks the frontmost app for its role, + which wakes the tree, then re-reads every 10 ms for up to 500 ms before + failing with no text field. Secure fields and existing selections fail at + once. Capture stays synchronous so commands behind a press keep their + order. Brave rejects `AXManualAccessibility` and `AXEnhancedUserInterface`. **Live composition** @@ -48,6 +58,10 @@ clipboard on its own. - Terminal and web targets buffer until recognition finalizes, then revalidate the same app, element, and caret before posting one sanitized payload. + Web carets compare by `AXSelectedTextMarkerRange` when the target exposes + one: numeric offsets also count text around the field, so an empty Gemini + prompt flips between 10 and 38 while its caret never moves. Markers stay + equal across those flips and change when the caret moves. - Replace CR, LF, and tab with spaces and strip other controls. Never synthesize Return, Enter, modifiers, escape sequences, or deletion. - Never use Accessibility and event insertion in one session, never replay @@ -76,3 +90,14 @@ clipboard on its own. Cursor's zsh terminal at an unchanged caret without submitting. Browser, Cursor, Terminal, focus-change, and no-submission behavior stay release gates. +- Measured 2026-11-17 on Brave 1.99.55 (Chromium 157) against + gemini.google.com in a fresh profile with the editor focused. Before: the + first press failed in 3 of 4 trials (no text field, a changed caret, or + keystrokes sent to the page body from a web-area target) and the next + press worked. With the wake: capture took 32–50 ms and 5 of 6 first + presses landed with a 1 s hold; every miss was the 10↔38 offset flip, + which appears about 1 s after the wake. Marker revalidation is unit-tested; + a live Gemini run with it is still open. +- `scripts/check_web_text_delivery.sh` proves a cold first press on a local + Gemini-shaped page in about 1.5 s. It focuses a throwaway browser window, + so it is opt-in, not part of `scripts/install_app.sh`. diff --git a/docs/voice_cujs.md b/docs/voice_cujs.md index 67e831c..42f0deb 100644 --- a/docs/voice_cujs.md +++ b/docs/voice_cujs.md @@ -34,7 +34,7 @@ events. | M2 | Latch a long prompt | First key-down begins; hold finishes on release; double press latches and finishes once. | `voice_trigger_test`, `voice_keyboard_trigger_controller_test` | | M3 | Format for purpose | Five Styles from one Raw; validated list blocks; safe flattening; protected tokens kept. | `voice_formatted_document_builder_test`, `voice_formatted_text_renderer_test`, `voice_formatting_draft_normalizer_test`, `voice_casing_policy_test`, `voice_list_intent_test` | | M4 | Backtrack explicitly | Exact commands become replayable typed edits; near misses stay text. | `voice_spoken_edit_engine_test`, `voice_spoken_edit_replayer_test` | -| M5 | Keep target ownership | Captured route and empty caret revalidated; changes stop delivery with a typed reason. | `focused_text_target_tests`, `transcript_writer_tests`, `terminal_text_delivery_tests` | +| M5 | Keep target ownership | Captured route and empty caret revalidated (web carets by text marker); changes stop delivery with a typed reason; the first press into a browser whose page accessibility is asleep wakes it instead of failing. | `focused_text_target_tests`, `transcript_writer_tests`, `terminal_text_delivery_tests`, `scripts/check_web_text_delivery.sh` | | M6 | Browse and reuse History | Search every stage; corrections, reruns, and re-delivery append; Dictionary suggestions need confirmation. | `voice_history_service_test`, `voice_history_model_test`, `voice_history_redeliverer_test`, `voice_history_reformatter_test`, `voice_dictionary_suggestion_test` | | M7 | Bound storage | Age, bytes, count, low disk; transcripts kept; active, pinned, recovery audio protected. | `sqlite_voice_history_retention_store_test`, `voice_history_retention_planner_test`, `Tests/cuj/voice_retention_v1.json` | | M8 | Recover from a crash | Partial and orphan audio become Recovery sessions; corrupt rows isolated; corrupt DB preserved. | `voice_history_reconciler_test`, `voice_history_recovery_test` | diff --git a/scripts/check_web_text_delivery.sh b/scripts/check_web_text_delivery.sh new file mode 100755 index 0000000..915a29b --- /dev/null +++ b/scripts/check_web_text_delivery.sh @@ -0,0 +1,104 @@ +#!/bin/zsh + +# Proves first-attempt Dictation delivery into a Chromium web field +# (docs/decisions/macos_text_delivery.md). A throwaway browser profile starts +# with its accessibility tree off, which is the state that made the first +# pedal press after a quiet period fail on Gemini. The app's +# --verify-focused-text-delivery diagnostic then captures and fills the field +# once. Needs a signed app with Accessibility granted, so it runs on installs, +# not in CI. Without a Chromium browser it does nothing. +# Usage: scripts/check_web_text_delivery.sh [APP] +# HC_WEB_CHECK_BROWSER a Chromium-based .app to use instead of the first found. + +set -euo pipefail +zmodload zsh/datetime + +repo_root="$(cd "$(dirname "$0")/.." && pwd)" +app="${1:-/Applications/Hardware Controller.app}" +fixture="$repo_root/scripts/fixtures/web_text_delivery.html" + +check_fail() { + print -u2 "Web text delivery failed: $1" + exit 1 +} + +browser="${HC_WEB_CHECK_BROWSER:-}" +if [[ -z "$browser" ]]; then + for candidate in "Brave Browser" "Google Chrome" "Chromium" "Microsoft Edge"; do + if [[ -d "/Applications/$candidate.app" ]]; then + browser="/Applications/$candidate.app" + break + fi + done +fi +if [[ -z "$browser" ]]; then + print "Web text delivery skipped: no Chromium-based browser in /Applications." + exit 0 +fi +[[ -d "$app" ]] || check_fail "$app does not exist." + +profile="$(mktemp -d)" +output="$(mktemp)" +browser_pid="" +cleanup() { + [[ -n "$browser_pid" ]] && kill -TERM "$browser_pid" 2>/dev/null || true + for _ in {1..50}; do + [[ -n "$browser_pid" ]] && kill -0 "$browser_pid" 2>/dev/null || break + sleep 0.1 + done + [[ -n "$browser_pid" ]] && kill -KILL "$browser_pid" 2>/dev/null || true + rm -rf "$profile" "$output" +} +trap cleanup EXIT + +# The browser must be a separate instance, so the user's own windows and +# profile are never touched. +open -n -a "$browser" --args \ + --user-data-dir="$profile" \ + --no-first-run \ + --no-default-browser-check \ + --disable-extensions \ + --remote-debugging-port=0 \ + "file://$fixture" + +# Readiness comes from DevTools, never Accessibility, so the diagnostic's +# capture is the first accessibility client the page sees. +ready="" +for _ in {1..150}; do + [[ -n "$browser_pid" ]] \ + || browser_pid="$(pgrep -f -- "--user-data-dir=$profile" | head -1 || true)" + if [[ -n "$browser_pid" && -f "$profile/DevToolsActivePort" ]]; then + port="$(head -1 "$profile/DevToolsActivePort")" + if curl -sf --max-time 1 "http://127.0.0.1:$port/json/list" | grep -q '"title": *"ready"'; then + ready=1 + break + fi + fi + sleep 0.1 +done +[[ -n "$ready" ]] || check_fail "the fixture never finished loading." + +# Launching the diagnostic can take keyboard focus, and LaunchServices may +# front the user's own instance of the same browser, so keep activating this +# instance by pid (AppKit, no Accessibility) until the diagnostic exits. The +# diagnostic waits for this window before it captures. +activate_browser() { + osascript -l JavaScript -e 'ObjC.import("AppKit")' -e \ + "\$.NSRunningApplication.runningApplicationWithProcessIdentifier($browser_pid).activateWithOptions(1)" \ + >/dev/null +} +marker="hc-web-check-$RANDOM$RANDOM" +start=$EPOCHREALTIME +open -n -g -W --stdout "$output" --stderr "$output" "$app" \ + --args --verify-focused-text-delivery "$browser_pid" "$marker" & +diagnostic=$! +while kill -0 "$diagnostic" 2>/dev/null; do + activate_browser + sleep 0.2 +done +wait "$diagnostic" || true +elapsed_ms=$(( (EPOCHREALTIME - start) * 1000 )) +grep -v '^Unable to block' "$output" || true +grep -q '^FAIL' "$output" && check_fail "see the lines above." +grep -q '^PASS delivered' "$output" || check_fail "the diagnostic reported no delivery." +printf 'Web text delivery passed: %s in %.0f ms.\n' "${browser:t:r}" "$elapsed_ms" diff --git a/scripts/fixtures/web_text_delivery.html b/scripts/fixtures/web_text_delivery.html new file mode 100644 index 0000000..ed1dab1 --- /dev/null +++ b/scripts/fixtures/web_text_delivery.html @@ -0,0 +1,24 @@ + + + + +loading +


+ +