diff --git a/packages/capture-kit/src/ios-snapshot-engine/engine.test.ts b/packages/capture-kit/src/ios-snapshot-engine/engine.test.ts index 7abb7f5f27..e3f3041cce 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/engine.test.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/engine.test.ts @@ -13,6 +13,7 @@ import { deriveIosCaptureHint, } from '@agent-device/capture-kit/ios-snapshot-planning'; import { toIosSnapshotEngineErrorDetails } from './types.ts'; +import { validateIosPayload } from './invariants.ts'; import { IosSnapshotEngineError, buildIosInteractiveSnapshotPresentation, @@ -196,6 +197,7 @@ test('engine error details preserve typed public context', () => { field: 'viewport', index: 4, parentIndex: 2, + indexTree: 'acquired', frame: { x: 0, y: 0, width: 10, height: 10 }, clip: { x: 1, y: 2, width: 3, height: 4 }, projection: 'regular', @@ -206,12 +208,128 @@ test('engine error details preserve typed public context', () => { field: 'viewport', index: 4, parentIndex: 2, + indexTree: 'acquired', frame: { x: 0, y: 0, width: 10, height: 10 }, clip: { x: 1, y: 2, width: 3, height: 4 }, projection: 'regular', }); }); +// #4701: one capture is numbered several times over — the raw acquisition, the tree the Apple runner +// published to the host, and the tree the host publishes after its own compaction — and every +// renumbering shifts a node. A refusal that reported a bare `index` asked the reader to guess which +// tree to open, while the recovery advice in the same message family points at a different tree than +// the refusal was counted in. Every refusal that names a node now names its index space. +test('a payload refusal names the runner payload as its index space, for either projection', () => { + for (const interactiveOnly of [false, true]) { + const request = createIosSnapshotRequest({ interactiveOnly }); + const payload = escapedRowNodes(); + + assert.throws( + () => presentIosSnapshot(runnerPresentedInput(request, payload), request), + (error: unknown) => { + assert.ok(error instanceof IosSnapshotEngineError); + assert.equal(error.reason, 'regular-node-outside-cumulative-clip'); + // The number is the payload's own: the escaping node sits at that index in the tree the + // producer published, which is the tree this refusal was counted in. + assert.equal(error.details.index, 3); + assert.equal(payload[error.details.index!]?.label, 'Escaping row'); + assert.equal(error.details.indexTree, 'runner-payload'); + return true; + }, + ); + } +}); + +test('a malformed acquired graph names the acquired tree the caller can list', () => { + const request = createIosSnapshotRequest(); + const malformed = acquisition(request, [ + node(0, 'Application', 'App', viewport), + { ...node(1, 'Button', 'Broken', { x: 1, y: 1, width: 10, height: 10 }, 0), parentIndex: 99 }, + ]); + + assert.throws( + () => publishIosSnapshot({ stage: 'acquired', acquisition: malformed }, request), + (error: unknown) => { + assert.ok(error instanceof IosSnapshotEngineError); + assert.equal(error.reason, 'malformed-graph'); + // An unscoped `snapshot --raw` lists this very tree, so naming it makes both numbers usable. + assert.equal(error.details.indexTree, 'acquired'); + assert.equal(error.details.index, 1); + assert.equal(error.details.parentIndex, 99); + return true; + }, + ); +}); + +test('each payload check reports an index that resolves inside the tree it names', () => { + // Every engine call site hands the check the tree it validated: `acquired` for the raw acquisition, + // `presented` for the tree about to be published, and the two runner payloads. Whichever it is, the + // reported index resolves to the refusing node in the named tree (#4701). + for (const indexTree of [ + 'acquired', + 'presented', + 'runner-payload', + 'runner-quality-payload', + ] as const) { + const nodes = escapedRowNodes(); + assert.throws( + () => validateIosPayload(nodes, indexTree, 'regular', viewport, 'cursor-projected'), + (error: unknown) => { + assert.ok(error instanceof IosSnapshotEngineError); + assert.equal(error.details.indexTree, indexTree); + assert.equal(nodes[error.details.index!]?.label, 'Escaping row'); + return true; + }, + ); + } +}); + +test('a quality-payload refusal names the quality payload as its index space', () => { + const request = createIosSnapshotRequest(); + const input: IosSnapshotInput = { + stage: 'presented', + presentation: { + producer: 'apple-runner', + intent: 'full', + payload: { nodes: ordinaryTreeNodes(), truncated: false }, + qualityPayload: { nodes: escapedRowNodes(), truncated: false, scope: null }, + }, + validation: validationFacts(request), + }; + + // The quality payload is reindexed and listed by no projection, so the reason alone left the + // number pointing at a tree the reader could not name. + assert.throws( + () => presentIosSnapshot(input, request), + (error: unknown) => { + assert.ok(error instanceof IosSnapshotEngineError); + assert.equal(error.reason, 'invalid-quality-payload'); + assert.equal(error.details.index, 3); + assert.equal(error.details.indexTree, 'runner-quality-payload'); + return true; + }, + ); +}); + +test('a refusal that names no node carries no index space', () => { + const request = createIosSnapshotRequest(); + const missingViewport: IosSnapshotAcquisition = { + ...acquisition(request, nestedNodes()), + viewport: { kind: 'missing', reason: 'not-provided' }, + }; + + assert.throws( + () => publishIosSnapshot({ stage: 'acquired', acquisition: missingViewport }, request), + (error: unknown) => { + assert.ok(error instanceof IosSnapshotEngineError); + assert.equal(error.reason, 'missing-viewport'); + assert.equal('indexTree' in error.details, false); + return true; + }, + ); +}); + test('viewport evidence prefers reported application and window roots', () => { assert.deepEqual( resolveIosViewportEvidenceFromRoots([ @@ -472,6 +590,21 @@ function acquiredInput(request: IosSnapshotRequest, nodes: RawSnapshotNode[]): I return { stage: 'acquired', acquisition: acquisition(request, nodes) }; } +function runnerPresentedInput( + request: IosSnapshotRequest, + nodes: RawSnapshotNode[], +): IosSnapshotInput { + return { + stage: 'presented', + presentation: { + producer: 'apple-runner', + intent: 'full', + payload: { nodes, truncated: false }, + }, + validation: validationFacts(request), + }; +} + function validationFacts(request: IosSnapshotRequest): IosSnapshotValidationFacts { return { presentationKey: buildIosSnapshotPresentationKey(request), @@ -492,6 +625,16 @@ function nestedNodes(): RawSnapshotNode[] { ]; } +/** A list whose last actionable row is inside the viewport but outside the list's clip (#4701). */ +function escapedRowNodes(): RawSnapshotNode[] { + return [ + node(0, 'Application', 'App', viewport), + node(1, 'ScrollView', 'List', { x: 0, y: 40, width: 320, height: 160 }, 0, 1), + node(2, 'Button', 'First row', { x: 8, y: 48, width: 304, height: 32 }, 1, 2), + node(3, 'Button', 'Escaping row', { x: 8, y: 200, width: 304, height: 32 }, 1, 2), + ]; +} + /** A UIKit-shaped tree over which a presentation is up: a second container carrying a dimming view. */ function presentedTreeNodes(): RawSnapshotNode[] { return [ diff --git a/packages/capture-kit/src/ios-snapshot-engine/engine.ts b/packages/capture-kit/src/ios-snapshot-engine/engine.ts index 9fad89dff8..47a8caa352 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/engine.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/engine.ts @@ -95,7 +95,7 @@ function presentAcquiredSnapshot( assertCaptureHintMatches(acquisition, expectedHint); if (request.projection === 'raw') { - validateIosSnapshotGraph(acquisition.nodes); + validateIosSnapshotGraph(acquisition.nodes, 'acquired'); const sourceNodes = acquisition.nodes.map((raw) => ({ raw, sourceIndex: raw.index })); const projected = projectIosSnapshot({ nodes: sourceNodes, @@ -152,6 +152,7 @@ function presentAcquiredSnapshot( }; const validation = validateIosPayload( compacted.nodes, + 'presented', 'regular', viewport, foldPolicy, diff --git a/packages/capture-kit/src/ios-snapshot-engine/geometry.ts b/packages/capture-kit/src/ios-snapshot-engine/geometry.ts index 8eae1dfa7a..e1358a6010 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/geometry.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/geometry.ts @@ -26,7 +26,8 @@ export function foldIosSnapshot( stats: IosSnapshotPresentationStats; qualityNotes?: SnapshotQualityNote[]; } { - validateIosSnapshotGraph(nodes); + // The fold interprets one acquisition's tree, so a refusal it raises counts in that tree. + validateIosSnapshotGraph(nodes, 'acquired'); const modalContained = collectModalContainedIndexes(nodes); const presentable = nodes.filter((node) => !modalContained.has(node.index)); const hasChildren = buildChildPresence(presentable); diff --git a/packages/capture-kit/src/ios-snapshot-engine/graph.ts b/packages/capture-kit/src/ios-snapshot-engine/graph.ts index 8b0575683f..f1951a625f 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/graph.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/graph.ts @@ -1,14 +1,22 @@ import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; import { IosSnapshotEngineError } from './types.ts'; +import type { IosSnapshotIndexTree } from './types.ts'; -export function validateIosSnapshotGraph(nodes: readonly RawSnapshotNode[]): void { +/** + * @param indexTree the tree `nodes` is numbered in, so a refusal naming a node states which of a + * capture's several numberings its `index` counts in (#4701). + */ +export function validateIosSnapshotGraph( + nodes: readonly RawSnapshotNode[], + indexTree: IosSnapshotIndexTree, +): void { const positions = new Map(); for (const [position, node] of nodes.entries()) { if (!Number.isInteger(node.index) || node.index < 0 || positions.has(node.index)) { throw new IosSnapshotEngineError( 'malformed-graph', 'iOS snapshot graph contains a duplicate or invalid node index', - { index: node.index }, + { index: node.index, indexTree }, ); } positions.set(node.index, position); @@ -16,7 +24,7 @@ export function validateIosSnapshotGraph(nodes: readonly RawSnapshotNode[]): voi throw new IosSnapshotEngineError( 'malformed-graph', 'iOS snapshot graph contains an invalid node depth', - { index: node.index, field: 'depth' }, + { index: node.index, indexTree, field: 'depth' }, ); } } @@ -28,7 +36,7 @@ export function validateIosSnapshotGraph(nodes: readonly RawSnapshotNode[]): voi throw new IosSnapshotEngineError( 'malformed-graph', 'iOS snapshot graph parent must precede its child', - { index: node.index, parentIndex: node.parentIndex }, + { index: node.index, indexTree, parentIndex: node.parentIndex }, ); } } diff --git a/packages/capture-kit/src/ios-snapshot-engine/invariants.ts b/packages/capture-kit/src/ios-snapshot-engine/invariants.ts index c289485a7d..cbf47d9fbe 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/invariants.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/invariants.ts @@ -7,7 +7,7 @@ import { containsPoint, rectContains, isPositiveFiniteRect } from '@agent-device import { normalizeType } from '@agent-device/contracts/snapshot'; import { validateIosSnapshotGraph } from './graph.ts'; import { IosSnapshotEngineError } from './types.ts'; -import type { IosSnapshotFoldPolicy } from './types.ts'; +import type { IosSnapshotFoldPolicy, IosSnapshotIndexTree } from './types.ts'; const SCROLL_CONTAINER_TYPES = new Set(['collectionview', 'scrollview', 'table']); @@ -35,29 +35,30 @@ export function resolveViewportEvidence(evidence: IosViewportEvidence): Rect { function validateIosRegularInvariant( nodes: readonly RawSnapshotNode[], + indexTree: IosSnapshotIndexTree, viewport: Rect, policy: IosSnapshotFoldPolicy, hittabilityAvailable = true, ): { parentClipLookups: number } { - validateIosSnapshotGraph(nodes); + validateIosSnapshotGraph(nodes, indexTree); const clipByIndex = new Map(); let parentClipLookups = 0; for (const node of nodes) { - const ancestorClip = resolveAncestorClip(node, clipByIndex, viewport, () => { + const ancestorClip = resolveAncestorClip(node, indexTree, clipByIndex, viewport, () => { parentClipLookups += 1; }); const frame = normalizeRect(node.rect); - validateHittabilityEvidence(node, hittabilityAvailable); + validateHittabilityEvidence(node, indexTree, hittabilityAvailable); if (!frame || !isPositiveFiniteRect(frame)) { - validateDegenerateActionability(node, frame); + validateDegenerateActionability(node, indexTree, frame); clipByIndex.set(node.index, ancestorClip); continue; } - validateContainedFrame(node, frame, ancestorClip); - validateActionability(node, frame, viewport); + validateContainedFrame(node, indexTree, frame, ancestorClip); + validateActionability(node, indexTree, frame, viewport); clipByIndex.set(node.index, clipForNode(node, frame, ancestorClip, policy)); } @@ -66,6 +67,7 @@ function validateIosRegularInvariant( function resolveAncestorClip( node: RawSnapshotNode, + indexTree: IosSnapshotIndexTree, clipByIndex: ReadonlyMap, viewport: Rect, onParentLookup: () => void, @@ -77,40 +79,58 @@ function resolveAncestorClip( throw new IosSnapshotEngineError( 'invalid-presented-payload', 'regular iOS snapshot payload refers to a parent outside the payload', - { index: node.index, parentIndex: node.parentIndex }, + { index: node.index, indexTree, parentIndex: node.parentIndex }, ); } return parentClip; } -function validateHittabilityEvidence(node: RawSnapshotNode, available: boolean): void { +function validateHittabilityEvidence( + node: RawSnapshotNode, + indexTree: IosSnapshotIndexTree, + available: boolean, +): void { if (node.hittable !== true || available) return; throw new IosSnapshotEngineError( 'invalid-presented-payload', 'iOS snapshot payload marked a node actionable without hittability evidence', - { index: node.index }, + { index: node.index, indexTree }, ); } -function validateDegenerateActionability(node: RawSnapshotNode, frame: Rect | undefined): void { +function validateDegenerateActionability( + node: RawSnapshotNode, + indexTree: IosSnapshotIndexTree, + frame: Rect | undefined, +): void { if (node.hittable !== true) return; throw new IosSnapshotEngineError( 'regular-degenerate-actionable-node', 'regular iOS snapshot node with a missing or degenerate frame is actionable', - { index: node.index, frame: frame ?? node.rect }, + { index: node.index, indexTree, frame: frame ?? node.rect }, ); } -function validateContainedFrame(node: RawSnapshotNode, frame: Rect, clip: Rect): void { +function validateContainedFrame( + node: RawSnapshotNode, + indexTree: IosSnapshotIndexTree, + frame: Rect, + clip: Rect, +): void { if (containsWithTolerance(frame, clip)) return; throw new IosSnapshotEngineError( 'regular-node-outside-cumulative-clip', 'regular iOS snapshot node escaped its cumulative clip', - { index: node.index, frame, clip }, + { index: node.index, indexTree, frame, clip }, ); } -function validateActionability(node: RawSnapshotNode, frame: Rect, viewport: Rect): void { +function validateActionability( + node: RawSnapshotNode, + indexTree: IosSnapshotIndexTree, + frame: Rect, + viewport: Rect, +): void { if ( node.hittable !== true || (node.enabled !== false && @@ -121,7 +141,7 @@ function validateActionability(node: RawSnapshotNode, frame: Rect, viewport: Rec throw new IosSnapshotEngineError( 'invalid-presented-payload', 'regular iOS snapshot payload marked a disabled or off-viewport node actionable', - { index: node.index, frame }, + { index: node.index, indexTree, frame }, ); } @@ -136,15 +156,20 @@ function clipForNode( : ancestorClip; } +/** + * @param indexTree the tree `nodes` is numbered in, carried onto every refusal this check raises so a + * reported `index` names the tree the reader has to open (#4701). + */ export function validateIosPayload( nodes: readonly RawSnapshotNode[], + indexTree: IosSnapshotIndexTree, projection: 'regular' | 'raw', viewport: Rect | undefined, policy: IosSnapshotFoldPolicy, hittabilityAvailable = true, ): { parentClipLookups: number } { if (projection === 'raw') { - validateIosSnapshotGraph(nodes); + validateIosSnapshotGraph(nodes, indexTree); return { parentClipLookups: 0 }; } if (!viewport) { @@ -155,7 +180,7 @@ export function validateIosPayload( ); } try { - return validateIosRegularInvariant(nodes, viewport, policy, hittabilityAvailable); + return validateIosRegularInvariant(nodes, indexTree, viewport, policy, hittabilityAvailable); } catch (error) { if (error instanceof IosSnapshotEngineError && error.code === 'IOS_SNAPSHOT_ENGINE_FAILED') { if (error.reason === 'malformed-graph') { diff --git a/packages/capture-kit/src/ios-snapshot-engine/runner-presentation.test.ts b/packages/capture-kit/src/ios-snapshot-engine/runner-presentation.test.ts index 84e97eb680..92d7d43c46 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/runner-presentation.test.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/runner-presentation.test.ts @@ -8,6 +8,7 @@ vi.mock('./invariants.ts', async (importOriginal) => { }); import type { RawSnapshotNode } from '@agent-device/kernel/snapshot'; import type { + IosRunnerQualityPayloadFacts, IosSnapshotInput, IosSnapshotRequest, IosSnapshotValidationFacts, @@ -172,13 +173,53 @@ test('a regular capture validates the runner payload once unless compaction chan assert.equal(validations.mock.calls.length, 2); }); -function runnerInput(request: IosSnapshotRequest, nodes: RawSnapshotNode[]): IosSnapshotInput { +// #4701: a refusal prints the index of the array it checked, and this route checks two arrays that +// hold the same nodes under different numbers. Each call has to name the tree it was handed. +test('each runner validation names the tree it checked', () => { + const validations = vi.mocked(validateIosPayload); + + const full = createIosSnapshotRequest({ interactiveOnly: false }); + validations.mockClear(); + presentIosSnapshot(runnerInput(full, runnerNodes()), full); + assert.deepEqual( + validations.mock.calls.map((call) => call[1]), + ['runner-payload'], + ); + + const interactive = createIosSnapshotRequest({ interactiveOnly: true }); + validations.mockClear(); + presentIosSnapshot(runnerInput(interactive, runnerNodes()), interactive); + assert.deepEqual( + validations.mock.calls.map((call) => call[1]), + ['runner-payload', 'presented'], + 'the second check reads the tree compaction renumbered, which is what the command publishes', + ); + + const withQuality = runnerInput(full, runnerNodes(), { + nodes: runnerNodes(), + truncated: false, + scope: null, + }); + validations.mockClear(); + presentIosSnapshot(withQuality, full); + assert.deepEqual( + validations.mock.calls.map((call) => call[1]), + ['runner-payload', 'runner-quality-payload'], + ); +}); + +function runnerInput( + request: IosSnapshotRequest, + nodes: RawSnapshotNode[], + qualityPayload?: IosRunnerQualityPayloadFacts, +): Extract { return { stage: 'presented', presentation: { producer: 'apple-runner', intent: 'full', payload: { nodes, truncated: false }, + ...(qualityPayload ? { qualityPayload } : {}), }, validation: validationFacts(request), }; diff --git a/packages/capture-kit/src/ios-snapshot-engine/runner-presentation.ts b/packages/capture-kit/src/ios-snapshot-engine/runner-presentation.ts index 9cf0ca46a1..fd2b0040c9 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/runner-presentation.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/runner-presentation.ts @@ -80,6 +80,7 @@ function validateRunnerPayloads( ): { parentClipLookups: number } { const payloadValidation = validateIosPayload( input.presentation.payload.nodes, + 'runner-payload', projection, viewport, foldPolicy, @@ -89,6 +90,7 @@ function validateRunnerPayloads( try { validateIosPayload( input.presentation.qualityPayload.nodes, + 'runner-quality-payload', projection, viewport, foldPolicy, @@ -130,7 +132,15 @@ function validateRunnerOutput( payloadValidation: { parentClipLookups: number }, ): { parentClipLookups: number } { if (projection !== 'regular' || !viewport) return payloadValidation; - return validateIosPayload(nodes, projection, viewport, foldPolicy, hittabilityAvailable); + // The compacted tree is what this command publishes, so a refusal raised here counts in it. + return validateIosPayload( + nodes, + 'presented', + projection, + viewport, + foldPolicy, + hittabilityAvailable, + ); } function presentationKeysEqual( diff --git a/packages/capture-kit/src/ios-snapshot-engine/types.ts b/packages/capture-kit/src/ios-snapshot-engine/types.ts index 356f688eec..3fe8629991 100644 --- a/packages/capture-kit/src/ios-snapshot-engine/types.ts +++ b/packages/capture-kit/src/ios-snapshot-engine/types.ts @@ -39,6 +39,28 @@ export type IosSnapshotEnginePresentation = Readonly<{ stats: IosSnapshotPresentationStats; }>; +/** + * The tree whose node numbering an {@link IosSnapshotEngineFailureDetails} `index` and `parentIndex` + * count in. One capture is numbered several times over — the raw acquisition, the tree the Apple + * runner published to the host, and the tree the host publishes after its own compaction — and every + * renumbering shifts a node, so a refusal that names an index without its tree asks the reader to + * guess which tree to open (#4701). + * + * Each value says where to read the node: + * - `acquired` — the raw acquisition tree, the numbering an unscoped `snapshot --raw` lists. + * - `presented` — the tree this snapshot command publishes. A capture of the same screen that + * passes lists the node at this index. + * - `runner-payload` — the tree the Apple runner published for this request. A passing plain + * `snapshot` publishes that tree at these same numbers. `snapshot -i` compacts it and renumbers + * what survives, and a refusal raised in that renumbered tree reads `presented` instead. + * - `runner-quality-payload` — the runner's unscoped quality payload, which no projection lists. + */ +export type IosSnapshotIndexTree = + | 'acquired' + | 'presented' + | 'runner-payload' + | 'runner-quality-payload'; + export type IosSnapshotEngineFailureReason = | 'projection-mismatch' | 'missing-viewport' @@ -52,6 +74,8 @@ export type IosSnapshotEngineFailureReason = export type IosSnapshotEngineFailureDetails = Readonly<{ index?: number; parentIndex?: number; + /** {@link IosSnapshotIndexTree} the `index` above counts in. Set on every refusal that names a node. */ + indexTree?: IosSnapshotIndexTree; frame?: Rect; clip?: Rect; projection?: string; diff --git a/website/docs/docs/snapshots.md b/website/docs/docs/snapshots.md index 49b74a7530..3f291be3a9 100644 --- a/website/docs/docs/snapshots.md +++ b/website/docs/docs/snapshots.md @@ -265,6 +265,18 @@ outside it, including system alerts at large text sizes. With `--json`, and `droppedNodeCount`. You can continue using visible controls. Use `--raw` to inspect reported frames before clipping. +A regular snapshot that can't present the screen fails with a typed `details.reason`, such as +`regular-node-outside-cumulative-clip`, and `details.index` names the node it refused. One capture +gets renumbered along the way, so `details.indexTree` tells you which numbering to read it in: + +- `presented` — the tree this command publishes. A passing capture asked the same way lists that node + at the same index. +- `acquired` — the tree an unscoped `snapshot --raw` lists, before any clipping. +- `runner-payload` — what the iOS capture published for the request. A passing plain `snapshot` + publishes that tree at the same numbers; a passing `snapshot -i` compacts and renumbers it. +- `runner-quality-payload` — a quality-only tree no command lists. Match `details.frame` against a + `snapshot --raw` capture to find that node. + iOS snapshots use XCTest on simulators and physical devices. You can't pick the capture backend. `--raw` switches between two strategies, and each strategy decides which backends it tries.