From 3ff19e63b7d7975bd0ecbb21090665da37973977 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 10:46:28 +0100 Subject: [PATCH 1/4] refactor(ios-runner): drop the XCTest tap fallback on simulators A simulator tap is now only its touchscreen HID contact. A contact that cannot be prepared, or never goes down, throws RunnerGestureRefusedWithoutFallback: performSynthesizedGesture answers it as an UNSUPPORTED_OPERATION refusal with the HID reason and a hint, and no XCTest event record or XCUICoordinate tap runs in its place. Physical devices keep the XCTest record and its fallback. The unit tests stub RunnerSimulatorTouch preparation and the lit-panel probe's prepared touch instead of XCTest tap synthesis, and the tests that asserted an XCTest fallback on a simulator now assert the refusal. Co-Authored-By: Claude Opus 5.5 --- .../RunnerTests+Alert.swift | 2 + .../RunnerTests+Interaction.swift | 8 + ...RunnerTests+SynthesizedGesturePolicy.swift | 7 + .../RunnerTests+SynthesizedInteraction.swift | 49 +++--- .../UnitTests/RunnerRequestPanelTests.swift | 51 ++++-- .../RunnerTests+AlertObservationTests.swift | 165 ++++++++++-------- .../RunnerTests+CommandExecutionTests.swift | 47 ++--- .../RunnerTests+SequenceExecutionTests.swift | 42 +++-- ...nerTests+SynthesizedInteractionTests.swift | 55 +++--- ...nnerTests+SynthesizedTapContextTests.swift | 22 +++ .../0011-interaction-guarantee-contract.md | 7 +- 11 files changed, 267 insertions(+), 188 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift index cad0fd549af..e13e50bd794 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift @@ -232,6 +232,8 @@ extension RunnerTests { context: hostContext, deadline: deadline ) + } catch let refusal as RunnerGestureRefusedWithoutFallback { + attempt = .unsupported(message: refusal.message, hint: refusal.hint) } catch { activationError = error return diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift index 909c2a31d0b..385ef4326a0 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift @@ -20,6 +20,14 @@ struct RunnerGestureOutcomeUnknown: Error { let hint: String? } +/// A synthesized gesture that sent nothing and that no XCTest gesture may replace: on a simulator a +/// tap whose touchscreen HID contact cannot be sent. Thrown rather than returned so that no fallback +/// policy answers it; `performSynthesizedGesture` turns it into an `UNSUPPORTED_OPERATION` refusal. +struct RunnerGestureRefusedWithoutFallback: Error { + let message: String + let hint: String? +} + private struct RunnerUnsupportedOperationError: LocalizedError { let message: String diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift index b3cc74e555f..0e77ce99a0b 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift @@ -173,12 +173,19 @@ extension RunnerTests { ) throws -> SynthesizedGestureAttempt { var outcome: RunnerInteractionOutcome? let timing: (gestureStartUptimeMs: Double, gestureEndUptimeMs: Double) + let gestureStartUptimeMs = currentUptimeMs() do { timing = try measureGesture { outcome = try synthesize() } } catch let unknown as RunnerGestureOutcomeUnknown { // A gesture that may have run is never repeated through a fallback. logSynthesizedGesturePolicyDecision(kind: kind, context: context, fallbackAttempted: false) throw unknown + } catch let refusal as RunnerGestureRefusedWithoutFallback { + logSynthesizedGesturePolicyDecision(kind: kind, context: context, fallbackAttempted: false) + return .refused( + timing: (gestureStartUptimeMs, currentUptimeMs()), + refusal: .unsupported(message: refusal.message, hint: refusal.hint) + ) } guard let outcome else { logSynthesizedGesturePolicyDecision(kind: kind, context: context, fallbackAttempted: false) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift index 5ae2ceea9e2..7ac28467dac 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift @@ -105,15 +105,8 @@ extension RunnerTests { orientation: orientation ) #if targetEnvironment(simulator) - switch try simulatorHIDTap(app: app, point: point, resolvedWindow: resolvedWindow, deadline: deadline) { - case .performed: - return .performed - case .deadlineExceeded: - return nil - case .unavailable: - break - } -#endif + return try simulatorHIDTap(app: app, point: point, resolvedWindow: resolvedWindow, deadline: deadline) +#else var message: NSString? let status = RunnerSynthesizedGesture.synthesizeTap( withApplication: app, @@ -139,6 +132,7 @@ extension RunnerTests { hint: "Inspect the current app before deciding whether to act again." ) } +#endif #elseif os(tvOS) return .unsupported( message: "coordinate tap is not supported on tvOS; move focus with swipe or scroll, then select the focused element", @@ -610,36 +604,30 @@ extension RunnerTests { } #if targetEnvironment(simulator) - /// How a simulator HID tap ended. `.unavailable` sent nothing, so the XCTest synthesis may run. - enum SimulatorHIDTapResult { - case performed - case deadlineExceeded - case unavailable - } - /// Taps `point` (native portrait points) with one touchscreen HID contact from inside the - /// simulator. XCTest event synthesis spends about 280 ms per tap waiting on its own round trip; - /// this contact returns once the finger lifts. A contact that went down and then failed may have - /// reached the app, so it throws `RunnerGestureOutcomeUnknown` and nothing repeats it. + /// simulator, its only tap route. XCTest event synthesis spends about 280 ms per tap waiting on its + /// own round trip; this contact returns once the finger lifts. A contact that cannot be prepared, + /// or that never went down, sent nothing: it throws `RunnerGestureRefusedWithoutFallback`, because + /// that is a broken simulator runtime, which no XCTest gesture may hide. A contact that went down + /// and then failed may have reached the app, so it throws `RunnerGestureOutcomeUnknown` and nothing + /// repeats it. Nil: the deadline passed before the contact. @MainActor private func simulatorHIDTap( app: XCUIApplication, point: CGPoint, resolvedWindow: XCUIElement?, deadline: Date? - ) throws -> SimulatorHIDTapResult { + ) throws -> RunnerInteractionOutcome? { let startedAt = Date() var failure: NSString? guard let screenSize = simulatorTouchDisplayPortraitSize(), let touch = RunnerSimulatorTouch.prepare(application: app, resolvedWindow: resolvedWindow, failure: &failure) else { - NSLog( - "AGENT_DEVICE_RUNNER_SIMULATOR_HID_TAP outcome=unavailable reason=%@", - (failure as String?) ?? "display size unreadable" - ) - return .unavailable + let reason = (failure as String?) ?? "the display size could not be read" + NSLog("AGENT_DEVICE_RUNNER_SIMULATOR_HID_TAP outcome=unavailable reason=%@", reason) + throw Self.simulatorHIDTapRefusal(reason: reason) } - if let deadline, deadline.timeIntervalSinceNow <= 0 { return .deadlineExceeded } + if let deadline, deadline.timeIntervalSinceNow <= 0 { return nil } let preparedAt = Date() var touchDown: ObjCBool = false let message = touch.dispatchTap(at: point, screenSize: screenSize, touchDown: &touchDown) @@ -650,12 +638,19 @@ extension RunnerTests { Date().timeIntervalSince(preparedAt) * 1000 ) guard let message else { return .performed } - guard touchDown.boolValue else { return .unavailable } + guard touchDown.boolValue else { throw Self.simulatorHIDTapRefusal(reason: message) } throw RunnerGestureOutcomeUnknown( message: message, hint: "Check the screen with snapshot before you retry; the tap may already have run." ) } + + static func simulatorHIDTapRefusal(reason: String) -> RunnerGestureRefusedWithoutFallback { + RunnerGestureRefusedWithoutFallback( + message: "simulator tap could not send a touchscreen HID contact: \(reason)", + hint: "Retry after the app is foregrounded on a simulator display with a touchscreen." + ) + } #endif /// Where a synthesized point gesture lands: its native point and the window that routes it, or the diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerRequestPanelTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerRequestPanelTests.swift index caef983dc9a..c1b065bb2b1 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerRequestPanelTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerRequestPanelTests.swift @@ -27,9 +27,29 @@ private struct RecordedSurfaceDispatch { let displayID: UInt let start: CGPoint let end: CGPoint? - let orientation: Int + /// Nil for a simulator HID tap, whose point is already in native portrait points. + let orientation: Int? } +#if targetEnvironment(simulator) +/// Stands in for a prepared `RunnerSimulatorTouch`: records its tap as the probe's dispatch. +@MainActor +private final class LitPanelSimulatorTouch: NSObject { + let window: AnyObject? + + init(window: AnyObject?) { + self.window = window + } + + @objc(dispatchTapAtPoint:screenSize:touchDown:) + func dispatchTap(at point: CGPoint, screenSize: CGSize, touchDown: UnsafeMutablePointer) -> NSString? { + touchDown.pointee = true + LitPanelBookingProbe.record(window: window, orientation: nil, start: point) + return nil + } +} +#endif + @MainActor private final class LitPanelBookingProbe: NSObject { static var originalValueForKey: IMP? @@ -135,12 +155,13 @@ private final class LitPanelBookingProbe: NSObject { return unsafeBitCast(SurfaceSelectorQuery(elements), to: XCUIElementQuery.self) } - @objc(synthesizeTapWithApplication:resolvedWindow:interfaceOrientation:point:deadline:errorMessage:) - class func synthesizeTap(_ app: AnyObject, resolvedWindow: AnyObject?, interfaceOrientation: Int, point: CGPoint, - deadline: NSDate?, errorMessage: AutoreleasingUnsafeMutablePointer?) -> Int { - record(window: resolvedWindow, orientation: interfaceOrientation, start: point) - return 0 +#if targetEnvironment(simulator) + @objc(prepareWithApplication:resolvedWindow:failure:) + class func prepareSimulatorTouch(_ app: AnyObject, resolvedWindow: AnyObject?, + failure: AutoreleasingUnsafeMutablePointer) -> AnyObject? { + LitPanelSimulatorTouch(window: resolvedWindow) } +#endif @objc(synthesizeDragWithApplication:resolvedWindow:interfaceOrientation:drag:dispatched:) class func synthesizeDrag(_ app: AnyObject, resolvedWindow: AnyObject?, interfaceOrientation: Int, @@ -166,7 +187,7 @@ private final class LitPanelBookingProbe: NSObject { return nil } - private static func record(window: AnyObject?, orientation: Int, start: CGPoint, end: CGPoint? = nil) { + static func record(window: AnyObject?, orientation: Int?, start: CGPoint, end: CGPoint? = nil) { var display: UInt = 0 if let window { _ = RunnerResolveWindowDisplayID(window, &display) } dispatches.append(RecordedSurfaceDispatch(window: window, displayID: display, start: start, end: end, orientation: orientation)) @@ -287,7 +308,6 @@ extension RunnerTests { let dispatch = try XCTUnwrap(LitPanelBookingProbe.dispatches.first) XCTAssertEqual(dispatch.displayID, 3) XCTAssertEqual(dispatch.start, CGPoint(x: 200, y: 150)) - XCTAssertEqual(dispatch.orientation, RunnerInterfaceOrientation.portrait) } } } @@ -393,7 +413,6 @@ extension RunnerTests { XCTAssertEqual(LitPanelBookingProbe.dispatches.count, 1) let dispatch = try XCTUnwrap(LitPanelBookingProbe.dispatches.first) XCTAssertEqual(dispatch.displayID, 1) - XCTAssertEqual(dispatch.orientation, RunnerInterfaceOrientation.landscapeRight) XCTAssertEqual(dispatch.start, CGPoint(x: 624, y: 300)) XCTAssertTrue(dispatch.window === LitPanelBookingProbe.window) XCTAssertEqual((dispatch.window as? XCUIElement)?.frame, CGRect(x: 224, y: 207, width: 386, height: 682)) @@ -765,10 +784,14 @@ extension RunnerTests { (#selector(getter: XCUIElement.frame), #selector(getter: LitPanelBookingProbe.frame)), (#selector(XCUIElement.descendants(matching:)), #selector(LitPanelBookingProbe.descendants(matching:))), ].map { (class_getInstanceMethod(windowClass, $0.0), class_getInstanceMethod(LitPanelBookingProbe.self, $0.1)) } - let synthesisSwap = ( - class_getClassMethod(RunnerSynthesizedGesture.self, NSSelectorFromString("synthesizeTapWithApplication:resolvedWindow:interfaceOrientation:point:deadline:errorMessage:")), - class_getClassMethod(LitPanelBookingProbe.self, #selector(LitPanelBookingProbe.synthesizeTap(_:resolvedWindow:interfaceOrientation:point:deadline:errorMessage:))) - ) +#if targetEnvironment(simulator) + let tapSwaps: [(Method?, Method?)] = [( + class_getClassMethod(RunnerSimulatorTouch.self, NSSelectorFromString("prepareWithApplication:resolvedWindow:failure:")), + class_getClassMethod(LitPanelBookingProbe.self, #selector(LitPanelBookingProbe.prepareSimulatorTouch(_:resolvedWindow:failure:))) + )] +#else + let tapSwaps: [(Method?, Method?)] = [] +#endif let dragStub = class_getClassMethod(LitPanelBookingProbe.self, #selector(LitPanelBookingProbe.synthesizeDrag(_:resolvedWindow:interfaceOrientation:drag:dispatched:))) let composedSwaps: [(Method?, Method?)] = [ (class_getInstanceMethod(try XCTUnwrap(object_getClass(app)), NSSelectorFromString("keyboards")), @@ -806,7 +829,7 @@ extension RunnerTests { litPanelState.panel = nil litPanelState.surface = nil } - for (method, stub) in swaps + (composed ? attributeSwaps + [synthesisSwap] + composedSwaps : []) { + for (method, stub) in swaps + (composed ? attributeSwaps + tapSwaps + composedSwaps : []) { let method = try XCTUnwrap(method) let stub = try XCTUnwrap(stub) originals.append((method, method_setImplementation(method, method_getImplementation(stub)))) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift index 6d34c66db92..8f511fbba0d 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift @@ -3,54 +3,50 @@ import XCTest #if AGENT_DEVICE_RUNNER_UNIT_TESTS && os(iOS) import ObjectiveC.runtime -final class RunnerTapSynthesisStub: NSObject { - static var status: RunnerTapSynthesisStatus? - static var interruptionHandlingDisabled: Bool? - - @objc(synthesizeTapWithApplication:resolvedWindow:interfaceOrientation:point:deadline:errorMessage:) - class func synthesizeTap( - application: XCUIApplication, - resolvedWindow: Any?, - interfaceOrientation: Int, - point: CGPoint, - deadline: NSDate?, - errorMessage: AutoreleasingUnsafeMutablePointer? - ) -> RunnerTapSynthesisStatus { - interruptionHandlingDisabled = (application.value(forKey: "doesNotHandleUIInterruptions") as? NSNumber)?.boolValue - if status == .failed { errorMessage?.pointee = "forced private synthesis failure" } - return status ?? (deadline == nil ? .succeeded : .deadlineExceeded) - } -} - -/// Answers that no simulator HID contact can be prepared, so a tap reaches the XCTest synthesis -/// seam that a test stubs. -final class RunnerSimulatorTouchUnavailableStub: NSObject { - @objc(prepareWithApplication:resolvedWindow:failure:) - class func prepare( - application: Any, - resolvedWindow: Any?, - failure: AutoreleasingUnsafeMutablePointer - ) -> AnyObject? { - failure.pointee = "simulator HID tap stubbed out so the test reaches tap synthesis" - return nil - } -} - -extension RunnerTests { - /// Routes every tap to `RunnerSynthesizedGesture.synthesizeTap` until the returned closure runs. - func disableSimulatorHIDTap() throws -> () -> Void { #if targetEnvironment(simulator) +extension RunnerTests { + static let stubbedSimulatorHIDTapFailure = "simulator HID tap stubbed out by the test" + + /// Replaces `RunnerSimulatorTouch.prepare` until the returned closure runs. `replacement` gets the + /// application, the resolved window, the failure out-parameter, and the original preparation. + func replaceSimulatorTouchPreparation( + _ replacement: @escaping ( + _ application: AnyObject, + _ resolvedWindow: AnyObject?, + _ failure: AutoreleasingUnsafeMutablePointer, + _ original: () -> AnyObject? + ) -> AnyObject? + ) throws -> () -> Void { let selector = NSSelectorFromString("prepareWithApplication:resolvedWindow:failure:") let method = try XCTUnwrap(class_getClassMethod(RunnerSimulatorTouch.self, selector)) - let stub = try XCTUnwrap(class_getClassMethod(RunnerSimulatorTouchUnavailableStub.self, selector)) - let original = method_setImplementation(method, method_getImplementation(stub)) - return { method_setImplementation(method, original) } -#else - return {} -#endif + let original = method_getImplementation(method) + typealias Prepare = @convention(c) ( + AnyObject, Selector, AnyObject, AnyObject?, AutoreleasingUnsafeMutablePointer + ) -> AnyObject? + let stub = imp_implementationWithBlock({ ( + target: AnyObject, application: AnyObject, window: AnyObject?, failure: AutoreleasingUnsafeMutablePointer + ) -> AnyObject? in + replacement(application, window, failure) { + unsafeBitCast(original, to: Prepare.self)(target, selector, application, window, failure) + } + } as @convention(block) (AnyObject, AnyObject, AnyObject?, AutoreleasingUnsafeMutablePointer) -> AnyObject?) + method_setImplementation(method, stub) + return { + method_setImplementation(method, original) + imp_removeBlock(stub) + } + } + + /// Makes every simulator tap's HID contact fail to prepare until the returned closure runs. + func makeSimulatorHIDTapUnavailable() throws -> () -> Void { + try replaceSimulatorTouchPreparation { _, _, failure, _ in + failure.pointee = Self.stubbedSimulatorHIDTapFailure as NSString + return nil + } } } #endif +#endif extension RunnerTests { #if AGENT_DEVICE_RUNNER_UNIT_TESTS && os(iOS) @@ -149,27 +145,52 @@ extension RunnerTests { XCTAssertEqual(app.staticTexts["agent-device-alert-actions"].label, "First actions: 0; replacement actions: 0") } +#if targetEnvironment(simulator) + /// The deadline passes while the simulator tap prepares its HID contact, so no contact goes down. @MainActor - func testAlertDeadlineDuringSynthesisPreparationLeavesTheOriginalUntouched() throws { + func testAlertDeadlineDuringTapPreparationLeavesTheOriginalUntouched() throws { defer { tearDownReplacementAlert() } let alert = try launchReplacementAlert() let button = try XCTUnwrap(alert.actions.first { $0.label == "OK" }) let frame = button.frame - try withAlertTapStub { - let outcome = try activateAlertButton(alert, button: button, action: "accept", frame: frame, deadline: .distantFuture) + let deadline = Date().addingTimeInterval(2) + var prepared = false + let restore = try replaceSimulatorTouchPreparation { _, _, _, original in + prepared = true + Thread.sleep(until: deadline) + return original() + } + defer { restore() } - XCTAssertNil(outcome) - XCTAssertTrue(app.alerts.firstMatch.exists) - XCTAssertEqual(app.staticTexts["agent-device-alert-actions"].label, "First actions: 0; replacement actions: 0") + let outcome = try activateAlertButton(alert, button: button, action: "accept", frame: frame, deadline: deadline) - RunnerTapSynthesisStub.status = RunnerTapSynthesisStatus(rawValue: 999) - let unknown = try activateAlertButton(alert, button: button, action: "accept", frame: frame, deadline: .distantFuture) - guard case .unsupported? = unknown else { - return XCTFail("an unknown native status must report failure rather than deadline expiry") - } + XCTAssertTrue(prepared, "the tap must reach its HID preparation before the deadline") + XCTAssertNil(outcome) + XCTAssertTrue(app.alerts.firstMatch.exists) XCTAssertEqual(app.staticTexts["agent-device-alert-actions"].label, "First actions: 0; replacement actions: 0") + } + + /// A simulator tap whose HID contact cannot be prepared refuses the alert action and taps nothing. + @MainActor + func testAlertActivationRefusesWhenTheSimulatorHIDTapCannotBePrepared() throws { + defer { tearDownReplacementAlert() } + let alert = try launchReplacementAlert() + let button = try XCTUnwrap(alert.actions.first { $0.label == "OK" }) + let frame = button.frame + let restore = try makeSimulatorHIDTapUnavailable() + defer { restore() } + + let outcome = try activateAlertButton(alert, button: button, action: "accept", frame: frame, deadline: .distantFuture) + + guard case .unsupported(let message, let hint)? = outcome else { + return XCTFail("an unprepared HID tap must refuse, got \(String(describing: outcome))") } + XCTAssertEqual(message, Self.simulatorHIDTapRefusal(reason: Self.stubbedSimulatorHIDTapFailure).message) + XCTAssertEqual(hint, "Inspect the current alert before deciding whether to act again.") + XCTAssertTrue(app.alerts.firstMatch.exists) + XCTAssertEqual(app.staticTexts["agent-device-alert-actions"].label, "First actions: 0; replacement actions: 0") } +#endif @MainActor func testAlertActivationIgnoresAnAppThatNeverSettlesBeforeTheDeadline() throws { @@ -220,16 +241,24 @@ extension RunnerTests { @MainActor private func assertAlertActivationDisablesInterruptionHandling(_ alert: RunnerAlert) throws { +#if targetEnvironment(simulator) let button = try XCTUnwrap(alert.actions.first { $0.label == "OK" }) let frame = button.frame - try withAlertTapStub { - RunnerTapSynthesisStub.status = .deadlineExceeded - let outcome = try activateAlertButton( - alert, button: button, action: "accept", frame: frame, deadline: .distantFuture - ) - XCTAssertNil(outcome) - XCTAssertEqual(RunnerTapSynthesisStub.interruptionHandlingDisabled, true) + var interruptionHandlingDisabled: Bool? + let restore = try replaceSimulatorTouchPreparation { application, _, failure, _ in + interruptionHandlingDisabled = (application.value(forKey: "doesNotHandleUIInterruptions") as? NSNumber)?.boolValue + failure.pointee = Self.stubbedSimulatorHIDTapFailure as NSString + return nil } + defer { restore() } + let outcome = try activateAlertButton( + alert, button: button, action: "accept", frame: frame, deadline: .distantFuture + ) + guard case .unsupported? = outcome else { + return XCTFail("the stubbed HID tap must refuse, got \(String(describing: outcome))") + } + XCTAssertEqual(interruptionHandlingDisabled, true) +#endif } @MainActor @@ -246,22 +275,6 @@ extension RunnerTests { app.terminate() } - @MainActor - private func withAlertTapStub(_ body: () throws -> Void) throws { - let selector = NSSelectorFromString("synthesizeTapWithApplication:resolvedWindow:interfaceOrientation:point:deadline:errorMessage:") - let method = try XCTUnwrap(class_getClassMethod(RunnerSynthesizedGesture.self, selector)) - let stub = try XCTUnwrap(class_getClassMethod(RunnerTapSynthesisStub.self, selector)) - let original = method_setImplementation(method, method_getImplementation(stub)) - let restoreSimulatorHIDTap = try disableSimulatorHIDTap() - defer { - restoreSimulatorHIDTap() - RunnerTapSynthesisStub.status = nil - RunnerTapSynthesisStub.interruptionHandlingDisabled = nil - method_setImplementation(method, original) - } - try body() - } - @MainActor private func withNotificationBannerAlert(_ assertions: (RunnerAlert) throws -> Void) throws { app.launchArguments = ["--agent-device-alert-replacement-regression", "--agent-device-alert-banner"] diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandExecutionTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandExecutionTests.swift index f690cd2e12d..bd71f77fa96 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandExecutionTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandExecutionTests.swift @@ -29,55 +29,40 @@ extension RunnerTests { imp_removeBlock(replacement) }) } - - /// Makes private tap synthesis fail until the returned closure restores it. - func forceSynthesizedTapFailure() throws -> () -> Void { - let selector = NSSelectorFromString("synthesizeTapWithApplication:resolvedWindow:interfaceOrientation:point:deadline:errorMessage:") - let synthesizedTapMethod = try XCTUnwrap(class_getClassMethod(RunnerSynthesizedGesture.self, selector)) - let failureStubMethod = try XCTUnwrap(class_getClassMethod(RunnerTapSynthesisStub.self, selector)) - let originalImplementation = method_getImplementation(synthesizedTapMethod) - method_setImplementation(synthesizedTapMethod, method_getImplementation(failureStubMethod)) - let restoreSimulatorHIDTap = try disableSimulatorHIDTap() - let status = RunnerTapSynthesisStub.status - RunnerTapSynthesisStub.status = .failed - return { - restoreSimulatorHIDTap() - RunnerTapSynthesisStub.status = status - RunnerTapSynthesisStub.interruptionHandlingDisabled = nil - method_setImplementation(synthesizedTapMethod, originalImplementation) - } - } } #endif #if AGENT_DEVICE_RUNNER_UNIT_TESTS extension RunnerTests { -#if os(iOS) +#if os(iOS) && targetEnvironment(simulator) + /// On a simulator a synthesized tap whose HID contact cannot be prepared refuses with the HID + /// reason; no XCTest coordinate tap stands in for it, even on a healthy tree. @MainActor - func testSelectorTapFallsBackToXCTestCoordinateWhenPrivateSynthesisFails() throws { - let restoreSynthesizedTap = try forceSynthesizedTapFailure() + func testSelectorTapRefusesWithoutAnXCTestCoordinateWhenTheSimulatorHIDTapCannotBePrepared() throws { + let restoreHIDTap = try makeSimulatorHIDTapUnavailable() app.launch() mainOwned.app = app mainOwned.accessibilityHealth = .healthy + let taps = try observeCoordinateTaps() defer { - restoreSynthesizedTap() + taps.restore() + restoreHIDTap() invalidateCachedTarget(reason: "unit_test_cleanup") app.terminate() } let command = try runnerCommandFixture( - #"{"command":"tap","commandId":"selector-tap-fallback","selectorKey":"label","selectorValue":"Agent Device Runner","synthesized":true}"# + #"{"command":"tap","commandId":"selector-tap-hid-refusal","selectorKey":"label","selectorValue":"Agent Device Runner","synthesized":true}"# ) let response = try executeOnMainPrepared(command: command, activeApp: app) - XCTAssertTrue(response.ok) - XCTAssertEqual(response.data?.message, "tapped") - XCTAssertEqual(response.data?.gestureFallback, "xctest-coordinate-tap") - XCTAssertEqual(response.data?.gestureFallbackMessage, "forced private synthesis failure") - XCTAssertEqual( - response.data?.gestureFallbackHint, - "Falling back to XCTest coordinate tap may be slower and can still need a healthy accessibility tree." - ) + let refusal = Self.simulatorHIDTapRefusal(reason: Self.stubbedSimulatorHIDTapFailure) + XCTAssertFalse(response.ok) + XCTAssertEqual(response.error?.code, "UNSUPPORTED_OPERATION") + XCTAssertEqual(response.error?.message, refusal.message) + XCTAssertEqual(response.error?.hint, refusal.hint) + XCTAssertNil(response.data?.gestureFallback) + XCTAssertEqual(taps.observer.count, 0) } #endif diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SequenceExecutionTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SequenceExecutionTests.swift index 131b91ef504..a55dd3b1dba 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SequenceExecutionTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SequenceExecutionTests.swift @@ -175,44 +175,47 @@ extension RunnerTests { } #endif -#if AGENT_DEVICE_RUNNER_UNIT_TESTS && os(iOS) +#if AGENT_DEVICE_RUNNER_UNIT_TESTS && os(iOS) && targetEnvironment(simulator) extension RunnerTests { + /// On a simulator a synthesized tap step whose HID contact cannot be prepared fails with the HID + /// refusal; no XCTest coordinate tap runs in its place. @MainActor - func testSynthesizedSequenceTapFallsBackToXCTestCoordinateTapWhenAccessibilityIsUnavailable() throws { - let restoreSynthesizedTap = try forceSynthesizedTapFailure() + func testSynthesizedSequenceTapRefusesWithoutAnXCTestCoordinateTapWhenTheSimulatorHIDTapCannotBePrepared() throws { + let restoreHIDTap = try makeSimulatorHIDTapUnavailable() app.launch() mainOwned.app = app defer { - restoreSynthesizedTap() + restoreHIDTap() invalidateCachedTarget(reason: "unit_test_cleanup") app.terminate() } let label = app.staticTexts["Agent Device Runner"] XCTAssertTrue(label.waitForFixtureExistence(timeout: appExistenceTimeout)) let point = CGPoint(x: label.frame.midX, y: label.frame.midY) - mainOwned.accessibilityHealth = .unavailable + mainOwned.accessibilityHealth = .healthy let command = try runnerCommandFixture( - #"{"command":"sequence","commandId":"sequence-synthesized-tap-fallback","steps":[{"kind":"tap","x":\#(point.x),"y":\#(point.y),"synthesized":true}]}"# + #"{"command":"sequence","commandId":"sequence-synthesized-tap-hid-refusal","steps":[{"kind":"tap","x":\#(point.x),"y":\#(point.y),"synthesized":true}]}"# ) let response = try executeOnMainPrepared(command: command, activeApp: app) - XCTAssertTrue(response.ok) - XCTAssertEqual(response.data?.completedSteps, 1) - XCTAssertNil(response.data?.failedStepIndex) - XCTAssertEqual(response.data?.sequenceResults?.first?.ok, true) + let step = try XCTUnwrap(response.data?.sequenceResults?.first) + XCTAssertEqual(response.data?.completedSteps, 0) + XCTAssertEqual(response.data?.failedStepIndex, 0) + XCTAssertEqual(step.errorCode, "UNSUPPORTED_OPERATION") + XCTAssertEqual(step.errorMessage, Self.simulatorHIDTapRefusal(reason: Self.stubbedSimulatorHIDTapFailure).message) } } #endif -#if AGENT_DEVICE_RUNNER_UNIT_TESTS && os(iOS) +#if AGENT_DEVICE_RUNNER_UNIT_TESTS && os(iOS) && targetEnvironment(simulator) extension RunnerTests { /// The iOS backend sends coordinate taps as synthesized steps. Where neither a window nor the sole /// screen gives that tap a context, its touch frame reads the app frame. On a tree XCTest cannot - /// snapshot that read is held, and the tap is synthesized without a touch frame, as the - /// synthesized `tap` command is. + /// snapshot that read is held. On a simulator the HID contact then needs the display size the + /// test hides, so the step refuses, with no recorded issue and no XCTest coordinate tap. @MainActor - func testSynthesizedTapSequenceWithoutASynthesisContextOnAnUnserializableTreeTapsWithoutARecordedIssue() throws { + func testSynthesizedTapSequenceWithoutASynthesisContextOnAnUnserializableTreeRefusesWithoutARecordedIssue() throws { app.launch() mainOwned.app = app let restoreDisplay = try simulateUnreadableDisplay() @@ -232,10 +235,13 @@ extension RunnerTests { let response = try executeOnMainPrepared(command: sequence, activeApp: app) XCTAssertFalse(didRecordXCTestFailure(since: failureCountBefore)) - XCTAssertTrue(response.ok, String(describing: response.error)) - XCTAssertEqual(response.data?.completedSteps, 1) - XCTAssertNil(response.data?.failedStepIndex) - XCTAssertEqual(response.data?.sequenceResults?.first?.ok, true) + XCTAssertEqual(response.data?.completedSteps, 0) + XCTAssertEqual(response.data?.failedStepIndex, 0) + XCTAssertEqual(response.data?.sequenceResults?.first?.errorCode, "UNSUPPORTED_OPERATION") + XCTAssertEqual( + response.data?.sequenceResults?.first?.errorMessage, + Self.simulatorHIDTapRefusal(reason: "the display size could not be read").message + ) XCTAssertEqual(RunnerCoordinateTapCounter.taps, 0) } } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SynthesizedInteractionTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SynthesizedInteractionTests.swift index 5028e1889d1..9cb50297ca6 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SynthesizedInteractionTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SynthesizedInteractionTests.swift @@ -697,12 +697,13 @@ extension RunnerTests { XCTAssertFalse(didRecordXCTestFailure(since: failureCountBefore)) } +#if targetEnvironment(simulator) /// A refused coordinate tap answers `UNSUPPORTED_OPERATION` with a hint, not an uncoded failure: /// the daemon surfaces the code, and the runner stays up. @MainActor func testRefusedCoordinateTapAnswersACodedUnsupportedOperationWithAHint() throws { - let restoreSynthesizedTap = try forceSynthesizedTapFailure() - defer { restoreSynthesizedTap() } + let restoreHIDTap = try makeSimulatorHIDTapUnavailable() + defer { restoreHIDTap() } app.launch() mainOwned.app = app let restoreXCTest = try simulateUnserializableAppTree() @@ -720,6 +721,7 @@ extension RunnerTests { XCTAssertNotNil(response.error?.hint) XCTAssertEqual(RunnerCoordinateTapCounter.taps, 0) } +#endif /// With the penalty lapsed and the windows query failing, a probe that still answers an input /// carries the fill through the synthesized replacement: one value decides the route, the @@ -976,10 +978,12 @@ extension RunnerTests { XCTAssertEqual(unscopedDigitizerBasis(app: app, window: placedWindow, interfaceOrientation: landscape), measured) } - /// #4091: a portrait turn leaves the point as it is, so an unreadable display box neither refuses - /// it nor is read for it: the tap is dispatched even through a placed window on either family. +#if targetEnvironment(simulator) + /// #4091: a portrait turn leaves the point as it is, so an unreadable display box does not refuse + /// it through a placed window. On a simulator the HID contact then needs that display size, so the + /// tap answers the HID refusal and sends nothing. @MainActor - func testPortraitTapDispatchesWhenTheSoleDisplayCannotBeMeasured() throws { + func testPortraitTapOnAnUnmeasuredSoleDisplayAnswersTheSimulatorHIDRefusal() throws { try XCTSkipUnless(XCUIScreen.screens.count == 1, "a multi-screen host keeps its panel's window box") let placedWindow = CGRect(x: 224, y: 207, width: 386, height: 682) let (context, cleanup) = try launchWithUnreadableDisplay(landscape: false, windowFrame: placedWindow) @@ -989,17 +993,14 @@ extension RunnerTests { RunnerInterfaceOrientation.portrait ) - let outcome = try synthesizedTapAt(app: app, x: 40, y: 40, context: context) - guard case .performed? = outcome else { - return XCTFail("expected a portrait tap to be dispatched, got \(String(describing: outcome))") - } + assertUnmeasuredDisplayHIDRefusal { try synthesizedTapAt(app: app, x: 40, y: 40, context: context) } } /// #4091: with the window query rejected (a tree XCTest cannot serialize) and the display /// unreadable there is no box at all. A portrait turn leaves the point as it is, so an admitted sole - /// screen still takes the tap as given. + /// screen admits the tap as given; on a simulator its HID contact then answers the refusal. @MainActor - func testWindowlessPortraitTapDispatchesWhenTheSoleDisplayCannotBeMeasured() throws { + func testWindowlessPortraitTapOnAnUnmeasuredSoleDisplayAnswersTheSimulatorHIDRefusal() throws { try XCTSkipUnless(XCUIScreen.screens.count == 1, "a multi-screen host keeps its panel's window box") let (_, cleanup) = try launchWithUnreadableDisplay(landscape: false, windowQueryRejected: true) defer { cleanup() } @@ -1012,11 +1013,26 @@ extension RunnerTests { RunnerInterfaceOrientation.portrait ) - let outcome = try synthesizedTapAt(app: app, x: 40, y: 40) - guard case .performed? = outcome else { - return XCTFail("expected a window-less portrait tap to be dispatched, got \(String(describing: outcome))") + assertUnmeasuredDisplayHIDRefusal { try synthesizedTapAt(app: app, x: 40, y: 40) } + } + + /// The HID refusal, not a rotation refusal, shows that the point resolved and only the contact + /// failed for want of the display size. + private func assertUnmeasuredDisplayHIDRefusal( + _ tap: () throws -> RunnerInteractionOutcome?, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertThrowsError(try tap(), file: file, line: line) { error in + XCTAssertEqual( + (error as? RunnerGestureRefusedWithoutFallback)?.message, + Self.simulatorHIDTapRefusal(reason: "the display size could not be read").message, + file: file, + line: line + ) } } +#endif /// #4091: a landscape turn needs the box, and with the window query rejected no window can stand in /// for an unreadable display, so the tap refuses before it dispatches instead of falling back to the @@ -1049,11 +1065,12 @@ extension RunnerTests { XCTAssertEqual(message, "synthesized coordinate drag could not resolve an app window with a finite screen frame") } +#if targetEnvironment(simulator) /// #4091: when the device's only screen will not report its size, an app the sole-screen rule /// proves full-screen (an iPhone by its idiom) has a window that is the display, so its tap still - /// turns about that window and is dispatched. + /// turns about that window. On a simulator its HID contact then answers the refusal. @MainActor - func testTapTurnsAboutTheWindowWhenTheSoleDisplayCannotBeMeasuredOnAFullScreenApp() throws { + func testTapTurnsAboutTheWindowOnAnUnmeasuredSoleDisplayAndAnswersTheSimulatorHIDRefusal() throws { try XCTSkipUnless(XCUIScreen.screens.count == 1, "a multi-screen host keeps its panel's window box") let (context, cleanup) = try launchWithUnreadableDisplay(landscape: true) defer { cleanup() } @@ -1068,11 +1085,9 @@ extension RunnerTests { unscopedDigitizerBasis(app: app, window: windowFrame, interfaceOrientation: orientation), windowFrame ) - let outcome = try synthesizedTapAt(app: app, x: 40, y: 40, context: context) - guard case .performed? = outcome else { - return XCTFail("expected the tap to be dispatched about the window, got \(String(describing: outcome))") - } + assertUnmeasuredDisplayHIDRefusal { try synthesizedTapAt(app: app, x: 40, y: 40, context: context) } } +#endif /// #4091: when the device's only screen will not report its size and the app is not proven to fill /// it, a placed window's smaller box is no basis to turn about (#3899), so a tap through a resolved diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SynthesizedTapContextTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SynthesizedTapContextTests.swift index 869ee8d550e..42ed0bd75e4 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SynthesizedTapContextTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SynthesizedTapContextTests.swift @@ -107,6 +107,28 @@ extension RunnerTests { ) } + /// A refusal that no XCTest gesture may replace stays the answer on a healthy tree, where any + /// other tap refusal takes the XCTest fallback, and no windows query runs to decide it. + @MainActor + func testRefusalWithoutFallbackSkipsTheXCTestFallbackOnAHealthyTree() throws { + let health = mainOwned.accessibilityHealth + defer { mainOwned.accessibilityHealth = health } + mainOwned.accessibilityHealth = .healthy + + let (attempt, queries) = try countingElementQueries { + try performSynthesizedGesture(app, kind: .coordinateTap, context: nil) { + throw RunnerGestureRefusedWithoutFallback(message: "injected refusal", hint: "injected hint") + } + } + + XCTAssertEqual(queries, 0) + guard case .refused(_, .unsupported(let message, let hint)) = attempt else { + return XCTFail("the refusal must not take the XCTest fallback: \(attempt)") + } + XCTAssertEqual(message, "injected refusal") + XCTAssertEqual(hint, "injected hint") + } + /// A resolved window that fills an iPhone's only screen routes its records to that screen, so /// dispatch does not re-read the window; the window stays on the context for its other reads. @MainActor diff --git a/docs/adr/0011-interaction-guarantee-contract.md b/docs/adr/0011-interaction-guarantee-contract.md index 79b9bdd33ec..6d7170e8cba 100644 --- a/docs/adr/0011-interaction-guarantee-contract.md +++ b/docs/adr/0011-interaction-guarantee-contract.md @@ -429,9 +429,12 @@ The reason: those sources can diverge from full-screen screenshot coordinates on On an iOS Simulator, the runner dispatches a synthesized tap as one touchscreen HID contact from inside the simulator. The contact goes down at the resolved native point, holds 50 ms, and lifts, as the XCTest tap record does. It uses the touchscreen sender of the app's display, the same sender the screen-edge touch uses. -The XCTest event record is used only when the HID contact cannot be prepared, because then nothing was sent. +A simulator tap has no XCTest event record and no XCUICoordinate fallback. +If the HID contact cannot be prepared, or does not go down, the tap answers `UNSUPPORTED_OPERATION` with the HID reason and a hint, and sends nothing. +These cases are missing IOKit symbols, a missing, ambiguous, or unrecognized touchscreen service, and an unreadable display size. +They are a broken simulator runtime, so the refusal surfaces them, as the screen-edge touch does. A contact that went down and then failed answers `SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN`, and no fallback repeats it. -Physical devices keep the XCTest event record, because only a simulator accepts this HID dispatch. +Physical devices keep the XCTest event record and its XCUICoordinate fallback, because only a simulator accepts this HID dispatch. The reason: XCTest event synthesis spends about 280 ms of its own round trip on every tap, and the HID contact returns when the finger lifts. The runner process is inside the simulator, so provider simulators get the same route as local ones. From fde8c609d544dd1716b3104ae642b88c193590b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 10:50:57 +0100 Subject: [PATCH 2/4] test(ios-runner): reuse the prepare replacement for the slow edge touch Co-Authored-By: Claude Opus 5.5 --- .../UnitTests/RunnerTests+NavigationTests.swift | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+NavigationTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+NavigationTests.swift index abc5afaabb7..cde362becfa 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+NavigationTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+NavigationTests.swift @@ -565,22 +565,9 @@ extension RunnerTests { /// Delays resolving the edge touch (display, HID client, touchscreen sender) by `seconds`. private func slowEdgeTouchPreparation(by seconds: TimeInterval) throws -> () -> Void { - let selector = NSSelectorFromString("prepareWithApplication:resolvedWindow:failure:") - let method = try XCTUnwrap(class_getClassMethod(RunnerSimulatorTouch.self, selector)) - let original = method_getImplementation(method) - typealias Prepare = @convention(c) ( - AnyObject, Selector, AnyObject, AnyObject?, AutoreleasingUnsafeMutablePointer - ) -> AnyObject? - let slowed = imp_implementationWithBlock({ ( - target: AnyObject, application: AnyObject, window: AnyObject?, failure: AutoreleasingUnsafeMutablePointer - ) -> AnyObject? in + try replaceSimulatorTouchPreparation { _, _, _, original in Thread.sleep(forTimeInterval: seconds) - return unsafeBitCast(original, to: Prepare.self)(target, selector, application, window, failure) - } as @convention(block) (AnyObject, AnyObject, AnyObject?, AutoreleasingUnsafeMutablePointer) -> AnyObject?) - method_setImplementation(method, slowed) - return { - method_setImplementation(method, original) - imp_removeBlock(slowed) + return original() } } From dcb2f8f85e6949e0fa8289070f186b54aab39a32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 10:54:03 +0100 Subject: [PATCH 3/4] fix(ios-runner): keep the HID refusal hint on alert taps and tighten the ADR wording Co-Authored-By: Claude Sonnet 5.5 --- .../RunnerTests+Alert.swift | 3 ++- .../RunnerTests+AlertObservationTests.swift | 5 +++-- .../RunnerTests+SequenceExecutionTests.swift | 16 ++++++++++------ docs/adr/0011-interaction-guarantee-contract.md | 6 +++--- 4 files changed, 18 insertions(+), 12 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift index e13e50bd794..06c34b984b4 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift @@ -233,7 +233,8 @@ extension RunnerTests { deadline: deadline ) } catch let refusal as RunnerGestureRefusedWithoutFallback { - attempt = .unsupported(message: refusal.message, hint: refusal.hint) + outcome = .unsupported(message: refusal.message, hint: refusal.hint) + return } catch { activationError = error return diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift index 8f511fbba0d..ff9935e2a7d 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift @@ -182,11 +182,12 @@ extension RunnerTests { let outcome = try activateAlertButton(alert, button: button, action: "accept", frame: frame, deadline: .distantFuture) + let refusal = Self.simulatorHIDTapRefusal(reason: Self.stubbedSimulatorHIDTapFailure) guard case .unsupported(let message, let hint)? = outcome else { return XCTFail("an unprepared HID tap must refuse, got \(String(describing: outcome))") } - XCTAssertEqual(message, Self.simulatorHIDTapRefusal(reason: Self.stubbedSimulatorHIDTapFailure).message) - XCTAssertEqual(hint, "Inspect the current alert before deciding whether to act again.") + XCTAssertEqual(message, refusal.message) + XCTAssertEqual(hint, refusal.hint) XCTAssertTrue(app.alerts.firstMatch.exists) XCTAssertEqual(app.staticTexts["agent-device-alert-actions"].label, "First actions: 0; replacement actions: 0") } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SequenceExecutionTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SequenceExecutionTests.swift index a55dd3b1dba..e085ab17c4e 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SequenceExecutionTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SequenceExecutionTests.swift @@ -202,8 +202,11 @@ extension RunnerTests { let step = try XCTUnwrap(response.data?.sequenceResults?.first) XCTAssertEqual(response.data?.completedSteps, 0) XCTAssertEqual(response.data?.failedStepIndex, 0) + let refusal = Self.simulatorHIDTapRefusal(reason: Self.stubbedSimulatorHIDTapFailure) + XCTAssertFalse(step.ok) XCTAssertEqual(step.errorCode, "UNSUPPORTED_OPERATION") - XCTAssertEqual(step.errorMessage, Self.simulatorHIDTapRefusal(reason: Self.stubbedSimulatorHIDTapFailure).message) + XCTAssertEqual(step.errorMessage, refusal.message) + XCTAssertEqual(step.errorHint, refusal.hint) } } #endif @@ -237,11 +240,12 @@ extension RunnerTests { XCTAssertFalse(didRecordXCTestFailure(since: failureCountBefore)) XCTAssertEqual(response.data?.completedSteps, 0) XCTAssertEqual(response.data?.failedStepIndex, 0) - XCTAssertEqual(response.data?.sequenceResults?.first?.errorCode, "UNSUPPORTED_OPERATION") - XCTAssertEqual( - response.data?.sequenceResults?.first?.errorMessage, - Self.simulatorHIDTapRefusal(reason: "the display size could not be read").message - ) + let step = try XCTUnwrap(response.data?.sequenceResults?.first) + let refusal = Self.simulatorHIDTapRefusal(reason: "the display size could not be read") + XCTAssertFalse(step.ok) + XCTAssertEqual(step.errorCode, "UNSUPPORTED_OPERATION") + XCTAssertEqual(step.errorMessage, refusal.message) + XCTAssertEqual(step.errorHint, refusal.hint) XCTAssertEqual(RunnerCoordinateTapCounter.taps, 0) } } diff --git a/docs/adr/0011-interaction-guarantee-contract.md b/docs/adr/0011-interaction-guarantee-contract.md index 6d7170e8cba..d6072edba3f 100644 --- a/docs/adr/0011-interaction-guarantee-contract.md +++ b/docs/adr/0011-interaction-guarantee-contract.md @@ -429,12 +429,12 @@ The reason: those sources can diverge from full-screen screenshot coordinates on On an iOS Simulator, the runner dispatches a synthesized tap as one touchscreen HID contact from inside the simulator. The contact goes down at the resolved native point, holds 50 ms, and lifts, as the XCTest tap record does. It uses the touchscreen sender of the app's display, the same sender the screen-edge touch uses. -A simulator tap has no XCTest event record and no XCUICoordinate fallback. +A synthesized simulator tap has no XCTest event record and no XCUICoordinate fallback. If the HID contact cannot be prepared, or does not go down, the tap answers `UNSUPPORTED_OPERATION` with the HID reason and a hint, and sends nothing. -These cases are missing IOKit symbols, a missing, ambiguous, or unrecognized touchscreen service, and an unreadable display size. +These cases include missing IOKit symbols, a missing, ambiguous, or unrecognized touchscreen service, an unreadable display size, and HID client or event creation failures before touch-down. They are a broken simulator runtime, so the refusal surfaces them, as the screen-edge touch does. A contact that went down and then failed answers `SYNTHESIZED_GESTURE_OUTCOME_UNKNOWN`, and no fallback repeats it. -Physical devices keep the XCTest event record and its XCUICoordinate fallback, because only a simulator accepts this HID dispatch. +Physical devices keep the XCTest event record and may use its XCUICoordinate fallback when the accessibility tree is readable, because only a simulator accepts this HID dispatch. The reason: XCTest event synthesis spends about 280 ms of its own round trip on every tap, and the HID contact returns when the finger lifts. The runner process is inside the simulator, so provider simulators get the same route as local ones. From 16489d4073c1b06da56cce965b9bfffc7f7aa861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 3 Dec 2026 13:35:10 +0100 Subject: [PATCH 4/4] fix(ios-runner): share the simulator HID refusal hint and cover a contact that never went down Co-Authored-By: Claude Sonnet 5.5 --- .../RunnerTests+ScreenEdgeGesture.swift | 2 +- .../RunnerTests+SynthesizedInteraction.swift | 7 ++++++- .../RunnerTests+AlertObservationTests.swift | 16 ++++++++++++++++ .../RunnerTests+CommandExecutionTests.swift | 14 +++++++++++++- 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenEdgeGesture.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenEdgeGesture.swift index 4d11327304b..4c78b09799b 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenEdgeGesture.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenEdgeGesture.swift @@ -43,7 +43,7 @@ extension RunnerTests { guard let portraitSize = simulatorTouchDisplayPortraitSize(), let samples = planned.pointerSamples.first else { return PreparedTouch(notSent: Self.unmeasuredSoleDisplayOutcome(gesture: "edge swipe")) } - let hint = "Retry after the app is foregrounded on a simulator display with a touchscreen." + let hint = Self.simulatorHIDRefusalHint var failure: NSString? guard let touch = RunnerSimulatorTouch.prepare( application: app, diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift index 7ac28467dac..d3bb88424e6 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift @@ -645,10 +645,15 @@ extension RunnerTests { ) } + /// The hint of every simulator HID refusal. A contact that cannot be prepared or never went down + /// means a broken simulator runtime or host, so foregrounding the app does not help. + static let simulatorHIDRefusalHint = + "Restart the simulator. If the failure persists, rebuild the runner." + static func simulatorHIDTapRefusal(reason: String) -> RunnerGestureRefusedWithoutFallback { RunnerGestureRefusedWithoutFallback( message: "simulator tap could not send a touchscreen HID contact: \(reason)", - hint: "Retry after the app is foregrounded on a simulator display with a touchscreen." + hint: simulatorHIDRefusalHint ) } #endif diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift index ff9935e2a7d..a8830165fbc 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift @@ -44,6 +44,22 @@ extension RunnerTests { return nil } } + + /// Makes every simulator tap prepare a touch whose contact never goes down until the returned + /// closure runs. + func makeSimulatorHIDContactNeverDown() throws -> () -> Void { + try replaceSimulatorTouchPreparation { _, _, _, _ in RunnerNeverDownTouch() } + } +} + +/// Answers `RunnerSimulatorTouch.dispatchTap` as a contact that failed before its touch-down. The +/// runner sends it the same message, so it stands in for a prepared touch. +final class RunnerNeverDownTouch: NSObject { + @objc(dispatchTapAtPoint:screenSize:touchDown:) + func dispatchTap(at point: CGPoint, screenSize: CGSize, touchDown: UnsafeMutablePointer) -> NSString? { + touchDown.pointee = false + return RunnerTests.stubbedSimulatorHIDTapFailure as NSString + } } #endif #endif diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandExecutionTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandExecutionTests.swift index bd71f77fa96..4eee27bdff5 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandExecutionTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandExecutionTests.swift @@ -39,7 +39,19 @@ extension RunnerTests { /// reason; no XCTest coordinate tap stands in for it, even on a healthy tree. @MainActor func testSelectorTapRefusesWithoutAnXCTestCoordinateWhenTheSimulatorHIDTapCannotBePrepared() throws { - let restoreHIDTap = try makeSimulatorHIDTapUnavailable() + try assertSelectorTapRefusesWithoutAnXCTestCoordinate(stubbedBy: makeSimulatorHIDTapUnavailable) + } + + /// A prepared touch whose contact never went down sent nothing, so it refuses like an unprepared + /// one and no XCTest coordinate tap replaces it. + @MainActor + func testSelectorTapRefusesWithoutAnXCTestCoordinateWhenThePreparedContactNeverWentDown() throws { + try assertSelectorTapRefusesWithoutAnXCTestCoordinate(stubbedBy: makeSimulatorHIDContactNeverDown) + } + + @MainActor + private func assertSelectorTapRefusesWithoutAnXCTestCoordinate(stubbedBy stub: () throws -> () -> Void) throws { + let restoreHIDTap = try stub() app.launch() mainOwned.app = app mainOwned.accessibilityHealth = .healthy