diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h index 3330817e67..d49dd7ccb2 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h @@ -102,6 +102,11 @@ FOUNDATION_EXPORT NSString *const RunnerAXSnapshotCustomActionsBlockedKey; /// snapshot target match uses; pids only — the client resolves no bundle id for an arbitrary app. + (NSArray *)activeApplicationProcessIdentifiers; +/// Pid of the accessibility element that testmanagerd hit-tests at a screen point, or 0 when the hit +/// test does not answer within one second. ++ (NSInteger)processIdentifierOfElementAtPoint:(CGPoint)point + NS_SWIFT_NAME(processIdentifierOfElement(at:)); + /// The frontier-extension loop, exposed for the runner unit bundle: a frontier whose element /// vanished or whose re-rooted request fails must count as missed, never as drained. + (nullable NSDictionary *)extendSnapshotFrontiers:(NSMutableArray *)frontiers diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m index ad6b04b00b..dd5495f818 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m @@ -28,6 +28,7 @@ // Bounds one read. It exists for the unresponsive case: without it one wedged element would // swallow the whole capture's budget and starve every remaining candidate. static const NSTimeInterval RunnerAXCustomActionReadTimeout = 1.0; +static const NSTimeInterval RunnerAXElementAtPointTimeout = 1.0; // The AX call is a synchronous XPC round trip that cannot be cancelled once issued, so the // timeout above only frees the caller — the call keeps running. Containment needs both parts: @@ -713,6 +714,40 @@ + (NSInteger)processIdentifierForApplication:(XCUIApplication *)application return processIdentifiers; } ++ (NSInteger)processIdentifierOfElementAtPoint:(CGPoint)point +{ + // The AX client's own hit test is macOS-only; on iOS the runner daemon session asks testmanagerd. + Class sessionClass = NSClassFromString(@"XCTRunnerDaemonSession"); + id session = [self objectFrom:sessionClass selectorName:@"sharedSession"]; + SEL selector = NSSelectorFromString(@"requestElementAtPoint:reply:"); + if (nil == session || ![session respondsToSelector:selector]) { + return 0; + } + // The reply is asynchronous, so the wait is bounded. On timeout the box is never read, so a late + // reply cannot race this thread. + NSMutableArray *box = [NSMutableArray array]; + dispatch_semaphore_t finished = dispatch_semaphore_create(0); + typedef void (*RunnerAXElementAtPointMsgSend)(id, SEL, CGPoint, void (^)(id, NSError *)); + RunnerAXElementAtPointMsgSend send = (RunnerAXElementAtPointMsgSend)objc_msgSend; + @try { + send(session, selector, point, ^(id element, NSError *error) { + if (nil != element) { + [box addObject:element]; + } + dispatch_semaphore_signal(finished); + }); + } @catch (NSException *exception) { + return 0; + } + long waited = dispatch_semaphore_wait( + finished, + dispatch_time(DISPATCH_TIME_NOW, (int64_t)(RunnerAXElementAtPointTimeout * NSEC_PER_SEC))); + if (waited != 0 || nil == box.firstObject) { + return 0; + } + return [self integerFrom:box.firstObject selectorName:@"processIdentifier"]; +} + + (id)accessibilityApplicationForApplication:(XCUIApplication *)application axClient:(id)axClient { NSInteger targetProcessID = [self integerFrom:application selectorName:@"processID"]; diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift index 0bee63000a..9dac27ba03 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift @@ -117,6 +117,8 @@ extension RunnerTests { /// Set when `app` is a system surface served in place over the still-bound session app (#2438). var systemSurface: SystemSurfaceHost? = nil var observation: SnapshotObservationPayload? = nil + /// Set when `app` is SpringBoard serving a coordinate tap in place (iOS only). + var servesSpringboard = false } enum ActiveCommandPreparation { @@ -389,7 +391,7 @@ extension RunnerTests { return response case .context(let context): activeApp = context.app - activeAppBundleId = routeToSpringboard + activeAppBundleId = context.servesSpringboard ? Self.springboardBundleId : context.systemSurface?.bundleId ?? mainOwned.bundleId } @@ -532,7 +534,7 @@ extension RunnerTests { #endif } if routeToSpringboard { - return .context(ActiveCommandContext(app: springboard)) + return .context(ActiveCommandContext(app: springboard, servesSpringboard: true)) } switch command.traits.launchPolicy { case .noApp: @@ -581,6 +583,9 @@ extension RunnerTests { // already foreground needs nothing brought forward. return .context(ActiveCommandContext(app: resolveAppWithoutActivation(command: command))) } + if coordinateTapLandsOnSpringboard(command) { + return .context(ActiveCommandContext(app: springboard, servesSpringboard: true)) + } return prepareActivatedTarget(command: command) } } @@ -778,6 +783,33 @@ extension RunnerTests { #endif } + /// A coordinate tap targets the screen. When the session app runs in the background and SpringBoard + /// owns the point (a notification banner, the Home Screen, Control Center), the tap is dispatched + /// there: activating the session app first would change what is under the point (#4655). The owner + /// is the pid of the accessibility hit test at the point, so a point over another app, a point off + /// the screen, or a point the hit test does not answer keeps the activation. A session app that is + /// not running keeps the launch. + @MainActor + private func coordinateTapLandsOnSpringboard(_ command: Command) -> Bool { +#if os(iOS) + guard isCoordinateOnlyTap(command), let x = command.x, let y = command.y else { return false } + let targetState = resolveAppWithoutActivation(command: command).state + guard targetState == .runningBackground || targetState == .runningBackgroundSuspended else { + return false + } + // The hit test waits on the main thread, so a point it cannot answer is not sent to it. + guard let screen = soleDisplayPortraitSize() else { return false } + let point = CGPoint(x: x, y: y) + guard CGRect(origin: .zero, size: screen).contains(point) + || CGRect(x: 0, y: 0, width: screen.height, height: screen.width).contains(point) + else { return false } + guard let springboardPid = Self.processIdentifier(of: springboard) else { return false } + return RunnerAXSnapshotBridge.processIdentifierOfElement(at: point) == springboardPid +#else + return false +#endif + } + private func isCoordinateOnlyTap(_ command: Command) -> Bool { return command.command == .tap && command.text == nil diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandDispatchTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandDispatchTests.swift index ec4be101ea..4737ea9912 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandDispatchTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+CommandDispatchTests.swift @@ -152,18 +152,26 @@ extension RunnerTests { } @MainActor - func testRegularSnapshotStillRepairsBackgroundAndDisclosesPriorState() throws { + private func bindRunnerHostAppInBackground() { app.launch() mainOwned.app = app mainOwned.bundleId = "com.callstack.agentdevice.runner" XCUIDevice.shared.press(.home) XCTAssertTrue(app.wait(for: .runningBackground, timeout: 10)) pendingTargetActivation = nil - defer { - invalidateCachedTarget(reason: "unit_test_cleanup") - pendingTargetActivation = nil - app.terminate() - } + } + + @MainActor + private func unbindRunnerHostApp() { + invalidateCachedTarget(reason: "unit_test_cleanup") + pendingTargetActivation = nil + app.terminate() + } + + @MainActor + func testRegularSnapshotStillRepairsBackgroundAndDisclosesPriorState() throws { + bindRunnerHostAppInBackground() + defer { unbindRunnerHostApp() } let command = try runnerCommandFixture( "{\"command\":\"snapshot\",\"appBundleId\":\"com.callstack.agentdevice.runner\"}" ) @@ -172,10 +180,60 @@ extension RunnerTests { } XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10)) XCTAssertNil(context.observation) + XCTAssertFalse(context.servesSpringboard) XCTAssertEqual(pendingTargetActivation?.priorState, Int(XCUIApplication.State.runningBackground.rawValue)) XCTAssertEqual(pendingTargetActivation?.reason, "stale_target") } + /// A coordinate tap targets the screen: over SpringBoard (here the Home Screen, in the field a + /// notification banner) it runs in place, and activating the background session app first would + /// change what is under the point (#4655). A point the hit test does not answer keeps the repair. + @MainActor + func testCoordinateTapOverSpringboardRunsInPlaceWithoutActivatingTheSessionApp() throws { + bindRunnerHostAppInBackground() + defer { unbindRunnerHostApp() } + let overSpringboard = try runnerCommandFixture( + #"{"command":"tap","commandId":"tap-home","appBundleId":"com.callstack.agentdevice.runner","x":200,"y":400}"# + ) + guard case .context(let context) = prepareActiveCommandContext(command: overSpringboard) else { + return XCTFail("a tap over SpringBoard must prepare a context") + } + XCTAssertTrue(context.app === springboard) + XCTAssertTrue(context.servesSpringboard) + XCTAssertEqual(app.state, .runningBackground) + XCTAssertNil(pendingTargetActivation) + + let offScreen = try runnerCommandFixture( + #"{"command":"tap","commandId":"tap-off-screen","appBundleId":"com.callstack.agentdevice.runner","x":-10000,"y":-10000}"# + ) + guard case .context(let repaired) = prepareActiveCommandContext(command: offScreen) else { + return XCTFail("a tap the hit test does not answer must keep the foreground repair") + } + XCTAssertFalse(repaired.app === springboard) + XCTAssertFalse(repaired.servesSpringboard) + XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10)) + XCTAssertEqual(pendingTargetActivation?.reason, "stale_target") + } + + /// The in-place route is for a session app in the background only: a stopped session app keeps the + /// launch a coordinate tap has always performed, even over the Home Screen. + @MainActor + func testCoordinateTapOverSpringboardStillLaunchesAStoppedSessionApp() throws { + app.terminate() + XCTAssertTrue(app.wait(for: .notRunning, timeout: 10)) + invalidateCachedTarget(reason: "unit_test_setup") + pendingTargetActivation = nil + defer { unbindRunnerHostApp() } + let tap = try runnerCommandFixture( + #"{"command":"tap","commandId":"tap-stopped","appBundleId":"com.callstack.agentdevice.runner","x":200,"y":400}"# + ) + guard case .context(let context) = prepareActiveCommandContext(command: tap) else { + return XCTFail("a tap for a stopped session app must prepare a context") + } + XCTAssertFalse(context.servesSpringboard) + XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10)) + } + @MainActor func testMissingBundleCommandInvalidatesCompleteCachedTargetState() throws { app.launch() diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index e0fa89a950..b682902318 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1966,6 +1966,10 @@ The `snapshot` response carries `targetActivation` and a warning: a `wait ` satisfied on its first poll may re-activate the app without saying so. When it matters, run `snapshot -i` and read its disclosure ([#2694](https://github.com/callstack/agent-device/issues/2694)). +- **A coordinate `press` on a system surface runs in place.** While the session app is in the + background, a `press ` on a point that SpringBoard owns (a notification banner, the Home + Screen, Control Center) reaches that point and does not bring the app back. A point over another + app still brings the session app back first. - **No read launches a stopped app.** `snapshot`, `wait`, `is`, `get`, a reading `find`, and the leading read of `gesture` or a selector `click`/`fill` bring a backgrounded app forward but never start one that is not running, because a launch could drop a URL waiting behind an "Open in …?"