diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift index 3cb00114d1..880e7ad563 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift @@ -4,6 +4,7 @@ extension RunnerTests { enum RunnerAlertSource { case blockingSystemModal case appAlert + case safariDialog case dismissPopup } @@ -12,6 +13,8 @@ extension RunnerTests { let ownerApp: XCUIApplication let buttons: [XCUIElement] let source: RunnerAlertSource + /// The window hosting a SpringBoard modal; nil routes through `ownerApp`. + let window: XCUIElement? } static let defaultAlertCommandTimeout: TimeInterval = 10 @@ -54,6 +57,11 @@ extension RunnerTests { if let alert = firstExistingElement(in: safeElementsQuery { activeApp.alerts.allElementsBoundByIndex }) { return runnerAlert(root: alert, ownerApp: activeApp, source: .appAlert) } + if let dialog = firstExistingElement(in: safeElementsQuery { + activeApp.otherElements.matching(identifier: Self.safariDialogIdentifier).allElementsBoundByIndex + }) { + return runnerAlert(root: dialog, ownerApp: activeApp, source: .safariDialog) + } if let popup = firstDismissPopupWindow(in: activeApp) { return runnerAlert(root: popup, ownerApp: activeApp, source: .dismissPopup) } @@ -162,7 +170,29 @@ extension RunnerTests { ) return } - switch synthesizedTapAt(app: alert.ownerApp, x: frame.midX, y: frame.midY, deadline: deadline) { + var hostContext: SynthesizedCoordinateContext? + if let window = alert.window { + // Never fall back to the owner app's first window: on a foldable it can be another panel. + guard let context = SynthesizedCoordinateContext( + validating: safely("ALERT_WINDOW", CGRect.null) { window.frame }, + resolvedWindow: window, + accessibilityHealth: mainOwned.accessibilityHealth + ) else { + outcome = .unsupported( + message: "alert activation could not read the window hosting the alert", + hint: "Inspect the current alert before deciding whether to act again." + ) + return + } + hostContext = context + } + switch synthesizedTapAt( + app: alert.ownerApp, + x: frame.midX, + y: frame.midY, + context: hostContext, + deadline: deadline + ) { case .performed?: typealias WaitForQuiescence = @convention(c) (NSObject, Selector, Bool) -> Void let waitForQuiescence = unsafeBitCast( @@ -217,7 +247,8 @@ extension RunnerTests { root: modal.root, ownerApp: modal.ownerApp, buttons: buttons, - source: .blockingSystemModal + source: .blockingSystemModal, + window: modal.window ) } @@ -230,13 +261,17 @@ extension RunnerTests { guard !buttons.isEmpty else { return nil } - return RunnerAlert(root: root, ownerApp: ownerApp, buttons: buttons, source: source) + return RunnerAlert(root: root, ownerApp: ownerApp, buttons: buttons, source: source, window: nil) } private func firstExistingElement(in elements: [XCUIElement]) -> XCUIElement? { elements.first { isVisibleElement($0) } } + /// Safari draws its page prompts, such as "Open this page in …?" and JavaScript dialogs, as a + /// view rather than an alert, so they are found by the view's identifier. + static let safariDialogIdentifier = "SFDialogView" + /// The marker is matched inside XCTest's query, so the screen is read once per query. Reading each /// descendant instead costs one round trip per element, and on a screen whose tree changes while /// it is read (a loading web view) each vanished element adds XCTest's retry cycle. `containing` diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift index a010810149..11397272f5 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift @@ -1,4 +1,5 @@ import XCTest +import AgentDeviceSnapshotPresentation extension RunnerTests { func captureAlertPresentation(_ element: XCUIElement) -> RunnerAlertPresentation? { @@ -47,24 +48,26 @@ extension RunnerTests { return Date() < deadline ? observation : .deadlineExceeded } - private func alertSnapshots( + func alertSnapshots( in snapshot: XCUIElementSnapshot, source: RunnerAlertSource, viewport: CGRect ) -> [XCUIElementSnapshot] { let frame = snapshot.frame - let visible = !frame.isNull && !frame.isEmpty && viewport.contains(CGPoint(x: frame.midX, y: frame.midY)) + let hostWindow = snapshot.elementType == .window && SnapshotGeometry.isPositiveFinite(frame) ? frame : viewport let matches: Bool switch source { case .blockingSystemModal: matches = snapshot.elementType == .alert || snapshot.elementType == .sheet case .appAlert: matches = snapshot.elementType == .alert + case .safariDialog: + matches = snapshot.identifier == Self.safariDialogIdentifier case .dismissPopup: matches = snapshot.elementType == .window && containsDismissPopupMarker(snapshot) } - if matches && visible { return [snapshot] } - return snapshot.children.flatMap { alertSnapshots(in: $0, source: source, viewport: viewport) } + if matches && Self.isPlaced(frame, in: hostWindow) { return [snapshot] } + return snapshot.children.flatMap { alertSnapshots(in: $0, source: source, viewport: hostWindow) } } private func containsDismissPopupMarker(_ snapshot: XCUIElementSnapshot) -> Bool { diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift index 687d36d8b8..c3a8bdb701 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift @@ -5,6 +5,8 @@ extension RunnerTests { let root: XCUIElement let ownerApp: XCUIApplication let actions: [XCUIElement] + /// The SpringBoard window hosting `root`; nil for a remote host queried as a whole app. + let window: XCUIElement? } enum BlockingSystemModalResolution { @@ -27,15 +29,16 @@ extension RunnerTests { return .absent } - let springboardActions = actionableElements(in: springboardModal) + let springboardActions = actionableElements(in: springboardModal.root) if !RemoteHostedSystemModalPolicy.shouldProbeRemoteHost( springboardActionCount: springboardActions.count ) { return .resolved( ResolvedBlockingSystemModal( - root: springboardModal, + root: springboardModal.root, ownerApp: springboard, - actions: springboardActions + actions: springboardActions, + window: springboardModal.window ) ) } @@ -64,7 +67,7 @@ extension RunnerTests { // inside actionableElements turn that disappearance into an empty result. let actions = actionableElements(in: host) guard !actions.isEmpty else { continue } - return ResolvedBlockingSystemModal(root: host, ownerApp: host, actions: actions) + return ResolvedBlockingSystemModal(root: host, ownerApp: host, actions: actions, window: nil) } return nil } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift index f78e61809c..99a1a4838c 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift @@ -190,3 +190,19 @@ extension RunnerTests { + " fallbackAttempted=\(fallbackAttempted)" } } + +extension SynthesizedCoordinateContext { + /// Nil when `referenceFrame` is not a finite, non-empty box a point can be placed in. + init?( + validating referenceFrame: CGRect, + resolvedWindow: XCUIElement?, + accessibilityHealth: RunnerAccessibilityHealth + ) { + guard SnapshotGeometry.isPositiveFinite(referenceFrame) else { return nil } + self.init( + referenceFrame: referenceFrame, + resolvedWindow: resolvedWindow, + accessibilityHealth: accessibilityHealth + ) + } +} diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift index 703c9c22eb..b0598958e5 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift @@ -465,13 +465,8 @@ extension RunnerTests { } else { return nil } - guard referenceFrame.width.isFinite, referenceFrame.height.isFinite, - referenceFrame.width > 0, referenceFrame.height > 0 - else { - return nil - } return SynthesizedCoordinateContext( - referenceFrame: referenceFrame, + validating: referenceFrame, resolvedWindow: window, accessibilityHealth: health ) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift index 726759e8d0..41e35882dc 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift @@ -102,17 +102,20 @@ extension RunnerTests { ) } + /// A SpringBoard modal and the window that hosts it. A foldable's SpringBoard has windows on + /// each panel, and `springboard.frame` names only one of them, so the modal is placed against + /// its own window and its activation is routed through that window's display. + struct SpringBoardModal { + let root: XCUIElement + let window: XCUIElement + } + func firstBlockingSystemModal( in springboard: XCUIApplication, deadline: Date = .distantFuture - ) -> XCUIElement? { - let alerts = safeElementsQuery { - springboard.alerts.allElementsBoundByIndex - } - for alert in alerts { - if safeIsBlockingSystemModal(alert, in: springboard) { - return alert - } + ) -> SpringBoardModal? { + if let alert = firstBlockingSystemModal(in: springboard, matching: .alert, deadline: deadline) { + return alert } // Don't start the second (sheet) enumeration once the shared probe deadline is spent (#1244). @@ -121,15 +124,29 @@ extension RunnerTests { return nil } - let sheets = safeElementsQuery { - springboard.sheets.allElementsBoundByIndex + return firstBlockingSystemModal(in: springboard, matching: .sheet, deadline: deadline) + } + + private func firstBlockingSystemModal( + in springboard: XCUIApplication, + matching type: XCUIElement.ElementType, + deadline: Date + ) -> SpringBoardModal? { + let windows = safeElementsQuery { + springboard.windows.containing(type, identifier: nil).allElementsBoundByIndex } - for sheet in sheets { - if safeIsBlockingSystemModal(sheet, in: springboard) { - return sheet + for window in windows { + guard Date() < deadline else { return nil } + let modals = safeElementsQuery { + window.descendants(matching: type).allElementsBoundByIndex + } + for modal in modals { + guard Date() < deadline else { return nil } + if safeIsBlockingSystemModal(modal, in: window) { + return SpringBoardModal(root: modal, window: window) + } } } - return nil } @@ -137,22 +154,19 @@ extension RunnerTests { safely("MODAL_QUERY", [], fetch) } - private func safeIsBlockingSystemModal(_ element: XCUIElement, in springboard: XCUIApplication) -> Bool { - safely("MODAL_CHECK", false) { isBlockingSystemModal(element, in: springboard) } + private func safeIsBlockingSystemModal(_ element: XCUIElement, in window: XCUIElement) -> Bool { + safely("MODAL_CHECK", false) { isBlockingSystemModal(element, in: window) } } - private func isBlockingSystemModal(_ element: XCUIElement, in springboard: XCUIApplication) -> Bool { - guard element.exists else { return false } - let frame = element.frame - if frame.isNull || frame.isEmpty { return false } - - let viewport = springboard.frame - if viewport.isNull || viewport.isEmpty { return false } - - let center = CGPoint(x: frame.midX, y: frame.midY) - if !viewport.contains(center) { return false } + private func isBlockingSystemModal(_ element: XCUIElement, in window: XCUIElement) -> Bool { + element.exists && Self.isPlaced(element.frame, in: window.frame) + } - return true + /// Whether a modal is on screen in the window that hosts it. A foldable's SpringBoard has a + /// window on each panel, and the application frame names only one of them. + static func isPlaced(_ frame: CGRect, in hostWindow: CGRect) -> Bool { + SnapshotGeometry.isPositiveFinite(frame) && SnapshotGeometry.isPositiveFinite(hostWindow) + && hostWindow.contains(CGPoint(x: frame.midX, y: frame.midY)) } func actionableElements(in element: XCUIElement) -> [XCUIElement] { diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift index 87b7bdae2f..ac603efae3 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+AlertObservationTests.swift @@ -294,5 +294,18 @@ extension RunnerTests { XCTAssertEqual(inspection.data?.items?.sorted(), ["Cancel", "OK"]) XCTAssertEqual(app.staticTexts["agent-device-alert-actions"].label, "First actions: 1; replacement actions: 0") } + + @MainActor + func testSafariDialogObservationMatchesOnlyTheDialogView() { + let dialog = ElementAttributesFixture(.other, CGRect(x: 20, y: 300, width: 360, height: 120), identifier: Self.safariDialogIdentifier) + let alert = ElementAttributesFixture(.alert, CGRect(x: 20, y: 500, width: 360, height: 120)) + let page = ElementAttributesFixture(.other, CGRect(x: 0, y: 100, width: 402, height: 600), identifier: "WebView") + let window = ElementAttributesFixture(.window, CGRect(x: 0, y: 0, width: 402, height: 874), children: [page, alert, dialog]) + XCTAssertEqual( + alertSnapshots(in: window, source: .safariDialog, viewport: window.frame).map(\.identifier), + [Self.safariDialogIdentifier] + ) + XCTAssertEqual(alertSnapshots(in: window, source: .appAlert, viewport: window.frame).map(\.elementType), [.alert]) + } #endif } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SystemModalTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SystemModalTests.swift index 8b6fbb8f23..c78c5b46d9 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SystemModalTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SystemModalTests.swift @@ -9,12 +9,27 @@ extension RunnerTests { app.launch() defer { app.terminate() } XCTAssertTrue(app.switches["native-off"].waitForFixtureExistence(timeout: appExistenceTimeout)) - let resolved = ResolvedBlockingSystemModal(root: app, ownerApp: app, actions: actionableElements(in: app)) + let resolved = ResolvedBlockingSystemModal( + root: app, + ownerApp: app, + actions: actionableElements(in: app), + window: nil + ) let payload = try XCTUnwrap(try snapshotForBlockingSystemModal(resolved)) let off = try XCTUnwrap(payload.nodes?.first { $0.identifier == "native-off" }) let on = try XCTUnwrap(payload.nodes?.first { $0.identifier == "native-on" }) XCTAssertEqual(off.value, "0") XCTAssertEqual(on.value, "1") } + + func testSpringBoardModalIsPlacedInItsOwnPanelWindow() { + let outerPanel = CGRect(x: 0, y: 0, width: 466, height: 678) + let innerPanel = CGRect(x: 0, y: 0, width: 951, height: 669) + let innerPanelAlert = CGRect(x: 341, y: 250, width: 270, height: 170) + XCTAssertTrue(Self.isPlaced(innerPanelAlert, in: innerPanel)) + XCTAssertFalse(Self.isPlaced(innerPanelAlert, in: outerPanel)) + XCTAssertFalse(Self.isPlaced(innerPanelAlert, in: CGRect(x: 0, y: 0, width: CGFloat.infinity, height: 669))) + XCTAssertFalse(Self.isPlaced(.zero, in: innerPanel)) + } #endif } diff --git a/src/commands/schema/cli-help-workflows.ts b/src/commands/schema/cli-help-workflows.ts index 8db8856d9b..7958f4b388 100644 --- a/src/commands/schema/cli-help-workflows.ts +++ b/src/commands/schema/cli-help-workflows.ts @@ -124,7 +124,7 @@ Alerts: agent-device alert wait 3000 agent-device alert accept agent-device alert dismiss - Android support is snapshot-derived for runtime permission prompts and native app dialogs. iOS support is runner-derived for XCTest alerts, app-owned modal popups with native blocking markers, and blocking system dialogs. Use cheap alert get for an immediate check; use alert wait only when a prompt may appear after async work. + Android support is snapshot-derived for runtime permission prompts and native app dialogs. iOS support is runner-derived for XCTest alerts, app-owned modal popups with native blocking markers, Safari page prompts such as "Open this page in …?", and blocking system dialogs. Use cheap alert get for an immediate check; use alert wait only when a prompt may appear after async work. If alert says no alert but a sheet is visibly on screen, treat it as app-owned UI: agent-device snapshot -i agent-device press 'label="Allow"' diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 734eef3869..2bf8d26ec2 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -434,7 +434,7 @@ agent-device alert dismiss - `wait_stable_timeout`: the UI did not settle. - Branch on `readableCaptures`, `waitedMs`, `matches`, and `firstMatch` instead of parsing error text. `firstMatch` carries identity and text only; absence failures make no visibility or rect claim. - Polling wait timeouts, and a replayed wait refused with `wait_landmark_identity_mismatch`, also carry `captures`, `readableCaptures`, and `polls` so you can see where the budget went. Each poll has `startedMs`, `durationMs`, and an `outcome`: `readable`, `unreadable`, `retriable`, `deadline`, `runner-restart`, or `readiness`. Long waits keep the first 5 and last 25 polls. A wait that never saw a readable capture reports the error its polls hit, with that error's code and retry details, instead of a generic timeout; `wait stable` and a never-readable strict absence keep their own diagnostics. `logPath` links the full request log. -- `alert` (same as `alert get`) inspects or handles system alerts on iOS simulator, macOS desktop, and Android permission dialogs. On iOS it also covers app-owned modal popups with native blocking markers. The `[timeout]` argument applies to `alert wait` only, on every backend: `alert wait ` takes a budget up to 2147483647 ms (~24.8 days), larger is refused as `INVALID_ARGS` before anything runs, while `get`/`accept`/`dismiss` run their own fixed per-backend budgets and ignore it. +- `alert` (same as `alert get`) inspects or handles system alerts on iOS simulator, macOS desktop, and Android permission dialogs. On iOS it also covers app-owned modal popups with native blocking markers. On the Apple XCUITest runner it also covers Safari's own page prompts, such as "Open this page in …?". The `[timeout]` argument applies to `alert wait` only, on every backend: `alert wait ` takes a budget up to 2147483647 ms (~24.8 days), larger is refused as `INVALID_ARGS` before anything runs, while `get`/`accept`/`dismiss` run their own fixed per-backend budgets and ignore it. - On the snapshot-derived backends (Android, Limrun iOS) `alert get --json` answers with a typed `status`: `visible`, `none`, or `undecided` (an alert-shaped capture that resolves to no single alert). Branch on `status`, not on the message. - On those backends, `alert accept` presses the lasting grant when a permission sheet offers several: Android orders its grants by the platform's own ids (full-access "Allow all", then foreground-only, then always, then the picker-limited "Select photos and videos", then one-time) whatever the button language — this is what makes the Android 14+ partial-media sheet answer "Allow all" — and elsewhere the English label table decides ("while using the app" over "only this time"). Android acts only on the grant ids it declares with a role and a rank; a sheet carrying an allow- or deny-shaped grant id it does not declare (a vendor fork's own button, or a newer Android grant) is refused for both `accept` and `dismiss` — `dismiss` answers with the Back key, the cancel that grants nothing. A sheet whose choices no rank orders — or that names the same choice at two points — is refused with `alert_button_undecided` and `dispatched: no`, never pressed by position; read the labels with `alert get` and press your choice by label/ref. - On those backends, when `alert accept`/`dismiss` fails before pressing anything, `error.details.reason` names why (a capture or transport failure that is not a driver refusal may instead surface as its own error without a `reason`). A budget never cancels a running capture or press: it only ends the polling loop, so every check that started inside the budget finishes and counts. Before any press, `dispatched: no` and the reason is `alert-not-found` (the action budget ended with no alert on screen), `alert_capture_undecided`, or `alert_button_undecided` (the sheet is too ambiguous to act on). After a press, `dispatched` is absent and the reason is `alert-window-expired`; “did not dismiss the visible alert” means the latest post-press capture that answered named the same dialog again, “could not be confirmed” means the press went out but the latest read was unresolvable or never answered, so the dialog may already be gone. If you cancel the request at any point from the press onward — the tap in flight, or the post-press checks — the cancellation reports `dispatched: unknown`: the device may already have received the tap. The one exception is a cancel whose post-press check nevertheless finished and proved the alert gone; then the command reports the handled alert, because the outcome is known. Run `alert get` before acting again.