Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
enum RunnerAlertSource {
case blockingSystemModal
case appAlert
case safariDialog
case dismissPopup
}

Expand All @@ -12,6 +13,8 @@
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
Expand Down Expand Up @@ -54,6 +57,11 @@
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)
}
Expand Down Expand Up @@ -162,7 +170,29 @@
)
return
}
switch synthesizedTapAt(app: alert.ownerApp, x: frame.midX, y: frame.midY, deadline: deadline) {
var hostContext: SynthesizedCoordinateContext?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Nit · New alert-activation failure path has no test

activateAlertButton gains a new refusal: when alert.window is set but its frame read fails (safely("ALERT_WINDOW", CGRect.null) yields a non-positive-finite box), the command returns .unsupported("alert activation could not read the window hosting the alert") instead of tapping. The sibling pre-synthesis refusal in the same function (missing _waitForQuiescenceAsPreEvent:) and the deadline paths are pinned by RunnerTests+AlertObservationTests, but this new branch is not, and the file already carries the stubbing hooks (alertResolutionOverrideForTesting, AlertTapDeadlineStub) needed to reach it.

Suggested change

Add a unit test that resolves an alert whose window frame read throws or returns CGRect.null and asserts the unsupported outcome and that no tap was synthesized.

Details

persona: javascript

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

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
}

Check notice on line 188 in apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

nit: New alert-activation failure path has no test

`activateAlertButton` gains a new refusal: when `alert.window` is set but its frame read fails (`safely("ALERT_WINDOW", CGRect.null)` yields a non-positive-finite box), the command returns `.unsupported("alert activation could not read the window hosting the alert")` instead of tapping. The sibling pre-synthesis refusal in the same function (missing `_waitForQuiescenceAsPreEvent:`) and the deadline paths are pinned by `RunnerTests+AlertObservationTests`, but this new branch is not, and the file already carries the stubbing hooks (`alertResolutionOverrideForTesting`, `AlertTapDeadlineStub`) needed to reach it.
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(
Expand Down Expand Up @@ -217,7 +247,8 @@
root: modal.root,
ownerApp: modal.ownerApp,
buttons: buttons,
source: .blockingSystemModal
source: .blockingSystemModal,
window: modal.window
)
}

