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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .oxfmtrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// One entry per line, so each pinned runner request changes as one reviewable diff line.
"contracts/fixtures/runner-requests.json",
// One captured node per line, so the real keyboard capture stays a compact reviewable table.
"packages/capture-kit/src/snapshot-chrome.fixtures.ts"
"packages/capture-kit/src/snapshot-chrome.fixtures.ts",
// One recorded node per line, so a recapture reads as a reviewable diff of changed nodes.
"apple/snapshot-presentation/Tests/AlertSurfaceCorpus/*.json"
]
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
struct RunnerAlertPresentation: Equatable {
let title: String
let content: [String]
let buttons: [String]
}
import AgentDeviceSnapshotPresentation

enum RunnerAlertObservation {
case visible(RunnerAlertPresentation)
case visible(AlertSurfacePresentation)
case absent
case unavailable
case deadlineExceeded
Expand All @@ -19,7 +15,7 @@ enum RunnerAlertVerification: Equatable {
case timedOut

static func verify(
original: RunnerAlertPresentation,
original: AlertSurfacePresentation,
observation: RunnerAlertObservation
) -> RunnerAlertVerification {
switch observation {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
enum RunnerAlertSource {
case blockingSystemModal
case appAlert
case safariDialog
case dismissPopup
}

struct RunnerAlert {
let root: XCUIElement
let ownerApp: XCUIApplication
let buttons: [XCUIElement]
let source: RunnerAlertSource
let source: AlertSurfaceSource
/// The window hosting a SpringBoard modal; nil routes through `ownerApp`.
let window: XCUIElement?
}
Expand Down Expand Up @@ -58,7 +52,7 @@ extension RunnerTests {
return runnerAlert(root: alert, ownerApp: activeApp, source: .appAlert)
}
if let dialog = firstExistingElement(in: safeElementsQuery {
activeApp.otherElements.matching(identifier: Self.safariDialogIdentifier).allElementsBoundByIndex
activeApp.otherElements.matching(identifier: AlertSurface.safariDialogIdentifier).allElementsBoundByIndex
}) {
return runnerAlert(root: dialog, ownerApp: activeApp, source: .safariDialog)
}
Expand Down Expand Up @@ -255,7 +249,7 @@ extension RunnerTests {
private func runnerAlert(
root: XCUIElement,
ownerApp: XCUIApplication,
source: RunnerAlertSource
source: AlertSurfaceSource
) -> RunnerAlert? {
let buttons = actionableElements(in: root).filter { isEnabledElement($0) }
guard !buttons.isEmpty else {
Expand All @@ -268,10 +262,6 @@ extension RunnerTests {
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 All @@ -282,15 +272,11 @@ extension RunnerTests {
})
}

/// The one definition of a popover's dismiss region: a label or identifier that reads "dismiss
/// popup", in any case, with any surrounding whitespace. XCTest queries take it as a format predicate.
private static let dismissPopupMarkerPattern = #"\s*dismiss popup\s*"#
private static let dismissPopupMarker = NSPredicate(
format: "label MATCHES[c] %@ OR identifier MATCHES[c] %@",
dismissPopupMarkerPattern,
dismissPopupMarkerPattern
AlertSurface.dismissPopupMarkerPattern,
AlertSurface.dismissPopupMarkerPattern
)
private static let dismissPopupMarkerText = NSPredicate(format: "SELF MATCHES[c] %@", dismissPopupMarkerPattern)

// Internal, not private: the dismiss-popup wiring is pinned by
// RunnerTests+AlertTests, and the label rule itself by RunnerAlertButtonChoice.
Expand Down Expand Up @@ -349,7 +335,7 @@ extension RunnerTests {

private func isGenericAlertLabel(_ label: String) -> Bool {
let normalized = label.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return isDismissPopupMarker(normalized) ||
return AlertSurface.isDismissPopupMarker(normalized) ||
normalized.hasPrefix("vertical scroll bar") ||
normalized.hasPrefix("horizontal scroll bar") ||
normalized == "tab bar"
Expand Down Expand Up @@ -399,8 +385,4 @@ extension RunnerTests {
})
return hittable
}

func isDismissPopupMarker(_ text: String) -> Bool {
Self.dismissPopupMarkerText.evaluate(with: text)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@
import AgentDeviceSnapshotPresentation

extension RunnerTests {
func captureAlertPresentation(_ element: XCUIElement) -> RunnerAlertPresentation? {
var presentation: RunnerAlertPresentation?
func captureAlertPresentation(_ element: XCUIElement) -> AlertSurfacePresentation? {
var presentation: AlertSurfacePresentation?
_ = RunnerObjCExceptionCatcher.catchException {
guard let snapshot = try? element.snapshot() else { return }
presentation = self.alertPresentation(snapshot)
presentation = AlertSurface.presentation(of: self.alertSurfaceNode(snapshot))
}
return presentation
}

func observeAlert(
in ownerApp: XCUIApplication,
source: RunnerAlertSource,
source: AlertSurfaceSource,
observesApplicationRoot: Bool,
deadline: Date
) -> RunnerAlertObservation {
Expand All @@ -37,62 +37,33 @@
}
guard Date() < deadline, let snapshot = try? ownerApp.snapshot(),
!snapshot.children.isEmpty, !snapshot.frame.isNull, !snapshot.frame.isEmpty else { return }
let root = self.alertSurfaceNode(snapshot)

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 · observeAlert converts the whole snapshot tree into AlertSurfaceNode structs on every verification poll

observeAlert now builds an AlertSurfaceNode for every node of the owner app's snapshot tree (alertSurfaceNode(snapshot) at RunnerTests+AlertObservation.swift:40) before it applies any rule, and handleAlert re-runs observeAlert in a loop every 0.2 s until the deadline (while true at RunnerTests+Alert.swift:118-131). The predecessor walked XCUIElementSnapshot in place, so the only allocation was the [XCUIElementSnapshot] candidate array, and it stopped recursing once a match was found. Each converted node allocates a struct holding two Swift Strings (identifier, label) plus a children array, so a SpringBoard tree of the size in the corpus (254 nodes, many with long labels) is deep-copied on each poll for the whole alert budget — up to ~50 full-tree copies for the default 10 s defaultAlertCommandTimeout, all on the main actor while the app is still settling. captureAlertPresentation pays the same conversion once per alert accept. Nothing is incorrect today; the cost is new and it lands on the slow path the surrounding comments already care about (a starved host delaying reads). AlertSurface.candidates could take the snapshot tree through a protocol/accessor, or the conversion could stop descending once a candidate is found.

Suggested change

Avoid rebuilding the whole tree as AlertSurfaceNode per observation poll: either give AlertSurface a view over XCUIElementSnapshot, or reuse one conversion across the verification loop when the tree is unchanged.

Details

persona: swift-ios

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 observesApplicationRoot {
observation = .visible(self.alertPresentation(snapshot))
observation = .visible(AlertSurface.presentation(of: root))
return
}
let candidates = self.alertSnapshots(in: snapshot, source: source, viewport: snapshot.frame)
let candidates = AlertSurface.candidates(in: root, source: source, viewport: root.frame)

Check notice on line 45 in apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AlertObservation.swift

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

nit: observeAlert converts the whole snapshot tree into AlertSurfaceNode structs on every verification poll

`observeAlert` now builds an `AlertSurfaceNode` for every node of the owner app's snapshot tree (`alertSurfaceNode(snapshot)` at RunnerTests+AlertObservation.swift:40) before it applies any rule, and `handleAlert` re-runs `observeAlert` in a loop every 0.2 s until the deadline (`while true` at RunnerTests+Alert.swift:118-131). The predecessor walked `XCUIElementSnapshot` in place, so the only allocation was the `[XCUIElementSnapshot]` candidate array, and it stopped recursing once a match was found. Each converted node allocates a struct holding two Swift `String`s (identifier, label) plus a children array, so a SpringBoard tree of the size in the corpus (254 nodes, many with long labels) is deep-copied on each poll for the whole alert budget — up to \~50 full-tree copies for the default 10 s `defaultAlertCommandTimeout`, all on the main actor while the app is still settling. `captureAlertPresentation` pays the same conversion once per `alert accept`. Nothing is incorrect today; the cost is new and it lands on the slow path the surrounding comments already care about (a starved host delaying reads). `AlertSurface.candidates` could take the snapshot tree through a protocol/accessor, or the conversion could stop descending once a candidate is found.
guard candidates.count <= 1 else { return }
observation = candidates.first.map { .visible(self.alertPresentation($0)) } ?? .absent
observation = candidates.first.map { .visible(AlertSurface.presentation(of: $0)) } ?? .absent
}
return Date() < deadline ? observation : .deadlineExceeded
}

func alertSnapshots(
in snapshot: XCUIElementSnapshot,
source: RunnerAlertSource,
viewport: CGRect
) -> [XCUIElementSnapshot] {
let frame = snapshot.frame
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)
/// The tree the alert rules read. Snapshot output has no names for alerts and sheets, so the
/// rules name them here.
func alertSurfaceNode(_ snapshot: XCUIElementSnapshot) -> AlertSurfaceNode {
let type: String
switch snapshot.elementType {
case .alert: type = "Alert"
case .sheet: type = "Sheet"
default: type = elementTypeName(snapshot.elementType)
}
if matches && Self.isPlaced(frame, in: viewport) { return [snapshot] }
// A window is placed in the box it sits in, and is itself the box of what it hosts.
let childViewport = snapshot.elementType == .window && SnapshotGeometry.isPositiveFinite(frame) ? frame : viewport
return snapshot.children.flatMap { alertSnapshots(in: $0, source: source, viewport: childViewport) }
}

private func containsDismissPopupMarker(_ snapshot: XCUIElementSnapshot) -> Bool {
[snapshot.label, snapshot.identifier].contains { isDismissPopupMarker($0) } ||
snapshot.children.contains { containsDismissPopupMarker($0) }
}

private func alertPresentation(_ snapshot: XCUIElementSnapshot) -> RunnerAlertPresentation {
var content: [String] = []
var buttons: [String] = []
func collect(_ node: XCUIElementSnapshot) {
let label = node.label.trimmingCharacters(in: .whitespacesAndNewlines)
if actionableTypes.contains(node.elementType) {
buttons.append(label)
} else if !label.isEmpty {
content.append(label)
}
node.children.forEach(collect)
}
snapshot.children.forEach(collect)
return RunnerAlertPresentation(
title: snapshot.label.trimmingCharacters(in: .whitespacesAndNewlines),
content: content,
buttons: buttons
return AlertSurfaceNode(
type: type,
identifier: snapshot.identifier,
label: snapshot.label,
frame: snapshot.frame,
children: snapshot.children.map { alertSurfaceNode($0) }
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,7 @@ extension RunnerTests {
}

private func isBlockingSystemModal(_ element: XCUIElement, in window: XCUIElement) -> Bool {
element.exists && Self.isPlaced(element.frame, in: window.frame)
}

/// 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))
element.exists && AlertSurface.isPlaced(element.frame, in: window.frame)
}

func actionableElements(in element: XCUIElement) -> [XCUIElement] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,15 +235,11 @@
var textInputProbeIssues: TextInputProbeIssues?
let suppressedIssueLock = NSLock()
var suppressedAxSnapshotIssueCount = 0
// Keep blocker actions narrow to avoid false positives from generic hittable containers.
let actionableTypes: Set<XCUIElement.ElementType> = [
.button,
.cell,
.link,
.menuItem,
.checkBox,
.switch
]
let actionableTypes: Set<XCUIElement.ElementType> = Set(

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 · Runner actionableTypes silently drops any shared name its own raw-value table lacks

actionableTypes is rebuilt by looking AlertSurface.actionableTypes names up in RunnerTests.elementTypeNamesByRawValue (RunnerTests+Snapshot.swift:78), a runner-local table. The match is stringly typed and compactMap drops every miss without a signal: add "RadioButton", "Toggle" or "Link"-like names to the shared AlertSurface.actionableTypes in apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/AlertSurface.swift:52, and the runner's set loses that type in silence. Consequence: actionableElements(in:) and firstAlertText stop treating that element as an action, so RunnerAlert.buttons can end up with no button for a real prompt while the corpus's AlertSurface.presentation(of:) still reports it as a button — the two readers of one rule diverge, which is the drift this PR exists to remove. Nothing in the checkout asserts the pair agrees: no test feeds AlertSurface.actionableTypes through elementTypeNamesByRawValue and asserts the result has the same count.

Suggested change
let actionableTypes: Set<XCUIElement.ElementType> = Set(
let actionableTypes: Set<XCUIElement.ElementType> = Set(
AlertSurface.actionableTypes.compactMap { name in
RunnerTests.elementTypeNamesByRawValue.first { $0.value == name }?.key.map(XCUIElement.ElementType.init(rawValue:))
}.compactMap { $0 }
)

Suggested change

Assert the invariant instead of trusting it: a unit test that every name in AlertSurface.actionableTypes appears in RunnerTests.elementTypeNamesByRawValue.values (and that the derived set has AlertSurface.actionableTypes.count members), so a new shared type either resolves or fails the test.

Details

Also raised here

Also raised at this location by senior-developer: Runner actionableTypes now depends on unenforced string equality between two tables — RunnerTests.actionableTypes used to be a literal Set<XCUIElement.ElementType> of .button, .cell, .link, .menuItem, .checkBox, .switch, which the compiler checked. It is now rebuilt by looking up AlertSurface.actionableTypes (the Swift package's Set<String>: ["Button", "Cell", "Link", "MenuItem", "CheckBox", "Switch"]) inside RunnerTests.elementTypeNamesByRawValue and converting each raw value back with XCUIElement.ElementType(rawValue:). The set is only complete while three unrelated tables agree exactly, case-sensitively: AlertSurface.actionableTypes (apple/snapshot-presentation/Sources/.../AlertSurface.swift:54) XCUIElement.ElementType(rawValue:) accepting those raw values again Nothing enforces that agreement. …

Also raised at this location by swift-ios: actionableTypes now derived through string names, so a name divergence silently drops an element type — RunnerTests.actionableTypes was a literal set of six XCUIElement.ElementType values. It is now rebuilt by matching AlertSurface.actionableTypes (strings) against elementTypeNamesByRawValue and converting the raw value back. The two sides agree only because the strings in AlertSurface.swift:54 ("Button", "Cell", "Link", "MenuItem", "CheckBox", "Switch") all happen to appear in the raw-value table at RunnerTests+Snapshot.swift:78-111, and nothing enforces that. If AlertSurface.actionableTypes gains a name the table lacks (or a table entry is renamed), compactMap yields nil for it and that element type silently disappears from actionableTypes — used by actionableElements(in:) (RunnerTests+SystemModal.swift:168), the modal-button filter at RunnerTests+SystemModal.swift:179 and firstAlertText (RunnerTests+Alert.swift:328). …

Also raised at this location by maintainability: RunnerTests.actionableTypes is now derived from a name table with nothing pinning the six names — RunnerTests.swift:238-242 replaces the literal [.button, .cell, .link, .menuItem, .checkBox, .switch] with a round trip rawValue -> name in RunnerTests.elementTypeNamesByRawValue -> AlertSurface.actionableTypes -> XCUIElement.ElementType(rawValue:). The set is only the old six if that table spells all six exactly Button, Cell, Link, MenuItem, CheckBox, Switch. A name change or a missing raw value in the table drops that type from actionableTypes with no compile error and no failing assertion, and the corpus cannot catch it: alertSurfaceNode builds the type string through the same table, so a missing entry (the Element(N) spellings in the fixtures) is invisible to both sides. Buttons then land in content instead of buttons, so the presentation the runner compares after a tap changes and alert verification misreports.

persona: javascript, senior-developer, swift-ios, 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.

RunnerTests.elementTypeNamesByRawValue.compactMap { rawValue, name in
AlertSurface.actionableTypes.contains(name) ? XCUIElement.ElementType(rawValue: rawValue) : nil
}
)

Check warning on line 242 in apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: Runner `actionableTypes` silently drops any shared name its own raw-value table lacks

`actionableTypes` is rebuilt by looking `AlertSurface.actionableTypes` names up in `RunnerTests.elementTypeNamesByRawValue` (`RunnerTests+Snapshot.swift:78`), a runner-local table. The match is stringly typed and `compactMap` drops every miss without a signal: add `"RadioButton"`, `"Toggle"` or `"Link"`-like names to the shared `AlertSurface.actionableTypes` in `apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/AlertSurface.swift:52`, and the runner's set loses that type in silence. Consequence: `actionableElements(in:)` and `firstAlertText` stop treating that element as an action, so `RunnerAlert.buttons` can end up with no button for a real prompt while the corpus's `AlertSurface.presentation(of:)` still reports it as a button — the two readers of one rule diverge, which is the drift this PR exists to remove. Nothing in the checkout asserts the pair agrees: no test feeds `AlertSurface.actionableTypes` through `elementTypeNamesByRawValue` and asserts the result has the same count. ### Also raised here Also raised at this location by senior-developer: Runner actionableTypes now depends on unenforced string equality between two tables — `RunnerTests.actionableTypes` used to be a literal `Set<XCUIElement.ElementType>` of `.button, .cell, .link, .menuItem, .checkBox, .switch`, which the compiler checked. It is now rebuilt by looking up `AlertSurface.actionableTypes` (the Swift package's `Set<String>`: `["Button", "Cell", "Link", "MenuItem", "CheckBox", "Switch"]`) inside `RunnerTests.elementTypeNamesByRawValue` and converting each raw value back with `XCUIElement.ElementType(rawValue:)`. The set is only complete while three unrelated tables agree exactly, case-sensitively: `AlertSurface.actionableTypes` (apple/snapshot-presentation/Sources/.../AlertSurface.swift:54) `XCUIElement.ElementType(rawValue:)` accepting those raw values again Nothing enforces that agreement. … Also raised at this location by swift-ios: actionableTypes now derived through …

// MARK: - XCTest Entry

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -327,38 +327,5 @@ 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])
}

@MainActor
func testDismissPopupWindowIsPlacedInTheBoxItSitsIn() {
let viewport = CGRect(x: 0, y: 0, width: 402, height: 874)
let popup = { (x: CGFloat) in
ElementAttributesFixture(.window, CGRect(x: x, y: 0, width: 402, height: 874), children: [
ElementAttributesFixture(.other, CGRect(x: x, y: 0, width: 402, height: 874), label: "dismiss popup")
])
}
XCTAssertEqual(alertSnapshots(in: popup(0), source: .dismissPopup, viewport: viewport).count, 1)
XCTAssertTrue(alertSnapshots(in: popup(1000), source: .dismissPopup, viewport: viewport).isEmpty)
}

@MainActor
func testAnInnerPanelAlertIsPlacedInItsWindowNotTheApplicationFrame() {
let alert = ElementAttributesFixture(.alert, CGRect(x: 341, y: 250, width: 270, height: 170))
let innerPanel = ElementAttributesFixture(.window, CGRect(x: 0, y: 0, width: 951, height: 669), children: [alert])
let root = ElementAttributesFixture(.application, CGRect(x: 0, y: 0, width: 466, height: 678), children: [innerPanel])
XCTAssertEqual(alertSnapshots(in: root, source: .appAlert, viewport: root.frame).map(\.elementType), [.alert])
}
#endif
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import XCTest
import AgentDeviceSnapshotPresentation

#if AGENT_DEVICE_RUNNER_UNIT_TESTS
/// A frame as the corpus spells it: the `FixtureRect` spelling, so an unusable box is named.
private struct RecordedAlertSurfaceRect: Encodable {
let frame: CGRect

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if frame.isInfinite {
try container.encode(true, forKey: .infinite)
} else if ![frame.minX, frame.minY, frame.width, frame.height].allSatisfy(\.isFinite) {
try container.encode(true, forKey: .nonFinite)
} else {
try container.encode(frame.minX, forKey: .x)
try container.encode(frame.minY, forKey: .y)
try container.encode(frame.width, forKey: .width)
try container.encode(frame.height, forKey: .height)
}
}

private enum CodingKeys: String, CodingKey {
case x, y, width, height, infinite, nonFinite
}
}

private struct RecordedAlertSurfaceNode: Encodable {
let index: Int
let parentIndex: Int?
let type: String
let identifier: String
let label: String
let rect: RecordedAlertSurfaceRect
}

extension RunnerTests {
/// Records an app's whole accessibility tree for the alert surface corpus. It runs only from
/// `pnpm capture:alert-surface`, which sets the bundle and the output path.
@MainActor
func testCaptureAlertSurfaceTree() throws {
let environment = ProcessInfo.processInfo.environment
guard let bundleId = environment["AGENT_DEVICE_ALERT_SURFACE_BUNDLE_ID"],
let output = environment["AGENT_DEVICE_ALERT_SURFACE_OUTPUT"]
else {
throw XCTSkip("Run through pnpm capture:alert-surface")
}
let snapshot = try XCUIApplication(bundleIdentifier: bundleId).snapshot()
var nodes: [RecordedAlertSurfaceNode] = []
func record(_ node: AlertSurfaceNode, parentIndex: Int?) {
let index = nodes.count
nodes.append(RecordedAlertSurfaceNode(
index: index,
parentIndex: parentIndex,
type: node.type,
identifier: node.identifier,
label: node.label,
rect: RecordedAlertSurfaceRect(frame: node.frame)
))
node.children.forEach { record($0, parentIndex: index) }
}
record(alertSurfaceNode(snapshot), parentIndex: nil)
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
try encoder.encode(nodes).write(to: URL(fileURLWithPath: output))
}
}
#endif
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import XCTest
import AgentDeviceSnapshotPresentation

#if AGENT_DEVICE_RUNNER_UNIT_TESTS
extension RunnerTests {
Expand Down
Loading
Loading