Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/skills/verify/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
9 changes: 9 additions & 0 deletions .mjrlee_repo_setup/test_ownership.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -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"
Expand Down
55 changes: 44 additions & 11 deletions Sources/HardwareControllerApp/application_entry.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
197 changes: 197 additions & 0 deletions Sources/HardwareControllerMac/focused_text_delivery_self_check.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading