diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift index 97cbcbb624..0c436516a8 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift @@ -217,7 +217,7 @@ extension RunnerTests { ) } - var seen = Set() + var regularTree = RegularSnapshotTree(policy: .platformDefault) var stack: [SnapshotTraversalEntry] = [] if Self.canDescendAtRawDepth(0, hint: hint) { stack = rootChildren.map { @@ -238,29 +238,15 @@ extension RunnerTests { index: nodes.count, parentIndex: entry.parentIndex ) - let key = Self.snapshotTraversalIdentity( - elementType: snapshot.elementType, - label: evaluation.label, - identifier: evaluation.identifier, - frame: snapshot.frame - ) - let isDuplicate = seen.contains(key) - if !isDuplicate { - seen.insert(key) - } - - // A repeated node collapses into its parent: its children re-parent onto `entry.parentIndex`, - // so identical rows share one addressable owner. - let currentIndex = isDuplicate ? entry.parentIndex : nodes.count + let included = regularTree.append(node, elementType: String(describing: snapshot.elementType), to: &nodes) + let currentIndex = included ? node.index : entry.parentIndex for child in snapshot.children.reversed() { stack.append( SnapshotTraversalEntry(snapshot: child, depth: depth + 1, parentIndex: currentIndex) ) } - if isDuplicate { continue } - - nodes.append(node) + if !included { continue } if nodes.count > Self.regularSnapshotMaxNodes { throw regularSnapshotTooLargeFailure(nodeCount: nodes.count) } diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift index cf09aa1208..54ee19e024 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotAcquisition.swift @@ -303,19 +303,6 @@ extension RunnerTests { #endif } - static func snapshotTraversalIdentity( - elementType: XCUIElement.ElementType, - label: String, - identifier: String, - frame: CGRect - ) -> String { - #if os(iOS) - "\(elementType)-\(label)-\(identifier)-\(frame.origin.x)-\(frame.origin.y)-\(frame.width)-\(frame.height)" - #else - return "\(elementType)-\(label)-\(identifier)-\(frame.origin.x)-\(frame.origin.y)" - #endif - } - private func aggregatedLabel(for snapshot: XCUIElementSnapshot, depth: Int = 0) -> String? { if depth > 4 { return nil } let text = snapshot.label.trimmingCharacters(in: .whitespacesAndNewlines) diff --git a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SnapshotTraversalIdentityTests.swift b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SnapshotTraversalIdentityTests.swift index 4d4391ad57..a1b722b87a 100644 --- a/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SnapshotTraversalIdentityTests.swift +++ b/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/UnitTests/RunnerTests+SnapshotTraversalIdentityTests.swift @@ -1,16 +1,17 @@ +import AgentDeviceSnapshotPresentation import XCTest extension RunnerTests { #if AGENT_DEVICE_RUNNER_UNIT_TESTS func testSnapshotTraversalIdentityPreservesSameOriginNodesWithDifferentBounds() { - let wrapper = Self.snapshotTraversalIdentity( - elementType: .other, + let wrapper = RegularSnapshotTree.Policy.platformDefault.identity( + elementType: "Other", label: "Article", identifier: "", frame: CGRect(x: 0, y: 97, width: 393, height: 48) ) - let leaf = Self.snapshotTraversalIdentity( - elementType: .other, + let leaf = RegularSnapshotTree.Policy.platformDefault.identity( + elementType: "Other", label: "Article", identifier: "", frame: CGRect(x: 0, y: 97, width: 131, height: 48) diff --git a/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/RegularSnapshotTree.swift b/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/RegularSnapshotTree.swift new file mode 100644 index 0000000000..43615877b9 --- /dev/null +++ b/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/RegularSnapshotTree.swift @@ -0,0 +1,61 @@ +import CoreGraphics + +/// Duplicate handling for the runner's regular XCTest tree walk. +public struct RegularSnapshotTree { + public enum Policy: String, Decodable { + case fullBounds + case originOnly + case tvOS + + public static var platformDefault: Self { + #if os(iOS) + return .fullBounds + #elseif os(tvOS) + return .tvOS + #else + return .originOnly + #endif + } + + public func identity(elementType: String, label: String, identifier: String, frame: CGRect) -> String { + let originIdentity = "\(elementType)-\(label)-\(identifier)-\(frame.origin.x)-\(frame.origin.y)" + if self == .fullBounds { + return "\(originIdentity)-\(frame.width)-\(frame.height)" + } + return originIdentity + } + } + + private let policy: Policy + private var firstIndexByIdentity: [String: Int] = [:] + + public init(policy: Policy) { + self.policy = policy + } + + /// Appends an admitted node. Children of a rejected duplicate retain the duplicate's parent. + public mutating func append(_ node: RawAXNode, elementType: String, to nodes: inout [RawAXNode]) -> Bool { + let identity = policy.identity( + elementType: elementType, + label: node.label ?? "", + identifier: node.identifier ?? "", + frame: node.rect.cgRect + ) + if let firstIndex = firstIndexByIdentity[identity] { + if policy == .tvOS, + node.focused == true, + node.type == "Other", + (node.label != nil || node.identifier != nil), + node.parentIndex == firstIndex, + nodes[firstIndex].label == node.label, + nodes[firstIndex].identifier == node.identifier + { + nodes[firstIndex].focused = true + } + return false + } + firstIndexByIdentity[identity] = node.index + nodes.append(node) + return true + } +} diff --git a/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift b/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift index 5ef97086db..d22460e116 100644 --- a/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +++ b/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift @@ -38,7 +38,7 @@ public struct RawAXNode: Equatable { public let placeholder: String? public var rect: SnapshotRect public let enabled: Bool - public let focused: Bool? + public internal(set) var focused: Bool? public let selected: Bool? /// Geometric actionability; `nil` when the capture has no viewport box to decide it against. public var hittable: Bool? diff --git a/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift b/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift index e0dd9b7818..fc4ece994f 100644 --- a/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift +++ b/apple/snapshot-presentation/Sources/SnapshotPresentationConformance/main.swift @@ -26,6 +26,7 @@ private struct ConformanceInput: Decodable { let depth: Int? let scope: String? let foldPolicy: String + let regularTreePolicy: RegularSnapshotTree.Policy? let viewport: SnapshotRect let nodes: [Node] } @@ -54,26 +55,29 @@ private struct BatchOutput: Encodable { private func acquisition(for input: ConformanceInput) -> SnapshotAcquisition { let inputOptions = options(for: input) + let rawNodes = input.nodes.map { node in + RawAXNode( + index: node.index, + type: node.type, + label: node.label, + identifier: node.identifier, + value: node.value, + rect: node.rect, + enabled: node.enabled, + focused: node.focused, + selected: node.selected, + hittable: node.hittable, + depth: node.depth, + parentIndex: node.parentIndex, + hiddenContentAbove: node.hiddenContentAbove, + hiddenContentBelow: node.hiddenContentBelow + ) + } + let hint = SnapshotPresentation.captureHint(for: inputOptions) + let nodes = hint.isRaw ? rawNodes : input.regularTreePolicy.map { regularTreeNodes(rawNodes, policy: $0) } ?? rawNodes return SnapshotAcquisition( - hint: SnapshotPresentation.captureHint(for: inputOptions), - nodes: input.nodes.map { node in - RawAXNode( - index: node.index, - type: node.type, - label: node.label, - identifier: node.identifier, - value: node.value, - rect: node.rect, - enabled: node.enabled, - focused: node.focused, - selected: node.selected, - hittable: node.hittable, - depth: node.depth, - parentIndex: node.parentIndex, - hiddenContentAbove: node.hiddenContentAbove, - hiddenContentBelow: node.hiddenContentBelow - ) - }, + hint: hint, + nodes: nodes, truncated: false, effectiveDepth: nil, // The host engine refuses to fold without a viewport, so the differential always reports one. @@ -81,6 +85,24 @@ private func acquisition(for input: ConformanceInput) -> SnapshotAcquisition { ) } +private func regularTreeNodes(_ rawNodes: [RawAXNode], policy: RegularSnapshotTree.Policy) -> [RawAXNode] { + var tree = RegularSnapshotTree(policy: policy) + var retained: [RawAXNode] = [] + var childParents: [Int: Int] = [:] + for raw in rawNodes { + let parentIndex = raw.parentIndex.flatMap { childParents[$0] } + let node = raw.reindexed(index: retained.count, depth: raw.depth, parentIndex: parentIndex) + if raw.parentIndex == nil { + retained.append(node) + childParents[raw.index] = node.index + } else { + let included = tree.append(node, elementType: node.type, to: &retained) + childParents[raw.index] = included ? node.index : parentIndex + } + } + return retained +} + private func options(for input: ConformanceInput) -> PresentationOptions { PresentationOptions( interactiveOnly: input.interactiveOnly, diff --git a/contracts/fixtures/ios-snapshot-engine-conformance.json b/contracts/fixtures/ios-snapshot-engine-conformance.json index 5704f9a28b..a4660d2042 100644 --- a/contracts/fixtures/ios-snapshot-engine-conformance.json +++ b/contracts/fixtures/ios-snapshot-engine-conformance.json @@ -1497,6 +1497,110 @@ } ] } + }, + { + "name": "focus-scaled cell content survives the plain-viewport fold", + "swift": true, + "projection": "regular", + "interactiveOnly": false, + "depth": null, + "scope": null, + "foldPolicy": "plain-viewport", + "truncated": false, + "residue": [], + "nodes": [ + { + "index": 0, + "type": "Application", + "label": "App", + "rect": { "x": 0, "y": 0, "width": 320, "height": 240 }, + "enabled": true, + "hittable": false, + "depth": 0 + }, + { + "index": 1, + "type": "CollectionView", + "label": "Row", + "rect": { "x": 0, "y": 80, "width": 320, "height": 100 }, + "enabled": true, + "hittable": false, + "depth": 1, + "parentIndex": 0 + }, + { + "index": 2, + "type": "Cell", + "label": "Focused tile", + "rect": { "x": 40, "y": 80, "width": 80, "height": 100 }, + "enabled": true, + "focused": true, + "hittable": true, + "depth": 2, + "parentIndex": 1 + }, + { + "index": 3, + "type": "StaticText", + "label": "Focus-scaled content", + "rect": { "x": 38, "y": 77.5, "width": 84, "height": 105 }, + "enabled": true, + "hittable": false, + "depth": 3, + "parentIndex": 2 + } + ], + "expected": { + "outcome": "success", + "truncated": false, + "residue": [], + "nodes": [ + { + "index": 0, + "type": "Application", + "label": "App", + "rect": { "x": 0, "y": 0, "width": 320, "height": 240 }, + "depth": 0, + "parentIndex": null, + "hittable": false, + "hiddenContentAbove": false, + "hiddenContentBelow": false + }, + { + "index": 1, + "type": "CollectionView", + "label": "Row", + "rect": { "x": 0, "y": 80, "width": 320, "height": 100 }, + "depth": 1, + "parentIndex": 0, + "hittable": false, + "hiddenContentAbove": false, + "hiddenContentBelow": false + }, + { + "index": 2, + "type": "Cell", + "label": "Focused tile", + "rect": { "x": 40, "y": 80, "width": 80, "height": 100 }, + "depth": 2, + "parentIndex": 1, + "hittable": true, + "hiddenContentAbove": false, + "hiddenContentBelow": false + }, + { + "index": 3, + "type": "StaticText", + "label": "Focus-scaled content", + "rect": { "x": 38, "y": 77.5, "width": 84, "height": 105 }, + "depth": 3, + "parentIndex": 2, + "hittable": false, + "hiddenContentAbove": false, + "hiddenContentBelow": false + } + ] + } } ] } diff --git a/docs/adr/0004-ios-snapshot-backend-strategy.md b/docs/adr/0004-ios-snapshot-backend-strategy.md index 2e6b36160c..c66b4382da 100644 --- a/docs/adr/0004-ios-snapshot-backend-strategy.md +++ b/docs/adr/0004-ios-snapshot-backend-strategy.md @@ -70,6 +70,7 @@ Before a Simulator capture uses the bridge, it proves host absence as ADR 0038 " If the proof fails or a host is present, use the runner for that capture without changing the app-generation circuit. Decision history: #3801 permits acquisition overflow from system alerts at large Dynamic Type sizes. Presentation clips it with one `regular-geometry-clipped` quality note instead of failing the capture. +Decision history: #4654 states that the fold policy is producer evidence. The Apple runner compiles its policy per runtime — the projection cursor on iPhone/iPad, plain viewport intersection on tvOS and visionOS — and the host revalidation of an already presented payload reuses that policy instead of its own default, because the tvOS focus effect scales a focused cell past its row by design. ## Rationale diff --git a/packages/capture-kit/src/ios-snapshot-engine/conformance-harness.ts b/packages/capture-kit/src/ios-snapshot-engine/conformance-harness.ts index b254015252..f548570c82 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/conformance-harness.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/conformance-harness.ts @@ -25,6 +25,7 @@ type DifferentialCase = Readonly<{ scope: string | null; foldPolicy: 'cursor-projected' | 'plain-viewport'; viewport: Rect; + regularTreePolicy?: 'fullBounds' | 'originOnly' | 'tvOS'; nodes: readonly RawSnapshotNode[]; requiredLabels?: readonly string[]; absentLabels?: readonly string[]; @@ -82,7 +83,7 @@ export function compareDifferentialCases( /* c8 ignore stop */ /* c8 ignore start */ -function runSwiftCases(cases: readonly DifferentialCase[]): DifferentialOutcome[] { +export function runSwiftCases(cases: readonly DifferentialCase[]): DifferentialOutcome[] { const stdout = execFileSync(swiftConformanceExecutable(), [], { cwd: REPO_ROOT, encoding: 'utf8', diff --git a/packages/capture-kit/src/ios-snapshot-engine/index.ts b/packages/capture-kit/src/ios-snapshot-engine/index.ts index 1d17095ec1..3641a75adc 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/index.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/index.ts @@ -2,4 +2,5 @@ export { presentIosSnapshot, publishIosSnapshot } from './engine.ts'; export { presentIosRunnerSnapshot } from './runner-presentation.ts'; export { buildIosInteractiveSnapshotPresentation } from './semantic-index.ts'; export { IosSnapshotEngineError, toIosSnapshotEngineErrorDetails } from './types.ts'; +export type { IosSnapshotFoldPolicy } from './types.ts'; export type { SnapshotTreeRuleContext } from './tree.ts'; diff --git a/packages/platform-apple/src/__tests__/device-fixtures.ts b/packages/platform-apple/src/__tests__/device-fixtures.ts index 406e663b9d..3fc761d292 100644 --- a/packages/platform-apple/src/__tests__/device-fixtures.ts +++ b/packages/platform-apple/src/__tests__/device-fixtures.ts @@ -27,6 +27,16 @@ export const IOS_DEVICE: DeviceInfo = { booted: true, }; +export const TVOS_SIMULATOR: DeviceInfo = { + platform: 'apple', + id: 'tv-sim-1', + name: 'Apple TV 4K', + kind: 'simulator', + target: 'tv', + appleOs: 'tvos', + booted: true, +}; + export const MACOS_DEVICE: DeviceInfo = { platform: 'apple', id: 'host-macos-local', diff --git a/packages/platform-apple/src/interactor.ts b/packages/platform-apple/src/interactor.ts index e4fab3635b..700811e728 100644 --- a/packages/platform-apple/src/interactor.ts +++ b/packages/platform-apple/src/interactor.ts @@ -437,7 +437,7 @@ function presentRunnerSnapshotForDevice( // The desktop runner's nodes are already presented and carry absolute window-space rects, which // no single box describes (#3182); the macOS surface capture publishes its own space instead. if (isMacOs(device)) return { nodes: result.nodes ?? [] }; - return presentAppleRunnerSnapshot(device.id, options, result); + return presentAppleRunnerSnapshot(device, options, result); } function acceptsEmptyScopedSnapshot( diff --git a/packages/platform-apple/src/snapshot-presentation-fold-policy.test.ts b/packages/platform-apple/src/snapshot-presentation-fold-policy.test.ts new file mode 100644 index 0000000000..6de3ac296e --- /dev/null +++ b/packages/platform-apple/src/snapshot-presentation-fold-policy.test.ts @@ -0,0 +1,101 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { test } from 'vitest'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { presentAppleRunnerSnapshot } from './snapshot-presentation.ts'; + +// The Apple runner compiles its fold policy per runtime and never states it on the wire +// (#4654). The host revalidates that runner payload and must read the same rule from the same Apple +// OS leaf, so `runnerFoldPolicy` in `snapshot-presentation.ts` and `platformDefault` in +// SnapshotVisibilityFold.swift are one fact in two languages. Nothing shares the two, so this guard +// reads the Swift branch from source and drives every Apple leaf through the host seam. + +const SWIFT_FOLD = path.join( + import.meta.dirname, + '..', + '..', + '..', + 'apple', + 'snapshot-presentation', + 'Sources', + 'AgentDeviceSnapshotPresentation', + 'SnapshotVisibilityFold.swift', +); + +const SWIFT_POLICY = + /public static var platformDefault: Self \{\s*#if os\(iOS\)\s*return \.(cursorProjected|plainViewport)\s*#else\s*return \.(cursorProjected|plainViewport)\s*#endif/; + +/** A focused collection-view cell whose content the tvOS focus effect scaled past the row's frame. */ +const FOCUS_SCALED_NODES = [ + { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 1920, height: 1080 }, depth: 0 }, + { + index: 1, + parentIndex: 0, + type: 'CollectionView', + rect: { x: 0, y: 210, width: 1920, height: 501 }, + depth: 1, + }, + { + index: 2, + parentIndex: 1, + type: 'Cell', + label: 'Focused tile', + rect: { x: 87.6625, y: 197.475, width: 350.175, height: 526.05 }, + depth: 2, + focused: true, + hittable: true, + }, +]; + +const LEAVES: ReadonlyArray> = [ + { device: leaf('iPhone 17 Pro', 'ios'), clipsToScrollContainers: true }, + { device: leaf('iPad Pro', 'ipados'), clipsToScrollContainers: true }, + { device: leaf('Apple TV 4K', 'tvos', 'tv'), clipsToScrollContainers: false }, + { device: leaf('Apple Vision Pro', 'visionos'), clipsToScrollContainers: false }, +]; + +function leaf( + name: string, + appleOs: DeviceInfo['appleOs'], + target?: DeviceInfo['target'], +): DeviceInfo { + return { platform: 'apple', id: `parity-${appleOs}`, name, kind: 'simulator', appleOs, target }; +} + +test("the runner's compile-time fold policy keeps the branch the host mirrors", () => { + const branches = readSource(SWIFT_FOLD).match(SWIFT_POLICY); + assert.ok(branches, 'platformDefault no longer matches the shape the host mirrors'); + assert.equal( + branches[1], + 'cursorProjected', + 'the iOS runtime stopped using the projection cursor', + ); + assert.equal(branches[2], 'plainViewport', 'the non-iOS runtimes stopped using plain viewport'); +}); + +for (const { device, clipsToScrollContainers } of LEAVES) { + test(`the host revalidates ${device.appleOs} with the fold policy its runner compiled`, () => { + const present = () => + presentAppleRunnerSnapshot(device, undefined, { + nodes: FOCUS_SCALED_NODES, + viewportEvidence: { kind: 'reported', rect: { x: 0, y: 0, width: 1920, height: 1080 } }, + }); + + if (clipsToScrollContainers) { + assert.throws( + present, + (error: unknown) => + error instanceof Error && + (error as { details?: { reason?: string } }).details?.reason === + 'regular-node-outside-cumulative-clip', + ); + return; + } + assert.equal(present().nodes.find((node) => node.focused === true)?.hittable, true); + }); +} + +function readSource(file: string): string { + return fs.readFileSync(file, 'utf8'); +} diff --git a/packages/platform-apple/src/snapshot-presentation.test.ts b/packages/platform-apple/src/snapshot-presentation.test.ts index 893f50e0bc..060ab33182 100644 --- a/packages/platform-apple/src/snapshot-presentation.test.ts +++ b/packages/platform-apple/src/snapshot-presentation.test.ts @@ -1,4 +1,4 @@ -import { IOS_SIMULATOR, MACOS_DEVICE } from './__tests__/device-fixtures.ts'; +import { IOS_SIMULATOR, MACOS_DEVICE, TVOS_SIMULATOR } from './__tests__/device-fixtures.ts'; import { AppError } from '@agent-device/kernel/errors'; import assert from 'node:assert/strict'; import { test } from 'vitest'; @@ -53,7 +53,7 @@ test.each([ IOS_SIMULATOR, ); assert.deepEqual(read.viewportEvidence, expected); - const presented = presentAppleRunnerSnapshot('device-1', undefined, read); + const presented = presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, read); assert.equal( presented.nodes.some((node) => node.identifier === 'action'), true, @@ -92,7 +92,7 @@ test('reported runner viewport retains screen authority through the wire reader IOS_SIMULATOR, ); assert.deepEqual(read.viewportEvidence, { kind: 'reported', rect }); - const presented = presentAppleRunnerSnapshot('device-1', undefined, read); + const presented = presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, read); assert.deepEqual(presented.viewport, { width: 551, height: 813 }); assert.deepEqual(presented.nodes.find((node) => node.identifier === 'action')?.rect, { x: 481, @@ -110,7 +110,7 @@ test('reported runner viewport retains screen authority through the wire reader function presentSparse(overrides: Partial = {}) { return () => - presentAppleRunnerSnapshot('device-1', undefined, { + presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { nodes: [NO_VIEWPORT_ROOT], truncated: true, quality: { @@ -228,7 +228,7 @@ test('an undeclared rootless payload keeps the plain engine invariant', () => { }); test('a sparse verdict still presents the nodes it did read', () => { - const nodes = presentAppleRunnerSnapshot('device-1', undefined, { + const nodes = presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { nodes: [ { index: 0, @@ -262,7 +262,7 @@ const SYSTEM_SHEET: IosSystemSurfaceProvenance = { test('a presented system surface travels with an undeclared-payload refusal as typed provenance', () => { try { - presentAppleRunnerSnapshot('device-1', undefined, { + presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { nodes: [NO_VIEWPORT_ROOT], quality: { state: 'healthy', backend: 'tree' }, systemSurface: SYSTEM_SHEET, @@ -310,7 +310,7 @@ test('a healthy payload with valid viewport roots still presents', () => { rect: { x: 16, y: 400, width: 80, height: 32 }, hittable: true, }; - const nodes = presentAppleRunnerSnapshot('device-1', undefined, { + const nodes = presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { nodes: [screen, button], }).nodes; assert.deepEqual( @@ -339,7 +339,11 @@ test('a runner payload with the hittable bit absent presents without declaring i }, ]; for (const interactiveOnly of [false, true]) { - const presented = presentAppleRunnerSnapshot('device-1', { interactiveOnly }, { nodes }).nodes; + const presented = presentAppleRunnerSnapshot( + IOS_SIMULATOR, + { interactiveOnly }, + { nodes }, + ).nodes; const button = presented.find((node) => node.label === 'Not Now'); assert.ok(button, `interactiveOnly=${interactiveOnly}: the undecided button is presented`); assert.equal('hittable' in button, false); @@ -462,7 +466,7 @@ test('the published viewport is the root box the presentation validated against hittable: true, }; - const presented = presentAppleRunnerSnapshot('device-1', undefined, { + const presented = presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { nodes: [screen, button], }); @@ -483,7 +487,7 @@ test('the published viewport follows the quality payload the fold prefers (#3182 rect: { x: 0, y: 0, width: 390, height: 844 }, }; - const presented = presentAppleRunnerSnapshot('device-1', undefined, { + const presented = presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { nodes: [scopedRoot], qualityPayload: { nodes: [qualityRoot], truncated: false, scope: null }, }); @@ -494,13 +498,13 @@ test('the published viewport follows the quality payload the fold prefers (#3182 test('a capture with no usable viewport box publishes no viewport, never a zero (#3182)', () => { // `runnerFatal` skips presentation, so this exercises the publication seam alone: a zero-extent // root is the failed Apple read, and the guard must answer with absence. - const fatalZero = presentAppleRunnerSnapshot('device-1', undefined, { + const fatalZero = presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { nodes: [{ index: 0, type: 'Application', rect: { x: 0, y: 0, width: 0, height: 0 } }], runnerFatal: true, }); assert.equal('viewport' in fatalZero, false); - const rootless = presentAppleRunnerSnapshot('device-1', undefined, { + const rootless = presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { nodes: [{ index: 0, type: 'Other' }], runnerFatal: true, }); @@ -510,7 +514,7 @@ test('a capture with no usable viewport box publishes no viewport, never a zero // one that reaches publication still holding an unchecked root. A zero-extent Application there // must answer with absence rather than the failed read's dimensions. const rawZero = presentAppleRunnerSnapshot( - 'device-1', + IOS_SIMULATOR, { raw: true }, { nodes: [{ index: 0, type: 'Application', rect: { x: 0, y: 0, width: 0, height: 0 } }], @@ -524,7 +528,7 @@ test('a raw projection publishes no viewport, because nothing validated its box // under `raw` would hand the caller the same largest-rect guess #3182 exists to retire, labelled // as a measured fact — and the regular path would refuse this very payload. const presented = presentAppleRunnerSnapshot( - 'device-1', + IOS_SIMULATOR, { raw: true }, { nodes: [ @@ -620,7 +624,7 @@ test('a clipped system alert passes host validation and retains its typed qualit }, IOS_SIMULATOR, ); - const presentation = presentAppleRunnerSnapshot('device-1', { interactiveOnly: true }, read); + const presentation = presentAppleRunnerSnapshot(IOS_SIMULATOR, { interactiveOnly: true }, read); assert.equal( presentation.nodes.some((node) => node.label === 'Ask App Not to Track'), true, @@ -629,6 +633,197 @@ test('a clipped system alert passes host validation and retains its typed qualit assert.equal(read.quality, undefined); }); +// #4654: a tvOS runner folds its tree with plain viewport intersection, because the tvOS focus +// effect scales a focused cell past its row by design and the row clip would hide that content. +// The host then revalidates that already-presented payload, so it must use the fold policy the +// producer used. The frames below are the reporter's `snapshot -i --raw` capture of a focused tile +// on a tvOS home row: raw 24 is the focused cell, raw 25/26/28 are its content scaled ×1.05 around +// the cell's centre, and raw 21 is the row that the host treated as the clip. +function tvFocusScaledRowNodes(): RawSnapshotNode[] { + return [ + { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 1920, height: 1080 }, depth: 0 }, + { + index: 1, + parentIndex: 0, + type: 'CollectionView', + identifier: 'home-collection', + rect: { x: 0, y: 0, width: 1920, height: 1080 }, + depth: 1, + }, + { + index: 2, + parentIndex: 1, + type: 'Cell', + rect: { x: 0, y: 210, width: 1920, height: 501 }, + depth: 2, + }, + { + index: 3, + parentIndex: 2, + type: 'CollectionView', + rect: { x: 0, y: 210, width: 1920, height: 501 }, + depth: 3, + }, + { + index: 4, + parentIndex: 3, + type: 'Cell', + identifier: 'tile-cell-1', + rect: { x: 96, y: 210, width: 333.6, height: 501 }, + depth: 4, + hittable: true, + }, + { + index: 5, + parentIndex: 4, + type: 'Other', + label: 'Focused tile', + rect: { x: 96, y: 210, width: 333.5, height: 501 }, + depth: 5, + focused: true, + hittable: true, + }, + { + index: 6, + parentIndex: 5, + type: 'Other', + label: 'Focused tile', + rect: { x: 96, y: 210, width: 333.5, height: 501 }, + depth: 6, + }, + { + index: 7, + parentIndex: 6, + type: 'Other', + label: 'Focused tile', + rect: { x: 87.6625, y: 197.475, width: 350.175, height: 526.05 }, + depth: 7, + }, + { + index: 8, + parentIndex: 7, + type: 'Other', + rect: { x: 87.6625, y: 197.475, width: 350.175, height: 526.05 }, + depth: 8, + }, + ]; +} + +test('a tvOS runner payload keeps its plain-viewport fold through host validation (#4654)', () => { + const read = readAppleSnapshotResult( + { + nodes: tvFocusScaledRowNodes(), + snapshotViewport: { kind: 'reported', rect: { x: 0, y: 0, width: 1920, height: 1080 } }, + }, + TVOS_SIMULATOR, + ); + + const presented = presentAppleRunnerSnapshot(TVOS_SIMULATOR, undefined, read); + + const focused = presented.nodes.find((node) => node.focused === true); + assert.equal(focused?.label, 'Focused tile'); + assert.equal(focused?.hittable, true); + // The tvOS fold publishes the focus-scaled frame it observed, so the capture keeps it verbatim. + assert.deepEqual(presented.nodes.find((node) => node.index === 7)?.rect, { + x: 87.6625, + y: 197.475, + width: 350.175, + height: 526.05, + }); +}); + +test('an interactive tvOS snapshot lists the focused tile its row clip would hide (#4654)', () => { + const read = readAppleSnapshotResult( + { + nodes: tvFocusScaledRowNodes(), + snapshotViewport: { kind: 'reported', rect: { x: 0, y: 0, width: 1920, height: 1080 } }, + }, + TVOS_SIMULATOR, + ); + + const presented = presentAppleRunnerSnapshot(TVOS_SIMULATOR, { interactiveOnly: true }, read); + + const focused = presented.nodes.filter((node) => node.focused === true); + assert.equal(focused.length, 1); + assert.equal(focused[0]?.label, 'Focused tile'); + assert.equal(focused[0]?.hittable, true); +}); + +test('a tvOS runner payload still refuses a node outside the viewport (#4654)', () => { + const offScreenAction: RawSnapshotNode = { + index: 9, + parentIndex: 3, + type: 'Button', + label: 'Below the screen', + rect: { x: 0, y: 1400, width: 200, height: 80 }, + depth: 4, + hittable: true, + }; + const read = readAppleSnapshotResult( + { + nodes: [...tvFocusScaledRowNodes(), offScreenAction], + snapshotViewport: { kind: 'reported', rect: { x: 0, y: 0, width: 1920, height: 1080 } }, + }, + TVOS_SIMULATOR, + ); + + assert.throws( + () => presentAppleRunnerSnapshot(TVOS_SIMULATOR, undefined, read), + (error: unknown) => { + if (!(error instanceof AppError)) return false; + const details = error.details as { + reason?: string; + index?: number; + frame?: { y: number }; + }; + // The refusal keeps naming the node the producer published at that index. + return ( + details.reason === 'regular-node-outside-cumulative-clip' && + details.index === 9 && + details.frame?.y === 1400 + ); + }, + ); +}); + +test('a tvOS runner payload still refuses an actionable node with no frame (#4654)', () => { + const framelessAction: RawSnapshotNode = { + index: 9, + parentIndex: 3, + type: 'Button', + label: 'Nowhere', + depth: 4, + hittable: true, + }; + const read = readAppleSnapshotResult( + { + nodes: [...tvFocusScaledRowNodes(), framelessAction], + snapshotViewport: { kind: 'reported', rect: { x: 0, y: 0, width: 1920, height: 1080 } }, + }, + TVOS_SIMULATOR, + ); + + assert.throws( + () => presentAppleRunnerSnapshot(TVOS_SIMULATOR, undefined, read), + (error: unknown) => + error instanceof AppError && + (error.details as { reason?: string }).reason === 'regular-degenerate-actionable-node', + ); +}); + +test('a handheld runner payload still refuses a node outside its cumulative clip (#4654)', () => { + assert.throws( + () => + presentAppleRunnerSnapshot(IOS_SIMULATOR, undefined, { + nodes: tvFocusScaledRowNodes(), + viewportEvidence: { kind: 'reported', rect: { x: 0, y: 0, width: 1920, height: 1080 } }, + }), + (error: unknown) => + error instanceof AppError && + (error.details as { reason?: string }).reason === 'regular-node-outside-cumulative-clip', + ); +}); + test('runner wire keeps real verdicts independent of clipping notes', () => { const quality = { state: 'recovered', backend: 'queries', reasonCode: 'ax-rejected' }; const note = { code: 'regular-geometry-clipped', clippedNodeCount: 1, droppedNodeCount: 2 }; diff --git a/packages/platform-apple/src/snapshot-presentation.ts b/packages/platform-apple/src/snapshot-presentation.ts index 0afddd96cc..ad8bc77541 100644 --- a/packages/platform-apple/src/snapshot-presentation.ts +++ b/packages/platform-apple/src/snapshot-presentation.ts @@ -9,6 +9,7 @@ import { IosSnapshotEngineError, presentIosRunnerSnapshot, toIosSnapshotEngineErrorDetails, + type IosSnapshotFoldPolicy, } from '@agent-device/capture-kit/ios-snapshot-engine'; import { interpretIosNode } from '@agent-device/capture-kit/ios-node-interpretation'; import { resolveIosViewportEvidenceFromRoots } from '@agent-device/capture-kit/ios-snapshot-acquisition'; @@ -159,8 +160,23 @@ export type AppleRunnerSnapshotPresentation = Readonly<{ viewport?: SnapshotViewportSize; }>; +/** + * The fold policy the Apple runner projected this payload with. The runner picks it at compile time + * (`SnapshotVisibilityFold.Policy.platformDefault`): the projection cursor on the iPhone/iPad + * runtime, plain viewport intersection on tvOS and visionOS. The host revalidates an already + * presented payload, so it must reuse that rule rather than its own default: the tvOS focus effect + * scales a focused cell past its row on purpose, and a cursor clip read from that row refuses the + * whole screen (#4654). The two predicates share their leaf set with the producer's `#if os(iOS)` + * so one runtime can only mean one policy. + */ +function runnerFoldPolicy( + device: Pick, +): IosSnapshotFoldPolicy { + return isHandheldAppleDevice(device) ? 'cursor-projected' : 'plain-viewport'; +} + export function presentAppleRunnerSnapshot( - deviceId: string, + device: Pick, options: SnapshotOptions | undefined, result: AppleRunnerSnapshotResult, ): AppleRunnerSnapshotPresentation { @@ -196,7 +212,7 @@ export function presentAppleRunnerSnapshot( presentationKey: buildIosSnapshotPresentationKey(request), viewport: validationViewport, hittability: { kind: 'available' }, - lineage: { targetId: deviceId }, + lineage: { targetId: device.id }, residue: [], }, }; @@ -204,7 +220,7 @@ export function presentAppleRunnerSnapshot( try { // The engine returns the box its regular projection validated this payload against and no box // for raw — deriving it here would only repeat that rule (#3182). - const presentation = presentIosRunnerSnapshot(input, request); + const presentation = presentIosRunnerSnapshot(input, request, runnerFoldPolicy(device)); attachSnapshotViewportEvidence(presentation.nodes, viewportEvidence); const validatedViewport = viewportEvidence.kind === 'reported' diff --git a/scripts/ios-snapshot-differential.test.ts b/scripts/ios-snapshot-differential.test.ts index 7d490384c6..7185c798b7 100644 --- a/scripts/ios-snapshot-differential.test.ts +++ b/scripts/ios-snapshot-differential.test.ts @@ -7,6 +7,7 @@ import { isGeometricallyActionable, isPositiveFiniteRect } from '@agent-device/k import type { Rect } from '@agent-device/kernel/snapshot'; import { compareDifferentialCases, + runSwiftCases, SWIFT_RUN_TIMEOUT_MS, } from '../packages/capture-kit/src/ios-snapshot-engine/conformance-harness.ts'; import { @@ -23,6 +24,14 @@ import { viewport as capturedViewport, } from '../packages/capture-kit/src/ios-snapshot-engine/runner-presentation-fixtures.ts'; +import { buildSnapshotState } from '@agent-device/capture-kit/snapshot-state'; +import { stampSnapshotIdentity } from '@agent-device/contracts/snapshot-producers'; +import { + presentAppleRunnerSnapshot, + readAppleSnapshotResult, +} from '../packages/platform-apple/src/snapshot-presentation.ts'; +import { TVOS_SIMULATOR } from '../packages/platform-apple/src/__tests__/device-fixtures.ts'; + type DifferentialCase = Parameters[0][number]; const FUZZ_SEEDS = [219101, 219102, 219103, 219104]; @@ -394,3 +403,179 @@ test('the TypeScript rows cover every viewport kind that carries a box', () => { 'reported', ]); }); + +test('regular tvOS tree captures publish focus on the surviving tile as focus moves', () => { + const cases = ([0, 1, 2] as const).flatMap((focusedTile) => + (['regular', 'interactive', 'raw'] as const).map((mode) => ({ + name: `${mode} tile ${focusedTile + 1}`, + route: 'runner-presented' as const, + projection: mode === 'raw' ? ('raw' as const) : ('regular' as const), + interactiveOnly: mode === 'interactive', + depth: null, + scope: null, + foldPolicy: 'plain-viewport' as const, + regularTreePolicy: 'tvOS' as const, + viewport: { x: 0, y: 0, width: 1920, height: 1080 }, + nodes: tvFocusRow(focusedTile), + focusedTile, + })), + ); + const swiftCases = runSwiftCases(cases); + for (const [index, testCase] of cases.entries()) { + const swift = swiftCases[index]!; + assert.equal(swift.outcome, 'success', testCase.name); + const raw = testCase.projection === 'raw'; + const read = readAppleSnapshotResult( + { + nodes: swift.rawNodes, + snapshotViewport: { kind: 'reported', rect: testCase.viewport }, + }, + TVOS_SIMULATOR, + ); + const presented = presentAppleRunnerSnapshot( + TVOS_SIMULATOR, + { raw, interactiveOnly: testCase.interactiveOnly }, + read, + ); + const capture = stampSnapshotIdentity(presented, { + backend: 'xctest', + producer: 'apple-runner', + }); + const state = buildSnapshotState(capture, { + snapshotRaw: raw, + snapshotInteractiveOnly: testCase.interactiveOnly, + }); + for (const nodes of [swift.rawNodes!, presented.nodes, state.nodes]) { + const focused = nodes.filter((node) => node.focused === true); + assert.deepEqual( + focused.map((node) => [ + node.type, + node.label, + node.rect && Number(node.rect.width.toFixed(9)), + node.hittable, + ]), + [['Other', `Tile ${testCase.focusedTile + 1}`, raw ? 333.5 : 333.6, true]], + testCase.name, + ); + } + const scaled = { + x: TILE_ORIGINS[testCase.focusedTile] - 8.3375, + y: 197.475, + width: 350.175, + height: 526.05, + }; + const geometryViews = testCase.interactiveOnly + ? [swift.rawNodes!] + : [swift.rawNodes!, presented.nodes, state.nodes]; + for (const nodes of geometryViews) { + assert.ok( + nodes.some( + ({ rect }) => + rect && + (['x', 'y', 'width', 'height'] as const).every( + (key) => Math.abs(rect[key] - scaled[key]) < 1e-9, + ), + ), + `${testCase.name} keeps the focus-scaled frame`, + ); + } + assert.ok(state.nodes.find((node) => node.focused)?.ref, testCase.name); + } +}); + +test('regular tree focus stays on the same branch and keeps each Apple identity policy', () => { + const nodes = tvFocusRow(0); + const base = { + route: 'runner-presented', + projection: 'regular', + interactiveOnly: false, + depth: null, + scope: null, + foldPolicy: 'plain-viewport', + viewport: { x: 0, y: 0, width: 1920, height: 1080 }, + } as const; + const siblingNodes = nodes.map((node) => { + if (node.focused) return { ...node, parentIndex: 4, depth: 5 }; + if (node.parentIndex === 6) return { ...node, depth: 6 }; + return node; + }); + const cases = runSwiftCases([ + { ...base, name: 'full bounds', regularTreePolicy: 'fullBounds', nodes }, + { ...base, name: 'origin only', regularTreePolicy: 'originOnly', nodes }, + { + ...base, + name: 'tvOS sibling duplicate', + regularTreePolicy: 'tvOS', + nodes: siblingNodes, + }, + ]); + for (const outcome of cases) assert.equal(outcome.outcome, 'success'); + assert.deepEqual( + cases.map((outcome) => + outcome.rawNodes?.filter((node) => node.focused).map((node) => node.rect?.width), + ), + [[333.5], [], []], + ); +}); + +const TILE_ORIGINS = [96, 441.5, 787] as const; + +function tvFocusRow(focusedTile: number): DifferentialCase['nodes'] { + const viewport = { x: 0, y: 0, width: 1920, height: 1080 }; + const row = { x: 0, y: 210, width: 1920, height: 501 }; + const facts = { enabled: true, hittable: true }; + return [ + { ...facts, index: 0, depth: 0, type: 'Application', rect: viewport, hittable: false }, + { + ...facts, + index: 1, + depth: 1, + parentIndex: 0, + type: 'CollectionView', + rect: viewport, + identifier: 'home-collection', + }, + { ...facts, index: 2, depth: 2, parentIndex: 1, type: 'Cell', rect: row }, + { ...facts, index: 3, depth: 3, parentIndex: 2, type: 'CollectionView', rect: row }, + ...TILE_ORIGINS.flatMap((x, tile) => { + const index = 4 + tile * 4; + const label = `Tile ${tile + 1}`; + const rect = { x, y: 210, width: 333.6, height: 501 }; + return [ + { + ...facts, + index, + depth: 4, + parentIndex: 3, + type: 'Cell', + identifier: `tile-cell-${tile + 1}`, + rect, + }, + { ...facts, index: index + 1, depth: 5, parentIndex: index, type: 'Other', label, rect }, + { + ...facts, + index: index + 2, + depth: 6, + parentIndex: index + 1, + type: 'Other', + label, + rect: { ...rect, width: 333.5 }, + ...(tile === focusedTile ? { focused: true } : {}), + }, + ...(tile === focusedTile + ? [ + { + ...facts, + index: index + 3, + depth: 7, + parentIndex: index + 2, + type: 'Other', + label, + rect: { x: x - 8.3375, y: 197.475, width: 350.175, height: 526.05 }, + }, + ] + : []), + ]; + }), + ]; +} diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 45e52fdd70..1b4c1640b3 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -250,6 +250,7 @@ tvOS: Focus and visual truth: On Android TV and tvOS, if snapshot -i exposes a focused node, verify it with is focused . + On tvOS, snapshot -i can report focus on the outer tile when duplicate accessibility wrappers collapse. Use wait focused=true only when repeated snapshots preserve focus metadata for the app. If the app exposes only a surface view, or focus metadata is transient, use screenshot --overlay-refs, screenshot, or diff snapshot as visual truth and keep moving focus with tv-remote. On Vega OS, use the VVD display as visual truth until capture support lands. Do not assume press/click @ref works on Android TV, tvOS, or Vega OS until the desired element is focused.`, diff --git a/website/docs/docs/snapshots.md b/website/docs/docs/snapshots.md index 0398cc1654..3057e0db55 100644 --- a/website/docs/docs/snapshots.md +++ b/website/docs/docs/snapshots.md @@ -79,6 +79,8 @@ and disclosure behavior ([#2682](https://github.com/callstack/agent-device/issue - iOS and Android produce the same kind of snapshot: visible elements first, refs you can act on now, and hints that point to hidden list content. - Use `snapshot -i` by default in agent loops. +- On tvOS, regular snapshots can mark the outer tile as focused when duplicate accessibility + wrappers collapse. Use `snapshot --raw` to see which wrapper the app reports as focused. - On Android, `snapshot -i` also keeps the title and message of a standard alert dialog, so you can see what its buttons confirm. - When the Android snapshot helper captures the tree, the `Page:` and `App:` lines (`appName` and `appBundleId` in `--json`) name the foreground application window: active or focused, at the highest layer, and not a system UI or keyboard window. After a failed `open`, for example, they name the launcher. An app other than the session app shows its package name in both lines. `androidSnapshot.foregroundWindowPackage` in `--json` carries it, and the session keeps its app. The UIAutomator fallback names the session app. - On Android, repeating an unfiltered snapshot when nothing on screen changed (content or bounds) returns a short acknowledgement instead of the tree. `-i`, `-d`, `-s`, `--json`, and `--raw` always print full output. Add `--force-full` to get the full tree anyway.