Expand All @@ -230,13 +261,17 @@
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`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
func captureAlertPresentation(_ element: XCUIElement) -> RunnerAlertPresentation? {
Expand Down Expand Up @@ -47,24 +48,26 @@
return Date() < deadline ? observation : .deadlineExceeded
}

private func alertSnapshots(
func alertSnapshots(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Minor · hostWindow widens from a placement check to an origin for every window-shaped snapshot

In alertSnapshots the host frame is taken from any snapshot whose elementType is .window, but .window is also the matching shape for .dismissPopup, and the recursion now overwrites viewport with that frame for all children. Two consequences: (1) a popup window that matches .dismissPopup is measured against its own frame, so isPlaced is self-referential and always true — the old viewport.contains(center) rejection of a window sitting outside the app's reported frame (a zero-height or off-panel SpringBoard window) is gone; (2) once one window frame is adopted it is never restored for sibling branches, and on the Duo SpringBoard's first window is the 223x317 status-bar window this PR's own description names, so modals below it are checked against that tiny box, or against a window frame on the wrong panel, and are dropped as not placed. Pass the viewport down unchanged and use the window frame only as the host for the one snapshot that is the window.

Suggested change

Keep viewport as the parameter passed to the recursive call, and compare a window-shaped snapshot against the viewport while comparing its descendants against that window's frame.

Details

persona: maintainability

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 Major · Placement guard for a dismiss-popup window is self-referential and can never reject a candidate

alertSnapshots now derives the containment box from the node being matched: for a .window snapshot with a positive finite frame, hostWindow = snapshot.frame (line 57). The .dismissPopup case matches only snapshot.elementType == .window (line 67), so whenever that match succeeds the box the node is tested against is the node's own frame, and Self.isPlaced(frame, in: frame) (line 69) is true for every positive finite frame — a rectangle's center is always inside it. The visibility read the predecessor had, viewport.contains(center) against the owner app's snapshot frame, is therefore gone for exactly the one source whose candidate is a window: no marked window can be refused for placement any more, including one offset off screen or on the foldable's other panel, and the recursion also hands every descendant that new per-window box.

Suggested change
let hostWindow = snapshot.elementType == .window && SnapshotGeometry.isPositiveFinite(frame) ? frame : viewport
func alertSnapshots(
in snapshot: XCUIElementSnapshot,
source: RunnerAlertSource,
viewport: CGRect
) -> [XCUIElementSnapshot] {
let frame = snapshot.frame
let isWindow = snapshot.elementType == .window && SnapshotGeometry.isPositiveFinite(frame)
let hostWindow = isWindow ? frame : viewport
// A window candidate is placed against the box it was enumerated in, never against itself.
let placementBox = (isWindow && source == .dismissPopup) ? viewport : hostWindow
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 = isWindow && containsDismissPopupMarker(snapshot)
}
if matches && Self.isPlaced(frame, in: placementBox) { return [snapshot] }
return snapshot.children.flatMap { alertSnapshots(in: $0, source: source, viewport: hostWindow) }
}

Suggested change

Keep the placement test anchored to the viewport the candidate was enumerated against when the candidate itself is the host window: pass the incoming viewport (not the node's own frame) as the box for the .dismissPopup window match, or track the outermost/owner viewport separately so a window candidate is still tested against the app's visible frame.

Details

Failing sequence: alert dismiss on a popup whose owner app's snapshot still carries a marked window outside the visible panel (a popover window SpringBoard/app keeps off-panel or at an offset position, which is what this PR's Duo work shows exists). Before, that window failed the viewport test, the walk found no candidate, the observation was .absent, and the command returned dismissed. Now it is a candidate whose presentation is unchanged, so the verification loop at RunnerTests+Alert.swift:124-137 spins on .stillVisible to the deadline and answers ALERT_DEADLINE_EXCEEDED / INTERACTION_FAILED with activated: true after the tap already went out. Two such windows (one per panel) additionally trip guard candidates.count <= 1 at line 45 and make the whole observation unavailable (ALERT_CONFIRMATION_UNAVAILABLE). No test covers .dismissPopup placement through this path; the new test in RunnerTests+AlertObservationTests.swift covers only .safariDialog and .appAlert.

Also raised here

Also raised at this location by swift-ios: Placement gate in alertSnapshots is vacuous for the .dismissPopup source — alertSnapshots now computes hostWindow as the snapshot's own frame whenever snapshot.elementType == .window and that frame is positive-finite (RunnerTests+AlertObservation.swift:57), and then requires Self.isPlaced(frame, in: hostWindow) (line 69). For source == .dismissPopup, matches is true only when snapshot.elementType == .window && containsDismissPopupMarker(snapshot) (lines 66-67) — i.e. the only snapshots that can match are exactly the ones for which hostWindow was just set to their own frame. The containment test therefore compares a window's center with its own rect and can never fail; isPlaced reduces to SnapshotGeometry.isPositiveFinite(frame), which is already the first clause. The predecessor passed the application snapshot frame down unchanged, so a dismiss-popup window whose center fell outside the app frame was refused as not visible. …

persona: swift-ios, senior-developer

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

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) }

Check failure on line 70 in apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

major: Placement guard for a dismiss-popup window is self-referential and can never reject a candidate

`alertSnapshots` now derives the containment box from the node being matched: for a `.window` snapshot with a positive finite frame, `hostWindow = snapshot.frame` (line 57). The `.dismissPopup` case matches only `snapshot.elementType == .window` (line 67), so whenever that match succeeds the box the node is tested against is the node's own frame, and `Self.isPlaced(frame, in: frame)` (line 69) is true for every positive finite frame — a rectangle's center is always inside it. The visibility read the predecessor had, `viewport.contains(center)` against the owner app's snapshot frame, is therefore gone for exactly the one source whose candidate is a window: no marked window can be refused for placement any more, including one offset off screen or on the foldable's other panel, and the recursion also hands every descendant that new per-window box. Failing sequence: `alert dismiss` on a popup whose owner app's snapshot still carries a marked window outside the visible panel (a popover window SpringBoard/app keeps off-panel or at an offset position, which is what this PR's Duo work shows exists). Before, that window failed the viewport test, the walk found no candidate, the observation was `.absent`, and the command returned `dismissed`. Now it is a candidate whose presentation is unchanged, so the verification loop at RunnerTests+Alert.swift:124-137 spins on `.stillVisible` to the deadline and answers `ALERT_DEADLINE_EXCEEDED` / `INTERACTION_FAILED` with `activated: true` after the tap already went out. Two such windows (one per panel) additionally trip `guard candidates.count <= 1` at line 45 and make the whole observation unavailable (`ALERT_CONFIRMATION_UNAVAILABLE`). No test covers `.dismissPopup` placement through this path; the new test in RunnerTests+AlertObservationTests.swift covers only `.safariDialog` and `.appAlert`. ### Also raised here Also raised at this location by swift-ios: Placement gate in alertSnapshots is vacuous for the .dismissPopup source — …

Check warning on line 70 in apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: hostWindow widens from a placement check to an origin for every window-shaped snapshot

In alertSnapshots the host frame is taken from any snapshot whose elementType is .window, but .window is also the matching shape for .dismissPopup, and the recursion now overwrites `viewport` with that frame for all children. Two consequences: (1) a popup window that matches `.dismissPopup` is measured against its own frame, so isPlaced is self-referential and always true — the old `viewport.contains(center)` rejection of a window sitting outside the app's reported frame (a zero-height or off-panel SpringBoard window) is gone; (2) once one window frame is adopted it is never restored for sibling branches, and on the Duo SpringBoard's first window is the 223x317 status-bar window this PR's own description names, so modals below it are checked against that tiny box, or against a window frame on the wrong panel, and are dropped as not placed. Pass the viewport down unchanged and use the window frame only as the host for the one snapshot that is the window.
}

private func containsDismissPopupMarker(_ snapshot: XCUIElementSnapshot) -> Bool {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
)
)
}
Expand Down Expand Up @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,19 @@
+ " fallbackAttempted=\(fallbackAttempted)"
}
}

extension SynthesizedCoordinateContext {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Nit · SynthesizedCoordinateContext now validates with a stricter box guard than the code it replaced

The inline guard in synthesizedCoordinateContext (isFinite + width/height > 0) was replaced by SnapshotGeometry.isPositiveFinite (RunnerTests+SynthesizedGesturePolicy.swift:201). The new guard also refuses CGRect.infinite and a finite box whose maxX/maxY overflow, and it checks all four coordinates' finiteness, not just the extents. That is a behavior change on the shared coordinate route: a previously accepted reference frame now yields nil, i.e. synthesizedTapAt answers "could not resolve an app window with a finite screen frame". The change is in the safer direction and matches the kernel/Swift twin rule cited in SnapshotGeometry.swift, but it is worth one comment saying the shared route intentionally uses the stricter box guard, since the two guards are not equivalent.

Details

persona: senior-developer

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

/// 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
)
}
}

Check notice on line 208 in apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

nit: SynthesizedCoordinateContext now validates with a stricter box guard than the code it replaced

The inline guard in `synthesizedCoordinateContext` (isFinite + width/height > 0) was replaced by `SnapshotGeometry.isPositiveFinite` (RunnerTests+SynthesizedGesturePolicy.swift:201). The new guard also refuses `CGRect.infinite` and a finite box whose `maxX`/`maxY` overflow, and it checks all four coordinates' finiteness, not just the extents. That is a behavior change on the shared coordinate route: a previously accepted reference frame now yields `nil`, i.e. `synthesizedTapAt` answers "could not resolve an app window with a finite screen frame". The change is in the safer direction and matches the kernel/Swift twin rule cited in SnapshotGeometry.swift, but it is worth one comment saying the shared route intentionally uses the stricter box guard, since the two guards are not equivalent.
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,17 +102,20 @@
)
}

/// 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).
Expand All @@ -121,38 +124,49 @@
return nil
}

let sheets = safeElementsQuery {
springboard.sheets.allElementsBoundByIndex
return firstBlockingSystemModal(in: springboard, matching: .sheet, deadline: deadline)
}

private func firstBlockingSystemModal(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Minor · Blocking system modal discovery now requires the modal to sit inside a SpringBoard window

firstBlockingSystemModal used to enumerate springboard.alerts / springboard.sheets directly, so any alert- or sheet-shaped element in SpringBoard's tree was a candidate regardless of where it sat. The replacement enumerates springboard.windows.containing(type, identifier: nil) and then window.descendants(matching: type), so a modal that XCTest surfaces directly under the application element (not under a windows child) is now invisible to the probe, and alert get/accept/dismiss and the blocking-system-modal snapshot report ALERT_NOT_FOUND/nil for it. This is the same discovery path the alert command's public iOS behavior depends on, so a regression here is user-visible. The PR's device validation covered SpringBoard openurl prompts only; no unit or fixture test pins a modal outside a window (the new test exercises only Self.isPlaced). If the window-nested assumption is intended, the probe should keep a fallback over springboard.alerts/sheets when no window candidate matches, and the assumption should be stated in the comment above SpringBoardModal.

Suggested change

Confirm on a device that every SpringBoard modal the probe previously matched is nested under a windows child; otherwise add a fallback to the old springboard.alerts/springboard.sheets enumeration when no window-hosted candidate resolves, and add a fixture test for a modal that is not under a window.

Details

Also raised here

Also raised at this location by senior-developer: Unanswered launch confirmations are no longer surfaced when the panel window names no alert or sheet — firstBlockingSystemModal changed the enumeration from the app-level queries springboard.alerts / springboard.sheets to springboard.windows.containing(type, identifier: nil) (line 136) and only then reads window.descendants(matching: type). A modal that XCTest reports through app.alerts/app.sheets but that is not a descendant of a window node — or sits in a window whose own frame is null/empty, which isBlockingSystemModal then refuses via isPlaced (line 162, 168) — is no longer found at all. The predecessor tested the element's center against springboard.frame and had no window prerequisite, so such a modal was resolved. This regresses the behavior commit 3d91901 ("report the alert's own title and surface an unanswered launch confirmation", #​3732) added: an unanswered launch confirmation must be surfaced, and with it the caller now gets ALERT_NOT_FOUND on a screen that visibly blocks the device. …

persona: javascript, senior-developer

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

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
}

Check warning on line 151 in apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: Blocking system modal discovery now requires the modal to sit inside a SpringBoard window

`firstBlockingSystemModal` used to enumerate `springboard.alerts` / `springboard.sheets` directly, so any alert- or sheet-shaped element in SpringBoard's tree was a candidate regardless of where it sat. The replacement enumerates `springboard.windows.containing(type, identifier: nil)` and then `window.descendants(matching: type)`, so a modal that XCTest surfaces directly under the application element (not under a `windows` child) is now invisible to the probe, and `alert get`/`accept`/`dismiss` and the blocking-system-modal snapshot report `ALERT_NOT_FOUND`/nil for it. This is the same discovery path the `alert` command's public iOS behavior depends on, so a regression here is user-visible. The PR's device validation covered SpringBoard `openurl` prompts only; no unit or fixture test pins a modal outside a window (the new test exercises only `Self.isPlaced`). If the window-nested assumption is intended, the probe should keep a fallback over `springboard.alerts`/`sheets` when no window candidate matches, and the assumption should be stated in the comment above `SpringBoardModal`. ### Also raised here Also raised at this location by senior-developer: Unanswered launch confirmations are no longer surfaced when the panel window names no alert or sheet — `firstBlockingSystemModal` changed the enumeration from the app-level queries `springboard.alerts` / `springboard.sheets` to `springboard.windows.containing(type, identifier: nil)` (line 136) and only then reads `window.descendants(matching: type)`. A modal that XCTest reports through `app.alerts`/`app.sheets` but that is not a _descendant of a window node_ — or sits in a window whose own frame is null/empty, which `isBlockingSystemModal` then refuses via `isPlaced` (line 162, 168) — is no longer found at all. The predecessor tested the element's center against `springboard.frame` and had no window prerequisite, so such a modal was resolved. This regresses the behavior commit 3d91901 ("report the alert's own title and…

func safeElementsQuery(_ fetch: () -> [XCUIElement]) -> [XCUIElement] {
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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Nit · isBlockingSystemModal keeps its name after becoming a placement test

Renaming the parameter from springboard to window and replacing the three guard clauses with one isPlaced call leaves the name promising more than the function now decides: existence and placement only, nothing about modality or blocking. safeIsBlockingSystemModal and firstBlockingSystemModal inherit the same drift two layers up.

Suggested change

Rename to something like isPresentedInWindow (and the same for the safe/first… wrappers) or state in the doc comment that blocking-ness is decided by the caller.

Details

persona: maintainability

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if this is wrong — I will re-check the cited code.

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

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))

Check notice on line 169 in apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

nit: isBlockingSystemModal keeps its name after becoming a placement test

Renaming the parameter from `springboard` to `window` and replacing the three guard clauses with one `isPlaced` call leaves the name promising more than the function now decides: existence and placement only, nothing about modality or blocking. `safeIsBlockingSystemModal` and `firstBlockingSystemModal` inherit the same drift two layers up.
}

func actionableElements(in element: XCUIElement) -> [XCUIElement] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion src/commands/schema/cli-help-workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <short-ms> 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 <short-ms> 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"'
Expand Down
2 changes: 1 addition & 1 deletion website/docs/docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <ms>` 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 <ms>` 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.
Expand Down
Loading